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