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