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