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