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