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