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