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