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