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