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