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