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