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