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