at v6.11-rc1 12118 lines 315 kB view raw
1// SPDX-License-Identifier: GPL-2.0-or-later 2/* 3 * NET3 Protocol independent device support routines. 4 * 5 * Derived from the non IP parts of dev.c 1.0.19 6 * Authors: Ross Biro 7 * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> 8 * Mark Evans, <evansmp@uhura.aston.ac.uk> 9 * 10 * Additional Authors: 11 * Florian la Roche <rzsfl@rz.uni-sb.de> 12 * Alan Cox <gw4pts@gw4pts.ampr.org> 13 * David Hinds <dahinds@users.sourceforge.net> 14 * Alexey Kuznetsov <kuznet@ms2.inr.ac.ru> 15 * Adam Sulmicki <adam@cfar.umd.edu> 16 * Pekka Riikonen <priikone@poesidon.pspt.fi> 17 * 18 * Changes: 19 * D.J. Barrow : Fixed bug where dev->refcnt gets set 20 * to 2 if register_netdev gets called 21 * before net_dev_init & also removed a 22 * few lines of code in the process. 23 * Alan Cox : device private ioctl copies fields back. 24 * Alan Cox : Transmit queue code does relevant 25 * stunts to keep the queue safe. 26 * Alan Cox : Fixed double lock. 27 * Alan Cox : Fixed promisc NULL pointer trap 28 * ???????? : Support the full private ioctl range 29 * Alan Cox : Moved ioctl permission check into 30 * drivers 31 * Tim Kordas : SIOCADDMULTI/SIOCDELMULTI 32 * Alan Cox : 100 backlog just doesn't cut it when 33 * you start doing multicast video 8) 34 * Alan Cox : Rewrote net_bh and list manager. 35 * Alan Cox : Fix ETH_P_ALL echoback lengths. 36 * Alan Cox : Took out transmit every packet pass 37 * Saved a few bytes in the ioctl handler 38 * Alan Cox : Network driver sets packet type before 39 * calling netif_rx. Saves a function 40 * call a packet. 41 * Alan Cox : Hashed net_bh() 42 * Richard Kooijman: Timestamp fixes. 43 * Alan Cox : Wrong field in SIOCGIFDSTADDR 44 * Alan Cox : Device lock protection. 45 * Alan Cox : Fixed nasty side effect of device close 46 * changes. 47 * Rudi Cilibrasi : Pass the right thing to 48 * set_mac_address() 49 * Dave Miller : 32bit quantity for the device lock to 50 * make it work out on a Sparc. 51 * Bjorn Ekwall : Added KERNELD hack. 52 * Alan Cox : Cleaned up the backlog initialise. 53 * Craig Metz : SIOCGIFCONF fix if space for under 54 * 1 device. 55 * Thomas Bogendoerfer : Return ENODEV for dev_open, if there 56 * is no device open function. 57 * Andi Kleen : Fix error reporting for SIOCGIFCONF 58 * Michael Chastain : Fix signed/unsigned for SIOCGIFCONF 59 * Cyrus Durgin : Cleaned for KMOD 60 * Adam Sulmicki : Bug Fix : Network Device Unload 61 * A network device unload needs to purge 62 * the backlog queue. 63 * Paul Rusty Russell : SIOCSIFNAME 64 * Pekka Riikonen : Netdev boot-time settings code 65 * Andrew Morton : Make unregister_netdevice wait 66 * indefinitely on dev->refcnt 67 * J Hadi Salim : - Backlog queue sampling 68 * - netif_rx() feedback 69 */ 70 71#include <linux/uaccess.h> 72#include <linux/bitmap.h> 73#include <linux/capability.h> 74#include <linux/cpu.h> 75#include <linux/types.h> 76#include <linux/kernel.h> 77#include <linux/hash.h> 78#include <linux/slab.h> 79#include <linux/sched.h> 80#include <linux/sched/isolation.h> 81#include <linux/sched/mm.h> 82#include <linux/smpboot.h> 83#include <linux/mutex.h> 84#include <linux/rwsem.h> 85#include <linux/string.h> 86#include <linux/mm.h> 87#include <linux/socket.h> 88#include <linux/sockios.h> 89#include <linux/errno.h> 90#include <linux/interrupt.h> 91#include <linux/if_ether.h> 92#include <linux/netdevice.h> 93#include <linux/etherdevice.h> 94#include <linux/ethtool.h> 95#include <linux/skbuff.h> 96#include <linux/kthread.h> 97#include <linux/bpf.h> 98#include <linux/bpf_trace.h> 99#include <net/net_namespace.h> 100#include <net/sock.h> 101#include <net/busy_poll.h> 102#include <linux/rtnetlink.h> 103#include <linux/stat.h> 104#include <net/dsa.h> 105#include <net/dst.h> 106#include <net/dst_metadata.h> 107#include <net/gro.h> 108#include <net/pkt_sched.h> 109#include <net/pkt_cls.h> 110#include <net/checksum.h> 111#include <net/xfrm.h> 112#include <net/tcx.h> 113#include <linux/highmem.h> 114#include <linux/init.h> 115#include <linux/module.h> 116#include <linux/netpoll.h> 117#include <linux/rcupdate.h> 118#include <linux/delay.h> 119#include <net/iw_handler.h> 120#include <asm/current.h> 121#include <linux/audit.h> 122#include <linux/dmaengine.h> 123#include <linux/err.h> 124#include <linux/ctype.h> 125#include <linux/if_arp.h> 126#include <linux/if_vlan.h> 127#include <linux/ip.h> 128#include <net/ip.h> 129#include <net/mpls.h> 130#include <linux/ipv6.h> 131#include <linux/in.h> 132#include <linux/jhash.h> 133#include <linux/random.h> 134#include <trace/events/napi.h> 135#include <trace/events/net.h> 136#include <trace/events/skb.h> 137#include <trace/events/qdisc.h> 138#include <trace/events/xdp.h> 139#include <linux/inetdevice.h> 140#include <linux/cpu_rmap.h> 141#include <linux/static_key.h> 142#include <linux/hashtable.h> 143#include <linux/vmalloc.h> 144#include <linux/if_macvlan.h> 145#include <linux/errqueue.h> 146#include <linux/hrtimer.h> 147#include <linux/netfilter_netdev.h> 148#include <linux/crash_dump.h> 149#include <linux/sctp.h> 150#include <net/udp_tunnel.h> 151#include <linux/net_namespace.h> 152#include <linux/indirect_call_wrapper.h> 153#include <net/devlink.h> 154#include <linux/pm_runtime.h> 155#include <linux/prandom.h> 156#include <linux/once_lite.h> 157#include <net/netdev_rx_queue.h> 158#include <net/page_pool/types.h> 159#include <net/page_pool/helpers.h> 160#include <net/rps.h> 161 162#include "dev.h" 163#include "net-sysfs.h" 164 165static DEFINE_SPINLOCK(ptype_lock); 166struct list_head ptype_base[PTYPE_HASH_SIZE] __read_mostly; 167 168static int netif_rx_internal(struct sk_buff *skb); 169static int call_netdevice_notifiers_extack(unsigned long val, 170 struct net_device *dev, 171 struct netlink_ext_ack *extack); 172 173static DEFINE_MUTEX(ifalias_mutex); 174 175/* protects napi_hash addition/deletion and napi_gen_id */ 176static DEFINE_SPINLOCK(napi_hash_lock); 177 178static unsigned int napi_gen_id = NR_CPUS; 179static DEFINE_READ_MOSTLY_HASHTABLE(napi_hash, 8); 180 181static DECLARE_RWSEM(devnet_rename_sem); 182 183static inline void dev_base_seq_inc(struct net *net) 184{ 185 unsigned int val = net->dev_base_seq + 1; 186 187 WRITE_ONCE(net->dev_base_seq, val ?: 1); 188} 189 190static inline struct hlist_head *dev_name_hash(struct net *net, const char *name) 191{ 192 unsigned int hash = full_name_hash(net, name, strnlen(name, IFNAMSIZ)); 193 194 return &net->dev_name_head[hash_32(hash, NETDEV_HASHBITS)]; 195} 196 197static inline struct hlist_head *dev_index_hash(struct net *net, int ifindex) 198{ 199 return &net->dev_index_head[ifindex & (NETDEV_HASHENTRIES - 1)]; 200} 201 202#ifndef CONFIG_PREEMPT_RT 203 204static DEFINE_STATIC_KEY_FALSE(use_backlog_threads_key); 205 206static int __init setup_backlog_napi_threads(char *arg) 207{ 208 static_branch_enable(&use_backlog_threads_key); 209 return 0; 210} 211early_param("thread_backlog_napi", setup_backlog_napi_threads); 212 213static bool use_backlog_threads(void) 214{ 215 return static_branch_unlikely(&use_backlog_threads_key); 216} 217 218#else 219 220static bool use_backlog_threads(void) 221{ 222 return true; 223} 224 225#endif 226 227static inline void backlog_lock_irq_save(struct softnet_data *sd, 228 unsigned long *flags) 229{ 230 if (IS_ENABLED(CONFIG_RPS) || use_backlog_threads()) 231 spin_lock_irqsave(&sd->input_pkt_queue.lock, *flags); 232 else 233 local_irq_save(*flags); 234} 235 236static inline void backlog_lock_irq_disable(struct softnet_data *sd) 237{ 238 if (IS_ENABLED(CONFIG_RPS) || use_backlog_threads()) 239 spin_lock_irq(&sd->input_pkt_queue.lock); 240 else 241 local_irq_disable(); 242} 243 244static inline void backlog_unlock_irq_restore(struct softnet_data *sd, 245 unsigned long *flags) 246{ 247 if (IS_ENABLED(CONFIG_RPS) || use_backlog_threads()) 248 spin_unlock_irqrestore(&sd->input_pkt_queue.lock, *flags); 249 else 250 local_irq_restore(*flags); 251} 252 253static inline void backlog_unlock_irq_enable(struct softnet_data *sd) 254{ 255 if (IS_ENABLED(CONFIG_RPS) || use_backlog_threads()) 256 spin_unlock_irq(&sd->input_pkt_queue.lock); 257 else 258 local_irq_enable(); 259} 260 261static struct netdev_name_node *netdev_name_node_alloc(struct net_device *dev, 262 const char *name) 263{ 264 struct netdev_name_node *name_node; 265 266 name_node = kmalloc(sizeof(*name_node), GFP_KERNEL); 267 if (!name_node) 268 return NULL; 269 INIT_HLIST_NODE(&name_node->hlist); 270 name_node->dev = dev; 271 name_node->name = name; 272 return name_node; 273} 274 275static struct netdev_name_node * 276netdev_name_node_head_alloc(struct net_device *dev) 277{ 278 struct netdev_name_node *name_node; 279 280 name_node = netdev_name_node_alloc(dev, dev->name); 281 if (!name_node) 282 return NULL; 283 INIT_LIST_HEAD(&name_node->list); 284 return name_node; 285} 286 287static void netdev_name_node_free(struct netdev_name_node *name_node) 288{ 289 kfree(name_node); 290} 291 292static void netdev_name_node_add(struct net *net, 293 struct netdev_name_node *name_node) 294{ 295 hlist_add_head_rcu(&name_node->hlist, 296 dev_name_hash(net, name_node->name)); 297} 298 299static void netdev_name_node_del(struct netdev_name_node *name_node) 300{ 301 hlist_del_rcu(&name_node->hlist); 302} 303 304static struct netdev_name_node *netdev_name_node_lookup(struct net *net, 305 const char *name) 306{ 307 struct hlist_head *head = dev_name_hash(net, name); 308 struct netdev_name_node *name_node; 309 310 hlist_for_each_entry(name_node, head, hlist) 311 if (!strcmp(name_node->name, name)) 312 return name_node; 313 return NULL; 314} 315 316static struct netdev_name_node *netdev_name_node_lookup_rcu(struct net *net, 317 const char *name) 318{ 319 struct hlist_head *head = dev_name_hash(net, name); 320 struct netdev_name_node *name_node; 321 322 hlist_for_each_entry_rcu(name_node, head, hlist) 323 if (!strcmp(name_node->name, name)) 324 return name_node; 325 return NULL; 326} 327 328bool netdev_name_in_use(struct net *net, const char *name) 329{ 330 return netdev_name_node_lookup(net, name); 331} 332EXPORT_SYMBOL(netdev_name_in_use); 333 334int netdev_name_node_alt_create(struct net_device *dev, const char *name) 335{ 336 struct netdev_name_node *name_node; 337 struct net *net = dev_net(dev); 338 339 name_node = netdev_name_node_lookup(net, name); 340 if (name_node) 341 return -EEXIST; 342 name_node = netdev_name_node_alloc(dev, name); 343 if (!name_node) 344 return -ENOMEM; 345 netdev_name_node_add(net, name_node); 346 /* The node that holds dev->name acts as a head of per-device list. */ 347 list_add_tail_rcu(&name_node->list, &dev->name_node->list); 348 349 return 0; 350} 351 352static void netdev_name_node_alt_free(struct rcu_head *head) 353{ 354 struct netdev_name_node *name_node = 355 container_of(head, struct netdev_name_node, rcu); 356 357 kfree(name_node->name); 358 netdev_name_node_free(name_node); 359} 360 361static void __netdev_name_node_alt_destroy(struct netdev_name_node *name_node) 362{ 363 netdev_name_node_del(name_node); 364 list_del(&name_node->list); 365 call_rcu(&name_node->rcu, netdev_name_node_alt_free); 366} 367 368int netdev_name_node_alt_destroy(struct net_device *dev, const char *name) 369{ 370 struct netdev_name_node *name_node; 371 struct net *net = dev_net(dev); 372 373 name_node = netdev_name_node_lookup(net, name); 374 if (!name_node) 375 return -ENOENT; 376 /* lookup might have found our primary name or a name belonging 377 * to another device. 378 */ 379 if (name_node == dev->name_node || name_node->dev != dev) 380 return -EINVAL; 381 382 __netdev_name_node_alt_destroy(name_node); 383 return 0; 384} 385 386static void netdev_name_node_alt_flush(struct net_device *dev) 387{ 388 struct netdev_name_node *name_node, *tmp; 389 390 list_for_each_entry_safe(name_node, tmp, &dev->name_node->list, list) { 391 list_del(&name_node->list); 392 netdev_name_node_alt_free(&name_node->rcu); 393 } 394} 395 396/* Device list insertion */ 397static void list_netdevice(struct net_device *dev) 398{ 399 struct netdev_name_node *name_node; 400 struct net *net = dev_net(dev); 401 402 ASSERT_RTNL(); 403 404 list_add_tail_rcu(&dev->dev_list, &net->dev_base_head); 405 netdev_name_node_add(net, dev->name_node); 406 hlist_add_head_rcu(&dev->index_hlist, 407 dev_index_hash(net, dev->ifindex)); 408 409 netdev_for_each_altname(dev, name_node) 410 netdev_name_node_add(net, name_node); 411 412 /* We reserved the ifindex, this can't fail */ 413 WARN_ON(xa_store(&net->dev_by_index, dev->ifindex, dev, GFP_KERNEL)); 414 415 dev_base_seq_inc(net); 416} 417 418/* Device list removal 419 * caller must respect a RCU grace period before freeing/reusing dev 420 */ 421static void unlist_netdevice(struct net_device *dev) 422{ 423 struct netdev_name_node *name_node; 424 struct net *net = dev_net(dev); 425 426 ASSERT_RTNL(); 427 428 xa_erase(&net->dev_by_index, dev->ifindex); 429 430 netdev_for_each_altname(dev, name_node) 431 netdev_name_node_del(name_node); 432 433 /* Unlink dev from the device chain */ 434 list_del_rcu(&dev->dev_list); 435 netdev_name_node_del(dev->name_node); 436 hlist_del_rcu(&dev->index_hlist); 437 438 dev_base_seq_inc(dev_net(dev)); 439} 440 441/* 442 * Our notifier list 443 */ 444 445static RAW_NOTIFIER_HEAD(netdev_chain); 446 447/* 448 * Device drivers call our routines to queue packets here. We empty the 449 * queue in the local softnet handler. 450 */ 451 452DEFINE_PER_CPU_ALIGNED(struct softnet_data, softnet_data) = { 453 .process_queue_bh_lock = INIT_LOCAL_LOCK(process_queue_bh_lock), 454}; 455EXPORT_PER_CPU_SYMBOL(softnet_data); 456 457/* Page_pool has a lockless array/stack to alloc/recycle pages. 458 * PP consumers must pay attention to run APIs in the appropriate context 459 * (e.g. NAPI context). 460 */ 461static DEFINE_PER_CPU(struct page_pool *, system_page_pool); 462 463#ifdef CONFIG_LOCKDEP 464/* 465 * register_netdevice() inits txq->_xmit_lock and sets lockdep class 466 * according to dev->type 467 */ 468static const unsigned short netdev_lock_type[] = { 469 ARPHRD_NETROM, ARPHRD_ETHER, ARPHRD_EETHER, ARPHRD_AX25, 470 ARPHRD_PRONET, ARPHRD_CHAOS, ARPHRD_IEEE802, ARPHRD_ARCNET, 471 ARPHRD_APPLETLK, ARPHRD_DLCI, ARPHRD_ATM, ARPHRD_METRICOM, 472 ARPHRD_IEEE1394, ARPHRD_EUI64, ARPHRD_INFINIBAND, ARPHRD_SLIP, 473 ARPHRD_CSLIP, ARPHRD_SLIP6, ARPHRD_CSLIP6, ARPHRD_RSRVD, 474 ARPHRD_ADAPT, ARPHRD_ROSE, ARPHRD_X25, ARPHRD_HWX25, 475 ARPHRD_PPP, ARPHRD_CISCO, ARPHRD_LAPB, ARPHRD_DDCMP, 476 ARPHRD_RAWHDLC, ARPHRD_TUNNEL, ARPHRD_TUNNEL6, ARPHRD_FRAD, 477 ARPHRD_SKIP, ARPHRD_LOOPBACK, ARPHRD_LOCALTLK, ARPHRD_FDDI, 478 ARPHRD_BIF, ARPHRD_SIT, ARPHRD_IPDDP, ARPHRD_IPGRE, 479 ARPHRD_PIMREG, ARPHRD_HIPPI, ARPHRD_ASH, ARPHRD_ECONET, 480 ARPHRD_IRDA, ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL, 481 ARPHRD_FCFABRIC, ARPHRD_IEEE80211, ARPHRD_IEEE80211_PRISM, 482 ARPHRD_IEEE80211_RADIOTAP, ARPHRD_PHONET, ARPHRD_PHONET_PIPE, 483 ARPHRD_IEEE802154, ARPHRD_VOID, ARPHRD_NONE}; 484 485static const char *const netdev_lock_name[] = { 486 "_xmit_NETROM", "_xmit_ETHER", "_xmit_EETHER", "_xmit_AX25", 487 "_xmit_PRONET", "_xmit_CHAOS", "_xmit_IEEE802", "_xmit_ARCNET", 488 "_xmit_APPLETLK", "_xmit_DLCI", "_xmit_ATM", "_xmit_METRICOM", 489 "_xmit_IEEE1394", "_xmit_EUI64", "_xmit_INFINIBAND", "_xmit_SLIP", 490 "_xmit_CSLIP", "_xmit_SLIP6", "_xmit_CSLIP6", "_xmit_RSRVD", 491 "_xmit_ADAPT", "_xmit_ROSE", "_xmit_X25", "_xmit_HWX25", 492 "_xmit_PPP", "_xmit_CISCO", "_xmit_LAPB", "_xmit_DDCMP", 493 "_xmit_RAWHDLC", "_xmit_TUNNEL", "_xmit_TUNNEL6", "_xmit_FRAD", 494 "_xmit_SKIP", "_xmit_LOOPBACK", "_xmit_LOCALTLK", "_xmit_FDDI", 495 "_xmit_BIF", "_xmit_SIT", "_xmit_IPDDP", "_xmit_IPGRE", 496 "_xmit_PIMREG", "_xmit_HIPPI", "_xmit_ASH", "_xmit_ECONET", 497 "_xmit_IRDA", "_xmit_FCPP", "_xmit_FCAL", "_xmit_FCPL", 498 "_xmit_FCFABRIC", "_xmit_IEEE80211", "_xmit_IEEE80211_PRISM", 499 "_xmit_IEEE80211_RADIOTAP", "_xmit_PHONET", "_xmit_PHONET_PIPE", 500 "_xmit_IEEE802154", "_xmit_VOID", "_xmit_NONE"}; 501 502static struct lock_class_key netdev_xmit_lock_key[ARRAY_SIZE(netdev_lock_type)]; 503static struct lock_class_key netdev_addr_lock_key[ARRAY_SIZE(netdev_lock_type)]; 504 505static inline unsigned short netdev_lock_pos(unsigned short dev_type) 506{ 507 int i; 508 509 for (i = 0; i < ARRAY_SIZE(netdev_lock_type); i++) 510 if (netdev_lock_type[i] == dev_type) 511 return i; 512 /* the last key is used by default */ 513 return ARRAY_SIZE(netdev_lock_type) - 1; 514} 515 516static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock, 517 unsigned short dev_type) 518{ 519 int i; 520 521 i = netdev_lock_pos(dev_type); 522 lockdep_set_class_and_name(lock, &netdev_xmit_lock_key[i], 523 netdev_lock_name[i]); 524} 525 526static inline void netdev_set_addr_lockdep_class(struct net_device *dev) 527{ 528 int i; 529 530 i = netdev_lock_pos(dev->type); 531 lockdep_set_class_and_name(&dev->addr_list_lock, 532 &netdev_addr_lock_key[i], 533 netdev_lock_name[i]); 534} 535#else 536static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock, 537 unsigned short dev_type) 538{ 539} 540 541static inline void netdev_set_addr_lockdep_class(struct net_device *dev) 542{ 543} 544#endif 545 546/******************************************************************************* 547 * 548 * Protocol management and registration routines 549 * 550 *******************************************************************************/ 551 552 553/* 554 * Add a protocol ID to the list. Now that the input handler is 555 * smarter we can dispense with all the messy stuff that used to be 556 * here. 557 * 558 * BEWARE!!! Protocol handlers, mangling input packets, 559 * MUST BE last in hash buckets and checking protocol handlers 560 * MUST start from promiscuous ptype_all chain in net_bh. 561 * It is true now, do not change it. 562 * Explanation follows: if protocol handler, mangling packet, will 563 * be the first on list, it is not able to sense, that packet 564 * is cloned and should be copied-on-write, so that it will 565 * change it and subsequent readers will get broken packet. 566 * --ANK (980803) 567 */ 568 569static inline struct list_head *ptype_head(const struct packet_type *pt) 570{ 571 if (pt->type == htons(ETH_P_ALL)) 572 return pt->dev ? &pt->dev->ptype_all : &net_hotdata.ptype_all; 573 else 574 return pt->dev ? &pt->dev->ptype_specific : 575 &ptype_base[ntohs(pt->type) & PTYPE_HASH_MASK]; 576} 577 578/** 579 * dev_add_pack - add packet handler 580 * @pt: packet type declaration 581 * 582 * Add a protocol handler to the networking stack. The passed &packet_type 583 * is linked into kernel lists and may not be freed until it has been 584 * removed from the kernel lists. 585 * 586 * This call does not sleep therefore it can not 587 * guarantee all CPU's that are in middle of receiving packets 588 * will see the new packet type (until the next received packet). 589 */ 590 591void dev_add_pack(struct packet_type *pt) 592{ 593 struct list_head *head = ptype_head(pt); 594 595 spin_lock(&ptype_lock); 596 list_add_rcu(&pt->list, head); 597 spin_unlock(&ptype_lock); 598} 599EXPORT_SYMBOL(dev_add_pack); 600 601/** 602 * __dev_remove_pack - remove packet handler 603 * @pt: packet type declaration 604 * 605 * Remove a protocol handler that was previously added to the kernel 606 * protocol handlers by dev_add_pack(). The passed &packet_type is removed 607 * from the kernel lists and can be freed or reused once this function 608 * returns. 609 * 610 * The packet type might still be in use by receivers 611 * and must not be freed until after all the CPU's have gone 612 * through a quiescent state. 613 */ 614void __dev_remove_pack(struct packet_type *pt) 615{ 616 struct list_head *head = ptype_head(pt); 617 struct packet_type *pt1; 618 619 spin_lock(&ptype_lock); 620 621 list_for_each_entry(pt1, head, list) { 622 if (pt == pt1) { 623 list_del_rcu(&pt->list); 624 goto out; 625 } 626 } 627 628 pr_warn("dev_remove_pack: %p not found\n", pt); 629out: 630 spin_unlock(&ptype_lock); 631} 632EXPORT_SYMBOL(__dev_remove_pack); 633 634/** 635 * dev_remove_pack - remove packet handler 636 * @pt: packet type declaration 637 * 638 * Remove a protocol handler that was previously added to the kernel 639 * protocol handlers by dev_add_pack(). The passed &packet_type is removed 640 * from the kernel lists and can be freed or reused once this function 641 * returns. 642 * 643 * This call sleeps to guarantee that no CPU is looking at the packet 644 * type after return. 645 */ 646void dev_remove_pack(struct packet_type *pt) 647{ 648 __dev_remove_pack(pt); 649 650 synchronize_net(); 651} 652EXPORT_SYMBOL(dev_remove_pack); 653 654 655/******************************************************************************* 656 * 657 * Device Interface Subroutines 658 * 659 *******************************************************************************/ 660 661/** 662 * dev_get_iflink - get 'iflink' value of a interface 663 * @dev: targeted interface 664 * 665 * Indicates the ifindex the interface is linked to. 666 * Physical interfaces have the same 'ifindex' and 'iflink' values. 667 */ 668 669int dev_get_iflink(const struct net_device *dev) 670{ 671 if (dev->netdev_ops && dev->netdev_ops->ndo_get_iflink) 672 return dev->netdev_ops->ndo_get_iflink(dev); 673 674 return READ_ONCE(dev->ifindex); 675} 676EXPORT_SYMBOL(dev_get_iflink); 677 678/** 679 * dev_fill_metadata_dst - Retrieve tunnel egress information. 680 * @dev: targeted interface 681 * @skb: The packet. 682 * 683 * For better visibility of tunnel traffic OVS needs to retrieve 684 * egress tunnel information for a packet. Following API allows 685 * user to get this info. 686 */ 687int dev_fill_metadata_dst(struct net_device *dev, struct sk_buff *skb) 688{ 689 struct ip_tunnel_info *info; 690 691 if (!dev->netdev_ops || !dev->netdev_ops->ndo_fill_metadata_dst) 692 return -EINVAL; 693 694 info = skb_tunnel_info_unclone(skb); 695 if (!info) 696 return -ENOMEM; 697 if (unlikely(!(info->mode & IP_TUNNEL_INFO_TX))) 698 return -EINVAL; 699 700 return dev->netdev_ops->ndo_fill_metadata_dst(dev, skb); 701} 702EXPORT_SYMBOL_GPL(dev_fill_metadata_dst); 703 704static struct net_device_path *dev_fwd_path(struct net_device_path_stack *stack) 705{ 706 int k = stack->num_paths++; 707 708 if (WARN_ON_ONCE(k >= NET_DEVICE_PATH_STACK_MAX)) 709 return NULL; 710 711 return &stack->path[k]; 712} 713 714int dev_fill_forward_path(const struct net_device *dev, const u8 *daddr, 715 struct net_device_path_stack *stack) 716{ 717 const struct net_device *last_dev; 718 struct net_device_path_ctx ctx = { 719 .dev = dev, 720 }; 721 struct net_device_path *path; 722 int ret = 0; 723 724 memcpy(ctx.daddr, daddr, sizeof(ctx.daddr)); 725 stack->num_paths = 0; 726 while (ctx.dev && ctx.dev->netdev_ops->ndo_fill_forward_path) { 727 last_dev = ctx.dev; 728 path = dev_fwd_path(stack); 729 if (!path) 730 return -1; 731 732 memset(path, 0, sizeof(struct net_device_path)); 733 ret = ctx.dev->netdev_ops->ndo_fill_forward_path(&ctx, path); 734 if (ret < 0) 735 return -1; 736 737 if (WARN_ON_ONCE(last_dev == ctx.dev)) 738 return -1; 739 } 740 741 if (!ctx.dev) 742 return ret; 743 744 path = dev_fwd_path(stack); 745 if (!path) 746 return -1; 747 path->type = DEV_PATH_ETHERNET; 748 path->dev = ctx.dev; 749 750 return ret; 751} 752EXPORT_SYMBOL_GPL(dev_fill_forward_path); 753 754/** 755 * __dev_get_by_name - find a device by its name 756 * @net: the applicable net namespace 757 * @name: name to find 758 * 759 * Find an interface by name. Must be called under RTNL semaphore. 760 * If the name is found a pointer to the device is returned. 761 * If the name is not found then %NULL is returned. The 762 * reference counters are not incremented so the caller must be 763 * careful with locks. 764 */ 765 766struct net_device *__dev_get_by_name(struct net *net, const char *name) 767{ 768 struct netdev_name_node *node_name; 769 770 node_name = netdev_name_node_lookup(net, name); 771 return node_name ? node_name->dev : NULL; 772} 773EXPORT_SYMBOL(__dev_get_by_name); 774 775/** 776 * dev_get_by_name_rcu - find a device by its name 777 * @net: the applicable net namespace 778 * @name: name to find 779 * 780 * Find an interface by name. 781 * If the name is found a pointer to the device is returned. 782 * If the name is not found then %NULL is returned. 783 * The reference counters are not incremented so the caller must be 784 * careful with locks. The caller must hold RCU lock. 785 */ 786 787struct net_device *dev_get_by_name_rcu(struct net *net, const char *name) 788{ 789 struct netdev_name_node *node_name; 790 791 node_name = netdev_name_node_lookup_rcu(net, name); 792 return node_name ? node_name->dev : NULL; 793} 794EXPORT_SYMBOL(dev_get_by_name_rcu); 795 796/* Deprecated for new users, call netdev_get_by_name() instead */ 797struct net_device *dev_get_by_name(struct net *net, const char *name) 798{ 799 struct net_device *dev; 800 801 rcu_read_lock(); 802 dev = dev_get_by_name_rcu(net, name); 803 dev_hold(dev); 804 rcu_read_unlock(); 805 return dev; 806} 807EXPORT_SYMBOL(dev_get_by_name); 808 809/** 810 * netdev_get_by_name() - find a device by its name 811 * @net: the applicable net namespace 812 * @name: name to find 813 * @tracker: tracking object for the acquired reference 814 * @gfp: allocation flags for the tracker 815 * 816 * Find an interface by name. This can be called from any 817 * context and does its own locking. The returned handle has 818 * the usage count incremented and the caller must use netdev_put() to 819 * release it when it is no longer needed. %NULL is returned if no 820 * matching device is found. 821 */ 822struct net_device *netdev_get_by_name(struct net *net, const char *name, 823 netdevice_tracker *tracker, gfp_t gfp) 824{ 825 struct net_device *dev; 826 827 dev = dev_get_by_name(net, name); 828 if (dev) 829 netdev_tracker_alloc(dev, tracker, gfp); 830 return dev; 831} 832EXPORT_SYMBOL(netdev_get_by_name); 833 834/** 835 * __dev_get_by_index - find a device by its ifindex 836 * @net: the applicable net namespace 837 * @ifindex: index of device 838 * 839 * Search for an interface by index. Returns %NULL if the device 840 * is not found or a pointer to the device. The device has not 841 * had its reference counter increased so the caller must be careful 842 * about locking. The caller must hold the RTNL semaphore. 843 */ 844 845struct net_device *__dev_get_by_index(struct net *net, int ifindex) 846{ 847 struct net_device *dev; 848 struct hlist_head *head = dev_index_hash(net, ifindex); 849 850 hlist_for_each_entry(dev, head, index_hlist) 851 if (dev->ifindex == ifindex) 852 return dev; 853 854 return NULL; 855} 856EXPORT_SYMBOL(__dev_get_by_index); 857 858/** 859 * dev_get_by_index_rcu - find a device by its ifindex 860 * @net: the applicable net namespace 861 * @ifindex: index of device 862 * 863 * Search for an interface by index. Returns %NULL if the device 864 * is not found or a pointer to the device. The device has not 865 * had its reference counter increased so the caller must be careful 866 * about locking. The caller must hold RCU lock. 867 */ 868 869struct net_device *dev_get_by_index_rcu(struct net *net, int ifindex) 870{ 871 struct net_device *dev; 872 struct hlist_head *head = dev_index_hash(net, ifindex); 873 874 hlist_for_each_entry_rcu(dev, head, index_hlist) 875 if (dev->ifindex == ifindex) 876 return dev; 877 878 return NULL; 879} 880EXPORT_SYMBOL(dev_get_by_index_rcu); 881 882/* Deprecated for new users, call netdev_get_by_index() instead */ 883struct net_device *dev_get_by_index(struct net *net, int ifindex) 884{ 885 struct net_device *dev; 886 887 rcu_read_lock(); 888 dev = dev_get_by_index_rcu(net, ifindex); 889 dev_hold(dev); 890 rcu_read_unlock(); 891 return dev; 892} 893EXPORT_SYMBOL(dev_get_by_index); 894 895/** 896 * netdev_get_by_index() - find a device by its ifindex 897 * @net: the applicable net namespace 898 * @ifindex: index of device 899 * @tracker: tracking object for the acquired reference 900 * @gfp: allocation flags for the tracker 901 * 902 * Search for an interface by index. Returns NULL if the device 903 * is not found or a pointer to the device. The device returned has 904 * had a reference added and the pointer is safe until the user calls 905 * netdev_put() to indicate they have finished with it. 906 */ 907struct net_device *netdev_get_by_index(struct net *net, int ifindex, 908 netdevice_tracker *tracker, gfp_t gfp) 909{ 910 struct net_device *dev; 911 912 dev = dev_get_by_index(net, ifindex); 913 if (dev) 914 netdev_tracker_alloc(dev, tracker, gfp); 915 return dev; 916} 917EXPORT_SYMBOL(netdev_get_by_index); 918 919/** 920 * dev_get_by_napi_id - find a device by napi_id 921 * @napi_id: ID of the NAPI struct 922 * 923 * Search for an interface by NAPI ID. Returns %NULL if the device 924 * is not found or a pointer to the device. The device has not had 925 * its reference counter increased so the caller must be careful 926 * about locking. The caller must hold RCU lock. 927 */ 928 929struct net_device *dev_get_by_napi_id(unsigned int napi_id) 930{ 931 struct napi_struct *napi; 932 933 WARN_ON_ONCE(!rcu_read_lock_held()); 934 935 if (napi_id < MIN_NAPI_ID) 936 return NULL; 937 938 napi = napi_by_id(napi_id); 939 940 return napi ? napi->dev : NULL; 941} 942EXPORT_SYMBOL(dev_get_by_napi_id); 943 944static DEFINE_SEQLOCK(netdev_rename_lock); 945 946void netdev_copy_name(struct net_device *dev, char *name) 947{ 948 unsigned int seq; 949 950 do { 951 seq = read_seqbegin(&netdev_rename_lock); 952 strscpy(name, dev->name, IFNAMSIZ); 953 } while (read_seqretry(&netdev_rename_lock, seq)); 954} 955 956/** 957 * netdev_get_name - get a netdevice name, knowing its ifindex. 958 * @net: network namespace 959 * @name: a pointer to the buffer where the name will be stored. 960 * @ifindex: the ifindex of the interface to get the name from. 961 */ 962int netdev_get_name(struct net *net, char *name, int ifindex) 963{ 964 struct net_device *dev; 965 int ret; 966 967 rcu_read_lock(); 968 969 dev = dev_get_by_index_rcu(net, ifindex); 970 if (!dev) { 971 ret = -ENODEV; 972 goto out; 973 } 974 975 netdev_copy_name(dev, name); 976 977 ret = 0; 978out: 979 rcu_read_unlock(); 980 return ret; 981} 982 983/** 984 * dev_getbyhwaddr_rcu - find a device by its hardware address 985 * @net: the applicable net namespace 986 * @type: media type of device 987 * @ha: hardware address 988 * 989 * Search for an interface by MAC address. Returns NULL if the device 990 * is not found or a pointer to the device. 991 * The caller must hold RCU or RTNL. 992 * The returned device has not had its ref count increased 993 * and the caller must therefore be careful about locking 994 * 995 */ 996 997struct net_device *dev_getbyhwaddr_rcu(struct net *net, unsigned short type, 998 const char *ha) 999{ 1000 struct net_device *dev; 1001 1002 for_each_netdev_rcu(net, dev) 1003 if (dev->type == type && 1004 !memcmp(dev->dev_addr, ha, dev->addr_len)) 1005 return dev; 1006 1007 return NULL; 1008} 1009EXPORT_SYMBOL(dev_getbyhwaddr_rcu); 1010 1011struct net_device *dev_getfirstbyhwtype(struct net *net, unsigned short type) 1012{ 1013 struct net_device *dev, *ret = NULL; 1014 1015 rcu_read_lock(); 1016 for_each_netdev_rcu(net, dev) 1017 if (dev->type == type) { 1018 dev_hold(dev); 1019 ret = dev; 1020 break; 1021 } 1022 rcu_read_unlock(); 1023 return ret; 1024} 1025EXPORT_SYMBOL(dev_getfirstbyhwtype); 1026 1027/** 1028 * __dev_get_by_flags - find any device with given flags 1029 * @net: the applicable net namespace 1030 * @if_flags: IFF_* values 1031 * @mask: bitmask of bits in if_flags to check 1032 * 1033 * Search for any interface with the given flags. Returns NULL if a device 1034 * is not found or a pointer to the device. Must be called inside 1035 * rtnl_lock(), and result refcount is unchanged. 1036 */ 1037 1038struct net_device *__dev_get_by_flags(struct net *net, unsigned short if_flags, 1039 unsigned short mask) 1040{ 1041 struct net_device *dev, *ret; 1042 1043 ASSERT_RTNL(); 1044 1045 ret = NULL; 1046 for_each_netdev(net, dev) { 1047 if (((dev->flags ^ if_flags) & mask) == 0) { 1048 ret = dev; 1049 break; 1050 } 1051 } 1052 return ret; 1053} 1054EXPORT_SYMBOL(__dev_get_by_flags); 1055 1056/** 1057 * dev_valid_name - check if name is okay for network device 1058 * @name: name string 1059 * 1060 * Network device names need to be valid file names to 1061 * allow sysfs to work. We also disallow any kind of 1062 * whitespace. 1063 */ 1064bool dev_valid_name(const char *name) 1065{ 1066 if (*name == '\0') 1067 return false; 1068 if (strnlen(name, IFNAMSIZ) == IFNAMSIZ) 1069 return false; 1070 if (!strcmp(name, ".") || !strcmp(name, "..")) 1071 return false; 1072 1073 while (*name) { 1074 if (*name == '/' || *name == ':' || isspace(*name)) 1075 return false; 1076 name++; 1077 } 1078 return true; 1079} 1080EXPORT_SYMBOL(dev_valid_name); 1081 1082/** 1083 * __dev_alloc_name - allocate a name for a device 1084 * @net: network namespace to allocate the device name in 1085 * @name: name format string 1086 * @res: result name string 1087 * 1088 * Passed a format string - eg "lt%d" it will try and find a suitable 1089 * id. It scans list of devices to build up a free map, then chooses 1090 * the first empty slot. The caller must hold the dev_base or rtnl lock 1091 * while allocating the name and adding the device in order to avoid 1092 * duplicates. 1093 * Limited to bits_per_byte * page size devices (ie 32K on most platforms). 1094 * Returns the number of the unit assigned or a negative errno code. 1095 */ 1096 1097static int __dev_alloc_name(struct net *net, const char *name, char *res) 1098{ 1099 int i = 0; 1100 const char *p; 1101 const int max_netdevices = 8*PAGE_SIZE; 1102 unsigned long *inuse; 1103 struct net_device *d; 1104 char buf[IFNAMSIZ]; 1105 1106 /* Verify the string as this thing may have come from the user. 1107 * There must be one "%d" and no other "%" characters. 1108 */ 1109 p = strchr(name, '%'); 1110 if (!p || p[1] != 'd' || strchr(p + 2, '%')) 1111 return -EINVAL; 1112 1113 /* Use one page as a bit array of possible slots */ 1114 inuse = bitmap_zalloc(max_netdevices, GFP_ATOMIC); 1115 if (!inuse) 1116 return -ENOMEM; 1117 1118 for_each_netdev(net, d) { 1119 struct netdev_name_node *name_node; 1120 1121 netdev_for_each_altname(d, name_node) { 1122 if (!sscanf(name_node->name, name, &i)) 1123 continue; 1124 if (i < 0 || i >= max_netdevices) 1125 continue; 1126 1127 /* avoid cases where sscanf is not exact inverse of printf */ 1128 snprintf(buf, IFNAMSIZ, name, i); 1129 if (!strncmp(buf, name_node->name, IFNAMSIZ)) 1130 __set_bit(i, inuse); 1131 } 1132 if (!sscanf(d->name, name, &i)) 1133 continue; 1134 if (i < 0 || i >= max_netdevices) 1135 continue; 1136 1137 /* avoid cases where sscanf is not exact inverse of printf */ 1138 snprintf(buf, IFNAMSIZ, name, i); 1139 if (!strncmp(buf, d->name, IFNAMSIZ)) 1140 __set_bit(i, inuse); 1141 } 1142 1143 i = find_first_zero_bit(inuse, max_netdevices); 1144 bitmap_free(inuse); 1145 if (i == max_netdevices) 1146 return -ENFILE; 1147 1148 /* 'res' and 'name' could overlap, use 'buf' as an intermediate buffer */ 1149 strscpy(buf, name, IFNAMSIZ); 1150 snprintf(res, IFNAMSIZ, buf, i); 1151 return i; 1152} 1153 1154/* Returns negative errno or allocated unit id (see __dev_alloc_name()) */ 1155static int dev_prep_valid_name(struct net *net, struct net_device *dev, 1156 const char *want_name, char *out_name, 1157 int dup_errno) 1158{ 1159 if (!dev_valid_name(want_name)) 1160 return -EINVAL; 1161 1162 if (strchr(want_name, '%')) 1163 return __dev_alloc_name(net, want_name, out_name); 1164 1165 if (netdev_name_in_use(net, want_name)) 1166 return -dup_errno; 1167 if (out_name != want_name) 1168 strscpy(out_name, want_name, IFNAMSIZ); 1169 return 0; 1170} 1171 1172/** 1173 * dev_alloc_name - allocate a name for a device 1174 * @dev: device 1175 * @name: name format string 1176 * 1177 * Passed a format string - eg "lt%d" it will try and find a suitable 1178 * id. It scans list of devices to build up a free map, then chooses 1179 * the first empty slot. The caller must hold the dev_base or rtnl lock 1180 * while allocating the name and adding the device in order to avoid 1181 * duplicates. 1182 * Limited to bits_per_byte * page size devices (ie 32K on most platforms). 1183 * Returns the number of the unit assigned or a negative errno code. 1184 */ 1185 1186int dev_alloc_name(struct net_device *dev, const char *name) 1187{ 1188 return dev_prep_valid_name(dev_net(dev), dev, name, dev->name, ENFILE); 1189} 1190EXPORT_SYMBOL(dev_alloc_name); 1191 1192static int dev_get_valid_name(struct net *net, struct net_device *dev, 1193 const char *name) 1194{ 1195 int ret; 1196 1197 ret = dev_prep_valid_name(net, dev, name, dev->name, EEXIST); 1198 return ret < 0 ? ret : 0; 1199} 1200 1201/** 1202 * dev_change_name - change name of a device 1203 * @dev: device 1204 * @newname: name (or format string) must be at least IFNAMSIZ 1205 * 1206 * Change name of a device, can pass format strings "eth%d". 1207 * for wildcarding. 1208 */ 1209int dev_change_name(struct net_device *dev, const char *newname) 1210{ 1211 unsigned char old_assign_type; 1212 char oldname[IFNAMSIZ]; 1213 int err = 0; 1214 int ret; 1215 struct net *net; 1216 1217 ASSERT_RTNL(); 1218 BUG_ON(!dev_net(dev)); 1219 1220 net = dev_net(dev); 1221 1222 down_write(&devnet_rename_sem); 1223 1224 if (strncmp(newname, dev->name, IFNAMSIZ) == 0) { 1225 up_write(&devnet_rename_sem); 1226 return 0; 1227 } 1228 1229 memcpy(oldname, dev->name, IFNAMSIZ); 1230 1231 write_seqlock_bh(&netdev_rename_lock); 1232 err = dev_get_valid_name(net, dev, newname); 1233 write_sequnlock_bh(&netdev_rename_lock); 1234 1235 if (err < 0) { 1236 up_write(&devnet_rename_sem); 1237 return err; 1238 } 1239 1240 if (oldname[0] && !strchr(oldname, '%')) 1241 netdev_info(dev, "renamed from %s%s\n", oldname, 1242 dev->flags & IFF_UP ? " (while UP)" : ""); 1243 1244 old_assign_type = dev->name_assign_type; 1245 WRITE_ONCE(dev->name_assign_type, NET_NAME_RENAMED); 1246 1247rollback: 1248 ret = device_rename(&dev->dev, dev->name); 1249 if (ret) { 1250 memcpy(dev->name, oldname, IFNAMSIZ); 1251 WRITE_ONCE(dev->name_assign_type, old_assign_type); 1252 up_write(&devnet_rename_sem); 1253 return ret; 1254 } 1255 1256 up_write(&devnet_rename_sem); 1257 1258 netdev_adjacent_rename_links(dev, oldname); 1259 1260 netdev_name_node_del(dev->name_node); 1261 1262 synchronize_net(); 1263 1264 netdev_name_node_add(net, dev->name_node); 1265 1266 ret = call_netdevice_notifiers(NETDEV_CHANGENAME, dev); 1267 ret = notifier_to_errno(ret); 1268 1269 if (ret) { 1270 /* err >= 0 after dev_alloc_name() or stores the first errno */ 1271 if (err >= 0) { 1272 err = ret; 1273 down_write(&devnet_rename_sem); 1274 write_seqlock_bh(&netdev_rename_lock); 1275 memcpy(dev->name, oldname, IFNAMSIZ); 1276 write_sequnlock_bh(&netdev_rename_lock); 1277 memcpy(oldname, newname, IFNAMSIZ); 1278 WRITE_ONCE(dev->name_assign_type, old_assign_type); 1279 old_assign_type = NET_NAME_RENAMED; 1280 goto rollback; 1281 } else { 1282 netdev_err(dev, "name change rollback failed: %d\n", 1283 ret); 1284 } 1285 } 1286 1287 return err; 1288} 1289 1290/** 1291 * dev_set_alias - change ifalias of a device 1292 * @dev: device 1293 * @alias: name up to IFALIASZ 1294 * @len: limit of bytes to copy from info 1295 * 1296 * Set ifalias for a device, 1297 */ 1298int dev_set_alias(struct net_device *dev, const char *alias, size_t len) 1299{ 1300 struct dev_ifalias *new_alias = NULL; 1301 1302 if (len >= IFALIASZ) 1303 return -EINVAL; 1304 1305 if (len) { 1306 new_alias = kmalloc(sizeof(*new_alias) + len + 1, GFP_KERNEL); 1307 if (!new_alias) 1308 return -ENOMEM; 1309 1310 memcpy(new_alias->ifalias, alias, len); 1311 new_alias->ifalias[len] = 0; 1312 } 1313 1314 mutex_lock(&ifalias_mutex); 1315 new_alias = rcu_replace_pointer(dev->ifalias, new_alias, 1316 mutex_is_locked(&ifalias_mutex)); 1317 mutex_unlock(&ifalias_mutex); 1318 1319 if (new_alias) 1320 kfree_rcu(new_alias, rcuhead); 1321 1322 return len; 1323} 1324EXPORT_SYMBOL(dev_set_alias); 1325 1326/** 1327 * dev_get_alias - get ifalias of a device 1328 * @dev: device 1329 * @name: buffer to store name of ifalias 1330 * @len: size of buffer 1331 * 1332 * get ifalias for a device. Caller must make sure dev cannot go 1333 * away, e.g. rcu read lock or own a reference count to device. 1334 */ 1335int dev_get_alias(const struct net_device *dev, char *name, size_t len) 1336{ 1337 const struct dev_ifalias *alias; 1338 int ret = 0; 1339 1340 rcu_read_lock(); 1341 alias = rcu_dereference(dev->ifalias); 1342 if (alias) 1343 ret = snprintf(name, len, "%s", alias->ifalias); 1344 rcu_read_unlock(); 1345 1346 return ret; 1347} 1348 1349/** 1350 * netdev_features_change - device changes features 1351 * @dev: device to cause notification 1352 * 1353 * Called to indicate a device has changed features. 1354 */ 1355void netdev_features_change(struct net_device *dev) 1356{ 1357 call_netdevice_notifiers(NETDEV_FEAT_CHANGE, dev); 1358} 1359EXPORT_SYMBOL(netdev_features_change); 1360 1361/** 1362 * netdev_state_change - device changes state 1363 * @dev: device to cause notification 1364 * 1365 * Called to indicate a device has changed state. This function calls 1366 * the notifier chains for netdev_chain and sends a NEWLINK message 1367 * to the routing socket. 1368 */ 1369void netdev_state_change(struct net_device *dev) 1370{ 1371 if (dev->flags & IFF_UP) { 1372 struct netdev_notifier_change_info change_info = { 1373 .info.dev = dev, 1374 }; 1375 1376 call_netdevice_notifiers_info(NETDEV_CHANGE, 1377 &change_info.info); 1378 rtmsg_ifinfo(RTM_NEWLINK, dev, 0, GFP_KERNEL, 0, NULL); 1379 } 1380} 1381EXPORT_SYMBOL(netdev_state_change); 1382 1383/** 1384 * __netdev_notify_peers - notify network peers about existence of @dev, 1385 * to be called when rtnl lock is already held. 1386 * @dev: network device 1387 * 1388 * Generate traffic such that interested network peers are aware of 1389 * @dev, such as by generating a gratuitous ARP. This may be used when 1390 * a device wants to inform the rest of the network about some sort of 1391 * reconfiguration such as a failover event or virtual machine 1392 * migration. 1393 */ 1394void __netdev_notify_peers(struct net_device *dev) 1395{ 1396 ASSERT_RTNL(); 1397 call_netdevice_notifiers(NETDEV_NOTIFY_PEERS, dev); 1398 call_netdevice_notifiers(NETDEV_RESEND_IGMP, dev); 1399} 1400EXPORT_SYMBOL(__netdev_notify_peers); 1401 1402/** 1403 * netdev_notify_peers - notify network peers about existence of @dev 1404 * @dev: network device 1405 * 1406 * Generate traffic such that interested network peers are aware of 1407 * @dev, such as by generating a gratuitous ARP. This may be used when 1408 * a device wants to inform the rest of the network about some sort of 1409 * reconfiguration such as a failover event or virtual machine 1410 * migration. 1411 */ 1412void netdev_notify_peers(struct net_device *dev) 1413{ 1414 rtnl_lock(); 1415 __netdev_notify_peers(dev); 1416 rtnl_unlock(); 1417} 1418EXPORT_SYMBOL(netdev_notify_peers); 1419 1420static int napi_threaded_poll(void *data); 1421 1422static int napi_kthread_create(struct napi_struct *n) 1423{ 1424 int err = 0; 1425 1426 /* Create and wake up the kthread once to put it in 1427 * TASK_INTERRUPTIBLE mode to avoid the blocked task 1428 * warning and work with loadavg. 1429 */ 1430 n->thread = kthread_run(napi_threaded_poll, n, "napi/%s-%d", 1431 n->dev->name, n->napi_id); 1432 if (IS_ERR(n->thread)) { 1433 err = PTR_ERR(n->thread); 1434 pr_err("kthread_run failed with err %d\n", err); 1435 n->thread = NULL; 1436 } 1437 1438 return err; 1439} 1440 1441static int __dev_open(struct net_device *dev, struct netlink_ext_ack *extack) 1442{ 1443 const struct net_device_ops *ops = dev->netdev_ops; 1444 int ret; 1445 1446 ASSERT_RTNL(); 1447 dev_addr_check(dev); 1448 1449 if (!netif_device_present(dev)) { 1450 /* may be detached because parent is runtime-suspended */ 1451 if (dev->dev.parent) 1452 pm_runtime_resume(dev->dev.parent); 1453 if (!netif_device_present(dev)) 1454 return -ENODEV; 1455 } 1456 1457 /* Block netpoll from trying to do any rx path servicing. 1458 * If we don't do this there is a chance ndo_poll_controller 1459 * or ndo_poll may be running while we open the device 1460 */ 1461 netpoll_poll_disable(dev); 1462 1463 ret = call_netdevice_notifiers_extack(NETDEV_PRE_UP, dev, extack); 1464 ret = notifier_to_errno(ret); 1465 if (ret) 1466 return ret; 1467 1468 set_bit(__LINK_STATE_START, &dev->state); 1469 1470 if (ops->ndo_validate_addr) 1471 ret = ops->ndo_validate_addr(dev); 1472 1473 if (!ret && ops->ndo_open) 1474 ret = ops->ndo_open(dev); 1475 1476 netpoll_poll_enable(dev); 1477 1478 if (ret) 1479 clear_bit(__LINK_STATE_START, &dev->state); 1480 else { 1481 dev->flags |= IFF_UP; 1482 dev_set_rx_mode(dev); 1483 dev_activate(dev); 1484 add_device_randomness(dev->dev_addr, dev->addr_len); 1485 } 1486 1487 return ret; 1488} 1489 1490/** 1491 * dev_open - prepare an interface for use. 1492 * @dev: device to open 1493 * @extack: netlink extended ack 1494 * 1495 * Takes a device from down to up state. The device's private open 1496 * function is invoked and then the multicast lists are loaded. Finally 1497 * the device is moved into the up state and a %NETDEV_UP message is 1498 * sent to the netdev notifier chain. 1499 * 1500 * Calling this function on an active interface is a nop. On a failure 1501 * a negative errno code is returned. 1502 */ 1503int dev_open(struct net_device *dev, struct netlink_ext_ack *extack) 1504{ 1505 int ret; 1506 1507 if (dev->flags & IFF_UP) 1508 return 0; 1509 1510 ret = __dev_open(dev, extack); 1511 if (ret < 0) 1512 return ret; 1513 1514 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP | IFF_RUNNING, GFP_KERNEL, 0, NULL); 1515 call_netdevice_notifiers(NETDEV_UP, dev); 1516 1517 return ret; 1518} 1519EXPORT_SYMBOL(dev_open); 1520 1521static void __dev_close_many(struct list_head *head) 1522{ 1523 struct net_device *dev; 1524 1525 ASSERT_RTNL(); 1526 might_sleep(); 1527 1528 list_for_each_entry(dev, head, close_list) { 1529 /* Temporarily disable netpoll until the interface is down */ 1530 netpoll_poll_disable(dev); 1531 1532 call_netdevice_notifiers(NETDEV_GOING_DOWN, dev); 1533 1534 clear_bit(__LINK_STATE_START, &dev->state); 1535 1536 /* Synchronize to scheduled poll. We cannot touch poll list, it 1537 * can be even on different cpu. So just clear netif_running(). 1538 * 1539 * dev->stop() will invoke napi_disable() on all of it's 1540 * napi_struct instances on this device. 1541 */ 1542 smp_mb__after_atomic(); /* Commit netif_running(). */ 1543 } 1544 1545 dev_deactivate_many(head); 1546 1547 list_for_each_entry(dev, head, close_list) { 1548 const struct net_device_ops *ops = dev->netdev_ops; 1549 1550 /* 1551 * Call the device specific close. This cannot fail. 1552 * Only if device is UP 1553 * 1554 * We allow it to be called even after a DETACH hot-plug 1555 * event. 1556 */ 1557 if (ops->ndo_stop) 1558 ops->ndo_stop(dev); 1559 1560 dev->flags &= ~IFF_UP; 1561 netpoll_poll_enable(dev); 1562 } 1563} 1564 1565static void __dev_close(struct net_device *dev) 1566{ 1567 LIST_HEAD(single); 1568 1569 list_add(&dev->close_list, &single); 1570 __dev_close_many(&single); 1571 list_del(&single); 1572} 1573 1574void dev_close_many(struct list_head *head, bool unlink) 1575{ 1576 struct net_device *dev, *tmp; 1577 1578 /* Remove the devices that don't need to be closed */ 1579 list_for_each_entry_safe(dev, tmp, head, close_list) 1580 if (!(dev->flags & IFF_UP)) 1581 list_del_init(&dev->close_list); 1582 1583 __dev_close_many(head); 1584 1585 list_for_each_entry_safe(dev, tmp, head, close_list) { 1586 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP | IFF_RUNNING, GFP_KERNEL, 0, NULL); 1587 call_netdevice_notifiers(NETDEV_DOWN, dev); 1588 if (unlink) 1589 list_del_init(&dev->close_list); 1590 } 1591} 1592EXPORT_SYMBOL(dev_close_many); 1593 1594/** 1595 * dev_close - shutdown an interface. 1596 * @dev: device to shutdown 1597 * 1598 * This function moves an active device into down state. A 1599 * %NETDEV_GOING_DOWN is sent to the netdev notifier chain. The device 1600 * is then deactivated and finally a %NETDEV_DOWN is sent to the notifier 1601 * chain. 1602 */ 1603void dev_close(struct net_device *dev) 1604{ 1605 if (dev->flags & IFF_UP) { 1606 LIST_HEAD(single); 1607 1608 list_add(&dev->close_list, &single); 1609 dev_close_many(&single, true); 1610 list_del(&single); 1611 } 1612} 1613EXPORT_SYMBOL(dev_close); 1614 1615 1616/** 1617 * dev_disable_lro - disable Large Receive Offload on a device 1618 * @dev: device 1619 * 1620 * Disable Large Receive Offload (LRO) on a net device. Must be 1621 * called under RTNL. This is needed if received packets may be 1622 * forwarded to another interface. 1623 */ 1624void dev_disable_lro(struct net_device *dev) 1625{ 1626 struct net_device *lower_dev; 1627 struct list_head *iter; 1628 1629 dev->wanted_features &= ~NETIF_F_LRO; 1630 netdev_update_features(dev); 1631 1632 if (unlikely(dev->features & NETIF_F_LRO)) 1633 netdev_WARN(dev, "failed to disable LRO!\n"); 1634 1635 netdev_for_each_lower_dev(dev, lower_dev, iter) 1636 dev_disable_lro(lower_dev); 1637} 1638EXPORT_SYMBOL(dev_disable_lro); 1639 1640/** 1641 * dev_disable_gro_hw - disable HW Generic Receive Offload on a device 1642 * @dev: device 1643 * 1644 * Disable HW Generic Receive Offload (GRO_HW) on a net device. Must be 1645 * called under RTNL. This is needed if Generic XDP is installed on 1646 * the device. 1647 */ 1648static void dev_disable_gro_hw(struct net_device *dev) 1649{ 1650 dev->wanted_features &= ~NETIF_F_GRO_HW; 1651 netdev_update_features(dev); 1652 1653 if (unlikely(dev->features & NETIF_F_GRO_HW)) 1654 netdev_WARN(dev, "failed to disable GRO_HW!\n"); 1655} 1656 1657const char *netdev_cmd_to_name(enum netdev_cmd cmd) 1658{ 1659#define N(val) \ 1660 case NETDEV_##val: \ 1661 return "NETDEV_" __stringify(val); 1662 switch (cmd) { 1663 N(UP) N(DOWN) N(REBOOT) N(CHANGE) N(REGISTER) N(UNREGISTER) 1664 N(CHANGEMTU) N(CHANGEADDR) N(GOING_DOWN) N(CHANGENAME) N(FEAT_CHANGE) 1665 N(BONDING_FAILOVER) N(PRE_UP) N(PRE_TYPE_CHANGE) N(POST_TYPE_CHANGE) 1666 N(POST_INIT) N(PRE_UNINIT) N(RELEASE) N(NOTIFY_PEERS) N(JOIN) 1667 N(CHANGEUPPER) N(RESEND_IGMP) N(PRECHANGEMTU) N(CHANGEINFODATA) 1668 N(BONDING_INFO) N(PRECHANGEUPPER) N(CHANGELOWERSTATE) 1669 N(UDP_TUNNEL_PUSH_INFO) N(UDP_TUNNEL_DROP_INFO) N(CHANGE_TX_QUEUE_LEN) 1670 N(CVLAN_FILTER_PUSH_INFO) N(CVLAN_FILTER_DROP_INFO) 1671 N(SVLAN_FILTER_PUSH_INFO) N(SVLAN_FILTER_DROP_INFO) 1672 N(PRE_CHANGEADDR) N(OFFLOAD_XSTATS_ENABLE) N(OFFLOAD_XSTATS_DISABLE) 1673 N(OFFLOAD_XSTATS_REPORT_USED) N(OFFLOAD_XSTATS_REPORT_DELTA) 1674 N(XDP_FEAT_CHANGE) 1675 } 1676#undef N 1677 return "UNKNOWN_NETDEV_EVENT"; 1678} 1679EXPORT_SYMBOL_GPL(netdev_cmd_to_name); 1680 1681static int call_netdevice_notifier(struct notifier_block *nb, unsigned long val, 1682 struct net_device *dev) 1683{ 1684 struct netdev_notifier_info info = { 1685 .dev = dev, 1686 }; 1687 1688 return nb->notifier_call(nb, val, &info); 1689} 1690 1691static int call_netdevice_register_notifiers(struct notifier_block *nb, 1692 struct net_device *dev) 1693{ 1694 int err; 1695 1696 err = call_netdevice_notifier(nb, NETDEV_REGISTER, dev); 1697 err = notifier_to_errno(err); 1698 if (err) 1699 return err; 1700 1701 if (!(dev->flags & IFF_UP)) 1702 return 0; 1703 1704 call_netdevice_notifier(nb, NETDEV_UP, dev); 1705 return 0; 1706} 1707 1708static void call_netdevice_unregister_notifiers(struct notifier_block *nb, 1709 struct net_device *dev) 1710{ 1711 if (dev->flags & IFF_UP) { 1712 call_netdevice_notifier(nb, NETDEV_GOING_DOWN, 1713 dev); 1714 call_netdevice_notifier(nb, NETDEV_DOWN, dev); 1715 } 1716 call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev); 1717} 1718 1719static int call_netdevice_register_net_notifiers(struct notifier_block *nb, 1720 struct net *net) 1721{ 1722 struct net_device *dev; 1723 int err; 1724 1725 for_each_netdev(net, dev) { 1726 err = call_netdevice_register_notifiers(nb, dev); 1727 if (err) 1728 goto rollback; 1729 } 1730 return 0; 1731 1732rollback: 1733 for_each_netdev_continue_reverse(net, dev) 1734 call_netdevice_unregister_notifiers(nb, dev); 1735 return err; 1736} 1737 1738static void call_netdevice_unregister_net_notifiers(struct notifier_block *nb, 1739 struct net *net) 1740{ 1741 struct net_device *dev; 1742 1743 for_each_netdev(net, dev) 1744 call_netdevice_unregister_notifiers(nb, dev); 1745} 1746 1747static int dev_boot_phase = 1; 1748 1749/** 1750 * register_netdevice_notifier - register a network notifier block 1751 * @nb: notifier 1752 * 1753 * Register a notifier to be called when network device events occur. 1754 * The notifier passed is linked into the kernel structures and must 1755 * not be reused until it has been unregistered. A negative errno code 1756 * is returned on a failure. 1757 * 1758 * When registered all registration and up events are replayed 1759 * to the new notifier to allow device to have a race free 1760 * view of the network device list. 1761 */ 1762 1763int register_netdevice_notifier(struct notifier_block *nb) 1764{ 1765 struct net *net; 1766 int err; 1767 1768 /* Close race with setup_net() and cleanup_net() */ 1769 down_write(&pernet_ops_rwsem); 1770 rtnl_lock(); 1771 err = raw_notifier_chain_register(&netdev_chain, nb); 1772 if (err) 1773 goto unlock; 1774 if (dev_boot_phase) 1775 goto unlock; 1776 for_each_net(net) { 1777 err = call_netdevice_register_net_notifiers(nb, net); 1778 if (err) 1779 goto rollback; 1780 } 1781 1782unlock: 1783 rtnl_unlock(); 1784 up_write(&pernet_ops_rwsem); 1785 return err; 1786 1787rollback: 1788 for_each_net_continue_reverse(net) 1789 call_netdevice_unregister_net_notifiers(nb, net); 1790 1791 raw_notifier_chain_unregister(&netdev_chain, nb); 1792 goto unlock; 1793} 1794EXPORT_SYMBOL(register_netdevice_notifier); 1795 1796/** 1797 * unregister_netdevice_notifier - unregister a network notifier block 1798 * @nb: notifier 1799 * 1800 * Unregister a notifier previously registered by 1801 * register_netdevice_notifier(). The notifier is unlinked into the 1802 * kernel structures and may then be reused. A negative errno code 1803 * is returned on a failure. 1804 * 1805 * After unregistering unregister and down device events are synthesized 1806 * for all devices on the device list to the removed notifier to remove 1807 * the need for special case cleanup code. 1808 */ 1809 1810int unregister_netdevice_notifier(struct notifier_block *nb) 1811{ 1812 struct net *net; 1813 int err; 1814 1815 /* Close race with setup_net() and cleanup_net() */ 1816 down_write(&pernet_ops_rwsem); 1817 rtnl_lock(); 1818 err = raw_notifier_chain_unregister(&netdev_chain, nb); 1819 if (err) 1820 goto unlock; 1821 1822 for_each_net(net) 1823 call_netdevice_unregister_net_notifiers(nb, net); 1824 1825unlock: 1826 rtnl_unlock(); 1827 up_write(&pernet_ops_rwsem); 1828 return err; 1829} 1830EXPORT_SYMBOL(unregister_netdevice_notifier); 1831 1832static int __register_netdevice_notifier_net(struct net *net, 1833 struct notifier_block *nb, 1834 bool ignore_call_fail) 1835{ 1836 int err; 1837 1838 err = raw_notifier_chain_register(&net->netdev_chain, nb); 1839 if (err) 1840 return err; 1841 if (dev_boot_phase) 1842 return 0; 1843 1844 err = call_netdevice_register_net_notifiers(nb, net); 1845 if (err && !ignore_call_fail) 1846 goto chain_unregister; 1847 1848 return 0; 1849 1850chain_unregister: 1851 raw_notifier_chain_unregister(&net->netdev_chain, nb); 1852 return err; 1853} 1854 1855static int __unregister_netdevice_notifier_net(struct net *net, 1856 struct notifier_block *nb) 1857{ 1858 int err; 1859 1860 err = raw_notifier_chain_unregister(&net->netdev_chain, nb); 1861 if (err) 1862 return err; 1863 1864 call_netdevice_unregister_net_notifiers(nb, net); 1865 return 0; 1866} 1867 1868/** 1869 * register_netdevice_notifier_net - register a per-netns network notifier block 1870 * @net: network namespace 1871 * @nb: notifier 1872 * 1873 * Register a notifier to be called when network device events occur. 1874 * The notifier passed is linked into the kernel structures and must 1875 * not be reused until it has been unregistered. A negative errno code 1876 * is returned on a failure. 1877 * 1878 * When registered all registration and up events are replayed 1879 * to the new notifier to allow device to have a race free 1880 * view of the network device list. 1881 */ 1882 1883int register_netdevice_notifier_net(struct net *net, struct notifier_block *nb) 1884{ 1885 int err; 1886 1887 rtnl_lock(); 1888 err = __register_netdevice_notifier_net(net, nb, false); 1889 rtnl_unlock(); 1890 return err; 1891} 1892EXPORT_SYMBOL(register_netdevice_notifier_net); 1893 1894/** 1895 * unregister_netdevice_notifier_net - unregister a per-netns 1896 * network notifier block 1897 * @net: network namespace 1898 * @nb: notifier 1899 * 1900 * Unregister a notifier previously registered by 1901 * register_netdevice_notifier_net(). The notifier is unlinked from the 1902 * kernel structures and may then be reused. A negative errno code 1903 * is returned on a failure. 1904 * 1905 * After unregistering unregister and down device events are synthesized 1906 * for all devices on the device list to the removed notifier to remove 1907 * the need for special case cleanup code. 1908 */ 1909 1910int unregister_netdevice_notifier_net(struct net *net, 1911 struct notifier_block *nb) 1912{ 1913 int err; 1914 1915 rtnl_lock(); 1916 err = __unregister_netdevice_notifier_net(net, nb); 1917 rtnl_unlock(); 1918 return err; 1919} 1920EXPORT_SYMBOL(unregister_netdevice_notifier_net); 1921 1922static void __move_netdevice_notifier_net(struct net *src_net, 1923 struct net *dst_net, 1924 struct notifier_block *nb) 1925{ 1926 __unregister_netdevice_notifier_net(src_net, nb); 1927 __register_netdevice_notifier_net(dst_net, nb, true); 1928} 1929 1930int register_netdevice_notifier_dev_net(struct net_device *dev, 1931 struct notifier_block *nb, 1932 struct netdev_net_notifier *nn) 1933{ 1934 int err; 1935 1936 rtnl_lock(); 1937 err = __register_netdevice_notifier_net(dev_net(dev), nb, false); 1938 if (!err) { 1939 nn->nb = nb; 1940 list_add(&nn->list, &dev->net_notifier_list); 1941 } 1942 rtnl_unlock(); 1943 return err; 1944} 1945EXPORT_SYMBOL(register_netdevice_notifier_dev_net); 1946 1947int unregister_netdevice_notifier_dev_net(struct net_device *dev, 1948 struct notifier_block *nb, 1949 struct netdev_net_notifier *nn) 1950{ 1951 int err; 1952 1953 rtnl_lock(); 1954 list_del(&nn->list); 1955 err = __unregister_netdevice_notifier_net(dev_net(dev), nb); 1956 rtnl_unlock(); 1957 return err; 1958} 1959EXPORT_SYMBOL(unregister_netdevice_notifier_dev_net); 1960 1961static void move_netdevice_notifiers_dev_net(struct net_device *dev, 1962 struct net *net) 1963{ 1964 struct netdev_net_notifier *nn; 1965 1966 list_for_each_entry(nn, &dev->net_notifier_list, list) 1967 __move_netdevice_notifier_net(dev_net(dev), net, nn->nb); 1968} 1969 1970/** 1971 * call_netdevice_notifiers_info - call all network notifier blocks 1972 * @val: value passed unmodified to notifier function 1973 * @info: notifier information data 1974 * 1975 * Call all network notifier blocks. Parameters and return value 1976 * are as for raw_notifier_call_chain(). 1977 */ 1978 1979int call_netdevice_notifiers_info(unsigned long val, 1980 struct netdev_notifier_info *info) 1981{ 1982 struct net *net = dev_net(info->dev); 1983 int ret; 1984 1985 ASSERT_RTNL(); 1986 1987 /* Run per-netns notifier block chain first, then run the global one. 1988 * Hopefully, one day, the global one is going to be removed after 1989 * all notifier block registrators get converted to be per-netns. 1990 */ 1991 ret = raw_notifier_call_chain(&net->netdev_chain, val, info); 1992 if (ret & NOTIFY_STOP_MASK) 1993 return ret; 1994 return raw_notifier_call_chain(&netdev_chain, val, info); 1995} 1996 1997/** 1998 * call_netdevice_notifiers_info_robust - call per-netns notifier blocks 1999 * for and rollback on error 2000 * @val_up: value passed unmodified to notifier function 2001 * @val_down: value passed unmodified to the notifier function when 2002 * recovering from an error on @val_up 2003 * @info: notifier information data 2004 * 2005 * Call all per-netns network notifier blocks, but not notifier blocks on 2006 * the global notifier chain. Parameters and return value are as for 2007 * raw_notifier_call_chain_robust(). 2008 */ 2009 2010static int 2011call_netdevice_notifiers_info_robust(unsigned long val_up, 2012 unsigned long val_down, 2013 struct netdev_notifier_info *info) 2014{ 2015 struct net *net = dev_net(info->dev); 2016 2017 ASSERT_RTNL(); 2018 2019 return raw_notifier_call_chain_robust(&net->netdev_chain, 2020 val_up, val_down, info); 2021} 2022 2023static int call_netdevice_notifiers_extack(unsigned long val, 2024 struct net_device *dev, 2025 struct netlink_ext_ack *extack) 2026{ 2027 struct netdev_notifier_info info = { 2028 .dev = dev, 2029 .extack = extack, 2030 }; 2031 2032 return call_netdevice_notifiers_info(val, &info); 2033} 2034 2035/** 2036 * call_netdevice_notifiers - call all network notifier blocks 2037 * @val: value passed unmodified to notifier function 2038 * @dev: net_device pointer passed unmodified to notifier function 2039 * 2040 * Call all network notifier blocks. Parameters and return value 2041 * are as for raw_notifier_call_chain(). 2042 */ 2043 2044int call_netdevice_notifiers(unsigned long val, struct net_device *dev) 2045{ 2046 return call_netdevice_notifiers_extack(val, dev, NULL); 2047} 2048EXPORT_SYMBOL(call_netdevice_notifiers); 2049 2050/** 2051 * call_netdevice_notifiers_mtu - call all network notifier blocks 2052 * @val: value passed unmodified to notifier function 2053 * @dev: net_device pointer passed unmodified to notifier function 2054 * @arg: additional u32 argument passed to the notifier function 2055 * 2056 * Call all network notifier blocks. Parameters and return value 2057 * are as for raw_notifier_call_chain(). 2058 */ 2059static int call_netdevice_notifiers_mtu(unsigned long val, 2060 struct net_device *dev, u32 arg) 2061{ 2062 struct netdev_notifier_info_ext info = { 2063 .info.dev = dev, 2064 .ext.mtu = arg, 2065 }; 2066 2067 BUILD_BUG_ON(offsetof(struct netdev_notifier_info_ext, info) != 0); 2068 2069 return call_netdevice_notifiers_info(val, &info.info); 2070} 2071 2072#ifdef CONFIG_NET_INGRESS 2073static DEFINE_STATIC_KEY_FALSE(ingress_needed_key); 2074 2075void net_inc_ingress_queue(void) 2076{ 2077 static_branch_inc(&ingress_needed_key); 2078} 2079EXPORT_SYMBOL_GPL(net_inc_ingress_queue); 2080 2081void net_dec_ingress_queue(void) 2082{ 2083 static_branch_dec(&ingress_needed_key); 2084} 2085EXPORT_SYMBOL_GPL(net_dec_ingress_queue); 2086#endif 2087 2088#ifdef CONFIG_NET_EGRESS 2089static DEFINE_STATIC_KEY_FALSE(egress_needed_key); 2090 2091void net_inc_egress_queue(void) 2092{ 2093 static_branch_inc(&egress_needed_key); 2094} 2095EXPORT_SYMBOL_GPL(net_inc_egress_queue); 2096 2097void net_dec_egress_queue(void) 2098{ 2099 static_branch_dec(&egress_needed_key); 2100} 2101EXPORT_SYMBOL_GPL(net_dec_egress_queue); 2102#endif 2103 2104#ifdef CONFIG_NET_CLS_ACT 2105DEFINE_STATIC_KEY_FALSE(tcf_bypass_check_needed_key); 2106EXPORT_SYMBOL(tcf_bypass_check_needed_key); 2107#endif 2108 2109DEFINE_STATIC_KEY_FALSE(netstamp_needed_key); 2110EXPORT_SYMBOL(netstamp_needed_key); 2111#ifdef CONFIG_JUMP_LABEL 2112static atomic_t netstamp_needed_deferred; 2113static atomic_t netstamp_wanted; 2114static void netstamp_clear(struct work_struct *work) 2115{ 2116 int deferred = atomic_xchg(&netstamp_needed_deferred, 0); 2117 int wanted; 2118 2119 wanted = atomic_add_return(deferred, &netstamp_wanted); 2120 if (wanted > 0) 2121 static_branch_enable(&netstamp_needed_key); 2122 else 2123 static_branch_disable(&netstamp_needed_key); 2124} 2125static DECLARE_WORK(netstamp_work, netstamp_clear); 2126#endif 2127 2128void net_enable_timestamp(void) 2129{ 2130#ifdef CONFIG_JUMP_LABEL 2131 int wanted = atomic_read(&netstamp_wanted); 2132 2133 while (wanted > 0) { 2134 if (atomic_try_cmpxchg(&netstamp_wanted, &wanted, wanted + 1)) 2135 return; 2136 } 2137 atomic_inc(&netstamp_needed_deferred); 2138 schedule_work(&netstamp_work); 2139#else 2140 static_branch_inc(&netstamp_needed_key); 2141#endif 2142} 2143EXPORT_SYMBOL(net_enable_timestamp); 2144 2145void net_disable_timestamp(void) 2146{ 2147#ifdef CONFIG_JUMP_LABEL 2148 int wanted = atomic_read(&netstamp_wanted); 2149 2150 while (wanted > 1) { 2151 if (atomic_try_cmpxchg(&netstamp_wanted, &wanted, wanted - 1)) 2152 return; 2153 } 2154 atomic_dec(&netstamp_needed_deferred); 2155 schedule_work(&netstamp_work); 2156#else 2157 static_branch_dec(&netstamp_needed_key); 2158#endif 2159} 2160EXPORT_SYMBOL(net_disable_timestamp); 2161 2162static inline void net_timestamp_set(struct sk_buff *skb) 2163{ 2164 skb->tstamp = 0; 2165 skb->tstamp_type = SKB_CLOCK_REALTIME; 2166 if (static_branch_unlikely(&netstamp_needed_key)) 2167 skb->tstamp = ktime_get_real(); 2168} 2169 2170#define net_timestamp_check(COND, SKB) \ 2171 if (static_branch_unlikely(&netstamp_needed_key)) { \ 2172 if ((COND) && !(SKB)->tstamp) \ 2173 (SKB)->tstamp = ktime_get_real(); \ 2174 } \ 2175 2176bool is_skb_forwardable(const struct net_device *dev, const struct sk_buff *skb) 2177{ 2178 return __is_skb_forwardable(dev, skb, true); 2179} 2180EXPORT_SYMBOL_GPL(is_skb_forwardable); 2181 2182static int __dev_forward_skb2(struct net_device *dev, struct sk_buff *skb, 2183 bool check_mtu) 2184{ 2185 int ret = ____dev_forward_skb(dev, skb, check_mtu); 2186 2187 if (likely(!ret)) { 2188 skb->protocol = eth_type_trans(skb, dev); 2189 skb_postpull_rcsum(skb, eth_hdr(skb), ETH_HLEN); 2190 } 2191 2192 return ret; 2193} 2194 2195int __dev_forward_skb(struct net_device *dev, struct sk_buff *skb) 2196{ 2197 return __dev_forward_skb2(dev, skb, true); 2198} 2199EXPORT_SYMBOL_GPL(__dev_forward_skb); 2200 2201/** 2202 * dev_forward_skb - loopback an skb to another netif 2203 * 2204 * @dev: destination network device 2205 * @skb: buffer to forward 2206 * 2207 * return values: 2208 * NET_RX_SUCCESS (no congestion) 2209 * NET_RX_DROP (packet was dropped, but freed) 2210 * 2211 * dev_forward_skb can be used for injecting an skb from the 2212 * start_xmit function of one device into the receive queue 2213 * of another device. 2214 * 2215 * The receiving device may be in another namespace, so 2216 * we have to clear all information in the skb that could 2217 * impact namespace isolation. 2218 */ 2219int dev_forward_skb(struct net_device *dev, struct sk_buff *skb) 2220{ 2221 return __dev_forward_skb(dev, skb) ?: netif_rx_internal(skb); 2222} 2223EXPORT_SYMBOL_GPL(dev_forward_skb); 2224 2225int dev_forward_skb_nomtu(struct net_device *dev, struct sk_buff *skb) 2226{ 2227 return __dev_forward_skb2(dev, skb, false) ?: netif_rx_internal(skb); 2228} 2229 2230static inline int deliver_skb(struct sk_buff *skb, 2231 struct packet_type *pt_prev, 2232 struct net_device *orig_dev) 2233{ 2234 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC))) 2235 return -ENOMEM; 2236 refcount_inc(&skb->users); 2237 return pt_prev->func(skb, skb->dev, pt_prev, orig_dev); 2238} 2239 2240static inline void deliver_ptype_list_skb(struct sk_buff *skb, 2241 struct packet_type **pt, 2242 struct net_device *orig_dev, 2243 __be16 type, 2244 struct list_head *ptype_list) 2245{ 2246 struct packet_type *ptype, *pt_prev = *pt; 2247 2248 list_for_each_entry_rcu(ptype, ptype_list, list) { 2249 if (ptype->type != type) 2250 continue; 2251 if (pt_prev) 2252 deliver_skb(skb, pt_prev, orig_dev); 2253 pt_prev = ptype; 2254 } 2255 *pt = pt_prev; 2256} 2257 2258static inline bool skb_loop_sk(struct packet_type *ptype, struct sk_buff *skb) 2259{ 2260 if (!ptype->af_packet_priv || !skb->sk) 2261 return false; 2262 2263 if (ptype->id_match) 2264 return ptype->id_match(ptype, skb->sk); 2265 else if ((struct sock *)ptype->af_packet_priv == skb->sk) 2266 return true; 2267 2268 return false; 2269} 2270 2271/** 2272 * dev_nit_active - return true if any network interface taps are in use 2273 * 2274 * @dev: network device to check for the presence of taps 2275 */ 2276bool dev_nit_active(struct net_device *dev) 2277{ 2278 return !list_empty(&net_hotdata.ptype_all) || 2279 !list_empty(&dev->ptype_all); 2280} 2281EXPORT_SYMBOL_GPL(dev_nit_active); 2282 2283/* 2284 * Support routine. Sends outgoing frames to any network 2285 * taps currently in use. 2286 */ 2287 2288void dev_queue_xmit_nit(struct sk_buff *skb, struct net_device *dev) 2289{ 2290 struct list_head *ptype_list = &net_hotdata.ptype_all; 2291 struct packet_type *ptype, *pt_prev = NULL; 2292 struct sk_buff *skb2 = NULL; 2293 2294 rcu_read_lock(); 2295again: 2296 list_for_each_entry_rcu(ptype, ptype_list, list) { 2297 if (READ_ONCE(ptype->ignore_outgoing)) 2298 continue; 2299 2300 /* Never send packets back to the socket 2301 * they originated from - MvS (miquels@drinkel.ow.org) 2302 */ 2303 if (skb_loop_sk(ptype, skb)) 2304 continue; 2305 2306 if (pt_prev) { 2307 deliver_skb(skb2, pt_prev, skb->dev); 2308 pt_prev = ptype; 2309 continue; 2310 } 2311 2312 /* need to clone skb, done only once */ 2313 skb2 = skb_clone(skb, GFP_ATOMIC); 2314 if (!skb2) 2315 goto out_unlock; 2316 2317 net_timestamp_set(skb2); 2318 2319 /* skb->nh should be correctly 2320 * set by sender, so that the second statement is 2321 * just protection against buggy protocols. 2322 */ 2323 skb_reset_mac_header(skb2); 2324 2325 if (skb_network_header(skb2) < skb2->data || 2326 skb_network_header(skb2) > skb_tail_pointer(skb2)) { 2327 net_crit_ratelimited("protocol %04x is buggy, dev %s\n", 2328 ntohs(skb2->protocol), 2329 dev->name); 2330 skb_reset_network_header(skb2); 2331 } 2332 2333 skb2->transport_header = skb2->network_header; 2334 skb2->pkt_type = PACKET_OUTGOING; 2335 pt_prev = ptype; 2336 } 2337 2338 if (ptype_list == &net_hotdata.ptype_all) { 2339 ptype_list = &dev->ptype_all; 2340 goto again; 2341 } 2342out_unlock: 2343 if (pt_prev) { 2344 if (!skb_orphan_frags_rx(skb2, GFP_ATOMIC)) 2345 pt_prev->func(skb2, skb->dev, pt_prev, skb->dev); 2346 else 2347 kfree_skb(skb2); 2348 } 2349 rcu_read_unlock(); 2350} 2351EXPORT_SYMBOL_GPL(dev_queue_xmit_nit); 2352 2353/** 2354 * netif_setup_tc - Handle tc mappings on real_num_tx_queues change 2355 * @dev: Network device 2356 * @txq: number of queues available 2357 * 2358 * If real_num_tx_queues is changed the tc mappings may no longer be 2359 * valid. To resolve this verify the tc mapping remains valid and if 2360 * not NULL the mapping. With no priorities mapping to this 2361 * offset/count pair it will no longer be used. In the worst case TC0 2362 * is invalid nothing can be done so disable priority mappings. If is 2363 * expected that drivers will fix this mapping if they can before 2364 * calling netif_set_real_num_tx_queues. 2365 */ 2366static void netif_setup_tc(struct net_device *dev, unsigned int txq) 2367{ 2368 int i; 2369 struct netdev_tc_txq *tc = &dev->tc_to_txq[0]; 2370 2371 /* If TC0 is invalidated disable TC mapping */ 2372 if (tc->offset + tc->count > txq) { 2373 netdev_warn(dev, "Number of in use tx queues changed invalidating tc mappings. Priority traffic classification disabled!\n"); 2374 dev->num_tc = 0; 2375 return; 2376 } 2377 2378 /* Invalidated prio to tc mappings set to TC0 */ 2379 for (i = 1; i < TC_BITMASK + 1; i++) { 2380 int q = netdev_get_prio_tc_map(dev, i); 2381 2382 tc = &dev->tc_to_txq[q]; 2383 if (tc->offset + tc->count > txq) { 2384 netdev_warn(dev, "Number of in use tx queues changed. Priority %i to tc mapping %i is no longer valid. Setting map to 0\n", 2385 i, q); 2386 netdev_set_prio_tc_map(dev, i, 0); 2387 } 2388 } 2389} 2390 2391int netdev_txq_to_tc(struct net_device *dev, unsigned int txq) 2392{ 2393 if (dev->num_tc) { 2394 struct netdev_tc_txq *tc = &dev->tc_to_txq[0]; 2395 int i; 2396 2397 /* walk through the TCs and see if it falls into any of them */ 2398 for (i = 0; i < TC_MAX_QUEUE; i++, tc++) { 2399 if ((txq - tc->offset) < tc->count) 2400 return i; 2401 } 2402 2403 /* didn't find it, just return -1 to indicate no match */ 2404 return -1; 2405 } 2406 2407 return 0; 2408} 2409EXPORT_SYMBOL(netdev_txq_to_tc); 2410 2411#ifdef CONFIG_XPS 2412static struct static_key xps_needed __read_mostly; 2413static struct static_key xps_rxqs_needed __read_mostly; 2414static DEFINE_MUTEX(xps_map_mutex); 2415#define xmap_dereference(P) \ 2416 rcu_dereference_protected((P), lockdep_is_held(&xps_map_mutex)) 2417 2418static bool remove_xps_queue(struct xps_dev_maps *dev_maps, 2419 struct xps_dev_maps *old_maps, int tci, u16 index) 2420{ 2421 struct xps_map *map = NULL; 2422 int pos; 2423 2424 map = xmap_dereference(dev_maps->attr_map[tci]); 2425 if (!map) 2426 return false; 2427 2428 for (pos = map->len; pos--;) { 2429 if (map->queues[pos] != index) 2430 continue; 2431 2432 if (map->len > 1) { 2433 map->queues[pos] = map->queues[--map->len]; 2434 break; 2435 } 2436 2437 if (old_maps) 2438 RCU_INIT_POINTER(old_maps->attr_map[tci], NULL); 2439 RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL); 2440 kfree_rcu(map, rcu); 2441 return false; 2442 } 2443 2444 return true; 2445} 2446 2447static bool remove_xps_queue_cpu(struct net_device *dev, 2448 struct xps_dev_maps *dev_maps, 2449 int cpu, u16 offset, u16 count) 2450{ 2451 int num_tc = dev_maps->num_tc; 2452 bool active = false; 2453 int tci; 2454 2455 for (tci = cpu * num_tc; num_tc--; tci++) { 2456 int i, j; 2457 2458 for (i = count, j = offset; i--; j++) { 2459 if (!remove_xps_queue(dev_maps, NULL, tci, j)) 2460 break; 2461 } 2462 2463 active |= i < 0; 2464 } 2465 2466 return active; 2467} 2468 2469static void reset_xps_maps(struct net_device *dev, 2470 struct xps_dev_maps *dev_maps, 2471 enum xps_map_type type) 2472{ 2473 static_key_slow_dec_cpuslocked(&xps_needed); 2474 if (type == XPS_RXQS) 2475 static_key_slow_dec_cpuslocked(&xps_rxqs_needed); 2476 2477 RCU_INIT_POINTER(dev->xps_maps[type], NULL); 2478 2479 kfree_rcu(dev_maps, rcu); 2480} 2481 2482static void clean_xps_maps(struct net_device *dev, enum xps_map_type type, 2483 u16 offset, u16 count) 2484{ 2485 struct xps_dev_maps *dev_maps; 2486 bool active = false; 2487 int i, j; 2488 2489 dev_maps = xmap_dereference(dev->xps_maps[type]); 2490 if (!dev_maps) 2491 return; 2492 2493 for (j = 0; j < dev_maps->nr_ids; j++) 2494 active |= remove_xps_queue_cpu(dev, dev_maps, j, offset, count); 2495 if (!active) 2496 reset_xps_maps(dev, dev_maps, type); 2497 2498 if (type == XPS_CPUS) { 2499 for (i = offset + (count - 1); count--; i--) 2500 netdev_queue_numa_node_write( 2501 netdev_get_tx_queue(dev, i), NUMA_NO_NODE); 2502 } 2503} 2504 2505static void netif_reset_xps_queues(struct net_device *dev, u16 offset, 2506 u16 count) 2507{ 2508 if (!static_key_false(&xps_needed)) 2509 return; 2510 2511 cpus_read_lock(); 2512 mutex_lock(&xps_map_mutex); 2513 2514 if (static_key_false(&xps_rxqs_needed)) 2515 clean_xps_maps(dev, XPS_RXQS, offset, count); 2516 2517 clean_xps_maps(dev, XPS_CPUS, offset, count); 2518 2519 mutex_unlock(&xps_map_mutex); 2520 cpus_read_unlock(); 2521} 2522 2523static void netif_reset_xps_queues_gt(struct net_device *dev, u16 index) 2524{ 2525 netif_reset_xps_queues(dev, index, dev->num_tx_queues - index); 2526} 2527 2528static struct xps_map *expand_xps_map(struct xps_map *map, int attr_index, 2529 u16 index, bool is_rxqs_map) 2530{ 2531 struct xps_map *new_map; 2532 int alloc_len = XPS_MIN_MAP_ALLOC; 2533 int i, pos; 2534 2535 for (pos = 0; map && pos < map->len; pos++) { 2536 if (map->queues[pos] != index) 2537 continue; 2538 return map; 2539 } 2540 2541 /* Need to add tx-queue to this CPU's/rx-queue's existing map */ 2542 if (map) { 2543 if (pos < map->alloc_len) 2544 return map; 2545 2546 alloc_len = map->alloc_len * 2; 2547 } 2548 2549 /* Need to allocate new map to store tx-queue on this CPU's/rx-queue's 2550 * map 2551 */ 2552 if (is_rxqs_map) 2553 new_map = kzalloc(XPS_MAP_SIZE(alloc_len), GFP_KERNEL); 2554 else 2555 new_map = kzalloc_node(XPS_MAP_SIZE(alloc_len), GFP_KERNEL, 2556 cpu_to_node(attr_index)); 2557 if (!new_map) 2558 return NULL; 2559 2560 for (i = 0; i < pos; i++) 2561 new_map->queues[i] = map->queues[i]; 2562 new_map->alloc_len = alloc_len; 2563 new_map->len = pos; 2564 2565 return new_map; 2566} 2567 2568/* Copy xps maps at a given index */ 2569static void xps_copy_dev_maps(struct xps_dev_maps *dev_maps, 2570 struct xps_dev_maps *new_dev_maps, int index, 2571 int tc, bool skip_tc) 2572{ 2573 int i, tci = index * dev_maps->num_tc; 2574 struct xps_map *map; 2575 2576 /* copy maps belonging to foreign traffic classes */ 2577 for (i = 0; i < dev_maps->num_tc; i++, tci++) { 2578 if (i == tc && skip_tc) 2579 continue; 2580 2581 /* fill in the new device map from the old device map */ 2582 map = xmap_dereference(dev_maps->attr_map[tci]); 2583 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map); 2584 } 2585} 2586 2587/* Must be called under cpus_read_lock */ 2588int __netif_set_xps_queue(struct net_device *dev, const unsigned long *mask, 2589 u16 index, enum xps_map_type type) 2590{ 2591 struct xps_dev_maps *dev_maps, *new_dev_maps = NULL, *old_dev_maps = NULL; 2592 const unsigned long *online_mask = NULL; 2593 bool active = false, copy = false; 2594 int i, j, tci, numa_node_id = -2; 2595 int maps_sz, num_tc = 1, tc = 0; 2596 struct xps_map *map, *new_map; 2597 unsigned int nr_ids; 2598 2599 WARN_ON_ONCE(index >= dev->num_tx_queues); 2600 2601 if (dev->num_tc) { 2602 /* Do not allow XPS on subordinate device directly */ 2603 num_tc = dev->num_tc; 2604 if (num_tc < 0) 2605 return -EINVAL; 2606 2607 /* If queue belongs to subordinate dev use its map */ 2608 dev = netdev_get_tx_queue(dev, index)->sb_dev ? : dev; 2609 2610 tc = netdev_txq_to_tc(dev, index); 2611 if (tc < 0) 2612 return -EINVAL; 2613 } 2614 2615 mutex_lock(&xps_map_mutex); 2616 2617 dev_maps = xmap_dereference(dev->xps_maps[type]); 2618 if (type == XPS_RXQS) { 2619 maps_sz = XPS_RXQ_DEV_MAPS_SIZE(num_tc, dev->num_rx_queues); 2620 nr_ids = dev->num_rx_queues; 2621 } else { 2622 maps_sz = XPS_CPU_DEV_MAPS_SIZE(num_tc); 2623 if (num_possible_cpus() > 1) 2624 online_mask = cpumask_bits(cpu_online_mask); 2625 nr_ids = nr_cpu_ids; 2626 } 2627 2628 if (maps_sz < L1_CACHE_BYTES) 2629 maps_sz = L1_CACHE_BYTES; 2630 2631 /* The old dev_maps could be larger or smaller than the one we're 2632 * setting up now, as dev->num_tc or nr_ids could have been updated in 2633 * between. We could try to be smart, but let's be safe instead and only 2634 * copy foreign traffic classes if the two map sizes match. 2635 */ 2636 if (dev_maps && 2637 dev_maps->num_tc == num_tc && dev_maps->nr_ids == nr_ids) 2638 copy = true; 2639 2640 /* allocate memory for queue storage */ 2641 for (j = -1; j = netif_attrmask_next_and(j, online_mask, mask, nr_ids), 2642 j < nr_ids;) { 2643 if (!new_dev_maps) { 2644 new_dev_maps = kzalloc(maps_sz, GFP_KERNEL); 2645 if (!new_dev_maps) { 2646 mutex_unlock(&xps_map_mutex); 2647 return -ENOMEM; 2648 } 2649 2650 new_dev_maps->nr_ids = nr_ids; 2651 new_dev_maps->num_tc = num_tc; 2652 } 2653 2654 tci = j * num_tc + tc; 2655 map = copy ? xmap_dereference(dev_maps->attr_map[tci]) : NULL; 2656 2657 map = expand_xps_map(map, j, index, type == XPS_RXQS); 2658 if (!map) 2659 goto error; 2660 2661 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map); 2662 } 2663 2664 if (!new_dev_maps) 2665 goto out_no_new_maps; 2666 2667 if (!dev_maps) { 2668 /* Increment static keys at most once per type */ 2669 static_key_slow_inc_cpuslocked(&xps_needed); 2670 if (type == XPS_RXQS) 2671 static_key_slow_inc_cpuslocked(&xps_rxqs_needed); 2672 } 2673 2674 for (j = 0; j < nr_ids; j++) { 2675 bool skip_tc = false; 2676 2677 tci = j * num_tc + tc; 2678 if (netif_attr_test_mask(j, mask, nr_ids) && 2679 netif_attr_test_online(j, online_mask, nr_ids)) { 2680 /* add tx-queue to CPU/rx-queue maps */ 2681 int pos = 0; 2682 2683 skip_tc = true; 2684 2685 map = xmap_dereference(new_dev_maps->attr_map[tci]); 2686 while ((pos < map->len) && (map->queues[pos] != index)) 2687 pos++; 2688 2689 if (pos == map->len) 2690 map->queues[map->len++] = index; 2691#ifdef CONFIG_NUMA 2692 if (type == XPS_CPUS) { 2693 if (numa_node_id == -2) 2694 numa_node_id = cpu_to_node(j); 2695 else if (numa_node_id != cpu_to_node(j)) 2696 numa_node_id = -1; 2697 } 2698#endif 2699 } 2700 2701 if (copy) 2702 xps_copy_dev_maps(dev_maps, new_dev_maps, j, tc, 2703 skip_tc); 2704 } 2705 2706 rcu_assign_pointer(dev->xps_maps[type], new_dev_maps); 2707 2708 /* Cleanup old maps */ 2709 if (!dev_maps) 2710 goto out_no_old_maps; 2711 2712 for (j = 0; j < dev_maps->nr_ids; j++) { 2713 for (i = num_tc, tci = j * dev_maps->num_tc; i--; tci++) { 2714 map = xmap_dereference(dev_maps->attr_map[tci]); 2715 if (!map) 2716 continue; 2717 2718 if (copy) { 2719 new_map = xmap_dereference(new_dev_maps->attr_map[tci]); 2720 if (map == new_map) 2721 continue; 2722 } 2723 2724 RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL); 2725 kfree_rcu(map, rcu); 2726 } 2727 } 2728 2729 old_dev_maps = dev_maps; 2730 2731out_no_old_maps: 2732 dev_maps = new_dev_maps; 2733 active = true; 2734 2735out_no_new_maps: 2736 if (type == XPS_CPUS) 2737 /* update Tx queue numa node */ 2738 netdev_queue_numa_node_write(netdev_get_tx_queue(dev, index), 2739 (numa_node_id >= 0) ? 2740 numa_node_id : NUMA_NO_NODE); 2741 2742 if (!dev_maps) 2743 goto out_no_maps; 2744 2745 /* removes tx-queue from unused CPUs/rx-queues */ 2746 for (j = 0; j < dev_maps->nr_ids; j++) { 2747 tci = j * dev_maps->num_tc; 2748 2749 for (i = 0; i < dev_maps->num_tc; i++, tci++) { 2750 if (i == tc && 2751 netif_attr_test_mask(j, mask, dev_maps->nr_ids) && 2752 netif_attr_test_online(j, online_mask, dev_maps->nr_ids)) 2753 continue; 2754 2755 active |= remove_xps_queue(dev_maps, 2756 copy ? old_dev_maps : NULL, 2757 tci, index); 2758 } 2759 } 2760 2761 if (old_dev_maps) 2762 kfree_rcu(old_dev_maps, rcu); 2763 2764 /* free map if not active */ 2765 if (!active) 2766 reset_xps_maps(dev, dev_maps, type); 2767 2768out_no_maps: 2769 mutex_unlock(&xps_map_mutex); 2770 2771 return 0; 2772error: 2773 /* remove any maps that we added */ 2774 for (j = 0; j < nr_ids; j++) { 2775 for (i = num_tc, tci = j * num_tc; i--; tci++) { 2776 new_map = xmap_dereference(new_dev_maps->attr_map[tci]); 2777 map = copy ? 2778 xmap_dereference(dev_maps->attr_map[tci]) : 2779 NULL; 2780 if (new_map && new_map != map) 2781 kfree(new_map); 2782 } 2783 } 2784 2785 mutex_unlock(&xps_map_mutex); 2786 2787 kfree(new_dev_maps); 2788 return -ENOMEM; 2789} 2790EXPORT_SYMBOL_GPL(__netif_set_xps_queue); 2791 2792int netif_set_xps_queue(struct net_device *dev, const struct cpumask *mask, 2793 u16 index) 2794{ 2795 int ret; 2796 2797 cpus_read_lock(); 2798 ret = __netif_set_xps_queue(dev, cpumask_bits(mask), index, XPS_CPUS); 2799 cpus_read_unlock(); 2800 2801 return ret; 2802} 2803EXPORT_SYMBOL(netif_set_xps_queue); 2804 2805#endif 2806static void netdev_unbind_all_sb_channels(struct net_device *dev) 2807{ 2808 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues]; 2809 2810 /* Unbind any subordinate channels */ 2811 while (txq-- != &dev->_tx[0]) { 2812 if (txq->sb_dev) 2813 netdev_unbind_sb_channel(dev, txq->sb_dev); 2814 } 2815} 2816 2817void netdev_reset_tc(struct net_device *dev) 2818{ 2819#ifdef CONFIG_XPS 2820 netif_reset_xps_queues_gt(dev, 0); 2821#endif 2822 netdev_unbind_all_sb_channels(dev); 2823 2824 /* Reset TC configuration of device */ 2825 dev->num_tc = 0; 2826 memset(dev->tc_to_txq, 0, sizeof(dev->tc_to_txq)); 2827 memset(dev->prio_tc_map, 0, sizeof(dev->prio_tc_map)); 2828} 2829EXPORT_SYMBOL(netdev_reset_tc); 2830 2831int netdev_set_tc_queue(struct net_device *dev, u8 tc, u16 count, u16 offset) 2832{ 2833 if (tc >= dev->num_tc) 2834 return -EINVAL; 2835 2836#ifdef CONFIG_XPS 2837 netif_reset_xps_queues(dev, offset, count); 2838#endif 2839 dev->tc_to_txq[tc].count = count; 2840 dev->tc_to_txq[tc].offset = offset; 2841 return 0; 2842} 2843EXPORT_SYMBOL(netdev_set_tc_queue); 2844 2845int netdev_set_num_tc(struct net_device *dev, u8 num_tc) 2846{ 2847 if (num_tc > TC_MAX_QUEUE) 2848 return -EINVAL; 2849 2850#ifdef CONFIG_XPS 2851 netif_reset_xps_queues_gt(dev, 0); 2852#endif 2853 netdev_unbind_all_sb_channels(dev); 2854 2855 dev->num_tc = num_tc; 2856 return 0; 2857} 2858EXPORT_SYMBOL(netdev_set_num_tc); 2859 2860void netdev_unbind_sb_channel(struct net_device *dev, 2861 struct net_device *sb_dev) 2862{ 2863 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues]; 2864 2865#ifdef CONFIG_XPS 2866 netif_reset_xps_queues_gt(sb_dev, 0); 2867#endif 2868 memset(sb_dev->tc_to_txq, 0, sizeof(sb_dev->tc_to_txq)); 2869 memset(sb_dev->prio_tc_map, 0, sizeof(sb_dev->prio_tc_map)); 2870 2871 while (txq-- != &dev->_tx[0]) { 2872 if (txq->sb_dev == sb_dev) 2873 txq->sb_dev = NULL; 2874 } 2875} 2876EXPORT_SYMBOL(netdev_unbind_sb_channel); 2877 2878int netdev_bind_sb_channel_queue(struct net_device *dev, 2879 struct net_device *sb_dev, 2880 u8 tc, u16 count, u16 offset) 2881{ 2882 /* Make certain the sb_dev and dev are already configured */ 2883 if (sb_dev->num_tc >= 0 || tc >= dev->num_tc) 2884 return -EINVAL; 2885 2886 /* We cannot hand out queues we don't have */ 2887 if ((offset + count) > dev->real_num_tx_queues) 2888 return -EINVAL; 2889 2890 /* Record the mapping */ 2891 sb_dev->tc_to_txq[tc].count = count; 2892 sb_dev->tc_to_txq[tc].offset = offset; 2893 2894 /* Provide a way for Tx queue to find the tc_to_txq map or 2895 * XPS map for itself. 2896 */ 2897 while (count--) 2898 netdev_get_tx_queue(dev, count + offset)->sb_dev = sb_dev; 2899 2900 return 0; 2901} 2902EXPORT_SYMBOL(netdev_bind_sb_channel_queue); 2903 2904int netdev_set_sb_channel(struct net_device *dev, u16 channel) 2905{ 2906 /* Do not use a multiqueue device to represent a subordinate channel */ 2907 if (netif_is_multiqueue(dev)) 2908 return -ENODEV; 2909 2910 /* We allow channels 1 - 32767 to be used for subordinate channels. 2911 * Channel 0 is meant to be "native" mode and used only to represent 2912 * the main root device. We allow writing 0 to reset the device back 2913 * to normal mode after being used as a subordinate channel. 2914 */ 2915 if (channel > S16_MAX) 2916 return -EINVAL; 2917 2918 dev->num_tc = -channel; 2919 2920 return 0; 2921} 2922EXPORT_SYMBOL(netdev_set_sb_channel); 2923 2924/* 2925 * Routine to help set real_num_tx_queues. To avoid skbs mapped to queues 2926 * greater than real_num_tx_queues stale skbs on the qdisc must be flushed. 2927 */ 2928int netif_set_real_num_tx_queues(struct net_device *dev, unsigned int txq) 2929{ 2930 bool disabling; 2931 int rc; 2932 2933 disabling = txq < dev->real_num_tx_queues; 2934 2935 if (txq < 1 || txq > dev->num_tx_queues) 2936 return -EINVAL; 2937 2938 if (dev->reg_state == NETREG_REGISTERED || 2939 dev->reg_state == NETREG_UNREGISTERING) { 2940 ASSERT_RTNL(); 2941 2942 rc = netdev_queue_update_kobjects(dev, dev->real_num_tx_queues, 2943 txq); 2944 if (rc) 2945 return rc; 2946 2947 if (dev->num_tc) 2948 netif_setup_tc(dev, txq); 2949 2950 dev_qdisc_change_real_num_tx(dev, txq); 2951 2952 dev->real_num_tx_queues = txq; 2953 2954 if (disabling) { 2955 synchronize_net(); 2956 qdisc_reset_all_tx_gt(dev, txq); 2957#ifdef CONFIG_XPS 2958 netif_reset_xps_queues_gt(dev, txq); 2959#endif 2960 } 2961 } else { 2962 dev->real_num_tx_queues = txq; 2963 } 2964 2965 return 0; 2966} 2967EXPORT_SYMBOL(netif_set_real_num_tx_queues); 2968 2969#ifdef CONFIG_SYSFS 2970/** 2971 * netif_set_real_num_rx_queues - set actual number of RX queues used 2972 * @dev: Network device 2973 * @rxq: Actual number of RX queues 2974 * 2975 * This must be called either with the rtnl_lock held or before 2976 * registration of the net device. Returns 0 on success, or a 2977 * negative error code. If called before registration, it always 2978 * succeeds. 2979 */ 2980int netif_set_real_num_rx_queues(struct net_device *dev, unsigned int rxq) 2981{ 2982 int rc; 2983 2984 if (rxq < 1 || rxq > dev->num_rx_queues) 2985 return -EINVAL; 2986 2987 if (dev->reg_state == NETREG_REGISTERED) { 2988 ASSERT_RTNL(); 2989 2990 rc = net_rx_queue_update_kobjects(dev, dev->real_num_rx_queues, 2991 rxq); 2992 if (rc) 2993 return rc; 2994 } 2995 2996 dev->real_num_rx_queues = rxq; 2997 return 0; 2998} 2999EXPORT_SYMBOL(netif_set_real_num_rx_queues); 3000#endif 3001 3002/** 3003 * netif_set_real_num_queues - set actual number of RX and TX queues used 3004 * @dev: Network device 3005 * @txq: Actual number of TX queues 3006 * @rxq: Actual number of RX queues 3007 * 3008 * Set the real number of both TX and RX queues. 3009 * Does nothing if the number of queues is already correct. 3010 */ 3011int netif_set_real_num_queues(struct net_device *dev, 3012 unsigned int txq, unsigned int rxq) 3013{ 3014 unsigned int old_rxq = dev->real_num_rx_queues; 3015 int err; 3016 3017 if (txq < 1 || txq > dev->num_tx_queues || 3018 rxq < 1 || rxq > dev->num_rx_queues) 3019 return -EINVAL; 3020 3021 /* Start from increases, so the error path only does decreases - 3022 * decreases can't fail. 3023 */ 3024 if (rxq > dev->real_num_rx_queues) { 3025 err = netif_set_real_num_rx_queues(dev, rxq); 3026 if (err) 3027 return err; 3028 } 3029 if (txq > dev->real_num_tx_queues) { 3030 err = netif_set_real_num_tx_queues(dev, txq); 3031 if (err) 3032 goto undo_rx; 3033 } 3034 if (rxq < dev->real_num_rx_queues) 3035 WARN_ON(netif_set_real_num_rx_queues(dev, rxq)); 3036 if (txq < dev->real_num_tx_queues) 3037 WARN_ON(netif_set_real_num_tx_queues(dev, txq)); 3038 3039 return 0; 3040undo_rx: 3041 WARN_ON(netif_set_real_num_rx_queues(dev, old_rxq)); 3042 return err; 3043} 3044EXPORT_SYMBOL(netif_set_real_num_queues); 3045 3046/** 3047 * netif_set_tso_max_size() - set the max size of TSO frames supported 3048 * @dev: netdev to update 3049 * @size: max skb->len of a TSO frame 3050 * 3051 * Set the limit on the size of TSO super-frames the device can handle. 3052 * Unless explicitly set the stack will assume the value of 3053 * %GSO_LEGACY_MAX_SIZE. 3054 */ 3055void netif_set_tso_max_size(struct net_device *dev, unsigned int size) 3056{ 3057 dev->tso_max_size = min(GSO_MAX_SIZE, size); 3058 if (size < READ_ONCE(dev->gso_max_size)) 3059 netif_set_gso_max_size(dev, size); 3060 if (size < READ_ONCE(dev->gso_ipv4_max_size)) 3061 netif_set_gso_ipv4_max_size(dev, size); 3062} 3063EXPORT_SYMBOL(netif_set_tso_max_size); 3064 3065/** 3066 * netif_set_tso_max_segs() - set the max number of segs supported for TSO 3067 * @dev: netdev to update 3068 * @segs: max number of TCP segments 3069 * 3070 * Set the limit on the number of TCP segments the device can generate from 3071 * a single TSO super-frame. 3072 * Unless explicitly set the stack will assume the value of %GSO_MAX_SEGS. 3073 */ 3074void netif_set_tso_max_segs(struct net_device *dev, unsigned int segs) 3075{ 3076 dev->tso_max_segs = segs; 3077 if (segs < READ_ONCE(dev->gso_max_segs)) 3078 netif_set_gso_max_segs(dev, segs); 3079} 3080EXPORT_SYMBOL(netif_set_tso_max_segs); 3081 3082/** 3083 * netif_inherit_tso_max() - copy all TSO limits from a lower device to an upper 3084 * @to: netdev to update 3085 * @from: netdev from which to copy the limits 3086 */ 3087void netif_inherit_tso_max(struct net_device *to, const struct net_device *from) 3088{ 3089 netif_set_tso_max_size(to, from->tso_max_size); 3090 netif_set_tso_max_segs(to, from->tso_max_segs); 3091} 3092EXPORT_SYMBOL(netif_inherit_tso_max); 3093 3094/** 3095 * netif_get_num_default_rss_queues - default number of RSS queues 3096 * 3097 * Default value is the number of physical cores if there are only 1 or 2, or 3098 * divided by 2 if there are more. 3099 */ 3100int netif_get_num_default_rss_queues(void) 3101{ 3102 cpumask_var_t cpus; 3103 int cpu, count = 0; 3104 3105 if (unlikely(is_kdump_kernel() || !zalloc_cpumask_var(&cpus, GFP_KERNEL))) 3106 return 1; 3107 3108 cpumask_copy(cpus, cpu_online_mask); 3109 for_each_cpu(cpu, cpus) { 3110 ++count; 3111 cpumask_andnot(cpus, cpus, topology_sibling_cpumask(cpu)); 3112 } 3113 free_cpumask_var(cpus); 3114 3115 return count > 2 ? DIV_ROUND_UP(count, 2) : count; 3116} 3117EXPORT_SYMBOL(netif_get_num_default_rss_queues); 3118 3119static void __netif_reschedule(struct Qdisc *q) 3120{ 3121 struct softnet_data *sd; 3122 unsigned long flags; 3123 3124 local_irq_save(flags); 3125 sd = this_cpu_ptr(&softnet_data); 3126 q->next_sched = NULL; 3127 *sd->output_queue_tailp = q; 3128 sd->output_queue_tailp = &q->next_sched; 3129 raise_softirq_irqoff(NET_TX_SOFTIRQ); 3130 local_irq_restore(flags); 3131} 3132 3133void __netif_schedule(struct Qdisc *q) 3134{ 3135 if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state)) 3136 __netif_reschedule(q); 3137} 3138EXPORT_SYMBOL(__netif_schedule); 3139 3140struct dev_kfree_skb_cb { 3141 enum skb_drop_reason reason; 3142}; 3143 3144static struct dev_kfree_skb_cb *get_kfree_skb_cb(const struct sk_buff *skb) 3145{ 3146 return (struct dev_kfree_skb_cb *)skb->cb; 3147} 3148 3149void netif_schedule_queue(struct netdev_queue *txq) 3150{ 3151 rcu_read_lock(); 3152 if (!netif_xmit_stopped(txq)) { 3153 struct Qdisc *q = rcu_dereference(txq->qdisc); 3154 3155 __netif_schedule(q); 3156 } 3157 rcu_read_unlock(); 3158} 3159EXPORT_SYMBOL(netif_schedule_queue); 3160 3161void netif_tx_wake_queue(struct netdev_queue *dev_queue) 3162{ 3163 if (test_and_clear_bit(__QUEUE_STATE_DRV_XOFF, &dev_queue->state)) { 3164 struct Qdisc *q; 3165 3166 rcu_read_lock(); 3167 q = rcu_dereference(dev_queue->qdisc); 3168 __netif_schedule(q); 3169 rcu_read_unlock(); 3170 } 3171} 3172EXPORT_SYMBOL(netif_tx_wake_queue); 3173 3174void dev_kfree_skb_irq_reason(struct sk_buff *skb, enum skb_drop_reason reason) 3175{ 3176 unsigned long flags; 3177 3178 if (unlikely(!skb)) 3179 return; 3180 3181 if (likely(refcount_read(&skb->users) == 1)) { 3182 smp_rmb(); 3183 refcount_set(&skb->users, 0); 3184 } else if (likely(!refcount_dec_and_test(&skb->users))) { 3185 return; 3186 } 3187 get_kfree_skb_cb(skb)->reason = reason; 3188 local_irq_save(flags); 3189 skb->next = __this_cpu_read(softnet_data.completion_queue); 3190 __this_cpu_write(softnet_data.completion_queue, skb); 3191 raise_softirq_irqoff(NET_TX_SOFTIRQ); 3192 local_irq_restore(flags); 3193} 3194EXPORT_SYMBOL(dev_kfree_skb_irq_reason); 3195 3196void dev_kfree_skb_any_reason(struct sk_buff *skb, enum skb_drop_reason reason) 3197{ 3198 if (in_hardirq() || irqs_disabled()) 3199 dev_kfree_skb_irq_reason(skb, reason); 3200 else 3201 kfree_skb_reason(skb, reason); 3202} 3203EXPORT_SYMBOL(dev_kfree_skb_any_reason); 3204 3205 3206/** 3207 * netif_device_detach - mark device as removed 3208 * @dev: network device 3209 * 3210 * Mark device as removed from system and therefore no longer available. 3211 */ 3212void netif_device_detach(struct net_device *dev) 3213{ 3214 if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) && 3215 netif_running(dev)) { 3216 netif_tx_stop_all_queues(dev); 3217 } 3218} 3219EXPORT_SYMBOL(netif_device_detach); 3220 3221/** 3222 * netif_device_attach - mark device as attached 3223 * @dev: network device 3224 * 3225 * Mark device as attached from system and restart if needed. 3226 */ 3227void netif_device_attach(struct net_device *dev) 3228{ 3229 if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) && 3230 netif_running(dev)) { 3231 netif_tx_wake_all_queues(dev); 3232 __netdev_watchdog_up(dev); 3233 } 3234} 3235EXPORT_SYMBOL(netif_device_attach); 3236 3237/* 3238 * Returns a Tx hash based on the given packet descriptor a Tx queues' number 3239 * to be used as a distribution range. 3240 */ 3241static u16 skb_tx_hash(const struct net_device *dev, 3242 const struct net_device *sb_dev, 3243 struct sk_buff *skb) 3244{ 3245 u32 hash; 3246 u16 qoffset = 0; 3247 u16 qcount = dev->real_num_tx_queues; 3248 3249 if (dev->num_tc) { 3250 u8 tc = netdev_get_prio_tc_map(dev, skb->priority); 3251 3252 qoffset = sb_dev->tc_to_txq[tc].offset; 3253 qcount = sb_dev->tc_to_txq[tc].count; 3254 if (unlikely(!qcount)) { 3255 net_warn_ratelimited("%s: invalid qcount, qoffset %u for tc %u\n", 3256 sb_dev->name, qoffset, tc); 3257 qoffset = 0; 3258 qcount = dev->real_num_tx_queues; 3259 } 3260 } 3261 3262 if (skb_rx_queue_recorded(skb)) { 3263 DEBUG_NET_WARN_ON_ONCE(qcount == 0); 3264 hash = skb_get_rx_queue(skb); 3265 if (hash >= qoffset) 3266 hash -= qoffset; 3267 while (unlikely(hash >= qcount)) 3268 hash -= qcount; 3269 return hash + qoffset; 3270 } 3271 3272 return (u16) reciprocal_scale(skb_get_hash(skb), qcount) + qoffset; 3273} 3274 3275void skb_warn_bad_offload(const struct sk_buff *skb) 3276{ 3277 static const netdev_features_t null_features; 3278 struct net_device *dev = skb->dev; 3279 const char *name = ""; 3280 3281 if (!net_ratelimit()) 3282 return; 3283 3284 if (dev) { 3285 if (dev->dev.parent) 3286 name = dev_driver_string(dev->dev.parent); 3287 else 3288 name = netdev_name(dev); 3289 } 3290 skb_dump(KERN_WARNING, skb, false); 3291 WARN(1, "%s: caps=(%pNF, %pNF)\n", 3292 name, dev ? &dev->features : &null_features, 3293 skb->sk ? &skb->sk->sk_route_caps : &null_features); 3294} 3295 3296/* 3297 * Invalidate hardware checksum when packet is to be mangled, and 3298 * complete checksum manually on outgoing path. 3299 */ 3300int skb_checksum_help(struct sk_buff *skb) 3301{ 3302 __wsum csum; 3303 int ret = 0, offset; 3304 3305 if (skb->ip_summed == CHECKSUM_COMPLETE) 3306 goto out_set_summed; 3307 3308 if (unlikely(skb_is_gso(skb))) { 3309 skb_warn_bad_offload(skb); 3310 return -EINVAL; 3311 } 3312 3313 /* Before computing a checksum, we should make sure no frag could 3314 * be modified by an external entity : checksum could be wrong. 3315 */ 3316 if (skb_has_shared_frag(skb)) { 3317 ret = __skb_linearize(skb); 3318 if (ret) 3319 goto out; 3320 } 3321 3322 offset = skb_checksum_start_offset(skb); 3323 ret = -EINVAL; 3324 if (unlikely(offset >= skb_headlen(skb))) { 3325 DO_ONCE_LITE(skb_dump, KERN_ERR, skb, false); 3326 WARN_ONCE(true, "offset (%d) >= skb_headlen() (%u)\n", 3327 offset, skb_headlen(skb)); 3328 goto out; 3329 } 3330 csum = skb_checksum(skb, offset, skb->len - offset, 0); 3331 3332 offset += skb->csum_offset; 3333 if (unlikely(offset + sizeof(__sum16) > skb_headlen(skb))) { 3334 DO_ONCE_LITE(skb_dump, KERN_ERR, skb, false); 3335 WARN_ONCE(true, "offset+2 (%zu) > skb_headlen() (%u)\n", 3336 offset + sizeof(__sum16), skb_headlen(skb)); 3337 goto out; 3338 } 3339 ret = skb_ensure_writable(skb, offset + sizeof(__sum16)); 3340 if (ret) 3341 goto out; 3342 3343 *(__sum16 *)(skb->data + offset) = csum_fold(csum) ?: CSUM_MANGLED_0; 3344out_set_summed: 3345 skb->ip_summed = CHECKSUM_NONE; 3346out: 3347 return ret; 3348} 3349EXPORT_SYMBOL(skb_checksum_help); 3350 3351int skb_crc32c_csum_help(struct sk_buff *skb) 3352{ 3353 __le32 crc32c_csum; 3354 int ret = 0, offset, start; 3355 3356 if (skb->ip_summed != CHECKSUM_PARTIAL) 3357 goto out; 3358 3359 if (unlikely(skb_is_gso(skb))) 3360 goto out; 3361 3362 /* Before computing a checksum, we should make sure no frag could 3363 * be modified by an external entity : checksum could be wrong. 3364 */ 3365 if (unlikely(skb_has_shared_frag(skb))) { 3366 ret = __skb_linearize(skb); 3367 if (ret) 3368 goto out; 3369 } 3370 start = skb_checksum_start_offset(skb); 3371 offset = start + offsetof(struct sctphdr, checksum); 3372 if (WARN_ON_ONCE(offset >= skb_headlen(skb))) { 3373 ret = -EINVAL; 3374 goto out; 3375 } 3376 3377 ret = skb_ensure_writable(skb, offset + sizeof(__le32)); 3378 if (ret) 3379 goto out; 3380 3381 crc32c_csum = cpu_to_le32(~__skb_checksum(skb, start, 3382 skb->len - start, ~(__u32)0, 3383 crc32c_csum_stub)); 3384 *(__le32 *)(skb->data + offset) = crc32c_csum; 3385 skb_reset_csum_not_inet(skb); 3386out: 3387 return ret; 3388} 3389 3390__be16 skb_network_protocol(struct sk_buff *skb, int *depth) 3391{ 3392 __be16 type = skb->protocol; 3393 3394 /* Tunnel gso handlers can set protocol to ethernet. */ 3395 if (type == htons(ETH_P_TEB)) { 3396 struct ethhdr *eth; 3397 3398 if (unlikely(!pskb_may_pull(skb, sizeof(struct ethhdr)))) 3399 return 0; 3400 3401 eth = (struct ethhdr *)skb->data; 3402 type = eth->h_proto; 3403 } 3404 3405 return vlan_get_protocol_and_depth(skb, type, depth); 3406} 3407 3408 3409/* Take action when hardware reception checksum errors are detected. */ 3410#ifdef CONFIG_BUG 3411static void do_netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb) 3412{ 3413 netdev_err(dev, "hw csum failure\n"); 3414 skb_dump(KERN_ERR, skb, true); 3415 dump_stack(); 3416} 3417 3418void netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb) 3419{ 3420 DO_ONCE_LITE(do_netdev_rx_csum_fault, dev, skb); 3421} 3422EXPORT_SYMBOL(netdev_rx_csum_fault); 3423#endif 3424 3425/* XXX: check that highmem exists at all on the given machine. */ 3426static int illegal_highdma(struct net_device *dev, struct sk_buff *skb) 3427{ 3428#ifdef CONFIG_HIGHMEM 3429 int i; 3430 3431 if (!(dev->features & NETIF_F_HIGHDMA)) { 3432 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { 3433 skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; 3434 3435 if (PageHighMem(skb_frag_page(frag))) 3436 return 1; 3437 } 3438 } 3439#endif 3440 return 0; 3441} 3442 3443/* If MPLS offload request, verify we are testing hardware MPLS features 3444 * instead of standard features for the netdev. 3445 */ 3446#if IS_ENABLED(CONFIG_NET_MPLS_GSO) 3447static netdev_features_t net_mpls_features(struct sk_buff *skb, 3448 netdev_features_t features, 3449 __be16 type) 3450{ 3451 if (eth_p_mpls(type)) 3452 features &= skb->dev->mpls_features; 3453 3454 return features; 3455} 3456#else 3457static netdev_features_t net_mpls_features(struct sk_buff *skb, 3458 netdev_features_t features, 3459 __be16 type) 3460{ 3461 return features; 3462} 3463#endif 3464 3465static netdev_features_t harmonize_features(struct sk_buff *skb, 3466 netdev_features_t features) 3467{ 3468 __be16 type; 3469 3470 type = skb_network_protocol(skb, NULL); 3471 features = net_mpls_features(skb, features, type); 3472 3473 if (skb->ip_summed != CHECKSUM_NONE && 3474 !can_checksum_protocol(features, type)) { 3475 features &= ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK); 3476 } 3477 if (illegal_highdma(skb->dev, skb)) 3478 features &= ~NETIF_F_SG; 3479 3480 return features; 3481} 3482 3483netdev_features_t passthru_features_check(struct sk_buff *skb, 3484 struct net_device *dev, 3485 netdev_features_t features) 3486{ 3487 return features; 3488} 3489EXPORT_SYMBOL(passthru_features_check); 3490 3491static netdev_features_t dflt_features_check(struct sk_buff *skb, 3492 struct net_device *dev, 3493 netdev_features_t features) 3494{ 3495 return vlan_features_check(skb, features); 3496} 3497 3498static netdev_features_t gso_features_check(const struct sk_buff *skb, 3499 struct net_device *dev, 3500 netdev_features_t features) 3501{ 3502 u16 gso_segs = skb_shinfo(skb)->gso_segs; 3503 3504 if (gso_segs > READ_ONCE(dev->gso_max_segs)) 3505 return features & ~NETIF_F_GSO_MASK; 3506 3507 if (unlikely(skb->len >= READ_ONCE(dev->gso_max_size))) 3508 return features & ~NETIF_F_GSO_MASK; 3509 3510 if (!skb_shinfo(skb)->gso_type) { 3511 skb_warn_bad_offload(skb); 3512 return features & ~NETIF_F_GSO_MASK; 3513 } 3514 3515 /* Support for GSO partial features requires software 3516 * intervention before we can actually process the packets 3517 * so we need to strip support for any partial features now 3518 * and we can pull them back in after we have partially 3519 * segmented the frame. 3520 */ 3521 if (!(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL)) 3522 features &= ~dev->gso_partial_features; 3523 3524 /* Make sure to clear the IPv4 ID mangling feature if the 3525 * IPv4 header has the potential to be fragmented. 3526 */ 3527 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) { 3528 struct iphdr *iph = skb->encapsulation ? 3529 inner_ip_hdr(skb) : ip_hdr(skb); 3530 3531 if (!(iph->frag_off & htons(IP_DF))) 3532 features &= ~NETIF_F_TSO_MANGLEID; 3533 } 3534 3535 return features; 3536} 3537 3538netdev_features_t netif_skb_features(struct sk_buff *skb) 3539{ 3540 struct net_device *dev = skb->dev; 3541 netdev_features_t features = dev->features; 3542 3543 if (skb_is_gso(skb)) 3544 features = gso_features_check(skb, dev, features); 3545 3546 /* If encapsulation offload request, verify we are testing 3547 * hardware encapsulation features instead of standard 3548 * features for the netdev 3549 */ 3550 if (skb->encapsulation) 3551 features &= dev->hw_enc_features; 3552 3553 if (skb_vlan_tagged(skb)) 3554 features = netdev_intersect_features(features, 3555 dev->vlan_features | 3556 NETIF_F_HW_VLAN_CTAG_TX | 3557 NETIF_F_HW_VLAN_STAG_TX); 3558 3559 if (dev->netdev_ops->ndo_features_check) 3560 features &= dev->netdev_ops->ndo_features_check(skb, dev, 3561 features); 3562 else 3563 features &= dflt_features_check(skb, dev, features); 3564 3565 return harmonize_features(skb, features); 3566} 3567EXPORT_SYMBOL(netif_skb_features); 3568 3569static int xmit_one(struct sk_buff *skb, struct net_device *dev, 3570 struct netdev_queue *txq, bool more) 3571{ 3572 unsigned int len; 3573 int rc; 3574 3575 if (dev_nit_active(dev)) 3576 dev_queue_xmit_nit(skb, dev); 3577 3578 len = skb->len; 3579 trace_net_dev_start_xmit(skb, dev); 3580 rc = netdev_start_xmit(skb, dev, txq, more); 3581 trace_net_dev_xmit(skb, rc, dev, len); 3582 3583 return rc; 3584} 3585 3586struct sk_buff *dev_hard_start_xmit(struct sk_buff *first, struct net_device *dev, 3587 struct netdev_queue *txq, int *ret) 3588{ 3589 struct sk_buff *skb = first; 3590 int rc = NETDEV_TX_OK; 3591 3592 while (skb) { 3593 struct sk_buff *next = skb->next; 3594 3595 skb_mark_not_on_list(skb); 3596 rc = xmit_one(skb, dev, txq, next != NULL); 3597 if (unlikely(!dev_xmit_complete(rc))) { 3598 skb->next = next; 3599 goto out; 3600 } 3601 3602 skb = next; 3603 if (netif_tx_queue_stopped(txq) && skb) { 3604 rc = NETDEV_TX_BUSY; 3605 break; 3606 } 3607 } 3608 3609out: 3610 *ret = rc; 3611 return skb; 3612} 3613 3614static struct sk_buff *validate_xmit_vlan(struct sk_buff *skb, 3615 netdev_features_t features) 3616{ 3617 if (skb_vlan_tag_present(skb) && 3618 !vlan_hw_offload_capable(features, skb->vlan_proto)) 3619 skb = __vlan_hwaccel_push_inside(skb); 3620 return skb; 3621} 3622 3623int skb_csum_hwoffload_help(struct sk_buff *skb, 3624 const netdev_features_t features) 3625{ 3626 if (unlikely(skb_csum_is_sctp(skb))) 3627 return !!(features & NETIF_F_SCTP_CRC) ? 0 : 3628 skb_crc32c_csum_help(skb); 3629 3630 if (features & NETIF_F_HW_CSUM) 3631 return 0; 3632 3633 if (features & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM)) { 3634 switch (skb->csum_offset) { 3635 case offsetof(struct tcphdr, check): 3636 case offsetof(struct udphdr, check): 3637 return 0; 3638 } 3639 } 3640 3641 return skb_checksum_help(skb); 3642} 3643EXPORT_SYMBOL(skb_csum_hwoffload_help); 3644 3645static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device *dev, bool *again) 3646{ 3647 netdev_features_t features; 3648 3649 features = netif_skb_features(skb); 3650 skb = validate_xmit_vlan(skb, features); 3651 if (unlikely(!skb)) 3652 goto out_null; 3653 3654 skb = sk_validate_xmit_skb(skb, dev); 3655 if (unlikely(!skb)) 3656 goto out_null; 3657 3658 if (netif_needs_gso(skb, features)) { 3659 struct sk_buff *segs; 3660 3661 segs = skb_gso_segment(skb, features); 3662 if (IS_ERR(segs)) { 3663 goto out_kfree_skb; 3664 } else if (segs) { 3665 consume_skb(skb); 3666 skb = segs; 3667 } 3668 } else { 3669 if (skb_needs_linearize(skb, features) && 3670 __skb_linearize(skb)) 3671 goto out_kfree_skb; 3672 3673 /* If packet is not checksummed and device does not 3674 * support checksumming for this protocol, complete 3675 * checksumming here. 3676 */ 3677 if (skb->ip_summed == CHECKSUM_PARTIAL) { 3678 if (skb->encapsulation) 3679 skb_set_inner_transport_header(skb, 3680 skb_checksum_start_offset(skb)); 3681 else 3682 skb_set_transport_header(skb, 3683 skb_checksum_start_offset(skb)); 3684 if (skb_csum_hwoffload_help(skb, features)) 3685 goto out_kfree_skb; 3686 } 3687 } 3688 3689 skb = validate_xmit_xfrm(skb, features, again); 3690 3691 return skb; 3692 3693out_kfree_skb: 3694 kfree_skb(skb); 3695out_null: 3696 dev_core_stats_tx_dropped_inc(dev); 3697 return NULL; 3698} 3699 3700struct sk_buff *validate_xmit_skb_list(struct sk_buff *skb, struct net_device *dev, bool *again) 3701{ 3702 struct sk_buff *next, *head = NULL, *tail; 3703 3704 for (; skb != NULL; skb = next) { 3705 next = skb->next; 3706 skb_mark_not_on_list(skb); 3707 3708 /* in case skb wont be segmented, point to itself */ 3709 skb->prev = skb; 3710 3711 skb = validate_xmit_skb(skb, dev, again); 3712 if (!skb) 3713 continue; 3714 3715 if (!head) 3716 head = skb; 3717 else 3718 tail->next = skb; 3719 /* If skb was segmented, skb->prev points to 3720 * the last segment. If not, it still contains skb. 3721 */ 3722 tail = skb->prev; 3723 } 3724 return head; 3725} 3726EXPORT_SYMBOL_GPL(validate_xmit_skb_list); 3727 3728static void qdisc_pkt_len_init(struct sk_buff *skb) 3729{ 3730 const struct skb_shared_info *shinfo = skb_shinfo(skb); 3731 3732 qdisc_skb_cb(skb)->pkt_len = skb->len; 3733 3734 /* To get more precise estimation of bytes sent on wire, 3735 * we add to pkt_len the headers size of all segments 3736 */ 3737 if (shinfo->gso_size && skb_transport_header_was_set(skb)) { 3738 u16 gso_segs = shinfo->gso_segs; 3739 unsigned int hdr_len; 3740 3741 /* mac layer + network layer */ 3742 hdr_len = skb_transport_offset(skb); 3743 3744 /* + transport layer */ 3745 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) { 3746 const struct tcphdr *th; 3747 struct tcphdr _tcphdr; 3748 3749 th = skb_header_pointer(skb, hdr_len, 3750 sizeof(_tcphdr), &_tcphdr); 3751 if (likely(th)) 3752 hdr_len += __tcp_hdrlen(th); 3753 } else { 3754 struct udphdr _udphdr; 3755 3756 if (skb_header_pointer(skb, hdr_len, 3757 sizeof(_udphdr), &_udphdr)) 3758 hdr_len += sizeof(struct udphdr); 3759 } 3760 3761 if (shinfo->gso_type & SKB_GSO_DODGY) 3762 gso_segs = DIV_ROUND_UP(skb->len - hdr_len, 3763 shinfo->gso_size); 3764 3765 qdisc_skb_cb(skb)->pkt_len += (gso_segs - 1) * hdr_len; 3766 } 3767} 3768 3769static int dev_qdisc_enqueue(struct sk_buff *skb, struct Qdisc *q, 3770 struct sk_buff **to_free, 3771 struct netdev_queue *txq) 3772{ 3773 int rc; 3774 3775 rc = q->enqueue(skb, q, to_free) & NET_XMIT_MASK; 3776 if (rc == NET_XMIT_SUCCESS) 3777 trace_qdisc_enqueue(q, txq, skb); 3778 return rc; 3779} 3780 3781static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q, 3782 struct net_device *dev, 3783 struct netdev_queue *txq) 3784{ 3785 spinlock_t *root_lock = qdisc_lock(q); 3786 struct sk_buff *to_free = NULL; 3787 bool contended; 3788 int rc; 3789 3790 qdisc_calculate_pkt_len(skb, q); 3791 3792 tcf_set_drop_reason(skb, SKB_DROP_REASON_QDISC_DROP); 3793 3794 if (q->flags & TCQ_F_NOLOCK) { 3795 if (q->flags & TCQ_F_CAN_BYPASS && nolock_qdisc_is_empty(q) && 3796 qdisc_run_begin(q)) { 3797 /* Retest nolock_qdisc_is_empty() within the protection 3798 * of q->seqlock to protect from racing with requeuing. 3799 */ 3800 if (unlikely(!nolock_qdisc_is_empty(q))) { 3801 rc = dev_qdisc_enqueue(skb, q, &to_free, txq); 3802 __qdisc_run(q); 3803 qdisc_run_end(q); 3804 3805 goto no_lock_out; 3806 } 3807 3808 qdisc_bstats_cpu_update(q, skb); 3809 if (sch_direct_xmit(skb, q, dev, txq, NULL, true) && 3810 !nolock_qdisc_is_empty(q)) 3811 __qdisc_run(q); 3812 3813 qdisc_run_end(q); 3814 return NET_XMIT_SUCCESS; 3815 } 3816 3817 rc = dev_qdisc_enqueue(skb, q, &to_free, txq); 3818 qdisc_run(q); 3819 3820no_lock_out: 3821 if (unlikely(to_free)) 3822 kfree_skb_list_reason(to_free, 3823 tcf_get_drop_reason(to_free)); 3824 return rc; 3825 } 3826 3827 if (unlikely(READ_ONCE(q->owner) == smp_processor_id())) { 3828 kfree_skb_reason(skb, SKB_DROP_REASON_TC_RECLASSIFY_LOOP); 3829 return NET_XMIT_DROP; 3830 } 3831 /* 3832 * Heuristic to force contended enqueues to serialize on a 3833 * separate lock before trying to get qdisc main lock. 3834 * This permits qdisc->running owner to get the lock more 3835 * often and dequeue packets faster. 3836 * On PREEMPT_RT it is possible to preempt the qdisc owner during xmit 3837 * and then other tasks will only enqueue packets. The packets will be 3838 * sent after the qdisc owner is scheduled again. To prevent this 3839 * scenario the task always serialize on the lock. 3840 */ 3841 contended = qdisc_is_running(q) || IS_ENABLED(CONFIG_PREEMPT_RT); 3842 if (unlikely(contended)) 3843 spin_lock(&q->busylock); 3844 3845 spin_lock(root_lock); 3846 if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) { 3847 __qdisc_drop(skb, &to_free); 3848 rc = NET_XMIT_DROP; 3849 } else if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) && 3850 qdisc_run_begin(q)) { 3851 /* 3852 * This is a work-conserving queue; there are no old skbs 3853 * waiting to be sent out; and the qdisc is not running - 3854 * xmit the skb directly. 3855 */ 3856 3857 qdisc_bstats_update(q, skb); 3858 3859 if (sch_direct_xmit(skb, q, dev, txq, root_lock, true)) { 3860 if (unlikely(contended)) { 3861 spin_unlock(&q->busylock); 3862 contended = false; 3863 } 3864 __qdisc_run(q); 3865 } 3866 3867 qdisc_run_end(q); 3868 rc = NET_XMIT_SUCCESS; 3869 } else { 3870 WRITE_ONCE(q->owner, smp_processor_id()); 3871 rc = dev_qdisc_enqueue(skb, q, &to_free, txq); 3872 WRITE_ONCE(q->owner, -1); 3873 if (qdisc_run_begin(q)) { 3874 if (unlikely(contended)) { 3875 spin_unlock(&q->busylock); 3876 contended = false; 3877 } 3878 __qdisc_run(q); 3879 qdisc_run_end(q); 3880 } 3881 } 3882 spin_unlock(root_lock); 3883 if (unlikely(to_free)) 3884 kfree_skb_list_reason(to_free, 3885 tcf_get_drop_reason(to_free)); 3886 if (unlikely(contended)) 3887 spin_unlock(&q->busylock); 3888 return rc; 3889} 3890 3891#if IS_ENABLED(CONFIG_CGROUP_NET_PRIO) 3892static void skb_update_prio(struct sk_buff *skb) 3893{ 3894 const struct netprio_map *map; 3895 const struct sock *sk; 3896 unsigned int prioidx; 3897 3898 if (skb->priority) 3899 return; 3900 map = rcu_dereference_bh(skb->dev->priomap); 3901 if (!map) 3902 return; 3903 sk = skb_to_full_sk(skb); 3904 if (!sk) 3905 return; 3906 3907 prioidx = sock_cgroup_prioidx(&sk->sk_cgrp_data); 3908 3909 if (prioidx < map->priomap_len) 3910 skb->priority = map->priomap[prioidx]; 3911} 3912#else 3913#define skb_update_prio(skb) 3914#endif 3915 3916/** 3917 * dev_loopback_xmit - loop back @skb 3918 * @net: network namespace this loopback is happening in 3919 * @sk: sk needed to be a netfilter okfn 3920 * @skb: buffer to transmit 3921 */ 3922int dev_loopback_xmit(struct net *net, struct sock *sk, struct sk_buff *skb) 3923{ 3924 skb_reset_mac_header(skb); 3925 __skb_pull(skb, skb_network_offset(skb)); 3926 skb->pkt_type = PACKET_LOOPBACK; 3927 if (skb->ip_summed == CHECKSUM_NONE) 3928 skb->ip_summed = CHECKSUM_UNNECESSARY; 3929 DEBUG_NET_WARN_ON_ONCE(!skb_dst(skb)); 3930 skb_dst_force(skb); 3931 netif_rx(skb); 3932 return 0; 3933} 3934EXPORT_SYMBOL(dev_loopback_xmit); 3935 3936#ifdef CONFIG_NET_EGRESS 3937static struct netdev_queue * 3938netdev_tx_queue_mapping(struct net_device *dev, struct sk_buff *skb) 3939{ 3940 int qm = skb_get_queue_mapping(skb); 3941 3942 return netdev_get_tx_queue(dev, netdev_cap_txqueue(dev, qm)); 3943} 3944 3945#ifndef CONFIG_PREEMPT_RT 3946static bool netdev_xmit_txqueue_skipped(void) 3947{ 3948 return __this_cpu_read(softnet_data.xmit.skip_txqueue); 3949} 3950 3951void netdev_xmit_skip_txqueue(bool skip) 3952{ 3953 __this_cpu_write(softnet_data.xmit.skip_txqueue, skip); 3954} 3955EXPORT_SYMBOL_GPL(netdev_xmit_skip_txqueue); 3956 3957#else 3958static bool netdev_xmit_txqueue_skipped(void) 3959{ 3960 return current->net_xmit.skip_txqueue; 3961} 3962 3963void netdev_xmit_skip_txqueue(bool skip) 3964{ 3965 current->net_xmit.skip_txqueue = skip; 3966} 3967EXPORT_SYMBOL_GPL(netdev_xmit_skip_txqueue); 3968#endif 3969#endif /* CONFIG_NET_EGRESS */ 3970 3971#ifdef CONFIG_NET_XGRESS 3972static int tc_run(struct tcx_entry *entry, struct sk_buff *skb, 3973 enum skb_drop_reason *drop_reason) 3974{ 3975 int ret = TC_ACT_UNSPEC; 3976#ifdef CONFIG_NET_CLS_ACT 3977 struct mini_Qdisc *miniq = rcu_dereference_bh(entry->miniq); 3978 struct tcf_result res; 3979 3980 if (!miniq) 3981 return ret; 3982 3983 if (static_branch_unlikely(&tcf_bypass_check_needed_key)) { 3984 if (tcf_block_bypass_sw(miniq->block)) 3985 return ret; 3986 } 3987 3988 tc_skb_cb(skb)->mru = 0; 3989 tc_skb_cb(skb)->post_ct = false; 3990 tcf_set_drop_reason(skb, *drop_reason); 3991 3992 mini_qdisc_bstats_cpu_update(miniq, skb); 3993 ret = tcf_classify(skb, miniq->block, miniq->filter_list, &res, false); 3994 /* Only tcf related quirks below. */ 3995 switch (ret) { 3996 case TC_ACT_SHOT: 3997 *drop_reason = tcf_get_drop_reason(skb); 3998 mini_qdisc_qstats_cpu_drop(miniq); 3999 break; 4000 case TC_ACT_OK: 4001 case TC_ACT_RECLASSIFY: 4002 skb->tc_index = TC_H_MIN(res.classid); 4003 break; 4004 } 4005#endif /* CONFIG_NET_CLS_ACT */ 4006 return ret; 4007} 4008 4009static DEFINE_STATIC_KEY_FALSE(tcx_needed_key); 4010 4011void tcx_inc(void) 4012{ 4013 static_branch_inc(&tcx_needed_key); 4014} 4015 4016void tcx_dec(void) 4017{ 4018 static_branch_dec(&tcx_needed_key); 4019} 4020 4021static __always_inline enum tcx_action_base 4022tcx_run(const struct bpf_mprog_entry *entry, struct sk_buff *skb, 4023 const bool needs_mac) 4024{ 4025 const struct bpf_mprog_fp *fp; 4026 const struct bpf_prog *prog; 4027 int ret = TCX_NEXT; 4028 4029 if (needs_mac) 4030 __skb_push(skb, skb->mac_len); 4031 bpf_mprog_foreach_prog(entry, fp, prog) { 4032 bpf_compute_data_pointers(skb); 4033 ret = bpf_prog_run(prog, skb); 4034 if (ret != TCX_NEXT) 4035 break; 4036 } 4037 if (needs_mac) 4038 __skb_pull(skb, skb->mac_len); 4039 return tcx_action_code(skb, ret); 4040} 4041 4042static __always_inline struct sk_buff * 4043sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret, 4044 struct net_device *orig_dev, bool *another) 4045{ 4046 struct bpf_mprog_entry *entry = rcu_dereference_bh(skb->dev->tcx_ingress); 4047 enum skb_drop_reason drop_reason = SKB_DROP_REASON_TC_INGRESS; 4048 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx; 4049 int sch_ret; 4050 4051 if (!entry) 4052 return skb; 4053 4054 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx); 4055 if (*pt_prev) { 4056 *ret = deliver_skb(skb, *pt_prev, orig_dev); 4057 *pt_prev = NULL; 4058 } 4059 4060 qdisc_skb_cb(skb)->pkt_len = skb->len; 4061 tcx_set_ingress(skb, true); 4062 4063 if (static_branch_unlikely(&tcx_needed_key)) { 4064 sch_ret = tcx_run(entry, skb, true); 4065 if (sch_ret != TC_ACT_UNSPEC) 4066 goto ingress_verdict; 4067 } 4068 sch_ret = tc_run(tcx_entry(entry), skb, &drop_reason); 4069ingress_verdict: 4070 switch (sch_ret) { 4071 case TC_ACT_REDIRECT: 4072 /* skb_mac_header check was done by BPF, so we can safely 4073 * push the L2 header back before redirecting to another 4074 * netdev. 4075 */ 4076 __skb_push(skb, skb->mac_len); 4077 if (skb_do_redirect(skb) == -EAGAIN) { 4078 __skb_pull(skb, skb->mac_len); 4079 *another = true; 4080 break; 4081 } 4082 *ret = NET_RX_SUCCESS; 4083 bpf_net_ctx_clear(bpf_net_ctx); 4084 return NULL; 4085 case TC_ACT_SHOT: 4086 kfree_skb_reason(skb, drop_reason); 4087 *ret = NET_RX_DROP; 4088 bpf_net_ctx_clear(bpf_net_ctx); 4089 return NULL; 4090 /* used by tc_run */ 4091 case TC_ACT_STOLEN: 4092 case TC_ACT_QUEUED: 4093 case TC_ACT_TRAP: 4094 consume_skb(skb); 4095 fallthrough; 4096 case TC_ACT_CONSUMED: 4097 *ret = NET_RX_SUCCESS; 4098 bpf_net_ctx_clear(bpf_net_ctx); 4099 return NULL; 4100 } 4101 bpf_net_ctx_clear(bpf_net_ctx); 4102 4103 return skb; 4104} 4105 4106static __always_inline struct sk_buff * 4107sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev) 4108{ 4109 struct bpf_mprog_entry *entry = rcu_dereference_bh(dev->tcx_egress); 4110 enum skb_drop_reason drop_reason = SKB_DROP_REASON_TC_EGRESS; 4111 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx; 4112 int sch_ret; 4113 4114 if (!entry) 4115 return skb; 4116 4117 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx); 4118 4119 /* qdisc_skb_cb(skb)->pkt_len & tcx_set_ingress() was 4120 * already set by the caller. 4121 */ 4122 if (static_branch_unlikely(&tcx_needed_key)) { 4123 sch_ret = tcx_run(entry, skb, false); 4124 if (sch_ret != TC_ACT_UNSPEC) 4125 goto egress_verdict; 4126 } 4127 sch_ret = tc_run(tcx_entry(entry), skb, &drop_reason); 4128egress_verdict: 4129 switch (sch_ret) { 4130 case TC_ACT_REDIRECT: 4131 /* No need to push/pop skb's mac_header here on egress! */ 4132 skb_do_redirect(skb); 4133 *ret = NET_XMIT_SUCCESS; 4134 bpf_net_ctx_clear(bpf_net_ctx); 4135 return NULL; 4136 case TC_ACT_SHOT: 4137 kfree_skb_reason(skb, drop_reason); 4138 *ret = NET_XMIT_DROP; 4139 bpf_net_ctx_clear(bpf_net_ctx); 4140 return NULL; 4141 /* used by tc_run */ 4142 case TC_ACT_STOLEN: 4143 case TC_ACT_QUEUED: 4144 case TC_ACT_TRAP: 4145 consume_skb(skb); 4146 fallthrough; 4147 case TC_ACT_CONSUMED: 4148 *ret = NET_XMIT_SUCCESS; 4149 bpf_net_ctx_clear(bpf_net_ctx); 4150 return NULL; 4151 } 4152 bpf_net_ctx_clear(bpf_net_ctx); 4153 4154 return skb; 4155} 4156#else 4157static __always_inline struct sk_buff * 4158sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret, 4159 struct net_device *orig_dev, bool *another) 4160{ 4161 return skb; 4162} 4163 4164static __always_inline struct sk_buff * 4165sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev) 4166{ 4167 return skb; 4168} 4169#endif /* CONFIG_NET_XGRESS */ 4170 4171#ifdef CONFIG_XPS 4172static int __get_xps_queue_idx(struct net_device *dev, struct sk_buff *skb, 4173 struct xps_dev_maps *dev_maps, unsigned int tci) 4174{ 4175 int tc = netdev_get_prio_tc_map(dev, skb->priority); 4176 struct xps_map *map; 4177 int queue_index = -1; 4178 4179 if (tc >= dev_maps->num_tc || tci >= dev_maps->nr_ids) 4180 return queue_index; 4181 4182 tci *= dev_maps->num_tc; 4183 tci += tc; 4184 4185 map = rcu_dereference(dev_maps->attr_map[tci]); 4186 if (map) { 4187 if (map->len == 1) 4188 queue_index = map->queues[0]; 4189 else 4190 queue_index = map->queues[reciprocal_scale( 4191 skb_get_hash(skb), map->len)]; 4192 if (unlikely(queue_index >= dev->real_num_tx_queues)) 4193 queue_index = -1; 4194 } 4195 return queue_index; 4196} 4197#endif 4198 4199static int get_xps_queue(struct net_device *dev, struct net_device *sb_dev, 4200 struct sk_buff *skb) 4201{ 4202#ifdef CONFIG_XPS 4203 struct xps_dev_maps *dev_maps; 4204 struct sock *sk = skb->sk; 4205 int queue_index = -1; 4206 4207 if (!static_key_false(&xps_needed)) 4208 return -1; 4209 4210 rcu_read_lock(); 4211 if (!static_key_false(&xps_rxqs_needed)) 4212 goto get_cpus_map; 4213 4214 dev_maps = rcu_dereference(sb_dev->xps_maps[XPS_RXQS]); 4215 if (dev_maps) { 4216 int tci = sk_rx_queue_get(sk); 4217 4218 if (tci >= 0) 4219 queue_index = __get_xps_queue_idx(dev, skb, dev_maps, 4220 tci); 4221 } 4222 4223get_cpus_map: 4224 if (queue_index < 0) { 4225 dev_maps = rcu_dereference(sb_dev->xps_maps[XPS_CPUS]); 4226 if (dev_maps) { 4227 unsigned int tci = skb->sender_cpu - 1; 4228 4229 queue_index = __get_xps_queue_idx(dev, skb, dev_maps, 4230 tci); 4231 } 4232 } 4233 rcu_read_unlock(); 4234 4235 return queue_index; 4236#else 4237 return -1; 4238#endif 4239} 4240 4241u16 dev_pick_tx_zero(struct net_device *dev, struct sk_buff *skb, 4242 struct net_device *sb_dev) 4243{ 4244 return 0; 4245} 4246EXPORT_SYMBOL(dev_pick_tx_zero); 4247 4248u16 dev_pick_tx_cpu_id(struct net_device *dev, struct sk_buff *skb, 4249 struct net_device *sb_dev) 4250{ 4251 return (u16)raw_smp_processor_id() % dev->real_num_tx_queues; 4252} 4253EXPORT_SYMBOL(dev_pick_tx_cpu_id); 4254 4255u16 netdev_pick_tx(struct net_device *dev, struct sk_buff *skb, 4256 struct net_device *sb_dev) 4257{ 4258 struct sock *sk = skb->sk; 4259 int queue_index = sk_tx_queue_get(sk); 4260 4261 sb_dev = sb_dev ? : dev; 4262 4263 if (queue_index < 0 || skb->ooo_okay || 4264 queue_index >= dev->real_num_tx_queues) { 4265 int new_index = get_xps_queue(dev, sb_dev, skb); 4266 4267 if (new_index < 0) 4268 new_index = skb_tx_hash(dev, sb_dev, skb); 4269 4270 if (queue_index != new_index && sk && 4271 sk_fullsock(sk) && 4272 rcu_access_pointer(sk->sk_dst_cache)) 4273 sk_tx_queue_set(sk, new_index); 4274 4275 queue_index = new_index; 4276 } 4277 4278 return queue_index; 4279} 4280EXPORT_SYMBOL(netdev_pick_tx); 4281 4282struct netdev_queue *netdev_core_pick_tx(struct net_device *dev, 4283 struct sk_buff *skb, 4284 struct net_device *sb_dev) 4285{ 4286 int queue_index = 0; 4287 4288#ifdef CONFIG_XPS 4289 u32 sender_cpu = skb->sender_cpu - 1; 4290 4291 if (sender_cpu >= (u32)NR_CPUS) 4292 skb->sender_cpu = raw_smp_processor_id() + 1; 4293#endif 4294 4295 if (dev->real_num_tx_queues != 1) { 4296 const struct net_device_ops *ops = dev->netdev_ops; 4297 4298 if (ops->ndo_select_queue) 4299 queue_index = ops->ndo_select_queue(dev, skb, sb_dev); 4300 else 4301 queue_index = netdev_pick_tx(dev, skb, sb_dev); 4302 4303 queue_index = netdev_cap_txqueue(dev, queue_index); 4304 } 4305 4306 skb_set_queue_mapping(skb, queue_index); 4307 return netdev_get_tx_queue(dev, queue_index); 4308} 4309 4310/** 4311 * __dev_queue_xmit() - transmit a buffer 4312 * @skb: buffer to transmit 4313 * @sb_dev: suboordinate device used for L2 forwarding offload 4314 * 4315 * Queue a buffer for transmission to a network device. The caller must 4316 * have set the device and priority and built the buffer before calling 4317 * this function. The function can be called from an interrupt. 4318 * 4319 * When calling this method, interrupts MUST be enabled. This is because 4320 * the BH enable code must have IRQs enabled so that it will not deadlock. 4321 * 4322 * Regardless of the return value, the skb is consumed, so it is currently 4323 * difficult to retry a send to this method. (You can bump the ref count 4324 * before sending to hold a reference for retry if you are careful.) 4325 * 4326 * Return: 4327 * * 0 - buffer successfully transmitted 4328 * * positive qdisc return code - NET_XMIT_DROP etc. 4329 * * negative errno - other errors 4330 */ 4331int __dev_queue_xmit(struct sk_buff *skb, struct net_device *sb_dev) 4332{ 4333 struct net_device *dev = skb->dev; 4334 struct netdev_queue *txq = NULL; 4335 struct Qdisc *q; 4336 int rc = -ENOMEM; 4337 bool again = false; 4338 4339 skb_reset_mac_header(skb); 4340 skb_assert_len(skb); 4341 4342 if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_SCHED_TSTAMP)) 4343 __skb_tstamp_tx(skb, NULL, NULL, skb->sk, SCM_TSTAMP_SCHED); 4344 4345 /* Disable soft irqs for various locks below. Also 4346 * stops preemption for RCU. 4347 */ 4348 rcu_read_lock_bh(); 4349 4350 skb_update_prio(skb); 4351 4352 qdisc_pkt_len_init(skb); 4353 tcx_set_ingress(skb, false); 4354#ifdef CONFIG_NET_EGRESS 4355 if (static_branch_unlikely(&egress_needed_key)) { 4356 if (nf_hook_egress_active()) { 4357 skb = nf_hook_egress(skb, &rc, dev); 4358 if (!skb) 4359 goto out; 4360 } 4361 4362 netdev_xmit_skip_txqueue(false); 4363 4364 nf_skip_egress(skb, true); 4365 skb = sch_handle_egress(skb, &rc, dev); 4366 if (!skb) 4367 goto out; 4368 nf_skip_egress(skb, false); 4369 4370 if (netdev_xmit_txqueue_skipped()) 4371 txq = netdev_tx_queue_mapping(dev, skb); 4372 } 4373#endif 4374 /* If device/qdisc don't need skb->dst, release it right now while 4375 * its hot in this cpu cache. 4376 */ 4377 if (dev->priv_flags & IFF_XMIT_DST_RELEASE) 4378 skb_dst_drop(skb); 4379 else 4380 skb_dst_force(skb); 4381 4382 if (!txq) 4383 txq = netdev_core_pick_tx(dev, skb, sb_dev); 4384 4385 q = rcu_dereference_bh(txq->qdisc); 4386 4387 trace_net_dev_queue(skb); 4388 if (q->enqueue) { 4389 rc = __dev_xmit_skb(skb, q, dev, txq); 4390 goto out; 4391 } 4392 4393 /* The device has no queue. Common case for software devices: 4394 * loopback, all the sorts of tunnels... 4395 4396 * Really, it is unlikely that netif_tx_lock protection is necessary 4397 * here. (f.e. loopback and IP tunnels are clean ignoring statistics 4398 * counters.) 4399 * However, it is possible, that they rely on protection 4400 * made by us here. 4401 4402 * Check this and shot the lock. It is not prone from deadlocks. 4403 *Either shot noqueue qdisc, it is even simpler 8) 4404 */ 4405 if (dev->flags & IFF_UP) { 4406 int cpu = smp_processor_id(); /* ok because BHs are off */ 4407 4408 /* Other cpus might concurrently change txq->xmit_lock_owner 4409 * to -1 or to their cpu id, but not to our id. 4410 */ 4411 if (READ_ONCE(txq->xmit_lock_owner) != cpu) { 4412 if (dev_xmit_recursion()) 4413 goto recursion_alert; 4414 4415 skb = validate_xmit_skb(skb, dev, &again); 4416 if (!skb) 4417 goto out; 4418 4419 HARD_TX_LOCK(dev, txq, cpu); 4420 4421 if (!netif_xmit_stopped(txq)) { 4422 dev_xmit_recursion_inc(); 4423 skb = dev_hard_start_xmit(skb, dev, txq, &rc); 4424 dev_xmit_recursion_dec(); 4425 if (dev_xmit_complete(rc)) { 4426 HARD_TX_UNLOCK(dev, txq); 4427 goto out; 4428 } 4429 } 4430 HARD_TX_UNLOCK(dev, txq); 4431 net_crit_ratelimited("Virtual device %s asks to queue packet!\n", 4432 dev->name); 4433 } else { 4434 /* Recursion is detected! It is possible, 4435 * unfortunately 4436 */ 4437recursion_alert: 4438 net_crit_ratelimited("Dead loop on virtual device %s, fix it urgently!\n", 4439 dev->name); 4440 } 4441 } 4442 4443 rc = -ENETDOWN; 4444 rcu_read_unlock_bh(); 4445 4446 dev_core_stats_tx_dropped_inc(dev); 4447 kfree_skb_list(skb); 4448 return rc; 4449out: 4450 rcu_read_unlock_bh(); 4451 return rc; 4452} 4453EXPORT_SYMBOL(__dev_queue_xmit); 4454 4455int __dev_direct_xmit(struct sk_buff *skb, u16 queue_id) 4456{ 4457 struct net_device *dev = skb->dev; 4458 struct sk_buff *orig_skb = skb; 4459 struct netdev_queue *txq; 4460 int ret = NETDEV_TX_BUSY; 4461 bool again = false; 4462 4463 if (unlikely(!netif_running(dev) || 4464 !netif_carrier_ok(dev))) 4465 goto drop; 4466 4467 skb = validate_xmit_skb_list(skb, dev, &again); 4468 if (skb != orig_skb) 4469 goto drop; 4470 4471 skb_set_queue_mapping(skb, queue_id); 4472 txq = skb_get_tx_queue(dev, skb); 4473 4474 local_bh_disable(); 4475 4476 dev_xmit_recursion_inc(); 4477 HARD_TX_LOCK(dev, txq, smp_processor_id()); 4478 if (!netif_xmit_frozen_or_drv_stopped(txq)) 4479 ret = netdev_start_xmit(skb, dev, txq, false); 4480 HARD_TX_UNLOCK(dev, txq); 4481 dev_xmit_recursion_dec(); 4482 4483 local_bh_enable(); 4484 return ret; 4485drop: 4486 dev_core_stats_tx_dropped_inc(dev); 4487 kfree_skb_list(skb); 4488 return NET_XMIT_DROP; 4489} 4490EXPORT_SYMBOL(__dev_direct_xmit); 4491 4492/************************************************************************* 4493 * Receiver routines 4494 *************************************************************************/ 4495static DEFINE_PER_CPU(struct task_struct *, backlog_napi); 4496 4497int weight_p __read_mostly = 64; /* old backlog weight */ 4498int dev_weight_rx_bias __read_mostly = 1; /* bias for backlog weight */ 4499int dev_weight_tx_bias __read_mostly = 1; /* bias for output_queue quota */ 4500 4501/* Called with irq disabled */ 4502static inline void ____napi_schedule(struct softnet_data *sd, 4503 struct napi_struct *napi) 4504{ 4505 struct task_struct *thread; 4506 4507 lockdep_assert_irqs_disabled(); 4508 4509 if (test_bit(NAPI_STATE_THREADED, &napi->state)) { 4510 /* Paired with smp_mb__before_atomic() in 4511 * napi_enable()/dev_set_threaded(). 4512 * Use READ_ONCE() to guarantee a complete 4513 * read on napi->thread. Only call 4514 * wake_up_process() when it's not NULL. 4515 */ 4516 thread = READ_ONCE(napi->thread); 4517 if (thread) { 4518 if (use_backlog_threads() && thread == raw_cpu_read(backlog_napi)) 4519 goto use_local_napi; 4520 4521 set_bit(NAPI_STATE_SCHED_THREADED, &napi->state); 4522 wake_up_process(thread); 4523 return; 4524 } 4525 } 4526 4527use_local_napi: 4528 list_add_tail(&napi->poll_list, &sd->poll_list); 4529 WRITE_ONCE(napi->list_owner, smp_processor_id()); 4530 /* If not called from net_rx_action() 4531 * we have to raise NET_RX_SOFTIRQ. 4532 */ 4533 if (!sd->in_net_rx_action) 4534 __raise_softirq_irqoff(NET_RX_SOFTIRQ); 4535} 4536 4537#ifdef CONFIG_RPS 4538 4539struct static_key_false rps_needed __read_mostly; 4540EXPORT_SYMBOL(rps_needed); 4541struct static_key_false rfs_needed __read_mostly; 4542EXPORT_SYMBOL(rfs_needed); 4543 4544static struct rps_dev_flow * 4545set_rps_cpu(struct net_device *dev, struct sk_buff *skb, 4546 struct rps_dev_flow *rflow, u16 next_cpu) 4547{ 4548 if (next_cpu < nr_cpu_ids) { 4549 u32 head; 4550#ifdef CONFIG_RFS_ACCEL 4551 struct netdev_rx_queue *rxqueue; 4552 struct rps_dev_flow_table *flow_table; 4553 struct rps_dev_flow *old_rflow; 4554 u16 rxq_index; 4555 u32 flow_id; 4556 int rc; 4557 4558 /* Should we steer this flow to a different hardware queue? */ 4559 if (!skb_rx_queue_recorded(skb) || !dev->rx_cpu_rmap || 4560 !(dev->features & NETIF_F_NTUPLE)) 4561 goto out; 4562 rxq_index = cpu_rmap_lookup_index(dev->rx_cpu_rmap, next_cpu); 4563 if (rxq_index == skb_get_rx_queue(skb)) 4564 goto out; 4565 4566 rxqueue = dev->_rx + rxq_index; 4567 flow_table = rcu_dereference(rxqueue->rps_flow_table); 4568 if (!flow_table) 4569 goto out; 4570 flow_id = skb_get_hash(skb) & flow_table->mask; 4571 rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb, 4572 rxq_index, flow_id); 4573 if (rc < 0) 4574 goto out; 4575 old_rflow = rflow; 4576 rflow = &flow_table->flows[flow_id]; 4577 WRITE_ONCE(rflow->filter, rc); 4578 if (old_rflow->filter == rc) 4579 WRITE_ONCE(old_rflow->filter, RPS_NO_FILTER); 4580 out: 4581#endif 4582 head = READ_ONCE(per_cpu(softnet_data, next_cpu).input_queue_head); 4583 rps_input_queue_tail_save(&rflow->last_qtail, head); 4584 } 4585 4586 WRITE_ONCE(rflow->cpu, next_cpu); 4587 return rflow; 4588} 4589 4590/* 4591 * get_rps_cpu is called from netif_receive_skb and returns the target 4592 * CPU from the RPS map of the receiving queue for a given skb. 4593 * rcu_read_lock must be held on entry. 4594 */ 4595static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb, 4596 struct rps_dev_flow **rflowp) 4597{ 4598 const struct rps_sock_flow_table *sock_flow_table; 4599 struct netdev_rx_queue *rxqueue = dev->_rx; 4600 struct rps_dev_flow_table *flow_table; 4601 struct rps_map *map; 4602 int cpu = -1; 4603 u32 tcpu; 4604 u32 hash; 4605 4606 if (skb_rx_queue_recorded(skb)) { 4607 u16 index = skb_get_rx_queue(skb); 4608 4609 if (unlikely(index >= dev->real_num_rx_queues)) { 4610 WARN_ONCE(dev->real_num_rx_queues > 1, 4611 "%s received packet on queue %u, but number " 4612 "of RX queues is %u\n", 4613 dev->name, index, dev->real_num_rx_queues); 4614 goto done; 4615 } 4616 rxqueue += index; 4617 } 4618 4619 /* Avoid computing hash if RFS/RPS is not active for this rxqueue */ 4620 4621 flow_table = rcu_dereference(rxqueue->rps_flow_table); 4622 map = rcu_dereference(rxqueue->rps_map); 4623 if (!flow_table && !map) 4624 goto done; 4625 4626 skb_reset_network_header(skb); 4627 hash = skb_get_hash(skb); 4628 if (!hash) 4629 goto done; 4630 4631 sock_flow_table = rcu_dereference(net_hotdata.rps_sock_flow_table); 4632 if (flow_table && sock_flow_table) { 4633 struct rps_dev_flow *rflow; 4634 u32 next_cpu; 4635 u32 ident; 4636 4637 /* First check into global flow table if there is a match. 4638 * This READ_ONCE() pairs with WRITE_ONCE() from rps_record_sock_flow(). 4639 */ 4640 ident = READ_ONCE(sock_flow_table->ents[hash & sock_flow_table->mask]); 4641 if ((ident ^ hash) & ~net_hotdata.rps_cpu_mask) 4642 goto try_rps; 4643 4644 next_cpu = ident & net_hotdata.rps_cpu_mask; 4645 4646 /* OK, now we know there is a match, 4647 * we can look at the local (per receive queue) flow table 4648 */ 4649 rflow = &flow_table->flows[hash & flow_table->mask]; 4650 tcpu = rflow->cpu; 4651 4652 /* 4653 * If the desired CPU (where last recvmsg was done) is 4654 * different from current CPU (one in the rx-queue flow 4655 * table entry), switch if one of the following holds: 4656 * - Current CPU is unset (>= nr_cpu_ids). 4657 * - Current CPU is offline. 4658 * - The current CPU's queue tail has advanced beyond the 4659 * last packet that was enqueued using this table entry. 4660 * This guarantees that all previous packets for the flow 4661 * have been dequeued, thus preserving in order delivery. 4662 */ 4663 if (unlikely(tcpu != next_cpu) && 4664 (tcpu >= nr_cpu_ids || !cpu_online(tcpu) || 4665 ((int)(READ_ONCE(per_cpu(softnet_data, tcpu).input_queue_head) - 4666 rflow->last_qtail)) >= 0)) { 4667 tcpu = next_cpu; 4668 rflow = set_rps_cpu(dev, skb, rflow, next_cpu); 4669 } 4670 4671 if (tcpu < nr_cpu_ids && cpu_online(tcpu)) { 4672 *rflowp = rflow; 4673 cpu = tcpu; 4674 goto done; 4675 } 4676 } 4677 4678try_rps: 4679 4680 if (map) { 4681 tcpu = map->cpus[reciprocal_scale(hash, map->len)]; 4682 if (cpu_online(tcpu)) { 4683 cpu = tcpu; 4684 goto done; 4685 } 4686 } 4687 4688done: 4689 return cpu; 4690} 4691 4692#ifdef CONFIG_RFS_ACCEL 4693 4694/** 4695 * rps_may_expire_flow - check whether an RFS hardware filter may be removed 4696 * @dev: Device on which the filter was set 4697 * @rxq_index: RX queue index 4698 * @flow_id: Flow ID passed to ndo_rx_flow_steer() 4699 * @filter_id: Filter ID returned by ndo_rx_flow_steer() 4700 * 4701 * Drivers that implement ndo_rx_flow_steer() should periodically call 4702 * this function for each installed filter and remove the filters for 4703 * which it returns %true. 4704 */ 4705bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index, 4706 u32 flow_id, u16 filter_id) 4707{ 4708 struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index; 4709 struct rps_dev_flow_table *flow_table; 4710 struct rps_dev_flow *rflow; 4711 bool expire = true; 4712 unsigned int cpu; 4713 4714 rcu_read_lock(); 4715 flow_table = rcu_dereference(rxqueue->rps_flow_table); 4716 if (flow_table && flow_id <= flow_table->mask) { 4717 rflow = &flow_table->flows[flow_id]; 4718 cpu = READ_ONCE(rflow->cpu); 4719 if (READ_ONCE(rflow->filter) == filter_id && cpu < nr_cpu_ids && 4720 ((int)(READ_ONCE(per_cpu(softnet_data, cpu).input_queue_head) - 4721 READ_ONCE(rflow->last_qtail)) < 4722 (int)(10 * flow_table->mask))) 4723 expire = false; 4724 } 4725 rcu_read_unlock(); 4726 return expire; 4727} 4728EXPORT_SYMBOL(rps_may_expire_flow); 4729 4730#endif /* CONFIG_RFS_ACCEL */ 4731 4732/* Called from hardirq (IPI) context */ 4733static void rps_trigger_softirq(void *data) 4734{ 4735 struct softnet_data *sd = data; 4736 4737 ____napi_schedule(sd, &sd->backlog); 4738 sd->received_rps++; 4739} 4740 4741#endif /* CONFIG_RPS */ 4742 4743/* Called from hardirq (IPI) context */ 4744static void trigger_rx_softirq(void *data) 4745{ 4746 struct softnet_data *sd = data; 4747 4748 __raise_softirq_irqoff(NET_RX_SOFTIRQ); 4749 smp_store_release(&sd->defer_ipi_scheduled, 0); 4750} 4751 4752/* 4753 * After we queued a packet into sd->input_pkt_queue, 4754 * we need to make sure this queue is serviced soon. 4755 * 4756 * - If this is another cpu queue, link it to our rps_ipi_list, 4757 * and make sure we will process rps_ipi_list from net_rx_action(). 4758 * 4759 * - If this is our own queue, NAPI schedule our backlog. 4760 * Note that this also raises NET_RX_SOFTIRQ. 4761 */ 4762static void napi_schedule_rps(struct softnet_data *sd) 4763{ 4764 struct softnet_data *mysd = this_cpu_ptr(&softnet_data); 4765 4766#ifdef CONFIG_RPS 4767 if (sd != mysd) { 4768 if (use_backlog_threads()) { 4769 __napi_schedule_irqoff(&sd->backlog); 4770 return; 4771 } 4772 4773 sd->rps_ipi_next = mysd->rps_ipi_list; 4774 mysd->rps_ipi_list = sd; 4775 4776 /* If not called from net_rx_action() or napi_threaded_poll() 4777 * we have to raise NET_RX_SOFTIRQ. 4778 */ 4779 if (!mysd->in_net_rx_action && !mysd->in_napi_threaded_poll) 4780 __raise_softirq_irqoff(NET_RX_SOFTIRQ); 4781 return; 4782 } 4783#endif /* CONFIG_RPS */ 4784 __napi_schedule_irqoff(&mysd->backlog); 4785} 4786 4787void kick_defer_list_purge(struct softnet_data *sd, unsigned int cpu) 4788{ 4789 unsigned long flags; 4790 4791 if (use_backlog_threads()) { 4792 backlog_lock_irq_save(sd, &flags); 4793 4794 if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state)) 4795 __napi_schedule_irqoff(&sd->backlog); 4796 4797 backlog_unlock_irq_restore(sd, &flags); 4798 4799 } else if (!cmpxchg(&sd->defer_ipi_scheduled, 0, 1)) { 4800 smp_call_function_single_async(cpu, &sd->defer_csd); 4801 } 4802} 4803 4804#ifdef CONFIG_NET_FLOW_LIMIT 4805int netdev_flow_limit_table_len __read_mostly = (1 << 12); 4806#endif 4807 4808static bool skb_flow_limit(struct sk_buff *skb, unsigned int qlen) 4809{ 4810#ifdef CONFIG_NET_FLOW_LIMIT 4811 struct sd_flow_limit *fl; 4812 struct softnet_data *sd; 4813 unsigned int old_flow, new_flow; 4814 4815 if (qlen < (READ_ONCE(net_hotdata.max_backlog) >> 1)) 4816 return false; 4817 4818 sd = this_cpu_ptr(&softnet_data); 4819 4820 rcu_read_lock(); 4821 fl = rcu_dereference(sd->flow_limit); 4822 if (fl) { 4823 new_flow = skb_get_hash(skb) & (fl->num_buckets - 1); 4824 old_flow = fl->history[fl->history_head]; 4825 fl->history[fl->history_head] = new_flow; 4826 4827 fl->history_head++; 4828 fl->history_head &= FLOW_LIMIT_HISTORY - 1; 4829 4830 if (likely(fl->buckets[old_flow])) 4831 fl->buckets[old_flow]--; 4832 4833 if (++fl->buckets[new_flow] > (FLOW_LIMIT_HISTORY >> 1)) { 4834 fl->count++; 4835 rcu_read_unlock(); 4836 return true; 4837 } 4838 } 4839 rcu_read_unlock(); 4840#endif 4841 return false; 4842} 4843 4844/* 4845 * enqueue_to_backlog is called to queue an skb to a per CPU backlog 4846 * queue (may be a remote CPU queue). 4847 */ 4848static int enqueue_to_backlog(struct sk_buff *skb, int cpu, 4849 unsigned int *qtail) 4850{ 4851 enum skb_drop_reason reason; 4852 struct softnet_data *sd; 4853 unsigned long flags; 4854 unsigned int qlen; 4855 int max_backlog; 4856 u32 tail; 4857 4858 reason = SKB_DROP_REASON_DEV_READY; 4859 if (!netif_running(skb->dev)) 4860 goto bad_dev; 4861 4862 reason = SKB_DROP_REASON_CPU_BACKLOG; 4863 sd = &per_cpu(softnet_data, cpu); 4864 4865 qlen = skb_queue_len_lockless(&sd->input_pkt_queue); 4866 max_backlog = READ_ONCE(net_hotdata.max_backlog); 4867 if (unlikely(qlen > max_backlog)) 4868 goto cpu_backlog_drop; 4869 backlog_lock_irq_save(sd, &flags); 4870 qlen = skb_queue_len(&sd->input_pkt_queue); 4871 if (qlen <= max_backlog && !skb_flow_limit(skb, qlen)) { 4872 if (!qlen) { 4873 /* Schedule NAPI for backlog device. We can use 4874 * non atomic operation as we own the queue lock. 4875 */ 4876 if (!__test_and_set_bit(NAPI_STATE_SCHED, 4877 &sd->backlog.state)) 4878 napi_schedule_rps(sd); 4879 } 4880 __skb_queue_tail(&sd->input_pkt_queue, skb); 4881 tail = rps_input_queue_tail_incr(sd); 4882 backlog_unlock_irq_restore(sd, &flags); 4883 4884 /* save the tail outside of the critical section */ 4885 rps_input_queue_tail_save(qtail, tail); 4886 return NET_RX_SUCCESS; 4887 } 4888 4889 backlog_unlock_irq_restore(sd, &flags); 4890 4891cpu_backlog_drop: 4892 atomic_inc(&sd->dropped); 4893bad_dev: 4894 dev_core_stats_rx_dropped_inc(skb->dev); 4895 kfree_skb_reason(skb, reason); 4896 return NET_RX_DROP; 4897} 4898 4899static struct netdev_rx_queue *netif_get_rxqueue(struct sk_buff *skb) 4900{ 4901 struct net_device *dev = skb->dev; 4902 struct netdev_rx_queue *rxqueue; 4903 4904 rxqueue = dev->_rx; 4905 4906 if (skb_rx_queue_recorded(skb)) { 4907 u16 index = skb_get_rx_queue(skb); 4908 4909 if (unlikely(index >= dev->real_num_rx_queues)) { 4910 WARN_ONCE(dev->real_num_rx_queues > 1, 4911 "%s received packet on queue %u, but number " 4912 "of RX queues is %u\n", 4913 dev->name, index, dev->real_num_rx_queues); 4914 4915 return rxqueue; /* Return first rxqueue */ 4916 } 4917 rxqueue += index; 4918 } 4919 return rxqueue; 4920} 4921 4922u32 bpf_prog_run_generic_xdp(struct sk_buff *skb, struct xdp_buff *xdp, 4923 struct bpf_prog *xdp_prog) 4924{ 4925 void *orig_data, *orig_data_end, *hard_start; 4926 struct netdev_rx_queue *rxqueue; 4927 bool orig_bcast, orig_host; 4928 u32 mac_len, frame_sz; 4929 __be16 orig_eth_type; 4930 struct ethhdr *eth; 4931 u32 metalen, act; 4932 int off; 4933 4934 /* The XDP program wants to see the packet starting at the MAC 4935 * header. 4936 */ 4937 mac_len = skb->data - skb_mac_header(skb); 4938 hard_start = skb->data - skb_headroom(skb); 4939 4940 /* SKB "head" area always have tailroom for skb_shared_info */ 4941 frame_sz = (void *)skb_end_pointer(skb) - hard_start; 4942 frame_sz += SKB_DATA_ALIGN(sizeof(struct skb_shared_info)); 4943 4944 rxqueue = netif_get_rxqueue(skb); 4945 xdp_init_buff(xdp, frame_sz, &rxqueue->xdp_rxq); 4946 xdp_prepare_buff(xdp, hard_start, skb_headroom(skb) - mac_len, 4947 skb_headlen(skb) + mac_len, true); 4948 if (skb_is_nonlinear(skb)) { 4949 skb_shinfo(skb)->xdp_frags_size = skb->data_len; 4950 xdp_buff_set_frags_flag(xdp); 4951 } else { 4952 xdp_buff_clear_frags_flag(xdp); 4953 } 4954 4955 orig_data_end = xdp->data_end; 4956 orig_data = xdp->data; 4957 eth = (struct ethhdr *)xdp->data; 4958 orig_host = ether_addr_equal_64bits(eth->h_dest, skb->dev->dev_addr); 4959 orig_bcast = is_multicast_ether_addr_64bits(eth->h_dest); 4960 orig_eth_type = eth->h_proto; 4961 4962 act = bpf_prog_run_xdp(xdp_prog, xdp); 4963 4964 /* check if bpf_xdp_adjust_head was used */ 4965 off = xdp->data - orig_data; 4966 if (off) { 4967 if (off > 0) 4968 __skb_pull(skb, off); 4969 else if (off < 0) 4970 __skb_push(skb, -off); 4971 4972 skb->mac_header += off; 4973 skb_reset_network_header(skb); 4974 } 4975 4976 /* check if bpf_xdp_adjust_tail was used */ 4977 off = xdp->data_end - orig_data_end; 4978 if (off != 0) { 4979 skb_set_tail_pointer(skb, xdp->data_end - xdp->data); 4980 skb->len += off; /* positive on grow, negative on shrink */ 4981 } 4982 4983 /* XDP frag metadata (e.g. nr_frags) are updated in eBPF helpers 4984 * (e.g. bpf_xdp_adjust_tail), we need to update data_len here. 4985 */ 4986 if (xdp_buff_has_frags(xdp)) 4987 skb->data_len = skb_shinfo(skb)->xdp_frags_size; 4988 else 4989 skb->data_len = 0; 4990 4991 /* check if XDP changed eth hdr such SKB needs update */ 4992 eth = (struct ethhdr *)xdp->data; 4993 if ((orig_eth_type != eth->h_proto) || 4994 (orig_host != ether_addr_equal_64bits(eth->h_dest, 4995 skb->dev->dev_addr)) || 4996 (orig_bcast != is_multicast_ether_addr_64bits(eth->h_dest))) { 4997 __skb_push(skb, ETH_HLEN); 4998 skb->pkt_type = PACKET_HOST; 4999 skb->protocol = eth_type_trans(skb, skb->dev); 5000 } 5001 5002 /* Redirect/Tx gives L2 packet, code that will reuse skb must __skb_pull 5003 * before calling us again on redirect path. We do not call do_redirect 5004 * as we leave that up to the caller. 5005 * 5006 * Caller is responsible for managing lifetime of skb (i.e. calling 5007 * kfree_skb in response to actions it cannot handle/XDP_DROP). 5008 */ 5009 switch (act) { 5010 case XDP_REDIRECT: 5011 case XDP_TX: 5012 __skb_push(skb, mac_len); 5013 break; 5014 case XDP_PASS: 5015 metalen = xdp->data - xdp->data_meta; 5016 if (metalen) 5017 skb_metadata_set(skb, metalen); 5018 break; 5019 } 5020 5021 return act; 5022} 5023 5024static int 5025netif_skb_check_for_xdp(struct sk_buff **pskb, struct bpf_prog *prog) 5026{ 5027 struct sk_buff *skb = *pskb; 5028 int err, hroom, troom; 5029 5030 if (!skb_cow_data_for_xdp(this_cpu_read(system_page_pool), pskb, prog)) 5031 return 0; 5032 5033 /* In case we have to go down the path and also linearize, 5034 * then lets do the pskb_expand_head() work just once here. 5035 */ 5036 hroom = XDP_PACKET_HEADROOM - skb_headroom(skb); 5037 troom = skb->tail + skb->data_len - skb->end; 5038 err = pskb_expand_head(skb, 5039 hroom > 0 ? ALIGN(hroom, NET_SKB_PAD) : 0, 5040 troom > 0 ? troom + 128 : 0, GFP_ATOMIC); 5041 if (err) 5042 return err; 5043 5044 return skb_linearize(skb); 5045} 5046 5047static u32 netif_receive_generic_xdp(struct sk_buff **pskb, 5048 struct xdp_buff *xdp, 5049 struct bpf_prog *xdp_prog) 5050{ 5051 struct sk_buff *skb = *pskb; 5052 u32 mac_len, act = XDP_DROP; 5053 5054 /* Reinjected packets coming from act_mirred or similar should 5055 * not get XDP generic processing. 5056 */ 5057 if (skb_is_redirected(skb)) 5058 return XDP_PASS; 5059 5060 /* XDP packets must have sufficient headroom of XDP_PACKET_HEADROOM 5061 * bytes. This is the guarantee that also native XDP provides, 5062 * thus we need to do it here as well. 5063 */ 5064 mac_len = skb->data - skb_mac_header(skb); 5065 __skb_push(skb, mac_len); 5066 5067 if (skb_cloned(skb) || skb_is_nonlinear(skb) || 5068 skb_headroom(skb) < XDP_PACKET_HEADROOM) { 5069 if (netif_skb_check_for_xdp(pskb, xdp_prog)) 5070 goto do_drop; 5071 } 5072 5073 __skb_pull(*pskb, mac_len); 5074 5075 act = bpf_prog_run_generic_xdp(*pskb, xdp, xdp_prog); 5076 switch (act) { 5077 case XDP_REDIRECT: 5078 case XDP_TX: 5079 case XDP_PASS: 5080 break; 5081 default: 5082 bpf_warn_invalid_xdp_action((*pskb)->dev, xdp_prog, act); 5083 fallthrough; 5084 case XDP_ABORTED: 5085 trace_xdp_exception((*pskb)->dev, xdp_prog, act); 5086 fallthrough; 5087 case XDP_DROP: 5088 do_drop: 5089 kfree_skb(*pskb); 5090 break; 5091 } 5092 5093 return act; 5094} 5095 5096/* When doing generic XDP we have to bypass the qdisc layer and the 5097 * network taps in order to match in-driver-XDP behavior. This also means 5098 * that XDP packets are able to starve other packets going through a qdisc, 5099 * and DDOS attacks will be more effective. In-driver-XDP use dedicated TX 5100 * queues, so they do not have this starvation issue. 5101 */ 5102void generic_xdp_tx(struct sk_buff *skb, struct bpf_prog *xdp_prog) 5103{ 5104 struct net_device *dev = skb->dev; 5105 struct netdev_queue *txq; 5106 bool free_skb = true; 5107 int cpu, rc; 5108 5109 txq = netdev_core_pick_tx(dev, skb, NULL); 5110 cpu = smp_processor_id(); 5111 HARD_TX_LOCK(dev, txq, cpu); 5112 if (!netif_xmit_frozen_or_drv_stopped(txq)) { 5113 rc = netdev_start_xmit(skb, dev, txq, 0); 5114 if (dev_xmit_complete(rc)) 5115 free_skb = false; 5116 } 5117 HARD_TX_UNLOCK(dev, txq); 5118 if (free_skb) { 5119 trace_xdp_exception(dev, xdp_prog, XDP_TX); 5120 dev_core_stats_tx_dropped_inc(dev); 5121 kfree_skb(skb); 5122 } 5123} 5124 5125static DEFINE_STATIC_KEY_FALSE(generic_xdp_needed_key); 5126 5127int do_xdp_generic(struct bpf_prog *xdp_prog, struct sk_buff **pskb) 5128{ 5129 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx; 5130 5131 if (xdp_prog) { 5132 struct xdp_buff xdp; 5133 u32 act; 5134 int err; 5135 5136 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx); 5137 act = netif_receive_generic_xdp(pskb, &xdp, xdp_prog); 5138 if (act != XDP_PASS) { 5139 switch (act) { 5140 case XDP_REDIRECT: 5141 err = xdp_do_generic_redirect((*pskb)->dev, *pskb, 5142 &xdp, xdp_prog); 5143 if (err) 5144 goto out_redir; 5145 break; 5146 case XDP_TX: 5147 generic_xdp_tx(*pskb, xdp_prog); 5148 break; 5149 } 5150 bpf_net_ctx_clear(bpf_net_ctx); 5151 return XDP_DROP; 5152 } 5153 } 5154 return XDP_PASS; 5155out_redir: 5156 bpf_net_ctx_clear(bpf_net_ctx); 5157 kfree_skb_reason(*pskb, SKB_DROP_REASON_XDP); 5158 return XDP_DROP; 5159} 5160EXPORT_SYMBOL_GPL(do_xdp_generic); 5161 5162static int netif_rx_internal(struct sk_buff *skb) 5163{ 5164 int ret; 5165 5166 net_timestamp_check(READ_ONCE(net_hotdata.tstamp_prequeue), skb); 5167 5168 trace_netif_rx(skb); 5169 5170#ifdef CONFIG_RPS 5171 if (static_branch_unlikely(&rps_needed)) { 5172 struct rps_dev_flow voidflow, *rflow = &voidflow; 5173 int cpu; 5174 5175 rcu_read_lock(); 5176 5177 cpu = get_rps_cpu(skb->dev, skb, &rflow); 5178 if (cpu < 0) 5179 cpu = smp_processor_id(); 5180 5181 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail); 5182 5183 rcu_read_unlock(); 5184 } else 5185#endif 5186 { 5187 unsigned int qtail; 5188 5189 ret = enqueue_to_backlog(skb, smp_processor_id(), &qtail); 5190 } 5191 return ret; 5192} 5193 5194/** 5195 * __netif_rx - Slightly optimized version of netif_rx 5196 * @skb: buffer to post 5197 * 5198 * This behaves as netif_rx except that it does not disable bottom halves. 5199 * As a result this function may only be invoked from the interrupt context 5200 * (either hard or soft interrupt). 5201 */ 5202int __netif_rx(struct sk_buff *skb) 5203{ 5204 int ret; 5205 5206 lockdep_assert_once(hardirq_count() | softirq_count()); 5207 5208 trace_netif_rx_entry(skb); 5209 ret = netif_rx_internal(skb); 5210 trace_netif_rx_exit(ret); 5211 return ret; 5212} 5213EXPORT_SYMBOL(__netif_rx); 5214 5215/** 5216 * netif_rx - post buffer to the network code 5217 * @skb: buffer to post 5218 * 5219 * This function receives a packet from a device driver and queues it for 5220 * the upper (protocol) levels to process via the backlog NAPI device. It 5221 * always succeeds. The buffer may be dropped during processing for 5222 * congestion control or by the protocol layers. 5223 * The network buffer is passed via the backlog NAPI device. Modern NIC 5224 * driver should use NAPI and GRO. 5225 * This function can used from interrupt and from process context. The 5226 * caller from process context must not disable interrupts before invoking 5227 * this function. 5228 * 5229 * return values: 5230 * NET_RX_SUCCESS (no congestion) 5231 * NET_RX_DROP (packet was dropped) 5232 * 5233 */ 5234int netif_rx(struct sk_buff *skb) 5235{ 5236 bool need_bh_off = !(hardirq_count() | softirq_count()); 5237 int ret; 5238 5239 if (need_bh_off) 5240 local_bh_disable(); 5241 trace_netif_rx_entry(skb); 5242 ret = netif_rx_internal(skb); 5243 trace_netif_rx_exit(ret); 5244 if (need_bh_off) 5245 local_bh_enable(); 5246 return ret; 5247} 5248EXPORT_SYMBOL(netif_rx); 5249 5250static __latent_entropy void net_tx_action(struct softirq_action *h) 5251{ 5252 struct softnet_data *sd = this_cpu_ptr(&softnet_data); 5253 5254 if (sd->completion_queue) { 5255 struct sk_buff *clist; 5256 5257 local_irq_disable(); 5258 clist = sd->completion_queue; 5259 sd->completion_queue = NULL; 5260 local_irq_enable(); 5261 5262 while (clist) { 5263 struct sk_buff *skb = clist; 5264 5265 clist = clist->next; 5266 5267 WARN_ON(refcount_read(&skb->users)); 5268 if (likely(get_kfree_skb_cb(skb)->reason == SKB_CONSUMED)) 5269 trace_consume_skb(skb, net_tx_action); 5270 else 5271 trace_kfree_skb(skb, net_tx_action, 5272 get_kfree_skb_cb(skb)->reason, NULL); 5273 5274 if (skb->fclone != SKB_FCLONE_UNAVAILABLE) 5275 __kfree_skb(skb); 5276 else 5277 __napi_kfree_skb(skb, 5278 get_kfree_skb_cb(skb)->reason); 5279 } 5280 } 5281 5282 if (sd->output_queue) { 5283 struct Qdisc *head; 5284 5285 local_irq_disable(); 5286 head = sd->output_queue; 5287 sd->output_queue = NULL; 5288 sd->output_queue_tailp = &sd->output_queue; 5289 local_irq_enable(); 5290 5291 rcu_read_lock(); 5292 5293 while (head) { 5294 struct Qdisc *q = head; 5295 spinlock_t *root_lock = NULL; 5296 5297 head = head->next_sched; 5298 5299 /* We need to make sure head->next_sched is read 5300 * before clearing __QDISC_STATE_SCHED 5301 */ 5302 smp_mb__before_atomic(); 5303 5304 if (!(q->flags & TCQ_F_NOLOCK)) { 5305 root_lock = qdisc_lock(q); 5306 spin_lock(root_lock); 5307 } else if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, 5308 &q->state))) { 5309 /* There is a synchronize_net() between 5310 * STATE_DEACTIVATED flag being set and 5311 * qdisc_reset()/some_qdisc_is_busy() in 5312 * dev_deactivate(), so we can safely bail out 5313 * early here to avoid data race between 5314 * qdisc_deactivate() and some_qdisc_is_busy() 5315 * for lockless qdisc. 5316 */ 5317 clear_bit(__QDISC_STATE_SCHED, &q->state); 5318 continue; 5319 } 5320 5321 clear_bit(__QDISC_STATE_SCHED, &q->state); 5322 qdisc_run(q); 5323 if (root_lock) 5324 spin_unlock(root_lock); 5325 } 5326 5327 rcu_read_unlock(); 5328 } 5329 5330 xfrm_dev_backlog(sd); 5331} 5332 5333#if IS_ENABLED(CONFIG_BRIDGE) && IS_ENABLED(CONFIG_ATM_LANE) 5334/* This hook is defined here for ATM LANE */ 5335int (*br_fdb_test_addr_hook)(struct net_device *dev, 5336 unsigned char *addr) __read_mostly; 5337EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook); 5338#endif 5339 5340/** 5341 * netdev_is_rx_handler_busy - check if receive handler is registered 5342 * @dev: device to check 5343 * 5344 * Check if a receive handler is already registered for a given device. 5345 * Return true if there one. 5346 * 5347 * The caller must hold the rtnl_mutex. 5348 */ 5349bool netdev_is_rx_handler_busy(struct net_device *dev) 5350{ 5351 ASSERT_RTNL(); 5352 return dev && rtnl_dereference(dev->rx_handler); 5353} 5354EXPORT_SYMBOL_GPL(netdev_is_rx_handler_busy); 5355 5356/** 5357 * netdev_rx_handler_register - register receive handler 5358 * @dev: device to register a handler for 5359 * @rx_handler: receive handler to register 5360 * @rx_handler_data: data pointer that is used by rx handler 5361 * 5362 * Register a receive handler for a device. This handler will then be 5363 * called from __netif_receive_skb. A negative errno code is returned 5364 * on a failure. 5365 * 5366 * The caller must hold the rtnl_mutex. 5367 * 5368 * For a general description of rx_handler, see enum rx_handler_result. 5369 */ 5370int netdev_rx_handler_register(struct net_device *dev, 5371 rx_handler_func_t *rx_handler, 5372 void *rx_handler_data) 5373{ 5374 if (netdev_is_rx_handler_busy(dev)) 5375 return -EBUSY; 5376 5377 if (dev->priv_flags & IFF_NO_RX_HANDLER) 5378 return -EINVAL; 5379 5380 /* Note: rx_handler_data must be set before rx_handler */ 5381 rcu_assign_pointer(dev->rx_handler_data, rx_handler_data); 5382 rcu_assign_pointer(dev->rx_handler, rx_handler); 5383 5384 return 0; 5385} 5386EXPORT_SYMBOL_GPL(netdev_rx_handler_register); 5387 5388/** 5389 * netdev_rx_handler_unregister - unregister receive handler 5390 * @dev: device to unregister a handler from 5391 * 5392 * Unregister a receive handler from a device. 5393 * 5394 * The caller must hold the rtnl_mutex. 5395 */ 5396void netdev_rx_handler_unregister(struct net_device *dev) 5397{ 5398 5399 ASSERT_RTNL(); 5400 RCU_INIT_POINTER(dev->rx_handler, NULL); 5401 /* a reader seeing a non NULL rx_handler in a rcu_read_lock() 5402 * section has a guarantee to see a non NULL rx_handler_data 5403 * as well. 5404 */ 5405 synchronize_net(); 5406 RCU_INIT_POINTER(dev->rx_handler_data, NULL); 5407} 5408EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister); 5409 5410/* 5411 * Limit the use of PFMEMALLOC reserves to those protocols that implement 5412 * the special handling of PFMEMALLOC skbs. 5413 */ 5414static bool skb_pfmemalloc_protocol(struct sk_buff *skb) 5415{ 5416 switch (skb->protocol) { 5417 case htons(ETH_P_ARP): 5418 case htons(ETH_P_IP): 5419 case htons(ETH_P_IPV6): 5420 case htons(ETH_P_8021Q): 5421 case htons(ETH_P_8021AD): 5422 return true; 5423 default: 5424 return false; 5425 } 5426} 5427 5428static inline int nf_ingress(struct sk_buff *skb, struct packet_type **pt_prev, 5429 int *ret, struct net_device *orig_dev) 5430{ 5431 if (nf_hook_ingress_active(skb)) { 5432 int ingress_retval; 5433 5434 if (*pt_prev) { 5435 *ret = deliver_skb(skb, *pt_prev, orig_dev); 5436 *pt_prev = NULL; 5437 } 5438 5439 rcu_read_lock(); 5440 ingress_retval = nf_hook_ingress(skb); 5441 rcu_read_unlock(); 5442 return ingress_retval; 5443 } 5444 return 0; 5445} 5446 5447static int __netif_receive_skb_core(struct sk_buff **pskb, bool pfmemalloc, 5448 struct packet_type **ppt_prev) 5449{ 5450 struct packet_type *ptype, *pt_prev; 5451 rx_handler_func_t *rx_handler; 5452 struct sk_buff *skb = *pskb; 5453 struct net_device *orig_dev; 5454 bool deliver_exact = false; 5455 int ret = NET_RX_DROP; 5456 __be16 type; 5457 5458 net_timestamp_check(!READ_ONCE(net_hotdata.tstamp_prequeue), skb); 5459 5460 trace_netif_receive_skb(skb); 5461 5462 orig_dev = skb->dev; 5463 5464 skb_reset_network_header(skb); 5465 if (!skb_transport_header_was_set(skb)) 5466 skb_reset_transport_header(skb); 5467 skb_reset_mac_len(skb); 5468 5469 pt_prev = NULL; 5470 5471another_round: 5472 skb->skb_iif = skb->dev->ifindex; 5473 5474 __this_cpu_inc(softnet_data.processed); 5475 5476 if (static_branch_unlikely(&generic_xdp_needed_key)) { 5477 int ret2; 5478 5479 migrate_disable(); 5480 ret2 = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog), 5481 &skb); 5482 migrate_enable(); 5483 5484 if (ret2 != XDP_PASS) { 5485 ret = NET_RX_DROP; 5486 goto out; 5487 } 5488 } 5489 5490 if (eth_type_vlan(skb->protocol)) { 5491 skb = skb_vlan_untag(skb); 5492 if (unlikely(!skb)) 5493 goto out; 5494 } 5495 5496 if (skb_skip_tc_classify(skb)) 5497 goto skip_classify; 5498 5499 if (pfmemalloc) 5500 goto skip_taps; 5501 5502 list_for_each_entry_rcu(ptype, &net_hotdata.ptype_all, list) { 5503 if (pt_prev) 5504 ret = deliver_skb(skb, pt_prev, orig_dev); 5505 pt_prev = ptype; 5506 } 5507 5508 list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) { 5509 if (pt_prev) 5510 ret = deliver_skb(skb, pt_prev, orig_dev); 5511 pt_prev = ptype; 5512 } 5513 5514skip_taps: 5515#ifdef CONFIG_NET_INGRESS 5516 if (static_branch_unlikely(&ingress_needed_key)) { 5517 bool another = false; 5518 5519 nf_skip_egress(skb, true); 5520 skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev, 5521 &another); 5522 if (another) 5523 goto another_round; 5524 if (!skb) 5525 goto out; 5526 5527 nf_skip_egress(skb, false); 5528 if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0) 5529 goto out; 5530 } 5531#endif 5532 skb_reset_redirect(skb); 5533skip_classify: 5534 if (pfmemalloc && !skb_pfmemalloc_protocol(skb)) 5535 goto drop; 5536 5537 if (skb_vlan_tag_present(skb)) { 5538 if (pt_prev) { 5539 ret = deliver_skb(skb, pt_prev, orig_dev); 5540 pt_prev = NULL; 5541 } 5542 if (vlan_do_receive(&skb)) 5543 goto another_round; 5544 else if (unlikely(!skb)) 5545 goto out; 5546 } 5547 5548 rx_handler = rcu_dereference(skb->dev->rx_handler); 5549 if (rx_handler) { 5550 if (pt_prev) { 5551 ret = deliver_skb(skb, pt_prev, orig_dev); 5552 pt_prev = NULL; 5553 } 5554 switch (rx_handler(&skb)) { 5555 case RX_HANDLER_CONSUMED: 5556 ret = NET_RX_SUCCESS; 5557 goto out; 5558 case RX_HANDLER_ANOTHER: 5559 goto another_round; 5560 case RX_HANDLER_EXACT: 5561 deliver_exact = true; 5562 break; 5563 case RX_HANDLER_PASS: 5564 break; 5565 default: 5566 BUG(); 5567 } 5568 } 5569 5570 if (unlikely(skb_vlan_tag_present(skb)) && !netdev_uses_dsa(skb->dev)) { 5571check_vlan_id: 5572 if (skb_vlan_tag_get_id(skb)) { 5573 /* Vlan id is non 0 and vlan_do_receive() above couldn't 5574 * find vlan device. 5575 */ 5576 skb->pkt_type = PACKET_OTHERHOST; 5577 } else if (eth_type_vlan(skb->protocol)) { 5578 /* Outer header is 802.1P with vlan 0, inner header is 5579 * 802.1Q or 802.1AD and vlan_do_receive() above could 5580 * not find vlan dev for vlan id 0. 5581 */ 5582 __vlan_hwaccel_clear_tag(skb); 5583 skb = skb_vlan_untag(skb); 5584 if (unlikely(!skb)) 5585 goto out; 5586 if (vlan_do_receive(&skb)) 5587 /* After stripping off 802.1P header with vlan 0 5588 * vlan dev is found for inner header. 5589 */ 5590 goto another_round; 5591 else if (unlikely(!skb)) 5592 goto out; 5593 else 5594 /* We have stripped outer 802.1P vlan 0 header. 5595 * But could not find vlan dev. 5596 * check again for vlan id to set OTHERHOST. 5597 */ 5598 goto check_vlan_id; 5599 } 5600 /* Note: we might in the future use prio bits 5601 * and set skb->priority like in vlan_do_receive() 5602 * For the time being, just ignore Priority Code Point 5603 */ 5604 __vlan_hwaccel_clear_tag(skb); 5605 } 5606 5607 type = skb->protocol; 5608 5609 /* deliver only exact match when indicated */ 5610 if (likely(!deliver_exact)) { 5611 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type, 5612 &ptype_base[ntohs(type) & 5613 PTYPE_HASH_MASK]); 5614 } 5615 5616 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type, 5617 &orig_dev->ptype_specific); 5618 5619 if (unlikely(skb->dev != orig_dev)) { 5620 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type, 5621 &skb->dev->ptype_specific); 5622 } 5623 5624 if (pt_prev) { 5625 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC))) 5626 goto drop; 5627 *ppt_prev = pt_prev; 5628 } else { 5629drop: 5630 if (!deliver_exact) 5631 dev_core_stats_rx_dropped_inc(skb->dev); 5632 else 5633 dev_core_stats_rx_nohandler_inc(skb->dev); 5634 kfree_skb_reason(skb, SKB_DROP_REASON_UNHANDLED_PROTO); 5635 /* Jamal, now you will not able to escape explaining 5636 * me how you were going to use this. :-) 5637 */ 5638 ret = NET_RX_DROP; 5639 } 5640 5641out: 5642 /* The invariant here is that if *ppt_prev is not NULL 5643 * then skb should also be non-NULL. 5644 * 5645 * Apparently *ppt_prev assignment above holds this invariant due to 5646 * skb dereferencing near it. 5647 */ 5648 *pskb = skb; 5649 return ret; 5650} 5651 5652static int __netif_receive_skb_one_core(struct sk_buff *skb, bool pfmemalloc) 5653{ 5654 struct net_device *orig_dev = skb->dev; 5655 struct packet_type *pt_prev = NULL; 5656 int ret; 5657 5658 ret = __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev); 5659 if (pt_prev) 5660 ret = INDIRECT_CALL_INET(pt_prev->func, ipv6_rcv, ip_rcv, skb, 5661 skb->dev, pt_prev, orig_dev); 5662 return ret; 5663} 5664 5665/** 5666 * netif_receive_skb_core - special purpose version of netif_receive_skb 5667 * @skb: buffer to process 5668 * 5669 * More direct receive version of netif_receive_skb(). It should 5670 * only be used by callers that have a need to skip RPS and Generic XDP. 5671 * Caller must also take care of handling if ``(page_is_)pfmemalloc``. 5672 * 5673 * This function may only be called from softirq context and interrupts 5674 * should be enabled. 5675 * 5676 * Return values (usually ignored): 5677 * NET_RX_SUCCESS: no congestion 5678 * NET_RX_DROP: packet was dropped 5679 */ 5680int netif_receive_skb_core(struct sk_buff *skb) 5681{ 5682 int ret; 5683 5684 rcu_read_lock(); 5685 ret = __netif_receive_skb_one_core(skb, false); 5686 rcu_read_unlock(); 5687 5688 return ret; 5689} 5690EXPORT_SYMBOL(netif_receive_skb_core); 5691 5692static inline void __netif_receive_skb_list_ptype(struct list_head *head, 5693 struct packet_type *pt_prev, 5694 struct net_device *orig_dev) 5695{ 5696 struct sk_buff *skb, *next; 5697 5698 if (!pt_prev) 5699 return; 5700 if (list_empty(head)) 5701 return; 5702 if (pt_prev->list_func != NULL) 5703 INDIRECT_CALL_INET(pt_prev->list_func, ipv6_list_rcv, 5704 ip_list_rcv, head, pt_prev, orig_dev); 5705 else 5706 list_for_each_entry_safe(skb, next, head, list) { 5707 skb_list_del_init(skb); 5708 pt_prev->func(skb, skb->dev, pt_prev, orig_dev); 5709 } 5710} 5711 5712static void __netif_receive_skb_list_core(struct list_head *head, bool pfmemalloc) 5713{ 5714 /* Fast-path assumptions: 5715 * - There is no RX handler. 5716 * - Only one packet_type matches. 5717 * If either of these fails, we will end up doing some per-packet 5718 * processing in-line, then handling the 'last ptype' for the whole 5719 * sublist. This can't cause out-of-order delivery to any single ptype, 5720 * because the 'last ptype' must be constant across the sublist, and all 5721 * other ptypes are handled per-packet. 5722 */ 5723 /* Current (common) ptype of sublist */ 5724 struct packet_type *pt_curr = NULL; 5725 /* Current (common) orig_dev of sublist */ 5726 struct net_device *od_curr = NULL; 5727 struct list_head sublist; 5728 struct sk_buff *skb, *next; 5729 5730 INIT_LIST_HEAD(&sublist); 5731 list_for_each_entry_safe(skb, next, head, list) { 5732 struct net_device *orig_dev = skb->dev; 5733 struct packet_type *pt_prev = NULL; 5734 5735 skb_list_del_init(skb); 5736 __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev); 5737 if (!pt_prev) 5738 continue; 5739 if (pt_curr != pt_prev || od_curr != orig_dev) { 5740 /* dispatch old sublist */ 5741 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr); 5742 /* start new sublist */ 5743 INIT_LIST_HEAD(&sublist); 5744 pt_curr = pt_prev; 5745 od_curr = orig_dev; 5746 } 5747 list_add_tail(&skb->list, &sublist); 5748 } 5749 5750 /* dispatch final sublist */ 5751 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr); 5752} 5753 5754static int __netif_receive_skb(struct sk_buff *skb) 5755{ 5756 int ret; 5757 5758 if (sk_memalloc_socks() && skb_pfmemalloc(skb)) { 5759 unsigned int noreclaim_flag; 5760 5761 /* 5762 * PFMEMALLOC skbs are special, they should 5763 * - be delivered to SOCK_MEMALLOC sockets only 5764 * - stay away from userspace 5765 * - have bounded memory usage 5766 * 5767 * Use PF_MEMALLOC as this saves us from propagating the allocation 5768 * context down to all allocation sites. 5769 */ 5770 noreclaim_flag = memalloc_noreclaim_save(); 5771 ret = __netif_receive_skb_one_core(skb, true); 5772 memalloc_noreclaim_restore(noreclaim_flag); 5773 } else 5774 ret = __netif_receive_skb_one_core(skb, false); 5775 5776 return ret; 5777} 5778 5779static void __netif_receive_skb_list(struct list_head *head) 5780{ 5781 unsigned long noreclaim_flag = 0; 5782 struct sk_buff *skb, *next; 5783 bool pfmemalloc = false; /* Is current sublist PF_MEMALLOC? */ 5784 5785 list_for_each_entry_safe(skb, next, head, list) { 5786 if ((sk_memalloc_socks() && skb_pfmemalloc(skb)) != pfmemalloc) { 5787 struct list_head sublist; 5788 5789 /* Handle the previous sublist */ 5790 list_cut_before(&sublist, head, &skb->list); 5791 if (!list_empty(&sublist)) 5792 __netif_receive_skb_list_core(&sublist, pfmemalloc); 5793 pfmemalloc = !pfmemalloc; 5794 /* See comments in __netif_receive_skb */ 5795 if (pfmemalloc) 5796 noreclaim_flag = memalloc_noreclaim_save(); 5797 else 5798 memalloc_noreclaim_restore(noreclaim_flag); 5799 } 5800 } 5801 /* Handle the remaining sublist */ 5802 if (!list_empty(head)) 5803 __netif_receive_skb_list_core(head, pfmemalloc); 5804 /* Restore pflags */ 5805 if (pfmemalloc) 5806 memalloc_noreclaim_restore(noreclaim_flag); 5807} 5808 5809static int generic_xdp_install(struct net_device *dev, struct netdev_bpf *xdp) 5810{ 5811 struct bpf_prog *old = rtnl_dereference(dev->xdp_prog); 5812 struct bpf_prog *new = xdp->prog; 5813 int ret = 0; 5814 5815 switch (xdp->command) { 5816 case XDP_SETUP_PROG: 5817 rcu_assign_pointer(dev->xdp_prog, new); 5818 if (old) 5819 bpf_prog_put(old); 5820 5821 if (old && !new) { 5822 static_branch_dec(&generic_xdp_needed_key); 5823 } else if (new && !old) { 5824 static_branch_inc(&generic_xdp_needed_key); 5825 dev_disable_lro(dev); 5826 dev_disable_gro_hw(dev); 5827 } 5828 break; 5829 5830 default: 5831 ret = -EINVAL; 5832 break; 5833 } 5834 5835 return ret; 5836} 5837 5838static int netif_receive_skb_internal(struct sk_buff *skb) 5839{ 5840 int ret; 5841 5842 net_timestamp_check(READ_ONCE(net_hotdata.tstamp_prequeue), skb); 5843 5844 if (skb_defer_rx_timestamp(skb)) 5845 return NET_RX_SUCCESS; 5846 5847 rcu_read_lock(); 5848#ifdef CONFIG_RPS 5849 if (static_branch_unlikely(&rps_needed)) { 5850 struct rps_dev_flow voidflow, *rflow = &voidflow; 5851 int cpu = get_rps_cpu(skb->dev, skb, &rflow); 5852 5853 if (cpu >= 0) { 5854 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail); 5855 rcu_read_unlock(); 5856 return ret; 5857 } 5858 } 5859#endif 5860 ret = __netif_receive_skb(skb); 5861 rcu_read_unlock(); 5862 return ret; 5863} 5864 5865void netif_receive_skb_list_internal(struct list_head *head) 5866{ 5867 struct sk_buff *skb, *next; 5868 struct list_head sublist; 5869 5870 INIT_LIST_HEAD(&sublist); 5871 list_for_each_entry_safe(skb, next, head, list) { 5872 net_timestamp_check(READ_ONCE(net_hotdata.tstamp_prequeue), 5873 skb); 5874 skb_list_del_init(skb); 5875 if (!skb_defer_rx_timestamp(skb)) 5876 list_add_tail(&skb->list, &sublist); 5877 } 5878 list_splice_init(&sublist, head); 5879 5880 rcu_read_lock(); 5881#ifdef CONFIG_RPS 5882 if (static_branch_unlikely(&rps_needed)) { 5883 list_for_each_entry_safe(skb, next, head, list) { 5884 struct rps_dev_flow voidflow, *rflow = &voidflow; 5885 int cpu = get_rps_cpu(skb->dev, skb, &rflow); 5886 5887 if (cpu >= 0) { 5888 /* Will be handled, remove from list */ 5889 skb_list_del_init(skb); 5890 enqueue_to_backlog(skb, cpu, &rflow->last_qtail); 5891 } 5892 } 5893 } 5894#endif 5895 __netif_receive_skb_list(head); 5896 rcu_read_unlock(); 5897} 5898 5899/** 5900 * netif_receive_skb - process receive buffer from network 5901 * @skb: buffer to process 5902 * 5903 * netif_receive_skb() is the main receive data processing function. 5904 * It always succeeds. The buffer may be dropped during processing 5905 * for congestion control or by the protocol layers. 5906 * 5907 * This function may only be called from softirq context and interrupts 5908 * should be enabled. 5909 * 5910 * Return values (usually ignored): 5911 * NET_RX_SUCCESS: no congestion 5912 * NET_RX_DROP: packet was dropped 5913 */ 5914int netif_receive_skb(struct sk_buff *skb) 5915{ 5916 int ret; 5917 5918 trace_netif_receive_skb_entry(skb); 5919 5920 ret = netif_receive_skb_internal(skb); 5921 trace_netif_receive_skb_exit(ret); 5922 5923 return ret; 5924} 5925EXPORT_SYMBOL(netif_receive_skb); 5926 5927/** 5928 * netif_receive_skb_list - process many receive buffers from network 5929 * @head: list of skbs to process. 5930 * 5931 * Since return value of netif_receive_skb() is normally ignored, and 5932 * wouldn't be meaningful for a list, this function returns void. 5933 * 5934 * This function may only be called from softirq context and interrupts 5935 * should be enabled. 5936 */ 5937void netif_receive_skb_list(struct list_head *head) 5938{ 5939 struct sk_buff *skb; 5940 5941 if (list_empty(head)) 5942 return; 5943 if (trace_netif_receive_skb_list_entry_enabled()) { 5944 list_for_each_entry(skb, head, list) 5945 trace_netif_receive_skb_list_entry(skb); 5946 } 5947 netif_receive_skb_list_internal(head); 5948 trace_netif_receive_skb_list_exit(0); 5949} 5950EXPORT_SYMBOL(netif_receive_skb_list); 5951 5952static DEFINE_PER_CPU(struct work_struct, flush_works); 5953 5954/* Network device is going away, flush any packets still pending */ 5955static void flush_backlog(struct work_struct *work) 5956{ 5957 struct sk_buff *skb, *tmp; 5958 struct softnet_data *sd; 5959 5960 local_bh_disable(); 5961 sd = this_cpu_ptr(&softnet_data); 5962 5963 backlog_lock_irq_disable(sd); 5964 skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) { 5965 if (skb->dev->reg_state == NETREG_UNREGISTERING) { 5966 __skb_unlink(skb, &sd->input_pkt_queue); 5967 dev_kfree_skb_irq(skb); 5968 rps_input_queue_head_incr(sd); 5969 } 5970 } 5971 backlog_unlock_irq_enable(sd); 5972 5973 local_lock_nested_bh(&softnet_data.process_queue_bh_lock); 5974 skb_queue_walk_safe(&sd->process_queue, skb, tmp) { 5975 if (skb->dev->reg_state == NETREG_UNREGISTERING) { 5976 __skb_unlink(skb, &sd->process_queue); 5977 kfree_skb(skb); 5978 rps_input_queue_head_incr(sd); 5979 } 5980 } 5981 local_unlock_nested_bh(&softnet_data.process_queue_bh_lock); 5982 local_bh_enable(); 5983} 5984 5985static bool flush_required(int cpu) 5986{ 5987#if IS_ENABLED(CONFIG_RPS) 5988 struct softnet_data *sd = &per_cpu(softnet_data, cpu); 5989 bool do_flush; 5990 5991 backlog_lock_irq_disable(sd); 5992 5993 /* as insertion into process_queue happens with the rps lock held, 5994 * process_queue access may race only with dequeue 5995 */ 5996 do_flush = !skb_queue_empty(&sd->input_pkt_queue) || 5997 !skb_queue_empty_lockless(&sd->process_queue); 5998 backlog_unlock_irq_enable(sd); 5999 6000 return do_flush; 6001#endif 6002 /* without RPS we can't safely check input_pkt_queue: during a 6003 * concurrent remote skb_queue_splice() we can detect as empty both 6004 * input_pkt_queue and process_queue even if the latter could end-up 6005 * containing a lot of packets. 6006 */ 6007 return true; 6008} 6009 6010static void flush_all_backlogs(void) 6011{ 6012 static cpumask_t flush_cpus; 6013 unsigned int cpu; 6014 6015 /* since we are under rtnl lock protection we can use static data 6016 * for the cpumask and avoid allocating on stack the possibly 6017 * large mask 6018 */ 6019 ASSERT_RTNL(); 6020 6021 cpus_read_lock(); 6022 6023 cpumask_clear(&flush_cpus); 6024 for_each_online_cpu(cpu) { 6025 if (flush_required(cpu)) { 6026 queue_work_on(cpu, system_highpri_wq, 6027 per_cpu_ptr(&flush_works, cpu)); 6028 cpumask_set_cpu(cpu, &flush_cpus); 6029 } 6030 } 6031 6032 /* we can have in flight packet[s] on the cpus we are not flushing, 6033 * synchronize_net() in unregister_netdevice_many() will take care of 6034 * them 6035 */ 6036 for_each_cpu(cpu, &flush_cpus) 6037 flush_work(per_cpu_ptr(&flush_works, cpu)); 6038 6039 cpus_read_unlock(); 6040} 6041 6042static void net_rps_send_ipi(struct softnet_data *remsd) 6043{ 6044#ifdef CONFIG_RPS 6045 while (remsd) { 6046 struct softnet_data *next = remsd->rps_ipi_next; 6047 6048 if (cpu_online(remsd->cpu)) 6049 smp_call_function_single_async(remsd->cpu, &remsd->csd); 6050 remsd = next; 6051 } 6052#endif 6053} 6054 6055/* 6056 * net_rps_action_and_irq_enable sends any pending IPI's for rps. 6057 * Note: called with local irq disabled, but exits with local irq enabled. 6058 */ 6059static void net_rps_action_and_irq_enable(struct softnet_data *sd) 6060{ 6061#ifdef CONFIG_RPS 6062 struct softnet_data *remsd = sd->rps_ipi_list; 6063 6064 if (!use_backlog_threads() && remsd) { 6065 sd->rps_ipi_list = NULL; 6066 6067 local_irq_enable(); 6068 6069 /* Send pending IPI's to kick RPS processing on remote cpus. */ 6070 net_rps_send_ipi(remsd); 6071 } else 6072#endif 6073 local_irq_enable(); 6074} 6075 6076static bool sd_has_rps_ipi_waiting(struct softnet_data *sd) 6077{ 6078#ifdef CONFIG_RPS 6079 return !use_backlog_threads() && sd->rps_ipi_list; 6080#else 6081 return false; 6082#endif 6083} 6084 6085static int process_backlog(struct napi_struct *napi, int quota) 6086{ 6087 struct softnet_data *sd = container_of(napi, struct softnet_data, backlog); 6088 bool again = true; 6089 int work = 0; 6090 6091 /* Check if we have pending ipi, its better to send them now, 6092 * not waiting net_rx_action() end. 6093 */ 6094 if (sd_has_rps_ipi_waiting(sd)) { 6095 local_irq_disable(); 6096 net_rps_action_and_irq_enable(sd); 6097 } 6098 6099 napi->weight = READ_ONCE(net_hotdata.dev_rx_weight); 6100 while (again) { 6101 struct sk_buff *skb; 6102 6103 local_lock_nested_bh(&softnet_data.process_queue_bh_lock); 6104 while ((skb = __skb_dequeue(&sd->process_queue))) { 6105 local_unlock_nested_bh(&softnet_data.process_queue_bh_lock); 6106 rcu_read_lock(); 6107 __netif_receive_skb(skb); 6108 rcu_read_unlock(); 6109 if (++work >= quota) { 6110 rps_input_queue_head_add(sd, work); 6111 return work; 6112 } 6113 6114 local_lock_nested_bh(&softnet_data.process_queue_bh_lock); 6115 } 6116 local_unlock_nested_bh(&softnet_data.process_queue_bh_lock); 6117 6118 backlog_lock_irq_disable(sd); 6119 if (skb_queue_empty(&sd->input_pkt_queue)) { 6120 /* 6121 * Inline a custom version of __napi_complete(). 6122 * only current cpu owns and manipulates this napi, 6123 * and NAPI_STATE_SCHED is the only possible flag set 6124 * on backlog. 6125 * We can use a plain write instead of clear_bit(), 6126 * and we dont need an smp_mb() memory barrier. 6127 */ 6128 napi->state &= NAPIF_STATE_THREADED; 6129 again = false; 6130 } else { 6131 local_lock_nested_bh(&softnet_data.process_queue_bh_lock); 6132 skb_queue_splice_tail_init(&sd->input_pkt_queue, 6133 &sd->process_queue); 6134 local_unlock_nested_bh(&softnet_data.process_queue_bh_lock); 6135 } 6136 backlog_unlock_irq_enable(sd); 6137 } 6138 6139 if (work) 6140 rps_input_queue_head_add(sd, work); 6141 return work; 6142} 6143 6144/** 6145 * __napi_schedule - schedule for receive 6146 * @n: entry to schedule 6147 * 6148 * The entry's receive function will be scheduled to run. 6149 * Consider using __napi_schedule_irqoff() if hard irqs are masked. 6150 */ 6151void __napi_schedule(struct napi_struct *n) 6152{ 6153 unsigned long flags; 6154 6155 local_irq_save(flags); 6156 ____napi_schedule(this_cpu_ptr(&softnet_data), n); 6157 local_irq_restore(flags); 6158} 6159EXPORT_SYMBOL(__napi_schedule); 6160 6161/** 6162 * napi_schedule_prep - check if napi can be scheduled 6163 * @n: napi context 6164 * 6165 * Test if NAPI routine is already running, and if not mark 6166 * it as running. This is used as a condition variable to 6167 * insure only one NAPI poll instance runs. We also make 6168 * sure there is no pending NAPI disable. 6169 */ 6170bool napi_schedule_prep(struct napi_struct *n) 6171{ 6172 unsigned long new, val = READ_ONCE(n->state); 6173 6174 do { 6175 if (unlikely(val & NAPIF_STATE_DISABLE)) 6176 return false; 6177 new = val | NAPIF_STATE_SCHED; 6178 6179 /* Sets STATE_MISSED bit if STATE_SCHED was already set 6180 * This was suggested by Alexander Duyck, as compiler 6181 * emits better code than : 6182 * if (val & NAPIF_STATE_SCHED) 6183 * new |= NAPIF_STATE_MISSED; 6184 */ 6185 new |= (val & NAPIF_STATE_SCHED) / NAPIF_STATE_SCHED * 6186 NAPIF_STATE_MISSED; 6187 } while (!try_cmpxchg(&n->state, &val, new)); 6188 6189 return !(val & NAPIF_STATE_SCHED); 6190} 6191EXPORT_SYMBOL(napi_schedule_prep); 6192 6193/** 6194 * __napi_schedule_irqoff - schedule for receive 6195 * @n: entry to schedule 6196 * 6197 * Variant of __napi_schedule() assuming hard irqs are masked. 6198 * 6199 * On PREEMPT_RT enabled kernels this maps to __napi_schedule() 6200 * because the interrupt disabled assumption might not be true 6201 * due to force-threaded interrupts and spinlock substitution. 6202 */ 6203void __napi_schedule_irqoff(struct napi_struct *n) 6204{ 6205 if (!IS_ENABLED(CONFIG_PREEMPT_RT)) 6206 ____napi_schedule(this_cpu_ptr(&softnet_data), n); 6207 else 6208 __napi_schedule(n); 6209} 6210EXPORT_SYMBOL(__napi_schedule_irqoff); 6211 6212bool napi_complete_done(struct napi_struct *n, int work_done) 6213{ 6214 unsigned long flags, val, new, timeout = 0; 6215 bool ret = true; 6216 6217 /* 6218 * 1) Don't let napi dequeue from the cpu poll list 6219 * just in case its running on a different cpu. 6220 * 2) If we are busy polling, do nothing here, we have 6221 * the guarantee we will be called later. 6222 */ 6223 if (unlikely(n->state & (NAPIF_STATE_NPSVC | 6224 NAPIF_STATE_IN_BUSY_POLL))) 6225 return false; 6226 6227 if (work_done) { 6228 if (n->gro_bitmask) 6229 timeout = READ_ONCE(n->dev->gro_flush_timeout); 6230 n->defer_hard_irqs_count = READ_ONCE(n->dev->napi_defer_hard_irqs); 6231 } 6232 if (n->defer_hard_irqs_count > 0) { 6233 n->defer_hard_irqs_count--; 6234 timeout = READ_ONCE(n->dev->gro_flush_timeout); 6235 if (timeout) 6236 ret = false; 6237 } 6238 if (n->gro_bitmask) { 6239 /* When the NAPI instance uses a timeout and keeps postponing 6240 * it, we need to bound somehow the time packets are kept in 6241 * the GRO layer 6242 */ 6243 napi_gro_flush(n, !!timeout); 6244 } 6245 6246 gro_normal_list(n); 6247 6248 if (unlikely(!list_empty(&n->poll_list))) { 6249 /* If n->poll_list is not empty, we need to mask irqs */ 6250 local_irq_save(flags); 6251 list_del_init(&n->poll_list); 6252 local_irq_restore(flags); 6253 } 6254 WRITE_ONCE(n->list_owner, -1); 6255 6256 val = READ_ONCE(n->state); 6257 do { 6258 WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED)); 6259 6260 new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED | 6261 NAPIF_STATE_SCHED_THREADED | 6262 NAPIF_STATE_PREFER_BUSY_POLL); 6263 6264 /* If STATE_MISSED was set, leave STATE_SCHED set, 6265 * because we will call napi->poll() one more time. 6266 * This C code was suggested by Alexander Duyck to help gcc. 6267 */ 6268 new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED * 6269 NAPIF_STATE_SCHED; 6270 } while (!try_cmpxchg(&n->state, &val, new)); 6271 6272 if (unlikely(val & NAPIF_STATE_MISSED)) { 6273 __napi_schedule(n); 6274 return false; 6275 } 6276 6277 if (timeout) 6278 hrtimer_start(&n->timer, ns_to_ktime(timeout), 6279 HRTIMER_MODE_REL_PINNED); 6280 return ret; 6281} 6282EXPORT_SYMBOL(napi_complete_done); 6283 6284/* must be called under rcu_read_lock(), as we dont take a reference */ 6285struct napi_struct *napi_by_id(unsigned int napi_id) 6286{ 6287 unsigned int hash = napi_id % HASH_SIZE(napi_hash); 6288 struct napi_struct *napi; 6289 6290 hlist_for_each_entry_rcu(napi, &napi_hash[hash], napi_hash_node) 6291 if (napi->napi_id == napi_id) 6292 return napi; 6293 6294 return NULL; 6295} 6296 6297static void skb_defer_free_flush(struct softnet_data *sd) 6298{ 6299 struct sk_buff *skb, *next; 6300 6301 /* Paired with WRITE_ONCE() in skb_attempt_defer_free() */ 6302 if (!READ_ONCE(sd->defer_list)) 6303 return; 6304 6305 spin_lock(&sd->defer_lock); 6306 skb = sd->defer_list; 6307 sd->defer_list = NULL; 6308 sd->defer_count = 0; 6309 spin_unlock(&sd->defer_lock); 6310 6311 while (skb != NULL) { 6312 next = skb->next; 6313 napi_consume_skb(skb, 1); 6314 skb = next; 6315 } 6316} 6317 6318#if defined(CONFIG_NET_RX_BUSY_POLL) 6319 6320static void __busy_poll_stop(struct napi_struct *napi, bool skip_schedule) 6321{ 6322 if (!skip_schedule) { 6323 gro_normal_list(napi); 6324 __napi_schedule(napi); 6325 return; 6326 } 6327 6328 if (napi->gro_bitmask) { 6329 /* flush too old packets 6330 * If HZ < 1000, flush all packets. 6331 */ 6332 napi_gro_flush(napi, HZ >= 1000); 6333 } 6334 6335 gro_normal_list(napi); 6336 clear_bit(NAPI_STATE_SCHED, &napi->state); 6337} 6338 6339enum { 6340 NAPI_F_PREFER_BUSY_POLL = 1, 6341 NAPI_F_END_ON_RESCHED = 2, 6342}; 6343 6344static void busy_poll_stop(struct napi_struct *napi, void *have_poll_lock, 6345 unsigned flags, u16 budget) 6346{ 6347 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx; 6348 bool skip_schedule = false; 6349 unsigned long timeout; 6350 int rc; 6351 6352 /* Busy polling means there is a high chance device driver hard irq 6353 * could not grab NAPI_STATE_SCHED, and that NAPI_STATE_MISSED was 6354 * set in napi_schedule_prep(). 6355 * Since we are about to call napi->poll() once more, we can safely 6356 * clear NAPI_STATE_MISSED. 6357 * 6358 * Note: x86 could use a single "lock and ..." instruction 6359 * to perform these two clear_bit() 6360 */ 6361 clear_bit(NAPI_STATE_MISSED, &napi->state); 6362 clear_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state); 6363 6364 local_bh_disable(); 6365 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx); 6366 6367 if (flags & NAPI_F_PREFER_BUSY_POLL) { 6368 napi->defer_hard_irqs_count = READ_ONCE(napi->dev->napi_defer_hard_irqs); 6369 timeout = READ_ONCE(napi->dev->gro_flush_timeout); 6370 if (napi->defer_hard_irqs_count && timeout) { 6371 hrtimer_start(&napi->timer, ns_to_ktime(timeout), HRTIMER_MODE_REL_PINNED); 6372 skip_schedule = true; 6373 } 6374 } 6375 6376 /* All we really want here is to re-enable device interrupts. 6377 * Ideally, a new ndo_busy_poll_stop() could avoid another round. 6378 */ 6379 rc = napi->poll(napi, budget); 6380 /* We can't gro_normal_list() here, because napi->poll() might have 6381 * rearmed the napi (napi_complete_done()) in which case it could 6382 * already be running on another CPU. 6383 */ 6384 trace_napi_poll(napi, rc, budget); 6385 netpoll_poll_unlock(have_poll_lock); 6386 if (rc == budget) 6387 __busy_poll_stop(napi, skip_schedule); 6388 bpf_net_ctx_clear(bpf_net_ctx); 6389 local_bh_enable(); 6390} 6391 6392static void __napi_busy_loop(unsigned int napi_id, 6393 bool (*loop_end)(void *, unsigned long), 6394 void *loop_end_arg, unsigned flags, u16 budget) 6395{ 6396 unsigned long start_time = loop_end ? busy_loop_current_time() : 0; 6397 int (*napi_poll)(struct napi_struct *napi, int budget); 6398 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx; 6399 void *have_poll_lock = NULL; 6400 struct napi_struct *napi; 6401 6402 WARN_ON_ONCE(!rcu_read_lock_held()); 6403 6404restart: 6405 napi_poll = NULL; 6406 6407 napi = napi_by_id(napi_id); 6408 if (!napi) 6409 return; 6410 6411 if (!IS_ENABLED(CONFIG_PREEMPT_RT)) 6412 preempt_disable(); 6413 for (;;) { 6414 int work = 0; 6415 6416 local_bh_disable(); 6417 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx); 6418 if (!napi_poll) { 6419 unsigned long val = READ_ONCE(napi->state); 6420 6421 /* If multiple threads are competing for this napi, 6422 * we avoid dirtying napi->state as much as we can. 6423 */ 6424 if (val & (NAPIF_STATE_DISABLE | NAPIF_STATE_SCHED | 6425 NAPIF_STATE_IN_BUSY_POLL)) { 6426 if (flags & NAPI_F_PREFER_BUSY_POLL) 6427 set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state); 6428 goto count; 6429 } 6430 if (cmpxchg(&napi->state, val, 6431 val | NAPIF_STATE_IN_BUSY_POLL | 6432 NAPIF_STATE_SCHED) != val) { 6433 if (flags & NAPI_F_PREFER_BUSY_POLL) 6434 set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state); 6435 goto count; 6436 } 6437 have_poll_lock = netpoll_poll_lock(napi); 6438 napi_poll = napi->poll; 6439 } 6440 work = napi_poll(napi, budget); 6441 trace_napi_poll(napi, work, budget); 6442 gro_normal_list(napi); 6443count: 6444 if (work > 0) 6445 __NET_ADD_STATS(dev_net(napi->dev), 6446 LINUX_MIB_BUSYPOLLRXPACKETS, work); 6447 skb_defer_free_flush(this_cpu_ptr(&softnet_data)); 6448 bpf_net_ctx_clear(bpf_net_ctx); 6449 local_bh_enable(); 6450 6451 if (!loop_end || loop_end(loop_end_arg, start_time)) 6452 break; 6453 6454 if (unlikely(need_resched())) { 6455 if (flags & NAPI_F_END_ON_RESCHED) 6456 break; 6457 if (napi_poll) 6458 busy_poll_stop(napi, have_poll_lock, flags, budget); 6459 if (!IS_ENABLED(CONFIG_PREEMPT_RT)) 6460 preempt_enable(); 6461 rcu_read_unlock(); 6462 cond_resched(); 6463 rcu_read_lock(); 6464 if (loop_end(loop_end_arg, start_time)) 6465 return; 6466 goto restart; 6467 } 6468 cpu_relax(); 6469 } 6470 if (napi_poll) 6471 busy_poll_stop(napi, have_poll_lock, flags, budget); 6472 if (!IS_ENABLED(CONFIG_PREEMPT_RT)) 6473 preempt_enable(); 6474} 6475 6476void napi_busy_loop_rcu(unsigned int napi_id, 6477 bool (*loop_end)(void *, unsigned long), 6478 void *loop_end_arg, bool prefer_busy_poll, u16 budget) 6479{ 6480 unsigned flags = NAPI_F_END_ON_RESCHED; 6481 6482 if (prefer_busy_poll) 6483 flags |= NAPI_F_PREFER_BUSY_POLL; 6484 6485 __napi_busy_loop(napi_id, loop_end, loop_end_arg, flags, budget); 6486} 6487 6488void napi_busy_loop(unsigned int napi_id, 6489 bool (*loop_end)(void *, unsigned long), 6490 void *loop_end_arg, bool prefer_busy_poll, u16 budget) 6491{ 6492 unsigned flags = prefer_busy_poll ? NAPI_F_PREFER_BUSY_POLL : 0; 6493 6494 rcu_read_lock(); 6495 __napi_busy_loop(napi_id, loop_end, loop_end_arg, flags, budget); 6496 rcu_read_unlock(); 6497} 6498EXPORT_SYMBOL(napi_busy_loop); 6499 6500#endif /* CONFIG_NET_RX_BUSY_POLL */ 6501 6502static void napi_hash_add(struct napi_struct *napi) 6503{ 6504 if (test_bit(NAPI_STATE_NO_BUSY_POLL, &napi->state)) 6505 return; 6506 6507 spin_lock(&napi_hash_lock); 6508 6509 /* 0..NR_CPUS range is reserved for sender_cpu use */ 6510 do { 6511 if (unlikely(++napi_gen_id < MIN_NAPI_ID)) 6512 napi_gen_id = MIN_NAPI_ID; 6513 } while (napi_by_id(napi_gen_id)); 6514 napi->napi_id = napi_gen_id; 6515 6516 hlist_add_head_rcu(&napi->napi_hash_node, 6517 &napi_hash[napi->napi_id % HASH_SIZE(napi_hash)]); 6518 6519 spin_unlock(&napi_hash_lock); 6520} 6521 6522/* Warning : caller is responsible to make sure rcu grace period 6523 * is respected before freeing memory containing @napi 6524 */ 6525static void napi_hash_del(struct napi_struct *napi) 6526{ 6527 spin_lock(&napi_hash_lock); 6528 6529 hlist_del_init_rcu(&napi->napi_hash_node); 6530 6531 spin_unlock(&napi_hash_lock); 6532} 6533 6534static enum hrtimer_restart napi_watchdog(struct hrtimer *timer) 6535{ 6536 struct napi_struct *napi; 6537 6538 napi = container_of(timer, struct napi_struct, timer); 6539 6540 /* Note : we use a relaxed variant of napi_schedule_prep() not setting 6541 * NAPI_STATE_MISSED, since we do not react to a device IRQ. 6542 */ 6543 if (!napi_disable_pending(napi) && 6544 !test_and_set_bit(NAPI_STATE_SCHED, &napi->state)) { 6545 clear_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state); 6546 __napi_schedule_irqoff(napi); 6547 } 6548 6549 return HRTIMER_NORESTART; 6550} 6551 6552static void init_gro_hash(struct napi_struct *napi) 6553{ 6554 int i; 6555 6556 for (i = 0; i < GRO_HASH_BUCKETS; i++) { 6557 INIT_LIST_HEAD(&napi->gro_hash[i].list); 6558 napi->gro_hash[i].count = 0; 6559 } 6560 napi->gro_bitmask = 0; 6561} 6562 6563int dev_set_threaded(struct net_device *dev, bool threaded) 6564{ 6565 struct napi_struct *napi; 6566 int err = 0; 6567 6568 if (dev->threaded == threaded) 6569 return 0; 6570 6571 if (threaded) { 6572 list_for_each_entry(napi, &dev->napi_list, dev_list) { 6573 if (!napi->thread) { 6574 err = napi_kthread_create(napi); 6575 if (err) { 6576 threaded = false; 6577 break; 6578 } 6579 } 6580 } 6581 } 6582 6583 WRITE_ONCE(dev->threaded, threaded); 6584 6585 /* Make sure kthread is created before THREADED bit 6586 * is set. 6587 */ 6588 smp_mb__before_atomic(); 6589 6590 /* Setting/unsetting threaded mode on a napi might not immediately 6591 * take effect, if the current napi instance is actively being 6592 * polled. In this case, the switch between threaded mode and 6593 * softirq mode will happen in the next round of napi_schedule(). 6594 * This should not cause hiccups/stalls to the live traffic. 6595 */ 6596 list_for_each_entry(napi, &dev->napi_list, dev_list) 6597 assign_bit(NAPI_STATE_THREADED, &napi->state, threaded); 6598 6599 return err; 6600} 6601EXPORT_SYMBOL(dev_set_threaded); 6602 6603/** 6604 * netif_queue_set_napi - Associate queue with the napi 6605 * @dev: device to which NAPI and queue belong 6606 * @queue_index: Index of queue 6607 * @type: queue type as RX or TX 6608 * @napi: NAPI context, pass NULL to clear previously set NAPI 6609 * 6610 * Set queue with its corresponding napi context. This should be done after 6611 * registering the NAPI handler for the queue-vector and the queues have been 6612 * mapped to the corresponding interrupt vector. 6613 */ 6614void netif_queue_set_napi(struct net_device *dev, unsigned int queue_index, 6615 enum netdev_queue_type type, struct napi_struct *napi) 6616{ 6617 struct netdev_rx_queue *rxq; 6618 struct netdev_queue *txq; 6619 6620 if (WARN_ON_ONCE(napi && !napi->dev)) 6621 return; 6622 if (dev->reg_state >= NETREG_REGISTERED) 6623 ASSERT_RTNL(); 6624 6625 switch (type) { 6626 case NETDEV_QUEUE_TYPE_RX: 6627 rxq = __netif_get_rx_queue(dev, queue_index); 6628 rxq->napi = napi; 6629 return; 6630 case NETDEV_QUEUE_TYPE_TX: 6631 txq = netdev_get_tx_queue(dev, queue_index); 6632 txq->napi = napi; 6633 return; 6634 default: 6635 return; 6636 } 6637} 6638EXPORT_SYMBOL(netif_queue_set_napi); 6639 6640void netif_napi_add_weight(struct net_device *dev, struct napi_struct *napi, 6641 int (*poll)(struct napi_struct *, int), int weight) 6642{ 6643 if (WARN_ON(test_and_set_bit(NAPI_STATE_LISTED, &napi->state))) 6644 return; 6645 6646 INIT_LIST_HEAD(&napi->poll_list); 6647 INIT_HLIST_NODE(&napi->napi_hash_node); 6648 hrtimer_init(&napi->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED); 6649 napi->timer.function = napi_watchdog; 6650 init_gro_hash(napi); 6651 napi->skb = NULL; 6652 INIT_LIST_HEAD(&napi->rx_list); 6653 napi->rx_count = 0; 6654 napi->poll = poll; 6655 if (weight > NAPI_POLL_WEIGHT) 6656 netdev_err_once(dev, "%s() called with weight %d\n", __func__, 6657 weight); 6658 napi->weight = weight; 6659 napi->dev = dev; 6660#ifdef CONFIG_NETPOLL 6661 napi->poll_owner = -1; 6662#endif 6663 napi->list_owner = -1; 6664 set_bit(NAPI_STATE_SCHED, &napi->state); 6665 set_bit(NAPI_STATE_NPSVC, &napi->state); 6666 list_add_rcu(&napi->dev_list, &dev->napi_list); 6667 napi_hash_add(napi); 6668 napi_get_frags_check(napi); 6669 /* Create kthread for this napi if dev->threaded is set. 6670 * Clear dev->threaded if kthread creation failed so that 6671 * threaded mode will not be enabled in napi_enable(). 6672 */ 6673 if (dev->threaded && napi_kthread_create(napi)) 6674 dev->threaded = false; 6675 netif_napi_set_irq(napi, -1); 6676} 6677EXPORT_SYMBOL(netif_napi_add_weight); 6678 6679void napi_disable(struct napi_struct *n) 6680{ 6681 unsigned long val, new; 6682 6683 might_sleep(); 6684 set_bit(NAPI_STATE_DISABLE, &n->state); 6685 6686 val = READ_ONCE(n->state); 6687 do { 6688 while (val & (NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC)) { 6689 usleep_range(20, 200); 6690 val = READ_ONCE(n->state); 6691 } 6692 6693 new = val | NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC; 6694 new &= ~(NAPIF_STATE_THREADED | NAPIF_STATE_PREFER_BUSY_POLL); 6695 } while (!try_cmpxchg(&n->state, &val, new)); 6696 6697 hrtimer_cancel(&n->timer); 6698 6699 clear_bit(NAPI_STATE_DISABLE, &n->state); 6700} 6701EXPORT_SYMBOL(napi_disable); 6702 6703/** 6704 * napi_enable - enable NAPI scheduling 6705 * @n: NAPI context 6706 * 6707 * Resume NAPI from being scheduled on this context. 6708 * Must be paired with napi_disable. 6709 */ 6710void napi_enable(struct napi_struct *n) 6711{ 6712 unsigned long new, val = READ_ONCE(n->state); 6713 6714 do { 6715 BUG_ON(!test_bit(NAPI_STATE_SCHED, &val)); 6716 6717 new = val & ~(NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC); 6718 if (n->dev->threaded && n->thread) 6719 new |= NAPIF_STATE_THREADED; 6720 } while (!try_cmpxchg(&n->state, &val, new)); 6721} 6722EXPORT_SYMBOL(napi_enable); 6723 6724static void flush_gro_hash(struct napi_struct *napi) 6725{ 6726 int i; 6727 6728 for (i = 0; i < GRO_HASH_BUCKETS; i++) { 6729 struct sk_buff *skb, *n; 6730 6731 list_for_each_entry_safe(skb, n, &napi->gro_hash[i].list, list) 6732 kfree_skb(skb); 6733 napi->gro_hash[i].count = 0; 6734 } 6735} 6736 6737/* Must be called in process context */ 6738void __netif_napi_del(struct napi_struct *napi) 6739{ 6740 if (!test_and_clear_bit(NAPI_STATE_LISTED, &napi->state)) 6741 return; 6742 6743 napi_hash_del(napi); 6744 list_del_rcu(&napi->dev_list); 6745 napi_free_frags(napi); 6746 6747 flush_gro_hash(napi); 6748 napi->gro_bitmask = 0; 6749 6750 if (napi->thread) { 6751 kthread_stop(napi->thread); 6752 napi->thread = NULL; 6753 } 6754} 6755EXPORT_SYMBOL(__netif_napi_del); 6756 6757static int __napi_poll(struct napi_struct *n, bool *repoll) 6758{ 6759 int work, weight; 6760 6761 weight = n->weight; 6762 6763 /* This NAPI_STATE_SCHED test is for avoiding a race 6764 * with netpoll's poll_napi(). Only the entity which 6765 * obtains the lock and sees NAPI_STATE_SCHED set will 6766 * actually make the ->poll() call. Therefore we avoid 6767 * accidentally calling ->poll() when NAPI is not scheduled. 6768 */ 6769 work = 0; 6770 if (napi_is_scheduled(n)) { 6771 work = n->poll(n, weight); 6772 trace_napi_poll(n, work, weight); 6773 6774 xdp_do_check_flushed(n); 6775 } 6776 6777 if (unlikely(work > weight)) 6778 netdev_err_once(n->dev, "NAPI poll function %pS returned %d, exceeding its budget of %d.\n", 6779 n->poll, work, weight); 6780 6781 if (likely(work < weight)) 6782 return work; 6783 6784 /* Drivers must not modify the NAPI state if they 6785 * consume the entire weight. In such cases this code 6786 * still "owns" the NAPI instance and therefore can 6787 * move the instance around on the list at-will. 6788 */ 6789 if (unlikely(napi_disable_pending(n))) { 6790 napi_complete(n); 6791 return work; 6792 } 6793 6794 /* The NAPI context has more processing work, but busy-polling 6795 * is preferred. Exit early. 6796 */ 6797 if (napi_prefer_busy_poll(n)) { 6798 if (napi_complete_done(n, work)) { 6799 /* If timeout is not set, we need to make sure 6800 * that the NAPI is re-scheduled. 6801 */ 6802 napi_schedule(n); 6803 } 6804 return work; 6805 } 6806 6807 if (n->gro_bitmask) { 6808 /* flush too old packets 6809 * If HZ < 1000, flush all packets. 6810 */ 6811 napi_gro_flush(n, HZ >= 1000); 6812 } 6813 6814 gro_normal_list(n); 6815 6816 /* Some drivers may have called napi_schedule 6817 * prior to exhausting their budget. 6818 */ 6819 if (unlikely(!list_empty(&n->poll_list))) { 6820 pr_warn_once("%s: Budget exhausted after napi rescheduled\n", 6821 n->dev ? n->dev->name : "backlog"); 6822 return work; 6823 } 6824 6825 *repoll = true; 6826 6827 return work; 6828} 6829 6830static int napi_poll(struct napi_struct *n, struct list_head *repoll) 6831{ 6832 bool do_repoll = false; 6833 void *have; 6834 int work; 6835 6836 list_del_init(&n->poll_list); 6837 6838 have = netpoll_poll_lock(n); 6839 6840 work = __napi_poll(n, &do_repoll); 6841 6842 if (do_repoll) 6843 list_add_tail(&n->poll_list, repoll); 6844 6845 netpoll_poll_unlock(have); 6846 6847 return work; 6848} 6849 6850static int napi_thread_wait(struct napi_struct *napi) 6851{ 6852 set_current_state(TASK_INTERRUPTIBLE); 6853 6854 while (!kthread_should_stop()) { 6855 /* Testing SCHED_THREADED bit here to make sure the current 6856 * kthread owns this napi and could poll on this napi. 6857 * Testing SCHED bit is not enough because SCHED bit might be 6858 * set by some other busy poll thread or by napi_disable(). 6859 */ 6860 if (test_bit(NAPI_STATE_SCHED_THREADED, &napi->state)) { 6861 WARN_ON(!list_empty(&napi->poll_list)); 6862 __set_current_state(TASK_RUNNING); 6863 return 0; 6864 } 6865 6866 schedule(); 6867 set_current_state(TASK_INTERRUPTIBLE); 6868 } 6869 __set_current_state(TASK_RUNNING); 6870 6871 return -1; 6872} 6873 6874static void napi_threaded_poll_loop(struct napi_struct *napi) 6875{ 6876 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx; 6877 struct softnet_data *sd; 6878 unsigned long last_qs = jiffies; 6879 6880 for (;;) { 6881 bool repoll = false; 6882 void *have; 6883 6884 local_bh_disable(); 6885 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx); 6886 6887 sd = this_cpu_ptr(&softnet_data); 6888 sd->in_napi_threaded_poll = true; 6889 6890 have = netpoll_poll_lock(napi); 6891 __napi_poll(napi, &repoll); 6892 netpoll_poll_unlock(have); 6893 6894 sd->in_napi_threaded_poll = false; 6895 barrier(); 6896 6897 if (sd_has_rps_ipi_waiting(sd)) { 6898 local_irq_disable(); 6899 net_rps_action_and_irq_enable(sd); 6900 } 6901 skb_defer_free_flush(sd); 6902 bpf_net_ctx_clear(bpf_net_ctx); 6903 local_bh_enable(); 6904 6905 if (!repoll) 6906 break; 6907 6908 rcu_softirq_qs_periodic(last_qs); 6909 cond_resched(); 6910 } 6911} 6912 6913static int napi_threaded_poll(void *data) 6914{ 6915 struct napi_struct *napi = data; 6916 6917 while (!napi_thread_wait(napi)) 6918 napi_threaded_poll_loop(napi); 6919 6920 return 0; 6921} 6922 6923static __latent_entropy void net_rx_action(struct softirq_action *h) 6924{ 6925 struct softnet_data *sd = this_cpu_ptr(&softnet_data); 6926 unsigned long time_limit = jiffies + 6927 usecs_to_jiffies(READ_ONCE(net_hotdata.netdev_budget_usecs)); 6928 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx; 6929 int budget = READ_ONCE(net_hotdata.netdev_budget); 6930 LIST_HEAD(list); 6931 LIST_HEAD(repoll); 6932 6933 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx); 6934start: 6935 sd->in_net_rx_action = true; 6936 local_irq_disable(); 6937 list_splice_init(&sd->poll_list, &list); 6938 local_irq_enable(); 6939 6940 for (;;) { 6941 struct napi_struct *n; 6942 6943 skb_defer_free_flush(sd); 6944 6945 if (list_empty(&list)) { 6946 if (list_empty(&repoll)) { 6947 sd->in_net_rx_action = false; 6948 barrier(); 6949 /* We need to check if ____napi_schedule() 6950 * had refilled poll_list while 6951 * sd->in_net_rx_action was true. 6952 */ 6953 if (!list_empty(&sd->poll_list)) 6954 goto start; 6955 if (!sd_has_rps_ipi_waiting(sd)) 6956 goto end; 6957 } 6958 break; 6959 } 6960 6961 n = list_first_entry(&list, struct napi_struct, poll_list); 6962 budget -= napi_poll(n, &repoll); 6963 6964 /* If softirq window is exhausted then punt. 6965 * Allow this to run for 2 jiffies since which will allow 6966 * an average latency of 1.5/HZ. 6967 */ 6968 if (unlikely(budget <= 0 || 6969 time_after_eq(jiffies, time_limit))) { 6970 sd->time_squeeze++; 6971 break; 6972 } 6973 } 6974 6975 local_irq_disable(); 6976 6977 list_splice_tail_init(&sd->poll_list, &list); 6978 list_splice_tail(&repoll, &list); 6979 list_splice(&list, &sd->poll_list); 6980 if (!list_empty(&sd->poll_list)) 6981 __raise_softirq_irqoff(NET_RX_SOFTIRQ); 6982 else 6983 sd->in_net_rx_action = false; 6984 6985 net_rps_action_and_irq_enable(sd); 6986end: 6987 bpf_net_ctx_clear(bpf_net_ctx); 6988} 6989 6990struct netdev_adjacent { 6991 struct net_device *dev; 6992 netdevice_tracker dev_tracker; 6993 6994 /* upper master flag, there can only be one master device per list */ 6995 bool master; 6996 6997 /* lookup ignore flag */ 6998 bool ignore; 6999 7000 /* counter for the number of times this device was added to us */ 7001 u16 ref_nr; 7002 7003 /* private field for the users */ 7004 void *private; 7005 7006 struct list_head list; 7007 struct rcu_head rcu; 7008}; 7009 7010static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev, 7011 struct list_head *adj_list) 7012{ 7013 struct netdev_adjacent *adj; 7014 7015 list_for_each_entry(adj, adj_list, list) { 7016 if (adj->dev == adj_dev) 7017 return adj; 7018 } 7019 return NULL; 7020} 7021 7022static int ____netdev_has_upper_dev(struct net_device *upper_dev, 7023 struct netdev_nested_priv *priv) 7024{ 7025 struct net_device *dev = (struct net_device *)priv->data; 7026 7027 return upper_dev == dev; 7028} 7029 7030/** 7031 * netdev_has_upper_dev - Check if device is linked to an upper device 7032 * @dev: device 7033 * @upper_dev: upper device to check 7034 * 7035 * Find out if a device is linked to specified upper device and return true 7036 * in case it is. Note that this checks only immediate upper device, 7037 * not through a complete stack of devices. The caller must hold the RTNL lock. 7038 */ 7039bool netdev_has_upper_dev(struct net_device *dev, 7040 struct net_device *upper_dev) 7041{ 7042 struct netdev_nested_priv priv = { 7043 .data = (void *)upper_dev, 7044 }; 7045 7046 ASSERT_RTNL(); 7047 7048 return netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev, 7049 &priv); 7050} 7051EXPORT_SYMBOL(netdev_has_upper_dev); 7052 7053/** 7054 * netdev_has_upper_dev_all_rcu - Check if device is linked to an upper device 7055 * @dev: device 7056 * @upper_dev: upper device to check 7057 * 7058 * Find out if a device is linked to specified upper device and return true 7059 * in case it is. Note that this checks the entire upper device chain. 7060 * The caller must hold rcu lock. 7061 */ 7062 7063bool netdev_has_upper_dev_all_rcu(struct net_device *dev, 7064 struct net_device *upper_dev) 7065{ 7066 struct netdev_nested_priv priv = { 7067 .data = (void *)upper_dev, 7068 }; 7069 7070 return !!netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev, 7071 &priv); 7072} 7073EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu); 7074 7075/** 7076 * netdev_has_any_upper_dev - Check if device is linked to some device 7077 * @dev: device 7078 * 7079 * Find out if a device is linked to an upper device and return true in case 7080 * it is. The caller must hold the RTNL lock. 7081 */ 7082bool netdev_has_any_upper_dev(struct net_device *dev) 7083{ 7084 ASSERT_RTNL(); 7085 7086 return !list_empty(&dev->adj_list.upper); 7087} 7088EXPORT_SYMBOL(netdev_has_any_upper_dev); 7089 7090/** 7091 * netdev_master_upper_dev_get - Get master upper device 7092 * @dev: device 7093 * 7094 * Find a master upper device and return pointer to it or NULL in case 7095 * it's not there. The caller must hold the RTNL lock. 7096 */ 7097struct net_device *netdev_master_upper_dev_get(struct net_device *dev) 7098{ 7099 struct netdev_adjacent *upper; 7100 7101 ASSERT_RTNL(); 7102 7103 if (list_empty(&dev->adj_list.upper)) 7104 return NULL; 7105 7106 upper = list_first_entry(&dev->adj_list.upper, 7107 struct netdev_adjacent, list); 7108 if (likely(upper->master)) 7109 return upper->dev; 7110 return NULL; 7111} 7112EXPORT_SYMBOL(netdev_master_upper_dev_get); 7113 7114static struct net_device *__netdev_master_upper_dev_get(struct net_device *dev) 7115{ 7116 struct netdev_adjacent *upper; 7117 7118 ASSERT_RTNL(); 7119 7120 if (list_empty(&dev->adj_list.upper)) 7121 return NULL; 7122 7123 upper = list_first_entry(&dev->adj_list.upper, 7124 struct netdev_adjacent, list); 7125 if (likely(upper->master) && !upper->ignore) 7126 return upper->dev; 7127 return NULL; 7128} 7129 7130/** 7131 * netdev_has_any_lower_dev - Check if device is linked to some device 7132 * @dev: device 7133 * 7134 * Find out if a device is linked to a lower device and return true in case 7135 * it is. The caller must hold the RTNL lock. 7136 */ 7137static bool netdev_has_any_lower_dev(struct net_device *dev) 7138{ 7139 ASSERT_RTNL(); 7140 7141 return !list_empty(&dev->adj_list.lower); 7142} 7143 7144void *netdev_adjacent_get_private(struct list_head *adj_list) 7145{ 7146 struct netdev_adjacent *adj; 7147 7148 adj = list_entry(adj_list, struct netdev_adjacent, list); 7149 7150 return adj->private; 7151} 7152EXPORT_SYMBOL(netdev_adjacent_get_private); 7153 7154/** 7155 * netdev_upper_get_next_dev_rcu - Get the next dev from upper list 7156 * @dev: device 7157 * @iter: list_head ** of the current position 7158 * 7159 * Gets the next device from the dev's upper list, starting from iter 7160 * position. The caller must hold RCU read lock. 7161 */ 7162struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev, 7163 struct list_head **iter) 7164{ 7165 struct netdev_adjacent *upper; 7166 7167 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held()); 7168 7169 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list); 7170 7171 if (&upper->list == &dev->adj_list.upper) 7172 return NULL; 7173 7174 *iter = &upper->list; 7175 7176 return upper->dev; 7177} 7178EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu); 7179 7180static struct net_device *__netdev_next_upper_dev(struct net_device *dev, 7181 struct list_head **iter, 7182 bool *ignore) 7183{ 7184 struct netdev_adjacent *upper; 7185 7186 upper = list_entry((*iter)->next, struct netdev_adjacent, list); 7187 7188 if (&upper->list == &dev->adj_list.upper) 7189 return NULL; 7190 7191 *iter = &upper->list; 7192 *ignore = upper->ignore; 7193 7194 return upper->dev; 7195} 7196 7197static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev, 7198 struct list_head **iter) 7199{ 7200 struct netdev_adjacent *upper; 7201 7202 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held()); 7203 7204 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list); 7205 7206 if (&upper->list == &dev->adj_list.upper) 7207 return NULL; 7208 7209 *iter = &upper->list; 7210 7211 return upper->dev; 7212} 7213 7214static int __netdev_walk_all_upper_dev(struct net_device *dev, 7215 int (*fn)(struct net_device *dev, 7216 struct netdev_nested_priv *priv), 7217 struct netdev_nested_priv *priv) 7218{ 7219 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1]; 7220 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1]; 7221 int ret, cur = 0; 7222 bool ignore; 7223 7224 now = dev; 7225 iter = &dev->adj_list.upper; 7226 7227 while (1) { 7228 if (now != dev) { 7229 ret = fn(now, priv); 7230 if (ret) 7231 return ret; 7232 } 7233 7234 next = NULL; 7235 while (1) { 7236 udev = __netdev_next_upper_dev(now, &iter, &ignore); 7237 if (!udev) 7238 break; 7239 if (ignore) 7240 continue; 7241 7242 next = udev; 7243 niter = &udev->adj_list.upper; 7244 dev_stack[cur] = now; 7245 iter_stack[cur++] = iter; 7246 break; 7247 } 7248 7249 if (!next) { 7250 if (!cur) 7251 return 0; 7252 next = dev_stack[--cur]; 7253 niter = iter_stack[cur]; 7254 } 7255 7256 now = next; 7257 iter = niter; 7258 } 7259 7260 return 0; 7261} 7262 7263int netdev_walk_all_upper_dev_rcu(struct net_device *dev, 7264 int (*fn)(struct net_device *dev, 7265 struct netdev_nested_priv *priv), 7266 struct netdev_nested_priv *priv) 7267{ 7268 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1]; 7269 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1]; 7270 int ret, cur = 0; 7271 7272 now = dev; 7273 iter = &dev->adj_list.upper; 7274 7275 while (1) { 7276 if (now != dev) { 7277 ret = fn(now, priv); 7278 if (ret) 7279 return ret; 7280 } 7281 7282 next = NULL; 7283 while (1) { 7284 udev = netdev_next_upper_dev_rcu(now, &iter); 7285 if (!udev) 7286 break; 7287 7288 next = udev; 7289 niter = &udev->adj_list.upper; 7290 dev_stack[cur] = now; 7291 iter_stack[cur++] = iter; 7292 break; 7293 } 7294 7295 if (!next) { 7296 if (!cur) 7297 return 0; 7298 next = dev_stack[--cur]; 7299 niter = iter_stack[cur]; 7300 } 7301 7302 now = next; 7303 iter = niter; 7304 } 7305 7306 return 0; 7307} 7308EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu); 7309 7310static bool __netdev_has_upper_dev(struct net_device *dev, 7311 struct net_device *upper_dev) 7312{ 7313 struct netdev_nested_priv priv = { 7314 .flags = 0, 7315 .data = (void *)upper_dev, 7316 }; 7317 7318 ASSERT_RTNL(); 7319 7320 return __netdev_walk_all_upper_dev(dev, ____netdev_has_upper_dev, 7321 &priv); 7322} 7323 7324/** 7325 * netdev_lower_get_next_private - Get the next ->private from the 7326 * lower neighbour list 7327 * @dev: device 7328 * @iter: list_head ** of the current position 7329 * 7330 * Gets the next netdev_adjacent->private from the dev's lower neighbour 7331 * list, starting from iter position. The caller must hold either hold the 7332 * RTNL lock or its own locking that guarantees that the neighbour lower 7333 * list will remain unchanged. 7334 */ 7335void *netdev_lower_get_next_private(struct net_device *dev, 7336 struct list_head **iter) 7337{ 7338 struct netdev_adjacent *lower; 7339 7340 lower = list_entry(*iter, struct netdev_adjacent, list); 7341 7342 if (&lower->list == &dev->adj_list.lower) 7343 return NULL; 7344 7345 *iter = lower->list.next; 7346 7347 return lower->private; 7348} 7349EXPORT_SYMBOL(netdev_lower_get_next_private); 7350 7351/** 7352 * netdev_lower_get_next_private_rcu - Get the next ->private from the 7353 * lower neighbour list, RCU 7354 * variant 7355 * @dev: device 7356 * @iter: list_head ** of the current position 7357 * 7358 * Gets the next netdev_adjacent->private from the dev's lower neighbour 7359 * list, starting from iter position. The caller must hold RCU read lock. 7360 */ 7361void *netdev_lower_get_next_private_rcu(struct net_device *dev, 7362 struct list_head **iter) 7363{ 7364 struct netdev_adjacent *lower; 7365 7366 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held()); 7367 7368 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list); 7369 7370 if (&lower->list == &dev->adj_list.lower) 7371 return NULL; 7372 7373 *iter = &lower->list; 7374 7375 return lower->private; 7376} 7377EXPORT_SYMBOL(netdev_lower_get_next_private_rcu); 7378 7379/** 7380 * netdev_lower_get_next - Get the next device from the lower neighbour 7381 * list 7382 * @dev: device 7383 * @iter: list_head ** of the current position 7384 * 7385 * Gets the next netdev_adjacent from the dev's lower neighbour 7386 * list, starting from iter position. The caller must hold RTNL lock or 7387 * its own locking that guarantees that the neighbour lower 7388 * list will remain unchanged. 7389 */ 7390void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter) 7391{ 7392 struct netdev_adjacent *lower; 7393 7394 lower = list_entry(*iter, struct netdev_adjacent, list); 7395 7396 if (&lower->list == &dev->adj_list.lower) 7397 return NULL; 7398 7399 *iter = lower->list.next; 7400 7401 return lower->dev; 7402} 7403EXPORT_SYMBOL(netdev_lower_get_next); 7404 7405static struct net_device *netdev_next_lower_dev(struct net_device *dev, 7406 struct list_head **iter) 7407{ 7408 struct netdev_adjacent *lower; 7409 7410 lower = list_entry((*iter)->next, struct netdev_adjacent, list); 7411 7412 if (&lower->list == &dev->adj_list.lower) 7413 return NULL; 7414 7415 *iter = &lower->list; 7416 7417 return lower->dev; 7418} 7419 7420static struct net_device *__netdev_next_lower_dev(struct net_device *dev, 7421 struct list_head **iter, 7422 bool *ignore) 7423{ 7424 struct netdev_adjacent *lower; 7425 7426 lower = list_entry((*iter)->next, struct netdev_adjacent, list); 7427 7428 if (&lower->list == &dev->adj_list.lower) 7429 return NULL; 7430 7431 *iter = &lower->list; 7432 *ignore = lower->ignore; 7433 7434 return lower->dev; 7435} 7436 7437int netdev_walk_all_lower_dev(struct net_device *dev, 7438 int (*fn)(struct net_device *dev, 7439 struct netdev_nested_priv *priv), 7440 struct netdev_nested_priv *priv) 7441{ 7442 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1]; 7443 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1]; 7444 int ret, cur = 0; 7445 7446 now = dev; 7447 iter = &dev->adj_list.lower; 7448 7449 while (1) { 7450 if (now != dev) { 7451 ret = fn(now, priv); 7452 if (ret) 7453 return ret; 7454 } 7455 7456 next = NULL; 7457 while (1) { 7458 ldev = netdev_next_lower_dev(now, &iter); 7459 if (!ldev) 7460 break; 7461 7462 next = ldev; 7463 niter = &ldev->adj_list.lower; 7464 dev_stack[cur] = now; 7465 iter_stack[cur++] = iter; 7466 break; 7467 } 7468 7469 if (!next) { 7470 if (!cur) 7471 return 0; 7472 next = dev_stack[--cur]; 7473 niter = iter_stack[cur]; 7474 } 7475 7476 now = next; 7477 iter = niter; 7478 } 7479 7480 return 0; 7481} 7482EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev); 7483 7484static int __netdev_walk_all_lower_dev(struct net_device *dev, 7485 int (*fn)(struct net_device *dev, 7486 struct netdev_nested_priv *priv), 7487 struct netdev_nested_priv *priv) 7488{ 7489 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1]; 7490 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1]; 7491 int ret, cur = 0; 7492 bool ignore; 7493 7494 now = dev; 7495 iter = &dev->adj_list.lower; 7496 7497 while (1) { 7498 if (now != dev) { 7499 ret = fn(now, priv); 7500 if (ret) 7501 return ret; 7502 } 7503 7504 next = NULL; 7505 while (1) { 7506 ldev = __netdev_next_lower_dev(now, &iter, &ignore); 7507 if (!ldev) 7508 break; 7509 if (ignore) 7510 continue; 7511 7512 next = ldev; 7513 niter = &ldev->adj_list.lower; 7514 dev_stack[cur] = now; 7515 iter_stack[cur++] = iter; 7516 break; 7517 } 7518 7519 if (!next) { 7520 if (!cur) 7521 return 0; 7522 next = dev_stack[--cur]; 7523 niter = iter_stack[cur]; 7524 } 7525 7526 now = next; 7527 iter = niter; 7528 } 7529 7530 return 0; 7531} 7532 7533struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev, 7534 struct list_head **iter) 7535{ 7536 struct netdev_adjacent *lower; 7537 7538 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list); 7539 if (&lower->list == &dev->adj_list.lower) 7540 return NULL; 7541 7542 *iter = &lower->list; 7543 7544 return lower->dev; 7545} 7546EXPORT_SYMBOL(netdev_next_lower_dev_rcu); 7547 7548static u8 __netdev_upper_depth(struct net_device *dev) 7549{ 7550 struct net_device *udev; 7551 struct list_head *iter; 7552 u8 max_depth = 0; 7553 bool ignore; 7554 7555 for (iter = &dev->adj_list.upper, 7556 udev = __netdev_next_upper_dev(dev, &iter, &ignore); 7557 udev; 7558 udev = __netdev_next_upper_dev(dev, &iter, &ignore)) { 7559 if (ignore) 7560 continue; 7561 if (max_depth < udev->upper_level) 7562 max_depth = udev->upper_level; 7563 } 7564 7565 return max_depth; 7566} 7567 7568static u8 __netdev_lower_depth(struct net_device *dev) 7569{ 7570 struct net_device *ldev; 7571 struct list_head *iter; 7572 u8 max_depth = 0; 7573 bool ignore; 7574 7575 for (iter = &dev->adj_list.lower, 7576 ldev = __netdev_next_lower_dev(dev, &iter, &ignore); 7577 ldev; 7578 ldev = __netdev_next_lower_dev(dev, &iter, &ignore)) { 7579 if (ignore) 7580 continue; 7581 if (max_depth < ldev->lower_level) 7582 max_depth = ldev->lower_level; 7583 } 7584 7585 return max_depth; 7586} 7587 7588static int __netdev_update_upper_level(struct net_device *dev, 7589 struct netdev_nested_priv *__unused) 7590{ 7591 dev->upper_level = __netdev_upper_depth(dev) + 1; 7592 return 0; 7593} 7594 7595#ifdef CONFIG_LOCKDEP 7596static LIST_HEAD(net_unlink_list); 7597 7598static void net_unlink_todo(struct net_device *dev) 7599{ 7600 if (list_empty(&dev->unlink_list)) 7601 list_add_tail(&dev->unlink_list, &net_unlink_list); 7602} 7603#endif 7604 7605static int __netdev_update_lower_level(struct net_device *dev, 7606 struct netdev_nested_priv *priv) 7607{ 7608 dev->lower_level = __netdev_lower_depth(dev) + 1; 7609 7610#ifdef CONFIG_LOCKDEP 7611 if (!priv) 7612 return 0; 7613 7614 if (priv->flags & NESTED_SYNC_IMM) 7615 dev->nested_level = dev->lower_level - 1; 7616 if (priv->flags & NESTED_SYNC_TODO) 7617 net_unlink_todo(dev); 7618#endif 7619 return 0; 7620} 7621 7622int netdev_walk_all_lower_dev_rcu(struct net_device *dev, 7623 int (*fn)(struct net_device *dev, 7624 struct netdev_nested_priv *priv), 7625 struct netdev_nested_priv *priv) 7626{ 7627 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1]; 7628 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1]; 7629 int ret, cur = 0; 7630 7631 now = dev; 7632 iter = &dev->adj_list.lower; 7633 7634 while (1) { 7635 if (now != dev) { 7636 ret = fn(now, priv); 7637 if (ret) 7638 return ret; 7639 } 7640 7641 next = NULL; 7642 while (1) { 7643 ldev = netdev_next_lower_dev_rcu(now, &iter); 7644 if (!ldev) 7645 break; 7646 7647 next = ldev; 7648 niter = &ldev->adj_list.lower; 7649 dev_stack[cur] = now; 7650 iter_stack[cur++] = iter; 7651 break; 7652 } 7653 7654 if (!next) { 7655 if (!cur) 7656 return 0; 7657 next = dev_stack[--cur]; 7658 niter = iter_stack[cur]; 7659 } 7660 7661 now = next; 7662 iter = niter; 7663 } 7664 7665 return 0; 7666} 7667EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu); 7668 7669/** 7670 * netdev_lower_get_first_private_rcu - Get the first ->private from the 7671 * lower neighbour list, RCU 7672 * variant 7673 * @dev: device 7674 * 7675 * Gets the first netdev_adjacent->private from the dev's lower neighbour 7676 * list. The caller must hold RCU read lock. 7677 */ 7678void *netdev_lower_get_first_private_rcu(struct net_device *dev) 7679{ 7680 struct netdev_adjacent *lower; 7681 7682 lower = list_first_or_null_rcu(&dev->adj_list.lower, 7683 struct netdev_adjacent, list); 7684 if (lower) 7685 return lower->private; 7686 return NULL; 7687} 7688EXPORT_SYMBOL(netdev_lower_get_first_private_rcu); 7689 7690/** 7691 * netdev_master_upper_dev_get_rcu - Get master upper device 7692 * @dev: device 7693 * 7694 * Find a master upper device and return pointer to it or NULL in case 7695 * it's not there. The caller must hold the RCU read lock. 7696 */ 7697struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev) 7698{ 7699 struct netdev_adjacent *upper; 7700 7701 upper = list_first_or_null_rcu(&dev->adj_list.upper, 7702 struct netdev_adjacent, list); 7703 if (upper && likely(upper->master)) 7704 return upper->dev; 7705 return NULL; 7706} 7707EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu); 7708 7709static int netdev_adjacent_sysfs_add(struct net_device *dev, 7710 struct net_device *adj_dev, 7711 struct list_head *dev_list) 7712{ 7713 char linkname[IFNAMSIZ+7]; 7714 7715 sprintf(linkname, dev_list == &dev->adj_list.upper ? 7716 "upper_%s" : "lower_%s", adj_dev->name); 7717 return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj), 7718 linkname); 7719} 7720static void netdev_adjacent_sysfs_del(struct net_device *dev, 7721 char *name, 7722 struct list_head *dev_list) 7723{ 7724 char linkname[IFNAMSIZ+7]; 7725 7726 sprintf(linkname, dev_list == &dev->adj_list.upper ? 7727 "upper_%s" : "lower_%s", name); 7728 sysfs_remove_link(&(dev->dev.kobj), linkname); 7729} 7730 7731static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev, 7732 struct net_device *adj_dev, 7733 struct list_head *dev_list) 7734{ 7735 return (dev_list == &dev->adj_list.upper || 7736 dev_list == &dev->adj_list.lower) && 7737 net_eq(dev_net(dev), dev_net(adj_dev)); 7738} 7739 7740static int __netdev_adjacent_dev_insert(struct net_device *dev, 7741 struct net_device *adj_dev, 7742 struct list_head *dev_list, 7743 void *private, bool master) 7744{ 7745 struct netdev_adjacent *adj; 7746 int ret; 7747 7748 adj = __netdev_find_adj(adj_dev, dev_list); 7749 7750 if (adj) { 7751 adj->ref_nr += 1; 7752 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n", 7753 dev->name, adj_dev->name, adj->ref_nr); 7754 7755 return 0; 7756 } 7757 7758 adj = kmalloc(sizeof(*adj), GFP_KERNEL); 7759 if (!adj) 7760 return -ENOMEM; 7761 7762 adj->dev = adj_dev; 7763 adj->master = master; 7764 adj->ref_nr = 1; 7765 adj->private = private; 7766 adj->ignore = false; 7767 netdev_hold(adj_dev, &adj->dev_tracker, GFP_KERNEL); 7768 7769 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n", 7770 dev->name, adj_dev->name, adj->ref_nr, adj_dev->name); 7771 7772 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) { 7773 ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list); 7774 if (ret) 7775 goto free_adj; 7776 } 7777 7778 /* Ensure that master link is always the first item in list. */ 7779 if (master) { 7780 ret = sysfs_create_link(&(dev->dev.kobj), 7781 &(adj_dev->dev.kobj), "master"); 7782 if (ret) 7783 goto remove_symlinks; 7784 7785 list_add_rcu(&adj->list, dev_list); 7786 } else { 7787 list_add_tail_rcu(&adj->list, dev_list); 7788 } 7789 7790 return 0; 7791 7792remove_symlinks: 7793 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) 7794 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list); 7795free_adj: 7796 netdev_put(adj_dev, &adj->dev_tracker); 7797 kfree(adj); 7798 7799 return ret; 7800} 7801 7802static void __netdev_adjacent_dev_remove(struct net_device *dev, 7803 struct net_device *adj_dev, 7804 u16 ref_nr, 7805 struct list_head *dev_list) 7806{ 7807 struct netdev_adjacent *adj; 7808 7809 pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n", 7810 dev->name, adj_dev->name, ref_nr); 7811 7812 adj = __netdev_find_adj(adj_dev, dev_list); 7813 7814 if (!adj) { 7815 pr_err("Adjacency does not exist for device %s from %s\n", 7816 dev->name, adj_dev->name); 7817 WARN_ON(1); 7818 return; 7819 } 7820 7821 if (adj->ref_nr > ref_nr) { 7822 pr_debug("adjacency: %s to %s ref_nr - %d = %d\n", 7823 dev->name, adj_dev->name, ref_nr, 7824 adj->ref_nr - ref_nr); 7825 adj->ref_nr -= ref_nr; 7826 return; 7827 } 7828 7829 if (adj->master) 7830 sysfs_remove_link(&(dev->dev.kobj), "master"); 7831 7832 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) 7833 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list); 7834 7835 list_del_rcu(&adj->list); 7836 pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n", 7837 adj_dev->name, dev->name, adj_dev->name); 7838 netdev_put(adj_dev, &adj->dev_tracker); 7839 kfree_rcu(adj, rcu); 7840} 7841 7842static int __netdev_adjacent_dev_link_lists(struct net_device *dev, 7843 struct net_device *upper_dev, 7844 struct list_head *up_list, 7845 struct list_head *down_list, 7846 void *private, bool master) 7847{ 7848 int ret; 7849 7850 ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list, 7851 private, master); 7852 if (ret) 7853 return ret; 7854 7855 ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list, 7856 private, false); 7857 if (ret) { 7858 __netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list); 7859 return ret; 7860 } 7861 7862 return 0; 7863} 7864 7865static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev, 7866 struct net_device *upper_dev, 7867 u16 ref_nr, 7868 struct list_head *up_list, 7869 struct list_head *down_list) 7870{ 7871 __netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list); 7872 __netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list); 7873} 7874 7875static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev, 7876 struct net_device *upper_dev, 7877 void *private, bool master) 7878{ 7879 return __netdev_adjacent_dev_link_lists(dev, upper_dev, 7880 &dev->adj_list.upper, 7881 &upper_dev->adj_list.lower, 7882 private, master); 7883} 7884 7885static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev, 7886 struct net_device *upper_dev) 7887{ 7888 __netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1, 7889 &dev->adj_list.upper, 7890 &upper_dev->adj_list.lower); 7891} 7892 7893static int __netdev_upper_dev_link(struct net_device *dev, 7894 struct net_device *upper_dev, bool master, 7895 void *upper_priv, void *upper_info, 7896 struct netdev_nested_priv *priv, 7897 struct netlink_ext_ack *extack) 7898{ 7899 struct netdev_notifier_changeupper_info changeupper_info = { 7900 .info = { 7901 .dev = dev, 7902 .extack = extack, 7903 }, 7904 .upper_dev = upper_dev, 7905 .master = master, 7906 .linking = true, 7907 .upper_info = upper_info, 7908 }; 7909 struct net_device *master_dev; 7910 int ret = 0; 7911 7912 ASSERT_RTNL(); 7913 7914 if (dev == upper_dev) 7915 return -EBUSY; 7916 7917 /* To prevent loops, check if dev is not upper device to upper_dev. */ 7918 if (__netdev_has_upper_dev(upper_dev, dev)) 7919 return -EBUSY; 7920 7921 if ((dev->lower_level + upper_dev->upper_level) > MAX_NEST_DEV) 7922 return -EMLINK; 7923 7924 if (!master) { 7925 if (__netdev_has_upper_dev(dev, upper_dev)) 7926 return -EEXIST; 7927 } else { 7928 master_dev = __netdev_master_upper_dev_get(dev); 7929 if (master_dev) 7930 return master_dev == upper_dev ? -EEXIST : -EBUSY; 7931 } 7932 7933 ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER, 7934 &changeupper_info.info); 7935 ret = notifier_to_errno(ret); 7936 if (ret) 7937 return ret; 7938 7939 ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv, 7940 master); 7941 if (ret) 7942 return ret; 7943 7944 ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER, 7945 &changeupper_info.info); 7946 ret = notifier_to_errno(ret); 7947 if (ret) 7948 goto rollback; 7949 7950 __netdev_update_upper_level(dev, NULL); 7951 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL); 7952 7953 __netdev_update_lower_level(upper_dev, priv); 7954 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level, 7955 priv); 7956 7957 return 0; 7958 7959rollback: 7960 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev); 7961 7962 return ret; 7963} 7964 7965/** 7966 * netdev_upper_dev_link - Add a link to the upper device 7967 * @dev: device 7968 * @upper_dev: new upper device 7969 * @extack: netlink extended ack 7970 * 7971 * Adds a link to device which is upper to this one. The caller must hold 7972 * the RTNL lock. On a failure a negative errno code is returned. 7973 * On success the reference counts are adjusted and the function 7974 * returns zero. 7975 */ 7976int netdev_upper_dev_link(struct net_device *dev, 7977 struct net_device *upper_dev, 7978 struct netlink_ext_ack *extack) 7979{ 7980 struct netdev_nested_priv priv = { 7981 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO, 7982 .data = NULL, 7983 }; 7984 7985 return __netdev_upper_dev_link(dev, upper_dev, false, 7986 NULL, NULL, &priv, extack); 7987} 7988EXPORT_SYMBOL(netdev_upper_dev_link); 7989 7990/** 7991 * netdev_master_upper_dev_link - Add a master link to the upper device 7992 * @dev: device 7993 * @upper_dev: new upper device 7994 * @upper_priv: upper device private 7995 * @upper_info: upper info to be passed down via notifier 7996 * @extack: netlink extended ack 7997 * 7998 * Adds a link to device which is upper to this one. In this case, only 7999 * one master upper device can be linked, although other non-master devices 8000 * might be linked as well. The caller must hold the RTNL lock. 8001 * On a failure a negative errno code is returned. On success the reference 8002 * counts are adjusted and the function returns zero. 8003 */ 8004int netdev_master_upper_dev_link(struct net_device *dev, 8005 struct net_device *upper_dev, 8006 void *upper_priv, void *upper_info, 8007 struct netlink_ext_ack *extack) 8008{ 8009 struct netdev_nested_priv priv = { 8010 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO, 8011 .data = NULL, 8012 }; 8013 8014 return __netdev_upper_dev_link(dev, upper_dev, true, 8015 upper_priv, upper_info, &priv, extack); 8016} 8017EXPORT_SYMBOL(netdev_master_upper_dev_link); 8018 8019static void __netdev_upper_dev_unlink(struct net_device *dev, 8020 struct net_device *upper_dev, 8021 struct netdev_nested_priv *priv) 8022{ 8023 struct netdev_notifier_changeupper_info changeupper_info = { 8024 .info = { 8025 .dev = dev, 8026 }, 8027 .upper_dev = upper_dev, 8028 .linking = false, 8029 }; 8030 8031 ASSERT_RTNL(); 8032 8033 changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev; 8034 8035 call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER, 8036 &changeupper_info.info); 8037 8038 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev); 8039 8040 call_netdevice_notifiers_info(NETDEV_CHANGEUPPER, 8041 &changeupper_info.info); 8042 8043 __netdev_update_upper_level(dev, NULL); 8044 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL); 8045 8046 __netdev_update_lower_level(upper_dev, priv); 8047 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level, 8048 priv); 8049} 8050 8051/** 8052 * netdev_upper_dev_unlink - Removes a link to upper device 8053 * @dev: device 8054 * @upper_dev: new upper device 8055 * 8056 * Removes a link to device which is upper to this one. The caller must hold 8057 * the RTNL lock. 8058 */ 8059void netdev_upper_dev_unlink(struct net_device *dev, 8060 struct net_device *upper_dev) 8061{ 8062 struct netdev_nested_priv priv = { 8063 .flags = NESTED_SYNC_TODO, 8064 .data = NULL, 8065 }; 8066 8067 __netdev_upper_dev_unlink(dev, upper_dev, &priv); 8068} 8069EXPORT_SYMBOL(netdev_upper_dev_unlink); 8070 8071static void __netdev_adjacent_dev_set(struct net_device *upper_dev, 8072 struct net_device *lower_dev, 8073 bool val) 8074{ 8075 struct netdev_adjacent *adj; 8076 8077 adj = __netdev_find_adj(lower_dev, &upper_dev->adj_list.lower); 8078 if (adj) 8079 adj->ignore = val; 8080 8081 adj = __netdev_find_adj(upper_dev, &lower_dev->adj_list.upper); 8082 if (adj) 8083 adj->ignore = val; 8084} 8085 8086static void netdev_adjacent_dev_disable(struct net_device *upper_dev, 8087 struct net_device *lower_dev) 8088{ 8089 __netdev_adjacent_dev_set(upper_dev, lower_dev, true); 8090} 8091 8092static void netdev_adjacent_dev_enable(struct net_device *upper_dev, 8093 struct net_device *lower_dev) 8094{ 8095 __netdev_adjacent_dev_set(upper_dev, lower_dev, false); 8096} 8097 8098int netdev_adjacent_change_prepare(struct net_device *old_dev, 8099 struct net_device *new_dev, 8100 struct net_device *dev, 8101 struct netlink_ext_ack *extack) 8102{ 8103 struct netdev_nested_priv priv = { 8104 .flags = 0, 8105 .data = NULL, 8106 }; 8107 int err; 8108 8109 if (!new_dev) 8110 return 0; 8111 8112 if (old_dev && new_dev != old_dev) 8113 netdev_adjacent_dev_disable(dev, old_dev); 8114 err = __netdev_upper_dev_link(new_dev, dev, false, NULL, NULL, &priv, 8115 extack); 8116 if (err) { 8117 if (old_dev && new_dev != old_dev) 8118 netdev_adjacent_dev_enable(dev, old_dev); 8119 return err; 8120 } 8121 8122 return 0; 8123} 8124EXPORT_SYMBOL(netdev_adjacent_change_prepare); 8125 8126void netdev_adjacent_change_commit(struct net_device *old_dev, 8127 struct net_device *new_dev, 8128 struct net_device *dev) 8129{ 8130 struct netdev_nested_priv priv = { 8131 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO, 8132 .data = NULL, 8133 }; 8134 8135 if (!new_dev || !old_dev) 8136 return; 8137 8138 if (new_dev == old_dev) 8139 return; 8140 8141 netdev_adjacent_dev_enable(dev, old_dev); 8142 __netdev_upper_dev_unlink(old_dev, dev, &priv); 8143} 8144EXPORT_SYMBOL(netdev_adjacent_change_commit); 8145 8146void netdev_adjacent_change_abort(struct net_device *old_dev, 8147 struct net_device *new_dev, 8148 struct net_device *dev) 8149{ 8150 struct netdev_nested_priv priv = { 8151 .flags = 0, 8152 .data = NULL, 8153 }; 8154 8155 if (!new_dev) 8156 return; 8157 8158 if (old_dev && new_dev != old_dev) 8159 netdev_adjacent_dev_enable(dev, old_dev); 8160 8161 __netdev_upper_dev_unlink(new_dev, dev, &priv); 8162} 8163EXPORT_SYMBOL(netdev_adjacent_change_abort); 8164 8165/** 8166 * netdev_bonding_info_change - Dispatch event about slave change 8167 * @dev: device 8168 * @bonding_info: info to dispatch 8169 * 8170 * Send NETDEV_BONDING_INFO to netdev notifiers with info. 8171 * The caller must hold the RTNL lock. 8172 */ 8173void netdev_bonding_info_change(struct net_device *dev, 8174 struct netdev_bonding_info *bonding_info) 8175{ 8176 struct netdev_notifier_bonding_info info = { 8177 .info.dev = dev, 8178 }; 8179 8180 memcpy(&info.bonding_info, bonding_info, 8181 sizeof(struct netdev_bonding_info)); 8182 call_netdevice_notifiers_info(NETDEV_BONDING_INFO, 8183 &info.info); 8184} 8185EXPORT_SYMBOL(netdev_bonding_info_change); 8186 8187static int netdev_offload_xstats_enable_l3(struct net_device *dev, 8188 struct netlink_ext_ack *extack) 8189{ 8190 struct netdev_notifier_offload_xstats_info info = { 8191 .info.dev = dev, 8192 .info.extack = extack, 8193 .type = NETDEV_OFFLOAD_XSTATS_TYPE_L3, 8194 }; 8195 int err; 8196 int rc; 8197 8198 dev->offload_xstats_l3 = kzalloc(sizeof(*dev->offload_xstats_l3), 8199 GFP_KERNEL); 8200 if (!dev->offload_xstats_l3) 8201 return -ENOMEM; 8202 8203 rc = call_netdevice_notifiers_info_robust(NETDEV_OFFLOAD_XSTATS_ENABLE, 8204 NETDEV_OFFLOAD_XSTATS_DISABLE, 8205 &info.info); 8206 err = notifier_to_errno(rc); 8207 if (err) 8208 goto free_stats; 8209 8210 return 0; 8211 8212free_stats: 8213 kfree(dev->offload_xstats_l3); 8214 dev->offload_xstats_l3 = NULL; 8215 return err; 8216} 8217 8218int netdev_offload_xstats_enable(struct net_device *dev, 8219 enum netdev_offload_xstats_type type, 8220 struct netlink_ext_ack *extack) 8221{ 8222 ASSERT_RTNL(); 8223 8224 if (netdev_offload_xstats_enabled(dev, type)) 8225 return -EALREADY; 8226 8227 switch (type) { 8228 case NETDEV_OFFLOAD_XSTATS_TYPE_L3: 8229 return netdev_offload_xstats_enable_l3(dev, extack); 8230 } 8231 8232 WARN_ON(1); 8233 return -EINVAL; 8234} 8235EXPORT_SYMBOL(netdev_offload_xstats_enable); 8236 8237static void netdev_offload_xstats_disable_l3(struct net_device *dev) 8238{ 8239 struct netdev_notifier_offload_xstats_info info = { 8240 .info.dev = dev, 8241 .type = NETDEV_OFFLOAD_XSTATS_TYPE_L3, 8242 }; 8243 8244 call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_DISABLE, 8245 &info.info); 8246 kfree(dev->offload_xstats_l3); 8247 dev->offload_xstats_l3 = NULL; 8248} 8249 8250int netdev_offload_xstats_disable(struct net_device *dev, 8251 enum netdev_offload_xstats_type type) 8252{ 8253 ASSERT_RTNL(); 8254 8255 if (!netdev_offload_xstats_enabled(dev, type)) 8256 return -EALREADY; 8257 8258 switch (type) { 8259 case NETDEV_OFFLOAD_XSTATS_TYPE_L3: 8260 netdev_offload_xstats_disable_l3(dev); 8261 return 0; 8262 } 8263 8264 WARN_ON(1); 8265 return -EINVAL; 8266} 8267EXPORT_SYMBOL(netdev_offload_xstats_disable); 8268 8269static void netdev_offload_xstats_disable_all(struct net_device *dev) 8270{ 8271 netdev_offload_xstats_disable(dev, NETDEV_OFFLOAD_XSTATS_TYPE_L3); 8272} 8273 8274static struct rtnl_hw_stats64 * 8275netdev_offload_xstats_get_ptr(const struct net_device *dev, 8276 enum netdev_offload_xstats_type type) 8277{ 8278 switch (type) { 8279 case NETDEV_OFFLOAD_XSTATS_TYPE_L3: 8280 return dev->offload_xstats_l3; 8281 } 8282 8283 WARN_ON(1); 8284 return NULL; 8285} 8286 8287bool netdev_offload_xstats_enabled(const struct net_device *dev, 8288 enum netdev_offload_xstats_type type) 8289{ 8290 ASSERT_RTNL(); 8291 8292 return netdev_offload_xstats_get_ptr(dev, type); 8293} 8294EXPORT_SYMBOL(netdev_offload_xstats_enabled); 8295 8296struct netdev_notifier_offload_xstats_ru { 8297 bool used; 8298}; 8299 8300struct netdev_notifier_offload_xstats_rd { 8301 struct rtnl_hw_stats64 stats; 8302 bool used; 8303}; 8304 8305static void netdev_hw_stats64_add(struct rtnl_hw_stats64 *dest, 8306 const struct rtnl_hw_stats64 *src) 8307{ 8308 dest->rx_packets += src->rx_packets; 8309 dest->tx_packets += src->tx_packets; 8310 dest->rx_bytes += src->rx_bytes; 8311 dest->tx_bytes += src->tx_bytes; 8312 dest->rx_errors += src->rx_errors; 8313 dest->tx_errors += src->tx_errors; 8314 dest->rx_dropped += src->rx_dropped; 8315 dest->tx_dropped += src->tx_dropped; 8316 dest->multicast += src->multicast; 8317} 8318 8319static int netdev_offload_xstats_get_used(struct net_device *dev, 8320 enum netdev_offload_xstats_type type, 8321 bool *p_used, 8322 struct netlink_ext_ack *extack) 8323{ 8324 struct netdev_notifier_offload_xstats_ru report_used = {}; 8325 struct netdev_notifier_offload_xstats_info info = { 8326 .info.dev = dev, 8327 .info.extack = extack, 8328 .type = type, 8329 .report_used = &report_used, 8330 }; 8331 int rc; 8332 8333 WARN_ON(!netdev_offload_xstats_enabled(dev, type)); 8334 rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_USED, 8335 &info.info); 8336 *p_used = report_used.used; 8337 return notifier_to_errno(rc); 8338} 8339 8340static int netdev_offload_xstats_get_stats(struct net_device *dev, 8341 enum netdev_offload_xstats_type type, 8342 struct rtnl_hw_stats64 *p_stats, 8343 bool *p_used, 8344 struct netlink_ext_ack *extack) 8345{ 8346 struct netdev_notifier_offload_xstats_rd report_delta = {}; 8347 struct netdev_notifier_offload_xstats_info info = { 8348 .info.dev = dev, 8349 .info.extack = extack, 8350 .type = type, 8351 .report_delta = &report_delta, 8352 }; 8353 struct rtnl_hw_stats64 *stats; 8354 int rc; 8355 8356 stats = netdev_offload_xstats_get_ptr(dev, type); 8357 if (WARN_ON(!stats)) 8358 return -EINVAL; 8359 8360 rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_DELTA, 8361 &info.info); 8362 8363 /* Cache whatever we got, even if there was an error, otherwise the 8364 * successful stats retrievals would get lost. 8365 */ 8366 netdev_hw_stats64_add(stats, &report_delta.stats); 8367 8368 if (p_stats) 8369 *p_stats = *stats; 8370 *p_used = report_delta.used; 8371 8372 return notifier_to_errno(rc); 8373} 8374 8375int netdev_offload_xstats_get(struct net_device *dev, 8376 enum netdev_offload_xstats_type type, 8377 struct rtnl_hw_stats64 *p_stats, bool *p_used, 8378 struct netlink_ext_ack *extack) 8379{ 8380 ASSERT_RTNL(); 8381 8382 if (p_stats) 8383 return netdev_offload_xstats_get_stats(dev, type, p_stats, 8384 p_used, extack); 8385 else 8386 return netdev_offload_xstats_get_used(dev, type, p_used, 8387 extack); 8388} 8389EXPORT_SYMBOL(netdev_offload_xstats_get); 8390 8391void 8392netdev_offload_xstats_report_delta(struct netdev_notifier_offload_xstats_rd *report_delta, 8393 const struct rtnl_hw_stats64 *stats) 8394{ 8395 report_delta->used = true; 8396 netdev_hw_stats64_add(&report_delta->stats, stats); 8397} 8398EXPORT_SYMBOL(netdev_offload_xstats_report_delta); 8399 8400void 8401netdev_offload_xstats_report_used(struct netdev_notifier_offload_xstats_ru *report_used) 8402{ 8403 report_used->used = true; 8404} 8405EXPORT_SYMBOL(netdev_offload_xstats_report_used); 8406 8407void netdev_offload_xstats_push_delta(struct net_device *dev, 8408 enum netdev_offload_xstats_type type, 8409 const struct rtnl_hw_stats64 *p_stats) 8410{ 8411 struct rtnl_hw_stats64 *stats; 8412 8413 ASSERT_RTNL(); 8414 8415 stats = netdev_offload_xstats_get_ptr(dev, type); 8416 if (WARN_ON(!stats)) 8417 return; 8418 8419 netdev_hw_stats64_add(stats, p_stats); 8420} 8421EXPORT_SYMBOL(netdev_offload_xstats_push_delta); 8422 8423/** 8424 * netdev_get_xmit_slave - Get the xmit slave of master device 8425 * @dev: device 8426 * @skb: The packet 8427 * @all_slaves: assume all the slaves are active 8428 * 8429 * The reference counters are not incremented so the caller must be 8430 * careful with locks. The caller must hold RCU lock. 8431 * %NULL is returned if no slave is found. 8432 */ 8433 8434struct net_device *netdev_get_xmit_slave(struct net_device *dev, 8435 struct sk_buff *skb, 8436 bool all_slaves) 8437{ 8438 const struct net_device_ops *ops = dev->netdev_ops; 8439 8440 if (!ops->ndo_get_xmit_slave) 8441 return NULL; 8442 return ops->ndo_get_xmit_slave(dev, skb, all_slaves); 8443} 8444EXPORT_SYMBOL(netdev_get_xmit_slave); 8445 8446static struct net_device *netdev_sk_get_lower_dev(struct net_device *dev, 8447 struct sock *sk) 8448{ 8449 const struct net_device_ops *ops = dev->netdev_ops; 8450 8451 if (!ops->ndo_sk_get_lower_dev) 8452 return NULL; 8453 return ops->ndo_sk_get_lower_dev(dev, sk); 8454} 8455 8456/** 8457 * netdev_sk_get_lowest_dev - Get the lowest device in chain given device and socket 8458 * @dev: device 8459 * @sk: the socket 8460 * 8461 * %NULL is returned if no lower device is found. 8462 */ 8463 8464struct net_device *netdev_sk_get_lowest_dev(struct net_device *dev, 8465 struct sock *sk) 8466{ 8467 struct net_device *lower; 8468 8469 lower = netdev_sk_get_lower_dev(dev, sk); 8470 while (lower) { 8471 dev = lower; 8472 lower = netdev_sk_get_lower_dev(dev, sk); 8473 } 8474 8475 return dev; 8476} 8477EXPORT_SYMBOL(netdev_sk_get_lowest_dev); 8478 8479static void netdev_adjacent_add_links(struct net_device *dev) 8480{ 8481 struct netdev_adjacent *iter; 8482 8483 struct net *net = dev_net(dev); 8484 8485 list_for_each_entry(iter, &dev->adj_list.upper, list) { 8486 if (!net_eq(net, dev_net(iter->dev))) 8487 continue; 8488 netdev_adjacent_sysfs_add(iter->dev, dev, 8489 &iter->dev->adj_list.lower); 8490 netdev_adjacent_sysfs_add(dev, iter->dev, 8491 &dev->adj_list.upper); 8492 } 8493 8494 list_for_each_entry(iter, &dev->adj_list.lower, list) { 8495 if (!net_eq(net, dev_net(iter->dev))) 8496 continue; 8497 netdev_adjacent_sysfs_add(iter->dev, dev, 8498 &iter->dev->adj_list.upper); 8499 netdev_adjacent_sysfs_add(dev, iter->dev, 8500 &dev->adj_list.lower); 8501 } 8502} 8503 8504static void netdev_adjacent_del_links(struct net_device *dev) 8505{ 8506 struct netdev_adjacent *iter; 8507 8508 struct net *net = dev_net(dev); 8509 8510 list_for_each_entry(iter, &dev->adj_list.upper, list) { 8511 if (!net_eq(net, dev_net(iter->dev))) 8512 continue; 8513 netdev_adjacent_sysfs_del(iter->dev, dev->name, 8514 &iter->dev->adj_list.lower); 8515 netdev_adjacent_sysfs_del(dev, iter->dev->name, 8516 &dev->adj_list.upper); 8517 } 8518 8519 list_for_each_entry(iter, &dev->adj_list.lower, list) { 8520 if (!net_eq(net, dev_net(iter->dev))) 8521 continue; 8522 netdev_adjacent_sysfs_del(iter->dev, dev->name, 8523 &iter->dev->adj_list.upper); 8524 netdev_adjacent_sysfs_del(dev, iter->dev->name, 8525 &dev->adj_list.lower); 8526 } 8527} 8528 8529void netdev_adjacent_rename_links(struct net_device *dev, char *oldname) 8530{ 8531 struct netdev_adjacent *iter; 8532 8533 struct net *net = dev_net(dev); 8534 8535 list_for_each_entry(iter, &dev->adj_list.upper, list) { 8536 if (!net_eq(net, dev_net(iter->dev))) 8537 continue; 8538 netdev_adjacent_sysfs_del(iter->dev, oldname, 8539 &iter->dev->adj_list.lower); 8540 netdev_adjacent_sysfs_add(iter->dev, dev, 8541 &iter->dev->adj_list.lower); 8542 } 8543 8544 list_for_each_entry(iter, &dev->adj_list.lower, list) { 8545 if (!net_eq(net, dev_net(iter->dev))) 8546 continue; 8547 netdev_adjacent_sysfs_del(iter->dev, oldname, 8548 &iter->dev->adj_list.upper); 8549 netdev_adjacent_sysfs_add(iter->dev, dev, 8550 &iter->dev->adj_list.upper); 8551 } 8552} 8553 8554void *netdev_lower_dev_get_private(struct net_device *dev, 8555 struct net_device *lower_dev) 8556{ 8557 struct netdev_adjacent *lower; 8558 8559 if (!lower_dev) 8560 return NULL; 8561 lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower); 8562 if (!lower) 8563 return NULL; 8564 8565 return lower->private; 8566} 8567EXPORT_SYMBOL(netdev_lower_dev_get_private); 8568 8569 8570/** 8571 * netdev_lower_state_changed - Dispatch event about lower device state change 8572 * @lower_dev: device 8573 * @lower_state_info: state to dispatch 8574 * 8575 * Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info. 8576 * The caller must hold the RTNL lock. 8577 */ 8578void netdev_lower_state_changed(struct net_device *lower_dev, 8579 void *lower_state_info) 8580{ 8581 struct netdev_notifier_changelowerstate_info changelowerstate_info = { 8582 .info.dev = lower_dev, 8583 }; 8584 8585 ASSERT_RTNL(); 8586 changelowerstate_info.lower_state_info = lower_state_info; 8587 call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE, 8588 &changelowerstate_info.info); 8589} 8590EXPORT_SYMBOL(netdev_lower_state_changed); 8591 8592static void dev_change_rx_flags(struct net_device *dev, int flags) 8593{ 8594 const struct net_device_ops *ops = dev->netdev_ops; 8595 8596 if (ops->ndo_change_rx_flags) 8597 ops->ndo_change_rx_flags(dev, flags); 8598} 8599 8600static int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify) 8601{ 8602 unsigned int old_flags = dev->flags; 8603 unsigned int promiscuity, flags; 8604 kuid_t uid; 8605 kgid_t gid; 8606 8607 ASSERT_RTNL(); 8608 8609 promiscuity = dev->promiscuity + inc; 8610 if (promiscuity == 0) { 8611 /* 8612 * Avoid overflow. 8613 * If inc causes overflow, untouch promisc and return error. 8614 */ 8615 if (unlikely(inc > 0)) { 8616 netdev_warn(dev, "promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n"); 8617 return -EOVERFLOW; 8618 } 8619 flags = old_flags & ~IFF_PROMISC; 8620 } else { 8621 flags = old_flags | IFF_PROMISC; 8622 } 8623 WRITE_ONCE(dev->promiscuity, promiscuity); 8624 if (flags != old_flags) { 8625 WRITE_ONCE(dev->flags, flags); 8626 netdev_info(dev, "%s promiscuous mode\n", 8627 dev->flags & IFF_PROMISC ? "entered" : "left"); 8628 if (audit_enabled) { 8629 current_uid_gid(&uid, &gid); 8630 audit_log(audit_context(), GFP_ATOMIC, 8631 AUDIT_ANOM_PROMISCUOUS, 8632 "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u", 8633 dev->name, (dev->flags & IFF_PROMISC), 8634 (old_flags & IFF_PROMISC), 8635 from_kuid(&init_user_ns, audit_get_loginuid(current)), 8636 from_kuid(&init_user_ns, uid), 8637 from_kgid(&init_user_ns, gid), 8638 audit_get_sessionid(current)); 8639 } 8640 8641 dev_change_rx_flags(dev, IFF_PROMISC); 8642 } 8643 if (notify) 8644 __dev_notify_flags(dev, old_flags, IFF_PROMISC, 0, NULL); 8645 return 0; 8646} 8647 8648/** 8649 * dev_set_promiscuity - update promiscuity count on a device 8650 * @dev: device 8651 * @inc: modifier 8652 * 8653 * Add or remove promiscuity from a device. While the count in the device 8654 * remains above zero the interface remains promiscuous. Once it hits zero 8655 * the device reverts back to normal filtering operation. A negative inc 8656 * value is used to drop promiscuity on the device. 8657 * Return 0 if successful or a negative errno code on error. 8658 */ 8659int dev_set_promiscuity(struct net_device *dev, int inc) 8660{ 8661 unsigned int old_flags = dev->flags; 8662 int err; 8663 8664 err = __dev_set_promiscuity(dev, inc, true); 8665 if (err < 0) 8666 return err; 8667 if (dev->flags != old_flags) 8668 dev_set_rx_mode(dev); 8669 return err; 8670} 8671EXPORT_SYMBOL(dev_set_promiscuity); 8672 8673static int __dev_set_allmulti(struct net_device *dev, int inc, bool notify) 8674{ 8675 unsigned int old_flags = dev->flags, old_gflags = dev->gflags; 8676 unsigned int allmulti, flags; 8677 8678 ASSERT_RTNL(); 8679 8680 allmulti = dev->allmulti + inc; 8681 if (allmulti == 0) { 8682 /* 8683 * Avoid overflow. 8684 * If inc causes overflow, untouch allmulti and return error. 8685 */ 8686 if (unlikely(inc > 0)) { 8687 netdev_warn(dev, "allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n"); 8688 return -EOVERFLOW; 8689 } 8690 flags = old_flags & ~IFF_ALLMULTI; 8691 } else { 8692 flags = old_flags | IFF_ALLMULTI; 8693 } 8694 WRITE_ONCE(dev->allmulti, allmulti); 8695 if (flags != old_flags) { 8696 WRITE_ONCE(dev->flags, flags); 8697 netdev_info(dev, "%s allmulticast mode\n", 8698 dev->flags & IFF_ALLMULTI ? "entered" : "left"); 8699 dev_change_rx_flags(dev, IFF_ALLMULTI); 8700 dev_set_rx_mode(dev); 8701 if (notify) 8702 __dev_notify_flags(dev, old_flags, 8703 dev->gflags ^ old_gflags, 0, NULL); 8704 } 8705 return 0; 8706} 8707 8708/** 8709 * dev_set_allmulti - update allmulti count on a device 8710 * @dev: device 8711 * @inc: modifier 8712 * 8713 * Add or remove reception of all multicast frames to a device. While the 8714 * count in the device remains above zero the interface remains listening 8715 * to all interfaces. Once it hits zero the device reverts back to normal 8716 * filtering operation. A negative @inc value is used to drop the counter 8717 * when releasing a resource needing all multicasts. 8718 * Return 0 if successful or a negative errno code on error. 8719 */ 8720 8721int dev_set_allmulti(struct net_device *dev, int inc) 8722{ 8723 return __dev_set_allmulti(dev, inc, true); 8724} 8725EXPORT_SYMBOL(dev_set_allmulti); 8726 8727/* 8728 * Upload unicast and multicast address lists to device and 8729 * configure RX filtering. When the device doesn't support unicast 8730 * filtering it is put in promiscuous mode while unicast addresses 8731 * are present. 8732 */ 8733void __dev_set_rx_mode(struct net_device *dev) 8734{ 8735 const struct net_device_ops *ops = dev->netdev_ops; 8736 8737 /* dev_open will call this function so the list will stay sane. */ 8738 if (!(dev->flags&IFF_UP)) 8739 return; 8740 8741 if (!netif_device_present(dev)) 8742 return; 8743 8744 if (!(dev->priv_flags & IFF_UNICAST_FLT)) { 8745 /* Unicast addresses changes may only happen under the rtnl, 8746 * therefore calling __dev_set_promiscuity here is safe. 8747 */ 8748 if (!netdev_uc_empty(dev) && !dev->uc_promisc) { 8749 __dev_set_promiscuity(dev, 1, false); 8750 dev->uc_promisc = true; 8751 } else if (netdev_uc_empty(dev) && dev->uc_promisc) { 8752 __dev_set_promiscuity(dev, -1, false); 8753 dev->uc_promisc = false; 8754 } 8755 } 8756 8757 if (ops->ndo_set_rx_mode) 8758 ops->ndo_set_rx_mode(dev); 8759} 8760 8761void dev_set_rx_mode(struct net_device *dev) 8762{ 8763 netif_addr_lock_bh(dev); 8764 __dev_set_rx_mode(dev); 8765 netif_addr_unlock_bh(dev); 8766} 8767 8768/** 8769 * dev_get_flags - get flags reported to userspace 8770 * @dev: device 8771 * 8772 * Get the combination of flag bits exported through APIs to userspace. 8773 */ 8774unsigned int dev_get_flags(const struct net_device *dev) 8775{ 8776 unsigned int flags; 8777 8778 flags = (READ_ONCE(dev->flags) & ~(IFF_PROMISC | 8779 IFF_ALLMULTI | 8780 IFF_RUNNING | 8781 IFF_LOWER_UP | 8782 IFF_DORMANT)) | 8783 (READ_ONCE(dev->gflags) & (IFF_PROMISC | 8784 IFF_ALLMULTI)); 8785 8786 if (netif_running(dev)) { 8787 if (netif_oper_up(dev)) 8788 flags |= IFF_RUNNING; 8789 if (netif_carrier_ok(dev)) 8790 flags |= IFF_LOWER_UP; 8791 if (netif_dormant(dev)) 8792 flags |= IFF_DORMANT; 8793 } 8794 8795 return flags; 8796} 8797EXPORT_SYMBOL(dev_get_flags); 8798 8799int __dev_change_flags(struct net_device *dev, unsigned int flags, 8800 struct netlink_ext_ack *extack) 8801{ 8802 unsigned int old_flags = dev->flags; 8803 int ret; 8804 8805 ASSERT_RTNL(); 8806 8807 /* 8808 * Set the flags on our device. 8809 */ 8810 8811 dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP | 8812 IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL | 8813 IFF_AUTOMEDIA)) | 8814 (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC | 8815 IFF_ALLMULTI)); 8816 8817 /* 8818 * Load in the correct multicast list now the flags have changed. 8819 */ 8820 8821 if ((old_flags ^ flags) & IFF_MULTICAST) 8822 dev_change_rx_flags(dev, IFF_MULTICAST); 8823 8824 dev_set_rx_mode(dev); 8825 8826 /* 8827 * Have we downed the interface. We handle IFF_UP ourselves 8828 * according to user attempts to set it, rather than blindly 8829 * setting it. 8830 */ 8831 8832 ret = 0; 8833 if ((old_flags ^ flags) & IFF_UP) { 8834 if (old_flags & IFF_UP) 8835 __dev_close(dev); 8836 else 8837 ret = __dev_open(dev, extack); 8838 } 8839 8840 if ((flags ^ dev->gflags) & IFF_PROMISC) { 8841 int inc = (flags & IFF_PROMISC) ? 1 : -1; 8842 unsigned int old_flags = dev->flags; 8843 8844 dev->gflags ^= IFF_PROMISC; 8845 8846 if (__dev_set_promiscuity(dev, inc, false) >= 0) 8847 if (dev->flags != old_flags) 8848 dev_set_rx_mode(dev); 8849 } 8850 8851 /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI 8852 * is important. Some (broken) drivers set IFF_PROMISC, when 8853 * IFF_ALLMULTI is requested not asking us and not reporting. 8854 */ 8855 if ((flags ^ dev->gflags) & IFF_ALLMULTI) { 8856 int inc = (flags & IFF_ALLMULTI) ? 1 : -1; 8857 8858 dev->gflags ^= IFF_ALLMULTI; 8859 __dev_set_allmulti(dev, inc, false); 8860 } 8861 8862 return ret; 8863} 8864 8865void __dev_notify_flags(struct net_device *dev, unsigned int old_flags, 8866 unsigned int gchanges, u32 portid, 8867 const struct nlmsghdr *nlh) 8868{ 8869 unsigned int changes = dev->flags ^ old_flags; 8870 8871 if (gchanges) 8872 rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC, portid, nlh); 8873 8874 if (changes & IFF_UP) { 8875 if (dev->flags & IFF_UP) 8876 call_netdevice_notifiers(NETDEV_UP, dev); 8877 else 8878 call_netdevice_notifiers(NETDEV_DOWN, dev); 8879 } 8880 8881 if (dev->flags & IFF_UP && 8882 (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) { 8883 struct netdev_notifier_change_info change_info = { 8884 .info = { 8885 .dev = dev, 8886 }, 8887 .flags_changed = changes, 8888 }; 8889 8890 call_netdevice_notifiers_info(NETDEV_CHANGE, &change_info.info); 8891 } 8892} 8893 8894/** 8895 * dev_change_flags - change device settings 8896 * @dev: device 8897 * @flags: device state flags 8898 * @extack: netlink extended ack 8899 * 8900 * Change settings on device based state flags. The flags are 8901 * in the userspace exported format. 8902 */ 8903int dev_change_flags(struct net_device *dev, unsigned int flags, 8904 struct netlink_ext_ack *extack) 8905{ 8906 int ret; 8907 unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags; 8908 8909 ret = __dev_change_flags(dev, flags, extack); 8910 if (ret < 0) 8911 return ret; 8912 8913 changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags); 8914 __dev_notify_flags(dev, old_flags, changes, 0, NULL); 8915 return ret; 8916} 8917EXPORT_SYMBOL(dev_change_flags); 8918 8919int __dev_set_mtu(struct net_device *dev, int new_mtu) 8920{ 8921 const struct net_device_ops *ops = dev->netdev_ops; 8922 8923 if (ops->ndo_change_mtu) 8924 return ops->ndo_change_mtu(dev, new_mtu); 8925 8926 /* Pairs with all the lockless reads of dev->mtu in the stack */ 8927 WRITE_ONCE(dev->mtu, new_mtu); 8928 return 0; 8929} 8930EXPORT_SYMBOL(__dev_set_mtu); 8931 8932int dev_validate_mtu(struct net_device *dev, int new_mtu, 8933 struct netlink_ext_ack *extack) 8934{ 8935 /* MTU must be positive, and in range */ 8936 if (new_mtu < 0 || new_mtu < dev->min_mtu) { 8937 NL_SET_ERR_MSG(extack, "mtu less than device minimum"); 8938 return -EINVAL; 8939 } 8940 8941 if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) { 8942 NL_SET_ERR_MSG(extack, "mtu greater than device maximum"); 8943 return -EINVAL; 8944 } 8945 return 0; 8946} 8947 8948/** 8949 * dev_set_mtu_ext - Change maximum transfer unit 8950 * @dev: device 8951 * @new_mtu: new transfer unit 8952 * @extack: netlink extended ack 8953 * 8954 * Change the maximum transfer size of the network device. 8955 */ 8956int dev_set_mtu_ext(struct net_device *dev, int new_mtu, 8957 struct netlink_ext_ack *extack) 8958{ 8959 int err, orig_mtu; 8960 8961 if (new_mtu == dev->mtu) 8962 return 0; 8963 8964 err = dev_validate_mtu(dev, new_mtu, extack); 8965 if (err) 8966 return err; 8967 8968 if (!netif_device_present(dev)) 8969 return -ENODEV; 8970 8971 err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev); 8972 err = notifier_to_errno(err); 8973 if (err) 8974 return err; 8975 8976 orig_mtu = dev->mtu; 8977 err = __dev_set_mtu(dev, new_mtu); 8978 8979 if (!err) { 8980 err = call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev, 8981 orig_mtu); 8982 err = notifier_to_errno(err); 8983 if (err) { 8984 /* setting mtu back and notifying everyone again, 8985 * so that they have a chance to revert changes. 8986 */ 8987 __dev_set_mtu(dev, orig_mtu); 8988 call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev, 8989 new_mtu); 8990 } 8991 } 8992 return err; 8993} 8994 8995int dev_set_mtu(struct net_device *dev, int new_mtu) 8996{ 8997 struct netlink_ext_ack extack; 8998 int err; 8999 9000 memset(&extack, 0, sizeof(extack)); 9001 err = dev_set_mtu_ext(dev, new_mtu, &extack); 9002 if (err && extack._msg) 9003 net_err_ratelimited("%s: %s\n", dev->name, extack._msg); 9004 return err; 9005} 9006EXPORT_SYMBOL(dev_set_mtu); 9007 9008/** 9009 * dev_change_tx_queue_len - Change TX queue length of a netdevice 9010 * @dev: device 9011 * @new_len: new tx queue length 9012 */ 9013int dev_change_tx_queue_len(struct net_device *dev, unsigned long new_len) 9014{ 9015 unsigned int orig_len = dev->tx_queue_len; 9016 int res; 9017 9018 if (new_len != (unsigned int)new_len) 9019 return -ERANGE; 9020 9021 if (new_len != orig_len) { 9022 WRITE_ONCE(dev->tx_queue_len, new_len); 9023 res = call_netdevice_notifiers(NETDEV_CHANGE_TX_QUEUE_LEN, dev); 9024 res = notifier_to_errno(res); 9025 if (res) 9026 goto err_rollback; 9027 res = dev_qdisc_change_tx_queue_len(dev); 9028 if (res) 9029 goto err_rollback; 9030 } 9031 9032 return 0; 9033 9034err_rollback: 9035 netdev_err(dev, "refused to change device tx_queue_len\n"); 9036 WRITE_ONCE(dev->tx_queue_len, orig_len); 9037 return res; 9038} 9039 9040/** 9041 * dev_set_group - Change group this device belongs to 9042 * @dev: device 9043 * @new_group: group this device should belong to 9044 */ 9045void dev_set_group(struct net_device *dev, int new_group) 9046{ 9047 dev->group = new_group; 9048} 9049 9050/** 9051 * dev_pre_changeaddr_notify - Call NETDEV_PRE_CHANGEADDR. 9052 * @dev: device 9053 * @addr: new address 9054 * @extack: netlink extended ack 9055 */ 9056int dev_pre_changeaddr_notify(struct net_device *dev, const char *addr, 9057 struct netlink_ext_ack *extack) 9058{ 9059 struct netdev_notifier_pre_changeaddr_info info = { 9060 .info.dev = dev, 9061 .info.extack = extack, 9062 .dev_addr = addr, 9063 }; 9064 int rc; 9065 9066 rc = call_netdevice_notifiers_info(NETDEV_PRE_CHANGEADDR, &info.info); 9067 return notifier_to_errno(rc); 9068} 9069EXPORT_SYMBOL(dev_pre_changeaddr_notify); 9070 9071/** 9072 * dev_set_mac_address - Change Media Access Control Address 9073 * @dev: device 9074 * @sa: new address 9075 * @extack: netlink extended ack 9076 * 9077 * Change the hardware (MAC) address of the device 9078 */ 9079int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa, 9080 struct netlink_ext_ack *extack) 9081{ 9082 const struct net_device_ops *ops = dev->netdev_ops; 9083 int err; 9084 9085 if (!ops->ndo_set_mac_address) 9086 return -EOPNOTSUPP; 9087 if (sa->sa_family != dev->type) 9088 return -EINVAL; 9089 if (!netif_device_present(dev)) 9090 return -ENODEV; 9091 err = dev_pre_changeaddr_notify(dev, sa->sa_data, extack); 9092 if (err) 9093 return err; 9094 if (memcmp(dev->dev_addr, sa->sa_data, dev->addr_len)) { 9095 err = ops->ndo_set_mac_address(dev, sa); 9096 if (err) 9097 return err; 9098 } 9099 dev->addr_assign_type = NET_ADDR_SET; 9100 call_netdevice_notifiers(NETDEV_CHANGEADDR, dev); 9101 add_device_randomness(dev->dev_addr, dev->addr_len); 9102 return 0; 9103} 9104EXPORT_SYMBOL(dev_set_mac_address); 9105 9106DECLARE_RWSEM(dev_addr_sem); 9107 9108int dev_set_mac_address_user(struct net_device *dev, struct sockaddr *sa, 9109 struct netlink_ext_ack *extack) 9110{ 9111 int ret; 9112 9113 down_write(&dev_addr_sem); 9114 ret = dev_set_mac_address(dev, sa, extack); 9115 up_write(&dev_addr_sem); 9116 return ret; 9117} 9118EXPORT_SYMBOL(dev_set_mac_address_user); 9119 9120int dev_get_mac_address(struct sockaddr *sa, struct net *net, char *dev_name) 9121{ 9122 size_t size = sizeof(sa->sa_data_min); 9123 struct net_device *dev; 9124 int ret = 0; 9125 9126 down_read(&dev_addr_sem); 9127 rcu_read_lock(); 9128 9129 dev = dev_get_by_name_rcu(net, dev_name); 9130 if (!dev) { 9131 ret = -ENODEV; 9132 goto unlock; 9133 } 9134 if (!dev->addr_len) 9135 memset(sa->sa_data, 0, size); 9136 else 9137 memcpy(sa->sa_data, dev->dev_addr, 9138 min_t(size_t, size, dev->addr_len)); 9139 sa->sa_family = dev->type; 9140 9141unlock: 9142 rcu_read_unlock(); 9143 up_read(&dev_addr_sem); 9144 return ret; 9145} 9146EXPORT_SYMBOL(dev_get_mac_address); 9147 9148/** 9149 * dev_change_carrier - Change device carrier 9150 * @dev: device 9151 * @new_carrier: new value 9152 * 9153 * Change device carrier 9154 */ 9155int dev_change_carrier(struct net_device *dev, bool new_carrier) 9156{ 9157 const struct net_device_ops *ops = dev->netdev_ops; 9158 9159 if (!ops->ndo_change_carrier) 9160 return -EOPNOTSUPP; 9161 if (!netif_device_present(dev)) 9162 return -ENODEV; 9163 return ops->ndo_change_carrier(dev, new_carrier); 9164} 9165 9166/** 9167 * dev_get_phys_port_id - Get device physical port ID 9168 * @dev: device 9169 * @ppid: port ID 9170 * 9171 * Get device physical port ID 9172 */ 9173int dev_get_phys_port_id(struct net_device *dev, 9174 struct netdev_phys_item_id *ppid) 9175{ 9176 const struct net_device_ops *ops = dev->netdev_ops; 9177 9178 if (!ops->ndo_get_phys_port_id) 9179 return -EOPNOTSUPP; 9180 return ops->ndo_get_phys_port_id(dev, ppid); 9181} 9182 9183/** 9184 * dev_get_phys_port_name - Get device physical port name 9185 * @dev: device 9186 * @name: port name 9187 * @len: limit of bytes to copy to name 9188 * 9189 * Get device physical port name 9190 */ 9191int dev_get_phys_port_name(struct net_device *dev, 9192 char *name, size_t len) 9193{ 9194 const struct net_device_ops *ops = dev->netdev_ops; 9195 int err; 9196 9197 if (ops->ndo_get_phys_port_name) { 9198 err = ops->ndo_get_phys_port_name(dev, name, len); 9199 if (err != -EOPNOTSUPP) 9200 return err; 9201 } 9202 return devlink_compat_phys_port_name_get(dev, name, len); 9203} 9204 9205/** 9206 * dev_get_port_parent_id - Get the device's port parent identifier 9207 * @dev: network device 9208 * @ppid: pointer to a storage for the port's parent identifier 9209 * @recurse: allow/disallow recursion to lower devices 9210 * 9211 * Get the devices's port parent identifier 9212 */ 9213int dev_get_port_parent_id(struct net_device *dev, 9214 struct netdev_phys_item_id *ppid, 9215 bool recurse) 9216{ 9217 const struct net_device_ops *ops = dev->netdev_ops; 9218 struct netdev_phys_item_id first = { }; 9219 struct net_device *lower_dev; 9220 struct list_head *iter; 9221 int err; 9222 9223 if (ops->ndo_get_port_parent_id) { 9224 err = ops->ndo_get_port_parent_id(dev, ppid); 9225 if (err != -EOPNOTSUPP) 9226 return err; 9227 } 9228 9229 err = devlink_compat_switch_id_get(dev, ppid); 9230 if (!recurse || err != -EOPNOTSUPP) 9231 return err; 9232 9233 netdev_for_each_lower_dev(dev, lower_dev, iter) { 9234 err = dev_get_port_parent_id(lower_dev, ppid, true); 9235 if (err) 9236 break; 9237 if (!first.id_len) 9238 first = *ppid; 9239 else if (memcmp(&first, ppid, sizeof(*ppid))) 9240 return -EOPNOTSUPP; 9241 } 9242 9243 return err; 9244} 9245EXPORT_SYMBOL(dev_get_port_parent_id); 9246 9247/** 9248 * netdev_port_same_parent_id - Indicate if two network devices have 9249 * the same port parent identifier 9250 * @a: first network device 9251 * @b: second network device 9252 */ 9253bool netdev_port_same_parent_id(struct net_device *a, struct net_device *b) 9254{ 9255 struct netdev_phys_item_id a_id = { }; 9256 struct netdev_phys_item_id b_id = { }; 9257 9258 if (dev_get_port_parent_id(a, &a_id, true) || 9259 dev_get_port_parent_id(b, &b_id, true)) 9260 return false; 9261 9262 return netdev_phys_item_id_same(&a_id, &b_id); 9263} 9264EXPORT_SYMBOL(netdev_port_same_parent_id); 9265 9266/** 9267 * dev_change_proto_down - set carrier according to proto_down. 9268 * 9269 * @dev: device 9270 * @proto_down: new value 9271 */ 9272int dev_change_proto_down(struct net_device *dev, bool proto_down) 9273{ 9274 if (!(dev->priv_flags & IFF_CHANGE_PROTO_DOWN)) 9275 return -EOPNOTSUPP; 9276 if (!netif_device_present(dev)) 9277 return -ENODEV; 9278 if (proto_down) 9279 netif_carrier_off(dev); 9280 else 9281 netif_carrier_on(dev); 9282 WRITE_ONCE(dev->proto_down, proto_down); 9283 return 0; 9284} 9285 9286/** 9287 * dev_change_proto_down_reason - proto down reason 9288 * 9289 * @dev: device 9290 * @mask: proto down mask 9291 * @value: proto down value 9292 */ 9293void dev_change_proto_down_reason(struct net_device *dev, unsigned long mask, 9294 u32 value) 9295{ 9296 u32 proto_down_reason; 9297 int b; 9298 9299 if (!mask) { 9300 proto_down_reason = value; 9301 } else { 9302 proto_down_reason = dev->proto_down_reason; 9303 for_each_set_bit(b, &mask, 32) { 9304 if (value & (1 << b)) 9305 proto_down_reason |= BIT(b); 9306 else 9307 proto_down_reason &= ~BIT(b); 9308 } 9309 } 9310 WRITE_ONCE(dev->proto_down_reason, proto_down_reason); 9311} 9312 9313struct bpf_xdp_link { 9314 struct bpf_link link; 9315 struct net_device *dev; /* protected by rtnl_lock, no refcnt held */ 9316 int flags; 9317}; 9318 9319static enum bpf_xdp_mode dev_xdp_mode(struct net_device *dev, u32 flags) 9320{ 9321 if (flags & XDP_FLAGS_HW_MODE) 9322 return XDP_MODE_HW; 9323 if (flags & XDP_FLAGS_DRV_MODE) 9324 return XDP_MODE_DRV; 9325 if (flags & XDP_FLAGS_SKB_MODE) 9326 return XDP_MODE_SKB; 9327 return dev->netdev_ops->ndo_bpf ? XDP_MODE_DRV : XDP_MODE_SKB; 9328} 9329 9330static bpf_op_t dev_xdp_bpf_op(struct net_device *dev, enum bpf_xdp_mode mode) 9331{ 9332 switch (mode) { 9333 case XDP_MODE_SKB: 9334 return generic_xdp_install; 9335 case XDP_MODE_DRV: 9336 case XDP_MODE_HW: 9337 return dev->netdev_ops->ndo_bpf; 9338 default: 9339 return NULL; 9340 } 9341} 9342 9343static struct bpf_xdp_link *dev_xdp_link(struct net_device *dev, 9344 enum bpf_xdp_mode mode) 9345{ 9346 return dev->xdp_state[mode].link; 9347} 9348 9349static struct bpf_prog *dev_xdp_prog(struct net_device *dev, 9350 enum bpf_xdp_mode mode) 9351{ 9352 struct bpf_xdp_link *link = dev_xdp_link(dev, mode); 9353 9354 if (link) 9355 return link->link.prog; 9356 return dev->xdp_state[mode].prog; 9357} 9358 9359u8 dev_xdp_prog_count(struct net_device *dev) 9360{ 9361 u8 count = 0; 9362 int i; 9363 9364 for (i = 0; i < __MAX_XDP_MODE; i++) 9365 if (dev->xdp_state[i].prog || dev->xdp_state[i].link) 9366 count++; 9367 return count; 9368} 9369EXPORT_SYMBOL_GPL(dev_xdp_prog_count); 9370 9371u32 dev_xdp_prog_id(struct net_device *dev, enum bpf_xdp_mode mode) 9372{ 9373 struct bpf_prog *prog = dev_xdp_prog(dev, mode); 9374 9375 return prog ? prog->aux->id : 0; 9376} 9377 9378static void dev_xdp_set_link(struct net_device *dev, enum bpf_xdp_mode mode, 9379 struct bpf_xdp_link *link) 9380{ 9381 dev->xdp_state[mode].link = link; 9382 dev->xdp_state[mode].prog = NULL; 9383} 9384 9385static void dev_xdp_set_prog(struct net_device *dev, enum bpf_xdp_mode mode, 9386 struct bpf_prog *prog) 9387{ 9388 dev->xdp_state[mode].link = NULL; 9389 dev->xdp_state[mode].prog = prog; 9390} 9391 9392static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode, 9393 bpf_op_t bpf_op, struct netlink_ext_ack *extack, 9394 u32 flags, struct bpf_prog *prog) 9395{ 9396 struct netdev_bpf xdp; 9397 int err; 9398 9399 memset(&xdp, 0, sizeof(xdp)); 9400 xdp.command = mode == XDP_MODE_HW ? XDP_SETUP_PROG_HW : XDP_SETUP_PROG; 9401 xdp.extack = extack; 9402 xdp.flags = flags; 9403 xdp.prog = prog; 9404 9405 /* Drivers assume refcnt is already incremented (i.e, prog pointer is 9406 * "moved" into driver), so they don't increment it on their own, but 9407 * they do decrement refcnt when program is detached or replaced. 9408 * Given net_device also owns link/prog, we need to bump refcnt here 9409 * to prevent drivers from underflowing it. 9410 */ 9411 if (prog) 9412 bpf_prog_inc(prog); 9413 err = bpf_op(dev, &xdp); 9414 if (err) { 9415 if (prog) 9416 bpf_prog_put(prog); 9417 return err; 9418 } 9419 9420 if (mode != XDP_MODE_HW) 9421 bpf_prog_change_xdp(dev_xdp_prog(dev, mode), prog); 9422 9423 return 0; 9424} 9425 9426static void dev_xdp_uninstall(struct net_device *dev) 9427{ 9428 struct bpf_xdp_link *link; 9429 struct bpf_prog *prog; 9430 enum bpf_xdp_mode mode; 9431 bpf_op_t bpf_op; 9432 9433 ASSERT_RTNL(); 9434 9435 for (mode = XDP_MODE_SKB; mode < __MAX_XDP_MODE; mode++) { 9436 prog = dev_xdp_prog(dev, mode); 9437 if (!prog) 9438 continue; 9439 9440 bpf_op = dev_xdp_bpf_op(dev, mode); 9441 if (!bpf_op) 9442 continue; 9443 9444 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL)); 9445 9446 /* auto-detach link from net device */ 9447 link = dev_xdp_link(dev, mode); 9448 if (link) 9449 link->dev = NULL; 9450 else 9451 bpf_prog_put(prog); 9452 9453 dev_xdp_set_link(dev, mode, NULL); 9454 } 9455} 9456 9457static int dev_xdp_attach(struct net_device *dev, struct netlink_ext_ack *extack, 9458 struct bpf_xdp_link *link, struct bpf_prog *new_prog, 9459 struct bpf_prog *old_prog, u32 flags) 9460{ 9461 unsigned int num_modes = hweight32(flags & XDP_FLAGS_MODES); 9462 struct bpf_prog *cur_prog; 9463 struct net_device *upper; 9464 struct list_head *iter; 9465 enum bpf_xdp_mode mode; 9466 bpf_op_t bpf_op; 9467 int err; 9468 9469 ASSERT_RTNL(); 9470 9471 /* either link or prog attachment, never both */ 9472 if (link && (new_prog || old_prog)) 9473 return -EINVAL; 9474 /* link supports only XDP mode flags */ 9475 if (link && (flags & ~XDP_FLAGS_MODES)) { 9476 NL_SET_ERR_MSG(extack, "Invalid XDP flags for BPF link attachment"); 9477 return -EINVAL; 9478 } 9479 /* just one XDP mode bit should be set, zero defaults to drv/skb mode */ 9480 if (num_modes > 1) { 9481 NL_SET_ERR_MSG(extack, "Only one XDP mode flag can be set"); 9482 return -EINVAL; 9483 } 9484 /* avoid ambiguity if offload + drv/skb mode progs are both loaded */ 9485 if (!num_modes && dev_xdp_prog_count(dev) > 1) { 9486 NL_SET_ERR_MSG(extack, 9487 "More than one program loaded, unset mode is ambiguous"); 9488 return -EINVAL; 9489 } 9490 /* old_prog != NULL implies XDP_FLAGS_REPLACE is set */ 9491 if (old_prog && !(flags & XDP_FLAGS_REPLACE)) { 9492 NL_SET_ERR_MSG(extack, "XDP_FLAGS_REPLACE is not specified"); 9493 return -EINVAL; 9494 } 9495 9496 mode = dev_xdp_mode(dev, flags); 9497 /* can't replace attached link */ 9498 if (dev_xdp_link(dev, mode)) { 9499 NL_SET_ERR_MSG(extack, "Can't replace active BPF XDP link"); 9500 return -EBUSY; 9501 } 9502 9503 /* don't allow if an upper device already has a program */ 9504 netdev_for_each_upper_dev_rcu(dev, upper, iter) { 9505 if (dev_xdp_prog_count(upper) > 0) { 9506 NL_SET_ERR_MSG(extack, "Cannot attach when an upper device already has a program"); 9507 return -EEXIST; 9508 } 9509 } 9510 9511 cur_prog = dev_xdp_prog(dev, mode); 9512 /* can't replace attached prog with link */ 9513 if (link && cur_prog) { 9514 NL_SET_ERR_MSG(extack, "Can't replace active XDP program with BPF link"); 9515 return -EBUSY; 9516 } 9517 if ((flags & XDP_FLAGS_REPLACE) && cur_prog != old_prog) { 9518 NL_SET_ERR_MSG(extack, "Active program does not match expected"); 9519 return -EEXIST; 9520 } 9521 9522 /* put effective new program into new_prog */ 9523 if (link) 9524 new_prog = link->link.prog; 9525 9526 if (new_prog) { 9527 bool offload = mode == XDP_MODE_HW; 9528 enum bpf_xdp_mode other_mode = mode == XDP_MODE_SKB 9529 ? XDP_MODE_DRV : XDP_MODE_SKB; 9530 9531 if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) && cur_prog) { 9532 NL_SET_ERR_MSG(extack, "XDP program already attached"); 9533 return -EBUSY; 9534 } 9535 if (!offload && dev_xdp_prog(dev, other_mode)) { 9536 NL_SET_ERR_MSG(extack, "Native and generic XDP can't be active at the same time"); 9537 return -EEXIST; 9538 } 9539 if (!offload && bpf_prog_is_offloaded(new_prog->aux)) { 9540 NL_SET_ERR_MSG(extack, "Using offloaded program without HW_MODE flag is not supported"); 9541 return -EINVAL; 9542 } 9543 if (bpf_prog_is_dev_bound(new_prog->aux) && !bpf_offload_dev_match(new_prog, dev)) { 9544 NL_SET_ERR_MSG(extack, "Program bound to different device"); 9545 return -EINVAL; 9546 } 9547 if (new_prog->expected_attach_type == BPF_XDP_DEVMAP) { 9548 NL_SET_ERR_MSG(extack, "BPF_XDP_DEVMAP programs can not be attached to a device"); 9549 return -EINVAL; 9550 } 9551 if (new_prog->expected_attach_type == BPF_XDP_CPUMAP) { 9552 NL_SET_ERR_MSG(extack, "BPF_XDP_CPUMAP programs can not be attached to a device"); 9553 return -EINVAL; 9554 } 9555 } 9556 9557 /* don't call drivers if the effective program didn't change */ 9558 if (new_prog != cur_prog) { 9559 bpf_op = dev_xdp_bpf_op(dev, mode); 9560 if (!bpf_op) { 9561 NL_SET_ERR_MSG(extack, "Underlying driver does not support XDP in native mode"); 9562 return -EOPNOTSUPP; 9563 } 9564 9565 err = dev_xdp_install(dev, mode, bpf_op, extack, flags, new_prog); 9566 if (err) 9567 return err; 9568 } 9569 9570 if (link) 9571 dev_xdp_set_link(dev, mode, link); 9572 else 9573 dev_xdp_set_prog(dev, mode, new_prog); 9574 if (cur_prog) 9575 bpf_prog_put(cur_prog); 9576 9577 return 0; 9578} 9579 9580static int dev_xdp_attach_link(struct net_device *dev, 9581 struct netlink_ext_ack *extack, 9582 struct bpf_xdp_link *link) 9583{ 9584 return dev_xdp_attach(dev, extack, link, NULL, NULL, link->flags); 9585} 9586 9587static int dev_xdp_detach_link(struct net_device *dev, 9588 struct netlink_ext_ack *extack, 9589 struct bpf_xdp_link *link) 9590{ 9591 enum bpf_xdp_mode mode; 9592 bpf_op_t bpf_op; 9593 9594 ASSERT_RTNL(); 9595 9596 mode = dev_xdp_mode(dev, link->flags); 9597 if (dev_xdp_link(dev, mode) != link) 9598 return -EINVAL; 9599 9600 bpf_op = dev_xdp_bpf_op(dev, mode); 9601 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL)); 9602 dev_xdp_set_link(dev, mode, NULL); 9603 return 0; 9604} 9605 9606static void bpf_xdp_link_release(struct bpf_link *link) 9607{ 9608 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link); 9609 9610 rtnl_lock(); 9611 9612 /* if racing with net_device's tear down, xdp_link->dev might be 9613 * already NULL, in which case link was already auto-detached 9614 */ 9615 if (xdp_link->dev) { 9616 WARN_ON(dev_xdp_detach_link(xdp_link->dev, NULL, xdp_link)); 9617 xdp_link->dev = NULL; 9618 } 9619 9620 rtnl_unlock(); 9621} 9622 9623static int bpf_xdp_link_detach(struct bpf_link *link) 9624{ 9625 bpf_xdp_link_release(link); 9626 return 0; 9627} 9628 9629static void bpf_xdp_link_dealloc(struct bpf_link *link) 9630{ 9631 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link); 9632 9633 kfree(xdp_link); 9634} 9635 9636static void bpf_xdp_link_show_fdinfo(const struct bpf_link *link, 9637 struct seq_file *seq) 9638{ 9639 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link); 9640 u32 ifindex = 0; 9641 9642 rtnl_lock(); 9643 if (xdp_link->dev) 9644 ifindex = xdp_link->dev->ifindex; 9645 rtnl_unlock(); 9646 9647 seq_printf(seq, "ifindex:\t%u\n", ifindex); 9648} 9649 9650static int bpf_xdp_link_fill_link_info(const struct bpf_link *link, 9651 struct bpf_link_info *info) 9652{ 9653 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link); 9654 u32 ifindex = 0; 9655 9656 rtnl_lock(); 9657 if (xdp_link->dev) 9658 ifindex = xdp_link->dev->ifindex; 9659 rtnl_unlock(); 9660 9661 info->xdp.ifindex = ifindex; 9662 return 0; 9663} 9664 9665static int bpf_xdp_link_update(struct bpf_link *link, struct bpf_prog *new_prog, 9666 struct bpf_prog *old_prog) 9667{ 9668 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link); 9669 enum bpf_xdp_mode mode; 9670 bpf_op_t bpf_op; 9671 int err = 0; 9672 9673 rtnl_lock(); 9674 9675 /* link might have been auto-released already, so fail */ 9676 if (!xdp_link->dev) { 9677 err = -ENOLINK; 9678 goto out_unlock; 9679 } 9680 9681 if (old_prog && link->prog != old_prog) { 9682 err = -EPERM; 9683 goto out_unlock; 9684 } 9685 old_prog = link->prog; 9686 if (old_prog->type != new_prog->type || 9687 old_prog->expected_attach_type != new_prog->expected_attach_type) { 9688 err = -EINVAL; 9689 goto out_unlock; 9690 } 9691 9692 if (old_prog == new_prog) { 9693 /* no-op, don't disturb drivers */ 9694 bpf_prog_put(new_prog); 9695 goto out_unlock; 9696 } 9697 9698 mode = dev_xdp_mode(xdp_link->dev, xdp_link->flags); 9699 bpf_op = dev_xdp_bpf_op(xdp_link->dev, mode); 9700 err = dev_xdp_install(xdp_link->dev, mode, bpf_op, NULL, 9701 xdp_link->flags, new_prog); 9702 if (err) 9703 goto out_unlock; 9704 9705 old_prog = xchg(&link->prog, new_prog); 9706 bpf_prog_put(old_prog); 9707 9708out_unlock: 9709 rtnl_unlock(); 9710 return err; 9711} 9712 9713static const struct bpf_link_ops bpf_xdp_link_lops = { 9714 .release = bpf_xdp_link_release, 9715 .dealloc = bpf_xdp_link_dealloc, 9716 .detach = bpf_xdp_link_detach, 9717 .show_fdinfo = bpf_xdp_link_show_fdinfo, 9718 .fill_link_info = bpf_xdp_link_fill_link_info, 9719 .update_prog = bpf_xdp_link_update, 9720}; 9721 9722int bpf_xdp_link_attach(const union bpf_attr *attr, struct bpf_prog *prog) 9723{ 9724 struct net *net = current->nsproxy->net_ns; 9725 struct bpf_link_primer link_primer; 9726 struct netlink_ext_ack extack = {}; 9727 struct bpf_xdp_link *link; 9728 struct net_device *dev; 9729 int err, fd; 9730 9731 rtnl_lock(); 9732 dev = dev_get_by_index(net, attr->link_create.target_ifindex); 9733 if (!dev) { 9734 rtnl_unlock(); 9735 return -EINVAL; 9736 } 9737 9738 link = kzalloc(sizeof(*link), GFP_USER); 9739 if (!link) { 9740 err = -ENOMEM; 9741 goto unlock; 9742 } 9743 9744 bpf_link_init(&link->link, BPF_LINK_TYPE_XDP, &bpf_xdp_link_lops, prog); 9745 link->dev = dev; 9746 link->flags = attr->link_create.flags; 9747 9748 err = bpf_link_prime(&link->link, &link_primer); 9749 if (err) { 9750 kfree(link); 9751 goto unlock; 9752 } 9753 9754 err = dev_xdp_attach_link(dev, &extack, link); 9755 rtnl_unlock(); 9756 9757 if (err) { 9758 link->dev = NULL; 9759 bpf_link_cleanup(&link_primer); 9760 trace_bpf_xdp_link_attach_failed(extack._msg); 9761 goto out_put_dev; 9762 } 9763 9764 fd = bpf_link_settle(&link_primer); 9765 /* link itself doesn't hold dev's refcnt to not complicate shutdown */ 9766 dev_put(dev); 9767 return fd; 9768 9769unlock: 9770 rtnl_unlock(); 9771 9772out_put_dev: 9773 dev_put(dev); 9774 return err; 9775} 9776 9777/** 9778 * dev_change_xdp_fd - set or clear a bpf program for a device rx path 9779 * @dev: device 9780 * @extack: netlink extended ack 9781 * @fd: new program fd or negative value to clear 9782 * @expected_fd: old program fd that userspace expects to replace or clear 9783 * @flags: xdp-related flags 9784 * 9785 * Set or clear a bpf program for a device 9786 */ 9787int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack, 9788 int fd, int expected_fd, u32 flags) 9789{ 9790 enum bpf_xdp_mode mode = dev_xdp_mode(dev, flags); 9791 struct bpf_prog *new_prog = NULL, *old_prog = NULL; 9792 int err; 9793 9794 ASSERT_RTNL(); 9795 9796 if (fd >= 0) { 9797 new_prog = bpf_prog_get_type_dev(fd, BPF_PROG_TYPE_XDP, 9798 mode != XDP_MODE_SKB); 9799 if (IS_ERR(new_prog)) 9800 return PTR_ERR(new_prog); 9801 } 9802 9803 if (expected_fd >= 0) { 9804 old_prog = bpf_prog_get_type_dev(expected_fd, BPF_PROG_TYPE_XDP, 9805 mode != XDP_MODE_SKB); 9806 if (IS_ERR(old_prog)) { 9807 err = PTR_ERR(old_prog); 9808 old_prog = NULL; 9809 goto err_out; 9810 } 9811 } 9812 9813 err = dev_xdp_attach(dev, extack, NULL, new_prog, old_prog, flags); 9814 9815err_out: 9816 if (err && new_prog) 9817 bpf_prog_put(new_prog); 9818 if (old_prog) 9819 bpf_prog_put(old_prog); 9820 return err; 9821} 9822 9823/** 9824 * dev_index_reserve() - allocate an ifindex in a namespace 9825 * @net: the applicable net namespace 9826 * @ifindex: requested ifindex, pass %0 to get one allocated 9827 * 9828 * Allocate a ifindex for a new device. Caller must either use the ifindex 9829 * to store the device (via list_netdevice()) or call dev_index_release() 9830 * to give the index up. 9831 * 9832 * Return: a suitable unique value for a new device interface number or -errno. 9833 */ 9834static int dev_index_reserve(struct net *net, u32 ifindex) 9835{ 9836 int err; 9837 9838 if (ifindex > INT_MAX) { 9839 DEBUG_NET_WARN_ON_ONCE(1); 9840 return -EINVAL; 9841 } 9842 9843 if (!ifindex) 9844 err = xa_alloc_cyclic(&net->dev_by_index, &ifindex, NULL, 9845 xa_limit_31b, &net->ifindex, GFP_KERNEL); 9846 else 9847 err = xa_insert(&net->dev_by_index, ifindex, NULL, GFP_KERNEL); 9848 if (err < 0) 9849 return err; 9850 9851 return ifindex; 9852} 9853 9854static void dev_index_release(struct net *net, int ifindex) 9855{ 9856 /* Expect only unused indexes, unlist_netdevice() removes the used */ 9857 WARN_ON(xa_erase(&net->dev_by_index, ifindex)); 9858} 9859 9860/* Delayed registration/unregisteration */ 9861LIST_HEAD(net_todo_list); 9862DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq); 9863atomic_t dev_unreg_count = ATOMIC_INIT(0); 9864 9865static void net_set_todo(struct net_device *dev) 9866{ 9867 list_add_tail(&dev->todo_list, &net_todo_list); 9868} 9869 9870static netdev_features_t netdev_sync_upper_features(struct net_device *lower, 9871 struct net_device *upper, netdev_features_t features) 9872{ 9873 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES; 9874 netdev_features_t feature; 9875 int feature_bit; 9876 9877 for_each_netdev_feature(upper_disables, feature_bit) { 9878 feature = __NETIF_F_BIT(feature_bit); 9879 if (!(upper->wanted_features & feature) 9880 && (features & feature)) { 9881 netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n", 9882 &feature, upper->name); 9883 features &= ~feature; 9884 } 9885 } 9886 9887 return features; 9888} 9889 9890static void netdev_sync_lower_features(struct net_device *upper, 9891 struct net_device *lower, netdev_features_t features) 9892{ 9893 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES; 9894 netdev_features_t feature; 9895 int feature_bit; 9896 9897 for_each_netdev_feature(upper_disables, feature_bit) { 9898 feature = __NETIF_F_BIT(feature_bit); 9899 if (!(features & feature) && (lower->features & feature)) { 9900 netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n", 9901 &feature, lower->name); 9902 lower->wanted_features &= ~feature; 9903 __netdev_update_features(lower); 9904 9905 if (unlikely(lower->features & feature)) 9906 netdev_WARN(upper, "failed to disable %pNF on %s!\n", 9907 &feature, lower->name); 9908 else 9909 netdev_features_change(lower); 9910 } 9911 } 9912} 9913 9914static netdev_features_t netdev_fix_features(struct net_device *dev, 9915 netdev_features_t features) 9916{ 9917 /* Fix illegal checksum combinations */ 9918 if ((features & NETIF_F_HW_CSUM) && 9919 (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) { 9920 netdev_warn(dev, "mixed HW and IP checksum settings.\n"); 9921 features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM); 9922 } 9923 9924 /* TSO requires that SG is present as well. */ 9925 if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) { 9926 netdev_dbg(dev, "Dropping TSO features since no SG feature.\n"); 9927 features &= ~NETIF_F_ALL_TSO; 9928 } 9929 9930 if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) && 9931 !(features & NETIF_F_IP_CSUM)) { 9932 netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n"); 9933 features &= ~NETIF_F_TSO; 9934 features &= ~NETIF_F_TSO_ECN; 9935 } 9936 9937 if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) && 9938 !(features & NETIF_F_IPV6_CSUM)) { 9939 netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n"); 9940 features &= ~NETIF_F_TSO6; 9941 } 9942 9943 /* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */ 9944 if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO)) 9945 features &= ~NETIF_F_TSO_MANGLEID; 9946 9947 /* TSO ECN requires that TSO is present as well. */ 9948 if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN) 9949 features &= ~NETIF_F_TSO_ECN; 9950 9951 /* Software GSO depends on SG. */ 9952 if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) { 9953 netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n"); 9954 features &= ~NETIF_F_GSO; 9955 } 9956 9957 /* GSO partial features require GSO partial be set */ 9958 if ((features & dev->gso_partial_features) && 9959 !(features & NETIF_F_GSO_PARTIAL)) { 9960 netdev_dbg(dev, 9961 "Dropping partially supported GSO features since no GSO partial.\n"); 9962 features &= ~dev->gso_partial_features; 9963 } 9964 9965 if (!(features & NETIF_F_RXCSUM)) { 9966 /* NETIF_F_GRO_HW implies doing RXCSUM since every packet 9967 * successfully merged by hardware must also have the 9968 * checksum verified by hardware. If the user does not 9969 * want to enable RXCSUM, logically, we should disable GRO_HW. 9970 */ 9971 if (features & NETIF_F_GRO_HW) { 9972 netdev_dbg(dev, "Dropping NETIF_F_GRO_HW since no RXCSUM feature.\n"); 9973 features &= ~NETIF_F_GRO_HW; 9974 } 9975 } 9976 9977 /* LRO/HW-GRO features cannot be combined with RX-FCS */ 9978 if (features & NETIF_F_RXFCS) { 9979 if (features & NETIF_F_LRO) { 9980 netdev_dbg(dev, "Dropping LRO feature since RX-FCS is requested.\n"); 9981 features &= ~NETIF_F_LRO; 9982 } 9983 9984 if (features & NETIF_F_GRO_HW) { 9985 netdev_dbg(dev, "Dropping HW-GRO feature since RX-FCS is requested.\n"); 9986 features &= ~NETIF_F_GRO_HW; 9987 } 9988 } 9989 9990 if ((features & NETIF_F_GRO_HW) && (features & NETIF_F_LRO)) { 9991 netdev_dbg(dev, "Dropping LRO feature since HW-GRO is requested.\n"); 9992 features &= ~NETIF_F_LRO; 9993 } 9994 9995 if (features & NETIF_F_HW_TLS_TX) { 9996 bool ip_csum = (features & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM)) == 9997 (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM); 9998 bool hw_csum = features & NETIF_F_HW_CSUM; 9999 10000 if (!ip_csum && !hw_csum) { 10001 netdev_dbg(dev, "Dropping TLS TX HW offload feature since no CSUM feature.\n"); 10002 features &= ~NETIF_F_HW_TLS_TX; 10003 } 10004 } 10005 10006 if ((features & NETIF_F_HW_TLS_RX) && !(features & NETIF_F_RXCSUM)) { 10007 netdev_dbg(dev, "Dropping TLS RX HW offload feature since no RXCSUM feature.\n"); 10008 features &= ~NETIF_F_HW_TLS_RX; 10009 } 10010 10011 return features; 10012} 10013 10014int __netdev_update_features(struct net_device *dev) 10015{ 10016 struct net_device *upper, *lower; 10017 netdev_features_t features; 10018 struct list_head *iter; 10019 int err = -1; 10020 10021 ASSERT_RTNL(); 10022 10023 features = netdev_get_wanted_features(dev); 10024 10025 if (dev->netdev_ops->ndo_fix_features) 10026 features = dev->netdev_ops->ndo_fix_features(dev, features); 10027 10028 /* driver might be less strict about feature dependencies */ 10029 features = netdev_fix_features(dev, features); 10030 10031 /* some features can't be enabled if they're off on an upper device */ 10032 netdev_for_each_upper_dev_rcu(dev, upper, iter) 10033 features = netdev_sync_upper_features(dev, upper, features); 10034 10035 if (dev->features == features) 10036 goto sync_lower; 10037 10038 netdev_dbg(dev, "Features changed: %pNF -> %pNF\n", 10039 &dev->features, &features); 10040 10041 if (dev->netdev_ops->ndo_set_features) 10042 err = dev->netdev_ops->ndo_set_features(dev, features); 10043 else 10044 err = 0; 10045 10046 if (unlikely(err < 0)) { 10047 netdev_err(dev, 10048 "set_features() failed (%d); wanted %pNF, left %pNF\n", 10049 err, &features, &dev->features); 10050 /* return non-0 since some features might have changed and 10051 * it's better to fire a spurious notification than miss it 10052 */ 10053 return -1; 10054 } 10055 10056sync_lower: 10057 /* some features must be disabled on lower devices when disabled 10058 * on an upper device (think: bonding master or bridge) 10059 */ 10060 netdev_for_each_lower_dev(dev, lower, iter) 10061 netdev_sync_lower_features(dev, lower, features); 10062 10063 if (!err) { 10064 netdev_features_t diff = features ^ dev->features; 10065 10066 if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) { 10067 /* udp_tunnel_{get,drop}_rx_info both need 10068 * NETIF_F_RX_UDP_TUNNEL_PORT enabled on the 10069 * device, or they won't do anything. 10070 * Thus we need to update dev->features 10071 * *before* calling udp_tunnel_get_rx_info, 10072 * but *after* calling udp_tunnel_drop_rx_info. 10073 */ 10074 if (features & NETIF_F_RX_UDP_TUNNEL_PORT) { 10075 dev->features = features; 10076 udp_tunnel_get_rx_info(dev); 10077 } else { 10078 udp_tunnel_drop_rx_info(dev); 10079 } 10080 } 10081 10082 if (diff & NETIF_F_HW_VLAN_CTAG_FILTER) { 10083 if (features & NETIF_F_HW_VLAN_CTAG_FILTER) { 10084 dev->features = features; 10085 err |= vlan_get_rx_ctag_filter_info(dev); 10086 } else { 10087 vlan_drop_rx_ctag_filter_info(dev); 10088 } 10089 } 10090 10091 if (diff & NETIF_F_HW_VLAN_STAG_FILTER) { 10092 if (features & NETIF_F_HW_VLAN_STAG_FILTER) { 10093 dev->features = features; 10094 err |= vlan_get_rx_stag_filter_info(dev); 10095 } else { 10096 vlan_drop_rx_stag_filter_info(dev); 10097 } 10098 } 10099 10100 dev->features = features; 10101 } 10102 10103 return err < 0 ? 0 : 1; 10104} 10105 10106/** 10107 * netdev_update_features - recalculate device features 10108 * @dev: the device to check 10109 * 10110 * Recalculate dev->features set and send notifications if it 10111 * has changed. Should be called after driver or hardware dependent 10112 * conditions might have changed that influence the features. 10113 */ 10114void netdev_update_features(struct net_device *dev) 10115{ 10116 if (__netdev_update_features(dev)) 10117 netdev_features_change(dev); 10118} 10119EXPORT_SYMBOL(netdev_update_features); 10120 10121/** 10122 * netdev_change_features - recalculate device features 10123 * @dev: the device to check 10124 * 10125 * Recalculate dev->features set and send notifications even 10126 * if they have not changed. Should be called instead of 10127 * netdev_update_features() if also dev->vlan_features might 10128 * have changed to allow the changes to be propagated to stacked 10129 * VLAN devices. 10130 */ 10131void netdev_change_features(struct net_device *dev) 10132{ 10133 __netdev_update_features(dev); 10134 netdev_features_change(dev); 10135} 10136EXPORT_SYMBOL(netdev_change_features); 10137 10138/** 10139 * netif_stacked_transfer_operstate - transfer operstate 10140 * @rootdev: the root or lower level device to transfer state from 10141 * @dev: the device to transfer operstate to 10142 * 10143 * Transfer operational state from root to device. This is normally 10144 * called when a stacking relationship exists between the root 10145 * device and the device(a leaf device). 10146 */ 10147void netif_stacked_transfer_operstate(const struct net_device *rootdev, 10148 struct net_device *dev) 10149{ 10150 if (rootdev->operstate == IF_OPER_DORMANT) 10151 netif_dormant_on(dev); 10152 else 10153 netif_dormant_off(dev); 10154 10155 if (rootdev->operstate == IF_OPER_TESTING) 10156 netif_testing_on(dev); 10157 else 10158 netif_testing_off(dev); 10159 10160 if (netif_carrier_ok(rootdev)) 10161 netif_carrier_on(dev); 10162 else 10163 netif_carrier_off(dev); 10164} 10165EXPORT_SYMBOL(netif_stacked_transfer_operstate); 10166 10167static int netif_alloc_rx_queues(struct net_device *dev) 10168{ 10169 unsigned int i, count = dev->num_rx_queues; 10170 struct netdev_rx_queue *rx; 10171 size_t sz = count * sizeof(*rx); 10172 int err = 0; 10173 10174 BUG_ON(count < 1); 10175 10176 rx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL); 10177 if (!rx) 10178 return -ENOMEM; 10179 10180 dev->_rx = rx; 10181 10182 for (i = 0; i < count; i++) { 10183 rx[i].dev = dev; 10184 10185 /* XDP RX-queue setup */ 10186 err = xdp_rxq_info_reg(&rx[i].xdp_rxq, dev, i, 0); 10187 if (err < 0) 10188 goto err_rxq_info; 10189 } 10190 return 0; 10191 10192err_rxq_info: 10193 /* Rollback successful reg's and free other resources */ 10194 while (i--) 10195 xdp_rxq_info_unreg(&rx[i].xdp_rxq); 10196 kvfree(dev->_rx); 10197 dev->_rx = NULL; 10198 return err; 10199} 10200 10201static void netif_free_rx_queues(struct net_device *dev) 10202{ 10203 unsigned int i, count = dev->num_rx_queues; 10204 10205 /* netif_alloc_rx_queues alloc failed, resources have been unreg'ed */ 10206 if (!dev->_rx) 10207 return; 10208 10209 for (i = 0; i < count; i++) 10210 xdp_rxq_info_unreg(&dev->_rx[i].xdp_rxq); 10211 10212 kvfree(dev->_rx); 10213} 10214 10215static void netdev_init_one_queue(struct net_device *dev, 10216 struct netdev_queue *queue, void *_unused) 10217{ 10218 /* Initialize queue lock */ 10219 spin_lock_init(&queue->_xmit_lock); 10220 netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type); 10221 queue->xmit_lock_owner = -1; 10222 netdev_queue_numa_node_write(queue, NUMA_NO_NODE); 10223 queue->dev = dev; 10224#ifdef CONFIG_BQL 10225 dql_init(&queue->dql, HZ); 10226#endif 10227} 10228 10229static void netif_free_tx_queues(struct net_device *dev) 10230{ 10231 kvfree(dev->_tx); 10232} 10233 10234static int netif_alloc_netdev_queues(struct net_device *dev) 10235{ 10236 unsigned int count = dev->num_tx_queues; 10237 struct netdev_queue *tx; 10238 size_t sz = count * sizeof(*tx); 10239 10240 if (count < 1 || count > 0xffff) 10241 return -EINVAL; 10242 10243 tx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL); 10244 if (!tx) 10245 return -ENOMEM; 10246 10247 dev->_tx = tx; 10248 10249 netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL); 10250 spin_lock_init(&dev->tx_global_lock); 10251 10252 return 0; 10253} 10254 10255void netif_tx_stop_all_queues(struct net_device *dev) 10256{ 10257 unsigned int i; 10258 10259 for (i = 0; i < dev->num_tx_queues; i++) { 10260 struct netdev_queue *txq = netdev_get_tx_queue(dev, i); 10261 10262 netif_tx_stop_queue(txq); 10263 } 10264} 10265EXPORT_SYMBOL(netif_tx_stop_all_queues); 10266 10267static int netdev_do_alloc_pcpu_stats(struct net_device *dev) 10268{ 10269 void __percpu *v; 10270 10271 /* Drivers implementing ndo_get_peer_dev must support tstat 10272 * accounting, so that skb_do_redirect() can bump the dev's 10273 * RX stats upon network namespace switch. 10274 */ 10275 if (dev->netdev_ops->ndo_get_peer_dev && 10276 dev->pcpu_stat_type != NETDEV_PCPU_STAT_TSTATS) 10277 return -EOPNOTSUPP; 10278 10279 switch (dev->pcpu_stat_type) { 10280 case NETDEV_PCPU_STAT_NONE: 10281 return 0; 10282 case NETDEV_PCPU_STAT_LSTATS: 10283 v = dev->lstats = netdev_alloc_pcpu_stats(struct pcpu_lstats); 10284 break; 10285 case NETDEV_PCPU_STAT_TSTATS: 10286 v = dev->tstats = netdev_alloc_pcpu_stats(struct pcpu_sw_netstats); 10287 break; 10288 case NETDEV_PCPU_STAT_DSTATS: 10289 v = dev->dstats = netdev_alloc_pcpu_stats(struct pcpu_dstats); 10290 break; 10291 default: 10292 return -EINVAL; 10293 } 10294 10295 return v ? 0 : -ENOMEM; 10296} 10297 10298static void netdev_do_free_pcpu_stats(struct net_device *dev) 10299{ 10300 switch (dev->pcpu_stat_type) { 10301 case NETDEV_PCPU_STAT_NONE: 10302 return; 10303 case NETDEV_PCPU_STAT_LSTATS: 10304 free_percpu(dev->lstats); 10305 break; 10306 case NETDEV_PCPU_STAT_TSTATS: 10307 free_percpu(dev->tstats); 10308 break; 10309 case NETDEV_PCPU_STAT_DSTATS: 10310 free_percpu(dev->dstats); 10311 break; 10312 } 10313} 10314 10315/** 10316 * register_netdevice() - register a network device 10317 * @dev: device to register 10318 * 10319 * Take a prepared network device structure and make it externally accessible. 10320 * A %NETDEV_REGISTER message is sent to the netdev notifier chain. 10321 * Callers must hold the rtnl lock - you may want register_netdev() 10322 * instead of this. 10323 */ 10324int register_netdevice(struct net_device *dev) 10325{ 10326 int ret; 10327 struct net *net = dev_net(dev); 10328 10329 BUILD_BUG_ON(sizeof(netdev_features_t) * BITS_PER_BYTE < 10330 NETDEV_FEATURE_COUNT); 10331 BUG_ON(dev_boot_phase); 10332 ASSERT_RTNL(); 10333 10334 might_sleep(); 10335 10336 /* When net_device's are persistent, this will be fatal. */ 10337 BUG_ON(dev->reg_state != NETREG_UNINITIALIZED); 10338 BUG_ON(!net); 10339 10340 ret = ethtool_check_ops(dev->ethtool_ops); 10341 if (ret) 10342 return ret; 10343 10344 /* rss ctx ID 0 is reserved for the default context, start from 1 */ 10345 xa_init_flags(&dev->ethtool->rss_ctx, XA_FLAGS_ALLOC1); 10346 mutex_init(&dev->ethtool->rss_lock); 10347 10348 spin_lock_init(&dev->addr_list_lock); 10349 netdev_set_addr_lockdep_class(dev); 10350 10351 ret = dev_get_valid_name(net, dev, dev->name); 10352 if (ret < 0) 10353 goto out; 10354 10355 ret = -ENOMEM; 10356 dev->name_node = netdev_name_node_head_alloc(dev); 10357 if (!dev->name_node) 10358 goto out; 10359 10360 /* Init, if this function is available */ 10361 if (dev->netdev_ops->ndo_init) { 10362 ret = dev->netdev_ops->ndo_init(dev); 10363 if (ret) { 10364 if (ret > 0) 10365 ret = -EIO; 10366 goto err_free_name; 10367 } 10368 } 10369 10370 if (((dev->hw_features | dev->features) & 10371 NETIF_F_HW_VLAN_CTAG_FILTER) && 10372 (!dev->netdev_ops->ndo_vlan_rx_add_vid || 10373 !dev->netdev_ops->ndo_vlan_rx_kill_vid)) { 10374 netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n"); 10375 ret = -EINVAL; 10376 goto err_uninit; 10377 } 10378 10379 ret = netdev_do_alloc_pcpu_stats(dev); 10380 if (ret) 10381 goto err_uninit; 10382 10383 ret = dev_index_reserve(net, dev->ifindex); 10384 if (ret < 0) 10385 goto err_free_pcpu; 10386 dev->ifindex = ret; 10387 10388 /* Transfer changeable features to wanted_features and enable 10389 * software offloads (GSO and GRO). 10390 */ 10391 dev->hw_features |= (NETIF_F_SOFT_FEATURES | NETIF_F_SOFT_FEATURES_OFF); 10392 dev->features |= NETIF_F_SOFT_FEATURES; 10393 10394 if (dev->udp_tunnel_nic_info) { 10395 dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT; 10396 dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT; 10397 } 10398 10399 dev->wanted_features = dev->features & dev->hw_features; 10400 10401 if (!(dev->flags & IFF_LOOPBACK)) 10402 dev->hw_features |= NETIF_F_NOCACHE_COPY; 10403 10404 /* If IPv4 TCP segmentation offload is supported we should also 10405 * allow the device to enable segmenting the frame with the option 10406 * of ignoring a static IP ID value. This doesn't enable the 10407 * feature itself but allows the user to enable it later. 10408 */ 10409 if (dev->hw_features & NETIF_F_TSO) 10410 dev->hw_features |= NETIF_F_TSO_MANGLEID; 10411 if (dev->vlan_features & NETIF_F_TSO) 10412 dev->vlan_features |= NETIF_F_TSO_MANGLEID; 10413 if (dev->mpls_features & NETIF_F_TSO) 10414 dev->mpls_features |= NETIF_F_TSO_MANGLEID; 10415 if (dev->hw_enc_features & NETIF_F_TSO) 10416 dev->hw_enc_features |= NETIF_F_TSO_MANGLEID; 10417 10418 /* Make NETIF_F_HIGHDMA inheritable to VLAN devices. 10419 */ 10420 dev->vlan_features |= NETIF_F_HIGHDMA; 10421 10422 /* Make NETIF_F_SG inheritable to tunnel devices. 10423 */ 10424 dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL; 10425 10426 /* Make NETIF_F_SG inheritable to MPLS. 10427 */ 10428 dev->mpls_features |= NETIF_F_SG; 10429 10430 ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev); 10431 ret = notifier_to_errno(ret); 10432 if (ret) 10433 goto err_ifindex_release; 10434 10435 ret = netdev_register_kobject(dev); 10436 10437 WRITE_ONCE(dev->reg_state, ret ? NETREG_UNREGISTERED : NETREG_REGISTERED); 10438 10439 if (ret) 10440 goto err_uninit_notify; 10441 10442 __netdev_update_features(dev); 10443 10444 /* 10445 * Default initial state at registry is that the 10446 * device is present. 10447 */ 10448 10449 set_bit(__LINK_STATE_PRESENT, &dev->state); 10450 10451 linkwatch_init_dev(dev); 10452 10453 dev_init_scheduler(dev); 10454 10455 netdev_hold(dev, &dev->dev_registered_tracker, GFP_KERNEL); 10456 list_netdevice(dev); 10457 10458 add_device_randomness(dev->dev_addr, dev->addr_len); 10459 10460 /* If the device has permanent device address, driver should 10461 * set dev_addr and also addr_assign_type should be set to 10462 * NET_ADDR_PERM (default value). 10463 */ 10464 if (dev->addr_assign_type == NET_ADDR_PERM) 10465 memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len); 10466 10467 /* Notify protocols, that a new device appeared. */ 10468 ret = call_netdevice_notifiers(NETDEV_REGISTER, dev); 10469 ret = notifier_to_errno(ret); 10470 if (ret) { 10471 /* Expect explicit free_netdev() on failure */ 10472 dev->needs_free_netdev = false; 10473 unregister_netdevice_queue(dev, NULL); 10474 goto out; 10475 } 10476 /* 10477 * Prevent userspace races by waiting until the network 10478 * device is fully setup before sending notifications. 10479 */ 10480 if (!dev->rtnl_link_ops || 10481 dev->rtnl_link_state == RTNL_LINK_INITIALIZED) 10482 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL, 0, NULL); 10483 10484out: 10485 return ret; 10486 10487err_uninit_notify: 10488 call_netdevice_notifiers(NETDEV_PRE_UNINIT, dev); 10489err_ifindex_release: 10490 dev_index_release(net, dev->ifindex); 10491err_free_pcpu: 10492 netdev_do_free_pcpu_stats(dev); 10493err_uninit: 10494 if (dev->netdev_ops->ndo_uninit) 10495 dev->netdev_ops->ndo_uninit(dev); 10496 if (dev->priv_destructor) 10497 dev->priv_destructor(dev); 10498err_free_name: 10499 netdev_name_node_free(dev->name_node); 10500 goto out; 10501} 10502EXPORT_SYMBOL(register_netdevice); 10503 10504/* Initialize the core of a dummy net device. 10505 * This is useful if you are calling this function after alloc_netdev(), 10506 * since it does not memset the net_device fields. 10507 */ 10508static void init_dummy_netdev_core(struct net_device *dev) 10509{ 10510 /* make sure we BUG if trying to hit standard 10511 * register/unregister code path 10512 */ 10513 dev->reg_state = NETREG_DUMMY; 10514 10515 /* NAPI wants this */ 10516 INIT_LIST_HEAD(&dev->napi_list); 10517 10518 /* a dummy interface is started by default */ 10519 set_bit(__LINK_STATE_PRESENT, &dev->state); 10520 set_bit(__LINK_STATE_START, &dev->state); 10521 10522 /* napi_busy_loop stats accounting wants this */ 10523 dev_net_set(dev, &init_net); 10524 10525 /* Note : We dont allocate pcpu_refcnt for dummy devices, 10526 * because users of this 'device' dont need to change 10527 * its refcount. 10528 */ 10529} 10530 10531/** 10532 * init_dummy_netdev - init a dummy network device for NAPI 10533 * @dev: device to init 10534 * 10535 * This takes a network device structure and initializes the minimum 10536 * amount of fields so it can be used to schedule NAPI polls without 10537 * registering a full blown interface. This is to be used by drivers 10538 * that need to tie several hardware interfaces to a single NAPI 10539 * poll scheduler due to HW limitations. 10540 */ 10541void init_dummy_netdev(struct net_device *dev) 10542{ 10543 /* Clear everything. Note we don't initialize spinlocks 10544 * as they aren't supposed to be taken by any of the 10545 * NAPI code and this dummy netdev is supposed to be 10546 * only ever used for NAPI polls 10547 */ 10548 memset(dev, 0, sizeof(struct net_device)); 10549 init_dummy_netdev_core(dev); 10550} 10551EXPORT_SYMBOL_GPL(init_dummy_netdev); 10552 10553/** 10554 * register_netdev - register a network device 10555 * @dev: device to register 10556 * 10557 * Take a completed network device structure and add it to the kernel 10558 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier 10559 * chain. 0 is returned on success. A negative errno code is returned 10560 * on a failure to set up the device, or if the name is a duplicate. 10561 * 10562 * This is a wrapper around register_netdevice that takes the rtnl semaphore 10563 * and expands the device name if you passed a format string to 10564 * alloc_netdev. 10565 */ 10566int register_netdev(struct net_device *dev) 10567{ 10568 int err; 10569 10570 if (rtnl_lock_killable()) 10571 return -EINTR; 10572 err = register_netdevice(dev); 10573 rtnl_unlock(); 10574 return err; 10575} 10576EXPORT_SYMBOL(register_netdev); 10577 10578int netdev_refcnt_read(const struct net_device *dev) 10579{ 10580#ifdef CONFIG_PCPU_DEV_REFCNT 10581 int i, refcnt = 0; 10582 10583 for_each_possible_cpu(i) 10584 refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i); 10585 return refcnt; 10586#else 10587 return refcount_read(&dev->dev_refcnt); 10588#endif 10589} 10590EXPORT_SYMBOL(netdev_refcnt_read); 10591 10592int netdev_unregister_timeout_secs __read_mostly = 10; 10593 10594#define WAIT_REFS_MIN_MSECS 1 10595#define WAIT_REFS_MAX_MSECS 250 10596/** 10597 * netdev_wait_allrefs_any - wait until all references are gone. 10598 * @list: list of net_devices to wait on 10599 * 10600 * This is called when unregistering network devices. 10601 * 10602 * Any protocol or device that holds a reference should register 10603 * for netdevice notification, and cleanup and put back the 10604 * reference if they receive an UNREGISTER event. 10605 * We can get stuck here if buggy protocols don't correctly 10606 * call dev_put. 10607 */ 10608static struct net_device *netdev_wait_allrefs_any(struct list_head *list) 10609{ 10610 unsigned long rebroadcast_time, warning_time; 10611 struct net_device *dev; 10612 int wait = 0; 10613 10614 rebroadcast_time = warning_time = jiffies; 10615 10616 list_for_each_entry(dev, list, todo_list) 10617 if (netdev_refcnt_read(dev) == 1) 10618 return dev; 10619 10620 while (true) { 10621 if (time_after(jiffies, rebroadcast_time + 1 * HZ)) { 10622 rtnl_lock(); 10623 10624 /* Rebroadcast unregister notification */ 10625 list_for_each_entry(dev, list, todo_list) 10626 call_netdevice_notifiers(NETDEV_UNREGISTER, dev); 10627 10628 __rtnl_unlock(); 10629 rcu_barrier(); 10630 rtnl_lock(); 10631 10632 list_for_each_entry(dev, list, todo_list) 10633 if (test_bit(__LINK_STATE_LINKWATCH_PENDING, 10634 &dev->state)) { 10635 /* We must not have linkwatch events 10636 * pending on unregister. If this 10637 * happens, we simply run the queue 10638 * unscheduled, resulting in a noop 10639 * for this device. 10640 */ 10641 linkwatch_run_queue(); 10642 break; 10643 } 10644 10645 __rtnl_unlock(); 10646 10647 rebroadcast_time = jiffies; 10648 } 10649 10650 rcu_barrier(); 10651 10652 if (!wait) { 10653 wait = WAIT_REFS_MIN_MSECS; 10654 } else { 10655 msleep(wait); 10656 wait = min(wait << 1, WAIT_REFS_MAX_MSECS); 10657 } 10658 10659 list_for_each_entry(dev, list, todo_list) 10660 if (netdev_refcnt_read(dev) == 1) 10661 return dev; 10662 10663 if (time_after(jiffies, warning_time + 10664 READ_ONCE(netdev_unregister_timeout_secs) * HZ)) { 10665 list_for_each_entry(dev, list, todo_list) { 10666 pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n", 10667 dev->name, netdev_refcnt_read(dev)); 10668 ref_tracker_dir_print(&dev->refcnt_tracker, 10); 10669 } 10670 10671 warning_time = jiffies; 10672 } 10673 } 10674} 10675 10676/* The sequence is: 10677 * 10678 * rtnl_lock(); 10679 * ... 10680 * register_netdevice(x1); 10681 * register_netdevice(x2); 10682 * ... 10683 * unregister_netdevice(y1); 10684 * unregister_netdevice(y2); 10685 * ... 10686 * rtnl_unlock(); 10687 * free_netdev(y1); 10688 * free_netdev(y2); 10689 * 10690 * We are invoked by rtnl_unlock(). 10691 * This allows us to deal with problems: 10692 * 1) We can delete sysfs objects which invoke hotplug 10693 * without deadlocking with linkwatch via keventd. 10694 * 2) Since we run with the RTNL semaphore not held, we can sleep 10695 * safely in order to wait for the netdev refcnt to drop to zero. 10696 * 10697 * We must not return until all unregister events added during 10698 * the interval the lock was held have been completed. 10699 */ 10700void netdev_run_todo(void) 10701{ 10702 struct net_device *dev, *tmp; 10703 struct list_head list; 10704 int cnt; 10705#ifdef CONFIG_LOCKDEP 10706 struct list_head unlink_list; 10707 10708 list_replace_init(&net_unlink_list, &unlink_list); 10709 10710 while (!list_empty(&unlink_list)) { 10711 struct net_device *dev = list_first_entry(&unlink_list, 10712 struct net_device, 10713 unlink_list); 10714 list_del_init(&dev->unlink_list); 10715 dev->nested_level = dev->lower_level - 1; 10716 } 10717#endif 10718 10719 /* Snapshot list, allow later requests */ 10720 list_replace_init(&net_todo_list, &list); 10721 10722 __rtnl_unlock(); 10723 10724 /* Wait for rcu callbacks to finish before next phase */ 10725 if (!list_empty(&list)) 10726 rcu_barrier(); 10727 10728 list_for_each_entry_safe(dev, tmp, &list, todo_list) { 10729 if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) { 10730 netdev_WARN(dev, "run_todo but not unregistering\n"); 10731 list_del(&dev->todo_list); 10732 continue; 10733 } 10734 10735 WRITE_ONCE(dev->reg_state, NETREG_UNREGISTERED); 10736 linkwatch_sync_dev(dev); 10737 } 10738 10739 cnt = 0; 10740 while (!list_empty(&list)) { 10741 dev = netdev_wait_allrefs_any(&list); 10742 list_del(&dev->todo_list); 10743 10744 /* paranoia */ 10745 BUG_ON(netdev_refcnt_read(dev) != 1); 10746 BUG_ON(!list_empty(&dev->ptype_all)); 10747 BUG_ON(!list_empty(&dev->ptype_specific)); 10748 WARN_ON(rcu_access_pointer(dev->ip_ptr)); 10749 WARN_ON(rcu_access_pointer(dev->ip6_ptr)); 10750 10751 netdev_do_free_pcpu_stats(dev); 10752 if (dev->priv_destructor) 10753 dev->priv_destructor(dev); 10754 if (dev->needs_free_netdev) 10755 free_netdev(dev); 10756 10757 cnt++; 10758 10759 /* Free network device */ 10760 kobject_put(&dev->dev.kobj); 10761 } 10762 if (cnt && atomic_sub_and_test(cnt, &dev_unreg_count)) 10763 wake_up(&netdev_unregistering_wq); 10764} 10765 10766/* Collate per-cpu network dstats statistics 10767 * 10768 * Read per-cpu network statistics from dev->dstats and populate the related 10769 * fields in @s. 10770 */ 10771static void dev_fetch_dstats(struct rtnl_link_stats64 *s, 10772 const struct pcpu_dstats __percpu *dstats) 10773{ 10774 int cpu; 10775 10776 for_each_possible_cpu(cpu) { 10777 u64 rx_packets, rx_bytes, rx_drops; 10778 u64 tx_packets, tx_bytes, tx_drops; 10779 const struct pcpu_dstats *stats; 10780 unsigned int start; 10781 10782 stats = per_cpu_ptr(dstats, cpu); 10783 do { 10784 start = u64_stats_fetch_begin(&stats->syncp); 10785 rx_packets = u64_stats_read(&stats->rx_packets); 10786 rx_bytes = u64_stats_read(&stats->rx_bytes); 10787 rx_drops = u64_stats_read(&stats->rx_drops); 10788 tx_packets = u64_stats_read(&stats->tx_packets); 10789 tx_bytes = u64_stats_read(&stats->tx_bytes); 10790 tx_drops = u64_stats_read(&stats->tx_drops); 10791 } while (u64_stats_fetch_retry(&stats->syncp, start)); 10792 10793 s->rx_packets += rx_packets; 10794 s->rx_bytes += rx_bytes; 10795 s->rx_dropped += rx_drops; 10796 s->tx_packets += tx_packets; 10797 s->tx_bytes += tx_bytes; 10798 s->tx_dropped += tx_drops; 10799 } 10800} 10801 10802/* ndo_get_stats64 implementation for dtstats-based accounting. 10803 * 10804 * Populate @s from dev->stats and dev->dstats. This is used internally by the 10805 * core for NETDEV_PCPU_STAT_DSTAT-type stats collection. 10806 */ 10807static void dev_get_dstats64(const struct net_device *dev, 10808 struct rtnl_link_stats64 *s) 10809{ 10810 netdev_stats_to_stats64(s, &dev->stats); 10811 dev_fetch_dstats(s, dev->dstats); 10812} 10813 10814/* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has 10815 * all the same fields in the same order as net_device_stats, with only 10816 * the type differing, but rtnl_link_stats64 may have additional fields 10817 * at the end for newer counters. 10818 */ 10819void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64, 10820 const struct net_device_stats *netdev_stats) 10821{ 10822 size_t i, n = sizeof(*netdev_stats) / sizeof(atomic_long_t); 10823 const atomic_long_t *src = (atomic_long_t *)netdev_stats; 10824 u64 *dst = (u64 *)stats64; 10825 10826 BUILD_BUG_ON(n > sizeof(*stats64) / sizeof(u64)); 10827 for (i = 0; i < n; i++) 10828 dst[i] = (unsigned long)atomic_long_read(&src[i]); 10829 /* zero out counters that only exist in rtnl_link_stats64 */ 10830 memset((char *)stats64 + n * sizeof(u64), 0, 10831 sizeof(*stats64) - n * sizeof(u64)); 10832} 10833EXPORT_SYMBOL(netdev_stats_to_stats64); 10834 10835static __cold struct net_device_core_stats __percpu *netdev_core_stats_alloc( 10836 struct net_device *dev) 10837{ 10838 struct net_device_core_stats __percpu *p; 10839 10840 p = alloc_percpu_gfp(struct net_device_core_stats, 10841 GFP_ATOMIC | __GFP_NOWARN); 10842 10843 if (p && cmpxchg(&dev->core_stats, NULL, p)) 10844 free_percpu(p); 10845 10846 /* This READ_ONCE() pairs with the cmpxchg() above */ 10847 return READ_ONCE(dev->core_stats); 10848} 10849 10850noinline void netdev_core_stats_inc(struct net_device *dev, u32 offset) 10851{ 10852 /* This READ_ONCE() pairs with the write in netdev_core_stats_alloc() */ 10853 struct net_device_core_stats __percpu *p = READ_ONCE(dev->core_stats); 10854 unsigned long __percpu *field; 10855 10856 if (unlikely(!p)) { 10857 p = netdev_core_stats_alloc(dev); 10858 if (!p) 10859 return; 10860 } 10861 10862 field = (__force unsigned long __percpu *)((__force void *)p + offset); 10863 this_cpu_inc(*field); 10864} 10865EXPORT_SYMBOL_GPL(netdev_core_stats_inc); 10866 10867/** 10868 * dev_get_stats - get network device statistics 10869 * @dev: device to get statistics from 10870 * @storage: place to store stats 10871 * 10872 * Get network statistics from device. Return @storage. 10873 * The device driver may provide its own method by setting 10874 * dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats; 10875 * otherwise the internal statistics structure is used. 10876 */ 10877struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev, 10878 struct rtnl_link_stats64 *storage) 10879{ 10880 const struct net_device_ops *ops = dev->netdev_ops; 10881 const struct net_device_core_stats __percpu *p; 10882 10883 if (ops->ndo_get_stats64) { 10884 memset(storage, 0, sizeof(*storage)); 10885 ops->ndo_get_stats64(dev, storage); 10886 } else if (ops->ndo_get_stats) { 10887 netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev)); 10888 } else if (dev->pcpu_stat_type == NETDEV_PCPU_STAT_TSTATS) { 10889 dev_get_tstats64(dev, storage); 10890 } else if (dev->pcpu_stat_type == NETDEV_PCPU_STAT_DSTATS) { 10891 dev_get_dstats64(dev, storage); 10892 } else { 10893 netdev_stats_to_stats64(storage, &dev->stats); 10894 } 10895 10896 /* This READ_ONCE() pairs with the write in netdev_core_stats_alloc() */ 10897 p = READ_ONCE(dev->core_stats); 10898 if (p) { 10899 const struct net_device_core_stats *core_stats; 10900 int i; 10901 10902 for_each_possible_cpu(i) { 10903 core_stats = per_cpu_ptr(p, i); 10904 storage->rx_dropped += READ_ONCE(core_stats->rx_dropped); 10905 storage->tx_dropped += READ_ONCE(core_stats->tx_dropped); 10906 storage->rx_nohandler += READ_ONCE(core_stats->rx_nohandler); 10907 storage->rx_otherhost_dropped += READ_ONCE(core_stats->rx_otherhost_dropped); 10908 } 10909 } 10910 return storage; 10911} 10912EXPORT_SYMBOL(dev_get_stats); 10913 10914/** 10915 * dev_fetch_sw_netstats - get per-cpu network device statistics 10916 * @s: place to store stats 10917 * @netstats: per-cpu network stats to read from 10918 * 10919 * Read per-cpu network statistics and populate the related fields in @s. 10920 */ 10921void dev_fetch_sw_netstats(struct rtnl_link_stats64 *s, 10922 const struct pcpu_sw_netstats __percpu *netstats) 10923{ 10924 int cpu; 10925 10926 for_each_possible_cpu(cpu) { 10927 u64 rx_packets, rx_bytes, tx_packets, tx_bytes; 10928 const struct pcpu_sw_netstats *stats; 10929 unsigned int start; 10930 10931 stats = per_cpu_ptr(netstats, cpu); 10932 do { 10933 start = u64_stats_fetch_begin(&stats->syncp); 10934 rx_packets = u64_stats_read(&stats->rx_packets); 10935 rx_bytes = u64_stats_read(&stats->rx_bytes); 10936 tx_packets = u64_stats_read(&stats->tx_packets); 10937 tx_bytes = u64_stats_read(&stats->tx_bytes); 10938 } while (u64_stats_fetch_retry(&stats->syncp, start)); 10939 10940 s->rx_packets += rx_packets; 10941 s->rx_bytes += rx_bytes; 10942 s->tx_packets += tx_packets; 10943 s->tx_bytes += tx_bytes; 10944 } 10945} 10946EXPORT_SYMBOL_GPL(dev_fetch_sw_netstats); 10947 10948/** 10949 * dev_get_tstats64 - ndo_get_stats64 implementation 10950 * @dev: device to get statistics from 10951 * @s: place to store stats 10952 * 10953 * Populate @s from dev->stats and dev->tstats. Can be used as 10954 * ndo_get_stats64() callback. 10955 */ 10956void dev_get_tstats64(struct net_device *dev, struct rtnl_link_stats64 *s) 10957{ 10958 netdev_stats_to_stats64(s, &dev->stats); 10959 dev_fetch_sw_netstats(s, dev->tstats); 10960} 10961EXPORT_SYMBOL_GPL(dev_get_tstats64); 10962 10963struct netdev_queue *dev_ingress_queue_create(struct net_device *dev) 10964{ 10965 struct netdev_queue *queue = dev_ingress_queue(dev); 10966 10967#ifdef CONFIG_NET_CLS_ACT 10968 if (queue) 10969 return queue; 10970 queue = kzalloc(sizeof(*queue), GFP_KERNEL); 10971 if (!queue) 10972 return NULL; 10973 netdev_init_one_queue(dev, queue, NULL); 10974 RCU_INIT_POINTER(queue->qdisc, &noop_qdisc); 10975 RCU_INIT_POINTER(queue->qdisc_sleeping, &noop_qdisc); 10976 rcu_assign_pointer(dev->ingress_queue, queue); 10977#endif 10978 return queue; 10979} 10980 10981static const struct ethtool_ops default_ethtool_ops; 10982 10983void netdev_set_default_ethtool_ops(struct net_device *dev, 10984 const struct ethtool_ops *ops) 10985{ 10986 if (dev->ethtool_ops == &default_ethtool_ops) 10987 dev->ethtool_ops = ops; 10988} 10989EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops); 10990 10991/** 10992 * netdev_sw_irq_coalesce_default_on() - enable SW IRQ coalescing by default 10993 * @dev: netdev to enable the IRQ coalescing on 10994 * 10995 * Sets a conservative default for SW IRQ coalescing. Users can use 10996 * sysfs attributes to override the default values. 10997 */ 10998void netdev_sw_irq_coalesce_default_on(struct net_device *dev) 10999{ 11000 WARN_ON(dev->reg_state == NETREG_REGISTERED); 11001 11002 if (!IS_ENABLED(CONFIG_PREEMPT_RT)) { 11003 dev->gro_flush_timeout = 20000; 11004 dev->napi_defer_hard_irqs = 1; 11005 } 11006} 11007EXPORT_SYMBOL_GPL(netdev_sw_irq_coalesce_default_on); 11008 11009/** 11010 * alloc_netdev_mqs - allocate network device 11011 * @sizeof_priv: size of private data to allocate space for 11012 * @name: device name format string 11013 * @name_assign_type: origin of device name 11014 * @setup: callback to initialize device 11015 * @txqs: the number of TX subqueues to allocate 11016 * @rxqs: the number of RX subqueues to allocate 11017 * 11018 * Allocates a struct net_device with private data area for driver use 11019 * and performs basic initialization. Also allocates subqueue structs 11020 * for each queue on the device. 11021 */ 11022struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name, 11023 unsigned char name_assign_type, 11024 void (*setup)(struct net_device *), 11025 unsigned int txqs, unsigned int rxqs) 11026{ 11027 struct net_device *dev; 11028 11029 BUG_ON(strlen(name) >= sizeof(dev->name)); 11030 11031 if (txqs < 1) { 11032 pr_err("alloc_netdev: Unable to allocate device with zero queues\n"); 11033 return NULL; 11034 } 11035 11036 if (rxqs < 1) { 11037 pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n"); 11038 return NULL; 11039 } 11040 11041 dev = kvzalloc(struct_size(dev, priv, sizeof_priv), 11042 GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL); 11043 if (!dev) 11044 return NULL; 11045 11046 dev->priv_len = sizeof_priv; 11047 11048 ref_tracker_dir_init(&dev->refcnt_tracker, 128, name); 11049#ifdef CONFIG_PCPU_DEV_REFCNT 11050 dev->pcpu_refcnt = alloc_percpu(int); 11051 if (!dev->pcpu_refcnt) 11052 goto free_dev; 11053 __dev_hold(dev); 11054#else 11055 refcount_set(&dev->dev_refcnt, 1); 11056#endif 11057 11058 if (dev_addr_init(dev)) 11059 goto free_pcpu; 11060 11061 dev_mc_init(dev); 11062 dev_uc_init(dev); 11063 11064 dev_net_set(dev, &init_net); 11065 11066 dev->gso_max_size = GSO_LEGACY_MAX_SIZE; 11067 dev->xdp_zc_max_segs = 1; 11068 dev->gso_max_segs = GSO_MAX_SEGS; 11069 dev->gro_max_size = GRO_LEGACY_MAX_SIZE; 11070 dev->gso_ipv4_max_size = GSO_LEGACY_MAX_SIZE; 11071 dev->gro_ipv4_max_size = GRO_LEGACY_MAX_SIZE; 11072 dev->tso_max_size = TSO_LEGACY_MAX_SIZE; 11073 dev->tso_max_segs = TSO_MAX_SEGS; 11074 dev->upper_level = 1; 11075 dev->lower_level = 1; 11076#ifdef CONFIG_LOCKDEP 11077 dev->nested_level = 0; 11078 INIT_LIST_HEAD(&dev->unlink_list); 11079#endif 11080 11081 INIT_LIST_HEAD(&dev->napi_list); 11082 INIT_LIST_HEAD(&dev->unreg_list); 11083 INIT_LIST_HEAD(&dev->close_list); 11084 INIT_LIST_HEAD(&dev->link_watch_list); 11085 INIT_LIST_HEAD(&dev->adj_list.upper); 11086 INIT_LIST_HEAD(&dev->adj_list.lower); 11087 INIT_LIST_HEAD(&dev->ptype_all); 11088 INIT_LIST_HEAD(&dev->ptype_specific); 11089 INIT_LIST_HEAD(&dev->net_notifier_list); 11090#ifdef CONFIG_NET_SCHED 11091 hash_init(dev->qdisc_hash); 11092#endif 11093 dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM; 11094 setup(dev); 11095 11096 if (!dev->tx_queue_len) { 11097 dev->priv_flags |= IFF_NO_QUEUE; 11098 dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN; 11099 } 11100 11101 dev->num_tx_queues = txqs; 11102 dev->real_num_tx_queues = txqs; 11103 if (netif_alloc_netdev_queues(dev)) 11104 goto free_all; 11105 11106 dev->num_rx_queues = rxqs; 11107 dev->real_num_rx_queues = rxqs; 11108 if (netif_alloc_rx_queues(dev)) 11109 goto free_all; 11110 dev->ethtool = kzalloc(sizeof(*dev->ethtool), GFP_KERNEL_ACCOUNT); 11111 if (!dev->ethtool) 11112 goto free_all; 11113 11114 strcpy(dev->name, name); 11115 dev->name_assign_type = name_assign_type; 11116 dev->group = INIT_NETDEV_GROUP; 11117 if (!dev->ethtool_ops) 11118 dev->ethtool_ops = &default_ethtool_ops; 11119 11120 nf_hook_netdev_init(dev); 11121 11122 return dev; 11123 11124free_all: 11125 free_netdev(dev); 11126 return NULL; 11127 11128free_pcpu: 11129#ifdef CONFIG_PCPU_DEV_REFCNT 11130 free_percpu(dev->pcpu_refcnt); 11131free_dev: 11132#endif 11133 kvfree(dev); 11134 return NULL; 11135} 11136EXPORT_SYMBOL(alloc_netdev_mqs); 11137 11138/** 11139 * free_netdev - free network device 11140 * @dev: device 11141 * 11142 * This function does the last stage of destroying an allocated device 11143 * interface. The reference to the device object is released. If this 11144 * is the last reference then it will be freed.Must be called in process 11145 * context. 11146 */ 11147void free_netdev(struct net_device *dev) 11148{ 11149 struct napi_struct *p, *n; 11150 11151 might_sleep(); 11152 11153 /* When called immediately after register_netdevice() failed the unwind 11154 * handling may still be dismantling the device. Handle that case by 11155 * deferring the free. 11156 */ 11157 if (dev->reg_state == NETREG_UNREGISTERING) { 11158 ASSERT_RTNL(); 11159 dev->needs_free_netdev = true; 11160 return; 11161 } 11162 11163 kfree(dev->ethtool); 11164 netif_free_tx_queues(dev); 11165 netif_free_rx_queues(dev); 11166 11167 kfree(rcu_dereference_protected(dev->ingress_queue, 1)); 11168 11169 /* Flush device addresses */ 11170 dev_addr_flush(dev); 11171 11172 list_for_each_entry_safe(p, n, &dev->napi_list, dev_list) 11173 netif_napi_del(p); 11174 11175 ref_tracker_dir_exit(&dev->refcnt_tracker); 11176#ifdef CONFIG_PCPU_DEV_REFCNT 11177 free_percpu(dev->pcpu_refcnt); 11178 dev->pcpu_refcnt = NULL; 11179#endif 11180 free_percpu(dev->core_stats); 11181 dev->core_stats = NULL; 11182 free_percpu(dev->xdp_bulkq); 11183 dev->xdp_bulkq = NULL; 11184 11185 /* Compatibility with error handling in drivers */ 11186 if (dev->reg_state == NETREG_UNINITIALIZED || 11187 dev->reg_state == NETREG_DUMMY) { 11188 kvfree(dev); 11189 return; 11190 } 11191 11192 BUG_ON(dev->reg_state != NETREG_UNREGISTERED); 11193 WRITE_ONCE(dev->reg_state, NETREG_RELEASED); 11194 11195 /* will free via device release */ 11196 put_device(&dev->dev); 11197} 11198EXPORT_SYMBOL(free_netdev); 11199 11200/** 11201 * alloc_netdev_dummy - Allocate and initialize a dummy net device. 11202 * @sizeof_priv: size of private data to allocate space for 11203 * 11204 * Return: the allocated net_device on success, NULL otherwise 11205 */ 11206struct net_device *alloc_netdev_dummy(int sizeof_priv) 11207{ 11208 return alloc_netdev(sizeof_priv, "dummy#", NET_NAME_UNKNOWN, 11209 init_dummy_netdev_core); 11210} 11211EXPORT_SYMBOL_GPL(alloc_netdev_dummy); 11212 11213/** 11214 * synchronize_net - Synchronize with packet receive processing 11215 * 11216 * Wait for packets currently being received to be done. 11217 * Does not block later packets from starting. 11218 */ 11219void synchronize_net(void) 11220{ 11221 might_sleep(); 11222 if (rtnl_is_locked()) 11223 synchronize_rcu_expedited(); 11224 else 11225 synchronize_rcu(); 11226} 11227EXPORT_SYMBOL(synchronize_net); 11228 11229static void netdev_rss_contexts_free(struct net_device *dev) 11230{ 11231 struct ethtool_rxfh_context *ctx; 11232 unsigned long context; 11233 11234 mutex_lock(&dev->ethtool->rss_lock); 11235 xa_for_each(&dev->ethtool->rss_ctx, context, ctx) { 11236 struct ethtool_rxfh_param rxfh; 11237 11238 rxfh.indir = ethtool_rxfh_context_indir(ctx); 11239 rxfh.key = ethtool_rxfh_context_key(ctx); 11240 rxfh.hfunc = ctx->hfunc; 11241 rxfh.input_xfrm = ctx->input_xfrm; 11242 rxfh.rss_context = context; 11243 rxfh.rss_delete = true; 11244 11245 xa_erase(&dev->ethtool->rss_ctx, context); 11246 if (dev->ethtool_ops->create_rxfh_context) 11247 dev->ethtool_ops->remove_rxfh_context(dev, ctx, 11248 context, NULL); 11249 else 11250 dev->ethtool_ops->set_rxfh(dev, &rxfh, NULL); 11251 kfree(ctx); 11252 } 11253 xa_destroy(&dev->ethtool->rss_ctx); 11254 mutex_unlock(&dev->ethtool->rss_lock); 11255} 11256 11257/** 11258 * unregister_netdevice_queue - remove device from the kernel 11259 * @dev: device 11260 * @head: list 11261 * 11262 * This function shuts down a device interface and removes it 11263 * from the kernel tables. 11264 * If head not NULL, device is queued to be unregistered later. 11265 * 11266 * Callers must hold the rtnl semaphore. You may want 11267 * unregister_netdev() instead of this. 11268 */ 11269 11270void unregister_netdevice_queue(struct net_device *dev, struct list_head *head) 11271{ 11272 ASSERT_RTNL(); 11273 11274 if (head) { 11275 list_move_tail(&dev->unreg_list, head); 11276 } else { 11277 LIST_HEAD(single); 11278 11279 list_add(&dev->unreg_list, &single); 11280 unregister_netdevice_many(&single); 11281 } 11282} 11283EXPORT_SYMBOL(unregister_netdevice_queue); 11284 11285void unregister_netdevice_many_notify(struct list_head *head, 11286 u32 portid, const struct nlmsghdr *nlh) 11287{ 11288 struct net_device *dev, *tmp; 11289 LIST_HEAD(close_head); 11290 int cnt = 0; 11291 11292 BUG_ON(dev_boot_phase); 11293 ASSERT_RTNL(); 11294 11295 if (list_empty(head)) 11296 return; 11297 11298 list_for_each_entry_safe(dev, tmp, head, unreg_list) { 11299 /* Some devices call without registering 11300 * for initialization unwind. Remove those 11301 * devices and proceed with the remaining. 11302 */ 11303 if (dev->reg_state == NETREG_UNINITIALIZED) { 11304 pr_debug("unregister_netdevice: device %s/%p never was registered\n", 11305 dev->name, dev); 11306 11307 WARN_ON(1); 11308 list_del(&dev->unreg_list); 11309 continue; 11310 } 11311 dev->dismantle = true; 11312 BUG_ON(dev->reg_state != NETREG_REGISTERED); 11313 } 11314 11315 /* If device is running, close it first. */ 11316 list_for_each_entry(dev, head, unreg_list) 11317 list_add_tail(&dev->close_list, &close_head); 11318 dev_close_many(&close_head, true); 11319 11320 list_for_each_entry(dev, head, unreg_list) { 11321 /* And unlink it from device chain. */ 11322 unlist_netdevice(dev); 11323 WRITE_ONCE(dev->reg_state, NETREG_UNREGISTERING); 11324 } 11325 flush_all_backlogs(); 11326 11327 synchronize_net(); 11328 11329 list_for_each_entry(dev, head, unreg_list) { 11330 struct sk_buff *skb = NULL; 11331 11332 /* Shutdown queueing discipline. */ 11333 dev_shutdown(dev); 11334 dev_tcx_uninstall(dev); 11335 dev_xdp_uninstall(dev); 11336 bpf_dev_bound_netdev_unregister(dev); 11337 11338 netdev_offload_xstats_disable_all(dev); 11339 11340 /* Notify protocols, that we are about to destroy 11341 * this device. They should clean all the things. 11342 */ 11343 call_netdevice_notifiers(NETDEV_UNREGISTER, dev); 11344 11345 if (!dev->rtnl_link_ops || 11346 dev->rtnl_link_state == RTNL_LINK_INITIALIZED) 11347 skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0, 11348 GFP_KERNEL, NULL, 0, 11349 portid, nlh); 11350 11351 /* 11352 * Flush the unicast and multicast chains 11353 */ 11354 dev_uc_flush(dev); 11355 dev_mc_flush(dev); 11356 11357 netdev_name_node_alt_flush(dev); 11358 netdev_name_node_free(dev->name_node); 11359 11360 netdev_rss_contexts_free(dev); 11361 11362 call_netdevice_notifiers(NETDEV_PRE_UNINIT, dev); 11363 11364 if (dev->netdev_ops->ndo_uninit) 11365 dev->netdev_ops->ndo_uninit(dev); 11366 11367 mutex_destroy(&dev->ethtool->rss_lock); 11368 11369 if (skb) 11370 rtmsg_ifinfo_send(skb, dev, GFP_KERNEL, portid, nlh); 11371 11372 /* Notifier chain MUST detach us all upper devices. */ 11373 WARN_ON(netdev_has_any_upper_dev(dev)); 11374 WARN_ON(netdev_has_any_lower_dev(dev)); 11375 11376 /* Remove entries from kobject tree */ 11377 netdev_unregister_kobject(dev); 11378#ifdef CONFIG_XPS 11379 /* Remove XPS queueing entries */ 11380 netif_reset_xps_queues_gt(dev, 0); 11381#endif 11382 } 11383 11384 synchronize_net(); 11385 11386 list_for_each_entry(dev, head, unreg_list) { 11387 netdev_put(dev, &dev->dev_registered_tracker); 11388 net_set_todo(dev); 11389 cnt++; 11390 } 11391 atomic_add(cnt, &dev_unreg_count); 11392 11393 list_del(head); 11394} 11395 11396/** 11397 * unregister_netdevice_many - unregister many devices 11398 * @head: list of devices 11399 * 11400 * Note: As most callers use a stack allocated list_head, 11401 * we force a list_del() to make sure stack wont be corrupted later. 11402 */ 11403void unregister_netdevice_many(struct list_head *head) 11404{ 11405 unregister_netdevice_many_notify(head, 0, NULL); 11406} 11407EXPORT_SYMBOL(unregister_netdevice_many); 11408 11409/** 11410 * unregister_netdev - remove device from the kernel 11411 * @dev: device 11412 * 11413 * This function shuts down a device interface and removes it 11414 * from the kernel tables. 11415 * 11416 * This is just a wrapper for unregister_netdevice that takes 11417 * the rtnl semaphore. In general you want to use this and not 11418 * unregister_netdevice. 11419 */ 11420void unregister_netdev(struct net_device *dev) 11421{ 11422 rtnl_lock(); 11423 unregister_netdevice(dev); 11424 rtnl_unlock(); 11425} 11426EXPORT_SYMBOL(unregister_netdev); 11427 11428/** 11429 * __dev_change_net_namespace - move device to different nethost namespace 11430 * @dev: device 11431 * @net: network namespace 11432 * @pat: If not NULL name pattern to try if the current device name 11433 * is already taken in the destination network namespace. 11434 * @new_ifindex: If not zero, specifies device index in the target 11435 * namespace. 11436 * 11437 * This function shuts down a device interface and moves it 11438 * to a new network namespace. On success 0 is returned, on 11439 * a failure a netagive errno code is returned. 11440 * 11441 * Callers must hold the rtnl semaphore. 11442 */ 11443 11444int __dev_change_net_namespace(struct net_device *dev, struct net *net, 11445 const char *pat, int new_ifindex) 11446{ 11447 struct netdev_name_node *name_node; 11448 struct net *net_old = dev_net(dev); 11449 char new_name[IFNAMSIZ] = {}; 11450 int err, new_nsid; 11451 11452 ASSERT_RTNL(); 11453 11454 /* Don't allow namespace local devices to be moved. */ 11455 err = -EINVAL; 11456 if (dev->features & NETIF_F_NETNS_LOCAL) 11457 goto out; 11458 11459 /* Ensure the device has been registrered */ 11460 if (dev->reg_state != NETREG_REGISTERED) 11461 goto out; 11462 11463 /* Get out if there is nothing todo */ 11464 err = 0; 11465 if (net_eq(net_old, net)) 11466 goto out; 11467 11468 /* Pick the destination device name, and ensure 11469 * we can use it in the destination network namespace. 11470 */ 11471 err = -EEXIST; 11472 if (netdev_name_in_use(net, dev->name)) { 11473 /* We get here if we can't use the current device name */ 11474 if (!pat) 11475 goto out; 11476 err = dev_prep_valid_name(net, dev, pat, new_name, EEXIST); 11477 if (err < 0) 11478 goto out; 11479 } 11480 /* Check that none of the altnames conflicts. */ 11481 err = -EEXIST; 11482 netdev_for_each_altname(dev, name_node) 11483 if (netdev_name_in_use(net, name_node->name)) 11484 goto out; 11485 11486 /* Check that new_ifindex isn't used yet. */ 11487 if (new_ifindex) { 11488 err = dev_index_reserve(net, new_ifindex); 11489 if (err < 0) 11490 goto out; 11491 } else { 11492 /* If there is an ifindex conflict assign a new one */ 11493 err = dev_index_reserve(net, dev->ifindex); 11494 if (err == -EBUSY) 11495 err = dev_index_reserve(net, 0); 11496 if (err < 0) 11497 goto out; 11498 new_ifindex = err; 11499 } 11500 11501 /* 11502 * And now a mini version of register_netdevice unregister_netdevice. 11503 */ 11504 11505 /* If device is running close it first. */ 11506 dev_close(dev); 11507 11508 /* And unlink it from device chain */ 11509 unlist_netdevice(dev); 11510 11511 synchronize_net(); 11512 11513 /* Shutdown queueing discipline. */ 11514 dev_shutdown(dev); 11515 11516 /* Notify protocols, that we are about to destroy 11517 * this device. They should clean all the things. 11518 * 11519 * Note that dev->reg_state stays at NETREG_REGISTERED. 11520 * This is wanted because this way 8021q and macvlan know 11521 * the device is just moving and can keep their slaves up. 11522 */ 11523 call_netdevice_notifiers(NETDEV_UNREGISTER, dev); 11524 rcu_barrier(); 11525 11526 new_nsid = peernet2id_alloc(dev_net(dev), net, GFP_KERNEL); 11527 11528 rtmsg_ifinfo_newnet(RTM_DELLINK, dev, ~0U, GFP_KERNEL, &new_nsid, 11529 new_ifindex); 11530 11531 /* 11532 * Flush the unicast and multicast chains 11533 */ 11534 dev_uc_flush(dev); 11535 dev_mc_flush(dev); 11536 11537 /* Send a netdev-removed uevent to the old namespace */ 11538 kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE); 11539 netdev_adjacent_del_links(dev); 11540 11541 /* Move per-net netdevice notifiers that are following the netdevice */ 11542 move_netdevice_notifiers_dev_net(dev, net); 11543 11544 /* Actually switch the network namespace */ 11545 dev_net_set(dev, net); 11546 dev->ifindex = new_ifindex; 11547 11548 if (new_name[0]) { 11549 /* Rename the netdev to prepared name */ 11550 write_seqlock_bh(&netdev_rename_lock); 11551 strscpy(dev->name, new_name, IFNAMSIZ); 11552 write_sequnlock_bh(&netdev_rename_lock); 11553 } 11554 11555 /* Fixup kobjects */ 11556 dev_set_uevent_suppress(&dev->dev, 1); 11557 err = device_rename(&dev->dev, dev->name); 11558 dev_set_uevent_suppress(&dev->dev, 0); 11559 WARN_ON(err); 11560 11561 /* Send a netdev-add uevent to the new namespace */ 11562 kobject_uevent(&dev->dev.kobj, KOBJ_ADD); 11563 netdev_adjacent_add_links(dev); 11564 11565 /* Adapt owner in case owning user namespace of target network 11566 * namespace is different from the original one. 11567 */ 11568 err = netdev_change_owner(dev, net_old, net); 11569 WARN_ON(err); 11570 11571 /* Add the device back in the hashes */ 11572 list_netdevice(dev); 11573 11574 /* Notify protocols, that a new device appeared. */ 11575 call_netdevice_notifiers(NETDEV_REGISTER, dev); 11576 11577 /* 11578 * Prevent userspace races by waiting until the network 11579 * device is fully setup before sending notifications. 11580 */ 11581 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL, 0, NULL); 11582 11583 synchronize_net(); 11584 err = 0; 11585out: 11586 return err; 11587} 11588EXPORT_SYMBOL_GPL(__dev_change_net_namespace); 11589 11590static int dev_cpu_dead(unsigned int oldcpu) 11591{ 11592 struct sk_buff **list_skb; 11593 struct sk_buff *skb; 11594 unsigned int cpu; 11595 struct softnet_data *sd, *oldsd, *remsd = NULL; 11596 11597 local_irq_disable(); 11598 cpu = smp_processor_id(); 11599 sd = &per_cpu(softnet_data, cpu); 11600 oldsd = &per_cpu(softnet_data, oldcpu); 11601 11602 /* Find end of our completion_queue. */ 11603 list_skb = &sd->completion_queue; 11604 while (*list_skb) 11605 list_skb = &(*list_skb)->next; 11606 /* Append completion queue from offline CPU. */ 11607 *list_skb = oldsd->completion_queue; 11608 oldsd->completion_queue = NULL; 11609 11610 /* Append output queue from offline CPU. */ 11611 if (oldsd->output_queue) { 11612 *sd->output_queue_tailp = oldsd->output_queue; 11613 sd->output_queue_tailp = oldsd->output_queue_tailp; 11614 oldsd->output_queue = NULL; 11615 oldsd->output_queue_tailp = &oldsd->output_queue; 11616 } 11617 /* Append NAPI poll list from offline CPU, with one exception : 11618 * process_backlog() must be called by cpu owning percpu backlog. 11619 * We properly handle process_queue & input_pkt_queue later. 11620 */ 11621 while (!list_empty(&oldsd->poll_list)) { 11622 struct napi_struct *napi = list_first_entry(&oldsd->poll_list, 11623 struct napi_struct, 11624 poll_list); 11625 11626 list_del_init(&napi->poll_list); 11627 if (napi->poll == process_backlog) 11628 napi->state &= NAPIF_STATE_THREADED; 11629 else 11630 ____napi_schedule(sd, napi); 11631 } 11632 11633 raise_softirq_irqoff(NET_TX_SOFTIRQ); 11634 local_irq_enable(); 11635 11636 if (!use_backlog_threads()) { 11637#ifdef CONFIG_RPS 11638 remsd = oldsd->rps_ipi_list; 11639 oldsd->rps_ipi_list = NULL; 11640#endif 11641 /* send out pending IPI's on offline CPU */ 11642 net_rps_send_ipi(remsd); 11643 } 11644 11645 /* Process offline CPU's input_pkt_queue */ 11646 while ((skb = __skb_dequeue(&oldsd->process_queue))) { 11647 netif_rx(skb); 11648 rps_input_queue_head_incr(oldsd); 11649 } 11650 while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) { 11651 netif_rx(skb); 11652 rps_input_queue_head_incr(oldsd); 11653 } 11654 11655 return 0; 11656} 11657 11658/** 11659 * netdev_increment_features - increment feature set by one 11660 * @all: current feature set 11661 * @one: new feature set 11662 * @mask: mask feature set 11663 * 11664 * Computes a new feature set after adding a device with feature set 11665 * @one to the master device with current feature set @all. Will not 11666 * enable anything that is off in @mask. Returns the new feature set. 11667 */ 11668netdev_features_t netdev_increment_features(netdev_features_t all, 11669 netdev_features_t one, netdev_features_t mask) 11670{ 11671 if (mask & NETIF_F_HW_CSUM) 11672 mask |= NETIF_F_CSUM_MASK; 11673 mask |= NETIF_F_VLAN_CHALLENGED; 11674 11675 all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask; 11676 all &= one | ~NETIF_F_ALL_FOR_ALL; 11677 11678 /* If one device supports hw checksumming, set for all. */ 11679 if (all & NETIF_F_HW_CSUM) 11680 all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM); 11681 11682 return all; 11683} 11684EXPORT_SYMBOL(netdev_increment_features); 11685 11686static struct hlist_head * __net_init netdev_create_hash(void) 11687{ 11688 int i; 11689 struct hlist_head *hash; 11690 11691 hash = kmalloc_array(NETDEV_HASHENTRIES, sizeof(*hash), GFP_KERNEL); 11692 if (hash != NULL) 11693 for (i = 0; i < NETDEV_HASHENTRIES; i++) 11694 INIT_HLIST_HEAD(&hash[i]); 11695 11696 return hash; 11697} 11698 11699/* Initialize per network namespace state */ 11700static int __net_init netdev_init(struct net *net) 11701{ 11702 BUILD_BUG_ON(GRO_HASH_BUCKETS > 11703 8 * sizeof_field(struct napi_struct, gro_bitmask)); 11704 11705 INIT_LIST_HEAD(&net->dev_base_head); 11706 11707 net->dev_name_head = netdev_create_hash(); 11708 if (net->dev_name_head == NULL) 11709 goto err_name; 11710 11711 net->dev_index_head = netdev_create_hash(); 11712 if (net->dev_index_head == NULL) 11713 goto err_idx; 11714 11715 xa_init_flags(&net->dev_by_index, XA_FLAGS_ALLOC1); 11716 11717 RAW_INIT_NOTIFIER_HEAD(&net->netdev_chain); 11718 11719 return 0; 11720 11721err_idx: 11722 kfree(net->dev_name_head); 11723err_name: 11724 return -ENOMEM; 11725} 11726 11727/** 11728 * netdev_drivername - network driver for the device 11729 * @dev: network device 11730 * 11731 * Determine network driver for device. 11732 */ 11733const char *netdev_drivername(const struct net_device *dev) 11734{ 11735 const struct device_driver *driver; 11736 const struct device *parent; 11737 const char *empty = ""; 11738 11739 parent = dev->dev.parent; 11740 if (!parent) 11741 return empty; 11742 11743 driver = parent->driver; 11744 if (driver && driver->name) 11745 return driver->name; 11746 return empty; 11747} 11748 11749static void __netdev_printk(const char *level, const struct net_device *dev, 11750 struct va_format *vaf) 11751{ 11752 if (dev && dev->dev.parent) { 11753 dev_printk_emit(level[1] - '0', 11754 dev->dev.parent, 11755 "%s %s %s%s: %pV", 11756 dev_driver_string(dev->dev.parent), 11757 dev_name(dev->dev.parent), 11758 netdev_name(dev), netdev_reg_state(dev), 11759 vaf); 11760 } else if (dev) { 11761 printk("%s%s%s: %pV", 11762 level, netdev_name(dev), netdev_reg_state(dev), vaf); 11763 } else { 11764 printk("%s(NULL net_device): %pV", level, vaf); 11765 } 11766} 11767 11768void netdev_printk(const char *level, const struct net_device *dev, 11769 const char *format, ...) 11770{ 11771 struct va_format vaf; 11772 va_list args; 11773 11774 va_start(args, format); 11775 11776 vaf.fmt = format; 11777 vaf.va = &args; 11778 11779 __netdev_printk(level, dev, &vaf); 11780 11781 va_end(args); 11782} 11783EXPORT_SYMBOL(netdev_printk); 11784 11785#define define_netdev_printk_level(func, level) \ 11786void func(const struct net_device *dev, const char *fmt, ...) \ 11787{ \ 11788 struct va_format vaf; \ 11789 va_list args; \ 11790 \ 11791 va_start(args, fmt); \ 11792 \ 11793 vaf.fmt = fmt; \ 11794 vaf.va = &args; \ 11795 \ 11796 __netdev_printk(level, dev, &vaf); \ 11797 \ 11798 va_end(args); \ 11799} \ 11800EXPORT_SYMBOL(func); 11801 11802define_netdev_printk_level(netdev_emerg, KERN_EMERG); 11803define_netdev_printk_level(netdev_alert, KERN_ALERT); 11804define_netdev_printk_level(netdev_crit, KERN_CRIT); 11805define_netdev_printk_level(netdev_err, KERN_ERR); 11806define_netdev_printk_level(netdev_warn, KERN_WARNING); 11807define_netdev_printk_level(netdev_notice, KERN_NOTICE); 11808define_netdev_printk_level(netdev_info, KERN_INFO); 11809 11810static void __net_exit netdev_exit(struct net *net) 11811{ 11812 kfree(net->dev_name_head); 11813 kfree(net->dev_index_head); 11814 xa_destroy(&net->dev_by_index); 11815 if (net != &init_net) 11816 WARN_ON_ONCE(!list_empty(&net->dev_base_head)); 11817} 11818 11819static struct pernet_operations __net_initdata netdev_net_ops = { 11820 .init = netdev_init, 11821 .exit = netdev_exit, 11822}; 11823 11824static void __net_exit default_device_exit_net(struct net *net) 11825{ 11826 struct netdev_name_node *name_node, *tmp; 11827 struct net_device *dev, *aux; 11828 /* 11829 * Push all migratable network devices back to the 11830 * initial network namespace 11831 */ 11832 ASSERT_RTNL(); 11833 for_each_netdev_safe(net, dev, aux) { 11834 int err; 11835 char fb_name[IFNAMSIZ]; 11836 11837 /* Ignore unmoveable devices (i.e. loopback) */ 11838 if (dev->features & NETIF_F_NETNS_LOCAL) 11839 continue; 11840 11841 /* Leave virtual devices for the generic cleanup */ 11842 if (dev->rtnl_link_ops && !dev->rtnl_link_ops->netns_refund) 11843 continue; 11844 11845 /* Push remaining network devices to init_net */ 11846 snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex); 11847 if (netdev_name_in_use(&init_net, fb_name)) 11848 snprintf(fb_name, IFNAMSIZ, "dev%%d"); 11849 11850 netdev_for_each_altname_safe(dev, name_node, tmp) 11851 if (netdev_name_in_use(&init_net, name_node->name)) 11852 __netdev_name_node_alt_destroy(name_node); 11853 11854 err = dev_change_net_namespace(dev, &init_net, fb_name); 11855 if (err) { 11856 pr_emerg("%s: failed to move %s to init_net: %d\n", 11857 __func__, dev->name, err); 11858 BUG(); 11859 } 11860 } 11861} 11862 11863static void __net_exit default_device_exit_batch(struct list_head *net_list) 11864{ 11865 /* At exit all network devices most be removed from a network 11866 * namespace. Do this in the reverse order of registration. 11867 * Do this across as many network namespaces as possible to 11868 * improve batching efficiency. 11869 */ 11870 struct net_device *dev; 11871 struct net *net; 11872 LIST_HEAD(dev_kill_list); 11873 11874 rtnl_lock(); 11875 list_for_each_entry(net, net_list, exit_list) { 11876 default_device_exit_net(net); 11877 cond_resched(); 11878 } 11879 11880 list_for_each_entry(net, net_list, exit_list) { 11881 for_each_netdev_reverse(net, dev) { 11882 if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink) 11883 dev->rtnl_link_ops->dellink(dev, &dev_kill_list); 11884 else 11885 unregister_netdevice_queue(dev, &dev_kill_list); 11886 } 11887 } 11888 unregister_netdevice_many(&dev_kill_list); 11889 rtnl_unlock(); 11890} 11891 11892static struct pernet_operations __net_initdata default_device_ops = { 11893 .exit_batch = default_device_exit_batch, 11894}; 11895 11896static void __init net_dev_struct_check(void) 11897{ 11898 /* TX read-mostly hotpath */ 11899 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, priv_flags); 11900 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, netdev_ops); 11901 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, header_ops); 11902 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, _tx); 11903 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, real_num_tx_queues); 11904 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_max_size); 11905 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_ipv4_max_size); 11906 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_max_segs); 11907 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_partial_features); 11908 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, num_tc); 11909 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, mtu); 11910 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, needed_headroom); 11911 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, tc_to_txq); 11912#ifdef CONFIG_XPS 11913 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, xps_maps); 11914#endif 11915#ifdef CONFIG_NETFILTER_EGRESS 11916 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, nf_hooks_egress); 11917#endif 11918#ifdef CONFIG_NET_XGRESS 11919 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, tcx_egress); 11920#endif 11921 CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_tx, 160); 11922 11923 /* TXRX read-mostly hotpath */ 11924 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, lstats); 11925 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, state); 11926 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, flags); 11927 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, hard_header_len); 11928 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, features); 11929 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, ip6_ptr); 11930 CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_txrx, 46); 11931 11932 /* RX read-mostly hotpath */ 11933 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, ptype_specific); 11934 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, ifindex); 11935 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, real_num_rx_queues); 11936 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, _rx); 11937 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, gro_flush_timeout); 11938 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, napi_defer_hard_irqs); 11939 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, gro_max_size); 11940 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, gro_ipv4_max_size); 11941 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, rx_handler); 11942 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, rx_handler_data); 11943 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, nd_net); 11944#ifdef CONFIG_NETPOLL 11945 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, npinfo); 11946#endif 11947#ifdef CONFIG_NET_XGRESS 11948 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, tcx_ingress); 11949#endif 11950 CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_rx, 104); 11951} 11952 11953/* 11954 * Initialize the DEV module. At boot time this walks the device list and 11955 * unhooks any devices that fail to initialise (normally hardware not 11956 * present) and leaves us with a valid list of present and active devices. 11957 * 11958 */ 11959 11960/* We allocate 256 pages for each CPU if PAGE_SHIFT is 12 */ 11961#define SYSTEM_PERCPU_PAGE_POOL_SIZE ((1 << 20) / PAGE_SIZE) 11962 11963static int net_page_pool_create(int cpuid) 11964{ 11965#if IS_ENABLED(CONFIG_PAGE_POOL) 11966 struct page_pool_params page_pool_params = { 11967 .pool_size = SYSTEM_PERCPU_PAGE_POOL_SIZE, 11968 .flags = PP_FLAG_SYSTEM_POOL, 11969 .nid = cpu_to_mem(cpuid), 11970 }; 11971 struct page_pool *pp_ptr; 11972 11973 pp_ptr = page_pool_create_percpu(&page_pool_params, cpuid); 11974 if (IS_ERR(pp_ptr)) 11975 return -ENOMEM; 11976 11977 per_cpu(system_page_pool, cpuid) = pp_ptr; 11978#endif 11979 return 0; 11980} 11981 11982static int backlog_napi_should_run(unsigned int cpu) 11983{ 11984 struct softnet_data *sd = per_cpu_ptr(&softnet_data, cpu); 11985 struct napi_struct *napi = &sd->backlog; 11986 11987 return test_bit(NAPI_STATE_SCHED_THREADED, &napi->state); 11988} 11989 11990static void run_backlog_napi(unsigned int cpu) 11991{ 11992 struct softnet_data *sd = per_cpu_ptr(&softnet_data, cpu); 11993 11994 napi_threaded_poll_loop(&sd->backlog); 11995} 11996 11997static void backlog_napi_setup(unsigned int cpu) 11998{ 11999 struct softnet_data *sd = per_cpu_ptr(&softnet_data, cpu); 12000 struct napi_struct *napi = &sd->backlog; 12001 12002 napi->thread = this_cpu_read(backlog_napi); 12003 set_bit(NAPI_STATE_THREADED, &napi->state); 12004} 12005 12006static struct smp_hotplug_thread backlog_threads = { 12007 .store = &backlog_napi, 12008 .thread_should_run = backlog_napi_should_run, 12009 .thread_fn = run_backlog_napi, 12010 .thread_comm = "backlog_napi/%u", 12011 .setup = backlog_napi_setup, 12012}; 12013 12014/* 12015 * This is called single threaded during boot, so no need 12016 * to take the rtnl semaphore. 12017 */ 12018static int __init net_dev_init(void) 12019{ 12020 int i, rc = -ENOMEM; 12021 12022 BUG_ON(!dev_boot_phase); 12023 12024 net_dev_struct_check(); 12025 12026 if (dev_proc_init()) 12027 goto out; 12028 12029 if (netdev_kobject_init()) 12030 goto out; 12031 12032 for (i = 0; i < PTYPE_HASH_SIZE; i++) 12033 INIT_LIST_HEAD(&ptype_base[i]); 12034 12035 if (register_pernet_subsys(&netdev_net_ops)) 12036 goto out; 12037 12038 /* 12039 * Initialise the packet receive queues. 12040 */ 12041 12042 for_each_possible_cpu(i) { 12043 struct work_struct *flush = per_cpu_ptr(&flush_works, i); 12044 struct softnet_data *sd = &per_cpu(softnet_data, i); 12045 12046 INIT_WORK(flush, flush_backlog); 12047 12048 skb_queue_head_init(&sd->input_pkt_queue); 12049 skb_queue_head_init(&sd->process_queue); 12050#ifdef CONFIG_XFRM_OFFLOAD 12051 skb_queue_head_init(&sd->xfrm_backlog); 12052#endif 12053 INIT_LIST_HEAD(&sd->poll_list); 12054 sd->output_queue_tailp = &sd->output_queue; 12055#ifdef CONFIG_RPS 12056 INIT_CSD(&sd->csd, rps_trigger_softirq, sd); 12057 sd->cpu = i; 12058#endif 12059 INIT_CSD(&sd->defer_csd, trigger_rx_softirq, sd); 12060 spin_lock_init(&sd->defer_lock); 12061 12062 init_gro_hash(&sd->backlog); 12063 sd->backlog.poll = process_backlog; 12064 sd->backlog.weight = weight_p; 12065 INIT_LIST_HEAD(&sd->backlog.poll_list); 12066 12067 if (net_page_pool_create(i)) 12068 goto out; 12069 } 12070 if (use_backlog_threads()) 12071 smpboot_register_percpu_thread(&backlog_threads); 12072 12073 dev_boot_phase = 0; 12074 12075 /* The loopback device is special if any other network devices 12076 * is present in a network namespace the loopback device must 12077 * be present. Since we now dynamically allocate and free the 12078 * loopback device ensure this invariant is maintained by 12079 * keeping the loopback device as the first device on the 12080 * list of network devices. Ensuring the loopback devices 12081 * is the first device that appears and the last network device 12082 * that disappears. 12083 */ 12084 if (register_pernet_device(&loopback_net_ops)) 12085 goto out; 12086 12087 if (register_pernet_device(&default_device_ops)) 12088 goto out; 12089 12090 open_softirq(NET_TX_SOFTIRQ, net_tx_action); 12091 open_softirq(NET_RX_SOFTIRQ, net_rx_action); 12092 12093 rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead", 12094 NULL, dev_cpu_dead); 12095 WARN_ON(rc < 0); 12096 rc = 0; 12097 12098 /* avoid static key IPIs to isolated CPUs */ 12099 if (housekeeping_enabled(HK_TYPE_MISC)) 12100 net_enable_timestamp(); 12101out: 12102 if (rc < 0) { 12103 for_each_possible_cpu(i) { 12104 struct page_pool *pp_ptr; 12105 12106 pp_ptr = per_cpu(system_page_pool, i); 12107 if (!pp_ptr) 12108 continue; 12109 12110 page_pool_destroy(pp_ptr); 12111 per_cpu(system_page_pool, i) = NULL; 12112 } 12113 } 12114 12115 return rc; 12116} 12117 12118subsys_initcall(net_dev_init);