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