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