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