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