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