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