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