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