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