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 (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 || tc >= num_tc) 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 if (smp_call_function_single_async(cpu, &sd->defer_csd)) 5380 WRITE_ONCE(sd->defer_ipi_scheduled, 0); 5381 } 5382 } 5383 5384 #ifdef CONFIG_NET_FLOW_LIMIT 5385 int netdev_flow_limit_table_len __read_mostly = (1 << 12); 5386 #endif 5387 5388 static bool skb_flow_limit(struct sk_buff *skb, unsigned int qlen, 5389 int max_backlog) 5390 { 5391 #ifdef CONFIG_NET_FLOW_LIMIT 5392 unsigned int old_flow, new_flow; 5393 const struct softnet_data *sd; 5394 struct sd_flow_limit *fl; 5395 5396 if (likely(qlen < (max_backlog >> 1))) 5397 return false; 5398 5399 sd = this_cpu_ptr(&softnet_data); 5400 5401 rcu_read_lock(); 5402 fl = rcu_dereference(sd->flow_limit); 5403 if (fl) { 5404 new_flow = hash_32(skb_get_hash(skb), fl->log_buckets); 5405 old_flow = fl->history[fl->history_head]; 5406 fl->history[fl->history_head] = new_flow; 5407 5408 fl->history_head++; 5409 fl->history_head &= FLOW_LIMIT_HISTORY - 1; 5410 5411 if (likely(fl->buckets[old_flow])) 5412 fl->buckets[old_flow]--; 5413 5414 if (++fl->buckets[new_flow] > (FLOW_LIMIT_HISTORY >> 1)) { 5415 /* Pairs with READ_ONCE() in softnet_seq_show() */ 5416 WRITE_ONCE(fl->count, fl->count + 1); 5417 rcu_read_unlock(); 5418 return true; 5419 } 5420 } 5421 rcu_read_unlock(); 5422 #endif 5423 return false; 5424 } 5425 5426 /* 5427 * enqueue_to_backlog is called to queue an skb to a per CPU backlog 5428 * queue (may be a remote CPU queue). 5429 */ 5430 static int enqueue_to_backlog(struct sk_buff *skb, int cpu, 5431 unsigned int *qtail) 5432 { 5433 enum skb_drop_reason reason; 5434 struct softnet_data *sd; 5435 unsigned long flags; 5436 unsigned int qlen; 5437 int max_backlog; 5438 u32 tail; 5439 5440 reason = SKB_DROP_REASON_DEV_READY; 5441 5442 sd = &per_cpu(softnet_data, cpu); 5443 5444 qlen = skb_queue_len_lockless(&sd->input_pkt_queue); 5445 max_backlog = READ_ONCE(net_hotdata.max_backlog); 5446 if (unlikely(qlen > max_backlog) || 5447 skb_flow_limit(skb, qlen, max_backlog)) 5448 goto cpu_backlog_drop; 5449 backlog_lock_irq_save(sd, &flags); 5450 qlen = skb_queue_len(&sd->input_pkt_queue); 5451 if (likely(qlen <= max_backlog)) { 5452 if (unlikely(!netif_running(skb->dev))) { 5453 backlog_unlock_irq_restore(sd, flags); 5454 goto bad_dev; 5455 } 5456 if (!qlen) { 5457 /* Schedule NAPI for backlog device. We can use 5458 * non atomic operation as we own the queue lock. 5459 */ 5460 if (!__test_and_set_bit(NAPI_STATE_SCHED, 5461 &sd->backlog.state)) 5462 napi_schedule_rps(sd); 5463 } 5464 __skb_queue_tail(&sd->input_pkt_queue, skb); 5465 tail = rps_input_queue_tail_incr(sd); 5466 backlog_unlock_irq_restore(sd, flags); 5467 5468 /* save the tail outside of the critical section */ 5469 rps_input_queue_tail_save(qtail, tail); 5470 return NET_RX_SUCCESS; 5471 } 5472 5473 backlog_unlock_irq_restore(sd, flags); 5474 5475 cpu_backlog_drop: 5476 reason = SKB_DROP_REASON_CPU_BACKLOG; 5477 numa_drop_add(&sd->drop_counters, 1); 5478 bad_dev: 5479 dev_core_stats_rx_dropped_inc(skb->dev); 5480 kfree_skb_reason(skb, reason); 5481 return NET_RX_DROP; 5482 } 5483 5484 static struct netdev_rx_queue *netif_get_rxqueue(struct sk_buff *skb) 5485 { 5486 struct net_device *dev = skb->dev; 5487 struct netdev_rx_queue *rxqueue; 5488 5489 rxqueue = dev->_rx; 5490 5491 if (skb_rx_queue_recorded(skb)) { 5492 u16 index = skb_get_rx_queue(skb); 5493 5494 if (unlikely(index >= dev->real_num_rx_queues)) { 5495 WARN_ONCE(dev->real_num_rx_queues > 1, 5496 "%s received packet on queue %u, but number " 5497 "of RX queues is %u\n", 5498 dev->name, index, dev->real_num_rx_queues); 5499 5500 return rxqueue; /* Return first rxqueue */ 5501 } 5502 rxqueue += index; 5503 } 5504 return rxqueue; 5505 } 5506 5507 u32 bpf_prog_run_generic_xdp(struct sk_buff *skb, struct xdp_buff *xdp, 5508 const struct bpf_prog *xdp_prog) 5509 { 5510 void *orig_data, *orig_data_end, *hard_start; 5511 struct netdev_rx_queue *rxqueue; 5512 bool orig_bcast, orig_host; 5513 u32 mac_len, frame_sz; 5514 __be16 orig_eth_type; 5515 struct ethhdr *eth; 5516 u32 metalen, act; 5517 int off; 5518 5519 /* The XDP program wants to see the packet starting at the MAC 5520 * header. 5521 */ 5522 mac_len = skb->data - skb_mac_header(skb); 5523 hard_start = skb->data - skb_headroom(skb); 5524 5525 /* SKB "head" area always have tailroom for skb_shared_info */ 5526 frame_sz = (void *)skb_end_pointer(skb) - hard_start; 5527 frame_sz += SKB_DATA_ALIGN(sizeof(struct skb_shared_info)); 5528 5529 rxqueue = netif_get_rxqueue(skb); 5530 xdp_init_buff(xdp, frame_sz, &rxqueue->xdp_rxq); 5531 xdp_prepare_buff(xdp, hard_start, skb_headroom(skb) - mac_len, 5532 skb_headlen(skb) + mac_len, true); 5533 if (skb_is_nonlinear(skb)) { 5534 skb_shinfo(skb)->xdp_frags_size = skb->data_len; 5535 xdp_buff_set_frags_flag(xdp); 5536 } else { 5537 xdp_buff_clear_frags_flag(xdp); 5538 } 5539 5540 orig_data_end = xdp->data_end; 5541 orig_data = xdp->data; 5542 eth = (struct ethhdr *)xdp->data; 5543 orig_host = ether_addr_equal_64bits(eth->h_dest, skb->dev->dev_addr); 5544 orig_bcast = is_multicast_ether_addr_64bits(eth->h_dest); 5545 orig_eth_type = eth->h_proto; 5546 5547 act = bpf_prog_run_xdp(xdp_prog, xdp); 5548 5549 /* check if bpf_xdp_adjust_head was used */ 5550 off = xdp->data - orig_data; 5551 if (off) { 5552 if (off > 0) 5553 __skb_pull(skb, off); 5554 else if (off < 0) 5555 __skb_push(skb, -off); 5556 5557 skb->mac_header += off; 5558 skb_reset_network_header(skb); 5559 } 5560 5561 /* check if bpf_xdp_adjust_tail was used */ 5562 off = xdp->data_end - orig_data_end; 5563 if (off != 0) { 5564 skb_set_tail_pointer(skb, xdp->data_end - xdp->data); 5565 skb->len += off; /* positive on grow, negative on shrink */ 5566 } 5567 5568 /* XDP frag metadata (e.g. nr_frags) are updated in eBPF helpers 5569 * (e.g. bpf_xdp_adjust_tail). Remove the old fragment contribution 5570 * from skb->len before updating data_len, then add the new one back. 5571 */ 5572 skb->len -= skb->data_len; 5573 if (xdp_buff_has_frags(xdp)) { 5574 skb->data_len = skb_shinfo(skb)->xdp_frags_size; 5575 skb->len += skb->data_len; 5576 } else { 5577 skb->data_len = 0; 5578 } 5579 5580 /* check if XDP changed eth hdr such SKB needs update */ 5581 eth = (struct ethhdr *)xdp->data; 5582 if ((orig_eth_type != eth->h_proto) || 5583 (orig_host != ether_addr_equal_64bits(eth->h_dest, 5584 skb->dev->dev_addr)) || 5585 (orig_bcast != is_multicast_ether_addr_64bits(eth->h_dest))) { 5586 __skb_push(skb, ETH_HLEN); 5587 skb->pkt_type = PACKET_HOST; 5588 skb->protocol = eth_type_trans(skb, skb->dev); 5589 } 5590 5591 /* Redirect/Tx gives L2 packet, code that will reuse skb must __skb_pull 5592 * before calling us again on redirect path. We do not call do_redirect 5593 * as we leave that up to the caller. 5594 * 5595 * Caller is responsible for managing lifetime of skb (i.e. calling 5596 * kfree_skb in response to actions it cannot handle/XDP_DROP). 5597 */ 5598 switch (act) { 5599 case XDP_REDIRECT: 5600 case XDP_TX: 5601 __skb_push(skb, mac_len); 5602 break; 5603 case XDP_PASS: 5604 metalen = xdp->data - xdp->data_meta; 5605 if (metalen) 5606 skb_metadata_set(skb, metalen); 5607 break; 5608 } 5609 5610 return act; 5611 } 5612 5613 static int 5614 netif_skb_check_for_xdp(struct sk_buff **pskb, const struct bpf_prog *prog) 5615 { 5616 struct sk_buff *skb = *pskb; 5617 int err, hroom, troom; 5618 5619 local_lock_nested_bh(&system_page_pool.bh_lock); 5620 err = skb_cow_data_for_xdp(this_cpu_read(system_page_pool.pool), pskb, prog); 5621 local_unlock_nested_bh(&system_page_pool.bh_lock); 5622 if (!err) 5623 return 0; 5624 5625 /* In case we have to go down the path and also linearize, 5626 * then lets do the pskb_expand_head() work just once here. 5627 */ 5628 hroom = XDP_PACKET_HEADROOM - skb_headroom(skb); 5629 troom = skb->tail + skb->data_len - skb->end; 5630 err = pskb_expand_head(skb, 5631 hroom > 0 ? ALIGN(hroom, NET_SKB_PAD) : 0, 5632 troom > 0 ? troom + 128 : 0, GFP_ATOMIC); 5633 if (err) 5634 return err; 5635 5636 return skb_linearize(skb); 5637 } 5638 5639 static u32 netif_receive_generic_xdp(struct sk_buff **pskb, 5640 struct xdp_buff *xdp, 5641 const struct bpf_prog *xdp_prog) 5642 { 5643 struct sk_buff *skb = *pskb; 5644 u32 mac_len, act = XDP_DROP; 5645 5646 /* Reinjected packets coming from act_mirred or similar should 5647 * not get XDP generic processing. 5648 */ 5649 if (skb_is_redirected(skb)) 5650 return XDP_PASS; 5651 5652 /* XDP packets must have sufficient headroom of XDP_PACKET_HEADROOM 5653 * bytes. This is the guarantee that also native XDP provides, 5654 * thus we need to do it here as well. 5655 */ 5656 mac_len = skb->data - skb_mac_header(skb); 5657 __skb_push(skb, mac_len); 5658 5659 if (skb_cloned(skb) || skb_is_nonlinear(skb) || 5660 skb_headroom(skb) < XDP_PACKET_HEADROOM) { 5661 if (netif_skb_check_for_xdp(pskb, xdp_prog)) 5662 goto do_drop; 5663 } 5664 5665 __skb_pull(*pskb, mac_len); 5666 5667 act = bpf_prog_run_generic_xdp(*pskb, xdp, xdp_prog); 5668 switch (act) { 5669 case XDP_REDIRECT: 5670 case XDP_TX: 5671 case XDP_PASS: 5672 break; 5673 default: 5674 bpf_warn_invalid_xdp_action((*pskb)->dev, xdp_prog, act); 5675 fallthrough; 5676 case XDP_ABORTED: 5677 trace_xdp_exception((*pskb)->dev, xdp_prog, act); 5678 fallthrough; 5679 case XDP_DROP: 5680 do_drop: 5681 kfree_skb(*pskb); 5682 break; 5683 } 5684 5685 return act; 5686 } 5687 5688 /* When doing generic XDP we have to bypass the qdisc layer and the 5689 * network taps in order to match in-driver-XDP behavior. This also means 5690 * that XDP packets are able to starve other packets going through a qdisc, 5691 * and DDOS attacks will be more effective. In-driver-XDP use dedicated TX 5692 * queues, so they do not have this starvation issue. 5693 */ 5694 void generic_xdp_tx(struct sk_buff *skb, const struct bpf_prog *xdp_prog) 5695 { 5696 struct net_device *dev = skb->dev; 5697 struct netdev_queue *txq; 5698 bool free_skb = true; 5699 int cpu, rc; 5700 5701 txq = netdev_core_pick_tx(dev, skb, NULL); 5702 cpu = smp_processor_id(); 5703 HARD_TX_LOCK(dev, txq, cpu); 5704 if (!netif_xmit_frozen_or_drv_stopped(txq)) { 5705 rc = netdev_start_xmit(skb, dev, txq, 0); 5706 if (dev_xmit_complete(rc)) 5707 free_skb = false; 5708 } 5709 HARD_TX_UNLOCK(dev, txq); 5710 if (free_skb) { 5711 trace_xdp_exception(dev, xdp_prog, XDP_TX); 5712 dev_core_stats_tx_dropped_inc(dev); 5713 kfree_skb(skb); 5714 } 5715 } 5716 5717 static DEFINE_STATIC_KEY_FALSE(generic_xdp_needed_key); 5718 5719 int do_xdp_generic(const struct bpf_prog *xdp_prog, struct sk_buff **pskb) 5720 { 5721 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx; 5722 5723 if (xdp_prog) { 5724 struct xdp_buff xdp; 5725 u32 act; 5726 int err; 5727 5728 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx); 5729 act = netif_receive_generic_xdp(pskb, &xdp, xdp_prog); 5730 if (act != XDP_PASS) { 5731 switch (act) { 5732 case XDP_REDIRECT: 5733 err = xdp_do_generic_redirect((*pskb)->dev, *pskb, 5734 &xdp, xdp_prog); 5735 if (err) 5736 goto out_redir; 5737 break; 5738 case XDP_TX: 5739 generic_xdp_tx(*pskb, xdp_prog); 5740 break; 5741 } 5742 bpf_net_ctx_clear(bpf_net_ctx); 5743 return XDP_DROP; 5744 } 5745 bpf_net_ctx_clear(bpf_net_ctx); 5746 } 5747 return XDP_PASS; 5748 out_redir: 5749 bpf_net_ctx_clear(bpf_net_ctx); 5750 kfree_skb_reason(*pskb, SKB_DROP_REASON_XDP); 5751 return XDP_DROP; 5752 } 5753 EXPORT_SYMBOL_GPL(do_xdp_generic); 5754 5755 static int netif_rx_internal(struct sk_buff *skb) 5756 { 5757 int ret; 5758 5759 net_timestamp_check(READ_ONCE(net_hotdata.tstamp_prequeue), skb); 5760 5761 trace_netif_rx(skb); 5762 5763 #ifdef CONFIG_RPS 5764 if (static_branch_unlikely(&rps_needed)) { 5765 struct rps_dev_flow voidflow, *rflow = &voidflow; 5766 int cpu; 5767 5768 rcu_read_lock(); 5769 5770 cpu = get_rps_cpu(skb->dev, skb, &rflow); 5771 if (cpu < 0) 5772 cpu = smp_processor_id(); 5773 5774 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail); 5775 5776 rcu_read_unlock(); 5777 } else 5778 #endif 5779 { 5780 unsigned int qtail; 5781 5782 ret = enqueue_to_backlog(skb, smp_processor_id(), &qtail); 5783 } 5784 return ret; 5785 } 5786 5787 /** 5788 * __netif_rx - Slightly optimized version of netif_rx 5789 * @skb: buffer to post 5790 * 5791 * This behaves as netif_rx except that it does not disable bottom halves. 5792 * As a result this function may only be invoked from the interrupt context 5793 * (either hard or soft interrupt). 5794 */ 5795 int __netif_rx(struct sk_buff *skb) 5796 { 5797 int ret; 5798 5799 lockdep_assert_once(hardirq_count() | softirq_count()); 5800 5801 trace_netif_rx_entry(skb); 5802 ret = netif_rx_internal(skb); 5803 trace_netif_rx_exit(ret); 5804 return ret; 5805 } 5806 EXPORT_SYMBOL(__netif_rx); 5807 5808 /** 5809 * netif_rx - post buffer to the network code 5810 * @skb: buffer to post 5811 * 5812 * This function receives a packet from a device driver and queues it for 5813 * the upper (protocol) levels to process via the backlog NAPI device. It 5814 * always succeeds. The buffer may be dropped during processing for 5815 * congestion control or by the protocol layers. 5816 * The network buffer is passed via the backlog NAPI device. Modern NIC 5817 * driver should use NAPI and GRO. 5818 * This function can used from interrupt and from process context. The 5819 * caller from process context must not disable interrupts before invoking 5820 * this function. 5821 * 5822 * return values: 5823 * NET_RX_SUCCESS (no congestion) 5824 * NET_RX_DROP (packet was dropped) 5825 * 5826 */ 5827 int netif_rx(struct sk_buff *skb) 5828 { 5829 bool need_bh_off = !(hardirq_count() | softirq_count()); 5830 int ret; 5831 5832 if (need_bh_off) 5833 local_bh_disable(); 5834 trace_netif_rx_entry(skb); 5835 ret = netif_rx_internal(skb); 5836 trace_netif_rx_exit(ret); 5837 if (need_bh_off) 5838 local_bh_enable(); 5839 return ret; 5840 } 5841 EXPORT_SYMBOL(netif_rx); 5842 5843 static __latent_entropy void net_tx_action(void) 5844 { 5845 struct softnet_data *sd = this_cpu_ptr(&softnet_data); 5846 5847 if (sd->completion_queue) { 5848 struct sk_buff *clist; 5849 5850 local_irq_disable(); 5851 clist = sd->completion_queue; 5852 sd->completion_queue = NULL; 5853 local_irq_enable(); 5854 5855 while (clist) { 5856 struct sk_buff *skb = clist; 5857 5858 clist = clist->next; 5859 5860 WARN_ON(refcount_read(&skb->users)); 5861 if (likely(get_kfree_skb_cb(skb)->reason == SKB_CONSUMED)) 5862 trace_consume_skb(skb, net_tx_action); 5863 else 5864 trace_kfree_skb(skb, net_tx_action, 5865 get_kfree_skb_cb(skb)->reason, NULL); 5866 5867 if (skb->fclone != SKB_FCLONE_UNAVAILABLE) 5868 __kfree_skb(skb); 5869 else 5870 __napi_kfree_skb(skb, 5871 get_kfree_skb_cb(skb)->reason); 5872 } 5873 } 5874 5875 if (sd->output_queue) { 5876 struct Qdisc *head; 5877 5878 local_irq_disable(); 5879 head = sd->output_queue; 5880 sd->output_queue = NULL; 5881 sd->output_queue_tailp = &sd->output_queue; 5882 local_irq_enable(); 5883 5884 rcu_read_lock(); 5885 5886 while (head) { 5887 spinlock_t *root_lock = NULL; 5888 struct sk_buff *to_free; 5889 struct Qdisc *q = head; 5890 5891 head = head->next_sched; 5892 5893 /* We need to make sure head->next_sched is read 5894 * before clearing __QDISC_STATE_SCHED 5895 */ 5896 smp_mb__before_atomic(); 5897 5898 if (!(q->flags & TCQ_F_NOLOCK)) { 5899 root_lock = qdisc_lock(q); 5900 spin_lock(root_lock); 5901 } else if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, 5902 &q->state))) { 5903 /* There is a synchronize_net() between 5904 * STATE_DEACTIVATED flag being set and 5905 * qdisc_reset()/some_qdisc_is_busy() in 5906 * dev_deactivate(), so we can safely bail out 5907 * early here to avoid data race between 5908 * qdisc_deactivate() and some_qdisc_is_busy() 5909 * for lockless qdisc. 5910 */ 5911 clear_bit(__QDISC_STATE_SCHED, &q->state); 5912 continue; 5913 } 5914 5915 clear_bit(__QDISC_STATE_SCHED, &q->state); 5916 to_free = qdisc_run(q); 5917 if (root_lock) 5918 spin_unlock(root_lock); 5919 tcf_kfree_skb_list(to_free, q, NULL, qdisc_dev(q)); 5920 } 5921 5922 rcu_read_unlock(); 5923 } 5924 5925 xfrm_dev_backlog(sd); 5926 } 5927 5928 /** 5929 * netdev_is_rx_handler_busy - check if receive handler is registered 5930 * @dev: device to check 5931 * 5932 * Check if a receive handler is already registered for a given device. 5933 * Return true if there one. 5934 * 5935 * The caller must hold the rtnl_mutex. 5936 */ 5937 bool netdev_is_rx_handler_busy(struct net_device *dev) 5938 { 5939 ASSERT_RTNL(); 5940 return dev && rtnl_dereference(dev->rx_handler); 5941 } 5942 EXPORT_SYMBOL_GPL(netdev_is_rx_handler_busy); 5943 5944 /** 5945 * netdev_rx_handler_register - register receive handler 5946 * @dev: device to register a handler for 5947 * @rx_handler: receive handler to register 5948 * @rx_handler_data: data pointer that is used by rx handler 5949 * 5950 * Register a receive handler for a device. This handler will then be 5951 * called from __netif_receive_skb. A negative errno code is returned 5952 * on a failure. 5953 * 5954 * The caller must hold the rtnl_mutex. 5955 * 5956 * For a general description of rx_handler, see enum rx_handler_result. 5957 */ 5958 int netdev_rx_handler_register(struct net_device *dev, 5959 rx_handler_func_t *rx_handler, 5960 void *rx_handler_data) 5961 { 5962 if (netdev_is_rx_handler_busy(dev)) 5963 return -EBUSY; 5964 5965 if (dev->priv_flags & IFF_NO_RX_HANDLER) 5966 return -EINVAL; 5967 5968 /* Note: rx_handler_data must be set before rx_handler */ 5969 rcu_assign_pointer(dev->rx_handler_data, rx_handler_data); 5970 rcu_assign_pointer(dev->rx_handler, rx_handler); 5971 5972 return 0; 5973 } 5974 EXPORT_SYMBOL_GPL(netdev_rx_handler_register); 5975 5976 /** 5977 * netdev_rx_handler_unregister - unregister receive handler 5978 * @dev: device to unregister a handler from 5979 * 5980 * Unregister a receive handler from a device. 5981 * 5982 * The caller must hold the rtnl_mutex. 5983 */ 5984 void netdev_rx_handler_unregister(struct net_device *dev) 5985 { 5986 5987 ASSERT_RTNL(); 5988 RCU_INIT_POINTER(dev->rx_handler, NULL); 5989 /* a reader seeing a non NULL rx_handler in a rcu_read_lock() 5990 * section has a guarantee to see a non NULL rx_handler_data 5991 * as well. 5992 */ 5993 synchronize_net(); 5994 RCU_INIT_POINTER(dev->rx_handler_data, NULL); 5995 } 5996 EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister); 5997 5998 /* 5999 * Limit the use of PFMEMALLOC reserves to those protocols that implement 6000 * the special handling of PFMEMALLOC skbs. 6001 */ 6002 static bool skb_pfmemalloc_protocol(struct sk_buff *skb) 6003 { 6004 switch (skb->protocol) { 6005 case htons(ETH_P_ARP): 6006 case htons(ETH_P_IP): 6007 case htons(ETH_P_IPV6): 6008 case htons(ETH_P_8021Q): 6009 case htons(ETH_P_8021AD): 6010 return true; 6011 default: 6012 return false; 6013 } 6014 } 6015 6016 static inline int nf_ingress(struct sk_buff *skb, struct packet_type **pt_prev, 6017 int *ret, struct net_device *orig_dev) 6018 { 6019 if (nf_hook_ingress_active(skb)) { 6020 int ingress_retval; 6021 6022 if (unlikely(*pt_prev)) { 6023 *ret = deliver_skb(skb, *pt_prev, orig_dev); 6024 *pt_prev = NULL; 6025 } 6026 6027 rcu_read_lock(); 6028 ingress_retval = nf_hook_ingress(skb); 6029 rcu_read_unlock(); 6030 return ingress_retval; 6031 } 6032 return 0; 6033 } 6034 6035 static int __netif_receive_skb_core(struct sk_buff **pskb, bool pfmemalloc, 6036 struct packet_type **ppt_prev) 6037 { 6038 enum skb_drop_reason drop_reason = SKB_DROP_REASON_UNHANDLED_PROTO; 6039 struct packet_type *ptype, *pt_prev; 6040 rx_handler_func_t *rx_handler; 6041 struct sk_buff *skb = *pskb; 6042 struct net_device *orig_dev; 6043 bool deliver_exact = false; 6044 int ret = NET_RX_DROP; 6045 __be16 type; 6046 6047 net_timestamp_check(!READ_ONCE(net_hotdata.tstamp_prequeue), skb); 6048 6049 trace_netif_receive_skb(skb); 6050 6051 orig_dev = skb->dev; 6052 6053 skb_reset_network_header(skb); 6054 #if !defined(CONFIG_DEBUG_NET) 6055 /* We plan to no longer reset the transport header here. 6056 * Give some time to fuzzers and dev build to catch bugs 6057 * in network stacks. 6058 */ 6059 if (!skb_transport_header_was_set(skb)) 6060 skb_reset_transport_header(skb); 6061 #endif 6062 skb_reset_mac_len(skb); 6063 6064 pt_prev = NULL; 6065 6066 another_round: 6067 skb->skb_iif = skb->dev->ifindex; 6068 6069 __this_cpu_inc(softnet_data.processed); 6070 6071 if (static_branch_unlikely(&generic_xdp_needed_key)) { 6072 int ret2; 6073 6074 migrate_disable(); 6075 ret2 = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog), 6076 &skb); 6077 migrate_enable(); 6078 6079 if (ret2 != XDP_PASS) { 6080 ret = NET_RX_DROP; 6081 goto out; 6082 } 6083 } 6084 6085 if (eth_type_vlan(skb->protocol)) { 6086 skb = skb_vlan_untag(skb); 6087 if (unlikely(!skb)) 6088 goto out; 6089 } 6090 6091 if (skb_skip_tc_classify(skb)) 6092 goto skip_classify; 6093 6094 if (pfmemalloc) 6095 goto skip_taps; 6096 6097 list_for_each_entry_rcu(ptype, &dev_net_rcu(skb->dev)->ptype_all, 6098 list) { 6099 if (unlikely(pt_prev)) 6100 ret = deliver_skb(skb, pt_prev, orig_dev); 6101 pt_prev = ptype; 6102 } 6103 6104 list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) { 6105 if (unlikely(pt_prev)) 6106 ret = deliver_skb(skb, pt_prev, orig_dev); 6107 pt_prev = ptype; 6108 } 6109 6110 skip_taps: 6111 #ifdef CONFIG_NET_INGRESS 6112 if (static_branch_unlikely(&ingress_needed_key)) { 6113 bool another = false; 6114 6115 nf_skip_egress(skb, true); 6116 skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev, 6117 &another); 6118 if (another) 6119 goto another_round; 6120 if (!skb) 6121 goto out; 6122 6123 nf_skip_egress(skb, false); 6124 if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0) 6125 goto out; 6126 } 6127 #endif 6128 skb_reset_redirect(skb); 6129 skip_classify: 6130 if (pfmemalloc && !skb_pfmemalloc_protocol(skb)) { 6131 drop_reason = SKB_DROP_REASON_PFMEMALLOC; 6132 goto drop; 6133 } 6134 6135 if (skb_vlan_tag_present(skb)) { 6136 if (unlikely(pt_prev)) { 6137 ret = deliver_skb(skb, pt_prev, orig_dev); 6138 pt_prev = NULL; 6139 } 6140 if (vlan_do_receive(&skb)) 6141 goto another_round; 6142 else if (unlikely(!skb)) 6143 goto out; 6144 } 6145 6146 rx_handler = rcu_dereference(skb->dev->rx_handler); 6147 if (rx_handler) { 6148 if (unlikely(pt_prev)) { 6149 ret = deliver_skb(skb, pt_prev, orig_dev); 6150 pt_prev = NULL; 6151 } 6152 switch (rx_handler(&skb)) { 6153 case RX_HANDLER_CONSUMED: 6154 ret = NET_RX_SUCCESS; 6155 goto out; 6156 case RX_HANDLER_ANOTHER: 6157 goto another_round; 6158 case RX_HANDLER_EXACT: 6159 deliver_exact = true; 6160 break; 6161 case RX_HANDLER_PASS: 6162 break; 6163 default: 6164 BUG(); 6165 } 6166 } 6167 6168 if (unlikely(skb_vlan_tag_present(skb)) && !netdev_uses_dsa(skb->dev)) { 6169 check_vlan_id: 6170 if (skb_vlan_tag_get_id(skb)) { 6171 /* Vlan id is non 0 and vlan_do_receive() above couldn't 6172 * find vlan device. 6173 */ 6174 skb->pkt_type = PACKET_OTHERHOST; 6175 } else if (eth_type_vlan(skb->protocol)) { 6176 /* Outer header is 802.1P with vlan 0, inner header is 6177 * 802.1Q or 802.1AD and vlan_do_receive() above could 6178 * not find vlan dev for vlan id 0. 6179 */ 6180 __vlan_hwaccel_clear_tag(skb); 6181 skb = skb_vlan_untag(skb); 6182 if (unlikely(!skb)) 6183 goto out; 6184 if (vlan_do_receive(&skb)) 6185 /* After stripping off 802.1P header with vlan 0 6186 * vlan dev is found for inner header. 6187 */ 6188 goto another_round; 6189 else if (unlikely(!skb)) 6190 goto out; 6191 else 6192 /* We have stripped outer 802.1P vlan 0 header. 6193 * But could not find vlan dev. 6194 * check again for vlan id to set OTHERHOST. 6195 */ 6196 goto check_vlan_id; 6197 } 6198 /* Note: we might in the future use prio bits 6199 * and set skb->priority like in vlan_do_receive() 6200 * For the time being, just ignore Priority Code Point 6201 */ 6202 __vlan_hwaccel_clear_tag(skb); 6203 } 6204 6205 type = skb->protocol; 6206 6207 /* deliver only exact match when indicated */ 6208 if (likely(!deliver_exact)) { 6209 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type, 6210 &ptype_base[ntohs(type) & 6211 PTYPE_HASH_MASK]); 6212 6213 /* orig_dev and skb->dev could belong to different netns; 6214 * Even in such case we need to traverse only the list 6215 * coming from skb->dev, as the ptype owner (packet socket) 6216 * will use dev_net(skb->dev) to do namespace filtering. 6217 */ 6218 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type, 6219 &dev_net_rcu(skb->dev)->ptype_specific); 6220 } 6221 6222 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type, 6223 &orig_dev->ptype_specific); 6224 6225 if (unlikely(skb->dev != orig_dev)) { 6226 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type, 6227 &skb->dev->ptype_specific); 6228 } 6229 6230 if (pt_prev) { 6231 *ppt_prev = pt_prev; 6232 } else { 6233 drop: 6234 if (!deliver_exact) 6235 dev_core_stats_rx_dropped_inc(skb->dev); 6236 else 6237 dev_core_stats_rx_nohandler_inc(skb->dev); 6238 6239 kfree_skb_reason(skb, drop_reason); 6240 /* Jamal, now you will not able to escape explaining 6241 * me how you were going to use this. :-) 6242 */ 6243 ret = NET_RX_DROP; 6244 } 6245 6246 out: 6247 /* The invariant here is that if *ppt_prev is not NULL 6248 * then skb should also be non-NULL. 6249 * 6250 * Apparently *ppt_prev assignment above holds this invariant due to 6251 * skb dereferencing near it. 6252 */ 6253 *pskb = skb; 6254 return ret; 6255 } 6256 6257 static int __netif_receive_skb_one_core(struct sk_buff *skb, bool pfmemalloc) 6258 { 6259 struct net_device *orig_dev = skb->dev; 6260 struct packet_type *pt_prev = NULL; 6261 int ret; 6262 6263 ret = __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev); 6264 if (pt_prev) 6265 ret = INDIRECT_CALL_INET(pt_prev->func, ipv6_rcv, ip_rcv, skb, 6266 skb->dev, pt_prev, orig_dev); 6267 return ret; 6268 } 6269 6270 /** 6271 * netif_receive_skb_core - special purpose version of netif_receive_skb 6272 * @skb: buffer to process 6273 * 6274 * More direct receive version of netif_receive_skb(). It should 6275 * only be used by callers that have a need to skip RPS and Generic XDP. 6276 * Caller must also take care of handling if ``(page_is_)pfmemalloc``. 6277 * 6278 * This function may only be called from softirq context and interrupts 6279 * should be enabled. 6280 * 6281 * Return values (usually ignored): 6282 * NET_RX_SUCCESS: no congestion 6283 * NET_RX_DROP: packet was dropped 6284 */ 6285 int netif_receive_skb_core(struct sk_buff *skb) 6286 { 6287 int ret; 6288 6289 rcu_read_lock(); 6290 ret = __netif_receive_skb_one_core(skb, false); 6291 rcu_read_unlock(); 6292 6293 return ret; 6294 } 6295 EXPORT_SYMBOL(netif_receive_skb_core); 6296 6297 static inline void __netif_receive_skb_list_ptype(struct list_head *head, 6298 struct packet_type *pt_prev, 6299 struct net_device *orig_dev) 6300 { 6301 struct sk_buff *skb, *next; 6302 6303 if (!pt_prev) 6304 return; 6305 if (list_empty(head)) 6306 return; 6307 if (pt_prev->list_func != NULL) 6308 INDIRECT_CALL_INET(pt_prev->list_func, ipv6_list_rcv, 6309 ip_list_rcv, head, pt_prev, orig_dev); 6310 else 6311 list_for_each_entry_safe(skb, next, head, list) { 6312 skb_list_del_init(skb); 6313 pt_prev->func(skb, skb->dev, pt_prev, orig_dev); 6314 } 6315 } 6316 6317 static void __netif_receive_skb_list_core(struct list_head *head, bool pfmemalloc) 6318 { 6319 /* Fast-path assumptions: 6320 * - There is no RX handler. 6321 * - Only one packet_type matches. 6322 * If either of these fails, we will end up doing some per-packet 6323 * processing in-line, then handling the 'last ptype' for the whole 6324 * sublist. This can't cause out-of-order delivery to any single ptype, 6325 * because the 'last ptype' must be constant across the sublist, and all 6326 * other ptypes are handled per-packet. 6327 */ 6328 /* Current (common) ptype of sublist */ 6329 struct packet_type *pt_curr = NULL; 6330 /* Current (common) orig_dev of sublist */ 6331 struct net_device *od_curr = NULL; 6332 struct sk_buff *skb, *next; 6333 LIST_HEAD(sublist); 6334 6335 list_for_each_entry_safe(skb, next, head, list) { 6336 struct net_device *orig_dev = skb->dev; 6337 struct packet_type *pt_prev = NULL; 6338 6339 skb_list_del_init(skb); 6340 __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev); 6341 if (!pt_prev) 6342 continue; 6343 if (pt_curr != pt_prev || od_curr != orig_dev) { 6344 /* dispatch old sublist */ 6345 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr); 6346 /* start new sublist */ 6347 INIT_LIST_HEAD(&sublist); 6348 pt_curr = pt_prev; 6349 od_curr = orig_dev; 6350 } 6351 list_add_tail(&skb->list, &sublist); 6352 } 6353 6354 /* dispatch final sublist */ 6355 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr); 6356 } 6357 6358 static int __netif_receive_skb(struct sk_buff *skb) 6359 { 6360 int ret; 6361 6362 if (sk_memalloc_socks() && skb_pfmemalloc(skb)) { 6363 unsigned int noreclaim_flag; 6364 6365 /* 6366 * PFMEMALLOC skbs are special, they should 6367 * - be delivered to SOCK_MEMALLOC sockets only 6368 * - stay away from userspace 6369 * - have bounded memory usage 6370 * 6371 * Use PF_MEMALLOC as this saves us from propagating the allocation 6372 * context down to all allocation sites. 6373 */ 6374 noreclaim_flag = memalloc_noreclaim_save(); 6375 ret = __netif_receive_skb_one_core(skb, true); 6376 memalloc_noreclaim_restore(noreclaim_flag); 6377 } else 6378 ret = __netif_receive_skb_one_core(skb, false); 6379 6380 return ret; 6381 } 6382 6383 static void __netif_receive_skb_list(struct list_head *head) 6384 { 6385 unsigned long noreclaim_flag = 0; 6386 struct sk_buff *skb, *next; 6387 bool pfmemalloc = false; /* Is current sublist PF_MEMALLOC? */ 6388 6389 list_for_each_entry_safe(skb, next, head, list) { 6390 if ((sk_memalloc_socks() && skb_pfmemalloc(skb)) != pfmemalloc) { 6391 struct list_head sublist; 6392 6393 /* Handle the previous sublist */ 6394 list_cut_before(&sublist, head, &skb->list); 6395 if (!list_empty(&sublist)) 6396 __netif_receive_skb_list_core(&sublist, pfmemalloc); 6397 pfmemalloc = !pfmemalloc; 6398 /* See comments in __netif_receive_skb */ 6399 if (pfmemalloc) 6400 noreclaim_flag = memalloc_noreclaim_save(); 6401 else 6402 memalloc_noreclaim_restore(noreclaim_flag); 6403 } 6404 } 6405 /* Handle the remaining sublist */ 6406 if (!list_empty(head)) 6407 __netif_receive_skb_list_core(head, pfmemalloc); 6408 /* Restore pflags */ 6409 if (pfmemalloc) 6410 memalloc_noreclaim_restore(noreclaim_flag); 6411 } 6412 6413 static int generic_xdp_install(struct net_device *dev, struct netdev_bpf *xdp) 6414 { 6415 struct bpf_prog *old = rtnl_dereference(dev->xdp_prog); 6416 struct bpf_prog *new = xdp->prog; 6417 int ret = 0; 6418 6419 switch (xdp->command) { 6420 case XDP_SETUP_PROG: 6421 rcu_assign_pointer(dev->xdp_prog, new); 6422 if (old) 6423 bpf_prog_put(old); 6424 6425 if (old && !new) { 6426 static_branch_dec(&generic_xdp_needed_key); 6427 } else if (new && !old) { 6428 static_branch_inc(&generic_xdp_needed_key); 6429 netif_disable_lro(dev); 6430 dev_disable_gro_hw(dev); 6431 } 6432 break; 6433 6434 default: 6435 ret = -EINVAL; 6436 break; 6437 } 6438 6439 return ret; 6440 } 6441 6442 static int netif_receive_skb_internal(struct sk_buff *skb) 6443 { 6444 int ret; 6445 6446 net_timestamp_check(READ_ONCE(net_hotdata.tstamp_prequeue), skb); 6447 6448 if (skb_defer_rx_timestamp(skb)) 6449 return NET_RX_SUCCESS; 6450 6451 rcu_read_lock(); 6452 #ifdef CONFIG_RPS 6453 if (static_branch_unlikely(&rps_needed)) { 6454 struct rps_dev_flow voidflow, *rflow = &voidflow; 6455 int cpu = get_rps_cpu(skb->dev, skb, &rflow); 6456 6457 if (cpu >= 0) { 6458 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail); 6459 rcu_read_unlock(); 6460 return ret; 6461 } 6462 } 6463 #endif 6464 ret = __netif_receive_skb(skb); 6465 rcu_read_unlock(); 6466 return ret; 6467 } 6468 6469 void netif_receive_skb_list_internal(struct list_head *head) 6470 { 6471 struct sk_buff *skb, *next; 6472 LIST_HEAD(sublist); 6473 6474 list_for_each_entry_safe(skb, next, head, list) { 6475 net_timestamp_check(READ_ONCE(net_hotdata.tstamp_prequeue), 6476 skb); 6477 skb_list_del_init(skb); 6478 if (!skb_defer_rx_timestamp(skb)) 6479 list_add_tail(&skb->list, &sublist); 6480 } 6481 list_splice_init(&sublist, head); 6482 6483 rcu_read_lock(); 6484 #ifdef CONFIG_RPS 6485 if (static_branch_unlikely(&rps_needed)) { 6486 list_for_each_entry_safe(skb, next, head, list) { 6487 struct rps_dev_flow voidflow, *rflow = &voidflow; 6488 int cpu = get_rps_cpu(skb->dev, skb, &rflow); 6489 6490 if (cpu >= 0) { 6491 /* Will be handled, remove from list */ 6492 skb_list_del_init(skb); 6493 enqueue_to_backlog(skb, cpu, &rflow->last_qtail); 6494 } 6495 } 6496 } 6497 #endif 6498 __netif_receive_skb_list(head); 6499 rcu_read_unlock(); 6500 } 6501 6502 /** 6503 * netif_receive_skb - process receive buffer from network 6504 * @skb: buffer to process 6505 * 6506 * netif_receive_skb() is the main receive data processing function. 6507 * It always succeeds. The buffer may be dropped during processing 6508 * for congestion control or by the protocol layers. 6509 * 6510 * This function may only be called from softirq context and interrupts 6511 * should be enabled. 6512 * 6513 * Return values (usually ignored): 6514 * NET_RX_SUCCESS: no congestion 6515 * NET_RX_DROP: packet was dropped 6516 */ 6517 int netif_receive_skb(struct sk_buff *skb) 6518 { 6519 int ret; 6520 6521 trace_netif_receive_skb_entry(skb); 6522 6523 ret = netif_receive_skb_internal(skb); 6524 trace_netif_receive_skb_exit(ret); 6525 6526 return ret; 6527 } 6528 EXPORT_SYMBOL(netif_receive_skb); 6529 6530 /** 6531 * netif_receive_skb_list - process many receive buffers from network 6532 * @head: list of skbs to process. 6533 * 6534 * Since return value of netif_receive_skb() is normally ignored, and 6535 * wouldn't be meaningful for a list, this function returns void. 6536 * 6537 * This function may only be called from softirq context and interrupts 6538 * should be enabled. 6539 */ 6540 void netif_receive_skb_list(struct list_head *head) 6541 { 6542 struct sk_buff *skb; 6543 6544 if (list_empty(head)) 6545 return; 6546 if (trace_netif_receive_skb_list_entry_enabled()) { 6547 list_for_each_entry(skb, head, list) 6548 trace_netif_receive_skb_list_entry(skb); 6549 } 6550 netif_receive_skb_list_internal(head); 6551 trace_netif_receive_skb_list_exit(0); 6552 } 6553 EXPORT_SYMBOL(netif_receive_skb_list); 6554 6555 /* Network device is going away, flush any packets still pending */ 6556 static void flush_backlog(struct work_struct *work) 6557 { 6558 struct sk_buff *skb, *tmp; 6559 struct sk_buff_head list; 6560 struct softnet_data *sd; 6561 6562 __skb_queue_head_init(&list); 6563 local_bh_disable(); 6564 sd = this_cpu_ptr(&softnet_data); 6565 6566 backlog_lock_irq_disable(sd); 6567 skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) { 6568 if (READ_ONCE(skb->dev->reg_state) == NETREG_UNREGISTERING) { 6569 __skb_unlink(skb, &sd->input_pkt_queue); 6570 __skb_queue_tail(&list, skb); 6571 rps_input_queue_head_incr(sd); 6572 } 6573 } 6574 backlog_unlock_irq_enable(sd); 6575 6576 local_lock_nested_bh(&softnet_data.process_queue_bh_lock); 6577 skb_queue_walk_safe(&sd->process_queue, skb, tmp) { 6578 if (READ_ONCE(skb->dev->reg_state) == NETREG_UNREGISTERING) { 6579 __skb_unlink(skb, &sd->process_queue); 6580 __skb_queue_tail(&list, skb); 6581 rps_input_queue_head_incr(sd); 6582 } 6583 } 6584 local_unlock_nested_bh(&softnet_data.process_queue_bh_lock); 6585 local_bh_enable(); 6586 6587 __skb_queue_purge_reason(&list, SKB_DROP_REASON_DEV_READY); 6588 } 6589 6590 static bool flush_required(int cpu) 6591 { 6592 #if IS_ENABLED(CONFIG_RPS) 6593 struct softnet_data *sd = &per_cpu(softnet_data, cpu); 6594 bool do_flush; 6595 6596 backlog_lock_irq_disable(sd); 6597 6598 /* as insertion into process_queue happens with the rps lock held, 6599 * process_queue access may race only with dequeue 6600 */ 6601 do_flush = !skb_queue_empty(&sd->input_pkt_queue) || 6602 !skb_queue_empty_lockless(&sd->process_queue); 6603 backlog_unlock_irq_enable(sd); 6604 6605 return do_flush; 6606 #endif 6607 /* without RPS we can't safely check input_pkt_queue: during a 6608 * concurrent remote skb_queue_splice() we can detect as empty both 6609 * input_pkt_queue and process_queue even if the latter could end-up 6610 * containing a lot of packets. 6611 */ 6612 return true; 6613 } 6614 6615 struct flush_backlogs { 6616 cpumask_t flush_cpus; 6617 struct work_struct w[]; 6618 }; 6619 6620 static struct flush_backlogs *flush_backlogs_alloc(void) 6621 { 6622 return kmalloc_flex(struct flush_backlogs, w, nr_cpu_ids); 6623 } 6624 6625 static struct flush_backlogs *flush_backlogs_fallback; 6626 static DEFINE_MUTEX(flush_backlogs_mutex); 6627 6628 static void flush_all_backlogs(void) 6629 { 6630 struct flush_backlogs *ptr = flush_backlogs_alloc(); 6631 unsigned int cpu; 6632 6633 if (!ptr) { 6634 mutex_lock(&flush_backlogs_mutex); 6635 ptr = flush_backlogs_fallback; 6636 } 6637 cpumask_clear(&ptr->flush_cpus); 6638 6639 cpus_read_lock(); 6640 6641 for_each_online_cpu(cpu) { 6642 if (flush_required(cpu)) { 6643 INIT_WORK(&ptr->w[cpu], flush_backlog); 6644 queue_work_on(cpu, system_highpri_wq, &ptr->w[cpu]); 6645 __cpumask_set_cpu(cpu, &ptr->flush_cpus); 6646 } 6647 } 6648 6649 /* we can have in flight packet[s] on the cpus we are not flushing, 6650 * synchronize_net() in unregister_netdevice_many() will take care of 6651 * them. 6652 */ 6653 for_each_cpu(cpu, &ptr->flush_cpus) 6654 flush_work(&ptr->w[cpu]); 6655 6656 cpus_read_unlock(); 6657 6658 if (ptr != flush_backlogs_fallback) 6659 kfree(ptr); 6660 else 6661 mutex_unlock(&flush_backlogs_mutex); 6662 } 6663 6664 static void net_rps_send_ipi(struct softnet_data *remsd) 6665 { 6666 #ifdef CONFIG_RPS 6667 while (remsd) { 6668 struct softnet_data *next = remsd->rps_ipi_next; 6669 6670 if (cpu_online(remsd->cpu)) 6671 smp_call_function_single_async(remsd->cpu, &remsd->csd); 6672 remsd = next; 6673 } 6674 #endif 6675 } 6676 6677 /* 6678 * net_rps_action_and_irq_enable sends any pending IPI's for rps. 6679 * Note: called with local irq disabled, but exits with local irq enabled. 6680 */ 6681 static void net_rps_action_and_irq_enable(struct softnet_data *sd) 6682 { 6683 #ifdef CONFIG_RPS 6684 struct softnet_data *remsd = sd->rps_ipi_list; 6685 6686 if (!use_backlog_threads() && remsd) { 6687 sd->rps_ipi_list = NULL; 6688 6689 local_irq_enable(); 6690 6691 /* Send pending IPI's to kick RPS processing on remote cpus. */ 6692 net_rps_send_ipi(remsd); 6693 } else 6694 #endif 6695 local_irq_enable(); 6696 } 6697 6698 static bool sd_has_rps_ipi_waiting(struct softnet_data *sd) 6699 { 6700 #ifdef CONFIG_RPS 6701 return !use_backlog_threads() && sd->rps_ipi_list; 6702 #else 6703 return false; 6704 #endif 6705 } 6706 6707 static int process_backlog(struct napi_struct *napi, int quota) 6708 { 6709 struct softnet_data *sd = container_of(napi, struct softnet_data, backlog); 6710 bool again = true; 6711 int work = 0; 6712 6713 /* Check if we have pending ipi, its better to send them now, 6714 * not waiting net_rx_action() end. 6715 */ 6716 if (sd_has_rps_ipi_waiting(sd)) { 6717 local_irq_disable(); 6718 net_rps_action_and_irq_enable(sd); 6719 } 6720 6721 napi->weight = READ_ONCE(net_hotdata.dev_rx_weight); 6722 while (again) { 6723 struct sk_buff *skb; 6724 6725 local_lock_nested_bh(&softnet_data.process_queue_bh_lock); 6726 while ((skb = __skb_dequeue(&sd->process_queue))) { 6727 local_unlock_nested_bh(&softnet_data.process_queue_bh_lock); 6728 rcu_read_lock(); 6729 __netif_receive_skb(skb); 6730 rcu_read_unlock(); 6731 if (++work >= quota) { 6732 rps_input_queue_head_add(sd, work); 6733 return work; 6734 } 6735 6736 local_lock_nested_bh(&softnet_data.process_queue_bh_lock); 6737 } 6738 local_unlock_nested_bh(&softnet_data.process_queue_bh_lock); 6739 6740 backlog_lock_irq_disable(sd); 6741 if (skb_queue_empty(&sd->input_pkt_queue)) { 6742 /* 6743 * Inline a custom version of __napi_complete(). 6744 * only current cpu owns and manipulates this napi, 6745 * and NAPI_STATE_SCHED is the only possible flag set 6746 * on backlog. 6747 * We can use a plain write instead of clear_bit(), 6748 * and we dont need an smp_mb() memory barrier. 6749 */ 6750 napi->state &= NAPIF_STATE_THREADED; 6751 again = false; 6752 } else { 6753 local_lock_nested_bh(&softnet_data.process_queue_bh_lock); 6754 skb_queue_splice_tail_init(&sd->input_pkt_queue, 6755 &sd->process_queue); 6756 local_unlock_nested_bh(&softnet_data.process_queue_bh_lock); 6757 } 6758 backlog_unlock_irq_enable(sd); 6759 } 6760 6761 if (work) 6762 rps_input_queue_head_add(sd, work); 6763 return work; 6764 } 6765 6766 /** 6767 * __napi_schedule - schedule for receive 6768 * @n: entry to schedule 6769 * 6770 * The entry's receive function will be scheduled to run. 6771 * Consider using __napi_schedule_irqoff() if hard irqs are masked. 6772 */ 6773 void __napi_schedule(struct napi_struct *n) 6774 { 6775 unsigned long flags; 6776 6777 local_irq_save(flags); 6778 ____napi_schedule(this_cpu_ptr(&softnet_data), n); 6779 local_irq_restore(flags); 6780 } 6781 EXPORT_SYMBOL(__napi_schedule); 6782 6783 /** 6784 * napi_schedule_prep - check if napi can be scheduled 6785 * @n: napi context 6786 * 6787 * Test if NAPI routine is already running, and if not mark 6788 * it as running. This is used as a condition variable to 6789 * insure only one NAPI poll instance runs. We also make 6790 * sure there is no pending NAPI disable. 6791 */ 6792 bool napi_schedule_prep(struct napi_struct *n) 6793 { 6794 unsigned long new, val = READ_ONCE(n->state); 6795 6796 do { 6797 if (unlikely(val & NAPIF_STATE_DISABLE)) 6798 return false; 6799 new = val | NAPIF_STATE_SCHED; 6800 6801 /* Sets STATE_MISSED bit if STATE_SCHED was already set 6802 * This was suggested by Alexander Duyck, as compiler 6803 * emits better code than : 6804 * if (val & NAPIF_STATE_SCHED) 6805 * new |= NAPIF_STATE_MISSED; 6806 */ 6807 new |= (val & NAPIF_STATE_SCHED) / NAPIF_STATE_SCHED * 6808 NAPIF_STATE_MISSED; 6809 } while (!try_cmpxchg(&n->state, &val, new)); 6810 6811 return !(val & NAPIF_STATE_SCHED); 6812 } 6813 EXPORT_SYMBOL(napi_schedule_prep); 6814 6815 /** 6816 * __napi_schedule_irqoff - schedule for receive 6817 * @n: entry to schedule 6818 * 6819 * Variant of __napi_schedule() assuming hard irqs are masked. 6820 * 6821 * On PREEMPT_RT enabled kernels this maps to __napi_schedule() 6822 * because the interrupt disabled assumption might not be true 6823 * due to force-threaded interrupts and spinlock substitution. 6824 */ 6825 void __napi_schedule_irqoff(struct napi_struct *n) 6826 { 6827 if (!IS_ENABLED(CONFIG_PREEMPT_RT)) 6828 ____napi_schedule(this_cpu_ptr(&softnet_data), n); 6829 else 6830 __napi_schedule(n); 6831 } 6832 EXPORT_SYMBOL(__napi_schedule_irqoff); 6833 6834 bool napi_complete_done(struct napi_struct *n, int work_done) 6835 { 6836 unsigned long flags, val, new, timeout = 0; 6837 bool ret = true; 6838 6839 /* 6840 * 1) Don't let napi dequeue from the cpu poll list 6841 * just in case its running on a different cpu. 6842 * 2) If we are busy polling, do nothing here, we have 6843 * the guarantee we will be called later. 6844 */ 6845 if (unlikely(n->state & (NAPIF_STATE_NPSVC | 6846 NAPIF_STATE_IN_BUSY_POLL))) 6847 return false; 6848 6849 if (work_done) { 6850 if (n->gro.bitmask) 6851 timeout = napi_get_gro_flush_timeout(n); 6852 n->defer_hard_irqs_count = napi_get_defer_hard_irqs(n); 6853 } 6854 if (n->defer_hard_irqs_count > 0) { 6855 n->defer_hard_irqs_count--; 6856 timeout = napi_get_gro_flush_timeout(n); 6857 if (timeout) 6858 ret = false; 6859 } 6860 6861 /* 6862 * When the NAPI instance uses a timeout and keeps postponing 6863 * it, we need to bound somehow the time packets are kept in 6864 * the GRO layer. 6865 */ 6866 gro_flush_normal(&n->gro, !!timeout); 6867 6868 if (unlikely(!list_empty(&n->poll_list))) { 6869 /* If n->poll_list is not empty, we need to mask irqs */ 6870 local_irq_save(flags); 6871 list_del_init(&n->poll_list); 6872 local_irq_restore(flags); 6873 } 6874 WRITE_ONCE(n->list_owner, -1); 6875 6876 val = READ_ONCE(n->state); 6877 do { 6878 WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED)); 6879 6880 new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED | 6881 NAPIF_STATE_SCHED_THREADED | 6882 NAPIF_STATE_PREFER_BUSY_POLL); 6883 6884 /* If STATE_MISSED was set, leave STATE_SCHED set, 6885 * because we will call napi->poll() one more time. 6886 * This C code was suggested by Alexander Duyck to help gcc. 6887 */ 6888 new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED * 6889 NAPIF_STATE_SCHED; 6890 } while (!try_cmpxchg(&n->state, &val, new)); 6891 6892 if (unlikely(val & NAPIF_STATE_MISSED)) { 6893 __napi_schedule(n); 6894 return false; 6895 } 6896 6897 if (timeout) 6898 hrtimer_start(&n->timer, ns_to_ktime(timeout), 6899 HRTIMER_MODE_REL_PINNED); 6900 return ret; 6901 } 6902 EXPORT_SYMBOL(napi_complete_done); 6903 6904 static void __skb_defer_free_flush(struct skb_defer_node *sdn, int budget) 6905 { 6906 struct llist_node *free_list; 6907 struct sk_buff *skb, *next; 6908 6909 if (llist_empty(&sdn->defer_list)) 6910 return; 6911 atomic_long_set(&sdn->defer_count, 0); 6912 free_list = llist_del_all(&sdn->defer_list); 6913 6914 llist_for_each_entry_safe(skb, next, free_list, ll_node) { 6915 prefetch(next); 6916 napi_consume_skb(skb, budget); 6917 } 6918 } 6919 6920 void skb_defer_node_flush(struct skb_defer_node *sdn) 6921 { 6922 __skb_defer_free_flush(sdn, 0); 6923 } 6924 6925 static void skb_defer_free_flush(void) 6926 { 6927 struct skb_defer_node *sdn; 6928 int node; 6929 6930 for_each_node(node) { 6931 sdn = this_cpu_ptr(net_hotdata.skb_defer_nodes) + node; 6932 __skb_defer_free_flush(sdn, 1); 6933 } 6934 } 6935 6936 #if defined(CONFIG_NET_RX_BUSY_POLL) 6937 6938 enum { 6939 NAPI_F_PREFER_BUSY_POLL = 1, 6940 NAPI_F_END_ON_RESCHED = 2, 6941 }; 6942 6943 static void busy_poll_stop(struct napi_struct *napi, void *have_poll_lock, 6944 unsigned flags, u16 budget) 6945 { 6946 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx; 6947 unsigned long timeout = 0; 6948 int rc; 6949 6950 /* Busy polling means there is a high chance device driver hard irq 6951 * could not grab NAPI_STATE_SCHED, and that NAPI_STATE_MISSED was 6952 * set in napi_schedule_prep(). 6953 * Since we either call napi->poll() once more or start the timer, 6954 * we can safely clear NAPI_STATE_MISSED. 6955 * 6956 * Note: x86 could use a single "lock and ..." instruction 6957 * to perform these two clear_bit() 6958 */ 6959 clear_bit(NAPI_STATE_MISSED, &napi->state); 6960 clear_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state); 6961 6962 local_bh_disable(); 6963 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx); 6964 6965 if (flags & NAPI_F_PREFER_BUSY_POLL) { 6966 napi->defer_hard_irqs_count = napi_get_defer_hard_irqs(napi); 6967 if (napi->defer_hard_irqs_count) 6968 timeout = napi_get_gro_flush_timeout(napi); 6969 } 6970 if (timeout) { 6971 netpoll_poll_unlock(have_poll_lock); 6972 6973 /* Drain aged GRO packets before clearing SCHED since the NAPI 6974 * won't run again until after the timer fires. When HZ < 1000, 6975 * GRO age comparison is too coarse, so flush everything. 6976 */ 6977 gro_flush_normal(&napi->gro, HZ >= 1000); 6978 6979 clear_bit(NAPI_STATE_SCHED, &napi->state); 6980 hrtimer_start(&napi->timer, ns_to_ktime(timeout), 6981 HRTIMER_MODE_REL_PINNED); 6982 } else { 6983 /* Use driver poll to re-enable device interrupts. */ 6984 rc = napi->poll(napi, budget); 6985 /* Unless rc == budget we no longer own the NAPI instance, 6986 * IRQ may fire on another CPU, poll this NAPI, and enter GRO. 6987 */ 6988 trace_napi_poll(napi, rc, budget); 6989 netpoll_poll_unlock(have_poll_lock); 6990 if (rc == budget) { 6991 gro_normal_list(&napi->gro); 6992 __napi_schedule(napi); 6993 } 6994 } 6995 6996 bpf_net_ctx_clear(bpf_net_ctx); 6997 local_bh_enable(); 6998 } 6999 7000 static void __napi_busy_loop(unsigned int napi_id, 7001 bool (*loop_end)(void *, unsigned long), 7002 void *loop_end_arg, unsigned flags, u16 budget) 7003 { 7004 unsigned long start_time = loop_end ? busy_loop_current_time() : 0; 7005 int (*napi_poll)(struct napi_struct *napi, int budget); 7006 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx; 7007 void *have_poll_lock = NULL; 7008 struct napi_struct *napi; 7009 7010 WARN_ON_ONCE(!rcu_read_lock_held()); 7011 7012 restart: 7013 napi_poll = NULL; 7014 7015 napi = napi_by_id(napi_id); 7016 if (!napi) 7017 return; 7018 7019 if (!IS_ENABLED(CONFIG_PREEMPT_RT)) 7020 preempt_disable(); 7021 for (;;) { 7022 int work = 0; 7023 7024 local_bh_disable(); 7025 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx); 7026 if (!napi_poll) { 7027 unsigned long val = READ_ONCE(napi->state); 7028 7029 /* If multiple threads are competing for this napi, 7030 * we avoid dirtying napi->state as much as we can. 7031 */ 7032 if (val & (NAPIF_STATE_DISABLE | NAPIF_STATE_SCHED | 7033 NAPIF_STATE_IN_BUSY_POLL)) { 7034 if (flags & NAPI_F_PREFER_BUSY_POLL) 7035 set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state); 7036 goto count; 7037 } 7038 if (cmpxchg(&napi->state, val, 7039 val | NAPIF_STATE_IN_BUSY_POLL | 7040 NAPIF_STATE_SCHED) != val) { 7041 if (flags & NAPI_F_PREFER_BUSY_POLL) 7042 set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state); 7043 goto count; 7044 } 7045 have_poll_lock = netpoll_poll_lock(napi); 7046 napi_poll = napi->poll; 7047 } 7048 work = napi_poll(napi, budget); 7049 trace_napi_poll(napi, work, budget); 7050 gro_normal_list(&napi->gro); 7051 count: 7052 if (work > 0) 7053 __NET_ADD_STATS(dev_net(napi->dev), 7054 LINUX_MIB_BUSYPOLLRXPACKETS, work); 7055 skb_defer_free_flush(); 7056 bpf_net_ctx_clear(bpf_net_ctx); 7057 local_bh_enable(); 7058 7059 if (!loop_end || loop_end(loop_end_arg, start_time)) 7060 break; 7061 7062 if (unlikely(need_resched())) { 7063 if (flags & NAPI_F_END_ON_RESCHED) 7064 break; 7065 if (napi_poll) 7066 busy_poll_stop(napi, have_poll_lock, flags, budget); 7067 if (!IS_ENABLED(CONFIG_PREEMPT_RT)) 7068 preempt_enable(); 7069 rcu_read_unlock(); 7070 cond_resched(); 7071 rcu_read_lock(); 7072 if (loop_end(loop_end_arg, start_time)) 7073 return; 7074 goto restart; 7075 } 7076 cpu_relax(); 7077 } 7078 if (napi_poll) 7079 busy_poll_stop(napi, have_poll_lock, flags, budget); 7080 if (!IS_ENABLED(CONFIG_PREEMPT_RT)) 7081 preempt_enable(); 7082 } 7083 7084 void napi_busy_loop_rcu(unsigned int napi_id, 7085 bool (*loop_end)(void *, unsigned long), 7086 void *loop_end_arg, bool prefer_busy_poll, u16 budget) 7087 { 7088 unsigned flags = NAPI_F_END_ON_RESCHED; 7089 7090 if (prefer_busy_poll) 7091 flags |= NAPI_F_PREFER_BUSY_POLL; 7092 7093 __napi_busy_loop(napi_id, loop_end, loop_end_arg, flags, budget); 7094 } 7095 7096 void napi_busy_loop(unsigned int napi_id, 7097 bool (*loop_end)(void *, unsigned long), 7098 void *loop_end_arg, bool prefer_busy_poll, u16 budget) 7099 { 7100 unsigned flags = prefer_busy_poll ? NAPI_F_PREFER_BUSY_POLL : 0; 7101 7102 rcu_read_lock(); 7103 __napi_busy_loop(napi_id, loop_end, loop_end_arg, flags, budget); 7104 rcu_read_unlock(); 7105 } 7106 EXPORT_SYMBOL(napi_busy_loop); 7107 7108 void napi_suspend_irqs(unsigned int napi_id) 7109 { 7110 struct napi_struct *napi; 7111 7112 rcu_read_lock(); 7113 napi = napi_by_id(napi_id); 7114 if (napi) { 7115 unsigned long timeout = napi_get_irq_suspend_timeout(napi); 7116 7117 if (timeout) 7118 hrtimer_start(&napi->timer, ns_to_ktime(timeout), 7119 HRTIMER_MODE_REL_PINNED); 7120 } 7121 rcu_read_unlock(); 7122 } 7123 7124 void napi_resume_irqs(unsigned int napi_id) 7125 { 7126 struct napi_struct *napi; 7127 7128 rcu_read_lock(); 7129 napi = napi_by_id(napi_id); 7130 if (napi) { 7131 /* If irq_suspend_timeout is set to 0 between the call to 7132 * napi_suspend_irqs and now, the original value still 7133 * determines the safety timeout as intended and napi_watchdog 7134 * will resume irq processing. 7135 */ 7136 if (napi_get_irq_suspend_timeout(napi)) { 7137 local_bh_disable(); 7138 napi_schedule(napi); 7139 local_bh_enable(); 7140 } 7141 } 7142 rcu_read_unlock(); 7143 } 7144 7145 #endif /* CONFIG_NET_RX_BUSY_POLL */ 7146 7147 static void __napi_hash_add_with_id(struct napi_struct *napi, 7148 unsigned int napi_id) 7149 { 7150 napi->gro.cached_napi_id = napi_id; 7151 7152 WRITE_ONCE(napi->napi_id, napi_id); 7153 hlist_add_head_rcu(&napi->napi_hash_node, 7154 &napi_hash[napi->napi_id % HASH_SIZE(napi_hash)]); 7155 } 7156 7157 static void napi_hash_add_with_id(struct napi_struct *napi, 7158 unsigned int napi_id) 7159 { 7160 unsigned long flags; 7161 7162 spin_lock_irqsave(&napi_hash_lock, flags); 7163 WARN_ON_ONCE(napi_by_id(napi_id)); 7164 __napi_hash_add_with_id(napi, napi_id); 7165 spin_unlock_irqrestore(&napi_hash_lock, flags); 7166 } 7167 7168 static void napi_hash_add(struct napi_struct *napi) 7169 { 7170 unsigned long flags; 7171 7172 if (test_bit(NAPI_STATE_NO_BUSY_POLL, &napi->state)) 7173 return; 7174 7175 spin_lock_irqsave(&napi_hash_lock, flags); 7176 7177 /* 0..NR_CPUS range is reserved for sender_cpu use */ 7178 do { 7179 if (unlikely(!napi_id_valid(++napi_gen_id))) 7180 napi_gen_id = MIN_NAPI_ID; 7181 } while (napi_by_id(napi_gen_id)); 7182 7183 __napi_hash_add_with_id(napi, napi_gen_id); 7184 7185 spin_unlock_irqrestore(&napi_hash_lock, flags); 7186 } 7187 7188 /* Warning : caller is responsible to make sure rcu grace period 7189 * is respected before freeing memory containing @napi 7190 */ 7191 static void napi_hash_del(struct napi_struct *napi) 7192 { 7193 unsigned long flags; 7194 7195 spin_lock_irqsave(&napi_hash_lock, flags); 7196 7197 hlist_del_init_rcu(&napi->napi_hash_node); 7198 7199 spin_unlock_irqrestore(&napi_hash_lock, flags); 7200 } 7201 7202 static enum hrtimer_restart napi_watchdog(struct hrtimer *timer) 7203 { 7204 struct napi_struct *napi; 7205 7206 napi = container_of(timer, struct napi_struct, timer); 7207 7208 /* Note : we use a relaxed variant of napi_schedule_prep() not setting 7209 * NAPI_STATE_MISSED, since we do not react to a device IRQ. 7210 */ 7211 if (!napi_disable_pending(napi) && 7212 !test_and_set_bit(NAPI_STATE_SCHED, &napi->state)) { 7213 clear_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state); 7214 __napi_schedule_irqoff(napi); 7215 } 7216 7217 return HRTIMER_NORESTART; 7218 } 7219 7220 static void napi_stop_kthread(struct napi_struct *napi) 7221 { 7222 unsigned long val, new; 7223 7224 /* Wait until the napi STATE_THREADED is unset. */ 7225 while (true) { 7226 val = READ_ONCE(napi->state); 7227 7228 /* If napi kthread own this napi or the napi is idle, 7229 * STATE_THREADED can be unset here. 7230 */ 7231 if ((val & NAPIF_STATE_SCHED_THREADED) || 7232 !(val & NAPIF_STATE_SCHED)) { 7233 new = val & (~(NAPIF_STATE_THREADED | 7234 NAPIF_STATE_THREADED_BUSY_POLL)); 7235 } else { 7236 msleep(20); 7237 continue; 7238 } 7239 7240 if (try_cmpxchg(&napi->state, &val, new)) 7241 break; 7242 } 7243 7244 /* Once STATE_THREADED is unset, wait for SCHED_THREADED to be unset by 7245 * the kthread. 7246 */ 7247 while (true) { 7248 if (!test_bit(NAPI_STATE_SCHED_THREADED, &napi->state)) 7249 break; 7250 7251 msleep(20); 7252 } 7253 7254 kthread_stop(napi->thread); 7255 napi->thread = NULL; 7256 } 7257 7258 static void napi_set_threaded_state(struct napi_struct *napi, 7259 enum netdev_napi_threaded threaded_mode) 7260 { 7261 bool threaded = threaded_mode != NETDEV_NAPI_THREADED_DISABLED; 7262 bool busy_poll = threaded_mode == NETDEV_NAPI_THREADED_BUSY_POLL; 7263 7264 assign_bit(NAPI_STATE_THREADED, &napi->state, threaded); 7265 assign_bit(NAPI_STATE_THREADED_BUSY_POLL, &napi->state, busy_poll); 7266 } 7267 7268 int napi_set_threaded(struct napi_struct *napi, 7269 enum netdev_napi_threaded threaded) 7270 { 7271 if (threaded) { 7272 if (!napi->thread) { 7273 int err = napi_kthread_create(napi); 7274 7275 if (err) 7276 return err; 7277 } 7278 } 7279 7280 if (napi->config) 7281 napi->config->threaded = threaded; 7282 7283 /* Setting/unsetting threaded mode on a napi might not immediately 7284 * take effect, if the current napi instance is actively being 7285 * polled. In this case, the switch between threaded mode and 7286 * softirq mode will happen in the next round of napi_schedule(). 7287 * This should not cause hiccups/stalls to the live traffic. 7288 */ 7289 if (!threaded && napi->thread) { 7290 napi_stop_kthread(napi); 7291 } else { 7292 /* Make sure kthread is created before THREADED bit is set. */ 7293 smp_mb__before_atomic(); 7294 napi_set_threaded_state(napi, threaded); 7295 } 7296 7297 return 0; 7298 } 7299 7300 int netif_set_threaded(struct net_device *dev, 7301 enum netdev_napi_threaded threaded) 7302 { 7303 struct napi_struct *napi; 7304 int i, err = 0; 7305 7306 netdev_assert_locked_or_invisible(dev); 7307 7308 if (threaded) { 7309 list_for_each_entry(napi, &dev->napi_list, dev_list) { 7310 if (!napi->thread) { 7311 err = napi_kthread_create(napi); 7312 if (err) { 7313 threaded = NETDEV_NAPI_THREADED_DISABLED; 7314 break; 7315 } 7316 } 7317 } 7318 } 7319 7320 WRITE_ONCE(dev->threaded, threaded); 7321 7322 /* The error should not occur as the kthreads are already created. */ 7323 list_for_each_entry(napi, &dev->napi_list, dev_list) 7324 WARN_ON_ONCE(napi_set_threaded(napi, threaded)); 7325 7326 /* Override the config for all NAPIs even if currently not listed */ 7327 for (i = 0; i < dev->num_napi_configs; i++) 7328 dev->napi_config[i].threaded = threaded; 7329 7330 return err; 7331 } 7332 7333 /** 7334 * netif_threaded_enable() - enable threaded NAPIs 7335 * @dev: net_device instance 7336 * 7337 * Enable threaded mode for the NAPI instances of the device. This may be useful 7338 * for devices where multiple NAPI instances get scheduled by a single 7339 * interrupt. Threaded NAPI allows moving the NAPI processing to cores other 7340 * than the core where IRQ is mapped. 7341 * 7342 * This function should be called before @dev is registered. 7343 */ 7344 void netif_threaded_enable(struct net_device *dev) 7345 { 7346 WARN_ON_ONCE(netif_set_threaded(dev, NETDEV_NAPI_THREADED_ENABLED)); 7347 } 7348 EXPORT_SYMBOL(netif_threaded_enable); 7349 7350 /** 7351 * netif_queue_set_napi - Associate queue with the napi 7352 * @dev: device to which NAPI and queue belong 7353 * @queue_index: Index of queue 7354 * @type: queue type as RX or TX 7355 * @napi: NAPI context, pass NULL to clear previously set NAPI 7356 * 7357 * Set queue with its corresponding napi context. This should be done after 7358 * registering the NAPI handler for the queue-vector and the queues have been 7359 * mapped to the corresponding interrupt vector. 7360 */ 7361 void netif_queue_set_napi(struct net_device *dev, unsigned int queue_index, 7362 enum netdev_queue_type type, struct napi_struct *napi) 7363 { 7364 struct netdev_rx_queue *rxq; 7365 struct netdev_queue *txq; 7366 7367 if (WARN_ON_ONCE(napi && !napi->dev)) 7368 return; 7369 netdev_assert_locked_ops_compat_or_invisible(dev); 7370 7371 switch (type) { 7372 case NETDEV_QUEUE_TYPE_RX: 7373 rxq = __netif_get_rx_queue(dev, queue_index); 7374 rxq->napi = napi; 7375 return; 7376 case NETDEV_QUEUE_TYPE_TX: 7377 txq = netdev_get_tx_queue(dev, queue_index); 7378 txq->napi = napi; 7379 return; 7380 default: 7381 return; 7382 } 7383 } 7384 EXPORT_SYMBOL(netif_queue_set_napi); 7385 7386 static void 7387 netif_napi_irq_notify(struct irq_affinity_notify *notify, 7388 const cpumask_t *mask) 7389 { 7390 struct napi_struct *napi = 7391 container_of(notify, struct napi_struct, notify); 7392 #ifdef CONFIG_RFS_ACCEL 7393 struct cpu_rmap *rmap = napi->dev->rx_cpu_rmap; 7394 int err; 7395 #endif 7396 7397 if (napi->config && napi->dev->irq_affinity_auto) 7398 cpumask_copy(&napi->config->affinity_mask, mask); 7399 7400 #ifdef CONFIG_RFS_ACCEL 7401 if (napi->dev->rx_cpu_rmap_auto) { 7402 err = cpu_rmap_update(rmap, napi->napi_rmap_idx, mask); 7403 if (err) 7404 netdev_warn(napi->dev, "RMAP update failed (%d)\n", 7405 err); 7406 } 7407 #endif 7408 } 7409 7410 #ifdef CONFIG_RFS_ACCEL 7411 static void netif_napi_affinity_release(struct kref *ref) 7412 { 7413 struct napi_struct *napi = 7414 container_of(ref, struct napi_struct, notify.kref); 7415 struct cpu_rmap *rmap = napi->dev->rx_cpu_rmap; 7416 7417 netdev_assert_locked(napi->dev); 7418 WARN_ON(test_and_clear_bit(NAPI_STATE_HAS_NOTIFIER, 7419 &napi->state)); 7420 7421 if (!napi->dev->rx_cpu_rmap_auto) 7422 return; 7423 rmap->obj[napi->napi_rmap_idx] = NULL; 7424 napi->napi_rmap_idx = -1; 7425 cpu_rmap_put(rmap); 7426 } 7427 7428 int netif_enable_cpu_rmap(struct net_device *dev, unsigned int num_irqs) 7429 { 7430 if (dev->rx_cpu_rmap_auto) 7431 return 0; 7432 7433 dev->rx_cpu_rmap = alloc_irq_cpu_rmap(num_irqs); 7434 if (!dev->rx_cpu_rmap) 7435 return -ENOMEM; 7436 7437 dev->rx_cpu_rmap_auto = true; 7438 return 0; 7439 } 7440 EXPORT_SYMBOL(netif_enable_cpu_rmap); 7441 7442 static void netif_del_cpu_rmap(struct net_device *dev) 7443 { 7444 struct cpu_rmap *rmap = dev->rx_cpu_rmap; 7445 7446 if (!dev->rx_cpu_rmap_auto) 7447 return; 7448 7449 /* Free the rmap */ 7450 cpu_rmap_put(rmap); 7451 dev->rx_cpu_rmap = NULL; 7452 dev->rx_cpu_rmap_auto = false; 7453 } 7454 7455 #else 7456 static void netif_napi_affinity_release(struct kref *ref) 7457 { 7458 } 7459 7460 int netif_enable_cpu_rmap(struct net_device *dev, unsigned int num_irqs) 7461 { 7462 return 0; 7463 } 7464 EXPORT_SYMBOL(netif_enable_cpu_rmap); 7465 7466 static void netif_del_cpu_rmap(struct net_device *dev) 7467 { 7468 } 7469 #endif 7470 7471 void netif_set_affinity_auto(struct net_device *dev) 7472 { 7473 unsigned int i, maxqs, numa; 7474 7475 maxqs = max(dev->num_tx_queues, dev->num_rx_queues); 7476 numa = dev_to_node(&dev->dev); 7477 7478 for (i = 0; i < maxqs; i++) 7479 cpumask_set_cpu(cpumask_local_spread(i, numa), 7480 &dev->napi_config[i].affinity_mask); 7481 7482 dev->irq_affinity_auto = true; 7483 } 7484 EXPORT_SYMBOL(netif_set_affinity_auto); 7485 7486 void netif_napi_set_irq_locked(struct napi_struct *napi, int irq) 7487 { 7488 int rc; 7489 7490 netdev_assert_locked_or_invisible(napi->dev); 7491 7492 if (napi->irq == irq) 7493 return; 7494 7495 /* Remove existing resources */ 7496 if (test_and_clear_bit(NAPI_STATE_HAS_NOTIFIER, &napi->state)) 7497 irq_set_affinity_notifier(napi->irq, NULL); 7498 7499 napi->irq = irq; 7500 if (irq < 0 || 7501 (!napi->dev->rx_cpu_rmap_auto && !napi->dev->irq_affinity_auto)) 7502 return; 7503 7504 /* Abort for buggy drivers */ 7505 if (napi->dev->irq_affinity_auto && WARN_ON_ONCE(!napi->config)) 7506 return; 7507 7508 #ifdef CONFIG_RFS_ACCEL 7509 if (napi->dev->rx_cpu_rmap_auto) { 7510 rc = cpu_rmap_add(napi->dev->rx_cpu_rmap, napi); 7511 if (rc < 0) 7512 return; 7513 7514 cpu_rmap_get(napi->dev->rx_cpu_rmap); 7515 napi->napi_rmap_idx = rc; 7516 } 7517 #endif 7518 7519 /* Use core IRQ notifier */ 7520 napi->notify.notify = netif_napi_irq_notify; 7521 napi->notify.release = netif_napi_affinity_release; 7522 rc = irq_set_affinity_notifier(irq, &napi->notify); 7523 if (rc) { 7524 netdev_warn(napi->dev, "Unable to set IRQ notifier (%d)\n", 7525 rc); 7526 goto put_rmap; 7527 } 7528 7529 set_bit(NAPI_STATE_HAS_NOTIFIER, &napi->state); 7530 return; 7531 7532 put_rmap: 7533 #ifdef CONFIG_RFS_ACCEL 7534 if (napi->dev->rx_cpu_rmap_auto) { 7535 napi->dev->rx_cpu_rmap->obj[napi->napi_rmap_idx] = NULL; 7536 cpu_rmap_put(napi->dev->rx_cpu_rmap); 7537 napi->napi_rmap_idx = -1; 7538 } 7539 #endif 7540 napi->notify.notify = NULL; 7541 napi->notify.release = NULL; 7542 } 7543 EXPORT_SYMBOL(netif_napi_set_irq_locked); 7544 7545 static void napi_restore_config(struct napi_struct *n) 7546 { 7547 n->defer_hard_irqs = n->config->defer_hard_irqs; 7548 n->gro_flush_timeout = n->config->gro_flush_timeout; 7549 n->irq_suspend_timeout = n->config->irq_suspend_timeout; 7550 7551 if (n->dev->irq_affinity_auto && 7552 test_bit(NAPI_STATE_HAS_NOTIFIER, &n->state)) 7553 irq_set_affinity(n->irq, &n->config->affinity_mask); 7554 7555 /* a NAPI ID might be stored in the config, if so use it. if not, use 7556 * napi_hash_add to generate one for us. 7557 */ 7558 if (n->config->napi_id) { 7559 napi_hash_add_with_id(n, n->config->napi_id); 7560 } else { 7561 napi_hash_add(n); 7562 n->config->napi_id = n->napi_id; 7563 } 7564 7565 WARN_ON_ONCE(napi_set_threaded(n, n->config->threaded)); 7566 } 7567 7568 static void napi_save_config(struct napi_struct *n) 7569 { 7570 n->config->defer_hard_irqs = n->defer_hard_irqs; 7571 n->config->gro_flush_timeout = n->gro_flush_timeout; 7572 n->config->irq_suspend_timeout = n->irq_suspend_timeout; 7573 napi_hash_del(n); 7574 } 7575 7576 /* Netlink wants the NAPI list to be sorted by ID, if adding a NAPI which will 7577 * inherit an existing ID try to insert it at the right position. 7578 */ 7579 static void 7580 netif_napi_dev_list_add(struct net_device *dev, struct napi_struct *napi) 7581 { 7582 unsigned int new_id, pos_id; 7583 struct list_head *higher; 7584 struct napi_struct *pos; 7585 7586 new_id = UINT_MAX; 7587 if (napi->config && napi->config->napi_id) 7588 new_id = napi->config->napi_id; 7589 7590 higher = &dev->napi_list; 7591 list_for_each_entry(pos, &dev->napi_list, dev_list) { 7592 if (napi_id_valid(pos->napi_id)) 7593 pos_id = pos->napi_id; 7594 else if (pos->config) 7595 pos_id = pos->config->napi_id; 7596 else 7597 pos_id = UINT_MAX; 7598 7599 if (pos_id <= new_id) 7600 break; 7601 higher = &pos->dev_list; 7602 } 7603 list_add_rcu(&napi->dev_list, higher); /* adds after higher */ 7604 } 7605 7606 /* Double check that napi_get_frags() allocates skbs with 7607 * skb->head being backed by slab, not a page fragment. 7608 * This is to make sure bug fixed in 3226b158e67c 7609 * ("net: avoid 32 x truesize under-estimation for tiny skbs") 7610 * does not accidentally come back. 7611 */ 7612 static void napi_get_frags_check(struct napi_struct *napi) 7613 { 7614 struct sk_buff *skb; 7615 7616 local_bh_disable(); 7617 skb = napi_get_frags(napi); 7618 WARN_ON_ONCE(skb && skb->head_frag); 7619 napi_free_frags(napi); 7620 local_bh_enable(); 7621 } 7622 7623 void netif_napi_add_weight_locked(struct net_device *dev, 7624 struct napi_struct *napi, 7625 int (*poll)(struct napi_struct *, int), 7626 int weight) 7627 { 7628 netdev_assert_locked(dev); 7629 if (WARN_ON(test_and_set_bit(NAPI_STATE_LISTED, &napi->state))) 7630 return; 7631 7632 INIT_LIST_HEAD(&napi->poll_list); 7633 INIT_HLIST_NODE(&napi->napi_hash_node); 7634 hrtimer_setup(&napi->timer, napi_watchdog, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED); 7635 gro_init(&napi->gro); 7636 napi->skb = NULL; 7637 napi->poll = poll; 7638 if (weight > NAPI_POLL_WEIGHT) 7639 netdev_err_once(dev, "%s() called with weight %d\n", __func__, 7640 weight); 7641 napi->weight = weight; 7642 napi->dev = dev; 7643 #ifdef CONFIG_NETPOLL 7644 napi->poll_owner = -1; 7645 #endif 7646 napi->list_owner = -1; 7647 set_bit(NAPI_STATE_SCHED, &napi->state); 7648 set_bit(NAPI_STATE_NPSVC, &napi->state); 7649 netif_napi_dev_list_add(dev, napi); 7650 7651 /* default settings from sysfs are applied to all NAPIs. any per-NAPI 7652 * configuration will be loaded in napi_enable 7653 */ 7654 napi_set_defer_hard_irqs(napi, READ_ONCE(dev->napi_defer_hard_irqs)); 7655 napi_set_gro_flush_timeout(napi, READ_ONCE(dev->gro_flush_timeout)); 7656 7657 napi_get_frags_check(napi); 7658 /* Create kthread for this napi if dev->threaded is set. 7659 * Clear dev->threaded if kthread creation failed so that 7660 * threaded mode will not be enabled in napi_enable(). 7661 */ 7662 if (napi_get_threaded_config(dev, napi)) 7663 if (napi_kthread_create(napi)) 7664 dev->threaded = NETDEV_NAPI_THREADED_DISABLED; 7665 netif_napi_set_irq_locked(napi, -1); 7666 } 7667 EXPORT_SYMBOL(netif_napi_add_weight_locked); 7668 7669 void napi_disable_locked(struct napi_struct *n) 7670 { 7671 unsigned long val, new; 7672 7673 might_sleep(); 7674 netdev_assert_locked(n->dev); 7675 7676 set_bit(NAPI_STATE_DISABLE, &n->state); 7677 7678 val = READ_ONCE(n->state); 7679 do { 7680 while (val & (NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC)) { 7681 usleep_range(20, 200); 7682 val = READ_ONCE(n->state); 7683 } 7684 7685 new = val | NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC; 7686 new &= ~(NAPIF_STATE_THREADED | 7687 NAPIF_STATE_THREADED_BUSY_POLL | 7688 NAPIF_STATE_PREFER_BUSY_POLL); 7689 } while (!try_cmpxchg(&n->state, &val, new)); 7690 7691 hrtimer_cancel(&n->timer); 7692 7693 if (n->config) 7694 napi_save_config(n); 7695 else 7696 napi_hash_del(n); 7697 7698 clear_bit(NAPI_STATE_DISABLE, &n->state); 7699 } 7700 EXPORT_SYMBOL(napi_disable_locked); 7701 7702 /** 7703 * napi_disable() - prevent NAPI from scheduling 7704 * @n: NAPI context 7705 * 7706 * Stop NAPI from being scheduled on this context. 7707 * Waits till any outstanding processing completes. 7708 * Takes netdev_lock() for associated net_device. 7709 */ 7710 void napi_disable(struct napi_struct *n) 7711 { 7712 netdev_lock(n->dev); 7713 napi_disable_locked(n); 7714 netdev_unlock(n->dev); 7715 } 7716 EXPORT_SYMBOL(napi_disable); 7717 7718 void napi_enable_locked(struct napi_struct *n) 7719 { 7720 unsigned long new, val = READ_ONCE(n->state); 7721 7722 if (n->config) 7723 napi_restore_config(n); 7724 else 7725 napi_hash_add(n); 7726 7727 do { 7728 BUG_ON(!test_bit(NAPI_STATE_SCHED, &val)); 7729 7730 new = val & ~(NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC); 7731 if (n->dev->threaded && n->thread) 7732 new |= NAPIF_STATE_THREADED; 7733 } while (!try_cmpxchg(&n->state, &val, new)); 7734 } 7735 EXPORT_SYMBOL(napi_enable_locked); 7736 7737 /** 7738 * napi_enable() - enable NAPI scheduling 7739 * @n: NAPI context 7740 * 7741 * Enable scheduling of a NAPI instance. 7742 * Must be paired with napi_disable(). 7743 * Takes netdev_lock() for associated net_device. 7744 */ 7745 void napi_enable(struct napi_struct *n) 7746 { 7747 netdev_lock(n->dev); 7748 napi_enable_locked(n); 7749 netdev_unlock(n->dev); 7750 } 7751 EXPORT_SYMBOL(napi_enable); 7752 7753 /* Must be called in process context */ 7754 void __netif_napi_del_locked(struct napi_struct *napi) 7755 { 7756 netdev_assert_locked(napi->dev); 7757 7758 if (!test_and_clear_bit(NAPI_STATE_LISTED, &napi->state)) 7759 return; 7760 7761 /* Make sure NAPI is disabled (or was never enabled). */ 7762 WARN_ON(!test_bit(NAPI_STATE_SCHED, &napi->state)); 7763 7764 if (test_and_clear_bit(NAPI_STATE_HAS_NOTIFIER, &napi->state)) 7765 irq_set_affinity_notifier(napi->irq, NULL); 7766 7767 if (napi->config) { 7768 napi->index = -1; 7769 napi->config = NULL; 7770 } 7771 7772 list_del_rcu(&napi->dev_list); 7773 napi_free_frags(napi); 7774 7775 gro_cleanup(&napi->gro); 7776 7777 if (napi->thread) { 7778 kthread_stop(napi->thread); 7779 napi->thread = NULL; 7780 } 7781 } 7782 EXPORT_SYMBOL(__netif_napi_del_locked); 7783 7784 static int __napi_poll(struct napi_struct *n, bool *repoll) 7785 { 7786 int work, weight; 7787 7788 weight = n->weight; 7789 7790 /* This NAPI_STATE_SCHED test is for avoiding a race 7791 * with netpoll's poll_napi(). Only the entity which 7792 * obtains the lock and sees NAPI_STATE_SCHED set will 7793 * actually make the ->poll() call. Therefore we avoid 7794 * accidentally calling ->poll() when NAPI is not scheduled. 7795 */ 7796 work = 0; 7797 if (napi_is_scheduled(n)) { 7798 work = n->poll(n, weight); 7799 trace_napi_poll(n, work, weight); 7800 7801 xdp_do_check_flushed(n); 7802 } 7803 7804 if (unlikely(work > weight)) 7805 netdev_err_once(n->dev, "NAPI poll function %pS returned %d, exceeding its budget of %d.\n", 7806 n->poll, work, weight); 7807 7808 if (likely(work < weight)) 7809 return work; 7810 7811 /* Drivers must not modify the NAPI state if they 7812 * consume the entire weight. In such cases this code 7813 * still "owns" the NAPI instance and therefore can 7814 * move the instance around on the list at-will. 7815 */ 7816 if (unlikely(napi_disable_pending(n))) { 7817 napi_complete(n); 7818 return work; 7819 } 7820 7821 /* The NAPI context has more processing work, but busy-polling 7822 * is preferred. Exit early. 7823 */ 7824 if (napi_prefer_busy_poll(n)) { 7825 if (napi_complete_done(n, work)) { 7826 /* If timeout is not set, we need to make sure 7827 * that the NAPI is re-scheduled. 7828 */ 7829 napi_schedule(n); 7830 } 7831 return work; 7832 } 7833 7834 /* Flush too old packets. If HZ < 1000, flush all packets */ 7835 gro_flush_normal(&n->gro, HZ >= 1000); 7836 7837 /* Some drivers may have called napi_schedule 7838 * prior to exhausting their budget. 7839 */ 7840 if (unlikely(!list_empty(&n->poll_list))) { 7841 pr_warn_once("%s: Budget exhausted after napi rescheduled\n", 7842 n->dev ? n->dev->name : "backlog"); 7843 return work; 7844 } 7845 7846 *repoll = true; 7847 7848 return work; 7849 } 7850 7851 static int napi_poll(struct napi_struct *n, struct list_head *repoll) 7852 { 7853 bool do_repoll = false; 7854 void *have; 7855 int work; 7856 7857 list_del_init(&n->poll_list); 7858 7859 have = netpoll_poll_lock(n); 7860 7861 work = __napi_poll(n, &do_repoll); 7862 7863 if (do_repoll) { 7864 #if defined(CONFIG_DEBUG_NET) 7865 if (unlikely(!napi_is_scheduled(n))) 7866 pr_crit("repoll requested for device %s %ps but napi is not scheduled.\n", 7867 n->dev->name, n->poll); 7868 #endif 7869 list_add_tail(&n->poll_list, repoll); 7870 } 7871 netpoll_poll_unlock(have); 7872 7873 return work; 7874 } 7875 7876 static int napi_thread_wait(struct napi_struct *napi) 7877 { 7878 set_current_state(TASK_INTERRUPTIBLE); 7879 7880 while (!kthread_should_stop()) { 7881 /* Testing SCHED_THREADED bit here to make sure the current 7882 * kthread owns this napi and could poll on this napi. 7883 * Testing SCHED bit is not enough because SCHED bit might be 7884 * set by some other busy poll thread or by napi_disable(). 7885 */ 7886 if (test_bit(NAPI_STATE_SCHED_THREADED, &napi->state)) { 7887 WARN_ON(!list_empty(&napi->poll_list)); 7888 __set_current_state(TASK_RUNNING); 7889 return 0; 7890 } 7891 7892 schedule(); 7893 set_current_state(TASK_INTERRUPTIBLE); 7894 } 7895 __set_current_state(TASK_RUNNING); 7896 7897 return -1; 7898 } 7899 7900 static void napi_threaded_poll_loop(struct napi_struct *napi, 7901 unsigned long *busy_poll_last_qs) 7902 { 7903 unsigned long last_qs = busy_poll_last_qs ? *busy_poll_last_qs : jiffies; 7904 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx; 7905 struct softnet_data *sd; 7906 7907 for (;;) { 7908 bool repoll = false; 7909 void *have; 7910 7911 local_bh_disable(); 7912 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx); 7913 7914 sd = this_cpu_ptr(&softnet_data); 7915 sd->in_napi_threaded_poll = true; 7916 7917 have = netpoll_poll_lock(napi); 7918 __napi_poll(napi, &repoll); 7919 netpoll_poll_unlock(have); 7920 7921 sd->in_napi_threaded_poll = false; 7922 barrier(); 7923 7924 if (sd_has_rps_ipi_waiting(sd)) { 7925 local_irq_disable(); 7926 net_rps_action_and_irq_enable(sd); 7927 } 7928 skb_defer_free_flush(); 7929 bpf_net_ctx_clear(bpf_net_ctx); 7930 7931 /* When busy poll is enabled, the old packets are not flushed in 7932 * napi_complete_done. So flush them here. 7933 */ 7934 if (busy_poll_last_qs) 7935 gro_flush_normal(&napi->gro, HZ >= 1000); 7936 local_bh_enable(); 7937 7938 /* Call cond_resched here to avoid watchdog warnings. */ 7939 if (repoll || busy_poll_last_qs) { 7940 rcu_softirq_qs_periodic(last_qs); 7941 cond_resched(); 7942 } 7943 7944 if (!repoll) 7945 break; 7946 } 7947 7948 if (busy_poll_last_qs) 7949 *busy_poll_last_qs = last_qs; 7950 } 7951 7952 static int napi_threaded_poll(void *data) 7953 { 7954 struct napi_struct *napi = data; 7955 unsigned long last_qs = jiffies; 7956 bool want_busy_poll; 7957 bool in_busy_poll; 7958 unsigned long val; 7959 7960 while (!napi_thread_wait(napi)) { 7961 val = READ_ONCE(napi->state); 7962 7963 want_busy_poll = val & NAPIF_STATE_THREADED_BUSY_POLL; 7964 in_busy_poll = val & NAPIF_STATE_IN_BUSY_POLL; 7965 7966 if (unlikely(val & NAPIF_STATE_DISABLE)) 7967 want_busy_poll = false; 7968 7969 if (want_busy_poll != in_busy_poll) 7970 assign_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state, 7971 want_busy_poll); 7972 7973 napi_threaded_poll_loop(napi, want_busy_poll ? &last_qs : NULL); 7974 } 7975 7976 return 0; 7977 } 7978 7979 static __latent_entropy void net_rx_action(void) 7980 { 7981 struct softnet_data *sd = this_cpu_ptr(&softnet_data); 7982 unsigned long time_limit = jiffies + 7983 usecs_to_jiffies(READ_ONCE(net_hotdata.netdev_budget_usecs)); 7984 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx; 7985 int budget = READ_ONCE(net_hotdata.netdev_budget); 7986 LIST_HEAD(list); 7987 LIST_HEAD(repoll); 7988 7989 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx); 7990 start: 7991 sd->in_net_rx_action = true; 7992 local_irq_disable(); 7993 list_splice_init(&sd->poll_list, &list); 7994 local_irq_enable(); 7995 7996 for (;;) { 7997 struct napi_struct *n; 7998 7999 skb_defer_free_flush(); 8000 8001 if (list_empty(&list)) { 8002 if (list_empty(&repoll)) { 8003 sd->in_net_rx_action = false; 8004 barrier(); 8005 /* We need to check if ____napi_schedule() 8006 * had refilled poll_list while 8007 * sd->in_net_rx_action was true. 8008 */ 8009 if (!list_empty(&sd->poll_list)) 8010 goto start; 8011 if (!sd_has_rps_ipi_waiting(sd)) 8012 goto end; 8013 } 8014 break; 8015 } 8016 8017 n = list_first_entry(&list, struct napi_struct, poll_list); 8018 budget -= napi_poll(n, &repoll); 8019 8020 /* If softirq window is exhausted then punt. 8021 * Allow this to run for 2 jiffies since which will allow 8022 * an average latency of 1.5/HZ. 8023 */ 8024 if (unlikely(budget <= 0 || 8025 time_after_eq(jiffies, time_limit))) { 8026 /* Pairs with READ_ONCE() in softnet_seq_show() */ 8027 WRITE_ONCE(sd->time_squeeze, sd->time_squeeze + 1); 8028 break; 8029 } 8030 } 8031 8032 local_irq_disable(); 8033 8034 list_splice_tail_init(&sd->poll_list, &list); 8035 list_splice_tail(&repoll, &list); 8036 list_splice(&list, &sd->poll_list); 8037 if (!list_empty(&sd->poll_list)) 8038 __raise_softirq_irqoff(NET_RX_SOFTIRQ); 8039 else 8040 sd->in_net_rx_action = false; 8041 8042 net_rps_action_and_irq_enable(sd); 8043 end: 8044 bpf_net_ctx_clear(bpf_net_ctx); 8045 } 8046 8047 struct netdev_adjacent { 8048 struct net_device *dev; 8049 netdevice_tracker dev_tracker; 8050 8051 /* upper master flag, there can only be one master device per list */ 8052 bool master; 8053 8054 /* lookup ignore flag */ 8055 bool ignore; 8056 8057 /* counter for the number of times this device was added to us */ 8058 u16 ref_nr; 8059 8060 /* private field for the users */ 8061 void *private; 8062 8063 struct list_head list; 8064 struct rcu_head rcu; 8065 }; 8066 8067 static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev, 8068 struct list_head *adj_list) 8069 { 8070 struct netdev_adjacent *adj; 8071 8072 list_for_each_entry(adj, adj_list, list) { 8073 if (adj->dev == adj_dev) 8074 return adj; 8075 } 8076 return NULL; 8077 } 8078 8079 static int ____netdev_has_upper_dev(struct net_device *upper_dev, 8080 struct netdev_nested_priv *priv) 8081 { 8082 struct net_device *dev = (struct net_device *)priv->data; 8083 8084 return upper_dev == dev; 8085 } 8086 8087 /** 8088 * netdev_has_upper_dev - Check if device is linked to an upper device 8089 * @dev: device 8090 * @upper_dev: upper device to check 8091 * 8092 * Find out if a device is linked to specified upper device and return true 8093 * in case it is. Note that this checks only immediate upper device, 8094 * not through a complete stack of devices. The caller must hold the RTNL lock. 8095 */ 8096 bool netdev_has_upper_dev(struct net_device *dev, 8097 struct net_device *upper_dev) 8098 { 8099 struct netdev_nested_priv priv = { 8100 .data = (void *)upper_dev, 8101 }; 8102 8103 ASSERT_RTNL(); 8104 8105 return netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev, 8106 &priv); 8107 } 8108 EXPORT_SYMBOL(netdev_has_upper_dev); 8109 8110 /** 8111 * netdev_has_upper_dev_all_rcu - Check if device is linked to an upper device 8112 * @dev: device 8113 * @upper_dev: upper device to check 8114 * 8115 * Find out if a device is linked to specified upper device and return true 8116 * in case it is. Note that this checks the entire upper device chain. 8117 * The caller must hold rcu lock. 8118 */ 8119 8120 bool netdev_has_upper_dev_all_rcu(struct net_device *dev, 8121 struct net_device *upper_dev) 8122 { 8123 struct netdev_nested_priv priv = { 8124 .data = (void *)upper_dev, 8125 }; 8126 8127 return !!netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev, 8128 &priv); 8129 } 8130 EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu); 8131 8132 /** 8133 * netdev_has_any_upper_dev - Check if device is linked to some device 8134 * @dev: device 8135 * 8136 * Find out if a device is linked to an upper device and return true in case 8137 * it is. The caller must hold the RTNL lock. 8138 */ 8139 bool netdev_has_any_upper_dev(struct net_device *dev) 8140 { 8141 ASSERT_RTNL(); 8142 8143 return !list_empty(&dev->adj_list.upper); 8144 } 8145 EXPORT_SYMBOL(netdev_has_any_upper_dev); 8146 8147 /** 8148 * netdev_master_upper_dev_get - Get master upper device 8149 * @dev: device 8150 * 8151 * Find a master upper device and return pointer to it or NULL in case 8152 * it's not there. The caller must hold the RTNL lock. 8153 */ 8154 struct net_device *netdev_master_upper_dev_get(struct net_device *dev) 8155 { 8156 struct netdev_adjacent *upper; 8157 8158 ASSERT_RTNL(); 8159 8160 if (list_empty(&dev->adj_list.upper)) 8161 return NULL; 8162 8163 upper = list_first_entry(&dev->adj_list.upper, 8164 struct netdev_adjacent, list); 8165 if (likely(upper->master)) 8166 return upper->dev; 8167 return NULL; 8168 } 8169 EXPORT_SYMBOL(netdev_master_upper_dev_get); 8170 8171 static struct net_device *__netdev_master_upper_dev_get(struct net_device *dev) 8172 { 8173 struct netdev_adjacent *upper; 8174 8175 ASSERT_RTNL(); 8176 8177 if (list_empty(&dev->adj_list.upper)) 8178 return NULL; 8179 8180 upper = list_first_entry(&dev->adj_list.upper, 8181 struct netdev_adjacent, list); 8182 if (likely(upper->master) && !upper->ignore) 8183 return upper->dev; 8184 return NULL; 8185 } 8186 8187 /** 8188 * netdev_has_any_lower_dev - Check if device is linked to some device 8189 * @dev: device 8190 * 8191 * Find out if a device is linked to a lower device and return true in case 8192 * it is. The caller must hold the RTNL lock. 8193 */ 8194 static bool netdev_has_any_lower_dev(struct net_device *dev) 8195 { 8196 ASSERT_RTNL(); 8197 8198 return !list_empty(&dev->adj_list.lower); 8199 } 8200 8201 void *netdev_adjacent_get_private(struct list_head *adj_list) 8202 { 8203 struct netdev_adjacent *adj; 8204 8205 adj = list_entry(adj_list, struct netdev_adjacent, list); 8206 8207 return adj->private; 8208 } 8209 EXPORT_SYMBOL(netdev_adjacent_get_private); 8210 8211 /** 8212 * netdev_upper_get_next_dev_rcu - Get the next dev from upper list 8213 * @dev: device 8214 * @iter: list_head ** of the current position 8215 * 8216 * Gets the next device from the dev's upper list, starting from iter 8217 * position. The caller must hold RCU read lock. 8218 */ 8219 struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev, 8220 struct list_head **iter) 8221 { 8222 struct netdev_adjacent *upper; 8223 8224 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held() && 8225 !lockdep_rtnl_is_held()); 8226 8227 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list); 8228 8229 if (&upper->list == &dev->adj_list.upper) 8230 return NULL; 8231 8232 *iter = &upper->list; 8233 8234 return upper->dev; 8235 } 8236 EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu); 8237 8238 static struct net_device *__netdev_next_upper_dev(struct net_device *dev, 8239 struct list_head **iter, 8240 bool *ignore) 8241 { 8242 struct netdev_adjacent *upper; 8243 8244 upper = list_entry((*iter)->next, struct netdev_adjacent, list); 8245 8246 if (&upper->list == &dev->adj_list.upper) 8247 return NULL; 8248 8249 *iter = &upper->list; 8250 *ignore = upper->ignore; 8251 8252 return upper->dev; 8253 } 8254 8255 static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev, 8256 struct list_head **iter) 8257 { 8258 struct netdev_adjacent *upper; 8259 8260 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held()); 8261 8262 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list); 8263 8264 if (&upper->list == &dev->adj_list.upper) 8265 return NULL; 8266 8267 *iter = &upper->list; 8268 8269 return upper->dev; 8270 } 8271 8272 static int __netdev_walk_all_upper_dev(struct net_device *dev, 8273 int (*fn)(struct net_device *dev, 8274 struct netdev_nested_priv *priv), 8275 struct netdev_nested_priv *priv) 8276 { 8277 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1]; 8278 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1]; 8279 int ret, cur = 0; 8280 bool ignore; 8281 8282 now = dev; 8283 iter = &dev->adj_list.upper; 8284 8285 while (1) { 8286 if (now != dev) { 8287 ret = fn(now, priv); 8288 if (ret) 8289 return ret; 8290 } 8291 8292 next = NULL; 8293 while (1) { 8294 udev = __netdev_next_upper_dev(now, &iter, &ignore); 8295 if (!udev) 8296 break; 8297 if (ignore) 8298 continue; 8299 8300 next = udev; 8301 niter = &udev->adj_list.upper; 8302 dev_stack[cur] = now; 8303 iter_stack[cur++] = iter; 8304 break; 8305 } 8306 8307 if (!next) { 8308 if (!cur) 8309 return 0; 8310 next = dev_stack[--cur]; 8311 niter = iter_stack[cur]; 8312 } 8313 8314 now = next; 8315 iter = niter; 8316 } 8317 8318 return 0; 8319 } 8320 8321 int netdev_walk_all_upper_dev_rcu(struct net_device *dev, 8322 int (*fn)(struct net_device *dev, 8323 struct netdev_nested_priv *priv), 8324 struct netdev_nested_priv *priv) 8325 { 8326 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1]; 8327 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1]; 8328 int ret, cur = 0; 8329 8330 now = dev; 8331 iter = &dev->adj_list.upper; 8332 8333 while (1) { 8334 if (now != dev) { 8335 ret = fn(now, priv); 8336 if (ret) 8337 return ret; 8338 } 8339 8340 next = NULL; 8341 while (1) { 8342 udev = netdev_next_upper_dev_rcu(now, &iter); 8343 if (!udev) 8344 break; 8345 8346 next = udev; 8347 niter = &udev->adj_list.upper; 8348 dev_stack[cur] = now; 8349 iter_stack[cur++] = iter; 8350 break; 8351 } 8352 8353 if (!next) { 8354 if (!cur) 8355 return 0; 8356 next = dev_stack[--cur]; 8357 niter = iter_stack[cur]; 8358 } 8359 8360 now = next; 8361 iter = niter; 8362 } 8363 8364 return 0; 8365 } 8366 EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu); 8367 8368 static bool __netdev_has_upper_dev(struct net_device *dev, 8369 struct net_device *upper_dev) 8370 { 8371 struct netdev_nested_priv priv = { 8372 .flags = 0, 8373 .data = (void *)upper_dev, 8374 }; 8375 8376 ASSERT_RTNL(); 8377 8378 return __netdev_walk_all_upper_dev(dev, ____netdev_has_upper_dev, 8379 &priv); 8380 } 8381 8382 /** 8383 * netdev_lower_get_next_private - Get the next ->private from the 8384 * lower neighbour list 8385 * @dev: device 8386 * @iter: list_head ** of the current position 8387 * 8388 * Gets the next netdev_adjacent->private from the dev's lower neighbour 8389 * list, starting from iter position. The caller must hold either hold the 8390 * RTNL lock or its own locking that guarantees that the neighbour lower 8391 * list will remain unchanged. 8392 */ 8393 void *netdev_lower_get_next_private(struct net_device *dev, 8394 struct list_head **iter) 8395 { 8396 struct netdev_adjacent *lower; 8397 8398 lower = list_entry(*iter, struct netdev_adjacent, list); 8399 8400 if (&lower->list == &dev->adj_list.lower) 8401 return NULL; 8402 8403 *iter = lower->list.next; 8404 8405 return lower->private; 8406 } 8407 EXPORT_SYMBOL(netdev_lower_get_next_private); 8408 8409 /** 8410 * netdev_lower_get_next_private_rcu - Get the next ->private from the 8411 * lower neighbour list, RCU 8412 * variant 8413 * @dev: device 8414 * @iter: list_head ** of the current position 8415 * 8416 * Gets the next netdev_adjacent->private from the dev's lower neighbour 8417 * list, starting from iter position. The caller must hold RCU read lock. 8418 */ 8419 void *netdev_lower_get_next_private_rcu(struct net_device *dev, 8420 struct list_head **iter) 8421 { 8422 struct netdev_adjacent *lower; 8423 8424 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held()); 8425 8426 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list); 8427 8428 if (&lower->list == &dev->adj_list.lower) 8429 return NULL; 8430 8431 *iter = &lower->list; 8432 8433 return lower->private; 8434 } 8435 EXPORT_SYMBOL(netdev_lower_get_next_private_rcu); 8436 8437 /** 8438 * netdev_lower_get_next - Get the next device from the lower neighbour 8439 * list 8440 * @dev: device 8441 * @iter: list_head ** of the current position 8442 * 8443 * Gets the next netdev_adjacent from the dev's lower neighbour 8444 * list, starting from iter position. The caller must hold RTNL lock or 8445 * its own locking that guarantees that the neighbour lower 8446 * list will remain unchanged. 8447 */ 8448 void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter) 8449 { 8450 struct netdev_adjacent *lower; 8451 8452 lower = list_entry(*iter, struct netdev_adjacent, list); 8453 8454 if (&lower->list == &dev->adj_list.lower) 8455 return NULL; 8456 8457 *iter = lower->list.next; 8458 8459 return lower->dev; 8460 } 8461 EXPORT_SYMBOL(netdev_lower_get_next); 8462 8463 static struct net_device *netdev_next_lower_dev(struct net_device *dev, 8464 struct list_head **iter) 8465 { 8466 struct netdev_adjacent *lower; 8467 8468 lower = list_entry((*iter)->next, struct netdev_adjacent, list); 8469 8470 if (&lower->list == &dev->adj_list.lower) 8471 return NULL; 8472 8473 *iter = &lower->list; 8474 8475 return lower->dev; 8476 } 8477 8478 static struct net_device *__netdev_next_lower_dev(struct net_device *dev, 8479 struct list_head **iter, 8480 bool *ignore) 8481 { 8482 struct netdev_adjacent *lower; 8483 8484 lower = list_entry((*iter)->next, struct netdev_adjacent, list); 8485 8486 if (&lower->list == &dev->adj_list.lower) 8487 return NULL; 8488 8489 *iter = &lower->list; 8490 *ignore = lower->ignore; 8491 8492 return lower->dev; 8493 } 8494 8495 int netdev_walk_all_lower_dev(struct net_device *dev, 8496 int (*fn)(struct net_device *dev, 8497 struct netdev_nested_priv *priv), 8498 struct netdev_nested_priv *priv) 8499 { 8500 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1]; 8501 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1]; 8502 int ret, cur = 0; 8503 8504 now = dev; 8505 iter = &dev->adj_list.lower; 8506 8507 while (1) { 8508 if (now != dev) { 8509 ret = fn(now, priv); 8510 if (ret) 8511 return ret; 8512 } 8513 8514 next = NULL; 8515 while (1) { 8516 ldev = netdev_next_lower_dev(now, &iter); 8517 if (!ldev) 8518 break; 8519 8520 next = ldev; 8521 niter = &ldev->adj_list.lower; 8522 dev_stack[cur] = now; 8523 iter_stack[cur++] = iter; 8524 break; 8525 } 8526 8527 if (!next) { 8528 if (!cur) 8529 return 0; 8530 next = dev_stack[--cur]; 8531 niter = iter_stack[cur]; 8532 } 8533 8534 now = next; 8535 iter = niter; 8536 } 8537 8538 return 0; 8539 } 8540 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev); 8541 8542 static int __netdev_walk_all_lower_dev(struct net_device *dev, 8543 int (*fn)(struct net_device *dev, 8544 struct netdev_nested_priv *priv), 8545 struct netdev_nested_priv *priv) 8546 { 8547 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1]; 8548 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1]; 8549 int ret, cur = 0; 8550 bool ignore; 8551 8552 now = dev; 8553 iter = &dev->adj_list.lower; 8554 8555 while (1) { 8556 if (now != dev) { 8557 ret = fn(now, priv); 8558 if (ret) 8559 return ret; 8560 } 8561 8562 next = NULL; 8563 while (1) { 8564 ldev = __netdev_next_lower_dev(now, &iter, &ignore); 8565 if (!ldev) 8566 break; 8567 if (ignore) 8568 continue; 8569 8570 next = ldev; 8571 niter = &ldev->adj_list.lower; 8572 dev_stack[cur] = now; 8573 iter_stack[cur++] = iter; 8574 break; 8575 } 8576 8577 if (!next) { 8578 if (!cur) 8579 return 0; 8580 next = dev_stack[--cur]; 8581 niter = iter_stack[cur]; 8582 } 8583 8584 now = next; 8585 iter = niter; 8586 } 8587 8588 return 0; 8589 } 8590 8591 struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev, 8592 struct list_head **iter) 8593 { 8594 struct netdev_adjacent *lower; 8595 8596 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list); 8597 if (&lower->list == &dev->adj_list.lower) 8598 return NULL; 8599 8600 *iter = &lower->list; 8601 8602 return lower->dev; 8603 } 8604 EXPORT_SYMBOL(netdev_next_lower_dev_rcu); 8605 8606 static u8 __netdev_upper_depth(struct net_device *dev) 8607 { 8608 struct net_device *udev; 8609 struct list_head *iter; 8610 u8 max_depth = 0; 8611 bool ignore; 8612 8613 for (iter = &dev->adj_list.upper, 8614 udev = __netdev_next_upper_dev(dev, &iter, &ignore); 8615 udev; 8616 udev = __netdev_next_upper_dev(dev, &iter, &ignore)) { 8617 if (ignore) 8618 continue; 8619 if (max_depth < udev->upper_level) 8620 max_depth = udev->upper_level; 8621 } 8622 8623 return max_depth; 8624 } 8625 8626 static u8 __netdev_lower_depth(struct net_device *dev) 8627 { 8628 struct net_device *ldev; 8629 struct list_head *iter; 8630 u8 max_depth = 0; 8631 bool ignore; 8632 8633 for (iter = &dev->adj_list.lower, 8634 ldev = __netdev_next_lower_dev(dev, &iter, &ignore); 8635 ldev; 8636 ldev = __netdev_next_lower_dev(dev, &iter, &ignore)) { 8637 if (ignore) 8638 continue; 8639 if (max_depth < ldev->lower_level) 8640 max_depth = ldev->lower_level; 8641 } 8642 8643 return max_depth; 8644 } 8645 8646 static int __netdev_update_upper_level(struct net_device *dev, 8647 struct netdev_nested_priv *__unused) 8648 { 8649 dev->upper_level = __netdev_upper_depth(dev) + 1; 8650 return 0; 8651 } 8652 8653 #ifdef CONFIG_LOCKDEP 8654 static LIST_HEAD(net_unlink_list); 8655 8656 static void net_unlink_todo(struct net_device *dev) 8657 { 8658 if (list_empty(&dev->unlink_list)) 8659 list_add_tail(&dev->unlink_list, &net_unlink_list); 8660 } 8661 #endif 8662 8663 static int __netdev_update_lower_level(struct net_device *dev, 8664 struct netdev_nested_priv *priv) 8665 { 8666 dev->lower_level = __netdev_lower_depth(dev) + 1; 8667 8668 #ifdef CONFIG_LOCKDEP 8669 if (!priv) 8670 return 0; 8671 8672 if (priv->flags & NESTED_SYNC_IMM) 8673 dev->nested_level = dev->lower_level - 1; 8674 if (priv->flags & NESTED_SYNC_TODO) 8675 net_unlink_todo(dev); 8676 #endif 8677 return 0; 8678 } 8679 8680 int netdev_walk_all_lower_dev_rcu(struct net_device *dev, 8681 int (*fn)(struct net_device *dev, 8682 struct netdev_nested_priv *priv), 8683 struct netdev_nested_priv *priv) 8684 { 8685 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1]; 8686 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1]; 8687 int ret, cur = 0; 8688 8689 now = dev; 8690 iter = &dev->adj_list.lower; 8691 8692 while (1) { 8693 if (now != dev) { 8694 ret = fn(now, priv); 8695 if (ret) 8696 return ret; 8697 } 8698 8699 next = NULL; 8700 while (1) { 8701 ldev = netdev_next_lower_dev_rcu(now, &iter); 8702 if (!ldev) 8703 break; 8704 8705 next = ldev; 8706 niter = &ldev->adj_list.lower; 8707 dev_stack[cur] = now; 8708 iter_stack[cur++] = iter; 8709 break; 8710 } 8711 8712 if (!next) { 8713 if (!cur) 8714 return 0; 8715 next = dev_stack[--cur]; 8716 niter = iter_stack[cur]; 8717 } 8718 8719 now = next; 8720 iter = niter; 8721 } 8722 8723 return 0; 8724 } 8725 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu); 8726 8727 /** 8728 * netdev_lower_get_first_private_rcu - Get the first ->private from the 8729 * lower neighbour list, RCU 8730 * variant 8731 * @dev: device 8732 * 8733 * Gets the first netdev_adjacent->private from the dev's lower neighbour 8734 * list. The caller must hold RCU read lock. 8735 */ 8736 void *netdev_lower_get_first_private_rcu(struct net_device *dev) 8737 { 8738 struct netdev_adjacent *lower; 8739 8740 lower = list_first_or_null_rcu(&dev->adj_list.lower, 8741 struct netdev_adjacent, list); 8742 if (lower) 8743 return lower->private; 8744 return NULL; 8745 } 8746 EXPORT_SYMBOL(netdev_lower_get_first_private_rcu); 8747 8748 /** 8749 * netdev_master_upper_dev_get_rcu - Get master upper device 8750 * @dev: device 8751 * 8752 * Find a master upper device and return pointer to it or NULL in case 8753 * it's not there. The caller must hold the RCU read lock. 8754 */ 8755 struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev) 8756 { 8757 struct netdev_adjacent *upper; 8758 8759 upper = list_first_or_null_rcu(&dev->adj_list.upper, 8760 struct netdev_adjacent, list); 8761 if (upper && likely(upper->master)) 8762 return upper->dev; 8763 return NULL; 8764 } 8765 EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu); 8766 8767 static int netdev_adjacent_sysfs_add(struct net_device *dev, 8768 struct net_device *adj_dev, 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", adj_dev->name); 8775 return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj), 8776 linkname); 8777 } 8778 static void netdev_adjacent_sysfs_del(struct net_device *dev, 8779 char *name, 8780 struct list_head *dev_list) 8781 { 8782 char linkname[IFNAMSIZ+7]; 8783 8784 sprintf(linkname, dev_list == &dev->adj_list.upper ? 8785 "upper_%s" : "lower_%s", name); 8786 sysfs_remove_link(&(dev->dev.kobj), linkname); 8787 } 8788 8789 static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev, 8790 struct net_device *adj_dev, 8791 struct list_head *dev_list) 8792 { 8793 return (dev_list == &dev->adj_list.upper || 8794 dev_list == &dev->adj_list.lower) && 8795 net_eq(dev_net(dev), dev_net(adj_dev)); 8796 } 8797 8798 static int __netdev_adjacent_dev_insert(struct net_device *dev, 8799 struct net_device *adj_dev, 8800 struct list_head *dev_list, 8801 void *private, bool master) 8802 { 8803 struct netdev_adjacent *adj; 8804 int ret; 8805 8806 adj = __netdev_find_adj(adj_dev, dev_list); 8807 8808 if (adj) { 8809 adj->ref_nr += 1; 8810 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n", 8811 dev->name, adj_dev->name, adj->ref_nr); 8812 8813 return 0; 8814 } 8815 8816 adj = kmalloc_obj(*adj); 8817 if (!adj) 8818 return -ENOMEM; 8819 8820 adj->dev = adj_dev; 8821 adj->master = master; 8822 adj->ref_nr = 1; 8823 adj->private = private; 8824 adj->ignore = false; 8825 netdev_hold(adj_dev, &adj->dev_tracker, GFP_KERNEL); 8826 8827 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n", 8828 dev->name, adj_dev->name, adj->ref_nr, adj_dev->name); 8829 8830 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) { 8831 ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list); 8832 if (ret) 8833 goto free_adj; 8834 } 8835 8836 /* Ensure that master link is always the first item in list. */ 8837 if (master) { 8838 ret = sysfs_create_link(&(dev->dev.kobj), 8839 &(adj_dev->dev.kobj), "master"); 8840 if (ret) 8841 goto remove_symlinks; 8842 8843 list_add_rcu(&adj->list, dev_list); 8844 } else { 8845 list_add_tail_rcu(&adj->list, dev_list); 8846 } 8847 8848 return 0; 8849 8850 remove_symlinks: 8851 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) 8852 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list); 8853 free_adj: 8854 netdev_put(adj_dev, &adj->dev_tracker); 8855 kfree(adj); 8856 8857 return ret; 8858 } 8859 8860 static void __netdev_adjacent_dev_remove(struct net_device *dev, 8861 struct net_device *adj_dev, 8862 u16 ref_nr, 8863 struct list_head *dev_list) 8864 { 8865 struct netdev_adjacent *adj; 8866 8867 pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n", 8868 dev->name, adj_dev->name, ref_nr); 8869 8870 adj = __netdev_find_adj(adj_dev, dev_list); 8871 8872 if (!adj) { 8873 pr_err("Adjacency does not exist for device %s from %s\n", 8874 dev->name, adj_dev->name); 8875 WARN_ON(1); 8876 return; 8877 } 8878 8879 if (adj->ref_nr > ref_nr) { 8880 pr_debug("adjacency: %s to %s ref_nr - %d = %d\n", 8881 dev->name, adj_dev->name, ref_nr, 8882 adj->ref_nr - ref_nr); 8883 adj->ref_nr -= ref_nr; 8884 return; 8885 } 8886 8887 if (adj->master) 8888 sysfs_remove_link(&(dev->dev.kobj), "master"); 8889 8890 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) 8891 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list); 8892 8893 list_del_rcu(&adj->list); 8894 pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n", 8895 adj_dev->name, dev->name, adj_dev->name); 8896 netdev_put(adj_dev, &adj->dev_tracker); 8897 kfree_rcu(adj, rcu); 8898 } 8899 8900 static int __netdev_adjacent_dev_link_lists(struct net_device *dev, 8901 struct net_device *upper_dev, 8902 struct list_head *up_list, 8903 struct list_head *down_list, 8904 void *private, bool master) 8905 { 8906 int ret; 8907 8908 ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list, 8909 private, master); 8910 if (ret) 8911 return ret; 8912 8913 ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list, 8914 private, false); 8915 if (ret) { 8916 __netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list); 8917 return ret; 8918 } 8919 8920 return 0; 8921 } 8922 8923 static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev, 8924 struct net_device *upper_dev, 8925 u16 ref_nr, 8926 struct list_head *up_list, 8927 struct list_head *down_list) 8928 { 8929 __netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list); 8930 __netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list); 8931 } 8932 8933 static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev, 8934 struct net_device *upper_dev, 8935 void *private, bool master) 8936 { 8937 return __netdev_adjacent_dev_link_lists(dev, upper_dev, 8938 &dev->adj_list.upper, 8939 &upper_dev->adj_list.lower, 8940 private, master); 8941 } 8942 8943 static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev, 8944 struct net_device *upper_dev) 8945 { 8946 __netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1, 8947 &dev->adj_list.upper, 8948 &upper_dev->adj_list.lower); 8949 } 8950 8951 static int __netdev_upper_dev_link(struct net_device *dev, 8952 struct net_device *upper_dev, bool master, 8953 void *upper_priv, void *upper_info, 8954 struct netdev_nested_priv *priv, 8955 struct netlink_ext_ack *extack) 8956 { 8957 struct netdev_notifier_changeupper_info changeupper_info = { 8958 .info = { 8959 .dev = dev, 8960 .extack = extack, 8961 }, 8962 .upper_dev = upper_dev, 8963 .master = master, 8964 .linking = true, 8965 .upper_info = upper_info, 8966 }; 8967 struct net_device *master_dev; 8968 int ret = 0; 8969 8970 ASSERT_RTNL(); 8971 8972 if (dev == upper_dev) 8973 return -EBUSY; 8974 8975 /* To prevent loops, check if dev is not upper device to upper_dev. */ 8976 if (__netdev_has_upper_dev(upper_dev, dev)) 8977 return -EBUSY; 8978 8979 if ((dev->lower_level + upper_dev->upper_level) > MAX_NEST_DEV) 8980 return -EMLINK; 8981 8982 if (!master) { 8983 if (__netdev_has_upper_dev(dev, upper_dev)) 8984 return -EEXIST; 8985 } else { 8986 master_dev = __netdev_master_upper_dev_get(dev); 8987 if (master_dev) 8988 return master_dev == upper_dev ? -EEXIST : -EBUSY; 8989 } 8990 8991 ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER, 8992 &changeupper_info.info); 8993 ret = notifier_to_errno(ret); 8994 if (ret) 8995 return ret; 8996 8997 ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv, 8998 master); 8999 if (ret) 9000 return ret; 9001 9002 ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER, 9003 &changeupper_info.info); 9004 ret = notifier_to_errno(ret); 9005 if (ret) 9006 goto rollback; 9007 9008 __netdev_update_upper_level(dev, NULL); 9009 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL); 9010 9011 __netdev_update_lower_level(upper_dev, priv); 9012 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level, 9013 priv); 9014 9015 return 0; 9016 9017 rollback: 9018 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev); 9019 9020 return ret; 9021 } 9022 9023 /** 9024 * netdev_upper_dev_link - Add a link to the upper device 9025 * @dev: device 9026 * @upper_dev: new upper device 9027 * @extack: netlink extended ack 9028 * 9029 * Adds a link to device which is upper to this one. The caller must hold 9030 * the RTNL lock. On a failure a negative errno code is returned. 9031 * On success the reference counts are adjusted and the function 9032 * returns zero. 9033 */ 9034 int netdev_upper_dev_link(struct net_device *dev, 9035 struct net_device *upper_dev, 9036 struct netlink_ext_ack *extack) 9037 { 9038 struct netdev_nested_priv priv = { 9039 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO, 9040 .data = NULL, 9041 }; 9042 9043 return __netdev_upper_dev_link(dev, upper_dev, false, 9044 NULL, NULL, &priv, extack); 9045 } 9046 EXPORT_SYMBOL(netdev_upper_dev_link); 9047 9048 /** 9049 * netdev_master_upper_dev_link - Add a master link to the upper device 9050 * @dev: device 9051 * @upper_dev: new upper device 9052 * @upper_priv: upper device private 9053 * @upper_info: upper info to be passed down via notifier 9054 * @extack: netlink extended ack 9055 * 9056 * Adds a link to device which is upper to this one. In this case, only 9057 * one master upper device can be linked, although other non-master devices 9058 * might be linked as well. The caller must hold the RTNL lock. 9059 * On a failure a negative errno code is returned. On success the reference 9060 * counts are adjusted and the function returns zero. 9061 */ 9062 int netdev_master_upper_dev_link(struct net_device *dev, 9063 struct net_device *upper_dev, 9064 void *upper_priv, void *upper_info, 9065 struct netlink_ext_ack *extack) 9066 { 9067 struct netdev_nested_priv priv = { 9068 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO, 9069 .data = NULL, 9070 }; 9071 9072 return __netdev_upper_dev_link(dev, upper_dev, true, 9073 upper_priv, upper_info, &priv, extack); 9074 } 9075 EXPORT_SYMBOL(netdev_master_upper_dev_link); 9076 9077 static void __netdev_upper_dev_unlink(struct net_device *dev, 9078 struct net_device *upper_dev, 9079 struct netdev_nested_priv *priv) 9080 { 9081 struct netdev_notifier_changeupper_info changeupper_info = { 9082 .info = { 9083 .dev = dev, 9084 }, 9085 .upper_dev = upper_dev, 9086 .linking = false, 9087 }; 9088 9089 ASSERT_RTNL(); 9090 9091 changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev; 9092 9093 call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER, 9094 &changeupper_info.info); 9095 9096 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev); 9097 9098 call_netdevice_notifiers_info(NETDEV_CHANGEUPPER, 9099 &changeupper_info.info); 9100 9101 __netdev_update_upper_level(dev, NULL); 9102 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL); 9103 9104 __netdev_update_lower_level(upper_dev, priv); 9105 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level, 9106 priv); 9107 } 9108 9109 /** 9110 * netdev_upper_dev_unlink - Removes a link to upper device 9111 * @dev: device 9112 * @upper_dev: new upper device 9113 * 9114 * Removes a link to device which is upper to this one. The caller must hold 9115 * the RTNL lock. 9116 */ 9117 void netdev_upper_dev_unlink(struct net_device *dev, 9118 struct net_device *upper_dev) 9119 { 9120 struct netdev_nested_priv priv = { 9121 .flags = NESTED_SYNC_TODO, 9122 .data = NULL, 9123 }; 9124 9125 __netdev_upper_dev_unlink(dev, upper_dev, &priv); 9126 } 9127 EXPORT_SYMBOL(netdev_upper_dev_unlink); 9128 9129 static void __netdev_adjacent_dev_set(struct net_device *upper_dev, 9130 struct net_device *lower_dev, 9131 bool val) 9132 { 9133 struct netdev_adjacent *adj; 9134 9135 adj = __netdev_find_adj(lower_dev, &upper_dev->adj_list.lower); 9136 if (adj) 9137 adj->ignore = val; 9138 9139 adj = __netdev_find_adj(upper_dev, &lower_dev->adj_list.upper); 9140 if (adj) 9141 adj->ignore = val; 9142 } 9143 9144 static void netdev_adjacent_dev_disable(struct net_device *upper_dev, 9145 struct net_device *lower_dev) 9146 { 9147 __netdev_adjacent_dev_set(upper_dev, lower_dev, true); 9148 } 9149 9150 static void netdev_adjacent_dev_enable(struct net_device *upper_dev, 9151 struct net_device *lower_dev) 9152 { 9153 __netdev_adjacent_dev_set(upper_dev, lower_dev, false); 9154 } 9155 9156 int netdev_adjacent_change_prepare(struct net_device *old_dev, 9157 struct net_device *new_dev, 9158 struct net_device *dev, 9159 struct netlink_ext_ack *extack) 9160 { 9161 struct netdev_nested_priv priv = { 9162 .flags = 0, 9163 .data = NULL, 9164 }; 9165 int err; 9166 9167 if (!new_dev) 9168 return 0; 9169 9170 if (old_dev && new_dev != old_dev) 9171 netdev_adjacent_dev_disable(dev, old_dev); 9172 err = __netdev_upper_dev_link(new_dev, dev, false, NULL, NULL, &priv, 9173 extack); 9174 if (err) { 9175 if (old_dev && new_dev != old_dev) 9176 netdev_adjacent_dev_enable(dev, old_dev); 9177 return err; 9178 } 9179 9180 return 0; 9181 } 9182 EXPORT_SYMBOL(netdev_adjacent_change_prepare); 9183 9184 void netdev_adjacent_change_commit(struct net_device *old_dev, 9185 struct net_device *new_dev, 9186 struct net_device *dev) 9187 { 9188 struct netdev_nested_priv priv = { 9189 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO, 9190 .data = NULL, 9191 }; 9192 9193 if (!new_dev || !old_dev) 9194 return; 9195 9196 if (new_dev == old_dev) 9197 return; 9198 9199 netdev_adjacent_dev_enable(dev, old_dev); 9200 __netdev_upper_dev_unlink(old_dev, dev, &priv); 9201 } 9202 EXPORT_SYMBOL(netdev_adjacent_change_commit); 9203 9204 void netdev_adjacent_change_abort(struct net_device *old_dev, 9205 struct net_device *new_dev, 9206 struct net_device *dev) 9207 { 9208 struct netdev_nested_priv priv = { 9209 .flags = 0, 9210 .data = NULL, 9211 }; 9212 9213 if (!new_dev) 9214 return; 9215 9216 if (old_dev && new_dev != old_dev) 9217 netdev_adjacent_dev_enable(dev, old_dev); 9218 9219 __netdev_upper_dev_unlink(new_dev, dev, &priv); 9220 } 9221 EXPORT_SYMBOL(netdev_adjacent_change_abort); 9222 9223 /** 9224 * netdev_bonding_info_change - Dispatch event about slave change 9225 * @dev: device 9226 * @bonding_info: info to dispatch 9227 * 9228 * Send NETDEV_BONDING_INFO to netdev notifiers with info. 9229 * The caller must hold the RTNL lock. 9230 */ 9231 void netdev_bonding_info_change(struct net_device *dev, 9232 struct netdev_bonding_info *bonding_info) 9233 { 9234 struct netdev_notifier_bonding_info info = { 9235 .info.dev = dev, 9236 }; 9237 9238 memcpy(&info.bonding_info, bonding_info, 9239 sizeof(struct netdev_bonding_info)); 9240 call_netdevice_notifiers_info(NETDEV_BONDING_INFO, 9241 &info.info); 9242 } 9243 EXPORT_SYMBOL(netdev_bonding_info_change); 9244 9245 static int netdev_offload_xstats_enable_l3(struct net_device *dev, 9246 struct netlink_ext_ack *extack) 9247 { 9248 struct netdev_notifier_offload_xstats_info info = { 9249 .info.dev = dev, 9250 .info.extack = extack, 9251 .type = NETDEV_OFFLOAD_XSTATS_TYPE_L3, 9252 }; 9253 int err; 9254 int rc; 9255 9256 dev->offload_xstats_l3 = kzalloc_obj(*dev->offload_xstats_l3); 9257 if (!dev->offload_xstats_l3) 9258 return -ENOMEM; 9259 9260 rc = call_netdevice_notifiers_info_robust(NETDEV_OFFLOAD_XSTATS_ENABLE, 9261 NETDEV_OFFLOAD_XSTATS_DISABLE, 9262 &info.info); 9263 err = notifier_to_errno(rc); 9264 if (err) 9265 goto free_stats; 9266 9267 return 0; 9268 9269 free_stats: 9270 kfree(dev->offload_xstats_l3); 9271 dev->offload_xstats_l3 = NULL; 9272 return err; 9273 } 9274 9275 int netdev_offload_xstats_enable(struct net_device *dev, 9276 enum netdev_offload_xstats_type type, 9277 struct netlink_ext_ack *extack) 9278 { 9279 ASSERT_RTNL(); 9280 9281 if (netdev_offload_xstats_enabled(dev, type)) 9282 return -EALREADY; 9283 9284 switch (type) { 9285 case NETDEV_OFFLOAD_XSTATS_TYPE_L3: 9286 return netdev_offload_xstats_enable_l3(dev, extack); 9287 } 9288 9289 WARN_ON(1); 9290 return -EINVAL; 9291 } 9292 EXPORT_SYMBOL(netdev_offload_xstats_enable); 9293 9294 static void netdev_offload_xstats_disable_l3(struct net_device *dev) 9295 { 9296 struct netdev_notifier_offload_xstats_info info = { 9297 .info.dev = dev, 9298 .type = NETDEV_OFFLOAD_XSTATS_TYPE_L3, 9299 }; 9300 9301 call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_DISABLE, 9302 &info.info); 9303 kfree(dev->offload_xstats_l3); 9304 dev->offload_xstats_l3 = NULL; 9305 } 9306 9307 int netdev_offload_xstats_disable(struct net_device *dev, 9308 enum netdev_offload_xstats_type type) 9309 { 9310 ASSERT_RTNL(); 9311 9312 if (!netdev_offload_xstats_enabled(dev, type)) 9313 return -EALREADY; 9314 9315 switch (type) { 9316 case NETDEV_OFFLOAD_XSTATS_TYPE_L3: 9317 netdev_offload_xstats_disable_l3(dev); 9318 return 0; 9319 } 9320 9321 WARN_ON(1); 9322 return -EINVAL; 9323 } 9324 EXPORT_SYMBOL(netdev_offload_xstats_disable); 9325 9326 static void netdev_offload_xstats_disable_all(struct net_device *dev) 9327 { 9328 netdev_offload_xstats_disable(dev, NETDEV_OFFLOAD_XSTATS_TYPE_L3); 9329 } 9330 9331 static struct rtnl_hw_stats64 * 9332 netdev_offload_xstats_get_ptr(const struct net_device *dev, 9333 enum netdev_offload_xstats_type type) 9334 { 9335 switch (type) { 9336 case NETDEV_OFFLOAD_XSTATS_TYPE_L3: 9337 return dev->offload_xstats_l3; 9338 } 9339 9340 WARN_ON(1); 9341 return NULL; 9342 } 9343 9344 bool netdev_offload_xstats_enabled(const struct net_device *dev, 9345 enum netdev_offload_xstats_type type) 9346 { 9347 ASSERT_RTNL(); 9348 9349 return netdev_offload_xstats_get_ptr(dev, type); 9350 } 9351 EXPORT_SYMBOL(netdev_offload_xstats_enabled); 9352 9353 struct netdev_notifier_offload_xstats_ru { 9354 bool used; 9355 }; 9356 9357 struct netdev_notifier_offload_xstats_rd { 9358 struct rtnl_hw_stats64 stats; 9359 bool used; 9360 }; 9361 9362 static void netdev_hw_stats64_add(struct rtnl_hw_stats64 *dest, 9363 const struct rtnl_hw_stats64 *src) 9364 { 9365 dest->rx_packets += src->rx_packets; 9366 dest->tx_packets += src->tx_packets; 9367 dest->rx_bytes += src->rx_bytes; 9368 dest->tx_bytes += src->tx_bytes; 9369 dest->rx_errors += src->rx_errors; 9370 dest->tx_errors += src->tx_errors; 9371 dest->rx_dropped += src->rx_dropped; 9372 dest->tx_dropped += src->tx_dropped; 9373 dest->multicast += src->multicast; 9374 } 9375 9376 static int netdev_offload_xstats_get_used(struct net_device *dev, 9377 enum netdev_offload_xstats_type type, 9378 bool *p_used, 9379 struct netlink_ext_ack *extack) 9380 { 9381 struct netdev_notifier_offload_xstats_ru report_used = {}; 9382 struct netdev_notifier_offload_xstats_info info = { 9383 .info.dev = dev, 9384 .info.extack = extack, 9385 .type = type, 9386 .report_used = &report_used, 9387 }; 9388 int rc; 9389 9390 WARN_ON(!netdev_offload_xstats_enabled(dev, type)); 9391 rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_USED, 9392 &info.info); 9393 *p_used = report_used.used; 9394 return notifier_to_errno(rc); 9395 } 9396 9397 static int netdev_offload_xstats_get_stats(struct net_device *dev, 9398 enum netdev_offload_xstats_type type, 9399 struct rtnl_hw_stats64 *p_stats, 9400 bool *p_used, 9401 struct netlink_ext_ack *extack) 9402 { 9403 struct netdev_notifier_offload_xstats_rd report_delta = {}; 9404 struct netdev_notifier_offload_xstats_info info = { 9405 .info.dev = dev, 9406 .info.extack = extack, 9407 .type = type, 9408 .report_delta = &report_delta, 9409 }; 9410 struct rtnl_hw_stats64 *stats; 9411 int rc; 9412 9413 stats = netdev_offload_xstats_get_ptr(dev, type); 9414 if (WARN_ON(!stats)) 9415 return -EINVAL; 9416 9417 rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_DELTA, 9418 &info.info); 9419 9420 /* Cache whatever we got, even if there was an error, otherwise the 9421 * successful stats retrievals would get lost. 9422 */ 9423 netdev_hw_stats64_add(stats, &report_delta.stats); 9424 9425 if (p_stats) 9426 *p_stats = *stats; 9427 *p_used = report_delta.used; 9428 9429 return notifier_to_errno(rc); 9430 } 9431 9432 int netdev_offload_xstats_get(struct net_device *dev, 9433 enum netdev_offload_xstats_type type, 9434 struct rtnl_hw_stats64 *p_stats, bool *p_used, 9435 struct netlink_ext_ack *extack) 9436 { 9437 ASSERT_RTNL(); 9438 9439 if (p_stats) 9440 return netdev_offload_xstats_get_stats(dev, type, p_stats, 9441 p_used, extack); 9442 else 9443 return netdev_offload_xstats_get_used(dev, type, p_used, 9444 extack); 9445 } 9446 EXPORT_SYMBOL(netdev_offload_xstats_get); 9447 9448 void 9449 netdev_offload_xstats_report_delta(struct netdev_notifier_offload_xstats_rd *report_delta, 9450 const struct rtnl_hw_stats64 *stats) 9451 { 9452 report_delta->used = true; 9453 netdev_hw_stats64_add(&report_delta->stats, stats); 9454 } 9455 EXPORT_SYMBOL(netdev_offload_xstats_report_delta); 9456 9457 void 9458 netdev_offload_xstats_report_used(struct netdev_notifier_offload_xstats_ru *report_used) 9459 { 9460 report_used->used = true; 9461 } 9462 EXPORT_SYMBOL(netdev_offload_xstats_report_used); 9463 9464 void netdev_offload_xstats_push_delta(struct net_device *dev, 9465 enum netdev_offload_xstats_type type, 9466 const struct rtnl_hw_stats64 *p_stats) 9467 { 9468 struct rtnl_hw_stats64 *stats; 9469 9470 ASSERT_RTNL(); 9471 9472 stats = netdev_offload_xstats_get_ptr(dev, type); 9473 if (WARN_ON(!stats)) 9474 return; 9475 9476 netdev_hw_stats64_add(stats, p_stats); 9477 } 9478 EXPORT_SYMBOL(netdev_offload_xstats_push_delta); 9479 9480 /** 9481 * netdev_get_xmit_slave - Get the xmit slave of master device 9482 * @dev: device 9483 * @skb: The packet 9484 * @all_slaves: assume all the slaves are active 9485 * 9486 * The reference counters are not incremented so the caller must be 9487 * careful with locks. The caller must hold RCU lock. 9488 * %NULL is returned if no slave is found. 9489 */ 9490 9491 struct net_device *netdev_get_xmit_slave(struct net_device *dev, 9492 struct sk_buff *skb, 9493 bool all_slaves) 9494 { 9495 const struct net_device_ops *ops = dev->netdev_ops; 9496 9497 if (!ops->ndo_get_xmit_slave) 9498 return NULL; 9499 return ops->ndo_get_xmit_slave(dev, skb, all_slaves); 9500 } 9501 EXPORT_SYMBOL(netdev_get_xmit_slave); 9502 9503 static struct net_device *netdev_sk_get_lower_dev(struct net_device *dev, 9504 struct sock *sk) 9505 { 9506 const struct net_device_ops *ops = dev->netdev_ops; 9507 9508 if (!ops->ndo_sk_get_lower_dev) 9509 return NULL; 9510 return ops->ndo_sk_get_lower_dev(dev, sk); 9511 } 9512 9513 /** 9514 * netdev_sk_get_lowest_dev - Get the lowest device in chain given device and socket 9515 * @dev: device 9516 * @sk: the socket 9517 * 9518 * %NULL is returned if no lower device is found. 9519 */ 9520 9521 struct net_device *netdev_sk_get_lowest_dev(struct net_device *dev, 9522 struct sock *sk) 9523 { 9524 struct net_device *lower; 9525 9526 lower = netdev_sk_get_lower_dev(dev, sk); 9527 while (lower) { 9528 dev = lower; 9529 lower = netdev_sk_get_lower_dev(dev, sk); 9530 } 9531 9532 return dev; 9533 } 9534 EXPORT_SYMBOL(netdev_sk_get_lowest_dev); 9535 9536 static void netdev_adjacent_add_links(struct net_device *dev) 9537 { 9538 struct netdev_adjacent *iter; 9539 9540 struct net *net = dev_net(dev); 9541 9542 list_for_each_entry(iter, &dev->adj_list.upper, list) { 9543 if (!net_eq(net, dev_net(iter->dev))) 9544 continue; 9545 netdev_adjacent_sysfs_add(iter->dev, dev, 9546 &iter->dev->adj_list.lower); 9547 netdev_adjacent_sysfs_add(dev, iter->dev, 9548 &dev->adj_list.upper); 9549 } 9550 9551 list_for_each_entry(iter, &dev->adj_list.lower, list) { 9552 if (!net_eq(net, dev_net(iter->dev))) 9553 continue; 9554 netdev_adjacent_sysfs_add(iter->dev, dev, 9555 &iter->dev->adj_list.upper); 9556 netdev_adjacent_sysfs_add(dev, iter->dev, 9557 &dev->adj_list.lower); 9558 } 9559 } 9560 9561 static void netdev_adjacent_del_links(struct net_device *dev) 9562 { 9563 struct netdev_adjacent *iter; 9564 9565 struct net *net = dev_net(dev); 9566 9567 list_for_each_entry(iter, &dev->adj_list.upper, list) { 9568 if (!net_eq(net, dev_net(iter->dev))) 9569 continue; 9570 netdev_adjacent_sysfs_del(iter->dev, dev->name, 9571 &iter->dev->adj_list.lower); 9572 netdev_adjacent_sysfs_del(dev, iter->dev->name, 9573 &dev->adj_list.upper); 9574 } 9575 9576 list_for_each_entry(iter, &dev->adj_list.lower, list) { 9577 if (!net_eq(net, dev_net(iter->dev))) 9578 continue; 9579 netdev_adjacent_sysfs_del(iter->dev, dev->name, 9580 &iter->dev->adj_list.upper); 9581 netdev_adjacent_sysfs_del(dev, iter->dev->name, 9582 &dev->adj_list.lower); 9583 } 9584 } 9585 9586 void netdev_adjacent_rename_links(struct net_device *dev, char *oldname) 9587 { 9588 struct netdev_adjacent *iter; 9589 9590 struct net *net = dev_net(dev); 9591 9592 list_for_each_entry(iter, &dev->adj_list.upper, list) { 9593 if (!net_eq(net, dev_net(iter->dev))) 9594 continue; 9595 netdev_adjacent_sysfs_del(iter->dev, oldname, 9596 &iter->dev->adj_list.lower); 9597 netdev_adjacent_sysfs_add(iter->dev, dev, 9598 &iter->dev->adj_list.lower); 9599 } 9600 9601 list_for_each_entry(iter, &dev->adj_list.lower, list) { 9602 if (!net_eq(net, dev_net(iter->dev))) 9603 continue; 9604 netdev_adjacent_sysfs_del(iter->dev, oldname, 9605 &iter->dev->adj_list.upper); 9606 netdev_adjacent_sysfs_add(iter->dev, dev, 9607 &iter->dev->adj_list.upper); 9608 } 9609 } 9610 9611 void *netdev_lower_dev_get_private(struct net_device *dev, 9612 struct net_device *lower_dev) 9613 { 9614 struct netdev_adjacent *lower; 9615 9616 if (!lower_dev) 9617 return NULL; 9618 lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower); 9619 if (!lower) 9620 return NULL; 9621 9622 return lower->private; 9623 } 9624 EXPORT_SYMBOL(netdev_lower_dev_get_private); 9625 9626 9627 /** 9628 * netdev_lower_state_changed - Dispatch event about lower device state change 9629 * @lower_dev: device 9630 * @lower_state_info: state to dispatch 9631 * 9632 * Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info. 9633 * The caller must hold the RTNL lock. 9634 */ 9635 void netdev_lower_state_changed(struct net_device *lower_dev, 9636 void *lower_state_info) 9637 { 9638 struct netdev_notifier_changelowerstate_info changelowerstate_info = { 9639 .info.dev = lower_dev, 9640 }; 9641 9642 ASSERT_RTNL(); 9643 changelowerstate_info.lower_state_info = lower_state_info; 9644 call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE, 9645 &changelowerstate_info.info); 9646 } 9647 EXPORT_SYMBOL(netdev_lower_state_changed); 9648 9649 static void dev_change_rx_flags(struct net_device *dev, int flags) 9650 { 9651 const struct net_device_ops *ops = dev->netdev_ops; 9652 9653 if (ops->ndo_change_rx_flags) 9654 ops->ndo_change_rx_flags(dev, flags); 9655 } 9656 9657 int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify) 9658 { 9659 unsigned int old_flags = dev->flags; 9660 unsigned int promiscuity, flags; 9661 kuid_t uid; 9662 kgid_t gid; 9663 9664 netdev_assert_locked_ops_compat(dev); 9665 9666 promiscuity = dev->promiscuity + inc; 9667 if (promiscuity == 0) { 9668 /* 9669 * Avoid overflow. 9670 * If inc causes overflow, untouch promisc and return error. 9671 */ 9672 if (unlikely(inc > 0)) { 9673 netdev_warn(dev, "promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n"); 9674 return -EOVERFLOW; 9675 } 9676 flags = old_flags & ~IFF_PROMISC; 9677 } else { 9678 flags = old_flags | IFF_PROMISC; 9679 } 9680 WRITE_ONCE(dev->promiscuity, promiscuity); 9681 if (flags != old_flags) { 9682 WRITE_ONCE(dev->flags, flags); 9683 netdev_info(dev, "%s promiscuous mode\n", 9684 dev->flags & IFF_PROMISC ? "entered" : "left"); 9685 if (audit_enabled) { 9686 current_uid_gid(&uid, &gid); 9687 audit_log(audit_context(), GFP_ATOMIC, 9688 AUDIT_ANOM_PROMISCUOUS, 9689 "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u", 9690 dev->name, (dev->flags & IFF_PROMISC), 9691 (old_flags & IFF_PROMISC), 9692 from_kuid(&init_user_ns, audit_get_loginuid(current)), 9693 from_kuid(&init_user_ns, uid), 9694 from_kgid(&init_user_ns, gid), 9695 audit_get_sessionid(current)); 9696 } 9697 9698 dev_change_rx_flags(dev, IFF_PROMISC); 9699 } 9700 if (notify) 9701 __dev_notify_flags(dev, old_flags, IFF_PROMISC, 0, NULL); 9702 return 0; 9703 } 9704 9705 int netif_set_promiscuity(struct net_device *dev, int inc) 9706 { 9707 unsigned int old_flags = dev->flags; 9708 int err; 9709 9710 err = __dev_set_promiscuity(dev, inc, true); 9711 if (err < 0) 9712 return err; 9713 if (dev->flags != old_flags) 9714 dev_set_rx_mode(dev); 9715 return err; 9716 } 9717 9718 int netif_set_allmulti(struct net_device *dev, int inc, bool notify) 9719 { 9720 unsigned int old_flags = dev->flags, old_gflags = dev->gflags; 9721 unsigned int allmulti, flags; 9722 9723 netdev_assert_locked_ops_compat(dev); 9724 9725 allmulti = dev->allmulti + inc; 9726 if (allmulti == 0) { 9727 /* 9728 * Avoid overflow. 9729 * If inc causes overflow, untouch allmulti and return error. 9730 */ 9731 if (unlikely(inc > 0)) { 9732 netdev_warn(dev, "allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n"); 9733 return -EOVERFLOW; 9734 } 9735 flags = old_flags & ~IFF_ALLMULTI; 9736 } else { 9737 flags = old_flags | IFF_ALLMULTI; 9738 } 9739 WRITE_ONCE(dev->allmulti, allmulti); 9740 if (flags != old_flags) { 9741 WRITE_ONCE(dev->flags, flags); 9742 netdev_info(dev, "%s allmulticast mode\n", 9743 dev->flags & IFF_ALLMULTI ? "entered" : "left"); 9744 dev_change_rx_flags(dev, IFF_ALLMULTI); 9745 dev_set_rx_mode(dev); 9746 if (notify) 9747 __dev_notify_flags(dev, old_flags, 9748 dev->gflags ^ old_gflags, 0, NULL); 9749 } 9750 return 0; 9751 } 9752 9753 9754 /** 9755 * netif_get_flags() - get flags reported to userspace 9756 * @dev: device 9757 * 9758 * Get the combination of flag bits exported through APIs to userspace. 9759 */ 9760 unsigned int netif_get_flags(const struct net_device *dev) 9761 { 9762 unsigned int flags; 9763 9764 flags = (READ_ONCE(dev->flags) & ~(IFF_PROMISC | 9765 IFF_ALLMULTI | 9766 IFF_RUNNING | 9767 IFF_LOWER_UP | 9768 IFF_DORMANT)) | 9769 (READ_ONCE(dev->gflags) & (IFF_PROMISC | 9770 IFF_ALLMULTI)); 9771 9772 if (netif_running(dev)) { 9773 if (netif_oper_up(dev)) 9774 flags |= IFF_RUNNING; 9775 if (netif_carrier_ok(dev)) 9776 flags |= IFF_LOWER_UP; 9777 if (netif_dormant(dev)) 9778 flags |= IFF_DORMANT; 9779 } 9780 9781 return flags; 9782 } 9783 EXPORT_SYMBOL(netif_get_flags); 9784 9785 int __dev_change_flags(struct net_device *dev, unsigned int flags, 9786 struct netlink_ext_ack *extack) 9787 { 9788 unsigned int old_flags = dev->flags; 9789 int ret; 9790 9791 netdev_assert_locked_ops_compat(dev); 9792 9793 /* 9794 * Set the flags on our device. 9795 */ 9796 9797 dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP | 9798 IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL | 9799 IFF_AUTOMEDIA)) | 9800 (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC | 9801 IFF_ALLMULTI)); 9802 9803 /* 9804 * Load in the correct multicast list now the flags have changed. 9805 */ 9806 9807 if ((old_flags ^ flags) & IFF_MULTICAST) 9808 dev_change_rx_flags(dev, IFF_MULTICAST); 9809 9810 dev_set_rx_mode(dev); 9811 9812 /* 9813 * Have we downed the interface. We handle IFF_UP ourselves 9814 * according to user attempts to set it, rather than blindly 9815 * setting it. 9816 */ 9817 9818 ret = 0; 9819 if ((old_flags ^ flags) & IFF_UP) { 9820 if (old_flags & IFF_UP) 9821 __dev_close(dev); 9822 else 9823 ret = __dev_open(dev, extack); 9824 } 9825 9826 if ((flags ^ dev->gflags) & IFF_PROMISC) { 9827 int inc = (flags & IFF_PROMISC) ? 1 : -1; 9828 old_flags = dev->flags; 9829 9830 dev->gflags ^= IFF_PROMISC; 9831 9832 if (__dev_set_promiscuity(dev, inc, false) >= 0) 9833 if (dev->flags != old_flags) 9834 dev_set_rx_mode(dev); 9835 } 9836 9837 /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI 9838 * is important. Some (broken) drivers set IFF_PROMISC, when 9839 * IFF_ALLMULTI is requested not asking us and not reporting. 9840 */ 9841 if ((flags ^ dev->gflags) & IFF_ALLMULTI) { 9842 int inc = (flags & IFF_ALLMULTI) ? 1 : -1; 9843 9844 dev->gflags ^= IFF_ALLMULTI; 9845 netif_set_allmulti(dev, inc, false); 9846 } 9847 9848 return ret; 9849 } 9850 9851 void __dev_notify_flags(struct net_device *dev, unsigned int old_flags, 9852 unsigned int gchanges, u32 portid, 9853 const struct nlmsghdr *nlh) 9854 { 9855 unsigned int changes = dev->flags ^ old_flags; 9856 9857 netdev_assert_locked_ops_compat(dev); 9858 9859 if (gchanges) 9860 rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC, portid, nlh); 9861 9862 if (changes & IFF_UP) { 9863 if (dev->flags & IFF_UP) 9864 call_netdevice_notifiers(NETDEV_UP, dev); 9865 else 9866 call_netdevice_notifiers(NETDEV_DOWN, dev); 9867 } 9868 9869 if (dev->flags & IFF_UP && 9870 (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) { 9871 struct netdev_notifier_change_info change_info = { 9872 .info = { 9873 .dev = dev, 9874 }, 9875 .flags_changed = changes, 9876 }; 9877 9878 call_netdevice_notifiers_info(NETDEV_CHANGE, &change_info.info); 9879 } 9880 } 9881 9882 int netif_change_flags(struct net_device *dev, unsigned int flags, 9883 struct netlink_ext_ack *extack) 9884 { 9885 int ret; 9886 unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags; 9887 9888 ret = __dev_change_flags(dev, flags, extack); 9889 if (ret < 0) 9890 return ret; 9891 9892 changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags); 9893 __dev_notify_flags(dev, old_flags, changes, 0, NULL); 9894 return ret; 9895 } 9896 EXPORT_SYMBOL(netif_change_flags); 9897 9898 int __netif_set_mtu(struct net_device *dev, int new_mtu) 9899 { 9900 const struct net_device_ops *ops = dev->netdev_ops; 9901 9902 if (ops->ndo_change_mtu) 9903 return ops->ndo_change_mtu(dev, new_mtu); 9904 9905 /* Pairs with all the lockless reads of dev->mtu in the stack */ 9906 WRITE_ONCE(dev->mtu, new_mtu); 9907 return 0; 9908 } 9909 EXPORT_SYMBOL_NS_GPL(__netif_set_mtu, "NETDEV_INTERNAL"); 9910 9911 int dev_validate_mtu(struct net_device *dev, int new_mtu, 9912 struct netlink_ext_ack *extack) 9913 { 9914 /* MTU must be positive, and in range */ 9915 if (new_mtu < 0 || new_mtu < dev->min_mtu) { 9916 NL_SET_ERR_MSG(extack, "mtu less than device minimum"); 9917 return -EINVAL; 9918 } 9919 9920 if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) { 9921 NL_SET_ERR_MSG(extack, "mtu greater than device maximum"); 9922 return -EINVAL; 9923 } 9924 return 0; 9925 } 9926 9927 /** 9928 * netif_set_mtu_ext() - Change maximum transfer unit 9929 * @dev: device 9930 * @new_mtu: new transfer unit 9931 * @extack: netlink extended ack 9932 * 9933 * Change the maximum transfer size of the network device. 9934 * 9935 * Return: 0 on success, -errno on failure. 9936 */ 9937 int netif_set_mtu_ext(struct net_device *dev, int new_mtu, 9938 struct netlink_ext_ack *extack) 9939 { 9940 int err, orig_mtu; 9941 9942 netdev_assert_locked_ops_compat(dev); 9943 9944 if (new_mtu == dev->mtu) 9945 return 0; 9946 9947 err = dev_validate_mtu(dev, new_mtu, extack); 9948 if (err) 9949 return err; 9950 9951 if (!netif_device_present(dev)) 9952 return -ENODEV; 9953 9954 err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev); 9955 err = notifier_to_errno(err); 9956 if (err) 9957 return err; 9958 9959 orig_mtu = dev->mtu; 9960 err = __netif_set_mtu(dev, new_mtu); 9961 9962 if (!err) { 9963 err = call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev, 9964 orig_mtu); 9965 err = notifier_to_errno(err); 9966 if (err) { 9967 /* setting mtu back and notifying everyone again, 9968 * so that they have a chance to revert changes. 9969 */ 9970 __netif_set_mtu(dev, orig_mtu); 9971 call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev, 9972 new_mtu); 9973 } 9974 } 9975 return err; 9976 } 9977 9978 int netif_set_mtu(struct net_device *dev, int new_mtu) 9979 { 9980 struct netlink_ext_ack extack; 9981 int err; 9982 9983 memset(&extack, 0, sizeof(extack)); 9984 err = netif_set_mtu_ext(dev, new_mtu, &extack); 9985 if (err && extack._msg) 9986 net_err_ratelimited("%s: %s\n", dev->name, extack._msg); 9987 return err; 9988 } 9989 EXPORT_SYMBOL(netif_set_mtu); 9990 9991 int netif_change_tx_queue_len(struct net_device *dev, unsigned long new_len) 9992 { 9993 unsigned int orig_len = dev->tx_queue_len; 9994 int res; 9995 9996 if (new_len > S16_MAX) 9997 return -ERANGE; 9998 9999 if (new_len != orig_len) { 10000 WRITE_ONCE(dev->tx_queue_len, new_len); 10001 res = call_netdevice_notifiers(NETDEV_CHANGE_TX_QUEUE_LEN, dev); 10002 res = notifier_to_errno(res); 10003 if (res) 10004 goto err_rollback; 10005 res = dev_qdisc_change_tx_queue_len(dev); 10006 if (res) 10007 goto err_rollback; 10008 } 10009 10010 return 0; 10011 10012 err_rollback: 10013 netdev_err(dev, "refused to change device tx_queue_len\n"); 10014 WRITE_ONCE(dev->tx_queue_len, orig_len); 10015 return res; 10016 } 10017 10018 void netif_set_group(struct net_device *dev, int new_group) 10019 { 10020 dev->group = new_group; 10021 } 10022 10023 /** 10024 * netif_pre_changeaddr_notify() - Call NETDEV_PRE_CHANGEADDR. 10025 * @dev: device 10026 * @addr: new address 10027 * @extack: netlink extended ack 10028 * 10029 * Return: 0 on success, -errno on failure. 10030 */ 10031 int netif_pre_changeaddr_notify(struct net_device *dev, const char *addr, 10032 struct netlink_ext_ack *extack) 10033 { 10034 struct netdev_notifier_pre_changeaddr_info info = { 10035 .info.dev = dev, 10036 .info.extack = extack, 10037 .dev_addr = addr, 10038 }; 10039 int rc; 10040 10041 rc = call_netdevice_notifiers_info(NETDEV_PRE_CHANGEADDR, &info.info); 10042 return notifier_to_errno(rc); 10043 } 10044 EXPORT_SYMBOL_NS_GPL(netif_pre_changeaddr_notify, "NETDEV_INTERNAL"); 10045 10046 int netif_set_mac_address(struct net_device *dev, struct sockaddr_storage *ss, 10047 struct netlink_ext_ack *extack) 10048 { 10049 const struct net_device_ops *ops = dev->netdev_ops; 10050 int err; 10051 10052 if (!ops->ndo_set_mac_address) 10053 return -EOPNOTSUPP; 10054 if (ss->ss_family != dev->type) 10055 return -EINVAL; 10056 if (!netif_device_present(dev)) 10057 return -ENODEV; 10058 err = netif_pre_changeaddr_notify(dev, ss->__data, extack); 10059 if (err) 10060 return err; 10061 if (memcmp(dev->dev_addr, ss->__data, dev->addr_len)) { 10062 err = ops->ndo_set_mac_address(dev, ss); 10063 if (err) 10064 return err; 10065 } 10066 dev->addr_assign_type = NET_ADDR_SET; 10067 call_netdevice_notifiers(NETDEV_CHANGEADDR, dev); 10068 add_device_randomness(dev->dev_addr, dev->addr_len); 10069 return 0; 10070 } 10071 10072 DECLARE_RWSEM(dev_addr_sem); 10073 10074 /* "sa" is a true struct sockaddr with limited "sa_data" member. */ 10075 int netif_get_mac_address(struct sockaddr *sa, struct net *net, char *dev_name) 10076 { 10077 size_t size = sizeof(sa->sa_data); 10078 struct net_device *dev; 10079 int ret = 0; 10080 10081 down_read(&dev_addr_sem); 10082 rcu_read_lock(); 10083 10084 dev = dev_get_by_name_rcu(net, dev_name); 10085 if (!dev) { 10086 ret = -ENODEV; 10087 goto unlock; 10088 } 10089 if (!dev->addr_len) 10090 memset(sa->sa_data, 0, size); 10091 else 10092 memcpy(sa->sa_data, dev->dev_addr, 10093 min_t(size_t, size, dev->addr_len)); 10094 sa->sa_family = dev->type; 10095 10096 unlock: 10097 rcu_read_unlock(); 10098 up_read(&dev_addr_sem); 10099 return ret; 10100 } 10101 EXPORT_SYMBOL_NS_GPL(netif_get_mac_address, "NETDEV_INTERNAL"); 10102 10103 int netif_change_carrier(struct net_device *dev, bool new_carrier) 10104 { 10105 const struct net_device_ops *ops = dev->netdev_ops; 10106 10107 if (!ops->ndo_change_carrier) 10108 return -EOPNOTSUPP; 10109 if (!netif_device_present(dev)) 10110 return -ENODEV; 10111 return ops->ndo_change_carrier(dev, new_carrier); 10112 } 10113 10114 /** 10115 * dev_get_phys_port_id - Get device physical port ID 10116 * @dev: device 10117 * @ppid: port ID 10118 * 10119 * Get device physical port ID 10120 */ 10121 int dev_get_phys_port_id(struct net_device *dev, 10122 struct netdev_phys_item_id *ppid) 10123 { 10124 const struct net_device_ops *ops = dev->netdev_ops; 10125 10126 if (!ops->ndo_get_phys_port_id) 10127 return -EOPNOTSUPP; 10128 return ops->ndo_get_phys_port_id(dev, ppid); 10129 } 10130 10131 /** 10132 * dev_get_phys_port_name - Get device physical port name 10133 * @dev: device 10134 * @name: port name 10135 * @len: limit of bytes to copy to name 10136 * 10137 * Get device physical port name 10138 */ 10139 int dev_get_phys_port_name(struct net_device *dev, 10140 char *name, size_t len) 10141 { 10142 const struct net_device_ops *ops = dev->netdev_ops; 10143 int err; 10144 10145 if (ops->ndo_get_phys_port_name) { 10146 err = ops->ndo_get_phys_port_name(dev, name, len); 10147 if (err != -EOPNOTSUPP) 10148 return err; 10149 } 10150 return devlink_compat_phys_port_name_get(dev, name, len); 10151 } 10152 10153 /** 10154 * netif_get_port_parent_id() - Get the device's port parent identifier 10155 * @dev: network device 10156 * @ppid: pointer to a storage for the port's parent identifier 10157 * @recurse: allow/disallow recursion to lower devices 10158 * 10159 * Get the devices's port parent identifier. 10160 * 10161 * Return: 0 on success, -errno on failure. 10162 */ 10163 int netif_get_port_parent_id(struct net_device *dev, 10164 struct netdev_phys_item_id *ppid, bool recurse) 10165 { 10166 const struct net_device_ops *ops = dev->netdev_ops; 10167 struct netdev_phys_item_id first = { }; 10168 struct net_device *lower_dev; 10169 struct list_head *iter; 10170 int err; 10171 10172 if (ops->ndo_get_port_parent_id) { 10173 err = ops->ndo_get_port_parent_id(dev, ppid); 10174 if (err != -EOPNOTSUPP) 10175 return err; 10176 } 10177 10178 err = devlink_compat_switch_id_get(dev, ppid); 10179 if (!recurse || err != -EOPNOTSUPP) 10180 return err; 10181 10182 netdev_for_each_lower_dev(dev, lower_dev, iter) { 10183 err = netif_get_port_parent_id(lower_dev, ppid, true); 10184 if (err) 10185 break; 10186 if (!first.id_len) 10187 first = *ppid; 10188 else if (memcmp(&first, ppid, sizeof(*ppid))) 10189 return -EOPNOTSUPP; 10190 } 10191 10192 return err; 10193 } 10194 EXPORT_SYMBOL(netif_get_port_parent_id); 10195 10196 /** 10197 * netdev_port_same_parent_id - Indicate if two network devices have 10198 * the same port parent identifier 10199 * @a: first network device 10200 * @b: second network device 10201 */ 10202 bool netdev_port_same_parent_id(struct net_device *a, struct net_device *b) 10203 { 10204 struct netdev_phys_item_id a_id = { }; 10205 struct netdev_phys_item_id b_id = { }; 10206 10207 if (netif_get_port_parent_id(a, &a_id, true) || 10208 netif_get_port_parent_id(b, &b_id, true)) 10209 return false; 10210 10211 return netdev_phys_item_id_same(&a_id, &b_id); 10212 } 10213 EXPORT_SYMBOL(netdev_port_same_parent_id); 10214 10215 static struct net_device *dev_get_iflink_dev(struct net_device *dev) 10216 { 10217 struct net *net; 10218 10219 ASSERT_RTNL(); 10220 10221 if (!dev->netdev_ops->ndo_get_iflink || !dev->rtnl_link_ops || 10222 !dev->rtnl_link_ops->get_link_net) 10223 return dev; 10224 10225 net = dev->rtnl_link_ops->get_link_net(dev); 10226 return __dev_get_by_index(net, dev_get_iflink(dev)); 10227 } 10228 10229 int netif_change_proto_down(struct net_device *dev, bool proto_down) 10230 { 10231 struct net_device *iflink_dev; 10232 10233 if (!dev->change_proto_down) 10234 return -EOPNOTSUPP; 10235 if (!netif_device_present(dev)) 10236 return -ENODEV; 10237 iflink_dev = dev_get_iflink_dev(dev); 10238 if (!iflink_dev) 10239 return -ENODEV; 10240 WRITE_ONCE(dev->proto_down, proto_down); 10241 if (proto_down) 10242 netif_carrier_off(dev); 10243 else if (dev == iflink_dev || netif_carrier_ok(iflink_dev)) 10244 netif_carrier_on(dev); 10245 return 0; 10246 } 10247 10248 /** 10249 * netdev_change_proto_down_reason_locked - proto down reason 10250 * 10251 * @dev: device 10252 * @mask: proto down mask 10253 * @value: proto down value 10254 */ 10255 void netdev_change_proto_down_reason_locked(struct net_device *dev, 10256 unsigned long mask, u32 value) 10257 { 10258 u32 proto_down_reason; 10259 int b; 10260 10261 if (!mask) { 10262 proto_down_reason = value; 10263 } else { 10264 proto_down_reason = dev->proto_down_reason; 10265 for_each_set_bit(b, &mask, 32) { 10266 if (value & (1 << b)) 10267 proto_down_reason |= BIT(b); 10268 else 10269 proto_down_reason &= ~BIT(b); 10270 } 10271 } 10272 WRITE_ONCE(dev->proto_down_reason, proto_down_reason); 10273 } 10274 10275 struct bpf_xdp_link { 10276 struct bpf_link link; 10277 struct net_device *dev; /* protected by rtnl_lock, no refcnt held */ 10278 int flags; 10279 }; 10280 10281 static enum bpf_xdp_mode dev_xdp_mode(struct net_device *dev, u32 flags) 10282 { 10283 if (flags & XDP_FLAGS_HW_MODE) 10284 return XDP_MODE_HW; 10285 if (flags & XDP_FLAGS_DRV_MODE) 10286 return XDP_MODE_DRV; 10287 if (flags & XDP_FLAGS_SKB_MODE) 10288 return XDP_MODE_SKB; 10289 return dev->netdev_ops->ndo_bpf ? XDP_MODE_DRV : XDP_MODE_SKB; 10290 } 10291 10292 static bpf_op_t dev_xdp_bpf_op(struct net_device *dev, enum bpf_xdp_mode mode) 10293 { 10294 switch (mode) { 10295 case XDP_MODE_SKB: 10296 return generic_xdp_install; 10297 case XDP_MODE_DRV: 10298 case XDP_MODE_HW: 10299 return dev->netdev_ops->ndo_bpf; 10300 default: 10301 return NULL; 10302 } 10303 } 10304 10305 static struct bpf_xdp_link *dev_xdp_link(struct net_device *dev, 10306 enum bpf_xdp_mode mode) 10307 { 10308 return dev->xdp_state[mode].link; 10309 } 10310 10311 static struct bpf_prog *dev_xdp_prog(struct net_device *dev, 10312 enum bpf_xdp_mode mode) 10313 { 10314 struct bpf_xdp_link *link = dev_xdp_link(dev, mode); 10315 10316 if (link) 10317 return link->link.prog; 10318 return dev->xdp_state[mode].prog; 10319 } 10320 10321 u8 dev_xdp_prog_count(struct net_device *dev) 10322 { 10323 u8 count = 0; 10324 int i; 10325 10326 for (i = 0; i < __MAX_XDP_MODE; i++) 10327 if (dev->xdp_state[i].prog || dev->xdp_state[i].link) 10328 count++; 10329 return count; 10330 } 10331 EXPORT_SYMBOL_GPL(dev_xdp_prog_count); 10332 10333 u8 dev_xdp_sb_prog_count(struct net_device *dev) 10334 { 10335 u8 count = 0; 10336 int i; 10337 10338 for (i = 0; i < __MAX_XDP_MODE; i++) 10339 if (dev->xdp_state[i].prog && 10340 !dev->xdp_state[i].prog->aux->xdp_has_frags) 10341 count++; 10342 return count; 10343 } 10344 10345 int netif_xdp_propagate(struct net_device *dev, struct netdev_bpf *bpf) 10346 { 10347 if (!dev->netdev_ops->ndo_bpf) 10348 return -EOPNOTSUPP; 10349 10350 if (dev->cfg->hds_config == ETHTOOL_TCP_DATA_SPLIT_ENABLED && 10351 bpf->command == XDP_SETUP_PROG && 10352 bpf->prog && !bpf->prog->aux->xdp_has_frags) { 10353 NL_SET_ERR_MSG(bpf->extack, 10354 "unable to propagate XDP to device using tcp-data-split"); 10355 return -EBUSY; 10356 } 10357 10358 if (dev_get_min_mp_channel_count(dev)) { 10359 NL_SET_ERR_MSG(bpf->extack, "unable to propagate XDP to device using memory provider"); 10360 return -EBUSY; 10361 } 10362 10363 return dev->netdev_ops->ndo_bpf(dev, bpf); 10364 } 10365 EXPORT_SYMBOL_GPL(netif_xdp_propagate); 10366 10367 u32 dev_xdp_prog_id(struct net_device *dev, enum bpf_xdp_mode mode) 10368 { 10369 struct bpf_prog *prog = dev_xdp_prog(dev, mode); 10370 10371 return prog ? prog->aux->id : 0; 10372 } 10373 10374 static void dev_xdp_set_link(struct net_device *dev, enum bpf_xdp_mode mode, 10375 struct bpf_xdp_link *link) 10376 { 10377 dev->xdp_state[mode].link = link; 10378 dev->xdp_state[mode].prog = NULL; 10379 } 10380 10381 static void dev_xdp_set_prog(struct net_device *dev, enum bpf_xdp_mode mode, 10382 struct bpf_prog *prog) 10383 { 10384 dev->xdp_state[mode].link = NULL; 10385 dev->xdp_state[mode].prog = prog; 10386 } 10387 10388 static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode, 10389 bpf_op_t bpf_op, struct netlink_ext_ack *extack, 10390 u32 flags, struct bpf_prog *prog) 10391 { 10392 struct netdev_bpf xdp; 10393 int err; 10394 10395 netdev_assert_locked_ops_compat(dev); 10396 10397 if (prog) { 10398 enum bpf_xdp_mode other_mode = mode == XDP_MODE_SKB 10399 ? XDP_MODE_DRV : XDP_MODE_SKB; 10400 bool offload = mode == XDP_MODE_HW; 10401 10402 if (!offload && dev_xdp_prog(dev, other_mode)) { 10403 NL_SET_ERR_MSG(extack, "Native and generic XDP can't be active at the same time"); 10404 return -EEXIST; 10405 } 10406 if (!offload && bpf_prog_is_offloaded(prog->aux)) { 10407 NL_SET_ERR_MSG(extack, "Using offloaded program without HW_MODE flag is not supported"); 10408 return -EINVAL; 10409 } 10410 if (bpf_prog_is_dev_bound(prog->aux) && !bpf_offload_dev_match(prog, dev)) { 10411 NL_SET_ERR_MSG(extack, "Program bound to different device"); 10412 return -EINVAL; 10413 } 10414 if (bpf_prog_is_dev_bound(prog->aux) && mode == XDP_MODE_SKB) { 10415 NL_SET_ERR_MSG(extack, "Can't attach device-bound programs in generic mode"); 10416 return -EINVAL; 10417 } 10418 if (prog->expected_attach_type == BPF_XDP_DEVMAP) { 10419 NL_SET_ERR_MSG(extack, "BPF_XDP_DEVMAP programs can not be attached to a device"); 10420 return -EINVAL; 10421 } 10422 if (prog->expected_attach_type == BPF_XDP_CPUMAP) { 10423 NL_SET_ERR_MSG(extack, "BPF_XDP_CPUMAP programs can not be attached to a device"); 10424 return -EINVAL; 10425 } 10426 } 10427 10428 if (dev->cfg->hds_config == ETHTOOL_TCP_DATA_SPLIT_ENABLED && 10429 prog && !prog->aux->xdp_has_frags) { 10430 NL_SET_ERR_MSG(extack, "unable to install XDP to device using tcp-data-split"); 10431 return -EBUSY; 10432 } 10433 10434 if (dev_get_min_mp_channel_count(dev)) { 10435 NL_SET_ERR_MSG(extack, "unable to install XDP to device using memory provider"); 10436 return -EBUSY; 10437 } 10438 10439 memset(&xdp, 0, sizeof(xdp)); 10440 xdp.command = mode == XDP_MODE_HW ? XDP_SETUP_PROG_HW : XDP_SETUP_PROG; 10441 xdp.extack = extack; 10442 xdp.flags = flags; 10443 xdp.prog = prog; 10444 10445 /* Drivers assume refcnt is already incremented (i.e, prog pointer is 10446 * "moved" into driver), so they don't increment it on their own, but 10447 * they do decrement refcnt when program is detached or replaced. 10448 * Given net_device also owns link/prog, we need to bump refcnt here 10449 * to prevent drivers from underflowing it. 10450 */ 10451 if (prog) 10452 bpf_prog_inc(prog); 10453 err = bpf_op(dev, &xdp); 10454 if (err) { 10455 if (prog) 10456 bpf_prog_put(prog); 10457 return err; 10458 } 10459 10460 if (mode != XDP_MODE_HW) 10461 bpf_prog_change_xdp(dev_xdp_prog(dev, mode), prog); 10462 10463 return 0; 10464 } 10465 10466 static void dev_xdp_uninstall(struct net_device *dev) 10467 { 10468 struct bpf_xdp_link *link; 10469 struct bpf_prog *prog; 10470 enum bpf_xdp_mode mode; 10471 bpf_op_t bpf_op; 10472 10473 ASSERT_RTNL(); 10474 10475 for (mode = XDP_MODE_SKB; mode < __MAX_XDP_MODE; mode++) { 10476 prog = dev_xdp_prog(dev, mode); 10477 if (!prog) 10478 continue; 10479 10480 bpf_op = dev_xdp_bpf_op(dev, mode); 10481 if (!bpf_op) 10482 continue; 10483 10484 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL)); 10485 10486 /* auto-detach link from net device */ 10487 link = dev_xdp_link(dev, mode); 10488 if (link) 10489 link->dev = NULL; 10490 else 10491 bpf_prog_put(prog); 10492 10493 dev_xdp_set_link(dev, mode, NULL); 10494 } 10495 } 10496 10497 static int dev_xdp_attach(struct net_device *dev, struct netlink_ext_ack *extack, 10498 struct bpf_xdp_link *link, struct bpf_prog *new_prog, 10499 struct bpf_prog *old_prog, u32 flags) 10500 { 10501 unsigned int num_modes = hweight32(flags & XDP_FLAGS_MODES); 10502 struct bpf_prog *cur_prog; 10503 struct net_device *upper; 10504 struct list_head *iter; 10505 enum bpf_xdp_mode mode; 10506 bpf_op_t bpf_op; 10507 int err; 10508 10509 ASSERT_RTNL(); 10510 10511 /* either link or prog attachment, never both */ 10512 if (link && (new_prog || old_prog)) 10513 return -EINVAL; 10514 /* link supports only XDP mode flags */ 10515 if (link && (flags & ~XDP_FLAGS_MODES)) { 10516 NL_SET_ERR_MSG(extack, "Invalid XDP flags for BPF link attachment"); 10517 return -EINVAL; 10518 } 10519 /* just one XDP mode bit should be set, zero defaults to drv/skb mode */ 10520 if (num_modes > 1) { 10521 NL_SET_ERR_MSG(extack, "Only one XDP mode flag can be set"); 10522 return -EINVAL; 10523 } 10524 /* avoid ambiguity if offload + drv/skb mode progs are both loaded */ 10525 if (!num_modes && dev_xdp_prog_count(dev) > 1) { 10526 NL_SET_ERR_MSG(extack, 10527 "More than one program loaded, unset mode is ambiguous"); 10528 return -EINVAL; 10529 } 10530 /* old_prog != NULL implies XDP_FLAGS_REPLACE is set */ 10531 if (old_prog && !(flags & XDP_FLAGS_REPLACE)) { 10532 NL_SET_ERR_MSG(extack, "XDP_FLAGS_REPLACE is not specified"); 10533 return -EINVAL; 10534 } 10535 10536 mode = dev_xdp_mode(dev, flags); 10537 /* can't replace attached link */ 10538 if (dev_xdp_link(dev, mode)) { 10539 NL_SET_ERR_MSG(extack, "Can't replace active BPF XDP link"); 10540 return -EBUSY; 10541 } 10542 10543 /* don't allow if an upper device already has a program */ 10544 netdev_for_each_upper_dev_rcu(dev, upper, iter) { 10545 if (dev_xdp_prog_count(upper) > 0) { 10546 NL_SET_ERR_MSG(extack, "Cannot attach when an upper device already has a program"); 10547 return -EEXIST; 10548 } 10549 } 10550 10551 cur_prog = dev_xdp_prog(dev, mode); 10552 /* can't replace attached prog with link */ 10553 if (link && cur_prog) { 10554 NL_SET_ERR_MSG(extack, "Can't replace active XDP program with BPF link"); 10555 return -EBUSY; 10556 } 10557 if ((flags & XDP_FLAGS_REPLACE) && cur_prog != old_prog) { 10558 NL_SET_ERR_MSG(extack, "Active program does not match expected"); 10559 return -EEXIST; 10560 } 10561 10562 /* put effective new program into new_prog */ 10563 if (link) 10564 new_prog = link->link.prog; 10565 10566 if (new_prog) { 10567 if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) && cur_prog) { 10568 NL_SET_ERR_MSG(extack, "XDP program already attached"); 10569 return -EBUSY; 10570 } 10571 } 10572 10573 /* don't call drivers if the effective program didn't change */ 10574 if (new_prog != cur_prog) { 10575 bpf_op = dev_xdp_bpf_op(dev, mode); 10576 if (!bpf_op) { 10577 NL_SET_ERR_MSG(extack, "Underlying driver does not support XDP in native mode"); 10578 return -EOPNOTSUPP; 10579 } 10580 10581 err = dev_xdp_install(dev, mode, bpf_op, extack, flags, new_prog); 10582 if (err) 10583 return err; 10584 } 10585 10586 if (link) 10587 dev_xdp_set_link(dev, mode, link); 10588 else 10589 dev_xdp_set_prog(dev, mode, new_prog); 10590 if (cur_prog) 10591 bpf_prog_put(cur_prog); 10592 10593 return 0; 10594 } 10595 10596 static int dev_xdp_attach_link(struct net_device *dev, 10597 struct netlink_ext_ack *extack, 10598 struct bpf_xdp_link *link) 10599 { 10600 return dev_xdp_attach(dev, extack, link, NULL, NULL, link->flags); 10601 } 10602 10603 static int dev_xdp_detach_link(struct net_device *dev, 10604 struct netlink_ext_ack *extack, 10605 struct bpf_xdp_link *link) 10606 { 10607 enum bpf_xdp_mode mode; 10608 bpf_op_t bpf_op; 10609 10610 ASSERT_RTNL(); 10611 10612 mode = dev_xdp_mode(dev, link->flags); 10613 if (dev_xdp_link(dev, mode) != link) 10614 return -EINVAL; 10615 10616 bpf_op = dev_xdp_bpf_op(dev, mode); 10617 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL)); 10618 dev_xdp_set_link(dev, mode, NULL); 10619 return 0; 10620 } 10621 10622 static void bpf_xdp_link_release(struct bpf_link *link) 10623 { 10624 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link); 10625 10626 rtnl_lock(); 10627 10628 /* if racing with net_device's tear down, xdp_link->dev might be 10629 * already NULL, in which case link was already auto-detached 10630 */ 10631 if (xdp_link->dev) { 10632 netdev_lock_ops(xdp_link->dev); 10633 WARN_ON(dev_xdp_detach_link(xdp_link->dev, NULL, xdp_link)); 10634 netdev_unlock_ops(xdp_link->dev); 10635 xdp_link->dev = NULL; 10636 } 10637 10638 rtnl_unlock(); 10639 } 10640 10641 static int bpf_xdp_link_detach(struct bpf_link *link) 10642 { 10643 bpf_xdp_link_release(link); 10644 return 0; 10645 } 10646 10647 static void bpf_xdp_link_dealloc(struct bpf_link *link) 10648 { 10649 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link); 10650 10651 kfree(xdp_link); 10652 } 10653 10654 static void bpf_xdp_link_show_fdinfo(const struct bpf_link *link, 10655 struct seq_file *seq) 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 seq_printf(seq, "ifindex:\t%u\n", ifindex); 10666 } 10667 10668 static int bpf_xdp_link_fill_link_info(const struct bpf_link *link, 10669 struct bpf_link_info *info) 10670 { 10671 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link); 10672 u32 ifindex = 0; 10673 10674 rtnl_lock(); 10675 if (xdp_link->dev) 10676 ifindex = xdp_link->dev->ifindex; 10677 rtnl_unlock(); 10678 10679 info->xdp.ifindex = ifindex; 10680 return 0; 10681 } 10682 10683 static int bpf_xdp_link_update(struct bpf_link *link, struct bpf_prog *new_prog, 10684 struct bpf_prog *old_prog) 10685 { 10686 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link); 10687 enum bpf_xdp_mode mode; 10688 bpf_op_t bpf_op; 10689 int err = 0; 10690 10691 rtnl_lock(); 10692 10693 /* link might have been auto-released already, so fail */ 10694 if (!xdp_link->dev) { 10695 err = -ENOLINK; 10696 goto out_unlock; 10697 } 10698 10699 if (old_prog && link->prog != old_prog) { 10700 err = -EPERM; 10701 goto out_unlock; 10702 } 10703 old_prog = link->prog; 10704 if (old_prog->type != new_prog->type || 10705 old_prog->expected_attach_type != new_prog->expected_attach_type) { 10706 err = -EINVAL; 10707 goto out_unlock; 10708 } 10709 10710 if (old_prog == new_prog) { 10711 /* no-op, don't disturb drivers */ 10712 bpf_prog_put(new_prog); 10713 goto out_unlock; 10714 } 10715 10716 netdev_lock_ops(xdp_link->dev); 10717 mode = dev_xdp_mode(xdp_link->dev, xdp_link->flags); 10718 bpf_op = dev_xdp_bpf_op(xdp_link->dev, mode); 10719 err = dev_xdp_install(xdp_link->dev, mode, bpf_op, NULL, 10720 xdp_link->flags, new_prog); 10721 netdev_unlock_ops(xdp_link->dev); 10722 if (err) 10723 goto out_unlock; 10724 10725 old_prog = xchg(&link->prog, new_prog); 10726 bpf_prog_put(old_prog); 10727 10728 out_unlock: 10729 rtnl_unlock(); 10730 return err; 10731 } 10732 10733 static const struct bpf_link_ops bpf_xdp_link_lops = { 10734 .release = bpf_xdp_link_release, 10735 .dealloc = bpf_xdp_link_dealloc, 10736 .detach = bpf_xdp_link_detach, 10737 .show_fdinfo = bpf_xdp_link_show_fdinfo, 10738 .fill_link_info = bpf_xdp_link_fill_link_info, 10739 .update_prog = bpf_xdp_link_update, 10740 }; 10741 10742 int bpf_xdp_link_attach(const union bpf_attr *attr, struct bpf_prog *prog) 10743 { 10744 struct net *net = current->nsproxy->net_ns; 10745 struct bpf_link_primer link_primer; 10746 struct netlink_ext_ack extack = {}; 10747 struct bpf_xdp_link *link; 10748 struct net_device *dev; 10749 int err, fd; 10750 10751 rtnl_lock(); 10752 dev = dev_get_by_index(net, attr->link_create.target_ifindex); 10753 if (!dev) { 10754 rtnl_unlock(); 10755 return -EINVAL; 10756 } 10757 10758 link = kzalloc_obj(*link, GFP_USER); 10759 if (!link) { 10760 err = -ENOMEM; 10761 goto unlock; 10762 } 10763 10764 bpf_link_init(&link->link, BPF_LINK_TYPE_XDP, &bpf_xdp_link_lops, prog, 10765 attr->link_create.attach_type); 10766 link->dev = dev; 10767 link->flags = attr->link_create.flags; 10768 10769 err = bpf_link_prime(&link->link, &link_primer); 10770 if (err) { 10771 kfree(link); 10772 goto unlock; 10773 } 10774 10775 netdev_lock_ops(dev); 10776 err = dev_xdp_attach_link(dev, &extack, link); 10777 netdev_unlock_ops(dev); 10778 rtnl_unlock(); 10779 10780 if (err) { 10781 link->dev = NULL; 10782 bpf_link_cleanup(&link_primer); 10783 trace_bpf_xdp_link_attach_failed(extack._msg); 10784 goto out_put_dev; 10785 } 10786 10787 fd = bpf_link_settle(&link_primer); 10788 /* link itself doesn't hold dev's refcnt to not complicate shutdown */ 10789 dev_put(dev); 10790 return fd; 10791 10792 unlock: 10793 rtnl_unlock(); 10794 10795 out_put_dev: 10796 dev_put(dev); 10797 return err; 10798 } 10799 10800 /** 10801 * dev_change_xdp_fd - set or clear a bpf program for a device rx path 10802 * @dev: device 10803 * @extack: netlink extended ack 10804 * @fd: new program fd or negative value to clear 10805 * @expected_fd: old program fd that userspace expects to replace or clear 10806 * @flags: xdp-related flags 10807 * 10808 * Set or clear a bpf program for a device 10809 */ 10810 int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack, 10811 int fd, int expected_fd, u32 flags) 10812 { 10813 enum bpf_xdp_mode mode = dev_xdp_mode(dev, flags); 10814 struct bpf_prog *new_prog = NULL, *old_prog = NULL; 10815 int err; 10816 10817 ASSERT_RTNL(); 10818 10819 if (fd >= 0) { 10820 new_prog = bpf_prog_get_type_dev(fd, BPF_PROG_TYPE_XDP, 10821 mode != XDP_MODE_SKB); 10822 if (IS_ERR(new_prog)) 10823 return PTR_ERR(new_prog); 10824 } 10825 10826 if (expected_fd >= 0) { 10827 old_prog = bpf_prog_get_type_dev(expected_fd, BPF_PROG_TYPE_XDP, 10828 mode != XDP_MODE_SKB); 10829 if (IS_ERR(old_prog)) { 10830 err = PTR_ERR(old_prog); 10831 old_prog = NULL; 10832 goto err_out; 10833 } 10834 } 10835 10836 err = dev_xdp_attach(dev, extack, NULL, new_prog, old_prog, flags); 10837 10838 err_out: 10839 if (err && new_prog) 10840 bpf_prog_put(new_prog); 10841 if (old_prog) 10842 bpf_prog_put(old_prog); 10843 return err; 10844 } 10845 10846 u32 dev_get_min_mp_channel_count(const struct net_device *dev) 10847 { 10848 int i; 10849 10850 netdev_assert_locked_ops_compat(dev); 10851 10852 for (i = dev->real_num_rx_queues - 1; i >= 0; i--) 10853 if (dev->_rx[i].mp_params.mp_priv) 10854 /* The channel count is the idx plus 1. */ 10855 return i + 1; 10856 10857 return 0; 10858 } 10859 10860 /** 10861 * dev_index_reserve() - allocate an ifindex in a namespace 10862 * @net: the applicable net namespace 10863 * @ifindex: requested ifindex, pass %0 to get one allocated 10864 * 10865 * Allocate a ifindex for a new device. Caller must either use the ifindex 10866 * to store the device (via list_netdevice()) or call dev_index_release() 10867 * to give the index up. 10868 * 10869 * Return: a suitable unique value for a new device interface number or -errno. 10870 */ 10871 static int dev_index_reserve(struct net *net, u32 ifindex) 10872 { 10873 int err; 10874 10875 if (ifindex > INT_MAX) { 10876 DEBUG_NET_WARN_ON_ONCE(1); 10877 return -EINVAL; 10878 } 10879 10880 if (!ifindex) 10881 err = xa_alloc_cyclic(&net->dev_by_index, &ifindex, NULL, 10882 xa_limit_31b, &net->ifindex, GFP_KERNEL); 10883 else 10884 err = xa_insert(&net->dev_by_index, ifindex, NULL, GFP_KERNEL); 10885 if (err < 0) 10886 return err; 10887 10888 return ifindex; 10889 } 10890 10891 static void dev_index_release(struct net *net, int ifindex) 10892 { 10893 /* Expect only unused indexes, unlist_netdevice() removes the used */ 10894 WARN_ON(xa_erase(&net->dev_by_index, ifindex)); 10895 } 10896 10897 static bool from_cleanup_net(void) 10898 { 10899 #ifdef CONFIG_NET_NS 10900 return current == READ_ONCE(cleanup_net_task); 10901 #else 10902 return false; 10903 #endif 10904 } 10905 10906 /* Delayed registration/unregisteration */ 10907 LIST_HEAD(net_todo_list); 10908 DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq); 10909 atomic_t dev_unreg_count = ATOMIC_INIT(0); 10910 10911 static void net_set_todo(struct net_device *dev) 10912 { 10913 list_add_tail(&dev->todo_list, &net_todo_list); 10914 } 10915 10916 static netdev_features_t netdev_sync_upper_features(struct net_device *lower, 10917 struct net_device *upper, netdev_features_t features) 10918 { 10919 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES; 10920 netdev_features_t feature; 10921 int feature_bit; 10922 10923 for_each_netdev_feature(upper_disables, feature_bit) { 10924 feature = __NETIF_F_BIT(feature_bit); 10925 if (!(upper->wanted_features & feature) 10926 && (features & feature)) { 10927 netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n", 10928 &feature, upper->name); 10929 features &= ~feature; 10930 } 10931 } 10932 10933 return features; 10934 } 10935 10936 static void netdev_sync_lower_features(struct net_device *upper, 10937 struct net_device *lower, netdev_features_t features) 10938 { 10939 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES; 10940 netdev_features_t feature; 10941 int feature_bit; 10942 10943 for_each_netdev_feature(upper_disables, feature_bit) { 10944 feature = __NETIF_F_BIT(feature_bit); 10945 if (!(features & feature) && (lower->features & feature)) { 10946 netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n", 10947 &feature, lower->name); 10948 netdev_lock_ops(lower); 10949 lower->wanted_features &= ~feature; 10950 __netdev_update_features(lower); 10951 10952 if (unlikely(lower->features & feature)) 10953 netdev_WARN(upper, "failed to disable %pNF on %s!\n", 10954 &feature, lower->name); 10955 else 10956 netdev_features_change(lower); 10957 netdev_unlock_ops(lower); 10958 } 10959 } 10960 } 10961 10962 static bool netdev_has_ip_or_hw_csum(netdev_features_t features) 10963 { 10964 netdev_features_t ip_csum_mask = NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM; 10965 bool ip_csum = (features & ip_csum_mask) == ip_csum_mask; 10966 bool hw_csum = features & NETIF_F_HW_CSUM; 10967 10968 return ip_csum || hw_csum; 10969 } 10970 10971 static netdev_features_t netdev_fix_features(struct net_device *dev, 10972 netdev_features_t features) 10973 { 10974 /* Fix illegal checksum combinations */ 10975 if ((features & NETIF_F_HW_CSUM) && 10976 (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) { 10977 netdev_warn(dev, "mixed HW and IP checksum settings.\n"); 10978 features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM); 10979 } 10980 10981 /* TSO requires that SG is present as well. */ 10982 if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) { 10983 netdev_dbg(dev, "Dropping TSO features since no SG feature.\n"); 10984 features &= ~NETIF_F_ALL_TSO; 10985 } 10986 10987 if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) && 10988 !(features & NETIF_F_IP_CSUM)) { 10989 netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n"); 10990 features &= ~NETIF_F_TSO; 10991 features &= ~NETIF_F_TSO_ECN; 10992 } 10993 10994 if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) && 10995 !(features & NETIF_F_IPV6_CSUM)) { 10996 netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n"); 10997 features &= ~NETIF_F_TSO6; 10998 } 10999 11000 /* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */ 11001 if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO)) 11002 features &= ~NETIF_F_TSO_MANGLEID; 11003 11004 /* TSO ECN requires that TSO is present as well. */ 11005 if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN) 11006 features &= ~NETIF_F_TSO_ECN; 11007 11008 /* Software GSO depends on SG. */ 11009 if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) { 11010 netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n"); 11011 features &= ~NETIF_F_GSO; 11012 } 11013 11014 /* GSO partial features require GSO partial be set */ 11015 if ((features & dev->gso_partial_features) && 11016 !(features & NETIF_F_GSO_PARTIAL)) { 11017 netdev_dbg(dev, 11018 "Dropping partially supported GSO features since no GSO partial.\n"); 11019 features &= ~dev->gso_partial_features; 11020 } 11021 11022 if (!(features & NETIF_F_RXCSUM)) { 11023 /* NETIF_F_GRO_HW implies doing RXCSUM since every packet 11024 * successfully merged by hardware must also have the 11025 * checksum verified by hardware. If the user does not 11026 * want to enable RXCSUM, logically, we should disable GRO_HW. 11027 */ 11028 if (features & NETIF_F_GRO_HW) { 11029 netdev_dbg(dev, "Dropping NETIF_F_GRO_HW since no RXCSUM feature.\n"); 11030 features &= ~NETIF_F_GRO_HW; 11031 } 11032 } 11033 11034 /* LRO/HW-GRO features cannot be combined with RX-FCS */ 11035 if (features & NETIF_F_RXFCS) { 11036 if (features & NETIF_F_LRO) { 11037 netdev_dbg(dev, "Dropping LRO feature since RX-FCS is requested.\n"); 11038 features &= ~NETIF_F_LRO; 11039 } 11040 11041 if (features & NETIF_F_GRO_HW) { 11042 netdev_dbg(dev, "Dropping HW-GRO feature since RX-FCS is requested.\n"); 11043 features &= ~NETIF_F_GRO_HW; 11044 } 11045 } 11046 11047 if ((features & NETIF_F_GRO_HW) && (features & NETIF_F_LRO)) { 11048 netdev_dbg(dev, "Dropping LRO feature since HW-GRO is requested.\n"); 11049 features &= ~NETIF_F_LRO; 11050 } 11051 11052 if ((features & NETIF_F_HW_TLS_TX) && !netdev_has_ip_or_hw_csum(features)) { 11053 netdev_dbg(dev, "Dropping TLS TX HW offload feature since no CSUM feature.\n"); 11054 features &= ~NETIF_F_HW_TLS_TX; 11055 } 11056 11057 if ((features & NETIF_F_HW_TLS_RX) && !(features & NETIF_F_RXCSUM)) { 11058 netdev_dbg(dev, "Dropping TLS RX HW offload feature since no RXCSUM feature.\n"); 11059 features &= ~NETIF_F_HW_TLS_RX; 11060 } 11061 11062 if ((features & NETIF_F_GSO_UDP_L4) && !netdev_has_ip_or_hw_csum(features)) { 11063 netdev_dbg(dev, "Dropping USO feature since no CSUM feature.\n"); 11064 features &= ~NETIF_F_GSO_UDP_L4; 11065 } 11066 11067 return features; 11068 } 11069 11070 int __netdev_update_features(struct net_device *dev) 11071 { 11072 struct net_device *upper, *lower; 11073 netdev_features_t features; 11074 struct list_head *iter; 11075 int err = -1; 11076 11077 ASSERT_RTNL(); 11078 netdev_assert_locked_ops_compat(dev); 11079 11080 features = netdev_get_wanted_features(dev); 11081 11082 if (dev->netdev_ops->ndo_fix_features) 11083 features = dev->netdev_ops->ndo_fix_features(dev, features); 11084 11085 /* driver might be less strict about feature dependencies */ 11086 features = netdev_fix_features(dev, features); 11087 11088 /* some features can't be enabled if they're off on an upper device */ 11089 netdev_for_each_upper_dev_rcu(dev, upper, iter) 11090 features = netdev_sync_upper_features(dev, upper, features); 11091 11092 if (dev->features == features) 11093 goto sync_lower; 11094 11095 netdev_dbg(dev, "Features changed: %pNF -> %pNF\n", 11096 &dev->features, &features); 11097 11098 if (dev->netdev_ops->ndo_set_features) 11099 err = dev->netdev_ops->ndo_set_features(dev, features); 11100 else 11101 err = 0; 11102 11103 if (unlikely(err < 0)) { 11104 netdev_err(dev, 11105 "set_features() failed (%d); wanted %pNF, left %pNF\n", 11106 err, &features, &dev->features); 11107 /* return non-0 since some features might have changed and 11108 * it's better to fire a spurious notification than miss it 11109 */ 11110 return -1; 11111 } 11112 11113 sync_lower: 11114 /* some features must be disabled on lower devices when disabled 11115 * on an upper device (think: bonding master or bridge) 11116 */ 11117 netdev_for_each_lower_dev(dev, lower, iter) 11118 netdev_sync_lower_features(dev, lower, features); 11119 11120 if (!err) { 11121 netdev_features_t diff = features ^ dev->features; 11122 11123 if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) { 11124 /* udp_tunnel_{get,drop}_rx_info both need 11125 * NETIF_F_RX_UDP_TUNNEL_PORT enabled on the 11126 * device, or they won't do anything. 11127 * Thus we need to update dev->features 11128 * *before* calling udp_tunnel_get_rx_info, 11129 * but *after* calling udp_tunnel_drop_rx_info. 11130 */ 11131 udp_tunnel_nic_lock(dev); 11132 if (features & NETIF_F_RX_UDP_TUNNEL_PORT) { 11133 dev->features = features; 11134 udp_tunnel_get_rx_info(dev); 11135 } else { 11136 udp_tunnel_drop_rx_info(dev); 11137 } 11138 udp_tunnel_nic_unlock(dev); 11139 } 11140 11141 if (diff & NETIF_F_HW_VLAN_CTAG_FILTER) { 11142 if (features & NETIF_F_HW_VLAN_CTAG_FILTER) { 11143 dev->features = features; 11144 err |= vlan_get_rx_ctag_filter_info(dev); 11145 } else { 11146 vlan_drop_rx_ctag_filter_info(dev); 11147 } 11148 } 11149 11150 if (diff & NETIF_F_HW_VLAN_STAG_FILTER) { 11151 if (features & NETIF_F_HW_VLAN_STAG_FILTER) { 11152 dev->features = features; 11153 err |= vlan_get_rx_stag_filter_info(dev); 11154 } else { 11155 vlan_drop_rx_stag_filter_info(dev); 11156 } 11157 } 11158 11159 dev->features = features; 11160 } 11161 11162 return err < 0 ? 0 : 1; 11163 } 11164 11165 /** 11166 * netdev_update_features - recalculate device features 11167 * @dev: the device to check 11168 * 11169 * Recalculate dev->features set and send notifications if it 11170 * has changed. Should be called after driver or hardware dependent 11171 * conditions might have changed that influence the features. 11172 */ 11173 void netdev_update_features(struct net_device *dev) 11174 { 11175 if (__netdev_update_features(dev)) 11176 netdev_features_change(dev); 11177 } 11178 EXPORT_SYMBOL(netdev_update_features); 11179 11180 /** 11181 * netdev_change_features - recalculate device features 11182 * @dev: the device to check 11183 * 11184 * Recalculate dev->features set and send notifications even 11185 * if they have not changed. Should be called instead of 11186 * netdev_update_features() if also dev->vlan_features might 11187 * have changed to allow the changes to be propagated to stacked 11188 * VLAN devices. 11189 */ 11190 void netdev_change_features(struct net_device *dev) 11191 { 11192 __netdev_update_features(dev); 11193 netdev_features_change(dev); 11194 } 11195 EXPORT_SYMBOL(netdev_change_features); 11196 11197 /** 11198 * netif_stacked_transfer_operstate - transfer operstate 11199 * @rootdev: the root or lower level device to transfer state from 11200 * @dev: the device to transfer operstate to 11201 * 11202 * Transfer operational state from root to device. This is normally 11203 * called when a stacking relationship exists between the root 11204 * device and the device(a leaf device). 11205 */ 11206 void netif_stacked_transfer_operstate(const struct net_device *rootdev, 11207 struct net_device *dev) 11208 { 11209 if (rootdev->operstate == IF_OPER_DORMANT) 11210 netif_dormant_on(dev); 11211 else 11212 netif_dormant_off(dev); 11213 11214 if (rootdev->operstate == IF_OPER_TESTING) 11215 netif_testing_on(dev); 11216 else 11217 netif_testing_off(dev); 11218 11219 if (netif_carrier_ok(rootdev)) 11220 netif_carrier_on(dev); 11221 else 11222 netif_carrier_off(dev); 11223 } 11224 EXPORT_SYMBOL(netif_stacked_transfer_operstate); 11225 11226 static int netif_alloc_rx_queues(struct net_device *dev) 11227 { 11228 unsigned int i, count = dev->num_rx_queues; 11229 struct netdev_rx_queue *rx; 11230 size_t sz = count * sizeof(*rx); 11231 int err = 0; 11232 11233 BUG_ON(count < 1); 11234 11235 rx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL); 11236 if (!rx) 11237 return -ENOMEM; 11238 11239 dev->_rx = rx; 11240 11241 for (i = 0; i < count; i++) { 11242 rx[i].dev = dev; 11243 11244 /* XDP RX-queue setup */ 11245 err = xdp_rxq_info_reg(&rx[i].xdp_rxq, dev, i, 0); 11246 if (err < 0) 11247 goto err_rxq_info; 11248 } 11249 return 0; 11250 11251 err_rxq_info: 11252 /* Rollback successful reg's and free other resources */ 11253 while (i--) 11254 xdp_rxq_info_unreg(&rx[i].xdp_rxq); 11255 kvfree(dev->_rx); 11256 dev->_rx = NULL; 11257 return err; 11258 } 11259 11260 static void netif_free_rx_queues(struct net_device *dev) 11261 { 11262 unsigned int i, count = dev->num_rx_queues; 11263 11264 /* netif_alloc_rx_queues alloc failed, resources have been unreg'ed */ 11265 if (!dev->_rx) 11266 return; 11267 11268 for (i = 0; i < count; i++) 11269 xdp_rxq_info_unreg(&dev->_rx[i].xdp_rxq); 11270 11271 kvfree(dev->_rx); 11272 } 11273 11274 static void netdev_init_one_queue(struct net_device *dev, 11275 struct netdev_queue *queue, void *_unused) 11276 { 11277 /* Initialize queue lock */ 11278 spin_lock_init(&queue->_xmit_lock); 11279 netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type); 11280 queue->xmit_lock_owner = -1; 11281 netdev_queue_numa_node_write(queue, NUMA_NO_NODE); 11282 queue->dev = dev; 11283 #ifdef CONFIG_BQL 11284 dql_init(&queue->dql, HZ); 11285 #endif 11286 } 11287 11288 static void netif_free_tx_queues(struct net_device *dev) 11289 { 11290 kvfree(dev->_tx); 11291 } 11292 11293 static int netif_alloc_netdev_queues(struct net_device *dev) 11294 { 11295 unsigned int count = dev->num_tx_queues; 11296 struct netdev_queue *tx; 11297 size_t sz = count * sizeof(*tx); 11298 11299 if (count < 1 || count > 0xffff) 11300 return -EINVAL; 11301 11302 tx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL); 11303 if (!tx) 11304 return -ENOMEM; 11305 11306 dev->_tx = tx; 11307 11308 netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL); 11309 spin_lock_init(&dev->tx_global_lock); 11310 spin_lock_init(&dev->watchdog_lock); 11311 dev->watchdog_ref_held = false; 11312 return 0; 11313 } 11314 11315 void netif_tx_stop_all_queues(struct net_device *dev) 11316 { 11317 unsigned int i; 11318 11319 for (i = 0; i < dev->num_tx_queues; i++) { 11320 struct netdev_queue *txq = netdev_get_tx_queue(dev, i); 11321 11322 netif_tx_stop_queue(txq); 11323 } 11324 } 11325 EXPORT_SYMBOL(netif_tx_stop_all_queues); 11326 11327 static int netdev_do_alloc_pcpu_stats(struct net_device *dev) 11328 { 11329 void __percpu *v; 11330 11331 /* Drivers implementing ndo_get_peer_dev must support tstat 11332 * accounting, so that skb_do_redirect() can bump the dev's 11333 * RX stats upon network namespace switch. 11334 */ 11335 if (dev->netdev_ops->ndo_get_peer_dev && 11336 dev->pcpu_stat_type != NETDEV_PCPU_STAT_TSTATS) 11337 return -EOPNOTSUPP; 11338 11339 switch (dev->pcpu_stat_type) { 11340 case NETDEV_PCPU_STAT_NONE: 11341 return 0; 11342 case NETDEV_PCPU_STAT_LSTATS: 11343 v = dev->lstats = netdev_alloc_pcpu_stats(struct pcpu_lstats); 11344 break; 11345 case NETDEV_PCPU_STAT_TSTATS: 11346 v = dev->tstats = netdev_alloc_pcpu_stats(struct pcpu_sw_netstats); 11347 break; 11348 case NETDEV_PCPU_STAT_DSTATS: 11349 v = dev->dstats = netdev_alloc_pcpu_stats(struct pcpu_dstats); 11350 break; 11351 default: 11352 return -EINVAL; 11353 } 11354 11355 return v ? 0 : -ENOMEM; 11356 } 11357 11358 static void netdev_do_free_pcpu_stats(struct net_device *dev) 11359 { 11360 switch (dev->pcpu_stat_type) { 11361 case NETDEV_PCPU_STAT_NONE: 11362 return; 11363 case NETDEV_PCPU_STAT_LSTATS: 11364 free_percpu(dev->lstats); 11365 break; 11366 case NETDEV_PCPU_STAT_TSTATS: 11367 free_percpu(dev->tstats); 11368 break; 11369 case NETDEV_PCPU_STAT_DSTATS: 11370 free_percpu(dev->dstats); 11371 break; 11372 } 11373 } 11374 11375 static void netdev_free_phy_link_topology(struct net_device *dev) 11376 { 11377 struct phy_link_topology *topo = dev->link_topo; 11378 11379 if (IS_ENABLED(CONFIG_PHYLIB) && topo) { 11380 xa_destroy(&topo->phys); 11381 kfree(topo); 11382 dev->link_topo = NULL; 11383 } 11384 } 11385 11386 /** 11387 * register_netdevice() - register a network device 11388 * @dev: device to register 11389 * 11390 * Take a prepared network device structure and make it externally accessible. 11391 * A %NETDEV_REGISTER message is sent to the netdev notifier chain. 11392 * Callers must hold the rtnl lock - you may want register_netdev() 11393 * instead of this. 11394 */ 11395 int register_netdevice(struct net_device *dev) 11396 { 11397 int ret; 11398 struct net *net = dev_net(dev); 11399 11400 BUILD_BUG_ON(sizeof(netdev_features_t) * BITS_PER_BYTE < 11401 NETDEV_FEATURE_COUNT); 11402 BUG_ON(dev_boot_phase); 11403 ASSERT_RTNL(); 11404 11405 might_sleep(); 11406 11407 /* When net_device's are persistent, this will be fatal. */ 11408 BUG_ON(dev->reg_state != NETREG_UNINITIALIZED); 11409 BUG_ON(!net); 11410 11411 ret = ethtool_check_ops(dev->ethtool_ops); 11412 if (ret) 11413 return ret; 11414 11415 /* rss ctx ID 0 is reserved for the default context, start from 1 */ 11416 xa_init_flags(&dev->ethtool->rss_ctx, XA_FLAGS_ALLOC1); 11417 mutex_init(&dev->ethtool->rss_lock); 11418 11419 spin_lock_init(&dev->addr_list_lock); 11420 netdev_set_addr_lockdep_class(dev); 11421 11422 ret = dev_get_valid_name(net, dev, dev->name); 11423 if (ret < 0) 11424 goto out; 11425 11426 ret = -ENOMEM; 11427 dev->name_node = netdev_name_node_head_alloc(dev); 11428 if (!dev->name_node) 11429 goto out; 11430 11431 /* Init, if this function is available */ 11432 if (dev->netdev_ops->ndo_init) { 11433 ret = dev->netdev_ops->ndo_init(dev); 11434 if (ret) { 11435 if (ret > 0) 11436 ret = -EIO; 11437 goto err_free_name; 11438 } 11439 } 11440 11441 if (((dev->hw_features | dev->features) & 11442 NETIF_F_HW_VLAN_CTAG_FILTER) && 11443 (!dev->netdev_ops->ndo_vlan_rx_add_vid || 11444 !dev->netdev_ops->ndo_vlan_rx_kill_vid)) { 11445 netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n"); 11446 ret = -EINVAL; 11447 goto err_uninit; 11448 } 11449 11450 if (netdev_need_ops_lock(dev) && 11451 dev->netdev_ops->ndo_set_rx_mode && 11452 !dev->netdev_ops->ndo_set_rx_mode_async) 11453 netdev_WARN(dev, "ops-locked drivers should use ndo_set_rx_mode_async\n"); 11454 11455 ret = netdev_do_alloc_pcpu_stats(dev); 11456 if (ret) 11457 goto err_uninit; 11458 11459 ret = dev_index_reserve(net, dev->ifindex); 11460 if (ret < 0) 11461 goto err_free_pcpu; 11462 dev->ifindex = ret; 11463 11464 /* Transfer changeable features to wanted_features and enable 11465 * software offloads (GSO and GRO). 11466 */ 11467 dev->hw_features |= (NETIF_F_SOFT_FEATURES | NETIF_F_SOFT_FEATURES_OFF); 11468 dev->features |= NETIF_F_SOFT_FEATURES; 11469 11470 if (dev->udp_tunnel_nic_info) { 11471 dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT; 11472 dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT; 11473 } 11474 11475 dev->wanted_features = dev->features & dev->hw_features; 11476 11477 if (!(dev->flags & IFF_LOOPBACK)) 11478 dev->hw_features |= NETIF_F_NOCACHE_COPY; 11479 11480 /* If IPv4 TCP segmentation offload is supported we should also 11481 * allow the device to enable segmenting the frame with the option 11482 * of ignoring a static IP ID value. This doesn't enable the 11483 * feature itself but allows the user to enable it later. 11484 */ 11485 if (dev->hw_features & NETIF_F_TSO) 11486 dev->hw_features |= NETIF_F_TSO_MANGLEID; 11487 if (dev->vlan_features & NETIF_F_TSO) 11488 dev->vlan_features |= NETIF_F_TSO_MANGLEID; 11489 if (dev->mpls_features & NETIF_F_TSO) 11490 dev->mpls_features |= NETIF_F_TSO_MANGLEID; 11491 if (dev->hw_enc_features & NETIF_F_TSO) 11492 dev->hw_enc_features |= NETIF_F_TSO_MANGLEID; 11493 11494 /* TSO_MANGLEID belongs in mangleid_features by definition */ 11495 dev->mangleid_features |= NETIF_F_TSO_MANGLEID; 11496 11497 /* Make NETIF_F_HIGHDMA inheritable to VLAN devices. 11498 */ 11499 dev->vlan_features |= NETIF_F_HIGHDMA; 11500 11501 /* Make NETIF_F_SG inheritable to tunnel devices. 11502 */ 11503 dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL; 11504 11505 /* Make NETIF_F_SG inheritable to MPLS. 11506 */ 11507 dev->mpls_features |= NETIF_F_SG; 11508 11509 ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev); 11510 ret = notifier_to_errno(ret); 11511 if (ret) 11512 goto err_ifindex_release; 11513 11514 ret = netdev_register_kobject(dev); 11515 11516 netdev_lock(dev); 11517 WRITE_ONCE(dev->reg_state, ret ? NETREG_UNREGISTERED : NETREG_REGISTERED); 11518 netdev_unlock(dev); 11519 11520 if (ret) 11521 goto err_uninit_notify; 11522 11523 netdev_lock_ops(dev); 11524 __netdev_update_features(dev); 11525 netdev_unlock_ops(dev); 11526 11527 /* 11528 * Default initial state at registry is that the 11529 * device is present. 11530 */ 11531 11532 set_bit(__LINK_STATE_PRESENT, &dev->state); 11533 11534 linkwatch_init_dev(dev); 11535 11536 dev_init_scheduler(dev); 11537 11538 netdev_hold(dev, &dev->dev_registered_tracker, GFP_KERNEL); 11539 list_netdevice(dev); 11540 11541 add_device_randomness(dev->dev_addr, dev->addr_len); 11542 11543 /* If the device has permanent device address, driver should 11544 * set dev_addr and also addr_assign_type should be set to 11545 * NET_ADDR_PERM (default value). 11546 */ 11547 if (dev->addr_assign_type == NET_ADDR_PERM) 11548 memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len); 11549 11550 /* Notify protocols, that a new device appeared. */ 11551 netdev_lock_ops(dev); 11552 ret = call_netdevice_notifiers(NETDEV_REGISTER, dev); 11553 netdev_unlock_ops(dev); 11554 ret = notifier_to_errno(ret); 11555 if (ret) { 11556 /* Expect explicit free_netdev() on failure */ 11557 dev->needs_free_netdev = false; 11558 unregister_netdevice_queue(dev, NULL); 11559 goto out; 11560 } 11561 /* 11562 * Prevent userspace races by waiting until the network 11563 * device is fully setup before sending notifications. 11564 */ 11565 netdev_uevent_add(dev); 11566 if (!(dev->rtnl_link_ops && dev->rtnl_link_initializing)) 11567 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL, 0, NULL); 11568 11569 out: 11570 return ret; 11571 11572 err_uninit_notify: 11573 call_netdevice_notifiers(NETDEV_PRE_UNINIT, dev); 11574 err_ifindex_release: 11575 dev_index_release(net, dev->ifindex); 11576 err_free_pcpu: 11577 netdev_do_free_pcpu_stats(dev); 11578 err_uninit: 11579 if (dev->netdev_ops->ndo_uninit) 11580 dev->netdev_ops->ndo_uninit(dev); 11581 if (dev->priv_destructor) 11582 dev->priv_destructor(dev); 11583 err_free_name: 11584 netdev_name_node_free(dev->name_node); 11585 goto out; 11586 } 11587 EXPORT_SYMBOL(register_netdevice); 11588 11589 /* Initialize the core of a dummy net device. 11590 * The setup steps dummy netdevs need which normal netdevs get by going 11591 * through register_netdevice(). 11592 */ 11593 static void init_dummy_netdev(struct net_device *dev) 11594 { 11595 /* make sure we BUG if trying to hit standard 11596 * register/unregister code path 11597 */ 11598 dev->reg_state = NETREG_DUMMY; 11599 11600 /* a dummy interface is started by default */ 11601 set_bit(__LINK_STATE_PRESENT, &dev->state); 11602 set_bit(__LINK_STATE_START, &dev->state); 11603 11604 /* Note : We dont allocate pcpu_refcnt for dummy devices, 11605 * because users of this 'device' dont need to change 11606 * its refcount. 11607 */ 11608 } 11609 11610 /** 11611 * register_netdev - register a network device 11612 * @dev: device to register 11613 * 11614 * Take a completed network device structure and add it to the kernel 11615 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier 11616 * chain. 0 is returned on success. A negative errno code is returned 11617 * on a failure to set up the device, or if the name is a duplicate. 11618 * 11619 * This is a wrapper around register_netdevice that takes the rtnl semaphore 11620 * and expands the device name if you passed a format string to 11621 * alloc_netdev. 11622 */ 11623 int register_netdev(struct net_device *dev) 11624 { 11625 struct net *net = dev_net(dev); 11626 int err; 11627 11628 if (rtnl_net_lock_killable(net)) 11629 return -EINTR; 11630 11631 err = register_netdevice(dev); 11632 11633 rtnl_net_unlock(net); 11634 11635 return err; 11636 } 11637 EXPORT_SYMBOL(register_netdev); 11638 11639 int netdev_refcnt_read(const struct net_device *dev) 11640 { 11641 #ifdef CONFIG_PCPU_DEV_REFCNT 11642 int i, refcnt = 0; 11643 11644 for_each_possible_cpu(i) 11645 refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i); 11646 return refcnt; 11647 #else 11648 return refcount_read(&dev->dev_refcnt); 11649 #endif 11650 } 11651 EXPORT_SYMBOL(netdev_refcnt_read); 11652 11653 int netdev_unregister_timeout_secs __read_mostly = 10; 11654 11655 #define WAIT_REFS_MIN_MSECS 1 11656 #define WAIT_REFS_MAX_MSECS 250 11657 /** 11658 * netdev_wait_allrefs_any - wait until all references are gone. 11659 * @list: list of net_devices to wait on 11660 * 11661 * This is called when unregistering network devices. 11662 * 11663 * Any protocol or device that holds a reference should register 11664 * for netdevice notification, and cleanup and put back the 11665 * reference if they receive an UNREGISTER event. 11666 * We can get stuck here if buggy protocols don't correctly 11667 * call dev_put. 11668 */ 11669 static struct net_device *netdev_wait_allrefs_any(struct list_head *list) 11670 { 11671 unsigned long rebroadcast_time, warning_time; 11672 struct net_device *dev; 11673 int wait = 0; 11674 11675 rebroadcast_time = warning_time = jiffies; 11676 11677 list_for_each_entry(dev, list, todo_list) 11678 if (netdev_refcnt_read(dev) == 1) 11679 return dev; 11680 11681 while (true) { 11682 if (time_after(jiffies, rebroadcast_time + 1 * HZ)) { 11683 rtnl_lock(); 11684 11685 /* Rebroadcast unregister notification */ 11686 list_for_each_entry(dev, list, todo_list) { 11687 struct net *net = dev_net(dev); 11688 11689 __rtnl_net_lock(net); 11690 call_netdevice_notifiers(NETDEV_UNREGISTER, dev); 11691 __rtnl_net_unlock(net); 11692 } 11693 11694 __rtnl_unlock(); 11695 rcu_barrier(); 11696 rtnl_lock(); 11697 11698 list_for_each_entry(dev, list, todo_list) 11699 if (test_bit(__LINK_STATE_LINKWATCH_PENDING, 11700 &dev->state)) { 11701 /* We must not have linkwatch events 11702 * pending on unregister. If this 11703 * happens, we simply run the queue 11704 * unscheduled, resulting in a noop 11705 * for this device. 11706 */ 11707 linkwatch_run_queue(); 11708 break; 11709 } 11710 11711 __rtnl_unlock(); 11712 11713 rebroadcast_time = jiffies; 11714 } 11715 11716 rcu_barrier(); 11717 11718 if (!wait) { 11719 wait = WAIT_REFS_MIN_MSECS; 11720 } else { 11721 msleep(wait); 11722 wait = min(wait << 1, WAIT_REFS_MAX_MSECS); 11723 } 11724 11725 list_for_each_entry(dev, list, todo_list) 11726 if (netdev_refcnt_read(dev) == 1) 11727 return dev; 11728 11729 if (time_after(jiffies, warning_time + 11730 READ_ONCE(netdev_unregister_timeout_secs) * HZ)) { 11731 list_for_each_entry(dev, list, todo_list) { 11732 pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n", 11733 dev->name, netdev_refcnt_read(dev)); 11734 ref_tracker_dir_print(&dev->refcnt_tracker, 10); 11735 } 11736 11737 warning_time = jiffies; 11738 } 11739 } 11740 } 11741 11742 /* The sequence is: 11743 * 11744 * rtnl_lock(); 11745 * ... 11746 * register_netdevice(x1); 11747 * register_netdevice(x2); 11748 * ... 11749 * unregister_netdevice(y1); 11750 * unregister_netdevice(y2); 11751 * ... 11752 * rtnl_unlock(); 11753 * free_netdev(y1); 11754 * free_netdev(y2); 11755 * 11756 * We are invoked by rtnl_unlock(). 11757 * This allows us to deal with problems: 11758 * 1) We can delete sysfs objects which invoke hotplug 11759 * without deadlocking with linkwatch via keventd. 11760 * 2) Since we run with the RTNL semaphore not held, we can sleep 11761 * safely in order to wait for the netdev refcnt to drop to zero. 11762 * 11763 * We must not return until all unregister events added during 11764 * the interval the lock was held have been completed. 11765 */ 11766 void netdev_run_todo(void) 11767 { 11768 struct net_device *dev, *tmp; 11769 struct list_head list; 11770 int cnt; 11771 #ifdef CONFIG_LOCKDEP 11772 struct list_head unlink_list; 11773 11774 list_replace_init(&net_unlink_list, &unlink_list); 11775 11776 while (!list_empty(&unlink_list)) { 11777 dev = list_first_entry(&unlink_list, struct net_device, 11778 unlink_list); 11779 list_del_init(&dev->unlink_list); 11780 dev->nested_level = dev->lower_level - 1; 11781 } 11782 #endif 11783 11784 /* Snapshot list, allow later requests */ 11785 list_replace_init(&net_todo_list, &list); 11786 11787 __rtnl_unlock(); 11788 11789 /* Wait for rcu callbacks to finish before next phase */ 11790 if (!list_empty(&list)) 11791 rcu_barrier(); 11792 11793 list_for_each_entry_safe(dev, tmp, &list, todo_list) { 11794 if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) { 11795 netdev_WARN(dev, "run_todo but not unregistering\n"); 11796 list_del(&dev->todo_list); 11797 continue; 11798 } 11799 11800 netdev_lock(dev); 11801 WRITE_ONCE(dev->reg_state, NETREG_UNREGISTERED); 11802 netdev_unlock(dev); 11803 linkwatch_sync_dev(dev); 11804 } 11805 11806 cnt = 0; 11807 while (!list_empty(&list)) { 11808 dev = netdev_wait_allrefs_any(&list); 11809 list_del(&dev->todo_list); 11810 11811 /* paranoia */ 11812 BUG_ON(netdev_refcnt_read(dev) != 1); 11813 BUG_ON(!list_empty(&dev->ptype_all)); 11814 BUG_ON(!list_empty(&dev->ptype_specific)); 11815 WARN_ON(rcu_access_pointer(dev->ip_ptr)); 11816 WARN_ON(rcu_access_pointer(dev->ip6_ptr)); 11817 11818 netdev_name_node_alt_flush(dev); 11819 netdev_name_node_free(dev->name_node); 11820 netdev_do_free_pcpu_stats(dev); 11821 if (dev->priv_destructor) 11822 dev->priv_destructor(dev); 11823 if (dev->needs_free_netdev) 11824 free_netdev(dev); 11825 11826 cnt++; 11827 11828 /* Free network device */ 11829 kobject_put(&dev->dev.kobj); 11830 } 11831 if (cnt && atomic_sub_and_test(cnt, &dev_unreg_count)) 11832 wake_up(&netdev_unregistering_wq); 11833 } 11834 11835 /* Collate per-cpu network dstats statistics 11836 * 11837 * Read per-cpu network statistics from dev->dstats and populate the related 11838 * fields in @s. 11839 */ 11840 static void dev_fetch_dstats(struct rtnl_link_stats64 *s, 11841 const struct pcpu_dstats __percpu *dstats) 11842 { 11843 int cpu; 11844 11845 for_each_possible_cpu(cpu) { 11846 u64 rx_packets, rx_bytes, rx_drops; 11847 u64 tx_packets, tx_bytes, tx_drops; 11848 const struct pcpu_dstats *stats; 11849 unsigned int start; 11850 11851 stats = per_cpu_ptr(dstats, cpu); 11852 do { 11853 start = u64_stats_fetch_begin(&stats->syncp); 11854 rx_packets = u64_stats_read(&stats->rx_packets); 11855 rx_bytes = u64_stats_read(&stats->rx_bytes); 11856 rx_drops = u64_stats_read(&stats->rx_drops); 11857 tx_packets = u64_stats_read(&stats->tx_packets); 11858 tx_bytes = u64_stats_read(&stats->tx_bytes); 11859 tx_drops = u64_stats_read(&stats->tx_drops); 11860 } while (u64_stats_fetch_retry(&stats->syncp, start)); 11861 11862 s->rx_packets += rx_packets; 11863 s->rx_bytes += rx_bytes; 11864 s->rx_dropped += rx_drops; 11865 s->tx_packets += tx_packets; 11866 s->tx_bytes += tx_bytes; 11867 s->tx_dropped += tx_drops; 11868 } 11869 } 11870 11871 /* ndo_get_stats64 implementation for dtstats-based accounting. 11872 * 11873 * Populate @s from dev->stats and dev->dstats. This is used internally by the 11874 * core for NETDEV_PCPU_STAT_DSTAT-type stats collection. 11875 */ 11876 static void dev_get_dstats64(const struct net_device *dev, 11877 struct rtnl_link_stats64 *s) 11878 { 11879 netdev_stats_to_stats64(s, &dev->stats); 11880 dev_fetch_dstats(s, dev->dstats); 11881 } 11882 11883 /* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has 11884 * all the same fields in the same order as net_device_stats, with only 11885 * the type differing, but rtnl_link_stats64 may have additional fields 11886 * at the end for newer counters. 11887 */ 11888 void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64, 11889 const struct net_device_stats *netdev_stats) 11890 { 11891 size_t i, n = sizeof(*netdev_stats) / sizeof(atomic_long_t); 11892 const atomic_long_t *src = (atomic_long_t *)netdev_stats; 11893 u64 *dst = (u64 *)stats64; 11894 11895 BUILD_BUG_ON(n > sizeof(*stats64) / sizeof(u64)); 11896 for (i = 0; i < n; i++) 11897 dst[i] = (unsigned long)atomic_long_read(&src[i]); 11898 /* zero out counters that only exist in rtnl_link_stats64 */ 11899 memset((char *)stats64 + n * sizeof(u64), 0, 11900 sizeof(*stats64) - n * sizeof(u64)); 11901 } 11902 EXPORT_SYMBOL(netdev_stats_to_stats64); 11903 11904 static __cold struct net_device_core_stats __percpu *netdev_core_stats_alloc( 11905 struct net_device *dev) 11906 { 11907 struct net_device_core_stats __percpu *p; 11908 11909 p = alloc_percpu_gfp(struct net_device_core_stats, 11910 GFP_ATOMIC | __GFP_NOWARN); 11911 11912 if (p && cmpxchg(&dev->core_stats, NULL, p)) 11913 free_percpu(p); 11914 11915 /* This READ_ONCE() pairs with the cmpxchg() above */ 11916 return READ_ONCE(dev->core_stats); 11917 } 11918 11919 noinline void netdev_core_stats_inc(struct net_device *dev, u32 offset) 11920 { 11921 /* This READ_ONCE() pairs with the write in netdev_core_stats_alloc() */ 11922 struct net_device_core_stats __percpu *p = READ_ONCE(dev->core_stats); 11923 unsigned long __percpu *field; 11924 11925 if (unlikely(!p)) { 11926 p = netdev_core_stats_alloc(dev); 11927 if (!p) 11928 return; 11929 } 11930 11931 field = (unsigned long __percpu *)((void __percpu *)p + offset); 11932 this_cpu_inc(*field); 11933 } 11934 EXPORT_SYMBOL_GPL(netdev_core_stats_inc); 11935 11936 /** 11937 * dev_get_stats - get network device statistics 11938 * @dev: device to get statistics from 11939 * @storage: place to store stats 11940 * 11941 * Get network statistics from device. Return @storage. 11942 * The device driver may provide its own method by setting 11943 * dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats; 11944 * otherwise the internal statistics structure is used. 11945 */ 11946 struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev, 11947 struct rtnl_link_stats64 *storage) 11948 { 11949 const struct net_device_ops *ops = dev->netdev_ops; 11950 const struct net_device_core_stats __percpu *p; 11951 11952 /* 11953 * IPv{4,6} and udp tunnels share common stat helpers and use 11954 * different stat type (NETDEV_PCPU_STAT_TSTATS vs 11955 * NETDEV_PCPU_STAT_DSTATS). Ensure the accounting is consistent. 11956 */ 11957 BUILD_BUG_ON(offsetof(struct pcpu_sw_netstats, rx_bytes) != 11958 offsetof(struct pcpu_dstats, rx_bytes)); 11959 BUILD_BUG_ON(offsetof(struct pcpu_sw_netstats, rx_packets) != 11960 offsetof(struct pcpu_dstats, rx_packets)); 11961 BUILD_BUG_ON(offsetof(struct pcpu_sw_netstats, tx_bytes) != 11962 offsetof(struct pcpu_dstats, tx_bytes)); 11963 BUILD_BUG_ON(offsetof(struct pcpu_sw_netstats, tx_packets) != 11964 offsetof(struct pcpu_dstats, tx_packets)); 11965 11966 if (ops->ndo_get_stats64) { 11967 memset(storage, 0, sizeof(*storage)); 11968 ops->ndo_get_stats64(dev, storage); 11969 } else if (ops->ndo_get_stats) { 11970 netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev)); 11971 } else if (dev->pcpu_stat_type == NETDEV_PCPU_STAT_TSTATS) { 11972 dev_get_tstats64(dev, storage); 11973 } else if (dev->pcpu_stat_type == NETDEV_PCPU_STAT_DSTATS) { 11974 dev_get_dstats64(dev, storage); 11975 } else { 11976 netdev_stats_to_stats64(storage, &dev->stats); 11977 } 11978 11979 /* This READ_ONCE() pairs with the write in netdev_core_stats_alloc() */ 11980 p = READ_ONCE(dev->core_stats); 11981 if (p) { 11982 const struct net_device_core_stats *core_stats; 11983 int i; 11984 11985 for_each_possible_cpu(i) { 11986 core_stats = per_cpu_ptr(p, i); 11987 storage->rx_dropped += READ_ONCE(core_stats->rx_dropped); 11988 storage->tx_dropped += READ_ONCE(core_stats->tx_dropped); 11989 storage->rx_nohandler += READ_ONCE(core_stats->rx_nohandler); 11990 storage->rx_otherhost_dropped += READ_ONCE(core_stats->rx_otherhost_dropped); 11991 } 11992 } 11993 return storage; 11994 } 11995 EXPORT_SYMBOL(dev_get_stats); 11996 11997 /** 11998 * dev_fetch_sw_netstats - get per-cpu network device statistics 11999 * @s: place to store stats 12000 * @netstats: per-cpu network stats to read from 12001 * 12002 * Read per-cpu network statistics and populate the related fields in @s. 12003 */ 12004 void dev_fetch_sw_netstats(struct rtnl_link_stats64 *s, 12005 const struct pcpu_sw_netstats __percpu *netstats) 12006 { 12007 int cpu; 12008 12009 for_each_possible_cpu(cpu) { 12010 u64 rx_packets, rx_bytes, tx_packets, tx_bytes; 12011 const struct pcpu_sw_netstats *stats; 12012 unsigned int start; 12013 12014 stats = per_cpu_ptr(netstats, cpu); 12015 do { 12016 start = u64_stats_fetch_begin(&stats->syncp); 12017 rx_packets = u64_stats_read(&stats->rx_packets); 12018 rx_bytes = u64_stats_read(&stats->rx_bytes); 12019 tx_packets = u64_stats_read(&stats->tx_packets); 12020 tx_bytes = u64_stats_read(&stats->tx_bytes); 12021 } while (u64_stats_fetch_retry(&stats->syncp, start)); 12022 12023 s->rx_packets += rx_packets; 12024 s->rx_bytes += rx_bytes; 12025 s->tx_packets += tx_packets; 12026 s->tx_bytes += tx_bytes; 12027 } 12028 } 12029 EXPORT_SYMBOL_GPL(dev_fetch_sw_netstats); 12030 12031 /** 12032 * dev_get_tstats64 - ndo_get_stats64 implementation 12033 * @dev: device to get statistics from 12034 * @s: place to store stats 12035 * 12036 * Populate @s from dev->stats and dev->tstats. Can be used as 12037 * ndo_get_stats64() callback. 12038 */ 12039 void dev_get_tstats64(struct net_device *dev, struct rtnl_link_stats64 *s) 12040 { 12041 netdev_stats_to_stats64(s, &dev->stats); 12042 dev_fetch_sw_netstats(s, dev->tstats); 12043 } 12044 EXPORT_SYMBOL_GPL(dev_get_tstats64); 12045 12046 struct netdev_queue *dev_ingress_queue_create(struct net_device *dev) 12047 { 12048 struct netdev_queue *queue = dev_ingress_queue(dev); 12049 12050 #ifdef CONFIG_NET_CLS_ACT 12051 if (queue) 12052 return queue; 12053 queue = kzalloc_obj(*queue); 12054 if (!queue) 12055 return NULL; 12056 netdev_init_one_queue(dev, queue, NULL); 12057 RCU_INIT_POINTER(queue->qdisc, &noop_qdisc); 12058 RCU_INIT_POINTER(queue->qdisc_sleeping, &noop_qdisc); 12059 rcu_assign_pointer(dev->ingress_queue, queue); 12060 #endif 12061 return queue; 12062 } 12063 12064 static const struct ethtool_ops default_ethtool_ops; 12065 12066 void netdev_set_default_ethtool_ops(struct net_device *dev, 12067 const struct ethtool_ops *ops) 12068 { 12069 if (dev->ethtool_ops == &default_ethtool_ops) 12070 dev->ethtool_ops = ops; 12071 } 12072 EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops); 12073 12074 /** 12075 * netdev_sw_irq_coalesce_default_on() - enable SW IRQ coalescing by default 12076 * @dev: netdev to enable the IRQ coalescing on 12077 * 12078 * Sets a conservative default for SW IRQ coalescing. Users can use 12079 * sysfs attributes to override the default values. 12080 */ 12081 void netdev_sw_irq_coalesce_default_on(struct net_device *dev) 12082 { 12083 WARN_ON(dev->reg_state == NETREG_REGISTERED); 12084 12085 if (!IS_ENABLED(CONFIG_PREEMPT_RT)) { 12086 netdev_set_gro_flush_timeout(dev, 20000); 12087 netdev_set_defer_hard_irqs(dev, 1); 12088 } 12089 } 12090 EXPORT_SYMBOL_GPL(netdev_sw_irq_coalesce_default_on); 12091 12092 /** 12093 * alloc_netdev_mqs - allocate network device 12094 * @sizeof_priv: size of private data to allocate space for 12095 * @name: device name format string 12096 * @name_assign_type: origin of device name 12097 * @setup: callback to initialize device 12098 * @txqs: the number of TX subqueues to allocate 12099 * @rxqs: the number of RX subqueues to allocate 12100 * 12101 * Allocates a struct net_device with private data area for driver use 12102 * and performs basic initialization. Also allocates subqueue structs 12103 * for each queue on the device. 12104 */ 12105 struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name, 12106 unsigned char name_assign_type, 12107 void (*setup)(struct net_device *), 12108 unsigned int txqs, unsigned int rxqs) 12109 { 12110 struct net_device *dev; 12111 size_t napi_config_sz; 12112 unsigned int maxqs; 12113 12114 BUG_ON(strlen(name) >= sizeof(dev->name)); 12115 12116 if (txqs < 1) { 12117 pr_err("alloc_netdev: Unable to allocate device with zero queues\n"); 12118 return NULL; 12119 } 12120 12121 if (rxqs < 1) { 12122 pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n"); 12123 return NULL; 12124 } 12125 12126 maxqs = max(txqs, rxqs); 12127 12128 dev = kvzalloc_flex(*dev, priv, sizeof_priv, 12129 GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL); 12130 if (!dev) 12131 return NULL; 12132 12133 dev->priv_len = sizeof_priv; 12134 12135 ref_tracker_dir_init(&dev->refcnt_tracker, 128, "netdev"); 12136 #ifdef CONFIG_PCPU_DEV_REFCNT 12137 dev->pcpu_refcnt = alloc_percpu(int); 12138 if (!dev->pcpu_refcnt) 12139 goto free_dev; 12140 __dev_hold(dev); 12141 #else 12142 refcount_set(&dev->dev_refcnt, 1); 12143 #endif 12144 12145 if (dev_addr_init(dev)) 12146 goto free_pcpu; 12147 12148 dev_mc_init(dev); 12149 dev_uc_init(dev); 12150 12151 dev_net_set(dev, &init_net); 12152 12153 dev->gso_max_size = GSO_LEGACY_MAX_SIZE; 12154 dev->xdp_zc_max_segs = 1; 12155 dev->gso_max_segs = GSO_MAX_SEGS; 12156 dev->gro_max_size = GRO_LEGACY_MAX_SIZE; 12157 dev->gso_ipv4_max_size = GSO_LEGACY_MAX_SIZE; 12158 dev->gro_ipv4_max_size = GRO_LEGACY_MAX_SIZE; 12159 dev->tso_max_size = TSO_LEGACY_MAX_SIZE; 12160 dev->tso_max_segs = TSO_MAX_SEGS; 12161 dev->upper_level = 1; 12162 dev->lower_level = 1; 12163 #ifdef CONFIG_LOCKDEP 12164 dev->nested_level = 0; 12165 INIT_LIST_HEAD(&dev->unlink_list); 12166 #endif 12167 12168 INIT_LIST_HEAD(&dev->napi_list); 12169 INIT_LIST_HEAD(&dev->unreg_list); 12170 #ifdef CONFIG_DEBUG_NET_SMALL_RTNL 12171 INIT_LIST_HEAD(&dev->unreg_list_net); 12172 #endif 12173 INIT_LIST_HEAD(&dev->close_list); 12174 INIT_LIST_HEAD(&dev->link_watch_list); 12175 INIT_LIST_HEAD(&dev->adj_list.upper); 12176 INIT_LIST_HEAD(&dev->adj_list.lower); 12177 INIT_LIST_HEAD(&dev->ptype_all); 12178 INIT_LIST_HEAD(&dev->ptype_specific); 12179 INIT_LIST_HEAD(&dev->net_notifier_list); 12180 INIT_LIST_HEAD(&dev->work_node); 12181 #ifdef CONFIG_NET_SCHED 12182 hash_init(dev->qdisc_hash); 12183 #endif 12184 12185 mutex_init(&dev->lock); 12186 netif_rx_mode_init(dev); 12187 12188 dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM; 12189 setup(dev); 12190 12191 if (!dev->tx_queue_len) { 12192 dev->priv_flags |= IFF_NO_QUEUE; 12193 dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN; 12194 } 12195 12196 dev->num_tx_queues = txqs; 12197 dev->real_num_tx_queues = txqs; 12198 if (netif_alloc_netdev_queues(dev)) 12199 goto free_all; 12200 12201 dev->num_rx_queues = rxqs; 12202 dev->real_num_rx_queues = rxqs; 12203 if (netif_alloc_rx_queues(dev)) 12204 goto free_all; 12205 dev->ethtool = kzalloc_obj(*dev->ethtool, GFP_KERNEL_ACCOUNT); 12206 if (!dev->ethtool) 12207 goto free_all; 12208 12209 dev->cfg = kzalloc_obj(*dev->cfg, GFP_KERNEL_ACCOUNT); 12210 if (!dev->cfg) 12211 goto free_all; 12212 dev->cfg_pending = dev->cfg; 12213 12214 dev->num_napi_configs = maxqs; 12215 napi_config_sz = array_size(maxqs, sizeof(*dev->napi_config)); 12216 dev->napi_config = kvzalloc(napi_config_sz, GFP_KERNEL_ACCOUNT); 12217 if (!dev->napi_config) 12218 goto free_all; 12219 12220 strscpy(dev->name, name); 12221 dev->name_assign_type = name_assign_type; 12222 dev->group = INIT_NETDEV_GROUP; 12223 if (!dev->ethtool_ops) 12224 dev->ethtool_ops = &default_ethtool_ops; 12225 12226 nf_hook_netdev_init(dev); 12227 12228 return dev; 12229 12230 free_all: 12231 free_netdev(dev); 12232 return NULL; 12233 12234 free_pcpu: 12235 #ifdef CONFIG_PCPU_DEV_REFCNT 12236 free_percpu(dev->pcpu_refcnt); 12237 free_dev: 12238 #endif 12239 ref_tracker_dir_exit(&dev->refcnt_tracker); 12240 kvfree(dev); 12241 return NULL; 12242 } 12243 EXPORT_SYMBOL(alloc_netdev_mqs); 12244 12245 static void netdev_napi_exit(struct net_device *dev) 12246 { 12247 if (!list_empty(&dev->napi_list)) { 12248 struct napi_struct *p, *n; 12249 12250 netdev_lock(dev); 12251 list_for_each_entry_safe(p, n, &dev->napi_list, dev_list) 12252 __netif_napi_del_locked(p); 12253 netdev_unlock(dev); 12254 12255 synchronize_net(); 12256 } 12257 12258 kvfree(dev->napi_config); 12259 } 12260 12261 /** 12262 * free_netdev - free network device 12263 * @dev: device 12264 * 12265 * This function does the last stage of destroying an allocated device 12266 * interface. The reference to the device object is released. If this 12267 * is the last reference then it will be freed.Must be called in process 12268 * context. 12269 */ 12270 void free_netdev(struct net_device *dev) 12271 { 12272 might_sleep(); 12273 12274 /* When called immediately after register_netdevice() failed the unwind 12275 * handling may still be dismantling the device. Handle that case by 12276 * deferring the free. 12277 */ 12278 if (dev->reg_state == NETREG_UNREGISTERING) { 12279 ASSERT_RTNL(); 12280 dev->needs_free_netdev = true; 12281 return; 12282 } 12283 12284 WARN_ON(dev->cfg != dev->cfg_pending); 12285 kfree(dev->cfg); 12286 kfree(dev->ethtool); 12287 netif_free_tx_queues(dev); 12288 netif_free_rx_queues(dev); 12289 12290 kfree(rcu_dereference_protected(dev->ingress_queue, 1)); 12291 12292 __hw_addr_flush(&dev->rx_mode_addr_cache); 12293 12294 /* Flush device addresses */ 12295 dev_addr_flush(dev); 12296 12297 netdev_napi_exit(dev); 12298 12299 netif_del_cpu_rmap(dev); 12300 12301 ref_tracker_dir_exit(&dev->refcnt_tracker); 12302 #ifdef CONFIG_PCPU_DEV_REFCNT 12303 free_percpu(dev->pcpu_refcnt); 12304 dev->pcpu_refcnt = NULL; 12305 #endif 12306 free_percpu(dev->core_stats); 12307 dev->core_stats = NULL; 12308 free_percpu(dev->xdp_bulkq); 12309 dev->xdp_bulkq = NULL; 12310 12311 netdev_free_phy_link_topology(dev); 12312 12313 mutex_destroy(&dev->lock); 12314 12315 /* Compatibility with error handling in drivers */ 12316 if (dev->reg_state == NETREG_UNINITIALIZED || 12317 dev->reg_state == NETREG_DUMMY) { 12318 kvfree(dev); 12319 return; 12320 } 12321 12322 BUG_ON(dev->reg_state != NETREG_UNREGISTERED); 12323 WRITE_ONCE(dev->reg_state, NETREG_RELEASED); 12324 12325 /* will free via device release */ 12326 put_device(&dev->dev); 12327 } 12328 EXPORT_SYMBOL(free_netdev); 12329 12330 /** 12331 * alloc_netdev_dummy - Allocate and initialize a dummy net device. 12332 * @sizeof_priv: size of private data to allocate space for 12333 * 12334 * Return: the allocated net_device on success, NULL otherwise 12335 */ 12336 struct net_device *alloc_netdev_dummy(int sizeof_priv) 12337 { 12338 return alloc_netdev(sizeof_priv, "dummy#", NET_NAME_UNKNOWN, 12339 init_dummy_netdev); 12340 } 12341 EXPORT_SYMBOL_GPL(alloc_netdev_dummy); 12342 12343 /** 12344 * synchronize_net - Synchronize with packet receive processing 12345 * 12346 * Wait for packets currently being received to be done. 12347 * Does not block later packets from starting. 12348 */ 12349 void synchronize_net(void) 12350 { 12351 might_sleep(); 12352 if (from_cleanup_net() || rtnl_is_locked()) 12353 synchronize_rcu_expedited(); 12354 else 12355 synchronize_rcu(); 12356 } 12357 EXPORT_SYMBOL(synchronize_net); 12358 12359 static void netdev_rss_contexts_free(struct net_device *dev) 12360 { 12361 struct ethtool_rxfh_context *ctx; 12362 unsigned long context; 12363 12364 mutex_lock(&dev->ethtool->rss_lock); 12365 xa_for_each(&dev->ethtool->rss_ctx, context, ctx) { 12366 xa_erase(&dev->ethtool->rss_ctx, context); 12367 dev->ethtool_ops->remove_rxfh_context(dev, ctx, context, NULL); 12368 kfree(ctx); 12369 } 12370 xa_destroy(&dev->ethtool->rss_ctx); 12371 mutex_unlock(&dev->ethtool->rss_lock); 12372 } 12373 12374 /** 12375 * unregister_netdevice_queue - remove device from the kernel 12376 * @dev: device 12377 * @head: list 12378 * 12379 * This function shuts down a device interface and removes it 12380 * from the kernel tables. 12381 * If head not NULL, device is queued to be unregistered later. 12382 * 12383 * Callers must hold the rtnl semaphore. You may want 12384 * unregister_netdev() instead of this. 12385 */ 12386 12387 void unregister_netdevice_queue(struct net_device *dev, struct list_head *head) 12388 { 12389 ASSERT_RTNL(); 12390 12391 #ifdef CONFIG_DEBUG_NET_SMALL_RTNL 12392 DEBUG_NET_WARN_ON_ONCE(!list_empty(&dev->unreg_list_net)); 12393 #endif 12394 12395 if (head) { 12396 list_move_tail(&dev->unreg_list, head); 12397 } else { 12398 LIST_HEAD(single); 12399 12400 list_add(&dev->unreg_list, &single); 12401 unregister_netdevice_many(&single); 12402 } 12403 } 12404 EXPORT_SYMBOL(unregister_netdevice_queue); 12405 12406 static void dev_memory_provider_uninstall(struct net_device *dev) 12407 { 12408 unsigned int i; 12409 12410 for (i = 0; i < dev->real_num_rx_queues; i++) { 12411 struct netdev_rx_queue *rxq = &dev->_rx[i]; 12412 12413 __netif_mp_uninstall_rxq(rxq, &rxq->mp_params); 12414 } 12415 } 12416 12417 /* devices must be UP and netdev_lock()'d */ 12418 static void netif_close_many_and_unlock(struct list_head *close_head) 12419 { 12420 struct net_device *dev, *tmp; 12421 12422 netif_close_many(close_head, false); 12423 12424 /* ... now unlock them */ 12425 list_for_each_entry_safe(dev, tmp, close_head, close_list) { 12426 netdev_unlock(dev); 12427 list_del_init(&dev->close_list); 12428 } 12429 } 12430 12431 static void netif_close_many_and_unlock_cond(struct list_head *close_head) 12432 { 12433 #ifdef CONFIG_LOCKDEP 12434 /* We can only track up to MAX_LOCK_DEPTH locks per task. 12435 * 12436 * Reserve half the available slots for additional locks possibly 12437 * taken by notifiers and (soft)irqs. 12438 */ 12439 unsigned int limit = MAX_LOCK_DEPTH / 2; 12440 12441 if (lockdep_depth(current) > limit) 12442 netif_close_many_and_unlock(close_head); 12443 #endif 12444 } 12445 12446 bool unregister_netdevice_queued(const struct net_device *dev) 12447 { 12448 ASSERT_RTNL(); 12449 return !list_empty(&dev->unreg_list); 12450 } 12451 12452 void unregister_netdevice_many_notify(struct list_head *head, 12453 u32 portid, const struct nlmsghdr *nlh) 12454 { 12455 struct net_device *dev, *tmp; 12456 LIST_HEAD(close_head); 12457 int cnt = 0; 12458 12459 BUG_ON(dev_boot_phase); 12460 ASSERT_RTNL(); 12461 12462 if (list_empty(head)) 12463 return; 12464 12465 list_for_each_entry_safe(dev, tmp, head, unreg_list) { 12466 /* Some devices call without registering 12467 * for initialization unwind. Remove those 12468 * devices and proceed with the remaining. 12469 */ 12470 if (dev->reg_state == NETREG_UNINITIALIZED) { 12471 pr_debug("unregister_netdevice: device %s/%p never was registered\n", 12472 dev->name, dev); 12473 12474 WARN_ON(1); 12475 list_del(&dev->unreg_list); 12476 continue; 12477 } 12478 dev->dismantle = true; 12479 BUG_ON(dev->reg_state != NETREG_REGISTERED); 12480 } 12481 12482 /* If device is running, close it first. Start with ops locked... */ 12483 list_for_each_entry(dev, head, unreg_list) { 12484 if (!(dev->flags & IFF_UP)) 12485 continue; 12486 if (netdev_need_ops_lock(dev)) { 12487 list_add_tail(&dev->close_list, &close_head); 12488 netdev_lock(dev); 12489 } 12490 netif_close_many_and_unlock_cond(&close_head); 12491 } 12492 netif_close_many_and_unlock(&close_head); 12493 /* ... now go over the rest. */ 12494 list_for_each_entry(dev, head, unreg_list) { 12495 if (!netdev_need_ops_lock(dev)) 12496 list_add_tail(&dev->close_list, &close_head); 12497 } 12498 netif_close_many(&close_head, true); 12499 12500 list_for_each_entry(dev, head, unreg_list) { 12501 /* And unlink it from device chain. */ 12502 unlist_netdevice(dev); 12503 netdev_lock(dev); 12504 WRITE_ONCE(dev->reg_state, NETREG_UNREGISTERING); 12505 netdev_unlock(dev); 12506 } 12507 flush_all_backlogs(); 12508 12509 synchronize_net(); 12510 12511 list_for_each_entry(dev, head, unreg_list) { 12512 struct sk_buff *skb = NULL; 12513 12514 /* Shutdown queueing discipline. */ 12515 netdev_lock_ops(dev); 12516 dev_shutdown(dev); 12517 dev_tcx_uninstall(dev); 12518 dev_xdp_uninstall(dev); 12519 dev_memory_provider_uninstall(dev); 12520 netdev_work_cancel_all(dev); 12521 netdev_unlock_ops(dev); 12522 bpf_dev_bound_netdev_unregister(dev); 12523 12524 netdev_offload_xstats_disable_all(dev); 12525 12526 /* Notify protocols, that we are about to destroy 12527 * this device. They should clean all the things. 12528 */ 12529 call_netdevice_notifiers(NETDEV_UNREGISTER, dev); 12530 12531 if (!(dev->rtnl_link_ops && dev->rtnl_link_initializing)) 12532 skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0, 12533 GFP_KERNEL, NULL, 0, 12534 portid, nlh); 12535 12536 /* 12537 * Flush the unicast and multicast chains 12538 */ 12539 dev_uc_flush(dev); 12540 dev_mc_flush(dev); 12541 12542 12543 netdev_rss_contexts_free(dev); 12544 12545 call_netdevice_notifiers(NETDEV_PRE_UNINIT, dev); 12546 12547 if (dev->netdev_ops->ndo_uninit) 12548 dev->netdev_ops->ndo_uninit(dev); 12549 12550 mutex_destroy(&dev->ethtool->rss_lock); 12551 12552 net_shaper_flush_netdev(dev); 12553 12554 if (skb) 12555 rtmsg_ifinfo_send(skb, dev, GFP_KERNEL, portid, nlh); 12556 12557 /* Notifier chain MUST detach us all upper devices. */ 12558 WARN_ON(netdev_has_any_upper_dev(dev)); 12559 WARN_ON(netdev_has_any_lower_dev(dev)); 12560 12561 /* Remove entries from kobject tree */ 12562 netdev_unregister_kobject(dev); 12563 #ifdef CONFIG_XPS 12564 /* Remove XPS queueing entries */ 12565 netif_reset_xps_queues_gt(dev, 0); 12566 #endif 12567 } 12568 12569 synchronize_net(); 12570 12571 list_for_each_entry(dev, head, unreg_list) { 12572 #ifdef CONFIG_DEBUG_NET_SMALL_RTNL 12573 struct net *net = dev_net(dev); 12574 12575 /* spin_lock() can be moved outside of the loop 12576 * once the per-netns RTNL conversion completes. 12577 */ 12578 spin_lock(&net->dev_unreg_lock); 12579 list_del(&dev->unreg_list_net); 12580 spin_unlock(&net->dev_unreg_lock); 12581 #endif 12582 netdev_put(dev, &dev->dev_registered_tracker); 12583 net_set_todo(dev); 12584 cnt++; 12585 } 12586 atomic_add(cnt, &dev_unreg_count); 12587 12588 list_del(head); 12589 } 12590 12591 /** 12592 * unregister_netdevice_many - unregister many devices 12593 * @head: list of devices 12594 * 12595 * Note: As most callers use a stack allocated list_head, 12596 * we force a list_del() to make sure stack won't be corrupted later. 12597 */ 12598 void unregister_netdevice_many(struct list_head *head) 12599 { 12600 unregister_netdevice_many_notify(head, 0, NULL); 12601 } 12602 EXPORT_SYMBOL(unregister_netdevice_many); 12603 12604 #ifdef CONFIG_DEBUG_NET_SMALL_RTNL 12605 void unregister_netdevice_queue_net(struct net *net, struct net_device *dev, 12606 struct list_head *head) 12607 { 12608 netdev_lock(dev); 12609 12610 if (net_eq(dev_net(dev), net)) { 12611 netdev_unlock(dev); 12612 unregister_netdevice_queue(dev, head); 12613 return; 12614 } 12615 12616 net = dev_net(dev); 12617 12618 spin_lock(&net->dev_unreg_lock); 12619 12620 DEBUG_NET_WARN_ON_ONCE(!list_empty(&dev->unreg_list)); 12621 DEBUG_NET_WARN_ON_ONCE(!list_empty(&dev->unreg_list_net)); 12622 12623 list_add_tail(&dev->unreg_list_net, &net->dev_unreg_head); 12624 rtnl_net_queue_work(net); 12625 12626 spin_unlock(&net->dev_unreg_lock); 12627 12628 netdev_unlock(dev); 12629 } 12630 EXPORT_SYMBOL(unregister_netdevice_queue_net); 12631 12632 void unregister_netdevice_queue_many_net(struct net *net, struct list_head *head) 12633 { 12634 struct net_device *dev, *tmp; 12635 12636 spin_lock(&net->dev_unreg_lock); 12637 list_for_each_entry_safe(dev, tmp, head, unreg_list) { 12638 /* Once all cross-netns unregister_netdevice_queue() is 12639 * converted to _net() (or for debugging), remove this check. 12640 */ 12641 if (!net_eq(dev_net(dev), net)) 12642 continue; 12643 12644 DEBUG_NET_WARN_ONCE(!net_eq(dev_net(dev), net), 12645 "%s was unregistered from a different netns.\n", 12646 dev->name); 12647 12648 list_del_init(&dev->unreg_list); 12649 list_move_tail(&dev->unreg_list_net, &net->dev_unreg_head); 12650 } 12651 spin_unlock(&net->dev_unreg_lock); 12652 } 12653 12654 static void unregister_netdevice_move_net(struct net *net_old, 12655 struct net *net, 12656 struct net_device *dev) 12657 { 12658 if (net_old > net) { 12659 spin_lock(&net->dev_unreg_lock); 12660 spin_lock_nested(&net_old->dev_unreg_lock, SINGLE_DEPTH_NESTING); 12661 } else { 12662 spin_lock(&net_old->dev_unreg_lock); 12663 spin_lock_nested(&net->dev_unreg_lock, SINGLE_DEPTH_NESTING); 12664 } 12665 12666 if (!list_empty(&dev->unreg_list_net)) { 12667 list_del(&dev->unreg_list_net); 12668 list_add_tail(&dev->unreg_list_net, &net->dev_unreg_head); 12669 } 12670 12671 spin_unlock(&net_old->dev_unreg_lock); 12672 spin_unlock(&net->dev_unreg_lock); 12673 } 12674 12675 void unregister_netdevice_many_net(struct net *net) 12676 { 12677 struct net_device *dev, *tmp; 12678 LIST_HEAD(unreg_head_net); 12679 LIST_HEAD(unreg_head); 12680 12681 spin_lock(&net->dev_unreg_lock); 12682 list_splice_init(&net->dev_unreg_head, &unreg_head_net); 12683 spin_unlock(&net->dev_unreg_lock); 12684 12685 list_for_each_entry_safe(dev, tmp, &unreg_head_net, unreg_list_net) { 12686 list_del_init(&dev->unreg_list_net); 12687 list_add_tail(&dev->unreg_list, &unreg_head); 12688 } 12689 12690 unregister_netdevice_many(&unreg_head); 12691 } 12692 #endif 12693 12694 /** 12695 * unregister_netdev - remove device from the kernel 12696 * @dev: device 12697 * 12698 * This function shuts down a device interface and removes it 12699 * from the kernel tables. 12700 * 12701 * This is just a wrapper for unregister_netdevice that takes 12702 * the rtnl semaphore. In general you want to use this and not 12703 * unregister_netdevice. 12704 */ 12705 void unregister_netdev(struct net_device *dev) 12706 { 12707 rtnl_net_dev_lock(dev); 12708 unregister_netdevice(dev); 12709 rtnl_net_dev_unlock(dev); 12710 } 12711 EXPORT_SYMBOL(unregister_netdev); 12712 12713 int __dev_change_net_namespace(struct net_device *dev, struct net *net, 12714 const char *pat, int new_ifindex, 12715 struct netlink_ext_ack *extack) 12716 { 12717 struct netdev_name_node *name_node, *tmp; 12718 struct net *net_old = dev_net(dev); 12719 char new_name[IFNAMSIZ] = {}; 12720 int err, new_nsid; 12721 12722 ASSERT_RTNL(); 12723 12724 /* Don't allow namespace local devices to be moved. */ 12725 err = -EINVAL; 12726 if (dev->netns_immutable) { 12727 NL_SET_ERR_MSG(extack, "The interface netns is immutable"); 12728 goto out; 12729 } 12730 12731 /* Ensure the device has been registered */ 12732 if (dev->reg_state != NETREG_REGISTERED) { 12733 NL_SET_ERR_MSG(extack, "The interface isn't registered"); 12734 goto out; 12735 } 12736 12737 /* Get out if there is nothing todo */ 12738 err = 0; 12739 if (net_eq(net_old, net)) 12740 goto out; 12741 12742 /* Pick the destination device name, and ensure 12743 * we can use it in the destination network namespace. 12744 */ 12745 err = -EEXIST; 12746 if (netdev_name_in_use(net, dev->name)) { 12747 /* We get here if we can't use the current device name */ 12748 if (!pat) { 12749 NL_SET_ERR_MSG(extack, 12750 "An interface with the same name exists in the target netns"); 12751 goto out; 12752 } 12753 err = dev_prep_valid_name(net, dev, pat, new_name, EEXIST); 12754 if (err < 0) { 12755 NL_SET_ERR_MSG_FMT(extack, 12756 "Unable to use '%s' for the new interface name in the target netns", 12757 pat); 12758 goto out; 12759 } 12760 } 12761 /* Check that none of the altnames conflicts. */ 12762 err = -EEXIST; 12763 netdev_for_each_altname_safe(dev, name_node, tmp) { 12764 if (!netdev_name_in_use(net, name_node->name)) 12765 continue; 12766 12767 if (!check_net(net_old)) { 12768 __netdev_name_node_alt_destroy(name_node); 12769 continue; 12770 } 12771 12772 NL_SET_ERR_MSG_FMT(extack, 12773 "An interface with the altname %s exists in the target netns", 12774 name_node->name); 12775 goto out; 12776 } 12777 12778 /* Check that new_ifindex isn't used yet. */ 12779 if (new_ifindex) { 12780 err = dev_index_reserve(net, new_ifindex); 12781 if (err < 0) { 12782 NL_SET_ERR_MSG_FMT(extack, 12783 "The ifindex %d is not available in the target netns", 12784 new_ifindex); 12785 goto out; 12786 } 12787 } else { 12788 /* If there is an ifindex conflict assign a new one */ 12789 err = dev_index_reserve(net, dev->ifindex); 12790 if (err == -EBUSY) 12791 err = dev_index_reserve(net, 0); 12792 if (err < 0) { 12793 NL_SET_ERR_MSG(extack, 12794 "Unable to allocate a new ifindex in the target netns"); 12795 goto out; 12796 } 12797 new_ifindex = err; 12798 } 12799 12800 /* 12801 * And now a mini version of register_netdevice unregister_netdevice. 12802 */ 12803 12804 netdev_lock_ops(dev); 12805 /* If device is running close it first. */ 12806 netif_close(dev); 12807 /* And unlink it from device chain */ 12808 unlist_netdevice(dev); 12809 12810 if (!netdev_need_ops_lock(dev)) 12811 netdev_lock(dev); 12812 dev->moving_ns = true; 12813 netdev_unlock(dev); 12814 12815 synchronize_net(); 12816 12817 /* Shutdown queueing discipline. */ 12818 netdev_lock_ops(dev); 12819 dev_shutdown(dev); 12820 netdev_unlock_ops(dev); 12821 12822 /* Notify protocols, that we are about to destroy 12823 * this device. They should clean all the things. 12824 * 12825 * Note that dev->reg_state stays at NETREG_REGISTERED. 12826 * This is wanted because this way 8021q and macvlan know 12827 * the device is just moving and can keep their slaves up. 12828 */ 12829 call_netdevice_notifiers(NETDEV_UNREGISTER, dev); 12830 rcu_barrier(); 12831 12832 new_nsid = peernet2id_alloc(dev_net(dev), net, GFP_KERNEL); 12833 12834 rtmsg_ifinfo_newnet(RTM_DELLINK, dev, ~0U, GFP_KERNEL, &new_nsid, 12835 new_ifindex); 12836 12837 /* 12838 * Flush the unicast and multicast chains 12839 */ 12840 dev_uc_flush(dev); 12841 dev_mc_flush(dev); 12842 12843 /* Send a netdev-removed uevent to the old namespace */ 12844 kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE); 12845 netdev_adjacent_del_links(dev); 12846 12847 /* Move per-net netdevice notifiers that are following the netdevice */ 12848 move_netdevice_notifiers_dev_net(dev, net); 12849 12850 /* Actually switch the network namespace */ 12851 netdev_lock(dev); 12852 dev_net_set(dev, net); 12853 netdev_unlock(dev); 12854 dev->ifindex = new_ifindex; 12855 12856 #ifdef CONFIG_DEBUG_NET_SMALL_RTNL 12857 unregister_netdevice_move_net(net_old, net, dev); 12858 #endif 12859 12860 if (new_name[0]) { 12861 /* Rename the netdev to prepared name */ 12862 write_seqlock_bh(&netdev_rename_lock); 12863 strscpy(dev->name, new_name, IFNAMSIZ); 12864 write_sequnlock_bh(&netdev_rename_lock); 12865 } 12866 12867 /* Fixup kobjects */ 12868 dev_set_uevent_suppress(&dev->dev, 1); 12869 err = device_rename(&dev->dev, dev->name); 12870 dev_set_uevent_suppress(&dev->dev, 0); 12871 WARN_ON(err); 12872 12873 /* Send a netdev-add uevent to the new namespace */ 12874 kobject_uevent(&dev->dev.kobj, KOBJ_ADD); 12875 netdev_adjacent_add_links(dev); 12876 12877 /* Adapt owner in case owning user namespace of target network 12878 * namespace is different from the original one. 12879 */ 12880 err = netdev_change_owner(dev, net_old, net); 12881 WARN_ON(err); 12882 12883 netdev_lock(dev); 12884 dev->moving_ns = false; 12885 if (!netdev_need_ops_lock(dev)) 12886 netdev_unlock(dev); 12887 12888 /* Add the device back in the hashes */ 12889 list_netdevice(dev); 12890 /* Notify protocols, that a new device appeared. */ 12891 call_netdevice_notifiers(NETDEV_REGISTER, dev); 12892 netdev_unlock_ops(dev); 12893 12894 /* 12895 * Prevent userspace races by waiting until the network 12896 * device is fully setup before sending notifications. 12897 */ 12898 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL, 0, NULL); 12899 12900 synchronize_net(); 12901 err = 0; 12902 out: 12903 return err; 12904 } 12905 12906 static int dev_cpu_dead(unsigned int oldcpu) 12907 { 12908 struct sk_buff **list_skb; 12909 struct sk_buff *skb; 12910 unsigned int cpu; 12911 int node; 12912 struct softnet_data *sd, *oldsd, *remsd = NULL; 12913 12914 local_irq_disable(); 12915 cpu = smp_processor_id(); 12916 sd = &per_cpu(softnet_data, cpu); 12917 oldsd = &per_cpu(softnet_data, oldcpu); 12918 12919 /* Find end of our completion_queue. */ 12920 list_skb = &sd->completion_queue; 12921 while (*list_skb) 12922 list_skb = &(*list_skb)->next; 12923 /* Append completion queue from offline CPU. */ 12924 *list_skb = oldsd->completion_queue; 12925 oldsd->completion_queue = NULL; 12926 12927 /* Append output queue from offline CPU. */ 12928 if (oldsd->output_queue) { 12929 *sd->output_queue_tailp = oldsd->output_queue; 12930 sd->output_queue_tailp = oldsd->output_queue_tailp; 12931 oldsd->output_queue = NULL; 12932 oldsd->output_queue_tailp = &oldsd->output_queue; 12933 } 12934 /* Append NAPI poll list from offline CPU, with one exception : 12935 * process_backlog() must be called by cpu owning percpu backlog. 12936 * We properly handle process_queue & input_pkt_queue later. 12937 */ 12938 while (!list_empty(&oldsd->poll_list)) { 12939 struct napi_struct *napi = list_first_entry(&oldsd->poll_list, 12940 struct napi_struct, 12941 poll_list); 12942 12943 list_del_init(&napi->poll_list); 12944 if (napi->poll == process_backlog) 12945 napi->state &= NAPIF_STATE_THREADED; 12946 else 12947 ____napi_schedule(sd, napi); 12948 } 12949 12950 raise_softirq_irqoff(NET_TX_SOFTIRQ); 12951 local_irq_enable(); 12952 12953 if (!use_backlog_threads()) { 12954 #ifdef CONFIG_RPS 12955 remsd = oldsd->rps_ipi_list; 12956 oldsd->rps_ipi_list = NULL; 12957 #endif 12958 /* send out pending IPI's on offline CPU */ 12959 net_rps_send_ipi(remsd); 12960 } 12961 12962 /* Process offline CPU's input_pkt_queue */ 12963 while ((skb = __skb_dequeue(&oldsd->process_queue))) { 12964 netif_rx(skb); 12965 rps_input_queue_head_incr(oldsd); 12966 } 12967 while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) { 12968 netif_rx(skb); 12969 rps_input_queue_head_incr(oldsd); 12970 } 12971 12972 for_each_node(node) 12973 skb_defer_node_flush(per_cpu_ptr(net_hotdata.skb_defer_nodes, 12974 oldcpu) + node); 12975 node = cpu_to_node(oldcpu); 12976 if (node_possible(node) && 12977 !cpumask_intersects(cpumask_of_node(node), cpu_online_mask)) { 12978 for_each_possible_cpu(cpu) 12979 skb_defer_node_flush(per_cpu_ptr(net_hotdata.skb_defer_nodes, 12980 cpu) + node); 12981 } 12982 12983 return 0; 12984 } 12985 12986 /** 12987 * netdev_increment_features - increment feature set by one 12988 * @all: current feature set 12989 * @one: new feature set 12990 * @mask: mask feature set 12991 * 12992 * Computes a new feature set after adding a device with feature set 12993 * @one to the master device with current feature set @all. Will not 12994 * enable anything that is off in @mask. Returns the new feature set. 12995 */ 12996 netdev_features_t netdev_increment_features(netdev_features_t all, 12997 netdev_features_t one, netdev_features_t mask) 12998 { 12999 if (mask & NETIF_F_HW_CSUM) 13000 mask |= NETIF_F_CSUM_MASK; 13001 mask |= NETIF_F_VLAN_CHALLENGED; 13002 13003 all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask; 13004 all &= one | ~NETIF_F_ALL_FOR_ALL; 13005 13006 /* If one device supports hw checksumming, set for all. */ 13007 if (all & NETIF_F_HW_CSUM) 13008 all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM); 13009 13010 return all; 13011 } 13012 EXPORT_SYMBOL(netdev_increment_features); 13013 13014 /** 13015 * netdev_compute_master_upper_features - compute feature from lowers 13016 * @dev: the upper device 13017 * @update_header: whether to update upper device's header_len/headroom/tailroom 13018 * 13019 * Recompute the upper device's feature based on all lower devices. 13020 */ 13021 void netdev_compute_master_upper_features(struct net_device *dev, bool update_header) 13022 { 13023 unsigned int dst_release_flag = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM; 13024 netdev_features_t gso_partial_features = MASTER_UPPER_DEV_GSO_PARTIAL_FEATURES; 13025 netdev_features_t xfrm_features = MASTER_UPPER_DEV_XFRM_FEATURES; 13026 netdev_features_t mpls_features = MASTER_UPPER_DEV_MPLS_FEATURES; 13027 netdev_features_t vlan_features = MASTER_UPPER_DEV_VLAN_FEATURES; 13028 netdev_features_t enc_features = MASTER_UPPER_DEV_ENC_FEATURES; 13029 unsigned short max_header_len = ETH_HLEN; 13030 unsigned int tso_max_size = TSO_MAX_SIZE; 13031 unsigned short max_headroom = 0; 13032 unsigned short max_tailroom = 0; 13033 u16 tso_max_segs = TSO_MAX_SEGS; 13034 struct net_device *lower_dev; 13035 struct list_head *iter; 13036 13037 mpls_features = netdev_base_features(mpls_features); 13038 vlan_features = netdev_base_features(vlan_features); 13039 enc_features = netdev_base_features(enc_features); 13040 13041 netdev_for_each_lower_dev(dev, lower_dev, iter) { 13042 gso_partial_features = netdev_increment_features(gso_partial_features, 13043 lower_dev->gso_partial_features, 13044 MASTER_UPPER_DEV_GSO_PARTIAL_FEATURES); 13045 13046 vlan_features = netdev_increment_features(vlan_features, 13047 lower_dev->vlan_features, 13048 MASTER_UPPER_DEV_VLAN_FEATURES); 13049 13050 enc_features = netdev_increment_features(enc_features, 13051 lower_dev->hw_enc_features, 13052 MASTER_UPPER_DEV_ENC_FEATURES); 13053 13054 if (IS_ENABLED(CONFIG_XFRM_OFFLOAD)) 13055 xfrm_features = netdev_increment_features(xfrm_features, 13056 lower_dev->hw_enc_features, 13057 MASTER_UPPER_DEV_XFRM_FEATURES); 13058 13059 mpls_features = netdev_increment_features(mpls_features, 13060 lower_dev->mpls_features, 13061 MASTER_UPPER_DEV_MPLS_FEATURES); 13062 13063 dst_release_flag &= lower_dev->priv_flags; 13064 13065 if (update_header) { 13066 max_header_len = max(max_header_len, lower_dev->hard_header_len); 13067 max_headroom = max(max_headroom, lower_dev->needed_headroom); 13068 max_tailroom = max(max_tailroom, lower_dev->needed_tailroom); 13069 } 13070 13071 tso_max_size = min(tso_max_size, lower_dev->tso_max_size); 13072 tso_max_segs = min(tso_max_segs, lower_dev->tso_max_segs); 13073 } 13074 13075 dev->gso_partial_features = gso_partial_features; 13076 dev->vlan_features = vlan_features; 13077 dev->hw_enc_features = enc_features | NETIF_F_GSO_ENCAP_ALL | 13078 NETIF_F_HW_VLAN_CTAG_TX | 13079 NETIF_F_HW_VLAN_STAG_TX; 13080 if (IS_ENABLED(CONFIG_XFRM_OFFLOAD)) 13081 dev->hw_enc_features |= xfrm_features; 13082 dev->mpls_features = mpls_features; 13083 13084 dev->priv_flags &= ~IFF_XMIT_DST_RELEASE; 13085 if ((dev->priv_flags & IFF_XMIT_DST_RELEASE_PERM) && 13086 dst_release_flag == (IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM)) 13087 dev->priv_flags |= IFF_XMIT_DST_RELEASE; 13088 13089 if (update_header) { 13090 dev->hard_header_len = max_header_len; 13091 dev->needed_headroom = max_headroom; 13092 dev->needed_tailroom = max_tailroom; 13093 } 13094 13095 netif_set_tso_max_segs(dev, tso_max_segs); 13096 netif_set_tso_max_size(dev, tso_max_size); 13097 13098 netdev_change_features(dev); 13099 } 13100 EXPORT_SYMBOL(netdev_compute_master_upper_features); 13101 13102 static struct hlist_head * __net_init netdev_create_hash(void) 13103 { 13104 int i; 13105 struct hlist_head *hash; 13106 13107 hash = kmalloc_objs(*hash, NETDEV_HASHENTRIES); 13108 if (hash != NULL) 13109 for (i = 0; i < NETDEV_HASHENTRIES; i++) 13110 INIT_HLIST_HEAD(&hash[i]); 13111 13112 return hash; 13113 } 13114 13115 /* Initialize per network namespace state */ 13116 static int __net_init netdev_init(struct net *net) 13117 { 13118 BUILD_BUG_ON(GRO_HASH_BUCKETS > 13119 BITS_PER_BYTE * sizeof_field(struct gro_node, bitmask)); 13120 13121 INIT_LIST_HEAD(&net->dev_base_head); 13122 13123 net->dev_name_head = netdev_create_hash(); 13124 if (net->dev_name_head == NULL) 13125 goto err_name; 13126 13127 net->dev_index_head = netdev_create_hash(); 13128 if (net->dev_index_head == NULL) 13129 goto err_idx; 13130 13131 xa_init_flags(&net->dev_by_index, XA_FLAGS_ALLOC1); 13132 13133 RAW_INIT_NOTIFIER_HEAD(&net->netdev_chain); 13134 13135 return 0; 13136 13137 err_idx: 13138 kfree(net->dev_name_head); 13139 err_name: 13140 return -ENOMEM; 13141 } 13142 13143 /** 13144 * netdev_drivername - network driver for the device 13145 * @dev: network device 13146 * 13147 * Determine network driver for device. 13148 */ 13149 const char *netdev_drivername(const struct net_device *dev) 13150 { 13151 const struct device_driver *driver; 13152 const struct device *parent; 13153 const char *empty = ""; 13154 13155 parent = dev->dev.parent; 13156 if (!parent) 13157 return empty; 13158 13159 driver = parent->driver; 13160 if (driver && driver->name) 13161 return driver->name; 13162 return empty; 13163 } 13164 13165 static void __netdev_printk(const char *level, const struct net_device *dev, 13166 struct va_format *vaf) 13167 { 13168 if (dev && dev->dev.parent) { 13169 dev_printk_emit(level[1] - '0', 13170 dev->dev.parent, 13171 "%s %s %s%s: %pV", 13172 dev_driver_string(dev->dev.parent), 13173 dev_name(dev->dev.parent), 13174 netdev_name(dev), netdev_reg_state(dev), 13175 vaf); 13176 } else if (dev) { 13177 printk("%s%s%s: %pV", 13178 level, netdev_name(dev), netdev_reg_state(dev), vaf); 13179 } else { 13180 printk("%s(NULL net_device): %pV", level, vaf); 13181 } 13182 } 13183 13184 void netdev_printk(const char *level, const struct net_device *dev, 13185 const char *format, ...) 13186 { 13187 struct va_format vaf; 13188 va_list args; 13189 13190 va_start(args, format); 13191 13192 vaf.fmt = format; 13193 vaf.va = &args; 13194 13195 __netdev_printk(level, dev, &vaf); 13196 13197 va_end(args); 13198 } 13199 EXPORT_SYMBOL(netdev_printk); 13200 13201 #define define_netdev_printk_level(func, level) \ 13202 void func(const struct net_device *dev, const char *fmt, ...) \ 13203 { \ 13204 struct va_format vaf; \ 13205 va_list args; \ 13206 \ 13207 va_start(args, fmt); \ 13208 \ 13209 vaf.fmt = fmt; \ 13210 vaf.va = &args; \ 13211 \ 13212 __netdev_printk(level, dev, &vaf); \ 13213 \ 13214 va_end(args); \ 13215 } \ 13216 EXPORT_SYMBOL(func); 13217 13218 define_netdev_printk_level(netdev_emerg, KERN_EMERG); 13219 define_netdev_printk_level(netdev_alert, KERN_ALERT); 13220 define_netdev_printk_level(netdev_crit, KERN_CRIT); 13221 define_netdev_printk_level(netdev_err, KERN_ERR); 13222 define_netdev_printk_level(netdev_warn, KERN_WARNING); 13223 define_netdev_printk_level(netdev_notice, KERN_NOTICE); 13224 define_netdev_printk_level(netdev_info, KERN_INFO); 13225 13226 static void __net_exit netdev_exit(struct net *net) 13227 { 13228 kfree(net->dev_name_head); 13229 kfree(net->dev_index_head); 13230 xa_destroy(&net->dev_by_index); 13231 if (net != &init_net) 13232 WARN_ON_ONCE(!list_empty(&net->dev_base_head)); 13233 } 13234 13235 static struct pernet_operations __net_initdata netdev_net_ops = { 13236 .init = netdev_init, 13237 .exit = netdev_exit, 13238 }; 13239 13240 static void __net_exit default_device_exit_net(struct net *net) 13241 { 13242 struct net_device *dev, *aux; 13243 /* 13244 * Push all migratable network devices back to the 13245 * initial network namespace 13246 */ 13247 13248 for_each_netdev_safe(net, dev, aux) { 13249 int err; 13250 char fb_name[IFNAMSIZ]; 13251 13252 /* Ignore unmoveable devices (i.e. loopback) */ 13253 if (dev->netns_immutable) 13254 continue; 13255 13256 /* Leave virtual devices for the generic cleanup */ 13257 if (dev->rtnl_link_ops && !dev->rtnl_link_ops->netns_refund) 13258 continue; 13259 13260 /* Push remaining network devices to init_net */ 13261 snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex); 13262 if (netdev_name_in_use(&init_net, fb_name)) 13263 snprintf(fb_name, IFNAMSIZ, "dev%%d"); 13264 13265 err = dev_change_net_namespace(dev, &init_net, fb_name); 13266 if (err) { 13267 pr_emerg("%s: failed to move %s to init_net: %d\n", 13268 __func__, dev->name, err); 13269 BUG(); 13270 } 13271 } 13272 } 13273 13274 static void __net_exit default_device_exit_batch(struct list_head *net_list) 13275 { 13276 /* At exit all network devices most be removed from a network 13277 * namespace. Do this in the reverse order of registration. 13278 * Do this across as many network namespaces as possible to 13279 * improve batching efficiency. 13280 */ 13281 struct net_device *dev; 13282 struct net *net; 13283 LIST_HEAD(dev_kill_list); 13284 13285 rtnl_lock(); 13286 13287 __rtnl_net_lock(&init_net); 13288 13289 list_for_each_entry(net, net_list, exit_list) { 13290 __rtnl_net_lock(net); 13291 default_device_exit_net(net); 13292 __rtnl_net_unlock(net); 13293 13294 cond_resched(); 13295 } 13296 13297 __rtnl_net_unlock(&init_net); 13298 13299 list_for_each_entry(net, net_list, exit_list) { 13300 __rtnl_net_lock(net); 13301 13302 for_each_netdev_reverse(net, dev) { 13303 if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink) 13304 dev->rtnl_link_ops->dellink(dev, &dev_kill_list); 13305 else 13306 unregister_netdevice_queue(dev, &dev_kill_list); 13307 } 13308 13309 unregister_netdevice_queue_many_net(net, &dev_kill_list); 13310 __rtnl_net_unlock(net); 13311 } 13312 unregister_netdevice_many(&dev_kill_list); 13313 rtnl_unlock(); 13314 13315 rtnl_net_flush_workqueue(); 13316 } 13317 13318 static struct pernet_operations __net_initdata default_device_ops = { 13319 .exit_batch = default_device_exit_batch, 13320 }; 13321 13322 static void __init net_dev_struct_check(void) 13323 { 13324 /* TX read-mostly hotpath */ 13325 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, priv_flags_fast); 13326 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, netdev_ops); 13327 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, header_ops); 13328 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, _tx); 13329 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, real_num_tx_queues); 13330 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_max_size); 13331 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_ipv4_max_size); 13332 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_max_segs); 13333 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_partial_features); 13334 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, num_tc); 13335 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, mtu); 13336 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, needed_headroom); 13337 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, tc_to_txq); 13338 #ifdef CONFIG_XPS 13339 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, xps_maps); 13340 #endif 13341 #ifdef CONFIG_NETFILTER_EGRESS 13342 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, nf_hooks_egress); 13343 #endif 13344 #ifdef CONFIG_NET_XGRESS 13345 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, tcx_egress); 13346 #endif 13347 CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_tx, 160); 13348 13349 /* TXRX read-mostly hotpath */ 13350 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, lstats); 13351 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, state); 13352 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, flags); 13353 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, hard_header_len); 13354 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, features); 13355 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, ip6_ptr); 13356 CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_txrx, 46); 13357 13358 /* RX read-mostly hotpath */ 13359 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, ptype_specific); 13360 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, ifindex); 13361 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, real_num_rx_queues); 13362 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, _rx); 13363 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, gro_max_size); 13364 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, gro_ipv4_max_size); 13365 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, rx_handler); 13366 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, rx_handler_data); 13367 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, nd_net); 13368 #ifdef CONFIG_NETPOLL 13369 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, npinfo); 13370 #endif 13371 #ifdef CONFIG_NET_XGRESS 13372 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, tcx_ingress); 13373 #endif 13374 CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_rx, 92); 13375 } 13376 13377 /* 13378 * Initialize the DEV module. At boot time this walks the device list and 13379 * unhooks any devices that fail to initialise (normally hardware not 13380 * present) and leaves us with a valid list of present and active devices. 13381 * 13382 */ 13383 13384 /* We allocate 256 pages for each CPU if PAGE_SHIFT is 12 */ 13385 #define SYSTEM_PERCPU_PAGE_POOL_SIZE ((1 << 20) / PAGE_SIZE) 13386 13387 static int net_page_pool_create(int cpuid) 13388 { 13389 #if IS_ENABLED(CONFIG_PAGE_POOL) 13390 struct page_pool_params page_pool_params = { 13391 .pool_size = SYSTEM_PERCPU_PAGE_POOL_SIZE, 13392 .flags = PP_FLAG_SYSTEM_POOL, 13393 .nid = cpu_to_mem(cpuid), 13394 }; 13395 struct page_pool *pp_ptr; 13396 int err; 13397 13398 pp_ptr = page_pool_create_percpu(&page_pool_params, cpuid); 13399 if (IS_ERR(pp_ptr)) 13400 return -ENOMEM; 13401 13402 err = xdp_reg_page_pool(pp_ptr); 13403 if (err) { 13404 page_pool_destroy(pp_ptr); 13405 return err; 13406 } 13407 13408 per_cpu(system_page_pool.pool, cpuid) = pp_ptr; 13409 #endif 13410 return 0; 13411 } 13412 13413 static int backlog_napi_should_run(unsigned int cpu) 13414 { 13415 struct softnet_data *sd = per_cpu_ptr(&softnet_data, cpu); 13416 struct napi_struct *napi = &sd->backlog; 13417 13418 return test_bit(NAPI_STATE_SCHED_THREADED, &napi->state); 13419 } 13420 13421 static void run_backlog_napi(unsigned int cpu) 13422 { 13423 struct softnet_data *sd = per_cpu_ptr(&softnet_data, cpu); 13424 13425 napi_threaded_poll_loop(&sd->backlog, NULL); 13426 } 13427 13428 static void backlog_napi_setup(unsigned int cpu) 13429 { 13430 struct softnet_data *sd = per_cpu_ptr(&softnet_data, cpu); 13431 struct napi_struct *napi = &sd->backlog; 13432 13433 napi->thread = this_cpu_read(backlog_napi); 13434 set_bit(NAPI_STATE_THREADED, &napi->state); 13435 } 13436 13437 static struct smp_hotplug_thread backlog_threads = { 13438 .store = &backlog_napi, 13439 .thread_should_run = backlog_napi_should_run, 13440 .thread_fn = run_backlog_napi, 13441 .thread_comm = "backlog_napi/%u", 13442 .setup = backlog_napi_setup, 13443 }; 13444 13445 /* 13446 * This is called single threaded during boot, so no need 13447 * to take the rtnl semaphore. 13448 */ 13449 static int __init net_dev_init(void) 13450 { 13451 int i, rc = -ENOMEM; 13452 13453 BUG_ON(!dev_boot_phase); 13454 13455 net_dev_struct_check(); 13456 13457 if (dev_proc_init()) 13458 goto out; 13459 13460 if (netdev_kobject_init()) 13461 goto out; 13462 13463 for (i = 0; i < PTYPE_HASH_SIZE; i++) 13464 INIT_LIST_HEAD(&ptype_base[i]); 13465 13466 if (register_pernet_subsys(&netdev_net_ops)) 13467 goto out; 13468 13469 /* 13470 * Initialise the packet receive queues. 13471 */ 13472 13473 flush_backlogs_fallback = flush_backlogs_alloc(); 13474 if (!flush_backlogs_fallback) 13475 goto out; 13476 13477 for_each_possible_cpu(i) { 13478 struct softnet_data *sd = &per_cpu(softnet_data, i); 13479 13480 skb_queue_head_init(&sd->input_pkt_queue); 13481 skb_queue_head_init(&sd->process_queue); 13482 #ifdef CONFIG_XFRM_OFFLOAD 13483 skb_queue_head_init(&sd->xfrm_backlog); 13484 #endif 13485 INIT_LIST_HEAD(&sd->poll_list); 13486 sd->output_queue_tailp = &sd->output_queue; 13487 #ifdef CONFIG_RPS 13488 INIT_CSD(&sd->csd, rps_trigger_softirq, sd); 13489 sd->cpu = i; 13490 #endif 13491 INIT_CSD(&sd->defer_csd, trigger_rx_softirq, sd); 13492 13493 gro_init(&sd->backlog.gro); 13494 sd->backlog.poll = process_backlog; 13495 sd->backlog.weight = weight_p; 13496 INIT_LIST_HEAD(&sd->backlog.poll_list); 13497 13498 if (net_page_pool_create(i)) 13499 goto out; 13500 } 13501 net_hotdata.skb_defer_nodes = 13502 __alloc_percpu(sizeof(struct skb_defer_node) * nr_node_ids, 13503 __alignof__(struct skb_defer_node)); 13504 if (!net_hotdata.skb_defer_nodes) 13505 goto out; 13506 if (use_backlog_threads()) 13507 smpboot_register_percpu_thread(&backlog_threads); 13508 13509 dev_boot_phase = 0; 13510 13511 /* The loopback device is special if any other network devices 13512 * is present in a network namespace the loopback device must 13513 * be present. Since we now dynamically allocate and free the 13514 * loopback device ensure this invariant is maintained by 13515 * keeping the loopback device as the first device on the 13516 * list of network devices. Ensuring the loopback devices 13517 * is the first device that appears and the last network device 13518 * that disappears. 13519 */ 13520 if (register_pernet_device(&loopback_net_ops)) 13521 goto out; 13522 13523 if (register_pernet_device(&default_device_ops)) 13524 goto out; 13525 13526 open_softirq(NET_TX_SOFTIRQ, net_tx_action); 13527 open_softirq(NET_RX_SOFTIRQ, net_rx_action); 13528 13529 rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead", 13530 NULL, dev_cpu_dead); 13531 WARN_ON(rc < 0); 13532 rc = 0; 13533 13534 /* avoid static key IPIs to isolated CPUs */ 13535 if (housekeeping_enabled(HK_TYPE_MISC)) 13536 net_enable_timestamp(); 13537 out: 13538 if (rc < 0) { 13539 for_each_possible_cpu(i) { 13540 struct page_pool *pp_ptr; 13541 13542 pp_ptr = per_cpu(system_page_pool.pool, i); 13543 if (!pp_ptr) 13544 continue; 13545 13546 xdp_unreg_page_pool(pp_ptr); 13547 page_pool_destroy(pp_ptr); 13548 per_cpu(system_page_pool.pool, i) = NULL; 13549 } 13550 } 13551 13552 return rc; 13553 } 13554 13555 subsys_initcall(net_dev_init); 13556