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