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