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