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