]> git.proxmox.com Git - mirror_ubuntu-zesty-kernel.git/blame - drivers/net/tun.c
tun: Add ability to create tun device with given index
[mirror_ubuntu-zesty-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>
47#include <linux/major.h>
48#include <linux/slab.h>
49#include <linux/poll.h>
50#include <linux/fcntl.h>
51#include <linux/init.h>
52#include <linux/skbuff.h>
53#include <linux/netdevice.h>
54#include <linux/etherdevice.h>
55#include <linux/miscdevice.h>
56#include <linux/ethtool.h>
57#include <linux/rtnetlink.h>
50857e2a 58#include <linux/compat.h>
1da177e4
LT
59#include <linux/if.h>
60#include <linux/if_arp.h>
61#include <linux/if_ether.h>
62#include <linux/if_tun.h>
6680ec68 63#include <linux/if_vlan.h>
1da177e4 64#include <linux/crc32.h>
d647a591 65#include <linux/nsproxy.h>
f43798c2 66#include <linux/virtio_net.h>
99405162 67#include <linux/rcupdate.h>
881d966b 68#include <net/net_namespace.h>
79d17604 69#include <net/netns/generic.h>
f019a7a5 70#include <net/rtnetlink.h>
33dccbb0 71#include <net/sock.h>
1da177e4 72
1da177e4
LT
73#include <asm/uaccess.h>
74
14daa021
RR
75/* Uncomment to enable debugging */
76/* #define TUN_DEBUG 1 */
77
1da177e4
LT
78#ifdef TUN_DEBUG
79static int debug;
14daa021 80
6b8a66ee
JP
81#define tun_debug(level, tun, fmt, args...) \
82do { \
83 if (tun->debug) \
84 netdev_printk(level, tun->dev, fmt, ##args); \
85} while (0)
86#define DBG1(level, fmt, args...) \
87do { \
88 if (debug == 2) \
89 printk(level fmt, ##args); \
90} while (0)
14daa021 91#else
6b8a66ee
JP
92#define tun_debug(level, tun, fmt, args...) \
93do { \
94 if (0) \
95 netdev_printk(level, tun->dev, fmt, ##args); \
96} while (0)
97#define DBG1(level, fmt, args...) \
98do { \
99 if (0) \
100 printk(level fmt, ##args); \
101} while (0)
14daa021
RR
102#endif
103
0690899b
MT
104#define GOODCOPY_LEN 128
105
f271b2cc
MK
106#define FLT_EXACT_COUNT 8
107struct tap_filter {
108 unsigned int count; /* Number of addrs. Zero means disabled */
109 u32 mask[2]; /* Mask of the hashed addrs */
110 unsigned char addr[FLT_EXACT_COUNT][ETH_ALEN];
111};
112
edfb6a14
JW
113/* DEFAULT_MAX_NUM_RSS_QUEUES were choosed to let the rx/tx queues allocated for
114 * the netdevice to be fit in one page. So we can make sure the success of
115 * memory allocation. TODO: increase the limit. */
116#define MAX_TAP_QUEUES DEFAULT_MAX_NUM_RSS_QUEUES
b8732fb7 117#define MAX_TAP_FLOWS 4096
c8d68e6b 118
96442e42
JW
119#define TUN_FLOW_EXPIRE (3 * HZ)
120
54f968d6
JW
121/* A tun_file connects an open character device to a tuntap netdevice. It
122 * also contains all socket related strctures (except sock_fprog and tap_filter)
123 * to serve as one transmit queue for tuntap device. The sock_fprog and
124 * tap_filter were kept in tun_struct since they were used for filtering for the
36fe8c09 125 * netdevice not for a specific queue (at least I didn't see the requirement for
54f968d6 126 * this).
6e914fc7
JW
127 *
128 * RCU usage:
36fe8c09 129 * The tun_file and tun_struct are loosely coupled, the pointer from one to the
6e914fc7 130 * other can only be read while rcu_read_lock or rtnl_lock is held.
54f968d6 131 */
631ab46b 132struct tun_file {
54f968d6
JW
133 struct sock sk;
134 struct socket socket;
135 struct socket_wq wq;
6e914fc7 136 struct tun_struct __rcu *tun;
36b50bab 137 struct net *net;
54f968d6
JW
138 struct fasync_struct *fasync;
139 /* only used for fasnyc */
140 unsigned int flags;
fb7589a1
PE
141 union {
142 u16 queue_index;
143 unsigned int ifindex;
144 };
4008e97f
JW
145 struct list_head next;
146 struct tun_struct *detached;
631ab46b
EB
147};
148
96442e42
JW
149struct tun_flow_entry {
150 struct hlist_node hash_link;
151 struct rcu_head rcu;
152 struct tun_struct *tun;
153
154 u32 rxhash;
155 int queue_index;
156 unsigned long updated;
157};
158
159#define TUN_NUM_FLOW_ENTRIES 1024
160
54f968d6 161/* Since the socket were moved to tun_file, to preserve the behavior of persist
36fe8c09 162 * device, socket filter, sndbuf and vnet header size were restore when the
54f968d6
JW
163 * file were attached to a persist device.
164 */
14daa021 165struct tun_struct {
c8d68e6b
JW
166 struct tun_file __rcu *tfiles[MAX_TAP_QUEUES];
167 unsigned int numqueues;
f271b2cc 168 unsigned int flags;
0625c883
EB
169 kuid_t owner;
170 kgid_t group;
14daa021 171
14daa021 172 struct net_device *dev;
c8f44aff 173 netdev_features_t set_features;
88255375
MM
174#define TUN_USER_FEATURES (NETIF_F_HW_CSUM|NETIF_F_TSO_ECN|NETIF_F_TSO| \
175 NETIF_F_TSO6|NETIF_F_UFO)
d9d52b51
MT
176
177 int vnet_hdr_sz;
54f968d6
JW
178 int sndbuf;
179 struct tap_filter txflt;
180 struct sock_fprog fprog;
181 /* protected by rtnl lock */
182 bool filter_attached;
14daa021
RR
183#ifdef TUN_DEBUG
184 int debug;
1da177e4 185#endif
96442e42 186 spinlock_t lock;
96442e42
JW
187 struct hlist_head flows[TUN_NUM_FLOW_ENTRIES];
188 struct timer_list flow_gc_timer;
189 unsigned long ageing_time;
4008e97f
JW
190 unsigned int numdisabled;
191 struct list_head disabled;
5dbbaf2d 192 void *security;
b8732fb7 193 u32 flow_count;
14daa021 194};
1da177e4 195
96442e42
JW
196static inline u32 tun_hashfn(u32 rxhash)
197{
198 return rxhash & 0x3ff;
199}
200
201static struct tun_flow_entry *tun_flow_find(struct hlist_head *head, u32 rxhash)
202{
203 struct tun_flow_entry *e;
96442e42 204
b67bfe0d 205 hlist_for_each_entry_rcu(e, head, hash_link) {
96442e42
JW
206 if (e->rxhash == rxhash)
207 return e;
208 }
209 return NULL;
210}
211
212static struct tun_flow_entry *tun_flow_create(struct tun_struct *tun,
213 struct hlist_head *head,
214 u32 rxhash, u16 queue_index)
215{
9fdc6bef
ED
216 struct tun_flow_entry *e = kmalloc(sizeof(*e), GFP_ATOMIC);
217
96442e42
JW
218 if (e) {
219 tun_debug(KERN_INFO, tun, "create flow: hash %u index %u\n",
220 rxhash, queue_index);
221 e->updated = jiffies;
222 e->rxhash = rxhash;
223 e->queue_index = queue_index;
224 e->tun = tun;
225 hlist_add_head_rcu(&e->hash_link, head);
b8732fb7 226 ++tun->flow_count;
96442e42
JW
227 }
228 return e;
229}
230
96442e42
JW
231static void tun_flow_delete(struct tun_struct *tun, struct tun_flow_entry *e)
232{
233 tun_debug(KERN_INFO, tun, "delete flow: hash %u index %u\n",
234 e->rxhash, e->queue_index);
235 hlist_del_rcu(&e->hash_link);
9fdc6bef 236 kfree_rcu(e, rcu);
b8732fb7 237 --tun->flow_count;
96442e42
JW
238}
239
240static void tun_flow_flush(struct tun_struct *tun)
241{
242 int i;
243
244 spin_lock_bh(&tun->lock);
245 for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
246 struct tun_flow_entry *e;
b67bfe0d 247 struct hlist_node *n;
96442e42 248
b67bfe0d 249 hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link)
96442e42
JW
250 tun_flow_delete(tun, e);
251 }
252 spin_unlock_bh(&tun->lock);
253}
254
255static void tun_flow_delete_by_queue(struct tun_struct *tun, u16 queue_index)
256{
257 int i;
258
259 spin_lock_bh(&tun->lock);
260 for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
261 struct tun_flow_entry *e;
b67bfe0d 262 struct hlist_node *n;
96442e42 263
b67bfe0d 264 hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
96442e42
JW
265 if (e->queue_index == queue_index)
266 tun_flow_delete(tun, e);
267 }
268 }
269 spin_unlock_bh(&tun->lock);
270}
271
272static void tun_flow_cleanup(unsigned long data)
273{
274 struct tun_struct *tun = (struct tun_struct *)data;
275 unsigned long delay = tun->ageing_time;
276 unsigned long next_timer = jiffies + delay;
277 unsigned long count = 0;
278 int i;
279
280 tun_debug(KERN_INFO, tun, "tun_flow_cleanup\n");
281
282 spin_lock_bh(&tun->lock);
283 for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
284 struct tun_flow_entry *e;
b67bfe0d 285 struct hlist_node *n;
96442e42 286
b67bfe0d 287 hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
96442e42
JW
288 unsigned long this_timer;
289 count++;
290 this_timer = e->updated + delay;
291 if (time_before_eq(this_timer, jiffies))
292 tun_flow_delete(tun, e);
293 else if (time_before(this_timer, next_timer))
294 next_timer = this_timer;
295 }
296 }
297
298 if (count)
299 mod_timer(&tun->flow_gc_timer, round_jiffies_up(next_timer));
300 spin_unlock_bh(&tun->lock);
301}
302
49974420 303static void tun_flow_update(struct tun_struct *tun, u32 rxhash,
9e85722d 304 struct tun_file *tfile)
96442e42
JW
305{
306 struct hlist_head *head;
307 struct tun_flow_entry *e;
308 unsigned long delay = tun->ageing_time;
9e85722d 309 u16 queue_index = tfile->queue_index;
96442e42
JW
310
311 if (!rxhash)
312 return;
313 else
314 head = &tun->flows[tun_hashfn(rxhash)];
315
316 rcu_read_lock();
317
9e85722d
JW
318 /* We may get a very small possibility of OOO during switching, not
319 * worth to optimize.*/
320 if (tun->numqueues == 1 || tfile->detached)
96442e42
JW
321 goto unlock;
322
323 e = tun_flow_find(head, rxhash);
324 if (likely(e)) {
325 /* TODO: keep queueing to old queue until it's empty? */
326 e->queue_index = queue_index;
327 e->updated = jiffies;
328 } else {
329 spin_lock_bh(&tun->lock);
b8732fb7
JW
330 if (!tun_flow_find(head, rxhash) &&
331 tun->flow_count < MAX_TAP_FLOWS)
96442e42
JW
332 tun_flow_create(tun, head, rxhash, queue_index);
333
334 if (!timer_pending(&tun->flow_gc_timer))
335 mod_timer(&tun->flow_gc_timer,
336 round_jiffies_up(jiffies + delay));
337 spin_unlock_bh(&tun->lock);
338 }
339
340unlock:
341 rcu_read_unlock();
342}
343
c8d68e6b
JW
344/* We try to identify a flow through its rxhash first. The reason that
345 * we do not check rxq no. is becuase some cards(e.g 82599), chooses
346 * the rxq based on the txq where the last packet of the flow comes. As
347 * the userspace application move between processors, we may get a
348 * different rxq no. here. If we could not get rxhash, then we would
349 * hope the rxq no. may help here.
350 */
351static u16 tun_select_queue(struct net_device *dev, struct sk_buff *skb)
352{
353 struct tun_struct *tun = netdev_priv(dev);
96442e42 354 struct tun_flow_entry *e;
c8d68e6b
JW
355 u32 txq = 0;
356 u32 numqueues = 0;
357
358 rcu_read_lock();
92bb73ea 359 numqueues = ACCESS_ONCE(tun->numqueues);
c8d68e6b
JW
360
361 txq = skb_get_rxhash(skb);
362 if (txq) {
96442e42
JW
363 e = tun_flow_find(&tun->flows[tun_hashfn(txq)], txq);
364 if (e)
365 txq = e->queue_index;
366 else
367 /* use multiply and shift instead of expensive divide */
368 txq = ((u64)txq * numqueues) >> 32;
c8d68e6b
JW
369 } else if (likely(skb_rx_queue_recorded(skb))) {
370 txq = skb_get_rx_queue(skb);
371 while (unlikely(txq >= numqueues))
372 txq -= numqueues;
373 }
374
375 rcu_read_unlock();
376 return txq;
377}
378
cde8b15f
JW
379static inline bool tun_not_capable(struct tun_struct *tun)
380{
381 const struct cred *cred = current_cred();
c260b772 382 struct net *net = dev_net(tun->dev);
cde8b15f
JW
383
384 return ((uid_valid(tun->owner) && !uid_eq(cred->euid, tun->owner)) ||
385 (gid_valid(tun->group) && !in_egroup_p(tun->group))) &&
c260b772 386 !ns_capable(net->user_ns, CAP_NET_ADMIN);
cde8b15f
JW
387}
388
c8d68e6b
JW
389static void tun_set_real_num_queues(struct tun_struct *tun)
390{
391 netif_set_real_num_tx_queues(tun->dev, tun->numqueues);
392 netif_set_real_num_rx_queues(tun->dev, tun->numqueues);
393}
394
4008e97f
JW
395static void tun_disable_queue(struct tun_struct *tun, struct tun_file *tfile)
396{
397 tfile->detached = tun;
398 list_add_tail(&tfile->next, &tun->disabled);
399 ++tun->numdisabled;
400}
401
d32649d1 402static struct tun_struct *tun_enable_queue(struct tun_file *tfile)
4008e97f
JW
403{
404 struct tun_struct *tun = tfile->detached;
405
406 tfile->detached = NULL;
407 list_del_init(&tfile->next);
408 --tun->numdisabled;
409 return tun;
410}
411
c8d68e6b
JW
412static void __tun_detach(struct tun_file *tfile, bool clean)
413{
414 struct tun_file *ntfile;
415 struct tun_struct *tun;
c8d68e6b 416
b8deabd3
JW
417 tun = rtnl_dereference(tfile->tun);
418
9e85722d 419 if (tun && !tfile->detached) {
c8d68e6b
JW
420 u16 index = tfile->queue_index;
421 BUG_ON(index >= tun->numqueues);
c8d68e6b
JW
422
423 rcu_assign_pointer(tun->tfiles[index],
424 tun->tfiles[tun->numqueues - 1]);
b8deabd3 425 ntfile = rtnl_dereference(tun->tfiles[index]);
c8d68e6b
JW
426 ntfile->queue_index = index;
427
428 --tun->numqueues;
9e85722d
JW
429 if (clean) {
430 rcu_assign_pointer(tfile->tun, NULL);
4008e97f 431 sock_put(&tfile->sk);
9e85722d 432 } else
4008e97f 433 tun_disable_queue(tun, tfile);
c8d68e6b
JW
434
435 synchronize_net();
96442e42 436 tun_flow_delete_by_queue(tun, tun->numqueues + 1);
c8d68e6b
JW
437 /* Drop read queue */
438 skb_queue_purge(&tfile->sk.sk_receive_queue);
439 tun_set_real_num_queues(tun);
dd38bd85 440 } else if (tfile->detached && clean) {
4008e97f 441 tun = tun_enable_queue(tfile);
dd38bd85
JW
442 sock_put(&tfile->sk);
443 }
c8d68e6b
JW
444
445 if (clean) {
af668b3c
MT
446 if (tun && tun->numqueues == 0 && tun->numdisabled == 0) {
447 netif_carrier_off(tun->dev);
448
449 if (!(tun->flags & TUN_PERSIST) &&
450 tun->dev->reg_state == NETREG_REGISTERED)
4008e97f 451 unregister_netdevice(tun->dev);
af668b3c 452 }
4008e97f 453
c8d68e6b
JW
454 BUG_ON(!test_bit(SOCK_EXTERNALLY_ALLOCATED,
455 &tfile->socket.flags));
456 sk_release_kernel(&tfile->sk);
457 }
458}
459
460static void tun_detach(struct tun_file *tfile, bool clean)
461{
462 rtnl_lock();
463 __tun_detach(tfile, clean);
464 rtnl_unlock();
465}
466
467static void tun_detach_all(struct net_device *dev)
468{
469 struct tun_struct *tun = netdev_priv(dev);
4008e97f 470 struct tun_file *tfile, *tmp;
c8d68e6b
JW
471 int i, n = tun->numqueues;
472
473 for (i = 0; i < n; i++) {
b8deabd3 474 tfile = rtnl_dereference(tun->tfiles[i]);
c8d68e6b
JW
475 BUG_ON(!tfile);
476 wake_up_all(&tfile->wq.wait);
477 rcu_assign_pointer(tfile->tun, NULL);
478 --tun->numqueues;
479 }
9e85722d
JW
480 list_for_each_entry(tfile, &tun->disabled, next) {
481 wake_up_all(&tfile->wq.wait);
482 rcu_assign_pointer(tfile->tun, NULL);
483 }
c8d68e6b
JW
484 BUG_ON(tun->numqueues != 0);
485
486 synchronize_net();
487 for (i = 0; i < n; i++) {
b8deabd3 488 tfile = rtnl_dereference(tun->tfiles[i]);
c8d68e6b
JW
489 /* Drop read queue */
490 skb_queue_purge(&tfile->sk.sk_receive_queue);
491 sock_put(&tfile->sk);
492 }
4008e97f
JW
493 list_for_each_entry_safe(tfile, tmp, &tun->disabled, next) {
494 tun_enable_queue(tfile);
495 skb_queue_purge(&tfile->sk.sk_receive_queue);
496 sock_put(&tfile->sk);
497 }
498 BUG_ON(tun->numdisabled != 0);
dd38bd85
JW
499
500 if (tun->flags & TUN_PERSIST)
501 module_put(THIS_MODULE);
c8d68e6b
JW
502}
503
a7385ba2
EB
504static int tun_attach(struct tun_struct *tun, struct file *file)
505{
631ab46b 506 struct tun_file *tfile = file->private_data;
38231b7a 507 int err;
a7385ba2 508
5dbbaf2d
PM
509 err = security_tun_dev_attach(tfile->socket.sk, tun->security);
510 if (err < 0)
511 goto out;
512
38231b7a 513 err = -EINVAL;
9e85722d 514 if (rtnl_dereference(tfile->tun) && !tfile->detached)
38231b7a
EB
515 goto out;
516
517 err = -EBUSY;
c8d68e6b
JW
518 if (!(tun->flags & TUN_TAP_MQ) && tun->numqueues == 1)
519 goto out;
520
521 err = -E2BIG;
4008e97f
JW
522 if (!tfile->detached &&
523 tun->numqueues + tun->numdisabled == MAX_TAP_QUEUES)
38231b7a
EB
524 goto out;
525
526 err = 0;
54f968d6 527
c8d68e6b 528 /* Re-attach the filter to presist device */
54f968d6
JW
529 if (tun->filter_attached == true) {
530 err = sk_attach_filter(&tun->fprog, tfile->socket.sk);
531 if (!err)
532 goto out;
533 }
c8d68e6b 534 tfile->queue_index = tun->numqueues;
6e914fc7 535 rcu_assign_pointer(tfile->tun, tun);
c8d68e6b 536 rcu_assign_pointer(tun->tfiles[tun->numqueues], tfile);
c8d68e6b 537 tun->numqueues++;
a7385ba2 538
4008e97f
JW
539 if (tfile->detached)
540 tun_enable_queue(tfile);
541 else
542 sock_hold(&tfile->sk);
543
c8d68e6b 544 tun_set_real_num_queues(tun);
a7385ba2 545
c8d68e6b
JW
546 /* device is allowed to go away first, so no need to hold extra
547 * refcnt.
548 */
549
550out:
551 return err;
631ab46b
EB
552}
553
554static struct tun_struct *__tun_get(struct tun_file *tfile)
555{
6e914fc7 556 struct tun_struct *tun;
c70f1829 557
6e914fc7
JW
558 rcu_read_lock();
559 tun = rcu_dereference(tfile->tun);
560 if (tun)
561 dev_hold(tun->dev);
562 rcu_read_unlock();
c70f1829
EB
563
564 return tun;
631ab46b
EB
565}
566
567static struct tun_struct *tun_get(struct file *file)
568{
569 return __tun_get(file->private_data);
570}
571
572static void tun_put(struct tun_struct *tun)
573{
6e914fc7 574 dev_put(tun->dev);
631ab46b
EB
575}
576
6b8a66ee 577/* TAP filtering */
f271b2cc
MK
578static void addr_hash_set(u32 *mask, const u8 *addr)
579{
580 int n = ether_crc(ETH_ALEN, addr) >> 26;
581 mask[n >> 5] |= (1 << (n & 31));
582}
583
584static unsigned int addr_hash_test(const u32 *mask, const u8 *addr)
585{
586 int n = ether_crc(ETH_ALEN, addr) >> 26;
587 return mask[n >> 5] & (1 << (n & 31));
588}
589
590static int update_filter(struct tap_filter *filter, void __user *arg)
591{
592 struct { u8 u[ETH_ALEN]; } *addr;
593 struct tun_filter uf;
594 int err, alen, n, nexact;
595
596 if (copy_from_user(&uf, arg, sizeof(uf)))
597 return -EFAULT;
598
599 if (!uf.count) {
600 /* Disabled */
601 filter->count = 0;
602 return 0;
603 }
604
605 alen = ETH_ALEN * uf.count;
606 addr = kmalloc(alen, GFP_KERNEL);
607 if (!addr)
608 return -ENOMEM;
609
610 if (copy_from_user(addr, arg + sizeof(uf), alen)) {
611 err = -EFAULT;
612 goto done;
613 }
614
615 /* The filter is updated without holding any locks. Which is
616 * perfectly safe. We disable it first and in the worst
617 * case we'll accept a few undesired packets. */
618 filter->count = 0;
619 wmb();
620
621 /* Use first set of addresses as an exact filter */
622 for (n = 0; n < uf.count && n < FLT_EXACT_COUNT; n++)
623 memcpy(filter->addr[n], addr[n].u, ETH_ALEN);
624
625 nexact = n;
626
cfbf84fc
AW
627 /* Remaining multicast addresses are hashed,
628 * unicast will leave the filter disabled. */
f271b2cc 629 memset(filter->mask, 0, sizeof(filter->mask));
cfbf84fc
AW
630 for (; n < uf.count; n++) {
631 if (!is_multicast_ether_addr(addr[n].u)) {
632 err = 0; /* no filter */
633 goto done;
634 }
f271b2cc 635 addr_hash_set(filter->mask, addr[n].u);
cfbf84fc 636 }
f271b2cc
MK
637
638 /* For ALLMULTI just set the mask to all ones.
639 * This overrides the mask populated above. */
640 if ((uf.flags & TUN_FLT_ALLMULTI))
641 memset(filter->mask, ~0, sizeof(filter->mask));
642
643 /* Now enable the filter */
644 wmb();
645 filter->count = nexact;
646
647 /* Return the number of exact filters */
648 err = nexact;
649
650done:
651 kfree(addr);
652 return err;
653}
654
655/* Returns: 0 - drop, !=0 - accept */
656static int run_filter(struct tap_filter *filter, const struct sk_buff *skb)
657{
658 /* Cannot use eth_hdr(skb) here because skb_mac_hdr() is incorrect
659 * at this point. */
660 struct ethhdr *eh = (struct ethhdr *) skb->data;
661 int i;
662
663 /* Exact match */
664 for (i = 0; i < filter->count; i++)
2e42e474 665 if (ether_addr_equal(eh->h_dest, filter->addr[i]))
f271b2cc
MK
666 return 1;
667
668 /* Inexact match (multicast only) */
669 if (is_multicast_ether_addr(eh->h_dest))
670 return addr_hash_test(filter->mask, eh->h_dest);
671
672 return 0;
673}
674
675/*
676 * Checks whether the packet is accepted or not.
677 * Returns: 0 - drop, !=0 - accept
678 */
679static int check_filter(struct tap_filter *filter, const struct sk_buff *skb)
680{
681 if (!filter->count)
682 return 1;
683
684 return run_filter(filter, skb);
685}
686
1da177e4
LT
687/* Network device part of the driver */
688
7282d491 689static const struct ethtool_ops tun_ethtool_ops;
1da177e4 690
c70f1829
EB
691/* Net device detach from fd. */
692static void tun_net_uninit(struct net_device *dev)
693{
c8d68e6b 694 tun_detach_all(dev);
c70f1829
EB
695}
696
1da177e4
LT
697/* Net device open. */
698static int tun_net_open(struct net_device *dev)
699{
c8d68e6b 700 netif_tx_start_all_queues(dev);
1da177e4
LT
701 return 0;
702}
703
704/* Net device close. */
705static int tun_net_close(struct net_device *dev)
706{
c8d68e6b 707 netif_tx_stop_all_queues(dev);
1da177e4
LT
708 return 0;
709}
710
711/* Net device start xmit */
424efe9c 712static netdev_tx_t tun_net_xmit(struct sk_buff *skb, struct net_device *dev)
1da177e4
LT
713{
714 struct tun_struct *tun = netdev_priv(dev);
c8d68e6b 715 int txq = skb->queue_mapping;
6e914fc7 716 struct tun_file *tfile;
1da177e4 717
6e914fc7 718 rcu_read_lock();
c8d68e6b
JW
719 tfile = rcu_dereference(tun->tfiles[txq]);
720
1da177e4 721 /* Drop packet if interface is not attached */
c8d68e6b 722 if (txq >= tun->numqueues)
1da177e4
LT
723 goto drop;
724
6e914fc7
JW
725 tun_debug(KERN_INFO, tun, "tun_net_xmit %d\n", skb->len);
726
c8d68e6b
JW
727 BUG_ON(!tfile);
728
f271b2cc
MK
729 /* Drop if the filter does not like it.
730 * This is a noop if the filter is disabled.
731 * Filter can be enabled only for the TAP devices. */
732 if (!check_filter(&tun->txflt, skb))
733 goto drop;
734
54f968d6
JW
735 if (tfile->socket.sk->sk_filter &&
736 sk_filter(tfile->socket.sk, skb))
99405162
MT
737 goto drop;
738
36fe8c09 739 /* Limit the number of packets queued by dividing txq length with the
c8d68e6b
JW
740 * number of queues.
741 */
54f968d6 742 if (skb_queue_len(&tfile->socket.sk->sk_receive_queue)
5d097109
MT
743 >= dev->tx_queue_len / tun->numqueues)
744 goto drop;
1da177e4 745
eda29772
RC
746 if (skb->sk) {
747 sock_tx_timestamp(skb->sk, &skb_shinfo(skb)->tx_flags);
748 sw_tx_timestamp(skb);
749 }
750
0110d6f2
MT
751 /* Orphan the skb - required as we might hang on to it
752 * for indefinite time. */
868eefeb
MT
753 if (unlikely(skb_orphan_frags(skb, GFP_ATOMIC)))
754 goto drop;
0110d6f2
MT
755 skb_orphan(skb);
756
f8af75f3
ED
757 nf_reset(skb);
758
f271b2cc 759 /* Enqueue packet */
54f968d6 760 skb_queue_tail(&tfile->socket.sk->sk_receive_queue, skb);
1da177e4
LT
761
762 /* Notify and wake up reader process */
54f968d6
JW
763 if (tfile->flags & TUN_FASYNC)
764 kill_fasync(&tfile->fasync, SIGIO, POLL_IN);
765 wake_up_interruptible_poll(&tfile->wq.wait, POLLIN |
05c2828c 766 POLLRDNORM | POLLRDBAND);
6e914fc7
JW
767
768 rcu_read_unlock();
6ed10654 769 return NETDEV_TX_OK;
1da177e4
LT
770
771drop:
09f75cd7 772 dev->stats.tx_dropped++;
149d36f7 773 skb_tx_error(skb);
1da177e4 774 kfree_skb(skb);
6e914fc7 775 rcu_read_unlock();
6ed10654 776 return NETDEV_TX_OK;
1da177e4
LT
777}
778
f271b2cc 779static void tun_net_mclist(struct net_device *dev)
1da177e4 780{
f271b2cc
MK
781 /*
782 * This callback is supposed to deal with mc filter in
783 * _rx_ path and has nothing to do with the _tx_ path.
784 * In rx path we always accept everything userspace gives us.
785 */
1da177e4
LT
786}
787
4885a504
ES
788#define MIN_MTU 68
789#define MAX_MTU 65535
790
791static int
792tun_net_change_mtu(struct net_device *dev, int new_mtu)
793{
794 if (new_mtu < MIN_MTU || new_mtu + dev->hard_header_len > MAX_MTU)
795 return -EINVAL;
796 dev->mtu = new_mtu;
797 return 0;
798}
799
c8f44aff
MM
800static netdev_features_t tun_net_fix_features(struct net_device *dev,
801 netdev_features_t features)
88255375
MM
802{
803 struct tun_struct *tun = netdev_priv(dev);
804
805 return (features & tun->set_features) | (features & ~TUN_USER_FEATURES);
806}
bebd097a
NH
807#ifdef CONFIG_NET_POLL_CONTROLLER
808static void tun_poll_controller(struct net_device *dev)
809{
810 /*
811 * Tun only receives frames when:
812 * 1) the char device endpoint gets data from user space
813 * 2) the tun socket gets a sendmsg call from user space
814 * Since both of those are syncronous operations, we are guaranteed
815 * never to have pending data when we poll for it
816 * so theres nothing to do here but return.
817 * We need this though so netpoll recognizes us as an interface that
818 * supports polling, which enables bridge devices in virt setups to
819 * still use netconsole
820 */
821 return;
822}
823#endif
758e43b7 824static const struct net_device_ops tun_netdev_ops = {
c70f1829 825 .ndo_uninit = tun_net_uninit,
758e43b7
SH
826 .ndo_open = tun_net_open,
827 .ndo_stop = tun_net_close,
00829823 828 .ndo_start_xmit = tun_net_xmit,
758e43b7 829 .ndo_change_mtu = tun_net_change_mtu,
88255375 830 .ndo_fix_features = tun_net_fix_features,
c8d68e6b 831 .ndo_select_queue = tun_select_queue,
bebd097a
NH
832#ifdef CONFIG_NET_POLL_CONTROLLER
833 .ndo_poll_controller = tun_poll_controller,
834#endif
758e43b7
SH
835};
836
837static const struct net_device_ops tap_netdev_ops = {
c70f1829 838 .ndo_uninit = tun_net_uninit,
758e43b7
SH
839 .ndo_open = tun_net_open,
840 .ndo_stop = tun_net_close,
00829823 841 .ndo_start_xmit = tun_net_xmit,
758e43b7 842 .ndo_change_mtu = tun_net_change_mtu,
88255375 843 .ndo_fix_features = tun_net_fix_features,
afc4b13d 844 .ndo_set_rx_mode = tun_net_mclist,
758e43b7
SH
845 .ndo_set_mac_address = eth_mac_addr,
846 .ndo_validate_addr = eth_validate_addr,
c8d68e6b 847 .ndo_select_queue = tun_select_queue,
bebd097a
NH
848#ifdef CONFIG_NET_POLL_CONTROLLER
849 .ndo_poll_controller = tun_poll_controller,
850#endif
758e43b7
SH
851};
852
944a1376 853static void tun_flow_init(struct tun_struct *tun)
96442e42
JW
854{
855 int i;
856
96442e42
JW
857 for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++)
858 INIT_HLIST_HEAD(&tun->flows[i]);
859
860 tun->ageing_time = TUN_FLOW_EXPIRE;
861 setup_timer(&tun->flow_gc_timer, tun_flow_cleanup, (unsigned long)tun);
862 mod_timer(&tun->flow_gc_timer,
863 round_jiffies_up(jiffies + tun->ageing_time));
96442e42
JW
864}
865
866static void tun_flow_uninit(struct tun_struct *tun)
867{
868 del_timer_sync(&tun->flow_gc_timer);
869 tun_flow_flush(tun);
96442e42
JW
870}
871
1da177e4
LT
872/* Initialize net device. */
873static void tun_net_init(struct net_device *dev)
874{
875 struct tun_struct *tun = netdev_priv(dev);
6aa20a22 876
1da177e4
LT
877 switch (tun->flags & TUN_TYPE_MASK) {
878 case TUN_TUN_DEV:
758e43b7
SH
879 dev->netdev_ops = &tun_netdev_ops;
880
1da177e4
LT
881 /* Point-to-Point TUN Device */
882 dev->hard_header_len = 0;
883 dev->addr_len = 0;
884 dev->mtu = 1500;
885
886 /* Zero header length */
6aa20a22 887 dev->type = ARPHRD_NONE;
1da177e4
LT
888 dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
889 dev->tx_queue_len = TUN_READQ_SIZE; /* We prefer our own queue length */
890 break;
891
892 case TUN_TAP_DEV:
7a0a9608 893 dev->netdev_ops = &tap_netdev_ops;
1da177e4 894 /* Ethernet TAP Device */
1da177e4 895 ether_setup(dev);
550fd08c 896 dev->priv_flags &= ~IFF_TX_SKB_SHARING;
a676847b 897 dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
36226a8d 898
f2cedb63 899 eth_hw_addr_random(dev);
36226a8d 900
1da177e4
LT
901 dev->tx_queue_len = TUN_READQ_SIZE; /* We prefer our own queue length */
902 break;
903 }
904}
905
906/* Character device part */
907
908/* Poll */
c8d68e6b 909static unsigned int tun_chr_poll(struct file *file, poll_table *wait)
6aa20a22 910{
b2430de3
EB
911 struct tun_file *tfile = file->private_data;
912 struct tun_struct *tun = __tun_get(tfile);
3c8a9c63 913 struct sock *sk;
33dccbb0 914 unsigned int mask = 0;
1da177e4
LT
915
916 if (!tun)
eac9e902 917 return POLLERR;
1da177e4 918
54f968d6 919 sk = tfile->socket.sk;
3c8a9c63 920
6b8a66ee 921 tun_debug(KERN_INFO, tun, "tun_chr_poll\n");
1da177e4 922
54f968d6 923 poll_wait(file, &tfile->wq.wait, wait);
6aa20a22 924
89f56d1e 925 if (!skb_queue_empty(&sk->sk_receive_queue))
1da177e4
LT
926 mask |= POLLIN | POLLRDNORM;
927
33dccbb0
HX
928 if (sock_writeable(sk) ||
929 (!test_and_set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags) &&
930 sock_writeable(sk)))
931 mask |= POLLOUT | POLLWRNORM;
932
c70f1829
EB
933 if (tun->dev->reg_state != NETREG_REGISTERED)
934 mask = POLLERR;
935
631ab46b 936 tun_put(tun);
1da177e4
LT
937 return mask;
938}
939
f42157cb
RR
940/* prepad is the amount to reserve at front. len is length after that.
941 * linear is a hint as to how much to copy (usually headers). */
54f968d6 942static struct sk_buff *tun_alloc_skb(struct tun_file *tfile,
6f7c156c 943 size_t prepad, size_t len,
944 size_t linear, int noblock)
f42157cb 945{
54f968d6 946 struct sock *sk = tfile->socket.sk;
f42157cb 947 struct sk_buff *skb;
33dccbb0 948 int err;
f42157cb
RR
949
950 /* Under a page? Don't bother with paged skb. */
0eca93bc 951 if (prepad + len < PAGE_SIZE || !linear)
33dccbb0 952 linear = len;
f42157cb 953
33dccbb0 954 skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
28d64271 955 &err, 0);
f42157cb 956 if (!skb)
33dccbb0 957 return ERR_PTR(err);
f42157cb
RR
958
959 skb_reserve(skb, prepad);
960 skb_put(skb, linear);
33dccbb0
HX
961 skb->data_len = len - linear;
962 skb->len += len - linear;
f42157cb
RR
963
964 return skb;
965}
966
1da177e4 967/* Get packet from user space buffer */
54f968d6
JW
968static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile,
969 void *msg_control, const struct iovec *iv,
970 size_t total_len, size_t count, int noblock)
1da177e4 971{
09640e63 972 struct tun_pi pi = { 0, cpu_to_be16(ETH_P_IP) };
1da177e4 973 struct sk_buff *skb;
3dd5c330 974 size_t len = total_len, align = NET_SKB_PAD, linear;
f43798c2 975 struct virtio_net_hdr gso = { 0 };
6f26c9a7 976 int offset = 0;
0690899b
MT
977 int copylen;
978 bool zerocopy = false;
979 int err;
49974420 980 u32 rxhash;
1da177e4
LT
981
982 if (!(tun->flags & TUN_NO_PI)) {
15718ea0 983 if (len < sizeof(pi))
1da177e4 984 return -EINVAL;
15718ea0 985 len -= sizeof(pi);
1da177e4 986
6f26c9a7 987 if (memcpy_fromiovecend((void *)&pi, iv, 0, sizeof(pi)))
1da177e4 988 return -EFAULT;
6f26c9a7 989 offset += sizeof(pi);
1da177e4
LT
990 }
991
f43798c2 992 if (tun->flags & TUN_VNET_HDR) {
15718ea0 993 if (len < tun->vnet_hdr_sz)
f43798c2 994 return -EINVAL;
15718ea0 995 len -= tun->vnet_hdr_sz;
f43798c2 996
6f26c9a7 997 if (memcpy_fromiovecend((void *)&gso, iv, offset, sizeof(gso)))
f43798c2
RR
998 return -EFAULT;
999
4909122f
HX
1000 if ((gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
1001 gso.csum_start + gso.csum_offset + 2 > gso.hdr_len)
1002 gso.hdr_len = gso.csum_start + gso.csum_offset + 2;
1003
f43798c2
RR
1004 if (gso.hdr_len > len)
1005 return -EINVAL;
d9d52b51 1006 offset += tun->vnet_hdr_sz;
f43798c2
RR
1007 }
1008
e01bf1c8 1009 if ((tun->flags & TUN_TYPE_MASK) == TUN_TAP_DEV) {
a504b86e 1010 align += NET_IP_ALIGN;
0eca93bc
HX
1011 if (unlikely(len < ETH_HLEN ||
1012 (gso.hdr_len && gso.hdr_len < ETH_HLEN)))
e01bf1c8
RR
1013 return -EINVAL;
1014 }
6aa20a22 1015
88529176
JW
1016 if (msg_control) {
1017 /* There are 256 bytes to be copied in skb, so there is
1018 * enough room for skb expand head in case it is used.
0690899b
MT
1019 * The rest of the buffer is mapped from userspace.
1020 */
88529176 1021 copylen = gso.hdr_len ? gso.hdr_len : GOODCOPY_LEN;
3dd5c330 1022 linear = copylen;
88529176
JW
1023 if (iov_pages(iv, offset + copylen, count) <= MAX_SKB_FRAGS)
1024 zerocopy = true;
1025 }
1026
1027 if (!zerocopy) {
0690899b 1028 copylen = len;
3dd5c330
JW
1029 linear = gso.hdr_len;
1030 }
0690899b 1031
3dd5c330 1032 skb = tun_alloc_skb(tfile, align, copylen, linear, noblock);
33dccbb0
HX
1033 if (IS_ERR(skb)) {
1034 if (PTR_ERR(skb) != -EAGAIN)
1035 tun->dev->stats.rx_dropped++;
1036 return PTR_ERR(skb);
1da177e4
LT
1037 }
1038
0690899b
MT
1039 if (zerocopy)
1040 err = zerocopy_sg_from_iovec(skb, iv, offset, count);
88529176 1041 else {
0690899b 1042 err = skb_copy_datagram_from_iovec(skb, 0, iv, offset, len);
88529176
JW
1043 if (!err && msg_control) {
1044 struct ubuf_info *uarg = msg_control;
1045 uarg->callback(uarg, false);
1046 }
1047 }
0690899b
MT
1048
1049 if (err) {
09f75cd7 1050 tun->dev->stats.rx_dropped++;
8f22757e 1051 kfree_skb(skb);
1da177e4 1052 return -EFAULT;
8f22757e 1053 }
1da177e4 1054
f43798c2
RR
1055 if (gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {
1056 if (!skb_partial_csum_set(skb, gso.csum_start,
1057 gso.csum_offset)) {
1058 tun->dev->stats.rx_frame_errors++;
1059 kfree_skb(skb);
1060 return -EINVAL;
1061 }
88255375 1062 }
f43798c2 1063
1da177e4
LT
1064 switch (tun->flags & TUN_TYPE_MASK) {
1065 case TUN_TUN_DEV:
f09f7ee2
AWC
1066 if (tun->flags & TUN_NO_PI) {
1067 switch (skb->data[0] & 0xf0) {
1068 case 0x40:
1069 pi.proto = htons(ETH_P_IP);
1070 break;
1071 case 0x60:
1072 pi.proto = htons(ETH_P_IPV6);
1073 break;
1074 default:
1075 tun->dev->stats.rx_dropped++;
1076 kfree_skb(skb);
1077 return -EINVAL;
1078 }
1079 }
1080
459a98ed 1081 skb_reset_mac_header(skb);
1da177e4 1082 skb->protocol = pi.proto;
4c13eb66 1083 skb->dev = tun->dev;
1da177e4
LT
1084 break;
1085 case TUN_TAP_DEV:
1086 skb->protocol = eth_type_trans(skb, tun->dev);
1087 break;
6403eab1 1088 }
1da177e4 1089
f43798c2
RR
1090 if (gso.gso_type != VIRTIO_NET_HDR_GSO_NONE) {
1091 pr_debug("GSO!\n");
1092 switch (gso.gso_type & ~VIRTIO_NET_HDR_GSO_ECN) {
1093 case VIRTIO_NET_HDR_GSO_TCPV4:
c9af6db4 1094 skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4;
f43798c2
RR
1095 break;
1096 case VIRTIO_NET_HDR_GSO_TCPV6:
c9af6db4 1097 skb_shinfo(skb)->gso_type = SKB_GSO_TCPV6;
f43798c2 1098 break;
e36aa25a 1099 case VIRTIO_NET_HDR_GSO_UDP:
c9af6db4 1100 skb_shinfo(skb)->gso_type = SKB_GSO_UDP;
e36aa25a 1101 break;
f43798c2
RR
1102 default:
1103 tun->dev->stats.rx_frame_errors++;
1104 kfree_skb(skb);
1105 return -EINVAL;
1106 }
1107
1108 if (gso.gso_type & VIRTIO_NET_HDR_GSO_ECN)
c9af6db4 1109 skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN;
f43798c2
RR
1110
1111 skb_shinfo(skb)->gso_size = gso.gso_size;
1112 if (skb_shinfo(skb)->gso_size == 0) {
1113 tun->dev->stats.rx_frame_errors++;
1114 kfree_skb(skb);
1115 return -EINVAL;
1116 }
1117
1118 /* Header must be checked, and gso_segs computed. */
1119 skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
1120 skb_shinfo(skb)->gso_segs = 0;
1121 }
6aa20a22 1122
0690899b
MT
1123 /* copy skb_ubuf_info for callback when skb has no error */
1124 if (zerocopy) {
1125 skb_shinfo(skb)->destructor_arg = msg_control;
1126 skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
c9af6db4 1127 skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG;
0690899b
MT
1128 }
1129
76fe4581 1130 skb_reset_network_header(skb);
40893fd0 1131 skb_probe_transport_header(skb, 0);
38502af7 1132
49974420 1133 rxhash = skb_get_rxhash(skb);
1da177e4 1134 netif_rx_ni(skb);
6aa20a22 1135
09f75cd7
JG
1136 tun->dev->stats.rx_packets++;
1137 tun->dev->stats.rx_bytes += len;
1da177e4 1138
9e85722d 1139 tun_flow_update(tun, rxhash, tfile);
0690899b 1140 return total_len;
6aa20a22 1141}
1da177e4 1142
ee0b3e67
BP
1143static ssize_t tun_chr_aio_write(struct kiocb *iocb, const struct iovec *iv,
1144 unsigned long count, loff_t pos)
1da177e4 1145{
33dccbb0 1146 struct file *file = iocb->ki_filp;
ab46d779 1147 struct tun_struct *tun = tun_get(file);
54f968d6 1148 struct tun_file *tfile = file->private_data;
631ab46b 1149 ssize_t result;
1da177e4
LT
1150
1151 if (!tun)
1152 return -EBADFD;
1153
6b8a66ee 1154 tun_debug(KERN_INFO, tun, "tun_chr_write %ld\n", count);
1da177e4 1155
54f968d6
JW
1156 result = tun_get_user(tun, tfile, NULL, iv, iov_length(iv, count),
1157 count, file->f_flags & O_NONBLOCK);
631ab46b
EB
1158
1159 tun_put(tun);
1160 return result;
1da177e4
LT
1161}
1162
1da177e4 1163/* Put packet to the user space buffer */
6f7c156c 1164static ssize_t tun_put_user(struct tun_struct *tun,
54f968d6 1165 struct tun_file *tfile,
6f7c156c 1166 struct sk_buff *skb,
1167 const struct iovec *iv, int len)
1da177e4
LT
1168{
1169 struct tun_pi pi = { 0, skb->protocol };
1170 ssize_t total = 0;
6680ec68 1171 int vlan_offset = 0;
1da177e4
LT
1172
1173 if (!(tun->flags & TUN_NO_PI)) {
1174 if ((len -= sizeof(pi)) < 0)
1175 return -EINVAL;
1176
1177 if (len < skb->len) {
1178 /* Packet will be striped */
1179 pi.flags |= TUN_PKT_STRIP;
1180 }
6aa20a22 1181
43b39dcd 1182 if (memcpy_toiovecend(iv, (void *) &pi, 0, sizeof(pi)))
1da177e4
LT
1183 return -EFAULT;
1184 total += sizeof(pi);
6aa20a22 1185 }
1da177e4 1186
f43798c2
RR
1187 if (tun->flags & TUN_VNET_HDR) {
1188 struct virtio_net_hdr gso = { 0 }; /* no info leak */
d9d52b51 1189 if ((len -= tun->vnet_hdr_sz) < 0)
f43798c2
RR
1190 return -EINVAL;
1191
1192 if (skb_is_gso(skb)) {
1193 struct skb_shared_info *sinfo = skb_shinfo(skb);
1194
1195 /* This is a hint as to how much should be linear. */
1196 gso.hdr_len = skb_headlen(skb);
1197 gso.gso_size = sinfo->gso_size;
1198 if (sinfo->gso_type & SKB_GSO_TCPV4)
1199 gso.gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
1200 else if (sinfo->gso_type & SKB_GSO_TCPV6)
1201 gso.gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
e36aa25a
SS
1202 else if (sinfo->gso_type & SKB_GSO_UDP)
1203 gso.gso_type = VIRTIO_NET_HDR_GSO_UDP;
ef3db4a5 1204 else {
6b8a66ee 1205 pr_err("unexpected GSO type: "
ef3db4a5
MT
1206 "0x%x, gso_size %d, hdr_len %d\n",
1207 sinfo->gso_type, gso.gso_size,
1208 gso.hdr_len);
1209 print_hex_dump(KERN_ERR, "tun: ",
1210 DUMP_PREFIX_NONE,
1211 16, 1, skb->head,
1212 min((int)gso.hdr_len, 64), true);
1213 WARN_ON_ONCE(1);
1214 return -EINVAL;
1215 }
f43798c2
RR
1216 if (sinfo->gso_type & SKB_GSO_TCP_ECN)
1217 gso.gso_type |= VIRTIO_NET_HDR_GSO_ECN;
1218 } else
1219 gso.gso_type = VIRTIO_NET_HDR_GSO_NONE;
1220
1221 if (skb->ip_summed == CHECKSUM_PARTIAL) {
1222 gso.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
55508d60 1223 gso.csum_start = skb_checksum_start_offset(skb);
f43798c2 1224 gso.csum_offset = skb->csum_offset;
10a8d94a
JW
1225 } else if (skb->ip_summed == CHECKSUM_UNNECESSARY) {
1226 gso.flags = VIRTIO_NET_HDR_F_DATA_VALID;
f43798c2
RR
1227 } /* else everything is zero */
1228
43b39dcd
MT
1229 if (unlikely(memcpy_toiovecend(iv, (void *)&gso, total,
1230 sizeof(gso))))
f43798c2 1231 return -EFAULT;
d9d52b51 1232 total += tun->vnet_hdr_sz;
f43798c2
RR
1233 }
1234
6680ec68
JW
1235 if (!vlan_tx_tag_present(skb)) {
1236 len = min_t(int, skb->len, len);
1237 } else {
1238 int copy, ret;
1239 struct {
1240 __be16 h_vlan_proto;
1241 __be16 h_vlan_TCI;
1242 } veth;
1243
1244 veth.h_vlan_proto = skb->vlan_proto;
1245 veth.h_vlan_TCI = htons(vlan_tx_tag_get(skb));
1246
1247 vlan_offset = offsetof(struct vlan_ethhdr, h_vlan_proto);
1248 len = min_t(int, skb->len + VLAN_HLEN, len);
1249
1250 copy = min_t(int, vlan_offset, len);
1251 ret = skb_copy_datagram_const_iovec(skb, 0, iv, total, copy);
1252 len -= copy;
1253 total += copy;
1254 if (ret || !len)
1255 goto done;
1256
1257 copy = min_t(int, sizeof(veth), len);
1258 ret = memcpy_toiovecend(iv, (void *)&veth, total, copy);
1259 len -= copy;
1260 total += copy;
1261 if (ret || !len)
1262 goto done;
1263 }
1da177e4 1264
6680ec68
JW
1265 skb_copy_datagram_const_iovec(skb, vlan_offset, iv, total, len);
1266 total += len;
1da177e4 1267
6680ec68 1268done:
09f75cd7
JG
1269 tun->dev->stats.tx_packets++;
1270 tun->dev->stats.tx_bytes += len;
1da177e4
LT
1271
1272 return total;
1273}
1274
54f968d6 1275static ssize_t tun_do_read(struct tun_struct *tun, struct tun_file *tfile,
05c2828c
MT
1276 struct kiocb *iocb, const struct iovec *iv,
1277 ssize_t len, int noblock)
1da177e4 1278{
1da177e4
LT
1279 DECLARE_WAITQUEUE(wait, current);
1280 struct sk_buff *skb;
05c2828c 1281 ssize_t ret = 0;
1da177e4 1282
3872baf6 1283 tun_debug(KERN_INFO, tun, "tun_do_read\n");
1da177e4 1284
61a5ff15 1285 if (unlikely(!noblock))
54f968d6 1286 add_wait_queue(&tfile->wq.wait, &wait);
1da177e4 1287 while (len) {
1da177e4
LT
1288 current->state = TASK_INTERRUPTIBLE;
1289
1290 /* Read frames from the queue */
54f968d6 1291 if (!(skb = skb_dequeue(&tfile->socket.sk->sk_receive_queue))) {
05c2828c 1292 if (noblock) {
1da177e4
LT
1293 ret = -EAGAIN;
1294 break;
1295 }
1296 if (signal_pending(current)) {
1297 ret = -ERESTARTSYS;
1298 break;
1299 }
c70f1829
EB
1300 if (tun->dev->reg_state != NETREG_REGISTERED) {
1301 ret = -EIO;
1302 break;
1303 }
1da177e4
LT
1304
1305 /* Nothing to read, let's sleep */
1306 schedule();
1307 continue;
1308 }
1da177e4 1309
54f968d6 1310 ret = tun_put_user(tun, tfile, skb, iv, len);
f271b2cc
MK
1311 kfree_skb(skb);
1312 break;
1da177e4
LT
1313 }
1314
1315 current->state = TASK_RUNNING;
61a5ff15 1316 if (unlikely(!noblock))
54f968d6 1317 remove_wait_queue(&tfile->wq.wait, &wait);
1da177e4 1318
05c2828c
MT
1319 return ret;
1320}
1321
1322static ssize_t tun_chr_aio_read(struct kiocb *iocb, const struct iovec *iv,
1323 unsigned long count, loff_t pos)
1324{
1325 struct file *file = iocb->ki_filp;
1326 struct tun_file *tfile = file->private_data;
1327 struct tun_struct *tun = __tun_get(tfile);
1328 ssize_t len, ret;
1329
1330 if (!tun)
1331 return -EBADFD;
1332 len = iov_length(iv, count);
1333 if (len < 0) {
1334 ret = -EINVAL;
1335 goto out;
1336 }
1337
54f968d6
JW
1338 ret = tun_do_read(tun, tfile, iocb, iv, len,
1339 file->f_flags & O_NONBLOCK);
05c2828c 1340 ret = min_t(ssize_t, ret, len);
631ab46b
EB
1341out:
1342 tun_put(tun);
1da177e4
LT
1343 return ret;
1344}
1345
96442e42
JW
1346static void tun_free_netdev(struct net_device *dev)
1347{
1348 struct tun_struct *tun = netdev_priv(dev);
1349
4008e97f 1350 BUG_ON(!(list_empty(&tun->disabled)));
96442e42 1351 tun_flow_uninit(tun);
5dbbaf2d 1352 security_tun_dev_free_security(tun->security);
96442e42
JW
1353 free_netdev(dev);
1354}
1355
1da177e4
LT
1356static void tun_setup(struct net_device *dev)
1357{
1358 struct tun_struct *tun = netdev_priv(dev);
1359
0625c883
EB
1360 tun->owner = INVALID_UID;
1361 tun->group = INVALID_GID;
1da177e4 1362
1da177e4 1363 dev->ethtool_ops = &tun_ethtool_ops;
96442e42 1364 dev->destructor = tun_free_netdev;
1da177e4
LT
1365}
1366
f019a7a5
EB
1367/* Trivial set of netlink ops to allow deleting tun or tap
1368 * device with netlink.
1369 */
1370static int tun_validate(struct nlattr *tb[], struct nlattr *data[])
1371{
1372 return -EINVAL;
1373}
1374
1375static struct rtnl_link_ops tun_link_ops __read_mostly = {
1376 .kind = DRV_NAME,
1377 .priv_size = sizeof(struct tun_struct),
1378 .setup = tun_setup,
1379 .validate = tun_validate,
1380};
1381
33dccbb0
HX
1382static void tun_sock_write_space(struct sock *sk)
1383{
54f968d6 1384 struct tun_file *tfile;
43815482 1385 wait_queue_head_t *wqueue;
33dccbb0
HX
1386
1387 if (!sock_writeable(sk))
1388 return;
1389
33dccbb0
HX
1390 if (!test_and_clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags))
1391 return;
1392
43815482
ED
1393 wqueue = sk_sleep(sk);
1394 if (wqueue && waitqueue_active(wqueue))
1395 wake_up_interruptible_sync_poll(wqueue, POLLOUT |
05c2828c 1396 POLLWRNORM | POLLWRBAND);
c722c625 1397
54f968d6
JW
1398 tfile = container_of(sk, struct tun_file, sk);
1399 kill_fasync(&tfile->fasync, SIGIO, POLL_OUT);
33dccbb0
HX
1400}
1401
05c2828c
MT
1402static int tun_sendmsg(struct kiocb *iocb, struct socket *sock,
1403 struct msghdr *m, size_t total_len)
1404{
54f968d6
JW
1405 int ret;
1406 struct tun_file *tfile = container_of(sock, struct tun_file, socket);
1407 struct tun_struct *tun = __tun_get(tfile);
1408
1409 if (!tun)
1410 return -EBADFD;
54f968d6
JW
1411 ret = tun_get_user(tun, tfile, m->msg_control, m->msg_iov, total_len,
1412 m->msg_iovlen, m->msg_flags & MSG_DONTWAIT);
1413 tun_put(tun);
1414 return ret;
05c2828c
MT
1415}
1416
1417static int tun_recvmsg(struct kiocb *iocb, struct socket *sock,
1418 struct msghdr *m, size_t total_len,
1419 int flags)
1420{
54f968d6
JW
1421 struct tun_file *tfile = container_of(sock, struct tun_file, socket);
1422 struct tun_struct *tun = __tun_get(tfile);
05c2828c 1423 int ret;
54f968d6
JW
1424
1425 if (!tun)
1426 return -EBADFD;
1427
eda29772 1428 if (flags & ~(MSG_DONTWAIT|MSG_TRUNC|MSG_ERRQUEUE)) {
3811ae76
G
1429 ret = -EINVAL;
1430 goto out;
1431 }
eda29772
RC
1432 if (flags & MSG_ERRQUEUE) {
1433 ret = sock_recv_errqueue(sock->sk, m, total_len,
1434 SOL_PACKET, TUN_TX_TIMESTAMP);
1435 goto out;
1436 }
54f968d6 1437 ret = tun_do_read(tun, tfile, iocb, m->msg_iov, total_len,
05c2828c
MT
1438 flags & MSG_DONTWAIT);
1439 if (ret > total_len) {
1440 m->msg_flags |= MSG_TRUNC;
1441 ret = flags & MSG_TRUNC ? ret : total_len;
1442 }
3811ae76 1443out:
54f968d6 1444 tun_put(tun);
05c2828c
MT
1445 return ret;
1446}
1447
1ab5ecb9
SK
1448static int tun_release(struct socket *sock)
1449{
1450 if (sock->sk)
1451 sock_put(sock->sk);
1452 return 0;
1453}
1454
05c2828c
MT
1455/* Ops structure to mimic raw sockets with tun */
1456static const struct proto_ops tun_socket_ops = {
1457 .sendmsg = tun_sendmsg,
1458 .recvmsg = tun_recvmsg,
1ab5ecb9 1459 .release = tun_release,
05c2828c
MT
1460};
1461
33dccbb0
HX
1462static struct proto tun_proto = {
1463 .name = "tun",
1464 .owner = THIS_MODULE,
54f968d6 1465 .obj_size = sizeof(struct tun_file),
33dccbb0 1466};
f019a7a5 1467
980c9e8c
DW
1468static int tun_flags(struct tun_struct *tun)
1469{
1470 int flags = 0;
1471
1472 if (tun->flags & TUN_TUN_DEV)
1473 flags |= IFF_TUN;
1474 else
1475 flags |= IFF_TAP;
1476
1477 if (tun->flags & TUN_NO_PI)
1478 flags |= IFF_NO_PI;
1479
5d097109
MT
1480 /* This flag has no real effect. We track the value for backwards
1481 * compatibility.
1482 */
980c9e8c
DW
1483 if (tun->flags & TUN_ONE_QUEUE)
1484 flags |= IFF_ONE_QUEUE;
1485
1486 if (tun->flags & TUN_VNET_HDR)
1487 flags |= IFF_VNET_HDR;
1488
c8d68e6b
JW
1489 if (tun->flags & TUN_TAP_MQ)
1490 flags |= IFF_MULTI_QUEUE;
1491
274038f8
PE
1492 if (tun->flags & TUN_PERSIST)
1493 flags |= IFF_PERSIST;
1494
980c9e8c
DW
1495 return flags;
1496}
1497
1498static ssize_t tun_show_flags(struct device *dev, struct device_attribute *attr,
1499 char *buf)
1500{
1501 struct tun_struct *tun = netdev_priv(to_net_dev(dev));
1502 return sprintf(buf, "0x%x\n", tun_flags(tun));
1503}
1504
1505static ssize_t tun_show_owner(struct device *dev, struct device_attribute *attr,
1506 char *buf)
1507{
1508 struct tun_struct *tun = netdev_priv(to_net_dev(dev));
0625c883
EB
1509 return uid_valid(tun->owner)?
1510 sprintf(buf, "%u\n",
1511 from_kuid_munged(current_user_ns(), tun->owner)):
1512 sprintf(buf, "-1\n");
980c9e8c
DW
1513}
1514
1515static ssize_t tun_show_group(struct device *dev, struct device_attribute *attr,
1516 char *buf)
1517{
1518 struct tun_struct *tun = netdev_priv(to_net_dev(dev));
0625c883
EB
1519 return gid_valid(tun->group) ?
1520 sprintf(buf, "%u\n",
1521 from_kgid_munged(current_user_ns(), tun->group)):
1522 sprintf(buf, "-1\n");
980c9e8c
DW
1523}
1524
1525static DEVICE_ATTR(tun_flags, 0444, tun_show_flags, NULL);
1526static DEVICE_ATTR(owner, 0444, tun_show_owner, NULL);
1527static DEVICE_ATTR(group, 0444, tun_show_group, NULL);
1528
d647a591 1529static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)
1da177e4
LT
1530{
1531 struct tun_struct *tun;
54f968d6 1532 struct tun_file *tfile = file->private_data;
1da177e4
LT
1533 struct net_device *dev;
1534 int err;
1535
7c0c3b1a
JW
1536 if (tfile->detached)
1537 return -EINVAL;
1538
74a3e5a7
EB
1539 dev = __dev_get_by_name(net, ifr->ifr_name);
1540 if (dev) {
f85ba780
DW
1541 if (ifr->ifr_flags & IFF_TUN_EXCL)
1542 return -EBUSY;
74a3e5a7
EB
1543 if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops)
1544 tun = netdev_priv(dev);
1545 else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops)
1546 tun = netdev_priv(dev);
1547 else
1548 return -EINVAL;
1549
8e6d91ae
JW
1550 if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) !=
1551 !!(tun->flags & TUN_TAP_MQ))
1552 return -EINVAL;
1553
cde8b15f 1554 if (tun_not_capable(tun))
2b980dbd 1555 return -EPERM;
5dbbaf2d 1556 err = security_tun_dev_open(tun->security);
2b980dbd
PM
1557 if (err < 0)
1558 return err;
1559
a7385ba2
EB
1560 err = tun_attach(tun, file);
1561 if (err < 0)
1562 return err;
4008e97f
JW
1563
1564 if (tun->flags & TUN_TAP_MQ &&
e8dbad66
JW
1565 (tun->numqueues + tun->numdisabled > 1)) {
1566 /* One or more queue has already been attached, no need
1567 * to initialize the device again.
1568 */
1569 return 0;
1570 }
6aa20a22 1571 }
1da177e4
LT
1572 else {
1573 char *name;
1574 unsigned long flags = 0;
edfb6a14
JW
1575 int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ?
1576 MAX_TAP_QUEUES : 1;
1da177e4 1577
c260b772 1578 if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
ca6bb5d7 1579 return -EPERM;
2b980dbd
PM
1580 err = security_tun_dev_create();
1581 if (err < 0)
1582 return err;
ca6bb5d7 1583
1da177e4
LT
1584 /* Set dev type */
1585 if (ifr->ifr_flags & IFF_TUN) {
1586 /* TUN device */
1587 flags |= TUN_TUN_DEV;
1588 name = "tun%d";
1589 } else if (ifr->ifr_flags & IFF_TAP) {
1590 /* TAP device */
1591 flags |= TUN_TAP_DEV;
1592 name = "tap%d";
6aa20a22 1593 } else
36989b90 1594 return -EINVAL;
6aa20a22 1595
1da177e4
LT
1596 if (*ifr->ifr_name)
1597 name = ifr->ifr_name;
1598
c8d68e6b 1599 dev = alloc_netdev_mqs(sizeof(struct tun_struct), name,
edfb6a14
JW
1600 tun_setup, queues, queues);
1601
1da177e4
LT
1602 if (!dev)
1603 return -ENOMEM;
1604
fc54c658 1605 dev_net_set(dev, net);
f019a7a5 1606 dev->rtnl_link_ops = &tun_link_ops;
fb7589a1 1607 dev->ifindex = tfile->ifindex;
758e43b7 1608
1da177e4
LT
1609 tun = netdev_priv(dev);
1610 tun->dev = dev;
1611 tun->flags = flags;
f271b2cc 1612 tun->txflt.count = 0;
d9d52b51 1613 tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
33dccbb0 1614
54f968d6
JW
1615 tun->filter_attached = false;
1616 tun->sndbuf = tfile->socket.sk->sk_sndbuf;
33dccbb0 1617
96442e42
JW
1618 spin_lock_init(&tun->lock);
1619
5dbbaf2d
PM
1620 err = security_tun_dev_alloc_security(&tun->security);
1621 if (err < 0)
1622 goto err_free_dev;
2b980dbd 1623
1da177e4 1624 tun_net_init(dev);
944a1376 1625 tun_flow_init(tun);
96442e42 1626
88255375 1627 dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST |
6680ec68
JW
1628 TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX |
1629 NETIF_F_HW_VLAN_STAG_TX;
88255375 1630 dev->features = dev->hw_features;
c0317998 1631 dev->vlan_features = dev->features;
88255375 1632
4008e97f 1633 INIT_LIST_HEAD(&tun->disabled);
eb0fb363
JW
1634 err = tun_attach(tun, file);
1635 if (err < 0)
1636 goto err_free_dev;
1637
1da177e4
LT
1638 err = register_netdevice(tun->dev);
1639 if (err < 0)
54f968d6 1640 goto err_free_dev;
9c3fea6a 1641
980c9e8c
DW
1642 if (device_create_file(&tun->dev->dev, &dev_attr_tun_flags) ||
1643 device_create_file(&tun->dev->dev, &dev_attr_owner) ||
1644 device_create_file(&tun->dev->dev, &dev_attr_group))
6b8a66ee 1645 pr_err("Failed to create tun sysfs files\n");
1da177e4
LT
1646 }
1647
af668b3c
MT
1648 netif_carrier_on(tun->dev);
1649
6b8a66ee 1650 tun_debug(KERN_INFO, tun, "tun_set_iff\n");
1da177e4
LT
1651
1652 if (ifr->ifr_flags & IFF_NO_PI)
1653 tun->flags |= TUN_NO_PI;
a26af1e0
NF
1654 else
1655 tun->flags &= ~TUN_NO_PI;
1da177e4 1656
5d097109
MT
1657 /* This flag has no real effect. We track the value for backwards
1658 * compatibility.
1659 */
1da177e4
LT
1660 if (ifr->ifr_flags & IFF_ONE_QUEUE)
1661 tun->flags |= TUN_ONE_QUEUE;
a26af1e0
NF
1662 else
1663 tun->flags &= ~TUN_ONE_QUEUE;
1da177e4 1664
f43798c2
RR
1665 if (ifr->ifr_flags & IFF_VNET_HDR)
1666 tun->flags |= TUN_VNET_HDR;
1667 else
1668 tun->flags &= ~TUN_VNET_HDR;
1669
c8d68e6b
JW
1670 if (ifr->ifr_flags & IFF_MULTI_QUEUE)
1671 tun->flags |= TUN_TAP_MQ;
1672 else
1673 tun->flags &= ~TUN_TAP_MQ;
1674
e35259a9
MK
1675 /* Make sure persistent devices do not get stuck in
1676 * xoff state.
1677 */
1678 if (netif_running(tun->dev))
c8d68e6b 1679 netif_tx_wake_all_queues(tun->dev);
e35259a9 1680
1da177e4
LT
1681 strcpy(ifr->ifr_name, tun->dev->name);
1682 return 0;
1683
1684 err_free_dev:
1685 free_netdev(dev);
1da177e4
LT
1686 return err;
1687}
1688
9ce99cf6 1689static void tun_get_iff(struct net *net, struct tun_struct *tun,
876bfd4d 1690 struct ifreq *ifr)
e3b99556 1691{
6b8a66ee 1692 tun_debug(KERN_INFO, tun, "tun_get_iff\n");
e3b99556
MM
1693
1694 strcpy(ifr->ifr_name, tun->dev->name);
1695
980c9e8c 1696 ifr->ifr_flags = tun_flags(tun);
e3b99556 1697
e3b99556
MM
1698}
1699
5228ddc9
RR
1700/* This is like a cut-down ethtool ops, except done via tun fd so no
1701 * privs required. */
88255375 1702static int set_offload(struct tun_struct *tun, unsigned long arg)
5228ddc9 1703{
c8f44aff 1704 netdev_features_t features = 0;
5228ddc9
RR
1705
1706 if (arg & TUN_F_CSUM) {
88255375 1707 features |= NETIF_F_HW_CSUM;
5228ddc9
RR
1708 arg &= ~TUN_F_CSUM;
1709
1710 if (arg & (TUN_F_TSO4|TUN_F_TSO6)) {
1711 if (arg & TUN_F_TSO_ECN) {
1712 features |= NETIF_F_TSO_ECN;
1713 arg &= ~TUN_F_TSO_ECN;
1714 }
1715 if (arg & TUN_F_TSO4)
1716 features |= NETIF_F_TSO;
1717 if (arg & TUN_F_TSO6)
1718 features |= NETIF_F_TSO6;
1719 arg &= ~(TUN_F_TSO4|TUN_F_TSO6);
1720 }
e36aa25a
SS
1721
1722 if (arg & TUN_F_UFO) {
1723 features |= NETIF_F_UFO;
1724 arg &= ~TUN_F_UFO;
1725 }
5228ddc9
RR
1726 }
1727
1728 /* This gives the user a way to test for new features in future by
1729 * trying to set them. */
1730 if (arg)
1731 return -EINVAL;
1732
88255375
MM
1733 tun->set_features = features;
1734 netdev_update_features(tun->dev);
5228ddc9
RR
1735
1736 return 0;
1737}
1738
c8d68e6b
JW
1739static void tun_detach_filter(struct tun_struct *tun, int n)
1740{
1741 int i;
1742 struct tun_file *tfile;
1743
1744 for (i = 0; i < n; i++) {
b8deabd3 1745 tfile = rtnl_dereference(tun->tfiles[i]);
c8d68e6b
JW
1746 sk_detach_filter(tfile->socket.sk);
1747 }
1748
1749 tun->filter_attached = false;
1750}
1751
1752static int tun_attach_filter(struct tun_struct *tun)
1753{
1754 int i, ret = 0;
1755 struct tun_file *tfile;
1756
1757 for (i = 0; i < tun->numqueues; i++) {
b8deabd3 1758 tfile = rtnl_dereference(tun->tfiles[i]);
c8d68e6b
JW
1759 ret = sk_attach_filter(&tun->fprog, tfile->socket.sk);
1760 if (ret) {
1761 tun_detach_filter(tun, i);
1762 return ret;
1763 }
1764 }
1765
1766 tun->filter_attached = true;
1767 return ret;
1768}
1769
1770static void tun_set_sndbuf(struct tun_struct *tun)
1771{
1772 struct tun_file *tfile;
1773 int i;
1774
1775 for (i = 0; i < tun->numqueues; i++) {
b8deabd3 1776 tfile = rtnl_dereference(tun->tfiles[i]);
c8d68e6b
JW
1777 tfile->socket.sk->sk_sndbuf = tun->sndbuf;
1778 }
1779}
1780
cde8b15f
JW
1781static int tun_set_queue(struct file *file, struct ifreq *ifr)
1782{
1783 struct tun_file *tfile = file->private_data;
1784 struct tun_struct *tun;
cde8b15f
JW
1785 int ret = 0;
1786
1787 rtnl_lock();
1788
1789 if (ifr->ifr_flags & IFF_ATTACH_QUEUE) {
4008e97f 1790 tun = tfile->detached;
5dbbaf2d 1791 if (!tun) {
cde8b15f 1792 ret = -EINVAL;
5dbbaf2d
PM
1793 goto unlock;
1794 }
1795 ret = security_tun_dev_attach_queue(tun->security);
1796 if (ret < 0)
1797 goto unlock;
1798 ret = tun_attach(tun, file);
4008e97f 1799 } else if (ifr->ifr_flags & IFF_DETACH_QUEUE) {
b8deabd3 1800 tun = rtnl_dereference(tfile->tun);
9e85722d 1801 if (!tun || !(tun->flags & TUN_TAP_MQ) || tfile->detached)
4008e97f
JW
1802 ret = -EINVAL;
1803 else
1804 __tun_detach(tfile, false);
1805 } else
cde8b15f
JW
1806 ret = -EINVAL;
1807
5dbbaf2d 1808unlock:
cde8b15f
JW
1809 rtnl_unlock();
1810 return ret;
1811}
1812
50857e2a
AB
1813static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
1814 unsigned long arg, int ifreq_len)
1da177e4 1815{
36b50bab 1816 struct tun_file *tfile = file->private_data;
631ab46b 1817 struct tun_struct *tun;
1da177e4
LT
1818 void __user* argp = (void __user*)arg;
1819 struct ifreq ifr;
0625c883
EB
1820 kuid_t owner;
1821 kgid_t group;
33dccbb0 1822 int sndbuf;
d9d52b51 1823 int vnet_hdr_sz;
fb7589a1 1824 unsigned int ifindex;
f271b2cc 1825 int ret;
1da177e4 1826
cde8b15f 1827 if (cmd == TUNSETIFF || cmd == TUNSETQUEUE || _IOC_TYPE(cmd) == 0x89) {
50857e2a 1828 if (copy_from_user(&ifr, argp, ifreq_len))
1da177e4 1829 return -EFAULT;
8bbb1813 1830 } else {
a117dacd 1831 memset(&ifr, 0, sizeof(ifr));
8bbb1813 1832 }
631ab46b
EB
1833 if (cmd == TUNGETFEATURES) {
1834 /* Currently this just means: "what IFF flags are valid?".
1835 * This is needed because we never checked for invalid flags on
1836 * TUNSETIFF. */
1837 return put_user(IFF_TUN | IFF_TAP | IFF_NO_PI | IFF_ONE_QUEUE |
cde8b15f 1838 IFF_VNET_HDR | IFF_MULTI_QUEUE,
631ab46b 1839 (unsigned int __user*)argp);
cde8b15f
JW
1840 } else if (cmd == TUNSETQUEUE)
1841 return tun_set_queue(file, &ifr);
631ab46b 1842
c8d68e6b 1843 ret = 0;
876bfd4d
HX
1844 rtnl_lock();
1845
36b50bab 1846 tun = __tun_get(tfile);
1da177e4 1847 if (cmd == TUNSETIFF && !tun) {
1da177e4
LT
1848 ifr.ifr_name[IFNAMSIZ-1] = '\0';
1849
876bfd4d 1850 ret = tun_set_iff(tfile->net, file, &ifr);
1da177e4 1851
876bfd4d
HX
1852 if (ret)
1853 goto unlock;
1da177e4 1854
50857e2a 1855 if (copy_to_user(argp, &ifr, ifreq_len))
876bfd4d
HX
1856 ret = -EFAULT;
1857 goto unlock;
1da177e4 1858 }
fb7589a1
PE
1859 if (cmd == TUNSETIFINDEX) {
1860 ret = -EPERM;
1861 if (tun)
1862 goto unlock;
1863
1864 ret = -EFAULT;
1865 if (copy_from_user(&ifindex, argp, sizeof(ifindex)))
1866 goto unlock;
1867
1868 ret = 0;
1869 tfile->ifindex = ifindex;
1870 goto unlock;
1871 }
1da177e4 1872
876bfd4d 1873 ret = -EBADFD;
1da177e4 1874 if (!tun)
876bfd4d 1875 goto unlock;
1da177e4 1876
1e588338 1877 tun_debug(KERN_INFO, tun, "tun_chr_ioctl cmd %u\n", cmd);
1da177e4 1878
631ab46b 1879 ret = 0;
1da177e4 1880 switch (cmd) {
e3b99556 1881 case TUNGETIFF:
9ce99cf6 1882 tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
e3b99556 1883
50857e2a 1884 if (copy_to_user(argp, &ifr, ifreq_len))
631ab46b 1885 ret = -EFAULT;
e3b99556
MM
1886 break;
1887
1da177e4
LT
1888 case TUNSETNOCSUM:
1889 /* Disable/Enable checksum */
1da177e4 1890
88255375
MM
1891 /* [unimplemented] */
1892 tun_debug(KERN_INFO, tun, "ignored: set checksum %s\n",
6b8a66ee 1893 arg ? "disabled" : "enabled");
1da177e4
LT
1894 break;
1895
1896 case TUNSETPERSIST:
54f968d6
JW
1897 /* Disable/Enable persist mode. Keep an extra reference to the
1898 * module to prevent the module being unprobed.
1899 */
dd38bd85 1900 if (arg && !(tun->flags & TUN_PERSIST)) {
1da177e4 1901 tun->flags |= TUN_PERSIST;
54f968d6 1902 __module_get(THIS_MODULE);
dd38bd85
JW
1903 }
1904 if (!arg && (tun->flags & TUN_PERSIST)) {
1da177e4 1905 tun->flags &= ~TUN_PERSIST;
54f968d6
JW
1906 module_put(THIS_MODULE);
1907 }
1da177e4 1908
6b8a66ee
JP
1909 tun_debug(KERN_INFO, tun, "persist %s\n",
1910 arg ? "enabled" : "disabled");
1da177e4
LT
1911 break;
1912
1913 case TUNSETOWNER:
1914 /* Set owner of the device */
0625c883
EB
1915 owner = make_kuid(current_user_ns(), arg);
1916 if (!uid_valid(owner)) {
1917 ret = -EINVAL;
1918 break;
1919 }
1920 tun->owner = owner;
1e588338 1921 tun_debug(KERN_INFO, tun, "owner set to %u\n",
0625c883 1922 from_kuid(&init_user_ns, tun->owner));
1da177e4
LT
1923 break;
1924
8c644623
GG
1925 case TUNSETGROUP:
1926 /* Set group of the device */
0625c883
EB
1927 group = make_kgid(current_user_ns(), arg);
1928 if (!gid_valid(group)) {
1929 ret = -EINVAL;
1930 break;
1931 }
1932 tun->group = group;
1e588338 1933 tun_debug(KERN_INFO, tun, "group set to %u\n",
0625c883 1934 from_kgid(&init_user_ns, tun->group));
8c644623
GG
1935 break;
1936
ff4cc3ac
MK
1937 case TUNSETLINK:
1938 /* Only allow setting the type when the interface is down */
1939 if (tun->dev->flags & IFF_UP) {
6b8a66ee
JP
1940 tun_debug(KERN_INFO, tun,
1941 "Linktype set failed because interface is up\n");
48abfe05 1942 ret = -EBUSY;
ff4cc3ac
MK
1943 } else {
1944 tun->dev->type = (int) arg;
6b8a66ee
JP
1945 tun_debug(KERN_INFO, tun, "linktype set to %d\n",
1946 tun->dev->type);
48abfe05 1947 ret = 0;
ff4cc3ac 1948 }
631ab46b 1949 break;
ff4cc3ac 1950
1da177e4
LT
1951#ifdef TUN_DEBUG
1952 case TUNSETDEBUG:
1953 tun->debug = arg;
1954 break;
1955#endif
5228ddc9 1956 case TUNSETOFFLOAD:
88255375 1957 ret = set_offload(tun, arg);
631ab46b 1958 break;
5228ddc9 1959
f271b2cc
MK
1960 case TUNSETTXFILTER:
1961 /* Can be set only for TAPs */
631ab46b 1962 ret = -EINVAL;
f271b2cc 1963 if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
631ab46b 1964 break;
c0e5a8c2 1965 ret = update_filter(&tun->txflt, (void __user *)arg);
631ab46b 1966 break;
1da177e4
LT
1967
1968 case SIOCGIFHWADDR:
b595076a 1969 /* Get hw address */
f271b2cc
MK
1970 memcpy(ifr.ifr_hwaddr.sa_data, tun->dev->dev_addr, ETH_ALEN);
1971 ifr.ifr_hwaddr.sa_family = tun->dev->type;
50857e2a 1972 if (copy_to_user(argp, &ifr, ifreq_len))
631ab46b
EB
1973 ret = -EFAULT;
1974 break;
1da177e4
LT
1975
1976 case SIOCSIFHWADDR:
f271b2cc 1977 /* Set hw address */
6b8a66ee
JP
1978 tun_debug(KERN_DEBUG, tun, "set hw address: %pM\n",
1979 ifr.ifr_hwaddr.sa_data);
40102371 1980
40102371 1981 ret = dev_set_mac_address(tun->dev, &ifr.ifr_hwaddr);
631ab46b 1982 break;
33dccbb0
HX
1983
1984 case TUNGETSNDBUF:
54f968d6 1985 sndbuf = tfile->socket.sk->sk_sndbuf;
33dccbb0
HX
1986 if (copy_to_user(argp, &sndbuf, sizeof(sndbuf)))
1987 ret = -EFAULT;
1988 break;
1989
1990 case TUNSETSNDBUF:
1991 if (copy_from_user(&sndbuf, argp, sizeof(sndbuf))) {
1992 ret = -EFAULT;
1993 break;
1994 }
1995
c8d68e6b
JW
1996 tun->sndbuf = sndbuf;
1997 tun_set_sndbuf(tun);
33dccbb0
HX
1998 break;
1999
d9d52b51
MT
2000 case TUNGETVNETHDRSZ:
2001 vnet_hdr_sz = tun->vnet_hdr_sz;
2002 if (copy_to_user(argp, &vnet_hdr_sz, sizeof(vnet_hdr_sz)))
2003 ret = -EFAULT;
2004 break;
2005
2006 case TUNSETVNETHDRSZ:
2007 if (copy_from_user(&vnet_hdr_sz, argp, sizeof(vnet_hdr_sz))) {
2008 ret = -EFAULT;
2009 break;
2010 }
2011 if (vnet_hdr_sz < (int)sizeof(struct virtio_net_hdr)) {
2012 ret = -EINVAL;
2013 break;
2014 }
2015
2016 tun->vnet_hdr_sz = vnet_hdr_sz;
2017 break;
2018
99405162
MT
2019 case TUNATTACHFILTER:
2020 /* Can be set only for TAPs */
2021 ret = -EINVAL;
2022 if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
2023 break;
2024 ret = -EFAULT;
54f968d6 2025 if (copy_from_user(&tun->fprog, argp, sizeof(tun->fprog)))
99405162
MT
2026 break;
2027
c8d68e6b 2028 ret = tun_attach_filter(tun);
99405162
MT
2029 break;
2030
2031 case TUNDETACHFILTER:
2032 /* Can be set only for TAPs */
2033 ret = -EINVAL;
2034 if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
2035 break;
c8d68e6b
JW
2036 ret = 0;
2037 tun_detach_filter(tun, tun->numqueues);
99405162
MT
2038 break;
2039
1da177e4 2040 default:
631ab46b
EB
2041 ret = -EINVAL;
2042 break;
ee289b64 2043 }
1da177e4 2044
876bfd4d
HX
2045unlock:
2046 rtnl_unlock();
2047 if (tun)
2048 tun_put(tun);
631ab46b 2049 return ret;
1da177e4
LT
2050}
2051
50857e2a
AB
2052static long tun_chr_ioctl(struct file *file,
2053 unsigned int cmd, unsigned long arg)
2054{
2055 return __tun_chr_ioctl(file, cmd, arg, sizeof (struct ifreq));
2056}
2057
2058#ifdef CONFIG_COMPAT
2059static long tun_chr_compat_ioctl(struct file *file,
2060 unsigned int cmd, unsigned long arg)
2061{
2062 switch (cmd) {
2063 case TUNSETIFF:
2064 case TUNGETIFF:
2065 case TUNSETTXFILTER:
2066 case TUNGETSNDBUF:
2067 case TUNSETSNDBUF:
2068 case SIOCGIFHWADDR:
2069 case SIOCSIFHWADDR:
2070 arg = (unsigned long)compat_ptr(arg);
2071 break;
2072 default:
2073 arg = (compat_ulong_t)arg;
2074 break;
2075 }
2076
2077 /*
2078 * compat_ifreq is shorter than ifreq, so we must not access beyond
2079 * the end of that structure. All fields that are used in this
2080 * driver are compatible though, we don't need to convert the
2081 * contents.
2082 */
2083 return __tun_chr_ioctl(file, cmd, arg, sizeof(struct compat_ifreq));
2084}
2085#endif /* CONFIG_COMPAT */
2086
1da177e4
LT
2087static int tun_chr_fasync(int fd, struct file *file, int on)
2088{
54f968d6 2089 struct tun_file *tfile = file->private_data;
1da177e4
LT
2090 int ret;
2091
54f968d6 2092 if ((ret = fasync_helper(fd, file, on, &tfile->fasync)) < 0)
9d319522 2093 goto out;
6aa20a22 2094
1da177e4 2095 if (on) {
609d7fa9 2096 ret = __f_setown(file, task_pid(current), PIDTYPE_PID, 0);
1da177e4 2097 if (ret)
9d319522 2098 goto out;
54f968d6 2099 tfile->flags |= TUN_FASYNC;
6aa20a22 2100 } else
54f968d6 2101 tfile->flags &= ~TUN_FASYNC;
9d319522
JC
2102 ret = 0;
2103out:
9d319522 2104 return ret;
1da177e4
LT
2105}
2106
2107static int tun_chr_open(struct inode *inode, struct file * file)
2108{
631ab46b 2109 struct tun_file *tfile;
deed49fb 2110
6b8a66ee 2111 DBG1(KERN_INFO, "tunX: tun_chr_open\n");
631ab46b 2112
54f968d6
JW
2113 tfile = (struct tun_file *)sk_alloc(&init_net, AF_UNSPEC, GFP_KERNEL,
2114 &tun_proto);
631ab46b
EB
2115 if (!tfile)
2116 return -ENOMEM;
6e914fc7 2117 rcu_assign_pointer(tfile->tun, NULL);
36b50bab 2118 tfile->net = get_net(current->nsproxy->net_ns);
54f968d6 2119 tfile->flags = 0;
fb7589a1 2120 tfile->ifindex = 0;
54f968d6
JW
2121
2122 rcu_assign_pointer(tfile->socket.wq, &tfile->wq);
2123 init_waitqueue_head(&tfile->wq.wait);
2124
2125 tfile->socket.file = file;
2126 tfile->socket.ops = &tun_socket_ops;
2127
2128 sock_init_data(&tfile->socket, &tfile->sk);
2129 sk_change_net(&tfile->sk, tfile->net);
2130
2131 tfile->sk.sk_write_space = tun_sock_write_space;
2132 tfile->sk.sk_sndbuf = INT_MAX;
2133
631ab46b 2134 file->private_data = tfile;
54f968d6 2135 set_bit(SOCK_EXTERNALLY_ALLOCATED, &tfile->socket.flags);
4008e97f 2136 INIT_LIST_HEAD(&tfile->next);
54f968d6 2137
19a6afb2
JW
2138 sock_set_flag(&tfile->sk, SOCK_ZEROCOPY);
2139
1da177e4
LT
2140 return 0;
2141}
2142
2143static int tun_chr_close(struct inode *inode, struct file *file)
2144{
631ab46b 2145 struct tun_file *tfile = file->private_data;
54f968d6 2146 struct net *net = tfile->net;
1da177e4 2147
c8d68e6b 2148 tun_detach(tfile, true);
54f968d6 2149 put_net(net);
1da177e4
LT
2150
2151 return 0;
2152}
2153
d54b1fdb 2154static const struct file_operations tun_fops = {
6aa20a22 2155 .owner = THIS_MODULE,
1da177e4 2156 .llseek = no_llseek,
ee0b3e67
BP
2157 .read = do_sync_read,
2158 .aio_read = tun_chr_aio_read,
2159 .write = do_sync_write,
2160 .aio_write = tun_chr_aio_write,
1da177e4 2161 .poll = tun_chr_poll,
50857e2a
AB
2162 .unlocked_ioctl = tun_chr_ioctl,
2163#ifdef CONFIG_COMPAT
2164 .compat_ioctl = tun_chr_compat_ioctl,
2165#endif
1da177e4
LT
2166 .open = tun_chr_open,
2167 .release = tun_chr_close,
6aa20a22 2168 .fasync = tun_chr_fasync
1da177e4
LT
2169};
2170
2171static struct miscdevice tun_miscdev = {
2172 .minor = TUN_MINOR,
2173 .name = "tun",
e454cea2 2174 .nodename = "net/tun",
1da177e4 2175 .fops = &tun_fops,
1da177e4
LT
2176};
2177
2178/* ethtool interface */
2179
2180static int tun_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
2181{
2182 cmd->supported = 0;
2183 cmd->advertising = 0;
70739497 2184 ethtool_cmd_speed_set(cmd, SPEED_10);
1da177e4
LT
2185 cmd->duplex = DUPLEX_FULL;
2186 cmd->port = PORT_TP;
2187 cmd->phy_address = 0;
2188 cmd->transceiver = XCVR_INTERNAL;
2189 cmd->autoneg = AUTONEG_DISABLE;
2190 cmd->maxtxpkt = 0;
2191 cmd->maxrxpkt = 0;
2192 return 0;
2193}
2194
2195static void tun_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
2196{
2197 struct tun_struct *tun = netdev_priv(dev);
2198
33a5ba14
RJ
2199 strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
2200 strlcpy(info->version, DRV_VERSION, sizeof(info->version));
1da177e4
LT
2201
2202 switch (tun->flags & TUN_TYPE_MASK) {
2203 case TUN_TUN_DEV:
33a5ba14 2204 strlcpy(info->bus_info, "tun", sizeof(info->bus_info));
1da177e4
LT
2205 break;
2206 case TUN_TAP_DEV:
33a5ba14 2207 strlcpy(info->bus_info, "tap", sizeof(info->bus_info));
1da177e4
LT
2208 break;
2209 }
2210}
2211
2212static u32 tun_get_msglevel(struct net_device *dev)
2213{
2214#ifdef TUN_DEBUG
2215 struct tun_struct *tun = netdev_priv(dev);
2216 return tun->debug;
2217#else
2218 return -EOPNOTSUPP;
2219#endif
2220}
2221
2222static void tun_set_msglevel(struct net_device *dev, u32 value)
2223{
2224#ifdef TUN_DEBUG
2225 struct tun_struct *tun = netdev_priv(dev);
2226 tun->debug = value;
2227#endif
2228}
2229
7282d491 2230static const struct ethtool_ops tun_ethtool_ops = {
1da177e4
LT
2231 .get_settings = tun_get_settings,
2232 .get_drvinfo = tun_get_drvinfo,
2233 .get_msglevel = tun_get_msglevel,
2234 .set_msglevel = tun_set_msglevel,
bee31369 2235 .get_link = ethtool_op_get_link,
eda29772 2236 .get_ts_info = ethtool_op_get_ts_info,
1da177e4
LT
2237};
2238
79d17604 2239
1da177e4
LT
2240static int __init tun_init(void)
2241{
2242 int ret = 0;
2243
6b8a66ee
JP
2244 pr_info("%s, %s\n", DRV_DESCRIPTION, DRV_VERSION);
2245 pr_info("%s\n", DRV_COPYRIGHT);
1da177e4 2246
f019a7a5 2247 ret = rtnl_link_register(&tun_link_ops);
79d17604 2248 if (ret) {
6b8a66ee 2249 pr_err("Can't register link_ops\n");
f019a7a5 2250 goto err_linkops;
79d17604
PE
2251 }
2252
1da177e4 2253 ret = misc_register(&tun_miscdev);
79d17604 2254 if (ret) {
6b8a66ee 2255 pr_err("Can't register misc device %d\n", TUN_MINOR);
79d17604
PE
2256 goto err_misc;
2257 }
f019a7a5 2258 return 0;
79d17604 2259err_misc:
f019a7a5
EB
2260 rtnl_link_unregister(&tun_link_ops);
2261err_linkops:
1da177e4
LT
2262 return ret;
2263}
2264
2265static void tun_cleanup(void)
2266{
6aa20a22 2267 misc_deregister(&tun_miscdev);
f019a7a5 2268 rtnl_link_unregister(&tun_link_ops);
1da177e4
LT
2269}
2270
05c2828c
MT
2271/* Get an underlying socket object from tun file. Returns error unless file is
2272 * attached to a device. The returned object works like a packet socket, it
2273 * can be used for sock_sendmsg/sock_recvmsg. The caller is responsible for
2274 * holding a reference to the file for as long as the socket is in use. */
2275struct socket *tun_get_socket(struct file *file)
2276{
6e914fc7 2277 struct tun_file *tfile;
05c2828c
MT
2278 if (file->f_op != &tun_fops)
2279 return ERR_PTR(-EINVAL);
6e914fc7
JW
2280 tfile = file->private_data;
2281 if (!tfile)
05c2828c 2282 return ERR_PTR(-EBADFD);
54f968d6 2283 return &tfile->socket;
05c2828c
MT
2284}
2285EXPORT_SYMBOL_GPL(tun_get_socket);
2286
1da177e4
LT
2287module_init(tun_init);
2288module_exit(tun_cleanup);
2289MODULE_DESCRIPTION(DRV_DESCRIPTION);
2290MODULE_AUTHOR(DRV_COPYRIGHT);
2291MODULE_LICENSE("GPL");
2292MODULE_ALIAS_MISCDEV(TUN_MINOR);
578454ff 2293MODULE_ALIAS("devname:net/tun");