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