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