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