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