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