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