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