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