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