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