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_get_num_default_rss_queues - default number of RSS queues 2997 * 2998 * Default value is the number of physical cores if there are only 1 or 2, or 2999 * divided by 2 if there are more. 3000 */ 3001 int netif_get_num_default_rss_queues(void) 3002 { 3003 cpumask_var_t cpus; 3004 int cpu, count = 0; 3005 3006 if (unlikely(is_kdump_kernel() || !zalloc_cpumask_var(&cpus, GFP_KERNEL))) 3007 return 1; 3008 3009 cpumask_copy(cpus, cpu_online_mask); 3010 for_each_cpu(cpu, cpus) { 3011 ++count; 3012 cpumask_andnot(cpus, cpus, topology_sibling_cpumask(cpu)); 3013 } 3014 free_cpumask_var(cpus); 3015 3016 return count > 2 ? DIV_ROUND_UP(count, 2) : count; 3017 } 3018 EXPORT_SYMBOL(netif_get_num_default_rss_queues); 3019 3020 static void __netif_reschedule(struct Qdisc *q) 3021 { 3022 struct softnet_data *sd; 3023 unsigned long flags; 3024 3025 local_irq_save(flags); 3026 sd = this_cpu_ptr(&softnet_data); 3027 q->next_sched = NULL; 3028 *sd->output_queue_tailp = q; 3029 sd->output_queue_tailp = &q->next_sched; 3030 raise_softirq_irqoff(NET_TX_SOFTIRQ); 3031 local_irq_restore(flags); 3032 } 3033 3034 void __netif_schedule(struct Qdisc *q) 3035 { 3036 if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state)) 3037 __netif_reschedule(q); 3038 } 3039 EXPORT_SYMBOL(__netif_schedule); 3040 3041 struct dev_kfree_skb_cb { 3042 enum skb_free_reason reason; 3043 }; 3044 3045 static struct dev_kfree_skb_cb *get_kfree_skb_cb(const struct sk_buff *skb) 3046 { 3047 return (struct dev_kfree_skb_cb *)skb->cb; 3048 } 3049 3050 void netif_schedule_queue(struct netdev_queue *txq) 3051 { 3052 rcu_read_lock(); 3053 if (!netif_xmit_stopped(txq)) { 3054 struct Qdisc *q = rcu_dereference(txq->qdisc); 3055 3056 __netif_schedule(q); 3057 } 3058 rcu_read_unlock(); 3059 } 3060 EXPORT_SYMBOL(netif_schedule_queue); 3061 3062 void netif_tx_wake_queue(struct netdev_queue *dev_queue) 3063 { 3064 if (test_and_clear_bit(__QUEUE_STATE_DRV_XOFF, &dev_queue->state)) { 3065 struct Qdisc *q; 3066 3067 rcu_read_lock(); 3068 q = rcu_dereference(dev_queue->qdisc); 3069 __netif_schedule(q); 3070 rcu_read_unlock(); 3071 } 3072 } 3073 EXPORT_SYMBOL(netif_tx_wake_queue); 3074 3075 void __dev_kfree_skb_irq(struct sk_buff *skb, enum skb_free_reason reason) 3076 { 3077 unsigned long flags; 3078 3079 if (unlikely(!skb)) 3080 return; 3081 3082 if (likely(refcount_read(&skb->users) == 1)) { 3083 smp_rmb(); 3084 refcount_set(&skb->users, 0); 3085 } else if (likely(!refcount_dec_and_test(&skb->users))) { 3086 return; 3087 } 3088 get_kfree_skb_cb(skb)->reason = reason; 3089 local_irq_save(flags); 3090 skb->next = __this_cpu_read(softnet_data.completion_queue); 3091 __this_cpu_write(softnet_data.completion_queue, skb); 3092 raise_softirq_irqoff(NET_TX_SOFTIRQ); 3093 local_irq_restore(flags); 3094 } 3095 EXPORT_SYMBOL(__dev_kfree_skb_irq); 3096 3097 void __dev_kfree_skb_any(struct sk_buff *skb, enum skb_free_reason reason) 3098 { 3099 if (in_hardirq() || irqs_disabled()) 3100 __dev_kfree_skb_irq(skb, reason); 3101 else 3102 dev_kfree_skb(skb); 3103 } 3104 EXPORT_SYMBOL(__dev_kfree_skb_any); 3105 3106 3107 /** 3108 * netif_device_detach - mark device as removed 3109 * @dev: network device 3110 * 3111 * Mark device as removed from system and therefore no longer available. 3112 */ 3113 void netif_device_detach(struct net_device *dev) 3114 { 3115 if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) && 3116 netif_running(dev)) { 3117 netif_tx_stop_all_queues(dev); 3118 } 3119 } 3120 EXPORT_SYMBOL(netif_device_detach); 3121 3122 /** 3123 * netif_device_attach - mark device as attached 3124 * @dev: network device 3125 * 3126 * Mark device as attached from system and restart if needed. 3127 */ 3128 void netif_device_attach(struct net_device *dev) 3129 { 3130 if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) && 3131 netif_running(dev)) { 3132 netif_tx_wake_all_queues(dev); 3133 __netdev_watchdog_up(dev); 3134 } 3135 } 3136 EXPORT_SYMBOL(netif_device_attach); 3137 3138 /* 3139 * Returns a Tx hash based on the given packet descriptor a Tx queues' number 3140 * to be used as a distribution range. 3141 */ 3142 static u16 skb_tx_hash(const struct net_device *dev, 3143 const struct net_device *sb_dev, 3144 struct sk_buff *skb) 3145 { 3146 u32 hash; 3147 u16 qoffset = 0; 3148 u16 qcount = dev->real_num_tx_queues; 3149 3150 if (dev->num_tc) { 3151 u8 tc = netdev_get_prio_tc_map(dev, skb->priority); 3152 3153 qoffset = sb_dev->tc_to_txq[tc].offset; 3154 qcount = sb_dev->tc_to_txq[tc].count; 3155 if (unlikely(!qcount)) { 3156 net_warn_ratelimited("%s: invalid qcount, qoffset %u for tc %u\n", 3157 sb_dev->name, qoffset, tc); 3158 qoffset = 0; 3159 qcount = dev->real_num_tx_queues; 3160 } 3161 } 3162 3163 if (skb_rx_queue_recorded(skb)) { 3164 hash = skb_get_rx_queue(skb); 3165 if (hash >= qoffset) 3166 hash -= qoffset; 3167 while (unlikely(hash >= qcount)) 3168 hash -= qcount; 3169 return hash + qoffset; 3170 } 3171 3172 return (u16) reciprocal_scale(skb_get_hash(skb), qcount) + qoffset; 3173 } 3174 3175 static void skb_warn_bad_offload(const struct sk_buff *skb) 3176 { 3177 static const netdev_features_t null_features; 3178 struct net_device *dev = skb->dev; 3179 const char *name = ""; 3180 3181 if (!net_ratelimit()) 3182 return; 3183 3184 if (dev) { 3185 if (dev->dev.parent) 3186 name = dev_driver_string(dev->dev.parent); 3187 else 3188 name = netdev_name(dev); 3189 } 3190 skb_dump(KERN_WARNING, skb, false); 3191 WARN(1, "%s: caps=(%pNF, %pNF)\n", 3192 name, dev ? &dev->features : &null_features, 3193 skb->sk ? &skb->sk->sk_route_caps : &null_features); 3194 } 3195 3196 /* 3197 * Invalidate hardware checksum when packet is to be mangled, and 3198 * complete checksum manually on outgoing path. 3199 */ 3200 int skb_checksum_help(struct sk_buff *skb) 3201 { 3202 __wsum csum; 3203 int ret = 0, offset; 3204 3205 if (skb->ip_summed == CHECKSUM_COMPLETE) 3206 goto out_set_summed; 3207 3208 if (unlikely(skb_is_gso(skb))) { 3209 skb_warn_bad_offload(skb); 3210 return -EINVAL; 3211 } 3212 3213 /* Before computing a checksum, we should make sure no frag could 3214 * be modified by an external entity : checksum could be wrong. 3215 */ 3216 if (skb_has_shared_frag(skb)) { 3217 ret = __skb_linearize(skb); 3218 if (ret) 3219 goto out; 3220 } 3221 3222 offset = skb_checksum_start_offset(skb); 3223 BUG_ON(offset >= skb_headlen(skb)); 3224 csum = skb_checksum(skb, offset, skb->len - offset, 0); 3225 3226 offset += skb->csum_offset; 3227 BUG_ON(offset + sizeof(__sum16) > skb_headlen(skb)); 3228 3229 ret = skb_ensure_writable(skb, offset + sizeof(__sum16)); 3230 if (ret) 3231 goto out; 3232 3233 *(__sum16 *)(skb->data + offset) = csum_fold(csum) ?: CSUM_MANGLED_0; 3234 out_set_summed: 3235 skb->ip_summed = CHECKSUM_NONE; 3236 out: 3237 return ret; 3238 } 3239 EXPORT_SYMBOL(skb_checksum_help); 3240 3241 int skb_crc32c_csum_help(struct sk_buff *skb) 3242 { 3243 __le32 crc32c_csum; 3244 int ret = 0, offset, start; 3245 3246 if (skb->ip_summed != CHECKSUM_PARTIAL) 3247 goto out; 3248 3249 if (unlikely(skb_is_gso(skb))) 3250 goto out; 3251 3252 /* Before computing a checksum, we should make sure no frag could 3253 * be modified by an external entity : checksum could be wrong. 3254 */ 3255 if (unlikely(skb_has_shared_frag(skb))) { 3256 ret = __skb_linearize(skb); 3257 if (ret) 3258 goto out; 3259 } 3260 start = skb_checksum_start_offset(skb); 3261 offset = start + offsetof(struct sctphdr, checksum); 3262 if (WARN_ON_ONCE(offset >= skb_headlen(skb))) { 3263 ret = -EINVAL; 3264 goto out; 3265 } 3266 3267 ret = skb_ensure_writable(skb, offset + sizeof(__le32)); 3268 if (ret) 3269 goto out; 3270 3271 crc32c_csum = cpu_to_le32(~__skb_checksum(skb, start, 3272 skb->len - start, ~(__u32)0, 3273 crc32c_csum_stub)); 3274 *(__le32 *)(skb->data + offset) = crc32c_csum; 3275 skb->ip_summed = CHECKSUM_NONE; 3276 skb->csum_not_inet = 0; 3277 out: 3278 return ret; 3279 } 3280 3281 __be16 skb_network_protocol(struct sk_buff *skb, int *depth) 3282 { 3283 __be16 type = skb->protocol; 3284 3285 /* Tunnel gso handlers can set protocol to ethernet. */ 3286 if (type == htons(ETH_P_TEB)) { 3287 struct ethhdr *eth; 3288 3289 if (unlikely(!pskb_may_pull(skb, sizeof(struct ethhdr)))) 3290 return 0; 3291 3292 eth = (struct ethhdr *)skb->data; 3293 type = eth->h_proto; 3294 } 3295 3296 return __vlan_get_protocol(skb, type, depth); 3297 } 3298 3299 /* openvswitch calls this on rx path, so we need a different check. 3300 */ 3301 static inline bool skb_needs_check(struct sk_buff *skb, bool tx_path) 3302 { 3303 if (tx_path) 3304 return skb->ip_summed != CHECKSUM_PARTIAL && 3305 skb->ip_summed != CHECKSUM_UNNECESSARY; 3306 3307 return skb->ip_summed == CHECKSUM_NONE; 3308 } 3309 3310 /** 3311 * __skb_gso_segment - Perform segmentation on skb. 3312 * @skb: buffer to segment 3313 * @features: features for the output path (see dev->features) 3314 * @tx_path: whether it is called in TX path 3315 * 3316 * This function segments the given skb and returns a list of segments. 3317 * 3318 * It may return NULL if the skb requires no segmentation. This is 3319 * only possible when GSO is used for verifying header integrity. 3320 * 3321 * Segmentation preserves SKB_GSO_CB_OFFSET bytes of previous skb cb. 3322 */ 3323 struct sk_buff *__skb_gso_segment(struct sk_buff *skb, 3324 netdev_features_t features, bool tx_path) 3325 { 3326 struct sk_buff *segs; 3327 3328 if (unlikely(skb_needs_check(skb, tx_path))) { 3329 int err; 3330 3331 /* We're going to init ->check field in TCP or UDP header */ 3332 err = skb_cow_head(skb, 0); 3333 if (err < 0) 3334 return ERR_PTR(err); 3335 } 3336 3337 /* Only report GSO partial support if it will enable us to 3338 * support segmentation on this frame without needing additional 3339 * work. 3340 */ 3341 if (features & NETIF_F_GSO_PARTIAL) { 3342 netdev_features_t partial_features = NETIF_F_GSO_ROBUST; 3343 struct net_device *dev = skb->dev; 3344 3345 partial_features |= dev->features & dev->gso_partial_features; 3346 if (!skb_gso_ok(skb, features | partial_features)) 3347 features &= ~NETIF_F_GSO_PARTIAL; 3348 } 3349 3350 BUILD_BUG_ON(SKB_GSO_CB_OFFSET + 3351 sizeof(*SKB_GSO_CB(skb)) > sizeof(skb->cb)); 3352 3353 SKB_GSO_CB(skb)->mac_offset = skb_headroom(skb); 3354 SKB_GSO_CB(skb)->encap_level = 0; 3355 3356 skb_reset_mac_header(skb); 3357 skb_reset_mac_len(skb); 3358 3359 segs = skb_mac_gso_segment(skb, features); 3360 3361 if (segs != skb && unlikely(skb_needs_check(skb, tx_path) && !IS_ERR(segs))) 3362 skb_warn_bad_offload(skb); 3363 3364 return segs; 3365 } 3366 EXPORT_SYMBOL(__skb_gso_segment); 3367 3368 /* Take action when hardware reception checksum errors are detected. */ 3369 #ifdef CONFIG_BUG 3370 static void do_netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb) 3371 { 3372 netdev_err(dev, "hw csum failure\n"); 3373 skb_dump(KERN_ERR, skb, true); 3374 dump_stack(); 3375 } 3376 3377 void netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb) 3378 { 3379 DO_ONCE_LITE(do_netdev_rx_csum_fault, dev, skb); 3380 } 3381 EXPORT_SYMBOL(netdev_rx_csum_fault); 3382 #endif 3383 3384 /* XXX: check that highmem exists at all on the given machine. */ 3385 static int illegal_highdma(struct net_device *dev, struct sk_buff *skb) 3386 { 3387 #ifdef CONFIG_HIGHMEM 3388 int i; 3389 3390 if (!(dev->features & NETIF_F_HIGHDMA)) { 3391 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { 3392 skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; 3393 3394 if (PageHighMem(skb_frag_page(frag))) 3395 return 1; 3396 } 3397 } 3398 #endif 3399 return 0; 3400 } 3401 3402 /* If MPLS offload request, verify we are testing hardware MPLS features 3403 * instead of standard features for the netdev. 3404 */ 3405 #if IS_ENABLED(CONFIG_NET_MPLS_GSO) 3406 static netdev_features_t net_mpls_features(struct sk_buff *skb, 3407 netdev_features_t features, 3408 __be16 type) 3409 { 3410 if (eth_p_mpls(type)) 3411 features &= skb->dev->mpls_features; 3412 3413 return features; 3414 } 3415 #else 3416 static netdev_features_t net_mpls_features(struct sk_buff *skb, 3417 netdev_features_t features, 3418 __be16 type) 3419 { 3420 return features; 3421 } 3422 #endif 3423 3424 static netdev_features_t harmonize_features(struct sk_buff *skb, 3425 netdev_features_t features) 3426 { 3427 __be16 type; 3428 3429 type = skb_network_protocol(skb, NULL); 3430 features = net_mpls_features(skb, features, type); 3431 3432 if (skb->ip_summed != CHECKSUM_NONE && 3433 !can_checksum_protocol(features, type)) { 3434 features &= ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK); 3435 } 3436 if (illegal_highdma(skb->dev, skb)) 3437 features &= ~NETIF_F_SG; 3438 3439 return features; 3440 } 3441 3442 netdev_features_t passthru_features_check(struct sk_buff *skb, 3443 struct net_device *dev, 3444 netdev_features_t features) 3445 { 3446 return features; 3447 } 3448 EXPORT_SYMBOL(passthru_features_check); 3449 3450 static netdev_features_t dflt_features_check(struct sk_buff *skb, 3451 struct net_device *dev, 3452 netdev_features_t features) 3453 { 3454 return vlan_features_check(skb, features); 3455 } 3456 3457 static netdev_features_t gso_features_check(const struct sk_buff *skb, 3458 struct net_device *dev, 3459 netdev_features_t features) 3460 { 3461 u16 gso_segs = skb_shinfo(skb)->gso_segs; 3462 3463 if (gso_segs > READ_ONCE(dev->gso_max_segs)) 3464 return features & ~NETIF_F_GSO_MASK; 3465 3466 if (!skb_shinfo(skb)->gso_type) { 3467 skb_warn_bad_offload(skb); 3468 return features & ~NETIF_F_GSO_MASK; 3469 } 3470 3471 /* Support for GSO partial features requires software 3472 * intervention before we can actually process the packets 3473 * so we need to strip support for any partial features now 3474 * and we can pull them back in after we have partially 3475 * segmented the frame. 3476 */ 3477 if (!(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL)) 3478 features &= ~dev->gso_partial_features; 3479 3480 /* Make sure to clear the IPv4 ID mangling feature if the 3481 * IPv4 header has the potential to be fragmented. 3482 */ 3483 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) { 3484 struct iphdr *iph = skb->encapsulation ? 3485 inner_ip_hdr(skb) : ip_hdr(skb); 3486 3487 if (!(iph->frag_off & htons(IP_DF))) 3488 features &= ~NETIF_F_TSO_MANGLEID; 3489 } 3490 3491 return features; 3492 } 3493 3494 netdev_features_t netif_skb_features(struct sk_buff *skb) 3495 { 3496 struct net_device *dev = skb->dev; 3497 netdev_features_t features = dev->features; 3498 3499 if (skb_is_gso(skb)) 3500 features = gso_features_check(skb, dev, features); 3501 3502 /* If encapsulation offload request, verify we are testing 3503 * hardware encapsulation features instead of standard 3504 * features for the netdev 3505 */ 3506 if (skb->encapsulation) 3507 features &= dev->hw_enc_features; 3508 3509 if (skb_vlan_tagged(skb)) 3510 features = netdev_intersect_features(features, 3511 dev->vlan_features | 3512 NETIF_F_HW_VLAN_CTAG_TX | 3513 NETIF_F_HW_VLAN_STAG_TX); 3514 3515 if (dev->netdev_ops->ndo_features_check) 3516 features &= dev->netdev_ops->ndo_features_check(skb, dev, 3517 features); 3518 else 3519 features &= dflt_features_check(skb, dev, features); 3520 3521 return harmonize_features(skb, features); 3522 } 3523 EXPORT_SYMBOL(netif_skb_features); 3524 3525 static int xmit_one(struct sk_buff *skb, struct net_device *dev, 3526 struct netdev_queue *txq, bool more) 3527 { 3528 unsigned int len; 3529 int rc; 3530 3531 if (dev_nit_active(dev)) 3532 dev_queue_xmit_nit(skb, dev); 3533 3534 len = skb->len; 3535 PRANDOM_ADD_NOISE(skb, dev, txq, len + jiffies); 3536 trace_net_dev_start_xmit(skb, dev); 3537 rc = netdev_start_xmit(skb, dev, txq, more); 3538 trace_net_dev_xmit(skb, rc, dev, len); 3539 3540 return rc; 3541 } 3542 3543 struct sk_buff *dev_hard_start_xmit(struct sk_buff *first, struct net_device *dev, 3544 struct netdev_queue *txq, int *ret) 3545 { 3546 struct sk_buff *skb = first; 3547 int rc = NETDEV_TX_OK; 3548 3549 while (skb) { 3550 struct sk_buff *next = skb->next; 3551 3552 skb_mark_not_on_list(skb); 3553 rc = xmit_one(skb, dev, txq, next != NULL); 3554 if (unlikely(!dev_xmit_complete(rc))) { 3555 skb->next = next; 3556 goto out; 3557 } 3558 3559 skb = next; 3560 if (netif_tx_queue_stopped(txq) && skb) { 3561 rc = NETDEV_TX_BUSY; 3562 break; 3563 } 3564 } 3565 3566 out: 3567 *ret = rc; 3568 return skb; 3569 } 3570 3571 static struct sk_buff *validate_xmit_vlan(struct sk_buff *skb, 3572 netdev_features_t features) 3573 { 3574 if (skb_vlan_tag_present(skb) && 3575 !vlan_hw_offload_capable(features, skb->vlan_proto)) 3576 skb = __vlan_hwaccel_push_inside(skb); 3577 return skb; 3578 } 3579 3580 int skb_csum_hwoffload_help(struct sk_buff *skb, 3581 const netdev_features_t features) 3582 { 3583 if (unlikely(skb_csum_is_sctp(skb))) 3584 return !!(features & NETIF_F_SCTP_CRC) ? 0 : 3585 skb_crc32c_csum_help(skb); 3586 3587 if (features & NETIF_F_HW_CSUM) 3588 return 0; 3589 3590 if (features & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM)) { 3591 switch (skb->csum_offset) { 3592 case offsetof(struct tcphdr, check): 3593 case offsetof(struct udphdr, check): 3594 return 0; 3595 } 3596 } 3597 3598 return skb_checksum_help(skb); 3599 } 3600 EXPORT_SYMBOL(skb_csum_hwoffload_help); 3601 3602 static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device *dev, bool *again) 3603 { 3604 netdev_features_t features; 3605 3606 features = netif_skb_features(skb); 3607 skb = validate_xmit_vlan(skb, features); 3608 if (unlikely(!skb)) 3609 goto out_null; 3610 3611 skb = sk_validate_xmit_skb(skb, dev); 3612 if (unlikely(!skb)) 3613 goto out_null; 3614 3615 if (netif_needs_gso(skb, features)) { 3616 struct sk_buff *segs; 3617 3618 segs = skb_gso_segment(skb, features); 3619 if (IS_ERR(segs)) { 3620 goto out_kfree_skb; 3621 } else if (segs) { 3622 consume_skb(skb); 3623 skb = segs; 3624 } 3625 } else { 3626 if (skb_needs_linearize(skb, features) && 3627 __skb_linearize(skb)) 3628 goto out_kfree_skb; 3629 3630 /* If packet is not checksummed and device does not 3631 * support checksumming for this protocol, complete 3632 * checksumming here. 3633 */ 3634 if (skb->ip_summed == CHECKSUM_PARTIAL) { 3635 if (skb->encapsulation) 3636 skb_set_inner_transport_header(skb, 3637 skb_checksum_start_offset(skb)); 3638 else 3639 skb_set_transport_header(skb, 3640 skb_checksum_start_offset(skb)); 3641 if (skb_csum_hwoffload_help(skb, features)) 3642 goto out_kfree_skb; 3643 } 3644 } 3645 3646 skb = validate_xmit_xfrm(skb, features, again); 3647 3648 return skb; 3649 3650 out_kfree_skb: 3651 kfree_skb(skb); 3652 out_null: 3653 dev_core_stats_tx_dropped_inc(dev); 3654 return NULL; 3655 } 3656 3657 struct sk_buff *validate_xmit_skb_list(struct sk_buff *skb, struct net_device *dev, bool *again) 3658 { 3659 struct sk_buff *next, *head = NULL, *tail; 3660 3661 for (; skb != NULL; skb = next) { 3662 next = skb->next; 3663 skb_mark_not_on_list(skb); 3664 3665 /* in case skb wont be segmented, point to itself */ 3666 skb->prev = skb; 3667 3668 skb = validate_xmit_skb(skb, dev, again); 3669 if (!skb) 3670 continue; 3671 3672 if (!head) 3673 head = skb; 3674 else 3675 tail->next = skb; 3676 /* If skb was segmented, skb->prev points to 3677 * the last segment. If not, it still contains skb. 3678 */ 3679 tail = skb->prev; 3680 } 3681 return head; 3682 } 3683 EXPORT_SYMBOL_GPL(validate_xmit_skb_list); 3684 3685 static void qdisc_pkt_len_init(struct sk_buff *skb) 3686 { 3687 const struct skb_shared_info *shinfo = skb_shinfo(skb); 3688 3689 qdisc_skb_cb(skb)->pkt_len = skb->len; 3690 3691 /* To get more precise estimation of bytes sent on wire, 3692 * we add to pkt_len the headers size of all segments 3693 */ 3694 if (shinfo->gso_size && skb_transport_header_was_set(skb)) { 3695 unsigned int hdr_len; 3696 u16 gso_segs = shinfo->gso_segs; 3697 3698 /* mac layer + network layer */ 3699 hdr_len = skb_transport_header(skb) - skb_mac_header(skb); 3700 3701 /* + transport layer */ 3702 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) { 3703 const struct tcphdr *th; 3704 struct tcphdr _tcphdr; 3705 3706 th = skb_header_pointer(skb, skb_transport_offset(skb), 3707 sizeof(_tcphdr), &_tcphdr); 3708 if (likely(th)) 3709 hdr_len += __tcp_hdrlen(th); 3710 } else { 3711 struct udphdr _udphdr; 3712 3713 if (skb_header_pointer(skb, skb_transport_offset(skb), 3714 sizeof(_udphdr), &_udphdr)) 3715 hdr_len += sizeof(struct udphdr); 3716 } 3717 3718 if (shinfo->gso_type & SKB_GSO_DODGY) 3719 gso_segs = DIV_ROUND_UP(skb->len - hdr_len, 3720 shinfo->gso_size); 3721 3722 qdisc_skb_cb(skb)->pkt_len += (gso_segs - 1) * hdr_len; 3723 } 3724 } 3725 3726 static int dev_qdisc_enqueue(struct sk_buff *skb, struct Qdisc *q, 3727 struct sk_buff **to_free, 3728 struct netdev_queue *txq) 3729 { 3730 int rc; 3731 3732 rc = q->enqueue(skb, q, to_free) & NET_XMIT_MASK; 3733 if (rc == NET_XMIT_SUCCESS) 3734 trace_qdisc_enqueue(q, txq, skb); 3735 return rc; 3736 } 3737 3738 static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q, 3739 struct net_device *dev, 3740 struct netdev_queue *txq) 3741 { 3742 spinlock_t *root_lock = qdisc_lock(q); 3743 struct sk_buff *to_free = NULL; 3744 bool contended; 3745 int rc; 3746 3747 qdisc_calculate_pkt_len(skb, q); 3748 3749 if (q->flags & TCQ_F_NOLOCK) { 3750 if (q->flags & TCQ_F_CAN_BYPASS && nolock_qdisc_is_empty(q) && 3751 qdisc_run_begin(q)) { 3752 /* Retest nolock_qdisc_is_empty() within the protection 3753 * of q->seqlock to protect from racing with requeuing. 3754 */ 3755 if (unlikely(!nolock_qdisc_is_empty(q))) { 3756 rc = dev_qdisc_enqueue(skb, q, &to_free, txq); 3757 __qdisc_run(q); 3758 qdisc_run_end(q); 3759 3760 goto no_lock_out; 3761 } 3762 3763 qdisc_bstats_cpu_update(q, skb); 3764 if (sch_direct_xmit(skb, q, dev, txq, NULL, true) && 3765 !nolock_qdisc_is_empty(q)) 3766 __qdisc_run(q); 3767 3768 qdisc_run_end(q); 3769 return NET_XMIT_SUCCESS; 3770 } 3771 3772 rc = dev_qdisc_enqueue(skb, q, &to_free, txq); 3773 qdisc_run(q); 3774 3775 no_lock_out: 3776 if (unlikely(to_free)) 3777 kfree_skb_list_reason(to_free, 3778 SKB_DROP_REASON_QDISC_DROP); 3779 return rc; 3780 } 3781 3782 /* 3783 * Heuristic to force contended enqueues to serialize on a 3784 * separate lock before trying to get qdisc main lock. 3785 * This permits qdisc->running owner to get the lock more 3786 * often and dequeue packets faster. 3787 * On PREEMPT_RT it is possible to preempt the qdisc owner during xmit 3788 * and then other tasks will only enqueue packets. The packets will be 3789 * sent after the qdisc owner is scheduled again. To prevent this 3790 * scenario the task always serialize on the lock. 3791 */ 3792 contended = qdisc_is_running(q) || IS_ENABLED(CONFIG_PREEMPT_RT); 3793 if (unlikely(contended)) 3794 spin_lock(&q->busylock); 3795 3796 spin_lock(root_lock); 3797 if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) { 3798 __qdisc_drop(skb, &to_free); 3799 rc = NET_XMIT_DROP; 3800 } else if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) && 3801 qdisc_run_begin(q)) { 3802 /* 3803 * This is a work-conserving queue; there are no old skbs 3804 * waiting to be sent out; and the qdisc is not running - 3805 * xmit the skb directly. 3806 */ 3807 3808 qdisc_bstats_update(q, skb); 3809 3810 if (sch_direct_xmit(skb, q, dev, txq, root_lock, true)) { 3811 if (unlikely(contended)) { 3812 spin_unlock(&q->busylock); 3813 contended = false; 3814 } 3815 __qdisc_run(q); 3816 } 3817 3818 qdisc_run_end(q); 3819 rc = NET_XMIT_SUCCESS; 3820 } else { 3821 rc = dev_qdisc_enqueue(skb, q, &to_free, txq); 3822 if (qdisc_run_begin(q)) { 3823 if (unlikely(contended)) { 3824 spin_unlock(&q->busylock); 3825 contended = false; 3826 } 3827 __qdisc_run(q); 3828 qdisc_run_end(q); 3829 } 3830 } 3831 spin_unlock(root_lock); 3832 if (unlikely(to_free)) 3833 kfree_skb_list_reason(to_free, SKB_DROP_REASON_QDISC_DROP); 3834 if (unlikely(contended)) 3835 spin_unlock(&q->busylock); 3836 return rc; 3837 } 3838 3839 #if IS_ENABLED(CONFIG_CGROUP_NET_PRIO) 3840 static void skb_update_prio(struct sk_buff *skb) 3841 { 3842 const struct netprio_map *map; 3843 const struct sock *sk; 3844 unsigned int prioidx; 3845 3846 if (skb->priority) 3847 return; 3848 map = rcu_dereference_bh(skb->dev->priomap); 3849 if (!map) 3850 return; 3851 sk = skb_to_full_sk(skb); 3852 if (!sk) 3853 return; 3854 3855 prioidx = sock_cgroup_prioidx(&sk->sk_cgrp_data); 3856 3857 if (prioidx < map->priomap_len) 3858 skb->priority = map->priomap[prioidx]; 3859 } 3860 #else 3861 #define skb_update_prio(skb) 3862 #endif 3863 3864 /** 3865 * dev_loopback_xmit - loop back @skb 3866 * @net: network namespace this loopback is happening in 3867 * @sk: sk needed to be a netfilter okfn 3868 * @skb: buffer to transmit 3869 */ 3870 int dev_loopback_xmit(struct net *net, struct sock *sk, struct sk_buff *skb) 3871 { 3872 skb_reset_mac_header(skb); 3873 __skb_pull(skb, skb_network_offset(skb)); 3874 skb->pkt_type = PACKET_LOOPBACK; 3875 if (skb->ip_summed == CHECKSUM_NONE) 3876 skb->ip_summed = CHECKSUM_UNNECESSARY; 3877 WARN_ON(!skb_dst(skb)); 3878 skb_dst_force(skb); 3879 netif_rx(skb); 3880 return 0; 3881 } 3882 EXPORT_SYMBOL(dev_loopback_xmit); 3883 3884 #ifdef CONFIG_NET_EGRESS 3885 static struct sk_buff * 3886 sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev) 3887 { 3888 #ifdef CONFIG_NET_CLS_ACT 3889 struct mini_Qdisc *miniq = rcu_dereference_bh(dev->miniq_egress); 3890 struct tcf_result cl_res; 3891 3892 if (!miniq) 3893 return skb; 3894 3895 /* qdisc_skb_cb(skb)->pkt_len was already set by the caller. */ 3896 tc_skb_cb(skb)->mru = 0; 3897 tc_skb_cb(skb)->post_ct = false; 3898 mini_qdisc_bstats_cpu_update(miniq, skb); 3899 3900 switch (tcf_classify(skb, miniq->block, miniq->filter_list, &cl_res, false)) { 3901 case TC_ACT_OK: 3902 case TC_ACT_RECLASSIFY: 3903 skb->tc_index = TC_H_MIN(cl_res.classid); 3904 break; 3905 case TC_ACT_SHOT: 3906 mini_qdisc_qstats_cpu_drop(miniq); 3907 *ret = NET_XMIT_DROP; 3908 kfree_skb_reason(skb, SKB_DROP_REASON_TC_EGRESS); 3909 return NULL; 3910 case TC_ACT_STOLEN: 3911 case TC_ACT_QUEUED: 3912 case TC_ACT_TRAP: 3913 *ret = NET_XMIT_SUCCESS; 3914 consume_skb(skb); 3915 return NULL; 3916 case TC_ACT_REDIRECT: 3917 /* No need to push/pop skb's mac_header here on egress! */ 3918 skb_do_redirect(skb); 3919 *ret = NET_XMIT_SUCCESS; 3920 return NULL; 3921 default: 3922 break; 3923 } 3924 #endif /* CONFIG_NET_CLS_ACT */ 3925 3926 return skb; 3927 } 3928 #endif /* CONFIG_NET_EGRESS */ 3929 3930 #ifdef CONFIG_XPS 3931 static int __get_xps_queue_idx(struct net_device *dev, struct sk_buff *skb, 3932 struct xps_dev_maps *dev_maps, unsigned int tci) 3933 { 3934 int tc = netdev_get_prio_tc_map(dev, skb->priority); 3935 struct xps_map *map; 3936 int queue_index = -1; 3937 3938 if (tc >= dev_maps->num_tc || tci >= dev_maps->nr_ids) 3939 return queue_index; 3940 3941 tci *= dev_maps->num_tc; 3942 tci += tc; 3943 3944 map = rcu_dereference(dev_maps->attr_map[tci]); 3945 if (map) { 3946 if (map->len == 1) 3947 queue_index = map->queues[0]; 3948 else 3949 queue_index = map->queues[reciprocal_scale( 3950 skb_get_hash(skb), map->len)]; 3951 if (unlikely(queue_index >= dev->real_num_tx_queues)) 3952 queue_index = -1; 3953 } 3954 return queue_index; 3955 } 3956 #endif 3957 3958 static int get_xps_queue(struct net_device *dev, struct net_device *sb_dev, 3959 struct sk_buff *skb) 3960 { 3961 #ifdef CONFIG_XPS 3962 struct xps_dev_maps *dev_maps; 3963 struct sock *sk = skb->sk; 3964 int queue_index = -1; 3965 3966 if (!static_key_false(&xps_needed)) 3967 return -1; 3968 3969 rcu_read_lock(); 3970 if (!static_key_false(&xps_rxqs_needed)) 3971 goto get_cpus_map; 3972 3973 dev_maps = rcu_dereference(sb_dev->xps_maps[XPS_RXQS]); 3974 if (dev_maps) { 3975 int tci = sk_rx_queue_get(sk); 3976 3977 if (tci >= 0) 3978 queue_index = __get_xps_queue_idx(dev, skb, dev_maps, 3979 tci); 3980 } 3981 3982 get_cpus_map: 3983 if (queue_index < 0) { 3984 dev_maps = rcu_dereference(sb_dev->xps_maps[XPS_CPUS]); 3985 if (dev_maps) { 3986 unsigned int tci = skb->sender_cpu - 1; 3987 3988 queue_index = __get_xps_queue_idx(dev, skb, dev_maps, 3989 tci); 3990 } 3991 } 3992 rcu_read_unlock(); 3993 3994 return queue_index; 3995 #else 3996 return -1; 3997 #endif 3998 } 3999 4000 u16 dev_pick_tx_zero(struct net_device *dev, struct sk_buff *skb, 4001 struct net_device *sb_dev) 4002 { 4003 return 0; 4004 } 4005 EXPORT_SYMBOL(dev_pick_tx_zero); 4006 4007 u16 dev_pick_tx_cpu_id(struct net_device *dev, struct sk_buff *skb, 4008 struct net_device *sb_dev) 4009 { 4010 return (u16)raw_smp_processor_id() % dev->real_num_tx_queues; 4011 } 4012 EXPORT_SYMBOL(dev_pick_tx_cpu_id); 4013 4014 u16 netdev_pick_tx(struct net_device *dev, struct sk_buff *skb, 4015 struct net_device *sb_dev) 4016 { 4017 struct sock *sk = skb->sk; 4018 int queue_index = sk_tx_queue_get(sk); 4019 4020 sb_dev = sb_dev ? : dev; 4021 4022 if (queue_index < 0 || skb->ooo_okay || 4023 queue_index >= dev->real_num_tx_queues) { 4024 int new_index = get_xps_queue(dev, sb_dev, skb); 4025 4026 if (new_index < 0) 4027 new_index = skb_tx_hash(dev, sb_dev, skb); 4028 4029 if (queue_index != new_index && sk && 4030 sk_fullsock(sk) && 4031 rcu_access_pointer(sk->sk_dst_cache)) 4032 sk_tx_queue_set(sk, new_index); 4033 4034 queue_index = new_index; 4035 } 4036 4037 return queue_index; 4038 } 4039 EXPORT_SYMBOL(netdev_pick_tx); 4040 4041 struct netdev_queue *netdev_core_pick_tx(struct net_device *dev, 4042 struct sk_buff *skb, 4043 struct net_device *sb_dev) 4044 { 4045 int queue_index = 0; 4046 4047 #ifdef CONFIG_XPS 4048 u32 sender_cpu = skb->sender_cpu - 1; 4049 4050 if (sender_cpu >= (u32)NR_CPUS) 4051 skb->sender_cpu = raw_smp_processor_id() + 1; 4052 #endif 4053 4054 if (dev->real_num_tx_queues != 1) { 4055 const struct net_device_ops *ops = dev->netdev_ops; 4056 4057 if (ops->ndo_select_queue) 4058 queue_index = ops->ndo_select_queue(dev, skb, sb_dev); 4059 else 4060 queue_index = netdev_pick_tx(dev, skb, sb_dev); 4061 4062 queue_index = netdev_cap_txqueue(dev, queue_index); 4063 } 4064 4065 skb_set_queue_mapping(skb, queue_index); 4066 return netdev_get_tx_queue(dev, queue_index); 4067 } 4068 4069 /** 4070 * __dev_queue_xmit - transmit a buffer 4071 * @skb: buffer to transmit 4072 * @sb_dev: suboordinate device used for L2 forwarding offload 4073 * 4074 * Queue a buffer for transmission to a network device. The caller must 4075 * have set the device and priority and built the buffer before calling 4076 * this function. The function can be called from an interrupt. 4077 * 4078 * A negative errno code is returned on a failure. A success does not 4079 * guarantee the frame will be transmitted as it may be dropped due 4080 * to congestion or traffic shaping. 4081 * 4082 * ----------------------------------------------------------------------------------- 4083 * I notice this method can also return errors from the queue disciplines, 4084 * including NET_XMIT_DROP, which is a positive value. So, errors can also 4085 * be positive. 4086 * 4087 * Regardless of the return value, the skb is consumed, so it is currently 4088 * difficult to retry a send to this method. (You can bump the ref count 4089 * before sending to hold a reference for retry if you are careful.) 4090 * 4091 * When calling this method, interrupts MUST be enabled. This is because 4092 * the BH enable code must have IRQs enabled so that it will not deadlock. 4093 * --BLG 4094 */ 4095 static int __dev_queue_xmit(struct sk_buff *skb, struct net_device *sb_dev) 4096 { 4097 struct net_device *dev = skb->dev; 4098 struct netdev_queue *txq; 4099 struct Qdisc *q; 4100 int rc = -ENOMEM; 4101 bool again = false; 4102 4103 skb_reset_mac_header(skb); 4104 4105 if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_SCHED_TSTAMP)) 4106 __skb_tstamp_tx(skb, NULL, NULL, skb->sk, SCM_TSTAMP_SCHED); 4107 4108 /* Disable soft irqs for various locks below. Also 4109 * stops preemption for RCU. 4110 */ 4111 rcu_read_lock_bh(); 4112 4113 skb_update_prio(skb); 4114 4115 qdisc_pkt_len_init(skb); 4116 #ifdef CONFIG_NET_CLS_ACT 4117 skb->tc_at_ingress = 0; 4118 #endif 4119 #ifdef CONFIG_NET_EGRESS 4120 if (static_branch_unlikely(&egress_needed_key)) { 4121 if (nf_hook_egress_active()) { 4122 skb = nf_hook_egress(skb, &rc, dev); 4123 if (!skb) 4124 goto out; 4125 } 4126 nf_skip_egress(skb, true); 4127 skb = sch_handle_egress(skb, &rc, dev); 4128 if (!skb) 4129 goto out; 4130 nf_skip_egress(skb, false); 4131 } 4132 #endif 4133 /* If device/qdisc don't need skb->dst, release it right now while 4134 * its hot in this cpu cache. 4135 */ 4136 if (dev->priv_flags & IFF_XMIT_DST_RELEASE) 4137 skb_dst_drop(skb); 4138 else 4139 skb_dst_force(skb); 4140 4141 txq = netdev_core_pick_tx(dev, skb, sb_dev); 4142 q = rcu_dereference_bh(txq->qdisc); 4143 4144 trace_net_dev_queue(skb); 4145 if (q->enqueue) { 4146 rc = __dev_xmit_skb(skb, q, dev, txq); 4147 goto out; 4148 } 4149 4150 /* The device has no queue. Common case for software devices: 4151 * loopback, all the sorts of tunnels... 4152 4153 * Really, it is unlikely that netif_tx_lock protection is necessary 4154 * here. (f.e. loopback and IP tunnels are clean ignoring statistics 4155 * counters.) 4156 * However, it is possible, that they rely on protection 4157 * made by us here. 4158 4159 * Check this and shot the lock. It is not prone from deadlocks. 4160 *Either shot noqueue qdisc, it is even simpler 8) 4161 */ 4162 if (dev->flags & IFF_UP) { 4163 int cpu = smp_processor_id(); /* ok because BHs are off */ 4164 4165 /* Other cpus might concurrently change txq->xmit_lock_owner 4166 * to -1 or to their cpu id, but not to our id. 4167 */ 4168 if (READ_ONCE(txq->xmit_lock_owner) != cpu) { 4169 if (dev_xmit_recursion()) 4170 goto recursion_alert; 4171 4172 skb = validate_xmit_skb(skb, dev, &again); 4173 if (!skb) 4174 goto out; 4175 4176 PRANDOM_ADD_NOISE(skb, dev, txq, jiffies); 4177 HARD_TX_LOCK(dev, txq, cpu); 4178 4179 if (!netif_xmit_stopped(txq)) { 4180 dev_xmit_recursion_inc(); 4181 skb = dev_hard_start_xmit(skb, dev, txq, &rc); 4182 dev_xmit_recursion_dec(); 4183 if (dev_xmit_complete(rc)) { 4184 HARD_TX_UNLOCK(dev, txq); 4185 goto out; 4186 } 4187 } 4188 HARD_TX_UNLOCK(dev, txq); 4189 net_crit_ratelimited("Virtual device %s asks to queue packet!\n", 4190 dev->name); 4191 } else { 4192 /* Recursion is detected! It is possible, 4193 * unfortunately 4194 */ 4195 recursion_alert: 4196 net_crit_ratelimited("Dead loop on virtual device %s, fix it urgently!\n", 4197 dev->name); 4198 } 4199 } 4200 4201 rc = -ENETDOWN; 4202 rcu_read_unlock_bh(); 4203 4204 dev_core_stats_tx_dropped_inc(dev); 4205 kfree_skb_list(skb); 4206 return rc; 4207 out: 4208 rcu_read_unlock_bh(); 4209 return rc; 4210 } 4211 4212 int dev_queue_xmit(struct sk_buff *skb) 4213 { 4214 return __dev_queue_xmit(skb, NULL); 4215 } 4216 EXPORT_SYMBOL(dev_queue_xmit); 4217 4218 int dev_queue_xmit_accel(struct sk_buff *skb, struct net_device *sb_dev) 4219 { 4220 return __dev_queue_xmit(skb, sb_dev); 4221 } 4222 EXPORT_SYMBOL(dev_queue_xmit_accel); 4223 4224 int __dev_direct_xmit(struct sk_buff *skb, u16 queue_id) 4225 { 4226 struct net_device *dev = skb->dev; 4227 struct sk_buff *orig_skb = skb; 4228 struct netdev_queue *txq; 4229 int ret = NETDEV_TX_BUSY; 4230 bool again = false; 4231 4232 if (unlikely(!netif_running(dev) || 4233 !netif_carrier_ok(dev))) 4234 goto drop; 4235 4236 skb = validate_xmit_skb_list(skb, dev, &again); 4237 if (skb != orig_skb) 4238 goto drop; 4239 4240 skb_set_queue_mapping(skb, queue_id); 4241 txq = skb_get_tx_queue(dev, skb); 4242 PRANDOM_ADD_NOISE(skb, dev, txq, jiffies); 4243 4244 local_bh_disable(); 4245 4246 dev_xmit_recursion_inc(); 4247 HARD_TX_LOCK(dev, txq, smp_processor_id()); 4248 if (!netif_xmit_frozen_or_drv_stopped(txq)) 4249 ret = netdev_start_xmit(skb, dev, txq, false); 4250 HARD_TX_UNLOCK(dev, txq); 4251 dev_xmit_recursion_dec(); 4252 4253 local_bh_enable(); 4254 return ret; 4255 drop: 4256 dev_core_stats_tx_dropped_inc(dev); 4257 kfree_skb_list(skb); 4258 return NET_XMIT_DROP; 4259 } 4260 EXPORT_SYMBOL(__dev_direct_xmit); 4261 4262 /************************************************************************* 4263 * Receiver routines 4264 *************************************************************************/ 4265 4266 int netdev_max_backlog __read_mostly = 1000; 4267 EXPORT_SYMBOL(netdev_max_backlog); 4268 4269 int netdev_tstamp_prequeue __read_mostly = 1; 4270 int netdev_budget __read_mostly = 300; 4271 /* Must be at least 2 jiffes to guarantee 1 jiffy timeout */ 4272 unsigned int __read_mostly netdev_budget_usecs = 2 * USEC_PER_SEC / HZ; 4273 int weight_p __read_mostly = 64; /* old backlog weight */ 4274 int dev_weight_rx_bias __read_mostly = 1; /* bias for backlog weight */ 4275 int dev_weight_tx_bias __read_mostly = 1; /* bias for output_queue quota */ 4276 int dev_rx_weight __read_mostly = 64; 4277 int dev_tx_weight __read_mostly = 64; 4278 4279 /* Called with irq disabled */ 4280 static inline void ____napi_schedule(struct softnet_data *sd, 4281 struct napi_struct *napi) 4282 { 4283 struct task_struct *thread; 4284 4285 lockdep_assert_irqs_disabled(); 4286 4287 if (test_bit(NAPI_STATE_THREADED, &napi->state)) { 4288 /* Paired with smp_mb__before_atomic() in 4289 * napi_enable()/dev_set_threaded(). 4290 * Use READ_ONCE() to guarantee a complete 4291 * read on napi->thread. Only call 4292 * wake_up_process() when it's not NULL. 4293 */ 4294 thread = READ_ONCE(napi->thread); 4295 if (thread) { 4296 /* Avoid doing set_bit() if the thread is in 4297 * INTERRUPTIBLE state, cause napi_thread_wait() 4298 * makes sure to proceed with napi polling 4299 * if the thread is explicitly woken from here. 4300 */ 4301 if (READ_ONCE(thread->__state) != TASK_INTERRUPTIBLE) 4302 set_bit(NAPI_STATE_SCHED_THREADED, &napi->state); 4303 wake_up_process(thread); 4304 return; 4305 } 4306 } 4307 4308 list_add_tail(&napi->poll_list, &sd->poll_list); 4309 __raise_softirq_irqoff(NET_RX_SOFTIRQ); 4310 } 4311 4312 #ifdef CONFIG_RPS 4313 4314 /* One global table that all flow-based protocols share. */ 4315 struct rps_sock_flow_table __rcu *rps_sock_flow_table __read_mostly; 4316 EXPORT_SYMBOL(rps_sock_flow_table); 4317 u32 rps_cpu_mask __read_mostly; 4318 EXPORT_SYMBOL(rps_cpu_mask); 4319 4320 struct static_key_false rps_needed __read_mostly; 4321 EXPORT_SYMBOL(rps_needed); 4322 struct static_key_false rfs_needed __read_mostly; 4323 EXPORT_SYMBOL(rfs_needed); 4324 4325 static struct rps_dev_flow * 4326 set_rps_cpu(struct net_device *dev, struct sk_buff *skb, 4327 struct rps_dev_flow *rflow, u16 next_cpu) 4328 { 4329 if (next_cpu < nr_cpu_ids) { 4330 #ifdef CONFIG_RFS_ACCEL 4331 struct netdev_rx_queue *rxqueue; 4332 struct rps_dev_flow_table *flow_table; 4333 struct rps_dev_flow *old_rflow; 4334 u32 flow_id; 4335 u16 rxq_index; 4336 int rc; 4337 4338 /* Should we steer this flow to a different hardware queue? */ 4339 if (!skb_rx_queue_recorded(skb) || !dev->rx_cpu_rmap || 4340 !(dev->features & NETIF_F_NTUPLE)) 4341 goto out; 4342 rxq_index = cpu_rmap_lookup_index(dev->rx_cpu_rmap, next_cpu); 4343 if (rxq_index == skb_get_rx_queue(skb)) 4344 goto out; 4345 4346 rxqueue = dev->_rx + rxq_index; 4347 flow_table = rcu_dereference(rxqueue->rps_flow_table); 4348 if (!flow_table) 4349 goto out; 4350 flow_id = skb_get_hash(skb) & flow_table->mask; 4351 rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb, 4352 rxq_index, flow_id); 4353 if (rc < 0) 4354 goto out; 4355 old_rflow = rflow; 4356 rflow = &flow_table->flows[flow_id]; 4357 rflow->filter = rc; 4358 if (old_rflow->filter == rflow->filter) 4359 old_rflow->filter = RPS_NO_FILTER; 4360 out: 4361 #endif 4362 rflow->last_qtail = 4363 per_cpu(softnet_data, next_cpu).input_queue_head; 4364 } 4365 4366 rflow->cpu = next_cpu; 4367 return rflow; 4368 } 4369 4370 /* 4371 * get_rps_cpu is called from netif_receive_skb and returns the target 4372 * CPU from the RPS map of the receiving queue for a given skb. 4373 * rcu_read_lock must be held on entry. 4374 */ 4375 static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb, 4376 struct rps_dev_flow **rflowp) 4377 { 4378 const struct rps_sock_flow_table *sock_flow_table; 4379 struct netdev_rx_queue *rxqueue = dev->_rx; 4380 struct rps_dev_flow_table *flow_table; 4381 struct rps_map *map; 4382 int cpu = -1; 4383 u32 tcpu; 4384 u32 hash; 4385 4386 if (skb_rx_queue_recorded(skb)) { 4387 u16 index = skb_get_rx_queue(skb); 4388 4389 if (unlikely(index >= dev->real_num_rx_queues)) { 4390 WARN_ONCE(dev->real_num_rx_queues > 1, 4391 "%s received packet on queue %u, but number " 4392 "of RX queues is %u\n", 4393 dev->name, index, dev->real_num_rx_queues); 4394 goto done; 4395 } 4396 rxqueue += index; 4397 } 4398 4399 /* Avoid computing hash if RFS/RPS is not active for this rxqueue */ 4400 4401 flow_table = rcu_dereference(rxqueue->rps_flow_table); 4402 map = rcu_dereference(rxqueue->rps_map); 4403 if (!flow_table && !map) 4404 goto done; 4405 4406 skb_reset_network_header(skb); 4407 hash = skb_get_hash(skb); 4408 if (!hash) 4409 goto done; 4410 4411 sock_flow_table = rcu_dereference(rps_sock_flow_table); 4412 if (flow_table && sock_flow_table) { 4413 struct rps_dev_flow *rflow; 4414 u32 next_cpu; 4415 u32 ident; 4416 4417 /* First check into global flow table if there is a match */ 4418 ident = sock_flow_table->ents[hash & sock_flow_table->mask]; 4419 if ((ident ^ hash) & ~rps_cpu_mask) 4420 goto try_rps; 4421 4422 next_cpu = ident & rps_cpu_mask; 4423 4424 /* OK, now we know there is a match, 4425 * we can look at the local (per receive queue) flow table 4426 */ 4427 rflow = &flow_table->flows[hash & flow_table->mask]; 4428 tcpu = rflow->cpu; 4429 4430 /* 4431 * If the desired CPU (where last recvmsg was done) is 4432 * different from current CPU (one in the rx-queue flow 4433 * table entry), switch if one of the following holds: 4434 * - Current CPU is unset (>= nr_cpu_ids). 4435 * - Current CPU is offline. 4436 * - The current CPU's queue tail has advanced beyond the 4437 * last packet that was enqueued using this table entry. 4438 * This guarantees that all previous packets for the flow 4439 * have been dequeued, thus preserving in order delivery. 4440 */ 4441 if (unlikely(tcpu != next_cpu) && 4442 (tcpu >= nr_cpu_ids || !cpu_online(tcpu) || 4443 ((int)(per_cpu(softnet_data, tcpu).input_queue_head - 4444 rflow->last_qtail)) >= 0)) { 4445 tcpu = next_cpu; 4446 rflow = set_rps_cpu(dev, skb, rflow, next_cpu); 4447 } 4448 4449 if (tcpu < nr_cpu_ids && cpu_online(tcpu)) { 4450 *rflowp = rflow; 4451 cpu = tcpu; 4452 goto done; 4453 } 4454 } 4455 4456 try_rps: 4457 4458 if (map) { 4459 tcpu = map->cpus[reciprocal_scale(hash, map->len)]; 4460 if (cpu_online(tcpu)) { 4461 cpu = tcpu; 4462 goto done; 4463 } 4464 } 4465 4466 done: 4467 return cpu; 4468 } 4469 4470 #ifdef CONFIG_RFS_ACCEL 4471 4472 /** 4473 * rps_may_expire_flow - check whether an RFS hardware filter may be removed 4474 * @dev: Device on which the filter was set 4475 * @rxq_index: RX queue index 4476 * @flow_id: Flow ID passed to ndo_rx_flow_steer() 4477 * @filter_id: Filter ID returned by ndo_rx_flow_steer() 4478 * 4479 * Drivers that implement ndo_rx_flow_steer() should periodically call 4480 * this function for each installed filter and remove the filters for 4481 * which it returns %true. 4482 */ 4483 bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index, 4484 u32 flow_id, u16 filter_id) 4485 { 4486 struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index; 4487 struct rps_dev_flow_table *flow_table; 4488 struct rps_dev_flow *rflow; 4489 bool expire = true; 4490 unsigned int cpu; 4491 4492 rcu_read_lock(); 4493 flow_table = rcu_dereference(rxqueue->rps_flow_table); 4494 if (flow_table && flow_id <= flow_table->mask) { 4495 rflow = &flow_table->flows[flow_id]; 4496 cpu = READ_ONCE(rflow->cpu); 4497 if (rflow->filter == filter_id && cpu < nr_cpu_ids && 4498 ((int)(per_cpu(softnet_data, cpu).input_queue_head - 4499 rflow->last_qtail) < 4500 (int)(10 * flow_table->mask))) 4501 expire = false; 4502 } 4503 rcu_read_unlock(); 4504 return expire; 4505 } 4506 EXPORT_SYMBOL(rps_may_expire_flow); 4507 4508 #endif /* CONFIG_RFS_ACCEL */ 4509 4510 /* Called from hardirq (IPI) context */ 4511 static void rps_trigger_softirq(void *data) 4512 { 4513 struct softnet_data *sd = data; 4514 4515 ____napi_schedule(sd, &sd->backlog); 4516 sd->received_rps++; 4517 } 4518 4519 #endif /* CONFIG_RPS */ 4520 4521 /* 4522 * Check if this softnet_data structure is another cpu one 4523 * If yes, queue it to our IPI list and return 1 4524 * If no, return 0 4525 */ 4526 static int napi_schedule_rps(struct softnet_data *sd) 4527 { 4528 struct softnet_data *mysd = this_cpu_ptr(&softnet_data); 4529 4530 #ifdef CONFIG_RPS 4531 if (sd != mysd) { 4532 sd->rps_ipi_next = mysd->rps_ipi_list; 4533 mysd->rps_ipi_list = sd; 4534 4535 __raise_softirq_irqoff(NET_RX_SOFTIRQ); 4536 return 1; 4537 } 4538 #endif /* CONFIG_RPS */ 4539 __napi_schedule_irqoff(&mysd->backlog); 4540 return 0; 4541 } 4542 4543 #ifdef CONFIG_NET_FLOW_LIMIT 4544 int netdev_flow_limit_table_len __read_mostly = (1 << 12); 4545 #endif 4546 4547 static bool skb_flow_limit(struct sk_buff *skb, unsigned int qlen) 4548 { 4549 #ifdef CONFIG_NET_FLOW_LIMIT 4550 struct sd_flow_limit *fl; 4551 struct softnet_data *sd; 4552 unsigned int old_flow, new_flow; 4553 4554 if (qlen < (netdev_max_backlog >> 1)) 4555 return false; 4556 4557 sd = this_cpu_ptr(&softnet_data); 4558 4559 rcu_read_lock(); 4560 fl = rcu_dereference(sd->flow_limit); 4561 if (fl) { 4562 new_flow = skb_get_hash(skb) & (fl->num_buckets - 1); 4563 old_flow = fl->history[fl->history_head]; 4564 fl->history[fl->history_head] = new_flow; 4565 4566 fl->history_head++; 4567 fl->history_head &= FLOW_LIMIT_HISTORY - 1; 4568 4569 if (likely(fl->buckets[old_flow])) 4570 fl->buckets[old_flow]--; 4571 4572 if (++fl->buckets[new_flow] > (FLOW_LIMIT_HISTORY >> 1)) { 4573 fl->count++; 4574 rcu_read_unlock(); 4575 return true; 4576 } 4577 } 4578 rcu_read_unlock(); 4579 #endif 4580 return false; 4581 } 4582 4583 /* 4584 * enqueue_to_backlog is called to queue an skb to a per CPU backlog 4585 * queue (may be a remote CPU queue). 4586 */ 4587 static int enqueue_to_backlog(struct sk_buff *skb, int cpu, 4588 unsigned int *qtail) 4589 { 4590 enum skb_drop_reason reason; 4591 struct softnet_data *sd; 4592 unsigned long flags; 4593 unsigned int qlen; 4594 4595 reason = SKB_DROP_REASON_NOT_SPECIFIED; 4596 sd = &per_cpu(softnet_data, cpu); 4597 4598 rps_lock_irqsave(sd, &flags); 4599 if (!netif_running(skb->dev)) 4600 goto drop; 4601 qlen = skb_queue_len(&sd->input_pkt_queue); 4602 if (qlen <= netdev_max_backlog && !skb_flow_limit(skb, qlen)) { 4603 if (qlen) { 4604 enqueue: 4605 __skb_queue_tail(&sd->input_pkt_queue, skb); 4606 input_queue_tail_incr_save(sd, qtail); 4607 rps_unlock_irq_restore(sd, &flags); 4608 return NET_RX_SUCCESS; 4609 } 4610 4611 /* Schedule NAPI for backlog device 4612 * We can use non atomic operation since we own the queue lock 4613 */ 4614 if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state)) 4615 napi_schedule_rps(sd); 4616 goto enqueue; 4617 } 4618 reason = SKB_DROP_REASON_CPU_BACKLOG; 4619 4620 drop: 4621 sd->dropped++; 4622 rps_unlock_irq_restore(sd, &flags); 4623 4624 dev_core_stats_rx_dropped_inc(skb->dev); 4625 kfree_skb_reason(skb, reason); 4626 return NET_RX_DROP; 4627 } 4628 4629 static struct netdev_rx_queue *netif_get_rxqueue(struct sk_buff *skb) 4630 { 4631 struct net_device *dev = skb->dev; 4632 struct netdev_rx_queue *rxqueue; 4633 4634 rxqueue = dev->_rx; 4635 4636 if (skb_rx_queue_recorded(skb)) { 4637 u16 index = skb_get_rx_queue(skb); 4638 4639 if (unlikely(index >= dev->real_num_rx_queues)) { 4640 WARN_ONCE(dev->real_num_rx_queues > 1, 4641 "%s received packet on queue %u, but number " 4642 "of RX queues is %u\n", 4643 dev->name, index, dev->real_num_rx_queues); 4644 4645 return rxqueue; /* Return first rxqueue */ 4646 } 4647 rxqueue += index; 4648 } 4649 return rxqueue; 4650 } 4651 4652 u32 bpf_prog_run_generic_xdp(struct sk_buff *skb, struct xdp_buff *xdp, 4653 struct bpf_prog *xdp_prog) 4654 { 4655 void *orig_data, *orig_data_end, *hard_start; 4656 struct netdev_rx_queue *rxqueue; 4657 bool orig_bcast, orig_host; 4658 u32 mac_len, frame_sz; 4659 __be16 orig_eth_type; 4660 struct ethhdr *eth; 4661 u32 metalen, act; 4662 int off; 4663 4664 /* The XDP program wants to see the packet starting at the MAC 4665 * header. 4666 */ 4667 mac_len = skb->data - skb_mac_header(skb); 4668 hard_start = skb->data - skb_headroom(skb); 4669 4670 /* SKB "head" area always have tailroom for skb_shared_info */ 4671 frame_sz = (void *)skb_end_pointer(skb) - hard_start; 4672 frame_sz += SKB_DATA_ALIGN(sizeof(struct skb_shared_info)); 4673 4674 rxqueue = netif_get_rxqueue(skb); 4675 xdp_init_buff(xdp, frame_sz, &rxqueue->xdp_rxq); 4676 xdp_prepare_buff(xdp, hard_start, skb_headroom(skb) - mac_len, 4677 skb_headlen(skb) + mac_len, true); 4678 4679 orig_data_end = xdp->data_end; 4680 orig_data = xdp->data; 4681 eth = (struct ethhdr *)xdp->data; 4682 orig_host = ether_addr_equal_64bits(eth->h_dest, skb->dev->dev_addr); 4683 orig_bcast = is_multicast_ether_addr_64bits(eth->h_dest); 4684 orig_eth_type = eth->h_proto; 4685 4686 act = bpf_prog_run_xdp(xdp_prog, xdp); 4687 4688 /* check if bpf_xdp_adjust_head was used */ 4689 off = xdp->data - orig_data; 4690 if (off) { 4691 if (off > 0) 4692 __skb_pull(skb, off); 4693 else if (off < 0) 4694 __skb_push(skb, -off); 4695 4696 skb->mac_header += off; 4697 skb_reset_network_header(skb); 4698 } 4699 4700 /* check if bpf_xdp_adjust_tail was used */ 4701 off = xdp->data_end - orig_data_end; 4702 if (off != 0) { 4703 skb_set_tail_pointer(skb, xdp->data_end - xdp->data); 4704 skb->len += off; /* positive on grow, negative on shrink */ 4705 } 4706 4707 /* check if XDP changed eth hdr such SKB needs update */ 4708 eth = (struct ethhdr *)xdp->data; 4709 if ((orig_eth_type != eth->h_proto) || 4710 (orig_host != ether_addr_equal_64bits(eth->h_dest, 4711 skb->dev->dev_addr)) || 4712 (orig_bcast != is_multicast_ether_addr_64bits(eth->h_dest))) { 4713 __skb_push(skb, ETH_HLEN); 4714 skb->pkt_type = PACKET_HOST; 4715 skb->protocol = eth_type_trans(skb, skb->dev); 4716 } 4717 4718 /* Redirect/Tx gives L2 packet, code that will reuse skb must __skb_pull 4719 * before calling us again on redirect path. We do not call do_redirect 4720 * as we leave that up to the caller. 4721 * 4722 * Caller is responsible for managing lifetime of skb (i.e. calling 4723 * kfree_skb in response to actions it cannot handle/XDP_DROP). 4724 */ 4725 switch (act) { 4726 case XDP_REDIRECT: 4727 case XDP_TX: 4728 __skb_push(skb, mac_len); 4729 break; 4730 case XDP_PASS: 4731 metalen = xdp->data - xdp->data_meta; 4732 if (metalen) 4733 skb_metadata_set(skb, metalen); 4734 break; 4735 } 4736 4737 return act; 4738 } 4739 4740 static u32 netif_receive_generic_xdp(struct sk_buff *skb, 4741 struct xdp_buff *xdp, 4742 struct bpf_prog *xdp_prog) 4743 { 4744 u32 act = XDP_DROP; 4745 4746 /* Reinjected packets coming from act_mirred or similar should 4747 * not get XDP generic processing. 4748 */ 4749 if (skb_is_redirected(skb)) 4750 return XDP_PASS; 4751 4752 /* XDP packets must be linear and must have sufficient headroom 4753 * of XDP_PACKET_HEADROOM bytes. This is the guarantee that also 4754 * native XDP provides, thus we need to do it here as well. 4755 */ 4756 if (skb_cloned(skb) || skb_is_nonlinear(skb) || 4757 skb_headroom(skb) < XDP_PACKET_HEADROOM) { 4758 int hroom = XDP_PACKET_HEADROOM - skb_headroom(skb); 4759 int troom = skb->tail + skb->data_len - skb->end; 4760 4761 /* In case we have to go down the path and also linearize, 4762 * then lets do the pskb_expand_head() work just once here. 4763 */ 4764 if (pskb_expand_head(skb, 4765 hroom > 0 ? ALIGN(hroom, NET_SKB_PAD) : 0, 4766 troom > 0 ? troom + 128 : 0, GFP_ATOMIC)) 4767 goto do_drop; 4768 if (skb_linearize(skb)) 4769 goto do_drop; 4770 } 4771 4772 act = bpf_prog_run_generic_xdp(skb, xdp, xdp_prog); 4773 switch (act) { 4774 case XDP_REDIRECT: 4775 case XDP_TX: 4776 case XDP_PASS: 4777 break; 4778 default: 4779 bpf_warn_invalid_xdp_action(skb->dev, xdp_prog, act); 4780 fallthrough; 4781 case XDP_ABORTED: 4782 trace_xdp_exception(skb->dev, xdp_prog, act); 4783 fallthrough; 4784 case XDP_DROP: 4785 do_drop: 4786 kfree_skb(skb); 4787 break; 4788 } 4789 4790 return act; 4791 } 4792 4793 /* When doing generic XDP we have to bypass the qdisc layer and the 4794 * network taps in order to match in-driver-XDP behavior. 4795 */ 4796 void generic_xdp_tx(struct sk_buff *skb, struct bpf_prog *xdp_prog) 4797 { 4798 struct net_device *dev = skb->dev; 4799 struct netdev_queue *txq; 4800 bool free_skb = true; 4801 int cpu, rc; 4802 4803 txq = netdev_core_pick_tx(dev, skb, NULL); 4804 cpu = smp_processor_id(); 4805 HARD_TX_LOCK(dev, txq, cpu); 4806 if (!netif_xmit_stopped(txq)) { 4807 rc = netdev_start_xmit(skb, dev, txq, 0); 4808 if (dev_xmit_complete(rc)) 4809 free_skb = false; 4810 } 4811 HARD_TX_UNLOCK(dev, txq); 4812 if (free_skb) { 4813 trace_xdp_exception(dev, xdp_prog, XDP_TX); 4814 kfree_skb(skb); 4815 } 4816 } 4817 4818 static DEFINE_STATIC_KEY_FALSE(generic_xdp_needed_key); 4819 4820 int do_xdp_generic(struct bpf_prog *xdp_prog, struct sk_buff *skb) 4821 { 4822 if (xdp_prog) { 4823 struct xdp_buff xdp; 4824 u32 act; 4825 int err; 4826 4827 act = netif_receive_generic_xdp(skb, &xdp, xdp_prog); 4828 if (act != XDP_PASS) { 4829 switch (act) { 4830 case XDP_REDIRECT: 4831 err = xdp_do_generic_redirect(skb->dev, skb, 4832 &xdp, xdp_prog); 4833 if (err) 4834 goto out_redir; 4835 break; 4836 case XDP_TX: 4837 generic_xdp_tx(skb, xdp_prog); 4838 break; 4839 } 4840 return XDP_DROP; 4841 } 4842 } 4843 return XDP_PASS; 4844 out_redir: 4845 kfree_skb_reason(skb, SKB_DROP_REASON_XDP); 4846 return XDP_DROP; 4847 } 4848 EXPORT_SYMBOL_GPL(do_xdp_generic); 4849 4850 static int netif_rx_internal(struct sk_buff *skb) 4851 { 4852 int ret; 4853 4854 net_timestamp_check(netdev_tstamp_prequeue, skb); 4855 4856 trace_netif_rx(skb); 4857 4858 #ifdef CONFIG_RPS 4859 if (static_branch_unlikely(&rps_needed)) { 4860 struct rps_dev_flow voidflow, *rflow = &voidflow; 4861 int cpu; 4862 4863 rcu_read_lock(); 4864 4865 cpu = get_rps_cpu(skb->dev, skb, &rflow); 4866 if (cpu < 0) 4867 cpu = smp_processor_id(); 4868 4869 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail); 4870 4871 rcu_read_unlock(); 4872 } else 4873 #endif 4874 { 4875 unsigned int qtail; 4876 4877 ret = enqueue_to_backlog(skb, smp_processor_id(), &qtail); 4878 } 4879 return ret; 4880 } 4881 4882 /** 4883 * __netif_rx - Slightly optimized version of netif_rx 4884 * @skb: buffer to post 4885 * 4886 * This behaves as netif_rx except that it does not disable bottom halves. 4887 * As a result this function may only be invoked from the interrupt context 4888 * (either hard or soft interrupt). 4889 */ 4890 int __netif_rx(struct sk_buff *skb) 4891 { 4892 int ret; 4893 4894 lockdep_assert_once(hardirq_count() | softirq_count()); 4895 4896 trace_netif_rx_entry(skb); 4897 ret = netif_rx_internal(skb); 4898 trace_netif_rx_exit(ret); 4899 return ret; 4900 } 4901 EXPORT_SYMBOL(__netif_rx); 4902 4903 /** 4904 * netif_rx - post buffer to the network code 4905 * @skb: buffer to post 4906 * 4907 * This function receives a packet from a device driver and queues it for 4908 * the upper (protocol) levels to process via the backlog NAPI device. It 4909 * always succeeds. The buffer may be dropped during processing for 4910 * congestion control or by the protocol layers. 4911 * The network buffer is passed via the backlog NAPI device. Modern NIC 4912 * driver should use NAPI and GRO. 4913 * This function can used from interrupt and from process context. The 4914 * caller from process context must not disable interrupts before invoking 4915 * this function. 4916 * 4917 * return values: 4918 * NET_RX_SUCCESS (no congestion) 4919 * NET_RX_DROP (packet was dropped) 4920 * 4921 */ 4922 int netif_rx(struct sk_buff *skb) 4923 { 4924 bool need_bh_off = !(hardirq_count() | softirq_count()); 4925 int ret; 4926 4927 if (need_bh_off) 4928 local_bh_disable(); 4929 trace_netif_rx_entry(skb); 4930 ret = netif_rx_internal(skb); 4931 trace_netif_rx_exit(ret); 4932 if (need_bh_off) 4933 local_bh_enable(); 4934 return ret; 4935 } 4936 EXPORT_SYMBOL(netif_rx); 4937 4938 static __latent_entropy void net_tx_action(struct softirq_action *h) 4939 { 4940 struct softnet_data *sd = this_cpu_ptr(&softnet_data); 4941 4942 if (sd->completion_queue) { 4943 struct sk_buff *clist; 4944 4945 local_irq_disable(); 4946 clist = sd->completion_queue; 4947 sd->completion_queue = NULL; 4948 local_irq_enable(); 4949 4950 while (clist) { 4951 struct sk_buff *skb = clist; 4952 4953 clist = clist->next; 4954 4955 WARN_ON(refcount_read(&skb->users)); 4956 if (likely(get_kfree_skb_cb(skb)->reason == SKB_REASON_CONSUMED)) 4957 trace_consume_skb(skb); 4958 else 4959 trace_kfree_skb(skb, net_tx_action, 4960 SKB_DROP_REASON_NOT_SPECIFIED); 4961 4962 if (skb->fclone != SKB_FCLONE_UNAVAILABLE) 4963 __kfree_skb(skb); 4964 else 4965 __kfree_skb_defer(skb); 4966 } 4967 } 4968 4969 if (sd->output_queue) { 4970 struct Qdisc *head; 4971 4972 local_irq_disable(); 4973 head = sd->output_queue; 4974 sd->output_queue = NULL; 4975 sd->output_queue_tailp = &sd->output_queue; 4976 local_irq_enable(); 4977 4978 rcu_read_lock(); 4979 4980 while (head) { 4981 struct Qdisc *q = head; 4982 spinlock_t *root_lock = NULL; 4983 4984 head = head->next_sched; 4985 4986 /* We need to make sure head->next_sched is read 4987 * before clearing __QDISC_STATE_SCHED 4988 */ 4989 smp_mb__before_atomic(); 4990 4991 if (!(q->flags & TCQ_F_NOLOCK)) { 4992 root_lock = qdisc_lock(q); 4993 spin_lock(root_lock); 4994 } else if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, 4995 &q->state))) { 4996 /* There is a synchronize_net() between 4997 * STATE_DEACTIVATED flag being set and 4998 * qdisc_reset()/some_qdisc_is_busy() in 4999 * dev_deactivate(), so we can safely bail out 5000 * early here to avoid data race between 5001 * qdisc_deactivate() and some_qdisc_is_busy() 5002 * for lockless qdisc. 5003 */ 5004 clear_bit(__QDISC_STATE_SCHED, &q->state); 5005 continue; 5006 } 5007 5008 clear_bit(__QDISC_STATE_SCHED, &q->state); 5009 qdisc_run(q); 5010 if (root_lock) 5011 spin_unlock(root_lock); 5012 } 5013 5014 rcu_read_unlock(); 5015 } 5016 5017 xfrm_dev_backlog(sd); 5018 } 5019 5020 #if IS_ENABLED(CONFIG_BRIDGE) && IS_ENABLED(CONFIG_ATM_LANE) 5021 /* This hook is defined here for ATM LANE */ 5022 int (*br_fdb_test_addr_hook)(struct net_device *dev, 5023 unsigned char *addr) __read_mostly; 5024 EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook); 5025 #endif 5026 5027 static inline struct sk_buff * 5028 sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret, 5029 struct net_device *orig_dev, bool *another) 5030 { 5031 #ifdef CONFIG_NET_CLS_ACT 5032 struct mini_Qdisc *miniq = rcu_dereference_bh(skb->dev->miniq_ingress); 5033 struct tcf_result cl_res; 5034 5035 /* If there's at least one ingress present somewhere (so 5036 * we get here via enabled static key), remaining devices 5037 * that are not configured with an ingress qdisc will bail 5038 * out here. 5039 */ 5040 if (!miniq) 5041 return skb; 5042 5043 if (*pt_prev) { 5044 *ret = deliver_skb(skb, *pt_prev, orig_dev); 5045 *pt_prev = NULL; 5046 } 5047 5048 qdisc_skb_cb(skb)->pkt_len = skb->len; 5049 tc_skb_cb(skb)->mru = 0; 5050 tc_skb_cb(skb)->post_ct = false; 5051 skb->tc_at_ingress = 1; 5052 mini_qdisc_bstats_cpu_update(miniq, skb); 5053 5054 switch (tcf_classify(skb, miniq->block, miniq->filter_list, &cl_res, false)) { 5055 case TC_ACT_OK: 5056 case TC_ACT_RECLASSIFY: 5057 skb->tc_index = TC_H_MIN(cl_res.classid); 5058 break; 5059 case TC_ACT_SHOT: 5060 mini_qdisc_qstats_cpu_drop(miniq); 5061 kfree_skb_reason(skb, SKB_DROP_REASON_TC_INGRESS); 5062 return NULL; 5063 case TC_ACT_STOLEN: 5064 case TC_ACT_QUEUED: 5065 case TC_ACT_TRAP: 5066 consume_skb(skb); 5067 return NULL; 5068 case TC_ACT_REDIRECT: 5069 /* skb_mac_header check was done by cls/act_bpf, so 5070 * we can safely push the L2 header back before 5071 * redirecting to another netdev 5072 */ 5073 __skb_push(skb, skb->mac_len); 5074 if (skb_do_redirect(skb) == -EAGAIN) { 5075 __skb_pull(skb, skb->mac_len); 5076 *another = true; 5077 break; 5078 } 5079 return NULL; 5080 case TC_ACT_CONSUMED: 5081 return NULL; 5082 default: 5083 break; 5084 } 5085 #endif /* CONFIG_NET_CLS_ACT */ 5086 return skb; 5087 } 5088 5089 /** 5090 * netdev_is_rx_handler_busy - check if receive handler is registered 5091 * @dev: device to check 5092 * 5093 * Check if a receive handler is already registered for a given device. 5094 * Return true if there one. 5095 * 5096 * The caller must hold the rtnl_mutex. 5097 */ 5098 bool netdev_is_rx_handler_busy(struct net_device *dev) 5099 { 5100 ASSERT_RTNL(); 5101 return dev && rtnl_dereference(dev->rx_handler); 5102 } 5103 EXPORT_SYMBOL_GPL(netdev_is_rx_handler_busy); 5104 5105 /** 5106 * netdev_rx_handler_register - register receive handler 5107 * @dev: device to register a handler for 5108 * @rx_handler: receive handler to register 5109 * @rx_handler_data: data pointer that is used by rx handler 5110 * 5111 * Register a receive handler for a device. This handler will then be 5112 * called from __netif_receive_skb. A negative errno code is returned 5113 * on a failure. 5114 * 5115 * The caller must hold the rtnl_mutex. 5116 * 5117 * For a general description of rx_handler, see enum rx_handler_result. 5118 */ 5119 int netdev_rx_handler_register(struct net_device *dev, 5120 rx_handler_func_t *rx_handler, 5121 void *rx_handler_data) 5122 { 5123 if (netdev_is_rx_handler_busy(dev)) 5124 return -EBUSY; 5125 5126 if (dev->priv_flags & IFF_NO_RX_HANDLER) 5127 return -EINVAL; 5128 5129 /* Note: rx_handler_data must be set before rx_handler */ 5130 rcu_assign_pointer(dev->rx_handler_data, rx_handler_data); 5131 rcu_assign_pointer(dev->rx_handler, rx_handler); 5132 5133 return 0; 5134 } 5135 EXPORT_SYMBOL_GPL(netdev_rx_handler_register); 5136 5137 /** 5138 * netdev_rx_handler_unregister - unregister receive handler 5139 * @dev: device to unregister a handler from 5140 * 5141 * Unregister a receive handler from a device. 5142 * 5143 * The caller must hold the rtnl_mutex. 5144 */ 5145 void netdev_rx_handler_unregister(struct net_device *dev) 5146 { 5147 5148 ASSERT_RTNL(); 5149 RCU_INIT_POINTER(dev->rx_handler, NULL); 5150 /* a reader seeing a non NULL rx_handler in a rcu_read_lock() 5151 * section has a guarantee to see a non NULL rx_handler_data 5152 * as well. 5153 */ 5154 synchronize_net(); 5155 RCU_INIT_POINTER(dev->rx_handler_data, NULL); 5156 } 5157 EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister); 5158 5159 /* 5160 * Limit the use of PFMEMALLOC reserves to those protocols that implement 5161 * the special handling of PFMEMALLOC skbs. 5162 */ 5163 static bool skb_pfmemalloc_protocol(struct sk_buff *skb) 5164 { 5165 switch (skb->protocol) { 5166 case htons(ETH_P_ARP): 5167 case htons(ETH_P_IP): 5168 case htons(ETH_P_IPV6): 5169 case htons(ETH_P_8021Q): 5170 case htons(ETH_P_8021AD): 5171 return true; 5172 default: 5173 return false; 5174 } 5175 } 5176 5177 static inline int nf_ingress(struct sk_buff *skb, struct packet_type **pt_prev, 5178 int *ret, struct net_device *orig_dev) 5179 { 5180 if (nf_hook_ingress_active(skb)) { 5181 int ingress_retval; 5182 5183 if (*pt_prev) { 5184 *ret = deliver_skb(skb, *pt_prev, orig_dev); 5185 *pt_prev = NULL; 5186 } 5187 5188 rcu_read_lock(); 5189 ingress_retval = nf_hook_ingress(skb); 5190 rcu_read_unlock(); 5191 return ingress_retval; 5192 } 5193 return 0; 5194 } 5195 5196 static int __netif_receive_skb_core(struct sk_buff **pskb, bool pfmemalloc, 5197 struct packet_type **ppt_prev) 5198 { 5199 struct packet_type *ptype, *pt_prev; 5200 rx_handler_func_t *rx_handler; 5201 struct sk_buff *skb = *pskb; 5202 struct net_device *orig_dev; 5203 bool deliver_exact = false; 5204 int ret = NET_RX_DROP; 5205 __be16 type; 5206 5207 net_timestamp_check(!netdev_tstamp_prequeue, skb); 5208 5209 trace_netif_receive_skb(skb); 5210 5211 orig_dev = skb->dev; 5212 5213 skb_reset_network_header(skb); 5214 if (!skb_transport_header_was_set(skb)) 5215 skb_reset_transport_header(skb); 5216 skb_reset_mac_len(skb); 5217 5218 pt_prev = NULL; 5219 5220 another_round: 5221 skb->skb_iif = skb->dev->ifindex; 5222 5223 __this_cpu_inc(softnet_data.processed); 5224 5225 if (static_branch_unlikely(&generic_xdp_needed_key)) { 5226 int ret2; 5227 5228 migrate_disable(); 5229 ret2 = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog), skb); 5230 migrate_enable(); 5231 5232 if (ret2 != XDP_PASS) { 5233 ret = NET_RX_DROP; 5234 goto out; 5235 } 5236 } 5237 5238 if (eth_type_vlan(skb->protocol)) { 5239 skb = skb_vlan_untag(skb); 5240 if (unlikely(!skb)) 5241 goto out; 5242 } 5243 5244 if (skb_skip_tc_classify(skb)) 5245 goto skip_classify; 5246 5247 if (pfmemalloc) 5248 goto skip_taps; 5249 5250 list_for_each_entry_rcu(ptype, &ptype_all, list) { 5251 if (pt_prev) 5252 ret = deliver_skb(skb, pt_prev, orig_dev); 5253 pt_prev = ptype; 5254 } 5255 5256 list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) { 5257 if (pt_prev) 5258 ret = deliver_skb(skb, pt_prev, orig_dev); 5259 pt_prev = ptype; 5260 } 5261 5262 skip_taps: 5263 #ifdef CONFIG_NET_INGRESS 5264 if (static_branch_unlikely(&ingress_needed_key)) { 5265 bool another = false; 5266 5267 nf_skip_egress(skb, true); 5268 skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev, 5269 &another); 5270 if (another) 5271 goto another_round; 5272 if (!skb) 5273 goto out; 5274 5275 nf_skip_egress(skb, false); 5276 if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0) 5277 goto out; 5278 } 5279 #endif 5280 skb_reset_redirect(skb); 5281 skip_classify: 5282 if (pfmemalloc && !skb_pfmemalloc_protocol(skb)) 5283 goto drop; 5284 5285 if (skb_vlan_tag_present(skb)) { 5286 if (pt_prev) { 5287 ret = deliver_skb(skb, pt_prev, orig_dev); 5288 pt_prev = NULL; 5289 } 5290 if (vlan_do_receive(&skb)) 5291 goto another_round; 5292 else if (unlikely(!skb)) 5293 goto out; 5294 } 5295 5296 rx_handler = rcu_dereference(skb->dev->rx_handler); 5297 if (rx_handler) { 5298 if (pt_prev) { 5299 ret = deliver_skb(skb, pt_prev, orig_dev); 5300 pt_prev = NULL; 5301 } 5302 switch (rx_handler(&skb)) { 5303 case RX_HANDLER_CONSUMED: 5304 ret = NET_RX_SUCCESS; 5305 goto out; 5306 case RX_HANDLER_ANOTHER: 5307 goto another_round; 5308 case RX_HANDLER_EXACT: 5309 deliver_exact = true; 5310 break; 5311 case RX_HANDLER_PASS: 5312 break; 5313 default: 5314 BUG(); 5315 } 5316 } 5317 5318 if (unlikely(skb_vlan_tag_present(skb)) && !netdev_uses_dsa(skb->dev)) { 5319 check_vlan_id: 5320 if (skb_vlan_tag_get_id(skb)) { 5321 /* Vlan id is non 0 and vlan_do_receive() above couldn't 5322 * find vlan device. 5323 */ 5324 skb->pkt_type = PACKET_OTHERHOST; 5325 } else if (eth_type_vlan(skb->protocol)) { 5326 /* Outer header is 802.1P with vlan 0, inner header is 5327 * 802.1Q or 802.1AD and vlan_do_receive() above could 5328 * not find vlan dev for vlan id 0. 5329 */ 5330 __vlan_hwaccel_clear_tag(skb); 5331 skb = skb_vlan_untag(skb); 5332 if (unlikely(!skb)) 5333 goto out; 5334 if (vlan_do_receive(&skb)) 5335 /* After stripping off 802.1P header with vlan 0 5336 * vlan dev is found for inner header. 5337 */ 5338 goto another_round; 5339 else if (unlikely(!skb)) 5340 goto out; 5341 else 5342 /* We have stripped outer 802.1P vlan 0 header. 5343 * But could not find vlan dev. 5344 * check again for vlan id to set OTHERHOST. 5345 */ 5346 goto check_vlan_id; 5347 } 5348 /* Note: we might in the future use prio bits 5349 * and set skb->priority like in vlan_do_receive() 5350 * For the time being, just ignore Priority Code Point 5351 */ 5352 __vlan_hwaccel_clear_tag(skb); 5353 } 5354 5355 type = skb->protocol; 5356 5357 /* deliver only exact match when indicated */ 5358 if (likely(!deliver_exact)) { 5359 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type, 5360 &ptype_base[ntohs(type) & 5361 PTYPE_HASH_MASK]); 5362 } 5363 5364 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type, 5365 &orig_dev->ptype_specific); 5366 5367 if (unlikely(skb->dev != orig_dev)) { 5368 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type, 5369 &skb->dev->ptype_specific); 5370 } 5371 5372 if (pt_prev) { 5373 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC))) 5374 goto drop; 5375 *ppt_prev = pt_prev; 5376 } else { 5377 drop: 5378 if (!deliver_exact) { 5379 dev_core_stats_rx_dropped_inc(skb->dev); 5380 kfree_skb_reason(skb, SKB_DROP_REASON_PTYPE_ABSENT); 5381 } else { 5382 dev_core_stats_rx_nohandler_inc(skb->dev); 5383 kfree_skb(skb); 5384 } 5385 /* Jamal, now you will not able to escape explaining 5386 * me how you were going to use this. :-) 5387 */ 5388 ret = NET_RX_DROP; 5389 } 5390 5391 out: 5392 /* The invariant here is that if *ppt_prev is not NULL 5393 * then skb should also be non-NULL. 5394 * 5395 * Apparently *ppt_prev assignment above holds this invariant due to 5396 * skb dereferencing near it. 5397 */ 5398 *pskb = skb; 5399 return ret; 5400 } 5401 5402 static int __netif_receive_skb_one_core(struct sk_buff *skb, bool pfmemalloc) 5403 { 5404 struct net_device *orig_dev = skb->dev; 5405 struct packet_type *pt_prev = NULL; 5406 int ret; 5407 5408 ret = __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev); 5409 if (pt_prev) 5410 ret = INDIRECT_CALL_INET(pt_prev->func, ipv6_rcv, ip_rcv, skb, 5411 skb->dev, pt_prev, orig_dev); 5412 return ret; 5413 } 5414 5415 /** 5416 * netif_receive_skb_core - special purpose version of netif_receive_skb 5417 * @skb: buffer to process 5418 * 5419 * More direct receive version of netif_receive_skb(). It should 5420 * only be used by callers that have a need to skip RPS and Generic XDP. 5421 * Caller must also take care of handling if ``(page_is_)pfmemalloc``. 5422 * 5423 * This function may only be called from softirq context and interrupts 5424 * should be enabled. 5425 * 5426 * Return values (usually ignored): 5427 * NET_RX_SUCCESS: no congestion 5428 * NET_RX_DROP: packet was dropped 5429 */ 5430 int netif_receive_skb_core(struct sk_buff *skb) 5431 { 5432 int ret; 5433 5434 rcu_read_lock(); 5435 ret = __netif_receive_skb_one_core(skb, false); 5436 rcu_read_unlock(); 5437 5438 return ret; 5439 } 5440 EXPORT_SYMBOL(netif_receive_skb_core); 5441 5442 static inline void __netif_receive_skb_list_ptype(struct list_head *head, 5443 struct packet_type *pt_prev, 5444 struct net_device *orig_dev) 5445 { 5446 struct sk_buff *skb, *next; 5447 5448 if (!pt_prev) 5449 return; 5450 if (list_empty(head)) 5451 return; 5452 if (pt_prev->list_func != NULL) 5453 INDIRECT_CALL_INET(pt_prev->list_func, ipv6_list_rcv, 5454 ip_list_rcv, head, pt_prev, orig_dev); 5455 else 5456 list_for_each_entry_safe(skb, next, head, list) { 5457 skb_list_del_init(skb); 5458 pt_prev->func(skb, skb->dev, pt_prev, orig_dev); 5459 } 5460 } 5461 5462 static void __netif_receive_skb_list_core(struct list_head *head, bool pfmemalloc) 5463 { 5464 /* Fast-path assumptions: 5465 * - There is no RX handler. 5466 * - Only one packet_type matches. 5467 * If either of these fails, we will end up doing some per-packet 5468 * processing in-line, then handling the 'last ptype' for the whole 5469 * sublist. This can't cause out-of-order delivery to any single ptype, 5470 * because the 'last ptype' must be constant across the sublist, and all 5471 * other ptypes are handled per-packet. 5472 */ 5473 /* Current (common) ptype of sublist */ 5474 struct packet_type *pt_curr = NULL; 5475 /* Current (common) orig_dev of sublist */ 5476 struct net_device *od_curr = NULL; 5477 struct list_head sublist; 5478 struct sk_buff *skb, *next; 5479 5480 INIT_LIST_HEAD(&sublist); 5481 list_for_each_entry_safe(skb, next, head, list) { 5482 struct net_device *orig_dev = skb->dev; 5483 struct packet_type *pt_prev = NULL; 5484 5485 skb_list_del_init(skb); 5486 __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev); 5487 if (!pt_prev) 5488 continue; 5489 if (pt_curr != pt_prev || od_curr != orig_dev) { 5490 /* dispatch old sublist */ 5491 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr); 5492 /* start new sublist */ 5493 INIT_LIST_HEAD(&sublist); 5494 pt_curr = pt_prev; 5495 od_curr = orig_dev; 5496 } 5497 list_add_tail(&skb->list, &sublist); 5498 } 5499 5500 /* dispatch final sublist */ 5501 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr); 5502 } 5503 5504 static int __netif_receive_skb(struct sk_buff *skb) 5505 { 5506 int ret; 5507 5508 if (sk_memalloc_socks() && skb_pfmemalloc(skb)) { 5509 unsigned int noreclaim_flag; 5510 5511 /* 5512 * PFMEMALLOC skbs are special, they should 5513 * - be delivered to SOCK_MEMALLOC sockets only 5514 * - stay away from userspace 5515 * - have bounded memory usage 5516 * 5517 * Use PF_MEMALLOC as this saves us from propagating the allocation 5518 * context down to all allocation sites. 5519 */ 5520 noreclaim_flag = memalloc_noreclaim_save(); 5521 ret = __netif_receive_skb_one_core(skb, true); 5522 memalloc_noreclaim_restore(noreclaim_flag); 5523 } else 5524 ret = __netif_receive_skb_one_core(skb, false); 5525 5526 return ret; 5527 } 5528 5529 static void __netif_receive_skb_list(struct list_head *head) 5530 { 5531 unsigned long noreclaim_flag = 0; 5532 struct sk_buff *skb, *next; 5533 bool pfmemalloc = false; /* Is current sublist PF_MEMALLOC? */ 5534 5535 list_for_each_entry_safe(skb, next, head, list) { 5536 if ((sk_memalloc_socks() && skb_pfmemalloc(skb)) != pfmemalloc) { 5537 struct list_head sublist; 5538 5539 /* Handle the previous sublist */ 5540 list_cut_before(&sublist, head, &skb->list); 5541 if (!list_empty(&sublist)) 5542 __netif_receive_skb_list_core(&sublist, pfmemalloc); 5543 pfmemalloc = !pfmemalloc; 5544 /* See comments in __netif_receive_skb */ 5545 if (pfmemalloc) 5546 noreclaim_flag = memalloc_noreclaim_save(); 5547 else 5548 memalloc_noreclaim_restore(noreclaim_flag); 5549 } 5550 } 5551 /* Handle the remaining sublist */ 5552 if (!list_empty(head)) 5553 __netif_receive_skb_list_core(head, pfmemalloc); 5554 /* Restore pflags */ 5555 if (pfmemalloc) 5556 memalloc_noreclaim_restore(noreclaim_flag); 5557 } 5558 5559 static int generic_xdp_install(struct net_device *dev, struct netdev_bpf *xdp) 5560 { 5561 struct bpf_prog *old = rtnl_dereference(dev->xdp_prog); 5562 struct bpf_prog *new = xdp->prog; 5563 int ret = 0; 5564 5565 switch (xdp->command) { 5566 case XDP_SETUP_PROG: 5567 rcu_assign_pointer(dev->xdp_prog, new); 5568 if (old) 5569 bpf_prog_put(old); 5570 5571 if (old && !new) { 5572 static_branch_dec(&generic_xdp_needed_key); 5573 } else if (new && !old) { 5574 static_branch_inc(&generic_xdp_needed_key); 5575 dev_disable_lro(dev); 5576 dev_disable_gro_hw(dev); 5577 } 5578 break; 5579 5580 default: 5581 ret = -EINVAL; 5582 break; 5583 } 5584 5585 return ret; 5586 } 5587 5588 static int netif_receive_skb_internal(struct sk_buff *skb) 5589 { 5590 int ret; 5591 5592 net_timestamp_check(netdev_tstamp_prequeue, skb); 5593 5594 if (skb_defer_rx_timestamp(skb)) 5595 return NET_RX_SUCCESS; 5596 5597 rcu_read_lock(); 5598 #ifdef CONFIG_RPS 5599 if (static_branch_unlikely(&rps_needed)) { 5600 struct rps_dev_flow voidflow, *rflow = &voidflow; 5601 int cpu = get_rps_cpu(skb->dev, skb, &rflow); 5602 5603 if (cpu >= 0) { 5604 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail); 5605 rcu_read_unlock(); 5606 return ret; 5607 } 5608 } 5609 #endif 5610 ret = __netif_receive_skb(skb); 5611 rcu_read_unlock(); 5612 return ret; 5613 } 5614 5615 void netif_receive_skb_list_internal(struct list_head *head) 5616 { 5617 struct sk_buff *skb, *next; 5618 struct list_head sublist; 5619 5620 INIT_LIST_HEAD(&sublist); 5621 list_for_each_entry_safe(skb, next, head, list) { 5622 net_timestamp_check(netdev_tstamp_prequeue, skb); 5623 skb_list_del_init(skb); 5624 if (!skb_defer_rx_timestamp(skb)) 5625 list_add_tail(&skb->list, &sublist); 5626 } 5627 list_splice_init(&sublist, head); 5628 5629 rcu_read_lock(); 5630 #ifdef CONFIG_RPS 5631 if (static_branch_unlikely(&rps_needed)) { 5632 list_for_each_entry_safe(skb, next, head, list) { 5633 struct rps_dev_flow voidflow, *rflow = &voidflow; 5634 int cpu = get_rps_cpu(skb->dev, skb, &rflow); 5635 5636 if (cpu >= 0) { 5637 /* Will be handled, remove from list */ 5638 skb_list_del_init(skb); 5639 enqueue_to_backlog(skb, cpu, &rflow->last_qtail); 5640 } 5641 } 5642 } 5643 #endif 5644 __netif_receive_skb_list(head); 5645 rcu_read_unlock(); 5646 } 5647 5648 /** 5649 * netif_receive_skb - process receive buffer from network 5650 * @skb: buffer to process 5651 * 5652 * netif_receive_skb() is the main receive data processing function. 5653 * It always succeeds. The buffer may be dropped during processing 5654 * for congestion control or by the protocol layers. 5655 * 5656 * This function may only be called from softirq context and interrupts 5657 * should be enabled. 5658 * 5659 * Return values (usually ignored): 5660 * NET_RX_SUCCESS: no congestion 5661 * NET_RX_DROP: packet was dropped 5662 */ 5663 int netif_receive_skb(struct sk_buff *skb) 5664 { 5665 int ret; 5666 5667 trace_netif_receive_skb_entry(skb); 5668 5669 ret = netif_receive_skb_internal(skb); 5670 trace_netif_receive_skb_exit(ret); 5671 5672 return ret; 5673 } 5674 EXPORT_SYMBOL(netif_receive_skb); 5675 5676 /** 5677 * netif_receive_skb_list - process many receive buffers from network 5678 * @head: list of skbs to process. 5679 * 5680 * Since return value of netif_receive_skb() is normally ignored, and 5681 * wouldn't be meaningful for a list, this function returns void. 5682 * 5683 * This function may only be called from softirq context and interrupts 5684 * should be enabled. 5685 */ 5686 void netif_receive_skb_list(struct list_head *head) 5687 { 5688 struct sk_buff *skb; 5689 5690 if (list_empty(head)) 5691 return; 5692 if (trace_netif_receive_skb_list_entry_enabled()) { 5693 list_for_each_entry(skb, head, list) 5694 trace_netif_receive_skb_list_entry(skb); 5695 } 5696 netif_receive_skb_list_internal(head); 5697 trace_netif_receive_skb_list_exit(0); 5698 } 5699 EXPORT_SYMBOL(netif_receive_skb_list); 5700 5701 static DEFINE_PER_CPU(struct work_struct, flush_works); 5702 5703 /* Network device is going away, flush any packets still pending */ 5704 static void flush_backlog(struct work_struct *work) 5705 { 5706 struct sk_buff *skb, *tmp; 5707 struct softnet_data *sd; 5708 5709 local_bh_disable(); 5710 sd = this_cpu_ptr(&softnet_data); 5711 5712 rps_lock_irq_disable(sd); 5713 skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) { 5714 if (skb->dev->reg_state == NETREG_UNREGISTERING) { 5715 __skb_unlink(skb, &sd->input_pkt_queue); 5716 dev_kfree_skb_irq(skb); 5717 input_queue_head_incr(sd); 5718 } 5719 } 5720 rps_unlock_irq_enable(sd); 5721 5722 skb_queue_walk_safe(&sd->process_queue, skb, tmp) { 5723 if (skb->dev->reg_state == NETREG_UNREGISTERING) { 5724 __skb_unlink(skb, &sd->process_queue); 5725 kfree_skb(skb); 5726 input_queue_head_incr(sd); 5727 } 5728 } 5729 local_bh_enable(); 5730 } 5731 5732 static bool flush_required(int cpu) 5733 { 5734 #if IS_ENABLED(CONFIG_RPS) 5735 struct softnet_data *sd = &per_cpu(softnet_data, cpu); 5736 bool do_flush; 5737 5738 rps_lock_irq_disable(sd); 5739 5740 /* as insertion into process_queue happens with the rps lock held, 5741 * process_queue access may race only with dequeue 5742 */ 5743 do_flush = !skb_queue_empty(&sd->input_pkt_queue) || 5744 !skb_queue_empty_lockless(&sd->process_queue); 5745 rps_unlock_irq_enable(sd); 5746 5747 return do_flush; 5748 #endif 5749 /* without RPS we can't safely check input_pkt_queue: during a 5750 * concurrent remote skb_queue_splice() we can detect as empty both 5751 * input_pkt_queue and process_queue even if the latter could end-up 5752 * containing a lot of packets. 5753 */ 5754 return true; 5755 } 5756 5757 static void flush_all_backlogs(void) 5758 { 5759 static cpumask_t flush_cpus; 5760 unsigned int cpu; 5761 5762 /* since we are under rtnl lock protection we can use static data 5763 * for the cpumask and avoid allocating on stack the possibly 5764 * large mask 5765 */ 5766 ASSERT_RTNL(); 5767 5768 cpus_read_lock(); 5769 5770 cpumask_clear(&flush_cpus); 5771 for_each_online_cpu(cpu) { 5772 if (flush_required(cpu)) { 5773 queue_work_on(cpu, system_highpri_wq, 5774 per_cpu_ptr(&flush_works, cpu)); 5775 cpumask_set_cpu(cpu, &flush_cpus); 5776 } 5777 } 5778 5779 /* we can have in flight packet[s] on the cpus we are not flushing, 5780 * synchronize_net() in unregister_netdevice_many() will take care of 5781 * them 5782 */ 5783 for_each_cpu(cpu, &flush_cpus) 5784 flush_work(per_cpu_ptr(&flush_works, cpu)); 5785 5786 cpus_read_unlock(); 5787 } 5788 5789 static void net_rps_send_ipi(struct softnet_data *remsd) 5790 { 5791 #ifdef CONFIG_RPS 5792 while (remsd) { 5793 struct softnet_data *next = remsd->rps_ipi_next; 5794 5795 if (cpu_online(remsd->cpu)) 5796 smp_call_function_single_async(remsd->cpu, &remsd->csd); 5797 remsd = next; 5798 } 5799 #endif 5800 } 5801 5802 /* 5803 * net_rps_action_and_irq_enable sends any pending IPI's for rps. 5804 * Note: called with local irq disabled, but exits with local irq enabled. 5805 */ 5806 static void net_rps_action_and_irq_enable(struct softnet_data *sd) 5807 { 5808 #ifdef CONFIG_RPS 5809 struct softnet_data *remsd = sd->rps_ipi_list; 5810 5811 if (remsd) { 5812 sd->rps_ipi_list = NULL; 5813 5814 local_irq_enable(); 5815 5816 /* Send pending IPI's to kick RPS processing on remote cpus. */ 5817 net_rps_send_ipi(remsd); 5818 } else 5819 #endif 5820 local_irq_enable(); 5821 } 5822 5823 static bool sd_has_rps_ipi_waiting(struct softnet_data *sd) 5824 { 5825 #ifdef CONFIG_RPS 5826 return sd->rps_ipi_list != NULL; 5827 #else 5828 return false; 5829 #endif 5830 } 5831 5832 static int process_backlog(struct napi_struct *napi, int quota) 5833 { 5834 struct softnet_data *sd = container_of(napi, struct softnet_data, backlog); 5835 bool again = true; 5836 int work = 0; 5837 5838 /* Check if we have pending ipi, its better to send them now, 5839 * not waiting net_rx_action() end. 5840 */ 5841 if (sd_has_rps_ipi_waiting(sd)) { 5842 local_irq_disable(); 5843 net_rps_action_and_irq_enable(sd); 5844 } 5845 5846 napi->weight = dev_rx_weight; 5847 while (again) { 5848 struct sk_buff *skb; 5849 5850 while ((skb = __skb_dequeue(&sd->process_queue))) { 5851 rcu_read_lock(); 5852 __netif_receive_skb(skb); 5853 rcu_read_unlock(); 5854 input_queue_head_incr(sd); 5855 if (++work >= quota) 5856 return work; 5857 5858 } 5859 5860 rps_lock_irq_disable(sd); 5861 if (skb_queue_empty(&sd->input_pkt_queue)) { 5862 /* 5863 * Inline a custom version of __napi_complete(). 5864 * only current cpu owns and manipulates this napi, 5865 * and NAPI_STATE_SCHED is the only possible flag set 5866 * on backlog. 5867 * We can use a plain write instead of clear_bit(), 5868 * and we dont need an smp_mb() memory barrier. 5869 */ 5870 napi->state = 0; 5871 again = false; 5872 } else { 5873 skb_queue_splice_tail_init(&sd->input_pkt_queue, 5874 &sd->process_queue); 5875 } 5876 rps_unlock_irq_enable(sd); 5877 } 5878 5879 return work; 5880 } 5881 5882 /** 5883 * __napi_schedule - schedule for receive 5884 * @n: entry to schedule 5885 * 5886 * The entry's receive function will be scheduled to run. 5887 * Consider using __napi_schedule_irqoff() if hard irqs are masked. 5888 */ 5889 void __napi_schedule(struct napi_struct *n) 5890 { 5891 unsigned long flags; 5892 5893 local_irq_save(flags); 5894 ____napi_schedule(this_cpu_ptr(&softnet_data), n); 5895 local_irq_restore(flags); 5896 } 5897 EXPORT_SYMBOL(__napi_schedule); 5898 5899 /** 5900 * napi_schedule_prep - check if napi can be scheduled 5901 * @n: napi context 5902 * 5903 * Test if NAPI routine is already running, and if not mark 5904 * it as running. This is used as a condition variable to 5905 * insure only one NAPI poll instance runs. We also make 5906 * sure there is no pending NAPI disable. 5907 */ 5908 bool napi_schedule_prep(struct napi_struct *n) 5909 { 5910 unsigned long val, new; 5911 5912 do { 5913 val = READ_ONCE(n->state); 5914 if (unlikely(val & NAPIF_STATE_DISABLE)) 5915 return false; 5916 new = val | NAPIF_STATE_SCHED; 5917 5918 /* Sets STATE_MISSED bit if STATE_SCHED was already set 5919 * This was suggested by Alexander Duyck, as compiler 5920 * emits better code than : 5921 * if (val & NAPIF_STATE_SCHED) 5922 * new |= NAPIF_STATE_MISSED; 5923 */ 5924 new |= (val & NAPIF_STATE_SCHED) / NAPIF_STATE_SCHED * 5925 NAPIF_STATE_MISSED; 5926 } while (cmpxchg(&n->state, val, new) != val); 5927 5928 return !(val & NAPIF_STATE_SCHED); 5929 } 5930 EXPORT_SYMBOL(napi_schedule_prep); 5931 5932 /** 5933 * __napi_schedule_irqoff - schedule for receive 5934 * @n: entry to schedule 5935 * 5936 * Variant of __napi_schedule() assuming hard irqs are masked. 5937 * 5938 * On PREEMPT_RT enabled kernels this maps to __napi_schedule() 5939 * because the interrupt disabled assumption might not be true 5940 * due to force-threaded interrupts and spinlock substitution. 5941 */ 5942 void __napi_schedule_irqoff(struct napi_struct *n) 5943 { 5944 if (!IS_ENABLED(CONFIG_PREEMPT_RT)) 5945 ____napi_schedule(this_cpu_ptr(&softnet_data), n); 5946 else 5947 __napi_schedule(n); 5948 } 5949 EXPORT_SYMBOL(__napi_schedule_irqoff); 5950 5951 bool napi_complete_done(struct napi_struct *n, int work_done) 5952 { 5953 unsigned long flags, val, new, timeout = 0; 5954 bool ret = true; 5955 5956 /* 5957 * 1) Don't let napi dequeue from the cpu poll list 5958 * just in case its running on a different cpu. 5959 * 2) If we are busy polling, do nothing here, we have 5960 * the guarantee we will be called later. 5961 */ 5962 if (unlikely(n->state & (NAPIF_STATE_NPSVC | 5963 NAPIF_STATE_IN_BUSY_POLL))) 5964 return false; 5965 5966 if (work_done) { 5967 if (n->gro_bitmask) 5968 timeout = READ_ONCE(n->dev->gro_flush_timeout); 5969 n->defer_hard_irqs_count = READ_ONCE(n->dev->napi_defer_hard_irqs); 5970 } 5971 if (n->defer_hard_irqs_count > 0) { 5972 n->defer_hard_irqs_count--; 5973 timeout = READ_ONCE(n->dev->gro_flush_timeout); 5974 if (timeout) 5975 ret = false; 5976 } 5977 if (n->gro_bitmask) { 5978 /* When the NAPI instance uses a timeout and keeps postponing 5979 * it, we need to bound somehow the time packets are kept in 5980 * the GRO layer 5981 */ 5982 napi_gro_flush(n, !!timeout); 5983 } 5984 5985 gro_normal_list(n); 5986 5987 if (unlikely(!list_empty(&n->poll_list))) { 5988 /* If n->poll_list is not empty, we need to mask irqs */ 5989 local_irq_save(flags); 5990 list_del_init(&n->poll_list); 5991 local_irq_restore(flags); 5992 } 5993 5994 do { 5995 val = READ_ONCE(n->state); 5996 5997 WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED)); 5998 5999 new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED | 6000 NAPIF_STATE_SCHED_THREADED | 6001 NAPIF_STATE_PREFER_BUSY_POLL); 6002 6003 /* If STATE_MISSED was set, leave STATE_SCHED set, 6004 * because we will call napi->poll() one more time. 6005 * This C code was suggested by Alexander Duyck to help gcc. 6006 */ 6007 new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED * 6008 NAPIF_STATE_SCHED; 6009 } while (cmpxchg(&n->state, val, new) != val); 6010 6011 if (unlikely(val & NAPIF_STATE_MISSED)) { 6012 __napi_schedule(n); 6013 return false; 6014 } 6015 6016 if (timeout) 6017 hrtimer_start(&n->timer, ns_to_ktime(timeout), 6018 HRTIMER_MODE_REL_PINNED); 6019 return ret; 6020 } 6021 EXPORT_SYMBOL(napi_complete_done); 6022 6023 /* must be called under rcu_read_lock(), as we dont take a reference */ 6024 static struct napi_struct *napi_by_id(unsigned int napi_id) 6025 { 6026 unsigned int hash = napi_id % HASH_SIZE(napi_hash); 6027 struct napi_struct *napi; 6028 6029 hlist_for_each_entry_rcu(napi, &napi_hash[hash], napi_hash_node) 6030 if (napi->napi_id == napi_id) 6031 return napi; 6032 6033 return NULL; 6034 } 6035 6036 #if defined(CONFIG_NET_RX_BUSY_POLL) 6037 6038 static void __busy_poll_stop(struct napi_struct *napi, bool skip_schedule) 6039 { 6040 if (!skip_schedule) { 6041 gro_normal_list(napi); 6042 __napi_schedule(napi); 6043 return; 6044 } 6045 6046 if (napi->gro_bitmask) { 6047 /* flush too old packets 6048 * If HZ < 1000, flush all packets. 6049 */ 6050 napi_gro_flush(napi, HZ >= 1000); 6051 } 6052 6053 gro_normal_list(napi); 6054 clear_bit(NAPI_STATE_SCHED, &napi->state); 6055 } 6056 6057 static void busy_poll_stop(struct napi_struct *napi, void *have_poll_lock, bool prefer_busy_poll, 6058 u16 budget) 6059 { 6060 bool skip_schedule = false; 6061 unsigned long timeout; 6062 int rc; 6063 6064 /* Busy polling means there is a high chance device driver hard irq 6065 * could not grab NAPI_STATE_SCHED, and that NAPI_STATE_MISSED was 6066 * set in napi_schedule_prep(). 6067 * Since we are about to call napi->poll() once more, we can safely 6068 * clear NAPI_STATE_MISSED. 6069 * 6070 * Note: x86 could use a single "lock and ..." instruction 6071 * to perform these two clear_bit() 6072 */ 6073 clear_bit(NAPI_STATE_MISSED, &napi->state); 6074 clear_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state); 6075 6076 local_bh_disable(); 6077 6078 if (prefer_busy_poll) { 6079 napi->defer_hard_irqs_count = READ_ONCE(napi->dev->napi_defer_hard_irqs); 6080 timeout = READ_ONCE(napi->dev->gro_flush_timeout); 6081 if (napi->defer_hard_irqs_count && timeout) { 6082 hrtimer_start(&napi->timer, ns_to_ktime(timeout), HRTIMER_MODE_REL_PINNED); 6083 skip_schedule = true; 6084 } 6085 } 6086 6087 /* All we really want here is to re-enable device interrupts. 6088 * Ideally, a new ndo_busy_poll_stop() could avoid another round. 6089 */ 6090 rc = napi->poll(napi, budget); 6091 /* We can't gro_normal_list() here, because napi->poll() might have 6092 * rearmed the napi (napi_complete_done()) in which case it could 6093 * already be running on another CPU. 6094 */ 6095 trace_napi_poll(napi, rc, budget); 6096 netpoll_poll_unlock(have_poll_lock); 6097 if (rc == budget) 6098 __busy_poll_stop(napi, skip_schedule); 6099 local_bh_enable(); 6100 } 6101 6102 void napi_busy_loop(unsigned int napi_id, 6103 bool (*loop_end)(void *, unsigned long), 6104 void *loop_end_arg, bool prefer_busy_poll, u16 budget) 6105 { 6106 unsigned long start_time = loop_end ? busy_loop_current_time() : 0; 6107 int (*napi_poll)(struct napi_struct *napi, int budget); 6108 void *have_poll_lock = NULL; 6109 struct napi_struct *napi; 6110 6111 restart: 6112 napi_poll = NULL; 6113 6114 rcu_read_lock(); 6115 6116 napi = napi_by_id(napi_id); 6117 if (!napi) 6118 goto out; 6119 6120 preempt_disable(); 6121 for (;;) { 6122 int work = 0; 6123 6124 local_bh_disable(); 6125 if (!napi_poll) { 6126 unsigned long val = READ_ONCE(napi->state); 6127 6128 /* If multiple threads are competing for this napi, 6129 * we avoid dirtying napi->state as much as we can. 6130 */ 6131 if (val & (NAPIF_STATE_DISABLE | NAPIF_STATE_SCHED | 6132 NAPIF_STATE_IN_BUSY_POLL)) { 6133 if (prefer_busy_poll) 6134 set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state); 6135 goto count; 6136 } 6137 if (cmpxchg(&napi->state, val, 6138 val | NAPIF_STATE_IN_BUSY_POLL | 6139 NAPIF_STATE_SCHED) != val) { 6140 if (prefer_busy_poll) 6141 set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state); 6142 goto count; 6143 } 6144 have_poll_lock = netpoll_poll_lock(napi); 6145 napi_poll = napi->poll; 6146 } 6147 work = napi_poll(napi, budget); 6148 trace_napi_poll(napi, work, budget); 6149 gro_normal_list(napi); 6150 count: 6151 if (work > 0) 6152 __NET_ADD_STATS(dev_net(napi->dev), 6153 LINUX_MIB_BUSYPOLLRXPACKETS, work); 6154 local_bh_enable(); 6155 6156 if (!loop_end || loop_end(loop_end_arg, start_time)) 6157 break; 6158 6159 if (unlikely(need_resched())) { 6160 if (napi_poll) 6161 busy_poll_stop(napi, have_poll_lock, prefer_busy_poll, budget); 6162 preempt_enable(); 6163 rcu_read_unlock(); 6164 cond_resched(); 6165 if (loop_end(loop_end_arg, start_time)) 6166 return; 6167 goto restart; 6168 } 6169 cpu_relax(); 6170 } 6171 if (napi_poll) 6172 busy_poll_stop(napi, have_poll_lock, prefer_busy_poll, budget); 6173 preempt_enable(); 6174 out: 6175 rcu_read_unlock(); 6176 } 6177 EXPORT_SYMBOL(napi_busy_loop); 6178 6179 #endif /* CONFIG_NET_RX_BUSY_POLL */ 6180 6181 static void napi_hash_add(struct napi_struct *napi) 6182 { 6183 if (test_bit(NAPI_STATE_NO_BUSY_POLL, &napi->state)) 6184 return; 6185 6186 spin_lock(&napi_hash_lock); 6187 6188 /* 0..NR_CPUS range is reserved for sender_cpu use */ 6189 do { 6190 if (unlikely(++napi_gen_id < MIN_NAPI_ID)) 6191 napi_gen_id = MIN_NAPI_ID; 6192 } while (napi_by_id(napi_gen_id)); 6193 napi->napi_id = napi_gen_id; 6194 6195 hlist_add_head_rcu(&napi->napi_hash_node, 6196 &napi_hash[napi->napi_id % HASH_SIZE(napi_hash)]); 6197 6198 spin_unlock(&napi_hash_lock); 6199 } 6200 6201 /* Warning : caller is responsible to make sure rcu grace period 6202 * is respected before freeing memory containing @napi 6203 */ 6204 static void napi_hash_del(struct napi_struct *napi) 6205 { 6206 spin_lock(&napi_hash_lock); 6207 6208 hlist_del_init_rcu(&napi->napi_hash_node); 6209 6210 spin_unlock(&napi_hash_lock); 6211 } 6212 6213 static enum hrtimer_restart napi_watchdog(struct hrtimer *timer) 6214 { 6215 struct napi_struct *napi; 6216 6217 napi = container_of(timer, struct napi_struct, timer); 6218 6219 /* Note : we use a relaxed variant of napi_schedule_prep() not setting 6220 * NAPI_STATE_MISSED, since we do not react to a device IRQ. 6221 */ 6222 if (!napi_disable_pending(napi) && 6223 !test_and_set_bit(NAPI_STATE_SCHED, &napi->state)) { 6224 clear_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state); 6225 __napi_schedule_irqoff(napi); 6226 } 6227 6228 return HRTIMER_NORESTART; 6229 } 6230 6231 static void init_gro_hash(struct napi_struct *napi) 6232 { 6233 int i; 6234 6235 for (i = 0; i < GRO_HASH_BUCKETS; i++) { 6236 INIT_LIST_HEAD(&napi->gro_hash[i].list); 6237 napi->gro_hash[i].count = 0; 6238 } 6239 napi->gro_bitmask = 0; 6240 } 6241 6242 int dev_set_threaded(struct net_device *dev, bool threaded) 6243 { 6244 struct napi_struct *napi; 6245 int err = 0; 6246 6247 if (dev->threaded == threaded) 6248 return 0; 6249 6250 if (threaded) { 6251 list_for_each_entry(napi, &dev->napi_list, dev_list) { 6252 if (!napi->thread) { 6253 err = napi_kthread_create(napi); 6254 if (err) { 6255 threaded = false; 6256 break; 6257 } 6258 } 6259 } 6260 } 6261 6262 dev->threaded = threaded; 6263 6264 /* Make sure kthread is created before THREADED bit 6265 * is set. 6266 */ 6267 smp_mb__before_atomic(); 6268 6269 /* Setting/unsetting threaded mode on a napi might not immediately 6270 * take effect, if the current napi instance is actively being 6271 * polled. In this case, the switch between threaded mode and 6272 * softirq mode will happen in the next round of napi_schedule(). 6273 * This should not cause hiccups/stalls to the live traffic. 6274 */ 6275 list_for_each_entry(napi, &dev->napi_list, dev_list) { 6276 if (threaded) 6277 set_bit(NAPI_STATE_THREADED, &napi->state); 6278 else 6279 clear_bit(NAPI_STATE_THREADED, &napi->state); 6280 } 6281 6282 return err; 6283 } 6284 EXPORT_SYMBOL(dev_set_threaded); 6285 6286 void netif_napi_add(struct net_device *dev, struct napi_struct *napi, 6287 int (*poll)(struct napi_struct *, int), int weight) 6288 { 6289 if (WARN_ON(test_and_set_bit(NAPI_STATE_LISTED, &napi->state))) 6290 return; 6291 6292 INIT_LIST_HEAD(&napi->poll_list); 6293 INIT_HLIST_NODE(&napi->napi_hash_node); 6294 hrtimer_init(&napi->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED); 6295 napi->timer.function = napi_watchdog; 6296 init_gro_hash(napi); 6297 napi->skb = NULL; 6298 INIT_LIST_HEAD(&napi->rx_list); 6299 napi->rx_count = 0; 6300 napi->poll = poll; 6301 if (weight > NAPI_POLL_WEIGHT) 6302 netdev_err_once(dev, "%s() called with weight %d\n", __func__, 6303 weight); 6304 napi->weight = weight; 6305 napi->dev = dev; 6306 #ifdef CONFIG_NETPOLL 6307 napi->poll_owner = -1; 6308 #endif 6309 set_bit(NAPI_STATE_SCHED, &napi->state); 6310 set_bit(NAPI_STATE_NPSVC, &napi->state); 6311 list_add_rcu(&napi->dev_list, &dev->napi_list); 6312 napi_hash_add(napi); 6313 /* Create kthread for this napi if dev->threaded is set. 6314 * Clear dev->threaded if kthread creation failed so that 6315 * threaded mode will not be enabled in napi_enable(). 6316 */ 6317 if (dev->threaded && napi_kthread_create(napi)) 6318 dev->threaded = 0; 6319 } 6320 EXPORT_SYMBOL(netif_napi_add); 6321 6322 void napi_disable(struct napi_struct *n) 6323 { 6324 unsigned long val, new; 6325 6326 might_sleep(); 6327 set_bit(NAPI_STATE_DISABLE, &n->state); 6328 6329 for ( ; ; ) { 6330 val = READ_ONCE(n->state); 6331 if (val & (NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC)) { 6332 usleep_range(20, 200); 6333 continue; 6334 } 6335 6336 new = val | NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC; 6337 new &= ~(NAPIF_STATE_THREADED | NAPIF_STATE_PREFER_BUSY_POLL); 6338 6339 if (cmpxchg(&n->state, val, new) == val) 6340 break; 6341 } 6342 6343 hrtimer_cancel(&n->timer); 6344 6345 clear_bit(NAPI_STATE_DISABLE, &n->state); 6346 } 6347 EXPORT_SYMBOL(napi_disable); 6348 6349 /** 6350 * napi_enable - enable NAPI scheduling 6351 * @n: NAPI context 6352 * 6353 * Resume NAPI from being scheduled on this context. 6354 * Must be paired with napi_disable. 6355 */ 6356 void napi_enable(struct napi_struct *n) 6357 { 6358 unsigned long val, new; 6359 6360 do { 6361 val = READ_ONCE(n->state); 6362 BUG_ON(!test_bit(NAPI_STATE_SCHED, &val)); 6363 6364 new = val & ~(NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC); 6365 if (n->dev->threaded && n->thread) 6366 new |= NAPIF_STATE_THREADED; 6367 } while (cmpxchg(&n->state, val, new) != val); 6368 } 6369 EXPORT_SYMBOL(napi_enable); 6370 6371 static void flush_gro_hash(struct napi_struct *napi) 6372 { 6373 int i; 6374 6375 for (i = 0; i < GRO_HASH_BUCKETS; i++) { 6376 struct sk_buff *skb, *n; 6377 6378 list_for_each_entry_safe(skb, n, &napi->gro_hash[i].list, list) 6379 kfree_skb(skb); 6380 napi->gro_hash[i].count = 0; 6381 } 6382 } 6383 6384 /* Must be called in process context */ 6385 void __netif_napi_del(struct napi_struct *napi) 6386 { 6387 if (!test_and_clear_bit(NAPI_STATE_LISTED, &napi->state)) 6388 return; 6389 6390 napi_hash_del(napi); 6391 list_del_rcu(&napi->dev_list); 6392 napi_free_frags(napi); 6393 6394 flush_gro_hash(napi); 6395 napi->gro_bitmask = 0; 6396 6397 if (napi->thread) { 6398 kthread_stop(napi->thread); 6399 napi->thread = NULL; 6400 } 6401 } 6402 EXPORT_SYMBOL(__netif_napi_del); 6403 6404 static int __napi_poll(struct napi_struct *n, bool *repoll) 6405 { 6406 int work, weight; 6407 6408 weight = n->weight; 6409 6410 /* This NAPI_STATE_SCHED test is for avoiding a race 6411 * with netpoll's poll_napi(). Only the entity which 6412 * obtains the lock and sees NAPI_STATE_SCHED set will 6413 * actually make the ->poll() call. Therefore we avoid 6414 * accidentally calling ->poll() when NAPI is not scheduled. 6415 */ 6416 work = 0; 6417 if (test_bit(NAPI_STATE_SCHED, &n->state)) { 6418 work = n->poll(n, weight); 6419 trace_napi_poll(n, work, weight); 6420 } 6421 6422 if (unlikely(work > weight)) 6423 netdev_err_once(n->dev, "NAPI poll function %pS returned %d, exceeding its budget of %d.\n", 6424 n->poll, work, weight); 6425 6426 if (likely(work < weight)) 6427 return work; 6428 6429 /* Drivers must not modify the NAPI state if they 6430 * consume the entire weight. In such cases this code 6431 * still "owns" the NAPI instance and therefore can 6432 * move the instance around on the list at-will. 6433 */ 6434 if (unlikely(napi_disable_pending(n))) { 6435 napi_complete(n); 6436 return work; 6437 } 6438 6439 /* The NAPI context has more processing work, but busy-polling 6440 * is preferred. Exit early. 6441 */ 6442 if (napi_prefer_busy_poll(n)) { 6443 if (napi_complete_done(n, work)) { 6444 /* If timeout is not set, we need to make sure 6445 * that the NAPI is re-scheduled. 6446 */ 6447 napi_schedule(n); 6448 } 6449 return work; 6450 } 6451 6452 if (n->gro_bitmask) { 6453 /* flush too old packets 6454 * If HZ < 1000, flush all packets. 6455 */ 6456 napi_gro_flush(n, HZ >= 1000); 6457 } 6458 6459 gro_normal_list(n); 6460 6461 /* Some drivers may have called napi_schedule 6462 * prior to exhausting their budget. 6463 */ 6464 if (unlikely(!list_empty(&n->poll_list))) { 6465 pr_warn_once("%s: Budget exhausted after napi rescheduled\n", 6466 n->dev ? n->dev->name : "backlog"); 6467 return work; 6468 } 6469 6470 *repoll = true; 6471 6472 return work; 6473 } 6474 6475 static int napi_poll(struct napi_struct *n, struct list_head *repoll) 6476 { 6477 bool do_repoll = false; 6478 void *have; 6479 int work; 6480 6481 list_del_init(&n->poll_list); 6482 6483 have = netpoll_poll_lock(n); 6484 6485 work = __napi_poll(n, &do_repoll); 6486 6487 if (do_repoll) 6488 list_add_tail(&n->poll_list, repoll); 6489 6490 netpoll_poll_unlock(have); 6491 6492 return work; 6493 } 6494 6495 static int napi_thread_wait(struct napi_struct *napi) 6496 { 6497 bool woken = false; 6498 6499 set_current_state(TASK_INTERRUPTIBLE); 6500 6501 while (!kthread_should_stop()) { 6502 /* Testing SCHED_THREADED bit here to make sure the current 6503 * kthread owns this napi and could poll on this napi. 6504 * Testing SCHED bit is not enough because SCHED bit might be 6505 * set by some other busy poll thread or by napi_disable(). 6506 */ 6507 if (test_bit(NAPI_STATE_SCHED_THREADED, &napi->state) || woken) { 6508 WARN_ON(!list_empty(&napi->poll_list)); 6509 __set_current_state(TASK_RUNNING); 6510 return 0; 6511 } 6512 6513 schedule(); 6514 /* woken being true indicates this thread owns this napi. */ 6515 woken = true; 6516 set_current_state(TASK_INTERRUPTIBLE); 6517 } 6518 __set_current_state(TASK_RUNNING); 6519 6520 return -1; 6521 } 6522 6523 static int napi_threaded_poll(void *data) 6524 { 6525 struct napi_struct *napi = data; 6526 void *have; 6527 6528 while (!napi_thread_wait(napi)) { 6529 for (;;) { 6530 bool repoll = false; 6531 6532 local_bh_disable(); 6533 6534 have = netpoll_poll_lock(napi); 6535 __napi_poll(napi, &repoll); 6536 netpoll_poll_unlock(have); 6537 6538 local_bh_enable(); 6539 6540 if (!repoll) 6541 break; 6542 6543 cond_resched(); 6544 } 6545 } 6546 return 0; 6547 } 6548 6549 static __latent_entropy void net_rx_action(struct softirq_action *h) 6550 { 6551 struct softnet_data *sd = this_cpu_ptr(&softnet_data); 6552 unsigned long time_limit = jiffies + 6553 usecs_to_jiffies(netdev_budget_usecs); 6554 int budget = netdev_budget; 6555 LIST_HEAD(list); 6556 LIST_HEAD(repoll); 6557 6558 local_irq_disable(); 6559 list_splice_init(&sd->poll_list, &list); 6560 local_irq_enable(); 6561 6562 for (;;) { 6563 struct napi_struct *n; 6564 6565 if (list_empty(&list)) { 6566 if (!sd_has_rps_ipi_waiting(sd) && list_empty(&repoll)) 6567 return; 6568 break; 6569 } 6570 6571 n = list_first_entry(&list, struct napi_struct, poll_list); 6572 budget -= napi_poll(n, &repoll); 6573 6574 /* If softirq window is exhausted then punt. 6575 * Allow this to run for 2 jiffies since which will allow 6576 * an average latency of 1.5/HZ. 6577 */ 6578 if (unlikely(budget <= 0 || 6579 time_after_eq(jiffies, time_limit))) { 6580 sd->time_squeeze++; 6581 break; 6582 } 6583 } 6584 6585 local_irq_disable(); 6586 6587 list_splice_tail_init(&sd->poll_list, &list); 6588 list_splice_tail(&repoll, &list); 6589 list_splice(&list, &sd->poll_list); 6590 if (!list_empty(&sd->poll_list)) 6591 __raise_softirq_irqoff(NET_RX_SOFTIRQ); 6592 6593 net_rps_action_and_irq_enable(sd); 6594 } 6595 6596 struct netdev_adjacent { 6597 struct net_device *dev; 6598 netdevice_tracker dev_tracker; 6599 6600 /* upper master flag, there can only be one master device per list */ 6601 bool master; 6602 6603 /* lookup ignore flag */ 6604 bool ignore; 6605 6606 /* counter for the number of times this device was added to us */ 6607 u16 ref_nr; 6608 6609 /* private field for the users */ 6610 void *private; 6611 6612 struct list_head list; 6613 struct rcu_head rcu; 6614 }; 6615 6616 static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev, 6617 struct list_head *adj_list) 6618 { 6619 struct netdev_adjacent *adj; 6620 6621 list_for_each_entry(adj, adj_list, list) { 6622 if (adj->dev == adj_dev) 6623 return adj; 6624 } 6625 return NULL; 6626 } 6627 6628 static int ____netdev_has_upper_dev(struct net_device *upper_dev, 6629 struct netdev_nested_priv *priv) 6630 { 6631 struct net_device *dev = (struct net_device *)priv->data; 6632 6633 return upper_dev == dev; 6634 } 6635 6636 /** 6637 * netdev_has_upper_dev - Check if device is linked to an upper device 6638 * @dev: device 6639 * @upper_dev: upper device to check 6640 * 6641 * Find out if a device is linked to specified upper device and return true 6642 * in case it is. Note that this checks only immediate upper device, 6643 * not through a complete stack of devices. The caller must hold the RTNL lock. 6644 */ 6645 bool netdev_has_upper_dev(struct net_device *dev, 6646 struct net_device *upper_dev) 6647 { 6648 struct netdev_nested_priv priv = { 6649 .data = (void *)upper_dev, 6650 }; 6651 6652 ASSERT_RTNL(); 6653 6654 return netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev, 6655 &priv); 6656 } 6657 EXPORT_SYMBOL(netdev_has_upper_dev); 6658 6659 /** 6660 * netdev_has_upper_dev_all_rcu - Check if device is linked to an upper device 6661 * @dev: device 6662 * @upper_dev: upper device to check 6663 * 6664 * Find out if a device is linked to specified upper device and return true 6665 * in case it is. Note that this checks the entire upper device chain. 6666 * The caller must hold rcu lock. 6667 */ 6668 6669 bool netdev_has_upper_dev_all_rcu(struct net_device *dev, 6670 struct net_device *upper_dev) 6671 { 6672 struct netdev_nested_priv priv = { 6673 .data = (void *)upper_dev, 6674 }; 6675 6676 return !!netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev, 6677 &priv); 6678 } 6679 EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu); 6680 6681 /** 6682 * netdev_has_any_upper_dev - Check if device is linked to some device 6683 * @dev: device 6684 * 6685 * Find out if a device is linked to an upper device and return true in case 6686 * it is. The caller must hold the RTNL lock. 6687 */ 6688 bool netdev_has_any_upper_dev(struct net_device *dev) 6689 { 6690 ASSERT_RTNL(); 6691 6692 return !list_empty(&dev->adj_list.upper); 6693 } 6694 EXPORT_SYMBOL(netdev_has_any_upper_dev); 6695 6696 /** 6697 * netdev_master_upper_dev_get - Get master upper device 6698 * @dev: device 6699 * 6700 * Find a master upper device and return pointer to it or NULL in case 6701 * it's not there. The caller must hold the RTNL lock. 6702 */ 6703 struct net_device *netdev_master_upper_dev_get(struct net_device *dev) 6704 { 6705 struct netdev_adjacent *upper; 6706 6707 ASSERT_RTNL(); 6708 6709 if (list_empty(&dev->adj_list.upper)) 6710 return NULL; 6711 6712 upper = list_first_entry(&dev->adj_list.upper, 6713 struct netdev_adjacent, list); 6714 if (likely(upper->master)) 6715 return upper->dev; 6716 return NULL; 6717 } 6718 EXPORT_SYMBOL(netdev_master_upper_dev_get); 6719 6720 static struct net_device *__netdev_master_upper_dev_get(struct net_device *dev) 6721 { 6722 struct netdev_adjacent *upper; 6723 6724 ASSERT_RTNL(); 6725 6726 if (list_empty(&dev->adj_list.upper)) 6727 return NULL; 6728 6729 upper = list_first_entry(&dev->adj_list.upper, 6730 struct netdev_adjacent, list); 6731 if (likely(upper->master) && !upper->ignore) 6732 return upper->dev; 6733 return NULL; 6734 } 6735 6736 /** 6737 * netdev_has_any_lower_dev - Check if device is linked to some device 6738 * @dev: device 6739 * 6740 * Find out if a device is linked to a lower device and return true in case 6741 * it is. The caller must hold the RTNL lock. 6742 */ 6743 static bool netdev_has_any_lower_dev(struct net_device *dev) 6744 { 6745 ASSERT_RTNL(); 6746 6747 return !list_empty(&dev->adj_list.lower); 6748 } 6749 6750 void *netdev_adjacent_get_private(struct list_head *adj_list) 6751 { 6752 struct netdev_adjacent *adj; 6753 6754 adj = list_entry(adj_list, struct netdev_adjacent, list); 6755 6756 return adj->private; 6757 } 6758 EXPORT_SYMBOL(netdev_adjacent_get_private); 6759 6760 /** 6761 * netdev_upper_get_next_dev_rcu - Get the next dev from upper list 6762 * @dev: device 6763 * @iter: list_head ** of the current position 6764 * 6765 * Gets the next device from the dev's upper list, starting from iter 6766 * position. The caller must hold RCU read lock. 6767 */ 6768 struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev, 6769 struct list_head **iter) 6770 { 6771 struct netdev_adjacent *upper; 6772 6773 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held()); 6774 6775 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list); 6776 6777 if (&upper->list == &dev->adj_list.upper) 6778 return NULL; 6779 6780 *iter = &upper->list; 6781 6782 return upper->dev; 6783 } 6784 EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu); 6785 6786 static struct net_device *__netdev_next_upper_dev(struct net_device *dev, 6787 struct list_head **iter, 6788 bool *ignore) 6789 { 6790 struct netdev_adjacent *upper; 6791 6792 upper = list_entry((*iter)->next, struct netdev_adjacent, list); 6793 6794 if (&upper->list == &dev->adj_list.upper) 6795 return NULL; 6796 6797 *iter = &upper->list; 6798 *ignore = upper->ignore; 6799 6800 return upper->dev; 6801 } 6802 6803 static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev, 6804 struct list_head **iter) 6805 { 6806 struct netdev_adjacent *upper; 6807 6808 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held()); 6809 6810 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list); 6811 6812 if (&upper->list == &dev->adj_list.upper) 6813 return NULL; 6814 6815 *iter = &upper->list; 6816 6817 return upper->dev; 6818 } 6819 6820 static int __netdev_walk_all_upper_dev(struct net_device *dev, 6821 int (*fn)(struct net_device *dev, 6822 struct netdev_nested_priv *priv), 6823 struct netdev_nested_priv *priv) 6824 { 6825 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1]; 6826 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1]; 6827 int ret, cur = 0; 6828 bool ignore; 6829 6830 now = dev; 6831 iter = &dev->adj_list.upper; 6832 6833 while (1) { 6834 if (now != dev) { 6835 ret = fn(now, priv); 6836 if (ret) 6837 return ret; 6838 } 6839 6840 next = NULL; 6841 while (1) { 6842 udev = __netdev_next_upper_dev(now, &iter, &ignore); 6843 if (!udev) 6844 break; 6845 if (ignore) 6846 continue; 6847 6848 next = udev; 6849 niter = &udev->adj_list.upper; 6850 dev_stack[cur] = now; 6851 iter_stack[cur++] = iter; 6852 break; 6853 } 6854 6855 if (!next) { 6856 if (!cur) 6857 return 0; 6858 next = dev_stack[--cur]; 6859 niter = iter_stack[cur]; 6860 } 6861 6862 now = next; 6863 iter = niter; 6864 } 6865 6866 return 0; 6867 } 6868 6869 int netdev_walk_all_upper_dev_rcu(struct net_device *dev, 6870 int (*fn)(struct net_device *dev, 6871 struct netdev_nested_priv *priv), 6872 struct netdev_nested_priv *priv) 6873 { 6874 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1]; 6875 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1]; 6876 int ret, cur = 0; 6877 6878 now = dev; 6879 iter = &dev->adj_list.upper; 6880 6881 while (1) { 6882 if (now != dev) { 6883 ret = fn(now, priv); 6884 if (ret) 6885 return ret; 6886 } 6887 6888 next = NULL; 6889 while (1) { 6890 udev = netdev_next_upper_dev_rcu(now, &iter); 6891 if (!udev) 6892 break; 6893 6894 next = udev; 6895 niter = &udev->adj_list.upper; 6896 dev_stack[cur] = now; 6897 iter_stack[cur++] = iter; 6898 break; 6899 } 6900 6901 if (!next) { 6902 if (!cur) 6903 return 0; 6904 next = dev_stack[--cur]; 6905 niter = iter_stack[cur]; 6906 } 6907 6908 now = next; 6909 iter = niter; 6910 } 6911 6912 return 0; 6913 } 6914 EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu); 6915 6916 static bool __netdev_has_upper_dev(struct net_device *dev, 6917 struct net_device *upper_dev) 6918 { 6919 struct netdev_nested_priv priv = { 6920 .flags = 0, 6921 .data = (void *)upper_dev, 6922 }; 6923 6924 ASSERT_RTNL(); 6925 6926 return __netdev_walk_all_upper_dev(dev, ____netdev_has_upper_dev, 6927 &priv); 6928 } 6929 6930 /** 6931 * netdev_lower_get_next_private - Get the next ->private from the 6932 * lower neighbour list 6933 * @dev: device 6934 * @iter: list_head ** of the current position 6935 * 6936 * Gets the next netdev_adjacent->private from the dev's lower neighbour 6937 * list, starting from iter position. The caller must hold either hold the 6938 * RTNL lock or its own locking that guarantees that the neighbour lower 6939 * list will remain unchanged. 6940 */ 6941 void *netdev_lower_get_next_private(struct net_device *dev, 6942 struct list_head **iter) 6943 { 6944 struct netdev_adjacent *lower; 6945 6946 lower = list_entry(*iter, struct netdev_adjacent, list); 6947 6948 if (&lower->list == &dev->adj_list.lower) 6949 return NULL; 6950 6951 *iter = lower->list.next; 6952 6953 return lower->private; 6954 } 6955 EXPORT_SYMBOL(netdev_lower_get_next_private); 6956 6957 /** 6958 * netdev_lower_get_next_private_rcu - Get the next ->private from the 6959 * lower neighbour list, RCU 6960 * variant 6961 * @dev: device 6962 * @iter: list_head ** of the current position 6963 * 6964 * Gets the next netdev_adjacent->private from the dev's lower neighbour 6965 * list, starting from iter position. The caller must hold RCU read lock. 6966 */ 6967 void *netdev_lower_get_next_private_rcu(struct net_device *dev, 6968 struct list_head **iter) 6969 { 6970 struct netdev_adjacent *lower; 6971 6972 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held()); 6973 6974 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list); 6975 6976 if (&lower->list == &dev->adj_list.lower) 6977 return NULL; 6978 6979 *iter = &lower->list; 6980 6981 return lower->private; 6982 } 6983 EXPORT_SYMBOL(netdev_lower_get_next_private_rcu); 6984 6985 /** 6986 * netdev_lower_get_next - Get the next device from the lower neighbour 6987 * list 6988 * @dev: device 6989 * @iter: list_head ** of the current position 6990 * 6991 * Gets the next netdev_adjacent from the dev's lower neighbour 6992 * list, starting from iter position. The caller must hold RTNL lock or 6993 * its own locking that guarantees that the neighbour lower 6994 * list will remain unchanged. 6995 */ 6996 void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter) 6997 { 6998 struct netdev_adjacent *lower; 6999 7000 lower = list_entry(*iter, struct netdev_adjacent, list); 7001 7002 if (&lower->list == &dev->adj_list.lower) 7003 return NULL; 7004 7005 *iter = lower->list.next; 7006 7007 return lower->dev; 7008 } 7009 EXPORT_SYMBOL(netdev_lower_get_next); 7010 7011 static struct net_device *netdev_next_lower_dev(struct net_device *dev, 7012 struct list_head **iter) 7013 { 7014 struct netdev_adjacent *lower; 7015 7016 lower = list_entry((*iter)->next, struct netdev_adjacent, list); 7017 7018 if (&lower->list == &dev->adj_list.lower) 7019 return NULL; 7020 7021 *iter = &lower->list; 7022 7023 return lower->dev; 7024 } 7025 7026 static struct net_device *__netdev_next_lower_dev(struct net_device *dev, 7027 struct list_head **iter, 7028 bool *ignore) 7029 { 7030 struct netdev_adjacent *lower; 7031 7032 lower = list_entry((*iter)->next, struct netdev_adjacent, list); 7033 7034 if (&lower->list == &dev->adj_list.lower) 7035 return NULL; 7036 7037 *iter = &lower->list; 7038 *ignore = lower->ignore; 7039 7040 return lower->dev; 7041 } 7042 7043 int netdev_walk_all_lower_dev(struct net_device *dev, 7044 int (*fn)(struct net_device *dev, 7045 struct netdev_nested_priv *priv), 7046 struct netdev_nested_priv *priv) 7047 { 7048 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1]; 7049 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1]; 7050 int ret, cur = 0; 7051 7052 now = dev; 7053 iter = &dev->adj_list.lower; 7054 7055 while (1) { 7056 if (now != dev) { 7057 ret = fn(now, priv); 7058 if (ret) 7059 return ret; 7060 } 7061 7062 next = NULL; 7063 while (1) { 7064 ldev = netdev_next_lower_dev(now, &iter); 7065 if (!ldev) 7066 break; 7067 7068 next = ldev; 7069 niter = &ldev->adj_list.lower; 7070 dev_stack[cur] = now; 7071 iter_stack[cur++] = iter; 7072 break; 7073 } 7074 7075 if (!next) { 7076 if (!cur) 7077 return 0; 7078 next = dev_stack[--cur]; 7079 niter = iter_stack[cur]; 7080 } 7081 7082 now = next; 7083 iter = niter; 7084 } 7085 7086 return 0; 7087 } 7088 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev); 7089 7090 static int __netdev_walk_all_lower_dev(struct net_device *dev, 7091 int (*fn)(struct net_device *dev, 7092 struct netdev_nested_priv *priv), 7093 struct netdev_nested_priv *priv) 7094 { 7095 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1]; 7096 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1]; 7097 int ret, cur = 0; 7098 bool ignore; 7099 7100 now = dev; 7101 iter = &dev->adj_list.lower; 7102 7103 while (1) { 7104 if (now != dev) { 7105 ret = fn(now, priv); 7106 if (ret) 7107 return ret; 7108 } 7109 7110 next = NULL; 7111 while (1) { 7112 ldev = __netdev_next_lower_dev(now, &iter, &ignore); 7113 if (!ldev) 7114 break; 7115 if (ignore) 7116 continue; 7117 7118 next = ldev; 7119 niter = &ldev->adj_list.lower; 7120 dev_stack[cur] = now; 7121 iter_stack[cur++] = iter; 7122 break; 7123 } 7124 7125 if (!next) { 7126 if (!cur) 7127 return 0; 7128 next = dev_stack[--cur]; 7129 niter = iter_stack[cur]; 7130 } 7131 7132 now = next; 7133 iter = niter; 7134 } 7135 7136 return 0; 7137 } 7138 7139 struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev, 7140 struct list_head **iter) 7141 { 7142 struct netdev_adjacent *lower; 7143 7144 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list); 7145 if (&lower->list == &dev->adj_list.lower) 7146 return NULL; 7147 7148 *iter = &lower->list; 7149 7150 return lower->dev; 7151 } 7152 EXPORT_SYMBOL(netdev_next_lower_dev_rcu); 7153 7154 static u8 __netdev_upper_depth(struct net_device *dev) 7155 { 7156 struct net_device *udev; 7157 struct list_head *iter; 7158 u8 max_depth = 0; 7159 bool ignore; 7160 7161 for (iter = &dev->adj_list.upper, 7162 udev = __netdev_next_upper_dev(dev, &iter, &ignore); 7163 udev; 7164 udev = __netdev_next_upper_dev(dev, &iter, &ignore)) { 7165 if (ignore) 7166 continue; 7167 if (max_depth < udev->upper_level) 7168 max_depth = udev->upper_level; 7169 } 7170 7171 return max_depth; 7172 } 7173 7174 static u8 __netdev_lower_depth(struct net_device *dev) 7175 { 7176 struct net_device *ldev; 7177 struct list_head *iter; 7178 u8 max_depth = 0; 7179 bool ignore; 7180 7181 for (iter = &dev->adj_list.lower, 7182 ldev = __netdev_next_lower_dev(dev, &iter, &ignore); 7183 ldev; 7184 ldev = __netdev_next_lower_dev(dev, &iter, &ignore)) { 7185 if (ignore) 7186 continue; 7187 if (max_depth < ldev->lower_level) 7188 max_depth = ldev->lower_level; 7189 } 7190 7191 return max_depth; 7192 } 7193 7194 static int __netdev_update_upper_level(struct net_device *dev, 7195 struct netdev_nested_priv *__unused) 7196 { 7197 dev->upper_level = __netdev_upper_depth(dev) + 1; 7198 return 0; 7199 } 7200 7201 #ifdef CONFIG_LOCKDEP 7202 static LIST_HEAD(net_unlink_list); 7203 7204 static void net_unlink_todo(struct net_device *dev) 7205 { 7206 if (list_empty(&dev->unlink_list)) 7207 list_add_tail(&dev->unlink_list, &net_unlink_list); 7208 } 7209 #endif 7210 7211 static int __netdev_update_lower_level(struct net_device *dev, 7212 struct netdev_nested_priv *priv) 7213 { 7214 dev->lower_level = __netdev_lower_depth(dev) + 1; 7215 7216 #ifdef CONFIG_LOCKDEP 7217 if (!priv) 7218 return 0; 7219 7220 if (priv->flags & NESTED_SYNC_IMM) 7221 dev->nested_level = dev->lower_level - 1; 7222 if (priv->flags & NESTED_SYNC_TODO) 7223 net_unlink_todo(dev); 7224 #endif 7225 return 0; 7226 } 7227 7228 int netdev_walk_all_lower_dev_rcu(struct net_device *dev, 7229 int (*fn)(struct net_device *dev, 7230 struct netdev_nested_priv *priv), 7231 struct netdev_nested_priv *priv) 7232 { 7233 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1]; 7234 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1]; 7235 int ret, cur = 0; 7236 7237 now = dev; 7238 iter = &dev->adj_list.lower; 7239 7240 while (1) { 7241 if (now != dev) { 7242 ret = fn(now, priv); 7243 if (ret) 7244 return ret; 7245 } 7246 7247 next = NULL; 7248 while (1) { 7249 ldev = netdev_next_lower_dev_rcu(now, &iter); 7250 if (!ldev) 7251 break; 7252 7253 next = ldev; 7254 niter = &ldev->adj_list.lower; 7255 dev_stack[cur] = now; 7256 iter_stack[cur++] = iter; 7257 break; 7258 } 7259 7260 if (!next) { 7261 if (!cur) 7262 return 0; 7263 next = dev_stack[--cur]; 7264 niter = iter_stack[cur]; 7265 } 7266 7267 now = next; 7268 iter = niter; 7269 } 7270 7271 return 0; 7272 } 7273 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu); 7274 7275 /** 7276 * netdev_lower_get_first_private_rcu - Get the first ->private from the 7277 * lower neighbour list, RCU 7278 * variant 7279 * @dev: device 7280 * 7281 * Gets the first netdev_adjacent->private from the dev's lower neighbour 7282 * list. The caller must hold RCU read lock. 7283 */ 7284 void *netdev_lower_get_first_private_rcu(struct net_device *dev) 7285 { 7286 struct netdev_adjacent *lower; 7287 7288 lower = list_first_or_null_rcu(&dev->adj_list.lower, 7289 struct netdev_adjacent, list); 7290 if (lower) 7291 return lower->private; 7292 return NULL; 7293 } 7294 EXPORT_SYMBOL(netdev_lower_get_first_private_rcu); 7295 7296 /** 7297 * netdev_master_upper_dev_get_rcu - Get master upper device 7298 * @dev: device 7299 * 7300 * Find a master upper device and return pointer to it or NULL in case 7301 * it's not there. The caller must hold the RCU read lock. 7302 */ 7303 struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev) 7304 { 7305 struct netdev_adjacent *upper; 7306 7307 upper = list_first_or_null_rcu(&dev->adj_list.upper, 7308 struct netdev_adjacent, list); 7309 if (upper && likely(upper->master)) 7310 return upper->dev; 7311 return NULL; 7312 } 7313 EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu); 7314 7315 static int netdev_adjacent_sysfs_add(struct net_device *dev, 7316 struct net_device *adj_dev, 7317 struct list_head *dev_list) 7318 { 7319 char linkname[IFNAMSIZ+7]; 7320 7321 sprintf(linkname, dev_list == &dev->adj_list.upper ? 7322 "upper_%s" : "lower_%s", adj_dev->name); 7323 return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj), 7324 linkname); 7325 } 7326 static void netdev_adjacent_sysfs_del(struct net_device *dev, 7327 char *name, 7328 struct list_head *dev_list) 7329 { 7330 char linkname[IFNAMSIZ+7]; 7331 7332 sprintf(linkname, dev_list == &dev->adj_list.upper ? 7333 "upper_%s" : "lower_%s", name); 7334 sysfs_remove_link(&(dev->dev.kobj), linkname); 7335 } 7336 7337 static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev, 7338 struct net_device *adj_dev, 7339 struct list_head *dev_list) 7340 { 7341 return (dev_list == &dev->adj_list.upper || 7342 dev_list == &dev->adj_list.lower) && 7343 net_eq(dev_net(dev), dev_net(adj_dev)); 7344 } 7345 7346 static int __netdev_adjacent_dev_insert(struct net_device *dev, 7347 struct net_device *adj_dev, 7348 struct list_head *dev_list, 7349 void *private, bool master) 7350 { 7351 struct netdev_adjacent *adj; 7352 int ret; 7353 7354 adj = __netdev_find_adj(adj_dev, dev_list); 7355 7356 if (adj) { 7357 adj->ref_nr += 1; 7358 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n", 7359 dev->name, adj_dev->name, adj->ref_nr); 7360 7361 return 0; 7362 } 7363 7364 adj = kmalloc(sizeof(*adj), GFP_KERNEL); 7365 if (!adj) 7366 return -ENOMEM; 7367 7368 adj->dev = adj_dev; 7369 adj->master = master; 7370 adj->ref_nr = 1; 7371 adj->private = private; 7372 adj->ignore = false; 7373 dev_hold_track(adj_dev, &adj->dev_tracker, GFP_KERNEL); 7374 7375 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n", 7376 dev->name, adj_dev->name, adj->ref_nr, adj_dev->name); 7377 7378 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) { 7379 ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list); 7380 if (ret) 7381 goto free_adj; 7382 } 7383 7384 /* Ensure that master link is always the first item in list. */ 7385 if (master) { 7386 ret = sysfs_create_link(&(dev->dev.kobj), 7387 &(adj_dev->dev.kobj), "master"); 7388 if (ret) 7389 goto remove_symlinks; 7390 7391 list_add_rcu(&adj->list, dev_list); 7392 } else { 7393 list_add_tail_rcu(&adj->list, dev_list); 7394 } 7395 7396 return 0; 7397 7398 remove_symlinks: 7399 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) 7400 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list); 7401 free_adj: 7402 dev_put_track(adj_dev, &adj->dev_tracker); 7403 kfree(adj); 7404 7405 return ret; 7406 } 7407 7408 static void __netdev_adjacent_dev_remove(struct net_device *dev, 7409 struct net_device *adj_dev, 7410 u16 ref_nr, 7411 struct list_head *dev_list) 7412 { 7413 struct netdev_adjacent *adj; 7414 7415 pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n", 7416 dev->name, adj_dev->name, ref_nr); 7417 7418 adj = __netdev_find_adj(adj_dev, dev_list); 7419 7420 if (!adj) { 7421 pr_err("Adjacency does not exist for device %s from %s\n", 7422 dev->name, adj_dev->name); 7423 WARN_ON(1); 7424 return; 7425 } 7426 7427 if (adj->ref_nr > ref_nr) { 7428 pr_debug("adjacency: %s to %s ref_nr - %d = %d\n", 7429 dev->name, adj_dev->name, ref_nr, 7430 adj->ref_nr - ref_nr); 7431 adj->ref_nr -= ref_nr; 7432 return; 7433 } 7434 7435 if (adj->master) 7436 sysfs_remove_link(&(dev->dev.kobj), "master"); 7437 7438 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) 7439 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list); 7440 7441 list_del_rcu(&adj->list); 7442 pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n", 7443 adj_dev->name, dev->name, adj_dev->name); 7444 dev_put_track(adj_dev, &adj->dev_tracker); 7445 kfree_rcu(adj, rcu); 7446 } 7447 7448 static int __netdev_adjacent_dev_link_lists(struct net_device *dev, 7449 struct net_device *upper_dev, 7450 struct list_head *up_list, 7451 struct list_head *down_list, 7452 void *private, bool master) 7453 { 7454 int ret; 7455 7456 ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list, 7457 private, master); 7458 if (ret) 7459 return ret; 7460 7461 ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list, 7462 private, false); 7463 if (ret) { 7464 __netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list); 7465 return ret; 7466 } 7467 7468 return 0; 7469 } 7470 7471 static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev, 7472 struct net_device *upper_dev, 7473 u16 ref_nr, 7474 struct list_head *up_list, 7475 struct list_head *down_list) 7476 { 7477 __netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list); 7478 __netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list); 7479 } 7480 7481 static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev, 7482 struct net_device *upper_dev, 7483 void *private, bool master) 7484 { 7485 return __netdev_adjacent_dev_link_lists(dev, upper_dev, 7486 &dev->adj_list.upper, 7487 &upper_dev->adj_list.lower, 7488 private, master); 7489 } 7490 7491 static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev, 7492 struct net_device *upper_dev) 7493 { 7494 __netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1, 7495 &dev->adj_list.upper, 7496 &upper_dev->adj_list.lower); 7497 } 7498 7499 static int __netdev_upper_dev_link(struct net_device *dev, 7500 struct net_device *upper_dev, bool master, 7501 void *upper_priv, void *upper_info, 7502 struct netdev_nested_priv *priv, 7503 struct netlink_ext_ack *extack) 7504 { 7505 struct netdev_notifier_changeupper_info changeupper_info = { 7506 .info = { 7507 .dev = dev, 7508 .extack = extack, 7509 }, 7510 .upper_dev = upper_dev, 7511 .master = master, 7512 .linking = true, 7513 .upper_info = upper_info, 7514 }; 7515 struct net_device *master_dev; 7516 int ret = 0; 7517 7518 ASSERT_RTNL(); 7519 7520 if (dev == upper_dev) 7521 return -EBUSY; 7522 7523 /* To prevent loops, check if dev is not upper device to upper_dev. */ 7524 if (__netdev_has_upper_dev(upper_dev, dev)) 7525 return -EBUSY; 7526 7527 if ((dev->lower_level + upper_dev->upper_level) > MAX_NEST_DEV) 7528 return -EMLINK; 7529 7530 if (!master) { 7531 if (__netdev_has_upper_dev(dev, upper_dev)) 7532 return -EEXIST; 7533 } else { 7534 master_dev = __netdev_master_upper_dev_get(dev); 7535 if (master_dev) 7536 return master_dev == upper_dev ? -EEXIST : -EBUSY; 7537 } 7538 7539 ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER, 7540 &changeupper_info.info); 7541 ret = notifier_to_errno(ret); 7542 if (ret) 7543 return ret; 7544 7545 ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv, 7546 master); 7547 if (ret) 7548 return ret; 7549 7550 ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER, 7551 &changeupper_info.info); 7552 ret = notifier_to_errno(ret); 7553 if (ret) 7554 goto rollback; 7555 7556 __netdev_update_upper_level(dev, NULL); 7557 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL); 7558 7559 __netdev_update_lower_level(upper_dev, priv); 7560 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level, 7561 priv); 7562 7563 return 0; 7564 7565 rollback: 7566 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev); 7567 7568 return ret; 7569 } 7570 7571 /** 7572 * netdev_upper_dev_link - Add a link to the upper device 7573 * @dev: device 7574 * @upper_dev: new upper device 7575 * @extack: netlink extended ack 7576 * 7577 * Adds a link to device which is upper to this one. The caller must hold 7578 * the RTNL lock. On a failure a negative errno code is returned. 7579 * On success the reference counts are adjusted and the function 7580 * returns zero. 7581 */ 7582 int netdev_upper_dev_link(struct net_device *dev, 7583 struct net_device *upper_dev, 7584 struct netlink_ext_ack *extack) 7585 { 7586 struct netdev_nested_priv priv = { 7587 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO, 7588 .data = NULL, 7589 }; 7590 7591 return __netdev_upper_dev_link(dev, upper_dev, false, 7592 NULL, NULL, &priv, extack); 7593 } 7594 EXPORT_SYMBOL(netdev_upper_dev_link); 7595 7596 /** 7597 * netdev_master_upper_dev_link - Add a master link to the upper device 7598 * @dev: device 7599 * @upper_dev: new upper device 7600 * @upper_priv: upper device private 7601 * @upper_info: upper info to be passed down via notifier 7602 * @extack: netlink extended ack 7603 * 7604 * Adds a link to device which is upper to this one. In this case, only 7605 * one master upper device can be linked, although other non-master devices 7606 * might be linked as well. The caller must hold the RTNL lock. 7607 * On a failure a negative errno code is returned. On success the reference 7608 * counts are adjusted and the function returns zero. 7609 */ 7610 int netdev_master_upper_dev_link(struct net_device *dev, 7611 struct net_device *upper_dev, 7612 void *upper_priv, void *upper_info, 7613 struct netlink_ext_ack *extack) 7614 { 7615 struct netdev_nested_priv priv = { 7616 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO, 7617 .data = NULL, 7618 }; 7619 7620 return __netdev_upper_dev_link(dev, upper_dev, true, 7621 upper_priv, upper_info, &priv, extack); 7622 } 7623 EXPORT_SYMBOL(netdev_master_upper_dev_link); 7624 7625 static void __netdev_upper_dev_unlink(struct net_device *dev, 7626 struct net_device *upper_dev, 7627 struct netdev_nested_priv *priv) 7628 { 7629 struct netdev_notifier_changeupper_info changeupper_info = { 7630 .info = { 7631 .dev = dev, 7632 }, 7633 .upper_dev = upper_dev, 7634 .linking = false, 7635 }; 7636 7637 ASSERT_RTNL(); 7638 7639 changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev; 7640 7641 call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER, 7642 &changeupper_info.info); 7643 7644 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev); 7645 7646 call_netdevice_notifiers_info(NETDEV_CHANGEUPPER, 7647 &changeupper_info.info); 7648 7649 __netdev_update_upper_level(dev, NULL); 7650 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL); 7651 7652 __netdev_update_lower_level(upper_dev, priv); 7653 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level, 7654 priv); 7655 } 7656 7657 /** 7658 * netdev_upper_dev_unlink - Removes a link to upper device 7659 * @dev: device 7660 * @upper_dev: new upper device 7661 * 7662 * Removes a link to device which is upper to this one. The caller must hold 7663 * the RTNL lock. 7664 */ 7665 void netdev_upper_dev_unlink(struct net_device *dev, 7666 struct net_device *upper_dev) 7667 { 7668 struct netdev_nested_priv priv = { 7669 .flags = NESTED_SYNC_TODO, 7670 .data = NULL, 7671 }; 7672 7673 __netdev_upper_dev_unlink(dev, upper_dev, &priv); 7674 } 7675 EXPORT_SYMBOL(netdev_upper_dev_unlink); 7676 7677 static void __netdev_adjacent_dev_set(struct net_device *upper_dev, 7678 struct net_device *lower_dev, 7679 bool val) 7680 { 7681 struct netdev_adjacent *adj; 7682 7683 adj = __netdev_find_adj(lower_dev, &upper_dev->adj_list.lower); 7684 if (adj) 7685 adj->ignore = val; 7686 7687 adj = __netdev_find_adj(upper_dev, &lower_dev->adj_list.upper); 7688 if (adj) 7689 adj->ignore = val; 7690 } 7691 7692 static void netdev_adjacent_dev_disable(struct net_device *upper_dev, 7693 struct net_device *lower_dev) 7694 { 7695 __netdev_adjacent_dev_set(upper_dev, lower_dev, true); 7696 } 7697 7698 static void netdev_adjacent_dev_enable(struct net_device *upper_dev, 7699 struct net_device *lower_dev) 7700 { 7701 __netdev_adjacent_dev_set(upper_dev, lower_dev, false); 7702 } 7703 7704 int netdev_adjacent_change_prepare(struct net_device *old_dev, 7705 struct net_device *new_dev, 7706 struct net_device *dev, 7707 struct netlink_ext_ack *extack) 7708 { 7709 struct netdev_nested_priv priv = { 7710 .flags = 0, 7711 .data = NULL, 7712 }; 7713 int err; 7714 7715 if (!new_dev) 7716 return 0; 7717 7718 if (old_dev && new_dev != old_dev) 7719 netdev_adjacent_dev_disable(dev, old_dev); 7720 err = __netdev_upper_dev_link(new_dev, dev, false, NULL, NULL, &priv, 7721 extack); 7722 if (err) { 7723 if (old_dev && new_dev != old_dev) 7724 netdev_adjacent_dev_enable(dev, old_dev); 7725 return err; 7726 } 7727 7728 return 0; 7729 } 7730 EXPORT_SYMBOL(netdev_adjacent_change_prepare); 7731 7732 void netdev_adjacent_change_commit(struct net_device *old_dev, 7733 struct net_device *new_dev, 7734 struct net_device *dev) 7735 { 7736 struct netdev_nested_priv priv = { 7737 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO, 7738 .data = NULL, 7739 }; 7740 7741 if (!new_dev || !old_dev) 7742 return; 7743 7744 if (new_dev == old_dev) 7745 return; 7746 7747 netdev_adjacent_dev_enable(dev, old_dev); 7748 __netdev_upper_dev_unlink(old_dev, dev, &priv); 7749 } 7750 EXPORT_SYMBOL(netdev_adjacent_change_commit); 7751 7752 void netdev_adjacent_change_abort(struct net_device *old_dev, 7753 struct net_device *new_dev, 7754 struct net_device *dev) 7755 { 7756 struct netdev_nested_priv priv = { 7757 .flags = 0, 7758 .data = NULL, 7759 }; 7760 7761 if (!new_dev) 7762 return; 7763 7764 if (old_dev && new_dev != old_dev) 7765 netdev_adjacent_dev_enable(dev, old_dev); 7766 7767 __netdev_upper_dev_unlink(new_dev, dev, &priv); 7768 } 7769 EXPORT_SYMBOL(netdev_adjacent_change_abort); 7770 7771 /** 7772 * netdev_bonding_info_change - Dispatch event about slave change 7773 * @dev: device 7774 * @bonding_info: info to dispatch 7775 * 7776 * Send NETDEV_BONDING_INFO to netdev notifiers with info. 7777 * The caller must hold the RTNL lock. 7778 */ 7779 void netdev_bonding_info_change(struct net_device *dev, 7780 struct netdev_bonding_info *bonding_info) 7781 { 7782 struct netdev_notifier_bonding_info info = { 7783 .info.dev = dev, 7784 }; 7785 7786 memcpy(&info.bonding_info, bonding_info, 7787 sizeof(struct netdev_bonding_info)); 7788 call_netdevice_notifiers_info(NETDEV_BONDING_INFO, 7789 &info.info); 7790 } 7791 EXPORT_SYMBOL(netdev_bonding_info_change); 7792 7793 static int netdev_offload_xstats_enable_l3(struct net_device *dev, 7794 struct netlink_ext_ack *extack) 7795 { 7796 struct netdev_notifier_offload_xstats_info info = { 7797 .info.dev = dev, 7798 .info.extack = extack, 7799 .type = NETDEV_OFFLOAD_XSTATS_TYPE_L3, 7800 }; 7801 int err; 7802 int rc; 7803 7804 dev->offload_xstats_l3 = kzalloc(sizeof(*dev->offload_xstats_l3), 7805 GFP_KERNEL); 7806 if (!dev->offload_xstats_l3) 7807 return -ENOMEM; 7808 7809 rc = call_netdevice_notifiers_info_robust(NETDEV_OFFLOAD_XSTATS_ENABLE, 7810 NETDEV_OFFLOAD_XSTATS_DISABLE, 7811 &info.info); 7812 err = notifier_to_errno(rc); 7813 if (err) 7814 goto free_stats; 7815 7816 return 0; 7817 7818 free_stats: 7819 kfree(dev->offload_xstats_l3); 7820 dev->offload_xstats_l3 = NULL; 7821 return err; 7822 } 7823 7824 int netdev_offload_xstats_enable(struct net_device *dev, 7825 enum netdev_offload_xstats_type type, 7826 struct netlink_ext_ack *extack) 7827 { 7828 ASSERT_RTNL(); 7829 7830 if (netdev_offload_xstats_enabled(dev, type)) 7831 return -EALREADY; 7832 7833 switch (type) { 7834 case NETDEV_OFFLOAD_XSTATS_TYPE_L3: 7835 return netdev_offload_xstats_enable_l3(dev, extack); 7836 } 7837 7838 WARN_ON(1); 7839 return -EINVAL; 7840 } 7841 EXPORT_SYMBOL(netdev_offload_xstats_enable); 7842 7843 static void netdev_offload_xstats_disable_l3(struct net_device *dev) 7844 { 7845 struct netdev_notifier_offload_xstats_info info = { 7846 .info.dev = dev, 7847 .type = NETDEV_OFFLOAD_XSTATS_TYPE_L3, 7848 }; 7849 7850 call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_DISABLE, 7851 &info.info); 7852 kfree(dev->offload_xstats_l3); 7853 dev->offload_xstats_l3 = NULL; 7854 } 7855 7856 int netdev_offload_xstats_disable(struct net_device *dev, 7857 enum netdev_offload_xstats_type type) 7858 { 7859 ASSERT_RTNL(); 7860 7861 if (!netdev_offload_xstats_enabled(dev, type)) 7862 return -EALREADY; 7863 7864 switch (type) { 7865 case NETDEV_OFFLOAD_XSTATS_TYPE_L3: 7866 netdev_offload_xstats_disable_l3(dev); 7867 return 0; 7868 } 7869 7870 WARN_ON(1); 7871 return -EINVAL; 7872 } 7873 EXPORT_SYMBOL(netdev_offload_xstats_disable); 7874 7875 static void netdev_offload_xstats_disable_all(struct net_device *dev) 7876 { 7877 netdev_offload_xstats_disable(dev, NETDEV_OFFLOAD_XSTATS_TYPE_L3); 7878 } 7879 7880 static struct rtnl_hw_stats64 * 7881 netdev_offload_xstats_get_ptr(const struct net_device *dev, 7882 enum netdev_offload_xstats_type type) 7883 { 7884 switch (type) { 7885 case NETDEV_OFFLOAD_XSTATS_TYPE_L3: 7886 return dev->offload_xstats_l3; 7887 } 7888 7889 WARN_ON(1); 7890 return NULL; 7891 } 7892 7893 bool netdev_offload_xstats_enabled(const struct net_device *dev, 7894 enum netdev_offload_xstats_type type) 7895 { 7896 ASSERT_RTNL(); 7897 7898 return netdev_offload_xstats_get_ptr(dev, type); 7899 } 7900 EXPORT_SYMBOL(netdev_offload_xstats_enabled); 7901 7902 struct netdev_notifier_offload_xstats_ru { 7903 bool used; 7904 }; 7905 7906 struct netdev_notifier_offload_xstats_rd { 7907 struct rtnl_hw_stats64 stats; 7908 bool used; 7909 }; 7910 7911 static void netdev_hw_stats64_add(struct rtnl_hw_stats64 *dest, 7912 const struct rtnl_hw_stats64 *src) 7913 { 7914 dest->rx_packets += src->rx_packets; 7915 dest->tx_packets += src->tx_packets; 7916 dest->rx_bytes += src->rx_bytes; 7917 dest->tx_bytes += src->tx_bytes; 7918 dest->rx_errors += src->rx_errors; 7919 dest->tx_errors += src->tx_errors; 7920 dest->rx_dropped += src->rx_dropped; 7921 dest->tx_dropped += src->tx_dropped; 7922 dest->multicast += src->multicast; 7923 } 7924 7925 static int netdev_offload_xstats_get_used(struct net_device *dev, 7926 enum netdev_offload_xstats_type type, 7927 bool *p_used, 7928 struct netlink_ext_ack *extack) 7929 { 7930 struct netdev_notifier_offload_xstats_ru report_used = {}; 7931 struct netdev_notifier_offload_xstats_info info = { 7932 .info.dev = dev, 7933 .info.extack = extack, 7934 .type = type, 7935 .report_used = &report_used, 7936 }; 7937 int rc; 7938 7939 WARN_ON(!netdev_offload_xstats_enabled(dev, type)); 7940 rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_USED, 7941 &info.info); 7942 *p_used = report_used.used; 7943 return notifier_to_errno(rc); 7944 } 7945 7946 static int netdev_offload_xstats_get_stats(struct net_device *dev, 7947 enum netdev_offload_xstats_type type, 7948 struct rtnl_hw_stats64 *p_stats, 7949 bool *p_used, 7950 struct netlink_ext_ack *extack) 7951 { 7952 struct netdev_notifier_offload_xstats_rd report_delta = {}; 7953 struct netdev_notifier_offload_xstats_info info = { 7954 .info.dev = dev, 7955 .info.extack = extack, 7956 .type = type, 7957 .report_delta = &report_delta, 7958 }; 7959 struct rtnl_hw_stats64 *stats; 7960 int rc; 7961 7962 stats = netdev_offload_xstats_get_ptr(dev, type); 7963 if (WARN_ON(!stats)) 7964 return -EINVAL; 7965 7966 rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_DELTA, 7967 &info.info); 7968 7969 /* Cache whatever we got, even if there was an error, otherwise the 7970 * successful stats retrievals would get lost. 7971 */ 7972 netdev_hw_stats64_add(stats, &report_delta.stats); 7973 7974 if (p_stats) 7975 *p_stats = *stats; 7976 *p_used = report_delta.used; 7977 7978 return notifier_to_errno(rc); 7979 } 7980 7981 int netdev_offload_xstats_get(struct net_device *dev, 7982 enum netdev_offload_xstats_type type, 7983 struct rtnl_hw_stats64 *p_stats, bool *p_used, 7984 struct netlink_ext_ack *extack) 7985 { 7986 ASSERT_RTNL(); 7987 7988 if (p_stats) 7989 return netdev_offload_xstats_get_stats(dev, type, p_stats, 7990 p_used, extack); 7991 else 7992 return netdev_offload_xstats_get_used(dev, type, p_used, 7993 extack); 7994 } 7995 EXPORT_SYMBOL(netdev_offload_xstats_get); 7996 7997 void 7998 netdev_offload_xstats_report_delta(struct netdev_notifier_offload_xstats_rd *report_delta, 7999 const struct rtnl_hw_stats64 *stats) 8000 { 8001 report_delta->used = true; 8002 netdev_hw_stats64_add(&report_delta->stats, stats); 8003 } 8004 EXPORT_SYMBOL(netdev_offload_xstats_report_delta); 8005 8006 void 8007 netdev_offload_xstats_report_used(struct netdev_notifier_offload_xstats_ru *report_used) 8008 { 8009 report_used->used = true; 8010 } 8011 EXPORT_SYMBOL(netdev_offload_xstats_report_used); 8012 8013 void netdev_offload_xstats_push_delta(struct net_device *dev, 8014 enum netdev_offload_xstats_type type, 8015 const struct rtnl_hw_stats64 *p_stats) 8016 { 8017 struct rtnl_hw_stats64 *stats; 8018 8019 ASSERT_RTNL(); 8020 8021 stats = netdev_offload_xstats_get_ptr(dev, type); 8022 if (WARN_ON(!stats)) 8023 return; 8024 8025 netdev_hw_stats64_add(stats, p_stats); 8026 } 8027 EXPORT_SYMBOL(netdev_offload_xstats_push_delta); 8028 8029 /** 8030 * netdev_get_xmit_slave - Get the xmit slave of master device 8031 * @dev: device 8032 * @skb: The packet 8033 * @all_slaves: assume all the slaves are active 8034 * 8035 * The reference counters are not incremented so the caller must be 8036 * careful with locks. The caller must hold RCU lock. 8037 * %NULL is returned if no slave is found. 8038 */ 8039 8040 struct net_device *netdev_get_xmit_slave(struct net_device *dev, 8041 struct sk_buff *skb, 8042 bool all_slaves) 8043 { 8044 const struct net_device_ops *ops = dev->netdev_ops; 8045 8046 if (!ops->ndo_get_xmit_slave) 8047 return NULL; 8048 return ops->ndo_get_xmit_slave(dev, skb, all_slaves); 8049 } 8050 EXPORT_SYMBOL(netdev_get_xmit_slave); 8051 8052 static struct net_device *netdev_sk_get_lower_dev(struct net_device *dev, 8053 struct sock *sk) 8054 { 8055 const struct net_device_ops *ops = dev->netdev_ops; 8056 8057 if (!ops->ndo_sk_get_lower_dev) 8058 return NULL; 8059 return ops->ndo_sk_get_lower_dev(dev, sk); 8060 } 8061 8062 /** 8063 * netdev_sk_get_lowest_dev - Get the lowest device in chain given device and socket 8064 * @dev: device 8065 * @sk: the socket 8066 * 8067 * %NULL is returned if no lower device is found. 8068 */ 8069 8070 struct net_device *netdev_sk_get_lowest_dev(struct net_device *dev, 8071 struct sock *sk) 8072 { 8073 struct net_device *lower; 8074 8075 lower = netdev_sk_get_lower_dev(dev, sk); 8076 while (lower) { 8077 dev = lower; 8078 lower = netdev_sk_get_lower_dev(dev, sk); 8079 } 8080 8081 return dev; 8082 } 8083 EXPORT_SYMBOL(netdev_sk_get_lowest_dev); 8084 8085 static void netdev_adjacent_add_links(struct net_device *dev) 8086 { 8087 struct netdev_adjacent *iter; 8088 8089 struct net *net = dev_net(dev); 8090 8091 list_for_each_entry(iter, &dev->adj_list.upper, list) { 8092 if (!net_eq(net, dev_net(iter->dev))) 8093 continue; 8094 netdev_adjacent_sysfs_add(iter->dev, dev, 8095 &iter->dev->adj_list.lower); 8096 netdev_adjacent_sysfs_add(dev, iter->dev, 8097 &dev->adj_list.upper); 8098 } 8099 8100 list_for_each_entry(iter, &dev->adj_list.lower, list) { 8101 if (!net_eq(net, dev_net(iter->dev))) 8102 continue; 8103 netdev_adjacent_sysfs_add(iter->dev, dev, 8104 &iter->dev->adj_list.upper); 8105 netdev_adjacent_sysfs_add(dev, iter->dev, 8106 &dev->adj_list.lower); 8107 } 8108 } 8109 8110 static void netdev_adjacent_del_links(struct net_device *dev) 8111 { 8112 struct netdev_adjacent *iter; 8113 8114 struct net *net = dev_net(dev); 8115 8116 list_for_each_entry(iter, &dev->adj_list.upper, list) { 8117 if (!net_eq(net, dev_net(iter->dev))) 8118 continue; 8119 netdev_adjacent_sysfs_del(iter->dev, dev->name, 8120 &iter->dev->adj_list.lower); 8121 netdev_adjacent_sysfs_del(dev, iter->dev->name, 8122 &dev->adj_list.upper); 8123 } 8124 8125 list_for_each_entry(iter, &dev->adj_list.lower, list) { 8126 if (!net_eq(net, dev_net(iter->dev))) 8127 continue; 8128 netdev_adjacent_sysfs_del(iter->dev, dev->name, 8129 &iter->dev->adj_list.upper); 8130 netdev_adjacent_sysfs_del(dev, iter->dev->name, 8131 &dev->adj_list.lower); 8132 } 8133 } 8134 8135 void netdev_adjacent_rename_links(struct net_device *dev, char *oldname) 8136 { 8137 struct netdev_adjacent *iter; 8138 8139 struct net *net = dev_net(dev); 8140 8141 list_for_each_entry(iter, &dev->adj_list.upper, list) { 8142 if (!net_eq(net, dev_net(iter->dev))) 8143 continue; 8144 netdev_adjacent_sysfs_del(iter->dev, oldname, 8145 &iter->dev->adj_list.lower); 8146 netdev_adjacent_sysfs_add(iter->dev, dev, 8147 &iter->dev->adj_list.lower); 8148 } 8149 8150 list_for_each_entry(iter, &dev->adj_list.lower, list) { 8151 if (!net_eq(net, dev_net(iter->dev))) 8152 continue; 8153 netdev_adjacent_sysfs_del(iter->dev, oldname, 8154 &iter->dev->adj_list.upper); 8155 netdev_adjacent_sysfs_add(iter->dev, dev, 8156 &iter->dev->adj_list.upper); 8157 } 8158 } 8159 8160 void *netdev_lower_dev_get_private(struct net_device *dev, 8161 struct net_device *lower_dev) 8162 { 8163 struct netdev_adjacent *lower; 8164 8165 if (!lower_dev) 8166 return NULL; 8167 lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower); 8168 if (!lower) 8169 return NULL; 8170 8171 return lower->private; 8172 } 8173 EXPORT_SYMBOL(netdev_lower_dev_get_private); 8174 8175 8176 /** 8177 * netdev_lower_state_changed - Dispatch event about lower device state change 8178 * @lower_dev: device 8179 * @lower_state_info: state to dispatch 8180 * 8181 * Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info. 8182 * The caller must hold the RTNL lock. 8183 */ 8184 void netdev_lower_state_changed(struct net_device *lower_dev, 8185 void *lower_state_info) 8186 { 8187 struct netdev_notifier_changelowerstate_info changelowerstate_info = { 8188 .info.dev = lower_dev, 8189 }; 8190 8191 ASSERT_RTNL(); 8192 changelowerstate_info.lower_state_info = lower_state_info; 8193 call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE, 8194 &changelowerstate_info.info); 8195 } 8196 EXPORT_SYMBOL(netdev_lower_state_changed); 8197 8198 static void dev_change_rx_flags(struct net_device *dev, int flags) 8199 { 8200 const struct net_device_ops *ops = dev->netdev_ops; 8201 8202 if (ops->ndo_change_rx_flags) 8203 ops->ndo_change_rx_flags(dev, flags); 8204 } 8205 8206 static int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify) 8207 { 8208 unsigned int old_flags = dev->flags; 8209 kuid_t uid; 8210 kgid_t gid; 8211 8212 ASSERT_RTNL(); 8213 8214 dev->flags |= IFF_PROMISC; 8215 dev->promiscuity += inc; 8216 if (dev->promiscuity == 0) { 8217 /* 8218 * Avoid overflow. 8219 * If inc causes overflow, untouch promisc and return error. 8220 */ 8221 if (inc < 0) 8222 dev->flags &= ~IFF_PROMISC; 8223 else { 8224 dev->promiscuity -= inc; 8225 netdev_warn(dev, "promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n"); 8226 return -EOVERFLOW; 8227 } 8228 } 8229 if (dev->flags != old_flags) { 8230 pr_info("device %s %s promiscuous mode\n", 8231 dev->name, 8232 dev->flags & IFF_PROMISC ? "entered" : "left"); 8233 if (audit_enabled) { 8234 current_uid_gid(&uid, &gid); 8235 audit_log(audit_context(), GFP_ATOMIC, 8236 AUDIT_ANOM_PROMISCUOUS, 8237 "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u", 8238 dev->name, (dev->flags & IFF_PROMISC), 8239 (old_flags & IFF_PROMISC), 8240 from_kuid(&init_user_ns, audit_get_loginuid(current)), 8241 from_kuid(&init_user_ns, uid), 8242 from_kgid(&init_user_ns, gid), 8243 audit_get_sessionid(current)); 8244 } 8245 8246 dev_change_rx_flags(dev, IFF_PROMISC); 8247 } 8248 if (notify) 8249 __dev_notify_flags(dev, old_flags, IFF_PROMISC); 8250 return 0; 8251 } 8252 8253 /** 8254 * dev_set_promiscuity - update promiscuity count on a device 8255 * @dev: device 8256 * @inc: modifier 8257 * 8258 * Add or remove promiscuity from a device. While the count in the device 8259 * remains above zero the interface remains promiscuous. Once it hits zero 8260 * the device reverts back to normal filtering operation. A negative inc 8261 * value is used to drop promiscuity on the device. 8262 * Return 0 if successful or a negative errno code on error. 8263 */ 8264 int dev_set_promiscuity(struct net_device *dev, int inc) 8265 { 8266 unsigned int old_flags = dev->flags; 8267 int err; 8268 8269 err = __dev_set_promiscuity(dev, inc, true); 8270 if (err < 0) 8271 return err; 8272 if (dev->flags != old_flags) 8273 dev_set_rx_mode(dev); 8274 return err; 8275 } 8276 EXPORT_SYMBOL(dev_set_promiscuity); 8277 8278 static int __dev_set_allmulti(struct net_device *dev, int inc, bool notify) 8279 { 8280 unsigned int old_flags = dev->flags, old_gflags = dev->gflags; 8281 8282 ASSERT_RTNL(); 8283 8284 dev->flags |= IFF_ALLMULTI; 8285 dev->allmulti += inc; 8286 if (dev->allmulti == 0) { 8287 /* 8288 * Avoid overflow. 8289 * If inc causes overflow, untouch allmulti and return error. 8290 */ 8291 if (inc < 0) 8292 dev->flags &= ~IFF_ALLMULTI; 8293 else { 8294 dev->allmulti -= inc; 8295 netdev_warn(dev, "allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n"); 8296 return -EOVERFLOW; 8297 } 8298 } 8299 if (dev->flags ^ old_flags) { 8300 dev_change_rx_flags(dev, IFF_ALLMULTI); 8301 dev_set_rx_mode(dev); 8302 if (notify) 8303 __dev_notify_flags(dev, old_flags, 8304 dev->gflags ^ old_gflags); 8305 } 8306 return 0; 8307 } 8308 8309 /** 8310 * dev_set_allmulti - update allmulti count on a device 8311 * @dev: device 8312 * @inc: modifier 8313 * 8314 * Add or remove reception of all multicast frames to a device. While the 8315 * count in the device remains above zero the interface remains listening 8316 * to all interfaces. Once it hits zero the device reverts back to normal 8317 * filtering operation. A negative @inc value is used to drop the counter 8318 * when releasing a resource needing all multicasts. 8319 * Return 0 if successful or a negative errno code on error. 8320 */ 8321 8322 int dev_set_allmulti(struct net_device *dev, int inc) 8323 { 8324 return __dev_set_allmulti(dev, inc, true); 8325 } 8326 EXPORT_SYMBOL(dev_set_allmulti); 8327 8328 /* 8329 * Upload unicast and multicast address lists to device and 8330 * configure RX filtering. When the device doesn't support unicast 8331 * filtering it is put in promiscuous mode while unicast addresses 8332 * are present. 8333 */ 8334 void __dev_set_rx_mode(struct net_device *dev) 8335 { 8336 const struct net_device_ops *ops = dev->netdev_ops; 8337 8338 /* dev_open will call this function so the list will stay sane. */ 8339 if (!(dev->flags&IFF_UP)) 8340 return; 8341 8342 if (!netif_device_present(dev)) 8343 return; 8344 8345 if (!(dev->priv_flags & IFF_UNICAST_FLT)) { 8346 /* Unicast addresses changes may only happen under the rtnl, 8347 * therefore calling __dev_set_promiscuity here is safe. 8348 */ 8349 if (!netdev_uc_empty(dev) && !dev->uc_promisc) { 8350 __dev_set_promiscuity(dev, 1, false); 8351 dev->uc_promisc = true; 8352 } else if (netdev_uc_empty(dev) && dev->uc_promisc) { 8353 __dev_set_promiscuity(dev, -1, false); 8354 dev->uc_promisc = false; 8355 } 8356 } 8357 8358 if (ops->ndo_set_rx_mode) 8359 ops->ndo_set_rx_mode(dev); 8360 } 8361 8362 void dev_set_rx_mode(struct net_device *dev) 8363 { 8364 netif_addr_lock_bh(dev); 8365 __dev_set_rx_mode(dev); 8366 netif_addr_unlock_bh(dev); 8367 } 8368 8369 /** 8370 * dev_get_flags - get flags reported to userspace 8371 * @dev: device 8372 * 8373 * Get the combination of flag bits exported through APIs to userspace. 8374 */ 8375 unsigned int dev_get_flags(const struct net_device *dev) 8376 { 8377 unsigned int flags; 8378 8379 flags = (dev->flags & ~(IFF_PROMISC | 8380 IFF_ALLMULTI | 8381 IFF_RUNNING | 8382 IFF_LOWER_UP | 8383 IFF_DORMANT)) | 8384 (dev->gflags & (IFF_PROMISC | 8385 IFF_ALLMULTI)); 8386 8387 if (netif_running(dev)) { 8388 if (netif_oper_up(dev)) 8389 flags |= IFF_RUNNING; 8390 if (netif_carrier_ok(dev)) 8391 flags |= IFF_LOWER_UP; 8392 if (netif_dormant(dev)) 8393 flags |= IFF_DORMANT; 8394 } 8395 8396 return flags; 8397 } 8398 EXPORT_SYMBOL(dev_get_flags); 8399 8400 int __dev_change_flags(struct net_device *dev, unsigned int flags, 8401 struct netlink_ext_ack *extack) 8402 { 8403 unsigned int old_flags = dev->flags; 8404 int ret; 8405 8406 ASSERT_RTNL(); 8407 8408 /* 8409 * Set the flags on our device. 8410 */ 8411 8412 dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP | 8413 IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL | 8414 IFF_AUTOMEDIA)) | 8415 (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC | 8416 IFF_ALLMULTI)); 8417 8418 /* 8419 * Load in the correct multicast list now the flags have changed. 8420 */ 8421 8422 if ((old_flags ^ flags) & IFF_MULTICAST) 8423 dev_change_rx_flags(dev, IFF_MULTICAST); 8424 8425 dev_set_rx_mode(dev); 8426 8427 /* 8428 * Have we downed the interface. We handle IFF_UP ourselves 8429 * according to user attempts to set it, rather than blindly 8430 * setting it. 8431 */ 8432 8433 ret = 0; 8434 if ((old_flags ^ flags) & IFF_UP) { 8435 if (old_flags & IFF_UP) 8436 __dev_close(dev); 8437 else 8438 ret = __dev_open(dev, extack); 8439 } 8440 8441 if ((flags ^ dev->gflags) & IFF_PROMISC) { 8442 int inc = (flags & IFF_PROMISC) ? 1 : -1; 8443 unsigned int old_flags = dev->flags; 8444 8445 dev->gflags ^= IFF_PROMISC; 8446 8447 if (__dev_set_promiscuity(dev, inc, false) >= 0) 8448 if (dev->flags != old_flags) 8449 dev_set_rx_mode(dev); 8450 } 8451 8452 /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI 8453 * is important. Some (broken) drivers set IFF_PROMISC, when 8454 * IFF_ALLMULTI is requested not asking us and not reporting. 8455 */ 8456 if ((flags ^ dev->gflags) & IFF_ALLMULTI) { 8457 int inc = (flags & IFF_ALLMULTI) ? 1 : -1; 8458 8459 dev->gflags ^= IFF_ALLMULTI; 8460 __dev_set_allmulti(dev, inc, false); 8461 } 8462 8463 return ret; 8464 } 8465 8466 void __dev_notify_flags(struct net_device *dev, unsigned int old_flags, 8467 unsigned int gchanges) 8468 { 8469 unsigned int changes = dev->flags ^ old_flags; 8470 8471 if (gchanges) 8472 rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC); 8473 8474 if (changes & IFF_UP) { 8475 if (dev->flags & IFF_UP) 8476 call_netdevice_notifiers(NETDEV_UP, dev); 8477 else 8478 call_netdevice_notifiers(NETDEV_DOWN, dev); 8479 } 8480 8481 if (dev->flags & IFF_UP && 8482 (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) { 8483 struct netdev_notifier_change_info change_info = { 8484 .info = { 8485 .dev = dev, 8486 }, 8487 .flags_changed = changes, 8488 }; 8489 8490 call_netdevice_notifiers_info(NETDEV_CHANGE, &change_info.info); 8491 } 8492 } 8493 8494 /** 8495 * dev_change_flags - change device settings 8496 * @dev: device 8497 * @flags: device state flags 8498 * @extack: netlink extended ack 8499 * 8500 * Change settings on device based state flags. The flags are 8501 * in the userspace exported format. 8502 */ 8503 int dev_change_flags(struct net_device *dev, unsigned int flags, 8504 struct netlink_ext_ack *extack) 8505 { 8506 int ret; 8507 unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags; 8508 8509 ret = __dev_change_flags(dev, flags, extack); 8510 if (ret < 0) 8511 return ret; 8512 8513 changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags); 8514 __dev_notify_flags(dev, old_flags, changes); 8515 return ret; 8516 } 8517 EXPORT_SYMBOL(dev_change_flags); 8518 8519 int __dev_set_mtu(struct net_device *dev, int new_mtu) 8520 { 8521 const struct net_device_ops *ops = dev->netdev_ops; 8522 8523 if (ops->ndo_change_mtu) 8524 return ops->ndo_change_mtu(dev, new_mtu); 8525 8526 /* Pairs with all the lockless reads of dev->mtu in the stack */ 8527 WRITE_ONCE(dev->mtu, new_mtu); 8528 return 0; 8529 } 8530 EXPORT_SYMBOL(__dev_set_mtu); 8531 8532 int dev_validate_mtu(struct net_device *dev, int new_mtu, 8533 struct netlink_ext_ack *extack) 8534 { 8535 /* MTU must be positive, and in range */ 8536 if (new_mtu < 0 || new_mtu < dev->min_mtu) { 8537 NL_SET_ERR_MSG(extack, "mtu less than device minimum"); 8538 return -EINVAL; 8539 } 8540 8541 if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) { 8542 NL_SET_ERR_MSG(extack, "mtu greater than device maximum"); 8543 return -EINVAL; 8544 } 8545 return 0; 8546 } 8547 8548 /** 8549 * dev_set_mtu_ext - Change maximum transfer unit 8550 * @dev: device 8551 * @new_mtu: new transfer unit 8552 * @extack: netlink extended ack 8553 * 8554 * Change the maximum transfer size of the network device. 8555 */ 8556 int dev_set_mtu_ext(struct net_device *dev, int new_mtu, 8557 struct netlink_ext_ack *extack) 8558 { 8559 int err, orig_mtu; 8560 8561 if (new_mtu == dev->mtu) 8562 return 0; 8563 8564 err = dev_validate_mtu(dev, new_mtu, extack); 8565 if (err) 8566 return err; 8567 8568 if (!netif_device_present(dev)) 8569 return -ENODEV; 8570 8571 err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev); 8572 err = notifier_to_errno(err); 8573 if (err) 8574 return err; 8575 8576 orig_mtu = dev->mtu; 8577 err = __dev_set_mtu(dev, new_mtu); 8578 8579 if (!err) { 8580 err = call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev, 8581 orig_mtu); 8582 err = notifier_to_errno(err); 8583 if (err) { 8584 /* setting mtu back and notifying everyone again, 8585 * so that they have a chance to revert changes. 8586 */ 8587 __dev_set_mtu(dev, orig_mtu); 8588 call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev, 8589 new_mtu); 8590 } 8591 } 8592 return err; 8593 } 8594 8595 int dev_set_mtu(struct net_device *dev, int new_mtu) 8596 { 8597 struct netlink_ext_ack extack; 8598 int err; 8599 8600 memset(&extack, 0, sizeof(extack)); 8601 err = dev_set_mtu_ext(dev, new_mtu, &extack); 8602 if (err && extack._msg) 8603 net_err_ratelimited("%s: %s\n", dev->name, extack._msg); 8604 return err; 8605 } 8606 EXPORT_SYMBOL(dev_set_mtu); 8607 8608 /** 8609 * dev_change_tx_queue_len - Change TX queue length of a netdevice 8610 * @dev: device 8611 * @new_len: new tx queue length 8612 */ 8613 int dev_change_tx_queue_len(struct net_device *dev, unsigned long new_len) 8614 { 8615 unsigned int orig_len = dev->tx_queue_len; 8616 int res; 8617 8618 if (new_len != (unsigned int)new_len) 8619 return -ERANGE; 8620 8621 if (new_len != orig_len) { 8622 dev->tx_queue_len = new_len; 8623 res = call_netdevice_notifiers(NETDEV_CHANGE_TX_QUEUE_LEN, dev); 8624 res = notifier_to_errno(res); 8625 if (res) 8626 goto err_rollback; 8627 res = dev_qdisc_change_tx_queue_len(dev); 8628 if (res) 8629 goto err_rollback; 8630 } 8631 8632 return 0; 8633 8634 err_rollback: 8635 netdev_err(dev, "refused to change device tx_queue_len\n"); 8636 dev->tx_queue_len = orig_len; 8637 return res; 8638 } 8639 8640 /** 8641 * dev_set_group - Change group this device belongs to 8642 * @dev: device 8643 * @new_group: group this device should belong to 8644 */ 8645 void dev_set_group(struct net_device *dev, int new_group) 8646 { 8647 dev->group = new_group; 8648 } 8649 8650 /** 8651 * dev_pre_changeaddr_notify - Call NETDEV_PRE_CHANGEADDR. 8652 * @dev: device 8653 * @addr: new address 8654 * @extack: netlink extended ack 8655 */ 8656 int dev_pre_changeaddr_notify(struct net_device *dev, const char *addr, 8657 struct netlink_ext_ack *extack) 8658 { 8659 struct netdev_notifier_pre_changeaddr_info info = { 8660 .info.dev = dev, 8661 .info.extack = extack, 8662 .dev_addr = addr, 8663 }; 8664 int rc; 8665 8666 rc = call_netdevice_notifiers_info(NETDEV_PRE_CHANGEADDR, &info.info); 8667 return notifier_to_errno(rc); 8668 } 8669 EXPORT_SYMBOL(dev_pre_changeaddr_notify); 8670 8671 /** 8672 * dev_set_mac_address - Change Media Access Control Address 8673 * @dev: device 8674 * @sa: new address 8675 * @extack: netlink extended ack 8676 * 8677 * Change the hardware (MAC) address of the device 8678 */ 8679 int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa, 8680 struct netlink_ext_ack *extack) 8681 { 8682 const struct net_device_ops *ops = dev->netdev_ops; 8683 int err; 8684 8685 if (!ops->ndo_set_mac_address) 8686 return -EOPNOTSUPP; 8687 if (sa->sa_family != dev->type) 8688 return -EINVAL; 8689 if (!netif_device_present(dev)) 8690 return -ENODEV; 8691 err = dev_pre_changeaddr_notify(dev, sa->sa_data, extack); 8692 if (err) 8693 return err; 8694 err = ops->ndo_set_mac_address(dev, sa); 8695 if (err) 8696 return err; 8697 dev->addr_assign_type = NET_ADDR_SET; 8698 call_netdevice_notifiers(NETDEV_CHANGEADDR, dev); 8699 add_device_randomness(dev->dev_addr, dev->addr_len); 8700 return 0; 8701 } 8702 EXPORT_SYMBOL(dev_set_mac_address); 8703 8704 static DECLARE_RWSEM(dev_addr_sem); 8705 8706 int dev_set_mac_address_user(struct net_device *dev, struct sockaddr *sa, 8707 struct netlink_ext_ack *extack) 8708 { 8709 int ret; 8710 8711 down_write(&dev_addr_sem); 8712 ret = dev_set_mac_address(dev, sa, extack); 8713 up_write(&dev_addr_sem); 8714 return ret; 8715 } 8716 EXPORT_SYMBOL(dev_set_mac_address_user); 8717 8718 int dev_get_mac_address(struct sockaddr *sa, struct net *net, char *dev_name) 8719 { 8720 size_t size = sizeof(sa->sa_data); 8721 struct net_device *dev; 8722 int ret = 0; 8723 8724 down_read(&dev_addr_sem); 8725 rcu_read_lock(); 8726 8727 dev = dev_get_by_name_rcu(net, dev_name); 8728 if (!dev) { 8729 ret = -ENODEV; 8730 goto unlock; 8731 } 8732 if (!dev->addr_len) 8733 memset(sa->sa_data, 0, size); 8734 else 8735 memcpy(sa->sa_data, dev->dev_addr, 8736 min_t(size_t, size, dev->addr_len)); 8737 sa->sa_family = dev->type; 8738 8739 unlock: 8740 rcu_read_unlock(); 8741 up_read(&dev_addr_sem); 8742 return ret; 8743 } 8744 EXPORT_SYMBOL(dev_get_mac_address); 8745 8746 /** 8747 * dev_change_carrier - Change device carrier 8748 * @dev: device 8749 * @new_carrier: new value 8750 * 8751 * Change device carrier 8752 */ 8753 int dev_change_carrier(struct net_device *dev, bool new_carrier) 8754 { 8755 const struct net_device_ops *ops = dev->netdev_ops; 8756 8757 if (!ops->ndo_change_carrier) 8758 return -EOPNOTSUPP; 8759 if (!netif_device_present(dev)) 8760 return -ENODEV; 8761 return ops->ndo_change_carrier(dev, new_carrier); 8762 } 8763 8764 /** 8765 * dev_get_phys_port_id - Get device physical port ID 8766 * @dev: device 8767 * @ppid: port ID 8768 * 8769 * Get device physical port ID 8770 */ 8771 int dev_get_phys_port_id(struct net_device *dev, 8772 struct netdev_phys_item_id *ppid) 8773 { 8774 const struct net_device_ops *ops = dev->netdev_ops; 8775 8776 if (!ops->ndo_get_phys_port_id) 8777 return -EOPNOTSUPP; 8778 return ops->ndo_get_phys_port_id(dev, ppid); 8779 } 8780 8781 /** 8782 * dev_get_phys_port_name - Get device physical port name 8783 * @dev: device 8784 * @name: port name 8785 * @len: limit of bytes to copy to name 8786 * 8787 * Get device physical port name 8788 */ 8789 int dev_get_phys_port_name(struct net_device *dev, 8790 char *name, size_t len) 8791 { 8792 const struct net_device_ops *ops = dev->netdev_ops; 8793 int err; 8794 8795 if (ops->ndo_get_phys_port_name) { 8796 err = ops->ndo_get_phys_port_name(dev, name, len); 8797 if (err != -EOPNOTSUPP) 8798 return err; 8799 } 8800 return devlink_compat_phys_port_name_get(dev, name, len); 8801 } 8802 8803 /** 8804 * dev_get_port_parent_id - Get the device's port parent identifier 8805 * @dev: network device 8806 * @ppid: pointer to a storage for the port's parent identifier 8807 * @recurse: allow/disallow recursion to lower devices 8808 * 8809 * Get the devices's port parent identifier 8810 */ 8811 int dev_get_port_parent_id(struct net_device *dev, 8812 struct netdev_phys_item_id *ppid, 8813 bool recurse) 8814 { 8815 const struct net_device_ops *ops = dev->netdev_ops; 8816 struct netdev_phys_item_id first = { }; 8817 struct net_device *lower_dev; 8818 struct list_head *iter; 8819 int err; 8820 8821 if (ops->ndo_get_port_parent_id) { 8822 err = ops->ndo_get_port_parent_id(dev, ppid); 8823 if (err != -EOPNOTSUPP) 8824 return err; 8825 } 8826 8827 err = devlink_compat_switch_id_get(dev, ppid); 8828 if (!recurse || err != -EOPNOTSUPP) 8829 return err; 8830 8831 netdev_for_each_lower_dev(dev, lower_dev, iter) { 8832 err = dev_get_port_parent_id(lower_dev, ppid, true); 8833 if (err) 8834 break; 8835 if (!first.id_len) 8836 first = *ppid; 8837 else if (memcmp(&first, ppid, sizeof(*ppid))) 8838 return -EOPNOTSUPP; 8839 } 8840 8841 return err; 8842 } 8843 EXPORT_SYMBOL(dev_get_port_parent_id); 8844 8845 /** 8846 * netdev_port_same_parent_id - Indicate if two network devices have 8847 * the same port parent identifier 8848 * @a: first network device 8849 * @b: second network device 8850 */ 8851 bool netdev_port_same_parent_id(struct net_device *a, struct net_device *b) 8852 { 8853 struct netdev_phys_item_id a_id = { }; 8854 struct netdev_phys_item_id b_id = { }; 8855 8856 if (dev_get_port_parent_id(a, &a_id, true) || 8857 dev_get_port_parent_id(b, &b_id, true)) 8858 return false; 8859 8860 return netdev_phys_item_id_same(&a_id, &b_id); 8861 } 8862 EXPORT_SYMBOL(netdev_port_same_parent_id); 8863 8864 /** 8865 * dev_change_proto_down - set carrier according to proto_down. 8866 * 8867 * @dev: device 8868 * @proto_down: new value 8869 */ 8870 int dev_change_proto_down(struct net_device *dev, bool proto_down) 8871 { 8872 if (!(dev->priv_flags & IFF_CHANGE_PROTO_DOWN)) 8873 return -EOPNOTSUPP; 8874 if (!netif_device_present(dev)) 8875 return -ENODEV; 8876 if (proto_down) 8877 netif_carrier_off(dev); 8878 else 8879 netif_carrier_on(dev); 8880 dev->proto_down = proto_down; 8881 return 0; 8882 } 8883 8884 /** 8885 * dev_change_proto_down_reason - proto down reason 8886 * 8887 * @dev: device 8888 * @mask: proto down mask 8889 * @value: proto down value 8890 */ 8891 void dev_change_proto_down_reason(struct net_device *dev, unsigned long mask, 8892 u32 value) 8893 { 8894 int b; 8895 8896 if (!mask) { 8897 dev->proto_down_reason = value; 8898 } else { 8899 for_each_set_bit(b, &mask, 32) { 8900 if (value & (1 << b)) 8901 dev->proto_down_reason |= BIT(b); 8902 else 8903 dev->proto_down_reason &= ~BIT(b); 8904 } 8905 } 8906 } 8907 8908 struct bpf_xdp_link { 8909 struct bpf_link link; 8910 struct net_device *dev; /* protected by rtnl_lock, no refcnt held */ 8911 int flags; 8912 }; 8913 8914 static enum bpf_xdp_mode dev_xdp_mode(struct net_device *dev, u32 flags) 8915 { 8916 if (flags & XDP_FLAGS_HW_MODE) 8917 return XDP_MODE_HW; 8918 if (flags & XDP_FLAGS_DRV_MODE) 8919 return XDP_MODE_DRV; 8920 if (flags & XDP_FLAGS_SKB_MODE) 8921 return XDP_MODE_SKB; 8922 return dev->netdev_ops->ndo_bpf ? XDP_MODE_DRV : XDP_MODE_SKB; 8923 } 8924 8925 static bpf_op_t dev_xdp_bpf_op(struct net_device *dev, enum bpf_xdp_mode mode) 8926 { 8927 switch (mode) { 8928 case XDP_MODE_SKB: 8929 return generic_xdp_install; 8930 case XDP_MODE_DRV: 8931 case XDP_MODE_HW: 8932 return dev->netdev_ops->ndo_bpf; 8933 default: 8934 return NULL; 8935 } 8936 } 8937 8938 static struct bpf_xdp_link *dev_xdp_link(struct net_device *dev, 8939 enum bpf_xdp_mode mode) 8940 { 8941 return dev->xdp_state[mode].link; 8942 } 8943 8944 static struct bpf_prog *dev_xdp_prog(struct net_device *dev, 8945 enum bpf_xdp_mode mode) 8946 { 8947 struct bpf_xdp_link *link = dev_xdp_link(dev, mode); 8948 8949 if (link) 8950 return link->link.prog; 8951 return dev->xdp_state[mode].prog; 8952 } 8953 8954 u8 dev_xdp_prog_count(struct net_device *dev) 8955 { 8956 u8 count = 0; 8957 int i; 8958 8959 for (i = 0; i < __MAX_XDP_MODE; i++) 8960 if (dev->xdp_state[i].prog || dev->xdp_state[i].link) 8961 count++; 8962 return count; 8963 } 8964 EXPORT_SYMBOL_GPL(dev_xdp_prog_count); 8965 8966 u32 dev_xdp_prog_id(struct net_device *dev, enum bpf_xdp_mode mode) 8967 { 8968 struct bpf_prog *prog = dev_xdp_prog(dev, mode); 8969 8970 return prog ? prog->aux->id : 0; 8971 } 8972 8973 static void dev_xdp_set_link(struct net_device *dev, enum bpf_xdp_mode mode, 8974 struct bpf_xdp_link *link) 8975 { 8976 dev->xdp_state[mode].link = link; 8977 dev->xdp_state[mode].prog = NULL; 8978 } 8979 8980 static void dev_xdp_set_prog(struct net_device *dev, enum bpf_xdp_mode mode, 8981 struct bpf_prog *prog) 8982 { 8983 dev->xdp_state[mode].link = NULL; 8984 dev->xdp_state[mode].prog = prog; 8985 } 8986 8987 static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode, 8988 bpf_op_t bpf_op, struct netlink_ext_ack *extack, 8989 u32 flags, struct bpf_prog *prog) 8990 { 8991 struct netdev_bpf xdp; 8992 int err; 8993 8994 memset(&xdp, 0, sizeof(xdp)); 8995 xdp.command = mode == XDP_MODE_HW ? XDP_SETUP_PROG_HW : XDP_SETUP_PROG; 8996 xdp.extack = extack; 8997 xdp.flags = flags; 8998 xdp.prog = prog; 8999 9000 /* Drivers assume refcnt is already incremented (i.e, prog pointer is 9001 * "moved" into driver), so they don't increment it on their own, but 9002 * they do decrement refcnt when program is detached or replaced. 9003 * Given net_device also owns link/prog, we need to bump refcnt here 9004 * to prevent drivers from underflowing it. 9005 */ 9006 if (prog) 9007 bpf_prog_inc(prog); 9008 err = bpf_op(dev, &xdp); 9009 if (err) { 9010 if (prog) 9011 bpf_prog_put(prog); 9012 return err; 9013 } 9014 9015 if (mode != XDP_MODE_HW) 9016 bpf_prog_change_xdp(dev_xdp_prog(dev, mode), prog); 9017 9018 return 0; 9019 } 9020 9021 static void dev_xdp_uninstall(struct net_device *dev) 9022 { 9023 struct bpf_xdp_link *link; 9024 struct bpf_prog *prog; 9025 enum bpf_xdp_mode mode; 9026 bpf_op_t bpf_op; 9027 9028 ASSERT_RTNL(); 9029 9030 for (mode = XDP_MODE_SKB; mode < __MAX_XDP_MODE; mode++) { 9031 prog = dev_xdp_prog(dev, mode); 9032 if (!prog) 9033 continue; 9034 9035 bpf_op = dev_xdp_bpf_op(dev, mode); 9036 if (!bpf_op) 9037 continue; 9038 9039 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL)); 9040 9041 /* auto-detach link from net device */ 9042 link = dev_xdp_link(dev, mode); 9043 if (link) 9044 link->dev = NULL; 9045 else 9046 bpf_prog_put(prog); 9047 9048 dev_xdp_set_link(dev, mode, NULL); 9049 } 9050 } 9051 9052 static int dev_xdp_attach(struct net_device *dev, struct netlink_ext_ack *extack, 9053 struct bpf_xdp_link *link, struct bpf_prog *new_prog, 9054 struct bpf_prog *old_prog, u32 flags) 9055 { 9056 unsigned int num_modes = hweight32(flags & XDP_FLAGS_MODES); 9057 struct bpf_prog *cur_prog; 9058 struct net_device *upper; 9059 struct list_head *iter; 9060 enum bpf_xdp_mode mode; 9061 bpf_op_t bpf_op; 9062 int err; 9063 9064 ASSERT_RTNL(); 9065 9066 /* either link or prog attachment, never both */ 9067 if (link && (new_prog || old_prog)) 9068 return -EINVAL; 9069 /* link supports only XDP mode flags */ 9070 if (link && (flags & ~XDP_FLAGS_MODES)) { 9071 NL_SET_ERR_MSG(extack, "Invalid XDP flags for BPF link attachment"); 9072 return -EINVAL; 9073 } 9074 /* just one XDP mode bit should be set, zero defaults to drv/skb mode */ 9075 if (num_modes > 1) { 9076 NL_SET_ERR_MSG(extack, "Only one XDP mode flag can be set"); 9077 return -EINVAL; 9078 } 9079 /* avoid ambiguity if offload + drv/skb mode progs are both loaded */ 9080 if (!num_modes && dev_xdp_prog_count(dev) > 1) { 9081 NL_SET_ERR_MSG(extack, 9082 "More than one program loaded, unset mode is ambiguous"); 9083 return -EINVAL; 9084 } 9085 /* old_prog != NULL implies XDP_FLAGS_REPLACE is set */ 9086 if (old_prog && !(flags & XDP_FLAGS_REPLACE)) { 9087 NL_SET_ERR_MSG(extack, "XDP_FLAGS_REPLACE is not specified"); 9088 return -EINVAL; 9089 } 9090 9091 mode = dev_xdp_mode(dev, flags); 9092 /* can't replace attached link */ 9093 if (dev_xdp_link(dev, mode)) { 9094 NL_SET_ERR_MSG(extack, "Can't replace active BPF XDP link"); 9095 return -EBUSY; 9096 } 9097 9098 /* don't allow if an upper device already has a program */ 9099 netdev_for_each_upper_dev_rcu(dev, upper, iter) { 9100 if (dev_xdp_prog_count(upper) > 0) { 9101 NL_SET_ERR_MSG(extack, "Cannot attach when an upper device already has a program"); 9102 return -EEXIST; 9103 } 9104 } 9105 9106 cur_prog = dev_xdp_prog(dev, mode); 9107 /* can't replace attached prog with link */ 9108 if (link && cur_prog) { 9109 NL_SET_ERR_MSG(extack, "Can't replace active XDP program with BPF link"); 9110 return -EBUSY; 9111 } 9112 if ((flags & XDP_FLAGS_REPLACE) && cur_prog != old_prog) { 9113 NL_SET_ERR_MSG(extack, "Active program does not match expected"); 9114 return -EEXIST; 9115 } 9116 9117 /* put effective new program into new_prog */ 9118 if (link) 9119 new_prog = link->link.prog; 9120 9121 if (new_prog) { 9122 bool offload = mode == XDP_MODE_HW; 9123 enum bpf_xdp_mode other_mode = mode == XDP_MODE_SKB 9124 ? XDP_MODE_DRV : XDP_MODE_SKB; 9125 9126 if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) && cur_prog) { 9127 NL_SET_ERR_MSG(extack, "XDP program already attached"); 9128 return -EBUSY; 9129 } 9130 if (!offload && dev_xdp_prog(dev, other_mode)) { 9131 NL_SET_ERR_MSG(extack, "Native and generic XDP can't be active at the same time"); 9132 return -EEXIST; 9133 } 9134 if (!offload && bpf_prog_is_dev_bound(new_prog->aux)) { 9135 NL_SET_ERR_MSG(extack, "Using device-bound program without HW_MODE flag is not supported"); 9136 return -EINVAL; 9137 } 9138 if (new_prog->expected_attach_type == BPF_XDP_DEVMAP) { 9139 NL_SET_ERR_MSG(extack, "BPF_XDP_DEVMAP programs can not be attached to a device"); 9140 return -EINVAL; 9141 } 9142 if (new_prog->expected_attach_type == BPF_XDP_CPUMAP) { 9143 NL_SET_ERR_MSG(extack, "BPF_XDP_CPUMAP programs can not be attached to a device"); 9144 return -EINVAL; 9145 } 9146 } 9147 9148 /* don't call drivers if the effective program didn't change */ 9149 if (new_prog != cur_prog) { 9150 bpf_op = dev_xdp_bpf_op(dev, mode); 9151 if (!bpf_op) { 9152 NL_SET_ERR_MSG(extack, "Underlying driver does not support XDP in native mode"); 9153 return -EOPNOTSUPP; 9154 } 9155 9156 err = dev_xdp_install(dev, mode, bpf_op, extack, flags, new_prog); 9157 if (err) 9158 return err; 9159 } 9160 9161 if (link) 9162 dev_xdp_set_link(dev, mode, link); 9163 else 9164 dev_xdp_set_prog(dev, mode, new_prog); 9165 if (cur_prog) 9166 bpf_prog_put(cur_prog); 9167 9168 return 0; 9169 } 9170 9171 static int dev_xdp_attach_link(struct net_device *dev, 9172 struct netlink_ext_ack *extack, 9173 struct bpf_xdp_link *link) 9174 { 9175 return dev_xdp_attach(dev, extack, link, NULL, NULL, link->flags); 9176 } 9177 9178 static int dev_xdp_detach_link(struct net_device *dev, 9179 struct netlink_ext_ack *extack, 9180 struct bpf_xdp_link *link) 9181 { 9182 enum bpf_xdp_mode mode; 9183 bpf_op_t bpf_op; 9184 9185 ASSERT_RTNL(); 9186 9187 mode = dev_xdp_mode(dev, link->flags); 9188 if (dev_xdp_link(dev, mode) != link) 9189 return -EINVAL; 9190 9191 bpf_op = dev_xdp_bpf_op(dev, mode); 9192 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL)); 9193 dev_xdp_set_link(dev, mode, NULL); 9194 return 0; 9195 } 9196 9197 static void bpf_xdp_link_release(struct bpf_link *link) 9198 { 9199 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link); 9200 9201 rtnl_lock(); 9202 9203 /* if racing with net_device's tear down, xdp_link->dev might be 9204 * already NULL, in which case link was already auto-detached 9205 */ 9206 if (xdp_link->dev) { 9207 WARN_ON(dev_xdp_detach_link(xdp_link->dev, NULL, xdp_link)); 9208 xdp_link->dev = NULL; 9209 } 9210 9211 rtnl_unlock(); 9212 } 9213 9214 static int bpf_xdp_link_detach(struct bpf_link *link) 9215 { 9216 bpf_xdp_link_release(link); 9217 return 0; 9218 } 9219 9220 static void bpf_xdp_link_dealloc(struct bpf_link *link) 9221 { 9222 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link); 9223 9224 kfree(xdp_link); 9225 } 9226 9227 static void bpf_xdp_link_show_fdinfo(const struct bpf_link *link, 9228 struct seq_file *seq) 9229 { 9230 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link); 9231 u32 ifindex = 0; 9232 9233 rtnl_lock(); 9234 if (xdp_link->dev) 9235 ifindex = xdp_link->dev->ifindex; 9236 rtnl_unlock(); 9237 9238 seq_printf(seq, "ifindex:\t%u\n", ifindex); 9239 } 9240 9241 static int bpf_xdp_link_fill_link_info(const struct bpf_link *link, 9242 struct bpf_link_info *info) 9243 { 9244 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link); 9245 u32 ifindex = 0; 9246 9247 rtnl_lock(); 9248 if (xdp_link->dev) 9249 ifindex = xdp_link->dev->ifindex; 9250 rtnl_unlock(); 9251 9252 info->xdp.ifindex = ifindex; 9253 return 0; 9254 } 9255 9256 static int bpf_xdp_link_update(struct bpf_link *link, struct bpf_prog *new_prog, 9257 struct bpf_prog *old_prog) 9258 { 9259 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link); 9260 enum bpf_xdp_mode mode; 9261 bpf_op_t bpf_op; 9262 int err = 0; 9263 9264 rtnl_lock(); 9265 9266 /* link might have been auto-released already, so fail */ 9267 if (!xdp_link->dev) { 9268 err = -ENOLINK; 9269 goto out_unlock; 9270 } 9271 9272 if (old_prog && link->prog != old_prog) { 9273 err = -EPERM; 9274 goto out_unlock; 9275 } 9276 old_prog = link->prog; 9277 if (old_prog->type != new_prog->type || 9278 old_prog->expected_attach_type != new_prog->expected_attach_type) { 9279 err = -EINVAL; 9280 goto out_unlock; 9281 } 9282 9283 if (old_prog == new_prog) { 9284 /* no-op, don't disturb drivers */ 9285 bpf_prog_put(new_prog); 9286 goto out_unlock; 9287 } 9288 9289 mode = dev_xdp_mode(xdp_link->dev, xdp_link->flags); 9290 bpf_op = dev_xdp_bpf_op(xdp_link->dev, mode); 9291 err = dev_xdp_install(xdp_link->dev, mode, bpf_op, NULL, 9292 xdp_link->flags, new_prog); 9293 if (err) 9294 goto out_unlock; 9295 9296 old_prog = xchg(&link->prog, new_prog); 9297 bpf_prog_put(old_prog); 9298 9299 out_unlock: 9300 rtnl_unlock(); 9301 return err; 9302 } 9303 9304 static const struct bpf_link_ops bpf_xdp_link_lops = { 9305 .release = bpf_xdp_link_release, 9306 .dealloc = bpf_xdp_link_dealloc, 9307 .detach = bpf_xdp_link_detach, 9308 .show_fdinfo = bpf_xdp_link_show_fdinfo, 9309 .fill_link_info = bpf_xdp_link_fill_link_info, 9310 .update_prog = bpf_xdp_link_update, 9311 }; 9312 9313 int bpf_xdp_link_attach(const union bpf_attr *attr, struct bpf_prog *prog) 9314 { 9315 struct net *net = current->nsproxy->net_ns; 9316 struct bpf_link_primer link_primer; 9317 struct bpf_xdp_link *link; 9318 struct net_device *dev; 9319 int err, fd; 9320 9321 rtnl_lock(); 9322 dev = dev_get_by_index(net, attr->link_create.target_ifindex); 9323 if (!dev) { 9324 rtnl_unlock(); 9325 return -EINVAL; 9326 } 9327 9328 link = kzalloc(sizeof(*link), GFP_USER); 9329 if (!link) { 9330 err = -ENOMEM; 9331 goto unlock; 9332 } 9333 9334 bpf_link_init(&link->link, BPF_LINK_TYPE_XDP, &bpf_xdp_link_lops, prog); 9335 link->dev = dev; 9336 link->flags = attr->link_create.flags; 9337 9338 err = bpf_link_prime(&link->link, &link_primer); 9339 if (err) { 9340 kfree(link); 9341 goto unlock; 9342 } 9343 9344 err = dev_xdp_attach_link(dev, NULL, link); 9345 rtnl_unlock(); 9346 9347 if (err) { 9348 link->dev = NULL; 9349 bpf_link_cleanup(&link_primer); 9350 goto out_put_dev; 9351 } 9352 9353 fd = bpf_link_settle(&link_primer); 9354 /* link itself doesn't hold dev's refcnt to not complicate shutdown */ 9355 dev_put(dev); 9356 return fd; 9357 9358 unlock: 9359 rtnl_unlock(); 9360 9361 out_put_dev: 9362 dev_put(dev); 9363 return err; 9364 } 9365 9366 /** 9367 * dev_change_xdp_fd - set or clear a bpf program for a device rx path 9368 * @dev: device 9369 * @extack: netlink extended ack 9370 * @fd: new program fd or negative value to clear 9371 * @expected_fd: old program fd that userspace expects to replace or clear 9372 * @flags: xdp-related flags 9373 * 9374 * Set or clear a bpf program for a device 9375 */ 9376 int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack, 9377 int fd, int expected_fd, u32 flags) 9378 { 9379 enum bpf_xdp_mode mode = dev_xdp_mode(dev, flags); 9380 struct bpf_prog *new_prog = NULL, *old_prog = NULL; 9381 int err; 9382 9383 ASSERT_RTNL(); 9384 9385 if (fd >= 0) { 9386 new_prog = bpf_prog_get_type_dev(fd, BPF_PROG_TYPE_XDP, 9387 mode != XDP_MODE_SKB); 9388 if (IS_ERR(new_prog)) 9389 return PTR_ERR(new_prog); 9390 } 9391 9392 if (expected_fd >= 0) { 9393 old_prog = bpf_prog_get_type_dev(expected_fd, BPF_PROG_TYPE_XDP, 9394 mode != XDP_MODE_SKB); 9395 if (IS_ERR(old_prog)) { 9396 err = PTR_ERR(old_prog); 9397 old_prog = NULL; 9398 goto err_out; 9399 } 9400 } 9401 9402 err = dev_xdp_attach(dev, extack, NULL, new_prog, old_prog, flags); 9403 9404 err_out: 9405 if (err && new_prog) 9406 bpf_prog_put(new_prog); 9407 if (old_prog) 9408 bpf_prog_put(old_prog); 9409 return err; 9410 } 9411 9412 /** 9413 * dev_new_index - allocate an ifindex 9414 * @net: the applicable net namespace 9415 * 9416 * Returns a suitable unique value for a new device interface 9417 * number. The caller must hold the rtnl semaphore or the 9418 * dev_base_lock to be sure it remains unique. 9419 */ 9420 static int dev_new_index(struct net *net) 9421 { 9422 int ifindex = net->ifindex; 9423 9424 for (;;) { 9425 if (++ifindex <= 0) 9426 ifindex = 1; 9427 if (!__dev_get_by_index(net, ifindex)) 9428 return net->ifindex = ifindex; 9429 } 9430 } 9431 9432 /* Delayed registration/unregisteration */ 9433 LIST_HEAD(net_todo_list); 9434 DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq); 9435 9436 static void net_set_todo(struct net_device *dev) 9437 { 9438 list_add_tail(&dev->todo_list, &net_todo_list); 9439 atomic_inc(&dev_net(dev)->dev_unreg_count); 9440 } 9441 9442 static netdev_features_t netdev_sync_upper_features(struct net_device *lower, 9443 struct net_device *upper, netdev_features_t features) 9444 { 9445 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES; 9446 netdev_features_t feature; 9447 int feature_bit; 9448 9449 for_each_netdev_feature(upper_disables, feature_bit) { 9450 feature = __NETIF_F_BIT(feature_bit); 9451 if (!(upper->wanted_features & feature) 9452 && (features & feature)) { 9453 netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n", 9454 &feature, upper->name); 9455 features &= ~feature; 9456 } 9457 } 9458 9459 return features; 9460 } 9461 9462 static void netdev_sync_lower_features(struct net_device *upper, 9463 struct net_device *lower, netdev_features_t features) 9464 { 9465 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES; 9466 netdev_features_t feature; 9467 int feature_bit; 9468 9469 for_each_netdev_feature(upper_disables, feature_bit) { 9470 feature = __NETIF_F_BIT(feature_bit); 9471 if (!(features & feature) && (lower->features & feature)) { 9472 netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n", 9473 &feature, lower->name); 9474 lower->wanted_features &= ~feature; 9475 __netdev_update_features(lower); 9476 9477 if (unlikely(lower->features & feature)) 9478 netdev_WARN(upper, "failed to disable %pNF on %s!\n", 9479 &feature, lower->name); 9480 else 9481 netdev_features_change(lower); 9482 } 9483 } 9484 } 9485 9486 static netdev_features_t netdev_fix_features(struct net_device *dev, 9487 netdev_features_t features) 9488 { 9489 /* Fix illegal checksum combinations */ 9490 if ((features & NETIF_F_HW_CSUM) && 9491 (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) { 9492 netdev_warn(dev, "mixed HW and IP checksum settings.\n"); 9493 features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM); 9494 } 9495 9496 /* TSO requires that SG is present as well. */ 9497 if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) { 9498 netdev_dbg(dev, "Dropping TSO features since no SG feature.\n"); 9499 features &= ~NETIF_F_ALL_TSO; 9500 } 9501 9502 if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) && 9503 !(features & NETIF_F_IP_CSUM)) { 9504 netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n"); 9505 features &= ~NETIF_F_TSO; 9506 features &= ~NETIF_F_TSO_ECN; 9507 } 9508 9509 if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) && 9510 !(features & NETIF_F_IPV6_CSUM)) { 9511 netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n"); 9512 features &= ~NETIF_F_TSO6; 9513 } 9514 9515 /* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */ 9516 if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO)) 9517 features &= ~NETIF_F_TSO_MANGLEID; 9518 9519 /* TSO ECN requires that TSO is present as well. */ 9520 if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN) 9521 features &= ~NETIF_F_TSO_ECN; 9522 9523 /* Software GSO depends on SG. */ 9524 if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) { 9525 netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n"); 9526 features &= ~NETIF_F_GSO; 9527 } 9528 9529 /* GSO partial features require GSO partial be set */ 9530 if ((features & dev->gso_partial_features) && 9531 !(features & NETIF_F_GSO_PARTIAL)) { 9532 netdev_dbg(dev, 9533 "Dropping partially supported GSO features since no GSO partial.\n"); 9534 features &= ~dev->gso_partial_features; 9535 } 9536 9537 if (!(features & NETIF_F_RXCSUM)) { 9538 /* NETIF_F_GRO_HW implies doing RXCSUM since every packet 9539 * successfully merged by hardware must also have the 9540 * checksum verified by hardware. If the user does not 9541 * want to enable RXCSUM, logically, we should disable GRO_HW. 9542 */ 9543 if (features & NETIF_F_GRO_HW) { 9544 netdev_dbg(dev, "Dropping NETIF_F_GRO_HW since no RXCSUM feature.\n"); 9545 features &= ~NETIF_F_GRO_HW; 9546 } 9547 } 9548 9549 /* LRO/HW-GRO features cannot be combined with RX-FCS */ 9550 if (features & NETIF_F_RXFCS) { 9551 if (features & NETIF_F_LRO) { 9552 netdev_dbg(dev, "Dropping LRO feature since RX-FCS is requested.\n"); 9553 features &= ~NETIF_F_LRO; 9554 } 9555 9556 if (features & NETIF_F_GRO_HW) { 9557 netdev_dbg(dev, "Dropping HW-GRO feature since RX-FCS is requested.\n"); 9558 features &= ~NETIF_F_GRO_HW; 9559 } 9560 } 9561 9562 if ((features & NETIF_F_GRO_HW) && (features & NETIF_F_LRO)) { 9563 netdev_dbg(dev, "Dropping LRO feature since HW-GRO is requested.\n"); 9564 features &= ~NETIF_F_LRO; 9565 } 9566 9567 if (features & NETIF_F_HW_TLS_TX) { 9568 bool ip_csum = (features & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM)) == 9569 (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM); 9570 bool hw_csum = features & NETIF_F_HW_CSUM; 9571 9572 if (!ip_csum && !hw_csum) { 9573 netdev_dbg(dev, "Dropping TLS TX HW offload feature since no CSUM feature.\n"); 9574 features &= ~NETIF_F_HW_TLS_TX; 9575 } 9576 } 9577 9578 if ((features & NETIF_F_HW_TLS_RX) && !(features & NETIF_F_RXCSUM)) { 9579 netdev_dbg(dev, "Dropping TLS RX HW offload feature since no RXCSUM feature.\n"); 9580 features &= ~NETIF_F_HW_TLS_RX; 9581 } 9582 9583 return features; 9584 } 9585 9586 int __netdev_update_features(struct net_device *dev) 9587 { 9588 struct net_device *upper, *lower; 9589 netdev_features_t features; 9590 struct list_head *iter; 9591 int err = -1; 9592 9593 ASSERT_RTNL(); 9594 9595 features = netdev_get_wanted_features(dev); 9596 9597 if (dev->netdev_ops->ndo_fix_features) 9598 features = dev->netdev_ops->ndo_fix_features(dev, features); 9599 9600 /* driver might be less strict about feature dependencies */ 9601 features = netdev_fix_features(dev, features); 9602 9603 /* some features can't be enabled if they're off on an upper device */ 9604 netdev_for_each_upper_dev_rcu(dev, upper, iter) 9605 features = netdev_sync_upper_features(dev, upper, features); 9606 9607 if (dev->features == features) 9608 goto sync_lower; 9609 9610 netdev_dbg(dev, "Features changed: %pNF -> %pNF\n", 9611 &dev->features, &features); 9612 9613 if (dev->netdev_ops->ndo_set_features) 9614 err = dev->netdev_ops->ndo_set_features(dev, features); 9615 else 9616 err = 0; 9617 9618 if (unlikely(err < 0)) { 9619 netdev_err(dev, 9620 "set_features() failed (%d); wanted %pNF, left %pNF\n", 9621 err, &features, &dev->features); 9622 /* return non-0 since some features might have changed and 9623 * it's better to fire a spurious notification than miss it 9624 */ 9625 return -1; 9626 } 9627 9628 sync_lower: 9629 /* some features must be disabled on lower devices when disabled 9630 * on an upper device (think: bonding master or bridge) 9631 */ 9632 netdev_for_each_lower_dev(dev, lower, iter) 9633 netdev_sync_lower_features(dev, lower, features); 9634 9635 if (!err) { 9636 netdev_features_t diff = features ^ dev->features; 9637 9638 if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) { 9639 /* udp_tunnel_{get,drop}_rx_info both need 9640 * NETIF_F_RX_UDP_TUNNEL_PORT enabled on the 9641 * device, or they won't do anything. 9642 * Thus we need to update dev->features 9643 * *before* calling udp_tunnel_get_rx_info, 9644 * but *after* calling udp_tunnel_drop_rx_info. 9645 */ 9646 if (features & NETIF_F_RX_UDP_TUNNEL_PORT) { 9647 dev->features = features; 9648 udp_tunnel_get_rx_info(dev); 9649 } else { 9650 udp_tunnel_drop_rx_info(dev); 9651 } 9652 } 9653 9654 if (diff & NETIF_F_HW_VLAN_CTAG_FILTER) { 9655 if (features & NETIF_F_HW_VLAN_CTAG_FILTER) { 9656 dev->features = features; 9657 err |= vlan_get_rx_ctag_filter_info(dev); 9658 } else { 9659 vlan_drop_rx_ctag_filter_info(dev); 9660 } 9661 } 9662 9663 if (diff & NETIF_F_HW_VLAN_STAG_FILTER) { 9664 if (features & NETIF_F_HW_VLAN_STAG_FILTER) { 9665 dev->features = features; 9666 err |= vlan_get_rx_stag_filter_info(dev); 9667 } else { 9668 vlan_drop_rx_stag_filter_info(dev); 9669 } 9670 } 9671 9672 dev->features = features; 9673 } 9674 9675 return err < 0 ? 0 : 1; 9676 } 9677 9678 /** 9679 * netdev_update_features - recalculate device features 9680 * @dev: the device to check 9681 * 9682 * Recalculate dev->features set and send notifications if it 9683 * has changed. Should be called after driver or hardware dependent 9684 * conditions might have changed that influence the features. 9685 */ 9686 void netdev_update_features(struct net_device *dev) 9687 { 9688 if (__netdev_update_features(dev)) 9689 netdev_features_change(dev); 9690 } 9691 EXPORT_SYMBOL(netdev_update_features); 9692 9693 /** 9694 * netdev_change_features - recalculate device features 9695 * @dev: the device to check 9696 * 9697 * Recalculate dev->features set and send notifications even 9698 * if they have not changed. Should be called instead of 9699 * netdev_update_features() if also dev->vlan_features might 9700 * have changed to allow the changes to be propagated to stacked 9701 * VLAN devices. 9702 */ 9703 void netdev_change_features(struct net_device *dev) 9704 { 9705 __netdev_update_features(dev); 9706 netdev_features_change(dev); 9707 } 9708 EXPORT_SYMBOL(netdev_change_features); 9709 9710 /** 9711 * netif_stacked_transfer_operstate - transfer operstate 9712 * @rootdev: the root or lower level device to transfer state from 9713 * @dev: the device to transfer operstate to 9714 * 9715 * Transfer operational state from root to device. This is normally 9716 * called when a stacking relationship exists between the root 9717 * device and the device(a leaf device). 9718 */ 9719 void netif_stacked_transfer_operstate(const struct net_device *rootdev, 9720 struct net_device *dev) 9721 { 9722 if (rootdev->operstate == IF_OPER_DORMANT) 9723 netif_dormant_on(dev); 9724 else 9725 netif_dormant_off(dev); 9726 9727 if (rootdev->operstate == IF_OPER_TESTING) 9728 netif_testing_on(dev); 9729 else 9730 netif_testing_off(dev); 9731 9732 if (netif_carrier_ok(rootdev)) 9733 netif_carrier_on(dev); 9734 else 9735 netif_carrier_off(dev); 9736 } 9737 EXPORT_SYMBOL(netif_stacked_transfer_operstate); 9738 9739 static int netif_alloc_rx_queues(struct net_device *dev) 9740 { 9741 unsigned int i, count = dev->num_rx_queues; 9742 struct netdev_rx_queue *rx; 9743 size_t sz = count * sizeof(*rx); 9744 int err = 0; 9745 9746 BUG_ON(count < 1); 9747 9748 rx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL); 9749 if (!rx) 9750 return -ENOMEM; 9751 9752 dev->_rx = rx; 9753 9754 for (i = 0; i < count; i++) { 9755 rx[i].dev = dev; 9756 9757 /* XDP RX-queue setup */ 9758 err = xdp_rxq_info_reg(&rx[i].xdp_rxq, dev, i, 0); 9759 if (err < 0) 9760 goto err_rxq_info; 9761 } 9762 return 0; 9763 9764 err_rxq_info: 9765 /* Rollback successful reg's and free other resources */ 9766 while (i--) 9767 xdp_rxq_info_unreg(&rx[i].xdp_rxq); 9768 kvfree(dev->_rx); 9769 dev->_rx = NULL; 9770 return err; 9771 } 9772 9773 static void netif_free_rx_queues(struct net_device *dev) 9774 { 9775 unsigned int i, count = dev->num_rx_queues; 9776 9777 /* netif_alloc_rx_queues alloc failed, resources have been unreg'ed */ 9778 if (!dev->_rx) 9779 return; 9780 9781 for (i = 0; i < count; i++) 9782 xdp_rxq_info_unreg(&dev->_rx[i].xdp_rxq); 9783 9784 kvfree(dev->_rx); 9785 } 9786 9787 static void netdev_init_one_queue(struct net_device *dev, 9788 struct netdev_queue *queue, void *_unused) 9789 { 9790 /* Initialize queue lock */ 9791 spin_lock_init(&queue->_xmit_lock); 9792 netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type); 9793 queue->xmit_lock_owner = -1; 9794 netdev_queue_numa_node_write(queue, NUMA_NO_NODE); 9795 queue->dev = dev; 9796 #ifdef CONFIG_BQL 9797 dql_init(&queue->dql, HZ); 9798 #endif 9799 } 9800 9801 static void netif_free_tx_queues(struct net_device *dev) 9802 { 9803 kvfree(dev->_tx); 9804 } 9805 9806 static int netif_alloc_netdev_queues(struct net_device *dev) 9807 { 9808 unsigned int count = dev->num_tx_queues; 9809 struct netdev_queue *tx; 9810 size_t sz = count * sizeof(*tx); 9811 9812 if (count < 1 || count > 0xffff) 9813 return -EINVAL; 9814 9815 tx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL); 9816 if (!tx) 9817 return -ENOMEM; 9818 9819 dev->_tx = tx; 9820 9821 netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL); 9822 spin_lock_init(&dev->tx_global_lock); 9823 9824 return 0; 9825 } 9826 9827 void netif_tx_stop_all_queues(struct net_device *dev) 9828 { 9829 unsigned int i; 9830 9831 for (i = 0; i < dev->num_tx_queues; i++) { 9832 struct netdev_queue *txq = netdev_get_tx_queue(dev, i); 9833 9834 netif_tx_stop_queue(txq); 9835 } 9836 } 9837 EXPORT_SYMBOL(netif_tx_stop_all_queues); 9838 9839 /** 9840 * register_netdevice - register a network device 9841 * @dev: device to register 9842 * 9843 * Take a completed network device structure and add it to the kernel 9844 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier 9845 * chain. 0 is returned on success. A negative errno code is returned 9846 * on a failure to set up the device, or if the name is a duplicate. 9847 * 9848 * Callers must hold the rtnl semaphore. You may want 9849 * register_netdev() instead of this. 9850 * 9851 * BUGS: 9852 * The locking appears insufficient to guarantee two parallel registers 9853 * will not get the same name. 9854 */ 9855 9856 int register_netdevice(struct net_device *dev) 9857 { 9858 int ret; 9859 struct net *net = dev_net(dev); 9860 9861 BUILD_BUG_ON(sizeof(netdev_features_t) * BITS_PER_BYTE < 9862 NETDEV_FEATURE_COUNT); 9863 BUG_ON(dev_boot_phase); 9864 ASSERT_RTNL(); 9865 9866 might_sleep(); 9867 9868 /* When net_device's are persistent, this will be fatal. */ 9869 BUG_ON(dev->reg_state != NETREG_UNINITIALIZED); 9870 BUG_ON(!net); 9871 9872 ret = ethtool_check_ops(dev->ethtool_ops); 9873 if (ret) 9874 return ret; 9875 9876 spin_lock_init(&dev->addr_list_lock); 9877 netdev_set_addr_lockdep_class(dev); 9878 9879 ret = dev_get_valid_name(net, dev, dev->name); 9880 if (ret < 0) 9881 goto out; 9882 9883 ret = -ENOMEM; 9884 dev->name_node = netdev_name_node_head_alloc(dev); 9885 if (!dev->name_node) 9886 goto out; 9887 9888 /* Init, if this function is available */ 9889 if (dev->netdev_ops->ndo_init) { 9890 ret = dev->netdev_ops->ndo_init(dev); 9891 if (ret) { 9892 if (ret > 0) 9893 ret = -EIO; 9894 goto err_free_name; 9895 } 9896 } 9897 9898 if (((dev->hw_features | dev->features) & 9899 NETIF_F_HW_VLAN_CTAG_FILTER) && 9900 (!dev->netdev_ops->ndo_vlan_rx_add_vid || 9901 !dev->netdev_ops->ndo_vlan_rx_kill_vid)) { 9902 netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n"); 9903 ret = -EINVAL; 9904 goto err_uninit; 9905 } 9906 9907 ret = -EBUSY; 9908 if (!dev->ifindex) 9909 dev->ifindex = dev_new_index(net); 9910 else if (__dev_get_by_index(net, dev->ifindex)) 9911 goto err_uninit; 9912 9913 /* Transfer changeable features to wanted_features and enable 9914 * software offloads (GSO and GRO). 9915 */ 9916 dev->hw_features |= (NETIF_F_SOFT_FEATURES | NETIF_F_SOFT_FEATURES_OFF); 9917 dev->features |= NETIF_F_SOFT_FEATURES; 9918 9919 if (dev->udp_tunnel_nic_info) { 9920 dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT; 9921 dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT; 9922 } 9923 9924 dev->wanted_features = dev->features & dev->hw_features; 9925 9926 if (!(dev->flags & IFF_LOOPBACK)) 9927 dev->hw_features |= NETIF_F_NOCACHE_COPY; 9928 9929 /* If IPv4 TCP segmentation offload is supported we should also 9930 * allow the device to enable segmenting the frame with the option 9931 * of ignoring a static IP ID value. This doesn't enable the 9932 * feature itself but allows the user to enable it later. 9933 */ 9934 if (dev->hw_features & NETIF_F_TSO) 9935 dev->hw_features |= NETIF_F_TSO_MANGLEID; 9936 if (dev->vlan_features & NETIF_F_TSO) 9937 dev->vlan_features |= NETIF_F_TSO_MANGLEID; 9938 if (dev->mpls_features & NETIF_F_TSO) 9939 dev->mpls_features |= NETIF_F_TSO_MANGLEID; 9940 if (dev->hw_enc_features & NETIF_F_TSO) 9941 dev->hw_enc_features |= NETIF_F_TSO_MANGLEID; 9942 9943 /* Make NETIF_F_HIGHDMA inheritable to VLAN devices. 9944 */ 9945 dev->vlan_features |= NETIF_F_HIGHDMA; 9946 9947 /* Make NETIF_F_SG inheritable to tunnel devices. 9948 */ 9949 dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL; 9950 9951 /* Make NETIF_F_SG inheritable to MPLS. 9952 */ 9953 dev->mpls_features |= NETIF_F_SG; 9954 9955 ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev); 9956 ret = notifier_to_errno(ret); 9957 if (ret) 9958 goto err_uninit; 9959 9960 ret = netdev_register_kobject(dev); 9961 if (ret) { 9962 dev->reg_state = NETREG_UNREGISTERED; 9963 goto err_uninit; 9964 } 9965 dev->reg_state = NETREG_REGISTERED; 9966 9967 __netdev_update_features(dev); 9968 9969 /* 9970 * Default initial state at registry is that the 9971 * device is present. 9972 */ 9973 9974 set_bit(__LINK_STATE_PRESENT, &dev->state); 9975 9976 linkwatch_init_dev(dev); 9977 9978 dev_init_scheduler(dev); 9979 9980 dev_hold_track(dev, &dev->dev_registered_tracker, GFP_KERNEL); 9981 list_netdevice(dev); 9982 9983 add_device_randomness(dev->dev_addr, dev->addr_len); 9984 9985 /* If the device has permanent device address, driver should 9986 * set dev_addr and also addr_assign_type should be set to 9987 * NET_ADDR_PERM (default value). 9988 */ 9989 if (dev->addr_assign_type == NET_ADDR_PERM) 9990 memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len); 9991 9992 /* Notify protocols, that a new device appeared. */ 9993 ret = call_netdevice_notifiers(NETDEV_REGISTER, dev); 9994 ret = notifier_to_errno(ret); 9995 if (ret) { 9996 /* Expect explicit free_netdev() on failure */ 9997 dev->needs_free_netdev = false; 9998 unregister_netdevice_queue(dev, NULL); 9999 goto out; 10000 } 10001 /* 10002 * Prevent userspace races by waiting until the network 10003 * device is fully setup before sending notifications. 10004 */ 10005 if (!dev->rtnl_link_ops || 10006 dev->rtnl_link_state == RTNL_LINK_INITIALIZED) 10007 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL); 10008 10009 out: 10010 return ret; 10011 10012 err_uninit: 10013 if (dev->netdev_ops->ndo_uninit) 10014 dev->netdev_ops->ndo_uninit(dev); 10015 if (dev->priv_destructor) 10016 dev->priv_destructor(dev); 10017 err_free_name: 10018 netdev_name_node_free(dev->name_node); 10019 goto out; 10020 } 10021 EXPORT_SYMBOL(register_netdevice); 10022 10023 /** 10024 * init_dummy_netdev - init a dummy network device for NAPI 10025 * @dev: device to init 10026 * 10027 * This takes a network device structure and initialize the minimum 10028 * amount of fields so it can be used to schedule NAPI polls without 10029 * registering a full blown interface. This is to be used by drivers 10030 * that need to tie several hardware interfaces to a single NAPI 10031 * poll scheduler due to HW limitations. 10032 */ 10033 int init_dummy_netdev(struct net_device *dev) 10034 { 10035 /* Clear everything. Note we don't initialize spinlocks 10036 * are they aren't supposed to be taken by any of the 10037 * NAPI code and this dummy netdev is supposed to be 10038 * only ever used for NAPI polls 10039 */ 10040 memset(dev, 0, sizeof(struct net_device)); 10041 10042 /* make sure we BUG if trying to hit standard 10043 * register/unregister code path 10044 */ 10045 dev->reg_state = NETREG_DUMMY; 10046 10047 /* NAPI wants this */ 10048 INIT_LIST_HEAD(&dev->napi_list); 10049 10050 /* a dummy interface is started by default */ 10051 set_bit(__LINK_STATE_PRESENT, &dev->state); 10052 set_bit(__LINK_STATE_START, &dev->state); 10053 10054 /* napi_busy_loop stats accounting wants this */ 10055 dev_net_set(dev, &init_net); 10056 10057 /* Note : We dont allocate pcpu_refcnt for dummy devices, 10058 * because users of this 'device' dont need to change 10059 * its refcount. 10060 */ 10061 10062 return 0; 10063 } 10064 EXPORT_SYMBOL_GPL(init_dummy_netdev); 10065 10066 10067 /** 10068 * register_netdev - register a network device 10069 * @dev: device to register 10070 * 10071 * Take a completed network device structure and add it to the kernel 10072 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier 10073 * chain. 0 is returned on success. A negative errno code is returned 10074 * on a failure to set up the device, or if the name is a duplicate. 10075 * 10076 * This is a wrapper around register_netdevice that takes the rtnl semaphore 10077 * and expands the device name if you passed a format string to 10078 * alloc_netdev. 10079 */ 10080 int register_netdev(struct net_device *dev) 10081 { 10082 int err; 10083 10084 if (rtnl_lock_killable()) 10085 return -EINTR; 10086 err = register_netdevice(dev); 10087 rtnl_unlock(); 10088 return err; 10089 } 10090 EXPORT_SYMBOL(register_netdev); 10091 10092 int netdev_refcnt_read(const struct net_device *dev) 10093 { 10094 #ifdef CONFIG_PCPU_DEV_REFCNT 10095 int i, refcnt = 0; 10096 10097 for_each_possible_cpu(i) 10098 refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i); 10099 return refcnt; 10100 #else 10101 return refcount_read(&dev->dev_refcnt); 10102 #endif 10103 } 10104 EXPORT_SYMBOL(netdev_refcnt_read); 10105 10106 int netdev_unregister_timeout_secs __read_mostly = 10; 10107 10108 #define WAIT_REFS_MIN_MSECS 1 10109 #define WAIT_REFS_MAX_MSECS 250 10110 /** 10111 * netdev_wait_allrefs_any - wait until all references are gone. 10112 * @list: list of net_devices to wait on 10113 * 10114 * This is called when unregistering network devices. 10115 * 10116 * Any protocol or device that holds a reference should register 10117 * for netdevice notification, and cleanup and put back the 10118 * reference if they receive an UNREGISTER event. 10119 * We can get stuck here if buggy protocols don't correctly 10120 * call dev_put. 10121 */ 10122 static struct net_device *netdev_wait_allrefs_any(struct list_head *list) 10123 { 10124 unsigned long rebroadcast_time, warning_time; 10125 struct net_device *dev; 10126 int wait = 0; 10127 10128 rebroadcast_time = warning_time = jiffies; 10129 10130 list_for_each_entry(dev, list, todo_list) 10131 if (netdev_refcnt_read(dev) == 1) 10132 return dev; 10133 10134 while (true) { 10135 if (time_after(jiffies, rebroadcast_time + 1 * HZ)) { 10136 rtnl_lock(); 10137 10138 /* Rebroadcast unregister notification */ 10139 list_for_each_entry(dev, list, todo_list) 10140 call_netdevice_notifiers(NETDEV_UNREGISTER, dev); 10141 10142 __rtnl_unlock(); 10143 rcu_barrier(); 10144 rtnl_lock(); 10145 10146 list_for_each_entry(dev, list, todo_list) 10147 if (test_bit(__LINK_STATE_LINKWATCH_PENDING, 10148 &dev->state)) { 10149 /* We must not have linkwatch events 10150 * pending on unregister. If this 10151 * happens, we simply run the queue 10152 * unscheduled, resulting in a noop 10153 * for this device. 10154 */ 10155 linkwatch_run_queue(); 10156 break; 10157 } 10158 10159 __rtnl_unlock(); 10160 10161 rebroadcast_time = jiffies; 10162 } 10163 10164 if (!wait) { 10165 rcu_barrier(); 10166 wait = WAIT_REFS_MIN_MSECS; 10167 } else { 10168 msleep(wait); 10169 wait = min(wait << 1, WAIT_REFS_MAX_MSECS); 10170 } 10171 10172 list_for_each_entry(dev, list, todo_list) 10173 if (netdev_refcnt_read(dev) == 1) 10174 return dev; 10175 10176 if (time_after(jiffies, warning_time + 10177 netdev_unregister_timeout_secs * HZ)) { 10178 list_for_each_entry(dev, list, todo_list) { 10179 pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n", 10180 dev->name, netdev_refcnt_read(dev)); 10181 ref_tracker_dir_print(&dev->refcnt_tracker, 10); 10182 } 10183 10184 warning_time = jiffies; 10185 } 10186 } 10187 } 10188 10189 /* The sequence is: 10190 * 10191 * rtnl_lock(); 10192 * ... 10193 * register_netdevice(x1); 10194 * register_netdevice(x2); 10195 * ... 10196 * unregister_netdevice(y1); 10197 * unregister_netdevice(y2); 10198 * ... 10199 * rtnl_unlock(); 10200 * free_netdev(y1); 10201 * free_netdev(y2); 10202 * 10203 * We are invoked by rtnl_unlock(). 10204 * This allows us to deal with problems: 10205 * 1) We can delete sysfs objects which invoke hotplug 10206 * without deadlocking with linkwatch via keventd. 10207 * 2) Since we run with the RTNL semaphore not held, we can sleep 10208 * safely in order to wait for the netdev refcnt to drop to zero. 10209 * 10210 * We must not return until all unregister events added during 10211 * the interval the lock was held have been completed. 10212 */ 10213 void netdev_run_todo(void) 10214 { 10215 struct net_device *dev, *tmp; 10216 struct list_head list; 10217 #ifdef CONFIG_LOCKDEP 10218 struct list_head unlink_list; 10219 10220 list_replace_init(&net_unlink_list, &unlink_list); 10221 10222 while (!list_empty(&unlink_list)) { 10223 struct net_device *dev = list_first_entry(&unlink_list, 10224 struct net_device, 10225 unlink_list); 10226 list_del_init(&dev->unlink_list); 10227 dev->nested_level = dev->lower_level - 1; 10228 } 10229 #endif 10230 10231 /* Snapshot list, allow later requests */ 10232 list_replace_init(&net_todo_list, &list); 10233 10234 __rtnl_unlock(); 10235 10236 /* Wait for rcu callbacks to finish before next phase */ 10237 if (!list_empty(&list)) 10238 rcu_barrier(); 10239 10240 list_for_each_entry_safe(dev, tmp, &list, todo_list) { 10241 if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) { 10242 netdev_WARN(dev, "run_todo but not unregistering\n"); 10243 list_del(&dev->todo_list); 10244 continue; 10245 } 10246 10247 dev->reg_state = NETREG_UNREGISTERED; 10248 linkwatch_forget_dev(dev); 10249 } 10250 10251 while (!list_empty(&list)) { 10252 dev = netdev_wait_allrefs_any(&list); 10253 list_del(&dev->todo_list); 10254 10255 /* paranoia */ 10256 BUG_ON(netdev_refcnt_read(dev) != 1); 10257 BUG_ON(!list_empty(&dev->ptype_all)); 10258 BUG_ON(!list_empty(&dev->ptype_specific)); 10259 WARN_ON(rcu_access_pointer(dev->ip_ptr)); 10260 WARN_ON(rcu_access_pointer(dev->ip6_ptr)); 10261 #if IS_ENABLED(CONFIG_DECNET) 10262 WARN_ON(dev->dn_ptr); 10263 #endif 10264 if (dev->priv_destructor) 10265 dev->priv_destructor(dev); 10266 if (dev->needs_free_netdev) 10267 free_netdev(dev); 10268 10269 if (atomic_dec_and_test(&dev_net(dev)->dev_unreg_count)) 10270 wake_up(&netdev_unregistering_wq); 10271 10272 /* Free network device */ 10273 kobject_put(&dev->dev.kobj); 10274 } 10275 } 10276 10277 /* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has 10278 * all the same fields in the same order as net_device_stats, with only 10279 * the type differing, but rtnl_link_stats64 may have additional fields 10280 * at the end for newer counters. 10281 */ 10282 void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64, 10283 const struct net_device_stats *netdev_stats) 10284 { 10285 #if BITS_PER_LONG == 64 10286 BUILD_BUG_ON(sizeof(*stats64) < sizeof(*netdev_stats)); 10287 memcpy(stats64, netdev_stats, sizeof(*netdev_stats)); 10288 /* zero out counters that only exist in rtnl_link_stats64 */ 10289 memset((char *)stats64 + sizeof(*netdev_stats), 0, 10290 sizeof(*stats64) - sizeof(*netdev_stats)); 10291 #else 10292 size_t i, n = sizeof(*netdev_stats) / sizeof(unsigned long); 10293 const unsigned long *src = (const unsigned long *)netdev_stats; 10294 u64 *dst = (u64 *)stats64; 10295 10296 BUILD_BUG_ON(n > sizeof(*stats64) / sizeof(u64)); 10297 for (i = 0; i < n; i++) 10298 dst[i] = src[i]; 10299 /* zero out counters that only exist in rtnl_link_stats64 */ 10300 memset((char *)stats64 + n * sizeof(u64), 0, 10301 sizeof(*stats64) - n * sizeof(u64)); 10302 #endif 10303 } 10304 EXPORT_SYMBOL(netdev_stats_to_stats64); 10305 10306 struct net_device_core_stats *netdev_core_stats_alloc(struct net_device *dev) 10307 { 10308 struct net_device_core_stats __percpu *p; 10309 10310 p = alloc_percpu_gfp(struct net_device_core_stats, 10311 GFP_ATOMIC | __GFP_NOWARN); 10312 10313 if (p && cmpxchg(&dev->core_stats, NULL, p)) 10314 free_percpu(p); 10315 10316 /* This READ_ONCE() pairs with the cmpxchg() above */ 10317 p = READ_ONCE(dev->core_stats); 10318 if (!p) 10319 return NULL; 10320 10321 return this_cpu_ptr(p); 10322 } 10323 EXPORT_SYMBOL(netdev_core_stats_alloc); 10324 10325 /** 10326 * dev_get_stats - get network device statistics 10327 * @dev: device to get statistics from 10328 * @storage: place to store stats 10329 * 10330 * Get network statistics from device. Return @storage. 10331 * The device driver may provide its own method by setting 10332 * dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats; 10333 * otherwise the internal statistics structure is used. 10334 */ 10335 struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev, 10336 struct rtnl_link_stats64 *storage) 10337 { 10338 const struct net_device_ops *ops = dev->netdev_ops; 10339 const struct net_device_core_stats __percpu *p; 10340 10341 if (ops->ndo_get_stats64) { 10342 memset(storage, 0, sizeof(*storage)); 10343 ops->ndo_get_stats64(dev, storage); 10344 } else if (ops->ndo_get_stats) { 10345 netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev)); 10346 } else { 10347 netdev_stats_to_stats64(storage, &dev->stats); 10348 } 10349 10350 /* This READ_ONCE() pairs with the write in netdev_core_stats_alloc() */ 10351 p = READ_ONCE(dev->core_stats); 10352 if (p) { 10353 const struct net_device_core_stats *core_stats; 10354 int i; 10355 10356 for_each_possible_cpu(i) { 10357 core_stats = per_cpu_ptr(p, i); 10358 storage->rx_dropped += local_read(&core_stats->rx_dropped); 10359 storage->tx_dropped += local_read(&core_stats->tx_dropped); 10360 storage->rx_nohandler += local_read(&core_stats->rx_nohandler); 10361 storage->rx_otherhost_dropped += local_read(&core_stats->rx_otherhost_dropped); 10362 } 10363 } 10364 return storage; 10365 } 10366 EXPORT_SYMBOL(dev_get_stats); 10367 10368 /** 10369 * dev_fetch_sw_netstats - get per-cpu network device statistics 10370 * @s: place to store stats 10371 * @netstats: per-cpu network stats to read from 10372 * 10373 * Read per-cpu network statistics and populate the related fields in @s. 10374 */ 10375 void dev_fetch_sw_netstats(struct rtnl_link_stats64 *s, 10376 const struct pcpu_sw_netstats __percpu *netstats) 10377 { 10378 int cpu; 10379 10380 for_each_possible_cpu(cpu) { 10381 const struct pcpu_sw_netstats *stats; 10382 struct pcpu_sw_netstats tmp; 10383 unsigned int start; 10384 10385 stats = per_cpu_ptr(netstats, cpu); 10386 do { 10387 start = u64_stats_fetch_begin_irq(&stats->syncp); 10388 tmp.rx_packets = stats->rx_packets; 10389 tmp.rx_bytes = stats->rx_bytes; 10390 tmp.tx_packets = stats->tx_packets; 10391 tmp.tx_bytes = stats->tx_bytes; 10392 } while (u64_stats_fetch_retry_irq(&stats->syncp, start)); 10393 10394 s->rx_packets += tmp.rx_packets; 10395 s->rx_bytes += tmp.rx_bytes; 10396 s->tx_packets += tmp.tx_packets; 10397 s->tx_bytes += tmp.tx_bytes; 10398 } 10399 } 10400 EXPORT_SYMBOL_GPL(dev_fetch_sw_netstats); 10401 10402 /** 10403 * dev_get_tstats64 - ndo_get_stats64 implementation 10404 * @dev: device to get statistics from 10405 * @s: place to store stats 10406 * 10407 * Populate @s from dev->stats and dev->tstats. Can be used as 10408 * ndo_get_stats64() callback. 10409 */ 10410 void dev_get_tstats64(struct net_device *dev, struct rtnl_link_stats64 *s) 10411 { 10412 netdev_stats_to_stats64(s, &dev->stats); 10413 dev_fetch_sw_netstats(s, dev->tstats); 10414 } 10415 EXPORT_SYMBOL_GPL(dev_get_tstats64); 10416 10417 struct netdev_queue *dev_ingress_queue_create(struct net_device *dev) 10418 { 10419 struct netdev_queue *queue = dev_ingress_queue(dev); 10420 10421 #ifdef CONFIG_NET_CLS_ACT 10422 if (queue) 10423 return queue; 10424 queue = kzalloc(sizeof(*queue), GFP_KERNEL); 10425 if (!queue) 10426 return NULL; 10427 netdev_init_one_queue(dev, queue, NULL); 10428 RCU_INIT_POINTER(queue->qdisc, &noop_qdisc); 10429 queue->qdisc_sleeping = &noop_qdisc; 10430 rcu_assign_pointer(dev->ingress_queue, queue); 10431 #endif 10432 return queue; 10433 } 10434 10435 static const struct ethtool_ops default_ethtool_ops; 10436 10437 void netdev_set_default_ethtool_ops(struct net_device *dev, 10438 const struct ethtool_ops *ops) 10439 { 10440 if (dev->ethtool_ops == &default_ethtool_ops) 10441 dev->ethtool_ops = ops; 10442 } 10443 EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops); 10444 10445 void netdev_freemem(struct net_device *dev) 10446 { 10447 char *addr = (char *)dev - dev->padded; 10448 10449 kvfree(addr); 10450 } 10451 10452 /** 10453 * alloc_netdev_mqs - allocate network device 10454 * @sizeof_priv: size of private data to allocate space for 10455 * @name: device name format string 10456 * @name_assign_type: origin of device name 10457 * @setup: callback to initialize device 10458 * @txqs: the number of TX subqueues to allocate 10459 * @rxqs: the number of RX subqueues to allocate 10460 * 10461 * Allocates a struct net_device with private data area for driver use 10462 * and performs basic initialization. Also allocates subqueue structs 10463 * for each queue on the device. 10464 */ 10465 struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name, 10466 unsigned char name_assign_type, 10467 void (*setup)(struct net_device *), 10468 unsigned int txqs, unsigned int rxqs) 10469 { 10470 struct net_device *dev; 10471 unsigned int alloc_size; 10472 struct net_device *p; 10473 10474 BUG_ON(strlen(name) >= sizeof(dev->name)); 10475 10476 if (txqs < 1) { 10477 pr_err("alloc_netdev: Unable to allocate device with zero queues\n"); 10478 return NULL; 10479 } 10480 10481 if (rxqs < 1) { 10482 pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n"); 10483 return NULL; 10484 } 10485 10486 alloc_size = sizeof(struct net_device); 10487 if (sizeof_priv) { 10488 /* ensure 32-byte alignment of private area */ 10489 alloc_size = ALIGN(alloc_size, NETDEV_ALIGN); 10490 alloc_size += sizeof_priv; 10491 } 10492 /* ensure 32-byte alignment of whole construct */ 10493 alloc_size += NETDEV_ALIGN - 1; 10494 10495 p = kvzalloc(alloc_size, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL); 10496 if (!p) 10497 return NULL; 10498 10499 dev = PTR_ALIGN(p, NETDEV_ALIGN); 10500 dev->padded = (char *)dev - (char *)p; 10501 10502 ref_tracker_dir_init(&dev->refcnt_tracker, 128); 10503 #ifdef CONFIG_PCPU_DEV_REFCNT 10504 dev->pcpu_refcnt = alloc_percpu(int); 10505 if (!dev->pcpu_refcnt) 10506 goto free_dev; 10507 __dev_hold(dev); 10508 #else 10509 refcount_set(&dev->dev_refcnt, 1); 10510 #endif 10511 10512 if (dev_addr_init(dev)) 10513 goto free_pcpu; 10514 10515 dev_mc_init(dev); 10516 dev_uc_init(dev); 10517 10518 dev_net_set(dev, &init_net); 10519 10520 dev->gso_max_size = GSO_MAX_SIZE; 10521 dev->gso_max_segs = GSO_MAX_SEGS; 10522 dev->gro_max_size = GRO_MAX_SIZE; 10523 dev->upper_level = 1; 10524 dev->lower_level = 1; 10525 #ifdef CONFIG_LOCKDEP 10526 dev->nested_level = 0; 10527 INIT_LIST_HEAD(&dev->unlink_list); 10528 #endif 10529 10530 INIT_LIST_HEAD(&dev->napi_list); 10531 INIT_LIST_HEAD(&dev->unreg_list); 10532 INIT_LIST_HEAD(&dev->close_list); 10533 INIT_LIST_HEAD(&dev->link_watch_list); 10534 INIT_LIST_HEAD(&dev->adj_list.upper); 10535 INIT_LIST_HEAD(&dev->adj_list.lower); 10536 INIT_LIST_HEAD(&dev->ptype_all); 10537 INIT_LIST_HEAD(&dev->ptype_specific); 10538 INIT_LIST_HEAD(&dev->net_notifier_list); 10539 #ifdef CONFIG_NET_SCHED 10540 hash_init(dev->qdisc_hash); 10541 #endif 10542 dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM; 10543 setup(dev); 10544 10545 if (!dev->tx_queue_len) { 10546 dev->priv_flags |= IFF_NO_QUEUE; 10547 dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN; 10548 } 10549 10550 dev->num_tx_queues = txqs; 10551 dev->real_num_tx_queues = txqs; 10552 if (netif_alloc_netdev_queues(dev)) 10553 goto free_all; 10554 10555 dev->num_rx_queues = rxqs; 10556 dev->real_num_rx_queues = rxqs; 10557 if (netif_alloc_rx_queues(dev)) 10558 goto free_all; 10559 10560 strcpy(dev->name, name); 10561 dev->name_assign_type = name_assign_type; 10562 dev->group = INIT_NETDEV_GROUP; 10563 if (!dev->ethtool_ops) 10564 dev->ethtool_ops = &default_ethtool_ops; 10565 10566 nf_hook_netdev_init(dev); 10567 10568 return dev; 10569 10570 free_all: 10571 free_netdev(dev); 10572 return NULL; 10573 10574 free_pcpu: 10575 #ifdef CONFIG_PCPU_DEV_REFCNT 10576 free_percpu(dev->pcpu_refcnt); 10577 free_dev: 10578 #endif 10579 netdev_freemem(dev); 10580 return NULL; 10581 } 10582 EXPORT_SYMBOL(alloc_netdev_mqs); 10583 10584 /** 10585 * free_netdev - free network device 10586 * @dev: device 10587 * 10588 * This function does the last stage of destroying an allocated device 10589 * interface. The reference to the device object is released. If this 10590 * is the last reference then it will be freed.Must be called in process 10591 * context. 10592 */ 10593 void free_netdev(struct net_device *dev) 10594 { 10595 struct napi_struct *p, *n; 10596 10597 might_sleep(); 10598 10599 /* When called immediately after register_netdevice() failed the unwind 10600 * handling may still be dismantling the device. Handle that case by 10601 * deferring the free. 10602 */ 10603 if (dev->reg_state == NETREG_UNREGISTERING) { 10604 ASSERT_RTNL(); 10605 dev->needs_free_netdev = true; 10606 return; 10607 } 10608 10609 netif_free_tx_queues(dev); 10610 netif_free_rx_queues(dev); 10611 10612 kfree(rcu_dereference_protected(dev->ingress_queue, 1)); 10613 10614 /* Flush device addresses */ 10615 dev_addr_flush(dev); 10616 10617 list_for_each_entry_safe(p, n, &dev->napi_list, dev_list) 10618 netif_napi_del(p); 10619 10620 ref_tracker_dir_exit(&dev->refcnt_tracker); 10621 #ifdef CONFIG_PCPU_DEV_REFCNT 10622 free_percpu(dev->pcpu_refcnt); 10623 dev->pcpu_refcnt = NULL; 10624 #endif 10625 free_percpu(dev->core_stats); 10626 dev->core_stats = NULL; 10627 free_percpu(dev->xdp_bulkq); 10628 dev->xdp_bulkq = NULL; 10629 10630 /* Compatibility with error handling in drivers */ 10631 if (dev->reg_state == NETREG_UNINITIALIZED) { 10632 netdev_freemem(dev); 10633 return; 10634 } 10635 10636 BUG_ON(dev->reg_state != NETREG_UNREGISTERED); 10637 dev->reg_state = NETREG_RELEASED; 10638 10639 /* will free via device release */ 10640 put_device(&dev->dev); 10641 } 10642 EXPORT_SYMBOL(free_netdev); 10643 10644 /** 10645 * synchronize_net - Synchronize with packet receive processing 10646 * 10647 * Wait for packets currently being received to be done. 10648 * Does not block later packets from starting. 10649 */ 10650 void synchronize_net(void) 10651 { 10652 might_sleep(); 10653 if (rtnl_is_locked()) 10654 synchronize_rcu_expedited(); 10655 else 10656 synchronize_rcu(); 10657 } 10658 EXPORT_SYMBOL(synchronize_net); 10659 10660 /** 10661 * unregister_netdevice_queue - remove device from the kernel 10662 * @dev: device 10663 * @head: list 10664 * 10665 * This function shuts down a device interface and removes it 10666 * from the kernel tables. 10667 * If head not NULL, device is queued to be unregistered later. 10668 * 10669 * Callers must hold the rtnl semaphore. You may want 10670 * unregister_netdev() instead of this. 10671 */ 10672 10673 void unregister_netdevice_queue(struct net_device *dev, struct list_head *head) 10674 { 10675 ASSERT_RTNL(); 10676 10677 if (head) { 10678 list_move_tail(&dev->unreg_list, head); 10679 } else { 10680 LIST_HEAD(single); 10681 10682 list_add(&dev->unreg_list, &single); 10683 unregister_netdevice_many(&single); 10684 } 10685 } 10686 EXPORT_SYMBOL(unregister_netdevice_queue); 10687 10688 /** 10689 * unregister_netdevice_many - unregister many devices 10690 * @head: list of devices 10691 * 10692 * Note: As most callers use a stack allocated list_head, 10693 * we force a list_del() to make sure stack wont be corrupted later. 10694 */ 10695 void unregister_netdevice_many(struct list_head *head) 10696 { 10697 struct net_device *dev, *tmp; 10698 LIST_HEAD(close_head); 10699 10700 BUG_ON(dev_boot_phase); 10701 ASSERT_RTNL(); 10702 10703 if (list_empty(head)) 10704 return; 10705 10706 list_for_each_entry_safe(dev, tmp, head, unreg_list) { 10707 /* Some devices call without registering 10708 * for initialization unwind. Remove those 10709 * devices and proceed with the remaining. 10710 */ 10711 if (dev->reg_state == NETREG_UNINITIALIZED) { 10712 pr_debug("unregister_netdevice: device %s/%p never was registered\n", 10713 dev->name, dev); 10714 10715 WARN_ON(1); 10716 list_del(&dev->unreg_list); 10717 continue; 10718 } 10719 dev->dismantle = true; 10720 BUG_ON(dev->reg_state != NETREG_REGISTERED); 10721 } 10722 10723 /* If device is running, close it first. */ 10724 list_for_each_entry(dev, head, unreg_list) 10725 list_add_tail(&dev->close_list, &close_head); 10726 dev_close_many(&close_head, true); 10727 10728 list_for_each_entry(dev, head, unreg_list) { 10729 /* And unlink it from device chain. */ 10730 unlist_netdevice(dev); 10731 10732 dev->reg_state = NETREG_UNREGISTERING; 10733 } 10734 flush_all_backlogs(); 10735 10736 synchronize_net(); 10737 10738 list_for_each_entry(dev, head, unreg_list) { 10739 struct sk_buff *skb = NULL; 10740 10741 /* Shutdown queueing discipline. */ 10742 dev_shutdown(dev); 10743 10744 dev_xdp_uninstall(dev); 10745 10746 netdev_offload_xstats_disable_all(dev); 10747 10748 /* Notify protocols, that we are about to destroy 10749 * this device. They should clean all the things. 10750 */ 10751 call_netdevice_notifiers(NETDEV_UNREGISTER, dev); 10752 10753 if (!dev->rtnl_link_ops || 10754 dev->rtnl_link_state == RTNL_LINK_INITIALIZED) 10755 skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0, 10756 GFP_KERNEL, NULL, 0); 10757 10758 /* 10759 * Flush the unicast and multicast chains 10760 */ 10761 dev_uc_flush(dev); 10762 dev_mc_flush(dev); 10763 10764 netdev_name_node_alt_flush(dev); 10765 netdev_name_node_free(dev->name_node); 10766 10767 if (dev->netdev_ops->ndo_uninit) 10768 dev->netdev_ops->ndo_uninit(dev); 10769 10770 if (skb) 10771 rtmsg_ifinfo_send(skb, dev, GFP_KERNEL); 10772 10773 /* Notifier chain MUST detach us all upper devices. */ 10774 WARN_ON(netdev_has_any_upper_dev(dev)); 10775 WARN_ON(netdev_has_any_lower_dev(dev)); 10776 10777 /* Remove entries from kobject tree */ 10778 netdev_unregister_kobject(dev); 10779 #ifdef CONFIG_XPS 10780 /* Remove XPS queueing entries */ 10781 netif_reset_xps_queues_gt(dev, 0); 10782 #endif 10783 } 10784 10785 synchronize_net(); 10786 10787 list_for_each_entry(dev, head, unreg_list) { 10788 dev_put_track(dev, &dev->dev_registered_tracker); 10789 net_set_todo(dev); 10790 } 10791 10792 list_del(head); 10793 } 10794 EXPORT_SYMBOL(unregister_netdevice_many); 10795 10796 /** 10797 * unregister_netdev - remove device from the kernel 10798 * @dev: device 10799 * 10800 * This function shuts down a device interface and removes it 10801 * from the kernel tables. 10802 * 10803 * This is just a wrapper for unregister_netdevice that takes 10804 * the rtnl semaphore. In general you want to use this and not 10805 * unregister_netdevice. 10806 */ 10807 void unregister_netdev(struct net_device *dev) 10808 { 10809 rtnl_lock(); 10810 unregister_netdevice(dev); 10811 rtnl_unlock(); 10812 } 10813 EXPORT_SYMBOL(unregister_netdev); 10814 10815 /** 10816 * __dev_change_net_namespace - move device to different nethost namespace 10817 * @dev: device 10818 * @net: network namespace 10819 * @pat: If not NULL name pattern to try if the current device name 10820 * is already taken in the destination network namespace. 10821 * @new_ifindex: If not zero, specifies device index in the target 10822 * namespace. 10823 * 10824 * This function shuts down a device interface and moves it 10825 * to a new network namespace. On success 0 is returned, on 10826 * a failure a netagive errno code is returned. 10827 * 10828 * Callers must hold the rtnl semaphore. 10829 */ 10830 10831 int __dev_change_net_namespace(struct net_device *dev, struct net *net, 10832 const char *pat, int new_ifindex) 10833 { 10834 struct net *net_old = dev_net(dev); 10835 int err, new_nsid; 10836 10837 ASSERT_RTNL(); 10838 10839 /* Don't allow namespace local devices to be moved. */ 10840 err = -EINVAL; 10841 if (dev->features & NETIF_F_NETNS_LOCAL) 10842 goto out; 10843 10844 /* Ensure the device has been registrered */ 10845 if (dev->reg_state != NETREG_REGISTERED) 10846 goto out; 10847 10848 /* Get out if there is nothing todo */ 10849 err = 0; 10850 if (net_eq(net_old, net)) 10851 goto out; 10852 10853 /* Pick the destination device name, and ensure 10854 * we can use it in the destination network namespace. 10855 */ 10856 err = -EEXIST; 10857 if (netdev_name_in_use(net, dev->name)) { 10858 /* We get here if we can't use the current device name */ 10859 if (!pat) 10860 goto out; 10861 err = dev_get_valid_name(net, dev, pat); 10862 if (err < 0) 10863 goto out; 10864 } 10865 10866 /* Check that new_ifindex isn't used yet. */ 10867 err = -EBUSY; 10868 if (new_ifindex && __dev_get_by_index(net, new_ifindex)) 10869 goto out; 10870 10871 /* 10872 * And now a mini version of register_netdevice unregister_netdevice. 10873 */ 10874 10875 /* If device is running close it first. */ 10876 dev_close(dev); 10877 10878 /* And unlink it from device chain */ 10879 unlist_netdevice(dev); 10880 10881 synchronize_net(); 10882 10883 /* Shutdown queueing discipline. */ 10884 dev_shutdown(dev); 10885 10886 /* Notify protocols, that we are about to destroy 10887 * this device. They should clean all the things. 10888 * 10889 * Note that dev->reg_state stays at NETREG_REGISTERED. 10890 * This is wanted because this way 8021q and macvlan know 10891 * the device is just moving and can keep their slaves up. 10892 */ 10893 call_netdevice_notifiers(NETDEV_UNREGISTER, dev); 10894 rcu_barrier(); 10895 10896 new_nsid = peernet2id_alloc(dev_net(dev), net, GFP_KERNEL); 10897 /* If there is an ifindex conflict assign a new one */ 10898 if (!new_ifindex) { 10899 if (__dev_get_by_index(net, dev->ifindex)) 10900 new_ifindex = dev_new_index(net); 10901 else 10902 new_ifindex = dev->ifindex; 10903 } 10904 10905 rtmsg_ifinfo_newnet(RTM_DELLINK, dev, ~0U, GFP_KERNEL, &new_nsid, 10906 new_ifindex); 10907 10908 /* 10909 * Flush the unicast and multicast chains 10910 */ 10911 dev_uc_flush(dev); 10912 dev_mc_flush(dev); 10913 10914 /* Send a netdev-removed uevent to the old namespace */ 10915 kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE); 10916 netdev_adjacent_del_links(dev); 10917 10918 /* Move per-net netdevice notifiers that are following the netdevice */ 10919 move_netdevice_notifiers_dev_net(dev, net); 10920 10921 /* Actually switch the network namespace */ 10922 dev_net_set(dev, net); 10923 dev->ifindex = new_ifindex; 10924 10925 /* Send a netdev-add uevent to the new namespace */ 10926 kobject_uevent(&dev->dev.kobj, KOBJ_ADD); 10927 netdev_adjacent_add_links(dev); 10928 10929 /* Fixup kobjects */ 10930 err = device_rename(&dev->dev, dev->name); 10931 WARN_ON(err); 10932 10933 /* Adapt owner in case owning user namespace of target network 10934 * namespace is different from the original one. 10935 */ 10936 err = netdev_change_owner(dev, net_old, net); 10937 WARN_ON(err); 10938 10939 /* Add the device back in the hashes */ 10940 list_netdevice(dev); 10941 10942 /* Notify protocols, that a new device appeared. */ 10943 call_netdevice_notifiers(NETDEV_REGISTER, dev); 10944 10945 /* 10946 * Prevent userspace races by waiting until the network 10947 * device is fully setup before sending notifications. 10948 */ 10949 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL); 10950 10951 synchronize_net(); 10952 err = 0; 10953 out: 10954 return err; 10955 } 10956 EXPORT_SYMBOL_GPL(__dev_change_net_namespace); 10957 10958 static int dev_cpu_dead(unsigned int oldcpu) 10959 { 10960 struct sk_buff **list_skb; 10961 struct sk_buff *skb; 10962 unsigned int cpu; 10963 struct softnet_data *sd, *oldsd, *remsd = NULL; 10964 10965 local_irq_disable(); 10966 cpu = smp_processor_id(); 10967 sd = &per_cpu(softnet_data, cpu); 10968 oldsd = &per_cpu(softnet_data, oldcpu); 10969 10970 /* Find end of our completion_queue. */ 10971 list_skb = &sd->completion_queue; 10972 while (*list_skb) 10973 list_skb = &(*list_skb)->next; 10974 /* Append completion queue from offline CPU. */ 10975 *list_skb = oldsd->completion_queue; 10976 oldsd->completion_queue = NULL; 10977 10978 /* Append output queue from offline CPU. */ 10979 if (oldsd->output_queue) { 10980 *sd->output_queue_tailp = oldsd->output_queue; 10981 sd->output_queue_tailp = oldsd->output_queue_tailp; 10982 oldsd->output_queue = NULL; 10983 oldsd->output_queue_tailp = &oldsd->output_queue; 10984 } 10985 /* Append NAPI poll list from offline CPU, with one exception : 10986 * process_backlog() must be called by cpu owning percpu backlog. 10987 * We properly handle process_queue & input_pkt_queue later. 10988 */ 10989 while (!list_empty(&oldsd->poll_list)) { 10990 struct napi_struct *napi = list_first_entry(&oldsd->poll_list, 10991 struct napi_struct, 10992 poll_list); 10993 10994 list_del_init(&napi->poll_list); 10995 if (napi->poll == process_backlog) 10996 napi->state = 0; 10997 else 10998 ____napi_schedule(sd, napi); 10999 } 11000 11001 raise_softirq_irqoff(NET_TX_SOFTIRQ); 11002 local_irq_enable(); 11003 11004 #ifdef CONFIG_RPS 11005 remsd = oldsd->rps_ipi_list; 11006 oldsd->rps_ipi_list = NULL; 11007 #endif 11008 /* send out pending IPI's on offline CPU */ 11009 net_rps_send_ipi(remsd); 11010 11011 /* Process offline CPU's input_pkt_queue */ 11012 while ((skb = __skb_dequeue(&oldsd->process_queue))) { 11013 netif_rx(skb); 11014 input_queue_head_incr(oldsd); 11015 } 11016 while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) { 11017 netif_rx(skb); 11018 input_queue_head_incr(oldsd); 11019 } 11020 11021 return 0; 11022 } 11023 11024 /** 11025 * netdev_increment_features - increment feature set by one 11026 * @all: current feature set 11027 * @one: new feature set 11028 * @mask: mask feature set 11029 * 11030 * Computes a new feature set after adding a device with feature set 11031 * @one to the master device with current feature set @all. Will not 11032 * enable anything that is off in @mask. Returns the new feature set. 11033 */ 11034 netdev_features_t netdev_increment_features(netdev_features_t all, 11035 netdev_features_t one, netdev_features_t mask) 11036 { 11037 if (mask & NETIF_F_HW_CSUM) 11038 mask |= NETIF_F_CSUM_MASK; 11039 mask |= NETIF_F_VLAN_CHALLENGED; 11040 11041 all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask; 11042 all &= one | ~NETIF_F_ALL_FOR_ALL; 11043 11044 /* If one device supports hw checksumming, set for all. */ 11045 if (all & NETIF_F_HW_CSUM) 11046 all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM); 11047 11048 return all; 11049 } 11050 EXPORT_SYMBOL(netdev_increment_features); 11051 11052 static struct hlist_head * __net_init netdev_create_hash(void) 11053 { 11054 int i; 11055 struct hlist_head *hash; 11056 11057 hash = kmalloc_array(NETDEV_HASHENTRIES, sizeof(*hash), GFP_KERNEL); 11058 if (hash != NULL) 11059 for (i = 0; i < NETDEV_HASHENTRIES; i++) 11060 INIT_HLIST_HEAD(&hash[i]); 11061 11062 return hash; 11063 } 11064 11065 /* Initialize per network namespace state */ 11066 static int __net_init netdev_init(struct net *net) 11067 { 11068 BUILD_BUG_ON(GRO_HASH_BUCKETS > 11069 8 * sizeof_field(struct napi_struct, gro_bitmask)); 11070 11071 INIT_LIST_HEAD(&net->dev_base_head); 11072 11073 net->dev_name_head = netdev_create_hash(); 11074 if (net->dev_name_head == NULL) 11075 goto err_name; 11076 11077 net->dev_index_head = netdev_create_hash(); 11078 if (net->dev_index_head == NULL) 11079 goto err_idx; 11080 11081 RAW_INIT_NOTIFIER_HEAD(&net->netdev_chain); 11082 11083 return 0; 11084 11085 err_idx: 11086 kfree(net->dev_name_head); 11087 err_name: 11088 return -ENOMEM; 11089 } 11090 11091 /** 11092 * netdev_drivername - network driver for the device 11093 * @dev: network device 11094 * 11095 * Determine network driver for device. 11096 */ 11097 const char *netdev_drivername(const struct net_device *dev) 11098 { 11099 const struct device_driver *driver; 11100 const struct device *parent; 11101 const char *empty = ""; 11102 11103 parent = dev->dev.parent; 11104 if (!parent) 11105 return empty; 11106 11107 driver = parent->driver; 11108 if (driver && driver->name) 11109 return driver->name; 11110 return empty; 11111 } 11112 11113 static void __netdev_printk(const char *level, const struct net_device *dev, 11114 struct va_format *vaf) 11115 { 11116 if (dev && dev->dev.parent) { 11117 dev_printk_emit(level[1] - '0', 11118 dev->dev.parent, 11119 "%s %s %s%s: %pV", 11120 dev_driver_string(dev->dev.parent), 11121 dev_name(dev->dev.parent), 11122 netdev_name(dev), netdev_reg_state(dev), 11123 vaf); 11124 } else if (dev) { 11125 printk("%s%s%s: %pV", 11126 level, netdev_name(dev), netdev_reg_state(dev), vaf); 11127 } else { 11128 printk("%s(NULL net_device): %pV", level, vaf); 11129 } 11130 } 11131 11132 void netdev_printk(const char *level, const struct net_device *dev, 11133 const char *format, ...) 11134 { 11135 struct va_format vaf; 11136 va_list args; 11137 11138 va_start(args, format); 11139 11140 vaf.fmt = format; 11141 vaf.va = &args; 11142 11143 __netdev_printk(level, dev, &vaf); 11144 11145 va_end(args); 11146 } 11147 EXPORT_SYMBOL(netdev_printk); 11148 11149 #define define_netdev_printk_level(func, level) \ 11150 void func(const struct net_device *dev, const char *fmt, ...) \ 11151 { \ 11152 struct va_format vaf; \ 11153 va_list args; \ 11154 \ 11155 va_start(args, fmt); \ 11156 \ 11157 vaf.fmt = fmt; \ 11158 vaf.va = &args; \ 11159 \ 11160 __netdev_printk(level, dev, &vaf); \ 11161 \ 11162 va_end(args); \ 11163 } \ 11164 EXPORT_SYMBOL(func); 11165 11166 define_netdev_printk_level(netdev_emerg, KERN_EMERG); 11167 define_netdev_printk_level(netdev_alert, KERN_ALERT); 11168 define_netdev_printk_level(netdev_crit, KERN_CRIT); 11169 define_netdev_printk_level(netdev_err, KERN_ERR); 11170 define_netdev_printk_level(netdev_warn, KERN_WARNING); 11171 define_netdev_printk_level(netdev_notice, KERN_NOTICE); 11172 define_netdev_printk_level(netdev_info, KERN_INFO); 11173 11174 static void __net_exit netdev_exit(struct net *net) 11175 { 11176 kfree(net->dev_name_head); 11177 kfree(net->dev_index_head); 11178 if (net != &init_net) 11179 WARN_ON_ONCE(!list_empty(&net->dev_base_head)); 11180 } 11181 11182 static struct pernet_operations __net_initdata netdev_net_ops = { 11183 .init = netdev_init, 11184 .exit = netdev_exit, 11185 }; 11186 11187 static void __net_exit default_device_exit_net(struct net *net) 11188 { 11189 struct net_device *dev, *aux; 11190 /* 11191 * Push all migratable network devices back to the 11192 * initial network namespace 11193 */ 11194 ASSERT_RTNL(); 11195 for_each_netdev_safe(net, dev, aux) { 11196 int err; 11197 char fb_name[IFNAMSIZ]; 11198 11199 /* Ignore unmoveable devices (i.e. loopback) */ 11200 if (dev->features & NETIF_F_NETNS_LOCAL) 11201 continue; 11202 11203 /* Leave virtual devices for the generic cleanup */ 11204 if (dev->rtnl_link_ops && !dev->rtnl_link_ops->netns_refund) 11205 continue; 11206 11207 /* Push remaining network devices to init_net */ 11208 snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex); 11209 if (netdev_name_in_use(&init_net, fb_name)) 11210 snprintf(fb_name, IFNAMSIZ, "dev%%d"); 11211 err = dev_change_net_namespace(dev, &init_net, fb_name); 11212 if (err) { 11213 pr_emerg("%s: failed to move %s to init_net: %d\n", 11214 __func__, dev->name, err); 11215 BUG(); 11216 } 11217 } 11218 } 11219 11220 static void __net_exit default_device_exit_batch(struct list_head *net_list) 11221 { 11222 /* At exit all network devices most be removed from a network 11223 * namespace. Do this in the reverse order of registration. 11224 * Do this across as many network namespaces as possible to 11225 * improve batching efficiency. 11226 */ 11227 struct net_device *dev; 11228 struct net *net; 11229 LIST_HEAD(dev_kill_list); 11230 11231 rtnl_lock(); 11232 list_for_each_entry(net, net_list, exit_list) { 11233 default_device_exit_net(net); 11234 cond_resched(); 11235 } 11236 11237 list_for_each_entry(net, net_list, exit_list) { 11238 for_each_netdev_reverse(net, dev) { 11239 if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink) 11240 dev->rtnl_link_ops->dellink(dev, &dev_kill_list); 11241 else 11242 unregister_netdevice_queue(dev, &dev_kill_list); 11243 } 11244 } 11245 unregister_netdevice_many(&dev_kill_list); 11246 rtnl_unlock(); 11247 } 11248 11249 static struct pernet_operations __net_initdata default_device_ops = { 11250 .exit_batch = default_device_exit_batch, 11251 }; 11252 11253 /* 11254 * Initialize the DEV module. At boot time this walks the device list and 11255 * unhooks any devices that fail to initialise (normally hardware not 11256 * present) and leaves us with a valid list of present and active devices. 11257 * 11258 */ 11259 11260 /* 11261 * This is called single threaded during boot, so no need 11262 * to take the rtnl semaphore. 11263 */ 11264 static int __init net_dev_init(void) 11265 { 11266 int i, rc = -ENOMEM; 11267 11268 BUG_ON(!dev_boot_phase); 11269 11270 if (dev_proc_init()) 11271 goto out; 11272 11273 if (netdev_kobject_init()) 11274 goto out; 11275 11276 INIT_LIST_HEAD(&ptype_all); 11277 for (i = 0; i < PTYPE_HASH_SIZE; i++) 11278 INIT_LIST_HEAD(&ptype_base[i]); 11279 11280 if (register_pernet_subsys(&netdev_net_ops)) 11281 goto out; 11282 11283 /* 11284 * Initialise the packet receive queues. 11285 */ 11286 11287 for_each_possible_cpu(i) { 11288 struct work_struct *flush = per_cpu_ptr(&flush_works, i); 11289 struct softnet_data *sd = &per_cpu(softnet_data, i); 11290 11291 INIT_WORK(flush, flush_backlog); 11292 11293 skb_queue_head_init(&sd->input_pkt_queue); 11294 skb_queue_head_init(&sd->process_queue); 11295 #ifdef CONFIG_XFRM_OFFLOAD 11296 skb_queue_head_init(&sd->xfrm_backlog); 11297 #endif 11298 INIT_LIST_HEAD(&sd->poll_list); 11299 sd->output_queue_tailp = &sd->output_queue; 11300 #ifdef CONFIG_RPS 11301 INIT_CSD(&sd->csd, rps_trigger_softirq, sd); 11302 sd->cpu = i; 11303 #endif 11304 11305 init_gro_hash(&sd->backlog); 11306 sd->backlog.poll = process_backlog; 11307 sd->backlog.weight = weight_p; 11308 } 11309 11310 dev_boot_phase = 0; 11311 11312 /* The loopback device is special if any other network devices 11313 * is present in a network namespace the loopback device must 11314 * be present. Since we now dynamically allocate and free the 11315 * loopback device ensure this invariant is maintained by 11316 * keeping the loopback device as the first device on the 11317 * list of network devices. Ensuring the loopback devices 11318 * is the first device that appears and the last network device 11319 * that disappears. 11320 */ 11321 if (register_pernet_device(&loopback_net_ops)) 11322 goto out; 11323 11324 if (register_pernet_device(&default_device_ops)) 11325 goto out; 11326 11327 open_softirq(NET_TX_SOFTIRQ, net_tx_action); 11328 open_softirq(NET_RX_SOFTIRQ, net_rx_action); 11329 11330 rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead", 11331 NULL, dev_cpu_dead); 11332 WARN_ON(rc < 0); 11333 rc = 0; 11334 out: 11335 return rc; 11336 } 11337 11338 subsys_initcall(net_dev_init); 11339