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