tuntap: add ioctl to attach or detach a file form tuntap device
[firefly-linux-kernel-4.4.55.git] / 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 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
207 static 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
213 static 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
253 static void tun_detach(struct tun_file *tfile, bool clean)
254 {
255         rtnl_lock();
256         __tun_detach(tfile, clean);
257         rtnl_unlock();
258 }
259
260 static 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
286 static int tun_attach(struct tun_struct *tun, struct file *file)
287 {
288         struct tun_file *tfile = file->private_data;
289         int err;
290
291         err = -EINVAL;
292         if (rcu_dereference_protected(tfile->tun, lockdep_rtnl_is_held()))
293                 goto out;
294
295         err = -EBUSY;
296         if (!(tun->flags & TUN_TAP_MQ) && tun->numqueues == 1)
297                 goto out;
298
299         err = -E2BIG;
300         if (tun->numqueues == MAX_TAP_QUEUES)
301                 goto out;
302
303         err = 0;
304
305         /* Re-attach the filter to presist device */
306         if (tun->filter_attached == true) {
307                 err = sk_attach_filter(&tun->fprog, tfile->socket.sk);
308                 if (!err)
309                         goto out;
310         }
311         tfile->queue_index = tun->numqueues;
312         rcu_assign_pointer(tfile->tun, tun);
313         rcu_assign_pointer(tun->tfiles[tun->numqueues], tfile);
314         sock_hold(&tfile->sk);
315         tun->numqueues++;
316
317         tun_set_real_num_queues(tun);
318
319         if (tun->numqueues == 1)
320                 netif_carrier_on(tun->dev);
321
322         /* device is allowed to go away first, so no need to hold extra
323          * refcnt.
324          */
325
326 out:
327         return err;
328 }
329
330 static struct tun_struct *__tun_get(struct tun_file *tfile)
331 {
332         struct tun_struct *tun;
333
334         rcu_read_lock();
335         tun = rcu_dereference(tfile->tun);
336         if (tun)
337                 dev_hold(tun->dev);
338         rcu_read_unlock();
339
340         return tun;
341 }
342
343 static struct tun_struct *tun_get(struct file *file)
344 {
345         return __tun_get(file->private_data);
346 }
347
348 static void tun_put(struct tun_struct *tun)
349 {
350         dev_put(tun->dev);
351 }
352
353 /* TAP filtering */
354 static 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
360 static 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
366 static 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
403         /* Remaining multicast addresses are hashed,
404          * unicast will leave the filter disabled. */
405         memset(filter->mask, 0, sizeof(filter->mask));
406         for (; n < uf.count; n++) {
407                 if (!is_multicast_ether_addr(addr[n].u)) {
408                         err = 0; /* no filter */
409                         goto done;
410                 }
411                 addr_hash_set(filter->mask, addr[n].u);
412         }
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
426 done:
427         kfree(addr);
428         return err;
429 }
430
431 /* Returns: 0 - drop, !=0 - accept */
432 static 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++)
441                 if (ether_addr_equal(eh->h_dest, filter->addr[i]))
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  */
455 static 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
463 /* Network device part of the driver */
464
465 static const struct ethtool_ops tun_ethtool_ops;
466
467 /* Net device detach from fd. */
468 static void tun_net_uninit(struct net_device *dev)
469 {
470         tun_detach_all(dev);
471 }
472
473 /* Net device open. */
474 static int tun_net_open(struct net_device *dev)
475 {
476         netif_tx_start_all_queues(dev);
477         return 0;
478 }
479
480 /* Net device close. */
481 static int tun_net_close(struct net_device *dev)
482 {
483         netif_tx_stop_all_queues(dev);
484         return 0;
485 }
486
487 /* Net device start xmit */
488 static netdev_tx_t tun_net_xmit(struct sk_buff *skb, struct net_device *dev)
489 {
490         struct tun_struct *tun = netdev_priv(dev);
491         int txq = skb->queue_mapping;
492         struct tun_file *tfile;
493
494         rcu_read_lock();
495         tfile = rcu_dereference(tun->tfiles[txq]);
496
497         /* Drop packet if interface is not attached */
498         if (txq >= tun->numqueues)
499                 goto drop;
500
501         tun_debug(KERN_INFO, tun, "tun_net_xmit %d\n", skb->len);
502
503         BUG_ON(!tfile);
504
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
511         if (tfile->socket.sk->sk_filter &&
512             sk_filter(tfile->socket.sk, skb))
513                 goto drop;
514
515         /* Limit the number of packets queued by divining txq length with the
516          * number of queues.
517          */
518         if (skb_queue_len(&tfile->socket.sk->sk_receive_queue)
519                           >= dev->tx_queue_len / tun->numqueues){
520                 if (!(tun->flags & TUN_ONE_QUEUE)) {
521                         /* Normal queueing mode. */
522                         /* Packet scheduler handles dropping of further packets. */
523                         netif_stop_subqueue(dev, txq);
524
525                         /* We won't see all dropped packets individually, so overrun
526                          * error is more appropriate. */
527                         dev->stats.tx_fifo_errors++;
528                 } else {
529                         /* Single queue mode.
530                          * Driver handles dropping of all packets itself. */
531                         goto drop;
532                 }
533         }
534
535         /* Orphan the skb - required as we might hang on to it
536          * for indefinite time. */
537         if (unlikely(skb_orphan_frags(skb, GFP_ATOMIC)))
538                 goto drop;
539         skb_orphan(skb);
540
541         /* Enqueue packet */
542         skb_queue_tail(&tfile->socket.sk->sk_receive_queue, skb);
543
544         /* Notify and wake up reader process */
545         if (tfile->flags & TUN_FASYNC)
546                 kill_fasync(&tfile->fasync, SIGIO, POLL_IN);
547         wake_up_interruptible_poll(&tfile->wq.wait, POLLIN |
548                                    POLLRDNORM | POLLRDBAND);
549
550         rcu_read_unlock();
551         return NETDEV_TX_OK;
552
553 drop:
554         dev->stats.tx_dropped++;
555         kfree_skb(skb);
556         rcu_read_unlock();
557         return NETDEV_TX_OK;
558 }
559
560 static void tun_net_mclist(struct net_device *dev)
561 {
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          */
567 }
568
569 #define MIN_MTU 68
570 #define MAX_MTU 65535
571
572 static int
573 tun_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
581 static netdev_features_t tun_net_fix_features(struct net_device *dev,
582         netdev_features_t features)
583 {
584         struct tun_struct *tun = netdev_priv(dev);
585
586         return (features & tun->set_features) | (features & ~TUN_USER_FEATURES);
587 }
588 #ifdef CONFIG_NET_POLL_CONTROLLER
589 static 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
605 static const struct net_device_ops tun_netdev_ops = {
606         .ndo_uninit             = tun_net_uninit,
607         .ndo_open               = tun_net_open,
608         .ndo_stop               = tun_net_close,
609         .ndo_start_xmit         = tun_net_xmit,
610         .ndo_change_mtu         = tun_net_change_mtu,
611         .ndo_fix_features       = tun_net_fix_features,
612         .ndo_select_queue       = tun_select_queue,
613 #ifdef CONFIG_NET_POLL_CONTROLLER
614         .ndo_poll_controller    = tun_poll_controller,
615 #endif
616 };
617
618 static const struct net_device_ops tap_netdev_ops = {
619         .ndo_uninit             = tun_net_uninit,
620         .ndo_open               = tun_net_open,
621         .ndo_stop               = tun_net_close,
622         .ndo_start_xmit         = tun_net_xmit,
623         .ndo_change_mtu         = tun_net_change_mtu,
624         .ndo_fix_features       = tun_net_fix_features,
625         .ndo_set_rx_mode        = tun_net_mclist,
626         .ndo_set_mac_address    = eth_mac_addr,
627         .ndo_validate_addr      = eth_validate_addr,
628         .ndo_select_queue       = tun_select_queue,
629 #ifdef CONFIG_NET_POLL_CONTROLLER
630         .ndo_poll_controller    = tun_poll_controller,
631 #endif
632 };
633
634 /* Initialize net device. */
635 static void tun_net_init(struct net_device *dev)
636 {
637         struct tun_struct *tun = netdev_priv(dev);
638
639         switch (tun->flags & TUN_TYPE_MASK) {
640         case TUN_TUN_DEV:
641                 dev->netdev_ops = &tun_netdev_ops;
642
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 */
649                 dev->type = ARPHRD_NONE;
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:
655                 dev->netdev_ops = &tap_netdev_ops;
656                 /* Ethernet TAP Device */
657                 ether_setup(dev);
658                 dev->priv_flags &= ~IFF_TX_SKB_SHARING;
659
660                 eth_hw_addr_random(dev);
661
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 */
670 static unsigned int tun_chr_poll(struct file *file, poll_table *wait)
671 {
672         struct tun_file *tfile = file->private_data;
673         struct tun_struct *tun = __tun_get(tfile);
674         struct sock *sk;
675         unsigned int mask = 0;
676
677         if (!tun)
678                 return POLLERR;
679
680         sk = tfile->socket.sk;
681
682         tun_debug(KERN_INFO, tun, "tun_chr_poll\n");
683
684         poll_wait(file, &tfile->wq.wait, wait);
685
686         if (!skb_queue_empty(&sk->sk_receive_queue))
687                 mask |= POLLIN | POLLRDNORM;
688
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
694         if (tun->dev->reg_state != NETREG_REGISTERED)
695                 mask = POLLERR;
696
697         tun_put(tun);
698         return mask;
699 }
700
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). */
703 static struct sk_buff *tun_alloc_skb(struct tun_file *tfile,
704                                      size_t prepad, size_t len,
705                                      size_t linear, int noblock)
706 {
707         struct sock *sk = tfile->socket.sk;
708         struct sk_buff *skb;
709         int err;
710
711         /* Under a page?  Don't bother with paged skb. */
712         if (prepad + len < PAGE_SIZE || !linear)
713                 linear = len;
714
715         skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
716                                    &err);
717         if (!skb)
718                 return ERR_PTR(err);
719
720         skb_reserve(skb, prepad);
721         skb_put(skb, linear);
722         skb->data_len = len - linear;
723         skb->len += len - linear;
724
725         return skb;
726 }
727
728 /* set skb frags from iovec, this can move to core network code for reuse */
729 static 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
806 /* Get packet from user space buffer */
807 static 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)
810 {
811         struct tun_pi pi = { 0, cpu_to_be16(ETH_P_IP) };
812         struct sk_buff *skb;
813         size_t len = total_len, align = NET_SKB_PAD;
814         struct virtio_net_hdr gso = { 0 };
815         int offset = 0;
816         int copylen;
817         bool zerocopy = false;
818         int err;
819
820         if (!(tun->flags & TUN_NO_PI)) {
821                 if ((len -= sizeof(pi)) > total_len)
822                         return -EINVAL;
823
824                 if (memcpy_fromiovecend((void *)&pi, iv, 0, sizeof(pi)))
825                         return -EFAULT;
826                 offset += sizeof(pi);
827         }
828
829         if (tun->flags & TUN_VNET_HDR) {
830                 if ((len -= tun->vnet_hdr_sz) > total_len)
831                         return -EINVAL;
832
833                 if (memcpy_fromiovecend((void *)&gso, iv, offset, sizeof(gso)))
834                         return -EFAULT;
835
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
840                 if (gso.hdr_len > len)
841                         return -EINVAL;
842                 offset += tun->vnet_hdr_sz;
843         }
844
845         if ((tun->flags & TUN_TYPE_MASK) == TUN_TAP_DEV) {
846                 align += NET_IP_ALIGN;
847                 if (unlikely(len < ETH_HLEN ||
848                              (gso.hdr_len && gso.hdr_len < ETH_HLEN)))
849                         return -EINVAL;
850         }
851
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
879         skb = tun_alloc_skb(tfile, align, copylen, gso.hdr_len, noblock);
880         if (IS_ERR(skb)) {
881                 if (PTR_ERR(skb) != -EAGAIN)
882                         tun->dev->stats.rx_dropped++;
883                 return PTR_ERR(skb);
884         }
885
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) {
892                 tun->dev->stats.rx_dropped++;
893                 kfree_skb(skb);
894                 return -EFAULT;
895         }
896
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                 }
904         }
905
906         switch (tun->flags & TUN_TYPE_MASK) {
907         case TUN_TUN_DEV:
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
923                 skb_reset_mac_header(skb);
924                 skb->protocol = pi.proto;
925                 skb->dev = tun->dev;
926                 break;
927         case TUN_TAP_DEV:
928                 skb->protocol = eth_type_trans(skb, tun->dev);
929                 break;
930         }
931
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;
941                 case VIRTIO_NET_HDR_GSO_UDP:
942                         skb_shinfo(skb)->gso_type = SKB_GSO_UDP;
943                         break;
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         }
964
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
971         netif_rx_ni(skb);
972
973         tun->dev->stats.rx_packets++;
974         tun->dev->stats.rx_bytes += len;
975
976         return total_len;
977 }
978
979 static ssize_t tun_chr_aio_write(struct kiocb *iocb, const struct iovec *iv,
980                               unsigned long count, loff_t pos)
981 {
982         struct file *file = iocb->ki_filp;
983         struct tun_struct *tun = tun_get(file);
984         struct tun_file *tfile = file->private_data;
985         ssize_t result;
986
987         if (!tun)
988                 return -EBADFD;
989
990         tun_debug(KERN_INFO, tun, "tun_chr_write %ld\n", count);
991
992         result = tun_get_user(tun, tfile, NULL, iv, iov_length(iv, count),
993                               count, file->f_flags & O_NONBLOCK);
994
995         tun_put(tun);
996         return result;
997 }
998
999 /* Put packet to the user space buffer */
1000 static ssize_t tun_put_user(struct tun_struct *tun,
1001                             struct tun_file *tfile,
1002                             struct sk_buff *skb,
1003                             const struct iovec *iv, int len)
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                 }
1016
1017                 if (memcpy_toiovecend(iv, (void *) &pi, 0, sizeof(pi)))
1018                         return -EFAULT;
1019                 total += sizeof(pi);
1020         }
1021
1022         if (tun->flags & TUN_VNET_HDR) {
1023                 struct virtio_net_hdr gso = { 0 }; /* no info leak */
1024                 if ((len -= tun->vnet_hdr_sz) < 0)
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;
1037                         else if (sinfo->gso_type & SKB_GSO_UDP)
1038                                 gso.gso_type = VIRTIO_NET_HDR_GSO_UDP;
1039                         else {
1040                                 pr_err("unexpected GSO type: "
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                         }
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;
1058                         gso.csum_start = skb_checksum_start_offset(skb);
1059                         gso.csum_offset = skb->csum_offset;
1060                 } else if (skb->ip_summed == CHECKSUM_UNNECESSARY) {
1061                         gso.flags = VIRTIO_NET_HDR_F_DATA_VALID;
1062                 } /* else everything is zero */
1063
1064                 if (unlikely(memcpy_toiovecend(iv, (void *)&gso, total,
1065                                                sizeof(gso))))
1066                         return -EFAULT;
1067                 total += tun->vnet_hdr_sz;
1068         }
1069
1070         len = min_t(int, skb->len, len);
1071
1072         skb_copy_datagram_const_iovec(skb, 0, iv, total, len);
1073         total += skb->len;
1074
1075         tun->dev->stats.tx_packets++;
1076         tun->dev->stats.tx_bytes += len;
1077
1078         return total;
1079 }
1080
1081 static ssize_t tun_do_read(struct tun_struct *tun, struct tun_file *tfile,
1082                            struct kiocb *iocb, const struct iovec *iv,
1083                            ssize_t len, int noblock)
1084 {
1085         DECLARE_WAITQUEUE(wait, current);
1086         struct sk_buff *skb;
1087         ssize_t ret = 0;
1088
1089         tun_debug(KERN_INFO, tun, "tun_chr_read\n");
1090
1091         if (unlikely(!noblock))
1092                 add_wait_queue(&tfile->wq.wait, &wait);
1093         while (len) {
1094                 current->state = TASK_INTERRUPTIBLE;
1095
1096                 /* Read frames from the queue */
1097                 if (!(skb = skb_dequeue(&tfile->socket.sk->sk_receive_queue))) {
1098                         if (noblock) {
1099                                 ret = -EAGAIN;
1100                                 break;
1101                         }
1102                         if (signal_pending(current)) {
1103                                 ret = -ERESTARTSYS;
1104                                 break;
1105                         }
1106                         if (tun->dev->reg_state != NETREG_REGISTERED) {
1107                                 ret = -EIO;
1108                                 break;
1109                         }
1110
1111                         /* Nothing to read, let's sleep */
1112                         schedule();
1113                         continue;
1114                 }
1115                 netif_wake_subqueue(tun->dev, tfile->queue_index);
1116
1117                 ret = tun_put_user(tun, tfile, skb, iv, len);
1118                 kfree_skb(skb);
1119                 break;
1120         }
1121
1122         current->state = TASK_RUNNING;
1123         if (unlikely(!noblock))
1124                 remove_wait_queue(&tfile->wq.wait, &wait);
1125
1126         return ret;
1127 }
1128
1129 static 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
1145         ret = tun_do_read(tun, tfile, iocb, iv, len,
1146                           file->f_flags & O_NONBLOCK);
1147         ret = min_t(ssize_t, ret, len);
1148 out:
1149         tun_put(tun);
1150         return ret;
1151 }
1152
1153 static void tun_setup(struct net_device *dev)
1154 {
1155         struct tun_struct *tun = netdev_priv(dev);
1156
1157         tun->owner = INVALID_UID;
1158         tun->group = INVALID_GID;
1159
1160         dev->ethtool_ops = &tun_ethtool_ops;
1161         dev->destructor = free_netdev;
1162 }
1163
1164 /* Trivial set of netlink ops to allow deleting tun or tap
1165  * device with netlink.
1166  */
1167 static int tun_validate(struct nlattr *tb[], struct nlattr *data[])
1168 {
1169         return -EINVAL;
1170 }
1171
1172 static 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
1179 static void tun_sock_write_space(struct sock *sk)
1180 {
1181         struct tun_file *tfile;
1182         wait_queue_head_t *wqueue;
1183
1184         if (!sock_writeable(sk))
1185                 return;
1186
1187         if (!test_and_clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags))
1188                 return;
1189
1190         wqueue = sk_sleep(sk);
1191         if (wqueue && waitqueue_active(wqueue))
1192                 wake_up_interruptible_sync_poll(wqueue, POLLOUT |
1193                                                 POLLWRNORM | POLLWRBAND);
1194
1195         tfile = container_of(sk, struct tun_file, sk);
1196         kill_fasync(&tfile->fasync, SIGIO, POLL_OUT);
1197 }
1198
1199 static int tun_sendmsg(struct kiocb *iocb, struct socket *sock,
1200                        struct msghdr *m, size_t total_len)
1201 {
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;
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;
1212 }
1213
1214
1215 static int tun_recvmsg(struct kiocb *iocb, struct socket *sock,
1216                        struct msghdr *m, size_t total_len,
1217                        int flags)
1218 {
1219         struct tun_file *tfile = container_of(sock, struct tun_file, socket);
1220         struct tun_struct *tun = __tun_get(tfile);
1221         int ret;
1222
1223         if (!tun)
1224                 return -EBADFD;
1225
1226         if (flags & ~(MSG_DONTWAIT|MSG_TRUNC))
1227                 return -EINVAL;
1228         ret = tun_do_read(tun, tfile, iocb, m->msg_iov, total_len,
1229                           flags & MSG_DONTWAIT);
1230         if (ret > total_len) {
1231                 m->msg_flags |= MSG_TRUNC;
1232                 ret = flags & MSG_TRUNC ? ret : total_len;
1233         }
1234         tun_put(tun);
1235         return ret;
1236 }
1237
1238 static int tun_release(struct socket *sock)
1239 {
1240         if (sock->sk)
1241                 sock_put(sock->sk);
1242         return 0;
1243 }
1244
1245 /* Ops structure to mimic raw sockets with tun */
1246 static const struct proto_ops tun_socket_ops = {
1247         .sendmsg = tun_sendmsg,
1248         .recvmsg = tun_recvmsg,
1249         .release = tun_release,
1250 };
1251
1252 static struct proto tun_proto = {
1253         .name           = "tun",
1254         .owner          = THIS_MODULE,
1255         .obj_size       = sizeof(struct tun_file),
1256 };
1257
1258 static 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
1276         if (tun->flags & TUN_TAP_MQ)
1277                 flags |= IFF_MULTI_QUEUE;
1278
1279         return flags;
1280 }
1281
1282 static 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
1289 static 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));
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");
1297 }
1298
1299 static 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));
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");
1307 }
1308
1309 static DEVICE_ATTR(tun_flags, 0444, tun_show_flags, NULL);
1310 static DEVICE_ATTR(owner, 0444, tun_show_owner, NULL);
1311 static DEVICE_ATTR(group, 0444, tun_show_group, NULL);
1312
1313 static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)
1314 {
1315         struct tun_struct *tun;
1316         struct tun_file *tfile = file->private_data;
1317         struct net_device *dev;
1318         int err;
1319
1320         dev = __dev_get_by_name(net, ifr->ifr_name);
1321         if (dev) {
1322                 if (ifr->ifr_flags & IFF_TUN_EXCL)
1323                         return -EBUSY;
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
1331                 if (tun_not_capable(tun))
1332                         return -EPERM;
1333                 err = security_tun_dev_attach(tfile->socket.sk);
1334                 if (err < 0)
1335                         return err;
1336
1337                 err = tun_attach(tun, file);
1338                 if (err < 0)
1339                         return err;
1340         }
1341         else {
1342                 char *name;
1343                 unsigned long flags = 0;
1344
1345                 if (!capable(CAP_NET_ADMIN))
1346                         return -EPERM;
1347                 err = security_tun_dev_create();
1348                 if (err < 0)
1349                         return err;
1350
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";
1360                 } else
1361                         return -EINVAL;
1362
1363                 if (*ifr->ifr_name)
1364                         name = ifr->ifr_name;
1365
1366                 dev = alloc_netdev_mqs(sizeof(struct tun_struct), name,
1367                                        tun_setup,
1368                                        MAX_TAP_QUEUES, MAX_TAP_QUEUES);
1369                 if (!dev)
1370                         return -ENOMEM;
1371
1372                 dev_net_set(dev, net);
1373                 dev->rtnl_link_ops = &tun_link_ops;
1374
1375                 tun = netdev_priv(dev);
1376                 tun->dev = dev;
1377                 tun->flags = flags;
1378                 tun->txflt.count = 0;
1379                 tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
1380
1381                 tun->filter_attached = false;
1382                 tun->sndbuf = tfile->socket.sk->sk_sndbuf;
1383
1384                 security_tun_dev_post_create(&tfile->sk);
1385
1386                 tun_net_init(dev);
1387
1388                 dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST |
1389                         TUN_USER_FEATURES;
1390                 dev->features = dev->hw_features;
1391
1392                 err = register_netdevice(tun->dev);
1393                 if (err < 0)
1394                         goto err_free_dev;
1395
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))
1399                         pr_err("Failed to create tun sysfs files\n");
1400
1401                 err = tun_attach(tun, file);
1402                 if (err < 0)
1403                         goto err_free_dev;
1404         }
1405
1406         tun_debug(KERN_INFO, tun, "tun_set_iff\n");
1407
1408         if (ifr->ifr_flags & IFF_NO_PI)
1409                 tun->flags |= TUN_NO_PI;
1410         else
1411                 tun->flags &= ~TUN_NO_PI;
1412
1413         if (ifr->ifr_flags & IFF_ONE_QUEUE)
1414                 tun->flags |= TUN_ONE_QUEUE;
1415         else
1416                 tun->flags &= ~TUN_ONE_QUEUE;
1417
1418         if (ifr->ifr_flags & IFF_VNET_HDR)
1419                 tun->flags |= TUN_VNET_HDR;
1420         else
1421                 tun->flags &= ~TUN_VNET_HDR;
1422
1423         if (ifr->ifr_flags & IFF_MULTI_QUEUE)
1424                 tun->flags |= TUN_TAP_MQ;
1425         else
1426                 tun->flags &= ~TUN_TAP_MQ;
1427
1428         /* Make sure persistent devices do not get stuck in
1429          * xoff state.
1430          */
1431         if (netif_running(tun->dev))
1432                 netif_tx_wake_all_queues(tun->dev);
1433
1434         strcpy(ifr->ifr_name, tun->dev->name);
1435         return 0;
1436
1437  err_free_dev:
1438         free_netdev(dev);
1439         return err;
1440 }
1441
1442 static int tun_get_iff(struct net *net, struct tun_struct *tun,
1443                        struct ifreq *ifr)
1444 {
1445         tun_debug(KERN_INFO, tun, "tun_get_iff\n");
1446
1447         strcpy(ifr->ifr_name, tun->dev->name);
1448
1449         ifr->ifr_flags = tun_flags(tun);
1450
1451         return 0;
1452 }
1453
1454 /* This is like a cut-down ethtool ops, except done via tun fd so no
1455  * privs required. */
1456 static int set_offload(struct tun_struct *tun, unsigned long arg)
1457 {
1458         netdev_features_t features = 0;
1459
1460         if (arg & TUN_F_CSUM) {
1461                 features |= NETIF_F_HW_CSUM;
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                 }
1475
1476                 if (arg & TUN_F_UFO) {
1477                         features |= NETIF_F_UFO;
1478                         arg &= ~TUN_F_UFO;
1479                 }
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
1487         tun->set_features = features;
1488         netdev_update_features(tun->dev);
1489
1490         return 0;
1491 }
1492
1493 static 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
1507 static 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
1526 static 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
1538 static 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
1567 unlock:
1568         rtnl_unlock();
1569         return ret;
1570 }
1571
1572 static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
1573                             unsigned long arg, int ifreq_len)
1574 {
1575         struct tun_file *tfile = file->private_data;
1576         struct tun_struct *tun;
1577         void __user* argp = (void __user*)arg;
1578         struct ifreq ifr;
1579         kuid_t owner;
1580         kgid_t group;
1581         int sndbuf;
1582         int vnet_hdr_sz;
1583         int ret;
1584
1585         if (cmd == TUNSETIFF || cmd == TUNSETQUEUE || _IOC_TYPE(cmd) == 0x89) {
1586                 if (copy_from_user(&ifr, argp, ifreq_len))
1587                         return -EFAULT;
1588         } else {
1589                 memset(&ifr, 0, sizeof(ifr));
1590         }
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 |
1596                                 IFF_VNET_HDR | IFF_MULTI_QUEUE,
1597                                 (unsigned int __user*)argp);
1598         } else if (cmd == TUNSETQUEUE)
1599                 return tun_set_queue(file, &ifr);
1600
1601         ret = 0;
1602         rtnl_lock();
1603
1604         tun = __tun_get(tfile);
1605         if (cmd == TUNSETIFF && !tun) {
1606                 ifr.ifr_name[IFNAMSIZ-1] = '\0';
1607
1608                 ret = tun_set_iff(tfile->net, file, &ifr);
1609
1610                 if (ret)
1611                         goto unlock;
1612
1613                 if (copy_to_user(argp, &ifr, ifreq_len))
1614                         ret = -EFAULT;
1615                 goto unlock;
1616         }
1617
1618         ret = -EBADFD;
1619         if (!tun)
1620                 goto unlock;
1621
1622         tun_debug(KERN_INFO, tun, "tun_chr_ioctl cmd %u\n", cmd);
1623
1624         ret = 0;
1625         switch (cmd) {
1626         case TUNGETIFF:
1627                 ret = tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
1628                 if (ret)
1629                         break;
1630
1631                 if (copy_to_user(argp, &ifr, ifreq_len))
1632                         ret = -EFAULT;
1633                 break;
1634
1635         case TUNSETNOCSUM:
1636                 /* Disable/Enable checksum */
1637
1638                 /* [unimplemented] */
1639                 tun_debug(KERN_INFO, tun, "ignored: set checksum %s\n",
1640                           arg ? "disabled" : "enabled");
1641                 break;
1642
1643         case TUNSETPERSIST:
1644                 /* Disable/Enable persist mode. Keep an extra reference to the
1645                  * module to prevent the module being unprobed.
1646                  */
1647                 if (arg) {
1648                         tun->flags |= TUN_PERSIST;
1649                         __module_get(THIS_MODULE);
1650                 } else {
1651                         tun->flags &= ~TUN_PERSIST;
1652                         module_put(THIS_MODULE);
1653                 }
1654
1655                 tun_debug(KERN_INFO, tun, "persist %s\n",
1656                           arg ? "enabled" : "disabled");
1657                 break;
1658
1659         case TUNSETOWNER:
1660                 /* Set owner of the device */
1661                 owner = make_kuid(current_user_ns(), arg);
1662                 if (!uid_valid(owner)) {
1663                         ret = -EINVAL;
1664                         break;
1665                 }
1666                 tun->owner = owner;
1667                 tun_debug(KERN_INFO, tun, "owner set to %u\n",
1668                           from_kuid(&init_user_ns, tun->owner));
1669                 break;
1670
1671         case TUNSETGROUP:
1672                 /* Set group of the device */
1673                 group = make_kgid(current_user_ns(), arg);
1674                 if (!gid_valid(group)) {
1675                         ret = -EINVAL;
1676                         break;
1677                 }
1678                 tun->group = group;
1679                 tun_debug(KERN_INFO, tun, "group set to %u\n",
1680                           from_kgid(&init_user_ns, tun->group));
1681                 break;
1682
1683         case TUNSETLINK:
1684                 /* Only allow setting the type when the interface is down */
1685                 if (tun->dev->flags & IFF_UP) {
1686                         tun_debug(KERN_INFO, tun,
1687                                   "Linktype set failed because interface is up\n");
1688                         ret = -EBUSY;
1689                 } else {
1690                         tun->dev->type = (int) arg;
1691                         tun_debug(KERN_INFO, tun, "linktype set to %d\n",
1692                                   tun->dev->type);
1693                         ret = 0;
1694                 }
1695                 break;
1696
1697 #ifdef TUN_DEBUG
1698         case TUNSETDEBUG:
1699                 tun->debug = arg;
1700                 break;
1701 #endif
1702         case TUNSETOFFLOAD:
1703                 ret = set_offload(tun, arg);
1704                 break;
1705
1706         case TUNSETTXFILTER:
1707                 /* Can be set only for TAPs */
1708                 ret = -EINVAL;
1709                 if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
1710                         break;
1711                 ret = update_filter(&tun->txflt, (void __user *)arg);
1712                 break;
1713
1714         case SIOCGIFHWADDR:
1715                 /* Get hw address */
1716                 memcpy(ifr.ifr_hwaddr.sa_data, tun->dev->dev_addr, ETH_ALEN);
1717                 ifr.ifr_hwaddr.sa_family = tun->dev->type;
1718                 if (copy_to_user(argp, &ifr, ifreq_len))
1719                         ret = -EFAULT;
1720                 break;
1721
1722         case SIOCSIFHWADDR:
1723                 /* Set hw address */
1724                 tun_debug(KERN_DEBUG, tun, "set hw address: %pM\n",
1725                           ifr.ifr_hwaddr.sa_data);
1726
1727                 ret = dev_set_mac_address(tun->dev, &ifr.ifr_hwaddr);
1728                 break;
1729
1730         case TUNGETSNDBUF:
1731                 sndbuf = tfile->socket.sk->sk_sndbuf;
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
1742                 tun->sndbuf = sndbuf;
1743                 tun_set_sndbuf(tun);
1744                 break;
1745
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
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;
1771                 if (copy_from_user(&tun->fprog, argp, sizeof(tun->fprog)))
1772                         break;
1773
1774                 ret = tun_attach_filter(tun);
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;
1782                 ret = 0;
1783                 tun_detach_filter(tun, tun->numqueues);
1784                 break;
1785
1786         default:
1787                 ret = -EINVAL;
1788                 break;
1789         }
1790
1791 unlock:
1792         rtnl_unlock();
1793         if (tun)
1794                 tun_put(tun);
1795         return ret;
1796 }
1797
1798 static 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
1805 static 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
1833 static int tun_chr_fasync(int fd, struct file *file, int on)
1834 {
1835         struct tun_file *tfile = file->private_data;
1836         int ret;
1837
1838         if ((ret = fasync_helper(fd, file, on, &tfile->fasync)) < 0)
1839                 goto out;
1840
1841         if (on) {
1842                 ret = __f_setown(file, task_pid(current), PIDTYPE_PID, 0);
1843                 if (ret)
1844                         goto out;
1845                 tfile->flags |= TUN_FASYNC;
1846         } else
1847                 tfile->flags &= ~TUN_FASYNC;
1848         ret = 0;
1849 out:
1850         return ret;
1851 }
1852
1853 static int tun_chr_open(struct inode *inode, struct file * file)
1854 {
1855         struct tun_file *tfile;
1856
1857         DBG1(KERN_INFO, "tunX: tun_chr_open\n");
1858
1859         tfile = (struct tun_file *)sk_alloc(&init_net, AF_UNSPEC, GFP_KERNEL,
1860                                             &tun_proto);
1861         if (!tfile)
1862                 return -ENOMEM;
1863         rcu_assign_pointer(tfile->tun, NULL);
1864         tfile->net = get_net(current->nsproxy->net_ns);
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
1879         file->private_data = tfile;
1880         set_bit(SOCK_EXTERNALLY_ALLOCATED, &tfile->socket.flags);
1881
1882         return 0;
1883 }
1884
1885 static int tun_chr_close(struct inode *inode, struct file *file)
1886 {
1887         struct tun_file *tfile = file->private_data;
1888         struct net *net = tfile->net;
1889
1890         tun_detach(tfile, true);
1891         put_net(net);
1892
1893         return 0;
1894 }
1895
1896 static const struct file_operations tun_fops = {
1897         .owner  = THIS_MODULE,
1898         .llseek = no_llseek,
1899         .read  = do_sync_read,
1900         .aio_read  = tun_chr_aio_read,
1901         .write = do_sync_write,
1902         .aio_write = tun_chr_aio_write,
1903         .poll   = tun_chr_poll,
1904         .unlocked_ioctl = tun_chr_ioctl,
1905 #ifdef CONFIG_COMPAT
1906         .compat_ioctl = tun_chr_compat_ioctl,
1907 #endif
1908         .open   = tun_chr_open,
1909         .release = tun_chr_close,
1910         .fasync = tun_chr_fasync
1911 };
1912
1913 static struct miscdevice tun_miscdev = {
1914         .minor = TUN_MINOR,
1915         .name = "tun",
1916         .nodename = "net/tun",
1917         .fops = &tun_fops,
1918 };
1919
1920 /* ethtool interface */
1921
1922 static int tun_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
1923 {
1924         cmd->supported          = 0;
1925         cmd->advertising        = 0;
1926         ethtool_cmd_speed_set(cmd, SPEED_10);
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
1937 static void tun_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
1938 {
1939         struct tun_struct *tun = netdev_priv(dev);
1940
1941         strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
1942         strlcpy(info->version, DRV_VERSION, sizeof(info->version));
1943
1944         switch (tun->flags & TUN_TYPE_MASK) {
1945         case TUN_TUN_DEV:
1946                 strlcpy(info->bus_info, "tun", sizeof(info->bus_info));
1947                 break;
1948         case TUN_TAP_DEV:
1949                 strlcpy(info->bus_info, "tap", sizeof(info->bus_info));
1950                 break;
1951         }
1952 }
1953
1954 static 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
1964 static 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
1972 static const struct ethtool_ops tun_ethtool_ops = {
1973         .get_settings   = tun_get_settings,
1974         .get_drvinfo    = tun_get_drvinfo,
1975         .get_msglevel   = tun_get_msglevel,
1976         .set_msglevel   = tun_set_msglevel,
1977         .get_link       = ethtool_op_get_link,
1978 };
1979
1980
1981 static int __init tun_init(void)
1982 {
1983         int ret = 0;
1984
1985         pr_info("%s, %s\n", DRV_DESCRIPTION, DRV_VERSION);
1986         pr_info("%s\n", DRV_COPYRIGHT);
1987
1988         ret = rtnl_link_register(&tun_link_ops);
1989         if (ret) {
1990                 pr_err("Can't register link_ops\n");
1991                 goto err_linkops;
1992         }
1993
1994         ret = misc_register(&tun_miscdev);
1995         if (ret) {
1996                 pr_err("Can't register misc device %d\n", TUN_MINOR);
1997                 goto err_misc;
1998         }
1999         return  0;
2000 err_misc:
2001         rtnl_link_unregister(&tun_link_ops);
2002 err_linkops:
2003         return ret;
2004 }
2005
2006 static void tun_cleanup(void)
2007 {
2008         misc_deregister(&tun_miscdev);
2009         rtnl_link_unregister(&tun_link_ops);
2010 }
2011
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. */
2016 struct socket *tun_get_socket(struct file *file)
2017 {
2018         struct tun_file *tfile;
2019         if (file->f_op != &tun_fops)
2020                 return ERR_PTR(-EINVAL);
2021         tfile = file->private_data;
2022         if (!tfile)
2023                 return ERR_PTR(-EBADFD);
2024         return &tfile->socket;
2025 }
2026 EXPORT_SYMBOL_GPL(tun_get_socket);
2027
2028 module_init(tun_init);
2029 module_exit(tun_cleanup);
2030 MODULE_DESCRIPTION(DRV_DESCRIPTION);
2031 MODULE_AUTHOR(DRV_COPYRIGHT);
2032 MODULE_LICENSE("GPL");
2033 MODULE_ALIAS_MISCDEV(TUN_MINOR);
2034 MODULE_ALIAS("devname:net/tun");