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