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