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