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