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