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 inline 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 (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 (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 (*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 (*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 (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 (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 (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 (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 } else { 7094 msleep(20); 7095 continue; 7096 } 7097 7098 if (try_cmpxchg(&napi->state, &val, new)) 7099 break; 7100 } 7101 7102 /* Once STATE_THREADED is unset, wait for SCHED_THREADED to be unset by 7103 * the kthread. 7104 */ 7105 while (true) { 7106 if (!test_bit(NAPI_STATE_SCHED_THREADED, &napi->state)) 7107 break; 7108 7109 msleep(20); 7110 } 7111 7112 kthread_stop(napi->thread); 7113 napi->thread = NULL; 7114 } 7115 7116 int napi_set_threaded(struct napi_struct *napi, 7117 enum netdev_napi_threaded threaded) 7118 { 7119 if (threaded) { 7120 if (!napi->thread) { 7121 int err = napi_kthread_create(napi); 7122 7123 if (err) 7124 return err; 7125 } 7126 } 7127 7128 if (napi->config) 7129 napi->config->threaded = threaded; 7130 7131 /* Setting/unsetting threaded mode on a napi might not immediately 7132 * take effect, if the current napi instance is actively being 7133 * polled. In this case, the switch between threaded mode and 7134 * softirq mode will happen in the next round of napi_schedule(). 7135 * This should not cause hiccups/stalls to the live traffic. 7136 */ 7137 if (!threaded && napi->thread) { 7138 napi_stop_kthread(napi); 7139 } else { 7140 /* Make sure kthread is created before THREADED bit is set. */ 7141 smp_mb__before_atomic(); 7142 assign_bit(NAPI_STATE_THREADED, &napi->state, threaded); 7143 } 7144 7145 return 0; 7146 } 7147 7148 int netif_set_threaded(struct net_device *dev, 7149 enum netdev_napi_threaded threaded) 7150 { 7151 struct napi_struct *napi; 7152 int i, err = 0; 7153 7154 netdev_assert_locked_or_invisible(dev); 7155 7156 if (threaded) { 7157 list_for_each_entry(napi, &dev->napi_list, dev_list) { 7158 if (!napi->thread) { 7159 err = napi_kthread_create(napi); 7160 if (err) { 7161 threaded = NETDEV_NAPI_THREADED_DISABLED; 7162 break; 7163 } 7164 } 7165 } 7166 } 7167 7168 WRITE_ONCE(dev->threaded, threaded); 7169 7170 /* The error should not occur as the kthreads are already created. */ 7171 list_for_each_entry(napi, &dev->napi_list, dev_list) 7172 WARN_ON_ONCE(napi_set_threaded(napi, threaded)); 7173 7174 /* Override the config for all NAPIs even if currently not listed */ 7175 for (i = 0; i < dev->num_napi_configs; i++) 7176 dev->napi_config[i].threaded = threaded; 7177 7178 return err; 7179 } 7180 7181 /** 7182 * netif_threaded_enable() - enable threaded NAPIs 7183 * @dev: net_device instance 7184 * 7185 * Enable threaded mode for the NAPI instances of the device. This may be useful 7186 * for devices where multiple NAPI instances get scheduled by a single 7187 * interrupt. Threaded NAPI allows moving the NAPI processing to cores other 7188 * than the core where IRQ is mapped. 7189 * 7190 * This function should be called before @dev is registered. 7191 */ 7192 void netif_threaded_enable(struct net_device *dev) 7193 { 7194 WARN_ON_ONCE(netif_set_threaded(dev, NETDEV_NAPI_THREADED_ENABLED)); 7195 } 7196 EXPORT_SYMBOL(netif_threaded_enable); 7197 7198 /** 7199 * netif_queue_set_napi - Associate queue with the napi 7200 * @dev: device to which NAPI and queue belong 7201 * @queue_index: Index of queue 7202 * @type: queue type as RX or TX 7203 * @napi: NAPI context, pass NULL to clear previously set NAPI 7204 * 7205 * Set queue with its corresponding napi context. This should be done after 7206 * registering the NAPI handler for the queue-vector and the queues have been 7207 * mapped to the corresponding interrupt vector. 7208 */ 7209 void netif_queue_set_napi(struct net_device *dev, unsigned int queue_index, 7210 enum netdev_queue_type type, struct napi_struct *napi) 7211 { 7212 struct netdev_rx_queue *rxq; 7213 struct netdev_queue *txq; 7214 7215 if (WARN_ON_ONCE(napi && !napi->dev)) 7216 return; 7217 netdev_ops_assert_locked_or_invisible(dev); 7218 7219 switch (type) { 7220 case NETDEV_QUEUE_TYPE_RX: 7221 rxq = __netif_get_rx_queue(dev, queue_index); 7222 rxq->napi = napi; 7223 return; 7224 case NETDEV_QUEUE_TYPE_TX: 7225 txq = netdev_get_tx_queue(dev, queue_index); 7226 txq->napi = napi; 7227 return; 7228 default: 7229 return; 7230 } 7231 } 7232 EXPORT_SYMBOL(netif_queue_set_napi); 7233 7234 static void 7235 netif_napi_irq_notify(struct irq_affinity_notify *notify, 7236 const cpumask_t *mask) 7237 { 7238 struct napi_struct *napi = 7239 container_of(notify, struct napi_struct, notify); 7240 #ifdef CONFIG_RFS_ACCEL 7241 struct cpu_rmap *rmap = napi->dev->rx_cpu_rmap; 7242 int err; 7243 #endif 7244 7245 if (napi->config && napi->dev->irq_affinity_auto) 7246 cpumask_copy(&napi->config->affinity_mask, mask); 7247 7248 #ifdef CONFIG_RFS_ACCEL 7249 if (napi->dev->rx_cpu_rmap_auto) { 7250 err = cpu_rmap_update(rmap, napi->napi_rmap_idx, mask); 7251 if (err) 7252 netdev_warn(napi->dev, "RMAP update failed (%d)\n", 7253 err); 7254 } 7255 #endif 7256 } 7257 7258 #ifdef CONFIG_RFS_ACCEL 7259 static void netif_napi_affinity_release(struct kref *ref) 7260 { 7261 struct napi_struct *napi = 7262 container_of(ref, struct napi_struct, notify.kref); 7263 struct cpu_rmap *rmap = napi->dev->rx_cpu_rmap; 7264 7265 netdev_assert_locked(napi->dev); 7266 WARN_ON(test_and_clear_bit(NAPI_STATE_HAS_NOTIFIER, 7267 &napi->state)); 7268 7269 if (!napi->dev->rx_cpu_rmap_auto) 7270 return; 7271 rmap->obj[napi->napi_rmap_idx] = NULL; 7272 napi->napi_rmap_idx = -1; 7273 cpu_rmap_put(rmap); 7274 } 7275 7276 int netif_enable_cpu_rmap(struct net_device *dev, unsigned int num_irqs) 7277 { 7278 if (dev->rx_cpu_rmap_auto) 7279 return 0; 7280 7281 dev->rx_cpu_rmap = alloc_irq_cpu_rmap(num_irqs); 7282 if (!dev->rx_cpu_rmap) 7283 return -ENOMEM; 7284 7285 dev->rx_cpu_rmap_auto = true; 7286 return 0; 7287 } 7288 EXPORT_SYMBOL(netif_enable_cpu_rmap); 7289 7290 static void netif_del_cpu_rmap(struct net_device *dev) 7291 { 7292 struct cpu_rmap *rmap = dev->rx_cpu_rmap; 7293 7294 if (!dev->rx_cpu_rmap_auto) 7295 return; 7296 7297 /* Free the rmap */ 7298 cpu_rmap_put(rmap); 7299 dev->rx_cpu_rmap = NULL; 7300 dev->rx_cpu_rmap_auto = false; 7301 } 7302 7303 #else 7304 static void netif_napi_affinity_release(struct kref *ref) 7305 { 7306 } 7307 7308 int netif_enable_cpu_rmap(struct net_device *dev, unsigned int num_irqs) 7309 { 7310 return 0; 7311 } 7312 EXPORT_SYMBOL(netif_enable_cpu_rmap); 7313 7314 static void netif_del_cpu_rmap(struct net_device *dev) 7315 { 7316 } 7317 #endif 7318 7319 void netif_set_affinity_auto(struct net_device *dev) 7320 { 7321 unsigned int i, maxqs, numa; 7322 7323 maxqs = max(dev->num_tx_queues, dev->num_rx_queues); 7324 numa = dev_to_node(&dev->dev); 7325 7326 for (i = 0; i < maxqs; i++) 7327 cpumask_set_cpu(cpumask_local_spread(i, numa), 7328 &dev->napi_config[i].affinity_mask); 7329 7330 dev->irq_affinity_auto = true; 7331 } 7332 EXPORT_SYMBOL(netif_set_affinity_auto); 7333 7334 void netif_napi_set_irq_locked(struct napi_struct *napi, int irq) 7335 { 7336 int rc; 7337 7338 netdev_assert_locked_or_invisible(napi->dev); 7339 7340 if (napi->irq == irq) 7341 return; 7342 7343 /* Remove existing resources */ 7344 if (test_and_clear_bit(NAPI_STATE_HAS_NOTIFIER, &napi->state)) 7345 irq_set_affinity_notifier(napi->irq, NULL); 7346 7347 napi->irq = irq; 7348 if (irq < 0 || 7349 (!napi->dev->rx_cpu_rmap_auto && !napi->dev->irq_affinity_auto)) 7350 return; 7351 7352 /* Abort for buggy drivers */ 7353 if (napi->dev->irq_affinity_auto && WARN_ON_ONCE(!napi->config)) 7354 return; 7355 7356 #ifdef CONFIG_RFS_ACCEL 7357 if (napi->dev->rx_cpu_rmap_auto) { 7358 rc = cpu_rmap_add(napi->dev->rx_cpu_rmap, napi); 7359 if (rc < 0) 7360 return; 7361 7362 cpu_rmap_get(napi->dev->rx_cpu_rmap); 7363 napi->napi_rmap_idx = rc; 7364 } 7365 #endif 7366 7367 /* Use core IRQ notifier */ 7368 napi->notify.notify = netif_napi_irq_notify; 7369 napi->notify.release = netif_napi_affinity_release; 7370 rc = irq_set_affinity_notifier(irq, &napi->notify); 7371 if (rc) { 7372 netdev_warn(napi->dev, "Unable to set IRQ notifier (%d)\n", 7373 rc); 7374 goto put_rmap; 7375 } 7376 7377 set_bit(NAPI_STATE_HAS_NOTIFIER, &napi->state); 7378 return; 7379 7380 put_rmap: 7381 #ifdef CONFIG_RFS_ACCEL 7382 if (napi->dev->rx_cpu_rmap_auto) { 7383 napi->dev->rx_cpu_rmap->obj[napi->napi_rmap_idx] = NULL; 7384 cpu_rmap_put(napi->dev->rx_cpu_rmap); 7385 napi->napi_rmap_idx = -1; 7386 } 7387 #endif 7388 napi->notify.notify = NULL; 7389 napi->notify.release = NULL; 7390 } 7391 EXPORT_SYMBOL(netif_napi_set_irq_locked); 7392 7393 static void napi_restore_config(struct napi_struct *n) 7394 { 7395 n->defer_hard_irqs = n->config->defer_hard_irqs; 7396 n->gro_flush_timeout = n->config->gro_flush_timeout; 7397 n->irq_suspend_timeout = n->config->irq_suspend_timeout; 7398 7399 if (n->dev->irq_affinity_auto && 7400 test_bit(NAPI_STATE_HAS_NOTIFIER, &n->state)) 7401 irq_set_affinity(n->irq, &n->config->affinity_mask); 7402 7403 /* a NAPI ID might be stored in the config, if so use it. if not, use 7404 * napi_hash_add to generate one for us. 7405 */ 7406 if (n->config->napi_id) { 7407 napi_hash_add_with_id(n, n->config->napi_id); 7408 } else { 7409 napi_hash_add(n); 7410 n->config->napi_id = n->napi_id; 7411 } 7412 7413 WARN_ON_ONCE(napi_set_threaded(n, n->config->threaded)); 7414 } 7415 7416 static void napi_save_config(struct napi_struct *n) 7417 { 7418 n->config->defer_hard_irqs = n->defer_hard_irqs; 7419 n->config->gro_flush_timeout = n->gro_flush_timeout; 7420 n->config->irq_suspend_timeout = n->irq_suspend_timeout; 7421 napi_hash_del(n); 7422 } 7423 7424 /* Netlink wants the NAPI list to be sorted by ID, if adding a NAPI which will 7425 * inherit an existing ID try to insert it at the right position. 7426 */ 7427 static void 7428 netif_napi_dev_list_add(struct net_device *dev, struct napi_struct *napi) 7429 { 7430 unsigned int new_id, pos_id; 7431 struct list_head *higher; 7432 struct napi_struct *pos; 7433 7434 new_id = UINT_MAX; 7435 if (napi->config && napi->config->napi_id) 7436 new_id = napi->config->napi_id; 7437 7438 higher = &dev->napi_list; 7439 list_for_each_entry(pos, &dev->napi_list, dev_list) { 7440 if (napi_id_valid(pos->napi_id)) 7441 pos_id = pos->napi_id; 7442 else if (pos->config) 7443 pos_id = pos->config->napi_id; 7444 else 7445 pos_id = UINT_MAX; 7446 7447 if (pos_id <= new_id) 7448 break; 7449 higher = &pos->dev_list; 7450 } 7451 list_add_rcu(&napi->dev_list, higher); /* adds after higher */ 7452 } 7453 7454 /* Double check that napi_get_frags() allocates skbs with 7455 * skb->head being backed by slab, not a page fragment. 7456 * This is to make sure bug fixed in 3226b158e67c 7457 * ("net: avoid 32 x truesize under-estimation for tiny skbs") 7458 * does not accidentally come back. 7459 */ 7460 static void napi_get_frags_check(struct napi_struct *napi) 7461 { 7462 struct sk_buff *skb; 7463 7464 local_bh_disable(); 7465 skb = napi_get_frags(napi); 7466 WARN_ON_ONCE(skb && skb->head_frag); 7467 napi_free_frags(napi); 7468 local_bh_enable(); 7469 } 7470 7471 void netif_napi_add_weight_locked(struct net_device *dev, 7472 struct napi_struct *napi, 7473 int (*poll)(struct napi_struct *, int), 7474 int weight) 7475 { 7476 netdev_assert_locked(dev); 7477 if (WARN_ON(test_and_set_bit(NAPI_STATE_LISTED, &napi->state))) 7478 return; 7479 7480 INIT_LIST_HEAD(&napi->poll_list); 7481 INIT_HLIST_NODE(&napi->napi_hash_node); 7482 hrtimer_setup(&napi->timer, napi_watchdog, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED); 7483 gro_init(&napi->gro); 7484 napi->skb = NULL; 7485 napi->poll = poll; 7486 if (weight > NAPI_POLL_WEIGHT) 7487 netdev_err_once(dev, "%s() called with weight %d\n", __func__, 7488 weight); 7489 napi->weight = weight; 7490 napi->dev = dev; 7491 #ifdef CONFIG_NETPOLL 7492 napi->poll_owner = -1; 7493 #endif 7494 napi->list_owner = -1; 7495 set_bit(NAPI_STATE_SCHED, &napi->state); 7496 set_bit(NAPI_STATE_NPSVC, &napi->state); 7497 netif_napi_dev_list_add(dev, napi); 7498 7499 /* default settings from sysfs are applied to all NAPIs. any per-NAPI 7500 * configuration will be loaded in napi_enable 7501 */ 7502 napi_set_defer_hard_irqs(napi, READ_ONCE(dev->napi_defer_hard_irqs)); 7503 napi_set_gro_flush_timeout(napi, READ_ONCE(dev->gro_flush_timeout)); 7504 7505 napi_get_frags_check(napi); 7506 /* Create kthread for this napi if dev->threaded is set. 7507 * Clear dev->threaded if kthread creation failed so that 7508 * threaded mode will not be enabled in napi_enable(). 7509 */ 7510 if (napi_get_threaded_config(dev, napi)) 7511 if (napi_kthread_create(napi)) 7512 dev->threaded = NETDEV_NAPI_THREADED_DISABLED; 7513 netif_napi_set_irq_locked(napi, -1); 7514 } 7515 EXPORT_SYMBOL(netif_napi_add_weight_locked); 7516 7517 void napi_disable_locked(struct napi_struct *n) 7518 { 7519 unsigned long val, new; 7520 7521 might_sleep(); 7522 netdev_assert_locked(n->dev); 7523 7524 set_bit(NAPI_STATE_DISABLE, &n->state); 7525 7526 val = READ_ONCE(n->state); 7527 do { 7528 while (val & (NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC)) { 7529 usleep_range(20, 200); 7530 val = READ_ONCE(n->state); 7531 } 7532 7533 new = val | NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC; 7534 new &= ~(NAPIF_STATE_THREADED | NAPIF_STATE_PREFER_BUSY_POLL); 7535 } while (!try_cmpxchg(&n->state, &val, new)); 7536 7537 hrtimer_cancel(&n->timer); 7538 7539 if (n->config) 7540 napi_save_config(n); 7541 else 7542 napi_hash_del(n); 7543 7544 clear_bit(NAPI_STATE_DISABLE, &n->state); 7545 } 7546 EXPORT_SYMBOL(napi_disable_locked); 7547 7548 /** 7549 * napi_disable() - prevent NAPI from scheduling 7550 * @n: NAPI context 7551 * 7552 * Stop NAPI from being scheduled on this context. 7553 * Waits till any outstanding processing completes. 7554 * Takes netdev_lock() for associated net_device. 7555 */ 7556 void napi_disable(struct napi_struct *n) 7557 { 7558 netdev_lock(n->dev); 7559 napi_disable_locked(n); 7560 netdev_unlock(n->dev); 7561 } 7562 EXPORT_SYMBOL(napi_disable); 7563 7564 void napi_enable_locked(struct napi_struct *n) 7565 { 7566 unsigned long new, val = READ_ONCE(n->state); 7567 7568 if (n->config) 7569 napi_restore_config(n); 7570 else 7571 napi_hash_add(n); 7572 7573 do { 7574 BUG_ON(!test_bit(NAPI_STATE_SCHED, &val)); 7575 7576 new = val & ~(NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC); 7577 if (n->dev->threaded && n->thread) 7578 new |= NAPIF_STATE_THREADED; 7579 } while (!try_cmpxchg(&n->state, &val, new)); 7580 } 7581 EXPORT_SYMBOL(napi_enable_locked); 7582 7583 /** 7584 * napi_enable() - enable NAPI scheduling 7585 * @n: NAPI context 7586 * 7587 * Enable scheduling of a NAPI instance. 7588 * Must be paired with napi_disable(). 7589 * Takes netdev_lock() for associated net_device. 7590 */ 7591 void napi_enable(struct napi_struct *n) 7592 { 7593 netdev_lock(n->dev); 7594 napi_enable_locked(n); 7595 netdev_unlock(n->dev); 7596 } 7597 EXPORT_SYMBOL(napi_enable); 7598 7599 /* Must be called in process context */ 7600 void __netif_napi_del_locked(struct napi_struct *napi) 7601 { 7602 netdev_assert_locked(napi->dev); 7603 7604 if (!test_and_clear_bit(NAPI_STATE_LISTED, &napi->state)) 7605 return; 7606 7607 /* Make sure NAPI is disabled (or was never enabled). */ 7608 WARN_ON(!test_bit(NAPI_STATE_SCHED, &napi->state)); 7609 7610 if (test_and_clear_bit(NAPI_STATE_HAS_NOTIFIER, &napi->state)) 7611 irq_set_affinity_notifier(napi->irq, NULL); 7612 7613 if (napi->config) { 7614 napi->index = -1; 7615 napi->config = NULL; 7616 } 7617 7618 list_del_rcu(&napi->dev_list); 7619 napi_free_frags(napi); 7620 7621 gro_cleanup(&napi->gro); 7622 7623 if (napi->thread) { 7624 kthread_stop(napi->thread); 7625 napi->thread = NULL; 7626 } 7627 } 7628 EXPORT_SYMBOL(__netif_napi_del_locked); 7629 7630 static int __napi_poll(struct napi_struct *n, bool *repoll) 7631 { 7632 int work, weight; 7633 7634 weight = n->weight; 7635 7636 /* This NAPI_STATE_SCHED test is for avoiding a race 7637 * with netpoll's poll_napi(). Only the entity which 7638 * obtains the lock and sees NAPI_STATE_SCHED set will 7639 * actually make the ->poll() call. Therefore we avoid 7640 * accidentally calling ->poll() when NAPI is not scheduled. 7641 */ 7642 work = 0; 7643 if (napi_is_scheduled(n)) { 7644 work = n->poll(n, weight); 7645 trace_napi_poll(n, work, weight); 7646 7647 xdp_do_check_flushed(n); 7648 } 7649 7650 if (unlikely(work > weight)) 7651 netdev_err_once(n->dev, "NAPI poll function %pS returned %d, exceeding its budget of %d.\n", 7652 n->poll, work, weight); 7653 7654 if (likely(work < weight)) 7655 return work; 7656 7657 /* Drivers must not modify the NAPI state if they 7658 * consume the entire weight. In such cases this code 7659 * still "owns" the NAPI instance and therefore can 7660 * move the instance around on the list at-will. 7661 */ 7662 if (unlikely(napi_disable_pending(n))) { 7663 napi_complete(n); 7664 return work; 7665 } 7666 7667 /* The NAPI context has more processing work, but busy-polling 7668 * is preferred. Exit early. 7669 */ 7670 if (napi_prefer_busy_poll(n)) { 7671 if (napi_complete_done(n, work)) { 7672 /* If timeout is not set, we need to make sure 7673 * that the NAPI is re-scheduled. 7674 */ 7675 napi_schedule(n); 7676 } 7677 return work; 7678 } 7679 7680 /* Flush too old packets. If HZ < 1000, flush all packets */ 7681 gro_flush_normal(&n->gro, HZ >= 1000); 7682 7683 /* Some drivers may have called napi_schedule 7684 * prior to exhausting their budget. 7685 */ 7686 if (unlikely(!list_empty(&n->poll_list))) { 7687 pr_warn_once("%s: Budget exhausted after napi rescheduled\n", 7688 n->dev ? n->dev->name : "backlog"); 7689 return work; 7690 } 7691 7692 *repoll = true; 7693 7694 return work; 7695 } 7696 7697 static int napi_poll(struct napi_struct *n, struct list_head *repoll) 7698 { 7699 bool do_repoll = false; 7700 void *have; 7701 int work; 7702 7703 list_del_init(&n->poll_list); 7704 7705 have = netpoll_poll_lock(n); 7706 7707 work = __napi_poll(n, &do_repoll); 7708 7709 if (do_repoll) { 7710 #if defined(CONFIG_DEBUG_NET) 7711 if (unlikely(!napi_is_scheduled(n))) 7712 pr_crit("repoll requested for device %s %ps but napi is not scheduled.\n", 7713 n->dev->name, n->poll); 7714 #endif 7715 list_add_tail(&n->poll_list, repoll); 7716 } 7717 netpoll_poll_unlock(have); 7718 7719 return work; 7720 } 7721 7722 static int napi_thread_wait(struct napi_struct *napi) 7723 { 7724 set_current_state(TASK_INTERRUPTIBLE); 7725 7726 while (!kthread_should_stop()) { 7727 /* Testing SCHED_THREADED bit here to make sure the current 7728 * kthread owns this napi and could poll on this napi. 7729 * Testing SCHED bit is not enough because SCHED bit might be 7730 * set by some other busy poll thread or by napi_disable(). 7731 */ 7732 if (test_bit(NAPI_STATE_SCHED_THREADED, &napi->state)) { 7733 WARN_ON(!list_empty(&napi->poll_list)); 7734 __set_current_state(TASK_RUNNING); 7735 return 0; 7736 } 7737 7738 schedule(); 7739 set_current_state(TASK_INTERRUPTIBLE); 7740 } 7741 __set_current_state(TASK_RUNNING); 7742 7743 return -1; 7744 } 7745 7746 static void napi_threaded_poll_loop(struct napi_struct *napi) 7747 { 7748 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx; 7749 struct softnet_data *sd; 7750 unsigned long last_qs = jiffies; 7751 7752 for (;;) { 7753 bool repoll = false; 7754 void *have; 7755 7756 local_bh_disable(); 7757 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx); 7758 7759 sd = this_cpu_ptr(&softnet_data); 7760 sd->in_napi_threaded_poll = true; 7761 7762 have = netpoll_poll_lock(napi); 7763 __napi_poll(napi, &repoll); 7764 netpoll_poll_unlock(have); 7765 7766 sd->in_napi_threaded_poll = false; 7767 barrier(); 7768 7769 if (sd_has_rps_ipi_waiting(sd)) { 7770 local_irq_disable(); 7771 net_rps_action_and_irq_enable(sd); 7772 } 7773 skb_defer_free_flush(); 7774 bpf_net_ctx_clear(bpf_net_ctx); 7775 local_bh_enable(); 7776 7777 if (!repoll) 7778 break; 7779 7780 rcu_softirq_qs_periodic(last_qs); 7781 cond_resched(); 7782 } 7783 } 7784 7785 static int napi_threaded_poll(void *data) 7786 { 7787 struct napi_struct *napi = data; 7788 7789 while (!napi_thread_wait(napi)) 7790 napi_threaded_poll_loop(napi); 7791 7792 return 0; 7793 } 7794 7795 static __latent_entropy void net_rx_action(void) 7796 { 7797 struct softnet_data *sd = this_cpu_ptr(&softnet_data); 7798 unsigned long time_limit = jiffies + 7799 usecs_to_jiffies(READ_ONCE(net_hotdata.netdev_budget_usecs)); 7800 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx; 7801 int budget = READ_ONCE(net_hotdata.netdev_budget); 7802 LIST_HEAD(list); 7803 LIST_HEAD(repoll); 7804 7805 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx); 7806 start: 7807 sd->in_net_rx_action = true; 7808 local_irq_disable(); 7809 list_splice_init(&sd->poll_list, &list); 7810 local_irq_enable(); 7811 7812 for (;;) { 7813 struct napi_struct *n; 7814 7815 skb_defer_free_flush(); 7816 7817 if (list_empty(&list)) { 7818 if (list_empty(&repoll)) { 7819 sd->in_net_rx_action = false; 7820 barrier(); 7821 /* We need to check if ____napi_schedule() 7822 * had refilled poll_list while 7823 * sd->in_net_rx_action was true. 7824 */ 7825 if (!list_empty(&sd->poll_list)) 7826 goto start; 7827 if (!sd_has_rps_ipi_waiting(sd)) 7828 goto end; 7829 } 7830 break; 7831 } 7832 7833 n = list_first_entry(&list, struct napi_struct, poll_list); 7834 budget -= napi_poll(n, &repoll); 7835 7836 /* If softirq window is exhausted then punt. 7837 * Allow this to run for 2 jiffies since which will allow 7838 * an average latency of 1.5/HZ. 7839 */ 7840 if (unlikely(budget <= 0 || 7841 time_after_eq(jiffies, time_limit))) { 7842 /* Pairs with READ_ONCE() in softnet_seq_show() */ 7843 WRITE_ONCE(sd->time_squeeze, sd->time_squeeze + 1); 7844 break; 7845 } 7846 } 7847 7848 local_irq_disable(); 7849 7850 list_splice_tail_init(&sd->poll_list, &list); 7851 list_splice_tail(&repoll, &list); 7852 list_splice(&list, &sd->poll_list); 7853 if (!list_empty(&sd->poll_list)) 7854 __raise_softirq_irqoff(NET_RX_SOFTIRQ); 7855 else 7856 sd->in_net_rx_action = false; 7857 7858 net_rps_action_and_irq_enable(sd); 7859 end: 7860 bpf_net_ctx_clear(bpf_net_ctx); 7861 } 7862 7863 struct netdev_adjacent { 7864 struct net_device *dev; 7865 netdevice_tracker dev_tracker; 7866 7867 /* upper master flag, there can only be one master device per list */ 7868 bool master; 7869 7870 /* lookup ignore flag */ 7871 bool ignore; 7872 7873 /* counter for the number of times this device was added to us */ 7874 u16 ref_nr; 7875 7876 /* private field for the users */ 7877 void *private; 7878 7879 struct list_head list; 7880 struct rcu_head rcu; 7881 }; 7882 7883 static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev, 7884 struct list_head *adj_list) 7885 { 7886 struct netdev_adjacent *adj; 7887 7888 list_for_each_entry(adj, adj_list, list) { 7889 if (adj->dev == adj_dev) 7890 return adj; 7891 } 7892 return NULL; 7893 } 7894 7895 static int ____netdev_has_upper_dev(struct net_device *upper_dev, 7896 struct netdev_nested_priv *priv) 7897 { 7898 struct net_device *dev = (struct net_device *)priv->data; 7899 7900 return upper_dev == dev; 7901 } 7902 7903 /** 7904 * netdev_has_upper_dev - Check if device is linked to an upper device 7905 * @dev: device 7906 * @upper_dev: upper device to check 7907 * 7908 * Find out if a device is linked to specified upper device and return true 7909 * in case it is. Note that this checks only immediate upper device, 7910 * not through a complete stack of devices. The caller must hold the RTNL lock. 7911 */ 7912 bool netdev_has_upper_dev(struct net_device *dev, 7913 struct net_device *upper_dev) 7914 { 7915 struct netdev_nested_priv priv = { 7916 .data = (void *)upper_dev, 7917 }; 7918 7919 ASSERT_RTNL(); 7920 7921 return netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev, 7922 &priv); 7923 } 7924 EXPORT_SYMBOL(netdev_has_upper_dev); 7925 7926 /** 7927 * netdev_has_upper_dev_all_rcu - Check if device is linked to an upper device 7928 * @dev: device 7929 * @upper_dev: upper device to check 7930 * 7931 * Find out if a device is linked to specified upper device and return true 7932 * in case it is. Note that this checks the entire upper device chain. 7933 * The caller must hold rcu lock. 7934 */ 7935 7936 bool netdev_has_upper_dev_all_rcu(struct net_device *dev, 7937 struct net_device *upper_dev) 7938 { 7939 struct netdev_nested_priv priv = { 7940 .data = (void *)upper_dev, 7941 }; 7942 7943 return !!netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev, 7944 &priv); 7945 } 7946 EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu); 7947 7948 /** 7949 * netdev_has_any_upper_dev - Check if device is linked to some device 7950 * @dev: device 7951 * 7952 * Find out if a device is linked to an upper device and return true in case 7953 * it is. The caller must hold the RTNL lock. 7954 */ 7955 bool netdev_has_any_upper_dev(struct net_device *dev) 7956 { 7957 ASSERT_RTNL(); 7958 7959 return !list_empty(&dev->adj_list.upper); 7960 } 7961 EXPORT_SYMBOL(netdev_has_any_upper_dev); 7962 7963 /** 7964 * netdev_master_upper_dev_get - Get master upper device 7965 * @dev: device 7966 * 7967 * Find a master upper device and return pointer to it or NULL in case 7968 * it's not there. The caller must hold the RTNL lock. 7969 */ 7970 struct net_device *netdev_master_upper_dev_get(struct net_device *dev) 7971 { 7972 struct netdev_adjacent *upper; 7973 7974 ASSERT_RTNL(); 7975 7976 if (list_empty(&dev->adj_list.upper)) 7977 return NULL; 7978 7979 upper = list_first_entry(&dev->adj_list.upper, 7980 struct netdev_adjacent, list); 7981 if (likely(upper->master)) 7982 return upper->dev; 7983 return NULL; 7984 } 7985 EXPORT_SYMBOL(netdev_master_upper_dev_get); 7986 7987 static struct net_device *__netdev_master_upper_dev_get(struct net_device *dev) 7988 { 7989 struct netdev_adjacent *upper; 7990 7991 ASSERT_RTNL(); 7992 7993 if (list_empty(&dev->adj_list.upper)) 7994 return NULL; 7995 7996 upper = list_first_entry(&dev->adj_list.upper, 7997 struct netdev_adjacent, list); 7998 if (likely(upper->master) && !upper->ignore) 7999 return upper->dev; 8000 return NULL; 8001 } 8002 8003 /** 8004 * netdev_has_any_lower_dev - Check if device is linked to some device 8005 * @dev: device 8006 * 8007 * Find out if a device is linked to a lower device and return true in case 8008 * it is. The caller must hold the RTNL lock. 8009 */ 8010 static bool netdev_has_any_lower_dev(struct net_device *dev) 8011 { 8012 ASSERT_RTNL(); 8013 8014 return !list_empty(&dev->adj_list.lower); 8015 } 8016 8017 void *netdev_adjacent_get_private(struct list_head *adj_list) 8018 { 8019 struct netdev_adjacent *adj; 8020 8021 adj = list_entry(adj_list, struct netdev_adjacent, list); 8022 8023 return adj->private; 8024 } 8025 EXPORT_SYMBOL(netdev_adjacent_get_private); 8026 8027 /** 8028 * netdev_upper_get_next_dev_rcu - Get the next dev from upper list 8029 * @dev: device 8030 * @iter: list_head ** of the current position 8031 * 8032 * Gets the next device from the dev's upper list, starting from iter 8033 * position. The caller must hold RCU read lock. 8034 */ 8035 struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev, 8036 struct list_head **iter) 8037 { 8038 struct netdev_adjacent *upper; 8039 8040 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held()); 8041 8042 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list); 8043 8044 if (&upper->list == &dev->adj_list.upper) 8045 return NULL; 8046 8047 *iter = &upper->list; 8048 8049 return upper->dev; 8050 } 8051 EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu); 8052 8053 static struct net_device *__netdev_next_upper_dev(struct net_device *dev, 8054 struct list_head **iter, 8055 bool *ignore) 8056 { 8057 struct netdev_adjacent *upper; 8058 8059 upper = list_entry((*iter)->next, struct netdev_adjacent, list); 8060 8061 if (&upper->list == &dev->adj_list.upper) 8062 return NULL; 8063 8064 *iter = &upper->list; 8065 *ignore = upper->ignore; 8066 8067 return upper->dev; 8068 } 8069 8070 static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev, 8071 struct list_head **iter) 8072 { 8073 struct netdev_adjacent *upper; 8074 8075 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held()); 8076 8077 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list); 8078 8079 if (&upper->list == &dev->adj_list.upper) 8080 return NULL; 8081 8082 *iter = &upper->list; 8083 8084 return upper->dev; 8085 } 8086 8087 static int __netdev_walk_all_upper_dev(struct net_device *dev, 8088 int (*fn)(struct net_device *dev, 8089 struct netdev_nested_priv *priv), 8090 struct netdev_nested_priv *priv) 8091 { 8092 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1]; 8093 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1]; 8094 int ret, cur = 0; 8095 bool ignore; 8096 8097 now = dev; 8098 iter = &dev->adj_list.upper; 8099 8100 while (1) { 8101 if (now != dev) { 8102 ret = fn(now, priv); 8103 if (ret) 8104 return ret; 8105 } 8106 8107 next = NULL; 8108 while (1) { 8109 udev = __netdev_next_upper_dev(now, &iter, &ignore); 8110 if (!udev) 8111 break; 8112 if (ignore) 8113 continue; 8114 8115 next = udev; 8116 niter = &udev->adj_list.upper; 8117 dev_stack[cur] = now; 8118 iter_stack[cur++] = iter; 8119 break; 8120 } 8121 8122 if (!next) { 8123 if (!cur) 8124 return 0; 8125 next = dev_stack[--cur]; 8126 niter = iter_stack[cur]; 8127 } 8128 8129 now = next; 8130 iter = niter; 8131 } 8132 8133 return 0; 8134 } 8135 8136 int netdev_walk_all_upper_dev_rcu(struct net_device *dev, 8137 int (*fn)(struct net_device *dev, 8138 struct netdev_nested_priv *priv), 8139 struct netdev_nested_priv *priv) 8140 { 8141 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1]; 8142 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1]; 8143 int ret, cur = 0; 8144 8145 now = dev; 8146 iter = &dev->adj_list.upper; 8147 8148 while (1) { 8149 if (now != dev) { 8150 ret = fn(now, priv); 8151 if (ret) 8152 return ret; 8153 } 8154 8155 next = NULL; 8156 while (1) { 8157 udev = netdev_next_upper_dev_rcu(now, &iter); 8158 if (!udev) 8159 break; 8160 8161 next = udev; 8162 niter = &udev->adj_list.upper; 8163 dev_stack[cur] = now; 8164 iter_stack[cur++] = iter; 8165 break; 8166 } 8167 8168 if (!next) { 8169 if (!cur) 8170 return 0; 8171 next = dev_stack[--cur]; 8172 niter = iter_stack[cur]; 8173 } 8174 8175 now = next; 8176 iter = niter; 8177 } 8178 8179 return 0; 8180 } 8181 EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu); 8182 8183 static bool __netdev_has_upper_dev(struct net_device *dev, 8184 struct net_device *upper_dev) 8185 { 8186 struct netdev_nested_priv priv = { 8187 .flags = 0, 8188 .data = (void *)upper_dev, 8189 }; 8190 8191 ASSERT_RTNL(); 8192 8193 return __netdev_walk_all_upper_dev(dev, ____netdev_has_upper_dev, 8194 &priv); 8195 } 8196 8197 /** 8198 * netdev_lower_get_next_private - Get the next ->private from the 8199 * lower neighbour list 8200 * @dev: device 8201 * @iter: list_head ** of the current position 8202 * 8203 * Gets the next netdev_adjacent->private from the dev's lower neighbour 8204 * list, starting from iter position. The caller must hold either hold the 8205 * RTNL lock or its own locking that guarantees that the neighbour lower 8206 * list will remain unchanged. 8207 */ 8208 void *netdev_lower_get_next_private(struct net_device *dev, 8209 struct list_head **iter) 8210 { 8211 struct netdev_adjacent *lower; 8212 8213 lower = list_entry(*iter, struct netdev_adjacent, list); 8214 8215 if (&lower->list == &dev->adj_list.lower) 8216 return NULL; 8217 8218 *iter = lower->list.next; 8219 8220 return lower->private; 8221 } 8222 EXPORT_SYMBOL(netdev_lower_get_next_private); 8223 8224 /** 8225 * netdev_lower_get_next_private_rcu - Get the next ->private from the 8226 * lower neighbour list, RCU 8227 * variant 8228 * @dev: device 8229 * @iter: list_head ** of the current position 8230 * 8231 * Gets the next netdev_adjacent->private from the dev's lower neighbour 8232 * list, starting from iter position. The caller must hold RCU read lock. 8233 */ 8234 void *netdev_lower_get_next_private_rcu(struct net_device *dev, 8235 struct list_head **iter) 8236 { 8237 struct netdev_adjacent *lower; 8238 8239 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held()); 8240 8241 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list); 8242 8243 if (&lower->list == &dev->adj_list.lower) 8244 return NULL; 8245 8246 *iter = &lower->list; 8247 8248 return lower->private; 8249 } 8250 EXPORT_SYMBOL(netdev_lower_get_next_private_rcu); 8251 8252 /** 8253 * netdev_lower_get_next - Get the next device from the lower neighbour 8254 * list 8255 * @dev: device 8256 * @iter: list_head ** of the current position 8257 * 8258 * Gets the next netdev_adjacent from the dev's lower neighbour 8259 * list, starting from iter position. The caller must hold RTNL lock or 8260 * its own locking that guarantees that the neighbour lower 8261 * list will remain unchanged. 8262 */ 8263 void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter) 8264 { 8265 struct netdev_adjacent *lower; 8266 8267 lower = list_entry(*iter, struct netdev_adjacent, list); 8268 8269 if (&lower->list == &dev->adj_list.lower) 8270 return NULL; 8271 8272 *iter = lower->list.next; 8273 8274 return lower->dev; 8275 } 8276 EXPORT_SYMBOL(netdev_lower_get_next); 8277 8278 static struct net_device *netdev_next_lower_dev(struct net_device *dev, 8279 struct list_head **iter) 8280 { 8281 struct netdev_adjacent *lower; 8282 8283 lower = list_entry((*iter)->next, struct netdev_adjacent, list); 8284 8285 if (&lower->list == &dev->adj_list.lower) 8286 return NULL; 8287 8288 *iter = &lower->list; 8289 8290 return lower->dev; 8291 } 8292 8293 static struct net_device *__netdev_next_lower_dev(struct net_device *dev, 8294 struct list_head **iter, 8295 bool *ignore) 8296 { 8297 struct netdev_adjacent *lower; 8298 8299 lower = list_entry((*iter)->next, struct netdev_adjacent, list); 8300 8301 if (&lower->list == &dev->adj_list.lower) 8302 return NULL; 8303 8304 *iter = &lower->list; 8305 *ignore = lower->ignore; 8306 8307 return lower->dev; 8308 } 8309 8310 int netdev_walk_all_lower_dev(struct net_device *dev, 8311 int (*fn)(struct net_device *dev, 8312 struct netdev_nested_priv *priv), 8313 struct netdev_nested_priv *priv) 8314 { 8315 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1]; 8316 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1]; 8317 int ret, cur = 0; 8318 8319 now = dev; 8320 iter = &dev->adj_list.lower; 8321 8322 while (1) { 8323 if (now != dev) { 8324 ret = fn(now, priv); 8325 if (ret) 8326 return ret; 8327 } 8328 8329 next = NULL; 8330 while (1) { 8331 ldev = netdev_next_lower_dev(now, &iter); 8332 if (!ldev) 8333 break; 8334 8335 next = ldev; 8336 niter = &ldev->adj_list.lower; 8337 dev_stack[cur] = now; 8338 iter_stack[cur++] = iter; 8339 break; 8340 } 8341 8342 if (!next) { 8343 if (!cur) 8344 return 0; 8345 next = dev_stack[--cur]; 8346 niter = iter_stack[cur]; 8347 } 8348 8349 now = next; 8350 iter = niter; 8351 } 8352 8353 return 0; 8354 } 8355 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev); 8356 8357 static int __netdev_walk_all_lower_dev(struct net_device *dev, 8358 int (*fn)(struct net_device *dev, 8359 struct netdev_nested_priv *priv), 8360 struct netdev_nested_priv *priv) 8361 { 8362 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1]; 8363 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1]; 8364 int ret, cur = 0; 8365 bool ignore; 8366 8367 now = dev; 8368 iter = &dev->adj_list.lower; 8369 8370 while (1) { 8371 if (now != dev) { 8372 ret = fn(now, priv); 8373 if (ret) 8374 return ret; 8375 } 8376 8377 next = NULL; 8378 while (1) { 8379 ldev = __netdev_next_lower_dev(now, &iter, &ignore); 8380 if (!ldev) 8381 break; 8382 if (ignore) 8383 continue; 8384 8385 next = ldev; 8386 niter = &ldev->adj_list.lower; 8387 dev_stack[cur] = now; 8388 iter_stack[cur++] = iter; 8389 break; 8390 } 8391 8392 if (!next) { 8393 if (!cur) 8394 return 0; 8395 next = dev_stack[--cur]; 8396 niter = iter_stack[cur]; 8397 } 8398 8399 now = next; 8400 iter = niter; 8401 } 8402 8403 return 0; 8404 } 8405 8406 struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev, 8407 struct list_head **iter) 8408 { 8409 struct netdev_adjacent *lower; 8410 8411 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list); 8412 if (&lower->list == &dev->adj_list.lower) 8413 return NULL; 8414 8415 *iter = &lower->list; 8416 8417 return lower->dev; 8418 } 8419 EXPORT_SYMBOL(netdev_next_lower_dev_rcu); 8420 8421 static u8 __netdev_upper_depth(struct net_device *dev) 8422 { 8423 struct net_device *udev; 8424 struct list_head *iter; 8425 u8 max_depth = 0; 8426 bool ignore; 8427 8428 for (iter = &dev->adj_list.upper, 8429 udev = __netdev_next_upper_dev(dev, &iter, &ignore); 8430 udev; 8431 udev = __netdev_next_upper_dev(dev, &iter, &ignore)) { 8432 if (ignore) 8433 continue; 8434 if (max_depth < udev->upper_level) 8435 max_depth = udev->upper_level; 8436 } 8437 8438 return max_depth; 8439 } 8440 8441 static u8 __netdev_lower_depth(struct net_device *dev) 8442 { 8443 struct net_device *ldev; 8444 struct list_head *iter; 8445 u8 max_depth = 0; 8446 bool ignore; 8447 8448 for (iter = &dev->adj_list.lower, 8449 ldev = __netdev_next_lower_dev(dev, &iter, &ignore); 8450 ldev; 8451 ldev = __netdev_next_lower_dev(dev, &iter, &ignore)) { 8452 if (ignore) 8453 continue; 8454 if (max_depth < ldev->lower_level) 8455 max_depth = ldev->lower_level; 8456 } 8457 8458 return max_depth; 8459 } 8460 8461 static int __netdev_update_upper_level(struct net_device *dev, 8462 struct netdev_nested_priv *__unused) 8463 { 8464 dev->upper_level = __netdev_upper_depth(dev) + 1; 8465 return 0; 8466 } 8467 8468 #ifdef CONFIG_LOCKDEP 8469 static LIST_HEAD(net_unlink_list); 8470 8471 static void net_unlink_todo(struct net_device *dev) 8472 { 8473 if (list_empty(&dev->unlink_list)) 8474 list_add_tail(&dev->unlink_list, &net_unlink_list); 8475 } 8476 #endif 8477 8478 static int __netdev_update_lower_level(struct net_device *dev, 8479 struct netdev_nested_priv *priv) 8480 { 8481 dev->lower_level = __netdev_lower_depth(dev) + 1; 8482 8483 #ifdef CONFIG_LOCKDEP 8484 if (!priv) 8485 return 0; 8486 8487 if (priv->flags & NESTED_SYNC_IMM) 8488 dev->nested_level = dev->lower_level - 1; 8489 if (priv->flags & NESTED_SYNC_TODO) 8490 net_unlink_todo(dev); 8491 #endif 8492 return 0; 8493 } 8494 8495 int netdev_walk_all_lower_dev_rcu(struct net_device *dev, 8496 int (*fn)(struct net_device *dev, 8497 struct netdev_nested_priv *priv), 8498 struct netdev_nested_priv *priv) 8499 { 8500 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1]; 8501 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1]; 8502 int ret, cur = 0; 8503 8504 now = dev; 8505 iter = &dev->adj_list.lower; 8506 8507 while (1) { 8508 if (now != dev) { 8509 ret = fn(now, priv); 8510 if (ret) 8511 return ret; 8512 } 8513 8514 next = NULL; 8515 while (1) { 8516 ldev = netdev_next_lower_dev_rcu(now, &iter); 8517 if (!ldev) 8518 break; 8519 8520 next = ldev; 8521 niter = &ldev->adj_list.lower; 8522 dev_stack[cur] = now; 8523 iter_stack[cur++] = iter; 8524 break; 8525 } 8526 8527 if (!next) { 8528 if (!cur) 8529 return 0; 8530 next = dev_stack[--cur]; 8531 niter = iter_stack[cur]; 8532 } 8533 8534 now = next; 8535 iter = niter; 8536 } 8537 8538 return 0; 8539 } 8540 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu); 8541 8542 /** 8543 * netdev_lower_get_first_private_rcu - Get the first ->private from the 8544 * lower neighbour list, RCU 8545 * variant 8546 * @dev: device 8547 * 8548 * Gets the first netdev_adjacent->private from the dev's lower neighbour 8549 * list. The caller must hold RCU read lock. 8550 */ 8551 void *netdev_lower_get_first_private_rcu(struct net_device *dev) 8552 { 8553 struct netdev_adjacent *lower; 8554 8555 lower = list_first_or_null_rcu(&dev->adj_list.lower, 8556 struct netdev_adjacent, list); 8557 if (lower) 8558 return lower->private; 8559 return NULL; 8560 } 8561 EXPORT_SYMBOL(netdev_lower_get_first_private_rcu); 8562 8563 /** 8564 * netdev_master_upper_dev_get_rcu - Get master upper device 8565 * @dev: device 8566 * 8567 * Find a master upper device and return pointer to it or NULL in case 8568 * it's not there. The caller must hold the RCU read lock. 8569 */ 8570 struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev) 8571 { 8572 struct netdev_adjacent *upper; 8573 8574 upper = list_first_or_null_rcu(&dev->adj_list.upper, 8575 struct netdev_adjacent, list); 8576 if (upper && likely(upper->master)) 8577 return upper->dev; 8578 return NULL; 8579 } 8580 EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu); 8581 8582 static int netdev_adjacent_sysfs_add(struct net_device *dev, 8583 struct net_device *adj_dev, 8584 struct list_head *dev_list) 8585 { 8586 char linkname[IFNAMSIZ+7]; 8587 8588 sprintf(linkname, dev_list == &dev->adj_list.upper ? 8589 "upper_%s" : "lower_%s", adj_dev->name); 8590 return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj), 8591 linkname); 8592 } 8593 static void netdev_adjacent_sysfs_del(struct net_device *dev, 8594 char *name, 8595 struct list_head *dev_list) 8596 { 8597 char linkname[IFNAMSIZ+7]; 8598 8599 sprintf(linkname, dev_list == &dev->adj_list.upper ? 8600 "upper_%s" : "lower_%s", name); 8601 sysfs_remove_link(&(dev->dev.kobj), linkname); 8602 } 8603 8604 static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev, 8605 struct net_device *adj_dev, 8606 struct list_head *dev_list) 8607 { 8608 return (dev_list == &dev->adj_list.upper || 8609 dev_list == &dev->adj_list.lower) && 8610 net_eq(dev_net(dev), dev_net(adj_dev)); 8611 } 8612 8613 static int __netdev_adjacent_dev_insert(struct net_device *dev, 8614 struct net_device *adj_dev, 8615 struct list_head *dev_list, 8616 void *private, bool master) 8617 { 8618 struct netdev_adjacent *adj; 8619 int ret; 8620 8621 adj = __netdev_find_adj(adj_dev, dev_list); 8622 8623 if (adj) { 8624 adj->ref_nr += 1; 8625 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n", 8626 dev->name, adj_dev->name, adj->ref_nr); 8627 8628 return 0; 8629 } 8630 8631 adj = kmalloc(sizeof(*adj), GFP_KERNEL); 8632 if (!adj) 8633 return -ENOMEM; 8634 8635 adj->dev = adj_dev; 8636 adj->master = master; 8637 adj->ref_nr = 1; 8638 adj->private = private; 8639 adj->ignore = false; 8640 netdev_hold(adj_dev, &adj->dev_tracker, GFP_KERNEL); 8641 8642 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n", 8643 dev->name, adj_dev->name, adj->ref_nr, adj_dev->name); 8644 8645 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) { 8646 ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list); 8647 if (ret) 8648 goto free_adj; 8649 } 8650 8651 /* Ensure that master link is always the first item in list. */ 8652 if (master) { 8653 ret = sysfs_create_link(&(dev->dev.kobj), 8654 &(adj_dev->dev.kobj), "master"); 8655 if (ret) 8656 goto remove_symlinks; 8657 8658 list_add_rcu(&adj->list, dev_list); 8659 } else { 8660 list_add_tail_rcu(&adj->list, dev_list); 8661 } 8662 8663 return 0; 8664 8665 remove_symlinks: 8666 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) 8667 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list); 8668 free_adj: 8669 netdev_put(adj_dev, &adj->dev_tracker); 8670 kfree(adj); 8671 8672 return ret; 8673 } 8674 8675 static void __netdev_adjacent_dev_remove(struct net_device *dev, 8676 struct net_device *adj_dev, 8677 u16 ref_nr, 8678 struct list_head *dev_list) 8679 { 8680 struct netdev_adjacent *adj; 8681 8682 pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n", 8683 dev->name, adj_dev->name, ref_nr); 8684 8685 adj = __netdev_find_adj(adj_dev, dev_list); 8686 8687 if (!adj) { 8688 pr_err("Adjacency does not exist for device %s from %s\n", 8689 dev->name, adj_dev->name); 8690 WARN_ON(1); 8691 return; 8692 } 8693 8694 if (adj->ref_nr > ref_nr) { 8695 pr_debug("adjacency: %s to %s ref_nr - %d = %d\n", 8696 dev->name, adj_dev->name, ref_nr, 8697 adj->ref_nr - ref_nr); 8698 adj->ref_nr -= ref_nr; 8699 return; 8700 } 8701 8702 if (adj->master) 8703 sysfs_remove_link(&(dev->dev.kobj), "master"); 8704 8705 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) 8706 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list); 8707 8708 list_del_rcu(&adj->list); 8709 pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n", 8710 adj_dev->name, dev->name, adj_dev->name); 8711 netdev_put(adj_dev, &adj->dev_tracker); 8712 kfree_rcu(adj, rcu); 8713 } 8714 8715 static int __netdev_adjacent_dev_link_lists(struct net_device *dev, 8716 struct net_device *upper_dev, 8717 struct list_head *up_list, 8718 struct list_head *down_list, 8719 void *private, bool master) 8720 { 8721 int ret; 8722 8723 ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list, 8724 private, master); 8725 if (ret) 8726 return ret; 8727 8728 ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list, 8729 private, false); 8730 if (ret) { 8731 __netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list); 8732 return ret; 8733 } 8734 8735 return 0; 8736 } 8737 8738 static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev, 8739 struct net_device *upper_dev, 8740 u16 ref_nr, 8741 struct list_head *up_list, 8742 struct list_head *down_list) 8743 { 8744 __netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list); 8745 __netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list); 8746 } 8747 8748 static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev, 8749 struct net_device *upper_dev, 8750 void *private, bool master) 8751 { 8752 return __netdev_adjacent_dev_link_lists(dev, upper_dev, 8753 &dev->adj_list.upper, 8754 &upper_dev->adj_list.lower, 8755 private, master); 8756 } 8757 8758 static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev, 8759 struct net_device *upper_dev) 8760 { 8761 __netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1, 8762 &dev->adj_list.upper, 8763 &upper_dev->adj_list.lower); 8764 } 8765 8766 static int __netdev_upper_dev_link(struct net_device *dev, 8767 struct net_device *upper_dev, bool master, 8768 void *upper_priv, void *upper_info, 8769 struct netdev_nested_priv *priv, 8770 struct netlink_ext_ack *extack) 8771 { 8772 struct netdev_notifier_changeupper_info changeupper_info = { 8773 .info = { 8774 .dev = dev, 8775 .extack = extack, 8776 }, 8777 .upper_dev = upper_dev, 8778 .master = master, 8779 .linking = true, 8780 .upper_info = upper_info, 8781 }; 8782 struct net_device *master_dev; 8783 int ret = 0; 8784 8785 ASSERT_RTNL(); 8786 8787 if (dev == upper_dev) 8788 return -EBUSY; 8789 8790 /* To prevent loops, check if dev is not upper device to upper_dev. */ 8791 if (__netdev_has_upper_dev(upper_dev, dev)) 8792 return -EBUSY; 8793 8794 if ((dev->lower_level + upper_dev->upper_level) > MAX_NEST_DEV) 8795 return -EMLINK; 8796 8797 if (!master) { 8798 if (__netdev_has_upper_dev(dev, upper_dev)) 8799 return -EEXIST; 8800 } else { 8801 master_dev = __netdev_master_upper_dev_get(dev); 8802 if (master_dev) 8803 return master_dev == upper_dev ? -EEXIST : -EBUSY; 8804 } 8805 8806 ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER, 8807 &changeupper_info.info); 8808 ret = notifier_to_errno(ret); 8809 if (ret) 8810 return ret; 8811 8812 ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv, 8813 master); 8814 if (ret) 8815 return ret; 8816 8817 ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER, 8818 &changeupper_info.info); 8819 ret = notifier_to_errno(ret); 8820 if (ret) 8821 goto rollback; 8822 8823 __netdev_update_upper_level(dev, NULL); 8824 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL); 8825 8826 __netdev_update_lower_level(upper_dev, priv); 8827 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level, 8828 priv); 8829 8830 return 0; 8831 8832 rollback: 8833 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev); 8834 8835 return ret; 8836 } 8837 8838 /** 8839 * netdev_upper_dev_link - Add a link to the upper device 8840 * @dev: device 8841 * @upper_dev: new upper device 8842 * @extack: netlink extended ack 8843 * 8844 * Adds a link to device which is upper to this one. The caller must hold 8845 * the RTNL lock. On a failure a negative errno code is returned. 8846 * On success the reference counts are adjusted and the function 8847 * returns zero. 8848 */ 8849 int netdev_upper_dev_link(struct net_device *dev, 8850 struct net_device *upper_dev, 8851 struct netlink_ext_ack *extack) 8852 { 8853 struct netdev_nested_priv priv = { 8854 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO, 8855 .data = NULL, 8856 }; 8857 8858 return __netdev_upper_dev_link(dev, upper_dev, false, 8859 NULL, NULL, &priv, extack); 8860 } 8861 EXPORT_SYMBOL(netdev_upper_dev_link); 8862 8863 /** 8864 * netdev_master_upper_dev_link - Add a master link to the upper device 8865 * @dev: device 8866 * @upper_dev: new upper device 8867 * @upper_priv: upper device private 8868 * @upper_info: upper info to be passed down via notifier 8869 * @extack: netlink extended ack 8870 * 8871 * Adds a link to device which is upper to this one. In this case, only 8872 * one master upper device can be linked, although other non-master devices 8873 * might be linked as well. The caller must hold the RTNL lock. 8874 * On a failure a negative errno code is returned. On success the reference 8875 * counts are adjusted and the function returns zero. 8876 */ 8877 int netdev_master_upper_dev_link(struct net_device *dev, 8878 struct net_device *upper_dev, 8879 void *upper_priv, void *upper_info, 8880 struct netlink_ext_ack *extack) 8881 { 8882 struct netdev_nested_priv priv = { 8883 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO, 8884 .data = NULL, 8885 }; 8886 8887 return __netdev_upper_dev_link(dev, upper_dev, true, 8888 upper_priv, upper_info, &priv, extack); 8889 } 8890 EXPORT_SYMBOL(netdev_master_upper_dev_link); 8891 8892 static void __netdev_upper_dev_unlink(struct net_device *dev, 8893 struct net_device *upper_dev, 8894 struct netdev_nested_priv *priv) 8895 { 8896 struct netdev_notifier_changeupper_info changeupper_info = { 8897 .info = { 8898 .dev = dev, 8899 }, 8900 .upper_dev = upper_dev, 8901 .linking = false, 8902 }; 8903 8904 ASSERT_RTNL(); 8905 8906 changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev; 8907 8908 call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER, 8909 &changeupper_info.info); 8910 8911 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev); 8912 8913 call_netdevice_notifiers_info(NETDEV_CHANGEUPPER, 8914 &changeupper_info.info); 8915 8916 __netdev_update_upper_level(dev, NULL); 8917 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL); 8918 8919 __netdev_update_lower_level(upper_dev, priv); 8920 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level, 8921 priv); 8922 } 8923 8924 /** 8925 * netdev_upper_dev_unlink - Removes a link to upper device 8926 * @dev: device 8927 * @upper_dev: new upper device 8928 * 8929 * Removes a link to device which is upper to this one. The caller must hold 8930 * the RTNL lock. 8931 */ 8932 void netdev_upper_dev_unlink(struct net_device *dev, 8933 struct net_device *upper_dev) 8934 { 8935 struct netdev_nested_priv priv = { 8936 .flags = NESTED_SYNC_TODO, 8937 .data = NULL, 8938 }; 8939 8940 __netdev_upper_dev_unlink(dev, upper_dev, &priv); 8941 } 8942 EXPORT_SYMBOL(netdev_upper_dev_unlink); 8943 8944 static void __netdev_adjacent_dev_set(struct net_device *upper_dev, 8945 struct net_device *lower_dev, 8946 bool val) 8947 { 8948 struct netdev_adjacent *adj; 8949 8950 adj = __netdev_find_adj(lower_dev, &upper_dev->adj_list.lower); 8951 if (adj) 8952 adj->ignore = val; 8953 8954 adj = __netdev_find_adj(upper_dev, &lower_dev->adj_list.upper); 8955 if (adj) 8956 adj->ignore = val; 8957 } 8958 8959 static void netdev_adjacent_dev_disable(struct net_device *upper_dev, 8960 struct net_device *lower_dev) 8961 { 8962 __netdev_adjacent_dev_set(upper_dev, lower_dev, true); 8963 } 8964 8965 static void netdev_adjacent_dev_enable(struct net_device *upper_dev, 8966 struct net_device *lower_dev) 8967 { 8968 __netdev_adjacent_dev_set(upper_dev, lower_dev, false); 8969 } 8970 8971 int netdev_adjacent_change_prepare(struct net_device *old_dev, 8972 struct net_device *new_dev, 8973 struct net_device *dev, 8974 struct netlink_ext_ack *extack) 8975 { 8976 struct netdev_nested_priv priv = { 8977 .flags = 0, 8978 .data = NULL, 8979 }; 8980 int err; 8981 8982 if (!new_dev) 8983 return 0; 8984 8985 if (old_dev && new_dev != old_dev) 8986 netdev_adjacent_dev_disable(dev, old_dev); 8987 err = __netdev_upper_dev_link(new_dev, dev, false, NULL, NULL, &priv, 8988 extack); 8989 if (err) { 8990 if (old_dev && new_dev != old_dev) 8991 netdev_adjacent_dev_enable(dev, old_dev); 8992 return err; 8993 } 8994 8995 return 0; 8996 } 8997 EXPORT_SYMBOL(netdev_adjacent_change_prepare); 8998 8999 void netdev_adjacent_change_commit(struct net_device *old_dev, 9000 struct net_device *new_dev, 9001 struct net_device *dev) 9002 { 9003 struct netdev_nested_priv priv = { 9004 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO, 9005 .data = NULL, 9006 }; 9007 9008 if (!new_dev || !old_dev) 9009 return; 9010 9011 if (new_dev == old_dev) 9012 return; 9013 9014 netdev_adjacent_dev_enable(dev, old_dev); 9015 __netdev_upper_dev_unlink(old_dev, dev, &priv); 9016 } 9017 EXPORT_SYMBOL(netdev_adjacent_change_commit); 9018 9019 void netdev_adjacent_change_abort(struct net_device *old_dev, 9020 struct net_device *new_dev, 9021 struct net_device *dev) 9022 { 9023 struct netdev_nested_priv priv = { 9024 .flags = 0, 9025 .data = NULL, 9026 }; 9027 9028 if (!new_dev) 9029 return; 9030 9031 if (old_dev && new_dev != old_dev) 9032 netdev_adjacent_dev_enable(dev, old_dev); 9033 9034 __netdev_upper_dev_unlink(new_dev, dev, &priv); 9035 } 9036 EXPORT_SYMBOL(netdev_adjacent_change_abort); 9037 9038 /** 9039 * netdev_bonding_info_change - Dispatch event about slave change 9040 * @dev: device 9041 * @bonding_info: info to dispatch 9042 * 9043 * Send NETDEV_BONDING_INFO to netdev notifiers with info. 9044 * The caller must hold the RTNL lock. 9045 */ 9046 void netdev_bonding_info_change(struct net_device *dev, 9047 struct netdev_bonding_info *bonding_info) 9048 { 9049 struct netdev_notifier_bonding_info info = { 9050 .info.dev = dev, 9051 }; 9052 9053 memcpy(&info.bonding_info, bonding_info, 9054 sizeof(struct netdev_bonding_info)); 9055 call_netdevice_notifiers_info(NETDEV_BONDING_INFO, 9056 &info.info); 9057 } 9058 EXPORT_SYMBOL(netdev_bonding_info_change); 9059 9060 static int netdev_offload_xstats_enable_l3(struct net_device *dev, 9061 struct netlink_ext_ack *extack) 9062 { 9063 struct netdev_notifier_offload_xstats_info info = { 9064 .info.dev = dev, 9065 .info.extack = extack, 9066 .type = NETDEV_OFFLOAD_XSTATS_TYPE_L3, 9067 }; 9068 int err; 9069 int rc; 9070 9071 dev->offload_xstats_l3 = kzalloc(sizeof(*dev->offload_xstats_l3), 9072 GFP_KERNEL); 9073 if (!dev->offload_xstats_l3) 9074 return -ENOMEM; 9075 9076 rc = call_netdevice_notifiers_info_robust(NETDEV_OFFLOAD_XSTATS_ENABLE, 9077 NETDEV_OFFLOAD_XSTATS_DISABLE, 9078 &info.info); 9079 err = notifier_to_errno(rc); 9080 if (err) 9081 goto free_stats; 9082 9083 return 0; 9084 9085 free_stats: 9086 kfree(dev->offload_xstats_l3); 9087 dev->offload_xstats_l3 = NULL; 9088 return err; 9089 } 9090 9091 int netdev_offload_xstats_enable(struct net_device *dev, 9092 enum netdev_offload_xstats_type type, 9093 struct netlink_ext_ack *extack) 9094 { 9095 ASSERT_RTNL(); 9096 9097 if (netdev_offload_xstats_enabled(dev, type)) 9098 return -EALREADY; 9099 9100 switch (type) { 9101 case NETDEV_OFFLOAD_XSTATS_TYPE_L3: 9102 return netdev_offload_xstats_enable_l3(dev, extack); 9103 } 9104 9105 WARN_ON(1); 9106 return -EINVAL; 9107 } 9108 EXPORT_SYMBOL(netdev_offload_xstats_enable); 9109 9110 static void netdev_offload_xstats_disable_l3(struct net_device *dev) 9111 { 9112 struct netdev_notifier_offload_xstats_info info = { 9113 .info.dev = dev, 9114 .type = NETDEV_OFFLOAD_XSTATS_TYPE_L3, 9115 }; 9116 9117 call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_DISABLE, 9118 &info.info); 9119 kfree(dev->offload_xstats_l3); 9120 dev->offload_xstats_l3 = NULL; 9121 } 9122 9123 int netdev_offload_xstats_disable(struct net_device *dev, 9124 enum netdev_offload_xstats_type type) 9125 { 9126 ASSERT_RTNL(); 9127 9128 if (!netdev_offload_xstats_enabled(dev, type)) 9129 return -EALREADY; 9130 9131 switch (type) { 9132 case NETDEV_OFFLOAD_XSTATS_TYPE_L3: 9133 netdev_offload_xstats_disable_l3(dev); 9134 return 0; 9135 } 9136 9137 WARN_ON(1); 9138 return -EINVAL; 9139 } 9140 EXPORT_SYMBOL(netdev_offload_xstats_disable); 9141 9142 static void netdev_offload_xstats_disable_all(struct net_device *dev) 9143 { 9144 netdev_offload_xstats_disable(dev, NETDEV_OFFLOAD_XSTATS_TYPE_L3); 9145 } 9146 9147 static struct rtnl_hw_stats64 * 9148 netdev_offload_xstats_get_ptr(const struct net_device *dev, 9149 enum netdev_offload_xstats_type type) 9150 { 9151 switch (type) { 9152 case NETDEV_OFFLOAD_XSTATS_TYPE_L3: 9153 return dev->offload_xstats_l3; 9154 } 9155 9156 WARN_ON(1); 9157 return NULL; 9158 } 9159 9160 bool netdev_offload_xstats_enabled(const struct net_device *dev, 9161 enum netdev_offload_xstats_type type) 9162 { 9163 ASSERT_RTNL(); 9164 9165 return netdev_offload_xstats_get_ptr(dev, type); 9166 } 9167 EXPORT_SYMBOL(netdev_offload_xstats_enabled); 9168 9169 struct netdev_notifier_offload_xstats_ru { 9170 bool used; 9171 }; 9172 9173 struct netdev_notifier_offload_xstats_rd { 9174 struct rtnl_hw_stats64 stats; 9175 bool used; 9176 }; 9177 9178 static void netdev_hw_stats64_add(struct rtnl_hw_stats64 *dest, 9179 const struct rtnl_hw_stats64 *src) 9180 { 9181 dest->rx_packets += src->rx_packets; 9182 dest->tx_packets += src->tx_packets; 9183 dest->rx_bytes += src->rx_bytes; 9184 dest->tx_bytes += src->tx_bytes; 9185 dest->rx_errors += src->rx_errors; 9186 dest->tx_errors += src->tx_errors; 9187 dest->rx_dropped += src->rx_dropped; 9188 dest->tx_dropped += src->tx_dropped; 9189 dest->multicast += src->multicast; 9190 } 9191 9192 static int netdev_offload_xstats_get_used(struct net_device *dev, 9193 enum netdev_offload_xstats_type type, 9194 bool *p_used, 9195 struct netlink_ext_ack *extack) 9196 { 9197 struct netdev_notifier_offload_xstats_ru report_used = {}; 9198 struct netdev_notifier_offload_xstats_info info = { 9199 .info.dev = dev, 9200 .info.extack = extack, 9201 .type = type, 9202 .report_used = &report_used, 9203 }; 9204 int rc; 9205 9206 WARN_ON(!netdev_offload_xstats_enabled(dev, type)); 9207 rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_USED, 9208 &info.info); 9209 *p_used = report_used.used; 9210 return notifier_to_errno(rc); 9211 } 9212 9213 static int netdev_offload_xstats_get_stats(struct net_device *dev, 9214 enum netdev_offload_xstats_type type, 9215 struct rtnl_hw_stats64 *p_stats, 9216 bool *p_used, 9217 struct netlink_ext_ack *extack) 9218 { 9219 struct netdev_notifier_offload_xstats_rd report_delta = {}; 9220 struct netdev_notifier_offload_xstats_info info = { 9221 .info.dev = dev, 9222 .info.extack = extack, 9223 .type = type, 9224 .report_delta = &report_delta, 9225 }; 9226 struct rtnl_hw_stats64 *stats; 9227 int rc; 9228 9229 stats = netdev_offload_xstats_get_ptr(dev, type); 9230 if (WARN_ON(!stats)) 9231 return -EINVAL; 9232 9233 rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_DELTA, 9234 &info.info); 9235 9236 /* Cache whatever we got, even if there was an error, otherwise the 9237 * successful stats retrievals would get lost. 9238 */ 9239 netdev_hw_stats64_add(stats, &report_delta.stats); 9240 9241 if (p_stats) 9242 *p_stats = *stats; 9243 *p_used = report_delta.used; 9244 9245 return notifier_to_errno(rc); 9246 } 9247 9248 int netdev_offload_xstats_get(struct net_device *dev, 9249 enum netdev_offload_xstats_type type, 9250 struct rtnl_hw_stats64 *p_stats, bool *p_used, 9251 struct netlink_ext_ack *extack) 9252 { 9253 ASSERT_RTNL(); 9254 9255 if (p_stats) 9256 return netdev_offload_xstats_get_stats(dev, type, p_stats, 9257 p_used, extack); 9258 else 9259 return netdev_offload_xstats_get_used(dev, type, p_used, 9260 extack); 9261 } 9262 EXPORT_SYMBOL(netdev_offload_xstats_get); 9263 9264 void 9265 netdev_offload_xstats_report_delta(struct netdev_notifier_offload_xstats_rd *report_delta, 9266 const struct rtnl_hw_stats64 *stats) 9267 { 9268 report_delta->used = true; 9269 netdev_hw_stats64_add(&report_delta->stats, stats); 9270 } 9271 EXPORT_SYMBOL(netdev_offload_xstats_report_delta); 9272 9273 void 9274 netdev_offload_xstats_report_used(struct netdev_notifier_offload_xstats_ru *report_used) 9275 { 9276 report_used->used = true; 9277 } 9278 EXPORT_SYMBOL(netdev_offload_xstats_report_used); 9279 9280 void netdev_offload_xstats_push_delta(struct net_device *dev, 9281 enum netdev_offload_xstats_type type, 9282 const struct rtnl_hw_stats64 *p_stats) 9283 { 9284 struct rtnl_hw_stats64 *stats; 9285 9286 ASSERT_RTNL(); 9287 9288 stats = netdev_offload_xstats_get_ptr(dev, type); 9289 if (WARN_ON(!stats)) 9290 return; 9291 9292 netdev_hw_stats64_add(stats, p_stats); 9293 } 9294 EXPORT_SYMBOL(netdev_offload_xstats_push_delta); 9295 9296 /** 9297 * netdev_get_xmit_slave - Get the xmit slave of master device 9298 * @dev: device 9299 * @skb: The packet 9300 * @all_slaves: assume all the slaves are active 9301 * 9302 * The reference counters are not incremented so the caller must be 9303 * careful with locks. The caller must hold RCU lock. 9304 * %NULL is returned if no slave is found. 9305 */ 9306 9307 struct net_device *netdev_get_xmit_slave(struct net_device *dev, 9308 struct sk_buff *skb, 9309 bool all_slaves) 9310 { 9311 const struct net_device_ops *ops = dev->netdev_ops; 9312 9313 if (!ops->ndo_get_xmit_slave) 9314 return NULL; 9315 return ops->ndo_get_xmit_slave(dev, skb, all_slaves); 9316 } 9317 EXPORT_SYMBOL(netdev_get_xmit_slave); 9318 9319 static struct net_device *netdev_sk_get_lower_dev(struct net_device *dev, 9320 struct sock *sk) 9321 { 9322 const struct net_device_ops *ops = dev->netdev_ops; 9323 9324 if (!ops->ndo_sk_get_lower_dev) 9325 return NULL; 9326 return ops->ndo_sk_get_lower_dev(dev, sk); 9327 } 9328 9329 /** 9330 * netdev_sk_get_lowest_dev - Get the lowest device in chain given device and socket 9331 * @dev: device 9332 * @sk: the socket 9333 * 9334 * %NULL is returned if no lower device is found. 9335 */ 9336 9337 struct net_device *netdev_sk_get_lowest_dev(struct net_device *dev, 9338 struct sock *sk) 9339 { 9340 struct net_device *lower; 9341 9342 lower = netdev_sk_get_lower_dev(dev, sk); 9343 while (lower) { 9344 dev = lower; 9345 lower = netdev_sk_get_lower_dev(dev, sk); 9346 } 9347 9348 return dev; 9349 } 9350 EXPORT_SYMBOL(netdev_sk_get_lowest_dev); 9351 9352 static void netdev_adjacent_add_links(struct net_device *dev) 9353 { 9354 struct netdev_adjacent *iter; 9355 9356 struct net *net = dev_net(dev); 9357 9358 list_for_each_entry(iter, &dev->adj_list.upper, list) { 9359 if (!net_eq(net, dev_net(iter->dev))) 9360 continue; 9361 netdev_adjacent_sysfs_add(iter->dev, dev, 9362 &iter->dev->adj_list.lower); 9363 netdev_adjacent_sysfs_add(dev, iter->dev, 9364 &dev->adj_list.upper); 9365 } 9366 9367 list_for_each_entry(iter, &dev->adj_list.lower, list) { 9368 if (!net_eq(net, dev_net(iter->dev))) 9369 continue; 9370 netdev_adjacent_sysfs_add(iter->dev, dev, 9371 &iter->dev->adj_list.upper); 9372 netdev_adjacent_sysfs_add(dev, iter->dev, 9373 &dev->adj_list.lower); 9374 } 9375 } 9376 9377 static void netdev_adjacent_del_links(struct net_device *dev) 9378 { 9379 struct netdev_adjacent *iter; 9380 9381 struct net *net = dev_net(dev); 9382 9383 list_for_each_entry(iter, &dev->adj_list.upper, list) { 9384 if (!net_eq(net, dev_net(iter->dev))) 9385 continue; 9386 netdev_adjacent_sysfs_del(iter->dev, dev->name, 9387 &iter->dev->adj_list.lower); 9388 netdev_adjacent_sysfs_del(dev, iter->dev->name, 9389 &dev->adj_list.upper); 9390 } 9391 9392 list_for_each_entry(iter, &dev->adj_list.lower, list) { 9393 if (!net_eq(net, dev_net(iter->dev))) 9394 continue; 9395 netdev_adjacent_sysfs_del(iter->dev, dev->name, 9396 &iter->dev->adj_list.upper); 9397 netdev_adjacent_sysfs_del(dev, iter->dev->name, 9398 &dev->adj_list.lower); 9399 } 9400 } 9401 9402 void netdev_adjacent_rename_links(struct net_device *dev, char *oldname) 9403 { 9404 struct netdev_adjacent *iter; 9405 9406 struct net *net = dev_net(dev); 9407 9408 list_for_each_entry(iter, &dev->adj_list.upper, list) { 9409 if (!net_eq(net, dev_net(iter->dev))) 9410 continue; 9411 netdev_adjacent_sysfs_del(iter->dev, oldname, 9412 &iter->dev->adj_list.lower); 9413 netdev_adjacent_sysfs_add(iter->dev, dev, 9414 &iter->dev->adj_list.lower); 9415 } 9416 9417 list_for_each_entry(iter, &dev->adj_list.lower, list) { 9418 if (!net_eq(net, dev_net(iter->dev))) 9419 continue; 9420 netdev_adjacent_sysfs_del(iter->dev, oldname, 9421 &iter->dev->adj_list.upper); 9422 netdev_adjacent_sysfs_add(iter->dev, dev, 9423 &iter->dev->adj_list.upper); 9424 } 9425 } 9426 9427 void *netdev_lower_dev_get_private(struct net_device *dev, 9428 struct net_device *lower_dev) 9429 { 9430 struct netdev_adjacent *lower; 9431 9432 if (!lower_dev) 9433 return NULL; 9434 lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower); 9435 if (!lower) 9436 return NULL; 9437 9438 return lower->private; 9439 } 9440 EXPORT_SYMBOL(netdev_lower_dev_get_private); 9441 9442 9443 /** 9444 * netdev_lower_state_changed - Dispatch event about lower device state change 9445 * @lower_dev: device 9446 * @lower_state_info: state to dispatch 9447 * 9448 * Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info. 9449 * The caller must hold the RTNL lock. 9450 */ 9451 void netdev_lower_state_changed(struct net_device *lower_dev, 9452 void *lower_state_info) 9453 { 9454 struct netdev_notifier_changelowerstate_info changelowerstate_info = { 9455 .info.dev = lower_dev, 9456 }; 9457 9458 ASSERT_RTNL(); 9459 changelowerstate_info.lower_state_info = lower_state_info; 9460 call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE, 9461 &changelowerstate_info.info); 9462 } 9463 EXPORT_SYMBOL(netdev_lower_state_changed); 9464 9465 static void dev_change_rx_flags(struct net_device *dev, int flags) 9466 { 9467 const struct net_device_ops *ops = dev->netdev_ops; 9468 9469 if (ops->ndo_change_rx_flags) 9470 ops->ndo_change_rx_flags(dev, flags); 9471 } 9472 9473 static int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify) 9474 { 9475 unsigned int old_flags = dev->flags; 9476 unsigned int promiscuity, flags; 9477 kuid_t uid; 9478 kgid_t gid; 9479 9480 ASSERT_RTNL(); 9481 9482 promiscuity = dev->promiscuity + inc; 9483 if (promiscuity == 0) { 9484 /* 9485 * Avoid overflow. 9486 * If inc causes overflow, untouch promisc and return error. 9487 */ 9488 if (unlikely(inc > 0)) { 9489 netdev_warn(dev, "promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n"); 9490 return -EOVERFLOW; 9491 } 9492 flags = old_flags & ~IFF_PROMISC; 9493 } else { 9494 flags = old_flags | IFF_PROMISC; 9495 } 9496 WRITE_ONCE(dev->promiscuity, promiscuity); 9497 if (flags != old_flags) { 9498 WRITE_ONCE(dev->flags, flags); 9499 netdev_info(dev, "%s promiscuous mode\n", 9500 dev->flags & IFF_PROMISC ? "entered" : "left"); 9501 if (audit_enabled) { 9502 current_uid_gid(&uid, &gid); 9503 audit_log(audit_context(), GFP_ATOMIC, 9504 AUDIT_ANOM_PROMISCUOUS, 9505 "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u", 9506 dev->name, (dev->flags & IFF_PROMISC), 9507 (old_flags & IFF_PROMISC), 9508 from_kuid(&init_user_ns, audit_get_loginuid(current)), 9509 from_kuid(&init_user_ns, uid), 9510 from_kgid(&init_user_ns, gid), 9511 audit_get_sessionid(current)); 9512 } 9513 9514 dev_change_rx_flags(dev, IFF_PROMISC); 9515 } 9516 if (notify) { 9517 /* The ops lock is only required to ensure consistent locking 9518 * for `NETDEV_CHANGE` notifiers. This function is sometimes 9519 * called without the lock, even for devices that are ops 9520 * locked, such as in `dev_uc_sync_multiple` when using 9521 * bonding or teaming. 9522 */ 9523 netdev_ops_assert_locked(dev); 9524 __dev_notify_flags(dev, old_flags, IFF_PROMISC, 0, NULL); 9525 } 9526 return 0; 9527 } 9528 9529 int netif_set_promiscuity(struct net_device *dev, int inc) 9530 { 9531 unsigned int old_flags = dev->flags; 9532 int err; 9533 9534 err = __dev_set_promiscuity(dev, inc, true); 9535 if (err < 0) 9536 return err; 9537 if (dev->flags != old_flags) 9538 dev_set_rx_mode(dev); 9539 return err; 9540 } 9541 9542 int netif_set_allmulti(struct net_device *dev, int inc, bool notify) 9543 { 9544 unsigned int old_flags = dev->flags, old_gflags = dev->gflags; 9545 unsigned int allmulti, flags; 9546 9547 ASSERT_RTNL(); 9548 9549 allmulti = dev->allmulti + inc; 9550 if (allmulti == 0) { 9551 /* 9552 * Avoid overflow. 9553 * If inc causes overflow, untouch allmulti and return error. 9554 */ 9555 if (unlikely(inc > 0)) { 9556 netdev_warn(dev, "allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n"); 9557 return -EOVERFLOW; 9558 } 9559 flags = old_flags & ~IFF_ALLMULTI; 9560 } else { 9561 flags = old_flags | IFF_ALLMULTI; 9562 } 9563 WRITE_ONCE(dev->allmulti, allmulti); 9564 if (flags != old_flags) { 9565 WRITE_ONCE(dev->flags, flags); 9566 netdev_info(dev, "%s allmulticast mode\n", 9567 dev->flags & IFF_ALLMULTI ? "entered" : "left"); 9568 dev_change_rx_flags(dev, IFF_ALLMULTI); 9569 dev_set_rx_mode(dev); 9570 if (notify) 9571 __dev_notify_flags(dev, old_flags, 9572 dev->gflags ^ old_gflags, 0, NULL); 9573 } 9574 return 0; 9575 } 9576 9577 /* 9578 * Upload unicast and multicast address lists to device and 9579 * configure RX filtering. When the device doesn't support unicast 9580 * filtering it is put in promiscuous mode while unicast addresses 9581 * are present. 9582 */ 9583 void __dev_set_rx_mode(struct net_device *dev) 9584 { 9585 const struct net_device_ops *ops = dev->netdev_ops; 9586 9587 /* dev_open will call this function so the list will stay sane. */ 9588 if (!(dev->flags&IFF_UP)) 9589 return; 9590 9591 if (!netif_device_present(dev)) 9592 return; 9593 9594 if (!(dev->priv_flags & IFF_UNICAST_FLT)) { 9595 /* Unicast addresses changes may only happen under the rtnl, 9596 * therefore calling __dev_set_promiscuity here is safe. 9597 */ 9598 if (!netdev_uc_empty(dev) && !dev->uc_promisc) { 9599 __dev_set_promiscuity(dev, 1, false); 9600 dev->uc_promisc = true; 9601 } else if (netdev_uc_empty(dev) && dev->uc_promisc) { 9602 __dev_set_promiscuity(dev, -1, false); 9603 dev->uc_promisc = false; 9604 } 9605 } 9606 9607 if (ops->ndo_set_rx_mode) 9608 ops->ndo_set_rx_mode(dev); 9609 } 9610 9611 void dev_set_rx_mode(struct net_device *dev) 9612 { 9613 netif_addr_lock_bh(dev); 9614 __dev_set_rx_mode(dev); 9615 netif_addr_unlock_bh(dev); 9616 } 9617 9618 /** 9619 * netif_get_flags() - get flags reported to userspace 9620 * @dev: device 9621 * 9622 * Get the combination of flag bits exported through APIs to userspace. 9623 */ 9624 unsigned int netif_get_flags(const struct net_device *dev) 9625 { 9626 unsigned int flags; 9627 9628 flags = (READ_ONCE(dev->flags) & ~(IFF_PROMISC | 9629 IFF_ALLMULTI | 9630 IFF_RUNNING | 9631 IFF_LOWER_UP | 9632 IFF_DORMANT)) | 9633 (READ_ONCE(dev->gflags) & (IFF_PROMISC | 9634 IFF_ALLMULTI)); 9635 9636 if (netif_running(dev)) { 9637 if (netif_oper_up(dev)) 9638 flags |= IFF_RUNNING; 9639 if (netif_carrier_ok(dev)) 9640 flags |= IFF_LOWER_UP; 9641 if (netif_dormant(dev)) 9642 flags |= IFF_DORMANT; 9643 } 9644 9645 return flags; 9646 } 9647 EXPORT_SYMBOL(netif_get_flags); 9648 9649 int __dev_change_flags(struct net_device *dev, unsigned int flags, 9650 struct netlink_ext_ack *extack) 9651 { 9652 unsigned int old_flags = dev->flags; 9653 int ret; 9654 9655 ASSERT_RTNL(); 9656 9657 /* 9658 * Set the flags on our device. 9659 */ 9660 9661 dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP | 9662 IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL | 9663 IFF_AUTOMEDIA)) | 9664 (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC | 9665 IFF_ALLMULTI)); 9666 9667 /* 9668 * Load in the correct multicast list now the flags have changed. 9669 */ 9670 9671 if ((old_flags ^ flags) & IFF_MULTICAST) 9672 dev_change_rx_flags(dev, IFF_MULTICAST); 9673 9674 dev_set_rx_mode(dev); 9675 9676 /* 9677 * Have we downed the interface. We handle IFF_UP ourselves 9678 * according to user attempts to set it, rather than blindly 9679 * setting it. 9680 */ 9681 9682 ret = 0; 9683 if ((old_flags ^ flags) & IFF_UP) { 9684 if (old_flags & IFF_UP) 9685 __dev_close(dev); 9686 else 9687 ret = __dev_open(dev, extack); 9688 } 9689 9690 if ((flags ^ dev->gflags) & IFF_PROMISC) { 9691 int inc = (flags & IFF_PROMISC) ? 1 : -1; 9692 old_flags = dev->flags; 9693 9694 dev->gflags ^= IFF_PROMISC; 9695 9696 if (__dev_set_promiscuity(dev, inc, false) >= 0) 9697 if (dev->flags != old_flags) 9698 dev_set_rx_mode(dev); 9699 } 9700 9701 /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI 9702 * is important. Some (broken) drivers set IFF_PROMISC, when 9703 * IFF_ALLMULTI is requested not asking us and not reporting. 9704 */ 9705 if ((flags ^ dev->gflags) & IFF_ALLMULTI) { 9706 int inc = (flags & IFF_ALLMULTI) ? 1 : -1; 9707 9708 dev->gflags ^= IFF_ALLMULTI; 9709 netif_set_allmulti(dev, inc, false); 9710 } 9711 9712 return ret; 9713 } 9714 9715 void __dev_notify_flags(struct net_device *dev, unsigned int old_flags, 9716 unsigned int gchanges, u32 portid, 9717 const struct nlmsghdr *nlh) 9718 { 9719 unsigned int changes = dev->flags ^ old_flags; 9720 9721 if (gchanges) 9722 rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC, portid, nlh); 9723 9724 if (changes & IFF_UP) { 9725 if (dev->flags & IFF_UP) 9726 call_netdevice_notifiers(NETDEV_UP, dev); 9727 else 9728 call_netdevice_notifiers(NETDEV_DOWN, dev); 9729 } 9730 9731 if (dev->flags & IFF_UP && 9732 (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) { 9733 struct netdev_notifier_change_info change_info = { 9734 .info = { 9735 .dev = dev, 9736 }, 9737 .flags_changed = changes, 9738 }; 9739 9740 call_netdevice_notifiers_info(NETDEV_CHANGE, &change_info.info); 9741 } 9742 } 9743 9744 int netif_change_flags(struct net_device *dev, unsigned int flags, 9745 struct netlink_ext_ack *extack) 9746 { 9747 int ret; 9748 unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags; 9749 9750 ret = __dev_change_flags(dev, flags, extack); 9751 if (ret < 0) 9752 return ret; 9753 9754 changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags); 9755 __dev_notify_flags(dev, old_flags, changes, 0, NULL); 9756 return ret; 9757 } 9758 9759 int __netif_set_mtu(struct net_device *dev, int new_mtu) 9760 { 9761 const struct net_device_ops *ops = dev->netdev_ops; 9762 9763 if (ops->ndo_change_mtu) 9764 return ops->ndo_change_mtu(dev, new_mtu); 9765 9766 /* Pairs with all the lockless reads of dev->mtu in the stack */ 9767 WRITE_ONCE(dev->mtu, new_mtu); 9768 return 0; 9769 } 9770 EXPORT_SYMBOL_NS_GPL(__netif_set_mtu, "NETDEV_INTERNAL"); 9771 9772 int dev_validate_mtu(struct net_device *dev, int new_mtu, 9773 struct netlink_ext_ack *extack) 9774 { 9775 /* MTU must be positive, and in range */ 9776 if (new_mtu < 0 || new_mtu < dev->min_mtu) { 9777 NL_SET_ERR_MSG(extack, "mtu less than device minimum"); 9778 return -EINVAL; 9779 } 9780 9781 if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) { 9782 NL_SET_ERR_MSG(extack, "mtu greater than device maximum"); 9783 return -EINVAL; 9784 } 9785 return 0; 9786 } 9787 9788 /** 9789 * netif_set_mtu_ext() - Change maximum transfer unit 9790 * @dev: device 9791 * @new_mtu: new transfer unit 9792 * @extack: netlink extended ack 9793 * 9794 * Change the maximum transfer size of the network device. 9795 * 9796 * Return: 0 on success, -errno on failure. 9797 */ 9798 int netif_set_mtu_ext(struct net_device *dev, int new_mtu, 9799 struct netlink_ext_ack *extack) 9800 { 9801 int err, orig_mtu; 9802 9803 netdev_ops_assert_locked(dev); 9804 9805 if (new_mtu == dev->mtu) 9806 return 0; 9807 9808 err = dev_validate_mtu(dev, new_mtu, extack); 9809 if (err) 9810 return err; 9811 9812 if (!netif_device_present(dev)) 9813 return -ENODEV; 9814 9815 err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev); 9816 err = notifier_to_errno(err); 9817 if (err) 9818 return err; 9819 9820 orig_mtu = dev->mtu; 9821 err = __netif_set_mtu(dev, new_mtu); 9822 9823 if (!err) { 9824 err = call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev, 9825 orig_mtu); 9826 err = notifier_to_errno(err); 9827 if (err) { 9828 /* setting mtu back and notifying everyone again, 9829 * so that they have a chance to revert changes. 9830 */ 9831 __netif_set_mtu(dev, orig_mtu); 9832 call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev, 9833 new_mtu); 9834 } 9835 } 9836 return err; 9837 } 9838 9839 int netif_set_mtu(struct net_device *dev, int new_mtu) 9840 { 9841 struct netlink_ext_ack extack; 9842 int err; 9843 9844 memset(&extack, 0, sizeof(extack)); 9845 err = netif_set_mtu_ext(dev, new_mtu, &extack); 9846 if (err && extack._msg) 9847 net_err_ratelimited("%s: %s\n", dev->name, extack._msg); 9848 return err; 9849 } 9850 EXPORT_SYMBOL(netif_set_mtu); 9851 9852 int netif_change_tx_queue_len(struct net_device *dev, unsigned long new_len) 9853 { 9854 unsigned int orig_len = dev->tx_queue_len; 9855 int res; 9856 9857 if (new_len != (unsigned int)new_len) 9858 return -ERANGE; 9859 9860 if (new_len != orig_len) { 9861 WRITE_ONCE(dev->tx_queue_len, new_len); 9862 res = call_netdevice_notifiers(NETDEV_CHANGE_TX_QUEUE_LEN, dev); 9863 res = notifier_to_errno(res); 9864 if (res) 9865 goto err_rollback; 9866 res = dev_qdisc_change_tx_queue_len(dev); 9867 if (res) 9868 goto err_rollback; 9869 } 9870 9871 return 0; 9872 9873 err_rollback: 9874 netdev_err(dev, "refused to change device tx_queue_len\n"); 9875 WRITE_ONCE(dev->tx_queue_len, orig_len); 9876 return res; 9877 } 9878 9879 void netif_set_group(struct net_device *dev, int new_group) 9880 { 9881 dev->group = new_group; 9882 } 9883 9884 /** 9885 * netif_pre_changeaddr_notify() - Call NETDEV_PRE_CHANGEADDR. 9886 * @dev: device 9887 * @addr: new address 9888 * @extack: netlink extended ack 9889 * 9890 * Return: 0 on success, -errno on failure. 9891 */ 9892 int netif_pre_changeaddr_notify(struct net_device *dev, const char *addr, 9893 struct netlink_ext_ack *extack) 9894 { 9895 struct netdev_notifier_pre_changeaddr_info info = { 9896 .info.dev = dev, 9897 .info.extack = extack, 9898 .dev_addr = addr, 9899 }; 9900 int rc; 9901 9902 rc = call_netdevice_notifiers_info(NETDEV_PRE_CHANGEADDR, &info.info); 9903 return notifier_to_errno(rc); 9904 } 9905 EXPORT_SYMBOL_NS_GPL(netif_pre_changeaddr_notify, "NETDEV_INTERNAL"); 9906 9907 int netif_set_mac_address(struct net_device *dev, struct sockaddr_storage *ss, 9908 struct netlink_ext_ack *extack) 9909 { 9910 const struct net_device_ops *ops = dev->netdev_ops; 9911 int err; 9912 9913 if (!ops->ndo_set_mac_address) 9914 return -EOPNOTSUPP; 9915 if (ss->ss_family != dev->type) 9916 return -EINVAL; 9917 if (!netif_device_present(dev)) 9918 return -ENODEV; 9919 err = netif_pre_changeaddr_notify(dev, ss->__data, extack); 9920 if (err) 9921 return err; 9922 if (memcmp(dev->dev_addr, ss->__data, dev->addr_len)) { 9923 err = ops->ndo_set_mac_address(dev, ss); 9924 if (err) 9925 return err; 9926 } 9927 dev->addr_assign_type = NET_ADDR_SET; 9928 call_netdevice_notifiers(NETDEV_CHANGEADDR, dev); 9929 add_device_randomness(dev->dev_addr, dev->addr_len); 9930 return 0; 9931 } 9932 9933 DECLARE_RWSEM(dev_addr_sem); 9934 9935 /* "sa" is a true struct sockaddr with limited "sa_data" member. */ 9936 int netif_get_mac_address(struct sockaddr *sa, struct net *net, char *dev_name) 9937 { 9938 size_t size = sizeof(sa->sa_data_min); 9939 struct net_device *dev; 9940 int ret = 0; 9941 9942 down_read(&dev_addr_sem); 9943 rcu_read_lock(); 9944 9945 dev = dev_get_by_name_rcu(net, dev_name); 9946 if (!dev) { 9947 ret = -ENODEV; 9948 goto unlock; 9949 } 9950 if (!dev->addr_len) 9951 memset(sa->sa_data, 0, size); 9952 else 9953 memcpy(sa->sa_data, dev->dev_addr, 9954 min_t(size_t, size, dev->addr_len)); 9955 sa->sa_family = dev->type; 9956 9957 unlock: 9958 rcu_read_unlock(); 9959 up_read(&dev_addr_sem); 9960 return ret; 9961 } 9962 EXPORT_SYMBOL_NS_GPL(netif_get_mac_address, "NETDEV_INTERNAL"); 9963 9964 int netif_change_carrier(struct net_device *dev, bool new_carrier) 9965 { 9966 const struct net_device_ops *ops = dev->netdev_ops; 9967 9968 if (!ops->ndo_change_carrier) 9969 return -EOPNOTSUPP; 9970 if (!netif_device_present(dev)) 9971 return -ENODEV; 9972 return ops->ndo_change_carrier(dev, new_carrier); 9973 } 9974 9975 /** 9976 * dev_get_phys_port_id - Get device physical port ID 9977 * @dev: device 9978 * @ppid: port ID 9979 * 9980 * Get device physical port ID 9981 */ 9982 int dev_get_phys_port_id(struct net_device *dev, 9983 struct netdev_phys_item_id *ppid) 9984 { 9985 const struct net_device_ops *ops = dev->netdev_ops; 9986 9987 if (!ops->ndo_get_phys_port_id) 9988 return -EOPNOTSUPP; 9989 return ops->ndo_get_phys_port_id(dev, ppid); 9990 } 9991 9992 /** 9993 * dev_get_phys_port_name - Get device physical port name 9994 * @dev: device 9995 * @name: port name 9996 * @len: limit of bytes to copy to name 9997 * 9998 * Get device physical port name 9999 */ 10000 int dev_get_phys_port_name(struct net_device *dev, 10001 char *name, size_t len) 10002 { 10003 const struct net_device_ops *ops = dev->netdev_ops; 10004 int err; 10005 10006 if (ops->ndo_get_phys_port_name) { 10007 err = ops->ndo_get_phys_port_name(dev, name, len); 10008 if (err != -EOPNOTSUPP) 10009 return err; 10010 } 10011 return devlink_compat_phys_port_name_get(dev, name, len); 10012 } 10013 10014 /** 10015 * netif_get_port_parent_id() - Get the device's port parent identifier 10016 * @dev: network device 10017 * @ppid: pointer to a storage for the port's parent identifier 10018 * @recurse: allow/disallow recursion to lower devices 10019 * 10020 * Get the devices's port parent identifier. 10021 * 10022 * Return: 0 on success, -errno on failure. 10023 */ 10024 int netif_get_port_parent_id(struct net_device *dev, 10025 struct netdev_phys_item_id *ppid, bool recurse) 10026 { 10027 const struct net_device_ops *ops = dev->netdev_ops; 10028 struct netdev_phys_item_id first = { }; 10029 struct net_device *lower_dev; 10030 struct list_head *iter; 10031 int err; 10032 10033 if (ops->ndo_get_port_parent_id) { 10034 err = ops->ndo_get_port_parent_id(dev, ppid); 10035 if (err != -EOPNOTSUPP) 10036 return err; 10037 } 10038 10039 err = devlink_compat_switch_id_get(dev, ppid); 10040 if (!recurse || err != -EOPNOTSUPP) 10041 return err; 10042 10043 netdev_for_each_lower_dev(dev, lower_dev, iter) { 10044 err = netif_get_port_parent_id(lower_dev, ppid, true); 10045 if (err) 10046 break; 10047 if (!first.id_len) 10048 first = *ppid; 10049 else if (memcmp(&first, ppid, sizeof(*ppid))) 10050 return -EOPNOTSUPP; 10051 } 10052 10053 return err; 10054 } 10055 EXPORT_SYMBOL(netif_get_port_parent_id); 10056 10057 /** 10058 * netdev_port_same_parent_id - Indicate if two network devices have 10059 * the same port parent identifier 10060 * @a: first network device 10061 * @b: second network device 10062 */ 10063 bool netdev_port_same_parent_id(struct net_device *a, struct net_device *b) 10064 { 10065 struct netdev_phys_item_id a_id = { }; 10066 struct netdev_phys_item_id b_id = { }; 10067 10068 if (netif_get_port_parent_id(a, &a_id, true) || 10069 netif_get_port_parent_id(b, &b_id, true)) 10070 return false; 10071 10072 return netdev_phys_item_id_same(&a_id, &b_id); 10073 } 10074 EXPORT_SYMBOL(netdev_port_same_parent_id); 10075 10076 int netif_change_proto_down(struct net_device *dev, bool proto_down) 10077 { 10078 if (!dev->change_proto_down) 10079 return -EOPNOTSUPP; 10080 if (!netif_device_present(dev)) 10081 return -ENODEV; 10082 if (proto_down) 10083 netif_carrier_off(dev); 10084 else 10085 netif_carrier_on(dev); 10086 WRITE_ONCE(dev->proto_down, proto_down); 10087 return 0; 10088 } 10089 10090 /** 10091 * netdev_change_proto_down_reason_locked - proto down reason 10092 * 10093 * @dev: device 10094 * @mask: proto down mask 10095 * @value: proto down value 10096 */ 10097 void netdev_change_proto_down_reason_locked(struct net_device *dev, 10098 unsigned long mask, u32 value) 10099 { 10100 u32 proto_down_reason; 10101 int b; 10102 10103 if (!mask) { 10104 proto_down_reason = value; 10105 } else { 10106 proto_down_reason = dev->proto_down_reason; 10107 for_each_set_bit(b, &mask, 32) { 10108 if (value & (1 << b)) 10109 proto_down_reason |= BIT(b); 10110 else 10111 proto_down_reason &= ~BIT(b); 10112 } 10113 } 10114 WRITE_ONCE(dev->proto_down_reason, proto_down_reason); 10115 } 10116 10117 struct bpf_xdp_link { 10118 struct bpf_link link; 10119 struct net_device *dev; /* protected by rtnl_lock, no refcnt held */ 10120 int flags; 10121 }; 10122 10123 static enum bpf_xdp_mode dev_xdp_mode(struct net_device *dev, u32 flags) 10124 { 10125 if (flags & XDP_FLAGS_HW_MODE) 10126 return XDP_MODE_HW; 10127 if (flags & XDP_FLAGS_DRV_MODE) 10128 return XDP_MODE_DRV; 10129 if (flags & XDP_FLAGS_SKB_MODE) 10130 return XDP_MODE_SKB; 10131 return dev->netdev_ops->ndo_bpf ? XDP_MODE_DRV : XDP_MODE_SKB; 10132 } 10133 10134 static bpf_op_t dev_xdp_bpf_op(struct net_device *dev, enum bpf_xdp_mode mode) 10135 { 10136 switch (mode) { 10137 case XDP_MODE_SKB: 10138 return generic_xdp_install; 10139 case XDP_MODE_DRV: 10140 case XDP_MODE_HW: 10141 return dev->netdev_ops->ndo_bpf; 10142 default: 10143 return NULL; 10144 } 10145 } 10146 10147 static struct bpf_xdp_link *dev_xdp_link(struct net_device *dev, 10148 enum bpf_xdp_mode mode) 10149 { 10150 return dev->xdp_state[mode].link; 10151 } 10152 10153 static struct bpf_prog *dev_xdp_prog(struct net_device *dev, 10154 enum bpf_xdp_mode mode) 10155 { 10156 struct bpf_xdp_link *link = dev_xdp_link(dev, mode); 10157 10158 if (link) 10159 return link->link.prog; 10160 return dev->xdp_state[mode].prog; 10161 } 10162 10163 u8 dev_xdp_prog_count(struct net_device *dev) 10164 { 10165 u8 count = 0; 10166 int i; 10167 10168 for (i = 0; i < __MAX_XDP_MODE; i++) 10169 if (dev->xdp_state[i].prog || dev->xdp_state[i].link) 10170 count++; 10171 return count; 10172 } 10173 EXPORT_SYMBOL_GPL(dev_xdp_prog_count); 10174 10175 u8 dev_xdp_sb_prog_count(struct net_device *dev) 10176 { 10177 u8 count = 0; 10178 int i; 10179 10180 for (i = 0; i < __MAX_XDP_MODE; i++) 10181 if (dev->xdp_state[i].prog && 10182 !dev->xdp_state[i].prog->aux->xdp_has_frags) 10183 count++; 10184 return count; 10185 } 10186 10187 int netif_xdp_propagate(struct net_device *dev, struct netdev_bpf *bpf) 10188 { 10189 if (!dev->netdev_ops->ndo_bpf) 10190 return -EOPNOTSUPP; 10191 10192 if (dev->cfg->hds_config == ETHTOOL_TCP_DATA_SPLIT_ENABLED && 10193 bpf->command == XDP_SETUP_PROG && 10194 bpf->prog && !bpf->prog->aux->xdp_has_frags) { 10195 NL_SET_ERR_MSG(bpf->extack, 10196 "unable to propagate XDP to device using tcp-data-split"); 10197 return -EBUSY; 10198 } 10199 10200 if (dev_get_min_mp_channel_count(dev)) { 10201 NL_SET_ERR_MSG(bpf->extack, "unable to propagate XDP to device using memory provider"); 10202 return -EBUSY; 10203 } 10204 10205 return dev->netdev_ops->ndo_bpf(dev, bpf); 10206 } 10207 EXPORT_SYMBOL_GPL(netif_xdp_propagate); 10208 10209 u32 dev_xdp_prog_id(struct net_device *dev, enum bpf_xdp_mode mode) 10210 { 10211 struct bpf_prog *prog = dev_xdp_prog(dev, mode); 10212 10213 return prog ? prog->aux->id : 0; 10214 } 10215 10216 static void dev_xdp_set_link(struct net_device *dev, enum bpf_xdp_mode mode, 10217 struct bpf_xdp_link *link) 10218 { 10219 dev->xdp_state[mode].link = link; 10220 dev->xdp_state[mode].prog = NULL; 10221 } 10222 10223 static void dev_xdp_set_prog(struct net_device *dev, enum bpf_xdp_mode mode, 10224 struct bpf_prog *prog) 10225 { 10226 dev->xdp_state[mode].link = NULL; 10227 dev->xdp_state[mode].prog = prog; 10228 } 10229 10230 static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode, 10231 bpf_op_t bpf_op, struct netlink_ext_ack *extack, 10232 u32 flags, struct bpf_prog *prog) 10233 { 10234 struct netdev_bpf xdp; 10235 int err; 10236 10237 netdev_ops_assert_locked(dev); 10238 10239 if (dev->cfg->hds_config == ETHTOOL_TCP_DATA_SPLIT_ENABLED && 10240 prog && !prog->aux->xdp_has_frags) { 10241 NL_SET_ERR_MSG(extack, "unable to install XDP to device using tcp-data-split"); 10242 return -EBUSY; 10243 } 10244 10245 if (dev_get_min_mp_channel_count(dev)) { 10246 NL_SET_ERR_MSG(extack, "unable to install XDP to device using memory provider"); 10247 return -EBUSY; 10248 } 10249 10250 memset(&xdp, 0, sizeof(xdp)); 10251 xdp.command = mode == XDP_MODE_HW ? XDP_SETUP_PROG_HW : XDP_SETUP_PROG; 10252 xdp.extack = extack; 10253 xdp.flags = flags; 10254 xdp.prog = prog; 10255 10256 /* Drivers assume refcnt is already incremented (i.e, prog pointer is 10257 * "moved" into driver), so they don't increment it on their own, but 10258 * they do decrement refcnt when program is detached or replaced. 10259 * Given net_device also owns link/prog, we need to bump refcnt here 10260 * to prevent drivers from underflowing it. 10261 */ 10262 if (prog) 10263 bpf_prog_inc(prog); 10264 err = bpf_op(dev, &xdp); 10265 if (err) { 10266 if (prog) 10267 bpf_prog_put(prog); 10268 return err; 10269 } 10270 10271 if (mode != XDP_MODE_HW) 10272 bpf_prog_change_xdp(dev_xdp_prog(dev, mode), prog); 10273 10274 return 0; 10275 } 10276 10277 static void dev_xdp_uninstall(struct net_device *dev) 10278 { 10279 struct bpf_xdp_link *link; 10280 struct bpf_prog *prog; 10281 enum bpf_xdp_mode mode; 10282 bpf_op_t bpf_op; 10283 10284 ASSERT_RTNL(); 10285 10286 for (mode = XDP_MODE_SKB; mode < __MAX_XDP_MODE; mode++) { 10287 prog = dev_xdp_prog(dev, mode); 10288 if (!prog) 10289 continue; 10290 10291 bpf_op = dev_xdp_bpf_op(dev, mode); 10292 if (!bpf_op) 10293 continue; 10294 10295 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL)); 10296 10297 /* auto-detach link from net device */ 10298 link = dev_xdp_link(dev, mode); 10299 if (link) 10300 link->dev = NULL; 10301 else 10302 bpf_prog_put(prog); 10303 10304 dev_xdp_set_link(dev, mode, NULL); 10305 } 10306 } 10307 10308 static int dev_xdp_attach(struct net_device *dev, struct netlink_ext_ack *extack, 10309 struct bpf_xdp_link *link, struct bpf_prog *new_prog, 10310 struct bpf_prog *old_prog, u32 flags) 10311 { 10312 unsigned int num_modes = hweight32(flags & XDP_FLAGS_MODES); 10313 struct bpf_prog *cur_prog; 10314 struct net_device *upper; 10315 struct list_head *iter; 10316 enum bpf_xdp_mode mode; 10317 bpf_op_t bpf_op; 10318 int err; 10319 10320 ASSERT_RTNL(); 10321 10322 /* either link or prog attachment, never both */ 10323 if (link && (new_prog || old_prog)) 10324 return -EINVAL; 10325 /* link supports only XDP mode flags */ 10326 if (link && (flags & ~XDP_FLAGS_MODES)) { 10327 NL_SET_ERR_MSG(extack, "Invalid XDP flags for BPF link attachment"); 10328 return -EINVAL; 10329 } 10330 /* just one XDP mode bit should be set, zero defaults to drv/skb mode */ 10331 if (num_modes > 1) { 10332 NL_SET_ERR_MSG(extack, "Only one XDP mode flag can be set"); 10333 return -EINVAL; 10334 } 10335 /* avoid ambiguity if offload + drv/skb mode progs are both loaded */ 10336 if (!num_modes && dev_xdp_prog_count(dev) > 1) { 10337 NL_SET_ERR_MSG(extack, 10338 "More than one program loaded, unset mode is ambiguous"); 10339 return -EINVAL; 10340 } 10341 /* old_prog != NULL implies XDP_FLAGS_REPLACE is set */ 10342 if (old_prog && !(flags & XDP_FLAGS_REPLACE)) { 10343 NL_SET_ERR_MSG(extack, "XDP_FLAGS_REPLACE is not specified"); 10344 return -EINVAL; 10345 } 10346 10347 mode = dev_xdp_mode(dev, flags); 10348 /* can't replace attached link */ 10349 if (dev_xdp_link(dev, mode)) { 10350 NL_SET_ERR_MSG(extack, "Can't replace active BPF XDP link"); 10351 return -EBUSY; 10352 } 10353 10354 /* don't allow if an upper device already has a program */ 10355 netdev_for_each_upper_dev_rcu(dev, upper, iter) { 10356 if (dev_xdp_prog_count(upper) > 0) { 10357 NL_SET_ERR_MSG(extack, "Cannot attach when an upper device already has a program"); 10358 return -EEXIST; 10359 } 10360 } 10361 10362 cur_prog = dev_xdp_prog(dev, mode); 10363 /* can't replace attached prog with link */ 10364 if (link && cur_prog) { 10365 NL_SET_ERR_MSG(extack, "Can't replace active XDP program with BPF link"); 10366 return -EBUSY; 10367 } 10368 if ((flags & XDP_FLAGS_REPLACE) && cur_prog != old_prog) { 10369 NL_SET_ERR_MSG(extack, "Active program does not match expected"); 10370 return -EEXIST; 10371 } 10372 10373 /* put effective new program into new_prog */ 10374 if (link) 10375 new_prog = link->link.prog; 10376 10377 if (new_prog) { 10378 bool offload = mode == XDP_MODE_HW; 10379 enum bpf_xdp_mode other_mode = mode == XDP_MODE_SKB 10380 ? XDP_MODE_DRV : XDP_MODE_SKB; 10381 10382 if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) && cur_prog) { 10383 NL_SET_ERR_MSG(extack, "XDP program already attached"); 10384 return -EBUSY; 10385 } 10386 if (!offload && dev_xdp_prog(dev, other_mode)) { 10387 NL_SET_ERR_MSG(extack, "Native and generic XDP can't be active at the same time"); 10388 return -EEXIST; 10389 } 10390 if (!offload && bpf_prog_is_offloaded(new_prog->aux)) { 10391 NL_SET_ERR_MSG(extack, "Using offloaded program without HW_MODE flag is not supported"); 10392 return -EINVAL; 10393 } 10394 if (bpf_prog_is_dev_bound(new_prog->aux) && !bpf_offload_dev_match(new_prog, dev)) { 10395 NL_SET_ERR_MSG(extack, "Program bound to different device"); 10396 return -EINVAL; 10397 } 10398 if (bpf_prog_is_dev_bound(new_prog->aux) && mode == XDP_MODE_SKB) { 10399 NL_SET_ERR_MSG(extack, "Can't attach device-bound programs in generic mode"); 10400 return -EINVAL; 10401 } 10402 if (new_prog->expected_attach_type == BPF_XDP_DEVMAP) { 10403 NL_SET_ERR_MSG(extack, "BPF_XDP_DEVMAP programs can not be attached to a device"); 10404 return -EINVAL; 10405 } 10406 if (new_prog->expected_attach_type == BPF_XDP_CPUMAP) { 10407 NL_SET_ERR_MSG(extack, "BPF_XDP_CPUMAP programs can not be attached to a device"); 10408 return -EINVAL; 10409 } 10410 } 10411 10412 /* don't call drivers if the effective program didn't change */ 10413 if (new_prog != cur_prog) { 10414 bpf_op = dev_xdp_bpf_op(dev, mode); 10415 if (!bpf_op) { 10416 NL_SET_ERR_MSG(extack, "Underlying driver does not support XDP in native mode"); 10417 return -EOPNOTSUPP; 10418 } 10419 10420 err = dev_xdp_install(dev, mode, bpf_op, extack, flags, new_prog); 10421 if (err) 10422 return err; 10423 } 10424 10425 if (link) 10426 dev_xdp_set_link(dev, mode, link); 10427 else 10428 dev_xdp_set_prog(dev, mode, new_prog); 10429 if (cur_prog) 10430 bpf_prog_put(cur_prog); 10431 10432 return 0; 10433 } 10434 10435 static int dev_xdp_attach_link(struct net_device *dev, 10436 struct netlink_ext_ack *extack, 10437 struct bpf_xdp_link *link) 10438 { 10439 return dev_xdp_attach(dev, extack, link, NULL, NULL, link->flags); 10440 } 10441 10442 static int dev_xdp_detach_link(struct net_device *dev, 10443 struct netlink_ext_ack *extack, 10444 struct bpf_xdp_link *link) 10445 { 10446 enum bpf_xdp_mode mode; 10447 bpf_op_t bpf_op; 10448 10449 ASSERT_RTNL(); 10450 10451 mode = dev_xdp_mode(dev, link->flags); 10452 if (dev_xdp_link(dev, mode) != link) 10453 return -EINVAL; 10454 10455 bpf_op = dev_xdp_bpf_op(dev, mode); 10456 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL)); 10457 dev_xdp_set_link(dev, mode, NULL); 10458 return 0; 10459 } 10460 10461 static void bpf_xdp_link_release(struct bpf_link *link) 10462 { 10463 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link); 10464 10465 rtnl_lock(); 10466 10467 /* if racing with net_device's tear down, xdp_link->dev might be 10468 * already NULL, in which case link was already auto-detached 10469 */ 10470 if (xdp_link->dev) { 10471 netdev_lock_ops(xdp_link->dev); 10472 WARN_ON(dev_xdp_detach_link(xdp_link->dev, NULL, xdp_link)); 10473 netdev_unlock_ops(xdp_link->dev); 10474 xdp_link->dev = NULL; 10475 } 10476 10477 rtnl_unlock(); 10478 } 10479 10480 static int bpf_xdp_link_detach(struct bpf_link *link) 10481 { 10482 bpf_xdp_link_release(link); 10483 return 0; 10484 } 10485 10486 static void bpf_xdp_link_dealloc(struct bpf_link *link) 10487 { 10488 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link); 10489 10490 kfree(xdp_link); 10491 } 10492 10493 static void bpf_xdp_link_show_fdinfo(const struct bpf_link *link, 10494 struct seq_file *seq) 10495 { 10496 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link); 10497 u32 ifindex = 0; 10498 10499 rtnl_lock(); 10500 if (xdp_link->dev) 10501 ifindex = xdp_link->dev->ifindex; 10502 rtnl_unlock(); 10503 10504 seq_printf(seq, "ifindex:\t%u\n", ifindex); 10505 } 10506 10507 static int bpf_xdp_link_fill_link_info(const struct bpf_link *link, 10508 struct bpf_link_info *info) 10509 { 10510 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link); 10511 u32 ifindex = 0; 10512 10513 rtnl_lock(); 10514 if (xdp_link->dev) 10515 ifindex = xdp_link->dev->ifindex; 10516 rtnl_unlock(); 10517 10518 info->xdp.ifindex = ifindex; 10519 return 0; 10520 } 10521 10522 static int bpf_xdp_link_update(struct bpf_link *link, struct bpf_prog *new_prog, 10523 struct bpf_prog *old_prog) 10524 { 10525 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link); 10526 enum bpf_xdp_mode mode; 10527 bpf_op_t bpf_op; 10528 int err = 0; 10529 10530 rtnl_lock(); 10531 10532 /* link might have been auto-released already, so fail */ 10533 if (!xdp_link->dev) { 10534 err = -ENOLINK; 10535 goto out_unlock; 10536 } 10537 10538 if (old_prog && link->prog != old_prog) { 10539 err = -EPERM; 10540 goto out_unlock; 10541 } 10542 old_prog = link->prog; 10543 if (old_prog->type != new_prog->type || 10544 old_prog->expected_attach_type != new_prog->expected_attach_type) { 10545 err = -EINVAL; 10546 goto out_unlock; 10547 } 10548 10549 if (old_prog == new_prog) { 10550 /* no-op, don't disturb drivers */ 10551 bpf_prog_put(new_prog); 10552 goto out_unlock; 10553 } 10554 10555 netdev_lock_ops(xdp_link->dev); 10556 mode = dev_xdp_mode(xdp_link->dev, xdp_link->flags); 10557 bpf_op = dev_xdp_bpf_op(xdp_link->dev, mode); 10558 err = dev_xdp_install(xdp_link->dev, mode, bpf_op, NULL, 10559 xdp_link->flags, new_prog); 10560 netdev_unlock_ops(xdp_link->dev); 10561 if (err) 10562 goto out_unlock; 10563 10564 old_prog = xchg(&link->prog, new_prog); 10565 bpf_prog_put(old_prog); 10566 10567 out_unlock: 10568 rtnl_unlock(); 10569 return err; 10570 } 10571 10572 static const struct bpf_link_ops bpf_xdp_link_lops = { 10573 .release = bpf_xdp_link_release, 10574 .dealloc = bpf_xdp_link_dealloc, 10575 .detach = bpf_xdp_link_detach, 10576 .show_fdinfo = bpf_xdp_link_show_fdinfo, 10577 .fill_link_info = bpf_xdp_link_fill_link_info, 10578 .update_prog = bpf_xdp_link_update, 10579 }; 10580 10581 int bpf_xdp_link_attach(const union bpf_attr *attr, struct bpf_prog *prog) 10582 { 10583 struct net *net = current->nsproxy->net_ns; 10584 struct bpf_link_primer link_primer; 10585 struct netlink_ext_ack extack = {}; 10586 struct bpf_xdp_link *link; 10587 struct net_device *dev; 10588 int err, fd; 10589 10590 rtnl_lock(); 10591 dev = dev_get_by_index(net, attr->link_create.target_ifindex); 10592 if (!dev) { 10593 rtnl_unlock(); 10594 return -EINVAL; 10595 } 10596 10597 link = kzalloc(sizeof(*link), GFP_USER); 10598 if (!link) { 10599 err = -ENOMEM; 10600 goto unlock; 10601 } 10602 10603 bpf_link_init(&link->link, BPF_LINK_TYPE_XDP, &bpf_xdp_link_lops, prog, 10604 attr->link_create.attach_type); 10605 link->dev = dev; 10606 link->flags = attr->link_create.flags; 10607 10608 err = bpf_link_prime(&link->link, &link_primer); 10609 if (err) { 10610 kfree(link); 10611 goto unlock; 10612 } 10613 10614 netdev_lock_ops(dev); 10615 err = dev_xdp_attach_link(dev, &extack, link); 10616 netdev_unlock_ops(dev); 10617 rtnl_unlock(); 10618 10619 if (err) { 10620 link->dev = NULL; 10621 bpf_link_cleanup(&link_primer); 10622 trace_bpf_xdp_link_attach_failed(extack._msg); 10623 goto out_put_dev; 10624 } 10625 10626 fd = bpf_link_settle(&link_primer); 10627 /* link itself doesn't hold dev's refcnt to not complicate shutdown */ 10628 dev_put(dev); 10629 return fd; 10630 10631 unlock: 10632 rtnl_unlock(); 10633 10634 out_put_dev: 10635 dev_put(dev); 10636 return err; 10637 } 10638 10639 /** 10640 * dev_change_xdp_fd - set or clear a bpf program for a device rx path 10641 * @dev: device 10642 * @extack: netlink extended ack 10643 * @fd: new program fd or negative value to clear 10644 * @expected_fd: old program fd that userspace expects to replace or clear 10645 * @flags: xdp-related flags 10646 * 10647 * Set or clear a bpf program for a device 10648 */ 10649 int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack, 10650 int fd, int expected_fd, u32 flags) 10651 { 10652 enum bpf_xdp_mode mode = dev_xdp_mode(dev, flags); 10653 struct bpf_prog *new_prog = NULL, *old_prog = NULL; 10654 int err; 10655 10656 ASSERT_RTNL(); 10657 10658 if (fd >= 0) { 10659 new_prog = bpf_prog_get_type_dev(fd, BPF_PROG_TYPE_XDP, 10660 mode != XDP_MODE_SKB); 10661 if (IS_ERR(new_prog)) 10662 return PTR_ERR(new_prog); 10663 } 10664 10665 if (expected_fd >= 0) { 10666 old_prog = bpf_prog_get_type_dev(expected_fd, BPF_PROG_TYPE_XDP, 10667 mode != XDP_MODE_SKB); 10668 if (IS_ERR(old_prog)) { 10669 err = PTR_ERR(old_prog); 10670 old_prog = NULL; 10671 goto err_out; 10672 } 10673 } 10674 10675 err = dev_xdp_attach(dev, extack, NULL, new_prog, old_prog, flags); 10676 10677 err_out: 10678 if (err && new_prog) 10679 bpf_prog_put(new_prog); 10680 if (old_prog) 10681 bpf_prog_put(old_prog); 10682 return err; 10683 } 10684 10685 u32 dev_get_min_mp_channel_count(const struct net_device *dev) 10686 { 10687 int i; 10688 10689 netdev_ops_assert_locked(dev); 10690 10691 for (i = dev->real_num_rx_queues - 1; i >= 0; i--) 10692 if (dev->_rx[i].mp_params.mp_priv) 10693 /* The channel count is the idx plus 1. */ 10694 return i + 1; 10695 10696 return 0; 10697 } 10698 10699 /** 10700 * dev_index_reserve() - allocate an ifindex in a namespace 10701 * @net: the applicable net namespace 10702 * @ifindex: requested ifindex, pass %0 to get one allocated 10703 * 10704 * Allocate a ifindex for a new device. Caller must either use the ifindex 10705 * to store the device (via list_netdevice()) or call dev_index_release() 10706 * to give the index up. 10707 * 10708 * Return: a suitable unique value for a new device interface number or -errno. 10709 */ 10710 static int dev_index_reserve(struct net *net, u32 ifindex) 10711 { 10712 int err; 10713 10714 if (ifindex > INT_MAX) { 10715 DEBUG_NET_WARN_ON_ONCE(1); 10716 return -EINVAL; 10717 } 10718 10719 if (!ifindex) 10720 err = xa_alloc_cyclic(&net->dev_by_index, &ifindex, NULL, 10721 xa_limit_31b, &net->ifindex, GFP_KERNEL); 10722 else 10723 err = xa_insert(&net->dev_by_index, ifindex, NULL, GFP_KERNEL); 10724 if (err < 0) 10725 return err; 10726 10727 return ifindex; 10728 } 10729 10730 static void dev_index_release(struct net *net, int ifindex) 10731 { 10732 /* Expect only unused indexes, unlist_netdevice() removes the used */ 10733 WARN_ON(xa_erase(&net->dev_by_index, ifindex)); 10734 } 10735 10736 static bool from_cleanup_net(void) 10737 { 10738 #ifdef CONFIG_NET_NS 10739 return current == READ_ONCE(cleanup_net_task); 10740 #else 10741 return false; 10742 #endif 10743 } 10744 10745 /* Delayed registration/unregisteration */ 10746 LIST_HEAD(net_todo_list); 10747 DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq); 10748 atomic_t dev_unreg_count = ATOMIC_INIT(0); 10749 10750 static void net_set_todo(struct net_device *dev) 10751 { 10752 list_add_tail(&dev->todo_list, &net_todo_list); 10753 } 10754 10755 static netdev_features_t netdev_sync_upper_features(struct net_device *lower, 10756 struct net_device *upper, netdev_features_t features) 10757 { 10758 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES; 10759 netdev_features_t feature; 10760 int feature_bit; 10761 10762 for_each_netdev_feature(upper_disables, feature_bit) { 10763 feature = __NETIF_F_BIT(feature_bit); 10764 if (!(upper->wanted_features & feature) 10765 && (features & feature)) { 10766 netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n", 10767 &feature, upper->name); 10768 features &= ~feature; 10769 } 10770 } 10771 10772 return features; 10773 } 10774 10775 static void netdev_sync_lower_features(struct net_device *upper, 10776 struct net_device *lower, netdev_features_t features) 10777 { 10778 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES; 10779 netdev_features_t feature; 10780 int feature_bit; 10781 10782 for_each_netdev_feature(upper_disables, feature_bit) { 10783 feature = __NETIF_F_BIT(feature_bit); 10784 if (!(features & feature) && (lower->features & feature)) { 10785 netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n", 10786 &feature, lower->name); 10787 netdev_lock_ops(lower); 10788 lower->wanted_features &= ~feature; 10789 __netdev_update_features(lower); 10790 10791 if (unlikely(lower->features & feature)) 10792 netdev_WARN(upper, "failed to disable %pNF on %s!\n", 10793 &feature, lower->name); 10794 else 10795 netdev_features_change(lower); 10796 netdev_unlock_ops(lower); 10797 } 10798 } 10799 } 10800 10801 static bool netdev_has_ip_or_hw_csum(netdev_features_t features) 10802 { 10803 netdev_features_t ip_csum_mask = NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM; 10804 bool ip_csum = (features & ip_csum_mask) == ip_csum_mask; 10805 bool hw_csum = features & NETIF_F_HW_CSUM; 10806 10807 return ip_csum || hw_csum; 10808 } 10809 10810 static netdev_features_t netdev_fix_features(struct net_device *dev, 10811 netdev_features_t features) 10812 { 10813 /* Fix illegal checksum combinations */ 10814 if ((features & NETIF_F_HW_CSUM) && 10815 (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) { 10816 netdev_warn(dev, "mixed HW and IP checksum settings.\n"); 10817 features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM); 10818 } 10819 10820 /* TSO requires that SG is present as well. */ 10821 if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) { 10822 netdev_dbg(dev, "Dropping TSO features since no SG feature.\n"); 10823 features &= ~NETIF_F_ALL_TSO; 10824 } 10825 10826 if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) && 10827 !(features & NETIF_F_IP_CSUM)) { 10828 netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n"); 10829 features &= ~NETIF_F_TSO; 10830 features &= ~NETIF_F_TSO_ECN; 10831 } 10832 10833 if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) && 10834 !(features & NETIF_F_IPV6_CSUM)) { 10835 netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n"); 10836 features &= ~NETIF_F_TSO6; 10837 } 10838 10839 /* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */ 10840 if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO)) 10841 features &= ~NETIF_F_TSO_MANGLEID; 10842 10843 /* TSO ECN requires that TSO is present as well. */ 10844 if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN) 10845 features &= ~NETIF_F_TSO_ECN; 10846 10847 /* Software GSO depends on SG. */ 10848 if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) { 10849 netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n"); 10850 features &= ~NETIF_F_GSO; 10851 } 10852 10853 /* GSO partial features require GSO partial be set */ 10854 if ((features & dev->gso_partial_features) && 10855 !(features & NETIF_F_GSO_PARTIAL)) { 10856 netdev_dbg(dev, 10857 "Dropping partially supported GSO features since no GSO partial.\n"); 10858 features &= ~dev->gso_partial_features; 10859 } 10860 10861 if (!(features & NETIF_F_RXCSUM)) { 10862 /* NETIF_F_GRO_HW implies doing RXCSUM since every packet 10863 * successfully merged by hardware must also have the 10864 * checksum verified by hardware. If the user does not 10865 * want to enable RXCSUM, logically, we should disable GRO_HW. 10866 */ 10867 if (features & NETIF_F_GRO_HW) { 10868 netdev_dbg(dev, "Dropping NETIF_F_GRO_HW since no RXCSUM feature.\n"); 10869 features &= ~NETIF_F_GRO_HW; 10870 } 10871 } 10872 10873 /* LRO/HW-GRO features cannot be combined with RX-FCS */ 10874 if (features & NETIF_F_RXFCS) { 10875 if (features & NETIF_F_LRO) { 10876 netdev_dbg(dev, "Dropping LRO feature since RX-FCS is requested.\n"); 10877 features &= ~NETIF_F_LRO; 10878 } 10879 10880 if (features & NETIF_F_GRO_HW) { 10881 netdev_dbg(dev, "Dropping HW-GRO feature since RX-FCS is requested.\n"); 10882 features &= ~NETIF_F_GRO_HW; 10883 } 10884 } 10885 10886 if ((features & NETIF_F_GRO_HW) && (features & NETIF_F_LRO)) { 10887 netdev_dbg(dev, "Dropping LRO feature since HW-GRO is requested.\n"); 10888 features &= ~NETIF_F_LRO; 10889 } 10890 10891 if ((features & NETIF_F_HW_TLS_TX) && !netdev_has_ip_or_hw_csum(features)) { 10892 netdev_dbg(dev, "Dropping TLS TX HW offload feature since no CSUM feature.\n"); 10893 features &= ~NETIF_F_HW_TLS_TX; 10894 } 10895 10896 if ((features & NETIF_F_HW_TLS_RX) && !(features & NETIF_F_RXCSUM)) { 10897 netdev_dbg(dev, "Dropping TLS RX HW offload feature since no RXCSUM feature.\n"); 10898 features &= ~NETIF_F_HW_TLS_RX; 10899 } 10900 10901 if ((features & NETIF_F_GSO_UDP_L4) && !netdev_has_ip_or_hw_csum(features)) { 10902 netdev_dbg(dev, "Dropping USO feature since no CSUM feature.\n"); 10903 features &= ~NETIF_F_GSO_UDP_L4; 10904 } 10905 10906 return features; 10907 } 10908 10909 int __netdev_update_features(struct net_device *dev) 10910 { 10911 struct net_device *upper, *lower; 10912 netdev_features_t features; 10913 struct list_head *iter; 10914 int err = -1; 10915 10916 ASSERT_RTNL(); 10917 netdev_ops_assert_locked(dev); 10918 10919 features = netdev_get_wanted_features(dev); 10920 10921 if (dev->netdev_ops->ndo_fix_features) 10922 features = dev->netdev_ops->ndo_fix_features(dev, features); 10923 10924 /* driver might be less strict about feature dependencies */ 10925 features = netdev_fix_features(dev, features); 10926 10927 /* some features can't be enabled if they're off on an upper device */ 10928 netdev_for_each_upper_dev_rcu(dev, upper, iter) 10929 features = netdev_sync_upper_features(dev, upper, features); 10930 10931 if (dev->features == features) 10932 goto sync_lower; 10933 10934 netdev_dbg(dev, "Features changed: %pNF -> %pNF\n", 10935 &dev->features, &features); 10936 10937 if (dev->netdev_ops->ndo_set_features) 10938 err = dev->netdev_ops->ndo_set_features(dev, features); 10939 else 10940 err = 0; 10941 10942 if (unlikely(err < 0)) { 10943 netdev_err(dev, 10944 "set_features() failed (%d); wanted %pNF, left %pNF\n", 10945 err, &features, &dev->features); 10946 /* return non-0 since some features might have changed and 10947 * it's better to fire a spurious notification than miss it 10948 */ 10949 return -1; 10950 } 10951 10952 sync_lower: 10953 /* some features must be disabled on lower devices when disabled 10954 * on an upper device (think: bonding master or bridge) 10955 */ 10956 netdev_for_each_lower_dev(dev, lower, iter) 10957 netdev_sync_lower_features(dev, lower, features); 10958 10959 if (!err) { 10960 netdev_features_t diff = features ^ dev->features; 10961 10962 if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) { 10963 /* udp_tunnel_{get,drop}_rx_info both need 10964 * NETIF_F_RX_UDP_TUNNEL_PORT enabled on the 10965 * device, or they won't do anything. 10966 * Thus we need to update dev->features 10967 * *before* calling udp_tunnel_get_rx_info, 10968 * but *after* calling udp_tunnel_drop_rx_info. 10969 */ 10970 udp_tunnel_nic_lock(dev); 10971 if (features & NETIF_F_RX_UDP_TUNNEL_PORT) { 10972 dev->features = features; 10973 udp_tunnel_get_rx_info(dev); 10974 } else { 10975 udp_tunnel_drop_rx_info(dev); 10976 } 10977 udp_tunnel_nic_unlock(dev); 10978 } 10979 10980 if (diff & NETIF_F_HW_VLAN_CTAG_FILTER) { 10981 if (features & NETIF_F_HW_VLAN_CTAG_FILTER) { 10982 dev->features = features; 10983 err |= vlan_get_rx_ctag_filter_info(dev); 10984 } else { 10985 vlan_drop_rx_ctag_filter_info(dev); 10986 } 10987 } 10988 10989 if (diff & NETIF_F_HW_VLAN_STAG_FILTER) { 10990 if (features & NETIF_F_HW_VLAN_STAG_FILTER) { 10991 dev->features = features; 10992 err |= vlan_get_rx_stag_filter_info(dev); 10993 } else { 10994 vlan_drop_rx_stag_filter_info(dev); 10995 } 10996 } 10997 10998 dev->features = features; 10999 } 11000 11001 return err < 0 ? 0 : 1; 11002 } 11003 11004 /** 11005 * netdev_update_features - recalculate device features 11006 * @dev: the device to check 11007 * 11008 * Recalculate dev->features set and send notifications if it 11009 * has changed. Should be called after driver or hardware dependent 11010 * conditions might have changed that influence the features. 11011 */ 11012 void netdev_update_features(struct net_device *dev) 11013 { 11014 if (__netdev_update_features(dev)) 11015 netdev_features_change(dev); 11016 } 11017 EXPORT_SYMBOL(netdev_update_features); 11018 11019 /** 11020 * netdev_change_features - recalculate device features 11021 * @dev: the device to check 11022 * 11023 * Recalculate dev->features set and send notifications even 11024 * if they have not changed. Should be called instead of 11025 * netdev_update_features() if also dev->vlan_features might 11026 * have changed to allow the changes to be propagated to stacked 11027 * VLAN devices. 11028 */ 11029 void netdev_change_features(struct net_device *dev) 11030 { 11031 __netdev_update_features(dev); 11032 netdev_features_change(dev); 11033 } 11034 EXPORT_SYMBOL(netdev_change_features); 11035 11036 /** 11037 * netif_stacked_transfer_operstate - transfer operstate 11038 * @rootdev: the root or lower level device to transfer state from 11039 * @dev: the device to transfer operstate to 11040 * 11041 * Transfer operational state from root to device. This is normally 11042 * called when a stacking relationship exists between the root 11043 * device and the device(a leaf device). 11044 */ 11045 void netif_stacked_transfer_operstate(const struct net_device *rootdev, 11046 struct net_device *dev) 11047 { 11048 if (rootdev->operstate == IF_OPER_DORMANT) 11049 netif_dormant_on(dev); 11050 else 11051 netif_dormant_off(dev); 11052 11053 if (rootdev->operstate == IF_OPER_TESTING) 11054 netif_testing_on(dev); 11055 else 11056 netif_testing_off(dev); 11057 11058 if (netif_carrier_ok(rootdev)) 11059 netif_carrier_on(dev); 11060 else 11061 netif_carrier_off(dev); 11062 } 11063 EXPORT_SYMBOL(netif_stacked_transfer_operstate); 11064 11065 static int netif_alloc_rx_queues(struct net_device *dev) 11066 { 11067 unsigned int i, count = dev->num_rx_queues; 11068 struct netdev_rx_queue *rx; 11069 size_t sz = count * sizeof(*rx); 11070 int err = 0; 11071 11072 BUG_ON(count < 1); 11073 11074 rx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL); 11075 if (!rx) 11076 return -ENOMEM; 11077 11078 dev->_rx = rx; 11079 11080 for (i = 0; i < count; i++) { 11081 rx[i].dev = dev; 11082 11083 /* XDP RX-queue setup */ 11084 err = xdp_rxq_info_reg(&rx[i].xdp_rxq, dev, i, 0); 11085 if (err < 0) 11086 goto err_rxq_info; 11087 } 11088 return 0; 11089 11090 err_rxq_info: 11091 /* Rollback successful reg's and free other resources */ 11092 while (i--) 11093 xdp_rxq_info_unreg(&rx[i].xdp_rxq); 11094 kvfree(dev->_rx); 11095 dev->_rx = NULL; 11096 return err; 11097 } 11098 11099 static void netif_free_rx_queues(struct net_device *dev) 11100 { 11101 unsigned int i, count = dev->num_rx_queues; 11102 11103 /* netif_alloc_rx_queues alloc failed, resources have been unreg'ed */ 11104 if (!dev->_rx) 11105 return; 11106 11107 for (i = 0; i < count; i++) 11108 xdp_rxq_info_unreg(&dev->_rx[i].xdp_rxq); 11109 11110 kvfree(dev->_rx); 11111 } 11112 11113 static void netdev_init_one_queue(struct net_device *dev, 11114 struct netdev_queue *queue, void *_unused) 11115 { 11116 /* Initialize queue lock */ 11117 spin_lock_init(&queue->_xmit_lock); 11118 netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type); 11119 queue->xmit_lock_owner = -1; 11120 netdev_queue_numa_node_write(queue, NUMA_NO_NODE); 11121 queue->dev = dev; 11122 #ifdef CONFIG_BQL 11123 dql_init(&queue->dql, HZ); 11124 #endif 11125 } 11126 11127 static void netif_free_tx_queues(struct net_device *dev) 11128 { 11129 kvfree(dev->_tx); 11130 } 11131 11132 static int netif_alloc_netdev_queues(struct net_device *dev) 11133 { 11134 unsigned int count = dev->num_tx_queues; 11135 struct netdev_queue *tx; 11136 size_t sz = count * sizeof(*tx); 11137 11138 if (count < 1 || count > 0xffff) 11139 return -EINVAL; 11140 11141 tx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL); 11142 if (!tx) 11143 return -ENOMEM; 11144 11145 dev->_tx = tx; 11146 11147 netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL); 11148 spin_lock_init(&dev->tx_global_lock); 11149 11150 return 0; 11151 } 11152 11153 void netif_tx_stop_all_queues(struct net_device *dev) 11154 { 11155 unsigned int i; 11156 11157 for (i = 0; i < dev->num_tx_queues; i++) { 11158 struct netdev_queue *txq = netdev_get_tx_queue(dev, i); 11159 11160 netif_tx_stop_queue(txq); 11161 } 11162 } 11163 EXPORT_SYMBOL(netif_tx_stop_all_queues); 11164 11165 static int netdev_do_alloc_pcpu_stats(struct net_device *dev) 11166 { 11167 void __percpu *v; 11168 11169 /* Drivers implementing ndo_get_peer_dev must support tstat 11170 * accounting, so that skb_do_redirect() can bump the dev's 11171 * RX stats upon network namespace switch. 11172 */ 11173 if (dev->netdev_ops->ndo_get_peer_dev && 11174 dev->pcpu_stat_type != NETDEV_PCPU_STAT_TSTATS) 11175 return -EOPNOTSUPP; 11176 11177 switch (dev->pcpu_stat_type) { 11178 case NETDEV_PCPU_STAT_NONE: 11179 return 0; 11180 case NETDEV_PCPU_STAT_LSTATS: 11181 v = dev->lstats = netdev_alloc_pcpu_stats(struct pcpu_lstats); 11182 break; 11183 case NETDEV_PCPU_STAT_TSTATS: 11184 v = dev->tstats = netdev_alloc_pcpu_stats(struct pcpu_sw_netstats); 11185 break; 11186 case NETDEV_PCPU_STAT_DSTATS: 11187 v = dev->dstats = netdev_alloc_pcpu_stats(struct pcpu_dstats); 11188 break; 11189 default: 11190 return -EINVAL; 11191 } 11192 11193 return v ? 0 : -ENOMEM; 11194 } 11195 11196 static void netdev_do_free_pcpu_stats(struct net_device *dev) 11197 { 11198 switch (dev->pcpu_stat_type) { 11199 case NETDEV_PCPU_STAT_NONE: 11200 return; 11201 case NETDEV_PCPU_STAT_LSTATS: 11202 free_percpu(dev->lstats); 11203 break; 11204 case NETDEV_PCPU_STAT_TSTATS: 11205 free_percpu(dev->tstats); 11206 break; 11207 case NETDEV_PCPU_STAT_DSTATS: 11208 free_percpu(dev->dstats); 11209 break; 11210 } 11211 } 11212 11213 static void netdev_free_phy_link_topology(struct net_device *dev) 11214 { 11215 struct phy_link_topology *topo = dev->link_topo; 11216 11217 if (IS_ENABLED(CONFIG_PHYLIB) && topo) { 11218 xa_destroy(&topo->phys); 11219 kfree(topo); 11220 dev->link_topo = NULL; 11221 } 11222 } 11223 11224 /** 11225 * register_netdevice() - register a network device 11226 * @dev: device to register 11227 * 11228 * Take a prepared network device structure and make it externally accessible. 11229 * A %NETDEV_REGISTER message is sent to the netdev notifier chain. 11230 * Callers must hold the rtnl lock - you may want register_netdev() 11231 * instead of this. 11232 */ 11233 int register_netdevice(struct net_device *dev) 11234 { 11235 int ret; 11236 struct net *net = dev_net(dev); 11237 11238 BUILD_BUG_ON(sizeof(netdev_features_t) * BITS_PER_BYTE < 11239 NETDEV_FEATURE_COUNT); 11240 BUG_ON(dev_boot_phase); 11241 ASSERT_RTNL(); 11242 11243 might_sleep(); 11244 11245 /* When net_device's are persistent, this will be fatal. */ 11246 BUG_ON(dev->reg_state != NETREG_UNINITIALIZED); 11247 BUG_ON(!net); 11248 11249 ret = ethtool_check_ops(dev->ethtool_ops); 11250 if (ret) 11251 return ret; 11252 11253 /* rss ctx ID 0 is reserved for the default context, start from 1 */ 11254 xa_init_flags(&dev->ethtool->rss_ctx, XA_FLAGS_ALLOC1); 11255 mutex_init(&dev->ethtool->rss_lock); 11256 11257 spin_lock_init(&dev->addr_list_lock); 11258 netdev_set_addr_lockdep_class(dev); 11259 11260 ret = dev_get_valid_name(net, dev, dev->name); 11261 if (ret < 0) 11262 goto out; 11263 11264 ret = -ENOMEM; 11265 dev->name_node = netdev_name_node_head_alloc(dev); 11266 if (!dev->name_node) 11267 goto out; 11268 11269 /* Init, if this function is available */ 11270 if (dev->netdev_ops->ndo_init) { 11271 ret = dev->netdev_ops->ndo_init(dev); 11272 if (ret) { 11273 if (ret > 0) 11274 ret = -EIO; 11275 goto err_free_name; 11276 } 11277 } 11278 11279 if (((dev->hw_features | dev->features) & 11280 NETIF_F_HW_VLAN_CTAG_FILTER) && 11281 (!dev->netdev_ops->ndo_vlan_rx_add_vid || 11282 !dev->netdev_ops->ndo_vlan_rx_kill_vid)) { 11283 netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n"); 11284 ret = -EINVAL; 11285 goto err_uninit; 11286 } 11287 11288 ret = netdev_do_alloc_pcpu_stats(dev); 11289 if (ret) 11290 goto err_uninit; 11291 11292 ret = dev_index_reserve(net, dev->ifindex); 11293 if (ret < 0) 11294 goto err_free_pcpu; 11295 dev->ifindex = ret; 11296 11297 /* Transfer changeable features to wanted_features and enable 11298 * software offloads (GSO and GRO). 11299 */ 11300 dev->hw_features |= (NETIF_F_SOFT_FEATURES | NETIF_F_SOFT_FEATURES_OFF); 11301 dev->features |= NETIF_F_SOFT_FEATURES; 11302 11303 if (dev->udp_tunnel_nic_info) { 11304 dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT; 11305 dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT; 11306 } 11307 11308 dev->wanted_features = dev->features & dev->hw_features; 11309 11310 if (!(dev->flags & IFF_LOOPBACK)) 11311 dev->hw_features |= NETIF_F_NOCACHE_COPY; 11312 11313 /* If IPv4 TCP segmentation offload is supported we should also 11314 * allow the device to enable segmenting the frame with the option 11315 * of ignoring a static IP ID value. This doesn't enable the 11316 * feature itself but allows the user to enable it later. 11317 */ 11318 if (dev->hw_features & NETIF_F_TSO) 11319 dev->hw_features |= NETIF_F_TSO_MANGLEID; 11320 if (dev->vlan_features & NETIF_F_TSO) 11321 dev->vlan_features |= NETIF_F_TSO_MANGLEID; 11322 if (dev->mpls_features & NETIF_F_TSO) 11323 dev->mpls_features |= NETIF_F_TSO_MANGLEID; 11324 if (dev->hw_enc_features & NETIF_F_TSO) 11325 dev->hw_enc_features |= NETIF_F_TSO_MANGLEID; 11326 11327 /* Make NETIF_F_HIGHDMA inheritable to VLAN devices. 11328 */ 11329 dev->vlan_features |= NETIF_F_HIGHDMA; 11330 11331 /* Make NETIF_F_SG inheritable to tunnel devices. 11332 */ 11333 dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL; 11334 11335 /* Make NETIF_F_SG inheritable to MPLS. 11336 */ 11337 dev->mpls_features |= NETIF_F_SG; 11338 11339 ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev); 11340 ret = notifier_to_errno(ret); 11341 if (ret) 11342 goto err_ifindex_release; 11343 11344 ret = netdev_register_kobject(dev); 11345 11346 netdev_lock(dev); 11347 WRITE_ONCE(dev->reg_state, ret ? NETREG_UNREGISTERED : NETREG_REGISTERED); 11348 netdev_unlock(dev); 11349 11350 if (ret) 11351 goto err_uninit_notify; 11352 11353 netdev_lock_ops(dev); 11354 __netdev_update_features(dev); 11355 netdev_unlock_ops(dev); 11356 11357 /* 11358 * Default initial state at registry is that the 11359 * device is present. 11360 */ 11361 11362 set_bit(__LINK_STATE_PRESENT, &dev->state); 11363 11364 linkwatch_init_dev(dev); 11365 11366 dev_init_scheduler(dev); 11367 11368 netdev_hold(dev, &dev->dev_registered_tracker, GFP_KERNEL); 11369 list_netdevice(dev); 11370 11371 add_device_randomness(dev->dev_addr, dev->addr_len); 11372 11373 /* If the device has permanent device address, driver should 11374 * set dev_addr and also addr_assign_type should be set to 11375 * NET_ADDR_PERM (default value). 11376 */ 11377 if (dev->addr_assign_type == NET_ADDR_PERM) 11378 memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len); 11379 11380 /* Notify protocols, that a new device appeared. */ 11381 netdev_lock_ops(dev); 11382 ret = call_netdevice_notifiers(NETDEV_REGISTER, dev); 11383 netdev_unlock_ops(dev); 11384 ret = notifier_to_errno(ret); 11385 if (ret) { 11386 /* Expect explicit free_netdev() on failure */ 11387 dev->needs_free_netdev = false; 11388 unregister_netdevice_queue(dev, NULL); 11389 goto out; 11390 } 11391 /* 11392 * Prevent userspace races by waiting until the network 11393 * device is fully setup before sending notifications. 11394 */ 11395 if (!(dev->rtnl_link_ops && dev->rtnl_link_initializing)) 11396 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL, 0, NULL); 11397 11398 out: 11399 return ret; 11400 11401 err_uninit_notify: 11402 call_netdevice_notifiers(NETDEV_PRE_UNINIT, dev); 11403 err_ifindex_release: 11404 dev_index_release(net, dev->ifindex); 11405 err_free_pcpu: 11406 netdev_do_free_pcpu_stats(dev); 11407 err_uninit: 11408 if (dev->netdev_ops->ndo_uninit) 11409 dev->netdev_ops->ndo_uninit(dev); 11410 if (dev->priv_destructor) 11411 dev->priv_destructor(dev); 11412 err_free_name: 11413 netdev_name_node_free(dev->name_node); 11414 goto out; 11415 } 11416 EXPORT_SYMBOL(register_netdevice); 11417 11418 /* Initialize the core of a dummy net device. 11419 * The setup steps dummy netdevs need which normal netdevs get by going 11420 * through register_netdevice(). 11421 */ 11422 static void init_dummy_netdev(struct net_device *dev) 11423 { 11424 /* make sure we BUG if trying to hit standard 11425 * register/unregister code path 11426 */ 11427 dev->reg_state = NETREG_DUMMY; 11428 11429 /* a dummy interface is started by default */ 11430 set_bit(__LINK_STATE_PRESENT, &dev->state); 11431 set_bit(__LINK_STATE_START, &dev->state); 11432 11433 /* Note : We dont allocate pcpu_refcnt for dummy devices, 11434 * because users of this 'device' dont need to change 11435 * its refcount. 11436 */ 11437 } 11438 11439 /** 11440 * register_netdev - register a network device 11441 * @dev: device to register 11442 * 11443 * Take a completed network device structure and add it to the kernel 11444 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier 11445 * chain. 0 is returned on success. A negative errno code is returned 11446 * on a failure to set up the device, or if the name is a duplicate. 11447 * 11448 * This is a wrapper around register_netdevice that takes the rtnl semaphore 11449 * and expands the device name if you passed a format string to 11450 * alloc_netdev. 11451 */ 11452 int register_netdev(struct net_device *dev) 11453 { 11454 struct net *net = dev_net(dev); 11455 int err; 11456 11457 if (rtnl_net_lock_killable(net)) 11458 return -EINTR; 11459 11460 err = register_netdevice(dev); 11461 11462 rtnl_net_unlock(net); 11463 11464 return err; 11465 } 11466 EXPORT_SYMBOL(register_netdev); 11467 11468 int netdev_refcnt_read(const struct net_device *dev) 11469 { 11470 #ifdef CONFIG_PCPU_DEV_REFCNT 11471 int i, refcnt = 0; 11472 11473 for_each_possible_cpu(i) 11474 refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i); 11475 return refcnt; 11476 #else 11477 return refcount_read(&dev->dev_refcnt); 11478 #endif 11479 } 11480 EXPORT_SYMBOL(netdev_refcnt_read); 11481 11482 int netdev_unregister_timeout_secs __read_mostly = 10; 11483 11484 #define WAIT_REFS_MIN_MSECS 1 11485 #define WAIT_REFS_MAX_MSECS 250 11486 /** 11487 * netdev_wait_allrefs_any - wait until all references are gone. 11488 * @list: list of net_devices to wait on 11489 * 11490 * This is called when unregistering network devices. 11491 * 11492 * Any protocol or device that holds a reference should register 11493 * for netdevice notification, and cleanup and put back the 11494 * reference if they receive an UNREGISTER event. 11495 * We can get stuck here if buggy protocols don't correctly 11496 * call dev_put. 11497 */ 11498 static struct net_device *netdev_wait_allrefs_any(struct list_head *list) 11499 { 11500 unsigned long rebroadcast_time, warning_time; 11501 struct net_device *dev; 11502 int wait = 0; 11503 11504 rebroadcast_time = warning_time = jiffies; 11505 11506 list_for_each_entry(dev, list, todo_list) 11507 if (netdev_refcnt_read(dev) == 1) 11508 return dev; 11509 11510 while (true) { 11511 if (time_after(jiffies, rebroadcast_time + 1 * HZ)) { 11512 rtnl_lock(); 11513 11514 /* Rebroadcast unregister notification */ 11515 list_for_each_entry(dev, list, todo_list) 11516 call_netdevice_notifiers(NETDEV_UNREGISTER, dev); 11517 11518 __rtnl_unlock(); 11519 rcu_barrier(); 11520 rtnl_lock(); 11521 11522 list_for_each_entry(dev, list, todo_list) 11523 if (test_bit(__LINK_STATE_LINKWATCH_PENDING, 11524 &dev->state)) { 11525 /* We must not have linkwatch events 11526 * pending on unregister. If this 11527 * happens, we simply run the queue 11528 * unscheduled, resulting in a noop 11529 * for this device. 11530 */ 11531 linkwatch_run_queue(); 11532 break; 11533 } 11534 11535 __rtnl_unlock(); 11536 11537 rebroadcast_time = jiffies; 11538 } 11539 11540 rcu_barrier(); 11541 11542 if (!wait) { 11543 wait = WAIT_REFS_MIN_MSECS; 11544 } else { 11545 msleep(wait); 11546 wait = min(wait << 1, WAIT_REFS_MAX_MSECS); 11547 } 11548 11549 list_for_each_entry(dev, list, todo_list) 11550 if (netdev_refcnt_read(dev) == 1) 11551 return dev; 11552 11553 if (time_after(jiffies, warning_time + 11554 READ_ONCE(netdev_unregister_timeout_secs) * HZ)) { 11555 list_for_each_entry(dev, list, todo_list) { 11556 pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n", 11557 dev->name, netdev_refcnt_read(dev)); 11558 ref_tracker_dir_print(&dev->refcnt_tracker, 10); 11559 } 11560 11561 warning_time = jiffies; 11562 } 11563 } 11564 } 11565 11566 /* The sequence is: 11567 * 11568 * rtnl_lock(); 11569 * ... 11570 * register_netdevice(x1); 11571 * register_netdevice(x2); 11572 * ... 11573 * unregister_netdevice(y1); 11574 * unregister_netdevice(y2); 11575 * ... 11576 * rtnl_unlock(); 11577 * free_netdev(y1); 11578 * free_netdev(y2); 11579 * 11580 * We are invoked by rtnl_unlock(). 11581 * This allows us to deal with problems: 11582 * 1) We can delete sysfs objects which invoke hotplug 11583 * without deadlocking with linkwatch via keventd. 11584 * 2) Since we run with the RTNL semaphore not held, we can sleep 11585 * safely in order to wait for the netdev refcnt to drop to zero. 11586 * 11587 * We must not return until all unregister events added during 11588 * the interval the lock was held have been completed. 11589 */ 11590 void netdev_run_todo(void) 11591 { 11592 struct net_device *dev, *tmp; 11593 struct list_head list; 11594 int cnt; 11595 #ifdef CONFIG_LOCKDEP 11596 struct list_head unlink_list; 11597 11598 list_replace_init(&net_unlink_list, &unlink_list); 11599 11600 while (!list_empty(&unlink_list)) { 11601 dev = list_first_entry(&unlink_list, struct net_device, 11602 unlink_list); 11603 list_del_init(&dev->unlink_list); 11604 dev->nested_level = dev->lower_level - 1; 11605 } 11606 #endif 11607 11608 /* Snapshot list, allow later requests */ 11609 list_replace_init(&net_todo_list, &list); 11610 11611 __rtnl_unlock(); 11612 11613 /* Wait for rcu callbacks to finish before next phase */ 11614 if (!list_empty(&list)) 11615 rcu_barrier(); 11616 11617 list_for_each_entry_safe(dev, tmp, &list, todo_list) { 11618 if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) { 11619 netdev_WARN(dev, "run_todo but not unregistering\n"); 11620 list_del(&dev->todo_list); 11621 continue; 11622 } 11623 11624 netdev_lock(dev); 11625 WRITE_ONCE(dev->reg_state, NETREG_UNREGISTERED); 11626 netdev_unlock(dev); 11627 linkwatch_sync_dev(dev); 11628 } 11629 11630 cnt = 0; 11631 while (!list_empty(&list)) { 11632 dev = netdev_wait_allrefs_any(&list); 11633 list_del(&dev->todo_list); 11634 11635 /* paranoia */ 11636 BUG_ON(netdev_refcnt_read(dev) != 1); 11637 BUG_ON(!list_empty(&dev->ptype_all)); 11638 BUG_ON(!list_empty(&dev->ptype_specific)); 11639 WARN_ON(rcu_access_pointer(dev->ip_ptr)); 11640 WARN_ON(rcu_access_pointer(dev->ip6_ptr)); 11641 11642 netdev_do_free_pcpu_stats(dev); 11643 if (dev->priv_destructor) 11644 dev->priv_destructor(dev); 11645 if (dev->needs_free_netdev) 11646 free_netdev(dev); 11647 11648 cnt++; 11649 11650 /* Free network device */ 11651 kobject_put(&dev->dev.kobj); 11652 } 11653 if (cnt && atomic_sub_and_test(cnt, &dev_unreg_count)) 11654 wake_up(&netdev_unregistering_wq); 11655 } 11656 11657 /* Collate per-cpu network dstats statistics 11658 * 11659 * Read per-cpu network statistics from dev->dstats and populate the related 11660 * fields in @s. 11661 */ 11662 static void dev_fetch_dstats(struct rtnl_link_stats64 *s, 11663 const struct pcpu_dstats __percpu *dstats) 11664 { 11665 int cpu; 11666 11667 for_each_possible_cpu(cpu) { 11668 u64 rx_packets, rx_bytes, rx_drops; 11669 u64 tx_packets, tx_bytes, tx_drops; 11670 const struct pcpu_dstats *stats; 11671 unsigned int start; 11672 11673 stats = per_cpu_ptr(dstats, cpu); 11674 do { 11675 start = u64_stats_fetch_begin(&stats->syncp); 11676 rx_packets = u64_stats_read(&stats->rx_packets); 11677 rx_bytes = u64_stats_read(&stats->rx_bytes); 11678 rx_drops = u64_stats_read(&stats->rx_drops); 11679 tx_packets = u64_stats_read(&stats->tx_packets); 11680 tx_bytes = u64_stats_read(&stats->tx_bytes); 11681 tx_drops = u64_stats_read(&stats->tx_drops); 11682 } while (u64_stats_fetch_retry(&stats->syncp, start)); 11683 11684 s->rx_packets += rx_packets; 11685 s->rx_bytes += rx_bytes; 11686 s->rx_dropped += rx_drops; 11687 s->tx_packets += tx_packets; 11688 s->tx_bytes += tx_bytes; 11689 s->tx_dropped += tx_drops; 11690 } 11691 } 11692 11693 /* ndo_get_stats64 implementation for dtstats-based accounting. 11694 * 11695 * Populate @s from dev->stats and dev->dstats. This is used internally by the 11696 * core for NETDEV_PCPU_STAT_DSTAT-type stats collection. 11697 */ 11698 static void dev_get_dstats64(const struct net_device *dev, 11699 struct rtnl_link_stats64 *s) 11700 { 11701 netdev_stats_to_stats64(s, &dev->stats); 11702 dev_fetch_dstats(s, dev->dstats); 11703 } 11704 11705 /* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has 11706 * all the same fields in the same order as net_device_stats, with only 11707 * the type differing, but rtnl_link_stats64 may have additional fields 11708 * at the end for newer counters. 11709 */ 11710 void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64, 11711 const struct net_device_stats *netdev_stats) 11712 { 11713 size_t i, n = sizeof(*netdev_stats) / sizeof(atomic_long_t); 11714 const atomic_long_t *src = (atomic_long_t *)netdev_stats; 11715 u64 *dst = (u64 *)stats64; 11716 11717 BUILD_BUG_ON(n > sizeof(*stats64) / sizeof(u64)); 11718 for (i = 0; i < n; i++) 11719 dst[i] = (unsigned long)atomic_long_read(&src[i]); 11720 /* zero out counters that only exist in rtnl_link_stats64 */ 11721 memset((char *)stats64 + n * sizeof(u64), 0, 11722 sizeof(*stats64) - n * sizeof(u64)); 11723 } 11724 EXPORT_SYMBOL(netdev_stats_to_stats64); 11725 11726 static __cold struct net_device_core_stats __percpu *netdev_core_stats_alloc( 11727 struct net_device *dev) 11728 { 11729 struct net_device_core_stats __percpu *p; 11730 11731 p = alloc_percpu_gfp(struct net_device_core_stats, 11732 GFP_ATOMIC | __GFP_NOWARN); 11733 11734 if (p && cmpxchg(&dev->core_stats, NULL, p)) 11735 free_percpu(p); 11736 11737 /* This READ_ONCE() pairs with the cmpxchg() above */ 11738 return READ_ONCE(dev->core_stats); 11739 } 11740 11741 noinline void netdev_core_stats_inc(struct net_device *dev, u32 offset) 11742 { 11743 /* This READ_ONCE() pairs with the write in netdev_core_stats_alloc() */ 11744 struct net_device_core_stats __percpu *p = READ_ONCE(dev->core_stats); 11745 unsigned long __percpu *field; 11746 11747 if (unlikely(!p)) { 11748 p = netdev_core_stats_alloc(dev); 11749 if (!p) 11750 return; 11751 } 11752 11753 field = (unsigned long __percpu *)((void __percpu *)p + offset); 11754 this_cpu_inc(*field); 11755 } 11756 EXPORT_SYMBOL_GPL(netdev_core_stats_inc); 11757 11758 /** 11759 * dev_get_stats - get network device statistics 11760 * @dev: device to get statistics from 11761 * @storage: place to store stats 11762 * 11763 * Get network statistics from device. Return @storage. 11764 * The device driver may provide its own method by setting 11765 * dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats; 11766 * otherwise the internal statistics structure is used. 11767 */ 11768 struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev, 11769 struct rtnl_link_stats64 *storage) 11770 { 11771 const struct net_device_ops *ops = dev->netdev_ops; 11772 const struct net_device_core_stats __percpu *p; 11773 11774 /* 11775 * IPv{4,6} and udp tunnels share common stat helpers and use 11776 * different stat type (NETDEV_PCPU_STAT_TSTATS vs 11777 * NETDEV_PCPU_STAT_DSTATS). Ensure the accounting is consistent. 11778 */ 11779 BUILD_BUG_ON(offsetof(struct pcpu_sw_netstats, rx_bytes) != 11780 offsetof(struct pcpu_dstats, rx_bytes)); 11781 BUILD_BUG_ON(offsetof(struct pcpu_sw_netstats, rx_packets) != 11782 offsetof(struct pcpu_dstats, rx_packets)); 11783 BUILD_BUG_ON(offsetof(struct pcpu_sw_netstats, tx_bytes) != 11784 offsetof(struct pcpu_dstats, tx_bytes)); 11785 BUILD_BUG_ON(offsetof(struct pcpu_sw_netstats, tx_packets) != 11786 offsetof(struct pcpu_dstats, tx_packets)); 11787 11788 if (ops->ndo_get_stats64) { 11789 memset(storage, 0, sizeof(*storage)); 11790 ops->ndo_get_stats64(dev, storage); 11791 } else if (ops->ndo_get_stats) { 11792 netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev)); 11793 } else if (dev->pcpu_stat_type == NETDEV_PCPU_STAT_TSTATS) { 11794 dev_get_tstats64(dev, storage); 11795 } else if (dev->pcpu_stat_type == NETDEV_PCPU_STAT_DSTATS) { 11796 dev_get_dstats64(dev, storage); 11797 } else { 11798 netdev_stats_to_stats64(storage, &dev->stats); 11799 } 11800 11801 /* This READ_ONCE() pairs with the write in netdev_core_stats_alloc() */ 11802 p = READ_ONCE(dev->core_stats); 11803 if (p) { 11804 const struct net_device_core_stats *core_stats; 11805 int i; 11806 11807 for_each_possible_cpu(i) { 11808 core_stats = per_cpu_ptr(p, i); 11809 storage->rx_dropped += READ_ONCE(core_stats->rx_dropped); 11810 storage->tx_dropped += READ_ONCE(core_stats->tx_dropped); 11811 storage->rx_nohandler += READ_ONCE(core_stats->rx_nohandler); 11812 storage->rx_otherhost_dropped += READ_ONCE(core_stats->rx_otherhost_dropped); 11813 } 11814 } 11815 return storage; 11816 } 11817 EXPORT_SYMBOL(dev_get_stats); 11818 11819 /** 11820 * dev_fetch_sw_netstats - get per-cpu network device statistics 11821 * @s: place to store stats 11822 * @netstats: per-cpu network stats to read from 11823 * 11824 * Read per-cpu network statistics and populate the related fields in @s. 11825 */ 11826 void dev_fetch_sw_netstats(struct rtnl_link_stats64 *s, 11827 const struct pcpu_sw_netstats __percpu *netstats) 11828 { 11829 int cpu; 11830 11831 for_each_possible_cpu(cpu) { 11832 u64 rx_packets, rx_bytes, tx_packets, tx_bytes; 11833 const struct pcpu_sw_netstats *stats; 11834 unsigned int start; 11835 11836 stats = per_cpu_ptr(netstats, cpu); 11837 do { 11838 start = u64_stats_fetch_begin(&stats->syncp); 11839 rx_packets = u64_stats_read(&stats->rx_packets); 11840 rx_bytes = u64_stats_read(&stats->rx_bytes); 11841 tx_packets = u64_stats_read(&stats->tx_packets); 11842 tx_bytes = u64_stats_read(&stats->tx_bytes); 11843 } while (u64_stats_fetch_retry(&stats->syncp, start)); 11844 11845 s->rx_packets += rx_packets; 11846 s->rx_bytes += rx_bytes; 11847 s->tx_packets += tx_packets; 11848 s->tx_bytes += tx_bytes; 11849 } 11850 } 11851 EXPORT_SYMBOL_GPL(dev_fetch_sw_netstats); 11852 11853 /** 11854 * dev_get_tstats64 - ndo_get_stats64 implementation 11855 * @dev: device to get statistics from 11856 * @s: place to store stats 11857 * 11858 * Populate @s from dev->stats and dev->tstats. Can be used as 11859 * ndo_get_stats64() callback. 11860 */ 11861 void dev_get_tstats64(struct net_device *dev, struct rtnl_link_stats64 *s) 11862 { 11863 netdev_stats_to_stats64(s, &dev->stats); 11864 dev_fetch_sw_netstats(s, dev->tstats); 11865 } 11866 EXPORT_SYMBOL_GPL(dev_get_tstats64); 11867 11868 struct netdev_queue *dev_ingress_queue_create(struct net_device *dev) 11869 { 11870 struct netdev_queue *queue = dev_ingress_queue(dev); 11871 11872 #ifdef CONFIG_NET_CLS_ACT 11873 if (queue) 11874 return queue; 11875 queue = kzalloc(sizeof(*queue), GFP_KERNEL); 11876 if (!queue) 11877 return NULL; 11878 netdev_init_one_queue(dev, queue, NULL); 11879 RCU_INIT_POINTER(queue->qdisc, &noop_qdisc); 11880 RCU_INIT_POINTER(queue->qdisc_sleeping, &noop_qdisc); 11881 rcu_assign_pointer(dev->ingress_queue, queue); 11882 #endif 11883 return queue; 11884 } 11885 11886 static const struct ethtool_ops default_ethtool_ops; 11887 11888 void netdev_set_default_ethtool_ops(struct net_device *dev, 11889 const struct ethtool_ops *ops) 11890 { 11891 if (dev->ethtool_ops == &default_ethtool_ops) 11892 dev->ethtool_ops = ops; 11893 } 11894 EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops); 11895 11896 /** 11897 * netdev_sw_irq_coalesce_default_on() - enable SW IRQ coalescing by default 11898 * @dev: netdev to enable the IRQ coalescing on 11899 * 11900 * Sets a conservative default for SW IRQ coalescing. Users can use 11901 * sysfs attributes to override the default values. 11902 */ 11903 void netdev_sw_irq_coalesce_default_on(struct net_device *dev) 11904 { 11905 WARN_ON(dev->reg_state == NETREG_REGISTERED); 11906 11907 if (!IS_ENABLED(CONFIG_PREEMPT_RT)) { 11908 netdev_set_gro_flush_timeout(dev, 20000); 11909 netdev_set_defer_hard_irqs(dev, 1); 11910 } 11911 } 11912 EXPORT_SYMBOL_GPL(netdev_sw_irq_coalesce_default_on); 11913 11914 /** 11915 * alloc_netdev_mqs - allocate network device 11916 * @sizeof_priv: size of private data to allocate space for 11917 * @name: device name format string 11918 * @name_assign_type: origin of device name 11919 * @setup: callback to initialize device 11920 * @txqs: the number of TX subqueues to allocate 11921 * @rxqs: the number of RX subqueues to allocate 11922 * 11923 * Allocates a struct net_device with private data area for driver use 11924 * and performs basic initialization. Also allocates subqueue structs 11925 * for each queue on the device. 11926 */ 11927 struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name, 11928 unsigned char name_assign_type, 11929 void (*setup)(struct net_device *), 11930 unsigned int txqs, unsigned int rxqs) 11931 { 11932 struct net_device *dev; 11933 size_t napi_config_sz; 11934 unsigned int maxqs; 11935 11936 BUG_ON(strlen(name) >= sizeof(dev->name)); 11937 11938 if (txqs < 1) { 11939 pr_err("alloc_netdev: Unable to allocate device with zero queues\n"); 11940 return NULL; 11941 } 11942 11943 if (rxqs < 1) { 11944 pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n"); 11945 return NULL; 11946 } 11947 11948 maxqs = max(txqs, rxqs); 11949 11950 dev = kvzalloc(struct_size(dev, priv, sizeof_priv), 11951 GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL); 11952 if (!dev) 11953 return NULL; 11954 11955 dev->priv_len = sizeof_priv; 11956 11957 ref_tracker_dir_init(&dev->refcnt_tracker, 128, "netdev"); 11958 #ifdef CONFIG_PCPU_DEV_REFCNT 11959 dev->pcpu_refcnt = alloc_percpu(int); 11960 if (!dev->pcpu_refcnt) 11961 goto free_dev; 11962 __dev_hold(dev); 11963 #else 11964 refcount_set(&dev->dev_refcnt, 1); 11965 #endif 11966 11967 if (dev_addr_init(dev)) 11968 goto free_pcpu; 11969 11970 dev_mc_init(dev); 11971 dev_uc_init(dev); 11972 11973 dev_net_set(dev, &init_net); 11974 11975 dev->gso_max_size = GSO_LEGACY_MAX_SIZE; 11976 dev->xdp_zc_max_segs = 1; 11977 dev->gso_max_segs = GSO_MAX_SEGS; 11978 dev->gro_max_size = GRO_LEGACY_MAX_SIZE; 11979 dev->gso_ipv4_max_size = GSO_LEGACY_MAX_SIZE; 11980 dev->gro_ipv4_max_size = GRO_LEGACY_MAX_SIZE; 11981 dev->tso_max_size = TSO_LEGACY_MAX_SIZE; 11982 dev->tso_max_segs = TSO_MAX_SEGS; 11983 dev->upper_level = 1; 11984 dev->lower_level = 1; 11985 #ifdef CONFIG_LOCKDEP 11986 dev->nested_level = 0; 11987 INIT_LIST_HEAD(&dev->unlink_list); 11988 #endif 11989 11990 INIT_LIST_HEAD(&dev->napi_list); 11991 INIT_LIST_HEAD(&dev->unreg_list); 11992 INIT_LIST_HEAD(&dev->close_list); 11993 INIT_LIST_HEAD(&dev->link_watch_list); 11994 INIT_LIST_HEAD(&dev->adj_list.upper); 11995 INIT_LIST_HEAD(&dev->adj_list.lower); 11996 INIT_LIST_HEAD(&dev->ptype_all); 11997 INIT_LIST_HEAD(&dev->ptype_specific); 11998 INIT_LIST_HEAD(&dev->net_notifier_list); 11999 #ifdef CONFIG_NET_SCHED 12000 hash_init(dev->qdisc_hash); 12001 #endif 12002 12003 mutex_init(&dev->lock); 12004 12005 dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM; 12006 setup(dev); 12007 12008 if (!dev->tx_queue_len) { 12009 dev->priv_flags |= IFF_NO_QUEUE; 12010 dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN; 12011 } 12012 12013 dev->num_tx_queues = txqs; 12014 dev->real_num_tx_queues = txqs; 12015 if (netif_alloc_netdev_queues(dev)) 12016 goto free_all; 12017 12018 dev->num_rx_queues = rxqs; 12019 dev->real_num_rx_queues = rxqs; 12020 if (netif_alloc_rx_queues(dev)) 12021 goto free_all; 12022 dev->ethtool = kzalloc(sizeof(*dev->ethtool), GFP_KERNEL_ACCOUNT); 12023 if (!dev->ethtool) 12024 goto free_all; 12025 12026 dev->cfg = kzalloc(sizeof(*dev->cfg), GFP_KERNEL_ACCOUNT); 12027 if (!dev->cfg) 12028 goto free_all; 12029 dev->cfg_pending = dev->cfg; 12030 12031 dev->num_napi_configs = maxqs; 12032 napi_config_sz = array_size(maxqs, sizeof(*dev->napi_config)); 12033 dev->napi_config = kvzalloc(napi_config_sz, GFP_KERNEL_ACCOUNT); 12034 if (!dev->napi_config) 12035 goto free_all; 12036 12037 strscpy(dev->name, name); 12038 dev->name_assign_type = name_assign_type; 12039 dev->group = INIT_NETDEV_GROUP; 12040 if (!dev->ethtool_ops) 12041 dev->ethtool_ops = &default_ethtool_ops; 12042 12043 nf_hook_netdev_init(dev); 12044 12045 return dev; 12046 12047 free_all: 12048 free_netdev(dev); 12049 return NULL; 12050 12051 free_pcpu: 12052 #ifdef CONFIG_PCPU_DEV_REFCNT 12053 free_percpu(dev->pcpu_refcnt); 12054 free_dev: 12055 #endif 12056 kvfree(dev); 12057 return NULL; 12058 } 12059 EXPORT_SYMBOL(alloc_netdev_mqs); 12060 12061 static void netdev_napi_exit(struct net_device *dev) 12062 { 12063 if (!list_empty(&dev->napi_list)) { 12064 struct napi_struct *p, *n; 12065 12066 netdev_lock(dev); 12067 list_for_each_entry_safe(p, n, &dev->napi_list, dev_list) 12068 __netif_napi_del_locked(p); 12069 netdev_unlock(dev); 12070 12071 synchronize_net(); 12072 } 12073 12074 kvfree(dev->napi_config); 12075 } 12076 12077 /** 12078 * free_netdev - free network device 12079 * @dev: device 12080 * 12081 * This function does the last stage of destroying an allocated device 12082 * interface. The reference to the device object is released. If this 12083 * is the last reference then it will be freed.Must be called in process 12084 * context. 12085 */ 12086 void free_netdev(struct net_device *dev) 12087 { 12088 might_sleep(); 12089 12090 /* When called immediately after register_netdevice() failed the unwind 12091 * handling may still be dismantling the device. Handle that case by 12092 * deferring the free. 12093 */ 12094 if (dev->reg_state == NETREG_UNREGISTERING) { 12095 ASSERT_RTNL(); 12096 dev->needs_free_netdev = true; 12097 return; 12098 } 12099 12100 WARN_ON(dev->cfg != dev->cfg_pending); 12101 kfree(dev->cfg); 12102 kfree(dev->ethtool); 12103 netif_free_tx_queues(dev); 12104 netif_free_rx_queues(dev); 12105 12106 kfree(rcu_dereference_protected(dev->ingress_queue, 1)); 12107 12108 /* Flush device addresses */ 12109 dev_addr_flush(dev); 12110 12111 netdev_napi_exit(dev); 12112 12113 netif_del_cpu_rmap(dev); 12114 12115 ref_tracker_dir_exit(&dev->refcnt_tracker); 12116 #ifdef CONFIG_PCPU_DEV_REFCNT 12117 free_percpu(dev->pcpu_refcnt); 12118 dev->pcpu_refcnt = NULL; 12119 #endif 12120 free_percpu(dev->core_stats); 12121 dev->core_stats = NULL; 12122 free_percpu(dev->xdp_bulkq); 12123 dev->xdp_bulkq = NULL; 12124 12125 netdev_free_phy_link_topology(dev); 12126 12127 mutex_destroy(&dev->lock); 12128 12129 /* Compatibility with error handling in drivers */ 12130 if (dev->reg_state == NETREG_UNINITIALIZED || 12131 dev->reg_state == NETREG_DUMMY) { 12132 kvfree(dev); 12133 return; 12134 } 12135 12136 BUG_ON(dev->reg_state != NETREG_UNREGISTERED); 12137 WRITE_ONCE(dev->reg_state, NETREG_RELEASED); 12138 12139 /* will free via device release */ 12140 put_device(&dev->dev); 12141 } 12142 EXPORT_SYMBOL(free_netdev); 12143 12144 /** 12145 * alloc_netdev_dummy - Allocate and initialize a dummy net device. 12146 * @sizeof_priv: size of private data to allocate space for 12147 * 12148 * Return: the allocated net_device on success, NULL otherwise 12149 */ 12150 struct net_device *alloc_netdev_dummy(int sizeof_priv) 12151 { 12152 return alloc_netdev(sizeof_priv, "dummy#", NET_NAME_UNKNOWN, 12153 init_dummy_netdev); 12154 } 12155 EXPORT_SYMBOL_GPL(alloc_netdev_dummy); 12156 12157 /** 12158 * synchronize_net - Synchronize with packet receive processing 12159 * 12160 * Wait for packets currently being received to be done. 12161 * Does not block later packets from starting. 12162 */ 12163 void synchronize_net(void) 12164 { 12165 might_sleep(); 12166 if (from_cleanup_net() || rtnl_is_locked()) 12167 synchronize_rcu_expedited(); 12168 else 12169 synchronize_rcu(); 12170 } 12171 EXPORT_SYMBOL(synchronize_net); 12172 12173 static void netdev_rss_contexts_free(struct net_device *dev) 12174 { 12175 struct ethtool_rxfh_context *ctx; 12176 unsigned long context; 12177 12178 mutex_lock(&dev->ethtool->rss_lock); 12179 xa_for_each(&dev->ethtool->rss_ctx, context, ctx) { 12180 xa_erase(&dev->ethtool->rss_ctx, context); 12181 dev->ethtool_ops->remove_rxfh_context(dev, ctx, context, NULL); 12182 kfree(ctx); 12183 } 12184 xa_destroy(&dev->ethtool->rss_ctx); 12185 mutex_unlock(&dev->ethtool->rss_lock); 12186 } 12187 12188 /** 12189 * unregister_netdevice_queue - remove device from the kernel 12190 * @dev: device 12191 * @head: list 12192 * 12193 * This function shuts down a device interface and removes it 12194 * from the kernel tables. 12195 * If head not NULL, device is queued to be unregistered later. 12196 * 12197 * Callers must hold the rtnl semaphore. You may want 12198 * unregister_netdev() instead of this. 12199 */ 12200 12201 void unregister_netdevice_queue(struct net_device *dev, struct list_head *head) 12202 { 12203 ASSERT_RTNL(); 12204 12205 if (head) { 12206 list_move_tail(&dev->unreg_list, head); 12207 } else { 12208 LIST_HEAD(single); 12209 12210 list_add(&dev->unreg_list, &single); 12211 unregister_netdevice_many(&single); 12212 } 12213 } 12214 EXPORT_SYMBOL(unregister_netdevice_queue); 12215 12216 static void dev_memory_provider_uninstall(struct net_device *dev) 12217 { 12218 unsigned int i; 12219 12220 for (i = 0; i < dev->real_num_rx_queues; i++) { 12221 struct netdev_rx_queue *rxq = &dev->_rx[i]; 12222 struct pp_memory_provider_params *p = &rxq->mp_params; 12223 12224 if (p->mp_ops && p->mp_ops->uninstall) 12225 p->mp_ops->uninstall(rxq->mp_params.mp_priv, rxq); 12226 } 12227 } 12228 12229 /* devices must be UP and netdev_lock()'d */ 12230 static void netif_close_many_and_unlock(struct list_head *close_head) 12231 { 12232 struct net_device *dev, *tmp; 12233 12234 netif_close_many(close_head, false); 12235 12236 /* ... now unlock them */ 12237 list_for_each_entry_safe(dev, tmp, close_head, close_list) { 12238 netdev_unlock(dev); 12239 list_del_init(&dev->close_list); 12240 } 12241 } 12242 12243 static void netif_close_many_and_unlock_cond(struct list_head *close_head) 12244 { 12245 #ifdef CONFIG_LOCKDEP 12246 /* We can only track up to MAX_LOCK_DEPTH locks per task. 12247 * 12248 * Reserve half the available slots for additional locks possibly 12249 * taken by notifiers and (soft)irqs. 12250 */ 12251 unsigned int limit = MAX_LOCK_DEPTH / 2; 12252 12253 if (lockdep_depth(current) > limit) 12254 netif_close_many_and_unlock(close_head); 12255 #endif 12256 } 12257 12258 void unregister_netdevice_many_notify(struct list_head *head, 12259 u32 portid, const struct nlmsghdr *nlh) 12260 { 12261 struct net_device *dev, *tmp; 12262 LIST_HEAD(close_head); 12263 int cnt = 0; 12264 12265 BUG_ON(dev_boot_phase); 12266 ASSERT_RTNL(); 12267 12268 if (list_empty(head)) 12269 return; 12270 12271 list_for_each_entry_safe(dev, tmp, head, unreg_list) { 12272 /* Some devices call without registering 12273 * for initialization unwind. Remove those 12274 * devices and proceed with the remaining. 12275 */ 12276 if (dev->reg_state == NETREG_UNINITIALIZED) { 12277 pr_debug("unregister_netdevice: device %s/%p never was registered\n", 12278 dev->name, dev); 12279 12280 WARN_ON(1); 12281 list_del(&dev->unreg_list); 12282 continue; 12283 } 12284 dev->dismantle = true; 12285 BUG_ON(dev->reg_state != NETREG_REGISTERED); 12286 } 12287 12288 /* If device is running, close it first. Start with ops locked... */ 12289 list_for_each_entry(dev, head, unreg_list) { 12290 if (!(dev->flags & IFF_UP)) 12291 continue; 12292 if (netdev_need_ops_lock(dev)) { 12293 list_add_tail(&dev->close_list, &close_head); 12294 netdev_lock(dev); 12295 } 12296 netif_close_many_and_unlock_cond(&close_head); 12297 } 12298 netif_close_many_and_unlock(&close_head); 12299 /* ... now go over the rest. */ 12300 list_for_each_entry(dev, head, unreg_list) { 12301 if (!netdev_need_ops_lock(dev)) 12302 list_add_tail(&dev->close_list, &close_head); 12303 } 12304 netif_close_many(&close_head, true); 12305 12306 list_for_each_entry(dev, head, unreg_list) { 12307 /* And unlink it from device chain. */ 12308 unlist_netdevice(dev); 12309 netdev_lock(dev); 12310 WRITE_ONCE(dev->reg_state, NETREG_UNREGISTERING); 12311 netdev_unlock(dev); 12312 } 12313 flush_all_backlogs(); 12314 12315 synchronize_net(); 12316 12317 list_for_each_entry(dev, head, unreg_list) { 12318 struct sk_buff *skb = NULL; 12319 12320 /* Shutdown queueing discipline. */ 12321 netdev_lock_ops(dev); 12322 dev_shutdown(dev); 12323 dev_tcx_uninstall(dev); 12324 dev_xdp_uninstall(dev); 12325 dev_memory_provider_uninstall(dev); 12326 netdev_unlock_ops(dev); 12327 bpf_dev_bound_netdev_unregister(dev); 12328 12329 netdev_offload_xstats_disable_all(dev); 12330 12331 /* Notify protocols, that we are about to destroy 12332 * this device. They should clean all the things. 12333 */ 12334 call_netdevice_notifiers(NETDEV_UNREGISTER, dev); 12335 12336 if (!(dev->rtnl_link_ops && dev->rtnl_link_initializing)) 12337 skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0, 12338 GFP_KERNEL, NULL, 0, 12339 portid, nlh); 12340 12341 /* 12342 * Flush the unicast and multicast chains 12343 */ 12344 dev_uc_flush(dev); 12345 dev_mc_flush(dev); 12346 12347 netdev_name_node_alt_flush(dev); 12348 netdev_name_node_free(dev->name_node); 12349 12350 netdev_rss_contexts_free(dev); 12351 12352 call_netdevice_notifiers(NETDEV_PRE_UNINIT, dev); 12353 12354 if (dev->netdev_ops->ndo_uninit) 12355 dev->netdev_ops->ndo_uninit(dev); 12356 12357 mutex_destroy(&dev->ethtool->rss_lock); 12358 12359 net_shaper_flush_netdev(dev); 12360 12361 if (skb) 12362 rtmsg_ifinfo_send(skb, dev, GFP_KERNEL, portid, nlh); 12363 12364 /* Notifier chain MUST detach us all upper devices. */ 12365 WARN_ON(netdev_has_any_upper_dev(dev)); 12366 WARN_ON(netdev_has_any_lower_dev(dev)); 12367 12368 /* Remove entries from kobject tree */ 12369 netdev_unregister_kobject(dev); 12370 #ifdef CONFIG_XPS 12371 /* Remove XPS queueing entries */ 12372 netif_reset_xps_queues_gt(dev, 0); 12373 #endif 12374 } 12375 12376 synchronize_net(); 12377 12378 list_for_each_entry(dev, head, unreg_list) { 12379 netdev_put(dev, &dev->dev_registered_tracker); 12380 net_set_todo(dev); 12381 cnt++; 12382 } 12383 atomic_add(cnt, &dev_unreg_count); 12384 12385 list_del(head); 12386 } 12387 12388 /** 12389 * unregister_netdevice_many - unregister many devices 12390 * @head: list of devices 12391 * 12392 * Note: As most callers use a stack allocated list_head, 12393 * we force a list_del() to make sure stack won't be corrupted later. 12394 */ 12395 void unregister_netdevice_many(struct list_head *head) 12396 { 12397 unregister_netdevice_many_notify(head, 0, NULL); 12398 } 12399 EXPORT_SYMBOL(unregister_netdevice_many); 12400 12401 /** 12402 * unregister_netdev - remove device from the kernel 12403 * @dev: device 12404 * 12405 * This function shuts down a device interface and removes it 12406 * from the kernel tables. 12407 * 12408 * This is just a wrapper for unregister_netdevice that takes 12409 * the rtnl semaphore. In general you want to use this and not 12410 * unregister_netdevice. 12411 */ 12412 void unregister_netdev(struct net_device *dev) 12413 { 12414 rtnl_net_dev_lock(dev); 12415 unregister_netdevice(dev); 12416 rtnl_net_dev_unlock(dev); 12417 } 12418 EXPORT_SYMBOL(unregister_netdev); 12419 12420 int __dev_change_net_namespace(struct net_device *dev, struct net *net, 12421 const char *pat, int new_ifindex, 12422 struct netlink_ext_ack *extack) 12423 { 12424 struct netdev_name_node *name_node; 12425 struct net *net_old = dev_net(dev); 12426 char new_name[IFNAMSIZ] = {}; 12427 int err, new_nsid; 12428 12429 ASSERT_RTNL(); 12430 12431 /* Don't allow namespace local devices to be moved. */ 12432 err = -EINVAL; 12433 if (dev->netns_immutable) { 12434 NL_SET_ERR_MSG(extack, "The interface netns is immutable"); 12435 goto out; 12436 } 12437 12438 /* Ensure the device has been registered */ 12439 if (dev->reg_state != NETREG_REGISTERED) { 12440 NL_SET_ERR_MSG(extack, "The interface isn't registered"); 12441 goto out; 12442 } 12443 12444 /* Get out if there is nothing todo */ 12445 err = 0; 12446 if (net_eq(net_old, net)) 12447 goto out; 12448 12449 /* Pick the destination device name, and ensure 12450 * we can use it in the destination network namespace. 12451 */ 12452 err = -EEXIST; 12453 if (netdev_name_in_use(net, dev->name)) { 12454 /* We get here if we can't use the current device name */ 12455 if (!pat) { 12456 NL_SET_ERR_MSG(extack, 12457 "An interface with the same name exists in the target netns"); 12458 goto out; 12459 } 12460 err = dev_prep_valid_name(net, dev, pat, new_name, EEXIST); 12461 if (err < 0) { 12462 NL_SET_ERR_MSG_FMT(extack, 12463 "Unable to use '%s' for the new interface name in the target netns", 12464 pat); 12465 goto out; 12466 } 12467 } 12468 /* Check that none of the altnames conflicts. */ 12469 err = -EEXIST; 12470 netdev_for_each_altname(dev, name_node) { 12471 if (netdev_name_in_use(net, name_node->name)) { 12472 NL_SET_ERR_MSG_FMT(extack, 12473 "An interface with the altname %s exists in the target netns", 12474 name_node->name); 12475 goto out; 12476 } 12477 } 12478 12479 /* Check that new_ifindex isn't used yet. */ 12480 if (new_ifindex) { 12481 err = dev_index_reserve(net, new_ifindex); 12482 if (err < 0) { 12483 NL_SET_ERR_MSG_FMT(extack, 12484 "The ifindex %d is not available in the target netns", 12485 new_ifindex); 12486 goto out; 12487 } 12488 } else { 12489 /* If there is an ifindex conflict assign a new one */ 12490 err = dev_index_reserve(net, dev->ifindex); 12491 if (err == -EBUSY) 12492 err = dev_index_reserve(net, 0); 12493 if (err < 0) { 12494 NL_SET_ERR_MSG(extack, 12495 "Unable to allocate a new ifindex in the target netns"); 12496 goto out; 12497 } 12498 new_ifindex = err; 12499 } 12500 12501 /* 12502 * And now a mini version of register_netdevice unregister_netdevice. 12503 */ 12504 12505 netdev_lock_ops(dev); 12506 /* If device is running close it first. */ 12507 netif_close(dev); 12508 /* And unlink it from device chain */ 12509 unlist_netdevice(dev); 12510 12511 if (!netdev_need_ops_lock(dev)) 12512 netdev_lock(dev); 12513 dev->moving_ns = true; 12514 netdev_unlock(dev); 12515 12516 synchronize_net(); 12517 12518 /* Shutdown queueing discipline. */ 12519 netdev_lock_ops(dev); 12520 dev_shutdown(dev); 12521 netdev_unlock_ops(dev); 12522 12523 /* Notify protocols, that we are about to destroy 12524 * this device. They should clean all the things. 12525 * 12526 * Note that dev->reg_state stays at NETREG_REGISTERED. 12527 * This is wanted because this way 8021q and macvlan know 12528 * the device is just moving and can keep their slaves up. 12529 */ 12530 call_netdevice_notifiers(NETDEV_UNREGISTER, dev); 12531 rcu_barrier(); 12532 12533 new_nsid = peernet2id_alloc(dev_net(dev), net, GFP_KERNEL); 12534 12535 rtmsg_ifinfo_newnet(RTM_DELLINK, dev, ~0U, GFP_KERNEL, &new_nsid, 12536 new_ifindex); 12537 12538 /* 12539 * Flush the unicast and multicast chains 12540 */ 12541 dev_uc_flush(dev); 12542 dev_mc_flush(dev); 12543 12544 /* Send a netdev-removed uevent to the old namespace */ 12545 kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE); 12546 netdev_adjacent_del_links(dev); 12547 12548 /* Move per-net netdevice notifiers that are following the netdevice */ 12549 move_netdevice_notifiers_dev_net(dev, net); 12550 12551 /* Actually switch the network namespace */ 12552 netdev_lock(dev); 12553 dev_net_set(dev, net); 12554 netdev_unlock(dev); 12555 dev->ifindex = new_ifindex; 12556 12557 if (new_name[0]) { 12558 /* Rename the netdev to prepared name */ 12559 write_seqlock_bh(&netdev_rename_lock); 12560 strscpy(dev->name, new_name, IFNAMSIZ); 12561 write_sequnlock_bh(&netdev_rename_lock); 12562 } 12563 12564 /* Fixup kobjects */ 12565 dev_set_uevent_suppress(&dev->dev, 1); 12566 err = device_rename(&dev->dev, dev->name); 12567 dev_set_uevent_suppress(&dev->dev, 0); 12568 WARN_ON(err); 12569 12570 /* Send a netdev-add uevent to the new namespace */ 12571 kobject_uevent(&dev->dev.kobj, KOBJ_ADD); 12572 netdev_adjacent_add_links(dev); 12573 12574 /* Adapt owner in case owning user namespace of target network 12575 * namespace is different from the original one. 12576 */ 12577 err = netdev_change_owner(dev, net_old, net); 12578 WARN_ON(err); 12579 12580 netdev_lock(dev); 12581 dev->moving_ns = false; 12582 if (!netdev_need_ops_lock(dev)) 12583 netdev_unlock(dev); 12584 12585 /* Add the device back in the hashes */ 12586 list_netdevice(dev); 12587 /* Notify protocols, that a new device appeared. */ 12588 call_netdevice_notifiers(NETDEV_REGISTER, dev); 12589 netdev_unlock_ops(dev); 12590 12591 /* 12592 * Prevent userspace races by waiting until the network 12593 * device is fully setup before sending notifications. 12594 */ 12595 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL, 0, NULL); 12596 12597 synchronize_net(); 12598 err = 0; 12599 out: 12600 return err; 12601 } 12602 12603 static int dev_cpu_dead(unsigned int oldcpu) 12604 { 12605 struct sk_buff **list_skb; 12606 struct sk_buff *skb; 12607 unsigned int cpu; 12608 struct softnet_data *sd, *oldsd, *remsd = NULL; 12609 12610 local_irq_disable(); 12611 cpu = smp_processor_id(); 12612 sd = &per_cpu(softnet_data, cpu); 12613 oldsd = &per_cpu(softnet_data, oldcpu); 12614 12615 /* Find end of our completion_queue. */ 12616 list_skb = &sd->completion_queue; 12617 while (*list_skb) 12618 list_skb = &(*list_skb)->next; 12619 /* Append completion queue from offline CPU. */ 12620 *list_skb = oldsd->completion_queue; 12621 oldsd->completion_queue = NULL; 12622 12623 /* Append output queue from offline CPU. */ 12624 if (oldsd->output_queue) { 12625 *sd->output_queue_tailp = oldsd->output_queue; 12626 sd->output_queue_tailp = oldsd->output_queue_tailp; 12627 oldsd->output_queue = NULL; 12628 oldsd->output_queue_tailp = &oldsd->output_queue; 12629 } 12630 /* Append NAPI poll list from offline CPU, with one exception : 12631 * process_backlog() must be called by cpu owning percpu backlog. 12632 * We properly handle process_queue & input_pkt_queue later. 12633 */ 12634 while (!list_empty(&oldsd->poll_list)) { 12635 struct napi_struct *napi = list_first_entry(&oldsd->poll_list, 12636 struct napi_struct, 12637 poll_list); 12638 12639 list_del_init(&napi->poll_list); 12640 if (napi->poll == process_backlog) 12641 napi->state &= NAPIF_STATE_THREADED; 12642 else 12643 ____napi_schedule(sd, napi); 12644 } 12645 12646 raise_softirq_irqoff(NET_TX_SOFTIRQ); 12647 local_irq_enable(); 12648 12649 if (!use_backlog_threads()) { 12650 #ifdef CONFIG_RPS 12651 remsd = oldsd->rps_ipi_list; 12652 oldsd->rps_ipi_list = NULL; 12653 #endif 12654 /* send out pending IPI's on offline CPU */ 12655 net_rps_send_ipi(remsd); 12656 } 12657 12658 /* Process offline CPU's input_pkt_queue */ 12659 while ((skb = __skb_dequeue(&oldsd->process_queue))) { 12660 netif_rx(skb); 12661 rps_input_queue_head_incr(oldsd); 12662 } 12663 while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) { 12664 netif_rx(skb); 12665 rps_input_queue_head_incr(oldsd); 12666 } 12667 12668 return 0; 12669 } 12670 12671 /** 12672 * netdev_increment_features - increment feature set by one 12673 * @all: current feature set 12674 * @one: new feature set 12675 * @mask: mask feature set 12676 * 12677 * Computes a new feature set after adding a device with feature set 12678 * @one to the master device with current feature set @all. Will not 12679 * enable anything that is off in @mask. Returns the new feature set. 12680 */ 12681 netdev_features_t netdev_increment_features(netdev_features_t all, 12682 netdev_features_t one, netdev_features_t mask) 12683 { 12684 if (mask & NETIF_F_HW_CSUM) 12685 mask |= NETIF_F_CSUM_MASK; 12686 mask |= NETIF_F_VLAN_CHALLENGED; 12687 12688 all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask; 12689 all &= one | ~NETIF_F_ALL_FOR_ALL; 12690 12691 /* If one device supports hw checksumming, set for all. */ 12692 if (all & NETIF_F_HW_CSUM) 12693 all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM); 12694 12695 return all; 12696 } 12697 EXPORT_SYMBOL(netdev_increment_features); 12698 12699 /** 12700 * netdev_compute_master_upper_features - compute feature from lowers 12701 * @dev: the upper device 12702 * @update_header: whether to update upper device's header_len/headroom/tailroom 12703 * 12704 * Recompute the upper device's feature based on all lower devices. 12705 */ 12706 void netdev_compute_master_upper_features(struct net_device *dev, bool update_header) 12707 { 12708 unsigned int dst_release_flag = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM; 12709 netdev_features_t gso_partial_features = MASTER_UPPER_DEV_GSO_PARTIAL_FEATURES; 12710 netdev_features_t xfrm_features = MASTER_UPPER_DEV_XFRM_FEATURES; 12711 netdev_features_t mpls_features = MASTER_UPPER_DEV_MPLS_FEATURES; 12712 netdev_features_t vlan_features = MASTER_UPPER_DEV_VLAN_FEATURES; 12713 netdev_features_t enc_features = MASTER_UPPER_DEV_ENC_FEATURES; 12714 unsigned short max_header_len = ETH_HLEN; 12715 unsigned int tso_max_size = TSO_MAX_SIZE; 12716 unsigned short max_headroom = 0; 12717 unsigned short max_tailroom = 0; 12718 u16 tso_max_segs = TSO_MAX_SEGS; 12719 struct net_device *lower_dev; 12720 struct list_head *iter; 12721 12722 mpls_features = netdev_base_features(mpls_features); 12723 vlan_features = netdev_base_features(vlan_features); 12724 enc_features = netdev_base_features(enc_features); 12725 12726 netdev_for_each_lower_dev(dev, lower_dev, iter) { 12727 gso_partial_features = netdev_increment_features(gso_partial_features, 12728 lower_dev->gso_partial_features, 12729 MASTER_UPPER_DEV_GSO_PARTIAL_FEATURES); 12730 12731 vlan_features = netdev_increment_features(vlan_features, 12732 lower_dev->vlan_features, 12733 MASTER_UPPER_DEV_VLAN_FEATURES); 12734 12735 enc_features = netdev_increment_features(enc_features, 12736 lower_dev->hw_enc_features, 12737 MASTER_UPPER_DEV_ENC_FEATURES); 12738 12739 if (IS_ENABLED(CONFIG_XFRM_OFFLOAD)) 12740 xfrm_features = netdev_increment_features(xfrm_features, 12741 lower_dev->hw_enc_features, 12742 MASTER_UPPER_DEV_XFRM_FEATURES); 12743 12744 mpls_features = netdev_increment_features(mpls_features, 12745 lower_dev->mpls_features, 12746 MASTER_UPPER_DEV_MPLS_FEATURES); 12747 12748 dst_release_flag &= lower_dev->priv_flags; 12749 12750 if (update_header) { 12751 max_header_len = max(max_header_len, lower_dev->hard_header_len); 12752 max_headroom = max(max_headroom, lower_dev->needed_headroom); 12753 max_tailroom = max(max_tailroom, lower_dev->needed_tailroom); 12754 } 12755 12756 tso_max_size = min(tso_max_size, lower_dev->tso_max_size); 12757 tso_max_segs = min(tso_max_segs, lower_dev->tso_max_segs); 12758 } 12759 12760 dev->gso_partial_features = gso_partial_features; 12761 dev->vlan_features = vlan_features; 12762 dev->hw_enc_features = enc_features | NETIF_F_GSO_ENCAP_ALL | 12763 NETIF_F_HW_VLAN_CTAG_TX | 12764 NETIF_F_HW_VLAN_STAG_TX; 12765 if (IS_ENABLED(CONFIG_XFRM_OFFLOAD)) 12766 dev->hw_enc_features |= xfrm_features; 12767 dev->mpls_features = mpls_features; 12768 12769 dev->priv_flags &= ~IFF_XMIT_DST_RELEASE; 12770 if ((dev->priv_flags & IFF_XMIT_DST_RELEASE_PERM) && 12771 dst_release_flag == (IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM)) 12772 dev->priv_flags |= IFF_XMIT_DST_RELEASE; 12773 12774 if (update_header) { 12775 dev->hard_header_len = max_header_len; 12776 dev->needed_headroom = max_headroom; 12777 dev->needed_tailroom = max_tailroom; 12778 } 12779 12780 netif_set_tso_max_segs(dev, tso_max_segs); 12781 netif_set_tso_max_size(dev, tso_max_size); 12782 12783 netdev_change_features(dev); 12784 } 12785 EXPORT_SYMBOL(netdev_compute_master_upper_features); 12786 12787 static struct hlist_head * __net_init netdev_create_hash(void) 12788 { 12789 int i; 12790 struct hlist_head *hash; 12791 12792 hash = kmalloc_array(NETDEV_HASHENTRIES, sizeof(*hash), GFP_KERNEL); 12793 if (hash != NULL) 12794 for (i = 0; i < NETDEV_HASHENTRIES; i++) 12795 INIT_HLIST_HEAD(&hash[i]); 12796 12797 return hash; 12798 } 12799 12800 /* Initialize per network namespace state */ 12801 static int __net_init netdev_init(struct net *net) 12802 { 12803 BUILD_BUG_ON(GRO_HASH_BUCKETS > 12804 BITS_PER_BYTE * sizeof_field(struct gro_node, bitmask)); 12805 12806 INIT_LIST_HEAD(&net->dev_base_head); 12807 12808 net->dev_name_head = netdev_create_hash(); 12809 if (net->dev_name_head == NULL) 12810 goto err_name; 12811 12812 net->dev_index_head = netdev_create_hash(); 12813 if (net->dev_index_head == NULL) 12814 goto err_idx; 12815 12816 xa_init_flags(&net->dev_by_index, XA_FLAGS_ALLOC1); 12817 12818 RAW_INIT_NOTIFIER_HEAD(&net->netdev_chain); 12819 12820 return 0; 12821 12822 err_idx: 12823 kfree(net->dev_name_head); 12824 err_name: 12825 return -ENOMEM; 12826 } 12827 12828 /** 12829 * netdev_drivername - network driver for the device 12830 * @dev: network device 12831 * 12832 * Determine network driver for device. 12833 */ 12834 const char *netdev_drivername(const struct net_device *dev) 12835 { 12836 const struct device_driver *driver; 12837 const struct device *parent; 12838 const char *empty = ""; 12839 12840 parent = dev->dev.parent; 12841 if (!parent) 12842 return empty; 12843 12844 driver = parent->driver; 12845 if (driver && driver->name) 12846 return driver->name; 12847 return empty; 12848 } 12849 12850 static void __netdev_printk(const char *level, const struct net_device *dev, 12851 struct va_format *vaf) 12852 { 12853 if (dev && dev->dev.parent) { 12854 dev_printk_emit(level[1] - '0', 12855 dev->dev.parent, 12856 "%s %s %s%s: %pV", 12857 dev_driver_string(dev->dev.parent), 12858 dev_name(dev->dev.parent), 12859 netdev_name(dev), netdev_reg_state(dev), 12860 vaf); 12861 } else if (dev) { 12862 printk("%s%s%s: %pV", 12863 level, netdev_name(dev), netdev_reg_state(dev), vaf); 12864 } else { 12865 printk("%s(NULL net_device): %pV", level, vaf); 12866 } 12867 } 12868 12869 void netdev_printk(const char *level, const struct net_device *dev, 12870 const char *format, ...) 12871 { 12872 struct va_format vaf; 12873 va_list args; 12874 12875 va_start(args, format); 12876 12877 vaf.fmt = format; 12878 vaf.va = &args; 12879 12880 __netdev_printk(level, dev, &vaf); 12881 12882 va_end(args); 12883 } 12884 EXPORT_SYMBOL(netdev_printk); 12885 12886 #define define_netdev_printk_level(func, level) \ 12887 void func(const struct net_device *dev, const char *fmt, ...) \ 12888 { \ 12889 struct va_format vaf; \ 12890 va_list args; \ 12891 \ 12892 va_start(args, fmt); \ 12893 \ 12894 vaf.fmt = fmt; \ 12895 vaf.va = &args; \ 12896 \ 12897 __netdev_printk(level, dev, &vaf); \ 12898 \ 12899 va_end(args); \ 12900 } \ 12901 EXPORT_SYMBOL(func); 12902 12903 define_netdev_printk_level(netdev_emerg, KERN_EMERG); 12904 define_netdev_printk_level(netdev_alert, KERN_ALERT); 12905 define_netdev_printk_level(netdev_crit, KERN_CRIT); 12906 define_netdev_printk_level(netdev_err, KERN_ERR); 12907 define_netdev_printk_level(netdev_warn, KERN_WARNING); 12908 define_netdev_printk_level(netdev_notice, KERN_NOTICE); 12909 define_netdev_printk_level(netdev_info, KERN_INFO); 12910 12911 static void __net_exit netdev_exit(struct net *net) 12912 { 12913 kfree(net->dev_name_head); 12914 kfree(net->dev_index_head); 12915 xa_destroy(&net->dev_by_index); 12916 if (net != &init_net) 12917 WARN_ON_ONCE(!list_empty(&net->dev_base_head)); 12918 } 12919 12920 static struct pernet_operations __net_initdata netdev_net_ops = { 12921 .init = netdev_init, 12922 .exit = netdev_exit, 12923 }; 12924 12925 static void __net_exit default_device_exit_net(struct net *net) 12926 { 12927 struct netdev_name_node *name_node, *tmp; 12928 struct net_device *dev, *aux; 12929 /* 12930 * Push all migratable network devices back to the 12931 * initial network namespace 12932 */ 12933 ASSERT_RTNL(); 12934 for_each_netdev_safe(net, dev, aux) { 12935 int err; 12936 char fb_name[IFNAMSIZ]; 12937 12938 /* Ignore unmoveable devices (i.e. loopback) */ 12939 if (dev->netns_immutable) 12940 continue; 12941 12942 /* Leave virtual devices for the generic cleanup */ 12943 if (dev->rtnl_link_ops && !dev->rtnl_link_ops->netns_refund) 12944 continue; 12945 12946 /* Push remaining network devices to init_net */ 12947 snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex); 12948 if (netdev_name_in_use(&init_net, fb_name)) 12949 snprintf(fb_name, IFNAMSIZ, "dev%%d"); 12950 12951 netdev_for_each_altname_safe(dev, name_node, tmp) 12952 if (netdev_name_in_use(&init_net, name_node->name)) 12953 __netdev_name_node_alt_destroy(name_node); 12954 12955 err = dev_change_net_namespace(dev, &init_net, fb_name); 12956 if (err) { 12957 pr_emerg("%s: failed to move %s to init_net: %d\n", 12958 __func__, dev->name, err); 12959 BUG(); 12960 } 12961 } 12962 } 12963 12964 static void __net_exit default_device_exit_batch(struct list_head *net_list) 12965 { 12966 /* At exit all network devices most be removed from a network 12967 * namespace. Do this in the reverse order of registration. 12968 * Do this across as many network namespaces as possible to 12969 * improve batching efficiency. 12970 */ 12971 struct net_device *dev; 12972 struct net *net; 12973 LIST_HEAD(dev_kill_list); 12974 12975 rtnl_lock(); 12976 list_for_each_entry(net, net_list, exit_list) { 12977 default_device_exit_net(net); 12978 cond_resched(); 12979 } 12980 12981 list_for_each_entry(net, net_list, exit_list) { 12982 for_each_netdev_reverse(net, dev) { 12983 if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink) 12984 dev->rtnl_link_ops->dellink(dev, &dev_kill_list); 12985 else 12986 unregister_netdevice_queue(dev, &dev_kill_list); 12987 } 12988 } 12989 unregister_netdevice_many(&dev_kill_list); 12990 rtnl_unlock(); 12991 } 12992 12993 static struct pernet_operations __net_initdata default_device_ops = { 12994 .exit_batch = default_device_exit_batch, 12995 }; 12996 12997 static void __init net_dev_struct_check(void) 12998 { 12999 /* TX read-mostly hotpath */ 13000 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, priv_flags_fast); 13001 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, netdev_ops); 13002 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, header_ops); 13003 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, _tx); 13004 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, real_num_tx_queues); 13005 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_max_size); 13006 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_ipv4_max_size); 13007 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_max_segs); 13008 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_partial_features); 13009 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, num_tc); 13010 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, mtu); 13011 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, needed_headroom); 13012 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, tc_to_txq); 13013 #ifdef CONFIG_XPS 13014 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, xps_maps); 13015 #endif 13016 #ifdef CONFIG_NETFILTER_EGRESS 13017 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, nf_hooks_egress); 13018 #endif 13019 #ifdef CONFIG_NET_XGRESS 13020 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, tcx_egress); 13021 #endif 13022 CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_tx, 160); 13023 13024 /* TXRX read-mostly hotpath */ 13025 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, lstats); 13026 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, state); 13027 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, flags); 13028 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, hard_header_len); 13029 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, features); 13030 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, ip6_ptr); 13031 CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_txrx, 46); 13032 13033 /* RX read-mostly hotpath */ 13034 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, ptype_specific); 13035 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, ifindex); 13036 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, real_num_rx_queues); 13037 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, _rx); 13038 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, gro_max_size); 13039 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, gro_ipv4_max_size); 13040 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, rx_handler); 13041 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, rx_handler_data); 13042 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, nd_net); 13043 #ifdef CONFIG_NETPOLL 13044 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, npinfo); 13045 #endif 13046 #ifdef CONFIG_NET_XGRESS 13047 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, tcx_ingress); 13048 #endif 13049 CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_rx, 92); 13050 } 13051 13052 /* 13053 * Initialize the DEV module. At boot time this walks the device list and 13054 * unhooks any devices that fail to initialise (normally hardware not 13055 * present) and leaves us with a valid list of present and active devices. 13056 * 13057 */ 13058 13059 /* We allocate 256 pages for each CPU if PAGE_SHIFT is 12 */ 13060 #define SYSTEM_PERCPU_PAGE_POOL_SIZE ((1 << 20) / PAGE_SIZE) 13061 13062 static int net_page_pool_create(int cpuid) 13063 { 13064 #if IS_ENABLED(CONFIG_PAGE_POOL) 13065 struct page_pool_params page_pool_params = { 13066 .pool_size = SYSTEM_PERCPU_PAGE_POOL_SIZE, 13067 .flags = PP_FLAG_SYSTEM_POOL, 13068 .nid = cpu_to_mem(cpuid), 13069 }; 13070 struct page_pool *pp_ptr; 13071 int err; 13072 13073 pp_ptr = page_pool_create_percpu(&page_pool_params, cpuid); 13074 if (IS_ERR(pp_ptr)) 13075 return -ENOMEM; 13076 13077 err = xdp_reg_page_pool(pp_ptr); 13078 if (err) { 13079 page_pool_destroy(pp_ptr); 13080 return err; 13081 } 13082 13083 per_cpu(system_page_pool.pool, cpuid) = pp_ptr; 13084 #endif 13085 return 0; 13086 } 13087 13088 static int backlog_napi_should_run(unsigned int cpu) 13089 { 13090 struct softnet_data *sd = per_cpu_ptr(&softnet_data, cpu); 13091 struct napi_struct *napi = &sd->backlog; 13092 13093 return test_bit(NAPI_STATE_SCHED_THREADED, &napi->state); 13094 } 13095 13096 static void run_backlog_napi(unsigned int cpu) 13097 { 13098 struct softnet_data *sd = per_cpu_ptr(&softnet_data, cpu); 13099 13100 napi_threaded_poll_loop(&sd->backlog); 13101 } 13102 13103 static void backlog_napi_setup(unsigned int cpu) 13104 { 13105 struct softnet_data *sd = per_cpu_ptr(&softnet_data, cpu); 13106 struct napi_struct *napi = &sd->backlog; 13107 13108 napi->thread = this_cpu_read(backlog_napi); 13109 set_bit(NAPI_STATE_THREADED, &napi->state); 13110 } 13111 13112 static struct smp_hotplug_thread backlog_threads = { 13113 .store = &backlog_napi, 13114 .thread_should_run = backlog_napi_should_run, 13115 .thread_fn = run_backlog_napi, 13116 .thread_comm = "backlog_napi/%u", 13117 .setup = backlog_napi_setup, 13118 }; 13119 13120 /* 13121 * This is called single threaded during boot, so no need 13122 * to take the rtnl semaphore. 13123 */ 13124 static int __init net_dev_init(void) 13125 { 13126 int i, rc = -ENOMEM; 13127 13128 BUG_ON(!dev_boot_phase); 13129 13130 net_dev_struct_check(); 13131 13132 if (dev_proc_init()) 13133 goto out; 13134 13135 if (netdev_kobject_init()) 13136 goto out; 13137 13138 for (i = 0; i < PTYPE_HASH_SIZE; i++) 13139 INIT_LIST_HEAD(&ptype_base[i]); 13140 13141 if (register_pernet_subsys(&netdev_net_ops)) 13142 goto out; 13143 13144 /* 13145 * Initialise the packet receive queues. 13146 */ 13147 13148 flush_backlogs_fallback = flush_backlogs_alloc(); 13149 if (!flush_backlogs_fallback) 13150 goto out; 13151 13152 for_each_possible_cpu(i) { 13153 struct softnet_data *sd = &per_cpu(softnet_data, i); 13154 13155 skb_queue_head_init(&sd->input_pkt_queue); 13156 skb_queue_head_init(&sd->process_queue); 13157 #ifdef CONFIG_XFRM_OFFLOAD 13158 skb_queue_head_init(&sd->xfrm_backlog); 13159 #endif 13160 INIT_LIST_HEAD(&sd->poll_list); 13161 sd->output_queue_tailp = &sd->output_queue; 13162 #ifdef CONFIG_RPS 13163 INIT_CSD(&sd->csd, rps_trigger_softirq, sd); 13164 sd->cpu = i; 13165 #endif 13166 INIT_CSD(&sd->defer_csd, trigger_rx_softirq, sd); 13167 13168 gro_init(&sd->backlog.gro); 13169 sd->backlog.poll = process_backlog; 13170 sd->backlog.weight = weight_p; 13171 INIT_LIST_HEAD(&sd->backlog.poll_list); 13172 13173 if (net_page_pool_create(i)) 13174 goto out; 13175 } 13176 net_hotdata.skb_defer_nodes = 13177 __alloc_percpu(sizeof(struct skb_defer_node) * nr_node_ids, 13178 __alignof__(struct skb_defer_node)); 13179 if (!net_hotdata.skb_defer_nodes) 13180 goto out; 13181 if (use_backlog_threads()) 13182 smpboot_register_percpu_thread(&backlog_threads); 13183 13184 dev_boot_phase = 0; 13185 13186 /* The loopback device is special if any other network devices 13187 * is present in a network namespace the loopback device must 13188 * be present. Since we now dynamically allocate and free the 13189 * loopback device ensure this invariant is maintained by 13190 * keeping the loopback device as the first device on the 13191 * list of network devices. Ensuring the loopback devices 13192 * is the first device that appears and the last network device 13193 * that disappears. 13194 */ 13195 if (register_pernet_device(&loopback_net_ops)) 13196 goto out; 13197 13198 if (register_pernet_device(&default_device_ops)) 13199 goto out; 13200 13201 open_softirq(NET_TX_SOFTIRQ, net_tx_action); 13202 open_softirq(NET_RX_SOFTIRQ, net_rx_action); 13203 13204 rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead", 13205 NULL, dev_cpu_dead); 13206 WARN_ON(rc < 0); 13207 rc = 0; 13208 13209 /* avoid static key IPIs to isolated CPUs */ 13210 if (housekeeping_enabled(HK_TYPE_MISC)) 13211 net_enable_timestamp(); 13212 out: 13213 if (rc < 0) { 13214 for_each_possible_cpu(i) { 13215 struct page_pool *pp_ptr; 13216 13217 pp_ptr = per_cpu(system_page_pool.pool, i); 13218 if (!pp_ptr) 13219 continue; 13220 13221 xdp_unreg_page_pool(pp_ptr); 13222 page_pool_destroy(pp_ptr); 13223 per_cpu(system_page_pool.pool, i) = NULL; 13224 } 13225 } 13226 13227 return rc; 13228 } 13229 13230 subsys_initcall(net_dev_init); 13231