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 EXPORT_IPV6_MOD_GPL(netdev_copy_name); 1167 1168 /** 1169 * netdev_get_name - get a netdevice name, knowing its ifindex. 1170 * @net: network namespace 1171 * @name: a pointer to the buffer where the name will be stored. 1172 * @ifindex: the ifindex of the interface to get the name from. 1173 */ 1174 int netdev_get_name(struct net *net, char *name, int ifindex) 1175 { 1176 struct net_device *dev; 1177 int ret; 1178 1179 rcu_read_lock(); 1180 1181 dev = dev_get_by_index_rcu(net, ifindex); 1182 if (!dev) { 1183 ret = -ENODEV; 1184 goto out; 1185 } 1186 1187 netdev_copy_name(dev, name); 1188 1189 ret = 0; 1190 out: 1191 rcu_read_unlock(); 1192 return ret; 1193 } 1194 1195 static bool dev_addr_cmp(struct net_device *dev, unsigned short type, 1196 const char *ha) 1197 { 1198 return dev->type == type && !memcmp(dev->dev_addr, ha, dev->addr_len); 1199 } 1200 1201 /** 1202 * dev_getbyhwaddr_rcu - find a device by its hardware address 1203 * @net: the applicable net namespace 1204 * @type: media type of device 1205 * @ha: hardware address 1206 * 1207 * Search for an interface by MAC address. Returns NULL if the device 1208 * is not found or a pointer to the device. 1209 * The caller must hold RCU. 1210 * The returned device has not had its ref count increased 1211 * and the caller must therefore be careful about locking 1212 * 1213 */ 1214 1215 struct net_device *dev_getbyhwaddr_rcu(struct net *net, unsigned short type, 1216 const char *ha) 1217 { 1218 struct net_device *dev; 1219 1220 for_each_netdev_rcu(net, dev) 1221 if (dev_addr_cmp(dev, type, ha)) 1222 return dev; 1223 1224 return NULL; 1225 } 1226 EXPORT_SYMBOL(dev_getbyhwaddr_rcu); 1227 1228 /** 1229 * dev_getbyhwaddr() - find a device by its hardware address 1230 * @net: the applicable net namespace 1231 * @type: media type of device 1232 * @ha: hardware address 1233 * 1234 * Similar to dev_getbyhwaddr_rcu(), but the owner needs to hold 1235 * rtnl_lock. 1236 * 1237 * Context: rtnl_lock() must be held. 1238 * Return: pointer to the net_device, or NULL if not found 1239 */ 1240 struct net_device *dev_getbyhwaddr(struct net *net, unsigned short type, 1241 const char *ha) 1242 { 1243 struct net_device *dev; 1244 1245 ASSERT_RTNL(); 1246 for_each_netdev(net, dev) 1247 if (dev_addr_cmp(dev, type, ha)) 1248 return dev; 1249 1250 return NULL; 1251 } 1252 EXPORT_SYMBOL(dev_getbyhwaddr); 1253 1254 struct net_device *dev_getfirstbyhwtype(struct net *net, unsigned short type) 1255 { 1256 struct net_device *dev, *ret = NULL; 1257 1258 rcu_read_lock(); 1259 for_each_netdev_rcu(net, dev) 1260 if (dev->type == type) { 1261 dev_hold(dev); 1262 ret = dev; 1263 break; 1264 } 1265 rcu_read_unlock(); 1266 return ret; 1267 } 1268 EXPORT_SYMBOL(dev_getfirstbyhwtype); 1269 1270 /** 1271 * netdev_get_by_flags_rcu - find any device with given flags 1272 * @net: the applicable net namespace 1273 * @tracker: tracking object for the acquired reference 1274 * @if_flags: IFF_* values 1275 * @mask: bitmask of bits in if_flags to check 1276 * 1277 * Search for any interface with the given flags. 1278 * 1279 * Context: rcu_read_lock() must be held. 1280 * Returns: NULL if a device is not found or a pointer to the device. 1281 */ 1282 struct net_device *netdev_get_by_flags_rcu(struct net *net, netdevice_tracker *tracker, 1283 unsigned short if_flags, unsigned short mask) 1284 { 1285 struct net_device *dev; 1286 1287 for_each_netdev_rcu(net, dev) { 1288 if (((READ_ONCE(dev->flags) ^ if_flags) & mask) == 0) { 1289 netdev_hold(dev, tracker, GFP_ATOMIC); 1290 return dev; 1291 } 1292 } 1293 1294 return NULL; 1295 } 1296 EXPORT_IPV6_MOD(netdev_get_by_flags_rcu); 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 netif_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_NS_GPL(netif_close_many, "NETDEV_INTERNAL"); 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 netif_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 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 (unlikely(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 (unlikely(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 netdev_ops_assert_locked(dev); 3183 3184 rc = netdev_queue_update_kobjects(dev, dev->real_num_tx_queues, 3185 txq); 3186 if (rc) 3187 return rc; 3188 3189 if (dev->num_tc) 3190 netif_setup_tc(dev, txq); 3191 3192 net_shaper_set_real_num_tx_queues(dev, txq); 3193 3194 dev_qdisc_change_real_num_tx(dev, txq); 3195 3196 dev->real_num_tx_queues = txq; 3197 3198 if (disabling) { 3199 synchronize_net(); 3200 qdisc_reset_all_tx_gt(dev, txq); 3201 #ifdef CONFIG_XPS 3202 netif_reset_xps_queues_gt(dev, txq); 3203 #endif 3204 } 3205 } else { 3206 dev->real_num_tx_queues = txq; 3207 } 3208 3209 return 0; 3210 } 3211 EXPORT_SYMBOL(netif_set_real_num_tx_queues); 3212 3213 /** 3214 * netif_set_real_num_rx_queues - set actual number of RX queues used 3215 * @dev: Network device 3216 * @rxq: Actual number of RX queues 3217 * 3218 * This must be called either with the rtnl_lock held or before 3219 * registration of the net device. Returns 0 on success, or a 3220 * negative error code. If called before registration, it always 3221 * succeeds. 3222 */ 3223 int netif_set_real_num_rx_queues(struct net_device *dev, unsigned int rxq) 3224 { 3225 int rc; 3226 3227 if (rxq < 1 || rxq > dev->num_rx_queues) 3228 return -EINVAL; 3229 3230 if (dev->reg_state == NETREG_REGISTERED) { 3231 netdev_ops_assert_locked(dev); 3232 3233 rc = net_rx_queue_update_kobjects(dev, dev->real_num_rx_queues, 3234 rxq); 3235 if (rc) 3236 return rc; 3237 } 3238 3239 dev->real_num_rx_queues = rxq; 3240 return 0; 3241 } 3242 EXPORT_SYMBOL(netif_set_real_num_rx_queues); 3243 3244 /** 3245 * netif_set_real_num_queues - set actual number of RX and TX queues used 3246 * @dev: Network device 3247 * @txq: Actual number of TX queues 3248 * @rxq: Actual number of RX queues 3249 * 3250 * Set the real number of both TX and RX queues. 3251 * Does nothing if the number of queues is already correct. 3252 */ 3253 int netif_set_real_num_queues(struct net_device *dev, 3254 unsigned int txq, unsigned int rxq) 3255 { 3256 unsigned int old_rxq = dev->real_num_rx_queues; 3257 int err; 3258 3259 if (txq < 1 || txq > dev->num_tx_queues || 3260 rxq < 1 || rxq > dev->num_rx_queues) 3261 return -EINVAL; 3262 3263 /* Start from increases, so the error path only does decreases - 3264 * decreases can't fail. 3265 */ 3266 if (rxq > dev->real_num_rx_queues) { 3267 err = netif_set_real_num_rx_queues(dev, rxq); 3268 if (err) 3269 return err; 3270 } 3271 if (txq > dev->real_num_tx_queues) { 3272 err = netif_set_real_num_tx_queues(dev, txq); 3273 if (err) 3274 goto undo_rx; 3275 } 3276 if (rxq < dev->real_num_rx_queues) 3277 WARN_ON(netif_set_real_num_rx_queues(dev, rxq)); 3278 if (txq < dev->real_num_tx_queues) 3279 WARN_ON(netif_set_real_num_tx_queues(dev, txq)); 3280 3281 return 0; 3282 undo_rx: 3283 WARN_ON(netif_set_real_num_rx_queues(dev, old_rxq)); 3284 return err; 3285 } 3286 EXPORT_SYMBOL(netif_set_real_num_queues); 3287 3288 /** 3289 * netif_set_tso_max_size() - set the max size of TSO frames supported 3290 * @dev: netdev to update 3291 * @size: max skb->len of a TSO frame 3292 * 3293 * Set the limit on the size of TSO super-frames the device can handle. 3294 * Unless explicitly set the stack will assume the value of 3295 * %GSO_LEGACY_MAX_SIZE. 3296 */ 3297 void netif_set_tso_max_size(struct net_device *dev, unsigned int size) 3298 { 3299 dev->tso_max_size = min(GSO_MAX_SIZE, size); 3300 if (size < READ_ONCE(dev->gso_max_size)) 3301 netif_set_gso_max_size(dev, size); 3302 if (size < READ_ONCE(dev->gso_ipv4_max_size)) 3303 netif_set_gso_ipv4_max_size(dev, size); 3304 } 3305 EXPORT_SYMBOL(netif_set_tso_max_size); 3306 3307 /** 3308 * netif_set_tso_max_segs() - set the max number of segs supported for TSO 3309 * @dev: netdev to update 3310 * @segs: max number of TCP segments 3311 * 3312 * Set the limit on the number of TCP segments the device can generate from 3313 * a single TSO super-frame. 3314 * Unless explicitly set the stack will assume the value of %GSO_MAX_SEGS. 3315 */ 3316 void netif_set_tso_max_segs(struct net_device *dev, unsigned int segs) 3317 { 3318 dev->tso_max_segs = segs; 3319 if (segs < READ_ONCE(dev->gso_max_segs)) 3320 netif_set_gso_max_segs(dev, segs); 3321 } 3322 EXPORT_SYMBOL(netif_set_tso_max_segs); 3323 3324 /** 3325 * netif_inherit_tso_max() - copy all TSO limits from a lower device to an upper 3326 * @to: netdev to update 3327 * @from: netdev from which to copy the limits 3328 */ 3329 void netif_inherit_tso_max(struct net_device *to, const struct net_device *from) 3330 { 3331 netif_set_tso_max_size(to, from->tso_max_size); 3332 netif_set_tso_max_segs(to, from->tso_max_segs); 3333 } 3334 EXPORT_SYMBOL(netif_inherit_tso_max); 3335 3336 /** 3337 * netif_get_num_default_rss_queues - default number of RSS queues 3338 * 3339 * Default value is the number of physical cores if there are only 1 or 2, or 3340 * divided by 2 if there are more. 3341 */ 3342 int netif_get_num_default_rss_queues(void) 3343 { 3344 cpumask_var_t cpus; 3345 int cpu, count = 0; 3346 3347 if (unlikely(is_kdump_kernel() || !zalloc_cpumask_var(&cpus, GFP_KERNEL))) 3348 return 1; 3349 3350 cpumask_copy(cpus, cpu_online_mask); 3351 for_each_cpu(cpu, cpus) { 3352 ++count; 3353 cpumask_andnot(cpus, cpus, topology_sibling_cpumask(cpu)); 3354 } 3355 free_cpumask_var(cpus); 3356 3357 return count > 2 ? DIV_ROUND_UP(count, 2) : count; 3358 } 3359 EXPORT_SYMBOL(netif_get_num_default_rss_queues); 3360 3361 static void __netif_reschedule(struct Qdisc *q) 3362 { 3363 struct softnet_data *sd; 3364 unsigned long flags; 3365 3366 local_irq_save(flags); 3367 sd = this_cpu_ptr(&softnet_data); 3368 q->next_sched = NULL; 3369 *sd->output_queue_tailp = q; 3370 sd->output_queue_tailp = &q->next_sched; 3371 raise_softirq_irqoff(NET_TX_SOFTIRQ); 3372 local_irq_restore(flags); 3373 } 3374 3375 void __netif_schedule(struct Qdisc *q) 3376 { 3377 /* If q->defer_list is not empty, at least one thread is 3378 * in __dev_xmit_skb() before llist_del_all(&q->defer_list). 3379 * This thread will attempt to run the queue. 3380 */ 3381 if (!llist_empty(&q->defer_list)) 3382 return; 3383 3384 if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state)) 3385 __netif_reschedule(q); 3386 } 3387 EXPORT_SYMBOL(__netif_schedule); 3388 3389 struct dev_kfree_skb_cb { 3390 enum skb_drop_reason reason; 3391 }; 3392 3393 static struct dev_kfree_skb_cb *get_kfree_skb_cb(const struct sk_buff *skb) 3394 { 3395 return (struct dev_kfree_skb_cb *)skb->cb; 3396 } 3397 3398 void netif_schedule_queue(struct netdev_queue *txq) 3399 { 3400 rcu_read_lock(); 3401 if (!netif_xmit_stopped(txq)) { 3402 struct Qdisc *q = rcu_dereference(txq->qdisc); 3403 3404 __netif_schedule(q); 3405 } 3406 rcu_read_unlock(); 3407 } 3408 EXPORT_SYMBOL(netif_schedule_queue); 3409 3410 void netif_tx_wake_queue(struct netdev_queue *dev_queue) 3411 { 3412 if (test_and_clear_bit(__QUEUE_STATE_DRV_XOFF, &dev_queue->state)) { 3413 struct Qdisc *q; 3414 3415 rcu_read_lock(); 3416 q = rcu_dereference(dev_queue->qdisc); 3417 __netif_schedule(q); 3418 rcu_read_unlock(); 3419 } 3420 } 3421 EXPORT_SYMBOL(netif_tx_wake_queue); 3422 3423 void dev_kfree_skb_irq_reason(struct sk_buff *skb, enum skb_drop_reason reason) 3424 { 3425 unsigned long flags; 3426 3427 if (unlikely(!skb)) 3428 return; 3429 3430 if (likely(refcount_read(&skb->users) == 1)) { 3431 smp_rmb(); 3432 refcount_set(&skb->users, 0); 3433 } else if (likely(!refcount_dec_and_test(&skb->users))) { 3434 return; 3435 } 3436 get_kfree_skb_cb(skb)->reason = reason; 3437 local_irq_save(flags); 3438 skb->next = __this_cpu_read(softnet_data.completion_queue); 3439 __this_cpu_write(softnet_data.completion_queue, skb); 3440 raise_softirq_irqoff(NET_TX_SOFTIRQ); 3441 local_irq_restore(flags); 3442 } 3443 EXPORT_SYMBOL(dev_kfree_skb_irq_reason); 3444 3445 void dev_kfree_skb_any_reason(struct sk_buff *skb, enum skb_drop_reason reason) 3446 { 3447 if (in_hardirq() || irqs_disabled()) 3448 dev_kfree_skb_irq_reason(skb, reason); 3449 else 3450 kfree_skb_reason(skb, reason); 3451 } 3452 EXPORT_SYMBOL(dev_kfree_skb_any_reason); 3453 3454 3455 /** 3456 * netif_device_detach - mark device as removed 3457 * @dev: network device 3458 * 3459 * Mark device as removed from system and therefore no longer available. 3460 */ 3461 void netif_device_detach(struct net_device *dev) 3462 { 3463 if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) && 3464 netif_running(dev)) { 3465 netif_tx_stop_all_queues(dev); 3466 } 3467 } 3468 EXPORT_SYMBOL(netif_device_detach); 3469 3470 /** 3471 * netif_device_attach - mark device as attached 3472 * @dev: network device 3473 * 3474 * Mark device as attached from system and restart if needed. 3475 */ 3476 void netif_device_attach(struct net_device *dev) 3477 { 3478 if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) && 3479 netif_running(dev)) { 3480 netif_tx_wake_all_queues(dev); 3481 netdev_watchdog_up(dev); 3482 } 3483 } 3484 EXPORT_SYMBOL(netif_device_attach); 3485 3486 /* 3487 * Returns a Tx hash based on the given packet descriptor a Tx queues' number 3488 * to be used as a distribution range. 3489 */ 3490 static u16 skb_tx_hash(const struct net_device *dev, 3491 const struct net_device *sb_dev, 3492 struct sk_buff *skb) 3493 { 3494 u32 hash; 3495 u16 qoffset = 0; 3496 u16 qcount = dev->real_num_tx_queues; 3497 3498 if (dev->num_tc) { 3499 u8 tc = netdev_get_prio_tc_map(dev, skb->priority); 3500 3501 qoffset = sb_dev->tc_to_txq[tc].offset; 3502 qcount = sb_dev->tc_to_txq[tc].count; 3503 if (unlikely(!qcount)) { 3504 net_warn_ratelimited("%s: invalid qcount, qoffset %u for tc %u\n", 3505 sb_dev->name, qoffset, tc); 3506 qoffset = 0; 3507 qcount = dev->real_num_tx_queues; 3508 } 3509 } 3510 3511 if (skb_rx_queue_recorded(skb)) { 3512 DEBUG_NET_WARN_ON_ONCE(qcount == 0); 3513 hash = skb_get_rx_queue(skb); 3514 if (hash >= qoffset) 3515 hash -= qoffset; 3516 while (unlikely(hash >= qcount)) 3517 hash -= qcount; 3518 return hash + qoffset; 3519 } 3520 3521 return (u16) reciprocal_scale(skb_get_hash(skb), qcount) + qoffset; 3522 } 3523 3524 void skb_warn_bad_offload(const struct sk_buff *skb) 3525 { 3526 static const netdev_features_t null_features; 3527 struct net_device *dev = skb->dev; 3528 const char *name = ""; 3529 3530 if (!net_ratelimit()) 3531 return; 3532 3533 if (dev) { 3534 if (dev->dev.parent) 3535 name = dev_driver_string(dev->dev.parent); 3536 else 3537 name = netdev_name(dev); 3538 } 3539 skb_dump(KERN_WARNING, skb, false); 3540 WARN(1, "%s: caps=(%pNF, %pNF)\n", 3541 name, dev ? &dev->features : &null_features, 3542 skb->sk ? &skb->sk->sk_route_caps : &null_features); 3543 } 3544 3545 /* 3546 * Invalidate hardware checksum when packet is to be mangled, and 3547 * complete checksum manually on outgoing path. 3548 */ 3549 int skb_checksum_help(struct sk_buff *skb) 3550 { 3551 __wsum csum; 3552 int ret = 0, offset; 3553 3554 if (skb->ip_summed == CHECKSUM_COMPLETE) 3555 goto out_set_summed; 3556 3557 if (unlikely(skb_is_gso(skb))) { 3558 skb_warn_bad_offload(skb); 3559 return -EINVAL; 3560 } 3561 3562 if (!skb_frags_readable(skb)) { 3563 return -EFAULT; 3564 } 3565 3566 /* Before computing a checksum, we should make sure no frag could 3567 * be modified by an external entity : checksum could be wrong. 3568 */ 3569 if (skb_has_shared_frag(skb)) { 3570 ret = __skb_linearize(skb); 3571 if (ret) 3572 goto out; 3573 } 3574 3575 offset = skb_checksum_start_offset(skb); 3576 ret = -EINVAL; 3577 if (unlikely(offset >= skb_headlen(skb))) { 3578 DO_ONCE_LITE(skb_dump, KERN_ERR, skb, false); 3579 WARN_ONCE(true, "offset (%d) >= skb_headlen() (%u)\n", 3580 offset, skb_headlen(skb)); 3581 goto out; 3582 } 3583 csum = skb_checksum(skb, offset, skb->len - offset, 0); 3584 3585 offset += skb->csum_offset; 3586 if (unlikely(offset + sizeof(__sum16) > skb_headlen(skb))) { 3587 DO_ONCE_LITE(skb_dump, KERN_ERR, skb, false); 3588 WARN_ONCE(true, "offset+2 (%zu) > skb_headlen() (%u)\n", 3589 offset + sizeof(__sum16), skb_headlen(skb)); 3590 goto out; 3591 } 3592 ret = skb_ensure_writable(skb, offset + sizeof(__sum16)); 3593 if (ret) 3594 goto out; 3595 3596 *(__sum16 *)(skb->data + offset) = csum_fold(csum) ?: CSUM_MANGLED_0; 3597 out_set_summed: 3598 skb->ip_summed = CHECKSUM_NONE; 3599 out: 3600 return ret; 3601 } 3602 EXPORT_SYMBOL(skb_checksum_help); 3603 3604 #ifdef CONFIG_NET_CRC32C 3605 int skb_crc32c_csum_help(struct sk_buff *skb) 3606 { 3607 u32 crc; 3608 int ret = 0, offset, start; 3609 3610 if (skb->ip_summed != CHECKSUM_PARTIAL) 3611 goto out; 3612 3613 if (unlikely(skb_is_gso(skb))) 3614 goto out; 3615 3616 /* Before computing a checksum, we should make sure no frag could 3617 * be modified by an external entity : checksum could be wrong. 3618 */ 3619 if (unlikely(skb_has_shared_frag(skb))) { 3620 ret = __skb_linearize(skb); 3621 if (ret) 3622 goto out; 3623 } 3624 start = skb_checksum_start_offset(skb); 3625 offset = start + offsetof(struct sctphdr, checksum); 3626 if (WARN_ON_ONCE(offset >= skb_headlen(skb))) { 3627 ret = -EINVAL; 3628 goto out; 3629 } 3630 3631 ret = skb_ensure_writable(skb, offset + sizeof(__le32)); 3632 if (ret) 3633 goto out; 3634 3635 crc = ~skb_crc32c(skb, start, skb->len - start, ~0); 3636 *(__le32 *)(skb->data + offset) = cpu_to_le32(crc); 3637 skb_reset_csum_not_inet(skb); 3638 out: 3639 return ret; 3640 } 3641 EXPORT_SYMBOL(skb_crc32c_csum_help); 3642 #endif /* CONFIG_NET_CRC32C */ 3643 3644 __be16 skb_network_protocol(struct sk_buff *skb, int *depth) 3645 { 3646 __be16 type = skb->protocol; 3647 3648 /* Tunnel gso handlers can set protocol to ethernet. */ 3649 if (type == htons(ETH_P_TEB)) { 3650 struct ethhdr *eth; 3651 3652 if (unlikely(!pskb_may_pull(skb, sizeof(struct ethhdr)))) 3653 return 0; 3654 3655 eth = (struct ethhdr *)skb->data; 3656 type = eth->h_proto; 3657 } 3658 3659 return vlan_get_protocol_and_depth(skb, type, depth); 3660 } 3661 3662 3663 /* Take action when hardware reception checksum errors are detected. */ 3664 #ifdef CONFIG_BUG 3665 static void do_netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb) 3666 { 3667 netdev_err(dev, "hw csum failure\n"); 3668 skb_dump(KERN_ERR, skb, true); 3669 dump_stack(); 3670 } 3671 3672 void netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb) 3673 { 3674 DO_ONCE_LITE(do_netdev_rx_csum_fault, dev, skb); 3675 } 3676 EXPORT_SYMBOL(netdev_rx_csum_fault); 3677 #endif 3678 3679 /* XXX: check that highmem exists at all on the given machine. */ 3680 static int illegal_highdma(struct net_device *dev, struct sk_buff *skb) 3681 { 3682 #ifdef CONFIG_HIGHMEM 3683 int i; 3684 3685 if (!(dev->features & NETIF_F_HIGHDMA)) { 3686 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { 3687 skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; 3688 struct page *page = skb_frag_page(frag); 3689 3690 if (page && PageHighMem(page)) 3691 return 1; 3692 } 3693 } 3694 #endif 3695 return 0; 3696 } 3697 3698 /* If MPLS offload request, verify we are testing hardware MPLS features 3699 * instead of standard features for the netdev. 3700 */ 3701 #if IS_ENABLED(CONFIG_NET_MPLS_GSO) 3702 static netdev_features_t net_mpls_features(struct sk_buff *skb, 3703 netdev_features_t features, 3704 __be16 type) 3705 { 3706 if (eth_p_mpls(type)) 3707 features &= skb->dev->mpls_features; 3708 3709 return features; 3710 } 3711 #else 3712 static netdev_features_t net_mpls_features(struct sk_buff *skb, 3713 netdev_features_t features, 3714 __be16 type) 3715 { 3716 return features; 3717 } 3718 #endif 3719 3720 static netdev_features_t harmonize_features(struct sk_buff *skb, 3721 netdev_features_t features) 3722 { 3723 __be16 type; 3724 3725 type = skb_network_protocol(skb, NULL); 3726 features = net_mpls_features(skb, features, type); 3727 3728 if (skb->ip_summed != CHECKSUM_NONE && 3729 !can_checksum_protocol(features, type)) { 3730 features &= ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK); 3731 } 3732 if (illegal_highdma(skb->dev, skb)) 3733 features &= ~NETIF_F_SG; 3734 3735 return features; 3736 } 3737 3738 netdev_features_t passthru_features_check(struct sk_buff *skb, 3739 struct net_device *dev, 3740 netdev_features_t features) 3741 { 3742 return features; 3743 } 3744 EXPORT_SYMBOL(passthru_features_check); 3745 3746 static netdev_features_t dflt_features_check(struct sk_buff *skb, 3747 struct net_device *dev, 3748 netdev_features_t features) 3749 { 3750 return vlan_features_check(skb, features); 3751 } 3752 3753 static netdev_features_t gso_features_check(const struct sk_buff *skb, 3754 struct net_device *dev, 3755 netdev_features_t features) 3756 { 3757 u16 gso_segs = skb_shinfo(skb)->gso_segs; 3758 3759 if (gso_segs > READ_ONCE(dev->gso_max_segs)) 3760 return features & ~NETIF_F_GSO_MASK; 3761 3762 if (unlikely(skb->len >= netif_get_gso_max_size(dev, skb))) 3763 return features & ~NETIF_F_GSO_MASK; 3764 3765 if (!skb_shinfo(skb)->gso_type) { 3766 skb_warn_bad_offload(skb); 3767 return features & ~NETIF_F_GSO_MASK; 3768 } 3769 3770 /* Support for GSO partial features requires software 3771 * intervention before we can actually process the packets 3772 * so we need to strip support for any partial features now 3773 * and we can pull them back in after we have partially 3774 * segmented the frame. 3775 */ 3776 if (!(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL)) 3777 features &= ~dev->gso_partial_features; 3778 3779 /* Make sure to clear the IPv4 ID mangling feature if the IPv4 header 3780 * has the potential to be fragmented so that TSO does not generate 3781 * segments with the same ID. For encapsulated packets, the ID mangling 3782 * feature is guaranteed not to use the same ID for the outer IPv4 3783 * headers of the generated segments if the headers have the potential 3784 * to be fragmented, so there is no need to clear the IPv4 ID mangling 3785 * feature (see the section about NETIF_F_TSO_MANGLEID in 3786 * segmentation-offloads.rst). 3787 */ 3788 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) { 3789 struct iphdr *iph = skb->encapsulation ? 3790 inner_ip_hdr(skb) : ip_hdr(skb); 3791 3792 if (!(iph->frag_off & htons(IP_DF))) 3793 features &= ~NETIF_F_TSO_MANGLEID; 3794 } 3795 3796 /* NETIF_F_IPV6_CSUM does not support IPv6 extension headers, 3797 * so neither does TSO that depends on it. 3798 */ 3799 if (features & NETIF_F_IPV6_CSUM && 3800 (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV6 || 3801 (skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4 && 3802 vlan_get_protocol(skb) == htons(ETH_P_IPV6))) && 3803 skb_transport_header_was_set(skb) && 3804 skb_network_header_len(skb) != sizeof(struct ipv6hdr) && 3805 !ipv6_has_hopopt_jumbo(skb)) 3806 features &= ~(NETIF_F_IPV6_CSUM | NETIF_F_TSO6 | NETIF_F_GSO_UDP_L4); 3807 3808 return features; 3809 } 3810 3811 netdev_features_t netif_skb_features(struct sk_buff *skb) 3812 { 3813 struct net_device *dev = skb->dev; 3814 netdev_features_t features = dev->features; 3815 3816 if (skb_is_gso(skb)) 3817 features = gso_features_check(skb, dev, features); 3818 3819 /* If encapsulation offload request, verify we are testing 3820 * hardware encapsulation features instead of standard 3821 * features for the netdev 3822 */ 3823 if (skb->encapsulation) 3824 features &= dev->hw_enc_features; 3825 3826 if (skb_vlan_tagged(skb)) 3827 features = netdev_intersect_features(features, 3828 dev->vlan_features | 3829 NETIF_F_HW_VLAN_CTAG_TX | 3830 NETIF_F_HW_VLAN_STAG_TX); 3831 3832 if (dev->netdev_ops->ndo_features_check) 3833 features &= dev->netdev_ops->ndo_features_check(skb, dev, 3834 features); 3835 else 3836 features &= dflt_features_check(skb, dev, features); 3837 3838 return harmonize_features(skb, features); 3839 } 3840 EXPORT_SYMBOL(netif_skb_features); 3841 3842 static int xmit_one(struct sk_buff *skb, struct net_device *dev, 3843 struct netdev_queue *txq, bool more) 3844 { 3845 unsigned int len; 3846 int rc; 3847 3848 if (dev_nit_active_rcu(dev)) 3849 dev_queue_xmit_nit(skb, dev); 3850 3851 len = skb->len; 3852 trace_net_dev_start_xmit(skb, dev); 3853 rc = netdev_start_xmit(skb, dev, txq, more); 3854 trace_net_dev_xmit(skb, rc, dev, len); 3855 3856 return rc; 3857 } 3858 3859 struct sk_buff *dev_hard_start_xmit(struct sk_buff *first, struct net_device *dev, 3860 struct netdev_queue *txq, int *ret) 3861 { 3862 struct sk_buff *skb = first; 3863 int rc = NETDEV_TX_OK; 3864 3865 while (skb) { 3866 struct sk_buff *next = skb->next; 3867 3868 skb_mark_not_on_list(skb); 3869 rc = xmit_one(skb, dev, txq, next != NULL); 3870 if (unlikely(!dev_xmit_complete(rc))) { 3871 skb->next = next; 3872 goto out; 3873 } 3874 3875 skb = next; 3876 if (netif_tx_queue_stopped(txq) && skb) { 3877 rc = NETDEV_TX_BUSY; 3878 break; 3879 } 3880 } 3881 3882 out: 3883 *ret = rc; 3884 return skb; 3885 } 3886 3887 static struct sk_buff *validate_xmit_vlan(struct sk_buff *skb, 3888 netdev_features_t features) 3889 { 3890 if (skb_vlan_tag_present(skb) && 3891 !vlan_hw_offload_capable(features, skb->vlan_proto)) 3892 skb = __vlan_hwaccel_push_inside(skb); 3893 return skb; 3894 } 3895 3896 int skb_csum_hwoffload_help(struct sk_buff *skb, 3897 const netdev_features_t features) 3898 { 3899 if (unlikely(skb_csum_is_sctp(skb))) 3900 return !!(features & NETIF_F_SCTP_CRC) ? 0 : 3901 skb_crc32c_csum_help(skb); 3902 3903 if (features & NETIF_F_HW_CSUM) 3904 return 0; 3905 3906 if (features & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM)) { 3907 if (vlan_get_protocol(skb) == htons(ETH_P_IPV6) && 3908 skb_network_header_len(skb) != sizeof(struct ipv6hdr) && 3909 !ipv6_has_hopopt_jumbo(skb)) 3910 goto sw_checksum; 3911 3912 switch (skb->csum_offset) { 3913 case offsetof(struct tcphdr, check): 3914 case offsetof(struct udphdr, check): 3915 return 0; 3916 } 3917 } 3918 3919 sw_checksum: 3920 return skb_checksum_help(skb); 3921 } 3922 EXPORT_SYMBOL(skb_csum_hwoffload_help); 3923 3924 /* Checks if this SKB belongs to an HW offloaded socket 3925 * and whether any SW fallbacks are required based on dev. 3926 * Check decrypted mark in case skb_orphan() cleared socket. 3927 */ 3928 static struct sk_buff *sk_validate_xmit_skb(struct sk_buff *skb, 3929 struct net_device *dev) 3930 { 3931 #ifdef CONFIG_SOCK_VALIDATE_XMIT 3932 struct sk_buff *(*sk_validate)(struct sock *sk, struct net_device *dev, 3933 struct sk_buff *skb); 3934 struct sock *sk = skb->sk; 3935 3936 sk_validate = NULL; 3937 if (sk) { 3938 if (sk_fullsock(sk)) 3939 sk_validate = sk->sk_validate_xmit_skb; 3940 else if (sk_is_inet(sk) && sk->sk_state == TCP_TIME_WAIT) 3941 sk_validate = inet_twsk(sk)->tw_validate_xmit_skb; 3942 } 3943 3944 if (sk_validate) { 3945 skb = sk_validate(sk, dev, skb); 3946 } else if (unlikely(skb_is_decrypted(skb))) { 3947 pr_warn_ratelimited("unencrypted skb with no associated socket - dropping\n"); 3948 kfree_skb(skb); 3949 skb = NULL; 3950 } 3951 #endif 3952 3953 return skb; 3954 } 3955 3956 static struct sk_buff *validate_xmit_unreadable_skb(struct sk_buff *skb, 3957 struct net_device *dev) 3958 { 3959 struct skb_shared_info *shinfo; 3960 struct net_iov *niov; 3961 3962 if (likely(skb_frags_readable(skb))) 3963 goto out; 3964 3965 if (!dev->netmem_tx) 3966 goto out_free; 3967 3968 shinfo = skb_shinfo(skb); 3969 3970 if (shinfo->nr_frags > 0) { 3971 niov = netmem_to_net_iov(skb_frag_netmem(&shinfo->frags[0])); 3972 if (net_is_devmem_iov(niov) && 3973 net_devmem_iov_binding(niov)->dev != dev) 3974 goto out_free; 3975 } 3976 3977 out: 3978 return skb; 3979 3980 out_free: 3981 kfree_skb(skb); 3982 return NULL; 3983 } 3984 3985 static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device *dev, bool *again) 3986 { 3987 netdev_features_t features; 3988 3989 skb = validate_xmit_unreadable_skb(skb, dev); 3990 if (unlikely(!skb)) 3991 goto out_null; 3992 3993 features = netif_skb_features(skb); 3994 skb = validate_xmit_vlan(skb, features); 3995 if (unlikely(!skb)) 3996 goto out_null; 3997 3998 skb = sk_validate_xmit_skb(skb, dev); 3999 if (unlikely(!skb)) 4000 goto out_null; 4001 4002 if (netif_needs_gso(skb, features)) { 4003 struct sk_buff *segs; 4004 4005 segs = skb_gso_segment(skb, features); 4006 if (IS_ERR(segs)) { 4007 goto out_kfree_skb; 4008 } else if (segs) { 4009 consume_skb(skb); 4010 skb = segs; 4011 } 4012 } else { 4013 if (skb_needs_linearize(skb, features) && 4014 __skb_linearize(skb)) 4015 goto out_kfree_skb; 4016 4017 /* If packet is not checksummed and device does not 4018 * support checksumming for this protocol, complete 4019 * checksumming here. 4020 */ 4021 if (skb->ip_summed == CHECKSUM_PARTIAL) { 4022 if (skb->encapsulation) 4023 skb_set_inner_transport_header(skb, 4024 skb_checksum_start_offset(skb)); 4025 else 4026 skb_set_transport_header(skb, 4027 skb_checksum_start_offset(skb)); 4028 if (skb_csum_hwoffload_help(skb, features)) 4029 goto out_kfree_skb; 4030 } 4031 } 4032 4033 skb = validate_xmit_xfrm(skb, features, again); 4034 4035 return skb; 4036 4037 out_kfree_skb: 4038 kfree_skb(skb); 4039 out_null: 4040 dev_core_stats_tx_dropped_inc(dev); 4041 return NULL; 4042 } 4043 4044 struct sk_buff *validate_xmit_skb_list(struct sk_buff *skb, struct net_device *dev, bool *again) 4045 { 4046 struct sk_buff *next, *head = NULL, *tail; 4047 4048 for (; skb != NULL; skb = next) { 4049 next = skb->next; 4050 skb_mark_not_on_list(skb); 4051 4052 /* in case skb won't be segmented, point to itself */ 4053 skb->prev = skb; 4054 4055 skb = validate_xmit_skb(skb, dev, again); 4056 if (!skb) 4057 continue; 4058 4059 if (!head) 4060 head = skb; 4061 else 4062 tail->next = skb; 4063 /* If skb was segmented, skb->prev points to 4064 * the last segment. If not, it still contains skb. 4065 */ 4066 tail = skb->prev; 4067 } 4068 return head; 4069 } 4070 EXPORT_SYMBOL_GPL(validate_xmit_skb_list); 4071 4072 static void qdisc_pkt_len_init(struct sk_buff *skb) 4073 { 4074 const struct skb_shared_info *shinfo = skb_shinfo(skb); 4075 4076 qdisc_skb_cb(skb)->pkt_len = skb->len; 4077 4078 /* To get more precise estimation of bytes sent on wire, 4079 * we add to pkt_len the headers size of all segments 4080 */ 4081 if (shinfo->gso_size && skb_transport_header_was_set(skb)) { 4082 u16 gso_segs = shinfo->gso_segs; 4083 unsigned int hdr_len; 4084 4085 /* mac layer + network layer */ 4086 if (!skb->encapsulation) 4087 hdr_len = skb_transport_offset(skb); 4088 else 4089 hdr_len = skb_inner_transport_offset(skb); 4090 4091 /* + transport layer */ 4092 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) { 4093 const struct tcphdr *th; 4094 struct tcphdr _tcphdr; 4095 4096 th = skb_header_pointer(skb, hdr_len, 4097 sizeof(_tcphdr), &_tcphdr); 4098 if (likely(th)) 4099 hdr_len += __tcp_hdrlen(th); 4100 } else if (shinfo->gso_type & SKB_GSO_UDP_L4) { 4101 struct udphdr _udphdr; 4102 4103 if (skb_header_pointer(skb, hdr_len, 4104 sizeof(_udphdr), &_udphdr)) 4105 hdr_len += sizeof(struct udphdr); 4106 } 4107 4108 if (unlikely(shinfo->gso_type & SKB_GSO_DODGY)) { 4109 int payload = skb->len - hdr_len; 4110 4111 /* Malicious packet. */ 4112 if (payload <= 0) 4113 return; 4114 gso_segs = DIV_ROUND_UP(payload, shinfo->gso_size); 4115 } 4116 qdisc_skb_cb(skb)->pkt_len += (gso_segs - 1) * hdr_len; 4117 } 4118 } 4119 4120 static int dev_qdisc_enqueue(struct sk_buff *skb, struct Qdisc *q, 4121 struct sk_buff **to_free, 4122 struct netdev_queue *txq) 4123 { 4124 int rc; 4125 4126 rc = q->enqueue(skb, q, to_free) & NET_XMIT_MASK; 4127 if (rc == NET_XMIT_SUCCESS) 4128 trace_qdisc_enqueue(q, txq, skb); 4129 return rc; 4130 } 4131 4132 static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q, 4133 struct net_device *dev, 4134 struct netdev_queue *txq) 4135 { 4136 struct sk_buff *next, *to_free = NULL; 4137 spinlock_t *root_lock = qdisc_lock(q); 4138 struct llist_node *ll_list, *first_n; 4139 unsigned long defer_count = 0; 4140 int rc; 4141 4142 qdisc_calculate_pkt_len(skb, q); 4143 4144 tcf_set_drop_reason(skb, SKB_DROP_REASON_QDISC_DROP); 4145 4146 if (q->flags & TCQ_F_NOLOCK) { 4147 if (q->flags & TCQ_F_CAN_BYPASS && nolock_qdisc_is_empty(q) && 4148 qdisc_run_begin(q)) { 4149 /* Retest nolock_qdisc_is_empty() within the protection 4150 * of q->seqlock to protect from racing with requeuing. 4151 */ 4152 if (unlikely(!nolock_qdisc_is_empty(q))) { 4153 rc = dev_qdisc_enqueue(skb, q, &to_free, txq); 4154 __qdisc_run(q); 4155 qdisc_run_end(q); 4156 4157 goto no_lock_out; 4158 } 4159 4160 qdisc_bstats_cpu_update(q, skb); 4161 if (sch_direct_xmit(skb, q, dev, txq, NULL, true) && 4162 !nolock_qdisc_is_empty(q)) 4163 __qdisc_run(q); 4164 4165 qdisc_run_end(q); 4166 return NET_XMIT_SUCCESS; 4167 } 4168 4169 rc = dev_qdisc_enqueue(skb, q, &to_free, txq); 4170 qdisc_run(q); 4171 4172 no_lock_out: 4173 if (unlikely(to_free)) 4174 kfree_skb_list_reason(to_free, 4175 tcf_get_drop_reason(to_free)); 4176 return rc; 4177 } 4178 4179 /* Open code llist_add(&skb->ll_node, &q->defer_list) + queue limit. 4180 * In the try_cmpxchg() loop, we want to increment q->defer_count 4181 * at most once to limit the number of skbs in defer_list. 4182 * We perform the defer_count increment only if the list is not empty, 4183 * because some arches have slow atomic_long_inc_return(). 4184 */ 4185 first_n = READ_ONCE(q->defer_list.first); 4186 do { 4187 if (first_n && !defer_count) { 4188 defer_count = atomic_long_inc_return(&q->defer_count); 4189 if (unlikely(defer_count > q->limit)) { 4190 kfree_skb_reason(skb, SKB_DROP_REASON_QDISC_DROP); 4191 return NET_XMIT_DROP; 4192 } 4193 } 4194 skb->ll_node.next = first_n; 4195 } while (!try_cmpxchg(&q->defer_list.first, &first_n, &skb->ll_node)); 4196 4197 /* If defer_list was not empty, we know the cpu which queued 4198 * the first skb will process the whole list for us. 4199 */ 4200 if (first_n) 4201 return NET_XMIT_SUCCESS; 4202 4203 spin_lock(root_lock); 4204 4205 ll_list = llist_del_all(&q->defer_list); 4206 /* There is a small race because we clear defer_count not atomically 4207 * with the prior llist_del_all(). This means defer_list could grow 4208 * over q->limit. 4209 */ 4210 atomic_long_set(&q->defer_count, 0); 4211 4212 ll_list = llist_reverse_order(ll_list); 4213 4214 if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) { 4215 llist_for_each_entry_safe(skb, next, ll_list, ll_node) 4216 __qdisc_drop(skb, &to_free); 4217 rc = NET_XMIT_DROP; 4218 goto unlock; 4219 } 4220 if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) && 4221 !llist_next(ll_list) && qdisc_run_begin(q)) { 4222 /* 4223 * This is a work-conserving queue; there are no old skbs 4224 * waiting to be sent out; and the qdisc is not running - 4225 * xmit the skb directly. 4226 */ 4227 4228 DEBUG_NET_WARN_ON_ONCE(skb != llist_entry(ll_list, 4229 struct sk_buff, 4230 ll_node)); 4231 qdisc_bstats_update(q, skb); 4232 if (sch_direct_xmit(skb, q, dev, txq, root_lock, true)) 4233 __qdisc_run(q); 4234 qdisc_run_end(q); 4235 rc = NET_XMIT_SUCCESS; 4236 } else { 4237 int count = 0; 4238 4239 llist_for_each_entry_safe(skb, next, ll_list, ll_node) { 4240 prefetch(next); 4241 skb_mark_not_on_list(skb); 4242 rc = dev_qdisc_enqueue(skb, q, &to_free, txq); 4243 count++; 4244 } 4245 qdisc_run(q); 4246 if (count != 1) 4247 rc = NET_XMIT_SUCCESS; 4248 } 4249 unlock: 4250 spin_unlock(root_lock); 4251 if (unlikely(to_free)) 4252 kfree_skb_list_reason(to_free, 4253 tcf_get_drop_reason(to_free)); 4254 return rc; 4255 } 4256 4257 #if IS_ENABLED(CONFIG_CGROUP_NET_PRIO) 4258 static void skb_update_prio(struct sk_buff *skb) 4259 { 4260 const struct netprio_map *map; 4261 const struct sock *sk; 4262 unsigned int prioidx; 4263 4264 if (skb->priority) 4265 return; 4266 map = rcu_dereference_bh(skb->dev->priomap); 4267 if (!map) 4268 return; 4269 sk = skb_to_full_sk(skb); 4270 if (!sk) 4271 return; 4272 4273 prioidx = sock_cgroup_prioidx(&sk->sk_cgrp_data); 4274 4275 if (prioidx < map->priomap_len) 4276 skb->priority = map->priomap[prioidx]; 4277 } 4278 #else 4279 #define skb_update_prio(skb) 4280 #endif 4281 4282 /** 4283 * dev_loopback_xmit - loop back @skb 4284 * @net: network namespace this loopback is happening in 4285 * @sk: sk needed to be a netfilter okfn 4286 * @skb: buffer to transmit 4287 */ 4288 int dev_loopback_xmit(struct net *net, struct sock *sk, struct sk_buff *skb) 4289 { 4290 skb_reset_mac_header(skb); 4291 __skb_pull(skb, skb_network_offset(skb)); 4292 skb->pkt_type = PACKET_LOOPBACK; 4293 if (skb->ip_summed == CHECKSUM_NONE) 4294 skb->ip_summed = CHECKSUM_UNNECESSARY; 4295 DEBUG_NET_WARN_ON_ONCE(!skb_dst(skb)); 4296 skb_dst_force(skb); 4297 netif_rx(skb); 4298 return 0; 4299 } 4300 EXPORT_SYMBOL(dev_loopback_xmit); 4301 4302 #ifdef CONFIG_NET_EGRESS 4303 static struct netdev_queue * 4304 netdev_tx_queue_mapping(struct net_device *dev, struct sk_buff *skb) 4305 { 4306 int qm = skb_get_queue_mapping(skb); 4307 4308 return netdev_get_tx_queue(dev, netdev_cap_txqueue(dev, qm)); 4309 } 4310 4311 #ifndef CONFIG_PREEMPT_RT 4312 static bool netdev_xmit_txqueue_skipped(void) 4313 { 4314 return __this_cpu_read(softnet_data.xmit.skip_txqueue); 4315 } 4316 4317 void netdev_xmit_skip_txqueue(bool skip) 4318 { 4319 __this_cpu_write(softnet_data.xmit.skip_txqueue, skip); 4320 } 4321 EXPORT_SYMBOL_GPL(netdev_xmit_skip_txqueue); 4322 4323 #else 4324 static bool netdev_xmit_txqueue_skipped(void) 4325 { 4326 return current->net_xmit.skip_txqueue; 4327 } 4328 4329 void netdev_xmit_skip_txqueue(bool skip) 4330 { 4331 current->net_xmit.skip_txqueue = skip; 4332 } 4333 EXPORT_SYMBOL_GPL(netdev_xmit_skip_txqueue); 4334 #endif 4335 #endif /* CONFIG_NET_EGRESS */ 4336 4337 #ifdef CONFIG_NET_XGRESS 4338 static int tc_run(struct tcx_entry *entry, struct sk_buff *skb, 4339 enum skb_drop_reason *drop_reason) 4340 { 4341 int ret = TC_ACT_UNSPEC; 4342 #ifdef CONFIG_NET_CLS_ACT 4343 struct mini_Qdisc *miniq = rcu_dereference_bh(entry->miniq); 4344 struct tcf_result res; 4345 4346 if (!miniq) 4347 return ret; 4348 4349 /* Global bypass */ 4350 if (!static_branch_likely(&tcf_sw_enabled_key)) 4351 return ret; 4352 4353 /* Block-wise bypass */ 4354 if (tcf_block_bypass_sw(miniq->block)) 4355 return ret; 4356 4357 tc_skb_cb(skb)->mru = 0; 4358 tc_skb_cb(skb)->post_ct = false; 4359 tcf_set_drop_reason(skb, *drop_reason); 4360 4361 mini_qdisc_bstats_cpu_update(miniq, skb); 4362 ret = tcf_classify(skb, miniq->block, miniq->filter_list, &res, false); 4363 /* Only tcf related quirks below. */ 4364 switch (ret) { 4365 case TC_ACT_SHOT: 4366 *drop_reason = tcf_get_drop_reason(skb); 4367 mini_qdisc_qstats_cpu_drop(miniq); 4368 break; 4369 case TC_ACT_OK: 4370 case TC_ACT_RECLASSIFY: 4371 skb->tc_index = TC_H_MIN(res.classid); 4372 break; 4373 } 4374 #endif /* CONFIG_NET_CLS_ACT */ 4375 return ret; 4376 } 4377 4378 static DEFINE_STATIC_KEY_FALSE(tcx_needed_key); 4379 4380 void tcx_inc(void) 4381 { 4382 static_branch_inc(&tcx_needed_key); 4383 } 4384 4385 void tcx_dec(void) 4386 { 4387 static_branch_dec(&tcx_needed_key); 4388 } 4389 4390 static __always_inline enum tcx_action_base 4391 tcx_run(const struct bpf_mprog_entry *entry, struct sk_buff *skb, 4392 const bool needs_mac) 4393 { 4394 const struct bpf_mprog_fp *fp; 4395 const struct bpf_prog *prog; 4396 int ret = TCX_NEXT; 4397 4398 if (needs_mac) 4399 __skb_push(skb, skb->mac_len); 4400 bpf_mprog_foreach_prog(entry, fp, prog) { 4401 bpf_compute_data_pointers(skb); 4402 ret = bpf_prog_run(prog, skb); 4403 if (ret != TCX_NEXT) 4404 break; 4405 } 4406 if (needs_mac) 4407 __skb_pull(skb, skb->mac_len); 4408 return tcx_action_code(skb, ret); 4409 } 4410 4411 static __always_inline struct sk_buff * 4412 sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret, 4413 struct net_device *orig_dev, bool *another) 4414 { 4415 struct bpf_mprog_entry *entry = rcu_dereference_bh(skb->dev->tcx_ingress); 4416 enum skb_drop_reason drop_reason = SKB_DROP_REASON_TC_INGRESS; 4417 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx; 4418 int sch_ret; 4419 4420 if (!entry) 4421 return skb; 4422 4423 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx); 4424 if (unlikely(*pt_prev)) { 4425 *ret = deliver_skb(skb, *pt_prev, orig_dev); 4426 *pt_prev = NULL; 4427 } 4428 4429 qdisc_skb_cb(skb)->pkt_len = skb->len; 4430 tcx_set_ingress(skb, true); 4431 4432 if (static_branch_unlikely(&tcx_needed_key)) { 4433 sch_ret = tcx_run(entry, skb, true); 4434 if (sch_ret != TC_ACT_UNSPEC) 4435 goto ingress_verdict; 4436 } 4437 sch_ret = tc_run(tcx_entry(entry), skb, &drop_reason); 4438 ingress_verdict: 4439 switch (sch_ret) { 4440 case TC_ACT_REDIRECT: 4441 /* skb_mac_header check was done by BPF, so we can safely 4442 * push the L2 header back before redirecting to another 4443 * netdev. 4444 */ 4445 __skb_push(skb, skb->mac_len); 4446 if (skb_do_redirect(skb) == -EAGAIN) { 4447 __skb_pull(skb, skb->mac_len); 4448 *another = true; 4449 break; 4450 } 4451 *ret = NET_RX_SUCCESS; 4452 bpf_net_ctx_clear(bpf_net_ctx); 4453 return NULL; 4454 case TC_ACT_SHOT: 4455 kfree_skb_reason(skb, drop_reason); 4456 *ret = NET_RX_DROP; 4457 bpf_net_ctx_clear(bpf_net_ctx); 4458 return NULL; 4459 /* used by tc_run */ 4460 case TC_ACT_STOLEN: 4461 case TC_ACT_QUEUED: 4462 case TC_ACT_TRAP: 4463 consume_skb(skb); 4464 fallthrough; 4465 case TC_ACT_CONSUMED: 4466 *ret = NET_RX_SUCCESS; 4467 bpf_net_ctx_clear(bpf_net_ctx); 4468 return NULL; 4469 } 4470 bpf_net_ctx_clear(bpf_net_ctx); 4471 4472 return skb; 4473 } 4474 4475 static __always_inline struct sk_buff * 4476 sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev) 4477 { 4478 struct bpf_mprog_entry *entry = rcu_dereference_bh(dev->tcx_egress); 4479 enum skb_drop_reason drop_reason = SKB_DROP_REASON_TC_EGRESS; 4480 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx; 4481 int sch_ret; 4482 4483 if (!entry) 4484 return skb; 4485 4486 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx); 4487 4488 /* qdisc_skb_cb(skb)->pkt_len & tcx_set_ingress() was 4489 * already set by the caller. 4490 */ 4491 if (static_branch_unlikely(&tcx_needed_key)) { 4492 sch_ret = tcx_run(entry, skb, false); 4493 if (sch_ret != TC_ACT_UNSPEC) 4494 goto egress_verdict; 4495 } 4496 sch_ret = tc_run(tcx_entry(entry), skb, &drop_reason); 4497 egress_verdict: 4498 switch (sch_ret) { 4499 case TC_ACT_REDIRECT: 4500 /* No need to push/pop skb's mac_header here on egress! */ 4501 skb_do_redirect(skb); 4502 *ret = NET_XMIT_SUCCESS; 4503 bpf_net_ctx_clear(bpf_net_ctx); 4504 return NULL; 4505 case TC_ACT_SHOT: 4506 kfree_skb_reason(skb, drop_reason); 4507 *ret = NET_XMIT_DROP; 4508 bpf_net_ctx_clear(bpf_net_ctx); 4509 return NULL; 4510 /* used by tc_run */ 4511 case TC_ACT_STOLEN: 4512 case TC_ACT_QUEUED: 4513 case TC_ACT_TRAP: 4514 consume_skb(skb); 4515 fallthrough; 4516 case TC_ACT_CONSUMED: 4517 *ret = NET_XMIT_SUCCESS; 4518 bpf_net_ctx_clear(bpf_net_ctx); 4519 return NULL; 4520 } 4521 bpf_net_ctx_clear(bpf_net_ctx); 4522 4523 return skb; 4524 } 4525 #else 4526 static __always_inline struct sk_buff * 4527 sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret, 4528 struct net_device *orig_dev, bool *another) 4529 { 4530 return skb; 4531 } 4532 4533 static __always_inline struct sk_buff * 4534 sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev) 4535 { 4536 return skb; 4537 } 4538 #endif /* CONFIG_NET_XGRESS */ 4539 4540 #ifdef CONFIG_XPS 4541 static int __get_xps_queue_idx(struct net_device *dev, struct sk_buff *skb, 4542 struct xps_dev_maps *dev_maps, unsigned int tci) 4543 { 4544 int tc = netdev_get_prio_tc_map(dev, skb->priority); 4545 struct xps_map *map; 4546 int queue_index = -1; 4547 4548 if (tc >= dev_maps->num_tc || tci >= dev_maps->nr_ids) 4549 return queue_index; 4550 4551 tci *= dev_maps->num_tc; 4552 tci += tc; 4553 4554 map = rcu_dereference(dev_maps->attr_map[tci]); 4555 if (map) { 4556 if (map->len == 1) 4557 queue_index = map->queues[0]; 4558 else 4559 queue_index = map->queues[reciprocal_scale( 4560 skb_get_hash(skb), map->len)]; 4561 if (unlikely(queue_index >= dev->real_num_tx_queues)) 4562 queue_index = -1; 4563 } 4564 return queue_index; 4565 } 4566 #endif 4567 4568 static int get_xps_queue(struct net_device *dev, struct net_device *sb_dev, 4569 struct sk_buff *skb) 4570 { 4571 #ifdef CONFIG_XPS 4572 struct xps_dev_maps *dev_maps; 4573 struct sock *sk = skb->sk; 4574 int queue_index = -1; 4575 4576 if (!static_key_false(&xps_needed)) 4577 return -1; 4578 4579 rcu_read_lock(); 4580 if (!static_key_false(&xps_rxqs_needed)) 4581 goto get_cpus_map; 4582 4583 dev_maps = rcu_dereference(sb_dev->xps_maps[XPS_RXQS]); 4584 if (dev_maps) { 4585 int tci = sk_rx_queue_get(sk); 4586 4587 if (tci >= 0) 4588 queue_index = __get_xps_queue_idx(dev, skb, dev_maps, 4589 tci); 4590 } 4591 4592 get_cpus_map: 4593 if (queue_index < 0) { 4594 dev_maps = rcu_dereference(sb_dev->xps_maps[XPS_CPUS]); 4595 if (dev_maps) { 4596 unsigned int tci = skb->sender_cpu - 1; 4597 4598 queue_index = __get_xps_queue_idx(dev, skb, dev_maps, 4599 tci); 4600 } 4601 } 4602 rcu_read_unlock(); 4603 4604 return queue_index; 4605 #else 4606 return -1; 4607 #endif 4608 } 4609 4610 u16 dev_pick_tx_zero(struct net_device *dev, struct sk_buff *skb, 4611 struct net_device *sb_dev) 4612 { 4613 return 0; 4614 } 4615 EXPORT_SYMBOL(dev_pick_tx_zero); 4616 4617 int sk_tx_queue_get(const struct sock *sk) 4618 { 4619 int resel, val; 4620 4621 if (!sk) 4622 return -1; 4623 /* Paired with WRITE_ONCE() in sk_tx_queue_clear() 4624 * and sk_tx_queue_set(). 4625 */ 4626 val = READ_ONCE(sk->sk_tx_queue_mapping); 4627 4628 if (val == NO_QUEUE_MAPPING) 4629 return -1; 4630 4631 if (!sk_fullsock(sk)) 4632 return val; 4633 4634 resel = READ_ONCE(sock_net(sk)->core.sysctl_txq_reselection); 4635 if (resel && time_is_before_jiffies( 4636 READ_ONCE(sk->sk_tx_queue_mapping_jiffies) + resel)) 4637 return -1; 4638 4639 return val; 4640 } 4641 EXPORT_SYMBOL(sk_tx_queue_get); 4642 4643 u16 netdev_pick_tx(struct net_device *dev, struct sk_buff *skb, 4644 struct net_device *sb_dev) 4645 { 4646 struct sock *sk = skb->sk; 4647 int queue_index = sk_tx_queue_get(sk); 4648 4649 sb_dev = sb_dev ? : dev; 4650 4651 if (queue_index < 0 || skb->ooo_okay || 4652 queue_index >= dev->real_num_tx_queues) { 4653 int new_index = get_xps_queue(dev, sb_dev, skb); 4654 4655 if (new_index < 0) 4656 new_index = skb_tx_hash(dev, sb_dev, skb); 4657 4658 if (sk && sk_fullsock(sk) && 4659 rcu_access_pointer(sk->sk_dst_cache)) 4660 sk_tx_queue_set(sk, new_index); 4661 4662 queue_index = new_index; 4663 } 4664 4665 return queue_index; 4666 } 4667 EXPORT_SYMBOL(netdev_pick_tx); 4668 4669 struct netdev_queue *netdev_core_pick_tx(struct net_device *dev, 4670 struct sk_buff *skb, 4671 struct net_device *sb_dev) 4672 { 4673 int queue_index = 0; 4674 4675 #ifdef CONFIG_XPS 4676 u32 sender_cpu = skb->sender_cpu - 1; 4677 4678 if (sender_cpu >= (u32)NR_CPUS) 4679 skb->sender_cpu = raw_smp_processor_id() + 1; 4680 #endif 4681 4682 if (dev->real_num_tx_queues != 1) { 4683 const struct net_device_ops *ops = dev->netdev_ops; 4684 4685 if (ops->ndo_select_queue) 4686 queue_index = ops->ndo_select_queue(dev, skb, sb_dev); 4687 else 4688 queue_index = netdev_pick_tx(dev, skb, sb_dev); 4689 4690 queue_index = netdev_cap_txqueue(dev, queue_index); 4691 } 4692 4693 skb_set_queue_mapping(skb, queue_index); 4694 return netdev_get_tx_queue(dev, queue_index); 4695 } 4696 4697 /** 4698 * __dev_queue_xmit() - transmit a buffer 4699 * @skb: buffer to transmit 4700 * @sb_dev: suboordinate device used for L2 forwarding offload 4701 * 4702 * Queue a buffer for transmission to a network device. The caller must 4703 * have set the device and priority and built the buffer before calling 4704 * this function. The function can be called from an interrupt. 4705 * 4706 * When calling this method, interrupts MUST be enabled. This is because 4707 * the BH enable code must have IRQs enabled so that it will not deadlock. 4708 * 4709 * Regardless of the return value, the skb is consumed, so it is currently 4710 * difficult to retry a send to this method. (You can bump the ref count 4711 * before sending to hold a reference for retry if you are careful.) 4712 * 4713 * Return: 4714 * * 0 - buffer successfully transmitted 4715 * * positive qdisc return code - NET_XMIT_DROP etc. 4716 * * negative errno - other errors 4717 */ 4718 int __dev_queue_xmit(struct sk_buff *skb, struct net_device *sb_dev) 4719 { 4720 struct net_device *dev = skb->dev; 4721 struct netdev_queue *txq = NULL; 4722 struct Qdisc *q; 4723 int rc = -ENOMEM; 4724 bool again = false; 4725 4726 skb_reset_mac_header(skb); 4727 skb_assert_len(skb); 4728 4729 if (unlikely(skb_shinfo(skb)->tx_flags & 4730 (SKBTX_SCHED_TSTAMP | SKBTX_BPF))) 4731 __skb_tstamp_tx(skb, NULL, NULL, skb->sk, SCM_TSTAMP_SCHED); 4732 4733 /* Disable soft irqs for various locks below. Also 4734 * stops preemption for RCU. 4735 */ 4736 rcu_read_lock_bh(); 4737 4738 skb_update_prio(skb); 4739 4740 qdisc_pkt_len_init(skb); 4741 tcx_set_ingress(skb, false); 4742 #ifdef CONFIG_NET_EGRESS 4743 if (static_branch_unlikely(&egress_needed_key)) { 4744 if (nf_hook_egress_active()) { 4745 skb = nf_hook_egress(skb, &rc, dev); 4746 if (!skb) 4747 goto out; 4748 } 4749 4750 netdev_xmit_skip_txqueue(false); 4751 4752 nf_skip_egress(skb, true); 4753 skb = sch_handle_egress(skb, &rc, dev); 4754 if (!skb) 4755 goto out; 4756 nf_skip_egress(skb, false); 4757 4758 if (netdev_xmit_txqueue_skipped()) 4759 txq = netdev_tx_queue_mapping(dev, skb); 4760 } 4761 #endif 4762 /* If device/qdisc don't need skb->dst, release it right now while 4763 * its hot in this cpu cache. 4764 */ 4765 if (dev->priv_flags & IFF_XMIT_DST_RELEASE) 4766 skb_dst_drop(skb); 4767 else 4768 skb_dst_force(skb); 4769 4770 if (!txq) 4771 txq = netdev_core_pick_tx(dev, skb, sb_dev); 4772 4773 q = rcu_dereference_bh(txq->qdisc); 4774 4775 trace_net_dev_queue(skb); 4776 if (q->enqueue) { 4777 rc = __dev_xmit_skb(skb, q, dev, txq); 4778 goto out; 4779 } 4780 4781 /* The device has no queue. Common case for software devices: 4782 * loopback, all the sorts of tunnels... 4783 4784 * Really, it is unlikely that netif_tx_lock protection is necessary 4785 * here. (f.e. loopback and IP tunnels are clean ignoring statistics 4786 * counters.) 4787 * However, it is possible, that they rely on protection 4788 * made by us here. 4789 4790 * Check this and shot the lock. It is not prone from deadlocks. 4791 *Either shot noqueue qdisc, it is even simpler 8) 4792 */ 4793 if (dev->flags & IFF_UP) { 4794 int cpu = smp_processor_id(); /* ok because BHs are off */ 4795 4796 /* Other cpus might concurrently change txq->xmit_lock_owner 4797 * to -1 or to their cpu id, but not to our id. 4798 */ 4799 if (READ_ONCE(txq->xmit_lock_owner) != cpu) { 4800 if (dev_xmit_recursion()) 4801 goto recursion_alert; 4802 4803 skb = validate_xmit_skb(skb, dev, &again); 4804 if (!skb) 4805 goto out; 4806 4807 HARD_TX_LOCK(dev, txq, cpu); 4808 4809 if (!netif_xmit_stopped(txq)) { 4810 dev_xmit_recursion_inc(); 4811 skb = dev_hard_start_xmit(skb, dev, txq, &rc); 4812 dev_xmit_recursion_dec(); 4813 if (dev_xmit_complete(rc)) { 4814 HARD_TX_UNLOCK(dev, txq); 4815 goto out; 4816 } 4817 } 4818 HARD_TX_UNLOCK(dev, txq); 4819 net_crit_ratelimited("Virtual device %s asks to queue packet!\n", 4820 dev->name); 4821 } else { 4822 /* Recursion is detected! It is possible, 4823 * unfortunately 4824 */ 4825 recursion_alert: 4826 net_crit_ratelimited("Dead loop on virtual device %s, fix it urgently!\n", 4827 dev->name); 4828 } 4829 } 4830 4831 rc = -ENETDOWN; 4832 rcu_read_unlock_bh(); 4833 4834 dev_core_stats_tx_dropped_inc(dev); 4835 kfree_skb_list(skb); 4836 return rc; 4837 out: 4838 rcu_read_unlock_bh(); 4839 return rc; 4840 } 4841 EXPORT_SYMBOL(__dev_queue_xmit); 4842 4843 int __dev_direct_xmit(struct sk_buff *skb, u16 queue_id) 4844 { 4845 struct net_device *dev = skb->dev; 4846 struct sk_buff *orig_skb = skb; 4847 struct netdev_queue *txq; 4848 int ret = NETDEV_TX_BUSY; 4849 bool again = false; 4850 4851 if (unlikely(!netif_running(dev) || 4852 !netif_carrier_ok(dev))) 4853 goto drop; 4854 4855 skb = validate_xmit_skb_list(skb, dev, &again); 4856 if (skb != orig_skb) 4857 goto drop; 4858 4859 skb_set_queue_mapping(skb, queue_id); 4860 txq = skb_get_tx_queue(dev, skb); 4861 4862 local_bh_disable(); 4863 4864 dev_xmit_recursion_inc(); 4865 HARD_TX_LOCK(dev, txq, smp_processor_id()); 4866 if (!netif_xmit_frozen_or_drv_stopped(txq)) 4867 ret = netdev_start_xmit(skb, dev, txq, false); 4868 HARD_TX_UNLOCK(dev, txq); 4869 dev_xmit_recursion_dec(); 4870 4871 local_bh_enable(); 4872 return ret; 4873 drop: 4874 dev_core_stats_tx_dropped_inc(dev); 4875 kfree_skb_list(skb); 4876 return NET_XMIT_DROP; 4877 } 4878 EXPORT_SYMBOL(__dev_direct_xmit); 4879 4880 /************************************************************************* 4881 * Receiver routines 4882 *************************************************************************/ 4883 static DEFINE_PER_CPU(struct task_struct *, backlog_napi); 4884 4885 int weight_p __read_mostly = 64; /* old backlog weight */ 4886 int dev_weight_rx_bias __read_mostly = 1; /* bias for backlog weight */ 4887 int dev_weight_tx_bias __read_mostly = 1; /* bias for output_queue quota */ 4888 4889 /* Called with irq disabled */ 4890 static inline void ____napi_schedule(struct softnet_data *sd, 4891 struct napi_struct *napi) 4892 { 4893 struct task_struct *thread; 4894 4895 lockdep_assert_irqs_disabled(); 4896 4897 if (test_bit(NAPI_STATE_THREADED, &napi->state)) { 4898 /* Paired with smp_mb__before_atomic() in 4899 * napi_enable()/netif_set_threaded(). 4900 * Use READ_ONCE() to guarantee a complete 4901 * read on napi->thread. Only call 4902 * wake_up_process() when it's not NULL. 4903 */ 4904 thread = READ_ONCE(napi->thread); 4905 if (thread) { 4906 if (use_backlog_threads() && thread == raw_cpu_read(backlog_napi)) 4907 goto use_local_napi; 4908 4909 set_bit(NAPI_STATE_SCHED_THREADED, &napi->state); 4910 wake_up_process(thread); 4911 return; 4912 } 4913 } 4914 4915 use_local_napi: 4916 DEBUG_NET_WARN_ON_ONCE(!list_empty(&napi->poll_list)); 4917 list_add_tail(&napi->poll_list, &sd->poll_list); 4918 WRITE_ONCE(napi->list_owner, smp_processor_id()); 4919 /* If not called from net_rx_action() 4920 * we have to raise NET_RX_SOFTIRQ. 4921 */ 4922 if (!sd->in_net_rx_action) 4923 raise_softirq_irqoff(NET_RX_SOFTIRQ); 4924 } 4925 4926 #ifdef CONFIG_RPS 4927 4928 struct static_key_false rps_needed __read_mostly; 4929 EXPORT_SYMBOL(rps_needed); 4930 struct static_key_false rfs_needed __read_mostly; 4931 EXPORT_SYMBOL(rfs_needed); 4932 4933 static u32 rfs_slot(u32 hash, const struct rps_dev_flow_table *flow_table) 4934 { 4935 return hash_32(hash, flow_table->log); 4936 } 4937 4938 #ifdef CONFIG_RFS_ACCEL 4939 /** 4940 * rps_flow_is_active - check whether the flow is recently active. 4941 * @rflow: Specific flow to check activity. 4942 * @flow_table: per-queue flowtable that @rflow belongs to. 4943 * @cpu: CPU saved in @rflow. 4944 * 4945 * If the CPU has processed many packets since the flow's last activity 4946 * (beyond 10 times the table size), the flow is considered stale. 4947 * 4948 * Return: true if flow was recently active. 4949 */ 4950 static bool rps_flow_is_active(struct rps_dev_flow *rflow, 4951 struct rps_dev_flow_table *flow_table, 4952 unsigned int cpu) 4953 { 4954 unsigned int flow_last_active; 4955 unsigned int sd_input_head; 4956 4957 if (cpu >= nr_cpu_ids) 4958 return false; 4959 4960 sd_input_head = READ_ONCE(per_cpu(softnet_data, cpu).input_queue_head); 4961 flow_last_active = READ_ONCE(rflow->last_qtail); 4962 4963 return (int)(sd_input_head - flow_last_active) < 4964 (int)(10 << flow_table->log); 4965 } 4966 #endif 4967 4968 static struct rps_dev_flow * 4969 set_rps_cpu(struct net_device *dev, struct sk_buff *skb, 4970 struct rps_dev_flow *rflow, u16 next_cpu, u32 hash, 4971 u32 flow_id) 4972 { 4973 if (next_cpu < nr_cpu_ids) { 4974 u32 head; 4975 #ifdef CONFIG_RFS_ACCEL 4976 struct netdev_rx_queue *rxqueue; 4977 struct rps_dev_flow_table *flow_table; 4978 struct rps_dev_flow *old_rflow; 4979 struct rps_dev_flow *tmp_rflow; 4980 unsigned int tmp_cpu; 4981 u16 rxq_index; 4982 int rc; 4983 4984 /* Should we steer this flow to a different hardware queue? */ 4985 if (!skb_rx_queue_recorded(skb) || !dev->rx_cpu_rmap || 4986 !(dev->features & NETIF_F_NTUPLE)) 4987 goto out; 4988 rxq_index = cpu_rmap_lookup_index(dev->rx_cpu_rmap, next_cpu); 4989 if (rxq_index == skb_get_rx_queue(skb)) 4990 goto out; 4991 4992 rxqueue = dev->_rx + rxq_index; 4993 flow_table = rcu_dereference(rxqueue->rps_flow_table); 4994 if (!flow_table) 4995 goto out; 4996 4997 tmp_rflow = &flow_table->flows[flow_id]; 4998 tmp_cpu = READ_ONCE(tmp_rflow->cpu); 4999 5000 if (READ_ONCE(tmp_rflow->filter) != RPS_NO_FILTER) { 5001 if (rps_flow_is_active(tmp_rflow, flow_table, 5002 tmp_cpu)) { 5003 if (hash != READ_ONCE(tmp_rflow->hash) || 5004 next_cpu == tmp_cpu) 5005 goto out; 5006 } 5007 } 5008 5009 rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb, 5010 rxq_index, flow_id); 5011 if (rc < 0) 5012 goto out; 5013 5014 old_rflow = rflow; 5015 rflow = tmp_rflow; 5016 WRITE_ONCE(rflow->filter, rc); 5017 WRITE_ONCE(rflow->hash, hash); 5018 5019 if (old_rflow->filter == rc) 5020 WRITE_ONCE(old_rflow->filter, RPS_NO_FILTER); 5021 out: 5022 #endif 5023 head = READ_ONCE(per_cpu(softnet_data, next_cpu).input_queue_head); 5024 rps_input_queue_tail_save(&rflow->last_qtail, head); 5025 } 5026 5027 WRITE_ONCE(rflow->cpu, next_cpu); 5028 return rflow; 5029 } 5030 5031 /* 5032 * get_rps_cpu is called from netif_receive_skb and returns the target 5033 * CPU from the RPS map of the receiving queue for a given skb. 5034 * rcu_read_lock must be held on entry. 5035 */ 5036 static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb, 5037 struct rps_dev_flow **rflowp) 5038 { 5039 const struct rps_sock_flow_table *sock_flow_table; 5040 struct netdev_rx_queue *rxqueue = dev->_rx; 5041 struct rps_dev_flow_table *flow_table; 5042 struct rps_map *map; 5043 int cpu = -1; 5044 u32 flow_id; 5045 u32 tcpu; 5046 u32 hash; 5047 5048 if (skb_rx_queue_recorded(skb)) { 5049 u16 index = skb_get_rx_queue(skb); 5050 5051 if (unlikely(index >= dev->real_num_rx_queues)) { 5052 WARN_ONCE(dev->real_num_rx_queues > 1, 5053 "%s received packet on queue %u, but number " 5054 "of RX queues is %u\n", 5055 dev->name, index, dev->real_num_rx_queues); 5056 goto done; 5057 } 5058 rxqueue += index; 5059 } 5060 5061 /* Avoid computing hash if RFS/RPS is not active for this rxqueue */ 5062 5063 flow_table = rcu_dereference(rxqueue->rps_flow_table); 5064 map = rcu_dereference(rxqueue->rps_map); 5065 if (!flow_table && !map) 5066 goto done; 5067 5068 skb_reset_network_header(skb); 5069 hash = skb_get_hash(skb); 5070 if (!hash) 5071 goto done; 5072 5073 sock_flow_table = rcu_dereference(net_hotdata.rps_sock_flow_table); 5074 if (flow_table && sock_flow_table) { 5075 struct rps_dev_flow *rflow; 5076 u32 next_cpu; 5077 u32 ident; 5078 5079 /* First check into global flow table if there is a match. 5080 * This READ_ONCE() pairs with WRITE_ONCE() from rps_record_sock_flow(). 5081 */ 5082 ident = READ_ONCE(sock_flow_table->ents[hash & sock_flow_table->mask]); 5083 if ((ident ^ hash) & ~net_hotdata.rps_cpu_mask) 5084 goto try_rps; 5085 5086 next_cpu = ident & net_hotdata.rps_cpu_mask; 5087 5088 /* OK, now we know there is a match, 5089 * we can look at the local (per receive queue) flow table 5090 */ 5091 flow_id = rfs_slot(hash, flow_table); 5092 rflow = &flow_table->flows[flow_id]; 5093 tcpu = rflow->cpu; 5094 5095 /* 5096 * If the desired CPU (where last recvmsg was done) is 5097 * different from current CPU (one in the rx-queue flow 5098 * table entry), switch if one of the following holds: 5099 * - Current CPU is unset (>= nr_cpu_ids). 5100 * - Current CPU is offline. 5101 * - The current CPU's queue tail has advanced beyond the 5102 * last packet that was enqueued using this table entry. 5103 * This guarantees that all previous packets for the flow 5104 * have been dequeued, thus preserving in order delivery. 5105 */ 5106 if (unlikely(tcpu != next_cpu) && 5107 (tcpu >= nr_cpu_ids || !cpu_online(tcpu) || 5108 ((int)(READ_ONCE(per_cpu(softnet_data, tcpu).input_queue_head) - 5109 rflow->last_qtail)) >= 0)) { 5110 tcpu = next_cpu; 5111 rflow = set_rps_cpu(dev, skb, rflow, next_cpu, hash, 5112 flow_id); 5113 } 5114 5115 if (tcpu < nr_cpu_ids && cpu_online(tcpu)) { 5116 *rflowp = rflow; 5117 cpu = tcpu; 5118 goto done; 5119 } 5120 } 5121 5122 try_rps: 5123 5124 if (map) { 5125 tcpu = map->cpus[reciprocal_scale(hash, map->len)]; 5126 if (cpu_online(tcpu)) { 5127 cpu = tcpu; 5128 goto done; 5129 } 5130 } 5131 5132 done: 5133 return cpu; 5134 } 5135 5136 #ifdef CONFIG_RFS_ACCEL 5137 5138 /** 5139 * rps_may_expire_flow - check whether an RFS hardware filter may be removed 5140 * @dev: Device on which the filter was set 5141 * @rxq_index: RX queue index 5142 * @flow_id: Flow ID passed to ndo_rx_flow_steer() 5143 * @filter_id: Filter ID returned by ndo_rx_flow_steer() 5144 * 5145 * Drivers that implement ndo_rx_flow_steer() should periodically call 5146 * this function for each installed filter and remove the filters for 5147 * which it returns %true. 5148 */ 5149 bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index, 5150 u32 flow_id, u16 filter_id) 5151 { 5152 struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index; 5153 struct rps_dev_flow_table *flow_table; 5154 struct rps_dev_flow *rflow; 5155 bool expire = true; 5156 5157 rcu_read_lock(); 5158 flow_table = rcu_dereference(rxqueue->rps_flow_table); 5159 if (flow_table && flow_id < (1UL << flow_table->log)) { 5160 unsigned int cpu; 5161 5162 rflow = &flow_table->flows[flow_id]; 5163 cpu = READ_ONCE(rflow->cpu); 5164 if (READ_ONCE(rflow->filter) == filter_id && 5165 rps_flow_is_active(rflow, flow_table, cpu)) 5166 expire = false; 5167 } 5168 rcu_read_unlock(); 5169 return expire; 5170 } 5171 EXPORT_SYMBOL(rps_may_expire_flow); 5172 5173 #endif /* CONFIG_RFS_ACCEL */ 5174 5175 /* Called from hardirq (IPI) context */ 5176 static void rps_trigger_softirq(void *data) 5177 { 5178 struct softnet_data *sd = data; 5179 5180 ____napi_schedule(sd, &sd->backlog); 5181 /* Pairs with READ_ONCE() in softnet_seq_show() */ 5182 WRITE_ONCE(sd->received_rps, sd->received_rps + 1); 5183 } 5184 5185 #endif /* CONFIG_RPS */ 5186 5187 /* Called from hardirq (IPI) context */ 5188 static void trigger_rx_softirq(void *data) 5189 { 5190 struct softnet_data *sd = data; 5191 5192 __raise_softirq_irqoff(NET_RX_SOFTIRQ); 5193 smp_store_release(&sd->defer_ipi_scheduled, 0); 5194 } 5195 5196 /* 5197 * After we queued a packet into sd->input_pkt_queue, 5198 * we need to make sure this queue is serviced soon. 5199 * 5200 * - If this is another cpu queue, link it to our rps_ipi_list, 5201 * and make sure we will process rps_ipi_list from net_rx_action(). 5202 * 5203 * - If this is our own queue, NAPI schedule our backlog. 5204 * Note that this also raises NET_RX_SOFTIRQ. 5205 */ 5206 static void napi_schedule_rps(struct softnet_data *sd) 5207 { 5208 struct softnet_data *mysd = this_cpu_ptr(&softnet_data); 5209 5210 #ifdef CONFIG_RPS 5211 if (sd != mysd) { 5212 if (use_backlog_threads()) { 5213 __napi_schedule_irqoff(&sd->backlog); 5214 return; 5215 } 5216 5217 sd->rps_ipi_next = mysd->rps_ipi_list; 5218 mysd->rps_ipi_list = sd; 5219 5220 /* If not called from net_rx_action() or napi_threaded_poll() 5221 * we have to raise NET_RX_SOFTIRQ. 5222 */ 5223 if (!mysd->in_net_rx_action && !mysd->in_napi_threaded_poll) 5224 __raise_softirq_irqoff(NET_RX_SOFTIRQ); 5225 return; 5226 } 5227 #endif /* CONFIG_RPS */ 5228 __napi_schedule_irqoff(&mysd->backlog); 5229 } 5230 5231 void kick_defer_list_purge(unsigned int cpu) 5232 { 5233 struct softnet_data *sd = &per_cpu(softnet_data, cpu); 5234 unsigned long flags; 5235 5236 if (use_backlog_threads()) { 5237 backlog_lock_irq_save(sd, &flags); 5238 5239 if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state)) 5240 __napi_schedule_irqoff(&sd->backlog); 5241 5242 backlog_unlock_irq_restore(sd, &flags); 5243 5244 } else if (!cmpxchg(&sd->defer_ipi_scheduled, 0, 1)) { 5245 smp_call_function_single_async(cpu, &sd->defer_csd); 5246 } 5247 } 5248 5249 #ifdef CONFIG_NET_FLOW_LIMIT 5250 int netdev_flow_limit_table_len __read_mostly = (1 << 12); 5251 #endif 5252 5253 static bool skb_flow_limit(struct sk_buff *skb, unsigned int qlen, 5254 int max_backlog) 5255 { 5256 #ifdef CONFIG_NET_FLOW_LIMIT 5257 unsigned int old_flow, new_flow; 5258 const struct softnet_data *sd; 5259 struct sd_flow_limit *fl; 5260 5261 if (likely(qlen < (max_backlog >> 1))) 5262 return false; 5263 5264 sd = this_cpu_ptr(&softnet_data); 5265 5266 rcu_read_lock(); 5267 fl = rcu_dereference(sd->flow_limit); 5268 if (fl) { 5269 new_flow = hash_32(skb_get_hash(skb), fl->log_buckets); 5270 old_flow = fl->history[fl->history_head]; 5271 fl->history[fl->history_head] = new_flow; 5272 5273 fl->history_head++; 5274 fl->history_head &= FLOW_LIMIT_HISTORY - 1; 5275 5276 if (likely(fl->buckets[old_flow])) 5277 fl->buckets[old_flow]--; 5278 5279 if (++fl->buckets[new_flow] > (FLOW_LIMIT_HISTORY >> 1)) { 5280 /* Pairs with READ_ONCE() in softnet_seq_show() */ 5281 WRITE_ONCE(fl->count, fl->count + 1); 5282 rcu_read_unlock(); 5283 return true; 5284 } 5285 } 5286 rcu_read_unlock(); 5287 #endif 5288 return false; 5289 } 5290 5291 /* 5292 * enqueue_to_backlog is called to queue an skb to a per CPU backlog 5293 * queue (may be a remote CPU queue). 5294 */ 5295 static int enqueue_to_backlog(struct sk_buff *skb, int cpu, 5296 unsigned int *qtail) 5297 { 5298 enum skb_drop_reason reason; 5299 struct softnet_data *sd; 5300 unsigned long flags; 5301 unsigned int qlen; 5302 int max_backlog; 5303 u32 tail; 5304 5305 reason = SKB_DROP_REASON_DEV_READY; 5306 if (unlikely(!netif_running(skb->dev))) 5307 goto bad_dev; 5308 5309 sd = &per_cpu(softnet_data, cpu); 5310 5311 qlen = skb_queue_len_lockless(&sd->input_pkt_queue); 5312 max_backlog = READ_ONCE(net_hotdata.max_backlog); 5313 if (unlikely(qlen > max_backlog) || 5314 skb_flow_limit(skb, qlen, max_backlog)) 5315 goto cpu_backlog_drop; 5316 backlog_lock_irq_save(sd, &flags); 5317 qlen = skb_queue_len(&sd->input_pkt_queue); 5318 if (likely(qlen <= max_backlog)) { 5319 if (!qlen) { 5320 /* Schedule NAPI for backlog device. We can use 5321 * non atomic operation as we own the queue lock. 5322 */ 5323 if (!__test_and_set_bit(NAPI_STATE_SCHED, 5324 &sd->backlog.state)) 5325 napi_schedule_rps(sd); 5326 } 5327 __skb_queue_tail(&sd->input_pkt_queue, skb); 5328 tail = rps_input_queue_tail_incr(sd); 5329 backlog_unlock_irq_restore(sd, &flags); 5330 5331 /* save the tail outside of the critical section */ 5332 rps_input_queue_tail_save(qtail, tail); 5333 return NET_RX_SUCCESS; 5334 } 5335 5336 backlog_unlock_irq_restore(sd, &flags); 5337 5338 cpu_backlog_drop: 5339 reason = SKB_DROP_REASON_CPU_BACKLOG; 5340 numa_drop_add(&sd->drop_counters, 1); 5341 bad_dev: 5342 dev_core_stats_rx_dropped_inc(skb->dev); 5343 kfree_skb_reason(skb, reason); 5344 return NET_RX_DROP; 5345 } 5346 5347 static struct netdev_rx_queue *netif_get_rxqueue(struct sk_buff *skb) 5348 { 5349 struct net_device *dev = skb->dev; 5350 struct netdev_rx_queue *rxqueue; 5351 5352 rxqueue = dev->_rx; 5353 5354 if (skb_rx_queue_recorded(skb)) { 5355 u16 index = skb_get_rx_queue(skb); 5356 5357 if (unlikely(index >= dev->real_num_rx_queues)) { 5358 WARN_ONCE(dev->real_num_rx_queues > 1, 5359 "%s received packet on queue %u, but number " 5360 "of RX queues is %u\n", 5361 dev->name, index, dev->real_num_rx_queues); 5362 5363 return rxqueue; /* Return first rxqueue */ 5364 } 5365 rxqueue += index; 5366 } 5367 return rxqueue; 5368 } 5369 5370 u32 bpf_prog_run_generic_xdp(struct sk_buff *skb, struct xdp_buff *xdp, 5371 const struct bpf_prog *xdp_prog) 5372 { 5373 void *orig_data, *orig_data_end, *hard_start; 5374 struct netdev_rx_queue *rxqueue; 5375 bool orig_bcast, orig_host; 5376 u32 mac_len, frame_sz; 5377 __be16 orig_eth_type; 5378 struct ethhdr *eth; 5379 u32 metalen, act; 5380 int off; 5381 5382 /* The XDP program wants to see the packet starting at the MAC 5383 * header. 5384 */ 5385 mac_len = skb->data - skb_mac_header(skb); 5386 hard_start = skb->data - skb_headroom(skb); 5387 5388 /* SKB "head" area always have tailroom for skb_shared_info */ 5389 frame_sz = (void *)skb_end_pointer(skb) - hard_start; 5390 frame_sz += SKB_DATA_ALIGN(sizeof(struct skb_shared_info)); 5391 5392 rxqueue = netif_get_rxqueue(skb); 5393 xdp_init_buff(xdp, frame_sz, &rxqueue->xdp_rxq); 5394 xdp_prepare_buff(xdp, hard_start, skb_headroom(skb) - mac_len, 5395 skb_headlen(skb) + mac_len, true); 5396 if (skb_is_nonlinear(skb)) { 5397 skb_shinfo(skb)->xdp_frags_size = skb->data_len; 5398 xdp_buff_set_frags_flag(xdp); 5399 } else { 5400 xdp_buff_clear_frags_flag(xdp); 5401 } 5402 5403 orig_data_end = xdp->data_end; 5404 orig_data = xdp->data; 5405 eth = (struct ethhdr *)xdp->data; 5406 orig_host = ether_addr_equal_64bits(eth->h_dest, skb->dev->dev_addr); 5407 orig_bcast = is_multicast_ether_addr_64bits(eth->h_dest); 5408 orig_eth_type = eth->h_proto; 5409 5410 act = bpf_prog_run_xdp(xdp_prog, xdp); 5411 5412 /* check if bpf_xdp_adjust_head was used */ 5413 off = xdp->data - orig_data; 5414 if (off) { 5415 if (off > 0) 5416 __skb_pull(skb, off); 5417 else if (off < 0) 5418 __skb_push(skb, -off); 5419 5420 skb->mac_header += off; 5421 skb_reset_network_header(skb); 5422 } 5423 5424 /* check if bpf_xdp_adjust_tail was used */ 5425 off = xdp->data_end - orig_data_end; 5426 if (off != 0) { 5427 skb_set_tail_pointer(skb, xdp->data_end - xdp->data); 5428 skb->len += off; /* positive on grow, negative on shrink */ 5429 } 5430 5431 /* XDP frag metadata (e.g. nr_frags) are updated in eBPF helpers 5432 * (e.g. bpf_xdp_adjust_tail), we need to update data_len here. 5433 */ 5434 if (xdp_buff_has_frags(xdp)) 5435 skb->data_len = skb_shinfo(skb)->xdp_frags_size; 5436 else 5437 skb->data_len = 0; 5438 5439 /* check if XDP changed eth hdr such SKB needs update */ 5440 eth = (struct ethhdr *)xdp->data; 5441 if ((orig_eth_type != eth->h_proto) || 5442 (orig_host != ether_addr_equal_64bits(eth->h_dest, 5443 skb->dev->dev_addr)) || 5444 (orig_bcast != is_multicast_ether_addr_64bits(eth->h_dest))) { 5445 __skb_push(skb, ETH_HLEN); 5446 skb->pkt_type = PACKET_HOST; 5447 skb->protocol = eth_type_trans(skb, skb->dev); 5448 } 5449 5450 /* Redirect/Tx gives L2 packet, code that will reuse skb must __skb_pull 5451 * before calling us again on redirect path. We do not call do_redirect 5452 * as we leave that up to the caller. 5453 * 5454 * Caller is responsible for managing lifetime of skb (i.e. calling 5455 * kfree_skb in response to actions it cannot handle/XDP_DROP). 5456 */ 5457 switch (act) { 5458 case XDP_REDIRECT: 5459 case XDP_TX: 5460 __skb_push(skb, mac_len); 5461 break; 5462 case XDP_PASS: 5463 metalen = xdp->data - xdp->data_meta; 5464 if (metalen) 5465 skb_metadata_set(skb, metalen); 5466 break; 5467 } 5468 5469 return act; 5470 } 5471 5472 static int 5473 netif_skb_check_for_xdp(struct sk_buff **pskb, const struct bpf_prog *prog) 5474 { 5475 struct sk_buff *skb = *pskb; 5476 int err, hroom, troom; 5477 5478 local_lock_nested_bh(&system_page_pool.bh_lock); 5479 err = skb_cow_data_for_xdp(this_cpu_read(system_page_pool.pool), pskb, prog); 5480 local_unlock_nested_bh(&system_page_pool.bh_lock); 5481 if (!err) 5482 return 0; 5483 5484 /* In case we have to go down the path and also linearize, 5485 * then lets do the pskb_expand_head() work just once here. 5486 */ 5487 hroom = XDP_PACKET_HEADROOM - skb_headroom(skb); 5488 troom = skb->tail + skb->data_len - skb->end; 5489 err = pskb_expand_head(skb, 5490 hroom > 0 ? ALIGN(hroom, NET_SKB_PAD) : 0, 5491 troom > 0 ? troom + 128 : 0, GFP_ATOMIC); 5492 if (err) 5493 return err; 5494 5495 return skb_linearize(skb); 5496 } 5497 5498 static u32 netif_receive_generic_xdp(struct sk_buff **pskb, 5499 struct xdp_buff *xdp, 5500 const struct bpf_prog *xdp_prog) 5501 { 5502 struct sk_buff *skb = *pskb; 5503 u32 mac_len, act = XDP_DROP; 5504 5505 /* Reinjected packets coming from act_mirred or similar should 5506 * not get XDP generic processing. 5507 */ 5508 if (skb_is_redirected(skb)) 5509 return XDP_PASS; 5510 5511 /* XDP packets must have sufficient headroom of XDP_PACKET_HEADROOM 5512 * bytes. This is the guarantee that also native XDP provides, 5513 * thus we need to do it here as well. 5514 */ 5515 mac_len = skb->data - skb_mac_header(skb); 5516 __skb_push(skb, mac_len); 5517 5518 if (skb_cloned(skb) || skb_is_nonlinear(skb) || 5519 skb_headroom(skb) < XDP_PACKET_HEADROOM) { 5520 if (netif_skb_check_for_xdp(pskb, xdp_prog)) 5521 goto do_drop; 5522 } 5523 5524 __skb_pull(*pskb, mac_len); 5525 5526 act = bpf_prog_run_generic_xdp(*pskb, xdp, xdp_prog); 5527 switch (act) { 5528 case XDP_REDIRECT: 5529 case XDP_TX: 5530 case XDP_PASS: 5531 break; 5532 default: 5533 bpf_warn_invalid_xdp_action((*pskb)->dev, xdp_prog, act); 5534 fallthrough; 5535 case XDP_ABORTED: 5536 trace_xdp_exception((*pskb)->dev, xdp_prog, act); 5537 fallthrough; 5538 case XDP_DROP: 5539 do_drop: 5540 kfree_skb(*pskb); 5541 break; 5542 } 5543 5544 return act; 5545 } 5546 5547 /* When doing generic XDP we have to bypass the qdisc layer and the 5548 * network taps in order to match in-driver-XDP behavior. This also means 5549 * that XDP packets are able to starve other packets going through a qdisc, 5550 * and DDOS attacks will be more effective. In-driver-XDP use dedicated TX 5551 * queues, so they do not have this starvation issue. 5552 */ 5553 void generic_xdp_tx(struct sk_buff *skb, const struct bpf_prog *xdp_prog) 5554 { 5555 struct net_device *dev = skb->dev; 5556 struct netdev_queue *txq; 5557 bool free_skb = true; 5558 int cpu, rc; 5559 5560 txq = netdev_core_pick_tx(dev, skb, NULL); 5561 cpu = smp_processor_id(); 5562 HARD_TX_LOCK(dev, txq, cpu); 5563 if (!netif_xmit_frozen_or_drv_stopped(txq)) { 5564 rc = netdev_start_xmit(skb, dev, txq, 0); 5565 if (dev_xmit_complete(rc)) 5566 free_skb = false; 5567 } 5568 HARD_TX_UNLOCK(dev, txq); 5569 if (free_skb) { 5570 trace_xdp_exception(dev, xdp_prog, XDP_TX); 5571 dev_core_stats_tx_dropped_inc(dev); 5572 kfree_skb(skb); 5573 } 5574 } 5575 5576 static DEFINE_STATIC_KEY_FALSE(generic_xdp_needed_key); 5577 5578 int do_xdp_generic(const struct bpf_prog *xdp_prog, struct sk_buff **pskb) 5579 { 5580 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx; 5581 5582 if (xdp_prog) { 5583 struct xdp_buff xdp; 5584 u32 act; 5585 int err; 5586 5587 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx); 5588 act = netif_receive_generic_xdp(pskb, &xdp, xdp_prog); 5589 if (act != XDP_PASS) { 5590 switch (act) { 5591 case XDP_REDIRECT: 5592 err = xdp_do_generic_redirect((*pskb)->dev, *pskb, 5593 &xdp, xdp_prog); 5594 if (err) 5595 goto out_redir; 5596 break; 5597 case XDP_TX: 5598 generic_xdp_tx(*pskb, xdp_prog); 5599 break; 5600 } 5601 bpf_net_ctx_clear(bpf_net_ctx); 5602 return XDP_DROP; 5603 } 5604 bpf_net_ctx_clear(bpf_net_ctx); 5605 } 5606 return XDP_PASS; 5607 out_redir: 5608 bpf_net_ctx_clear(bpf_net_ctx); 5609 kfree_skb_reason(*pskb, SKB_DROP_REASON_XDP); 5610 return XDP_DROP; 5611 } 5612 EXPORT_SYMBOL_GPL(do_xdp_generic); 5613 5614 static int netif_rx_internal(struct sk_buff *skb) 5615 { 5616 int ret; 5617 5618 net_timestamp_check(READ_ONCE(net_hotdata.tstamp_prequeue), skb); 5619 5620 trace_netif_rx(skb); 5621 5622 #ifdef CONFIG_RPS 5623 if (static_branch_unlikely(&rps_needed)) { 5624 struct rps_dev_flow voidflow, *rflow = &voidflow; 5625 int cpu; 5626 5627 rcu_read_lock(); 5628 5629 cpu = get_rps_cpu(skb->dev, skb, &rflow); 5630 if (cpu < 0) 5631 cpu = smp_processor_id(); 5632 5633 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail); 5634 5635 rcu_read_unlock(); 5636 } else 5637 #endif 5638 { 5639 unsigned int qtail; 5640 5641 ret = enqueue_to_backlog(skb, smp_processor_id(), &qtail); 5642 } 5643 return ret; 5644 } 5645 5646 /** 5647 * __netif_rx - Slightly optimized version of netif_rx 5648 * @skb: buffer to post 5649 * 5650 * This behaves as netif_rx except that it does not disable bottom halves. 5651 * As a result this function may only be invoked from the interrupt context 5652 * (either hard or soft interrupt). 5653 */ 5654 int __netif_rx(struct sk_buff *skb) 5655 { 5656 int ret; 5657 5658 lockdep_assert_once(hardirq_count() | softirq_count()); 5659 5660 trace_netif_rx_entry(skb); 5661 ret = netif_rx_internal(skb); 5662 trace_netif_rx_exit(ret); 5663 return ret; 5664 } 5665 EXPORT_SYMBOL(__netif_rx); 5666 5667 /** 5668 * netif_rx - post buffer to the network code 5669 * @skb: buffer to post 5670 * 5671 * This function receives a packet from a device driver and queues it for 5672 * the upper (protocol) levels to process via the backlog NAPI device. It 5673 * always succeeds. The buffer may be dropped during processing for 5674 * congestion control or by the protocol layers. 5675 * The network buffer is passed via the backlog NAPI device. Modern NIC 5676 * driver should use NAPI and GRO. 5677 * This function can used from interrupt and from process context. The 5678 * caller from process context must not disable interrupts before invoking 5679 * this function. 5680 * 5681 * return values: 5682 * NET_RX_SUCCESS (no congestion) 5683 * NET_RX_DROP (packet was dropped) 5684 * 5685 */ 5686 int netif_rx(struct sk_buff *skb) 5687 { 5688 bool need_bh_off = !(hardirq_count() | softirq_count()); 5689 int ret; 5690 5691 if (need_bh_off) 5692 local_bh_disable(); 5693 trace_netif_rx_entry(skb); 5694 ret = netif_rx_internal(skb); 5695 trace_netif_rx_exit(ret); 5696 if (need_bh_off) 5697 local_bh_enable(); 5698 return ret; 5699 } 5700 EXPORT_SYMBOL(netif_rx); 5701 5702 static __latent_entropy void net_tx_action(void) 5703 { 5704 struct softnet_data *sd = this_cpu_ptr(&softnet_data); 5705 5706 if (sd->completion_queue) { 5707 struct sk_buff *clist; 5708 5709 local_irq_disable(); 5710 clist = sd->completion_queue; 5711 sd->completion_queue = NULL; 5712 local_irq_enable(); 5713 5714 while (clist) { 5715 struct sk_buff *skb = clist; 5716 5717 clist = clist->next; 5718 5719 WARN_ON(refcount_read(&skb->users)); 5720 if (likely(get_kfree_skb_cb(skb)->reason == SKB_CONSUMED)) 5721 trace_consume_skb(skb, net_tx_action); 5722 else 5723 trace_kfree_skb(skb, net_tx_action, 5724 get_kfree_skb_cb(skb)->reason, NULL); 5725 5726 if (skb->fclone != SKB_FCLONE_UNAVAILABLE) 5727 __kfree_skb(skb); 5728 else 5729 __napi_kfree_skb(skb, 5730 get_kfree_skb_cb(skb)->reason); 5731 } 5732 } 5733 5734 if (sd->output_queue) { 5735 struct Qdisc *head; 5736 5737 local_irq_disable(); 5738 head = sd->output_queue; 5739 sd->output_queue = NULL; 5740 sd->output_queue_tailp = &sd->output_queue; 5741 local_irq_enable(); 5742 5743 rcu_read_lock(); 5744 5745 while (head) { 5746 struct Qdisc *q = head; 5747 spinlock_t *root_lock = NULL; 5748 5749 head = head->next_sched; 5750 5751 /* We need to make sure head->next_sched is read 5752 * before clearing __QDISC_STATE_SCHED 5753 */ 5754 smp_mb__before_atomic(); 5755 5756 if (!(q->flags & TCQ_F_NOLOCK)) { 5757 root_lock = qdisc_lock(q); 5758 spin_lock(root_lock); 5759 } else if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, 5760 &q->state))) { 5761 /* There is a synchronize_net() between 5762 * STATE_DEACTIVATED flag being set and 5763 * qdisc_reset()/some_qdisc_is_busy() in 5764 * dev_deactivate(), so we can safely bail out 5765 * early here to avoid data race between 5766 * qdisc_deactivate() and some_qdisc_is_busy() 5767 * for lockless qdisc. 5768 */ 5769 clear_bit(__QDISC_STATE_SCHED, &q->state); 5770 continue; 5771 } 5772 5773 clear_bit(__QDISC_STATE_SCHED, &q->state); 5774 qdisc_run(q); 5775 if (root_lock) 5776 spin_unlock(root_lock); 5777 } 5778 5779 rcu_read_unlock(); 5780 } 5781 5782 xfrm_dev_backlog(sd); 5783 } 5784 5785 #if IS_ENABLED(CONFIG_BRIDGE) && IS_ENABLED(CONFIG_ATM_LANE) 5786 /* This hook is defined here for ATM LANE */ 5787 int (*br_fdb_test_addr_hook)(struct net_device *dev, 5788 unsigned char *addr) __read_mostly; 5789 EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook); 5790 #endif 5791 5792 /** 5793 * netdev_is_rx_handler_busy - check if receive handler is registered 5794 * @dev: device to check 5795 * 5796 * Check if a receive handler is already registered for a given device. 5797 * Return true if there one. 5798 * 5799 * The caller must hold the rtnl_mutex. 5800 */ 5801 bool netdev_is_rx_handler_busy(struct net_device *dev) 5802 { 5803 ASSERT_RTNL(); 5804 return dev && rtnl_dereference(dev->rx_handler); 5805 } 5806 EXPORT_SYMBOL_GPL(netdev_is_rx_handler_busy); 5807 5808 /** 5809 * netdev_rx_handler_register - register receive handler 5810 * @dev: device to register a handler for 5811 * @rx_handler: receive handler to register 5812 * @rx_handler_data: data pointer that is used by rx handler 5813 * 5814 * Register a receive handler for a device. This handler will then be 5815 * called from __netif_receive_skb. A negative errno code is returned 5816 * on a failure. 5817 * 5818 * The caller must hold the rtnl_mutex. 5819 * 5820 * For a general description of rx_handler, see enum rx_handler_result. 5821 */ 5822 int netdev_rx_handler_register(struct net_device *dev, 5823 rx_handler_func_t *rx_handler, 5824 void *rx_handler_data) 5825 { 5826 if (netdev_is_rx_handler_busy(dev)) 5827 return -EBUSY; 5828 5829 if (dev->priv_flags & IFF_NO_RX_HANDLER) 5830 return -EINVAL; 5831 5832 /* Note: rx_handler_data must be set before rx_handler */ 5833 rcu_assign_pointer(dev->rx_handler_data, rx_handler_data); 5834 rcu_assign_pointer(dev->rx_handler, rx_handler); 5835 5836 return 0; 5837 } 5838 EXPORT_SYMBOL_GPL(netdev_rx_handler_register); 5839 5840 /** 5841 * netdev_rx_handler_unregister - unregister receive handler 5842 * @dev: device to unregister a handler from 5843 * 5844 * Unregister a receive handler from a device. 5845 * 5846 * The caller must hold the rtnl_mutex. 5847 */ 5848 void netdev_rx_handler_unregister(struct net_device *dev) 5849 { 5850 5851 ASSERT_RTNL(); 5852 RCU_INIT_POINTER(dev->rx_handler, NULL); 5853 /* a reader seeing a non NULL rx_handler in a rcu_read_lock() 5854 * section has a guarantee to see a non NULL rx_handler_data 5855 * as well. 5856 */ 5857 synchronize_net(); 5858 RCU_INIT_POINTER(dev->rx_handler_data, NULL); 5859 } 5860 EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister); 5861 5862 /* 5863 * Limit the use of PFMEMALLOC reserves to those protocols that implement 5864 * the special handling of PFMEMALLOC skbs. 5865 */ 5866 static bool skb_pfmemalloc_protocol(struct sk_buff *skb) 5867 { 5868 switch (skb->protocol) { 5869 case htons(ETH_P_ARP): 5870 case htons(ETH_P_IP): 5871 case htons(ETH_P_IPV6): 5872 case htons(ETH_P_8021Q): 5873 case htons(ETH_P_8021AD): 5874 return true; 5875 default: 5876 return false; 5877 } 5878 } 5879 5880 static inline int nf_ingress(struct sk_buff *skb, struct packet_type **pt_prev, 5881 int *ret, struct net_device *orig_dev) 5882 { 5883 if (nf_hook_ingress_active(skb)) { 5884 int ingress_retval; 5885 5886 if (unlikely(*pt_prev)) { 5887 *ret = deliver_skb(skb, *pt_prev, orig_dev); 5888 *pt_prev = NULL; 5889 } 5890 5891 rcu_read_lock(); 5892 ingress_retval = nf_hook_ingress(skb); 5893 rcu_read_unlock(); 5894 return ingress_retval; 5895 } 5896 return 0; 5897 } 5898 5899 static int __netif_receive_skb_core(struct sk_buff **pskb, bool pfmemalloc, 5900 struct packet_type **ppt_prev) 5901 { 5902 enum skb_drop_reason drop_reason = SKB_DROP_REASON_UNHANDLED_PROTO; 5903 struct packet_type *ptype, *pt_prev; 5904 rx_handler_func_t *rx_handler; 5905 struct sk_buff *skb = *pskb; 5906 struct net_device *orig_dev; 5907 bool deliver_exact = false; 5908 int ret = NET_RX_DROP; 5909 __be16 type; 5910 5911 net_timestamp_check(!READ_ONCE(net_hotdata.tstamp_prequeue), skb); 5912 5913 trace_netif_receive_skb(skb); 5914 5915 orig_dev = skb->dev; 5916 5917 skb_reset_network_header(skb); 5918 #if !defined(CONFIG_DEBUG_NET) 5919 /* We plan to no longer reset the transport header here. 5920 * Give some time to fuzzers and dev build to catch bugs 5921 * in network stacks. 5922 */ 5923 if (!skb_transport_header_was_set(skb)) 5924 skb_reset_transport_header(skb); 5925 #endif 5926 skb_reset_mac_len(skb); 5927 5928 pt_prev = NULL; 5929 5930 another_round: 5931 skb->skb_iif = skb->dev->ifindex; 5932 5933 __this_cpu_inc(softnet_data.processed); 5934 5935 if (static_branch_unlikely(&generic_xdp_needed_key)) { 5936 int ret2; 5937 5938 migrate_disable(); 5939 ret2 = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog), 5940 &skb); 5941 migrate_enable(); 5942 5943 if (ret2 != XDP_PASS) { 5944 ret = NET_RX_DROP; 5945 goto out; 5946 } 5947 } 5948 5949 if (eth_type_vlan(skb->protocol)) { 5950 skb = skb_vlan_untag(skb); 5951 if (unlikely(!skb)) 5952 goto out; 5953 } 5954 5955 if (skb_skip_tc_classify(skb)) 5956 goto skip_classify; 5957 5958 if (pfmemalloc) 5959 goto skip_taps; 5960 5961 list_for_each_entry_rcu(ptype, &dev_net_rcu(skb->dev)->ptype_all, 5962 list) { 5963 if (unlikely(pt_prev)) 5964 ret = deliver_skb(skb, pt_prev, orig_dev); 5965 pt_prev = ptype; 5966 } 5967 5968 list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) { 5969 if (unlikely(pt_prev)) 5970 ret = deliver_skb(skb, pt_prev, orig_dev); 5971 pt_prev = ptype; 5972 } 5973 5974 skip_taps: 5975 #ifdef CONFIG_NET_INGRESS 5976 if (static_branch_unlikely(&ingress_needed_key)) { 5977 bool another = false; 5978 5979 nf_skip_egress(skb, true); 5980 skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev, 5981 &another); 5982 if (another) 5983 goto another_round; 5984 if (!skb) 5985 goto out; 5986 5987 nf_skip_egress(skb, false); 5988 if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0) 5989 goto out; 5990 } 5991 #endif 5992 skb_reset_redirect(skb); 5993 skip_classify: 5994 if (pfmemalloc && !skb_pfmemalloc_protocol(skb)) { 5995 drop_reason = SKB_DROP_REASON_PFMEMALLOC; 5996 goto drop; 5997 } 5998 5999 if (skb_vlan_tag_present(skb)) { 6000 if (unlikely(pt_prev)) { 6001 ret = deliver_skb(skb, pt_prev, orig_dev); 6002 pt_prev = NULL; 6003 } 6004 if (vlan_do_receive(&skb)) 6005 goto another_round; 6006 else if (unlikely(!skb)) 6007 goto out; 6008 } 6009 6010 rx_handler = rcu_dereference(skb->dev->rx_handler); 6011 if (rx_handler) { 6012 if (unlikely(pt_prev)) { 6013 ret = deliver_skb(skb, pt_prev, orig_dev); 6014 pt_prev = NULL; 6015 } 6016 switch (rx_handler(&skb)) { 6017 case RX_HANDLER_CONSUMED: 6018 ret = NET_RX_SUCCESS; 6019 goto out; 6020 case RX_HANDLER_ANOTHER: 6021 goto another_round; 6022 case RX_HANDLER_EXACT: 6023 deliver_exact = true; 6024 break; 6025 case RX_HANDLER_PASS: 6026 break; 6027 default: 6028 BUG(); 6029 } 6030 } 6031 6032 if (unlikely(skb_vlan_tag_present(skb)) && !netdev_uses_dsa(skb->dev)) { 6033 check_vlan_id: 6034 if (skb_vlan_tag_get_id(skb)) { 6035 /* Vlan id is non 0 and vlan_do_receive() above couldn't 6036 * find vlan device. 6037 */ 6038 skb->pkt_type = PACKET_OTHERHOST; 6039 } else if (eth_type_vlan(skb->protocol)) { 6040 /* Outer header is 802.1P with vlan 0, inner header is 6041 * 802.1Q or 802.1AD and vlan_do_receive() above could 6042 * not find vlan dev for vlan id 0. 6043 */ 6044 __vlan_hwaccel_clear_tag(skb); 6045 skb = skb_vlan_untag(skb); 6046 if (unlikely(!skb)) 6047 goto out; 6048 if (vlan_do_receive(&skb)) 6049 /* After stripping off 802.1P header with vlan 0 6050 * vlan dev is found for inner header. 6051 */ 6052 goto another_round; 6053 else if (unlikely(!skb)) 6054 goto out; 6055 else 6056 /* We have stripped outer 802.1P vlan 0 header. 6057 * But could not find vlan dev. 6058 * check again for vlan id to set OTHERHOST. 6059 */ 6060 goto check_vlan_id; 6061 } 6062 /* Note: we might in the future use prio bits 6063 * and set skb->priority like in vlan_do_receive() 6064 * For the time being, just ignore Priority Code Point 6065 */ 6066 __vlan_hwaccel_clear_tag(skb); 6067 } 6068 6069 type = skb->protocol; 6070 6071 /* deliver only exact match when indicated */ 6072 if (likely(!deliver_exact)) { 6073 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type, 6074 &ptype_base[ntohs(type) & 6075 PTYPE_HASH_MASK]); 6076 6077 /* orig_dev and skb->dev could belong to different netns; 6078 * Even in such case we need to traverse only the list 6079 * coming from skb->dev, as the ptype owner (packet socket) 6080 * will use dev_net(skb->dev) to do namespace filtering. 6081 */ 6082 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type, 6083 &dev_net_rcu(skb->dev)->ptype_specific); 6084 } 6085 6086 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type, 6087 &orig_dev->ptype_specific); 6088 6089 if (unlikely(skb->dev != orig_dev)) { 6090 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type, 6091 &skb->dev->ptype_specific); 6092 } 6093 6094 if (pt_prev) { 6095 *ppt_prev = pt_prev; 6096 } else { 6097 drop: 6098 if (!deliver_exact) 6099 dev_core_stats_rx_dropped_inc(skb->dev); 6100 else 6101 dev_core_stats_rx_nohandler_inc(skb->dev); 6102 6103 kfree_skb_reason(skb, drop_reason); 6104 /* Jamal, now you will not able to escape explaining 6105 * me how you were going to use this. :-) 6106 */ 6107 ret = NET_RX_DROP; 6108 } 6109 6110 out: 6111 /* The invariant here is that if *ppt_prev is not NULL 6112 * then skb should also be non-NULL. 6113 * 6114 * Apparently *ppt_prev assignment above holds this invariant due to 6115 * skb dereferencing near it. 6116 */ 6117 *pskb = skb; 6118 return ret; 6119 } 6120 6121 static int __netif_receive_skb_one_core(struct sk_buff *skb, bool pfmemalloc) 6122 { 6123 struct net_device *orig_dev = skb->dev; 6124 struct packet_type *pt_prev = NULL; 6125 int ret; 6126 6127 ret = __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev); 6128 if (pt_prev) 6129 ret = INDIRECT_CALL_INET(pt_prev->func, ipv6_rcv, ip_rcv, skb, 6130 skb->dev, pt_prev, orig_dev); 6131 return ret; 6132 } 6133 6134 /** 6135 * netif_receive_skb_core - special purpose version of netif_receive_skb 6136 * @skb: buffer to process 6137 * 6138 * More direct receive version of netif_receive_skb(). It should 6139 * only be used by callers that have a need to skip RPS and Generic XDP. 6140 * Caller must also take care of handling if ``(page_is_)pfmemalloc``. 6141 * 6142 * This function may only be called from softirq context and interrupts 6143 * should be enabled. 6144 * 6145 * Return values (usually ignored): 6146 * NET_RX_SUCCESS: no congestion 6147 * NET_RX_DROP: packet was dropped 6148 */ 6149 int netif_receive_skb_core(struct sk_buff *skb) 6150 { 6151 int ret; 6152 6153 rcu_read_lock(); 6154 ret = __netif_receive_skb_one_core(skb, false); 6155 rcu_read_unlock(); 6156 6157 return ret; 6158 } 6159 EXPORT_SYMBOL(netif_receive_skb_core); 6160 6161 static inline void __netif_receive_skb_list_ptype(struct list_head *head, 6162 struct packet_type *pt_prev, 6163 struct net_device *orig_dev) 6164 { 6165 struct sk_buff *skb, *next; 6166 6167 if (!pt_prev) 6168 return; 6169 if (list_empty(head)) 6170 return; 6171 if (pt_prev->list_func != NULL) 6172 INDIRECT_CALL_INET(pt_prev->list_func, ipv6_list_rcv, 6173 ip_list_rcv, head, pt_prev, orig_dev); 6174 else 6175 list_for_each_entry_safe(skb, next, head, list) { 6176 skb_list_del_init(skb); 6177 pt_prev->func(skb, skb->dev, pt_prev, orig_dev); 6178 } 6179 } 6180 6181 static void __netif_receive_skb_list_core(struct list_head *head, bool pfmemalloc) 6182 { 6183 /* Fast-path assumptions: 6184 * - There is no RX handler. 6185 * - Only one packet_type matches. 6186 * If either of these fails, we will end up doing some per-packet 6187 * processing in-line, then handling the 'last ptype' for the whole 6188 * sublist. This can't cause out-of-order delivery to any single ptype, 6189 * because the 'last ptype' must be constant across the sublist, and all 6190 * other ptypes are handled per-packet. 6191 */ 6192 /* Current (common) ptype of sublist */ 6193 struct packet_type *pt_curr = NULL; 6194 /* Current (common) orig_dev of sublist */ 6195 struct net_device *od_curr = NULL; 6196 struct sk_buff *skb, *next; 6197 LIST_HEAD(sublist); 6198 6199 list_for_each_entry_safe(skb, next, head, list) { 6200 struct net_device *orig_dev = skb->dev; 6201 struct packet_type *pt_prev = NULL; 6202 6203 skb_list_del_init(skb); 6204 __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev); 6205 if (!pt_prev) 6206 continue; 6207 if (pt_curr != pt_prev || od_curr != orig_dev) { 6208 /* dispatch old sublist */ 6209 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr); 6210 /* start new sublist */ 6211 INIT_LIST_HEAD(&sublist); 6212 pt_curr = pt_prev; 6213 od_curr = orig_dev; 6214 } 6215 list_add_tail(&skb->list, &sublist); 6216 } 6217 6218 /* dispatch final sublist */ 6219 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr); 6220 } 6221 6222 static int __netif_receive_skb(struct sk_buff *skb) 6223 { 6224 int ret; 6225 6226 if (sk_memalloc_socks() && skb_pfmemalloc(skb)) { 6227 unsigned int noreclaim_flag; 6228 6229 /* 6230 * PFMEMALLOC skbs are special, they should 6231 * - be delivered to SOCK_MEMALLOC sockets only 6232 * - stay away from userspace 6233 * - have bounded memory usage 6234 * 6235 * Use PF_MEMALLOC as this saves us from propagating the allocation 6236 * context down to all allocation sites. 6237 */ 6238 noreclaim_flag = memalloc_noreclaim_save(); 6239 ret = __netif_receive_skb_one_core(skb, true); 6240 memalloc_noreclaim_restore(noreclaim_flag); 6241 } else 6242 ret = __netif_receive_skb_one_core(skb, false); 6243 6244 return ret; 6245 } 6246 6247 static void __netif_receive_skb_list(struct list_head *head) 6248 { 6249 unsigned long noreclaim_flag = 0; 6250 struct sk_buff *skb, *next; 6251 bool pfmemalloc = false; /* Is current sublist PF_MEMALLOC? */ 6252 6253 list_for_each_entry_safe(skb, next, head, list) { 6254 if ((sk_memalloc_socks() && skb_pfmemalloc(skb)) != pfmemalloc) { 6255 struct list_head sublist; 6256 6257 /* Handle the previous sublist */ 6258 list_cut_before(&sublist, head, &skb->list); 6259 if (!list_empty(&sublist)) 6260 __netif_receive_skb_list_core(&sublist, pfmemalloc); 6261 pfmemalloc = !pfmemalloc; 6262 /* See comments in __netif_receive_skb */ 6263 if (pfmemalloc) 6264 noreclaim_flag = memalloc_noreclaim_save(); 6265 else 6266 memalloc_noreclaim_restore(noreclaim_flag); 6267 } 6268 } 6269 /* Handle the remaining sublist */ 6270 if (!list_empty(head)) 6271 __netif_receive_skb_list_core(head, pfmemalloc); 6272 /* Restore pflags */ 6273 if (pfmemalloc) 6274 memalloc_noreclaim_restore(noreclaim_flag); 6275 } 6276 6277 static int generic_xdp_install(struct net_device *dev, struct netdev_bpf *xdp) 6278 { 6279 struct bpf_prog *old = rtnl_dereference(dev->xdp_prog); 6280 struct bpf_prog *new = xdp->prog; 6281 int ret = 0; 6282 6283 switch (xdp->command) { 6284 case XDP_SETUP_PROG: 6285 rcu_assign_pointer(dev->xdp_prog, new); 6286 if (old) 6287 bpf_prog_put(old); 6288 6289 if (old && !new) { 6290 static_branch_dec(&generic_xdp_needed_key); 6291 } else if (new && !old) { 6292 static_branch_inc(&generic_xdp_needed_key); 6293 netif_disable_lro(dev); 6294 dev_disable_gro_hw(dev); 6295 } 6296 break; 6297 6298 default: 6299 ret = -EINVAL; 6300 break; 6301 } 6302 6303 return ret; 6304 } 6305 6306 static int netif_receive_skb_internal(struct sk_buff *skb) 6307 { 6308 int ret; 6309 6310 net_timestamp_check(READ_ONCE(net_hotdata.tstamp_prequeue), skb); 6311 6312 if (skb_defer_rx_timestamp(skb)) 6313 return NET_RX_SUCCESS; 6314 6315 rcu_read_lock(); 6316 #ifdef CONFIG_RPS 6317 if (static_branch_unlikely(&rps_needed)) { 6318 struct rps_dev_flow voidflow, *rflow = &voidflow; 6319 int cpu = get_rps_cpu(skb->dev, skb, &rflow); 6320 6321 if (cpu >= 0) { 6322 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail); 6323 rcu_read_unlock(); 6324 return ret; 6325 } 6326 } 6327 #endif 6328 ret = __netif_receive_skb(skb); 6329 rcu_read_unlock(); 6330 return ret; 6331 } 6332 6333 void netif_receive_skb_list_internal(struct list_head *head) 6334 { 6335 struct sk_buff *skb, *next; 6336 LIST_HEAD(sublist); 6337 6338 list_for_each_entry_safe(skb, next, head, list) { 6339 net_timestamp_check(READ_ONCE(net_hotdata.tstamp_prequeue), 6340 skb); 6341 skb_list_del_init(skb); 6342 if (!skb_defer_rx_timestamp(skb)) 6343 list_add_tail(&skb->list, &sublist); 6344 } 6345 list_splice_init(&sublist, head); 6346 6347 rcu_read_lock(); 6348 #ifdef CONFIG_RPS 6349 if (static_branch_unlikely(&rps_needed)) { 6350 list_for_each_entry_safe(skb, next, head, list) { 6351 struct rps_dev_flow voidflow, *rflow = &voidflow; 6352 int cpu = get_rps_cpu(skb->dev, skb, &rflow); 6353 6354 if (cpu >= 0) { 6355 /* Will be handled, remove from list */ 6356 skb_list_del_init(skb); 6357 enqueue_to_backlog(skb, cpu, &rflow->last_qtail); 6358 } 6359 } 6360 } 6361 #endif 6362 __netif_receive_skb_list(head); 6363 rcu_read_unlock(); 6364 } 6365 6366 /** 6367 * netif_receive_skb - process receive buffer from network 6368 * @skb: buffer to process 6369 * 6370 * netif_receive_skb() is the main receive data processing function. 6371 * It always succeeds. The buffer may be dropped during processing 6372 * for congestion control or by the protocol layers. 6373 * 6374 * This function may only be called from softirq context and interrupts 6375 * should be enabled. 6376 * 6377 * Return values (usually ignored): 6378 * NET_RX_SUCCESS: no congestion 6379 * NET_RX_DROP: packet was dropped 6380 */ 6381 int netif_receive_skb(struct sk_buff *skb) 6382 { 6383 int ret; 6384 6385 trace_netif_receive_skb_entry(skb); 6386 6387 ret = netif_receive_skb_internal(skb); 6388 trace_netif_receive_skb_exit(ret); 6389 6390 return ret; 6391 } 6392 EXPORT_SYMBOL(netif_receive_skb); 6393 6394 /** 6395 * netif_receive_skb_list - process many receive buffers from network 6396 * @head: list of skbs to process. 6397 * 6398 * Since return value of netif_receive_skb() is normally ignored, and 6399 * wouldn't be meaningful for a list, this function returns void. 6400 * 6401 * This function may only be called from softirq context and interrupts 6402 * should be enabled. 6403 */ 6404 void netif_receive_skb_list(struct list_head *head) 6405 { 6406 struct sk_buff *skb; 6407 6408 if (list_empty(head)) 6409 return; 6410 if (trace_netif_receive_skb_list_entry_enabled()) { 6411 list_for_each_entry(skb, head, list) 6412 trace_netif_receive_skb_list_entry(skb); 6413 } 6414 netif_receive_skb_list_internal(head); 6415 trace_netif_receive_skb_list_exit(0); 6416 } 6417 EXPORT_SYMBOL(netif_receive_skb_list); 6418 6419 /* Network device is going away, flush any packets still pending */ 6420 static void flush_backlog(struct work_struct *work) 6421 { 6422 struct sk_buff *skb, *tmp; 6423 struct sk_buff_head list; 6424 struct softnet_data *sd; 6425 6426 __skb_queue_head_init(&list); 6427 local_bh_disable(); 6428 sd = this_cpu_ptr(&softnet_data); 6429 6430 backlog_lock_irq_disable(sd); 6431 skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) { 6432 if (READ_ONCE(skb->dev->reg_state) == NETREG_UNREGISTERING) { 6433 __skb_unlink(skb, &sd->input_pkt_queue); 6434 __skb_queue_tail(&list, skb); 6435 rps_input_queue_head_incr(sd); 6436 } 6437 } 6438 backlog_unlock_irq_enable(sd); 6439 6440 local_lock_nested_bh(&softnet_data.process_queue_bh_lock); 6441 skb_queue_walk_safe(&sd->process_queue, skb, tmp) { 6442 if (READ_ONCE(skb->dev->reg_state) == NETREG_UNREGISTERING) { 6443 __skb_unlink(skb, &sd->process_queue); 6444 __skb_queue_tail(&list, skb); 6445 rps_input_queue_head_incr(sd); 6446 } 6447 } 6448 local_unlock_nested_bh(&softnet_data.process_queue_bh_lock); 6449 local_bh_enable(); 6450 6451 __skb_queue_purge_reason(&list, SKB_DROP_REASON_DEV_READY); 6452 } 6453 6454 static bool flush_required(int cpu) 6455 { 6456 #if IS_ENABLED(CONFIG_RPS) 6457 struct softnet_data *sd = &per_cpu(softnet_data, cpu); 6458 bool do_flush; 6459 6460 backlog_lock_irq_disable(sd); 6461 6462 /* as insertion into process_queue happens with the rps lock held, 6463 * process_queue access may race only with dequeue 6464 */ 6465 do_flush = !skb_queue_empty(&sd->input_pkt_queue) || 6466 !skb_queue_empty_lockless(&sd->process_queue); 6467 backlog_unlock_irq_enable(sd); 6468 6469 return do_flush; 6470 #endif 6471 /* without RPS we can't safely check input_pkt_queue: during a 6472 * concurrent remote skb_queue_splice() we can detect as empty both 6473 * input_pkt_queue and process_queue even if the latter could end-up 6474 * containing a lot of packets. 6475 */ 6476 return true; 6477 } 6478 6479 struct flush_backlogs { 6480 cpumask_t flush_cpus; 6481 struct work_struct w[]; 6482 }; 6483 6484 static struct flush_backlogs *flush_backlogs_alloc(void) 6485 { 6486 return kmalloc(struct_size_t(struct flush_backlogs, w, nr_cpu_ids), 6487 GFP_KERNEL); 6488 } 6489 6490 static struct flush_backlogs *flush_backlogs_fallback; 6491 static DEFINE_MUTEX(flush_backlogs_mutex); 6492 6493 static void flush_all_backlogs(void) 6494 { 6495 struct flush_backlogs *ptr = flush_backlogs_alloc(); 6496 unsigned int cpu; 6497 6498 if (!ptr) { 6499 mutex_lock(&flush_backlogs_mutex); 6500 ptr = flush_backlogs_fallback; 6501 } 6502 cpumask_clear(&ptr->flush_cpus); 6503 6504 cpus_read_lock(); 6505 6506 for_each_online_cpu(cpu) { 6507 if (flush_required(cpu)) { 6508 INIT_WORK(&ptr->w[cpu], flush_backlog); 6509 queue_work_on(cpu, system_highpri_wq, &ptr->w[cpu]); 6510 __cpumask_set_cpu(cpu, &ptr->flush_cpus); 6511 } 6512 } 6513 6514 /* we can have in flight packet[s] on the cpus we are not flushing, 6515 * synchronize_net() in unregister_netdevice_many() will take care of 6516 * them. 6517 */ 6518 for_each_cpu(cpu, &ptr->flush_cpus) 6519 flush_work(&ptr->w[cpu]); 6520 6521 cpus_read_unlock(); 6522 6523 if (ptr != flush_backlogs_fallback) 6524 kfree(ptr); 6525 else 6526 mutex_unlock(&flush_backlogs_mutex); 6527 } 6528 6529 static void net_rps_send_ipi(struct softnet_data *remsd) 6530 { 6531 #ifdef CONFIG_RPS 6532 while (remsd) { 6533 struct softnet_data *next = remsd->rps_ipi_next; 6534 6535 if (cpu_online(remsd->cpu)) 6536 smp_call_function_single_async(remsd->cpu, &remsd->csd); 6537 remsd = next; 6538 } 6539 #endif 6540 } 6541 6542 /* 6543 * net_rps_action_and_irq_enable sends any pending IPI's for rps. 6544 * Note: called with local irq disabled, but exits with local irq enabled. 6545 */ 6546 static void net_rps_action_and_irq_enable(struct softnet_data *sd) 6547 { 6548 #ifdef CONFIG_RPS 6549 struct softnet_data *remsd = sd->rps_ipi_list; 6550 6551 if (!use_backlog_threads() && remsd) { 6552 sd->rps_ipi_list = NULL; 6553 6554 local_irq_enable(); 6555 6556 /* Send pending IPI's to kick RPS processing on remote cpus. */ 6557 net_rps_send_ipi(remsd); 6558 } else 6559 #endif 6560 local_irq_enable(); 6561 } 6562 6563 static bool sd_has_rps_ipi_waiting(struct softnet_data *sd) 6564 { 6565 #ifdef CONFIG_RPS 6566 return !use_backlog_threads() && sd->rps_ipi_list; 6567 #else 6568 return false; 6569 #endif 6570 } 6571 6572 static int process_backlog(struct napi_struct *napi, int quota) 6573 { 6574 struct softnet_data *sd = container_of(napi, struct softnet_data, backlog); 6575 bool again = true; 6576 int work = 0; 6577 6578 /* Check if we have pending ipi, its better to send them now, 6579 * not waiting net_rx_action() end. 6580 */ 6581 if (sd_has_rps_ipi_waiting(sd)) { 6582 local_irq_disable(); 6583 net_rps_action_and_irq_enable(sd); 6584 } 6585 6586 napi->weight = READ_ONCE(net_hotdata.dev_rx_weight); 6587 while (again) { 6588 struct sk_buff *skb; 6589 6590 local_lock_nested_bh(&softnet_data.process_queue_bh_lock); 6591 while ((skb = __skb_dequeue(&sd->process_queue))) { 6592 local_unlock_nested_bh(&softnet_data.process_queue_bh_lock); 6593 rcu_read_lock(); 6594 __netif_receive_skb(skb); 6595 rcu_read_unlock(); 6596 if (++work >= quota) { 6597 rps_input_queue_head_add(sd, work); 6598 return work; 6599 } 6600 6601 local_lock_nested_bh(&softnet_data.process_queue_bh_lock); 6602 } 6603 local_unlock_nested_bh(&softnet_data.process_queue_bh_lock); 6604 6605 backlog_lock_irq_disable(sd); 6606 if (skb_queue_empty(&sd->input_pkt_queue)) { 6607 /* 6608 * Inline a custom version of __napi_complete(). 6609 * only current cpu owns and manipulates this napi, 6610 * and NAPI_STATE_SCHED is the only possible flag set 6611 * on backlog. 6612 * We can use a plain write instead of clear_bit(), 6613 * and we dont need an smp_mb() memory barrier. 6614 */ 6615 napi->state &= NAPIF_STATE_THREADED; 6616 again = false; 6617 } else { 6618 local_lock_nested_bh(&softnet_data.process_queue_bh_lock); 6619 skb_queue_splice_tail_init(&sd->input_pkt_queue, 6620 &sd->process_queue); 6621 local_unlock_nested_bh(&softnet_data.process_queue_bh_lock); 6622 } 6623 backlog_unlock_irq_enable(sd); 6624 } 6625 6626 if (work) 6627 rps_input_queue_head_add(sd, work); 6628 return work; 6629 } 6630 6631 /** 6632 * __napi_schedule - schedule for receive 6633 * @n: entry to schedule 6634 * 6635 * The entry's receive function will be scheduled to run. 6636 * Consider using __napi_schedule_irqoff() if hard irqs are masked. 6637 */ 6638 void __napi_schedule(struct napi_struct *n) 6639 { 6640 unsigned long flags; 6641 6642 local_irq_save(flags); 6643 ____napi_schedule(this_cpu_ptr(&softnet_data), n); 6644 local_irq_restore(flags); 6645 } 6646 EXPORT_SYMBOL(__napi_schedule); 6647 6648 /** 6649 * napi_schedule_prep - check if napi can be scheduled 6650 * @n: napi context 6651 * 6652 * Test if NAPI routine is already running, and if not mark 6653 * it as running. This is used as a condition variable to 6654 * insure only one NAPI poll instance runs. We also make 6655 * sure there is no pending NAPI disable. 6656 */ 6657 bool napi_schedule_prep(struct napi_struct *n) 6658 { 6659 unsigned long new, val = READ_ONCE(n->state); 6660 6661 do { 6662 if (unlikely(val & NAPIF_STATE_DISABLE)) 6663 return false; 6664 new = val | NAPIF_STATE_SCHED; 6665 6666 /* Sets STATE_MISSED bit if STATE_SCHED was already set 6667 * This was suggested by Alexander Duyck, as compiler 6668 * emits better code than : 6669 * if (val & NAPIF_STATE_SCHED) 6670 * new |= NAPIF_STATE_MISSED; 6671 */ 6672 new |= (val & NAPIF_STATE_SCHED) / NAPIF_STATE_SCHED * 6673 NAPIF_STATE_MISSED; 6674 } while (!try_cmpxchg(&n->state, &val, new)); 6675 6676 return !(val & NAPIF_STATE_SCHED); 6677 } 6678 EXPORT_SYMBOL(napi_schedule_prep); 6679 6680 /** 6681 * __napi_schedule_irqoff - schedule for receive 6682 * @n: entry to schedule 6683 * 6684 * Variant of __napi_schedule() assuming hard irqs are masked. 6685 * 6686 * On PREEMPT_RT enabled kernels this maps to __napi_schedule() 6687 * because the interrupt disabled assumption might not be true 6688 * due to force-threaded interrupts and spinlock substitution. 6689 */ 6690 void __napi_schedule_irqoff(struct napi_struct *n) 6691 { 6692 if (!IS_ENABLED(CONFIG_PREEMPT_RT)) 6693 ____napi_schedule(this_cpu_ptr(&softnet_data), n); 6694 else 6695 __napi_schedule(n); 6696 } 6697 EXPORT_SYMBOL(__napi_schedule_irqoff); 6698 6699 bool napi_complete_done(struct napi_struct *n, int work_done) 6700 { 6701 unsigned long flags, val, new, timeout = 0; 6702 bool ret = true; 6703 6704 /* 6705 * 1) Don't let napi dequeue from the cpu poll list 6706 * just in case its running on a different cpu. 6707 * 2) If we are busy polling, do nothing here, we have 6708 * the guarantee we will be called later. 6709 */ 6710 if (unlikely(n->state & (NAPIF_STATE_NPSVC | 6711 NAPIF_STATE_IN_BUSY_POLL))) 6712 return false; 6713 6714 if (work_done) { 6715 if (n->gro.bitmask) 6716 timeout = napi_get_gro_flush_timeout(n); 6717 n->defer_hard_irqs_count = napi_get_defer_hard_irqs(n); 6718 } 6719 if (n->defer_hard_irqs_count > 0) { 6720 n->defer_hard_irqs_count--; 6721 timeout = napi_get_gro_flush_timeout(n); 6722 if (timeout) 6723 ret = false; 6724 } 6725 6726 /* 6727 * When the NAPI instance uses a timeout and keeps postponing 6728 * it, we need to bound somehow the time packets are kept in 6729 * the GRO layer. 6730 */ 6731 gro_flush_normal(&n->gro, !!timeout); 6732 6733 if (unlikely(!list_empty(&n->poll_list))) { 6734 /* If n->poll_list is not empty, we need to mask irqs */ 6735 local_irq_save(flags); 6736 list_del_init(&n->poll_list); 6737 local_irq_restore(flags); 6738 } 6739 WRITE_ONCE(n->list_owner, -1); 6740 6741 val = READ_ONCE(n->state); 6742 do { 6743 WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED)); 6744 6745 new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED | 6746 NAPIF_STATE_SCHED_THREADED | 6747 NAPIF_STATE_PREFER_BUSY_POLL); 6748 6749 /* If STATE_MISSED was set, leave STATE_SCHED set, 6750 * because we will call napi->poll() one more time. 6751 * This C code was suggested by Alexander Duyck to help gcc. 6752 */ 6753 new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED * 6754 NAPIF_STATE_SCHED; 6755 } while (!try_cmpxchg(&n->state, &val, new)); 6756 6757 if (unlikely(val & NAPIF_STATE_MISSED)) { 6758 __napi_schedule(n); 6759 return false; 6760 } 6761 6762 if (timeout) 6763 hrtimer_start(&n->timer, ns_to_ktime(timeout), 6764 HRTIMER_MODE_REL_PINNED); 6765 return ret; 6766 } 6767 EXPORT_SYMBOL(napi_complete_done); 6768 6769 static void skb_defer_free_flush(void) 6770 { 6771 struct llist_node *free_list; 6772 struct sk_buff *skb, *next; 6773 struct skb_defer_node *sdn; 6774 int node; 6775 6776 for_each_node(node) { 6777 sdn = this_cpu_ptr(net_hotdata.skb_defer_nodes) + node; 6778 6779 if (llist_empty(&sdn->defer_list)) 6780 continue; 6781 atomic_long_set(&sdn->defer_count, 0); 6782 free_list = llist_del_all(&sdn->defer_list); 6783 6784 llist_for_each_entry_safe(skb, next, free_list, ll_node) { 6785 prefetch(next); 6786 napi_consume_skb(skb, 1); 6787 } 6788 } 6789 } 6790 6791 #if defined(CONFIG_NET_RX_BUSY_POLL) 6792 6793 static void __busy_poll_stop(struct napi_struct *napi, bool skip_schedule) 6794 { 6795 if (!skip_schedule) { 6796 gro_normal_list(&napi->gro); 6797 __napi_schedule(napi); 6798 return; 6799 } 6800 6801 /* Flush too old packets. If HZ < 1000, flush all packets */ 6802 gro_flush_normal(&napi->gro, HZ >= 1000); 6803 6804 clear_bit(NAPI_STATE_SCHED, &napi->state); 6805 } 6806 6807 enum { 6808 NAPI_F_PREFER_BUSY_POLL = 1, 6809 NAPI_F_END_ON_RESCHED = 2, 6810 }; 6811 6812 static void busy_poll_stop(struct napi_struct *napi, void *have_poll_lock, 6813 unsigned flags, u16 budget) 6814 { 6815 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx; 6816 bool skip_schedule = false; 6817 unsigned long timeout; 6818 int rc; 6819 6820 /* Busy polling means there is a high chance device driver hard irq 6821 * could not grab NAPI_STATE_SCHED, and that NAPI_STATE_MISSED was 6822 * set in napi_schedule_prep(). 6823 * Since we are about to call napi->poll() once more, we can safely 6824 * clear NAPI_STATE_MISSED. 6825 * 6826 * Note: x86 could use a single "lock and ..." instruction 6827 * to perform these two clear_bit() 6828 */ 6829 clear_bit(NAPI_STATE_MISSED, &napi->state); 6830 clear_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state); 6831 6832 local_bh_disable(); 6833 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx); 6834 6835 if (flags & NAPI_F_PREFER_BUSY_POLL) { 6836 napi->defer_hard_irqs_count = napi_get_defer_hard_irqs(napi); 6837 timeout = napi_get_gro_flush_timeout(napi); 6838 if (napi->defer_hard_irqs_count && timeout) { 6839 hrtimer_start(&napi->timer, ns_to_ktime(timeout), HRTIMER_MODE_REL_PINNED); 6840 skip_schedule = true; 6841 } 6842 } 6843 6844 /* All we really want here is to re-enable device interrupts. 6845 * Ideally, a new ndo_busy_poll_stop() could avoid another round. 6846 */ 6847 rc = napi->poll(napi, budget); 6848 /* We can't gro_normal_list() here, because napi->poll() might have 6849 * rearmed the napi (napi_complete_done()) in which case it could 6850 * already be running on another CPU. 6851 */ 6852 trace_napi_poll(napi, rc, budget); 6853 netpoll_poll_unlock(have_poll_lock); 6854 if (rc == budget) 6855 __busy_poll_stop(napi, skip_schedule); 6856 bpf_net_ctx_clear(bpf_net_ctx); 6857 local_bh_enable(); 6858 } 6859 6860 static void __napi_busy_loop(unsigned int napi_id, 6861 bool (*loop_end)(void *, unsigned long), 6862 void *loop_end_arg, unsigned flags, u16 budget) 6863 { 6864 unsigned long start_time = loop_end ? busy_loop_current_time() : 0; 6865 int (*napi_poll)(struct napi_struct *napi, int budget); 6866 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx; 6867 void *have_poll_lock = NULL; 6868 struct napi_struct *napi; 6869 6870 WARN_ON_ONCE(!rcu_read_lock_held()); 6871 6872 restart: 6873 napi_poll = NULL; 6874 6875 napi = napi_by_id(napi_id); 6876 if (!napi) 6877 return; 6878 6879 if (!IS_ENABLED(CONFIG_PREEMPT_RT)) 6880 preempt_disable(); 6881 for (;;) { 6882 int work = 0; 6883 6884 local_bh_disable(); 6885 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx); 6886 if (!napi_poll) { 6887 unsigned long val = READ_ONCE(napi->state); 6888 6889 /* If multiple threads are competing for this napi, 6890 * we avoid dirtying napi->state as much as we can. 6891 */ 6892 if (val & (NAPIF_STATE_DISABLE | NAPIF_STATE_SCHED | 6893 NAPIF_STATE_IN_BUSY_POLL)) { 6894 if (flags & NAPI_F_PREFER_BUSY_POLL) 6895 set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state); 6896 goto count; 6897 } 6898 if (cmpxchg(&napi->state, val, 6899 val | NAPIF_STATE_IN_BUSY_POLL | 6900 NAPIF_STATE_SCHED) != val) { 6901 if (flags & NAPI_F_PREFER_BUSY_POLL) 6902 set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state); 6903 goto count; 6904 } 6905 have_poll_lock = netpoll_poll_lock(napi); 6906 napi_poll = napi->poll; 6907 } 6908 work = napi_poll(napi, budget); 6909 trace_napi_poll(napi, work, budget); 6910 gro_normal_list(&napi->gro); 6911 count: 6912 if (work > 0) 6913 __NET_ADD_STATS(dev_net(napi->dev), 6914 LINUX_MIB_BUSYPOLLRXPACKETS, work); 6915 skb_defer_free_flush(); 6916 bpf_net_ctx_clear(bpf_net_ctx); 6917 local_bh_enable(); 6918 6919 if (!loop_end || loop_end(loop_end_arg, start_time)) 6920 break; 6921 6922 if (unlikely(need_resched())) { 6923 if (flags & NAPI_F_END_ON_RESCHED) 6924 break; 6925 if (napi_poll) 6926 busy_poll_stop(napi, have_poll_lock, flags, budget); 6927 if (!IS_ENABLED(CONFIG_PREEMPT_RT)) 6928 preempt_enable(); 6929 rcu_read_unlock(); 6930 cond_resched(); 6931 rcu_read_lock(); 6932 if (loop_end(loop_end_arg, start_time)) 6933 return; 6934 goto restart; 6935 } 6936 cpu_relax(); 6937 } 6938 if (napi_poll) 6939 busy_poll_stop(napi, have_poll_lock, flags, budget); 6940 if (!IS_ENABLED(CONFIG_PREEMPT_RT)) 6941 preempt_enable(); 6942 } 6943 6944 void napi_busy_loop_rcu(unsigned int napi_id, 6945 bool (*loop_end)(void *, unsigned long), 6946 void *loop_end_arg, bool prefer_busy_poll, u16 budget) 6947 { 6948 unsigned flags = NAPI_F_END_ON_RESCHED; 6949 6950 if (prefer_busy_poll) 6951 flags |= NAPI_F_PREFER_BUSY_POLL; 6952 6953 __napi_busy_loop(napi_id, loop_end, loop_end_arg, flags, budget); 6954 } 6955 6956 void napi_busy_loop(unsigned int napi_id, 6957 bool (*loop_end)(void *, unsigned long), 6958 void *loop_end_arg, bool prefer_busy_poll, u16 budget) 6959 { 6960 unsigned flags = prefer_busy_poll ? NAPI_F_PREFER_BUSY_POLL : 0; 6961 6962 rcu_read_lock(); 6963 __napi_busy_loop(napi_id, loop_end, loop_end_arg, flags, budget); 6964 rcu_read_unlock(); 6965 } 6966 EXPORT_SYMBOL(napi_busy_loop); 6967 6968 void napi_suspend_irqs(unsigned int napi_id) 6969 { 6970 struct napi_struct *napi; 6971 6972 rcu_read_lock(); 6973 napi = napi_by_id(napi_id); 6974 if (napi) { 6975 unsigned long timeout = napi_get_irq_suspend_timeout(napi); 6976 6977 if (timeout) 6978 hrtimer_start(&napi->timer, ns_to_ktime(timeout), 6979 HRTIMER_MODE_REL_PINNED); 6980 } 6981 rcu_read_unlock(); 6982 } 6983 6984 void napi_resume_irqs(unsigned int napi_id) 6985 { 6986 struct napi_struct *napi; 6987 6988 rcu_read_lock(); 6989 napi = napi_by_id(napi_id); 6990 if (napi) { 6991 /* If irq_suspend_timeout is set to 0 between the call to 6992 * napi_suspend_irqs and now, the original value still 6993 * determines the safety timeout as intended and napi_watchdog 6994 * will resume irq processing. 6995 */ 6996 if (napi_get_irq_suspend_timeout(napi)) { 6997 local_bh_disable(); 6998 napi_schedule(napi); 6999 local_bh_enable(); 7000 } 7001 } 7002 rcu_read_unlock(); 7003 } 7004 7005 #endif /* CONFIG_NET_RX_BUSY_POLL */ 7006 7007 static void __napi_hash_add_with_id(struct napi_struct *napi, 7008 unsigned int napi_id) 7009 { 7010 napi->gro.cached_napi_id = napi_id; 7011 7012 WRITE_ONCE(napi->napi_id, napi_id); 7013 hlist_add_head_rcu(&napi->napi_hash_node, 7014 &napi_hash[napi->napi_id % HASH_SIZE(napi_hash)]); 7015 } 7016 7017 static void napi_hash_add_with_id(struct napi_struct *napi, 7018 unsigned int napi_id) 7019 { 7020 unsigned long flags; 7021 7022 spin_lock_irqsave(&napi_hash_lock, flags); 7023 WARN_ON_ONCE(napi_by_id(napi_id)); 7024 __napi_hash_add_with_id(napi, napi_id); 7025 spin_unlock_irqrestore(&napi_hash_lock, flags); 7026 } 7027 7028 static void napi_hash_add(struct napi_struct *napi) 7029 { 7030 unsigned long flags; 7031 7032 if (test_bit(NAPI_STATE_NO_BUSY_POLL, &napi->state)) 7033 return; 7034 7035 spin_lock_irqsave(&napi_hash_lock, flags); 7036 7037 /* 0..NR_CPUS range is reserved for sender_cpu use */ 7038 do { 7039 if (unlikely(!napi_id_valid(++napi_gen_id))) 7040 napi_gen_id = MIN_NAPI_ID; 7041 } while (napi_by_id(napi_gen_id)); 7042 7043 __napi_hash_add_with_id(napi, napi_gen_id); 7044 7045 spin_unlock_irqrestore(&napi_hash_lock, flags); 7046 } 7047 7048 /* Warning : caller is responsible to make sure rcu grace period 7049 * is respected before freeing memory containing @napi 7050 */ 7051 static void napi_hash_del(struct napi_struct *napi) 7052 { 7053 unsigned long flags; 7054 7055 spin_lock_irqsave(&napi_hash_lock, flags); 7056 7057 hlist_del_init_rcu(&napi->napi_hash_node); 7058 7059 spin_unlock_irqrestore(&napi_hash_lock, flags); 7060 } 7061 7062 static enum hrtimer_restart napi_watchdog(struct hrtimer *timer) 7063 { 7064 struct napi_struct *napi; 7065 7066 napi = container_of(timer, struct napi_struct, timer); 7067 7068 /* Note : we use a relaxed variant of napi_schedule_prep() not setting 7069 * NAPI_STATE_MISSED, since we do not react to a device IRQ. 7070 */ 7071 if (!napi_disable_pending(napi) && 7072 !test_and_set_bit(NAPI_STATE_SCHED, &napi->state)) { 7073 clear_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state); 7074 __napi_schedule_irqoff(napi); 7075 } 7076 7077 return HRTIMER_NORESTART; 7078 } 7079 7080 static void napi_stop_kthread(struct napi_struct *napi) 7081 { 7082 unsigned long val, new; 7083 7084 /* Wait until the napi STATE_THREADED is unset. */ 7085 while (true) { 7086 val = READ_ONCE(napi->state); 7087 7088 /* If napi kthread own this napi or the napi is idle, 7089 * STATE_THREADED can be unset here. 7090 */ 7091 if ((val & NAPIF_STATE_SCHED_THREADED) || 7092 !(val & NAPIF_STATE_SCHED)) { 7093 new = val & (~(NAPIF_STATE_THREADED | 7094 NAPIF_STATE_THREADED_BUSY_POLL)); 7095 } else { 7096 msleep(20); 7097 continue; 7098 } 7099 7100 if (try_cmpxchg(&napi->state, &val, new)) 7101 break; 7102 } 7103 7104 /* Once STATE_THREADED is unset, wait for SCHED_THREADED to be unset by 7105 * the kthread. 7106 */ 7107 while (true) { 7108 if (!test_bit(NAPI_STATE_SCHED_THREADED, &napi->state)) 7109 break; 7110 7111 msleep(20); 7112 } 7113 7114 kthread_stop(napi->thread); 7115 napi->thread = NULL; 7116 } 7117 7118 static void napi_set_threaded_state(struct napi_struct *napi, 7119 enum netdev_napi_threaded threaded_mode) 7120 { 7121 bool threaded = threaded_mode != NETDEV_NAPI_THREADED_DISABLED; 7122 bool busy_poll = threaded_mode == NETDEV_NAPI_THREADED_BUSY_POLL; 7123 7124 assign_bit(NAPI_STATE_THREADED, &napi->state, threaded); 7125 assign_bit(NAPI_STATE_THREADED_BUSY_POLL, &napi->state, busy_poll); 7126 } 7127 7128 int napi_set_threaded(struct napi_struct *napi, 7129 enum netdev_napi_threaded threaded) 7130 { 7131 if (threaded) { 7132 if (!napi->thread) { 7133 int err = napi_kthread_create(napi); 7134 7135 if (err) 7136 return err; 7137 } 7138 } 7139 7140 if (napi->config) 7141 napi->config->threaded = threaded; 7142 7143 /* Setting/unsetting threaded mode on a napi might not immediately 7144 * take effect, if the current napi instance is actively being 7145 * polled. In this case, the switch between threaded mode and 7146 * softirq mode will happen in the next round of napi_schedule(). 7147 * This should not cause hiccups/stalls to the live traffic. 7148 */ 7149 if (!threaded && napi->thread) { 7150 napi_stop_kthread(napi); 7151 } else { 7152 /* Make sure kthread is created before THREADED bit is set. */ 7153 smp_mb__before_atomic(); 7154 napi_set_threaded_state(napi, threaded); 7155 } 7156 7157 return 0; 7158 } 7159 7160 int netif_set_threaded(struct net_device *dev, 7161 enum netdev_napi_threaded threaded) 7162 { 7163 struct napi_struct *napi; 7164 int i, err = 0; 7165 7166 netdev_assert_locked_or_invisible(dev); 7167 7168 if (threaded) { 7169 list_for_each_entry(napi, &dev->napi_list, dev_list) { 7170 if (!napi->thread) { 7171 err = napi_kthread_create(napi); 7172 if (err) { 7173 threaded = NETDEV_NAPI_THREADED_DISABLED; 7174 break; 7175 } 7176 } 7177 } 7178 } 7179 7180 WRITE_ONCE(dev->threaded, threaded); 7181 7182 /* The error should not occur as the kthreads are already created. */ 7183 list_for_each_entry(napi, &dev->napi_list, dev_list) 7184 WARN_ON_ONCE(napi_set_threaded(napi, threaded)); 7185 7186 /* Override the config for all NAPIs even if currently not listed */ 7187 for (i = 0; i < dev->num_napi_configs; i++) 7188 dev->napi_config[i].threaded = threaded; 7189 7190 return err; 7191 } 7192 7193 /** 7194 * netif_threaded_enable() - enable threaded NAPIs 7195 * @dev: net_device instance 7196 * 7197 * Enable threaded mode for the NAPI instances of the device. This may be useful 7198 * for devices where multiple NAPI instances get scheduled by a single 7199 * interrupt. Threaded NAPI allows moving the NAPI processing to cores other 7200 * than the core where IRQ is mapped. 7201 * 7202 * This function should be called before @dev is registered. 7203 */ 7204 void netif_threaded_enable(struct net_device *dev) 7205 { 7206 WARN_ON_ONCE(netif_set_threaded(dev, NETDEV_NAPI_THREADED_ENABLED)); 7207 } 7208 EXPORT_SYMBOL(netif_threaded_enable); 7209 7210 /** 7211 * netif_queue_set_napi - Associate queue with the napi 7212 * @dev: device to which NAPI and queue belong 7213 * @queue_index: Index of queue 7214 * @type: queue type as RX or TX 7215 * @napi: NAPI context, pass NULL to clear previously set NAPI 7216 * 7217 * Set queue with its corresponding napi context. This should be done after 7218 * registering the NAPI handler for the queue-vector and the queues have been 7219 * mapped to the corresponding interrupt vector. 7220 */ 7221 void netif_queue_set_napi(struct net_device *dev, unsigned int queue_index, 7222 enum netdev_queue_type type, struct napi_struct *napi) 7223 { 7224 struct netdev_rx_queue *rxq; 7225 struct netdev_queue *txq; 7226 7227 if (WARN_ON_ONCE(napi && !napi->dev)) 7228 return; 7229 netdev_ops_assert_locked_or_invisible(dev); 7230 7231 switch (type) { 7232 case NETDEV_QUEUE_TYPE_RX: 7233 rxq = __netif_get_rx_queue(dev, queue_index); 7234 rxq->napi = napi; 7235 return; 7236 case NETDEV_QUEUE_TYPE_TX: 7237 txq = netdev_get_tx_queue(dev, queue_index); 7238 txq->napi = napi; 7239 return; 7240 default: 7241 return; 7242 } 7243 } 7244 EXPORT_SYMBOL(netif_queue_set_napi); 7245 7246 static void 7247 netif_napi_irq_notify(struct irq_affinity_notify *notify, 7248 const cpumask_t *mask) 7249 { 7250 struct napi_struct *napi = 7251 container_of(notify, struct napi_struct, notify); 7252 #ifdef CONFIG_RFS_ACCEL 7253 struct cpu_rmap *rmap = napi->dev->rx_cpu_rmap; 7254 int err; 7255 #endif 7256 7257 if (napi->config && napi->dev->irq_affinity_auto) 7258 cpumask_copy(&napi->config->affinity_mask, mask); 7259 7260 #ifdef CONFIG_RFS_ACCEL 7261 if (napi->dev->rx_cpu_rmap_auto) { 7262 err = cpu_rmap_update(rmap, napi->napi_rmap_idx, mask); 7263 if (err) 7264 netdev_warn(napi->dev, "RMAP update failed (%d)\n", 7265 err); 7266 } 7267 #endif 7268 } 7269 7270 #ifdef CONFIG_RFS_ACCEL 7271 static void netif_napi_affinity_release(struct kref *ref) 7272 { 7273 struct napi_struct *napi = 7274 container_of(ref, struct napi_struct, notify.kref); 7275 struct cpu_rmap *rmap = napi->dev->rx_cpu_rmap; 7276 7277 netdev_assert_locked(napi->dev); 7278 WARN_ON(test_and_clear_bit(NAPI_STATE_HAS_NOTIFIER, 7279 &napi->state)); 7280 7281 if (!napi->dev->rx_cpu_rmap_auto) 7282 return; 7283 rmap->obj[napi->napi_rmap_idx] = NULL; 7284 napi->napi_rmap_idx = -1; 7285 cpu_rmap_put(rmap); 7286 } 7287 7288 int netif_enable_cpu_rmap(struct net_device *dev, unsigned int num_irqs) 7289 { 7290 if (dev->rx_cpu_rmap_auto) 7291 return 0; 7292 7293 dev->rx_cpu_rmap = alloc_irq_cpu_rmap(num_irqs); 7294 if (!dev->rx_cpu_rmap) 7295 return -ENOMEM; 7296 7297 dev->rx_cpu_rmap_auto = true; 7298 return 0; 7299 } 7300 EXPORT_SYMBOL(netif_enable_cpu_rmap); 7301 7302 static void netif_del_cpu_rmap(struct net_device *dev) 7303 { 7304 struct cpu_rmap *rmap = dev->rx_cpu_rmap; 7305 7306 if (!dev->rx_cpu_rmap_auto) 7307 return; 7308 7309 /* Free the rmap */ 7310 cpu_rmap_put(rmap); 7311 dev->rx_cpu_rmap = NULL; 7312 dev->rx_cpu_rmap_auto = false; 7313 } 7314 7315 #else 7316 static void netif_napi_affinity_release(struct kref *ref) 7317 { 7318 } 7319 7320 int netif_enable_cpu_rmap(struct net_device *dev, unsigned int num_irqs) 7321 { 7322 return 0; 7323 } 7324 EXPORT_SYMBOL(netif_enable_cpu_rmap); 7325 7326 static void netif_del_cpu_rmap(struct net_device *dev) 7327 { 7328 } 7329 #endif 7330 7331 void netif_set_affinity_auto(struct net_device *dev) 7332 { 7333 unsigned int i, maxqs, numa; 7334 7335 maxqs = max(dev->num_tx_queues, dev->num_rx_queues); 7336 numa = dev_to_node(&dev->dev); 7337 7338 for (i = 0; i < maxqs; i++) 7339 cpumask_set_cpu(cpumask_local_spread(i, numa), 7340 &dev->napi_config[i].affinity_mask); 7341 7342 dev->irq_affinity_auto = true; 7343 } 7344 EXPORT_SYMBOL(netif_set_affinity_auto); 7345 7346 void netif_napi_set_irq_locked(struct napi_struct *napi, int irq) 7347 { 7348 int rc; 7349 7350 netdev_assert_locked_or_invisible(napi->dev); 7351 7352 if (napi->irq == irq) 7353 return; 7354 7355 /* Remove existing resources */ 7356 if (test_and_clear_bit(NAPI_STATE_HAS_NOTIFIER, &napi->state)) 7357 irq_set_affinity_notifier(napi->irq, NULL); 7358 7359 napi->irq = irq; 7360 if (irq < 0 || 7361 (!napi->dev->rx_cpu_rmap_auto && !napi->dev->irq_affinity_auto)) 7362 return; 7363 7364 /* Abort for buggy drivers */ 7365 if (napi->dev->irq_affinity_auto && WARN_ON_ONCE(!napi->config)) 7366 return; 7367 7368 #ifdef CONFIG_RFS_ACCEL 7369 if (napi->dev->rx_cpu_rmap_auto) { 7370 rc = cpu_rmap_add(napi->dev->rx_cpu_rmap, napi); 7371 if (rc < 0) 7372 return; 7373 7374 cpu_rmap_get(napi->dev->rx_cpu_rmap); 7375 napi->napi_rmap_idx = rc; 7376 } 7377 #endif 7378 7379 /* Use core IRQ notifier */ 7380 napi->notify.notify = netif_napi_irq_notify; 7381 napi->notify.release = netif_napi_affinity_release; 7382 rc = irq_set_affinity_notifier(irq, &napi->notify); 7383 if (rc) { 7384 netdev_warn(napi->dev, "Unable to set IRQ notifier (%d)\n", 7385 rc); 7386 goto put_rmap; 7387 } 7388 7389 set_bit(NAPI_STATE_HAS_NOTIFIER, &napi->state); 7390 return; 7391 7392 put_rmap: 7393 #ifdef CONFIG_RFS_ACCEL 7394 if (napi->dev->rx_cpu_rmap_auto) { 7395 napi->dev->rx_cpu_rmap->obj[napi->napi_rmap_idx] = NULL; 7396 cpu_rmap_put(napi->dev->rx_cpu_rmap); 7397 napi->napi_rmap_idx = -1; 7398 } 7399 #endif 7400 napi->notify.notify = NULL; 7401 napi->notify.release = NULL; 7402 } 7403 EXPORT_SYMBOL(netif_napi_set_irq_locked); 7404 7405 static void napi_restore_config(struct napi_struct *n) 7406 { 7407 n->defer_hard_irqs = n->config->defer_hard_irqs; 7408 n->gro_flush_timeout = n->config->gro_flush_timeout; 7409 n->irq_suspend_timeout = n->config->irq_suspend_timeout; 7410 7411 if (n->dev->irq_affinity_auto && 7412 test_bit(NAPI_STATE_HAS_NOTIFIER, &n->state)) 7413 irq_set_affinity(n->irq, &n->config->affinity_mask); 7414 7415 /* a NAPI ID might be stored in the config, if so use it. if not, use 7416 * napi_hash_add to generate one for us. 7417 */ 7418 if (n->config->napi_id) { 7419 napi_hash_add_with_id(n, n->config->napi_id); 7420 } else { 7421 napi_hash_add(n); 7422 n->config->napi_id = n->napi_id; 7423 } 7424 7425 WARN_ON_ONCE(napi_set_threaded(n, n->config->threaded)); 7426 } 7427 7428 static void napi_save_config(struct napi_struct *n) 7429 { 7430 n->config->defer_hard_irqs = n->defer_hard_irqs; 7431 n->config->gro_flush_timeout = n->gro_flush_timeout; 7432 n->config->irq_suspend_timeout = n->irq_suspend_timeout; 7433 napi_hash_del(n); 7434 } 7435 7436 /* Netlink wants the NAPI list to be sorted by ID, if adding a NAPI which will 7437 * inherit an existing ID try to insert it at the right position. 7438 */ 7439 static void 7440 netif_napi_dev_list_add(struct net_device *dev, struct napi_struct *napi) 7441 { 7442 unsigned int new_id, pos_id; 7443 struct list_head *higher; 7444 struct napi_struct *pos; 7445 7446 new_id = UINT_MAX; 7447 if (napi->config && napi->config->napi_id) 7448 new_id = napi->config->napi_id; 7449 7450 higher = &dev->napi_list; 7451 list_for_each_entry(pos, &dev->napi_list, dev_list) { 7452 if (napi_id_valid(pos->napi_id)) 7453 pos_id = pos->napi_id; 7454 else if (pos->config) 7455 pos_id = pos->config->napi_id; 7456 else 7457 pos_id = UINT_MAX; 7458 7459 if (pos_id <= new_id) 7460 break; 7461 higher = &pos->dev_list; 7462 } 7463 list_add_rcu(&napi->dev_list, higher); /* adds after higher */ 7464 } 7465 7466 /* Double check that napi_get_frags() allocates skbs with 7467 * skb->head being backed by slab, not a page fragment. 7468 * This is to make sure bug fixed in 3226b158e67c 7469 * ("net: avoid 32 x truesize under-estimation for tiny skbs") 7470 * does not accidentally come back. 7471 */ 7472 static void napi_get_frags_check(struct napi_struct *napi) 7473 { 7474 struct sk_buff *skb; 7475 7476 local_bh_disable(); 7477 skb = napi_get_frags(napi); 7478 WARN_ON_ONCE(skb && skb->head_frag); 7479 napi_free_frags(napi); 7480 local_bh_enable(); 7481 } 7482 7483 void netif_napi_add_weight_locked(struct net_device *dev, 7484 struct napi_struct *napi, 7485 int (*poll)(struct napi_struct *, int), 7486 int weight) 7487 { 7488 netdev_assert_locked(dev); 7489 if (WARN_ON(test_and_set_bit(NAPI_STATE_LISTED, &napi->state))) 7490 return; 7491 7492 INIT_LIST_HEAD(&napi->poll_list); 7493 INIT_HLIST_NODE(&napi->napi_hash_node); 7494 hrtimer_setup(&napi->timer, napi_watchdog, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED); 7495 gro_init(&napi->gro); 7496 napi->skb = NULL; 7497 napi->poll = poll; 7498 if (weight > NAPI_POLL_WEIGHT) 7499 netdev_err_once(dev, "%s() called with weight %d\n", __func__, 7500 weight); 7501 napi->weight = weight; 7502 napi->dev = dev; 7503 #ifdef CONFIG_NETPOLL 7504 napi->poll_owner = -1; 7505 #endif 7506 napi->list_owner = -1; 7507 set_bit(NAPI_STATE_SCHED, &napi->state); 7508 set_bit(NAPI_STATE_NPSVC, &napi->state); 7509 netif_napi_dev_list_add(dev, napi); 7510 7511 /* default settings from sysfs are applied to all NAPIs. any per-NAPI 7512 * configuration will be loaded in napi_enable 7513 */ 7514 napi_set_defer_hard_irqs(napi, READ_ONCE(dev->napi_defer_hard_irqs)); 7515 napi_set_gro_flush_timeout(napi, READ_ONCE(dev->gro_flush_timeout)); 7516 7517 napi_get_frags_check(napi); 7518 /* Create kthread for this napi if dev->threaded is set. 7519 * Clear dev->threaded if kthread creation failed so that 7520 * threaded mode will not be enabled in napi_enable(). 7521 */ 7522 if (napi_get_threaded_config(dev, napi)) 7523 if (napi_kthread_create(napi)) 7524 dev->threaded = NETDEV_NAPI_THREADED_DISABLED; 7525 netif_napi_set_irq_locked(napi, -1); 7526 } 7527 EXPORT_SYMBOL(netif_napi_add_weight_locked); 7528 7529 void napi_disable_locked(struct napi_struct *n) 7530 { 7531 unsigned long val, new; 7532 7533 might_sleep(); 7534 netdev_assert_locked(n->dev); 7535 7536 set_bit(NAPI_STATE_DISABLE, &n->state); 7537 7538 val = READ_ONCE(n->state); 7539 do { 7540 while (val & (NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC)) { 7541 usleep_range(20, 200); 7542 val = READ_ONCE(n->state); 7543 } 7544 7545 new = val | NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC; 7546 new &= ~(NAPIF_STATE_THREADED | 7547 NAPIF_STATE_THREADED_BUSY_POLL | 7548 NAPIF_STATE_PREFER_BUSY_POLL); 7549 } while (!try_cmpxchg(&n->state, &val, new)); 7550 7551 hrtimer_cancel(&n->timer); 7552 7553 if (n->config) 7554 napi_save_config(n); 7555 else 7556 napi_hash_del(n); 7557 7558 clear_bit(NAPI_STATE_DISABLE, &n->state); 7559 } 7560 EXPORT_SYMBOL(napi_disable_locked); 7561 7562 /** 7563 * napi_disable() - prevent NAPI from scheduling 7564 * @n: NAPI context 7565 * 7566 * Stop NAPI from being scheduled on this context. 7567 * Waits till any outstanding processing completes. 7568 * Takes netdev_lock() for associated net_device. 7569 */ 7570 void napi_disable(struct napi_struct *n) 7571 { 7572 netdev_lock(n->dev); 7573 napi_disable_locked(n); 7574 netdev_unlock(n->dev); 7575 } 7576 EXPORT_SYMBOL(napi_disable); 7577 7578 void napi_enable_locked(struct napi_struct *n) 7579 { 7580 unsigned long new, val = READ_ONCE(n->state); 7581 7582 if (n->config) 7583 napi_restore_config(n); 7584 else 7585 napi_hash_add(n); 7586 7587 do { 7588 BUG_ON(!test_bit(NAPI_STATE_SCHED, &val)); 7589 7590 new = val & ~(NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC); 7591 if (n->dev->threaded && n->thread) 7592 new |= NAPIF_STATE_THREADED; 7593 } while (!try_cmpxchg(&n->state, &val, new)); 7594 } 7595 EXPORT_SYMBOL(napi_enable_locked); 7596 7597 /** 7598 * napi_enable() - enable NAPI scheduling 7599 * @n: NAPI context 7600 * 7601 * Enable scheduling of a NAPI instance. 7602 * Must be paired with napi_disable(). 7603 * Takes netdev_lock() for associated net_device. 7604 */ 7605 void napi_enable(struct napi_struct *n) 7606 { 7607 netdev_lock(n->dev); 7608 napi_enable_locked(n); 7609 netdev_unlock(n->dev); 7610 } 7611 EXPORT_SYMBOL(napi_enable); 7612 7613 /* Must be called in process context */ 7614 void __netif_napi_del_locked(struct napi_struct *napi) 7615 { 7616 netdev_assert_locked(napi->dev); 7617 7618 if (!test_and_clear_bit(NAPI_STATE_LISTED, &napi->state)) 7619 return; 7620 7621 /* Make sure NAPI is disabled (or was never enabled). */ 7622 WARN_ON(!test_bit(NAPI_STATE_SCHED, &napi->state)); 7623 7624 if (test_and_clear_bit(NAPI_STATE_HAS_NOTIFIER, &napi->state)) 7625 irq_set_affinity_notifier(napi->irq, NULL); 7626 7627 if (napi->config) { 7628 napi->index = -1; 7629 napi->config = NULL; 7630 } 7631 7632 list_del_rcu(&napi->dev_list); 7633 napi_free_frags(napi); 7634 7635 gro_cleanup(&napi->gro); 7636 7637 if (napi->thread) { 7638 kthread_stop(napi->thread); 7639 napi->thread = NULL; 7640 } 7641 } 7642 EXPORT_SYMBOL(__netif_napi_del_locked); 7643 7644 static int __napi_poll(struct napi_struct *n, bool *repoll) 7645 { 7646 int work, weight; 7647 7648 weight = n->weight; 7649 7650 /* This NAPI_STATE_SCHED test is for avoiding a race 7651 * with netpoll's poll_napi(). Only the entity which 7652 * obtains the lock and sees NAPI_STATE_SCHED set will 7653 * actually make the ->poll() call. Therefore we avoid 7654 * accidentally calling ->poll() when NAPI is not scheduled. 7655 */ 7656 work = 0; 7657 if (napi_is_scheduled(n)) { 7658 work = n->poll(n, weight); 7659 trace_napi_poll(n, work, weight); 7660 7661 xdp_do_check_flushed(n); 7662 } 7663 7664 if (unlikely(work > weight)) 7665 netdev_err_once(n->dev, "NAPI poll function %pS returned %d, exceeding its budget of %d.\n", 7666 n->poll, work, weight); 7667 7668 if (likely(work < weight)) 7669 return work; 7670 7671 /* Drivers must not modify the NAPI state if they 7672 * consume the entire weight. In such cases this code 7673 * still "owns" the NAPI instance and therefore can 7674 * move the instance around on the list at-will. 7675 */ 7676 if (unlikely(napi_disable_pending(n))) { 7677 napi_complete(n); 7678 return work; 7679 } 7680 7681 /* The NAPI context has more processing work, but busy-polling 7682 * is preferred. Exit early. 7683 */ 7684 if (napi_prefer_busy_poll(n)) { 7685 if (napi_complete_done(n, work)) { 7686 /* If timeout is not set, we need to make sure 7687 * that the NAPI is re-scheduled. 7688 */ 7689 napi_schedule(n); 7690 } 7691 return work; 7692 } 7693 7694 /* Flush too old packets. If HZ < 1000, flush all packets */ 7695 gro_flush_normal(&n->gro, HZ >= 1000); 7696 7697 /* Some drivers may have called napi_schedule 7698 * prior to exhausting their budget. 7699 */ 7700 if (unlikely(!list_empty(&n->poll_list))) { 7701 pr_warn_once("%s: Budget exhausted after napi rescheduled\n", 7702 n->dev ? n->dev->name : "backlog"); 7703 return work; 7704 } 7705 7706 *repoll = true; 7707 7708 return work; 7709 } 7710 7711 static int napi_poll(struct napi_struct *n, struct list_head *repoll) 7712 { 7713 bool do_repoll = false; 7714 void *have; 7715 int work; 7716 7717 list_del_init(&n->poll_list); 7718 7719 have = netpoll_poll_lock(n); 7720 7721 work = __napi_poll(n, &do_repoll); 7722 7723 if (do_repoll) { 7724 #if defined(CONFIG_DEBUG_NET) 7725 if (unlikely(!napi_is_scheduled(n))) 7726 pr_crit("repoll requested for device %s %ps but napi is not scheduled.\n", 7727 n->dev->name, n->poll); 7728 #endif 7729 list_add_tail(&n->poll_list, repoll); 7730 } 7731 netpoll_poll_unlock(have); 7732 7733 return work; 7734 } 7735 7736 static int napi_thread_wait(struct napi_struct *napi) 7737 { 7738 set_current_state(TASK_INTERRUPTIBLE); 7739 7740 while (!kthread_should_stop()) { 7741 /* Testing SCHED_THREADED bit here to make sure the current 7742 * kthread owns this napi and could poll on this napi. 7743 * Testing SCHED bit is not enough because SCHED bit might be 7744 * set by some other busy poll thread or by napi_disable(). 7745 */ 7746 if (test_bit(NAPI_STATE_SCHED_THREADED, &napi->state)) { 7747 WARN_ON(!list_empty(&napi->poll_list)); 7748 __set_current_state(TASK_RUNNING); 7749 return 0; 7750 } 7751 7752 schedule(); 7753 set_current_state(TASK_INTERRUPTIBLE); 7754 } 7755 __set_current_state(TASK_RUNNING); 7756 7757 return -1; 7758 } 7759 7760 static void napi_threaded_poll_loop(struct napi_struct *napi, bool busy_poll) 7761 { 7762 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx; 7763 struct softnet_data *sd; 7764 unsigned long last_qs = jiffies; 7765 7766 for (;;) { 7767 bool repoll = false; 7768 void *have; 7769 7770 local_bh_disable(); 7771 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx); 7772 7773 sd = this_cpu_ptr(&softnet_data); 7774 sd->in_napi_threaded_poll = true; 7775 7776 have = netpoll_poll_lock(napi); 7777 __napi_poll(napi, &repoll); 7778 netpoll_poll_unlock(have); 7779 7780 sd->in_napi_threaded_poll = false; 7781 barrier(); 7782 7783 if (sd_has_rps_ipi_waiting(sd)) { 7784 local_irq_disable(); 7785 net_rps_action_and_irq_enable(sd); 7786 } 7787 skb_defer_free_flush(); 7788 bpf_net_ctx_clear(bpf_net_ctx); 7789 7790 /* When busy poll is enabled, the old packets are not flushed in 7791 * napi_complete_done. So flush them here. 7792 */ 7793 if (busy_poll) 7794 gro_flush_normal(&napi->gro, HZ >= 1000); 7795 local_bh_enable(); 7796 7797 /* Call cond_resched here to avoid watchdog warnings. */ 7798 if (repoll || busy_poll) { 7799 rcu_softirq_qs_periodic(last_qs); 7800 cond_resched(); 7801 } 7802 7803 if (!repoll) 7804 break; 7805 } 7806 } 7807 7808 static int napi_threaded_poll(void *data) 7809 { 7810 struct napi_struct *napi = data; 7811 bool want_busy_poll; 7812 bool in_busy_poll; 7813 unsigned long val; 7814 7815 while (!napi_thread_wait(napi)) { 7816 val = READ_ONCE(napi->state); 7817 7818 want_busy_poll = val & NAPIF_STATE_THREADED_BUSY_POLL; 7819 in_busy_poll = val & NAPIF_STATE_IN_BUSY_POLL; 7820 7821 if (unlikely(val & NAPIF_STATE_DISABLE)) 7822 want_busy_poll = false; 7823 7824 if (want_busy_poll != in_busy_poll) 7825 assign_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state, 7826 want_busy_poll); 7827 7828 napi_threaded_poll_loop(napi, want_busy_poll); 7829 } 7830 7831 return 0; 7832 } 7833 7834 static __latent_entropy void net_rx_action(void) 7835 { 7836 struct softnet_data *sd = this_cpu_ptr(&softnet_data); 7837 unsigned long time_limit = jiffies + 7838 usecs_to_jiffies(READ_ONCE(net_hotdata.netdev_budget_usecs)); 7839 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx; 7840 int budget = READ_ONCE(net_hotdata.netdev_budget); 7841 LIST_HEAD(list); 7842 LIST_HEAD(repoll); 7843 7844 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx); 7845 start: 7846 sd->in_net_rx_action = true; 7847 local_irq_disable(); 7848 list_splice_init(&sd->poll_list, &list); 7849 local_irq_enable(); 7850 7851 for (;;) { 7852 struct napi_struct *n; 7853 7854 skb_defer_free_flush(); 7855 7856 if (list_empty(&list)) { 7857 if (list_empty(&repoll)) { 7858 sd->in_net_rx_action = false; 7859 barrier(); 7860 /* We need to check if ____napi_schedule() 7861 * had refilled poll_list while 7862 * sd->in_net_rx_action was true. 7863 */ 7864 if (!list_empty(&sd->poll_list)) 7865 goto start; 7866 if (!sd_has_rps_ipi_waiting(sd)) 7867 goto end; 7868 } 7869 break; 7870 } 7871 7872 n = list_first_entry(&list, struct napi_struct, poll_list); 7873 budget -= napi_poll(n, &repoll); 7874 7875 /* If softirq window is exhausted then punt. 7876 * Allow this to run for 2 jiffies since which will allow 7877 * an average latency of 1.5/HZ. 7878 */ 7879 if (unlikely(budget <= 0 || 7880 time_after_eq(jiffies, time_limit))) { 7881 /* Pairs with READ_ONCE() in softnet_seq_show() */ 7882 WRITE_ONCE(sd->time_squeeze, sd->time_squeeze + 1); 7883 break; 7884 } 7885 } 7886 7887 local_irq_disable(); 7888 7889 list_splice_tail_init(&sd->poll_list, &list); 7890 list_splice_tail(&repoll, &list); 7891 list_splice(&list, &sd->poll_list); 7892 if (!list_empty(&sd->poll_list)) 7893 __raise_softirq_irqoff(NET_RX_SOFTIRQ); 7894 else 7895 sd->in_net_rx_action = false; 7896 7897 net_rps_action_and_irq_enable(sd); 7898 end: 7899 bpf_net_ctx_clear(bpf_net_ctx); 7900 } 7901 7902 struct netdev_adjacent { 7903 struct net_device *dev; 7904 netdevice_tracker dev_tracker; 7905 7906 /* upper master flag, there can only be one master device per list */ 7907 bool master; 7908 7909 /* lookup ignore flag */ 7910 bool ignore; 7911 7912 /* counter for the number of times this device was added to us */ 7913 u16 ref_nr; 7914 7915 /* private field for the users */ 7916 void *private; 7917 7918 struct list_head list; 7919 struct rcu_head rcu; 7920 }; 7921 7922 static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev, 7923 struct list_head *adj_list) 7924 { 7925 struct netdev_adjacent *adj; 7926 7927 list_for_each_entry(adj, adj_list, list) { 7928 if (adj->dev == adj_dev) 7929 return adj; 7930 } 7931 return NULL; 7932 } 7933 7934 static int ____netdev_has_upper_dev(struct net_device *upper_dev, 7935 struct netdev_nested_priv *priv) 7936 { 7937 struct net_device *dev = (struct net_device *)priv->data; 7938 7939 return upper_dev == dev; 7940 } 7941 7942 /** 7943 * netdev_has_upper_dev - Check if device is linked to an upper device 7944 * @dev: device 7945 * @upper_dev: upper device to check 7946 * 7947 * Find out if a device is linked to specified upper device and return true 7948 * in case it is. Note that this checks only immediate upper device, 7949 * not through a complete stack of devices. The caller must hold the RTNL lock. 7950 */ 7951 bool netdev_has_upper_dev(struct net_device *dev, 7952 struct net_device *upper_dev) 7953 { 7954 struct netdev_nested_priv priv = { 7955 .data = (void *)upper_dev, 7956 }; 7957 7958 ASSERT_RTNL(); 7959 7960 return netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev, 7961 &priv); 7962 } 7963 EXPORT_SYMBOL(netdev_has_upper_dev); 7964 7965 /** 7966 * netdev_has_upper_dev_all_rcu - Check if device is linked to an upper device 7967 * @dev: device 7968 * @upper_dev: upper device to check 7969 * 7970 * Find out if a device is linked to specified upper device and return true 7971 * in case it is. Note that this checks the entire upper device chain. 7972 * The caller must hold rcu lock. 7973 */ 7974 7975 bool netdev_has_upper_dev_all_rcu(struct net_device *dev, 7976 struct net_device *upper_dev) 7977 { 7978 struct netdev_nested_priv priv = { 7979 .data = (void *)upper_dev, 7980 }; 7981 7982 return !!netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev, 7983 &priv); 7984 } 7985 EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu); 7986 7987 /** 7988 * netdev_has_any_upper_dev - Check if device is linked to some device 7989 * @dev: device 7990 * 7991 * Find out if a device is linked to an upper device and return true in case 7992 * it is. The caller must hold the RTNL lock. 7993 */ 7994 bool netdev_has_any_upper_dev(struct net_device *dev) 7995 { 7996 ASSERT_RTNL(); 7997 7998 return !list_empty(&dev->adj_list.upper); 7999 } 8000 EXPORT_SYMBOL(netdev_has_any_upper_dev); 8001 8002 /** 8003 * netdev_master_upper_dev_get - Get master upper device 8004 * @dev: device 8005 * 8006 * Find a master upper device and return pointer to it or NULL in case 8007 * it's not there. The caller must hold the RTNL lock. 8008 */ 8009 struct net_device *netdev_master_upper_dev_get(struct net_device *dev) 8010 { 8011 struct netdev_adjacent *upper; 8012 8013 ASSERT_RTNL(); 8014 8015 if (list_empty(&dev->adj_list.upper)) 8016 return NULL; 8017 8018 upper = list_first_entry(&dev->adj_list.upper, 8019 struct netdev_adjacent, list); 8020 if (likely(upper->master)) 8021 return upper->dev; 8022 return NULL; 8023 } 8024 EXPORT_SYMBOL(netdev_master_upper_dev_get); 8025 8026 static struct net_device *__netdev_master_upper_dev_get(struct net_device *dev) 8027 { 8028 struct netdev_adjacent *upper; 8029 8030 ASSERT_RTNL(); 8031 8032 if (list_empty(&dev->adj_list.upper)) 8033 return NULL; 8034 8035 upper = list_first_entry(&dev->adj_list.upper, 8036 struct netdev_adjacent, list); 8037 if (likely(upper->master) && !upper->ignore) 8038 return upper->dev; 8039 return NULL; 8040 } 8041 8042 /** 8043 * netdev_has_any_lower_dev - Check if device is linked to some device 8044 * @dev: device 8045 * 8046 * Find out if a device is linked to a lower device and return true in case 8047 * it is. The caller must hold the RTNL lock. 8048 */ 8049 static bool netdev_has_any_lower_dev(struct net_device *dev) 8050 { 8051 ASSERT_RTNL(); 8052 8053 return !list_empty(&dev->adj_list.lower); 8054 } 8055 8056 void *netdev_adjacent_get_private(struct list_head *adj_list) 8057 { 8058 struct netdev_adjacent *adj; 8059 8060 adj = list_entry(adj_list, struct netdev_adjacent, list); 8061 8062 return adj->private; 8063 } 8064 EXPORT_SYMBOL(netdev_adjacent_get_private); 8065 8066 /** 8067 * netdev_upper_get_next_dev_rcu - Get the next dev from upper list 8068 * @dev: device 8069 * @iter: list_head ** of the current position 8070 * 8071 * Gets the next device from the dev's upper list, starting from iter 8072 * position. The caller must hold RCU read lock. 8073 */ 8074 struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev, 8075 struct list_head **iter) 8076 { 8077 struct netdev_adjacent *upper; 8078 8079 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held()); 8080 8081 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list); 8082 8083 if (&upper->list == &dev->adj_list.upper) 8084 return NULL; 8085 8086 *iter = &upper->list; 8087 8088 return upper->dev; 8089 } 8090 EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu); 8091 8092 static struct net_device *__netdev_next_upper_dev(struct net_device *dev, 8093 struct list_head **iter, 8094 bool *ignore) 8095 { 8096 struct netdev_adjacent *upper; 8097 8098 upper = list_entry((*iter)->next, struct netdev_adjacent, list); 8099 8100 if (&upper->list == &dev->adj_list.upper) 8101 return NULL; 8102 8103 *iter = &upper->list; 8104 *ignore = upper->ignore; 8105 8106 return upper->dev; 8107 } 8108 8109 static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev, 8110 struct list_head **iter) 8111 { 8112 struct netdev_adjacent *upper; 8113 8114 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held()); 8115 8116 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list); 8117 8118 if (&upper->list == &dev->adj_list.upper) 8119 return NULL; 8120 8121 *iter = &upper->list; 8122 8123 return upper->dev; 8124 } 8125 8126 static int __netdev_walk_all_upper_dev(struct net_device *dev, 8127 int (*fn)(struct net_device *dev, 8128 struct netdev_nested_priv *priv), 8129 struct netdev_nested_priv *priv) 8130 { 8131 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1]; 8132 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1]; 8133 int ret, cur = 0; 8134 bool ignore; 8135 8136 now = dev; 8137 iter = &dev->adj_list.upper; 8138 8139 while (1) { 8140 if (now != dev) { 8141 ret = fn(now, priv); 8142 if (ret) 8143 return ret; 8144 } 8145 8146 next = NULL; 8147 while (1) { 8148 udev = __netdev_next_upper_dev(now, &iter, &ignore); 8149 if (!udev) 8150 break; 8151 if (ignore) 8152 continue; 8153 8154 next = udev; 8155 niter = &udev->adj_list.upper; 8156 dev_stack[cur] = now; 8157 iter_stack[cur++] = iter; 8158 break; 8159 } 8160 8161 if (!next) { 8162 if (!cur) 8163 return 0; 8164 next = dev_stack[--cur]; 8165 niter = iter_stack[cur]; 8166 } 8167 8168 now = next; 8169 iter = niter; 8170 } 8171 8172 return 0; 8173 } 8174 8175 int netdev_walk_all_upper_dev_rcu(struct net_device *dev, 8176 int (*fn)(struct net_device *dev, 8177 struct netdev_nested_priv *priv), 8178 struct netdev_nested_priv *priv) 8179 { 8180 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1]; 8181 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1]; 8182 int ret, cur = 0; 8183 8184 now = dev; 8185 iter = &dev->adj_list.upper; 8186 8187 while (1) { 8188 if (now != dev) { 8189 ret = fn(now, priv); 8190 if (ret) 8191 return ret; 8192 } 8193 8194 next = NULL; 8195 while (1) { 8196 udev = netdev_next_upper_dev_rcu(now, &iter); 8197 if (!udev) 8198 break; 8199 8200 next = udev; 8201 niter = &udev->adj_list.upper; 8202 dev_stack[cur] = now; 8203 iter_stack[cur++] = iter; 8204 break; 8205 } 8206 8207 if (!next) { 8208 if (!cur) 8209 return 0; 8210 next = dev_stack[--cur]; 8211 niter = iter_stack[cur]; 8212 } 8213 8214 now = next; 8215 iter = niter; 8216 } 8217 8218 return 0; 8219 } 8220 EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu); 8221 8222 static bool __netdev_has_upper_dev(struct net_device *dev, 8223 struct net_device *upper_dev) 8224 { 8225 struct netdev_nested_priv priv = { 8226 .flags = 0, 8227 .data = (void *)upper_dev, 8228 }; 8229 8230 ASSERT_RTNL(); 8231 8232 return __netdev_walk_all_upper_dev(dev, ____netdev_has_upper_dev, 8233 &priv); 8234 } 8235 8236 /** 8237 * netdev_lower_get_next_private - Get the next ->private from the 8238 * lower neighbour list 8239 * @dev: device 8240 * @iter: list_head ** of the current position 8241 * 8242 * Gets the next netdev_adjacent->private from the dev's lower neighbour 8243 * list, starting from iter position. The caller must hold either hold the 8244 * RTNL lock or its own locking that guarantees that the neighbour lower 8245 * list will remain unchanged. 8246 */ 8247 void *netdev_lower_get_next_private(struct net_device *dev, 8248 struct list_head **iter) 8249 { 8250 struct netdev_adjacent *lower; 8251 8252 lower = list_entry(*iter, struct netdev_adjacent, list); 8253 8254 if (&lower->list == &dev->adj_list.lower) 8255 return NULL; 8256 8257 *iter = lower->list.next; 8258 8259 return lower->private; 8260 } 8261 EXPORT_SYMBOL(netdev_lower_get_next_private); 8262 8263 /** 8264 * netdev_lower_get_next_private_rcu - Get the next ->private from the 8265 * lower neighbour list, RCU 8266 * variant 8267 * @dev: device 8268 * @iter: list_head ** of the current position 8269 * 8270 * Gets the next netdev_adjacent->private from the dev's lower neighbour 8271 * list, starting from iter position. The caller must hold RCU read lock. 8272 */ 8273 void *netdev_lower_get_next_private_rcu(struct net_device *dev, 8274 struct list_head **iter) 8275 { 8276 struct netdev_adjacent *lower; 8277 8278 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held()); 8279 8280 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list); 8281 8282 if (&lower->list == &dev->adj_list.lower) 8283 return NULL; 8284 8285 *iter = &lower->list; 8286 8287 return lower->private; 8288 } 8289 EXPORT_SYMBOL(netdev_lower_get_next_private_rcu); 8290 8291 /** 8292 * netdev_lower_get_next - Get the next device from the lower neighbour 8293 * list 8294 * @dev: device 8295 * @iter: list_head ** of the current position 8296 * 8297 * Gets the next netdev_adjacent from the dev's lower neighbour 8298 * list, starting from iter position. The caller must hold RTNL lock or 8299 * its own locking that guarantees that the neighbour lower 8300 * list will remain unchanged. 8301 */ 8302 void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter) 8303 { 8304 struct netdev_adjacent *lower; 8305 8306 lower = list_entry(*iter, struct netdev_adjacent, list); 8307 8308 if (&lower->list == &dev->adj_list.lower) 8309 return NULL; 8310 8311 *iter = lower->list.next; 8312 8313 return lower->dev; 8314 } 8315 EXPORT_SYMBOL(netdev_lower_get_next); 8316 8317 static struct net_device *netdev_next_lower_dev(struct net_device *dev, 8318 struct list_head **iter) 8319 { 8320 struct netdev_adjacent *lower; 8321 8322 lower = list_entry((*iter)->next, struct netdev_adjacent, list); 8323 8324 if (&lower->list == &dev->adj_list.lower) 8325 return NULL; 8326 8327 *iter = &lower->list; 8328 8329 return lower->dev; 8330 } 8331 8332 static struct net_device *__netdev_next_lower_dev(struct net_device *dev, 8333 struct list_head **iter, 8334 bool *ignore) 8335 { 8336 struct netdev_adjacent *lower; 8337 8338 lower = list_entry((*iter)->next, struct netdev_adjacent, list); 8339 8340 if (&lower->list == &dev->adj_list.lower) 8341 return NULL; 8342 8343 *iter = &lower->list; 8344 *ignore = lower->ignore; 8345 8346 return lower->dev; 8347 } 8348 8349 int netdev_walk_all_lower_dev(struct net_device *dev, 8350 int (*fn)(struct net_device *dev, 8351 struct netdev_nested_priv *priv), 8352 struct netdev_nested_priv *priv) 8353 { 8354 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1]; 8355 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1]; 8356 int ret, cur = 0; 8357 8358 now = dev; 8359 iter = &dev->adj_list.lower; 8360 8361 while (1) { 8362 if (now != dev) { 8363 ret = fn(now, priv); 8364 if (ret) 8365 return ret; 8366 } 8367 8368 next = NULL; 8369 while (1) { 8370 ldev = netdev_next_lower_dev(now, &iter); 8371 if (!ldev) 8372 break; 8373 8374 next = ldev; 8375 niter = &ldev->adj_list.lower; 8376 dev_stack[cur] = now; 8377 iter_stack[cur++] = iter; 8378 break; 8379 } 8380 8381 if (!next) { 8382 if (!cur) 8383 return 0; 8384 next = dev_stack[--cur]; 8385 niter = iter_stack[cur]; 8386 } 8387 8388 now = next; 8389 iter = niter; 8390 } 8391 8392 return 0; 8393 } 8394 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev); 8395 8396 static int __netdev_walk_all_lower_dev(struct net_device *dev, 8397 int (*fn)(struct net_device *dev, 8398 struct netdev_nested_priv *priv), 8399 struct netdev_nested_priv *priv) 8400 { 8401 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1]; 8402 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1]; 8403 int ret, cur = 0; 8404 bool ignore; 8405 8406 now = dev; 8407 iter = &dev->adj_list.lower; 8408 8409 while (1) { 8410 if (now != dev) { 8411 ret = fn(now, priv); 8412 if (ret) 8413 return ret; 8414 } 8415 8416 next = NULL; 8417 while (1) { 8418 ldev = __netdev_next_lower_dev(now, &iter, &ignore); 8419 if (!ldev) 8420 break; 8421 if (ignore) 8422 continue; 8423 8424 next = ldev; 8425 niter = &ldev->adj_list.lower; 8426 dev_stack[cur] = now; 8427 iter_stack[cur++] = iter; 8428 break; 8429 } 8430 8431 if (!next) { 8432 if (!cur) 8433 return 0; 8434 next = dev_stack[--cur]; 8435 niter = iter_stack[cur]; 8436 } 8437 8438 now = next; 8439 iter = niter; 8440 } 8441 8442 return 0; 8443 } 8444 8445 struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev, 8446 struct list_head **iter) 8447 { 8448 struct netdev_adjacent *lower; 8449 8450 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list); 8451 if (&lower->list == &dev->adj_list.lower) 8452 return NULL; 8453 8454 *iter = &lower->list; 8455 8456 return lower->dev; 8457 } 8458 EXPORT_SYMBOL(netdev_next_lower_dev_rcu); 8459 8460 static u8 __netdev_upper_depth(struct net_device *dev) 8461 { 8462 struct net_device *udev; 8463 struct list_head *iter; 8464 u8 max_depth = 0; 8465 bool ignore; 8466 8467 for (iter = &dev->adj_list.upper, 8468 udev = __netdev_next_upper_dev(dev, &iter, &ignore); 8469 udev; 8470 udev = __netdev_next_upper_dev(dev, &iter, &ignore)) { 8471 if (ignore) 8472 continue; 8473 if (max_depth < udev->upper_level) 8474 max_depth = udev->upper_level; 8475 } 8476 8477 return max_depth; 8478 } 8479 8480 static u8 __netdev_lower_depth(struct net_device *dev) 8481 { 8482 struct net_device *ldev; 8483 struct list_head *iter; 8484 u8 max_depth = 0; 8485 bool ignore; 8486 8487 for (iter = &dev->adj_list.lower, 8488 ldev = __netdev_next_lower_dev(dev, &iter, &ignore); 8489 ldev; 8490 ldev = __netdev_next_lower_dev(dev, &iter, &ignore)) { 8491 if (ignore) 8492 continue; 8493 if (max_depth < ldev->lower_level) 8494 max_depth = ldev->lower_level; 8495 } 8496 8497 return max_depth; 8498 } 8499 8500 static int __netdev_update_upper_level(struct net_device *dev, 8501 struct netdev_nested_priv *__unused) 8502 { 8503 dev->upper_level = __netdev_upper_depth(dev) + 1; 8504 return 0; 8505 } 8506 8507 #ifdef CONFIG_LOCKDEP 8508 static LIST_HEAD(net_unlink_list); 8509 8510 static void net_unlink_todo(struct net_device *dev) 8511 { 8512 if (list_empty(&dev->unlink_list)) 8513 list_add_tail(&dev->unlink_list, &net_unlink_list); 8514 } 8515 #endif 8516 8517 static int __netdev_update_lower_level(struct net_device *dev, 8518 struct netdev_nested_priv *priv) 8519 { 8520 dev->lower_level = __netdev_lower_depth(dev) + 1; 8521 8522 #ifdef CONFIG_LOCKDEP 8523 if (!priv) 8524 return 0; 8525 8526 if (priv->flags & NESTED_SYNC_IMM) 8527 dev->nested_level = dev->lower_level - 1; 8528 if (priv->flags & NESTED_SYNC_TODO) 8529 net_unlink_todo(dev); 8530 #endif 8531 return 0; 8532 } 8533 8534 int netdev_walk_all_lower_dev_rcu(struct net_device *dev, 8535 int (*fn)(struct net_device *dev, 8536 struct netdev_nested_priv *priv), 8537 struct netdev_nested_priv *priv) 8538 { 8539 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1]; 8540 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1]; 8541 int ret, cur = 0; 8542 8543 now = dev; 8544 iter = &dev->adj_list.lower; 8545 8546 while (1) { 8547 if (now != dev) { 8548 ret = fn(now, priv); 8549 if (ret) 8550 return ret; 8551 } 8552 8553 next = NULL; 8554 while (1) { 8555 ldev = netdev_next_lower_dev_rcu(now, &iter); 8556 if (!ldev) 8557 break; 8558 8559 next = ldev; 8560 niter = &ldev->adj_list.lower; 8561 dev_stack[cur] = now; 8562 iter_stack[cur++] = iter; 8563 break; 8564 } 8565 8566 if (!next) { 8567 if (!cur) 8568 return 0; 8569 next = dev_stack[--cur]; 8570 niter = iter_stack[cur]; 8571 } 8572 8573 now = next; 8574 iter = niter; 8575 } 8576 8577 return 0; 8578 } 8579 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu); 8580 8581 /** 8582 * netdev_lower_get_first_private_rcu - Get the first ->private from the 8583 * lower neighbour list, RCU 8584 * variant 8585 * @dev: device 8586 * 8587 * Gets the first netdev_adjacent->private from the dev's lower neighbour 8588 * list. The caller must hold RCU read lock. 8589 */ 8590 void *netdev_lower_get_first_private_rcu(struct net_device *dev) 8591 { 8592 struct netdev_adjacent *lower; 8593 8594 lower = list_first_or_null_rcu(&dev->adj_list.lower, 8595 struct netdev_adjacent, list); 8596 if (lower) 8597 return lower->private; 8598 return NULL; 8599 } 8600 EXPORT_SYMBOL(netdev_lower_get_first_private_rcu); 8601 8602 /** 8603 * netdev_master_upper_dev_get_rcu - Get master upper device 8604 * @dev: device 8605 * 8606 * Find a master upper device and return pointer to it or NULL in case 8607 * it's not there. The caller must hold the RCU read lock. 8608 */ 8609 struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev) 8610 { 8611 struct netdev_adjacent *upper; 8612 8613 upper = list_first_or_null_rcu(&dev->adj_list.upper, 8614 struct netdev_adjacent, list); 8615 if (upper && likely(upper->master)) 8616 return upper->dev; 8617 return NULL; 8618 } 8619 EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu); 8620 8621 static int netdev_adjacent_sysfs_add(struct net_device *dev, 8622 struct net_device *adj_dev, 8623 struct list_head *dev_list) 8624 { 8625 char linkname[IFNAMSIZ+7]; 8626 8627 sprintf(linkname, dev_list == &dev->adj_list.upper ? 8628 "upper_%s" : "lower_%s", adj_dev->name); 8629 return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj), 8630 linkname); 8631 } 8632 static void netdev_adjacent_sysfs_del(struct net_device *dev, 8633 char *name, 8634 struct list_head *dev_list) 8635 { 8636 char linkname[IFNAMSIZ+7]; 8637 8638 sprintf(linkname, dev_list == &dev->adj_list.upper ? 8639 "upper_%s" : "lower_%s", name); 8640 sysfs_remove_link(&(dev->dev.kobj), linkname); 8641 } 8642 8643 static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev, 8644 struct net_device *adj_dev, 8645 struct list_head *dev_list) 8646 { 8647 return (dev_list == &dev->adj_list.upper || 8648 dev_list == &dev->adj_list.lower) && 8649 net_eq(dev_net(dev), dev_net(adj_dev)); 8650 } 8651 8652 static int __netdev_adjacent_dev_insert(struct net_device *dev, 8653 struct net_device *adj_dev, 8654 struct list_head *dev_list, 8655 void *private, bool master) 8656 { 8657 struct netdev_adjacent *adj; 8658 int ret; 8659 8660 adj = __netdev_find_adj(adj_dev, dev_list); 8661 8662 if (adj) { 8663 adj->ref_nr += 1; 8664 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n", 8665 dev->name, adj_dev->name, adj->ref_nr); 8666 8667 return 0; 8668 } 8669 8670 adj = kmalloc(sizeof(*adj), GFP_KERNEL); 8671 if (!adj) 8672 return -ENOMEM; 8673 8674 adj->dev = adj_dev; 8675 adj->master = master; 8676 adj->ref_nr = 1; 8677 adj->private = private; 8678 adj->ignore = false; 8679 netdev_hold(adj_dev, &adj->dev_tracker, GFP_KERNEL); 8680 8681 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n", 8682 dev->name, adj_dev->name, adj->ref_nr, adj_dev->name); 8683 8684 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) { 8685 ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list); 8686 if (ret) 8687 goto free_adj; 8688 } 8689 8690 /* Ensure that master link is always the first item in list. */ 8691 if (master) { 8692 ret = sysfs_create_link(&(dev->dev.kobj), 8693 &(adj_dev->dev.kobj), "master"); 8694 if (ret) 8695 goto remove_symlinks; 8696 8697 list_add_rcu(&adj->list, dev_list); 8698 } else { 8699 list_add_tail_rcu(&adj->list, dev_list); 8700 } 8701 8702 return 0; 8703 8704 remove_symlinks: 8705 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) 8706 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list); 8707 free_adj: 8708 netdev_put(adj_dev, &adj->dev_tracker); 8709 kfree(adj); 8710 8711 return ret; 8712 } 8713 8714 static void __netdev_adjacent_dev_remove(struct net_device *dev, 8715 struct net_device *adj_dev, 8716 u16 ref_nr, 8717 struct list_head *dev_list) 8718 { 8719 struct netdev_adjacent *adj; 8720 8721 pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n", 8722 dev->name, adj_dev->name, ref_nr); 8723 8724 adj = __netdev_find_adj(adj_dev, dev_list); 8725 8726 if (!adj) { 8727 pr_err("Adjacency does not exist for device %s from %s\n", 8728 dev->name, adj_dev->name); 8729 WARN_ON(1); 8730 return; 8731 } 8732 8733 if (adj->ref_nr > ref_nr) { 8734 pr_debug("adjacency: %s to %s ref_nr - %d = %d\n", 8735 dev->name, adj_dev->name, ref_nr, 8736 adj->ref_nr - ref_nr); 8737 adj->ref_nr -= ref_nr; 8738 return; 8739 } 8740 8741 if (adj->master) 8742 sysfs_remove_link(&(dev->dev.kobj), "master"); 8743 8744 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) 8745 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list); 8746 8747 list_del_rcu(&adj->list); 8748 pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n", 8749 adj_dev->name, dev->name, adj_dev->name); 8750 netdev_put(adj_dev, &adj->dev_tracker); 8751 kfree_rcu(adj, rcu); 8752 } 8753 8754 static int __netdev_adjacent_dev_link_lists(struct net_device *dev, 8755 struct net_device *upper_dev, 8756 struct list_head *up_list, 8757 struct list_head *down_list, 8758 void *private, bool master) 8759 { 8760 int ret; 8761 8762 ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list, 8763 private, master); 8764 if (ret) 8765 return ret; 8766 8767 ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list, 8768 private, false); 8769 if (ret) { 8770 __netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list); 8771 return ret; 8772 } 8773 8774 return 0; 8775 } 8776 8777 static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev, 8778 struct net_device *upper_dev, 8779 u16 ref_nr, 8780 struct list_head *up_list, 8781 struct list_head *down_list) 8782 { 8783 __netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list); 8784 __netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list); 8785 } 8786 8787 static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev, 8788 struct net_device *upper_dev, 8789 void *private, bool master) 8790 { 8791 return __netdev_adjacent_dev_link_lists(dev, upper_dev, 8792 &dev->adj_list.upper, 8793 &upper_dev->adj_list.lower, 8794 private, master); 8795 } 8796 8797 static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev, 8798 struct net_device *upper_dev) 8799 { 8800 __netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1, 8801 &dev->adj_list.upper, 8802 &upper_dev->adj_list.lower); 8803 } 8804 8805 static int __netdev_upper_dev_link(struct net_device *dev, 8806 struct net_device *upper_dev, bool master, 8807 void *upper_priv, void *upper_info, 8808 struct netdev_nested_priv *priv, 8809 struct netlink_ext_ack *extack) 8810 { 8811 struct netdev_notifier_changeupper_info changeupper_info = { 8812 .info = { 8813 .dev = dev, 8814 .extack = extack, 8815 }, 8816 .upper_dev = upper_dev, 8817 .master = master, 8818 .linking = true, 8819 .upper_info = upper_info, 8820 }; 8821 struct net_device *master_dev; 8822 int ret = 0; 8823 8824 ASSERT_RTNL(); 8825 8826 if (dev == upper_dev) 8827 return -EBUSY; 8828 8829 /* To prevent loops, check if dev is not upper device to upper_dev. */ 8830 if (__netdev_has_upper_dev(upper_dev, dev)) 8831 return -EBUSY; 8832 8833 if ((dev->lower_level + upper_dev->upper_level) > MAX_NEST_DEV) 8834 return -EMLINK; 8835 8836 if (!master) { 8837 if (__netdev_has_upper_dev(dev, upper_dev)) 8838 return -EEXIST; 8839 } else { 8840 master_dev = __netdev_master_upper_dev_get(dev); 8841 if (master_dev) 8842 return master_dev == upper_dev ? -EEXIST : -EBUSY; 8843 } 8844 8845 ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER, 8846 &changeupper_info.info); 8847 ret = notifier_to_errno(ret); 8848 if (ret) 8849 return ret; 8850 8851 ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv, 8852 master); 8853 if (ret) 8854 return ret; 8855 8856 ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER, 8857 &changeupper_info.info); 8858 ret = notifier_to_errno(ret); 8859 if (ret) 8860 goto rollback; 8861 8862 __netdev_update_upper_level(dev, NULL); 8863 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL); 8864 8865 __netdev_update_lower_level(upper_dev, priv); 8866 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level, 8867 priv); 8868 8869 return 0; 8870 8871 rollback: 8872 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev); 8873 8874 return ret; 8875 } 8876 8877 /** 8878 * netdev_upper_dev_link - Add a link to the upper device 8879 * @dev: device 8880 * @upper_dev: new upper device 8881 * @extack: netlink extended ack 8882 * 8883 * Adds a link to device which is upper to this one. The caller must hold 8884 * the RTNL lock. On a failure a negative errno code is returned. 8885 * On success the reference counts are adjusted and the function 8886 * returns zero. 8887 */ 8888 int netdev_upper_dev_link(struct net_device *dev, 8889 struct net_device *upper_dev, 8890 struct netlink_ext_ack *extack) 8891 { 8892 struct netdev_nested_priv priv = { 8893 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO, 8894 .data = NULL, 8895 }; 8896 8897 return __netdev_upper_dev_link(dev, upper_dev, false, 8898 NULL, NULL, &priv, extack); 8899 } 8900 EXPORT_SYMBOL(netdev_upper_dev_link); 8901 8902 /** 8903 * netdev_master_upper_dev_link - Add a master link to the upper device 8904 * @dev: device 8905 * @upper_dev: new upper device 8906 * @upper_priv: upper device private 8907 * @upper_info: upper info to be passed down via notifier 8908 * @extack: netlink extended ack 8909 * 8910 * Adds a link to device which is upper to this one. In this case, only 8911 * one master upper device can be linked, although other non-master devices 8912 * might be linked as well. The caller must hold the RTNL lock. 8913 * On a failure a negative errno code is returned. On success the reference 8914 * counts are adjusted and the function returns zero. 8915 */ 8916 int netdev_master_upper_dev_link(struct net_device *dev, 8917 struct net_device *upper_dev, 8918 void *upper_priv, void *upper_info, 8919 struct netlink_ext_ack *extack) 8920 { 8921 struct netdev_nested_priv priv = { 8922 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO, 8923 .data = NULL, 8924 }; 8925 8926 return __netdev_upper_dev_link(dev, upper_dev, true, 8927 upper_priv, upper_info, &priv, extack); 8928 } 8929 EXPORT_SYMBOL(netdev_master_upper_dev_link); 8930 8931 static void __netdev_upper_dev_unlink(struct net_device *dev, 8932 struct net_device *upper_dev, 8933 struct netdev_nested_priv *priv) 8934 { 8935 struct netdev_notifier_changeupper_info changeupper_info = { 8936 .info = { 8937 .dev = dev, 8938 }, 8939 .upper_dev = upper_dev, 8940 .linking = false, 8941 }; 8942 8943 ASSERT_RTNL(); 8944 8945 changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev; 8946 8947 call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER, 8948 &changeupper_info.info); 8949 8950 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev); 8951 8952 call_netdevice_notifiers_info(NETDEV_CHANGEUPPER, 8953 &changeupper_info.info); 8954 8955 __netdev_update_upper_level(dev, NULL); 8956 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL); 8957 8958 __netdev_update_lower_level(upper_dev, priv); 8959 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level, 8960 priv); 8961 } 8962 8963 /** 8964 * netdev_upper_dev_unlink - Removes a link to upper device 8965 * @dev: device 8966 * @upper_dev: new upper device 8967 * 8968 * Removes a link to device which is upper to this one. The caller must hold 8969 * the RTNL lock. 8970 */ 8971 void netdev_upper_dev_unlink(struct net_device *dev, 8972 struct net_device *upper_dev) 8973 { 8974 struct netdev_nested_priv priv = { 8975 .flags = NESTED_SYNC_TODO, 8976 .data = NULL, 8977 }; 8978 8979 __netdev_upper_dev_unlink(dev, upper_dev, &priv); 8980 } 8981 EXPORT_SYMBOL(netdev_upper_dev_unlink); 8982 8983 static void __netdev_adjacent_dev_set(struct net_device *upper_dev, 8984 struct net_device *lower_dev, 8985 bool val) 8986 { 8987 struct netdev_adjacent *adj; 8988 8989 adj = __netdev_find_adj(lower_dev, &upper_dev->adj_list.lower); 8990 if (adj) 8991 adj->ignore = val; 8992 8993 adj = __netdev_find_adj(upper_dev, &lower_dev->adj_list.upper); 8994 if (adj) 8995 adj->ignore = val; 8996 } 8997 8998 static void netdev_adjacent_dev_disable(struct net_device *upper_dev, 8999 struct net_device *lower_dev) 9000 { 9001 __netdev_adjacent_dev_set(upper_dev, lower_dev, true); 9002 } 9003 9004 static void netdev_adjacent_dev_enable(struct net_device *upper_dev, 9005 struct net_device *lower_dev) 9006 { 9007 __netdev_adjacent_dev_set(upper_dev, lower_dev, false); 9008 } 9009 9010 int netdev_adjacent_change_prepare(struct net_device *old_dev, 9011 struct net_device *new_dev, 9012 struct net_device *dev, 9013 struct netlink_ext_ack *extack) 9014 { 9015 struct netdev_nested_priv priv = { 9016 .flags = 0, 9017 .data = NULL, 9018 }; 9019 int err; 9020 9021 if (!new_dev) 9022 return 0; 9023 9024 if (old_dev && new_dev != old_dev) 9025 netdev_adjacent_dev_disable(dev, old_dev); 9026 err = __netdev_upper_dev_link(new_dev, dev, false, NULL, NULL, &priv, 9027 extack); 9028 if (err) { 9029 if (old_dev && new_dev != old_dev) 9030 netdev_adjacent_dev_enable(dev, old_dev); 9031 return err; 9032 } 9033 9034 return 0; 9035 } 9036 EXPORT_SYMBOL(netdev_adjacent_change_prepare); 9037 9038 void netdev_adjacent_change_commit(struct net_device *old_dev, 9039 struct net_device *new_dev, 9040 struct net_device *dev) 9041 { 9042 struct netdev_nested_priv priv = { 9043 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO, 9044 .data = NULL, 9045 }; 9046 9047 if (!new_dev || !old_dev) 9048 return; 9049 9050 if (new_dev == old_dev) 9051 return; 9052 9053 netdev_adjacent_dev_enable(dev, old_dev); 9054 __netdev_upper_dev_unlink(old_dev, dev, &priv); 9055 } 9056 EXPORT_SYMBOL(netdev_adjacent_change_commit); 9057 9058 void netdev_adjacent_change_abort(struct net_device *old_dev, 9059 struct net_device *new_dev, 9060 struct net_device *dev) 9061 { 9062 struct netdev_nested_priv priv = { 9063 .flags = 0, 9064 .data = NULL, 9065 }; 9066 9067 if (!new_dev) 9068 return; 9069 9070 if (old_dev && new_dev != old_dev) 9071 netdev_adjacent_dev_enable(dev, old_dev); 9072 9073 __netdev_upper_dev_unlink(new_dev, dev, &priv); 9074 } 9075 EXPORT_SYMBOL(netdev_adjacent_change_abort); 9076 9077 /** 9078 * netdev_bonding_info_change - Dispatch event about slave change 9079 * @dev: device 9080 * @bonding_info: info to dispatch 9081 * 9082 * Send NETDEV_BONDING_INFO to netdev notifiers with info. 9083 * The caller must hold the RTNL lock. 9084 */ 9085 void netdev_bonding_info_change(struct net_device *dev, 9086 struct netdev_bonding_info *bonding_info) 9087 { 9088 struct netdev_notifier_bonding_info info = { 9089 .info.dev = dev, 9090 }; 9091 9092 memcpy(&info.bonding_info, bonding_info, 9093 sizeof(struct netdev_bonding_info)); 9094 call_netdevice_notifiers_info(NETDEV_BONDING_INFO, 9095 &info.info); 9096 } 9097 EXPORT_SYMBOL(netdev_bonding_info_change); 9098 9099 static int netdev_offload_xstats_enable_l3(struct net_device *dev, 9100 struct netlink_ext_ack *extack) 9101 { 9102 struct netdev_notifier_offload_xstats_info info = { 9103 .info.dev = dev, 9104 .info.extack = extack, 9105 .type = NETDEV_OFFLOAD_XSTATS_TYPE_L3, 9106 }; 9107 int err; 9108 int rc; 9109 9110 dev->offload_xstats_l3 = kzalloc(sizeof(*dev->offload_xstats_l3), 9111 GFP_KERNEL); 9112 if (!dev->offload_xstats_l3) 9113 return -ENOMEM; 9114 9115 rc = call_netdevice_notifiers_info_robust(NETDEV_OFFLOAD_XSTATS_ENABLE, 9116 NETDEV_OFFLOAD_XSTATS_DISABLE, 9117 &info.info); 9118 err = notifier_to_errno(rc); 9119 if (err) 9120 goto free_stats; 9121 9122 return 0; 9123 9124 free_stats: 9125 kfree(dev->offload_xstats_l3); 9126 dev->offload_xstats_l3 = NULL; 9127 return err; 9128 } 9129 9130 int netdev_offload_xstats_enable(struct net_device *dev, 9131 enum netdev_offload_xstats_type type, 9132 struct netlink_ext_ack *extack) 9133 { 9134 ASSERT_RTNL(); 9135 9136 if (netdev_offload_xstats_enabled(dev, type)) 9137 return -EALREADY; 9138 9139 switch (type) { 9140 case NETDEV_OFFLOAD_XSTATS_TYPE_L3: 9141 return netdev_offload_xstats_enable_l3(dev, extack); 9142 } 9143 9144 WARN_ON(1); 9145 return -EINVAL; 9146 } 9147 EXPORT_SYMBOL(netdev_offload_xstats_enable); 9148 9149 static void netdev_offload_xstats_disable_l3(struct net_device *dev) 9150 { 9151 struct netdev_notifier_offload_xstats_info info = { 9152 .info.dev = dev, 9153 .type = NETDEV_OFFLOAD_XSTATS_TYPE_L3, 9154 }; 9155 9156 call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_DISABLE, 9157 &info.info); 9158 kfree(dev->offload_xstats_l3); 9159 dev->offload_xstats_l3 = NULL; 9160 } 9161 9162 int netdev_offload_xstats_disable(struct net_device *dev, 9163 enum netdev_offload_xstats_type type) 9164 { 9165 ASSERT_RTNL(); 9166 9167 if (!netdev_offload_xstats_enabled(dev, type)) 9168 return -EALREADY; 9169 9170 switch (type) { 9171 case NETDEV_OFFLOAD_XSTATS_TYPE_L3: 9172 netdev_offload_xstats_disable_l3(dev); 9173 return 0; 9174 } 9175 9176 WARN_ON(1); 9177 return -EINVAL; 9178 } 9179 EXPORT_SYMBOL(netdev_offload_xstats_disable); 9180 9181 static void netdev_offload_xstats_disable_all(struct net_device *dev) 9182 { 9183 netdev_offload_xstats_disable(dev, NETDEV_OFFLOAD_XSTATS_TYPE_L3); 9184 } 9185 9186 static struct rtnl_hw_stats64 * 9187 netdev_offload_xstats_get_ptr(const struct net_device *dev, 9188 enum netdev_offload_xstats_type type) 9189 { 9190 switch (type) { 9191 case NETDEV_OFFLOAD_XSTATS_TYPE_L3: 9192 return dev->offload_xstats_l3; 9193 } 9194 9195 WARN_ON(1); 9196 return NULL; 9197 } 9198 9199 bool netdev_offload_xstats_enabled(const struct net_device *dev, 9200 enum netdev_offload_xstats_type type) 9201 { 9202 ASSERT_RTNL(); 9203 9204 return netdev_offload_xstats_get_ptr(dev, type); 9205 } 9206 EXPORT_SYMBOL(netdev_offload_xstats_enabled); 9207 9208 struct netdev_notifier_offload_xstats_ru { 9209 bool used; 9210 }; 9211 9212 struct netdev_notifier_offload_xstats_rd { 9213 struct rtnl_hw_stats64 stats; 9214 bool used; 9215 }; 9216 9217 static void netdev_hw_stats64_add(struct rtnl_hw_stats64 *dest, 9218 const struct rtnl_hw_stats64 *src) 9219 { 9220 dest->rx_packets += src->rx_packets; 9221 dest->tx_packets += src->tx_packets; 9222 dest->rx_bytes += src->rx_bytes; 9223 dest->tx_bytes += src->tx_bytes; 9224 dest->rx_errors += src->rx_errors; 9225 dest->tx_errors += src->tx_errors; 9226 dest->rx_dropped += src->rx_dropped; 9227 dest->tx_dropped += src->tx_dropped; 9228 dest->multicast += src->multicast; 9229 } 9230 9231 static int netdev_offload_xstats_get_used(struct net_device *dev, 9232 enum netdev_offload_xstats_type type, 9233 bool *p_used, 9234 struct netlink_ext_ack *extack) 9235 { 9236 struct netdev_notifier_offload_xstats_ru report_used = {}; 9237 struct netdev_notifier_offload_xstats_info info = { 9238 .info.dev = dev, 9239 .info.extack = extack, 9240 .type = type, 9241 .report_used = &report_used, 9242 }; 9243 int rc; 9244 9245 WARN_ON(!netdev_offload_xstats_enabled(dev, type)); 9246 rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_USED, 9247 &info.info); 9248 *p_used = report_used.used; 9249 return notifier_to_errno(rc); 9250 } 9251 9252 static int netdev_offload_xstats_get_stats(struct net_device *dev, 9253 enum netdev_offload_xstats_type type, 9254 struct rtnl_hw_stats64 *p_stats, 9255 bool *p_used, 9256 struct netlink_ext_ack *extack) 9257 { 9258 struct netdev_notifier_offload_xstats_rd report_delta = {}; 9259 struct netdev_notifier_offload_xstats_info info = { 9260 .info.dev = dev, 9261 .info.extack = extack, 9262 .type = type, 9263 .report_delta = &report_delta, 9264 }; 9265 struct rtnl_hw_stats64 *stats; 9266 int rc; 9267 9268 stats = netdev_offload_xstats_get_ptr(dev, type); 9269 if (WARN_ON(!stats)) 9270 return -EINVAL; 9271 9272 rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_DELTA, 9273 &info.info); 9274 9275 /* Cache whatever we got, even if there was an error, otherwise the 9276 * successful stats retrievals would get lost. 9277 */ 9278 netdev_hw_stats64_add(stats, &report_delta.stats); 9279 9280 if (p_stats) 9281 *p_stats = *stats; 9282 *p_used = report_delta.used; 9283 9284 return notifier_to_errno(rc); 9285 } 9286 9287 int netdev_offload_xstats_get(struct net_device *dev, 9288 enum netdev_offload_xstats_type type, 9289 struct rtnl_hw_stats64 *p_stats, bool *p_used, 9290 struct netlink_ext_ack *extack) 9291 { 9292 ASSERT_RTNL(); 9293 9294 if (p_stats) 9295 return netdev_offload_xstats_get_stats(dev, type, p_stats, 9296 p_used, extack); 9297 else 9298 return netdev_offload_xstats_get_used(dev, type, p_used, 9299 extack); 9300 } 9301 EXPORT_SYMBOL(netdev_offload_xstats_get); 9302 9303 void 9304 netdev_offload_xstats_report_delta(struct netdev_notifier_offload_xstats_rd *report_delta, 9305 const struct rtnl_hw_stats64 *stats) 9306 { 9307 report_delta->used = true; 9308 netdev_hw_stats64_add(&report_delta->stats, stats); 9309 } 9310 EXPORT_SYMBOL(netdev_offload_xstats_report_delta); 9311 9312 void 9313 netdev_offload_xstats_report_used(struct netdev_notifier_offload_xstats_ru *report_used) 9314 { 9315 report_used->used = true; 9316 } 9317 EXPORT_SYMBOL(netdev_offload_xstats_report_used); 9318 9319 void netdev_offload_xstats_push_delta(struct net_device *dev, 9320 enum netdev_offload_xstats_type type, 9321 const struct rtnl_hw_stats64 *p_stats) 9322 { 9323 struct rtnl_hw_stats64 *stats; 9324 9325 ASSERT_RTNL(); 9326 9327 stats = netdev_offload_xstats_get_ptr(dev, type); 9328 if (WARN_ON(!stats)) 9329 return; 9330 9331 netdev_hw_stats64_add(stats, p_stats); 9332 } 9333 EXPORT_SYMBOL(netdev_offload_xstats_push_delta); 9334 9335 /** 9336 * netdev_get_xmit_slave - Get the xmit slave of master device 9337 * @dev: device 9338 * @skb: The packet 9339 * @all_slaves: assume all the slaves are active 9340 * 9341 * The reference counters are not incremented so the caller must be 9342 * careful with locks. The caller must hold RCU lock. 9343 * %NULL is returned if no slave is found. 9344 */ 9345 9346 struct net_device *netdev_get_xmit_slave(struct net_device *dev, 9347 struct sk_buff *skb, 9348 bool all_slaves) 9349 { 9350 const struct net_device_ops *ops = dev->netdev_ops; 9351 9352 if (!ops->ndo_get_xmit_slave) 9353 return NULL; 9354 return ops->ndo_get_xmit_slave(dev, skb, all_slaves); 9355 } 9356 EXPORT_SYMBOL(netdev_get_xmit_slave); 9357 9358 static struct net_device *netdev_sk_get_lower_dev(struct net_device *dev, 9359 struct sock *sk) 9360 { 9361 const struct net_device_ops *ops = dev->netdev_ops; 9362 9363 if (!ops->ndo_sk_get_lower_dev) 9364 return NULL; 9365 return ops->ndo_sk_get_lower_dev(dev, sk); 9366 } 9367 9368 /** 9369 * netdev_sk_get_lowest_dev - Get the lowest device in chain given device and socket 9370 * @dev: device 9371 * @sk: the socket 9372 * 9373 * %NULL is returned if no lower device is found. 9374 */ 9375 9376 struct net_device *netdev_sk_get_lowest_dev(struct net_device *dev, 9377 struct sock *sk) 9378 { 9379 struct net_device *lower; 9380 9381 lower = netdev_sk_get_lower_dev(dev, sk); 9382 while (lower) { 9383 dev = lower; 9384 lower = netdev_sk_get_lower_dev(dev, sk); 9385 } 9386 9387 return dev; 9388 } 9389 EXPORT_SYMBOL(netdev_sk_get_lowest_dev); 9390 9391 static void netdev_adjacent_add_links(struct net_device *dev) 9392 { 9393 struct netdev_adjacent *iter; 9394 9395 struct net *net = dev_net(dev); 9396 9397 list_for_each_entry(iter, &dev->adj_list.upper, list) { 9398 if (!net_eq(net, dev_net(iter->dev))) 9399 continue; 9400 netdev_adjacent_sysfs_add(iter->dev, dev, 9401 &iter->dev->adj_list.lower); 9402 netdev_adjacent_sysfs_add(dev, iter->dev, 9403 &dev->adj_list.upper); 9404 } 9405 9406 list_for_each_entry(iter, &dev->adj_list.lower, list) { 9407 if (!net_eq(net, dev_net(iter->dev))) 9408 continue; 9409 netdev_adjacent_sysfs_add(iter->dev, dev, 9410 &iter->dev->adj_list.upper); 9411 netdev_adjacent_sysfs_add(dev, iter->dev, 9412 &dev->adj_list.lower); 9413 } 9414 } 9415 9416 static void netdev_adjacent_del_links(struct net_device *dev) 9417 { 9418 struct netdev_adjacent *iter; 9419 9420 struct net *net = dev_net(dev); 9421 9422 list_for_each_entry(iter, &dev->adj_list.upper, list) { 9423 if (!net_eq(net, dev_net(iter->dev))) 9424 continue; 9425 netdev_adjacent_sysfs_del(iter->dev, dev->name, 9426 &iter->dev->adj_list.lower); 9427 netdev_adjacent_sysfs_del(dev, iter->dev->name, 9428 &dev->adj_list.upper); 9429 } 9430 9431 list_for_each_entry(iter, &dev->adj_list.lower, list) { 9432 if (!net_eq(net, dev_net(iter->dev))) 9433 continue; 9434 netdev_adjacent_sysfs_del(iter->dev, dev->name, 9435 &iter->dev->adj_list.upper); 9436 netdev_adjacent_sysfs_del(dev, iter->dev->name, 9437 &dev->adj_list.lower); 9438 } 9439 } 9440 9441 void netdev_adjacent_rename_links(struct net_device *dev, char *oldname) 9442 { 9443 struct netdev_adjacent *iter; 9444 9445 struct net *net = dev_net(dev); 9446 9447 list_for_each_entry(iter, &dev->adj_list.upper, list) { 9448 if (!net_eq(net, dev_net(iter->dev))) 9449 continue; 9450 netdev_adjacent_sysfs_del(iter->dev, oldname, 9451 &iter->dev->adj_list.lower); 9452 netdev_adjacent_sysfs_add(iter->dev, dev, 9453 &iter->dev->adj_list.lower); 9454 } 9455 9456 list_for_each_entry(iter, &dev->adj_list.lower, list) { 9457 if (!net_eq(net, dev_net(iter->dev))) 9458 continue; 9459 netdev_adjacent_sysfs_del(iter->dev, oldname, 9460 &iter->dev->adj_list.upper); 9461 netdev_adjacent_sysfs_add(iter->dev, dev, 9462 &iter->dev->adj_list.upper); 9463 } 9464 } 9465 9466 void *netdev_lower_dev_get_private(struct net_device *dev, 9467 struct net_device *lower_dev) 9468 { 9469 struct netdev_adjacent *lower; 9470 9471 if (!lower_dev) 9472 return NULL; 9473 lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower); 9474 if (!lower) 9475 return NULL; 9476 9477 return lower->private; 9478 } 9479 EXPORT_SYMBOL(netdev_lower_dev_get_private); 9480 9481 9482 /** 9483 * netdev_lower_state_changed - Dispatch event about lower device state change 9484 * @lower_dev: device 9485 * @lower_state_info: state to dispatch 9486 * 9487 * Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info. 9488 * The caller must hold the RTNL lock. 9489 */ 9490 void netdev_lower_state_changed(struct net_device *lower_dev, 9491 void *lower_state_info) 9492 { 9493 struct netdev_notifier_changelowerstate_info changelowerstate_info = { 9494 .info.dev = lower_dev, 9495 }; 9496 9497 ASSERT_RTNL(); 9498 changelowerstate_info.lower_state_info = lower_state_info; 9499 call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE, 9500 &changelowerstate_info.info); 9501 } 9502 EXPORT_SYMBOL(netdev_lower_state_changed); 9503 9504 static void dev_change_rx_flags(struct net_device *dev, int flags) 9505 { 9506 const struct net_device_ops *ops = dev->netdev_ops; 9507 9508 if (ops->ndo_change_rx_flags) 9509 ops->ndo_change_rx_flags(dev, flags); 9510 } 9511 9512 static int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify) 9513 { 9514 unsigned int old_flags = dev->flags; 9515 unsigned int promiscuity, flags; 9516 kuid_t uid; 9517 kgid_t gid; 9518 9519 ASSERT_RTNL(); 9520 9521 promiscuity = dev->promiscuity + inc; 9522 if (promiscuity == 0) { 9523 /* 9524 * Avoid overflow. 9525 * If inc causes overflow, untouch promisc and return error. 9526 */ 9527 if (unlikely(inc > 0)) { 9528 netdev_warn(dev, "promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n"); 9529 return -EOVERFLOW; 9530 } 9531 flags = old_flags & ~IFF_PROMISC; 9532 } else { 9533 flags = old_flags | IFF_PROMISC; 9534 } 9535 WRITE_ONCE(dev->promiscuity, promiscuity); 9536 if (flags != old_flags) { 9537 WRITE_ONCE(dev->flags, flags); 9538 netdev_info(dev, "%s promiscuous mode\n", 9539 dev->flags & IFF_PROMISC ? "entered" : "left"); 9540 if (audit_enabled) { 9541 current_uid_gid(&uid, &gid); 9542 audit_log(audit_context(), GFP_ATOMIC, 9543 AUDIT_ANOM_PROMISCUOUS, 9544 "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u", 9545 dev->name, (dev->flags & IFF_PROMISC), 9546 (old_flags & IFF_PROMISC), 9547 from_kuid(&init_user_ns, audit_get_loginuid(current)), 9548 from_kuid(&init_user_ns, uid), 9549 from_kgid(&init_user_ns, gid), 9550 audit_get_sessionid(current)); 9551 } 9552 9553 dev_change_rx_flags(dev, IFF_PROMISC); 9554 } 9555 if (notify) { 9556 /* The ops lock is only required to ensure consistent locking 9557 * for `NETDEV_CHANGE` notifiers. This function is sometimes 9558 * called without the lock, even for devices that are ops 9559 * locked, such as in `dev_uc_sync_multiple` when using 9560 * bonding or teaming. 9561 */ 9562 netdev_ops_assert_locked(dev); 9563 __dev_notify_flags(dev, old_flags, IFF_PROMISC, 0, NULL); 9564 } 9565 return 0; 9566 } 9567 9568 int netif_set_promiscuity(struct net_device *dev, int inc) 9569 { 9570 unsigned int old_flags = dev->flags; 9571 int err; 9572 9573 err = __dev_set_promiscuity(dev, inc, true); 9574 if (err < 0) 9575 return err; 9576 if (dev->flags != old_flags) 9577 dev_set_rx_mode(dev); 9578 return err; 9579 } 9580 9581 int netif_set_allmulti(struct net_device *dev, int inc, bool notify) 9582 { 9583 unsigned int old_flags = dev->flags, old_gflags = dev->gflags; 9584 unsigned int allmulti, flags; 9585 9586 ASSERT_RTNL(); 9587 9588 allmulti = dev->allmulti + inc; 9589 if (allmulti == 0) { 9590 /* 9591 * Avoid overflow. 9592 * If inc causes overflow, untouch allmulti and return error. 9593 */ 9594 if (unlikely(inc > 0)) { 9595 netdev_warn(dev, "allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n"); 9596 return -EOVERFLOW; 9597 } 9598 flags = old_flags & ~IFF_ALLMULTI; 9599 } else { 9600 flags = old_flags | IFF_ALLMULTI; 9601 } 9602 WRITE_ONCE(dev->allmulti, allmulti); 9603 if (flags != old_flags) { 9604 WRITE_ONCE(dev->flags, flags); 9605 netdev_info(dev, "%s allmulticast mode\n", 9606 dev->flags & IFF_ALLMULTI ? "entered" : "left"); 9607 dev_change_rx_flags(dev, IFF_ALLMULTI); 9608 dev_set_rx_mode(dev); 9609 if (notify) 9610 __dev_notify_flags(dev, old_flags, 9611 dev->gflags ^ old_gflags, 0, NULL); 9612 } 9613 return 0; 9614 } 9615 9616 /* 9617 * Upload unicast and multicast address lists to device and 9618 * configure RX filtering. When the device doesn't support unicast 9619 * filtering it is put in promiscuous mode while unicast addresses 9620 * are present. 9621 */ 9622 void __dev_set_rx_mode(struct net_device *dev) 9623 { 9624 const struct net_device_ops *ops = dev->netdev_ops; 9625 9626 /* dev_open will call this function so the list will stay sane. */ 9627 if (!(dev->flags&IFF_UP)) 9628 return; 9629 9630 if (!netif_device_present(dev)) 9631 return; 9632 9633 if (!(dev->priv_flags & IFF_UNICAST_FLT)) { 9634 /* Unicast addresses changes may only happen under the rtnl, 9635 * therefore calling __dev_set_promiscuity here is safe. 9636 */ 9637 if (!netdev_uc_empty(dev) && !dev->uc_promisc) { 9638 __dev_set_promiscuity(dev, 1, false); 9639 dev->uc_promisc = true; 9640 } else if (netdev_uc_empty(dev) && dev->uc_promisc) { 9641 __dev_set_promiscuity(dev, -1, false); 9642 dev->uc_promisc = false; 9643 } 9644 } 9645 9646 if (ops->ndo_set_rx_mode) 9647 ops->ndo_set_rx_mode(dev); 9648 } 9649 9650 void dev_set_rx_mode(struct net_device *dev) 9651 { 9652 netif_addr_lock_bh(dev); 9653 __dev_set_rx_mode(dev); 9654 netif_addr_unlock_bh(dev); 9655 } 9656 9657 /** 9658 * netif_get_flags() - get flags reported to userspace 9659 * @dev: device 9660 * 9661 * Get the combination of flag bits exported through APIs to userspace. 9662 */ 9663 unsigned int netif_get_flags(const struct net_device *dev) 9664 { 9665 unsigned int flags; 9666 9667 flags = (READ_ONCE(dev->flags) & ~(IFF_PROMISC | 9668 IFF_ALLMULTI | 9669 IFF_RUNNING | 9670 IFF_LOWER_UP | 9671 IFF_DORMANT)) | 9672 (READ_ONCE(dev->gflags) & (IFF_PROMISC | 9673 IFF_ALLMULTI)); 9674 9675 if (netif_running(dev)) { 9676 if (netif_oper_up(dev)) 9677 flags |= IFF_RUNNING; 9678 if (netif_carrier_ok(dev)) 9679 flags |= IFF_LOWER_UP; 9680 if (netif_dormant(dev)) 9681 flags |= IFF_DORMANT; 9682 } 9683 9684 return flags; 9685 } 9686 EXPORT_SYMBOL(netif_get_flags); 9687 9688 int __dev_change_flags(struct net_device *dev, unsigned int flags, 9689 struct netlink_ext_ack *extack) 9690 { 9691 unsigned int old_flags = dev->flags; 9692 int ret; 9693 9694 ASSERT_RTNL(); 9695 9696 /* 9697 * Set the flags on our device. 9698 */ 9699 9700 dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP | 9701 IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL | 9702 IFF_AUTOMEDIA)) | 9703 (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC | 9704 IFF_ALLMULTI)); 9705 9706 /* 9707 * Load in the correct multicast list now the flags have changed. 9708 */ 9709 9710 if ((old_flags ^ flags) & IFF_MULTICAST) 9711 dev_change_rx_flags(dev, IFF_MULTICAST); 9712 9713 dev_set_rx_mode(dev); 9714 9715 /* 9716 * Have we downed the interface. We handle IFF_UP ourselves 9717 * according to user attempts to set it, rather than blindly 9718 * setting it. 9719 */ 9720 9721 ret = 0; 9722 if ((old_flags ^ flags) & IFF_UP) { 9723 if (old_flags & IFF_UP) 9724 __dev_close(dev); 9725 else 9726 ret = __dev_open(dev, extack); 9727 } 9728 9729 if ((flags ^ dev->gflags) & IFF_PROMISC) { 9730 int inc = (flags & IFF_PROMISC) ? 1 : -1; 9731 old_flags = dev->flags; 9732 9733 dev->gflags ^= IFF_PROMISC; 9734 9735 if (__dev_set_promiscuity(dev, inc, false) >= 0) 9736 if (dev->flags != old_flags) 9737 dev_set_rx_mode(dev); 9738 } 9739 9740 /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI 9741 * is important. Some (broken) drivers set IFF_PROMISC, when 9742 * IFF_ALLMULTI is requested not asking us and not reporting. 9743 */ 9744 if ((flags ^ dev->gflags) & IFF_ALLMULTI) { 9745 int inc = (flags & IFF_ALLMULTI) ? 1 : -1; 9746 9747 dev->gflags ^= IFF_ALLMULTI; 9748 netif_set_allmulti(dev, inc, false); 9749 } 9750 9751 return ret; 9752 } 9753 9754 void __dev_notify_flags(struct net_device *dev, unsigned int old_flags, 9755 unsigned int gchanges, u32 portid, 9756 const struct nlmsghdr *nlh) 9757 { 9758 unsigned int changes = dev->flags ^ old_flags; 9759 9760 if (gchanges) 9761 rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC, portid, nlh); 9762 9763 if (changes & IFF_UP) { 9764 if (dev->flags & IFF_UP) 9765 call_netdevice_notifiers(NETDEV_UP, dev); 9766 else 9767 call_netdevice_notifiers(NETDEV_DOWN, dev); 9768 } 9769 9770 if (dev->flags & IFF_UP && 9771 (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) { 9772 struct netdev_notifier_change_info change_info = { 9773 .info = { 9774 .dev = dev, 9775 }, 9776 .flags_changed = changes, 9777 }; 9778 9779 call_netdevice_notifiers_info(NETDEV_CHANGE, &change_info.info); 9780 } 9781 } 9782 9783 int netif_change_flags(struct net_device *dev, unsigned int flags, 9784 struct netlink_ext_ack *extack) 9785 { 9786 int ret; 9787 unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags; 9788 9789 ret = __dev_change_flags(dev, flags, extack); 9790 if (ret < 0) 9791 return ret; 9792 9793 changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags); 9794 __dev_notify_flags(dev, old_flags, changes, 0, NULL); 9795 return ret; 9796 } 9797 9798 int __netif_set_mtu(struct net_device *dev, int new_mtu) 9799 { 9800 const struct net_device_ops *ops = dev->netdev_ops; 9801 9802 if (ops->ndo_change_mtu) 9803 return ops->ndo_change_mtu(dev, new_mtu); 9804 9805 /* Pairs with all the lockless reads of dev->mtu in the stack */ 9806 WRITE_ONCE(dev->mtu, new_mtu); 9807 return 0; 9808 } 9809 EXPORT_SYMBOL_NS_GPL(__netif_set_mtu, "NETDEV_INTERNAL"); 9810 9811 int dev_validate_mtu(struct net_device *dev, int new_mtu, 9812 struct netlink_ext_ack *extack) 9813 { 9814 /* MTU must be positive, and in range */ 9815 if (new_mtu < 0 || new_mtu < dev->min_mtu) { 9816 NL_SET_ERR_MSG(extack, "mtu less than device minimum"); 9817 return -EINVAL; 9818 } 9819 9820 if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) { 9821 NL_SET_ERR_MSG(extack, "mtu greater than device maximum"); 9822 return -EINVAL; 9823 } 9824 return 0; 9825 } 9826 9827 /** 9828 * netif_set_mtu_ext() - Change maximum transfer unit 9829 * @dev: device 9830 * @new_mtu: new transfer unit 9831 * @extack: netlink extended ack 9832 * 9833 * Change the maximum transfer size of the network device. 9834 * 9835 * Return: 0 on success, -errno on failure. 9836 */ 9837 int netif_set_mtu_ext(struct net_device *dev, int new_mtu, 9838 struct netlink_ext_ack *extack) 9839 { 9840 int err, orig_mtu; 9841 9842 netdev_ops_assert_locked(dev); 9843 9844 if (new_mtu == dev->mtu) 9845 return 0; 9846 9847 err = dev_validate_mtu(dev, new_mtu, extack); 9848 if (err) 9849 return err; 9850 9851 if (!netif_device_present(dev)) 9852 return -ENODEV; 9853 9854 err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev); 9855 err = notifier_to_errno(err); 9856 if (err) 9857 return err; 9858 9859 orig_mtu = dev->mtu; 9860 err = __netif_set_mtu(dev, new_mtu); 9861 9862 if (!err) { 9863 err = call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev, 9864 orig_mtu); 9865 err = notifier_to_errno(err); 9866 if (err) { 9867 /* setting mtu back and notifying everyone again, 9868 * so that they have a chance to revert changes. 9869 */ 9870 __netif_set_mtu(dev, orig_mtu); 9871 call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev, 9872 new_mtu); 9873 } 9874 } 9875 return err; 9876 } 9877 9878 int netif_set_mtu(struct net_device *dev, int new_mtu) 9879 { 9880 struct netlink_ext_ack extack; 9881 int err; 9882 9883 memset(&extack, 0, sizeof(extack)); 9884 err = netif_set_mtu_ext(dev, new_mtu, &extack); 9885 if (err && extack._msg) 9886 net_err_ratelimited("%s: %s\n", dev->name, extack._msg); 9887 return err; 9888 } 9889 EXPORT_SYMBOL(netif_set_mtu); 9890 9891 int netif_change_tx_queue_len(struct net_device *dev, unsigned long new_len) 9892 { 9893 unsigned int orig_len = dev->tx_queue_len; 9894 int res; 9895 9896 if (new_len != (unsigned int)new_len) 9897 return -ERANGE; 9898 9899 if (new_len != orig_len) { 9900 WRITE_ONCE(dev->tx_queue_len, new_len); 9901 res = call_netdevice_notifiers(NETDEV_CHANGE_TX_QUEUE_LEN, dev); 9902 res = notifier_to_errno(res); 9903 if (res) 9904 goto err_rollback; 9905 res = dev_qdisc_change_tx_queue_len(dev); 9906 if (res) 9907 goto err_rollback; 9908 } 9909 9910 return 0; 9911 9912 err_rollback: 9913 netdev_err(dev, "refused to change device tx_queue_len\n"); 9914 WRITE_ONCE(dev->tx_queue_len, orig_len); 9915 return res; 9916 } 9917 9918 void netif_set_group(struct net_device *dev, int new_group) 9919 { 9920 dev->group = new_group; 9921 } 9922 9923 /** 9924 * netif_pre_changeaddr_notify() - Call NETDEV_PRE_CHANGEADDR. 9925 * @dev: device 9926 * @addr: new address 9927 * @extack: netlink extended ack 9928 * 9929 * Return: 0 on success, -errno on failure. 9930 */ 9931 int netif_pre_changeaddr_notify(struct net_device *dev, const char *addr, 9932 struct netlink_ext_ack *extack) 9933 { 9934 struct netdev_notifier_pre_changeaddr_info info = { 9935 .info.dev = dev, 9936 .info.extack = extack, 9937 .dev_addr = addr, 9938 }; 9939 int rc; 9940 9941 rc = call_netdevice_notifiers_info(NETDEV_PRE_CHANGEADDR, &info.info); 9942 return notifier_to_errno(rc); 9943 } 9944 EXPORT_SYMBOL_NS_GPL(netif_pre_changeaddr_notify, "NETDEV_INTERNAL"); 9945 9946 int netif_set_mac_address(struct net_device *dev, struct sockaddr_storage *ss, 9947 struct netlink_ext_ack *extack) 9948 { 9949 const struct net_device_ops *ops = dev->netdev_ops; 9950 int err; 9951 9952 if (!ops->ndo_set_mac_address) 9953 return -EOPNOTSUPP; 9954 if (ss->ss_family != dev->type) 9955 return -EINVAL; 9956 if (!netif_device_present(dev)) 9957 return -ENODEV; 9958 err = netif_pre_changeaddr_notify(dev, ss->__data, extack); 9959 if (err) 9960 return err; 9961 if (memcmp(dev->dev_addr, ss->__data, dev->addr_len)) { 9962 err = ops->ndo_set_mac_address(dev, ss); 9963 if (err) 9964 return err; 9965 } 9966 dev->addr_assign_type = NET_ADDR_SET; 9967 call_netdevice_notifiers(NETDEV_CHANGEADDR, dev); 9968 add_device_randomness(dev->dev_addr, dev->addr_len); 9969 return 0; 9970 } 9971 9972 DECLARE_RWSEM(dev_addr_sem); 9973 9974 /* "sa" is a true struct sockaddr with limited "sa_data" member. */ 9975 int netif_get_mac_address(struct sockaddr *sa, struct net *net, char *dev_name) 9976 { 9977 size_t size = sizeof(sa->sa_data); 9978 struct net_device *dev; 9979 int ret = 0; 9980 9981 down_read(&dev_addr_sem); 9982 rcu_read_lock(); 9983 9984 dev = dev_get_by_name_rcu(net, dev_name); 9985 if (!dev) { 9986 ret = -ENODEV; 9987 goto unlock; 9988 } 9989 if (!dev->addr_len) 9990 memset(sa->sa_data, 0, size); 9991 else 9992 memcpy(sa->sa_data, dev->dev_addr, 9993 min_t(size_t, size, dev->addr_len)); 9994 sa->sa_family = dev->type; 9995 9996 unlock: 9997 rcu_read_unlock(); 9998 up_read(&dev_addr_sem); 9999 return ret; 10000 } 10001 EXPORT_SYMBOL_NS_GPL(netif_get_mac_address, "NETDEV_INTERNAL"); 10002 10003 int netif_change_carrier(struct net_device *dev, bool new_carrier) 10004 { 10005 const struct net_device_ops *ops = dev->netdev_ops; 10006 10007 if (!ops->ndo_change_carrier) 10008 return -EOPNOTSUPP; 10009 if (!netif_device_present(dev)) 10010 return -ENODEV; 10011 return ops->ndo_change_carrier(dev, new_carrier); 10012 } 10013 10014 /** 10015 * dev_get_phys_port_id - Get device physical port ID 10016 * @dev: device 10017 * @ppid: port ID 10018 * 10019 * Get device physical port ID 10020 */ 10021 int dev_get_phys_port_id(struct net_device *dev, 10022 struct netdev_phys_item_id *ppid) 10023 { 10024 const struct net_device_ops *ops = dev->netdev_ops; 10025 10026 if (!ops->ndo_get_phys_port_id) 10027 return -EOPNOTSUPP; 10028 return ops->ndo_get_phys_port_id(dev, ppid); 10029 } 10030 10031 /** 10032 * dev_get_phys_port_name - Get device physical port name 10033 * @dev: device 10034 * @name: port name 10035 * @len: limit of bytes to copy to name 10036 * 10037 * Get device physical port name 10038 */ 10039 int dev_get_phys_port_name(struct net_device *dev, 10040 char *name, size_t len) 10041 { 10042 const struct net_device_ops *ops = dev->netdev_ops; 10043 int err; 10044 10045 if (ops->ndo_get_phys_port_name) { 10046 err = ops->ndo_get_phys_port_name(dev, name, len); 10047 if (err != -EOPNOTSUPP) 10048 return err; 10049 } 10050 return devlink_compat_phys_port_name_get(dev, name, len); 10051 } 10052 10053 /** 10054 * netif_get_port_parent_id() - Get the device's port parent identifier 10055 * @dev: network device 10056 * @ppid: pointer to a storage for the port's parent identifier 10057 * @recurse: allow/disallow recursion to lower devices 10058 * 10059 * Get the devices's port parent identifier. 10060 * 10061 * Return: 0 on success, -errno on failure. 10062 */ 10063 int netif_get_port_parent_id(struct net_device *dev, 10064 struct netdev_phys_item_id *ppid, bool recurse) 10065 { 10066 const struct net_device_ops *ops = dev->netdev_ops; 10067 struct netdev_phys_item_id first = { }; 10068 struct net_device *lower_dev; 10069 struct list_head *iter; 10070 int err; 10071 10072 if (ops->ndo_get_port_parent_id) { 10073 err = ops->ndo_get_port_parent_id(dev, ppid); 10074 if (err != -EOPNOTSUPP) 10075 return err; 10076 } 10077 10078 err = devlink_compat_switch_id_get(dev, ppid); 10079 if (!recurse || err != -EOPNOTSUPP) 10080 return err; 10081 10082 netdev_for_each_lower_dev(dev, lower_dev, iter) { 10083 err = netif_get_port_parent_id(lower_dev, ppid, true); 10084 if (err) 10085 break; 10086 if (!first.id_len) 10087 first = *ppid; 10088 else if (memcmp(&first, ppid, sizeof(*ppid))) 10089 return -EOPNOTSUPP; 10090 } 10091 10092 return err; 10093 } 10094 EXPORT_SYMBOL(netif_get_port_parent_id); 10095 10096 /** 10097 * netdev_port_same_parent_id - Indicate if two network devices have 10098 * the same port parent identifier 10099 * @a: first network device 10100 * @b: second network device 10101 */ 10102 bool netdev_port_same_parent_id(struct net_device *a, struct net_device *b) 10103 { 10104 struct netdev_phys_item_id a_id = { }; 10105 struct netdev_phys_item_id b_id = { }; 10106 10107 if (netif_get_port_parent_id(a, &a_id, true) || 10108 netif_get_port_parent_id(b, &b_id, true)) 10109 return false; 10110 10111 return netdev_phys_item_id_same(&a_id, &b_id); 10112 } 10113 EXPORT_SYMBOL(netdev_port_same_parent_id); 10114 10115 int netif_change_proto_down(struct net_device *dev, bool proto_down) 10116 { 10117 if (!dev->change_proto_down) 10118 return -EOPNOTSUPP; 10119 if (!netif_device_present(dev)) 10120 return -ENODEV; 10121 if (proto_down) 10122 netif_carrier_off(dev); 10123 else 10124 netif_carrier_on(dev); 10125 WRITE_ONCE(dev->proto_down, proto_down); 10126 return 0; 10127 } 10128 10129 /** 10130 * netdev_change_proto_down_reason_locked - proto down reason 10131 * 10132 * @dev: device 10133 * @mask: proto down mask 10134 * @value: proto down value 10135 */ 10136 void netdev_change_proto_down_reason_locked(struct net_device *dev, 10137 unsigned long mask, u32 value) 10138 { 10139 u32 proto_down_reason; 10140 int b; 10141 10142 if (!mask) { 10143 proto_down_reason = value; 10144 } else { 10145 proto_down_reason = dev->proto_down_reason; 10146 for_each_set_bit(b, &mask, 32) { 10147 if (value & (1 << b)) 10148 proto_down_reason |= BIT(b); 10149 else 10150 proto_down_reason &= ~BIT(b); 10151 } 10152 } 10153 WRITE_ONCE(dev->proto_down_reason, proto_down_reason); 10154 } 10155 10156 struct bpf_xdp_link { 10157 struct bpf_link link; 10158 struct net_device *dev; /* protected by rtnl_lock, no refcnt held */ 10159 int flags; 10160 }; 10161 10162 static enum bpf_xdp_mode dev_xdp_mode(struct net_device *dev, u32 flags) 10163 { 10164 if (flags & XDP_FLAGS_HW_MODE) 10165 return XDP_MODE_HW; 10166 if (flags & XDP_FLAGS_DRV_MODE) 10167 return XDP_MODE_DRV; 10168 if (flags & XDP_FLAGS_SKB_MODE) 10169 return XDP_MODE_SKB; 10170 return dev->netdev_ops->ndo_bpf ? XDP_MODE_DRV : XDP_MODE_SKB; 10171 } 10172 10173 static bpf_op_t dev_xdp_bpf_op(struct net_device *dev, enum bpf_xdp_mode mode) 10174 { 10175 switch (mode) { 10176 case XDP_MODE_SKB: 10177 return generic_xdp_install; 10178 case XDP_MODE_DRV: 10179 case XDP_MODE_HW: 10180 return dev->netdev_ops->ndo_bpf; 10181 default: 10182 return NULL; 10183 } 10184 } 10185 10186 static struct bpf_xdp_link *dev_xdp_link(struct net_device *dev, 10187 enum bpf_xdp_mode mode) 10188 { 10189 return dev->xdp_state[mode].link; 10190 } 10191 10192 static struct bpf_prog *dev_xdp_prog(struct net_device *dev, 10193 enum bpf_xdp_mode mode) 10194 { 10195 struct bpf_xdp_link *link = dev_xdp_link(dev, mode); 10196 10197 if (link) 10198 return link->link.prog; 10199 return dev->xdp_state[mode].prog; 10200 } 10201 10202 u8 dev_xdp_prog_count(struct net_device *dev) 10203 { 10204 u8 count = 0; 10205 int i; 10206 10207 for (i = 0; i < __MAX_XDP_MODE; i++) 10208 if (dev->xdp_state[i].prog || dev->xdp_state[i].link) 10209 count++; 10210 return count; 10211 } 10212 EXPORT_SYMBOL_GPL(dev_xdp_prog_count); 10213 10214 u8 dev_xdp_sb_prog_count(struct net_device *dev) 10215 { 10216 u8 count = 0; 10217 int i; 10218 10219 for (i = 0; i < __MAX_XDP_MODE; i++) 10220 if (dev->xdp_state[i].prog && 10221 !dev->xdp_state[i].prog->aux->xdp_has_frags) 10222 count++; 10223 return count; 10224 } 10225 10226 int netif_xdp_propagate(struct net_device *dev, struct netdev_bpf *bpf) 10227 { 10228 if (!dev->netdev_ops->ndo_bpf) 10229 return -EOPNOTSUPP; 10230 10231 if (dev->cfg->hds_config == ETHTOOL_TCP_DATA_SPLIT_ENABLED && 10232 bpf->command == XDP_SETUP_PROG && 10233 bpf->prog && !bpf->prog->aux->xdp_has_frags) { 10234 NL_SET_ERR_MSG(bpf->extack, 10235 "unable to propagate XDP to device using tcp-data-split"); 10236 return -EBUSY; 10237 } 10238 10239 if (dev_get_min_mp_channel_count(dev)) { 10240 NL_SET_ERR_MSG(bpf->extack, "unable to propagate XDP to device using memory provider"); 10241 return -EBUSY; 10242 } 10243 10244 return dev->netdev_ops->ndo_bpf(dev, bpf); 10245 } 10246 EXPORT_SYMBOL_GPL(netif_xdp_propagate); 10247 10248 u32 dev_xdp_prog_id(struct net_device *dev, enum bpf_xdp_mode mode) 10249 { 10250 struct bpf_prog *prog = dev_xdp_prog(dev, mode); 10251 10252 return prog ? prog->aux->id : 0; 10253 } 10254 10255 static void dev_xdp_set_link(struct net_device *dev, enum bpf_xdp_mode mode, 10256 struct bpf_xdp_link *link) 10257 { 10258 dev->xdp_state[mode].link = link; 10259 dev->xdp_state[mode].prog = NULL; 10260 } 10261 10262 static void dev_xdp_set_prog(struct net_device *dev, enum bpf_xdp_mode mode, 10263 struct bpf_prog *prog) 10264 { 10265 dev->xdp_state[mode].link = NULL; 10266 dev->xdp_state[mode].prog = prog; 10267 } 10268 10269 static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode, 10270 bpf_op_t bpf_op, struct netlink_ext_ack *extack, 10271 u32 flags, struct bpf_prog *prog) 10272 { 10273 struct netdev_bpf xdp; 10274 int err; 10275 10276 netdev_ops_assert_locked(dev); 10277 10278 if (dev->cfg->hds_config == ETHTOOL_TCP_DATA_SPLIT_ENABLED && 10279 prog && !prog->aux->xdp_has_frags) { 10280 NL_SET_ERR_MSG(extack, "unable to install XDP to device using tcp-data-split"); 10281 return -EBUSY; 10282 } 10283 10284 if (dev_get_min_mp_channel_count(dev)) { 10285 NL_SET_ERR_MSG(extack, "unable to install XDP to device using memory provider"); 10286 return -EBUSY; 10287 } 10288 10289 memset(&xdp, 0, sizeof(xdp)); 10290 xdp.command = mode == XDP_MODE_HW ? XDP_SETUP_PROG_HW : XDP_SETUP_PROG; 10291 xdp.extack = extack; 10292 xdp.flags = flags; 10293 xdp.prog = prog; 10294 10295 /* Drivers assume refcnt is already incremented (i.e, prog pointer is 10296 * "moved" into driver), so they don't increment it on their own, but 10297 * they do decrement refcnt when program is detached or replaced. 10298 * Given net_device also owns link/prog, we need to bump refcnt here 10299 * to prevent drivers from underflowing it. 10300 */ 10301 if (prog) 10302 bpf_prog_inc(prog); 10303 err = bpf_op(dev, &xdp); 10304 if (err) { 10305 if (prog) 10306 bpf_prog_put(prog); 10307 return err; 10308 } 10309 10310 if (mode != XDP_MODE_HW) 10311 bpf_prog_change_xdp(dev_xdp_prog(dev, mode), prog); 10312 10313 return 0; 10314 } 10315 10316 static void dev_xdp_uninstall(struct net_device *dev) 10317 { 10318 struct bpf_xdp_link *link; 10319 struct bpf_prog *prog; 10320 enum bpf_xdp_mode mode; 10321 bpf_op_t bpf_op; 10322 10323 ASSERT_RTNL(); 10324 10325 for (mode = XDP_MODE_SKB; mode < __MAX_XDP_MODE; mode++) { 10326 prog = dev_xdp_prog(dev, mode); 10327 if (!prog) 10328 continue; 10329 10330 bpf_op = dev_xdp_bpf_op(dev, mode); 10331 if (!bpf_op) 10332 continue; 10333 10334 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL)); 10335 10336 /* auto-detach link from net device */ 10337 link = dev_xdp_link(dev, mode); 10338 if (link) 10339 link->dev = NULL; 10340 else 10341 bpf_prog_put(prog); 10342 10343 dev_xdp_set_link(dev, mode, NULL); 10344 } 10345 } 10346 10347 static int dev_xdp_attach(struct net_device *dev, struct netlink_ext_ack *extack, 10348 struct bpf_xdp_link *link, struct bpf_prog *new_prog, 10349 struct bpf_prog *old_prog, u32 flags) 10350 { 10351 unsigned int num_modes = hweight32(flags & XDP_FLAGS_MODES); 10352 struct bpf_prog *cur_prog; 10353 struct net_device *upper; 10354 struct list_head *iter; 10355 enum bpf_xdp_mode mode; 10356 bpf_op_t bpf_op; 10357 int err; 10358 10359 ASSERT_RTNL(); 10360 10361 /* either link or prog attachment, never both */ 10362 if (link && (new_prog || old_prog)) 10363 return -EINVAL; 10364 /* link supports only XDP mode flags */ 10365 if (link && (flags & ~XDP_FLAGS_MODES)) { 10366 NL_SET_ERR_MSG(extack, "Invalid XDP flags for BPF link attachment"); 10367 return -EINVAL; 10368 } 10369 /* just one XDP mode bit should be set, zero defaults to drv/skb mode */ 10370 if (num_modes > 1) { 10371 NL_SET_ERR_MSG(extack, "Only one XDP mode flag can be set"); 10372 return -EINVAL; 10373 } 10374 /* avoid ambiguity if offload + drv/skb mode progs are both loaded */ 10375 if (!num_modes && dev_xdp_prog_count(dev) > 1) { 10376 NL_SET_ERR_MSG(extack, 10377 "More than one program loaded, unset mode is ambiguous"); 10378 return -EINVAL; 10379 } 10380 /* old_prog != NULL implies XDP_FLAGS_REPLACE is set */ 10381 if (old_prog && !(flags & XDP_FLAGS_REPLACE)) { 10382 NL_SET_ERR_MSG(extack, "XDP_FLAGS_REPLACE is not specified"); 10383 return -EINVAL; 10384 } 10385 10386 mode = dev_xdp_mode(dev, flags); 10387 /* can't replace attached link */ 10388 if (dev_xdp_link(dev, mode)) { 10389 NL_SET_ERR_MSG(extack, "Can't replace active BPF XDP link"); 10390 return -EBUSY; 10391 } 10392 10393 /* don't allow if an upper device already has a program */ 10394 netdev_for_each_upper_dev_rcu(dev, upper, iter) { 10395 if (dev_xdp_prog_count(upper) > 0) { 10396 NL_SET_ERR_MSG(extack, "Cannot attach when an upper device already has a program"); 10397 return -EEXIST; 10398 } 10399 } 10400 10401 cur_prog = dev_xdp_prog(dev, mode); 10402 /* can't replace attached prog with link */ 10403 if (link && cur_prog) { 10404 NL_SET_ERR_MSG(extack, "Can't replace active XDP program with BPF link"); 10405 return -EBUSY; 10406 } 10407 if ((flags & XDP_FLAGS_REPLACE) && cur_prog != old_prog) { 10408 NL_SET_ERR_MSG(extack, "Active program does not match expected"); 10409 return -EEXIST; 10410 } 10411 10412 /* put effective new program into new_prog */ 10413 if (link) 10414 new_prog = link->link.prog; 10415 10416 if (new_prog) { 10417 bool offload = mode == XDP_MODE_HW; 10418 enum bpf_xdp_mode other_mode = mode == XDP_MODE_SKB 10419 ? XDP_MODE_DRV : XDP_MODE_SKB; 10420 10421 if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) && cur_prog) { 10422 NL_SET_ERR_MSG(extack, "XDP program already attached"); 10423 return -EBUSY; 10424 } 10425 if (!offload && dev_xdp_prog(dev, other_mode)) { 10426 NL_SET_ERR_MSG(extack, "Native and generic XDP can't be active at the same time"); 10427 return -EEXIST; 10428 } 10429 if (!offload && bpf_prog_is_offloaded(new_prog->aux)) { 10430 NL_SET_ERR_MSG(extack, "Using offloaded program without HW_MODE flag is not supported"); 10431 return -EINVAL; 10432 } 10433 if (bpf_prog_is_dev_bound(new_prog->aux) && !bpf_offload_dev_match(new_prog, dev)) { 10434 NL_SET_ERR_MSG(extack, "Program bound to different device"); 10435 return -EINVAL; 10436 } 10437 if (bpf_prog_is_dev_bound(new_prog->aux) && mode == XDP_MODE_SKB) { 10438 NL_SET_ERR_MSG(extack, "Can't attach device-bound programs in generic mode"); 10439 return -EINVAL; 10440 } 10441 if (new_prog->expected_attach_type == BPF_XDP_DEVMAP) { 10442 NL_SET_ERR_MSG(extack, "BPF_XDP_DEVMAP programs can not be attached to a device"); 10443 return -EINVAL; 10444 } 10445 if (new_prog->expected_attach_type == BPF_XDP_CPUMAP) { 10446 NL_SET_ERR_MSG(extack, "BPF_XDP_CPUMAP programs can not be attached to a device"); 10447 return -EINVAL; 10448 } 10449 } 10450 10451 /* don't call drivers if the effective program didn't change */ 10452 if (new_prog != cur_prog) { 10453 bpf_op = dev_xdp_bpf_op(dev, mode); 10454 if (!bpf_op) { 10455 NL_SET_ERR_MSG(extack, "Underlying driver does not support XDP in native mode"); 10456 return -EOPNOTSUPP; 10457 } 10458 10459 err = dev_xdp_install(dev, mode, bpf_op, extack, flags, new_prog); 10460 if (err) 10461 return err; 10462 } 10463 10464 if (link) 10465 dev_xdp_set_link(dev, mode, link); 10466 else 10467 dev_xdp_set_prog(dev, mode, new_prog); 10468 if (cur_prog) 10469 bpf_prog_put(cur_prog); 10470 10471 return 0; 10472 } 10473 10474 static int dev_xdp_attach_link(struct net_device *dev, 10475 struct netlink_ext_ack *extack, 10476 struct bpf_xdp_link *link) 10477 { 10478 return dev_xdp_attach(dev, extack, link, NULL, NULL, link->flags); 10479 } 10480 10481 static int dev_xdp_detach_link(struct net_device *dev, 10482 struct netlink_ext_ack *extack, 10483 struct bpf_xdp_link *link) 10484 { 10485 enum bpf_xdp_mode mode; 10486 bpf_op_t bpf_op; 10487 10488 ASSERT_RTNL(); 10489 10490 mode = dev_xdp_mode(dev, link->flags); 10491 if (dev_xdp_link(dev, mode) != link) 10492 return -EINVAL; 10493 10494 bpf_op = dev_xdp_bpf_op(dev, mode); 10495 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL)); 10496 dev_xdp_set_link(dev, mode, NULL); 10497 return 0; 10498 } 10499 10500 static void bpf_xdp_link_release(struct bpf_link *link) 10501 { 10502 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link); 10503 10504 rtnl_lock(); 10505 10506 /* if racing with net_device's tear down, xdp_link->dev might be 10507 * already NULL, in which case link was already auto-detached 10508 */ 10509 if (xdp_link->dev) { 10510 netdev_lock_ops(xdp_link->dev); 10511 WARN_ON(dev_xdp_detach_link(xdp_link->dev, NULL, xdp_link)); 10512 netdev_unlock_ops(xdp_link->dev); 10513 xdp_link->dev = NULL; 10514 } 10515 10516 rtnl_unlock(); 10517 } 10518 10519 static int bpf_xdp_link_detach(struct bpf_link *link) 10520 { 10521 bpf_xdp_link_release(link); 10522 return 0; 10523 } 10524 10525 static void bpf_xdp_link_dealloc(struct bpf_link *link) 10526 { 10527 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link); 10528 10529 kfree(xdp_link); 10530 } 10531 10532 static void bpf_xdp_link_show_fdinfo(const struct bpf_link *link, 10533 struct seq_file *seq) 10534 { 10535 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link); 10536 u32 ifindex = 0; 10537 10538 rtnl_lock(); 10539 if (xdp_link->dev) 10540 ifindex = xdp_link->dev->ifindex; 10541 rtnl_unlock(); 10542 10543 seq_printf(seq, "ifindex:\t%u\n", ifindex); 10544 } 10545 10546 static int bpf_xdp_link_fill_link_info(const struct bpf_link *link, 10547 struct bpf_link_info *info) 10548 { 10549 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link); 10550 u32 ifindex = 0; 10551 10552 rtnl_lock(); 10553 if (xdp_link->dev) 10554 ifindex = xdp_link->dev->ifindex; 10555 rtnl_unlock(); 10556 10557 info->xdp.ifindex = ifindex; 10558 return 0; 10559 } 10560 10561 static int bpf_xdp_link_update(struct bpf_link *link, struct bpf_prog *new_prog, 10562 struct bpf_prog *old_prog) 10563 { 10564 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link); 10565 enum bpf_xdp_mode mode; 10566 bpf_op_t bpf_op; 10567 int err = 0; 10568 10569 rtnl_lock(); 10570 10571 /* link might have been auto-released already, so fail */ 10572 if (!xdp_link->dev) { 10573 err = -ENOLINK; 10574 goto out_unlock; 10575 } 10576 10577 if (old_prog && link->prog != old_prog) { 10578 err = -EPERM; 10579 goto out_unlock; 10580 } 10581 old_prog = link->prog; 10582 if (old_prog->type != new_prog->type || 10583 old_prog->expected_attach_type != new_prog->expected_attach_type) { 10584 err = -EINVAL; 10585 goto out_unlock; 10586 } 10587 10588 if (old_prog == new_prog) { 10589 /* no-op, don't disturb drivers */ 10590 bpf_prog_put(new_prog); 10591 goto out_unlock; 10592 } 10593 10594 netdev_lock_ops(xdp_link->dev); 10595 mode = dev_xdp_mode(xdp_link->dev, xdp_link->flags); 10596 bpf_op = dev_xdp_bpf_op(xdp_link->dev, mode); 10597 err = dev_xdp_install(xdp_link->dev, mode, bpf_op, NULL, 10598 xdp_link->flags, new_prog); 10599 netdev_unlock_ops(xdp_link->dev); 10600 if (err) 10601 goto out_unlock; 10602 10603 old_prog = xchg(&link->prog, new_prog); 10604 bpf_prog_put(old_prog); 10605 10606 out_unlock: 10607 rtnl_unlock(); 10608 return err; 10609 } 10610 10611 static const struct bpf_link_ops bpf_xdp_link_lops = { 10612 .release = bpf_xdp_link_release, 10613 .dealloc = bpf_xdp_link_dealloc, 10614 .detach = bpf_xdp_link_detach, 10615 .show_fdinfo = bpf_xdp_link_show_fdinfo, 10616 .fill_link_info = bpf_xdp_link_fill_link_info, 10617 .update_prog = bpf_xdp_link_update, 10618 }; 10619 10620 int bpf_xdp_link_attach(const union bpf_attr *attr, struct bpf_prog *prog) 10621 { 10622 struct net *net = current->nsproxy->net_ns; 10623 struct bpf_link_primer link_primer; 10624 struct netlink_ext_ack extack = {}; 10625 struct bpf_xdp_link *link; 10626 struct net_device *dev; 10627 int err, fd; 10628 10629 rtnl_lock(); 10630 dev = dev_get_by_index(net, attr->link_create.target_ifindex); 10631 if (!dev) { 10632 rtnl_unlock(); 10633 return -EINVAL; 10634 } 10635 10636 link = kzalloc(sizeof(*link), GFP_USER); 10637 if (!link) { 10638 err = -ENOMEM; 10639 goto unlock; 10640 } 10641 10642 bpf_link_init(&link->link, BPF_LINK_TYPE_XDP, &bpf_xdp_link_lops, prog, 10643 attr->link_create.attach_type); 10644 link->dev = dev; 10645 link->flags = attr->link_create.flags; 10646 10647 err = bpf_link_prime(&link->link, &link_primer); 10648 if (err) { 10649 kfree(link); 10650 goto unlock; 10651 } 10652 10653 netdev_lock_ops(dev); 10654 err = dev_xdp_attach_link(dev, &extack, link); 10655 netdev_unlock_ops(dev); 10656 rtnl_unlock(); 10657 10658 if (err) { 10659 link->dev = NULL; 10660 bpf_link_cleanup(&link_primer); 10661 trace_bpf_xdp_link_attach_failed(extack._msg); 10662 goto out_put_dev; 10663 } 10664 10665 fd = bpf_link_settle(&link_primer); 10666 /* link itself doesn't hold dev's refcnt to not complicate shutdown */ 10667 dev_put(dev); 10668 return fd; 10669 10670 unlock: 10671 rtnl_unlock(); 10672 10673 out_put_dev: 10674 dev_put(dev); 10675 return err; 10676 } 10677 10678 /** 10679 * dev_change_xdp_fd - set or clear a bpf program for a device rx path 10680 * @dev: device 10681 * @extack: netlink extended ack 10682 * @fd: new program fd or negative value to clear 10683 * @expected_fd: old program fd that userspace expects to replace or clear 10684 * @flags: xdp-related flags 10685 * 10686 * Set or clear a bpf program for a device 10687 */ 10688 int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack, 10689 int fd, int expected_fd, u32 flags) 10690 { 10691 enum bpf_xdp_mode mode = dev_xdp_mode(dev, flags); 10692 struct bpf_prog *new_prog = NULL, *old_prog = NULL; 10693 int err; 10694 10695 ASSERT_RTNL(); 10696 10697 if (fd >= 0) { 10698 new_prog = bpf_prog_get_type_dev(fd, BPF_PROG_TYPE_XDP, 10699 mode != XDP_MODE_SKB); 10700 if (IS_ERR(new_prog)) 10701 return PTR_ERR(new_prog); 10702 } 10703 10704 if (expected_fd >= 0) { 10705 old_prog = bpf_prog_get_type_dev(expected_fd, BPF_PROG_TYPE_XDP, 10706 mode != XDP_MODE_SKB); 10707 if (IS_ERR(old_prog)) { 10708 err = PTR_ERR(old_prog); 10709 old_prog = NULL; 10710 goto err_out; 10711 } 10712 } 10713 10714 err = dev_xdp_attach(dev, extack, NULL, new_prog, old_prog, flags); 10715 10716 err_out: 10717 if (err && new_prog) 10718 bpf_prog_put(new_prog); 10719 if (old_prog) 10720 bpf_prog_put(old_prog); 10721 return err; 10722 } 10723 10724 u32 dev_get_min_mp_channel_count(const struct net_device *dev) 10725 { 10726 int i; 10727 10728 netdev_ops_assert_locked(dev); 10729 10730 for (i = dev->real_num_rx_queues - 1; i >= 0; i--) 10731 if (dev->_rx[i].mp_params.mp_priv) 10732 /* The channel count is the idx plus 1. */ 10733 return i + 1; 10734 10735 return 0; 10736 } 10737 10738 /** 10739 * dev_index_reserve() - allocate an ifindex in a namespace 10740 * @net: the applicable net namespace 10741 * @ifindex: requested ifindex, pass %0 to get one allocated 10742 * 10743 * Allocate a ifindex for a new device. Caller must either use the ifindex 10744 * to store the device (via list_netdevice()) or call dev_index_release() 10745 * to give the index up. 10746 * 10747 * Return: a suitable unique value for a new device interface number or -errno. 10748 */ 10749 static int dev_index_reserve(struct net *net, u32 ifindex) 10750 { 10751 int err; 10752 10753 if (ifindex > INT_MAX) { 10754 DEBUG_NET_WARN_ON_ONCE(1); 10755 return -EINVAL; 10756 } 10757 10758 if (!ifindex) 10759 err = xa_alloc_cyclic(&net->dev_by_index, &ifindex, NULL, 10760 xa_limit_31b, &net->ifindex, GFP_KERNEL); 10761 else 10762 err = xa_insert(&net->dev_by_index, ifindex, NULL, GFP_KERNEL); 10763 if (err < 0) 10764 return err; 10765 10766 return ifindex; 10767 } 10768 10769 static void dev_index_release(struct net *net, int ifindex) 10770 { 10771 /* Expect only unused indexes, unlist_netdevice() removes the used */ 10772 WARN_ON(xa_erase(&net->dev_by_index, ifindex)); 10773 } 10774 10775 static bool from_cleanup_net(void) 10776 { 10777 #ifdef CONFIG_NET_NS 10778 return current == READ_ONCE(cleanup_net_task); 10779 #else 10780 return false; 10781 #endif 10782 } 10783 10784 /* Delayed registration/unregisteration */ 10785 LIST_HEAD(net_todo_list); 10786 DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq); 10787 atomic_t dev_unreg_count = ATOMIC_INIT(0); 10788 10789 static void net_set_todo(struct net_device *dev) 10790 { 10791 list_add_tail(&dev->todo_list, &net_todo_list); 10792 } 10793 10794 static netdev_features_t netdev_sync_upper_features(struct net_device *lower, 10795 struct net_device *upper, netdev_features_t features) 10796 { 10797 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES; 10798 netdev_features_t feature; 10799 int feature_bit; 10800 10801 for_each_netdev_feature(upper_disables, feature_bit) { 10802 feature = __NETIF_F_BIT(feature_bit); 10803 if (!(upper->wanted_features & feature) 10804 && (features & feature)) { 10805 netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n", 10806 &feature, upper->name); 10807 features &= ~feature; 10808 } 10809 } 10810 10811 return features; 10812 } 10813 10814 static void netdev_sync_lower_features(struct net_device *upper, 10815 struct net_device *lower, netdev_features_t features) 10816 { 10817 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES; 10818 netdev_features_t feature; 10819 int feature_bit; 10820 10821 for_each_netdev_feature(upper_disables, feature_bit) { 10822 feature = __NETIF_F_BIT(feature_bit); 10823 if (!(features & feature) && (lower->features & feature)) { 10824 netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n", 10825 &feature, lower->name); 10826 netdev_lock_ops(lower); 10827 lower->wanted_features &= ~feature; 10828 __netdev_update_features(lower); 10829 10830 if (unlikely(lower->features & feature)) 10831 netdev_WARN(upper, "failed to disable %pNF on %s!\n", 10832 &feature, lower->name); 10833 else 10834 netdev_features_change(lower); 10835 netdev_unlock_ops(lower); 10836 } 10837 } 10838 } 10839 10840 static bool netdev_has_ip_or_hw_csum(netdev_features_t features) 10841 { 10842 netdev_features_t ip_csum_mask = NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM; 10843 bool ip_csum = (features & ip_csum_mask) == ip_csum_mask; 10844 bool hw_csum = features & NETIF_F_HW_CSUM; 10845 10846 return ip_csum || hw_csum; 10847 } 10848 10849 static netdev_features_t netdev_fix_features(struct net_device *dev, 10850 netdev_features_t features) 10851 { 10852 /* Fix illegal checksum combinations */ 10853 if ((features & NETIF_F_HW_CSUM) && 10854 (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) { 10855 netdev_warn(dev, "mixed HW and IP checksum settings.\n"); 10856 features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM); 10857 } 10858 10859 /* TSO requires that SG is present as well. */ 10860 if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) { 10861 netdev_dbg(dev, "Dropping TSO features since no SG feature.\n"); 10862 features &= ~NETIF_F_ALL_TSO; 10863 } 10864 10865 if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) && 10866 !(features & NETIF_F_IP_CSUM)) { 10867 netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n"); 10868 features &= ~NETIF_F_TSO; 10869 features &= ~NETIF_F_TSO_ECN; 10870 } 10871 10872 if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) && 10873 !(features & NETIF_F_IPV6_CSUM)) { 10874 netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n"); 10875 features &= ~NETIF_F_TSO6; 10876 } 10877 10878 /* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */ 10879 if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO)) 10880 features &= ~NETIF_F_TSO_MANGLEID; 10881 10882 /* TSO ECN requires that TSO is present as well. */ 10883 if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN) 10884 features &= ~NETIF_F_TSO_ECN; 10885 10886 /* Software GSO depends on SG. */ 10887 if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) { 10888 netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n"); 10889 features &= ~NETIF_F_GSO; 10890 } 10891 10892 /* GSO partial features require GSO partial be set */ 10893 if ((features & dev->gso_partial_features) && 10894 !(features & NETIF_F_GSO_PARTIAL)) { 10895 netdev_dbg(dev, 10896 "Dropping partially supported GSO features since no GSO partial.\n"); 10897 features &= ~dev->gso_partial_features; 10898 } 10899 10900 if (!(features & NETIF_F_RXCSUM)) { 10901 /* NETIF_F_GRO_HW implies doing RXCSUM since every packet 10902 * successfully merged by hardware must also have the 10903 * checksum verified by hardware. If the user does not 10904 * want to enable RXCSUM, logically, we should disable GRO_HW. 10905 */ 10906 if (features & NETIF_F_GRO_HW) { 10907 netdev_dbg(dev, "Dropping NETIF_F_GRO_HW since no RXCSUM feature.\n"); 10908 features &= ~NETIF_F_GRO_HW; 10909 } 10910 } 10911 10912 /* LRO/HW-GRO features cannot be combined with RX-FCS */ 10913 if (features & NETIF_F_RXFCS) { 10914 if (features & NETIF_F_LRO) { 10915 netdev_dbg(dev, "Dropping LRO feature since RX-FCS is requested.\n"); 10916 features &= ~NETIF_F_LRO; 10917 } 10918 10919 if (features & NETIF_F_GRO_HW) { 10920 netdev_dbg(dev, "Dropping HW-GRO feature since RX-FCS is requested.\n"); 10921 features &= ~NETIF_F_GRO_HW; 10922 } 10923 } 10924 10925 if ((features & NETIF_F_GRO_HW) && (features & NETIF_F_LRO)) { 10926 netdev_dbg(dev, "Dropping LRO feature since HW-GRO is requested.\n"); 10927 features &= ~NETIF_F_LRO; 10928 } 10929 10930 if ((features & NETIF_F_HW_TLS_TX) && !netdev_has_ip_or_hw_csum(features)) { 10931 netdev_dbg(dev, "Dropping TLS TX HW offload feature since no CSUM feature.\n"); 10932 features &= ~NETIF_F_HW_TLS_TX; 10933 } 10934 10935 if ((features & NETIF_F_HW_TLS_RX) && !(features & NETIF_F_RXCSUM)) { 10936 netdev_dbg(dev, "Dropping TLS RX HW offload feature since no RXCSUM feature.\n"); 10937 features &= ~NETIF_F_HW_TLS_RX; 10938 } 10939 10940 if ((features & NETIF_F_GSO_UDP_L4) && !netdev_has_ip_or_hw_csum(features)) { 10941 netdev_dbg(dev, "Dropping USO feature since no CSUM feature.\n"); 10942 features &= ~NETIF_F_GSO_UDP_L4; 10943 } 10944 10945 return features; 10946 } 10947 10948 int __netdev_update_features(struct net_device *dev) 10949 { 10950 struct net_device *upper, *lower; 10951 netdev_features_t features; 10952 struct list_head *iter; 10953 int err = -1; 10954 10955 ASSERT_RTNL(); 10956 netdev_ops_assert_locked(dev); 10957 10958 features = netdev_get_wanted_features(dev); 10959 10960 if (dev->netdev_ops->ndo_fix_features) 10961 features = dev->netdev_ops->ndo_fix_features(dev, features); 10962 10963 /* driver might be less strict about feature dependencies */ 10964 features = netdev_fix_features(dev, features); 10965 10966 /* some features can't be enabled if they're off on an upper device */ 10967 netdev_for_each_upper_dev_rcu(dev, upper, iter) 10968 features = netdev_sync_upper_features(dev, upper, features); 10969 10970 if (dev->features == features) 10971 goto sync_lower; 10972 10973 netdev_dbg(dev, "Features changed: %pNF -> %pNF\n", 10974 &dev->features, &features); 10975 10976 if (dev->netdev_ops->ndo_set_features) 10977 err = dev->netdev_ops->ndo_set_features(dev, features); 10978 else 10979 err = 0; 10980 10981 if (unlikely(err < 0)) { 10982 netdev_err(dev, 10983 "set_features() failed (%d); wanted %pNF, left %pNF\n", 10984 err, &features, &dev->features); 10985 /* return non-0 since some features might have changed and 10986 * it's better to fire a spurious notification than miss it 10987 */ 10988 return -1; 10989 } 10990 10991 sync_lower: 10992 /* some features must be disabled on lower devices when disabled 10993 * on an upper device (think: bonding master or bridge) 10994 */ 10995 netdev_for_each_lower_dev(dev, lower, iter) 10996 netdev_sync_lower_features(dev, lower, features); 10997 10998 if (!err) { 10999 netdev_features_t diff = features ^ dev->features; 11000 11001 if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) { 11002 /* udp_tunnel_{get,drop}_rx_info both need 11003 * NETIF_F_RX_UDP_TUNNEL_PORT enabled on the 11004 * device, or they won't do anything. 11005 * Thus we need to update dev->features 11006 * *before* calling udp_tunnel_get_rx_info, 11007 * but *after* calling udp_tunnel_drop_rx_info. 11008 */ 11009 udp_tunnel_nic_lock(dev); 11010 if (features & NETIF_F_RX_UDP_TUNNEL_PORT) { 11011 dev->features = features; 11012 udp_tunnel_get_rx_info(dev); 11013 } else { 11014 udp_tunnel_drop_rx_info(dev); 11015 } 11016 udp_tunnel_nic_unlock(dev); 11017 } 11018 11019 if (diff & NETIF_F_HW_VLAN_CTAG_FILTER) { 11020 if (features & NETIF_F_HW_VLAN_CTAG_FILTER) { 11021 dev->features = features; 11022 err |= vlan_get_rx_ctag_filter_info(dev); 11023 } else { 11024 vlan_drop_rx_ctag_filter_info(dev); 11025 } 11026 } 11027 11028 if (diff & NETIF_F_HW_VLAN_STAG_FILTER) { 11029 if (features & NETIF_F_HW_VLAN_STAG_FILTER) { 11030 dev->features = features; 11031 err |= vlan_get_rx_stag_filter_info(dev); 11032 } else { 11033 vlan_drop_rx_stag_filter_info(dev); 11034 } 11035 } 11036 11037 dev->features = features; 11038 } 11039 11040 return err < 0 ? 0 : 1; 11041 } 11042 11043 /** 11044 * netdev_update_features - recalculate device features 11045 * @dev: the device to check 11046 * 11047 * Recalculate dev->features set and send notifications if it 11048 * has changed. Should be called after driver or hardware dependent 11049 * conditions might have changed that influence the features. 11050 */ 11051 void netdev_update_features(struct net_device *dev) 11052 { 11053 if (__netdev_update_features(dev)) 11054 netdev_features_change(dev); 11055 } 11056 EXPORT_SYMBOL(netdev_update_features); 11057 11058 /** 11059 * netdev_change_features - recalculate device features 11060 * @dev: the device to check 11061 * 11062 * Recalculate dev->features set and send notifications even 11063 * if they have not changed. Should be called instead of 11064 * netdev_update_features() if also dev->vlan_features might 11065 * have changed to allow the changes to be propagated to stacked 11066 * VLAN devices. 11067 */ 11068 void netdev_change_features(struct net_device *dev) 11069 { 11070 __netdev_update_features(dev); 11071 netdev_features_change(dev); 11072 } 11073 EXPORT_SYMBOL(netdev_change_features); 11074 11075 /** 11076 * netif_stacked_transfer_operstate - transfer operstate 11077 * @rootdev: the root or lower level device to transfer state from 11078 * @dev: the device to transfer operstate to 11079 * 11080 * Transfer operational state from root to device. This is normally 11081 * called when a stacking relationship exists between the root 11082 * device and the device(a leaf device). 11083 */ 11084 void netif_stacked_transfer_operstate(const struct net_device *rootdev, 11085 struct net_device *dev) 11086 { 11087 if (rootdev->operstate == IF_OPER_DORMANT) 11088 netif_dormant_on(dev); 11089 else 11090 netif_dormant_off(dev); 11091 11092 if (rootdev->operstate == IF_OPER_TESTING) 11093 netif_testing_on(dev); 11094 else 11095 netif_testing_off(dev); 11096 11097 if (netif_carrier_ok(rootdev)) 11098 netif_carrier_on(dev); 11099 else 11100 netif_carrier_off(dev); 11101 } 11102 EXPORT_SYMBOL(netif_stacked_transfer_operstate); 11103 11104 static int netif_alloc_rx_queues(struct net_device *dev) 11105 { 11106 unsigned int i, count = dev->num_rx_queues; 11107 struct netdev_rx_queue *rx; 11108 size_t sz = count * sizeof(*rx); 11109 int err = 0; 11110 11111 BUG_ON(count < 1); 11112 11113 rx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL); 11114 if (!rx) 11115 return -ENOMEM; 11116 11117 dev->_rx = rx; 11118 11119 for (i = 0; i < count; i++) { 11120 rx[i].dev = dev; 11121 11122 /* XDP RX-queue setup */ 11123 err = xdp_rxq_info_reg(&rx[i].xdp_rxq, dev, i, 0); 11124 if (err < 0) 11125 goto err_rxq_info; 11126 } 11127 return 0; 11128 11129 err_rxq_info: 11130 /* Rollback successful reg's and free other resources */ 11131 while (i--) 11132 xdp_rxq_info_unreg(&rx[i].xdp_rxq); 11133 kvfree(dev->_rx); 11134 dev->_rx = NULL; 11135 return err; 11136 } 11137 11138 static void netif_free_rx_queues(struct net_device *dev) 11139 { 11140 unsigned int i, count = dev->num_rx_queues; 11141 11142 /* netif_alloc_rx_queues alloc failed, resources have been unreg'ed */ 11143 if (!dev->_rx) 11144 return; 11145 11146 for (i = 0; i < count; i++) 11147 xdp_rxq_info_unreg(&dev->_rx[i].xdp_rxq); 11148 11149 kvfree(dev->_rx); 11150 } 11151 11152 static void netdev_init_one_queue(struct net_device *dev, 11153 struct netdev_queue *queue, void *_unused) 11154 { 11155 /* Initialize queue lock */ 11156 spin_lock_init(&queue->_xmit_lock); 11157 netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type); 11158 queue->xmit_lock_owner = -1; 11159 netdev_queue_numa_node_write(queue, NUMA_NO_NODE); 11160 queue->dev = dev; 11161 #ifdef CONFIG_BQL 11162 dql_init(&queue->dql, HZ); 11163 #endif 11164 } 11165 11166 static void netif_free_tx_queues(struct net_device *dev) 11167 { 11168 kvfree(dev->_tx); 11169 } 11170 11171 static int netif_alloc_netdev_queues(struct net_device *dev) 11172 { 11173 unsigned int count = dev->num_tx_queues; 11174 struct netdev_queue *tx; 11175 size_t sz = count * sizeof(*tx); 11176 11177 if (count < 1 || count > 0xffff) 11178 return -EINVAL; 11179 11180 tx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL); 11181 if (!tx) 11182 return -ENOMEM; 11183 11184 dev->_tx = tx; 11185 11186 netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL); 11187 spin_lock_init(&dev->tx_global_lock); 11188 11189 return 0; 11190 } 11191 11192 void netif_tx_stop_all_queues(struct net_device *dev) 11193 { 11194 unsigned int i; 11195 11196 for (i = 0; i < dev->num_tx_queues; i++) { 11197 struct netdev_queue *txq = netdev_get_tx_queue(dev, i); 11198 11199 netif_tx_stop_queue(txq); 11200 } 11201 } 11202 EXPORT_SYMBOL(netif_tx_stop_all_queues); 11203 11204 static int netdev_do_alloc_pcpu_stats(struct net_device *dev) 11205 { 11206 void __percpu *v; 11207 11208 /* Drivers implementing ndo_get_peer_dev must support tstat 11209 * accounting, so that skb_do_redirect() can bump the dev's 11210 * RX stats upon network namespace switch. 11211 */ 11212 if (dev->netdev_ops->ndo_get_peer_dev && 11213 dev->pcpu_stat_type != NETDEV_PCPU_STAT_TSTATS) 11214 return -EOPNOTSUPP; 11215 11216 switch (dev->pcpu_stat_type) { 11217 case NETDEV_PCPU_STAT_NONE: 11218 return 0; 11219 case NETDEV_PCPU_STAT_LSTATS: 11220 v = dev->lstats = netdev_alloc_pcpu_stats(struct pcpu_lstats); 11221 break; 11222 case NETDEV_PCPU_STAT_TSTATS: 11223 v = dev->tstats = netdev_alloc_pcpu_stats(struct pcpu_sw_netstats); 11224 break; 11225 case NETDEV_PCPU_STAT_DSTATS: 11226 v = dev->dstats = netdev_alloc_pcpu_stats(struct pcpu_dstats); 11227 break; 11228 default: 11229 return -EINVAL; 11230 } 11231 11232 return v ? 0 : -ENOMEM; 11233 } 11234 11235 static void netdev_do_free_pcpu_stats(struct net_device *dev) 11236 { 11237 switch (dev->pcpu_stat_type) { 11238 case NETDEV_PCPU_STAT_NONE: 11239 return; 11240 case NETDEV_PCPU_STAT_LSTATS: 11241 free_percpu(dev->lstats); 11242 break; 11243 case NETDEV_PCPU_STAT_TSTATS: 11244 free_percpu(dev->tstats); 11245 break; 11246 case NETDEV_PCPU_STAT_DSTATS: 11247 free_percpu(dev->dstats); 11248 break; 11249 } 11250 } 11251 11252 static void netdev_free_phy_link_topology(struct net_device *dev) 11253 { 11254 struct phy_link_topology *topo = dev->link_topo; 11255 11256 if (IS_ENABLED(CONFIG_PHYLIB) && topo) { 11257 xa_destroy(&topo->phys); 11258 kfree(topo); 11259 dev->link_topo = NULL; 11260 } 11261 } 11262 11263 /** 11264 * register_netdevice() - register a network device 11265 * @dev: device to register 11266 * 11267 * Take a prepared network device structure and make it externally accessible. 11268 * A %NETDEV_REGISTER message is sent to the netdev notifier chain. 11269 * Callers must hold the rtnl lock - you may want register_netdev() 11270 * instead of this. 11271 */ 11272 int register_netdevice(struct net_device *dev) 11273 { 11274 int ret; 11275 struct net *net = dev_net(dev); 11276 11277 BUILD_BUG_ON(sizeof(netdev_features_t) * BITS_PER_BYTE < 11278 NETDEV_FEATURE_COUNT); 11279 BUG_ON(dev_boot_phase); 11280 ASSERT_RTNL(); 11281 11282 might_sleep(); 11283 11284 /* When net_device's are persistent, this will be fatal. */ 11285 BUG_ON(dev->reg_state != NETREG_UNINITIALIZED); 11286 BUG_ON(!net); 11287 11288 ret = ethtool_check_ops(dev->ethtool_ops); 11289 if (ret) 11290 return ret; 11291 11292 /* rss ctx ID 0 is reserved for the default context, start from 1 */ 11293 xa_init_flags(&dev->ethtool->rss_ctx, XA_FLAGS_ALLOC1); 11294 mutex_init(&dev->ethtool->rss_lock); 11295 11296 spin_lock_init(&dev->addr_list_lock); 11297 netdev_set_addr_lockdep_class(dev); 11298 11299 ret = dev_get_valid_name(net, dev, dev->name); 11300 if (ret < 0) 11301 goto out; 11302 11303 ret = -ENOMEM; 11304 dev->name_node = netdev_name_node_head_alloc(dev); 11305 if (!dev->name_node) 11306 goto out; 11307 11308 /* Init, if this function is available */ 11309 if (dev->netdev_ops->ndo_init) { 11310 ret = dev->netdev_ops->ndo_init(dev); 11311 if (ret) { 11312 if (ret > 0) 11313 ret = -EIO; 11314 goto err_free_name; 11315 } 11316 } 11317 11318 if (((dev->hw_features | dev->features) & 11319 NETIF_F_HW_VLAN_CTAG_FILTER) && 11320 (!dev->netdev_ops->ndo_vlan_rx_add_vid || 11321 !dev->netdev_ops->ndo_vlan_rx_kill_vid)) { 11322 netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n"); 11323 ret = -EINVAL; 11324 goto err_uninit; 11325 } 11326 11327 ret = netdev_do_alloc_pcpu_stats(dev); 11328 if (ret) 11329 goto err_uninit; 11330 11331 ret = dev_index_reserve(net, dev->ifindex); 11332 if (ret < 0) 11333 goto err_free_pcpu; 11334 dev->ifindex = ret; 11335 11336 /* Transfer changeable features to wanted_features and enable 11337 * software offloads (GSO and GRO). 11338 */ 11339 dev->hw_features |= (NETIF_F_SOFT_FEATURES | NETIF_F_SOFT_FEATURES_OFF); 11340 dev->features |= NETIF_F_SOFT_FEATURES; 11341 11342 if (dev->udp_tunnel_nic_info) { 11343 dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT; 11344 dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT; 11345 } 11346 11347 dev->wanted_features = dev->features & dev->hw_features; 11348 11349 if (!(dev->flags & IFF_LOOPBACK)) 11350 dev->hw_features |= NETIF_F_NOCACHE_COPY; 11351 11352 /* If IPv4 TCP segmentation offload is supported we should also 11353 * allow the device to enable segmenting the frame with the option 11354 * of ignoring a static IP ID value. This doesn't enable the 11355 * feature itself but allows the user to enable it later. 11356 */ 11357 if (dev->hw_features & NETIF_F_TSO) 11358 dev->hw_features |= NETIF_F_TSO_MANGLEID; 11359 if (dev->vlan_features & NETIF_F_TSO) 11360 dev->vlan_features |= NETIF_F_TSO_MANGLEID; 11361 if (dev->mpls_features & NETIF_F_TSO) 11362 dev->mpls_features |= NETIF_F_TSO_MANGLEID; 11363 if (dev->hw_enc_features & NETIF_F_TSO) 11364 dev->hw_enc_features |= NETIF_F_TSO_MANGLEID; 11365 11366 /* Make NETIF_F_HIGHDMA inheritable to VLAN devices. 11367 */ 11368 dev->vlan_features |= NETIF_F_HIGHDMA; 11369 11370 /* Make NETIF_F_SG inheritable to tunnel devices. 11371 */ 11372 dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL; 11373 11374 /* Make NETIF_F_SG inheritable to MPLS. 11375 */ 11376 dev->mpls_features |= NETIF_F_SG; 11377 11378 ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev); 11379 ret = notifier_to_errno(ret); 11380 if (ret) 11381 goto err_ifindex_release; 11382 11383 ret = netdev_register_kobject(dev); 11384 11385 netdev_lock(dev); 11386 WRITE_ONCE(dev->reg_state, ret ? NETREG_UNREGISTERED : NETREG_REGISTERED); 11387 netdev_unlock(dev); 11388 11389 if (ret) 11390 goto err_uninit_notify; 11391 11392 netdev_lock_ops(dev); 11393 __netdev_update_features(dev); 11394 netdev_unlock_ops(dev); 11395 11396 /* 11397 * Default initial state at registry is that the 11398 * device is present. 11399 */ 11400 11401 set_bit(__LINK_STATE_PRESENT, &dev->state); 11402 11403 linkwatch_init_dev(dev); 11404 11405 dev_init_scheduler(dev); 11406 11407 netdev_hold(dev, &dev->dev_registered_tracker, GFP_KERNEL); 11408 list_netdevice(dev); 11409 11410 add_device_randomness(dev->dev_addr, dev->addr_len); 11411 11412 /* If the device has permanent device address, driver should 11413 * set dev_addr and also addr_assign_type should be set to 11414 * NET_ADDR_PERM (default value). 11415 */ 11416 if (dev->addr_assign_type == NET_ADDR_PERM) 11417 memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len); 11418 11419 /* Notify protocols, that a new device appeared. */ 11420 netdev_lock_ops(dev); 11421 ret = call_netdevice_notifiers(NETDEV_REGISTER, dev); 11422 netdev_unlock_ops(dev); 11423 ret = notifier_to_errno(ret); 11424 if (ret) { 11425 /* Expect explicit free_netdev() on failure */ 11426 dev->needs_free_netdev = false; 11427 unregister_netdevice_queue(dev, NULL); 11428 goto out; 11429 } 11430 /* 11431 * Prevent userspace races by waiting until the network 11432 * device is fully setup before sending notifications. 11433 */ 11434 if (!(dev->rtnl_link_ops && dev->rtnl_link_initializing)) 11435 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL, 0, NULL); 11436 11437 out: 11438 return ret; 11439 11440 err_uninit_notify: 11441 call_netdevice_notifiers(NETDEV_PRE_UNINIT, dev); 11442 err_ifindex_release: 11443 dev_index_release(net, dev->ifindex); 11444 err_free_pcpu: 11445 netdev_do_free_pcpu_stats(dev); 11446 err_uninit: 11447 if (dev->netdev_ops->ndo_uninit) 11448 dev->netdev_ops->ndo_uninit(dev); 11449 if (dev->priv_destructor) 11450 dev->priv_destructor(dev); 11451 err_free_name: 11452 netdev_name_node_free(dev->name_node); 11453 goto out; 11454 } 11455 EXPORT_SYMBOL(register_netdevice); 11456 11457 /* Initialize the core of a dummy net device. 11458 * The setup steps dummy netdevs need which normal netdevs get by going 11459 * through register_netdevice(). 11460 */ 11461 static void init_dummy_netdev(struct net_device *dev) 11462 { 11463 /* make sure we BUG if trying to hit standard 11464 * register/unregister code path 11465 */ 11466 dev->reg_state = NETREG_DUMMY; 11467 11468 /* a dummy interface is started by default */ 11469 set_bit(__LINK_STATE_PRESENT, &dev->state); 11470 set_bit(__LINK_STATE_START, &dev->state); 11471 11472 /* Note : We dont allocate pcpu_refcnt for dummy devices, 11473 * because users of this 'device' dont need to change 11474 * its refcount. 11475 */ 11476 } 11477 11478 /** 11479 * register_netdev - register a network device 11480 * @dev: device to register 11481 * 11482 * Take a completed network device structure and add it to the kernel 11483 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier 11484 * chain. 0 is returned on success. A negative errno code is returned 11485 * on a failure to set up the device, or if the name is a duplicate. 11486 * 11487 * This is a wrapper around register_netdevice that takes the rtnl semaphore 11488 * and expands the device name if you passed a format string to 11489 * alloc_netdev. 11490 */ 11491 int register_netdev(struct net_device *dev) 11492 { 11493 struct net *net = dev_net(dev); 11494 int err; 11495 11496 if (rtnl_net_lock_killable(net)) 11497 return -EINTR; 11498 11499 err = register_netdevice(dev); 11500 11501 rtnl_net_unlock(net); 11502 11503 return err; 11504 } 11505 EXPORT_SYMBOL(register_netdev); 11506 11507 int netdev_refcnt_read(const struct net_device *dev) 11508 { 11509 #ifdef CONFIG_PCPU_DEV_REFCNT 11510 int i, refcnt = 0; 11511 11512 for_each_possible_cpu(i) 11513 refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i); 11514 return refcnt; 11515 #else 11516 return refcount_read(&dev->dev_refcnt); 11517 #endif 11518 } 11519 EXPORT_SYMBOL(netdev_refcnt_read); 11520 11521 int netdev_unregister_timeout_secs __read_mostly = 10; 11522 11523 #define WAIT_REFS_MIN_MSECS 1 11524 #define WAIT_REFS_MAX_MSECS 250 11525 /** 11526 * netdev_wait_allrefs_any - wait until all references are gone. 11527 * @list: list of net_devices to wait on 11528 * 11529 * This is called when unregistering network devices. 11530 * 11531 * Any protocol or device that holds a reference should register 11532 * for netdevice notification, and cleanup and put back the 11533 * reference if they receive an UNREGISTER event. 11534 * We can get stuck here if buggy protocols don't correctly 11535 * call dev_put. 11536 */ 11537 static struct net_device *netdev_wait_allrefs_any(struct list_head *list) 11538 { 11539 unsigned long rebroadcast_time, warning_time; 11540 struct net_device *dev; 11541 int wait = 0; 11542 11543 rebroadcast_time = warning_time = jiffies; 11544 11545 list_for_each_entry(dev, list, todo_list) 11546 if (netdev_refcnt_read(dev) == 1) 11547 return dev; 11548 11549 while (true) { 11550 if (time_after(jiffies, rebroadcast_time + 1 * HZ)) { 11551 rtnl_lock(); 11552 11553 /* Rebroadcast unregister notification */ 11554 list_for_each_entry(dev, list, todo_list) 11555 call_netdevice_notifiers(NETDEV_UNREGISTER, dev); 11556 11557 __rtnl_unlock(); 11558 rcu_barrier(); 11559 rtnl_lock(); 11560 11561 list_for_each_entry(dev, list, todo_list) 11562 if (test_bit(__LINK_STATE_LINKWATCH_PENDING, 11563 &dev->state)) { 11564 /* We must not have linkwatch events 11565 * pending on unregister. If this 11566 * happens, we simply run the queue 11567 * unscheduled, resulting in a noop 11568 * for this device. 11569 */ 11570 linkwatch_run_queue(); 11571 break; 11572 } 11573 11574 __rtnl_unlock(); 11575 11576 rebroadcast_time = jiffies; 11577 } 11578 11579 rcu_barrier(); 11580 11581 if (!wait) { 11582 wait = WAIT_REFS_MIN_MSECS; 11583 } else { 11584 msleep(wait); 11585 wait = min(wait << 1, WAIT_REFS_MAX_MSECS); 11586 } 11587 11588 list_for_each_entry(dev, list, todo_list) 11589 if (netdev_refcnt_read(dev) == 1) 11590 return dev; 11591 11592 if (time_after(jiffies, warning_time + 11593 READ_ONCE(netdev_unregister_timeout_secs) * HZ)) { 11594 list_for_each_entry(dev, list, todo_list) { 11595 pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n", 11596 dev->name, netdev_refcnt_read(dev)); 11597 ref_tracker_dir_print(&dev->refcnt_tracker, 10); 11598 } 11599 11600 warning_time = jiffies; 11601 } 11602 } 11603 } 11604 11605 /* The sequence is: 11606 * 11607 * rtnl_lock(); 11608 * ... 11609 * register_netdevice(x1); 11610 * register_netdevice(x2); 11611 * ... 11612 * unregister_netdevice(y1); 11613 * unregister_netdevice(y2); 11614 * ... 11615 * rtnl_unlock(); 11616 * free_netdev(y1); 11617 * free_netdev(y2); 11618 * 11619 * We are invoked by rtnl_unlock(). 11620 * This allows us to deal with problems: 11621 * 1) We can delete sysfs objects which invoke hotplug 11622 * without deadlocking with linkwatch via keventd. 11623 * 2) Since we run with the RTNL semaphore not held, we can sleep 11624 * safely in order to wait for the netdev refcnt to drop to zero. 11625 * 11626 * We must not return until all unregister events added during 11627 * the interval the lock was held have been completed. 11628 */ 11629 void netdev_run_todo(void) 11630 { 11631 struct net_device *dev, *tmp; 11632 struct list_head list; 11633 int cnt; 11634 #ifdef CONFIG_LOCKDEP 11635 struct list_head unlink_list; 11636 11637 list_replace_init(&net_unlink_list, &unlink_list); 11638 11639 while (!list_empty(&unlink_list)) { 11640 dev = list_first_entry(&unlink_list, struct net_device, 11641 unlink_list); 11642 list_del_init(&dev->unlink_list); 11643 dev->nested_level = dev->lower_level - 1; 11644 } 11645 #endif 11646 11647 /* Snapshot list, allow later requests */ 11648 list_replace_init(&net_todo_list, &list); 11649 11650 __rtnl_unlock(); 11651 11652 /* Wait for rcu callbacks to finish before next phase */ 11653 if (!list_empty(&list)) 11654 rcu_barrier(); 11655 11656 list_for_each_entry_safe(dev, tmp, &list, todo_list) { 11657 if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) { 11658 netdev_WARN(dev, "run_todo but not unregistering\n"); 11659 list_del(&dev->todo_list); 11660 continue; 11661 } 11662 11663 netdev_lock(dev); 11664 WRITE_ONCE(dev->reg_state, NETREG_UNREGISTERED); 11665 netdev_unlock(dev); 11666 linkwatch_sync_dev(dev); 11667 } 11668 11669 cnt = 0; 11670 while (!list_empty(&list)) { 11671 dev = netdev_wait_allrefs_any(&list); 11672 list_del(&dev->todo_list); 11673 11674 /* paranoia */ 11675 BUG_ON(netdev_refcnt_read(dev) != 1); 11676 BUG_ON(!list_empty(&dev->ptype_all)); 11677 BUG_ON(!list_empty(&dev->ptype_specific)); 11678 WARN_ON(rcu_access_pointer(dev->ip_ptr)); 11679 WARN_ON(rcu_access_pointer(dev->ip6_ptr)); 11680 11681 netdev_do_free_pcpu_stats(dev); 11682 if (dev->priv_destructor) 11683 dev->priv_destructor(dev); 11684 if (dev->needs_free_netdev) 11685 free_netdev(dev); 11686 11687 cnt++; 11688 11689 /* Free network device */ 11690 kobject_put(&dev->dev.kobj); 11691 } 11692 if (cnt && atomic_sub_and_test(cnt, &dev_unreg_count)) 11693 wake_up(&netdev_unregistering_wq); 11694 } 11695 11696 /* Collate per-cpu network dstats statistics 11697 * 11698 * Read per-cpu network statistics from dev->dstats and populate the related 11699 * fields in @s. 11700 */ 11701 static void dev_fetch_dstats(struct rtnl_link_stats64 *s, 11702 const struct pcpu_dstats __percpu *dstats) 11703 { 11704 int cpu; 11705 11706 for_each_possible_cpu(cpu) { 11707 u64 rx_packets, rx_bytes, rx_drops; 11708 u64 tx_packets, tx_bytes, tx_drops; 11709 const struct pcpu_dstats *stats; 11710 unsigned int start; 11711 11712 stats = per_cpu_ptr(dstats, cpu); 11713 do { 11714 start = u64_stats_fetch_begin(&stats->syncp); 11715 rx_packets = u64_stats_read(&stats->rx_packets); 11716 rx_bytes = u64_stats_read(&stats->rx_bytes); 11717 rx_drops = u64_stats_read(&stats->rx_drops); 11718 tx_packets = u64_stats_read(&stats->tx_packets); 11719 tx_bytes = u64_stats_read(&stats->tx_bytes); 11720 tx_drops = u64_stats_read(&stats->tx_drops); 11721 } while (u64_stats_fetch_retry(&stats->syncp, start)); 11722 11723 s->rx_packets += rx_packets; 11724 s->rx_bytes += rx_bytes; 11725 s->rx_dropped += rx_drops; 11726 s->tx_packets += tx_packets; 11727 s->tx_bytes += tx_bytes; 11728 s->tx_dropped += tx_drops; 11729 } 11730 } 11731 11732 /* ndo_get_stats64 implementation for dtstats-based accounting. 11733 * 11734 * Populate @s from dev->stats and dev->dstats. This is used internally by the 11735 * core for NETDEV_PCPU_STAT_DSTAT-type stats collection. 11736 */ 11737 static void dev_get_dstats64(const struct net_device *dev, 11738 struct rtnl_link_stats64 *s) 11739 { 11740 netdev_stats_to_stats64(s, &dev->stats); 11741 dev_fetch_dstats(s, dev->dstats); 11742 } 11743 11744 /* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has 11745 * all the same fields in the same order as net_device_stats, with only 11746 * the type differing, but rtnl_link_stats64 may have additional fields 11747 * at the end for newer counters. 11748 */ 11749 void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64, 11750 const struct net_device_stats *netdev_stats) 11751 { 11752 size_t i, n = sizeof(*netdev_stats) / sizeof(atomic_long_t); 11753 const atomic_long_t *src = (atomic_long_t *)netdev_stats; 11754 u64 *dst = (u64 *)stats64; 11755 11756 BUILD_BUG_ON(n > sizeof(*stats64) / sizeof(u64)); 11757 for (i = 0; i < n; i++) 11758 dst[i] = (unsigned long)atomic_long_read(&src[i]); 11759 /* zero out counters that only exist in rtnl_link_stats64 */ 11760 memset((char *)stats64 + n * sizeof(u64), 0, 11761 sizeof(*stats64) - n * sizeof(u64)); 11762 } 11763 EXPORT_SYMBOL(netdev_stats_to_stats64); 11764 11765 static __cold struct net_device_core_stats __percpu *netdev_core_stats_alloc( 11766 struct net_device *dev) 11767 { 11768 struct net_device_core_stats __percpu *p; 11769 11770 p = alloc_percpu_gfp(struct net_device_core_stats, 11771 GFP_ATOMIC | __GFP_NOWARN); 11772 11773 if (p && cmpxchg(&dev->core_stats, NULL, p)) 11774 free_percpu(p); 11775 11776 /* This READ_ONCE() pairs with the cmpxchg() above */ 11777 return READ_ONCE(dev->core_stats); 11778 } 11779 11780 noinline void netdev_core_stats_inc(struct net_device *dev, u32 offset) 11781 { 11782 /* This READ_ONCE() pairs with the write in netdev_core_stats_alloc() */ 11783 struct net_device_core_stats __percpu *p = READ_ONCE(dev->core_stats); 11784 unsigned long __percpu *field; 11785 11786 if (unlikely(!p)) { 11787 p = netdev_core_stats_alloc(dev); 11788 if (!p) 11789 return; 11790 } 11791 11792 field = (unsigned long __percpu *)((void __percpu *)p + offset); 11793 this_cpu_inc(*field); 11794 } 11795 EXPORT_SYMBOL_GPL(netdev_core_stats_inc); 11796 11797 /** 11798 * dev_get_stats - get network device statistics 11799 * @dev: device to get statistics from 11800 * @storage: place to store stats 11801 * 11802 * Get network statistics from device. Return @storage. 11803 * The device driver may provide its own method by setting 11804 * dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats; 11805 * otherwise the internal statistics structure is used. 11806 */ 11807 struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev, 11808 struct rtnl_link_stats64 *storage) 11809 { 11810 const struct net_device_ops *ops = dev->netdev_ops; 11811 const struct net_device_core_stats __percpu *p; 11812 11813 /* 11814 * IPv{4,6} and udp tunnels share common stat helpers and use 11815 * different stat type (NETDEV_PCPU_STAT_TSTATS vs 11816 * NETDEV_PCPU_STAT_DSTATS). Ensure the accounting is consistent. 11817 */ 11818 BUILD_BUG_ON(offsetof(struct pcpu_sw_netstats, rx_bytes) != 11819 offsetof(struct pcpu_dstats, rx_bytes)); 11820 BUILD_BUG_ON(offsetof(struct pcpu_sw_netstats, rx_packets) != 11821 offsetof(struct pcpu_dstats, rx_packets)); 11822 BUILD_BUG_ON(offsetof(struct pcpu_sw_netstats, tx_bytes) != 11823 offsetof(struct pcpu_dstats, tx_bytes)); 11824 BUILD_BUG_ON(offsetof(struct pcpu_sw_netstats, tx_packets) != 11825 offsetof(struct pcpu_dstats, tx_packets)); 11826 11827 if (ops->ndo_get_stats64) { 11828 memset(storage, 0, sizeof(*storage)); 11829 ops->ndo_get_stats64(dev, storage); 11830 } else if (ops->ndo_get_stats) { 11831 netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev)); 11832 } else if (dev->pcpu_stat_type == NETDEV_PCPU_STAT_TSTATS) { 11833 dev_get_tstats64(dev, storage); 11834 } else if (dev->pcpu_stat_type == NETDEV_PCPU_STAT_DSTATS) { 11835 dev_get_dstats64(dev, storage); 11836 } else { 11837 netdev_stats_to_stats64(storage, &dev->stats); 11838 } 11839 11840 /* This READ_ONCE() pairs with the write in netdev_core_stats_alloc() */ 11841 p = READ_ONCE(dev->core_stats); 11842 if (p) { 11843 const struct net_device_core_stats *core_stats; 11844 int i; 11845 11846 for_each_possible_cpu(i) { 11847 core_stats = per_cpu_ptr(p, i); 11848 storage->rx_dropped += READ_ONCE(core_stats->rx_dropped); 11849 storage->tx_dropped += READ_ONCE(core_stats->tx_dropped); 11850 storage->rx_nohandler += READ_ONCE(core_stats->rx_nohandler); 11851 storage->rx_otherhost_dropped += READ_ONCE(core_stats->rx_otherhost_dropped); 11852 } 11853 } 11854 return storage; 11855 } 11856 EXPORT_SYMBOL(dev_get_stats); 11857 11858 /** 11859 * dev_fetch_sw_netstats - get per-cpu network device statistics 11860 * @s: place to store stats 11861 * @netstats: per-cpu network stats to read from 11862 * 11863 * Read per-cpu network statistics and populate the related fields in @s. 11864 */ 11865 void dev_fetch_sw_netstats(struct rtnl_link_stats64 *s, 11866 const struct pcpu_sw_netstats __percpu *netstats) 11867 { 11868 int cpu; 11869 11870 for_each_possible_cpu(cpu) { 11871 u64 rx_packets, rx_bytes, tx_packets, tx_bytes; 11872 const struct pcpu_sw_netstats *stats; 11873 unsigned int start; 11874 11875 stats = per_cpu_ptr(netstats, cpu); 11876 do { 11877 start = u64_stats_fetch_begin(&stats->syncp); 11878 rx_packets = u64_stats_read(&stats->rx_packets); 11879 rx_bytes = u64_stats_read(&stats->rx_bytes); 11880 tx_packets = u64_stats_read(&stats->tx_packets); 11881 tx_bytes = u64_stats_read(&stats->tx_bytes); 11882 } while (u64_stats_fetch_retry(&stats->syncp, start)); 11883 11884 s->rx_packets += rx_packets; 11885 s->rx_bytes += rx_bytes; 11886 s->tx_packets += tx_packets; 11887 s->tx_bytes += tx_bytes; 11888 } 11889 } 11890 EXPORT_SYMBOL_GPL(dev_fetch_sw_netstats); 11891 11892 /** 11893 * dev_get_tstats64 - ndo_get_stats64 implementation 11894 * @dev: device to get statistics from 11895 * @s: place to store stats 11896 * 11897 * Populate @s from dev->stats and dev->tstats. Can be used as 11898 * ndo_get_stats64() callback. 11899 */ 11900 void dev_get_tstats64(struct net_device *dev, struct rtnl_link_stats64 *s) 11901 { 11902 netdev_stats_to_stats64(s, &dev->stats); 11903 dev_fetch_sw_netstats(s, dev->tstats); 11904 } 11905 EXPORT_SYMBOL_GPL(dev_get_tstats64); 11906 11907 struct netdev_queue *dev_ingress_queue_create(struct net_device *dev) 11908 { 11909 struct netdev_queue *queue = dev_ingress_queue(dev); 11910 11911 #ifdef CONFIG_NET_CLS_ACT 11912 if (queue) 11913 return queue; 11914 queue = kzalloc(sizeof(*queue), GFP_KERNEL); 11915 if (!queue) 11916 return NULL; 11917 netdev_init_one_queue(dev, queue, NULL); 11918 RCU_INIT_POINTER(queue->qdisc, &noop_qdisc); 11919 RCU_INIT_POINTER(queue->qdisc_sleeping, &noop_qdisc); 11920 rcu_assign_pointer(dev->ingress_queue, queue); 11921 #endif 11922 return queue; 11923 } 11924 11925 static const struct ethtool_ops default_ethtool_ops; 11926 11927 void netdev_set_default_ethtool_ops(struct net_device *dev, 11928 const struct ethtool_ops *ops) 11929 { 11930 if (dev->ethtool_ops == &default_ethtool_ops) 11931 dev->ethtool_ops = ops; 11932 } 11933 EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops); 11934 11935 /** 11936 * netdev_sw_irq_coalesce_default_on() - enable SW IRQ coalescing by default 11937 * @dev: netdev to enable the IRQ coalescing on 11938 * 11939 * Sets a conservative default for SW IRQ coalescing. Users can use 11940 * sysfs attributes to override the default values. 11941 */ 11942 void netdev_sw_irq_coalesce_default_on(struct net_device *dev) 11943 { 11944 WARN_ON(dev->reg_state == NETREG_REGISTERED); 11945 11946 if (!IS_ENABLED(CONFIG_PREEMPT_RT)) { 11947 netdev_set_gro_flush_timeout(dev, 20000); 11948 netdev_set_defer_hard_irqs(dev, 1); 11949 } 11950 } 11951 EXPORT_SYMBOL_GPL(netdev_sw_irq_coalesce_default_on); 11952 11953 /** 11954 * alloc_netdev_mqs - allocate network device 11955 * @sizeof_priv: size of private data to allocate space for 11956 * @name: device name format string 11957 * @name_assign_type: origin of device name 11958 * @setup: callback to initialize device 11959 * @txqs: the number of TX subqueues to allocate 11960 * @rxqs: the number of RX subqueues to allocate 11961 * 11962 * Allocates a struct net_device with private data area for driver use 11963 * and performs basic initialization. Also allocates subqueue structs 11964 * for each queue on the device. 11965 */ 11966 struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name, 11967 unsigned char name_assign_type, 11968 void (*setup)(struct net_device *), 11969 unsigned int txqs, unsigned int rxqs) 11970 { 11971 struct net_device *dev; 11972 size_t napi_config_sz; 11973 unsigned int maxqs; 11974 11975 BUG_ON(strlen(name) >= sizeof(dev->name)); 11976 11977 if (txqs < 1) { 11978 pr_err("alloc_netdev: Unable to allocate device with zero queues\n"); 11979 return NULL; 11980 } 11981 11982 if (rxqs < 1) { 11983 pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n"); 11984 return NULL; 11985 } 11986 11987 maxqs = max(txqs, rxqs); 11988 11989 dev = kvzalloc(struct_size(dev, priv, sizeof_priv), 11990 GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL); 11991 if (!dev) 11992 return NULL; 11993 11994 dev->priv_len = sizeof_priv; 11995 11996 ref_tracker_dir_init(&dev->refcnt_tracker, 128, "netdev"); 11997 #ifdef CONFIG_PCPU_DEV_REFCNT 11998 dev->pcpu_refcnt = alloc_percpu(int); 11999 if (!dev->pcpu_refcnt) 12000 goto free_dev; 12001 __dev_hold(dev); 12002 #else 12003 refcount_set(&dev->dev_refcnt, 1); 12004 #endif 12005 12006 if (dev_addr_init(dev)) 12007 goto free_pcpu; 12008 12009 dev_mc_init(dev); 12010 dev_uc_init(dev); 12011 12012 dev_net_set(dev, &init_net); 12013 12014 dev->gso_max_size = GSO_LEGACY_MAX_SIZE; 12015 dev->xdp_zc_max_segs = 1; 12016 dev->gso_max_segs = GSO_MAX_SEGS; 12017 dev->gro_max_size = GRO_LEGACY_MAX_SIZE; 12018 dev->gso_ipv4_max_size = GSO_LEGACY_MAX_SIZE; 12019 dev->gro_ipv4_max_size = GRO_LEGACY_MAX_SIZE; 12020 dev->tso_max_size = TSO_LEGACY_MAX_SIZE; 12021 dev->tso_max_segs = TSO_MAX_SEGS; 12022 dev->upper_level = 1; 12023 dev->lower_level = 1; 12024 #ifdef CONFIG_LOCKDEP 12025 dev->nested_level = 0; 12026 INIT_LIST_HEAD(&dev->unlink_list); 12027 #endif 12028 12029 INIT_LIST_HEAD(&dev->napi_list); 12030 INIT_LIST_HEAD(&dev->unreg_list); 12031 INIT_LIST_HEAD(&dev->close_list); 12032 INIT_LIST_HEAD(&dev->link_watch_list); 12033 INIT_LIST_HEAD(&dev->adj_list.upper); 12034 INIT_LIST_HEAD(&dev->adj_list.lower); 12035 INIT_LIST_HEAD(&dev->ptype_all); 12036 INIT_LIST_HEAD(&dev->ptype_specific); 12037 INIT_LIST_HEAD(&dev->net_notifier_list); 12038 #ifdef CONFIG_NET_SCHED 12039 hash_init(dev->qdisc_hash); 12040 #endif 12041 12042 mutex_init(&dev->lock); 12043 12044 dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM; 12045 setup(dev); 12046 12047 if (!dev->tx_queue_len) { 12048 dev->priv_flags |= IFF_NO_QUEUE; 12049 dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN; 12050 } 12051 12052 dev->num_tx_queues = txqs; 12053 dev->real_num_tx_queues = txqs; 12054 if (netif_alloc_netdev_queues(dev)) 12055 goto free_all; 12056 12057 dev->num_rx_queues = rxqs; 12058 dev->real_num_rx_queues = rxqs; 12059 if (netif_alloc_rx_queues(dev)) 12060 goto free_all; 12061 dev->ethtool = kzalloc(sizeof(*dev->ethtool), GFP_KERNEL_ACCOUNT); 12062 if (!dev->ethtool) 12063 goto free_all; 12064 12065 dev->cfg = kzalloc(sizeof(*dev->cfg), GFP_KERNEL_ACCOUNT); 12066 if (!dev->cfg) 12067 goto free_all; 12068 dev->cfg_pending = dev->cfg; 12069 12070 dev->num_napi_configs = maxqs; 12071 napi_config_sz = array_size(maxqs, sizeof(*dev->napi_config)); 12072 dev->napi_config = kvzalloc(napi_config_sz, GFP_KERNEL_ACCOUNT); 12073 if (!dev->napi_config) 12074 goto free_all; 12075 12076 strscpy(dev->name, name); 12077 dev->name_assign_type = name_assign_type; 12078 dev->group = INIT_NETDEV_GROUP; 12079 if (!dev->ethtool_ops) 12080 dev->ethtool_ops = &default_ethtool_ops; 12081 12082 nf_hook_netdev_init(dev); 12083 12084 return dev; 12085 12086 free_all: 12087 free_netdev(dev); 12088 return NULL; 12089 12090 free_pcpu: 12091 #ifdef CONFIG_PCPU_DEV_REFCNT 12092 free_percpu(dev->pcpu_refcnt); 12093 free_dev: 12094 #endif 12095 kvfree(dev); 12096 return NULL; 12097 } 12098 EXPORT_SYMBOL(alloc_netdev_mqs); 12099 12100 static void netdev_napi_exit(struct net_device *dev) 12101 { 12102 if (!list_empty(&dev->napi_list)) { 12103 struct napi_struct *p, *n; 12104 12105 netdev_lock(dev); 12106 list_for_each_entry_safe(p, n, &dev->napi_list, dev_list) 12107 __netif_napi_del_locked(p); 12108 netdev_unlock(dev); 12109 12110 synchronize_net(); 12111 } 12112 12113 kvfree(dev->napi_config); 12114 } 12115 12116 /** 12117 * free_netdev - free network device 12118 * @dev: device 12119 * 12120 * This function does the last stage of destroying an allocated device 12121 * interface. The reference to the device object is released. If this 12122 * is the last reference then it will be freed.Must be called in process 12123 * context. 12124 */ 12125 void free_netdev(struct net_device *dev) 12126 { 12127 might_sleep(); 12128 12129 /* When called immediately after register_netdevice() failed the unwind 12130 * handling may still be dismantling the device. Handle that case by 12131 * deferring the free. 12132 */ 12133 if (dev->reg_state == NETREG_UNREGISTERING) { 12134 ASSERT_RTNL(); 12135 dev->needs_free_netdev = true; 12136 return; 12137 } 12138 12139 WARN_ON(dev->cfg != dev->cfg_pending); 12140 kfree(dev->cfg); 12141 kfree(dev->ethtool); 12142 netif_free_tx_queues(dev); 12143 netif_free_rx_queues(dev); 12144 12145 kfree(rcu_dereference_protected(dev->ingress_queue, 1)); 12146 12147 /* Flush device addresses */ 12148 dev_addr_flush(dev); 12149 12150 netdev_napi_exit(dev); 12151 12152 netif_del_cpu_rmap(dev); 12153 12154 ref_tracker_dir_exit(&dev->refcnt_tracker); 12155 #ifdef CONFIG_PCPU_DEV_REFCNT 12156 free_percpu(dev->pcpu_refcnt); 12157 dev->pcpu_refcnt = NULL; 12158 #endif 12159 free_percpu(dev->core_stats); 12160 dev->core_stats = NULL; 12161 free_percpu(dev->xdp_bulkq); 12162 dev->xdp_bulkq = NULL; 12163 12164 netdev_free_phy_link_topology(dev); 12165 12166 mutex_destroy(&dev->lock); 12167 12168 /* Compatibility with error handling in drivers */ 12169 if (dev->reg_state == NETREG_UNINITIALIZED || 12170 dev->reg_state == NETREG_DUMMY) { 12171 kvfree(dev); 12172 return; 12173 } 12174 12175 BUG_ON(dev->reg_state != NETREG_UNREGISTERED); 12176 WRITE_ONCE(dev->reg_state, NETREG_RELEASED); 12177 12178 /* will free via device release */ 12179 put_device(&dev->dev); 12180 } 12181 EXPORT_SYMBOL(free_netdev); 12182 12183 /** 12184 * alloc_netdev_dummy - Allocate and initialize a dummy net device. 12185 * @sizeof_priv: size of private data to allocate space for 12186 * 12187 * Return: the allocated net_device on success, NULL otherwise 12188 */ 12189 struct net_device *alloc_netdev_dummy(int sizeof_priv) 12190 { 12191 return alloc_netdev(sizeof_priv, "dummy#", NET_NAME_UNKNOWN, 12192 init_dummy_netdev); 12193 } 12194 EXPORT_SYMBOL_GPL(alloc_netdev_dummy); 12195 12196 /** 12197 * synchronize_net - Synchronize with packet receive processing 12198 * 12199 * Wait for packets currently being received to be done. 12200 * Does not block later packets from starting. 12201 */ 12202 void synchronize_net(void) 12203 { 12204 might_sleep(); 12205 if (from_cleanup_net() || rtnl_is_locked()) 12206 synchronize_rcu_expedited(); 12207 else 12208 synchronize_rcu(); 12209 } 12210 EXPORT_SYMBOL(synchronize_net); 12211 12212 static void netdev_rss_contexts_free(struct net_device *dev) 12213 { 12214 struct ethtool_rxfh_context *ctx; 12215 unsigned long context; 12216 12217 mutex_lock(&dev->ethtool->rss_lock); 12218 xa_for_each(&dev->ethtool->rss_ctx, context, ctx) { 12219 xa_erase(&dev->ethtool->rss_ctx, context); 12220 dev->ethtool_ops->remove_rxfh_context(dev, ctx, context, NULL); 12221 kfree(ctx); 12222 } 12223 xa_destroy(&dev->ethtool->rss_ctx); 12224 mutex_unlock(&dev->ethtool->rss_lock); 12225 } 12226 12227 /** 12228 * unregister_netdevice_queue - remove device from the kernel 12229 * @dev: device 12230 * @head: list 12231 * 12232 * This function shuts down a device interface and removes it 12233 * from the kernel tables. 12234 * If head not NULL, device is queued to be unregistered later. 12235 * 12236 * Callers must hold the rtnl semaphore. You may want 12237 * unregister_netdev() instead of this. 12238 */ 12239 12240 void unregister_netdevice_queue(struct net_device *dev, struct list_head *head) 12241 { 12242 ASSERT_RTNL(); 12243 12244 if (head) { 12245 list_move_tail(&dev->unreg_list, head); 12246 } else { 12247 LIST_HEAD(single); 12248 12249 list_add(&dev->unreg_list, &single); 12250 unregister_netdevice_many(&single); 12251 } 12252 } 12253 EXPORT_SYMBOL(unregister_netdevice_queue); 12254 12255 static void dev_memory_provider_uninstall(struct net_device *dev) 12256 { 12257 unsigned int i; 12258 12259 for (i = 0; i < dev->real_num_rx_queues; i++) { 12260 struct netdev_rx_queue *rxq = &dev->_rx[i]; 12261 struct pp_memory_provider_params *p = &rxq->mp_params; 12262 12263 if (p->mp_ops && p->mp_ops->uninstall) 12264 p->mp_ops->uninstall(rxq->mp_params.mp_priv, rxq); 12265 } 12266 } 12267 12268 /* devices must be UP and netdev_lock()'d */ 12269 static void netif_close_many_and_unlock(struct list_head *close_head) 12270 { 12271 struct net_device *dev, *tmp; 12272 12273 netif_close_many(close_head, false); 12274 12275 /* ... now unlock them */ 12276 list_for_each_entry_safe(dev, tmp, close_head, close_list) { 12277 netdev_unlock(dev); 12278 list_del_init(&dev->close_list); 12279 } 12280 } 12281 12282 static void netif_close_many_and_unlock_cond(struct list_head *close_head) 12283 { 12284 #ifdef CONFIG_LOCKDEP 12285 /* We can only track up to MAX_LOCK_DEPTH locks per task. 12286 * 12287 * Reserve half the available slots for additional locks possibly 12288 * taken by notifiers and (soft)irqs. 12289 */ 12290 unsigned int limit = MAX_LOCK_DEPTH / 2; 12291 12292 if (lockdep_depth(current) > limit) 12293 netif_close_many_and_unlock(close_head); 12294 #endif 12295 } 12296 12297 void unregister_netdevice_many_notify(struct list_head *head, 12298 u32 portid, const struct nlmsghdr *nlh) 12299 { 12300 struct net_device *dev, *tmp; 12301 LIST_HEAD(close_head); 12302 int cnt = 0; 12303 12304 BUG_ON(dev_boot_phase); 12305 ASSERT_RTNL(); 12306 12307 if (list_empty(head)) 12308 return; 12309 12310 list_for_each_entry_safe(dev, tmp, head, unreg_list) { 12311 /* Some devices call without registering 12312 * for initialization unwind. Remove those 12313 * devices and proceed with the remaining. 12314 */ 12315 if (dev->reg_state == NETREG_UNINITIALIZED) { 12316 pr_debug("unregister_netdevice: device %s/%p never was registered\n", 12317 dev->name, dev); 12318 12319 WARN_ON(1); 12320 list_del(&dev->unreg_list); 12321 continue; 12322 } 12323 dev->dismantle = true; 12324 BUG_ON(dev->reg_state != NETREG_REGISTERED); 12325 } 12326 12327 /* If device is running, close it first. Start with ops locked... */ 12328 list_for_each_entry(dev, head, unreg_list) { 12329 if (!(dev->flags & IFF_UP)) 12330 continue; 12331 if (netdev_need_ops_lock(dev)) { 12332 list_add_tail(&dev->close_list, &close_head); 12333 netdev_lock(dev); 12334 } 12335 netif_close_many_and_unlock_cond(&close_head); 12336 } 12337 netif_close_many_and_unlock(&close_head); 12338 /* ... now go over the rest. */ 12339 list_for_each_entry(dev, head, unreg_list) { 12340 if (!netdev_need_ops_lock(dev)) 12341 list_add_tail(&dev->close_list, &close_head); 12342 } 12343 netif_close_many(&close_head, true); 12344 12345 list_for_each_entry(dev, head, unreg_list) { 12346 /* And unlink it from device chain. */ 12347 unlist_netdevice(dev); 12348 netdev_lock(dev); 12349 WRITE_ONCE(dev->reg_state, NETREG_UNREGISTERING); 12350 netdev_unlock(dev); 12351 } 12352 flush_all_backlogs(); 12353 12354 synchronize_net(); 12355 12356 list_for_each_entry(dev, head, unreg_list) { 12357 struct sk_buff *skb = NULL; 12358 12359 /* Shutdown queueing discipline. */ 12360 netdev_lock_ops(dev); 12361 dev_shutdown(dev); 12362 dev_tcx_uninstall(dev); 12363 dev_xdp_uninstall(dev); 12364 dev_memory_provider_uninstall(dev); 12365 netdev_unlock_ops(dev); 12366 bpf_dev_bound_netdev_unregister(dev); 12367 12368 netdev_offload_xstats_disable_all(dev); 12369 12370 /* Notify protocols, that we are about to destroy 12371 * this device. They should clean all the things. 12372 */ 12373 call_netdevice_notifiers(NETDEV_UNREGISTER, dev); 12374 12375 if (!(dev->rtnl_link_ops && dev->rtnl_link_initializing)) 12376 skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0, 12377 GFP_KERNEL, NULL, 0, 12378 portid, nlh); 12379 12380 /* 12381 * Flush the unicast and multicast chains 12382 */ 12383 dev_uc_flush(dev); 12384 dev_mc_flush(dev); 12385 12386 netdev_name_node_alt_flush(dev); 12387 netdev_name_node_free(dev->name_node); 12388 12389 netdev_rss_contexts_free(dev); 12390 12391 call_netdevice_notifiers(NETDEV_PRE_UNINIT, dev); 12392 12393 if (dev->netdev_ops->ndo_uninit) 12394 dev->netdev_ops->ndo_uninit(dev); 12395 12396 mutex_destroy(&dev->ethtool->rss_lock); 12397 12398 net_shaper_flush_netdev(dev); 12399 12400 if (skb) 12401 rtmsg_ifinfo_send(skb, dev, GFP_KERNEL, portid, nlh); 12402 12403 /* Notifier chain MUST detach us all upper devices. */ 12404 WARN_ON(netdev_has_any_upper_dev(dev)); 12405 WARN_ON(netdev_has_any_lower_dev(dev)); 12406 12407 /* Remove entries from kobject tree */ 12408 netdev_unregister_kobject(dev); 12409 #ifdef CONFIG_XPS 12410 /* Remove XPS queueing entries */ 12411 netif_reset_xps_queues_gt(dev, 0); 12412 #endif 12413 } 12414 12415 synchronize_net(); 12416 12417 list_for_each_entry(dev, head, unreg_list) { 12418 netdev_put(dev, &dev->dev_registered_tracker); 12419 net_set_todo(dev); 12420 cnt++; 12421 } 12422 atomic_add(cnt, &dev_unreg_count); 12423 12424 list_del(head); 12425 } 12426 12427 /** 12428 * unregister_netdevice_many - unregister many devices 12429 * @head: list of devices 12430 * 12431 * Note: As most callers use a stack allocated list_head, 12432 * we force a list_del() to make sure stack won't be corrupted later. 12433 */ 12434 void unregister_netdevice_many(struct list_head *head) 12435 { 12436 unregister_netdevice_many_notify(head, 0, NULL); 12437 } 12438 EXPORT_SYMBOL(unregister_netdevice_many); 12439 12440 /** 12441 * unregister_netdev - remove device from the kernel 12442 * @dev: device 12443 * 12444 * This function shuts down a device interface and removes it 12445 * from the kernel tables. 12446 * 12447 * This is just a wrapper for unregister_netdevice that takes 12448 * the rtnl semaphore. In general you want to use this and not 12449 * unregister_netdevice. 12450 */ 12451 void unregister_netdev(struct net_device *dev) 12452 { 12453 rtnl_net_dev_lock(dev); 12454 unregister_netdevice(dev); 12455 rtnl_net_dev_unlock(dev); 12456 } 12457 EXPORT_SYMBOL(unregister_netdev); 12458 12459 int __dev_change_net_namespace(struct net_device *dev, struct net *net, 12460 const char *pat, int new_ifindex, 12461 struct netlink_ext_ack *extack) 12462 { 12463 struct netdev_name_node *name_node; 12464 struct net *net_old = dev_net(dev); 12465 char new_name[IFNAMSIZ] = {}; 12466 int err, new_nsid; 12467 12468 ASSERT_RTNL(); 12469 12470 /* Don't allow namespace local devices to be moved. */ 12471 err = -EINVAL; 12472 if (dev->netns_immutable) { 12473 NL_SET_ERR_MSG(extack, "The interface netns is immutable"); 12474 goto out; 12475 } 12476 12477 /* Ensure the device has been registered */ 12478 if (dev->reg_state != NETREG_REGISTERED) { 12479 NL_SET_ERR_MSG(extack, "The interface isn't registered"); 12480 goto out; 12481 } 12482 12483 /* Get out if there is nothing todo */ 12484 err = 0; 12485 if (net_eq(net_old, net)) 12486 goto out; 12487 12488 /* Pick the destination device name, and ensure 12489 * we can use it in the destination network namespace. 12490 */ 12491 err = -EEXIST; 12492 if (netdev_name_in_use(net, dev->name)) { 12493 /* We get here if we can't use the current device name */ 12494 if (!pat) { 12495 NL_SET_ERR_MSG(extack, 12496 "An interface with the same name exists in the target netns"); 12497 goto out; 12498 } 12499 err = dev_prep_valid_name(net, dev, pat, new_name, EEXIST); 12500 if (err < 0) { 12501 NL_SET_ERR_MSG_FMT(extack, 12502 "Unable to use '%s' for the new interface name in the target netns", 12503 pat); 12504 goto out; 12505 } 12506 } 12507 /* Check that none of the altnames conflicts. */ 12508 err = -EEXIST; 12509 netdev_for_each_altname(dev, name_node) { 12510 if (netdev_name_in_use(net, name_node->name)) { 12511 NL_SET_ERR_MSG_FMT(extack, 12512 "An interface with the altname %s exists in the target netns", 12513 name_node->name); 12514 goto out; 12515 } 12516 } 12517 12518 /* Check that new_ifindex isn't used yet. */ 12519 if (new_ifindex) { 12520 err = dev_index_reserve(net, new_ifindex); 12521 if (err < 0) { 12522 NL_SET_ERR_MSG_FMT(extack, 12523 "The ifindex %d is not available in the target netns", 12524 new_ifindex); 12525 goto out; 12526 } 12527 } else { 12528 /* If there is an ifindex conflict assign a new one */ 12529 err = dev_index_reserve(net, dev->ifindex); 12530 if (err == -EBUSY) 12531 err = dev_index_reserve(net, 0); 12532 if (err < 0) { 12533 NL_SET_ERR_MSG(extack, 12534 "Unable to allocate a new ifindex in the target netns"); 12535 goto out; 12536 } 12537 new_ifindex = err; 12538 } 12539 12540 /* 12541 * And now a mini version of register_netdevice unregister_netdevice. 12542 */ 12543 12544 netdev_lock_ops(dev); 12545 /* If device is running close it first. */ 12546 netif_close(dev); 12547 /* And unlink it from device chain */ 12548 unlist_netdevice(dev); 12549 12550 if (!netdev_need_ops_lock(dev)) 12551 netdev_lock(dev); 12552 dev->moving_ns = true; 12553 netdev_unlock(dev); 12554 12555 synchronize_net(); 12556 12557 /* Shutdown queueing discipline. */ 12558 netdev_lock_ops(dev); 12559 dev_shutdown(dev); 12560 netdev_unlock_ops(dev); 12561 12562 /* Notify protocols, that we are about to destroy 12563 * this device. They should clean all the things. 12564 * 12565 * Note that dev->reg_state stays at NETREG_REGISTERED. 12566 * This is wanted because this way 8021q and macvlan know 12567 * the device is just moving and can keep their slaves up. 12568 */ 12569 call_netdevice_notifiers(NETDEV_UNREGISTER, dev); 12570 rcu_barrier(); 12571 12572 new_nsid = peernet2id_alloc(dev_net(dev), net, GFP_KERNEL); 12573 12574 rtmsg_ifinfo_newnet(RTM_DELLINK, dev, ~0U, GFP_KERNEL, &new_nsid, 12575 new_ifindex); 12576 12577 /* 12578 * Flush the unicast and multicast chains 12579 */ 12580 dev_uc_flush(dev); 12581 dev_mc_flush(dev); 12582 12583 /* Send a netdev-removed uevent to the old namespace */ 12584 kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE); 12585 netdev_adjacent_del_links(dev); 12586 12587 /* Move per-net netdevice notifiers that are following the netdevice */ 12588 move_netdevice_notifiers_dev_net(dev, net); 12589 12590 /* Actually switch the network namespace */ 12591 netdev_lock(dev); 12592 dev_net_set(dev, net); 12593 netdev_unlock(dev); 12594 dev->ifindex = new_ifindex; 12595 12596 if (new_name[0]) { 12597 /* Rename the netdev to prepared name */ 12598 write_seqlock_bh(&netdev_rename_lock); 12599 strscpy(dev->name, new_name, IFNAMSIZ); 12600 write_sequnlock_bh(&netdev_rename_lock); 12601 } 12602 12603 /* Fixup kobjects */ 12604 dev_set_uevent_suppress(&dev->dev, 1); 12605 err = device_rename(&dev->dev, dev->name); 12606 dev_set_uevent_suppress(&dev->dev, 0); 12607 WARN_ON(err); 12608 12609 /* Send a netdev-add uevent to the new namespace */ 12610 kobject_uevent(&dev->dev.kobj, KOBJ_ADD); 12611 netdev_adjacent_add_links(dev); 12612 12613 /* Adapt owner in case owning user namespace of target network 12614 * namespace is different from the original one. 12615 */ 12616 err = netdev_change_owner(dev, net_old, net); 12617 WARN_ON(err); 12618 12619 netdev_lock(dev); 12620 dev->moving_ns = false; 12621 if (!netdev_need_ops_lock(dev)) 12622 netdev_unlock(dev); 12623 12624 /* Add the device back in the hashes */ 12625 list_netdevice(dev); 12626 /* Notify protocols, that a new device appeared. */ 12627 call_netdevice_notifiers(NETDEV_REGISTER, dev); 12628 netdev_unlock_ops(dev); 12629 12630 /* 12631 * Prevent userspace races by waiting until the network 12632 * device is fully setup before sending notifications. 12633 */ 12634 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL, 0, NULL); 12635 12636 synchronize_net(); 12637 err = 0; 12638 out: 12639 return err; 12640 } 12641 12642 static int dev_cpu_dead(unsigned int oldcpu) 12643 { 12644 struct sk_buff **list_skb; 12645 struct sk_buff *skb; 12646 unsigned int cpu; 12647 struct softnet_data *sd, *oldsd, *remsd = NULL; 12648 12649 local_irq_disable(); 12650 cpu = smp_processor_id(); 12651 sd = &per_cpu(softnet_data, cpu); 12652 oldsd = &per_cpu(softnet_data, oldcpu); 12653 12654 /* Find end of our completion_queue. */ 12655 list_skb = &sd->completion_queue; 12656 while (*list_skb) 12657 list_skb = &(*list_skb)->next; 12658 /* Append completion queue from offline CPU. */ 12659 *list_skb = oldsd->completion_queue; 12660 oldsd->completion_queue = NULL; 12661 12662 /* Append output queue from offline CPU. */ 12663 if (oldsd->output_queue) { 12664 *sd->output_queue_tailp = oldsd->output_queue; 12665 sd->output_queue_tailp = oldsd->output_queue_tailp; 12666 oldsd->output_queue = NULL; 12667 oldsd->output_queue_tailp = &oldsd->output_queue; 12668 } 12669 /* Append NAPI poll list from offline CPU, with one exception : 12670 * process_backlog() must be called by cpu owning percpu backlog. 12671 * We properly handle process_queue & input_pkt_queue later. 12672 */ 12673 while (!list_empty(&oldsd->poll_list)) { 12674 struct napi_struct *napi = list_first_entry(&oldsd->poll_list, 12675 struct napi_struct, 12676 poll_list); 12677 12678 list_del_init(&napi->poll_list); 12679 if (napi->poll == process_backlog) 12680 napi->state &= NAPIF_STATE_THREADED; 12681 else 12682 ____napi_schedule(sd, napi); 12683 } 12684 12685 raise_softirq_irqoff(NET_TX_SOFTIRQ); 12686 local_irq_enable(); 12687 12688 if (!use_backlog_threads()) { 12689 #ifdef CONFIG_RPS 12690 remsd = oldsd->rps_ipi_list; 12691 oldsd->rps_ipi_list = NULL; 12692 #endif 12693 /* send out pending IPI's on offline CPU */ 12694 net_rps_send_ipi(remsd); 12695 } 12696 12697 /* Process offline CPU's input_pkt_queue */ 12698 while ((skb = __skb_dequeue(&oldsd->process_queue))) { 12699 netif_rx(skb); 12700 rps_input_queue_head_incr(oldsd); 12701 } 12702 while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) { 12703 netif_rx(skb); 12704 rps_input_queue_head_incr(oldsd); 12705 } 12706 12707 return 0; 12708 } 12709 12710 /** 12711 * netdev_increment_features - increment feature set by one 12712 * @all: current feature set 12713 * @one: new feature set 12714 * @mask: mask feature set 12715 * 12716 * Computes a new feature set after adding a device with feature set 12717 * @one to the master device with current feature set @all. Will not 12718 * enable anything that is off in @mask. Returns the new feature set. 12719 */ 12720 netdev_features_t netdev_increment_features(netdev_features_t all, 12721 netdev_features_t one, netdev_features_t mask) 12722 { 12723 if (mask & NETIF_F_HW_CSUM) 12724 mask |= NETIF_F_CSUM_MASK; 12725 mask |= NETIF_F_VLAN_CHALLENGED; 12726 12727 all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask; 12728 all &= one | ~NETIF_F_ALL_FOR_ALL; 12729 12730 /* If one device supports hw checksumming, set for all. */ 12731 if (all & NETIF_F_HW_CSUM) 12732 all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM); 12733 12734 return all; 12735 } 12736 EXPORT_SYMBOL(netdev_increment_features); 12737 12738 /** 12739 * netdev_compute_master_upper_features - compute feature from lowers 12740 * @dev: the upper device 12741 * @update_header: whether to update upper device's header_len/headroom/tailroom 12742 * 12743 * Recompute the upper device's feature based on all lower devices. 12744 */ 12745 void netdev_compute_master_upper_features(struct net_device *dev, bool update_header) 12746 { 12747 unsigned int dst_release_flag = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM; 12748 netdev_features_t gso_partial_features = MASTER_UPPER_DEV_GSO_PARTIAL_FEATURES; 12749 netdev_features_t xfrm_features = MASTER_UPPER_DEV_XFRM_FEATURES; 12750 netdev_features_t mpls_features = MASTER_UPPER_DEV_MPLS_FEATURES; 12751 netdev_features_t vlan_features = MASTER_UPPER_DEV_VLAN_FEATURES; 12752 netdev_features_t enc_features = MASTER_UPPER_DEV_ENC_FEATURES; 12753 unsigned short max_header_len = ETH_HLEN; 12754 unsigned int tso_max_size = TSO_MAX_SIZE; 12755 unsigned short max_headroom = 0; 12756 unsigned short max_tailroom = 0; 12757 u16 tso_max_segs = TSO_MAX_SEGS; 12758 struct net_device *lower_dev; 12759 struct list_head *iter; 12760 12761 mpls_features = netdev_base_features(mpls_features); 12762 vlan_features = netdev_base_features(vlan_features); 12763 enc_features = netdev_base_features(enc_features); 12764 12765 netdev_for_each_lower_dev(dev, lower_dev, iter) { 12766 gso_partial_features = netdev_increment_features(gso_partial_features, 12767 lower_dev->gso_partial_features, 12768 MASTER_UPPER_DEV_GSO_PARTIAL_FEATURES); 12769 12770 vlan_features = netdev_increment_features(vlan_features, 12771 lower_dev->vlan_features, 12772 MASTER_UPPER_DEV_VLAN_FEATURES); 12773 12774 enc_features = netdev_increment_features(enc_features, 12775 lower_dev->hw_enc_features, 12776 MASTER_UPPER_DEV_ENC_FEATURES); 12777 12778 if (IS_ENABLED(CONFIG_XFRM_OFFLOAD)) 12779 xfrm_features = netdev_increment_features(xfrm_features, 12780 lower_dev->hw_enc_features, 12781 MASTER_UPPER_DEV_XFRM_FEATURES); 12782 12783 mpls_features = netdev_increment_features(mpls_features, 12784 lower_dev->mpls_features, 12785 MASTER_UPPER_DEV_MPLS_FEATURES); 12786 12787 dst_release_flag &= lower_dev->priv_flags; 12788 12789 if (update_header) { 12790 max_header_len = max(max_header_len, lower_dev->hard_header_len); 12791 max_headroom = max(max_headroom, lower_dev->needed_headroom); 12792 max_tailroom = max(max_tailroom, lower_dev->needed_tailroom); 12793 } 12794 12795 tso_max_size = min(tso_max_size, lower_dev->tso_max_size); 12796 tso_max_segs = min(tso_max_segs, lower_dev->tso_max_segs); 12797 } 12798 12799 dev->gso_partial_features = gso_partial_features; 12800 dev->vlan_features = vlan_features; 12801 dev->hw_enc_features = enc_features | NETIF_F_GSO_ENCAP_ALL | 12802 NETIF_F_HW_VLAN_CTAG_TX | 12803 NETIF_F_HW_VLAN_STAG_TX; 12804 if (IS_ENABLED(CONFIG_XFRM_OFFLOAD)) 12805 dev->hw_enc_features |= xfrm_features; 12806 dev->mpls_features = mpls_features; 12807 12808 dev->priv_flags &= ~IFF_XMIT_DST_RELEASE; 12809 if ((dev->priv_flags & IFF_XMIT_DST_RELEASE_PERM) && 12810 dst_release_flag == (IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM)) 12811 dev->priv_flags |= IFF_XMIT_DST_RELEASE; 12812 12813 if (update_header) { 12814 dev->hard_header_len = max_header_len; 12815 dev->needed_headroom = max_headroom; 12816 dev->needed_tailroom = max_tailroom; 12817 } 12818 12819 netif_set_tso_max_segs(dev, tso_max_segs); 12820 netif_set_tso_max_size(dev, tso_max_size); 12821 12822 netdev_change_features(dev); 12823 } 12824 EXPORT_SYMBOL(netdev_compute_master_upper_features); 12825 12826 static struct hlist_head * __net_init netdev_create_hash(void) 12827 { 12828 int i; 12829 struct hlist_head *hash; 12830 12831 hash = kmalloc_array(NETDEV_HASHENTRIES, sizeof(*hash), GFP_KERNEL); 12832 if (hash != NULL) 12833 for (i = 0; i < NETDEV_HASHENTRIES; i++) 12834 INIT_HLIST_HEAD(&hash[i]); 12835 12836 return hash; 12837 } 12838 12839 /* Initialize per network namespace state */ 12840 static int __net_init netdev_init(struct net *net) 12841 { 12842 BUILD_BUG_ON(GRO_HASH_BUCKETS > 12843 BITS_PER_BYTE * sizeof_field(struct gro_node, bitmask)); 12844 12845 INIT_LIST_HEAD(&net->dev_base_head); 12846 12847 net->dev_name_head = netdev_create_hash(); 12848 if (net->dev_name_head == NULL) 12849 goto err_name; 12850 12851 net->dev_index_head = netdev_create_hash(); 12852 if (net->dev_index_head == NULL) 12853 goto err_idx; 12854 12855 xa_init_flags(&net->dev_by_index, XA_FLAGS_ALLOC1); 12856 12857 RAW_INIT_NOTIFIER_HEAD(&net->netdev_chain); 12858 12859 return 0; 12860 12861 err_idx: 12862 kfree(net->dev_name_head); 12863 err_name: 12864 return -ENOMEM; 12865 } 12866 12867 /** 12868 * netdev_drivername - network driver for the device 12869 * @dev: network device 12870 * 12871 * Determine network driver for device. 12872 */ 12873 const char *netdev_drivername(const struct net_device *dev) 12874 { 12875 const struct device_driver *driver; 12876 const struct device *parent; 12877 const char *empty = ""; 12878 12879 parent = dev->dev.parent; 12880 if (!parent) 12881 return empty; 12882 12883 driver = parent->driver; 12884 if (driver && driver->name) 12885 return driver->name; 12886 return empty; 12887 } 12888 12889 static void __netdev_printk(const char *level, const struct net_device *dev, 12890 struct va_format *vaf) 12891 { 12892 if (dev && dev->dev.parent) { 12893 dev_printk_emit(level[1] - '0', 12894 dev->dev.parent, 12895 "%s %s %s%s: %pV", 12896 dev_driver_string(dev->dev.parent), 12897 dev_name(dev->dev.parent), 12898 netdev_name(dev), netdev_reg_state(dev), 12899 vaf); 12900 } else if (dev) { 12901 printk("%s%s%s: %pV", 12902 level, netdev_name(dev), netdev_reg_state(dev), vaf); 12903 } else { 12904 printk("%s(NULL net_device): %pV", level, vaf); 12905 } 12906 } 12907 12908 void netdev_printk(const char *level, const struct net_device *dev, 12909 const char *format, ...) 12910 { 12911 struct va_format vaf; 12912 va_list args; 12913 12914 va_start(args, format); 12915 12916 vaf.fmt = format; 12917 vaf.va = &args; 12918 12919 __netdev_printk(level, dev, &vaf); 12920 12921 va_end(args); 12922 } 12923 EXPORT_SYMBOL(netdev_printk); 12924 12925 #define define_netdev_printk_level(func, level) \ 12926 void func(const struct net_device *dev, const char *fmt, ...) \ 12927 { \ 12928 struct va_format vaf; \ 12929 va_list args; \ 12930 \ 12931 va_start(args, fmt); \ 12932 \ 12933 vaf.fmt = fmt; \ 12934 vaf.va = &args; \ 12935 \ 12936 __netdev_printk(level, dev, &vaf); \ 12937 \ 12938 va_end(args); \ 12939 } \ 12940 EXPORT_SYMBOL(func); 12941 12942 define_netdev_printk_level(netdev_emerg, KERN_EMERG); 12943 define_netdev_printk_level(netdev_alert, KERN_ALERT); 12944 define_netdev_printk_level(netdev_crit, KERN_CRIT); 12945 define_netdev_printk_level(netdev_err, KERN_ERR); 12946 define_netdev_printk_level(netdev_warn, KERN_WARNING); 12947 define_netdev_printk_level(netdev_notice, KERN_NOTICE); 12948 define_netdev_printk_level(netdev_info, KERN_INFO); 12949 12950 static void __net_exit netdev_exit(struct net *net) 12951 { 12952 kfree(net->dev_name_head); 12953 kfree(net->dev_index_head); 12954 xa_destroy(&net->dev_by_index); 12955 if (net != &init_net) 12956 WARN_ON_ONCE(!list_empty(&net->dev_base_head)); 12957 } 12958 12959 static struct pernet_operations __net_initdata netdev_net_ops = { 12960 .init = netdev_init, 12961 .exit = netdev_exit, 12962 }; 12963 12964 static void __net_exit default_device_exit_net(struct net *net) 12965 { 12966 struct netdev_name_node *name_node, *tmp; 12967 struct net_device *dev, *aux; 12968 /* 12969 * Push all migratable network devices back to the 12970 * initial network namespace 12971 */ 12972 ASSERT_RTNL(); 12973 for_each_netdev_safe(net, dev, aux) { 12974 int err; 12975 char fb_name[IFNAMSIZ]; 12976 12977 /* Ignore unmoveable devices (i.e. loopback) */ 12978 if (dev->netns_immutable) 12979 continue; 12980 12981 /* Leave virtual devices for the generic cleanup */ 12982 if (dev->rtnl_link_ops && !dev->rtnl_link_ops->netns_refund) 12983 continue; 12984 12985 /* Push remaining network devices to init_net */ 12986 snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex); 12987 if (netdev_name_in_use(&init_net, fb_name)) 12988 snprintf(fb_name, IFNAMSIZ, "dev%%d"); 12989 12990 netdev_for_each_altname_safe(dev, name_node, tmp) 12991 if (netdev_name_in_use(&init_net, name_node->name)) 12992 __netdev_name_node_alt_destroy(name_node); 12993 12994 err = dev_change_net_namespace(dev, &init_net, fb_name); 12995 if (err) { 12996 pr_emerg("%s: failed to move %s to init_net: %d\n", 12997 __func__, dev->name, err); 12998 BUG(); 12999 } 13000 } 13001 } 13002 13003 static void __net_exit default_device_exit_batch(struct list_head *net_list) 13004 { 13005 /* At exit all network devices most be removed from a network 13006 * namespace. Do this in the reverse order of registration. 13007 * Do this across as many network namespaces as possible to 13008 * improve batching efficiency. 13009 */ 13010 struct net_device *dev; 13011 struct net *net; 13012 LIST_HEAD(dev_kill_list); 13013 13014 rtnl_lock(); 13015 list_for_each_entry(net, net_list, exit_list) { 13016 default_device_exit_net(net); 13017 cond_resched(); 13018 } 13019 13020 list_for_each_entry(net, net_list, exit_list) { 13021 for_each_netdev_reverse(net, dev) { 13022 if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink) 13023 dev->rtnl_link_ops->dellink(dev, &dev_kill_list); 13024 else 13025 unregister_netdevice_queue(dev, &dev_kill_list); 13026 } 13027 } 13028 unregister_netdevice_many(&dev_kill_list); 13029 rtnl_unlock(); 13030 } 13031 13032 static struct pernet_operations __net_initdata default_device_ops = { 13033 .exit_batch = default_device_exit_batch, 13034 }; 13035 13036 static void __init net_dev_struct_check(void) 13037 { 13038 /* TX read-mostly hotpath */ 13039 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, priv_flags_fast); 13040 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, netdev_ops); 13041 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, header_ops); 13042 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, _tx); 13043 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, real_num_tx_queues); 13044 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_max_size); 13045 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_ipv4_max_size); 13046 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_max_segs); 13047 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_partial_features); 13048 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, num_tc); 13049 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, mtu); 13050 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, needed_headroom); 13051 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, tc_to_txq); 13052 #ifdef CONFIG_XPS 13053 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, xps_maps); 13054 #endif 13055 #ifdef CONFIG_NETFILTER_EGRESS 13056 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, nf_hooks_egress); 13057 #endif 13058 #ifdef CONFIG_NET_XGRESS 13059 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, tcx_egress); 13060 #endif 13061 CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_tx, 160); 13062 13063 /* TXRX read-mostly hotpath */ 13064 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, lstats); 13065 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, state); 13066 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, flags); 13067 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, hard_header_len); 13068 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, features); 13069 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, ip6_ptr); 13070 CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_txrx, 46); 13071 13072 /* RX read-mostly hotpath */ 13073 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, ptype_specific); 13074 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, ifindex); 13075 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, real_num_rx_queues); 13076 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, _rx); 13077 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, gro_max_size); 13078 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, gro_ipv4_max_size); 13079 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, rx_handler); 13080 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, rx_handler_data); 13081 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, nd_net); 13082 #ifdef CONFIG_NETPOLL 13083 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, npinfo); 13084 #endif 13085 #ifdef CONFIG_NET_XGRESS 13086 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, tcx_ingress); 13087 #endif 13088 CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_rx, 92); 13089 } 13090 13091 /* 13092 * Initialize the DEV module. At boot time this walks the device list and 13093 * unhooks any devices that fail to initialise (normally hardware not 13094 * present) and leaves us with a valid list of present and active devices. 13095 * 13096 */ 13097 13098 /* We allocate 256 pages for each CPU if PAGE_SHIFT is 12 */ 13099 #define SYSTEM_PERCPU_PAGE_POOL_SIZE ((1 << 20) / PAGE_SIZE) 13100 13101 static int net_page_pool_create(int cpuid) 13102 { 13103 #if IS_ENABLED(CONFIG_PAGE_POOL) 13104 struct page_pool_params page_pool_params = { 13105 .pool_size = SYSTEM_PERCPU_PAGE_POOL_SIZE, 13106 .flags = PP_FLAG_SYSTEM_POOL, 13107 .nid = cpu_to_mem(cpuid), 13108 }; 13109 struct page_pool *pp_ptr; 13110 int err; 13111 13112 pp_ptr = page_pool_create_percpu(&page_pool_params, cpuid); 13113 if (IS_ERR(pp_ptr)) 13114 return -ENOMEM; 13115 13116 err = xdp_reg_page_pool(pp_ptr); 13117 if (err) { 13118 page_pool_destroy(pp_ptr); 13119 return err; 13120 } 13121 13122 per_cpu(system_page_pool.pool, cpuid) = pp_ptr; 13123 #endif 13124 return 0; 13125 } 13126 13127 static int backlog_napi_should_run(unsigned int cpu) 13128 { 13129 struct softnet_data *sd = per_cpu_ptr(&softnet_data, cpu); 13130 struct napi_struct *napi = &sd->backlog; 13131 13132 return test_bit(NAPI_STATE_SCHED_THREADED, &napi->state); 13133 } 13134 13135 static void run_backlog_napi(unsigned int cpu) 13136 { 13137 struct softnet_data *sd = per_cpu_ptr(&softnet_data, cpu); 13138 13139 napi_threaded_poll_loop(&sd->backlog, false); 13140 } 13141 13142 static void backlog_napi_setup(unsigned int cpu) 13143 { 13144 struct softnet_data *sd = per_cpu_ptr(&softnet_data, cpu); 13145 struct napi_struct *napi = &sd->backlog; 13146 13147 napi->thread = this_cpu_read(backlog_napi); 13148 set_bit(NAPI_STATE_THREADED, &napi->state); 13149 } 13150 13151 static struct smp_hotplug_thread backlog_threads = { 13152 .store = &backlog_napi, 13153 .thread_should_run = backlog_napi_should_run, 13154 .thread_fn = run_backlog_napi, 13155 .thread_comm = "backlog_napi/%u", 13156 .setup = backlog_napi_setup, 13157 }; 13158 13159 /* 13160 * This is called single threaded during boot, so no need 13161 * to take the rtnl semaphore. 13162 */ 13163 static int __init net_dev_init(void) 13164 { 13165 int i, rc = -ENOMEM; 13166 13167 BUG_ON(!dev_boot_phase); 13168 13169 net_dev_struct_check(); 13170 13171 if (dev_proc_init()) 13172 goto out; 13173 13174 if (netdev_kobject_init()) 13175 goto out; 13176 13177 for (i = 0; i < PTYPE_HASH_SIZE; i++) 13178 INIT_LIST_HEAD(&ptype_base[i]); 13179 13180 if (register_pernet_subsys(&netdev_net_ops)) 13181 goto out; 13182 13183 /* 13184 * Initialise the packet receive queues. 13185 */ 13186 13187 flush_backlogs_fallback = flush_backlogs_alloc(); 13188 if (!flush_backlogs_fallback) 13189 goto out; 13190 13191 for_each_possible_cpu(i) { 13192 struct softnet_data *sd = &per_cpu(softnet_data, i); 13193 13194 skb_queue_head_init(&sd->input_pkt_queue); 13195 skb_queue_head_init(&sd->process_queue); 13196 #ifdef CONFIG_XFRM_OFFLOAD 13197 skb_queue_head_init(&sd->xfrm_backlog); 13198 #endif 13199 INIT_LIST_HEAD(&sd->poll_list); 13200 sd->output_queue_tailp = &sd->output_queue; 13201 #ifdef CONFIG_RPS 13202 INIT_CSD(&sd->csd, rps_trigger_softirq, sd); 13203 sd->cpu = i; 13204 #endif 13205 INIT_CSD(&sd->defer_csd, trigger_rx_softirq, sd); 13206 13207 gro_init(&sd->backlog.gro); 13208 sd->backlog.poll = process_backlog; 13209 sd->backlog.weight = weight_p; 13210 INIT_LIST_HEAD(&sd->backlog.poll_list); 13211 13212 if (net_page_pool_create(i)) 13213 goto out; 13214 } 13215 net_hotdata.skb_defer_nodes = 13216 __alloc_percpu(sizeof(struct skb_defer_node) * nr_node_ids, 13217 __alignof__(struct skb_defer_node)); 13218 if (!net_hotdata.skb_defer_nodes) 13219 goto out; 13220 if (use_backlog_threads()) 13221 smpboot_register_percpu_thread(&backlog_threads); 13222 13223 dev_boot_phase = 0; 13224 13225 /* The loopback device is special if any other network devices 13226 * is present in a network namespace the loopback device must 13227 * be present. Since we now dynamically allocate and free the 13228 * loopback device ensure this invariant is maintained by 13229 * keeping the loopback device as the first device on the 13230 * list of network devices. Ensuring the loopback devices 13231 * is the first device that appears and the last network device 13232 * that disappears. 13233 */ 13234 if (register_pernet_device(&loopback_net_ops)) 13235 goto out; 13236 13237 if (register_pernet_device(&default_device_ops)) 13238 goto out; 13239 13240 open_softirq(NET_TX_SOFTIRQ, net_tx_action); 13241 open_softirq(NET_RX_SOFTIRQ, net_rx_action); 13242 13243 rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead", 13244 NULL, dev_cpu_dead); 13245 WARN_ON(rc < 0); 13246 rc = 0; 13247 13248 /* avoid static key IPIs to isolated CPUs */ 13249 if (housekeeping_enabled(HK_TYPE_MISC)) 13250 net_enable_timestamp(); 13251 out: 13252 if (rc < 0) { 13253 for_each_possible_cpu(i) { 13254 struct page_pool *pp_ptr; 13255 13256 pp_ptr = per_cpu(system_page_pool.pool, i); 13257 if (!pp_ptr) 13258 continue; 13259 13260 xdp_unreg_page_pool(pp_ptr); 13261 page_pool_destroy(pp_ptr); 13262 per_cpu(system_page_pool.pool, i) = NULL; 13263 } 13264 } 13265 13266 return rc; 13267 } 13268 13269 subsys_initcall(net_dev_init); 13270