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