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