1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * NET3 Protocol independent device support routines.
5 * Derived from the non IP parts of dev.c 1.0.19
7 * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
8 * Mark Evans, <evansmp@uhura.aston.ac.uk>
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>
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
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
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
47 * Rudi Cilibrasi : Pass the right thing to
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
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
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
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>
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/bpf.h>
95 #include <linux/bpf_trace.h>
96 #include <net/net_namespace.h>
98 #include <net/busy_poll.h>
99 #include <linux/rtnetlink.h>
100 #include <linux/stat.h>
103 #include <net/dst_metadata.h>
104 #include <net/pkt_sched.h>
105 #include <net/pkt_cls.h>
106 #include <net/checksum.h>
107 #include <net/xfrm.h>
108 #include <linux/highmem.h>
109 #include <linux/init.h>
110 #include <linux/module.h>
111 #include <linux/netpoll.h>
112 #include <linux/rcupdate.h>
113 #include <linux/delay.h>
114 #include <net/iw_handler.h>
115 #include <asm/current.h>
116 #include <linux/audit.h>
117 #include <linux/dmaengine.h>
118 #include <linux/err.h>
119 #include <linux/ctype.h>
120 #include <linux/if_arp.h>
121 #include <linux/if_vlan.h>
122 #include <linux/ip.h>
124 #include <net/mpls.h>
125 #include <linux/ipv6.h>
126 #include <linux/in.h>
127 #include <linux/jhash.h>
128 #include <linux/random.h>
129 #include <trace/events/napi.h>
130 #include <trace/events/net.h>
131 #include <trace/events/skb.h>
132 #include <linux/inetdevice.h>
133 #include <linux/cpu_rmap.h>
134 #include <linux/static_key.h>
135 #include <linux/hashtable.h>
136 #include <linux/vmalloc.h>
137 #include <linux/if_macvlan.h>
138 #include <linux/errqueue.h>
139 #include <linux/hrtimer.h>
140 #include <linux/netfilter_ingress.h>
141 #include <linux/crash_dump.h>
142 #include <linux/sctp.h>
143 #include <net/udp_tunnel.h>
144 #include <linux/net_namespace.h>
145 #include <linux/indirect_call_wrapper.h>
146 #include <net/devlink.h>
147 #include <linux/pm_runtime.h>
149 #include "net-sysfs.h"
151 #define MAX_GRO_SKBS 8
153 /* This should be increased if a protocol with a bigger head is added. */
154 #define GRO_MAX_HEAD (MAX_HEADER + 128)
156 static DEFINE_SPINLOCK(ptype_lock);
157 static DEFINE_SPINLOCK(offload_lock);
158 struct list_head ptype_base[PTYPE_HASH_SIZE] __read_mostly;
159 struct list_head ptype_all __read_mostly; /* Taps */
160 static struct list_head offload_base __read_mostly;
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);
171 * The @dev_base_head list is protected by @dev_base_lock and the rtnl
174 * Pure readers hold dev_base_lock for reading, or rcu_read_lock()
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.
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.
185 * See, for example usages, register_netdevice() and
186 * unregister_netdevice(), which must be called with the rtnl
189 DEFINE_RWLOCK(dev_base_lock);
190 EXPORT_SYMBOL(dev_base_lock);
192 static DEFINE_MUTEX(ifalias_mutex);
194 /* protects napi_hash addition/deletion and napi_gen_id */
195 static DEFINE_SPINLOCK(napi_hash_lock);
197 static unsigned int napi_gen_id = NR_CPUS;
198 static DEFINE_READ_MOSTLY_HASHTABLE(napi_hash, 8);
200 static DECLARE_RWSEM(devnet_rename_sem);
202 static inline void dev_base_seq_inc(struct net *net)
204 while (++net->dev_base_seq == 0)
208 static inline struct hlist_head *dev_name_hash(struct net *net, const char *name)
210 unsigned int hash = full_name_hash(net, name, strnlen(name, IFNAMSIZ));
212 return &net->dev_name_head[hash_32(hash, NETDEV_HASHBITS)];
215 static inline struct hlist_head *dev_index_hash(struct net *net, int ifindex)
217 return &net->dev_index_head[ifindex & (NETDEV_HASHENTRIES - 1)];
220 static inline void rps_lock(struct softnet_data *sd)
223 spin_lock(&sd->input_pkt_queue.lock);
227 static inline void rps_unlock(struct softnet_data *sd)
230 spin_unlock(&sd->input_pkt_queue.lock);
234 static struct netdev_name_node *netdev_name_node_alloc(struct net_device *dev,
237 struct netdev_name_node *name_node;
239 name_node = kmalloc(sizeof(*name_node), GFP_KERNEL);
242 INIT_HLIST_NODE(&name_node->hlist);
243 name_node->dev = dev;
244 name_node->name = name;
248 static struct netdev_name_node *
249 netdev_name_node_head_alloc(struct net_device *dev)
251 struct netdev_name_node *name_node;
253 name_node = netdev_name_node_alloc(dev, dev->name);
256 INIT_LIST_HEAD(&name_node->list);
260 static void netdev_name_node_free(struct netdev_name_node *name_node)
265 static void netdev_name_node_add(struct net *net,
266 struct netdev_name_node *name_node)
268 hlist_add_head_rcu(&name_node->hlist,
269 dev_name_hash(net, name_node->name));
272 static void netdev_name_node_del(struct netdev_name_node *name_node)
274 hlist_del_rcu(&name_node->hlist);
277 static struct netdev_name_node *netdev_name_node_lookup(struct net *net,
280 struct hlist_head *head = dev_name_hash(net, name);
281 struct netdev_name_node *name_node;
283 hlist_for_each_entry(name_node, head, hlist)
284 if (!strcmp(name_node->name, name))
289 static struct netdev_name_node *netdev_name_node_lookup_rcu(struct net *net,
292 struct hlist_head *head = dev_name_hash(net, name);
293 struct netdev_name_node *name_node;
295 hlist_for_each_entry_rcu(name_node, head, hlist)
296 if (!strcmp(name_node->name, name))
301 int netdev_name_node_alt_create(struct net_device *dev, const char *name)
303 struct netdev_name_node *name_node;
304 struct net *net = dev_net(dev);
306 name_node = netdev_name_node_lookup(net, name);
309 name_node = netdev_name_node_alloc(dev, name);
312 netdev_name_node_add(net, name_node);
313 /* The node that holds dev->name acts as a head of per-device list. */
314 list_add_tail(&name_node->list, &dev->name_node->list);
318 EXPORT_SYMBOL(netdev_name_node_alt_create);
320 static void __netdev_name_node_alt_destroy(struct netdev_name_node *name_node)
322 list_del(&name_node->list);
323 netdev_name_node_del(name_node);
324 kfree(name_node->name);
325 netdev_name_node_free(name_node);
328 int netdev_name_node_alt_destroy(struct net_device *dev, const char *name)
330 struct netdev_name_node *name_node;
331 struct net *net = dev_net(dev);
333 name_node = netdev_name_node_lookup(net, name);
336 /* lookup might have found our primary name or a name belonging
339 if (name_node == dev->name_node || name_node->dev != dev)
342 __netdev_name_node_alt_destroy(name_node);
346 EXPORT_SYMBOL(netdev_name_node_alt_destroy);
348 static void netdev_name_node_alt_flush(struct net_device *dev)
350 struct netdev_name_node *name_node, *tmp;
352 list_for_each_entry_safe(name_node, tmp, &dev->name_node->list, list)
353 __netdev_name_node_alt_destroy(name_node);
356 /* Device list insertion */
357 static void list_netdevice(struct net_device *dev)
359 struct net *net = dev_net(dev);
363 write_lock_bh(&dev_base_lock);
364 list_add_tail_rcu(&dev->dev_list, &net->dev_base_head);
365 netdev_name_node_add(net, dev->name_node);
366 hlist_add_head_rcu(&dev->index_hlist,
367 dev_index_hash(net, dev->ifindex));
368 write_unlock_bh(&dev_base_lock);
370 dev_base_seq_inc(net);
373 /* Device list removal
374 * caller must respect a RCU grace period before freeing/reusing dev
376 static void unlist_netdevice(struct net_device *dev)
380 /* Unlink dev from the device chain */
381 write_lock_bh(&dev_base_lock);
382 list_del_rcu(&dev->dev_list);
383 netdev_name_node_del(dev->name_node);
384 hlist_del_rcu(&dev->index_hlist);
385 write_unlock_bh(&dev_base_lock);
387 dev_base_seq_inc(dev_net(dev));
394 static RAW_NOTIFIER_HEAD(netdev_chain);
397 * Device drivers call our routines to queue packets here. We empty the
398 * queue in the local softnet handler.
401 DEFINE_PER_CPU_ALIGNED(struct softnet_data, softnet_data);
402 EXPORT_PER_CPU_SYMBOL(softnet_data);
404 #ifdef CONFIG_LOCKDEP
406 * register_netdevice() inits txq->_xmit_lock and sets lockdep class
407 * according to dev->type
409 static const unsigned short netdev_lock_type[] = {
410 ARPHRD_NETROM, ARPHRD_ETHER, ARPHRD_EETHER, ARPHRD_AX25,
411 ARPHRD_PRONET, ARPHRD_CHAOS, ARPHRD_IEEE802, ARPHRD_ARCNET,
412 ARPHRD_APPLETLK, ARPHRD_DLCI, ARPHRD_ATM, ARPHRD_METRICOM,
413 ARPHRD_IEEE1394, ARPHRD_EUI64, ARPHRD_INFINIBAND, ARPHRD_SLIP,
414 ARPHRD_CSLIP, ARPHRD_SLIP6, ARPHRD_CSLIP6, ARPHRD_RSRVD,
415 ARPHRD_ADAPT, ARPHRD_ROSE, ARPHRD_X25, ARPHRD_HWX25,
416 ARPHRD_PPP, ARPHRD_CISCO, ARPHRD_LAPB, ARPHRD_DDCMP,
417 ARPHRD_RAWHDLC, ARPHRD_TUNNEL, ARPHRD_TUNNEL6, ARPHRD_FRAD,
418 ARPHRD_SKIP, ARPHRD_LOOPBACK, ARPHRD_LOCALTLK, ARPHRD_FDDI,
419 ARPHRD_BIF, ARPHRD_SIT, ARPHRD_IPDDP, ARPHRD_IPGRE,
420 ARPHRD_PIMREG, ARPHRD_HIPPI, ARPHRD_ASH, ARPHRD_ECONET,
421 ARPHRD_IRDA, ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL,
422 ARPHRD_FCFABRIC, ARPHRD_IEEE80211, ARPHRD_IEEE80211_PRISM,
423 ARPHRD_IEEE80211_RADIOTAP, ARPHRD_PHONET, ARPHRD_PHONET_PIPE,
424 ARPHRD_IEEE802154, ARPHRD_VOID, ARPHRD_NONE};
426 static const char *const netdev_lock_name[] = {
427 "_xmit_NETROM", "_xmit_ETHER", "_xmit_EETHER", "_xmit_AX25",
428 "_xmit_PRONET", "_xmit_CHAOS", "_xmit_IEEE802", "_xmit_ARCNET",
429 "_xmit_APPLETLK", "_xmit_DLCI", "_xmit_ATM", "_xmit_METRICOM",
430 "_xmit_IEEE1394", "_xmit_EUI64", "_xmit_INFINIBAND", "_xmit_SLIP",
431 "_xmit_CSLIP", "_xmit_SLIP6", "_xmit_CSLIP6", "_xmit_RSRVD",
432 "_xmit_ADAPT", "_xmit_ROSE", "_xmit_X25", "_xmit_HWX25",
433 "_xmit_PPP", "_xmit_CISCO", "_xmit_LAPB", "_xmit_DDCMP",
434 "_xmit_RAWHDLC", "_xmit_TUNNEL", "_xmit_TUNNEL6", "_xmit_FRAD",
435 "_xmit_SKIP", "_xmit_LOOPBACK", "_xmit_LOCALTLK", "_xmit_FDDI",
436 "_xmit_BIF", "_xmit_SIT", "_xmit_IPDDP", "_xmit_IPGRE",
437 "_xmit_PIMREG", "_xmit_HIPPI", "_xmit_ASH", "_xmit_ECONET",
438 "_xmit_IRDA", "_xmit_FCPP", "_xmit_FCAL", "_xmit_FCPL",
439 "_xmit_FCFABRIC", "_xmit_IEEE80211", "_xmit_IEEE80211_PRISM",
440 "_xmit_IEEE80211_RADIOTAP", "_xmit_PHONET", "_xmit_PHONET_PIPE",
441 "_xmit_IEEE802154", "_xmit_VOID", "_xmit_NONE"};
443 static struct lock_class_key netdev_xmit_lock_key[ARRAY_SIZE(netdev_lock_type)];
444 static struct lock_class_key netdev_addr_lock_key[ARRAY_SIZE(netdev_lock_type)];
446 static inline unsigned short netdev_lock_pos(unsigned short dev_type)
450 for (i = 0; i < ARRAY_SIZE(netdev_lock_type); i++)
451 if (netdev_lock_type[i] == dev_type)
453 /* the last key is used by default */
454 return ARRAY_SIZE(netdev_lock_type) - 1;
457 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
458 unsigned short dev_type)
462 i = netdev_lock_pos(dev_type);
463 lockdep_set_class_and_name(lock, &netdev_xmit_lock_key[i],
464 netdev_lock_name[i]);
467 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
471 i = netdev_lock_pos(dev->type);
472 lockdep_set_class_and_name(&dev->addr_list_lock,
473 &netdev_addr_lock_key[i],
474 netdev_lock_name[i]);
477 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
478 unsigned short dev_type)
482 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
487 /*******************************************************************************
489 * Protocol management and registration routines
491 *******************************************************************************/
495 * Add a protocol ID to the list. Now that the input handler is
496 * smarter we can dispense with all the messy stuff that used to be
499 * BEWARE!!! Protocol handlers, mangling input packets,
500 * MUST BE last in hash buckets and checking protocol handlers
501 * MUST start from promiscuous ptype_all chain in net_bh.
502 * It is true now, do not change it.
503 * Explanation follows: if protocol handler, mangling packet, will
504 * be the first on list, it is not able to sense, that packet
505 * is cloned and should be copied-on-write, so that it will
506 * change it and subsequent readers will get broken packet.
510 static inline struct list_head *ptype_head(const struct packet_type *pt)
512 if (pt->type == htons(ETH_P_ALL))
513 return pt->dev ? &pt->dev->ptype_all : &ptype_all;
515 return pt->dev ? &pt->dev->ptype_specific :
516 &ptype_base[ntohs(pt->type) & PTYPE_HASH_MASK];
520 * dev_add_pack - add packet handler
521 * @pt: packet type declaration
523 * Add a protocol handler to the networking stack. The passed &packet_type
524 * is linked into kernel lists and may not be freed until it has been
525 * removed from the kernel lists.
527 * This call does not sleep therefore it can not
528 * guarantee all CPU's that are in middle of receiving packets
529 * will see the new packet type (until the next received packet).
532 void dev_add_pack(struct packet_type *pt)
534 struct list_head *head = ptype_head(pt);
536 spin_lock(&ptype_lock);
537 list_add_rcu(&pt->list, head);
538 spin_unlock(&ptype_lock);
540 EXPORT_SYMBOL(dev_add_pack);
543 * __dev_remove_pack - remove packet handler
544 * @pt: packet type declaration
546 * Remove a protocol handler that was previously added to the kernel
547 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
548 * from the kernel lists and can be freed or reused once this function
551 * The packet type might still be in use by receivers
552 * and must not be freed until after all the CPU's have gone
553 * through a quiescent state.
555 void __dev_remove_pack(struct packet_type *pt)
557 struct list_head *head = ptype_head(pt);
558 struct packet_type *pt1;
560 spin_lock(&ptype_lock);
562 list_for_each_entry(pt1, head, list) {
564 list_del_rcu(&pt->list);
569 pr_warn("dev_remove_pack: %p not found\n", pt);
571 spin_unlock(&ptype_lock);
573 EXPORT_SYMBOL(__dev_remove_pack);
576 * dev_remove_pack - remove packet handler
577 * @pt: packet type declaration
579 * Remove a protocol handler that was previously added to the kernel
580 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
581 * from the kernel lists and can be freed or reused once this function
584 * This call sleeps to guarantee that no CPU is looking at the packet
587 void dev_remove_pack(struct packet_type *pt)
589 __dev_remove_pack(pt);
593 EXPORT_SYMBOL(dev_remove_pack);
597 * dev_add_offload - register offload handlers
598 * @po: protocol offload declaration
600 * Add protocol offload handlers to the networking stack. The passed
601 * &proto_offload is linked into kernel lists and may not be freed until
602 * it has been removed from the kernel lists.
604 * This call does not sleep therefore it can not
605 * guarantee all CPU's that are in middle of receiving packets
606 * will see the new offload handlers (until the next received packet).
608 void dev_add_offload(struct packet_offload *po)
610 struct packet_offload *elem;
612 spin_lock(&offload_lock);
613 list_for_each_entry(elem, &offload_base, list) {
614 if (po->priority < elem->priority)
617 list_add_rcu(&po->list, elem->list.prev);
618 spin_unlock(&offload_lock);
620 EXPORT_SYMBOL(dev_add_offload);
623 * __dev_remove_offload - remove offload handler
624 * @po: packet offload declaration
626 * Remove a protocol offload handler that was previously added to the
627 * kernel offload handlers by dev_add_offload(). The passed &offload_type
628 * is removed from the kernel lists and can be freed or reused once this
631 * The packet type might still be in use by receivers
632 * and must not be freed until after all the CPU's have gone
633 * through a quiescent state.
635 static void __dev_remove_offload(struct packet_offload *po)
637 struct list_head *head = &offload_base;
638 struct packet_offload *po1;
640 spin_lock(&offload_lock);
642 list_for_each_entry(po1, head, list) {
644 list_del_rcu(&po->list);
649 pr_warn("dev_remove_offload: %p not found\n", po);
651 spin_unlock(&offload_lock);
655 * dev_remove_offload - remove packet offload handler
656 * @po: packet offload declaration
658 * Remove a packet offload handler that was previously added to the kernel
659 * offload handlers by dev_add_offload(). The passed &offload_type is
660 * removed from the kernel lists and can be freed or reused once this
663 * This call sleeps to guarantee that no CPU is looking at the packet
666 void dev_remove_offload(struct packet_offload *po)
668 __dev_remove_offload(po);
672 EXPORT_SYMBOL(dev_remove_offload);
674 /******************************************************************************
676 * Device Boot-time Settings Routines
678 ******************************************************************************/
680 /* Boot time configuration table */
681 static struct netdev_boot_setup dev_boot_setup[NETDEV_BOOT_SETUP_MAX];
684 * netdev_boot_setup_add - add new setup entry
685 * @name: name of the device
686 * @map: configured settings for the device
688 * Adds new setup entry to the dev_boot_setup list. The function
689 * returns 0 on error and 1 on success. This is a generic routine to
692 static int netdev_boot_setup_add(char *name, struct ifmap *map)
694 struct netdev_boot_setup *s;
698 for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
699 if (s[i].name[0] == '\0' || s[i].name[0] == ' ') {
700 memset(s[i].name, 0, sizeof(s[i].name));
701 strlcpy(s[i].name, name, IFNAMSIZ);
702 memcpy(&s[i].map, map, sizeof(s[i].map));
707 return i >= NETDEV_BOOT_SETUP_MAX ? 0 : 1;
711 * netdev_boot_setup_check - check boot time settings
712 * @dev: the netdevice
714 * Check boot time settings for the device.
715 * The found settings are set for the device to be used
716 * later in the device probing.
717 * Returns 0 if no settings found, 1 if they are.
719 int netdev_boot_setup_check(struct net_device *dev)
721 struct netdev_boot_setup *s = dev_boot_setup;
724 for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
725 if (s[i].name[0] != '\0' && s[i].name[0] != ' ' &&
726 !strcmp(dev->name, s[i].name)) {
727 dev->irq = s[i].map.irq;
728 dev->base_addr = s[i].map.base_addr;
729 dev->mem_start = s[i].map.mem_start;
730 dev->mem_end = s[i].map.mem_end;
736 EXPORT_SYMBOL(netdev_boot_setup_check);
740 * netdev_boot_base - get address from boot time settings
741 * @prefix: prefix for network device
742 * @unit: id for network device
744 * Check boot time settings for the base address of device.
745 * The found settings are set for the device to be used
746 * later in the device probing.
747 * Returns 0 if no settings found.
749 unsigned long netdev_boot_base(const char *prefix, int unit)
751 const struct netdev_boot_setup *s = dev_boot_setup;
755 sprintf(name, "%s%d", prefix, unit);
758 * If device already registered then return base of 1
759 * to indicate not to probe for this interface
761 if (__dev_get_by_name(&init_net, name))
764 for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++)
765 if (!strcmp(name, s[i].name))
766 return s[i].map.base_addr;
771 * Saves at boot time configured settings for any netdevice.
773 int __init netdev_boot_setup(char *str)
778 str = get_options(str, ARRAY_SIZE(ints), ints);
783 memset(&map, 0, sizeof(map));
787 map.base_addr = ints[2];
789 map.mem_start = ints[3];
791 map.mem_end = ints[4];
793 /* Add new entry to the list */
794 return netdev_boot_setup_add(str, &map);
797 __setup("netdev=", netdev_boot_setup);
799 /*******************************************************************************
801 * Device Interface Subroutines
803 *******************************************************************************/
806 * dev_get_iflink - get 'iflink' value of a interface
807 * @dev: targeted interface
809 * Indicates the ifindex the interface is linked to.
810 * Physical interfaces have the same 'ifindex' and 'iflink' values.
813 int dev_get_iflink(const struct net_device *dev)
815 if (dev->netdev_ops && dev->netdev_ops->ndo_get_iflink)
816 return dev->netdev_ops->ndo_get_iflink(dev);
820 EXPORT_SYMBOL(dev_get_iflink);
823 * dev_fill_metadata_dst - Retrieve tunnel egress information.
824 * @dev: targeted interface
827 * For better visibility of tunnel traffic OVS needs to retrieve
828 * egress tunnel information for a packet. Following API allows
829 * user to get this info.
831 int dev_fill_metadata_dst(struct net_device *dev, struct sk_buff *skb)
833 struct ip_tunnel_info *info;
835 if (!dev->netdev_ops || !dev->netdev_ops->ndo_fill_metadata_dst)
838 info = skb_tunnel_info_unclone(skb);
841 if (unlikely(!(info->mode & IP_TUNNEL_INFO_TX)))
844 return dev->netdev_ops->ndo_fill_metadata_dst(dev, skb);
846 EXPORT_SYMBOL_GPL(dev_fill_metadata_dst);
849 * __dev_get_by_name - find a device by its name
850 * @net: the applicable net namespace
851 * @name: name to find
853 * Find an interface by name. Must be called under RTNL semaphore
854 * or @dev_base_lock. If the name is found a pointer to the device
855 * is returned. If the name is not found then %NULL is returned. The
856 * reference counters are not incremented so the caller must be
857 * careful with locks.
860 struct net_device *__dev_get_by_name(struct net *net, const char *name)
862 struct netdev_name_node *node_name;
864 node_name = netdev_name_node_lookup(net, name);
865 return node_name ? node_name->dev : NULL;
867 EXPORT_SYMBOL(__dev_get_by_name);
870 * dev_get_by_name_rcu - find a device by its name
871 * @net: the applicable net namespace
872 * @name: name to find
874 * Find an interface by name.
875 * If the name is found a pointer to the device is returned.
876 * If the name is not found then %NULL is returned.
877 * The reference counters are not incremented so the caller must be
878 * careful with locks. The caller must hold RCU lock.
881 struct net_device *dev_get_by_name_rcu(struct net *net, const char *name)
883 struct netdev_name_node *node_name;
885 node_name = netdev_name_node_lookup_rcu(net, name);
886 return node_name ? node_name->dev : NULL;
888 EXPORT_SYMBOL(dev_get_by_name_rcu);
891 * dev_get_by_name - find a device by its name
892 * @net: the applicable net namespace
893 * @name: name to find
895 * Find an interface by name. This can be called from any
896 * context and does its own locking. The returned handle has
897 * the usage count incremented and the caller must use dev_put() to
898 * release it when it is no longer needed. %NULL is returned if no
899 * matching device is found.
902 struct net_device *dev_get_by_name(struct net *net, const char *name)
904 struct net_device *dev;
907 dev = dev_get_by_name_rcu(net, name);
913 EXPORT_SYMBOL(dev_get_by_name);
916 * __dev_get_by_index - find a device by its ifindex
917 * @net: the applicable net namespace
918 * @ifindex: index of device
920 * Search for an interface by index. Returns %NULL if the device
921 * is not found or a pointer to the device. The device has not
922 * had its reference counter increased so the caller must be careful
923 * about locking. The caller must hold either the RTNL semaphore
927 struct net_device *__dev_get_by_index(struct net *net, int ifindex)
929 struct net_device *dev;
930 struct hlist_head *head = dev_index_hash(net, ifindex);
932 hlist_for_each_entry(dev, head, index_hlist)
933 if (dev->ifindex == ifindex)
938 EXPORT_SYMBOL(__dev_get_by_index);
941 * dev_get_by_index_rcu - find a device by its ifindex
942 * @net: the applicable net namespace
943 * @ifindex: index of device
945 * Search for an interface by index. Returns %NULL if the device
946 * is not found or a pointer to the device. The device has not
947 * had its reference counter increased so the caller must be careful
948 * about locking. The caller must hold RCU lock.
951 struct net_device *dev_get_by_index_rcu(struct net *net, int ifindex)
953 struct net_device *dev;
954 struct hlist_head *head = dev_index_hash(net, ifindex);
956 hlist_for_each_entry_rcu(dev, head, index_hlist)
957 if (dev->ifindex == ifindex)
962 EXPORT_SYMBOL(dev_get_by_index_rcu);
966 * dev_get_by_index - find a device by its ifindex
967 * @net: the applicable net namespace
968 * @ifindex: index of device
970 * Search for an interface by index. Returns NULL if the device
971 * is not found or a pointer to the device. The device returned has
972 * had a reference added and the pointer is safe until the user calls
973 * dev_put to indicate they have finished with it.
976 struct net_device *dev_get_by_index(struct net *net, int ifindex)
978 struct net_device *dev;
981 dev = dev_get_by_index_rcu(net, ifindex);
987 EXPORT_SYMBOL(dev_get_by_index);
990 * dev_get_by_napi_id - find a device by napi_id
991 * @napi_id: ID of the NAPI struct
993 * Search for an interface by NAPI ID. Returns %NULL if the device
994 * is not found or a pointer to the device. The device has not had
995 * its reference counter increased so the caller must be careful
996 * about locking. The caller must hold RCU lock.
999 struct net_device *dev_get_by_napi_id(unsigned int napi_id)
1001 struct napi_struct *napi;
1003 WARN_ON_ONCE(!rcu_read_lock_held());
1005 if (napi_id < MIN_NAPI_ID)
1008 napi = napi_by_id(napi_id);
1010 return napi ? napi->dev : NULL;
1012 EXPORT_SYMBOL(dev_get_by_napi_id);
1015 * netdev_get_name - get a netdevice name, knowing its ifindex.
1016 * @net: network namespace
1017 * @name: a pointer to the buffer where the name will be stored.
1018 * @ifindex: the ifindex of the interface to get the name from.
1020 int netdev_get_name(struct net *net, char *name, int ifindex)
1022 struct net_device *dev;
1025 down_read(&devnet_rename_sem);
1028 dev = dev_get_by_index_rcu(net, ifindex);
1034 strcpy(name, dev->name);
1039 up_read(&devnet_rename_sem);
1044 * dev_getbyhwaddr_rcu - find a device by its hardware address
1045 * @net: the applicable net namespace
1046 * @type: media type of device
1047 * @ha: hardware address
1049 * Search for an interface by MAC address. Returns NULL if the device
1050 * is not found or a pointer to the device.
1051 * The caller must hold RCU or RTNL.
1052 * The returned device has not had its ref count increased
1053 * and the caller must therefore be careful about locking
1057 struct net_device *dev_getbyhwaddr_rcu(struct net *net, unsigned short type,
1060 struct net_device *dev;
1062 for_each_netdev_rcu(net, dev)
1063 if (dev->type == type &&
1064 !memcmp(dev->dev_addr, ha, dev->addr_len))
1069 EXPORT_SYMBOL(dev_getbyhwaddr_rcu);
1071 struct net_device *__dev_getfirstbyhwtype(struct net *net, unsigned short type)
1073 struct net_device *dev;
1076 for_each_netdev(net, dev)
1077 if (dev->type == type)
1082 EXPORT_SYMBOL(__dev_getfirstbyhwtype);
1084 struct net_device *dev_getfirstbyhwtype(struct net *net, unsigned short type)
1086 struct net_device *dev, *ret = NULL;
1089 for_each_netdev_rcu(net, dev)
1090 if (dev->type == type) {
1098 EXPORT_SYMBOL(dev_getfirstbyhwtype);
1101 * __dev_get_by_flags - find any device with given flags
1102 * @net: the applicable net namespace
1103 * @if_flags: IFF_* values
1104 * @mask: bitmask of bits in if_flags to check
1106 * Search for any interface with the given flags. Returns NULL if a device
1107 * is not found or a pointer to the device. Must be called inside
1108 * rtnl_lock(), and result refcount is unchanged.
1111 struct net_device *__dev_get_by_flags(struct net *net, unsigned short if_flags,
1112 unsigned short mask)
1114 struct net_device *dev, *ret;
1119 for_each_netdev(net, dev) {
1120 if (((dev->flags ^ if_flags) & mask) == 0) {
1127 EXPORT_SYMBOL(__dev_get_by_flags);
1130 * dev_valid_name - check if name is okay for network device
1131 * @name: name string
1133 * Network device names need to be valid file names to
1134 * allow sysfs to work. We also disallow any kind of
1137 bool dev_valid_name(const char *name)
1141 if (strnlen(name, IFNAMSIZ) == IFNAMSIZ)
1143 if (!strcmp(name, ".") || !strcmp(name, ".."))
1147 if (*name == '/' || *name == ':' || isspace(*name))
1153 EXPORT_SYMBOL(dev_valid_name);
1156 * __dev_alloc_name - allocate a name for a device
1157 * @net: network namespace to allocate the device name in
1158 * @name: name format string
1159 * @buf: scratch buffer and result name string
1161 * Passed a format string - eg "lt%d" it will try and find a suitable
1162 * id. It scans list of devices to build up a free map, then chooses
1163 * the first empty slot. The caller must hold the dev_base or rtnl lock
1164 * while allocating the name and adding the device in order to avoid
1166 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1167 * Returns the number of the unit assigned or a negative errno code.
1170 static int __dev_alloc_name(struct net *net, const char *name, char *buf)
1174 const int max_netdevices = 8*PAGE_SIZE;
1175 unsigned long *inuse;
1176 struct net_device *d;
1178 if (!dev_valid_name(name))
1181 p = strchr(name, '%');
1184 * Verify the string as this thing may have come from
1185 * the user. There must be either one "%d" and no other "%"
1188 if (p[1] != 'd' || strchr(p + 2, '%'))
1191 /* Use one page as a bit array of possible slots */
1192 inuse = (unsigned long *) get_zeroed_page(GFP_ATOMIC);
1196 for_each_netdev(net, d) {
1197 if (!sscanf(d->name, name, &i))
1199 if (i < 0 || i >= max_netdevices)
1202 /* avoid cases where sscanf is not exact inverse of printf */
1203 snprintf(buf, IFNAMSIZ, name, i);
1204 if (!strncmp(buf, d->name, IFNAMSIZ))
1208 i = find_first_zero_bit(inuse, max_netdevices);
1209 free_page((unsigned long) inuse);
1212 snprintf(buf, IFNAMSIZ, name, i);
1213 if (!__dev_get_by_name(net, buf))
1216 /* It is possible to run out of possible slots
1217 * when the name is long and there isn't enough space left
1218 * for the digits, or if all bits are used.
1223 static int dev_alloc_name_ns(struct net *net,
1224 struct net_device *dev,
1231 ret = __dev_alloc_name(net, name, buf);
1233 strlcpy(dev->name, buf, IFNAMSIZ);
1238 * dev_alloc_name - allocate a name for a device
1240 * @name: name format string
1242 * Passed a format string - eg "lt%d" it will try and find a suitable
1243 * id. It scans list of devices to build up a free map, then chooses
1244 * the first empty slot. The caller must hold the dev_base or rtnl lock
1245 * while allocating the name and adding the device in order to avoid
1247 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1248 * Returns the number of the unit assigned or a negative errno code.
1251 int dev_alloc_name(struct net_device *dev, const char *name)
1253 return dev_alloc_name_ns(dev_net(dev), dev, name);
1255 EXPORT_SYMBOL(dev_alloc_name);
1257 static int dev_get_valid_name(struct net *net, struct net_device *dev,
1262 if (!dev_valid_name(name))
1265 if (strchr(name, '%'))
1266 return dev_alloc_name_ns(net, dev, name);
1267 else if (__dev_get_by_name(net, name))
1269 else if (dev->name != name)
1270 strlcpy(dev->name, name, IFNAMSIZ);
1276 * dev_change_name - change name of a device
1278 * @newname: name (or format string) must be at least IFNAMSIZ
1280 * Change name of a device, can pass format strings "eth%d".
1283 int dev_change_name(struct net_device *dev, const char *newname)
1285 unsigned char old_assign_type;
1286 char oldname[IFNAMSIZ];
1292 BUG_ON(!dev_net(dev));
1296 /* Some auto-enslaved devices e.g. failover slaves are
1297 * special, as userspace might rename the device after
1298 * the interface had been brought up and running since
1299 * the point kernel initiated auto-enslavement. Allow
1300 * live name change even when these slave devices are
1303 * Typically, users of these auto-enslaving devices
1304 * don't actually care about slave name change, as
1305 * they are supposed to operate on master interface
1308 if (dev->flags & IFF_UP &&
1309 likely(!(dev->priv_flags & IFF_LIVE_RENAME_OK)))
1312 down_write(&devnet_rename_sem);
1314 if (strncmp(newname, dev->name, IFNAMSIZ) == 0) {
1315 up_write(&devnet_rename_sem);
1319 memcpy(oldname, dev->name, IFNAMSIZ);
1321 err = dev_get_valid_name(net, dev, newname);
1323 up_write(&devnet_rename_sem);
1327 if (oldname[0] && !strchr(oldname, '%'))
1328 netdev_info(dev, "renamed from %s\n", oldname);
1330 old_assign_type = dev->name_assign_type;
1331 dev->name_assign_type = NET_NAME_RENAMED;
1334 ret = device_rename(&dev->dev, dev->name);
1336 memcpy(dev->name, oldname, IFNAMSIZ);
1337 dev->name_assign_type = old_assign_type;
1338 up_write(&devnet_rename_sem);
1342 up_write(&devnet_rename_sem);
1344 netdev_adjacent_rename_links(dev, oldname);
1346 write_lock_bh(&dev_base_lock);
1347 netdev_name_node_del(dev->name_node);
1348 write_unlock_bh(&dev_base_lock);
1352 write_lock_bh(&dev_base_lock);
1353 netdev_name_node_add(net, dev->name_node);
1354 write_unlock_bh(&dev_base_lock);
1356 ret = call_netdevice_notifiers(NETDEV_CHANGENAME, dev);
1357 ret = notifier_to_errno(ret);
1360 /* err >= 0 after dev_alloc_name() or stores the first errno */
1363 down_write(&devnet_rename_sem);
1364 memcpy(dev->name, oldname, IFNAMSIZ);
1365 memcpy(oldname, newname, IFNAMSIZ);
1366 dev->name_assign_type = old_assign_type;
1367 old_assign_type = NET_NAME_RENAMED;
1370 pr_err("%s: name change rollback failed: %d\n",
1379 * dev_set_alias - change ifalias of a device
1381 * @alias: name up to IFALIASZ
1382 * @len: limit of bytes to copy from info
1384 * Set ifalias for a device,
1386 int dev_set_alias(struct net_device *dev, const char *alias, size_t len)
1388 struct dev_ifalias *new_alias = NULL;
1390 if (len >= IFALIASZ)
1394 new_alias = kmalloc(sizeof(*new_alias) + len + 1, GFP_KERNEL);
1398 memcpy(new_alias->ifalias, alias, len);
1399 new_alias->ifalias[len] = 0;
1402 mutex_lock(&ifalias_mutex);
1403 new_alias = rcu_replace_pointer(dev->ifalias, new_alias,
1404 mutex_is_locked(&ifalias_mutex));
1405 mutex_unlock(&ifalias_mutex);
1408 kfree_rcu(new_alias, rcuhead);
1412 EXPORT_SYMBOL(dev_set_alias);
1415 * dev_get_alias - get ifalias of a device
1417 * @name: buffer to store name of ifalias
1418 * @len: size of buffer
1420 * get ifalias for a device. Caller must make sure dev cannot go
1421 * away, e.g. rcu read lock or own a reference count to device.
1423 int dev_get_alias(const struct net_device *dev, char *name, size_t len)
1425 const struct dev_ifalias *alias;
1429 alias = rcu_dereference(dev->ifalias);
1431 ret = snprintf(name, len, "%s", alias->ifalias);
1438 * netdev_features_change - device changes features
1439 * @dev: device to cause notification
1441 * Called to indicate a device has changed features.
1443 void netdev_features_change(struct net_device *dev)
1445 call_netdevice_notifiers(NETDEV_FEAT_CHANGE, dev);
1447 EXPORT_SYMBOL(netdev_features_change);
1450 * netdev_state_change - device changes state
1451 * @dev: device to cause notification
1453 * Called to indicate a device has changed state. This function calls
1454 * the notifier chains for netdev_chain and sends a NEWLINK message
1455 * to the routing socket.
1457 void netdev_state_change(struct net_device *dev)
1459 if (dev->flags & IFF_UP) {
1460 struct netdev_notifier_change_info change_info = {
1464 call_netdevice_notifiers_info(NETDEV_CHANGE,
1466 rtmsg_ifinfo(RTM_NEWLINK, dev, 0, GFP_KERNEL);
1469 EXPORT_SYMBOL(netdev_state_change);
1472 * netdev_notify_peers - notify network peers about existence of @dev
1473 * @dev: network device
1475 * Generate traffic such that interested network peers are aware of
1476 * @dev, such as by generating a gratuitous ARP. This may be used when
1477 * a device wants to inform the rest of the network about some sort of
1478 * reconfiguration such as a failover event or virtual machine
1481 void netdev_notify_peers(struct net_device *dev)
1484 call_netdevice_notifiers(NETDEV_NOTIFY_PEERS, dev);
1485 call_netdevice_notifiers(NETDEV_RESEND_IGMP, dev);
1488 EXPORT_SYMBOL(netdev_notify_peers);
1490 static int __dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1492 const struct net_device_ops *ops = dev->netdev_ops;
1497 if (!netif_device_present(dev)) {
1498 /* may be detached because parent is runtime-suspended */
1499 if (dev->dev.parent)
1500 pm_runtime_resume(dev->dev.parent);
1501 if (!netif_device_present(dev))
1505 /* Block netpoll from trying to do any rx path servicing.
1506 * If we don't do this there is a chance ndo_poll_controller
1507 * or ndo_poll may be running while we open the device
1509 netpoll_poll_disable(dev);
1511 ret = call_netdevice_notifiers_extack(NETDEV_PRE_UP, dev, extack);
1512 ret = notifier_to_errno(ret);
1516 set_bit(__LINK_STATE_START, &dev->state);
1518 if (ops->ndo_validate_addr)
1519 ret = ops->ndo_validate_addr(dev);
1521 if (!ret && ops->ndo_open)
1522 ret = ops->ndo_open(dev);
1524 netpoll_poll_enable(dev);
1527 clear_bit(__LINK_STATE_START, &dev->state);
1529 dev->flags |= IFF_UP;
1530 dev_set_rx_mode(dev);
1532 add_device_randomness(dev->dev_addr, dev->addr_len);
1539 * dev_open - prepare an interface for use.
1540 * @dev: device to open
1541 * @extack: netlink extended ack
1543 * Takes a device from down to up state. The device's private open
1544 * function is invoked and then the multicast lists are loaded. Finally
1545 * the device is moved into the up state and a %NETDEV_UP message is
1546 * sent to the netdev notifier chain.
1548 * Calling this function on an active interface is a nop. On a failure
1549 * a negative errno code is returned.
1551 int dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1555 if (dev->flags & IFF_UP)
1558 ret = __dev_open(dev, extack);
1562 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING, GFP_KERNEL);
1563 call_netdevice_notifiers(NETDEV_UP, dev);
1567 EXPORT_SYMBOL(dev_open);
1569 static void __dev_close_many(struct list_head *head)
1571 struct net_device *dev;
1576 list_for_each_entry(dev, head, close_list) {
1577 /* Temporarily disable netpoll until the interface is down */
1578 netpoll_poll_disable(dev);
1580 call_netdevice_notifiers(NETDEV_GOING_DOWN, dev);
1582 clear_bit(__LINK_STATE_START, &dev->state);
1584 /* Synchronize to scheduled poll. We cannot touch poll list, it
1585 * can be even on different cpu. So just clear netif_running().
1587 * dev->stop() will invoke napi_disable() on all of it's
1588 * napi_struct instances on this device.
1590 smp_mb__after_atomic(); /* Commit netif_running(). */
1593 dev_deactivate_many(head);
1595 list_for_each_entry(dev, head, close_list) {
1596 const struct net_device_ops *ops = dev->netdev_ops;
1599 * Call the device specific close. This cannot fail.
1600 * Only if device is UP
1602 * We allow it to be called even after a DETACH hot-plug
1608 dev->flags &= ~IFF_UP;
1609 netpoll_poll_enable(dev);
1613 static void __dev_close(struct net_device *dev)
1617 list_add(&dev->close_list, &single);
1618 __dev_close_many(&single);
1622 void dev_close_many(struct list_head *head, bool unlink)
1624 struct net_device *dev, *tmp;
1626 /* Remove the devices that don't need to be closed */
1627 list_for_each_entry_safe(dev, tmp, head, close_list)
1628 if (!(dev->flags & IFF_UP))
1629 list_del_init(&dev->close_list);
1631 __dev_close_many(head);
1633 list_for_each_entry_safe(dev, tmp, head, close_list) {
1634 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING, GFP_KERNEL);
1635 call_netdevice_notifiers(NETDEV_DOWN, dev);
1637 list_del_init(&dev->close_list);
1640 EXPORT_SYMBOL(dev_close_many);
1643 * dev_close - shutdown an interface.
1644 * @dev: device to shutdown
1646 * This function moves an active device into down state. A
1647 * %NETDEV_GOING_DOWN is sent to the netdev notifier chain. The device
1648 * is then deactivated and finally a %NETDEV_DOWN is sent to the notifier
1651 void dev_close(struct net_device *dev)
1653 if (dev->flags & IFF_UP) {
1656 list_add(&dev->close_list, &single);
1657 dev_close_many(&single, true);
1661 EXPORT_SYMBOL(dev_close);
1665 * dev_disable_lro - disable Large Receive Offload on a device
1668 * Disable Large Receive Offload (LRO) on a net device. Must be
1669 * called under RTNL. This is needed if received packets may be
1670 * forwarded to another interface.
1672 void dev_disable_lro(struct net_device *dev)
1674 struct net_device *lower_dev;
1675 struct list_head *iter;
1677 dev->wanted_features &= ~NETIF_F_LRO;
1678 netdev_update_features(dev);
1680 if (unlikely(dev->features & NETIF_F_LRO))
1681 netdev_WARN(dev, "failed to disable LRO!\n");
1683 netdev_for_each_lower_dev(dev, lower_dev, iter)
1684 dev_disable_lro(lower_dev);
1686 EXPORT_SYMBOL(dev_disable_lro);
1689 * dev_disable_gro_hw - disable HW Generic Receive Offload on a device
1692 * Disable HW Generic Receive Offload (GRO_HW) on a net device. Must be
1693 * called under RTNL. This is needed if Generic XDP is installed on
1696 static void dev_disable_gro_hw(struct net_device *dev)
1698 dev->wanted_features &= ~NETIF_F_GRO_HW;
1699 netdev_update_features(dev);
1701 if (unlikely(dev->features & NETIF_F_GRO_HW))
1702 netdev_WARN(dev, "failed to disable GRO_HW!\n");
1705 const char *netdev_cmd_to_name(enum netdev_cmd cmd)
1708 case NETDEV_##val: \
1709 return "NETDEV_" __stringify(val);
1711 N(UP) N(DOWN) N(REBOOT) N(CHANGE) N(REGISTER) N(UNREGISTER)
1712 N(CHANGEMTU) N(CHANGEADDR) N(GOING_DOWN) N(CHANGENAME) N(FEAT_CHANGE)
1713 N(BONDING_FAILOVER) N(PRE_UP) N(PRE_TYPE_CHANGE) N(POST_TYPE_CHANGE)
1714 N(POST_INIT) N(RELEASE) N(NOTIFY_PEERS) N(JOIN) N(CHANGEUPPER)
1715 N(RESEND_IGMP) N(PRECHANGEMTU) N(CHANGEINFODATA) N(BONDING_INFO)
1716 N(PRECHANGEUPPER) N(CHANGELOWERSTATE) N(UDP_TUNNEL_PUSH_INFO)
1717 N(UDP_TUNNEL_DROP_INFO) N(CHANGE_TX_QUEUE_LEN)
1718 N(CVLAN_FILTER_PUSH_INFO) N(CVLAN_FILTER_DROP_INFO)
1719 N(SVLAN_FILTER_PUSH_INFO) N(SVLAN_FILTER_DROP_INFO)
1723 return "UNKNOWN_NETDEV_EVENT";
1725 EXPORT_SYMBOL_GPL(netdev_cmd_to_name);
1727 static int call_netdevice_notifier(struct notifier_block *nb, unsigned long val,
1728 struct net_device *dev)
1730 struct netdev_notifier_info info = {
1734 return nb->notifier_call(nb, val, &info);
1737 static int call_netdevice_register_notifiers(struct notifier_block *nb,
1738 struct net_device *dev)
1742 err = call_netdevice_notifier(nb, NETDEV_REGISTER, dev);
1743 err = notifier_to_errno(err);
1747 if (!(dev->flags & IFF_UP))
1750 call_netdevice_notifier(nb, NETDEV_UP, dev);
1754 static void call_netdevice_unregister_notifiers(struct notifier_block *nb,
1755 struct net_device *dev)
1757 if (dev->flags & IFF_UP) {
1758 call_netdevice_notifier(nb, NETDEV_GOING_DOWN,
1760 call_netdevice_notifier(nb, NETDEV_DOWN, dev);
1762 call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev);
1765 static int call_netdevice_register_net_notifiers(struct notifier_block *nb,
1768 struct net_device *dev;
1771 for_each_netdev(net, dev) {
1772 err = call_netdevice_register_notifiers(nb, dev);
1779 for_each_netdev_continue_reverse(net, dev)
1780 call_netdevice_unregister_notifiers(nb, dev);
1784 static void call_netdevice_unregister_net_notifiers(struct notifier_block *nb,
1787 struct net_device *dev;
1789 for_each_netdev(net, dev)
1790 call_netdevice_unregister_notifiers(nb, dev);
1793 static int dev_boot_phase = 1;
1796 * register_netdevice_notifier - register a network notifier block
1799 * Register a notifier to be called when network device events occur.
1800 * The notifier passed is linked into the kernel structures and must
1801 * not be reused until it has been unregistered. A negative errno code
1802 * is returned on a failure.
1804 * When registered all registration and up events are replayed
1805 * to the new notifier to allow device to have a race free
1806 * view of the network device list.
1809 int register_netdevice_notifier(struct notifier_block *nb)
1814 /* Close race with setup_net() and cleanup_net() */
1815 down_write(&pernet_ops_rwsem);
1817 err = raw_notifier_chain_register(&netdev_chain, nb);
1823 err = call_netdevice_register_net_notifiers(nb, net);
1830 up_write(&pernet_ops_rwsem);
1834 for_each_net_continue_reverse(net)
1835 call_netdevice_unregister_net_notifiers(nb, net);
1837 raw_notifier_chain_unregister(&netdev_chain, nb);
1840 EXPORT_SYMBOL(register_netdevice_notifier);
1843 * unregister_netdevice_notifier - unregister a network notifier block
1846 * Unregister a notifier previously registered by
1847 * register_netdevice_notifier(). The notifier is unlinked into the
1848 * kernel structures and may then be reused. A negative errno code
1849 * is returned on a failure.
1851 * After unregistering unregister and down device events are synthesized
1852 * for all devices on the device list to the removed notifier to remove
1853 * the need for special case cleanup code.
1856 int unregister_netdevice_notifier(struct notifier_block *nb)
1861 /* Close race with setup_net() and cleanup_net() */
1862 down_write(&pernet_ops_rwsem);
1864 err = raw_notifier_chain_unregister(&netdev_chain, nb);
1869 call_netdevice_unregister_net_notifiers(nb, net);
1873 up_write(&pernet_ops_rwsem);
1876 EXPORT_SYMBOL(unregister_netdevice_notifier);
1878 static int __register_netdevice_notifier_net(struct net *net,
1879 struct notifier_block *nb,
1880 bool ignore_call_fail)
1884 err = raw_notifier_chain_register(&net->netdev_chain, nb);
1890 err = call_netdevice_register_net_notifiers(nb, net);
1891 if (err && !ignore_call_fail)
1892 goto chain_unregister;
1897 raw_notifier_chain_unregister(&net->netdev_chain, nb);
1901 static int __unregister_netdevice_notifier_net(struct net *net,
1902 struct notifier_block *nb)
1906 err = raw_notifier_chain_unregister(&net->netdev_chain, nb);
1910 call_netdevice_unregister_net_notifiers(nb, net);
1915 * register_netdevice_notifier_net - register a per-netns network notifier block
1916 * @net: network namespace
1919 * Register a notifier to be called when network device events occur.
1920 * The notifier passed is linked into the kernel structures and must
1921 * not be reused until it has been unregistered. A negative errno code
1922 * is returned on a failure.
1924 * When registered all registration and up events are replayed
1925 * to the new notifier to allow device to have a race free
1926 * view of the network device list.
1929 int register_netdevice_notifier_net(struct net *net, struct notifier_block *nb)
1934 err = __register_netdevice_notifier_net(net, nb, false);
1938 EXPORT_SYMBOL(register_netdevice_notifier_net);
1941 * unregister_netdevice_notifier_net - unregister a per-netns
1942 * network notifier block
1943 * @net: network namespace
1946 * Unregister a notifier previously registered by
1947 * register_netdevice_notifier(). The notifier is unlinked into the
1948 * kernel structures and may then be reused. A negative errno code
1949 * is returned on a failure.
1951 * After unregistering unregister and down device events are synthesized
1952 * for all devices on the device list to the removed notifier to remove
1953 * the need for special case cleanup code.
1956 int unregister_netdevice_notifier_net(struct net *net,
1957 struct notifier_block *nb)
1962 err = __unregister_netdevice_notifier_net(net, nb);
1966 EXPORT_SYMBOL(unregister_netdevice_notifier_net);
1968 int register_netdevice_notifier_dev_net(struct net_device *dev,
1969 struct notifier_block *nb,
1970 struct netdev_net_notifier *nn)
1975 err = __register_netdevice_notifier_net(dev_net(dev), nb, false);
1978 list_add(&nn->list, &dev->net_notifier_list);
1983 EXPORT_SYMBOL(register_netdevice_notifier_dev_net);
1985 int unregister_netdevice_notifier_dev_net(struct net_device *dev,
1986 struct notifier_block *nb,
1987 struct netdev_net_notifier *nn)
1992 list_del(&nn->list);
1993 err = __unregister_netdevice_notifier_net(dev_net(dev), nb);
1997 EXPORT_SYMBOL(unregister_netdevice_notifier_dev_net);
1999 static void move_netdevice_notifiers_dev_net(struct net_device *dev,
2002 struct netdev_net_notifier *nn;
2004 list_for_each_entry(nn, &dev->net_notifier_list, list) {
2005 __unregister_netdevice_notifier_net(dev_net(dev), nn->nb);
2006 __register_netdevice_notifier_net(net, nn->nb, true);
2011 * call_netdevice_notifiers_info - call all network notifier blocks
2012 * @val: value passed unmodified to notifier function
2013 * @info: notifier information data
2015 * Call all network notifier blocks. Parameters and return value
2016 * are as for raw_notifier_call_chain().
2019 static int call_netdevice_notifiers_info(unsigned long val,
2020 struct netdev_notifier_info *info)
2022 struct net *net = dev_net(info->dev);
2027 /* Run per-netns notifier block chain first, then run the global one.
2028 * Hopefully, one day, the global one is going to be removed after
2029 * all notifier block registrators get converted to be per-netns.
2031 ret = raw_notifier_call_chain(&net->netdev_chain, val, info);
2032 if (ret & NOTIFY_STOP_MASK)
2034 return raw_notifier_call_chain(&netdev_chain, val, info);
2037 static int call_netdevice_notifiers_extack(unsigned long val,
2038 struct net_device *dev,
2039 struct netlink_ext_ack *extack)
2041 struct netdev_notifier_info info = {
2046 return call_netdevice_notifiers_info(val, &info);
2050 * call_netdevice_notifiers - call all network notifier blocks
2051 * @val: value passed unmodified to notifier function
2052 * @dev: net_device pointer passed unmodified to notifier function
2054 * Call all network notifier blocks. Parameters and return value
2055 * are as for raw_notifier_call_chain().
2058 int call_netdevice_notifiers(unsigned long val, struct net_device *dev)
2060 return call_netdevice_notifiers_extack(val, dev, NULL);
2062 EXPORT_SYMBOL(call_netdevice_notifiers);
2065 * call_netdevice_notifiers_mtu - call all network notifier blocks
2066 * @val: value passed unmodified to notifier function
2067 * @dev: net_device pointer passed unmodified to notifier function
2068 * @arg: additional u32 argument passed to the notifier function
2070 * Call all network notifier blocks. Parameters and return value
2071 * are as for raw_notifier_call_chain().
2073 static int call_netdevice_notifiers_mtu(unsigned long val,
2074 struct net_device *dev, u32 arg)
2076 struct netdev_notifier_info_ext info = {
2081 BUILD_BUG_ON(offsetof(struct netdev_notifier_info_ext, info) != 0);
2083 return call_netdevice_notifiers_info(val, &info.info);
2086 #ifdef CONFIG_NET_INGRESS
2087 static DEFINE_STATIC_KEY_FALSE(ingress_needed_key);
2089 void net_inc_ingress_queue(void)
2091 static_branch_inc(&ingress_needed_key);
2093 EXPORT_SYMBOL_GPL(net_inc_ingress_queue);
2095 void net_dec_ingress_queue(void)
2097 static_branch_dec(&ingress_needed_key);
2099 EXPORT_SYMBOL_GPL(net_dec_ingress_queue);
2102 #ifdef CONFIG_NET_EGRESS
2103 static DEFINE_STATIC_KEY_FALSE(egress_needed_key);
2105 void net_inc_egress_queue(void)
2107 static_branch_inc(&egress_needed_key);
2109 EXPORT_SYMBOL_GPL(net_inc_egress_queue);
2111 void net_dec_egress_queue(void)
2113 static_branch_dec(&egress_needed_key);
2115 EXPORT_SYMBOL_GPL(net_dec_egress_queue);
2118 static DEFINE_STATIC_KEY_FALSE(netstamp_needed_key);
2119 #ifdef CONFIG_JUMP_LABEL
2120 static atomic_t netstamp_needed_deferred;
2121 static atomic_t netstamp_wanted;
2122 static void netstamp_clear(struct work_struct *work)
2124 int deferred = atomic_xchg(&netstamp_needed_deferred, 0);
2127 wanted = atomic_add_return(deferred, &netstamp_wanted);
2129 static_branch_enable(&netstamp_needed_key);
2131 static_branch_disable(&netstamp_needed_key);
2133 static DECLARE_WORK(netstamp_work, netstamp_clear);
2136 void net_enable_timestamp(void)
2138 #ifdef CONFIG_JUMP_LABEL
2142 wanted = atomic_read(&netstamp_wanted);
2145 if (atomic_cmpxchg(&netstamp_wanted, wanted, wanted + 1) == wanted)
2148 atomic_inc(&netstamp_needed_deferred);
2149 schedule_work(&netstamp_work);
2151 static_branch_inc(&netstamp_needed_key);
2154 EXPORT_SYMBOL(net_enable_timestamp);
2156 void net_disable_timestamp(void)
2158 #ifdef CONFIG_JUMP_LABEL
2162 wanted = atomic_read(&netstamp_wanted);
2165 if (atomic_cmpxchg(&netstamp_wanted, wanted, wanted - 1) == wanted)
2168 atomic_dec(&netstamp_needed_deferred);
2169 schedule_work(&netstamp_work);
2171 static_branch_dec(&netstamp_needed_key);
2174 EXPORT_SYMBOL(net_disable_timestamp);
2176 static inline void net_timestamp_set(struct sk_buff *skb)
2179 if (static_branch_unlikely(&netstamp_needed_key))
2180 __net_timestamp(skb);
2183 #define net_timestamp_check(COND, SKB) \
2184 if (static_branch_unlikely(&netstamp_needed_key)) { \
2185 if ((COND) && !(SKB)->tstamp) \
2186 __net_timestamp(SKB); \
2189 bool is_skb_forwardable(const struct net_device *dev, const struct sk_buff *skb)
2193 if (!(dev->flags & IFF_UP))
2196 len = dev->mtu + dev->hard_header_len + VLAN_HLEN;
2197 if (skb->len <= len)
2200 /* if TSO is enabled, we don't care about the length as the packet
2201 * could be forwarded without being segmented before
2203 if (skb_is_gso(skb))
2208 EXPORT_SYMBOL_GPL(is_skb_forwardable);
2210 int __dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
2212 int ret = ____dev_forward_skb(dev, skb);
2215 skb->protocol = eth_type_trans(skb, dev);
2216 skb_postpull_rcsum(skb, eth_hdr(skb), ETH_HLEN);
2221 EXPORT_SYMBOL_GPL(__dev_forward_skb);
2224 * dev_forward_skb - loopback an skb to another netif
2226 * @dev: destination network device
2227 * @skb: buffer to forward
2230 * NET_RX_SUCCESS (no congestion)
2231 * NET_RX_DROP (packet was dropped, but freed)
2233 * dev_forward_skb can be used for injecting an skb from the
2234 * start_xmit function of one device into the receive queue
2235 * of another device.
2237 * The receiving device may be in another namespace, so
2238 * we have to clear all information in the skb that could
2239 * impact namespace isolation.
2241 int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
2243 return __dev_forward_skb(dev, skb) ?: netif_rx_internal(skb);
2245 EXPORT_SYMBOL_GPL(dev_forward_skb);
2247 static inline int deliver_skb(struct sk_buff *skb,
2248 struct packet_type *pt_prev,
2249 struct net_device *orig_dev)
2251 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
2253 refcount_inc(&skb->users);
2254 return pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
2257 static inline void deliver_ptype_list_skb(struct sk_buff *skb,
2258 struct packet_type **pt,
2259 struct net_device *orig_dev,
2261 struct list_head *ptype_list)
2263 struct packet_type *ptype, *pt_prev = *pt;
2265 list_for_each_entry_rcu(ptype, ptype_list, list) {
2266 if (ptype->type != type)
2269 deliver_skb(skb, pt_prev, orig_dev);
2275 static inline bool skb_loop_sk(struct packet_type *ptype, struct sk_buff *skb)
2277 if (!ptype->af_packet_priv || !skb->sk)
2280 if (ptype->id_match)
2281 return ptype->id_match(ptype, skb->sk);
2282 else if ((struct sock *)ptype->af_packet_priv == skb->sk)
2289 * dev_nit_active - return true if any network interface taps are in use
2291 * @dev: network device to check for the presence of taps
2293 bool dev_nit_active(struct net_device *dev)
2295 return !list_empty(&ptype_all) || !list_empty(&dev->ptype_all);
2297 EXPORT_SYMBOL_GPL(dev_nit_active);
2300 * Support routine. Sends outgoing frames to any network
2301 * taps currently in use.
2304 void dev_queue_xmit_nit(struct sk_buff *skb, struct net_device *dev)
2306 struct packet_type *ptype;
2307 struct sk_buff *skb2 = NULL;
2308 struct packet_type *pt_prev = NULL;
2309 struct list_head *ptype_list = &ptype_all;
2313 list_for_each_entry_rcu(ptype, ptype_list, list) {
2314 if (ptype->ignore_outgoing)
2317 /* Never send packets back to the socket
2318 * they originated from - MvS (miquels@drinkel.ow.org)
2320 if (skb_loop_sk(ptype, skb))
2324 deliver_skb(skb2, pt_prev, skb->dev);
2329 /* need to clone skb, done only once */
2330 skb2 = skb_clone(skb, GFP_ATOMIC);
2334 net_timestamp_set(skb2);
2336 /* skb->nh should be correctly
2337 * set by sender, so that the second statement is
2338 * just protection against buggy protocols.
2340 skb_reset_mac_header(skb2);
2342 if (skb_network_header(skb2) < skb2->data ||
2343 skb_network_header(skb2) > skb_tail_pointer(skb2)) {
2344 net_crit_ratelimited("protocol %04x is buggy, dev %s\n",
2345 ntohs(skb2->protocol),
2347 skb_reset_network_header(skb2);
2350 skb2->transport_header = skb2->network_header;
2351 skb2->pkt_type = PACKET_OUTGOING;
2355 if (ptype_list == &ptype_all) {
2356 ptype_list = &dev->ptype_all;
2361 if (!skb_orphan_frags_rx(skb2, GFP_ATOMIC))
2362 pt_prev->func(skb2, skb->dev, pt_prev, skb->dev);
2368 EXPORT_SYMBOL_GPL(dev_queue_xmit_nit);
2371 * netif_setup_tc - Handle tc mappings on real_num_tx_queues change
2372 * @dev: Network device
2373 * @txq: number of queues available
2375 * If real_num_tx_queues is changed the tc mappings may no longer be
2376 * valid. To resolve this verify the tc mapping remains valid and if
2377 * not NULL the mapping. With no priorities mapping to this
2378 * offset/count pair it will no longer be used. In the worst case TC0
2379 * is invalid nothing can be done so disable priority mappings. If is
2380 * expected that drivers will fix this mapping if they can before
2381 * calling netif_set_real_num_tx_queues.
2383 static void netif_setup_tc(struct net_device *dev, unsigned int txq)
2386 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2388 /* If TC0 is invalidated disable TC mapping */
2389 if (tc->offset + tc->count > txq) {
2390 pr_warn("Number of in use tx queues changed invalidating tc mappings. Priority traffic classification disabled!\n");
2395 /* Invalidated prio to tc mappings set to TC0 */
2396 for (i = 1; i < TC_BITMASK + 1; i++) {
2397 int q = netdev_get_prio_tc_map(dev, i);
2399 tc = &dev->tc_to_txq[q];
2400 if (tc->offset + tc->count > txq) {
2401 pr_warn("Number of in use tx queues changed. Priority %i to tc mapping %i is no longer valid. Setting map to 0\n",
2403 netdev_set_prio_tc_map(dev, i, 0);
2408 int netdev_txq_to_tc(struct net_device *dev, unsigned int txq)
2411 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2414 /* walk through the TCs and see if it falls into any of them */
2415 for (i = 0; i < TC_MAX_QUEUE; i++, tc++) {
2416 if ((txq - tc->offset) < tc->count)
2420 /* didn't find it, just return -1 to indicate no match */
2426 EXPORT_SYMBOL(netdev_txq_to_tc);
2429 struct static_key xps_needed __read_mostly;
2430 EXPORT_SYMBOL(xps_needed);
2431 struct static_key xps_rxqs_needed __read_mostly;
2432 EXPORT_SYMBOL(xps_rxqs_needed);
2433 static DEFINE_MUTEX(xps_map_mutex);
2434 #define xmap_dereference(P) \
2435 rcu_dereference_protected((P), lockdep_is_held(&xps_map_mutex))
2437 static bool remove_xps_queue(struct xps_dev_maps *dev_maps,
2440 struct xps_map *map = NULL;
2444 map = xmap_dereference(dev_maps->attr_map[tci]);
2448 for (pos = map->len; pos--;) {
2449 if (map->queues[pos] != index)
2453 map->queues[pos] = map->queues[--map->len];
2457 RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
2458 kfree_rcu(map, rcu);
2465 static bool remove_xps_queue_cpu(struct net_device *dev,
2466 struct xps_dev_maps *dev_maps,
2467 int cpu, u16 offset, u16 count)
2469 int num_tc = dev->num_tc ? : 1;
2470 bool active = false;
2473 for (tci = cpu * num_tc; num_tc--; tci++) {
2476 for (i = count, j = offset; i--; j++) {
2477 if (!remove_xps_queue(dev_maps, tci, j))
2487 static void reset_xps_maps(struct net_device *dev,
2488 struct xps_dev_maps *dev_maps,
2492 static_key_slow_dec_cpuslocked(&xps_rxqs_needed);
2493 RCU_INIT_POINTER(dev->xps_rxqs_map, NULL);
2495 RCU_INIT_POINTER(dev->xps_cpus_map, NULL);
2497 static_key_slow_dec_cpuslocked(&xps_needed);
2498 kfree_rcu(dev_maps, rcu);
2501 static void clean_xps_maps(struct net_device *dev, const unsigned long *mask,
2502 struct xps_dev_maps *dev_maps, unsigned int nr_ids,
2503 u16 offset, u16 count, bool is_rxqs_map)
2505 bool active = false;
2508 for (j = -1; j = netif_attrmask_next(j, mask, nr_ids),
2510 active |= remove_xps_queue_cpu(dev, dev_maps, j, offset,
2513 reset_xps_maps(dev, dev_maps, is_rxqs_map);
2516 for (i = offset + (count - 1); count--; i--) {
2517 netdev_queue_numa_node_write(
2518 netdev_get_tx_queue(dev, i),
2524 static void netif_reset_xps_queues(struct net_device *dev, u16 offset,
2527 const unsigned long *possible_mask = NULL;
2528 struct xps_dev_maps *dev_maps;
2529 unsigned int nr_ids;
2531 if (!static_key_false(&xps_needed))
2535 mutex_lock(&xps_map_mutex);
2537 if (static_key_false(&xps_rxqs_needed)) {
2538 dev_maps = xmap_dereference(dev->xps_rxqs_map);
2540 nr_ids = dev->num_rx_queues;
2541 clean_xps_maps(dev, possible_mask, dev_maps, nr_ids,
2542 offset, count, true);
2546 dev_maps = xmap_dereference(dev->xps_cpus_map);
2550 if (num_possible_cpus() > 1)
2551 possible_mask = cpumask_bits(cpu_possible_mask);
2552 nr_ids = nr_cpu_ids;
2553 clean_xps_maps(dev, possible_mask, dev_maps, nr_ids, offset, count,
2557 mutex_unlock(&xps_map_mutex);
2561 static void netif_reset_xps_queues_gt(struct net_device *dev, u16 index)
2563 netif_reset_xps_queues(dev, index, dev->num_tx_queues - index);
2566 static struct xps_map *expand_xps_map(struct xps_map *map, int attr_index,
2567 u16 index, bool is_rxqs_map)
2569 struct xps_map *new_map;
2570 int alloc_len = XPS_MIN_MAP_ALLOC;
2573 for (pos = 0; map && pos < map->len; pos++) {
2574 if (map->queues[pos] != index)
2579 /* Need to add tx-queue to this CPU's/rx-queue's existing map */
2581 if (pos < map->alloc_len)
2584 alloc_len = map->alloc_len * 2;
2587 /* Need to allocate new map to store tx-queue on this CPU's/rx-queue's
2591 new_map = kzalloc(XPS_MAP_SIZE(alloc_len), GFP_KERNEL);
2593 new_map = kzalloc_node(XPS_MAP_SIZE(alloc_len), GFP_KERNEL,
2594 cpu_to_node(attr_index));
2598 for (i = 0; i < pos; i++)
2599 new_map->queues[i] = map->queues[i];
2600 new_map->alloc_len = alloc_len;
2606 /* Must be called under cpus_read_lock */
2607 int __netif_set_xps_queue(struct net_device *dev, const unsigned long *mask,
2608 u16 index, bool is_rxqs_map)
2610 const unsigned long *online_mask = NULL, *possible_mask = NULL;
2611 struct xps_dev_maps *dev_maps, *new_dev_maps = NULL;
2612 int i, j, tci, numa_node_id = -2;
2613 int maps_sz, num_tc = 1, tc = 0;
2614 struct xps_map *map, *new_map;
2615 bool active = false;
2616 unsigned int nr_ids;
2619 /* Do not allow XPS on subordinate device directly */
2620 num_tc = dev->num_tc;
2624 /* If queue belongs to subordinate dev use its map */
2625 dev = netdev_get_tx_queue(dev, index)->sb_dev ? : dev;
2627 tc = netdev_txq_to_tc(dev, index);
2632 mutex_lock(&xps_map_mutex);
2634 maps_sz = XPS_RXQ_DEV_MAPS_SIZE(num_tc, dev->num_rx_queues);
2635 dev_maps = xmap_dereference(dev->xps_rxqs_map);
2636 nr_ids = dev->num_rx_queues;
2638 maps_sz = XPS_CPU_DEV_MAPS_SIZE(num_tc);
2639 if (num_possible_cpus() > 1) {
2640 online_mask = cpumask_bits(cpu_online_mask);
2641 possible_mask = cpumask_bits(cpu_possible_mask);
2643 dev_maps = xmap_dereference(dev->xps_cpus_map);
2644 nr_ids = nr_cpu_ids;
2647 if (maps_sz < L1_CACHE_BYTES)
2648 maps_sz = L1_CACHE_BYTES;
2650 /* allocate memory for queue storage */
2651 for (j = -1; j = netif_attrmask_next_and(j, online_mask, mask, nr_ids),
2654 new_dev_maps = kzalloc(maps_sz, GFP_KERNEL);
2655 if (!new_dev_maps) {
2656 mutex_unlock(&xps_map_mutex);
2660 tci = j * num_tc + tc;
2661 map = dev_maps ? xmap_dereference(dev_maps->attr_map[tci]) :
2664 map = expand_xps_map(map, j, index, is_rxqs_map);
2668 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2672 goto out_no_new_maps;
2675 /* Increment static keys at most once per type */
2676 static_key_slow_inc_cpuslocked(&xps_needed);
2678 static_key_slow_inc_cpuslocked(&xps_rxqs_needed);
2681 for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2683 /* copy maps belonging to foreign traffic classes */
2684 for (i = tc, tci = j * num_tc; dev_maps && i--; tci++) {
2685 /* fill in the new device map from the old device map */
2686 map = xmap_dereference(dev_maps->attr_map[tci]);
2687 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2690 /* We need to explicitly update tci as prevous loop
2691 * could break out early if dev_maps is NULL.
2693 tci = j * num_tc + tc;
2695 if (netif_attr_test_mask(j, mask, nr_ids) &&
2696 netif_attr_test_online(j, online_mask, nr_ids)) {
2697 /* add tx-queue to CPU/rx-queue maps */
2700 map = xmap_dereference(new_dev_maps->attr_map[tci]);
2701 while ((pos < map->len) && (map->queues[pos] != index))
2704 if (pos == map->len)
2705 map->queues[map->len++] = index;
2708 if (numa_node_id == -2)
2709 numa_node_id = cpu_to_node(j);
2710 else if (numa_node_id != cpu_to_node(j))
2714 } else if (dev_maps) {
2715 /* fill in the new device map from the old device map */
2716 map = xmap_dereference(dev_maps->attr_map[tci]);
2717 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2720 /* copy maps belonging to foreign traffic classes */
2721 for (i = num_tc - tc, tci++; dev_maps && --i; tci++) {
2722 /* fill in the new device map from the old device map */
2723 map = xmap_dereference(dev_maps->attr_map[tci]);
2724 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2729 rcu_assign_pointer(dev->xps_rxqs_map, new_dev_maps);
2731 rcu_assign_pointer(dev->xps_cpus_map, new_dev_maps);
2733 /* Cleanup old maps */
2735 goto out_no_old_maps;
2737 for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2739 for (i = num_tc, tci = j * num_tc; i--; tci++) {
2740 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2741 map = xmap_dereference(dev_maps->attr_map[tci]);
2742 if (map && map != new_map)
2743 kfree_rcu(map, rcu);
2747 kfree_rcu(dev_maps, rcu);
2750 dev_maps = new_dev_maps;
2755 /* update Tx queue numa node */
2756 netdev_queue_numa_node_write(netdev_get_tx_queue(dev, index),
2757 (numa_node_id >= 0) ?
2758 numa_node_id : NUMA_NO_NODE);
2764 /* removes tx-queue from unused CPUs/rx-queues */
2765 for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2767 for (i = tc, tci = j * num_tc; i--; tci++)
2768 active |= remove_xps_queue(dev_maps, tci, index);
2769 if (!netif_attr_test_mask(j, mask, nr_ids) ||
2770 !netif_attr_test_online(j, online_mask, nr_ids))
2771 active |= remove_xps_queue(dev_maps, tci, index);
2772 for (i = num_tc - tc, tci++; --i; tci++)
2773 active |= remove_xps_queue(dev_maps, tci, index);
2776 /* free map if not active */
2778 reset_xps_maps(dev, dev_maps, is_rxqs_map);
2781 mutex_unlock(&xps_map_mutex);
2785 /* remove any maps that we added */
2786 for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2788 for (i = num_tc, tci = j * num_tc; i--; tci++) {
2789 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2791 xmap_dereference(dev_maps->attr_map[tci]) :
2793 if (new_map && new_map != map)
2798 mutex_unlock(&xps_map_mutex);
2800 kfree(new_dev_maps);
2803 EXPORT_SYMBOL_GPL(__netif_set_xps_queue);
2805 int netif_set_xps_queue(struct net_device *dev, const struct cpumask *mask,
2811 ret = __netif_set_xps_queue(dev, cpumask_bits(mask), index, false);
2816 EXPORT_SYMBOL(netif_set_xps_queue);
2819 static void netdev_unbind_all_sb_channels(struct net_device *dev)
2821 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2823 /* Unbind any subordinate channels */
2824 while (txq-- != &dev->_tx[0]) {
2826 netdev_unbind_sb_channel(dev, txq->sb_dev);
2830 void netdev_reset_tc(struct net_device *dev)
2833 netif_reset_xps_queues_gt(dev, 0);
2835 netdev_unbind_all_sb_channels(dev);
2837 /* Reset TC configuration of device */
2839 memset(dev->tc_to_txq, 0, sizeof(dev->tc_to_txq));
2840 memset(dev->prio_tc_map, 0, sizeof(dev->prio_tc_map));
2842 EXPORT_SYMBOL(netdev_reset_tc);
2844 int netdev_set_tc_queue(struct net_device *dev, u8 tc, u16 count, u16 offset)
2846 if (tc >= dev->num_tc)
2850 netif_reset_xps_queues(dev, offset, count);
2852 dev->tc_to_txq[tc].count = count;
2853 dev->tc_to_txq[tc].offset = offset;
2856 EXPORT_SYMBOL(netdev_set_tc_queue);
2858 int netdev_set_num_tc(struct net_device *dev, u8 num_tc)
2860 if (num_tc > TC_MAX_QUEUE)
2864 netif_reset_xps_queues_gt(dev, 0);
2866 netdev_unbind_all_sb_channels(dev);
2868 dev->num_tc = num_tc;
2871 EXPORT_SYMBOL(netdev_set_num_tc);
2873 void netdev_unbind_sb_channel(struct net_device *dev,
2874 struct net_device *sb_dev)
2876 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2879 netif_reset_xps_queues_gt(sb_dev, 0);
2881 memset(sb_dev->tc_to_txq, 0, sizeof(sb_dev->tc_to_txq));
2882 memset(sb_dev->prio_tc_map, 0, sizeof(sb_dev->prio_tc_map));
2884 while (txq-- != &dev->_tx[0]) {
2885 if (txq->sb_dev == sb_dev)
2889 EXPORT_SYMBOL(netdev_unbind_sb_channel);
2891 int netdev_bind_sb_channel_queue(struct net_device *dev,
2892 struct net_device *sb_dev,
2893 u8 tc, u16 count, u16 offset)
2895 /* Make certain the sb_dev and dev are already configured */
2896 if (sb_dev->num_tc >= 0 || tc >= dev->num_tc)
2899 /* We cannot hand out queues we don't have */
2900 if ((offset + count) > dev->real_num_tx_queues)
2903 /* Record the mapping */
2904 sb_dev->tc_to_txq[tc].count = count;
2905 sb_dev->tc_to_txq[tc].offset = offset;
2907 /* Provide a way for Tx queue to find the tc_to_txq map or
2908 * XPS map for itself.
2911 netdev_get_tx_queue(dev, count + offset)->sb_dev = sb_dev;
2915 EXPORT_SYMBOL(netdev_bind_sb_channel_queue);
2917 int netdev_set_sb_channel(struct net_device *dev, u16 channel)
2919 /* Do not use a multiqueue device to represent a subordinate channel */
2920 if (netif_is_multiqueue(dev))
2923 /* We allow channels 1 - 32767 to be used for subordinate channels.
2924 * Channel 0 is meant to be "native" mode and used only to represent
2925 * the main root device. We allow writing 0 to reset the device back
2926 * to normal mode after being used as a subordinate channel.
2928 if (channel > S16_MAX)
2931 dev->num_tc = -channel;
2935 EXPORT_SYMBOL(netdev_set_sb_channel);
2938 * Routine to help set real_num_tx_queues. To avoid skbs mapped to queues
2939 * greater than real_num_tx_queues stale skbs on the qdisc must be flushed.
2941 int netif_set_real_num_tx_queues(struct net_device *dev, unsigned int txq)
2946 disabling = txq < dev->real_num_tx_queues;
2948 if (txq < 1 || txq > dev->num_tx_queues)
2951 if (dev->reg_state == NETREG_REGISTERED ||
2952 dev->reg_state == NETREG_UNREGISTERING) {
2955 rc = netdev_queue_update_kobjects(dev, dev->real_num_tx_queues,
2961 netif_setup_tc(dev, txq);
2963 dev->real_num_tx_queues = txq;
2967 qdisc_reset_all_tx_gt(dev, txq);
2969 netif_reset_xps_queues_gt(dev, txq);
2973 dev->real_num_tx_queues = txq;
2978 EXPORT_SYMBOL(netif_set_real_num_tx_queues);
2982 * netif_set_real_num_rx_queues - set actual number of RX queues used
2983 * @dev: Network device
2984 * @rxq: Actual number of RX queues
2986 * This must be called either with the rtnl_lock held or before
2987 * registration of the net device. Returns 0 on success, or a
2988 * negative error code. If called before registration, it always
2991 int netif_set_real_num_rx_queues(struct net_device *dev, unsigned int rxq)
2995 if (rxq < 1 || rxq > dev->num_rx_queues)
2998 if (dev->reg_state == NETREG_REGISTERED) {
3001 rc = net_rx_queue_update_kobjects(dev, dev->real_num_rx_queues,
3007 dev->real_num_rx_queues = rxq;
3010 EXPORT_SYMBOL(netif_set_real_num_rx_queues);
3014 * netif_get_num_default_rss_queues - default number of RSS queues
3016 * This routine should set an upper limit on the number of RSS queues
3017 * used by default by multiqueue devices.
3019 int netif_get_num_default_rss_queues(void)
3021 return is_kdump_kernel() ?
3022 1 : min_t(int, DEFAULT_MAX_NUM_RSS_QUEUES, num_online_cpus());
3024 EXPORT_SYMBOL(netif_get_num_default_rss_queues);
3026 static void __netif_reschedule(struct Qdisc *q)
3028 struct softnet_data *sd;
3029 unsigned long flags;
3031 local_irq_save(flags);
3032 sd = this_cpu_ptr(&softnet_data);
3033 q->next_sched = NULL;
3034 *sd->output_queue_tailp = q;
3035 sd->output_queue_tailp = &q->next_sched;
3036 raise_softirq_irqoff(NET_TX_SOFTIRQ);
3037 local_irq_restore(flags);
3040 void __netif_schedule(struct Qdisc *q)
3042 if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state))
3043 __netif_reschedule(q);
3045 EXPORT_SYMBOL(__netif_schedule);
3047 struct dev_kfree_skb_cb {
3048 enum skb_free_reason reason;
3051 static struct dev_kfree_skb_cb *get_kfree_skb_cb(const struct sk_buff *skb)
3053 return (struct dev_kfree_skb_cb *)skb->cb;
3056 void netif_schedule_queue(struct netdev_queue *txq)
3059 if (!netif_xmit_stopped(txq)) {
3060 struct Qdisc *q = rcu_dereference(txq->qdisc);
3062 __netif_schedule(q);
3066 EXPORT_SYMBOL(netif_schedule_queue);
3068 void netif_tx_wake_queue(struct netdev_queue *dev_queue)
3070 if (test_and_clear_bit(__QUEUE_STATE_DRV_XOFF, &dev_queue->state)) {
3074 q = rcu_dereference(dev_queue->qdisc);
3075 __netif_schedule(q);
3079 EXPORT_SYMBOL(netif_tx_wake_queue);
3081 void __dev_kfree_skb_irq(struct sk_buff *skb, enum skb_free_reason reason)
3083 unsigned long flags;
3088 if (likely(refcount_read(&skb->users) == 1)) {
3090 refcount_set(&skb->users, 0);
3091 } else if (likely(!refcount_dec_and_test(&skb->users))) {
3094 get_kfree_skb_cb(skb)->reason = reason;
3095 local_irq_save(flags);
3096 skb->next = __this_cpu_read(softnet_data.completion_queue);
3097 __this_cpu_write(softnet_data.completion_queue, skb);
3098 raise_softirq_irqoff(NET_TX_SOFTIRQ);
3099 local_irq_restore(flags);
3101 EXPORT_SYMBOL(__dev_kfree_skb_irq);
3103 void __dev_kfree_skb_any(struct sk_buff *skb, enum skb_free_reason reason)
3105 if (in_irq() || irqs_disabled())
3106 __dev_kfree_skb_irq(skb, reason);
3110 EXPORT_SYMBOL(__dev_kfree_skb_any);
3114 * netif_device_detach - mark device as removed
3115 * @dev: network device
3117 * Mark device as removed from system and therefore no longer available.
3119 void netif_device_detach(struct net_device *dev)
3121 if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) &&
3122 netif_running(dev)) {
3123 netif_tx_stop_all_queues(dev);
3126 EXPORT_SYMBOL(netif_device_detach);
3129 * netif_device_attach - mark device as attached
3130 * @dev: network device
3132 * Mark device as attached from system and restart if needed.
3134 void netif_device_attach(struct net_device *dev)
3136 if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) &&
3137 netif_running(dev)) {
3138 netif_tx_wake_all_queues(dev);
3139 __netdev_watchdog_up(dev);
3142 EXPORT_SYMBOL(netif_device_attach);
3145 * Returns a Tx hash based on the given packet descriptor a Tx queues' number
3146 * to be used as a distribution range.
3148 static u16 skb_tx_hash(const struct net_device *dev,
3149 const struct net_device *sb_dev,
3150 struct sk_buff *skb)
3154 u16 qcount = dev->real_num_tx_queues;
3157 u8 tc = netdev_get_prio_tc_map(dev, skb->priority);
3159 qoffset = sb_dev->tc_to_txq[tc].offset;
3160 qcount = sb_dev->tc_to_txq[tc].count;
3163 if (skb_rx_queue_recorded(skb)) {
3164 hash = skb_get_rx_queue(skb);
3165 if (hash >= qoffset)
3167 while (unlikely(hash >= qcount))
3169 return hash + qoffset;
3172 return (u16) reciprocal_scale(skb_get_hash(skb), qcount) + qoffset;
3175 static void skb_warn_bad_offload(const struct sk_buff *skb)
3177 static const netdev_features_t null_features;
3178 struct net_device *dev = skb->dev;
3179 const char *name = "";
3181 if (!net_ratelimit())
3185 if (dev->dev.parent)
3186 name = dev_driver_string(dev->dev.parent);
3188 name = netdev_name(dev);
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);
3197 * Invalidate hardware checksum when packet is to be mangled, and
3198 * complete checksum manually on outgoing path.
3200 int skb_checksum_help(struct sk_buff *skb)
3203 int ret = 0, offset;
3205 if (skb->ip_summed == CHECKSUM_COMPLETE)
3206 goto out_set_summed;
3208 if (unlikely(skb_shinfo(skb)->gso_size)) {
3209 skb_warn_bad_offload(skb);
3213 /* Before computing a checksum, we should make sure no frag could
3214 * be modified by an external entity : checksum could be wrong.
3216 if (skb_has_shared_frag(skb)) {
3217 ret = __skb_linearize(skb);
3222 offset = skb_checksum_start_offset(skb);
3223 BUG_ON(offset >= skb_headlen(skb));
3224 csum = skb_checksum(skb, offset, skb->len - offset, 0);
3226 offset += skb->csum_offset;
3227 BUG_ON(offset + sizeof(__sum16) > skb_headlen(skb));
3229 ret = skb_ensure_writable(skb, offset + sizeof(__sum16));
3233 *(__sum16 *)(skb->data + offset) = csum_fold(csum) ?: CSUM_MANGLED_0;
3235 skb->ip_summed = CHECKSUM_NONE;
3239 EXPORT_SYMBOL(skb_checksum_help);
3241 int skb_crc32c_csum_help(struct sk_buff *skb)
3244 int ret = 0, offset, start;
3246 if (skb->ip_summed != CHECKSUM_PARTIAL)
3249 if (unlikely(skb_is_gso(skb)))
3252 /* Before computing a checksum, we should make sure no frag could
3253 * be modified by an external entity : checksum could be wrong.
3255 if (unlikely(skb_has_shared_frag(skb))) {
3256 ret = __skb_linearize(skb);
3260 start = skb_checksum_start_offset(skb);
3261 offset = start + offsetof(struct sctphdr, checksum);
3262 if (WARN_ON_ONCE(offset >= skb_headlen(skb))) {
3267 ret = skb_ensure_writable(skb, offset + sizeof(__le32));
3271 crc32c_csum = cpu_to_le32(~__skb_checksum(skb, start,
3272 skb->len - start, ~(__u32)0,
3274 *(__le32 *)(skb->data + offset) = crc32c_csum;
3275 skb->ip_summed = CHECKSUM_NONE;
3276 skb->csum_not_inet = 0;
3281 __be16 skb_network_protocol(struct sk_buff *skb, int *depth)
3283 __be16 type = skb->protocol;
3285 /* Tunnel gso handlers can set protocol to ethernet. */
3286 if (type == htons(ETH_P_TEB)) {
3289 if (unlikely(!pskb_may_pull(skb, sizeof(struct ethhdr))))
3292 eth = (struct ethhdr *)skb->data;
3293 type = eth->h_proto;
3296 return __vlan_get_protocol(skb, type, depth);
3300 * skb_mac_gso_segment - mac layer segmentation handler.
3301 * @skb: buffer to segment
3302 * @features: features for the output path (see dev->features)
3304 struct sk_buff *skb_mac_gso_segment(struct sk_buff *skb,
3305 netdev_features_t features)
3307 struct sk_buff *segs = ERR_PTR(-EPROTONOSUPPORT);
3308 struct packet_offload *ptype;
3309 int vlan_depth = skb->mac_len;
3310 __be16 type = skb_network_protocol(skb, &vlan_depth);
3312 if (unlikely(!type))
3313 return ERR_PTR(-EINVAL);
3315 __skb_pull(skb, vlan_depth);
3318 list_for_each_entry_rcu(ptype, &offload_base, list) {
3319 if (ptype->type == type && ptype->callbacks.gso_segment) {
3320 segs = ptype->callbacks.gso_segment(skb, features);
3326 __skb_push(skb, skb->data - skb_mac_header(skb));
3330 EXPORT_SYMBOL(skb_mac_gso_segment);
3333 /* openvswitch calls this on rx path, so we need a different check.
3335 static inline bool skb_needs_check(struct sk_buff *skb, bool tx_path)
3338 return skb->ip_summed != CHECKSUM_PARTIAL &&
3339 skb->ip_summed != CHECKSUM_UNNECESSARY;
3341 return skb->ip_summed == CHECKSUM_NONE;
3345 * __skb_gso_segment - Perform segmentation on skb.
3346 * @skb: buffer to segment
3347 * @features: features for the output path (see dev->features)
3348 * @tx_path: whether it is called in TX path
3350 * This function segments the given skb and returns a list of segments.
3352 * It may return NULL if the skb requires no segmentation. This is
3353 * only possible when GSO is used for verifying header integrity.
3355 * Segmentation preserves SKB_GSO_CB_OFFSET bytes of previous skb cb.
3357 struct sk_buff *__skb_gso_segment(struct sk_buff *skb,
3358 netdev_features_t features, bool tx_path)
3360 struct sk_buff *segs;
3362 if (unlikely(skb_needs_check(skb, tx_path))) {
3365 /* We're going to init ->check field in TCP or UDP header */
3366 err = skb_cow_head(skb, 0);
3368 return ERR_PTR(err);
3371 /* Only report GSO partial support if it will enable us to
3372 * support segmentation on this frame without needing additional
3375 if (features & NETIF_F_GSO_PARTIAL) {
3376 netdev_features_t partial_features = NETIF_F_GSO_ROBUST;
3377 struct net_device *dev = skb->dev;
3379 partial_features |= dev->features & dev->gso_partial_features;
3380 if (!skb_gso_ok(skb, features | partial_features))
3381 features &= ~NETIF_F_GSO_PARTIAL;
3384 BUILD_BUG_ON(SKB_GSO_CB_OFFSET +
3385 sizeof(*SKB_GSO_CB(skb)) > sizeof(skb->cb));
3387 SKB_GSO_CB(skb)->mac_offset = skb_headroom(skb);
3388 SKB_GSO_CB(skb)->encap_level = 0;
3390 skb_reset_mac_header(skb);
3391 skb_reset_mac_len(skb);
3393 segs = skb_mac_gso_segment(skb, features);
3395 if (segs != skb && unlikely(skb_needs_check(skb, tx_path) && !IS_ERR(segs)))
3396 skb_warn_bad_offload(skb);
3400 EXPORT_SYMBOL(__skb_gso_segment);
3402 /* Take action when hardware reception checksum errors are detected. */
3404 void netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
3406 if (net_ratelimit()) {
3407 pr_err("%s: hw csum failure\n", dev ? dev->name : "<unknown>");
3408 skb_dump(KERN_ERR, skb, true);
3412 EXPORT_SYMBOL(netdev_rx_csum_fault);
3415 /* XXX: check that highmem exists at all on the given machine. */
3416 static int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
3418 #ifdef CONFIG_HIGHMEM
3421 if (!(dev->features & NETIF_F_HIGHDMA)) {
3422 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3423 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3425 if (PageHighMem(skb_frag_page(frag)))
3433 /* If MPLS offload request, verify we are testing hardware MPLS features
3434 * instead of standard features for the netdev.
3436 #if IS_ENABLED(CONFIG_NET_MPLS_GSO)
3437 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3438 netdev_features_t features,
3441 if (eth_p_mpls(type))
3442 features &= skb->dev->mpls_features;
3447 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3448 netdev_features_t features,
3455 static netdev_features_t harmonize_features(struct sk_buff *skb,
3456 netdev_features_t features)
3460 type = skb_network_protocol(skb, NULL);
3461 features = net_mpls_features(skb, features, type);
3463 if (skb->ip_summed != CHECKSUM_NONE &&
3464 !can_checksum_protocol(features, type)) {
3465 features &= ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
3467 if (illegal_highdma(skb->dev, skb))
3468 features &= ~NETIF_F_SG;
3473 netdev_features_t passthru_features_check(struct sk_buff *skb,
3474 struct net_device *dev,
3475 netdev_features_t features)
3479 EXPORT_SYMBOL(passthru_features_check);
3481 static netdev_features_t dflt_features_check(struct sk_buff *skb,
3482 struct net_device *dev,
3483 netdev_features_t features)
3485 return vlan_features_check(skb, features);
3488 static netdev_features_t gso_features_check(const struct sk_buff *skb,
3489 struct net_device *dev,
3490 netdev_features_t features)
3492 u16 gso_segs = skb_shinfo(skb)->gso_segs;
3494 if (gso_segs > dev->gso_max_segs)
3495 return features & ~NETIF_F_GSO_MASK;
3497 /* Support for GSO partial features requires software
3498 * intervention before we can actually process the packets
3499 * so we need to strip support for any partial features now
3500 * and we can pull them back in after we have partially
3501 * segmented the frame.
3503 if (!(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL))
3504 features &= ~dev->gso_partial_features;
3506 /* Make sure to clear the IPv4 ID mangling feature if the
3507 * IPv4 header has the potential to be fragmented.
3509 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) {
3510 struct iphdr *iph = skb->encapsulation ?
3511 inner_ip_hdr(skb) : ip_hdr(skb);
3513 if (!(iph->frag_off & htons(IP_DF)))
3514 features &= ~NETIF_F_TSO_MANGLEID;
3520 netdev_features_t netif_skb_features(struct sk_buff *skb)
3522 struct net_device *dev = skb->dev;
3523 netdev_features_t features = dev->features;
3525 if (skb_is_gso(skb))
3526 features = gso_features_check(skb, dev, features);
3528 /* If encapsulation offload request, verify we are testing
3529 * hardware encapsulation features instead of standard
3530 * features for the netdev
3532 if (skb->encapsulation)
3533 features &= dev->hw_enc_features;
3535 if (skb_vlan_tagged(skb))
3536 features = netdev_intersect_features(features,
3537 dev->vlan_features |
3538 NETIF_F_HW_VLAN_CTAG_TX |
3539 NETIF_F_HW_VLAN_STAG_TX);
3541 if (dev->netdev_ops->ndo_features_check)
3542 features &= dev->netdev_ops->ndo_features_check(skb, dev,
3545 features &= dflt_features_check(skb, dev, features);
3547 return harmonize_features(skb, features);
3549 EXPORT_SYMBOL(netif_skb_features);
3551 static int xmit_one(struct sk_buff *skb, struct net_device *dev,
3552 struct netdev_queue *txq, bool more)
3557 if (dev_nit_active(dev))
3558 dev_queue_xmit_nit(skb, dev);
3561 trace_net_dev_start_xmit(skb, dev);
3562 rc = netdev_start_xmit(skb, dev, txq, more);
3563 trace_net_dev_xmit(skb, rc, dev, len);
3568 struct sk_buff *dev_hard_start_xmit(struct sk_buff *first, struct net_device *dev,
3569 struct netdev_queue *txq, int *ret)
3571 struct sk_buff *skb = first;
3572 int rc = NETDEV_TX_OK;
3575 struct sk_buff *next = skb->next;
3577 skb_mark_not_on_list(skb);
3578 rc = xmit_one(skb, dev, txq, next != NULL);
3579 if (unlikely(!dev_xmit_complete(rc))) {
3585 if (netif_tx_queue_stopped(txq) && skb) {
3586 rc = NETDEV_TX_BUSY;
3596 static struct sk_buff *validate_xmit_vlan(struct sk_buff *skb,
3597 netdev_features_t features)
3599 if (skb_vlan_tag_present(skb) &&
3600 !vlan_hw_offload_capable(features, skb->vlan_proto))
3601 skb = __vlan_hwaccel_push_inside(skb);
3605 int skb_csum_hwoffload_help(struct sk_buff *skb,
3606 const netdev_features_t features)
3608 if (unlikely(skb->csum_not_inet))
3609 return !!(features & NETIF_F_SCTP_CRC) ? 0 :
3610 skb_crc32c_csum_help(skb);
3612 return !!(features & NETIF_F_CSUM_MASK) ? 0 : skb_checksum_help(skb);
3614 EXPORT_SYMBOL(skb_csum_hwoffload_help);
3616 static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device *dev, bool *again)
3618 netdev_features_t features;
3620 features = netif_skb_features(skb);
3621 skb = validate_xmit_vlan(skb, features);
3625 skb = sk_validate_xmit_skb(skb, dev);
3629 if (netif_needs_gso(skb, features)) {
3630 struct sk_buff *segs;
3632 segs = skb_gso_segment(skb, features);
3640 if (skb_needs_linearize(skb, features) &&
3641 __skb_linearize(skb))
3644 /* If packet is not checksummed and device does not
3645 * support checksumming for this protocol, complete
3646 * checksumming here.
3648 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3649 if (skb->encapsulation)
3650 skb_set_inner_transport_header(skb,
3651 skb_checksum_start_offset(skb));
3653 skb_set_transport_header(skb,
3654 skb_checksum_start_offset(skb));
3655 if (skb_csum_hwoffload_help(skb, features))
3660 skb = validate_xmit_xfrm(skb, features, again);
3667 atomic_long_inc(&dev->tx_dropped);
3671 struct sk_buff *validate_xmit_skb_list(struct sk_buff *skb, struct net_device *dev, bool *again)
3673 struct sk_buff *next, *head = NULL, *tail;
3675 for (; skb != NULL; skb = next) {
3677 skb_mark_not_on_list(skb);
3679 /* in case skb wont be segmented, point to itself */
3682 skb = validate_xmit_skb(skb, dev, again);
3690 /* If skb was segmented, skb->prev points to
3691 * the last segment. If not, it still contains skb.
3697 EXPORT_SYMBOL_GPL(validate_xmit_skb_list);
3699 static void qdisc_pkt_len_init(struct sk_buff *skb)
3701 const struct skb_shared_info *shinfo = skb_shinfo(skb);
3703 qdisc_skb_cb(skb)->pkt_len = skb->len;
3705 /* To get more precise estimation of bytes sent on wire,
3706 * we add to pkt_len the headers size of all segments
3708 if (shinfo->gso_size && skb_transport_header_was_set(skb)) {
3709 unsigned int hdr_len;
3710 u16 gso_segs = shinfo->gso_segs;
3712 /* mac layer + network layer */
3713 hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
3715 /* + transport layer */
3716 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
3717 const struct tcphdr *th;
3718 struct tcphdr _tcphdr;
3720 th = skb_header_pointer(skb, skb_transport_offset(skb),
3721 sizeof(_tcphdr), &_tcphdr);
3723 hdr_len += __tcp_hdrlen(th);
3725 struct udphdr _udphdr;
3727 if (skb_header_pointer(skb, skb_transport_offset(skb),
3728 sizeof(_udphdr), &_udphdr))
3729 hdr_len += sizeof(struct udphdr);
3732 if (shinfo->gso_type & SKB_GSO_DODGY)
3733 gso_segs = DIV_ROUND_UP(skb->len - hdr_len,
3736 qdisc_skb_cb(skb)->pkt_len += (gso_segs - 1) * hdr_len;
3740 static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q,
3741 struct net_device *dev,
3742 struct netdev_queue *txq)
3744 spinlock_t *root_lock = qdisc_lock(q);
3745 struct sk_buff *to_free = NULL;
3749 qdisc_calculate_pkt_len(skb, q);
3751 if (q->flags & TCQ_F_NOLOCK) {
3752 rc = q->enqueue(skb, q, &to_free) & NET_XMIT_MASK;
3755 if (unlikely(to_free))
3756 kfree_skb_list(to_free);
3761 * Heuristic to force contended enqueues to serialize on a
3762 * separate lock before trying to get qdisc main lock.
3763 * This permits qdisc->running owner to get the lock more
3764 * often and dequeue packets faster.
3766 contended = qdisc_is_running(q);
3767 if (unlikely(contended))
3768 spin_lock(&q->busylock);
3770 spin_lock(root_lock);
3771 if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) {
3772 __qdisc_drop(skb, &to_free);
3774 } else if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) &&
3775 qdisc_run_begin(q)) {
3777 * This is a work-conserving queue; there are no old skbs
3778 * waiting to be sent out; and the qdisc is not running -
3779 * xmit the skb directly.
3782 qdisc_bstats_update(q, skb);
3784 if (sch_direct_xmit(skb, q, dev, txq, root_lock, true)) {
3785 if (unlikely(contended)) {
3786 spin_unlock(&q->busylock);
3793 rc = NET_XMIT_SUCCESS;
3795 rc = q->enqueue(skb, q, &to_free) & NET_XMIT_MASK;
3796 if (qdisc_run_begin(q)) {
3797 if (unlikely(contended)) {
3798 spin_unlock(&q->busylock);
3805 spin_unlock(root_lock);
3806 if (unlikely(to_free))
3807 kfree_skb_list(to_free);
3808 if (unlikely(contended))
3809 spin_unlock(&q->busylock);
3813 #if IS_ENABLED(CONFIG_CGROUP_NET_PRIO)
3814 static void skb_update_prio(struct sk_buff *skb)
3816 const struct netprio_map *map;
3817 const struct sock *sk;
3818 unsigned int prioidx;
3822 map = rcu_dereference_bh(skb->dev->priomap);
3825 sk = skb_to_full_sk(skb);
3829 prioidx = sock_cgroup_prioidx(&sk->sk_cgrp_data);
3831 if (prioidx < map->priomap_len)
3832 skb->priority = map->priomap[prioidx];
3835 #define skb_update_prio(skb)
3839 * dev_loopback_xmit - loop back @skb
3840 * @net: network namespace this loopback is happening in
3841 * @sk: sk needed to be a netfilter okfn
3842 * @skb: buffer to transmit
3844 int dev_loopback_xmit(struct net *net, struct sock *sk, struct sk_buff *skb)
3846 skb_reset_mac_header(skb);
3847 __skb_pull(skb, skb_network_offset(skb));
3848 skb->pkt_type = PACKET_LOOPBACK;
3849 skb->ip_summed = CHECKSUM_UNNECESSARY;
3850 WARN_ON(!skb_dst(skb));
3855 EXPORT_SYMBOL(dev_loopback_xmit);
3857 #ifdef CONFIG_NET_EGRESS
3858 static struct sk_buff *
3859 sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
3861 struct mini_Qdisc *miniq = rcu_dereference_bh(dev->miniq_egress);
3862 struct tcf_result cl_res;
3867 /* qdisc_skb_cb(skb)->pkt_len was already set by the caller. */
3868 mini_qdisc_bstats_cpu_update(miniq, skb);
3870 switch (tcf_classify(skb, miniq->filter_list, &cl_res, false)) {
3872 case TC_ACT_RECLASSIFY:
3873 skb->tc_index = TC_H_MIN(cl_res.classid);
3876 mini_qdisc_qstats_cpu_drop(miniq);
3877 *ret = NET_XMIT_DROP;
3883 *ret = NET_XMIT_SUCCESS;
3886 case TC_ACT_REDIRECT:
3887 /* No need to push/pop skb's mac_header here on egress! */
3888 skb_do_redirect(skb);
3889 *ret = NET_XMIT_SUCCESS;
3897 #endif /* CONFIG_NET_EGRESS */
3900 static int __get_xps_queue_idx(struct net_device *dev, struct sk_buff *skb,
3901 struct xps_dev_maps *dev_maps, unsigned int tci)
3903 struct xps_map *map;
3904 int queue_index = -1;
3908 tci += netdev_get_prio_tc_map(dev, skb->priority);
3911 map = rcu_dereference(dev_maps->attr_map[tci]);
3914 queue_index = map->queues[0];
3916 queue_index = map->queues[reciprocal_scale(
3917 skb_get_hash(skb), map->len)];
3918 if (unlikely(queue_index >= dev->real_num_tx_queues))
3925 static int get_xps_queue(struct net_device *dev, struct net_device *sb_dev,
3926 struct sk_buff *skb)
3929 struct xps_dev_maps *dev_maps;
3930 struct sock *sk = skb->sk;
3931 int queue_index = -1;
3933 if (!static_key_false(&xps_needed))
3937 if (!static_key_false(&xps_rxqs_needed))
3940 dev_maps = rcu_dereference(sb_dev->xps_rxqs_map);
3942 int tci = sk_rx_queue_get(sk);
3944 if (tci >= 0 && tci < dev->num_rx_queues)
3945 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
3950 if (queue_index < 0) {
3951 dev_maps = rcu_dereference(sb_dev->xps_cpus_map);
3953 unsigned int tci = skb->sender_cpu - 1;
3955 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
3967 u16 dev_pick_tx_zero(struct net_device *dev, struct sk_buff *skb,
3968 struct net_device *sb_dev)
3972 EXPORT_SYMBOL(dev_pick_tx_zero);
3974 u16 dev_pick_tx_cpu_id(struct net_device *dev, struct sk_buff *skb,
3975 struct net_device *sb_dev)
3977 return (u16)raw_smp_processor_id() % dev->real_num_tx_queues;
3979 EXPORT_SYMBOL(dev_pick_tx_cpu_id);
3981 u16 netdev_pick_tx(struct net_device *dev, struct sk_buff *skb,
3982 struct net_device *sb_dev)
3984 struct sock *sk = skb->sk;
3985 int queue_index = sk_tx_queue_get(sk);
3987 sb_dev = sb_dev ? : dev;
3989 if (queue_index < 0 || skb->ooo_okay ||
3990 queue_index >= dev->real_num_tx_queues) {
3991 int new_index = get_xps_queue(dev, sb_dev, skb);
3994 new_index = skb_tx_hash(dev, sb_dev, skb);
3996 if (queue_index != new_index && sk &&
3998 rcu_access_pointer(sk->sk_dst_cache))
3999 sk_tx_queue_set(sk, new_index);
4001 queue_index = new_index;
4006 EXPORT_SYMBOL(netdev_pick_tx);
4008 struct netdev_queue *netdev_core_pick_tx(struct net_device *dev,
4009 struct sk_buff *skb,
4010 struct net_device *sb_dev)
4012 int queue_index = 0;
4015 u32 sender_cpu = skb->sender_cpu - 1;
4017 if (sender_cpu >= (u32)NR_CPUS)
4018 skb->sender_cpu = raw_smp_processor_id() + 1;
4021 if (dev->real_num_tx_queues != 1) {
4022 const struct net_device_ops *ops = dev->netdev_ops;
4024 if (ops->ndo_select_queue)
4025 queue_index = ops->ndo_select_queue(dev, skb, sb_dev);
4027 queue_index = netdev_pick_tx(dev, skb, sb_dev);
4029 queue_index = netdev_cap_txqueue(dev, queue_index);
4032 skb_set_queue_mapping(skb, queue_index);
4033 return netdev_get_tx_queue(dev, queue_index);
4037 * __dev_queue_xmit - transmit a buffer
4038 * @skb: buffer to transmit
4039 * @sb_dev: suboordinate device used for L2 forwarding offload
4041 * Queue a buffer for transmission to a network device. The caller must
4042 * have set the device and priority and built the buffer before calling
4043 * this function. The function can be called from an interrupt.
4045 * A negative errno code is returned on a failure. A success does not
4046 * guarantee the frame will be transmitted as it may be dropped due
4047 * to congestion or traffic shaping.
4049 * -----------------------------------------------------------------------------------
4050 * I notice this method can also return errors from the queue disciplines,
4051 * including NET_XMIT_DROP, which is a positive value. So, errors can also
4054 * Regardless of the return value, the skb is consumed, so it is currently
4055 * difficult to retry a send to this method. (You can bump the ref count
4056 * before sending to hold a reference for retry if you are careful.)
4058 * When calling this method, interrupts MUST be enabled. This is because
4059 * the BH enable code must have IRQs enabled so that it will not deadlock.
4062 static int __dev_queue_xmit(struct sk_buff *skb, struct net_device *sb_dev)
4064 struct net_device *dev = skb->dev;
4065 struct netdev_queue *txq;
4070 skb_reset_mac_header(skb);
4072 if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_SCHED_TSTAMP))
4073 __skb_tstamp_tx(skb, NULL, skb->sk, SCM_TSTAMP_SCHED);
4075 /* Disable soft irqs for various locks below. Also
4076 * stops preemption for RCU.
4080 skb_update_prio(skb);
4082 qdisc_pkt_len_init(skb);
4083 #ifdef CONFIG_NET_CLS_ACT
4084 skb->tc_at_ingress = 0;
4085 # ifdef CONFIG_NET_EGRESS
4086 if (static_branch_unlikely(&egress_needed_key)) {
4087 skb = sch_handle_egress(skb, &rc, dev);
4093 /* If device/qdisc don't need skb->dst, release it right now while
4094 * its hot in this cpu cache.
4096 if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
4101 txq = netdev_core_pick_tx(dev, skb, sb_dev);
4102 q = rcu_dereference_bh(txq->qdisc);
4104 trace_net_dev_queue(skb);
4106 rc = __dev_xmit_skb(skb, q, dev, txq);
4110 /* The device has no queue. Common case for software devices:
4111 * loopback, all the sorts of tunnels...
4113 * Really, it is unlikely that netif_tx_lock protection is necessary
4114 * here. (f.e. loopback and IP tunnels are clean ignoring statistics
4116 * However, it is possible, that they rely on protection
4119 * Check this and shot the lock. It is not prone from deadlocks.
4120 *Either shot noqueue qdisc, it is even simpler 8)
4122 if (dev->flags & IFF_UP) {
4123 int cpu = smp_processor_id(); /* ok because BHs are off */
4125 if (txq->xmit_lock_owner != cpu) {
4126 if (dev_xmit_recursion())
4127 goto recursion_alert;
4129 skb = validate_xmit_skb(skb, dev, &again);
4133 HARD_TX_LOCK(dev, txq, cpu);
4135 if (!netif_xmit_stopped(txq)) {
4136 dev_xmit_recursion_inc();
4137 skb = dev_hard_start_xmit(skb, dev, txq, &rc);
4138 dev_xmit_recursion_dec();
4139 if (dev_xmit_complete(rc)) {
4140 HARD_TX_UNLOCK(dev, txq);
4144 HARD_TX_UNLOCK(dev, txq);
4145 net_crit_ratelimited("Virtual device %s asks to queue packet!\n",
4148 /* Recursion is detected! It is possible,
4152 net_crit_ratelimited("Dead loop on virtual device %s, fix it urgently!\n",
4158 rcu_read_unlock_bh();
4160 atomic_long_inc(&dev->tx_dropped);
4161 kfree_skb_list(skb);
4164 rcu_read_unlock_bh();
4168 int dev_queue_xmit(struct sk_buff *skb)
4170 return __dev_queue_xmit(skb, NULL);
4172 EXPORT_SYMBOL(dev_queue_xmit);
4174 int dev_queue_xmit_accel(struct sk_buff *skb, struct net_device *sb_dev)
4176 return __dev_queue_xmit(skb, sb_dev);
4178 EXPORT_SYMBOL(dev_queue_xmit_accel);
4180 int dev_direct_xmit(struct sk_buff *skb, u16 queue_id)
4182 struct net_device *dev = skb->dev;
4183 struct sk_buff *orig_skb = skb;
4184 struct netdev_queue *txq;
4185 int ret = NETDEV_TX_BUSY;
4188 if (unlikely(!netif_running(dev) ||
4189 !netif_carrier_ok(dev)))
4192 skb = validate_xmit_skb_list(skb, dev, &again);
4193 if (skb != orig_skb)
4196 skb_set_queue_mapping(skb, queue_id);
4197 txq = skb_get_tx_queue(dev, skb);
4201 dev_xmit_recursion_inc();
4202 HARD_TX_LOCK(dev, txq, smp_processor_id());
4203 if (!netif_xmit_frozen_or_drv_stopped(txq))
4204 ret = netdev_start_xmit(skb, dev, txq, false);
4205 HARD_TX_UNLOCK(dev, txq);
4206 dev_xmit_recursion_dec();
4210 if (!dev_xmit_complete(ret))
4215 atomic_long_inc(&dev->tx_dropped);
4216 kfree_skb_list(skb);
4217 return NET_XMIT_DROP;
4219 EXPORT_SYMBOL(dev_direct_xmit);
4221 /*************************************************************************
4223 *************************************************************************/
4225 int netdev_max_backlog __read_mostly = 1000;
4226 EXPORT_SYMBOL(netdev_max_backlog);
4228 int netdev_tstamp_prequeue __read_mostly = 1;
4229 int netdev_budget __read_mostly = 300;
4230 /* Must be at least 2 jiffes to guarantee 1 jiffy timeout */
4231 unsigned int __read_mostly netdev_budget_usecs = 2 * USEC_PER_SEC / HZ;
4232 int weight_p __read_mostly = 64; /* old backlog weight */
4233 int dev_weight_rx_bias __read_mostly = 1; /* bias for backlog weight */
4234 int dev_weight_tx_bias __read_mostly = 1; /* bias for output_queue quota */
4235 int dev_rx_weight __read_mostly = 64;
4236 int dev_tx_weight __read_mostly = 64;
4237 /* Maximum number of GRO_NORMAL skbs to batch up for list-RX */
4238 int gro_normal_batch __read_mostly = 8;
4240 /* Called with irq disabled */
4241 static inline void ____napi_schedule(struct softnet_data *sd,
4242 struct napi_struct *napi)
4244 list_add_tail(&napi->poll_list, &sd->poll_list);
4245 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4250 /* One global table that all flow-based protocols share. */
4251 struct rps_sock_flow_table __rcu *rps_sock_flow_table __read_mostly;
4252 EXPORT_SYMBOL(rps_sock_flow_table);
4253 u32 rps_cpu_mask __read_mostly;
4254 EXPORT_SYMBOL(rps_cpu_mask);
4256 struct static_key_false rps_needed __read_mostly;
4257 EXPORT_SYMBOL(rps_needed);
4258 struct static_key_false rfs_needed __read_mostly;
4259 EXPORT_SYMBOL(rfs_needed);
4261 static struct rps_dev_flow *
4262 set_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4263 struct rps_dev_flow *rflow, u16 next_cpu)
4265 if (next_cpu < nr_cpu_ids) {
4266 #ifdef CONFIG_RFS_ACCEL
4267 struct netdev_rx_queue *rxqueue;
4268 struct rps_dev_flow_table *flow_table;
4269 struct rps_dev_flow *old_rflow;
4274 /* Should we steer this flow to a different hardware queue? */
4275 if (!skb_rx_queue_recorded(skb) || !dev->rx_cpu_rmap ||
4276 !(dev->features & NETIF_F_NTUPLE))
4278 rxq_index = cpu_rmap_lookup_index(dev->rx_cpu_rmap, next_cpu);
4279 if (rxq_index == skb_get_rx_queue(skb))
4282 rxqueue = dev->_rx + rxq_index;
4283 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4286 flow_id = skb_get_hash(skb) & flow_table->mask;
4287 rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb,
4288 rxq_index, flow_id);
4292 rflow = &flow_table->flows[flow_id];
4294 if (old_rflow->filter == rflow->filter)
4295 old_rflow->filter = RPS_NO_FILTER;
4299 per_cpu(softnet_data, next_cpu).input_queue_head;
4302 rflow->cpu = next_cpu;
4307 * get_rps_cpu is called from netif_receive_skb and returns the target
4308 * CPU from the RPS map of the receiving queue for a given skb.
4309 * rcu_read_lock must be held on entry.
4311 static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4312 struct rps_dev_flow **rflowp)
4314 const struct rps_sock_flow_table *sock_flow_table;
4315 struct netdev_rx_queue *rxqueue = dev->_rx;
4316 struct rps_dev_flow_table *flow_table;
4317 struct rps_map *map;
4322 if (skb_rx_queue_recorded(skb)) {
4323 u16 index = skb_get_rx_queue(skb);
4325 if (unlikely(index >= dev->real_num_rx_queues)) {
4326 WARN_ONCE(dev->real_num_rx_queues > 1,
4327 "%s received packet on queue %u, but number "
4328 "of RX queues is %u\n",
4329 dev->name, index, dev->real_num_rx_queues);
4335 /* Avoid computing hash if RFS/RPS is not active for this rxqueue */
4337 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4338 map = rcu_dereference(rxqueue->rps_map);
4339 if (!flow_table && !map)
4342 skb_reset_network_header(skb);
4343 hash = skb_get_hash(skb);
4347 sock_flow_table = rcu_dereference(rps_sock_flow_table);
4348 if (flow_table && sock_flow_table) {
4349 struct rps_dev_flow *rflow;
4353 /* First check into global flow table if there is a match */
4354 ident = sock_flow_table->ents[hash & sock_flow_table->mask];
4355 if ((ident ^ hash) & ~rps_cpu_mask)
4358 next_cpu = ident & rps_cpu_mask;
4360 /* OK, now we know there is a match,
4361 * we can look at the local (per receive queue) flow table
4363 rflow = &flow_table->flows[hash & flow_table->mask];
4367 * If the desired CPU (where last recvmsg was done) is
4368 * different from current CPU (one in the rx-queue flow
4369 * table entry), switch if one of the following holds:
4370 * - Current CPU is unset (>= nr_cpu_ids).
4371 * - Current CPU is offline.
4372 * - The current CPU's queue tail has advanced beyond the
4373 * last packet that was enqueued using this table entry.
4374 * This guarantees that all previous packets for the flow
4375 * have been dequeued, thus preserving in order delivery.
4377 if (unlikely(tcpu != next_cpu) &&
4378 (tcpu >= nr_cpu_ids || !cpu_online(tcpu) ||
4379 ((int)(per_cpu(softnet_data, tcpu).input_queue_head -
4380 rflow->last_qtail)) >= 0)) {
4382 rflow = set_rps_cpu(dev, skb, rflow, next_cpu);
4385 if (tcpu < nr_cpu_ids && cpu_online(tcpu)) {
4395 tcpu = map->cpus[reciprocal_scale(hash, map->len)];
4396 if (cpu_online(tcpu)) {
4406 #ifdef CONFIG_RFS_ACCEL
4409 * rps_may_expire_flow - check whether an RFS hardware filter may be removed
4410 * @dev: Device on which the filter was set
4411 * @rxq_index: RX queue index
4412 * @flow_id: Flow ID passed to ndo_rx_flow_steer()
4413 * @filter_id: Filter ID returned by ndo_rx_flow_steer()
4415 * Drivers that implement ndo_rx_flow_steer() should periodically call
4416 * this function for each installed filter and remove the filters for
4417 * which it returns %true.
4419 bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index,
4420 u32 flow_id, u16 filter_id)
4422 struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index;
4423 struct rps_dev_flow_table *flow_table;
4424 struct rps_dev_flow *rflow;
4429 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4430 if (flow_table && flow_id <= flow_table->mask) {
4431 rflow = &flow_table->flows[flow_id];
4432 cpu = READ_ONCE(rflow->cpu);
4433 if (rflow->filter == filter_id && cpu < nr_cpu_ids &&
4434 ((int)(per_cpu(softnet_data, cpu).input_queue_head -
4435 rflow->last_qtail) <
4436 (int)(10 * flow_table->mask)))
4442 EXPORT_SYMBOL(rps_may_expire_flow);
4444 #endif /* CONFIG_RFS_ACCEL */
4446 /* Called from hardirq (IPI) context */
4447 static void rps_trigger_softirq(void *data)
4449 struct softnet_data *sd = data;
4451 ____napi_schedule(sd, &sd->backlog);
4455 #endif /* CONFIG_RPS */
4458 * Check if this softnet_data structure is another cpu one
4459 * If yes, queue it to our IPI list and return 1
4462 static int rps_ipi_queued(struct softnet_data *sd)
4465 struct softnet_data *mysd = this_cpu_ptr(&softnet_data);
4468 sd->rps_ipi_next = mysd->rps_ipi_list;
4469 mysd->rps_ipi_list = sd;
4471 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4474 #endif /* CONFIG_RPS */
4478 #ifdef CONFIG_NET_FLOW_LIMIT
4479 int netdev_flow_limit_table_len __read_mostly = (1 << 12);
4482 static bool skb_flow_limit(struct sk_buff *skb, unsigned int qlen)
4484 #ifdef CONFIG_NET_FLOW_LIMIT
4485 struct sd_flow_limit *fl;
4486 struct softnet_data *sd;
4487 unsigned int old_flow, new_flow;
4489 if (qlen < (netdev_max_backlog >> 1))
4492 sd = this_cpu_ptr(&softnet_data);
4495 fl = rcu_dereference(sd->flow_limit);
4497 new_flow = skb_get_hash(skb) & (fl->num_buckets - 1);
4498 old_flow = fl->history[fl->history_head];
4499 fl->history[fl->history_head] = new_flow;
4502 fl->history_head &= FLOW_LIMIT_HISTORY - 1;
4504 if (likely(fl->buckets[old_flow]))
4505 fl->buckets[old_flow]--;
4507 if (++fl->buckets[new_flow] > (FLOW_LIMIT_HISTORY >> 1)) {
4519 * enqueue_to_backlog is called to queue an skb to a per CPU backlog
4520 * queue (may be a remote CPU queue).
4522 static int enqueue_to_backlog(struct sk_buff *skb, int cpu,
4523 unsigned int *qtail)
4525 struct softnet_data *sd;
4526 unsigned long flags;
4529 sd = &per_cpu(softnet_data, cpu);
4531 local_irq_save(flags);
4534 if (!netif_running(skb->dev))
4536 qlen = skb_queue_len(&sd->input_pkt_queue);
4537 if (qlen <= netdev_max_backlog && !skb_flow_limit(skb, qlen)) {
4540 __skb_queue_tail(&sd->input_pkt_queue, skb);
4541 input_queue_tail_incr_save(sd, qtail);
4543 local_irq_restore(flags);
4544 return NET_RX_SUCCESS;
4547 /* Schedule NAPI for backlog device
4548 * We can use non atomic operation since we own the queue lock
4550 if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state)) {
4551 if (!rps_ipi_queued(sd))
4552 ____napi_schedule(sd, &sd->backlog);
4561 local_irq_restore(flags);
4563 atomic_long_inc(&skb->dev->rx_dropped);
4568 static struct netdev_rx_queue *netif_get_rxqueue(struct sk_buff *skb)
4570 struct net_device *dev = skb->dev;
4571 struct netdev_rx_queue *rxqueue;
4575 if (skb_rx_queue_recorded(skb)) {
4576 u16 index = skb_get_rx_queue(skb);
4578 if (unlikely(index >= dev->real_num_rx_queues)) {
4579 WARN_ONCE(dev->real_num_rx_queues > 1,
4580 "%s received packet on queue %u, but number "
4581 "of RX queues is %u\n",
4582 dev->name, index, dev->real_num_rx_queues);
4584 return rxqueue; /* Return first rxqueue */
4591 static u32 netif_receive_generic_xdp(struct sk_buff *skb,
4592 struct xdp_buff *xdp,
4593 struct bpf_prog *xdp_prog)
4595 struct netdev_rx_queue *rxqueue;
4596 void *orig_data, *orig_data_end;
4597 u32 metalen, act = XDP_DROP;
4598 __be16 orig_eth_type;
4604 /* Reinjected packets coming from act_mirred or similar should
4605 * not get XDP generic processing.
4607 if (skb_is_redirected(skb))
4610 /* XDP packets must be linear and must have sufficient headroom
4611 * of XDP_PACKET_HEADROOM bytes. This is the guarantee that also
4612 * native XDP provides, thus we need to do it here as well.
4614 if (skb_cloned(skb) || skb_is_nonlinear(skb) ||
4615 skb_headroom(skb) < XDP_PACKET_HEADROOM) {
4616 int hroom = XDP_PACKET_HEADROOM - skb_headroom(skb);
4617 int troom = skb->tail + skb->data_len - skb->end;
4619 /* In case we have to go down the path and also linearize,
4620 * then lets do the pskb_expand_head() work just once here.
4622 if (pskb_expand_head(skb,
4623 hroom > 0 ? ALIGN(hroom, NET_SKB_PAD) : 0,
4624 troom > 0 ? troom + 128 : 0, GFP_ATOMIC))
4626 if (skb_linearize(skb))
4630 /* The XDP program wants to see the packet starting at the MAC
4633 mac_len = skb->data - skb_mac_header(skb);
4634 hlen = skb_headlen(skb) + mac_len;
4635 xdp->data = skb->data - mac_len;
4636 xdp->data_meta = xdp->data;
4637 xdp->data_end = xdp->data + hlen;
4638 xdp->data_hard_start = skb->data - skb_headroom(skb);
4640 /* SKB "head" area always have tailroom for skb_shared_info */
4641 xdp->frame_sz = (void *)skb_end_pointer(skb) - xdp->data_hard_start;
4642 xdp->frame_sz += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
4644 orig_data_end = xdp->data_end;
4645 orig_data = xdp->data;
4646 eth = (struct ethhdr *)xdp->data;
4647 orig_bcast = is_multicast_ether_addr_64bits(eth->h_dest);
4648 orig_eth_type = eth->h_proto;
4650 rxqueue = netif_get_rxqueue(skb);
4651 xdp->rxq = &rxqueue->xdp_rxq;
4653 act = bpf_prog_run_xdp(xdp_prog, xdp);
4655 /* check if bpf_xdp_adjust_head was used */
4656 off = xdp->data - orig_data;
4659 __skb_pull(skb, off);
4661 __skb_push(skb, -off);
4663 skb->mac_header += off;
4664 skb_reset_network_header(skb);
4667 /* check if bpf_xdp_adjust_tail was used */
4668 off = xdp->data_end - orig_data_end;
4670 skb_set_tail_pointer(skb, xdp->data_end - xdp->data);
4671 skb->len += off; /* positive on grow, negative on shrink */
4674 /* check if XDP changed eth hdr such SKB needs update */
4675 eth = (struct ethhdr *)xdp->data;
4676 if ((orig_eth_type != eth->h_proto) ||
4677 (orig_bcast != is_multicast_ether_addr_64bits(eth->h_dest))) {
4678 __skb_push(skb, ETH_HLEN);
4679 skb->protocol = eth_type_trans(skb, skb->dev);
4685 __skb_push(skb, mac_len);
4688 metalen = xdp->data - xdp->data_meta;
4690 skb_metadata_set(skb, metalen);
4693 bpf_warn_invalid_xdp_action(act);
4696 trace_xdp_exception(skb->dev, xdp_prog, act);
4707 /* When doing generic XDP we have to bypass the qdisc layer and the
4708 * network taps in order to match in-driver-XDP behavior.
4710 void generic_xdp_tx(struct sk_buff *skb, struct bpf_prog *xdp_prog)
4712 struct net_device *dev = skb->dev;
4713 struct netdev_queue *txq;
4714 bool free_skb = true;
4717 txq = netdev_core_pick_tx(dev, skb, NULL);
4718 cpu = smp_processor_id();
4719 HARD_TX_LOCK(dev, txq, cpu);
4720 if (!netif_xmit_stopped(txq)) {
4721 rc = netdev_start_xmit(skb, dev, txq, 0);
4722 if (dev_xmit_complete(rc))
4725 HARD_TX_UNLOCK(dev, txq);
4727 trace_xdp_exception(dev, xdp_prog, XDP_TX);
4732 static DEFINE_STATIC_KEY_FALSE(generic_xdp_needed_key);
4734 int do_xdp_generic(struct bpf_prog *xdp_prog, struct sk_buff *skb)
4737 struct xdp_buff xdp;
4741 act = netif_receive_generic_xdp(skb, &xdp, xdp_prog);
4742 if (act != XDP_PASS) {
4745 err = xdp_do_generic_redirect(skb->dev, skb,
4751 generic_xdp_tx(skb, xdp_prog);
4762 EXPORT_SYMBOL_GPL(do_xdp_generic);
4764 static int netif_rx_internal(struct sk_buff *skb)
4768 net_timestamp_check(netdev_tstamp_prequeue, skb);
4770 trace_netif_rx(skb);
4773 if (static_branch_unlikely(&rps_needed)) {
4774 struct rps_dev_flow voidflow, *rflow = &voidflow;
4780 cpu = get_rps_cpu(skb->dev, skb, &rflow);
4782 cpu = smp_processor_id();
4784 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
4793 ret = enqueue_to_backlog(skb, get_cpu(), &qtail);
4800 * netif_rx - post buffer to the network code
4801 * @skb: buffer to post
4803 * This function receives a packet from a device driver and queues it for
4804 * the upper (protocol) levels to process. It always succeeds. The buffer
4805 * may be dropped during processing for congestion control or by the
4809 * NET_RX_SUCCESS (no congestion)
4810 * NET_RX_DROP (packet was dropped)
4814 int netif_rx(struct sk_buff *skb)
4818 trace_netif_rx_entry(skb);
4820 ret = netif_rx_internal(skb);
4821 trace_netif_rx_exit(ret);
4825 EXPORT_SYMBOL(netif_rx);
4827 int netif_rx_ni(struct sk_buff *skb)
4831 trace_netif_rx_ni_entry(skb);
4834 err = netif_rx_internal(skb);
4835 if (local_softirq_pending())
4838 trace_netif_rx_ni_exit(err);
4842 EXPORT_SYMBOL(netif_rx_ni);
4844 int netif_rx_any_context(struct sk_buff *skb)
4847 * If invoked from contexts which do not invoke bottom half
4848 * processing either at return from interrupt or when softrqs are
4849 * reenabled, use netif_rx_ni() which invokes bottomhalf processing
4853 return netif_rx(skb);
4855 return netif_rx_ni(skb);
4857 EXPORT_SYMBOL(netif_rx_any_context);
4859 static __latent_entropy void net_tx_action(struct softirq_action *h)
4861 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
4863 if (sd->completion_queue) {
4864 struct sk_buff *clist;
4866 local_irq_disable();
4867 clist = sd->completion_queue;
4868 sd->completion_queue = NULL;
4872 struct sk_buff *skb = clist;
4874 clist = clist->next;
4876 WARN_ON(refcount_read(&skb->users));
4877 if (likely(get_kfree_skb_cb(skb)->reason == SKB_REASON_CONSUMED))
4878 trace_consume_skb(skb);
4880 trace_kfree_skb(skb, net_tx_action);
4882 if (skb->fclone != SKB_FCLONE_UNAVAILABLE)
4885 __kfree_skb_defer(skb);
4888 __kfree_skb_flush();
4891 if (sd->output_queue) {
4894 local_irq_disable();
4895 head = sd->output_queue;
4896 sd->output_queue = NULL;
4897 sd->output_queue_tailp = &sd->output_queue;
4901 struct Qdisc *q = head;
4902 spinlock_t *root_lock = NULL;
4904 head = head->next_sched;
4906 if (!(q->flags & TCQ_F_NOLOCK)) {
4907 root_lock = qdisc_lock(q);
4908 spin_lock(root_lock);
4910 /* We need to make sure head->next_sched is read
4911 * before clearing __QDISC_STATE_SCHED
4913 smp_mb__before_atomic();
4914 clear_bit(__QDISC_STATE_SCHED, &q->state);
4917 spin_unlock(root_lock);
4921 xfrm_dev_backlog(sd);
4924 #if IS_ENABLED(CONFIG_BRIDGE) && IS_ENABLED(CONFIG_ATM_LANE)
4925 /* This hook is defined here for ATM LANE */
4926 int (*br_fdb_test_addr_hook)(struct net_device *dev,
4927 unsigned char *addr) __read_mostly;
4928 EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook);
4931 static inline struct sk_buff *
4932 sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
4933 struct net_device *orig_dev)
4935 #ifdef CONFIG_NET_CLS_ACT
4936 struct mini_Qdisc *miniq = rcu_dereference_bh(skb->dev->miniq_ingress);
4937 struct tcf_result cl_res;
4939 /* If there's at least one ingress present somewhere (so
4940 * we get here via enabled static key), remaining devices
4941 * that are not configured with an ingress qdisc will bail
4948 *ret = deliver_skb(skb, *pt_prev, orig_dev);
4952 qdisc_skb_cb(skb)->pkt_len = skb->len;
4953 skb->tc_at_ingress = 1;
4954 mini_qdisc_bstats_cpu_update(miniq, skb);
4956 switch (tcf_classify_ingress(skb, miniq->block, miniq->filter_list,
4959 case TC_ACT_RECLASSIFY:
4960 skb->tc_index = TC_H_MIN(cl_res.classid);
4963 mini_qdisc_qstats_cpu_drop(miniq);
4971 case TC_ACT_REDIRECT:
4972 /* skb_mac_header check was done by cls/act_bpf, so
4973 * we can safely push the L2 header back before
4974 * redirecting to another netdev
4976 __skb_push(skb, skb->mac_len);
4977 skb_do_redirect(skb);
4979 case TC_ACT_CONSUMED:
4984 #endif /* CONFIG_NET_CLS_ACT */
4989 * netdev_is_rx_handler_busy - check if receive handler is registered
4990 * @dev: device to check
4992 * Check if a receive handler is already registered for a given device.
4993 * Return true if there one.
4995 * The caller must hold the rtnl_mutex.
4997 bool netdev_is_rx_handler_busy(struct net_device *dev)
5000 return dev && rtnl_dereference(dev->rx_handler);
5002 EXPORT_SYMBOL_GPL(netdev_is_rx_handler_busy);
5005 * netdev_rx_handler_register - register receive handler
5006 * @dev: device to register a handler for
5007 * @rx_handler: receive handler to register
5008 * @rx_handler_data: data pointer that is used by rx handler
5010 * Register a receive handler for a device. This handler will then be
5011 * called from __netif_receive_skb. A negative errno code is returned
5014 * The caller must hold the rtnl_mutex.
5016 * For a general description of rx_handler, see enum rx_handler_result.
5018 int netdev_rx_handler_register(struct net_device *dev,
5019 rx_handler_func_t *rx_handler,
5020 void *rx_handler_data)
5022 if (netdev_is_rx_handler_busy(dev))
5025 if (dev->priv_flags & IFF_NO_RX_HANDLER)
5028 /* Note: rx_handler_data must be set before rx_handler */
5029 rcu_assign_pointer(dev->rx_handler_data, rx_handler_data);
5030 rcu_assign_pointer(dev->rx_handler, rx_handler);
5034 EXPORT_SYMBOL_GPL(netdev_rx_handler_register);
5037 * netdev_rx_handler_unregister - unregister receive handler
5038 * @dev: device to unregister a handler from
5040 * Unregister a receive handler from a device.
5042 * The caller must hold the rtnl_mutex.
5044 void netdev_rx_handler_unregister(struct net_device *dev)
5048 RCU_INIT_POINTER(dev->rx_handler, NULL);
5049 /* a reader seeing a non NULL rx_handler in a rcu_read_lock()
5050 * section has a guarantee to see a non NULL rx_handler_data
5054 RCU_INIT_POINTER(dev->rx_handler_data, NULL);
5056 EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister);
5059 * Limit the use of PFMEMALLOC reserves to those protocols that implement
5060 * the special handling of PFMEMALLOC skbs.
5062 static bool skb_pfmemalloc_protocol(struct sk_buff *skb)
5064 switch (skb->protocol) {
5065 case htons(ETH_P_ARP):
5066 case htons(ETH_P_IP):
5067 case htons(ETH_P_IPV6):
5068 case htons(ETH_P_8021Q):
5069 case htons(ETH_P_8021AD):
5076 static inline int nf_ingress(struct sk_buff *skb, struct packet_type **pt_prev,
5077 int *ret, struct net_device *orig_dev)
5079 if (nf_hook_ingress_active(skb)) {
5083 *ret = deliver_skb(skb, *pt_prev, orig_dev);
5088 ingress_retval = nf_hook_ingress(skb);
5090 return ingress_retval;
5095 static int __netif_receive_skb_core(struct sk_buff **pskb, bool pfmemalloc,
5096 struct packet_type **ppt_prev)
5098 struct packet_type *ptype, *pt_prev;
5099 rx_handler_func_t *rx_handler;
5100 struct sk_buff *skb = *pskb;
5101 struct net_device *orig_dev;
5102 bool deliver_exact = false;
5103 int ret = NET_RX_DROP;
5106 net_timestamp_check(!netdev_tstamp_prequeue, skb);
5108 trace_netif_receive_skb(skb);
5110 orig_dev = skb->dev;
5112 skb_reset_network_header(skb);
5113 if (!skb_transport_header_was_set(skb))
5114 skb_reset_transport_header(skb);
5115 skb_reset_mac_len(skb);
5120 skb->skb_iif = skb->dev->ifindex;
5122 __this_cpu_inc(softnet_data.processed);
5124 if (static_branch_unlikely(&generic_xdp_needed_key)) {
5128 ret2 = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog), skb);
5131 if (ret2 != XDP_PASS) {
5135 skb_reset_mac_len(skb);
5138 if (skb->protocol == cpu_to_be16(ETH_P_8021Q) ||
5139 skb->protocol == cpu_to_be16(ETH_P_8021AD)) {
5140 skb = skb_vlan_untag(skb);
5145 if (skb_skip_tc_classify(skb))
5151 list_for_each_entry_rcu(ptype, &ptype_all, list) {
5153 ret = deliver_skb(skb, pt_prev, orig_dev);
5157 list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) {
5159 ret = deliver_skb(skb, pt_prev, orig_dev);
5164 #ifdef CONFIG_NET_INGRESS
5165 if (static_branch_unlikely(&ingress_needed_key)) {
5166 skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev);
5170 if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0)
5174 skb_reset_redirect(skb);
5176 if (pfmemalloc && !skb_pfmemalloc_protocol(skb))
5179 if (skb_vlan_tag_present(skb)) {
5181 ret = deliver_skb(skb, pt_prev, orig_dev);
5184 if (vlan_do_receive(&skb))
5186 else if (unlikely(!skb))
5190 rx_handler = rcu_dereference(skb->dev->rx_handler);
5193 ret = deliver_skb(skb, pt_prev, orig_dev);
5196 switch (rx_handler(&skb)) {
5197 case RX_HANDLER_CONSUMED:
5198 ret = NET_RX_SUCCESS;
5200 case RX_HANDLER_ANOTHER:
5202 case RX_HANDLER_EXACT:
5203 deliver_exact = true;
5204 case RX_HANDLER_PASS:
5211 if (unlikely(skb_vlan_tag_present(skb)) && !netdev_uses_dsa(skb->dev)) {
5213 if (skb_vlan_tag_get_id(skb)) {
5214 /* Vlan id is non 0 and vlan_do_receive() above couldn't
5217 skb->pkt_type = PACKET_OTHERHOST;
5218 } else if (skb->protocol == cpu_to_be16(ETH_P_8021Q) ||
5219 skb->protocol == cpu_to_be16(ETH_P_8021AD)) {
5220 /* Outer header is 802.1P with vlan 0, inner header is
5221 * 802.1Q or 802.1AD and vlan_do_receive() above could
5222 * not find vlan dev for vlan id 0.
5224 __vlan_hwaccel_clear_tag(skb);
5225 skb = skb_vlan_untag(skb);
5228 if (vlan_do_receive(&skb))
5229 /* After stripping off 802.1P header with vlan 0
5230 * vlan dev is found for inner header.
5233 else if (unlikely(!skb))
5236 /* We have stripped outer 802.1P vlan 0 header.
5237 * But could not find vlan dev.
5238 * check again for vlan id to set OTHERHOST.
5242 /* Note: we might in the future use prio bits
5243 * and set skb->priority like in vlan_do_receive()
5244 * For the time being, just ignore Priority Code Point
5246 __vlan_hwaccel_clear_tag(skb);
5249 type = skb->protocol;
5251 /* deliver only exact match when indicated */
5252 if (likely(!deliver_exact)) {
5253 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5254 &ptype_base[ntohs(type) &
5258 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5259 &orig_dev->ptype_specific);
5261 if (unlikely(skb->dev != orig_dev)) {
5262 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5263 &skb->dev->ptype_specific);
5267 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
5269 *ppt_prev = pt_prev;
5273 atomic_long_inc(&skb->dev->rx_dropped);
5275 atomic_long_inc(&skb->dev->rx_nohandler);
5277 /* Jamal, now you will not able to escape explaining
5278 * me how you were going to use this. :-)
5284 /* The invariant here is that if *ppt_prev is not NULL
5285 * then skb should also be non-NULL.
5287 * Apparently *ppt_prev assignment above holds this invariant due to
5288 * skb dereferencing near it.
5294 static int __netif_receive_skb_one_core(struct sk_buff *skb, bool pfmemalloc)
5296 struct net_device *orig_dev = skb->dev;
5297 struct packet_type *pt_prev = NULL;
5300 ret = __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5302 ret = INDIRECT_CALL_INET(pt_prev->func, ipv6_rcv, ip_rcv, skb,
5303 skb->dev, pt_prev, orig_dev);
5308 * netif_receive_skb_core - special purpose version of netif_receive_skb
5309 * @skb: buffer to process
5311 * More direct receive version of netif_receive_skb(). It should
5312 * only be used by callers that have a need to skip RPS and Generic XDP.
5313 * Caller must also take care of handling if ``(page_is_)pfmemalloc``.
5315 * This function may only be called from softirq context and interrupts
5316 * should be enabled.
5318 * Return values (usually ignored):
5319 * NET_RX_SUCCESS: no congestion
5320 * NET_RX_DROP: packet was dropped
5322 int netif_receive_skb_core(struct sk_buff *skb)
5327 ret = __netif_receive_skb_one_core(skb, false);
5332 EXPORT_SYMBOL(netif_receive_skb_core);
5334 static inline void __netif_receive_skb_list_ptype(struct list_head *head,
5335 struct packet_type *pt_prev,
5336 struct net_device *orig_dev)
5338 struct sk_buff *skb, *next;
5342 if (list_empty(head))
5344 if (pt_prev->list_func != NULL)
5345 INDIRECT_CALL_INET(pt_prev->list_func, ipv6_list_rcv,
5346 ip_list_rcv, head, pt_prev, orig_dev);
5348 list_for_each_entry_safe(skb, next, head, list) {
5349 skb_list_del_init(skb);
5350 pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
5354 static void __netif_receive_skb_list_core(struct list_head *head, bool pfmemalloc)
5356 /* Fast-path assumptions:
5357 * - There is no RX handler.
5358 * - Only one packet_type matches.
5359 * If either of these fails, we will end up doing some per-packet
5360 * processing in-line, then handling the 'last ptype' for the whole
5361 * sublist. This can't cause out-of-order delivery to any single ptype,
5362 * because the 'last ptype' must be constant across the sublist, and all
5363 * other ptypes are handled per-packet.
5365 /* Current (common) ptype of sublist */
5366 struct packet_type *pt_curr = NULL;
5367 /* Current (common) orig_dev of sublist */
5368 struct net_device *od_curr = NULL;
5369 struct list_head sublist;
5370 struct sk_buff *skb, *next;
5372 INIT_LIST_HEAD(&sublist);
5373 list_for_each_entry_safe(skb, next, head, list) {
5374 struct net_device *orig_dev = skb->dev;
5375 struct packet_type *pt_prev = NULL;
5377 skb_list_del_init(skb);
5378 __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5381 if (pt_curr != pt_prev || od_curr != orig_dev) {
5382 /* dispatch old sublist */
5383 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5384 /* start new sublist */
5385 INIT_LIST_HEAD(&sublist);
5389 list_add_tail(&skb->list, &sublist);
5392 /* dispatch final sublist */
5393 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5396 static int __netif_receive_skb(struct sk_buff *skb)
5400 if (sk_memalloc_socks() && skb_pfmemalloc(skb)) {
5401 unsigned int noreclaim_flag;
5404 * PFMEMALLOC skbs are special, they should
5405 * - be delivered to SOCK_MEMALLOC sockets only
5406 * - stay away from userspace
5407 * - have bounded memory usage
5409 * Use PF_MEMALLOC as this saves us from propagating the allocation
5410 * context down to all allocation sites.
5412 noreclaim_flag = memalloc_noreclaim_save();
5413 ret = __netif_receive_skb_one_core(skb, true);
5414 memalloc_noreclaim_restore(noreclaim_flag);
5416 ret = __netif_receive_skb_one_core(skb, false);
5421 static void __netif_receive_skb_list(struct list_head *head)
5423 unsigned long noreclaim_flag = 0;
5424 struct sk_buff *skb, *next;
5425 bool pfmemalloc = false; /* Is current sublist PF_MEMALLOC? */
5427 list_for_each_entry_safe(skb, next, head, list) {
5428 if ((sk_memalloc_socks() && skb_pfmemalloc(skb)) != pfmemalloc) {
5429 struct list_head sublist;
5431 /* Handle the previous sublist */
5432 list_cut_before(&sublist, head, &skb->list);
5433 if (!list_empty(&sublist))
5434 __netif_receive_skb_list_core(&sublist, pfmemalloc);
5435 pfmemalloc = !pfmemalloc;
5436 /* See comments in __netif_receive_skb */
5438 noreclaim_flag = memalloc_noreclaim_save();
5440 memalloc_noreclaim_restore(noreclaim_flag);
5443 /* Handle the remaining sublist */
5444 if (!list_empty(head))
5445 __netif_receive_skb_list_core(head, pfmemalloc);
5446 /* Restore pflags */
5448 memalloc_noreclaim_restore(noreclaim_flag);
5451 static int generic_xdp_install(struct net_device *dev, struct netdev_bpf *xdp)
5453 struct bpf_prog *old = rtnl_dereference(dev->xdp_prog);
5454 struct bpf_prog *new = xdp->prog;
5460 mutex_lock(&new->aux->used_maps_mutex);
5462 /* generic XDP does not work with DEVMAPs that can
5463 * have a bpf_prog installed on an entry
5465 for (i = 0; i < new->aux->used_map_cnt; i++) {
5466 if (dev_map_can_have_prog(new->aux->used_maps[i]) ||
5467 cpu_map_prog_allowed(new->aux->used_maps[i])) {
5468 mutex_unlock(&new->aux->used_maps_mutex);
5473 mutex_unlock(&new->aux->used_maps_mutex);
5476 switch (xdp->command) {
5477 case XDP_SETUP_PROG:
5478 rcu_assign_pointer(dev->xdp_prog, new);
5483 static_branch_dec(&generic_xdp_needed_key);
5484 } else if (new && !old) {
5485 static_branch_inc(&generic_xdp_needed_key);
5486 dev_disable_lro(dev);
5487 dev_disable_gro_hw(dev);
5499 static int netif_receive_skb_internal(struct sk_buff *skb)
5503 net_timestamp_check(netdev_tstamp_prequeue, skb);
5505 if (skb_defer_rx_timestamp(skb))
5506 return NET_RX_SUCCESS;
5510 if (static_branch_unlikely(&rps_needed)) {
5511 struct rps_dev_flow voidflow, *rflow = &voidflow;
5512 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5515 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5521 ret = __netif_receive_skb(skb);
5526 static void netif_receive_skb_list_internal(struct list_head *head)
5528 struct sk_buff *skb, *next;
5529 struct list_head sublist;
5531 INIT_LIST_HEAD(&sublist);
5532 list_for_each_entry_safe(skb, next, head, list) {
5533 net_timestamp_check(netdev_tstamp_prequeue, skb);
5534 skb_list_del_init(skb);
5535 if (!skb_defer_rx_timestamp(skb))
5536 list_add_tail(&skb->list, &sublist);
5538 list_splice_init(&sublist, head);
5542 if (static_branch_unlikely(&rps_needed)) {
5543 list_for_each_entry_safe(skb, next, head, list) {
5544 struct rps_dev_flow voidflow, *rflow = &voidflow;
5545 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5548 /* Will be handled, remove from list */
5549 skb_list_del_init(skb);
5550 enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5555 __netif_receive_skb_list(head);
5560 * netif_receive_skb - process receive buffer from network
5561 * @skb: buffer to process
5563 * netif_receive_skb() is the main receive data processing function.
5564 * It always succeeds. The buffer may be dropped during processing
5565 * for congestion control or by the protocol layers.
5567 * This function may only be called from softirq context and interrupts
5568 * should be enabled.
5570 * Return values (usually ignored):
5571 * NET_RX_SUCCESS: no congestion
5572 * NET_RX_DROP: packet was dropped
5574 int netif_receive_skb(struct sk_buff *skb)
5578 trace_netif_receive_skb_entry(skb);
5580 ret = netif_receive_skb_internal(skb);
5581 trace_netif_receive_skb_exit(ret);
5585 EXPORT_SYMBOL(netif_receive_skb);
5588 * netif_receive_skb_list - process many receive buffers from network
5589 * @head: list of skbs to process.
5591 * Since return value of netif_receive_skb() is normally ignored, and
5592 * wouldn't be meaningful for a list, this function returns void.
5594 * This function may only be called from softirq context and interrupts
5595 * should be enabled.
5597 void netif_receive_skb_list(struct list_head *head)
5599 struct sk_buff *skb;
5601 if (list_empty(head))
5603 if (trace_netif_receive_skb_list_entry_enabled()) {
5604 list_for_each_entry(skb, head, list)
5605 trace_netif_receive_skb_list_entry(skb);
5607 netif_receive_skb_list_internal(head);
5608 trace_netif_receive_skb_list_exit(0);
5610 EXPORT_SYMBOL(netif_receive_skb_list);
5612 static DEFINE_PER_CPU(struct work_struct, flush_works);
5614 /* Network device is going away, flush any packets still pending */
5615 static void flush_backlog(struct work_struct *work)
5617 struct sk_buff *skb, *tmp;
5618 struct softnet_data *sd;
5621 sd = this_cpu_ptr(&softnet_data);
5623 local_irq_disable();
5625 skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) {
5626 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5627 __skb_unlink(skb, &sd->input_pkt_queue);
5628 dev_kfree_skb_irq(skb);
5629 input_queue_head_incr(sd);
5635 skb_queue_walk_safe(&sd->process_queue, skb, tmp) {
5636 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5637 __skb_unlink(skb, &sd->process_queue);
5639 input_queue_head_incr(sd);
5645 static bool flush_required(int cpu)
5647 #if IS_ENABLED(CONFIG_RPS)
5648 struct softnet_data *sd = &per_cpu(softnet_data, cpu);
5651 local_irq_disable();
5654 /* as insertion into process_queue happens with the rps lock held,
5655 * process_queue access may race only with dequeue
5657 do_flush = !skb_queue_empty(&sd->input_pkt_queue) ||
5658 !skb_queue_empty_lockless(&sd->process_queue);
5664 /* without RPS we can't safely check input_pkt_queue: during a
5665 * concurrent remote skb_queue_splice() we can detect as empty both
5666 * input_pkt_queue and process_queue even if the latter could end-up
5667 * containing a lot of packets.
5672 static void flush_all_backlogs(void)
5674 static cpumask_t flush_cpus;
5677 /* since we are under rtnl lock protection we can use static data
5678 * for the cpumask and avoid allocating on stack the possibly
5685 cpumask_clear(&flush_cpus);
5686 for_each_online_cpu(cpu) {
5687 if (flush_required(cpu)) {
5688 queue_work_on(cpu, system_highpri_wq,
5689 per_cpu_ptr(&flush_works, cpu));
5690 cpumask_set_cpu(cpu, &flush_cpus);
5694 /* we can have in flight packet[s] on the cpus we are not flushing,
5695 * synchronize_net() in rollback_registered_many() will take care of
5698 for_each_cpu(cpu, &flush_cpus)
5699 flush_work(per_cpu_ptr(&flush_works, cpu));
5704 /* Pass the currently batched GRO_NORMAL SKBs up to the stack. */
5705 static void gro_normal_list(struct napi_struct *napi)
5707 if (!napi->rx_count)
5709 netif_receive_skb_list_internal(&napi->rx_list);
5710 INIT_LIST_HEAD(&napi->rx_list);
5714 /* Queue one GRO_NORMAL SKB up for list processing. If batch size exceeded,
5715 * pass the whole batch up to the stack.
5717 static void gro_normal_one(struct napi_struct *napi, struct sk_buff *skb)
5719 list_add_tail(&skb->list, &napi->rx_list);
5720 if (++napi->rx_count >= gro_normal_batch)
5721 gro_normal_list(napi);
5724 INDIRECT_CALLABLE_DECLARE(int inet_gro_complete(struct sk_buff *, int));
5725 INDIRECT_CALLABLE_DECLARE(int ipv6_gro_complete(struct sk_buff *, int));
5726 static int napi_gro_complete(struct napi_struct *napi, struct sk_buff *skb)
5728 struct packet_offload *ptype;
5729 __be16 type = skb->protocol;
5730 struct list_head *head = &offload_base;
5733 BUILD_BUG_ON(sizeof(struct napi_gro_cb) > sizeof(skb->cb));
5735 if (NAPI_GRO_CB(skb)->count == 1) {
5736 skb_shinfo(skb)->gso_size = 0;
5741 list_for_each_entry_rcu(ptype, head, list) {
5742 if (ptype->type != type || !ptype->callbacks.gro_complete)
5745 err = INDIRECT_CALL_INET(ptype->callbacks.gro_complete,
5746 ipv6_gro_complete, inet_gro_complete,
5753 WARN_ON(&ptype->list == head);
5755 return NET_RX_SUCCESS;
5759 gro_normal_one(napi, skb);
5760 return NET_RX_SUCCESS;
5763 static void __napi_gro_flush_chain(struct napi_struct *napi, u32 index,
5766 struct list_head *head = &napi->gro_hash[index].list;
5767 struct sk_buff *skb, *p;
5769 list_for_each_entry_safe_reverse(skb, p, head, list) {
5770 if (flush_old && NAPI_GRO_CB(skb)->age == jiffies)
5772 skb_list_del_init(skb);
5773 napi_gro_complete(napi, skb);
5774 napi->gro_hash[index].count--;
5777 if (!napi->gro_hash[index].count)
5778 __clear_bit(index, &napi->gro_bitmask);
5781 /* napi->gro_hash[].list contains packets ordered by age.
5782 * youngest packets at the head of it.
5783 * Complete skbs in reverse order to reduce latencies.
5785 void napi_gro_flush(struct napi_struct *napi, bool flush_old)
5787 unsigned long bitmask = napi->gro_bitmask;
5788 unsigned int i, base = ~0U;
5790 while ((i = ffs(bitmask)) != 0) {
5793 __napi_gro_flush_chain(napi, base, flush_old);
5796 EXPORT_SYMBOL(napi_gro_flush);
5798 static struct list_head *gro_list_prepare(struct napi_struct *napi,
5799 struct sk_buff *skb)
5801 unsigned int maclen = skb->dev->hard_header_len;
5802 u32 hash = skb_get_hash_raw(skb);
5803 struct list_head *head;
5806 head = &napi->gro_hash[hash & (GRO_HASH_BUCKETS - 1)].list;
5807 list_for_each_entry(p, head, list) {
5808 unsigned long diffs;
5810 NAPI_GRO_CB(p)->flush = 0;
5812 if (hash != skb_get_hash_raw(p)) {
5813 NAPI_GRO_CB(p)->same_flow = 0;
5817 diffs = (unsigned long)p->dev ^ (unsigned long)skb->dev;
5818 diffs |= skb_vlan_tag_present(p) ^ skb_vlan_tag_present(skb);
5819 if (skb_vlan_tag_present(p))
5820 diffs |= skb_vlan_tag_get(p) ^ skb_vlan_tag_get(skb);
5821 diffs |= skb_metadata_dst_cmp(p, skb);
5822 diffs |= skb_metadata_differs(p, skb);
5823 if (maclen == ETH_HLEN)
5824 diffs |= compare_ether_header(skb_mac_header(p),
5825 skb_mac_header(skb));
5827 diffs = memcmp(skb_mac_header(p),
5828 skb_mac_header(skb),
5830 NAPI_GRO_CB(p)->same_flow = !diffs;
5836 static void skb_gro_reset_offset(struct sk_buff *skb)
5838 const struct skb_shared_info *pinfo = skb_shinfo(skb);
5839 const skb_frag_t *frag0 = &pinfo->frags[0];
5841 NAPI_GRO_CB(skb)->data_offset = 0;
5842 NAPI_GRO_CB(skb)->frag0 = NULL;
5843 NAPI_GRO_CB(skb)->frag0_len = 0;
5845 if (!skb_headlen(skb) && pinfo->nr_frags &&
5846 !PageHighMem(skb_frag_page(frag0))) {
5847 NAPI_GRO_CB(skb)->frag0 = skb_frag_address(frag0);
5848 NAPI_GRO_CB(skb)->frag0_len = min_t(unsigned int,
5849 skb_frag_size(frag0),
5850 skb->end - skb->tail);
5854 static void gro_pull_from_frag0(struct sk_buff *skb, int grow)
5856 struct skb_shared_info *pinfo = skb_shinfo(skb);
5858 BUG_ON(skb->end - skb->tail < grow);
5860 memcpy(skb_tail_pointer(skb), NAPI_GRO_CB(skb)->frag0, grow);
5862 skb->data_len -= grow;
5865 skb_frag_off_add(&pinfo->frags[0], grow);
5866 skb_frag_size_sub(&pinfo->frags[0], grow);
5868 if (unlikely(!skb_frag_size(&pinfo->frags[0]))) {
5869 skb_frag_unref(skb, 0);
5870 memmove(pinfo->frags, pinfo->frags + 1,
5871 --pinfo->nr_frags * sizeof(pinfo->frags[0]));
5875 static void gro_flush_oldest(struct napi_struct *napi, struct list_head *head)
5877 struct sk_buff *oldest;
5879 oldest = list_last_entry(head, struct sk_buff, list);
5881 /* We are called with head length >= MAX_GRO_SKBS, so this is
5884 if (WARN_ON_ONCE(!oldest))
5887 /* Do not adjust napi->gro_hash[].count, caller is adding a new
5890 skb_list_del_init(oldest);
5891 napi_gro_complete(napi, oldest);
5894 INDIRECT_CALLABLE_DECLARE(struct sk_buff *inet_gro_receive(struct list_head *,
5896 INDIRECT_CALLABLE_DECLARE(struct sk_buff *ipv6_gro_receive(struct list_head *,
5898 static enum gro_result dev_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
5900 u32 hash = skb_get_hash_raw(skb) & (GRO_HASH_BUCKETS - 1);
5901 struct list_head *head = &offload_base;
5902 struct packet_offload *ptype;
5903 __be16 type = skb->protocol;
5904 struct list_head *gro_head;
5905 struct sk_buff *pp = NULL;
5906 enum gro_result ret;
5910 if (netif_elide_gro(skb->dev))
5913 gro_head = gro_list_prepare(napi, skb);
5916 list_for_each_entry_rcu(ptype, head, list) {
5917 if (ptype->type != type || !ptype->callbacks.gro_receive)
5920 skb_set_network_header(skb, skb_gro_offset(skb));
5921 skb_reset_mac_len(skb);
5922 NAPI_GRO_CB(skb)->same_flow = 0;
5923 NAPI_GRO_CB(skb)->flush = skb_is_gso(skb) || skb_has_frag_list(skb);
5924 NAPI_GRO_CB(skb)->free = 0;
5925 NAPI_GRO_CB(skb)->encap_mark = 0;
5926 NAPI_GRO_CB(skb)->recursion_counter = 0;
5927 NAPI_GRO_CB(skb)->is_fou = 0;
5928 NAPI_GRO_CB(skb)->is_atomic = 1;
5929 NAPI_GRO_CB(skb)->gro_remcsum_start = 0;
5931 /* Setup for GRO checksum validation */
5932 switch (skb->ip_summed) {
5933 case CHECKSUM_COMPLETE:
5934 NAPI_GRO_CB(skb)->csum = skb->csum;
5935 NAPI_GRO_CB(skb)->csum_valid = 1;
5936 NAPI_GRO_CB(skb)->csum_cnt = 0;
5938 case CHECKSUM_UNNECESSARY:
5939 NAPI_GRO_CB(skb)->csum_cnt = skb->csum_level + 1;
5940 NAPI_GRO_CB(skb)->csum_valid = 0;
5943 NAPI_GRO_CB(skb)->csum_cnt = 0;
5944 NAPI_GRO_CB(skb)->csum_valid = 0;
5947 pp = INDIRECT_CALL_INET(ptype->callbacks.gro_receive,
5948 ipv6_gro_receive, inet_gro_receive,
5954 if (&ptype->list == head)
5957 if (PTR_ERR(pp) == -EINPROGRESS) {
5962 same_flow = NAPI_GRO_CB(skb)->same_flow;
5963 ret = NAPI_GRO_CB(skb)->free ? GRO_MERGED_FREE : GRO_MERGED;
5966 skb_list_del_init(pp);
5967 napi_gro_complete(napi, pp);
5968 napi->gro_hash[hash].count--;
5974 if (NAPI_GRO_CB(skb)->flush)
5977 if (unlikely(napi->gro_hash[hash].count >= MAX_GRO_SKBS)) {
5978 gro_flush_oldest(napi, gro_head);
5980 napi->gro_hash[hash].count++;
5982 NAPI_GRO_CB(skb)->count = 1;
5983 NAPI_GRO_CB(skb)->age = jiffies;
5984 NAPI_GRO_CB(skb)->last = skb;
5985 skb_shinfo(skb)->gso_size = skb_gro_len(skb);
5986 list_add(&skb->list, gro_head);
5990 grow = skb_gro_offset(skb) - skb_headlen(skb);
5992 gro_pull_from_frag0(skb, grow);
5994 if (napi->gro_hash[hash].count) {
5995 if (!test_bit(hash, &napi->gro_bitmask))
5996 __set_bit(hash, &napi->gro_bitmask);
5997 } else if (test_bit(hash, &napi->gro_bitmask)) {
5998 __clear_bit(hash, &napi->gro_bitmask);
6008 struct packet_offload *gro_find_receive_by_type(__be16 type)
6010 struct list_head *offload_head = &offload_base;
6011 struct packet_offload *ptype;
6013 list_for_each_entry_rcu(ptype, offload_head, list) {
6014 if (ptype->type != type || !ptype->callbacks.gro_receive)
6020 EXPORT_SYMBOL(gro_find_receive_by_type);
6022 struct packet_offload *gro_find_complete_by_type(__be16 type)
6024 struct list_head *offload_head = &offload_base;
6025 struct packet_offload *ptype;
6027 list_for_each_entry_rcu(ptype, offload_head, list) {
6028 if (ptype->type != type || !ptype->callbacks.gro_complete)
6034 EXPORT_SYMBOL(gro_find_complete_by_type);
6036 static void napi_skb_free_stolen_head(struct sk_buff *skb)
6040 kmem_cache_free(skbuff_head_cache, skb);
6043 static gro_result_t napi_skb_finish(struct napi_struct *napi,
6044 struct sk_buff *skb,
6049 gro_normal_one(napi, skb);
6056 case GRO_MERGED_FREE:
6057 if (NAPI_GRO_CB(skb)->free == NAPI_GRO_FREE_STOLEN_HEAD)
6058 napi_skb_free_stolen_head(skb);
6072 gro_result_t napi_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
6076 skb_mark_napi_id(skb, napi);
6077 trace_napi_gro_receive_entry(skb);
6079 skb_gro_reset_offset(skb);
6081 ret = napi_skb_finish(napi, skb, dev_gro_receive(napi, skb));
6082 trace_napi_gro_receive_exit(ret);
6086 EXPORT_SYMBOL(napi_gro_receive);
6088 static void napi_reuse_skb(struct napi_struct *napi, struct sk_buff *skb)
6090 if (unlikely(skb->pfmemalloc)) {
6094 __skb_pull(skb, skb_headlen(skb));
6095 /* restore the reserve we had after netdev_alloc_skb_ip_align() */
6096 skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN - skb_headroom(skb));
6097 __vlan_hwaccel_clear_tag(skb);
6098 skb->dev = napi->dev;
6101 /* eth_type_trans() assumes pkt_type is PACKET_HOST */
6102 skb->pkt_type = PACKET_HOST;
6104 skb->encapsulation = 0;
6105 skb_shinfo(skb)->gso_type = 0;
6106 skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
6112 struct sk_buff *napi_get_frags(struct napi_struct *napi)
6114 struct sk_buff *skb = napi->skb;
6117 skb = napi_alloc_skb(napi, GRO_MAX_HEAD);
6120 skb_mark_napi_id(skb, napi);
6125 EXPORT_SYMBOL(napi_get_frags);
6127 static gro_result_t napi_frags_finish(struct napi_struct *napi,
6128 struct sk_buff *skb,
6134 __skb_push(skb, ETH_HLEN);
6135 skb->protocol = eth_type_trans(skb, skb->dev);
6136 if (ret == GRO_NORMAL)
6137 gro_normal_one(napi, skb);
6141 napi_reuse_skb(napi, skb);
6144 case GRO_MERGED_FREE:
6145 if (NAPI_GRO_CB(skb)->free == NAPI_GRO_FREE_STOLEN_HEAD)
6146 napi_skb_free_stolen_head(skb);
6148 napi_reuse_skb(napi, skb);
6159 /* Upper GRO stack assumes network header starts at gro_offset=0
6160 * Drivers could call both napi_gro_frags() and napi_gro_receive()
6161 * We copy ethernet header into skb->data to have a common layout.
6163 static struct sk_buff *napi_frags_skb(struct napi_struct *napi)
6165 struct sk_buff *skb = napi->skb;
6166 const struct ethhdr *eth;
6167 unsigned int hlen = sizeof(*eth);
6171 skb_reset_mac_header(skb);
6172 skb_gro_reset_offset(skb);
6174 if (unlikely(skb_gro_header_hard(skb, hlen))) {
6175 eth = skb_gro_header_slow(skb, hlen, 0);
6176 if (unlikely(!eth)) {
6177 net_warn_ratelimited("%s: dropping impossible skb from %s\n",
6178 __func__, napi->dev->name);
6179 napi_reuse_skb(napi, skb);
6183 eth = (const struct ethhdr *)skb->data;
6184 gro_pull_from_frag0(skb, hlen);
6185 NAPI_GRO_CB(skb)->frag0 += hlen;
6186 NAPI_GRO_CB(skb)->frag0_len -= hlen;
6188 __skb_pull(skb, hlen);
6191 * This works because the only protocols we care about don't require
6193 * We'll fix it up properly in napi_frags_finish()
6195 skb->protocol = eth->h_proto;
6200 gro_result_t napi_gro_frags(struct napi_struct *napi)
6203 struct sk_buff *skb = napi_frags_skb(napi);
6208 trace_napi_gro_frags_entry(skb);
6210 ret = napi_frags_finish(napi, skb, dev_gro_receive(napi, skb));
6211 trace_napi_gro_frags_exit(ret);
6215 EXPORT_SYMBOL(napi_gro_frags);
6217 /* Compute the checksum from gro_offset and return the folded value
6218 * after adding in any pseudo checksum.
6220 __sum16 __skb_gro_checksum_complete(struct sk_buff *skb)
6225 wsum = skb_checksum(skb, skb_gro_offset(skb), skb_gro_len(skb), 0);
6227 /* NAPI_GRO_CB(skb)->csum holds pseudo checksum */
6228 sum = csum_fold(csum_add(NAPI_GRO_CB(skb)->csum, wsum));
6229 /* See comments in __skb_checksum_complete(). */
6231 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
6232 !skb->csum_complete_sw)
6233 netdev_rx_csum_fault(skb->dev, skb);
6236 NAPI_GRO_CB(skb)->csum = wsum;
6237 NAPI_GRO_CB(skb)->csum_valid = 1;
6241 EXPORT_SYMBOL(__skb_gro_checksum_complete);
6243 static void net_rps_send_ipi(struct softnet_data *remsd)
6247 struct softnet_data *next = remsd->rps_ipi_next;
6249 if (cpu_online(remsd->cpu))
6250 smp_call_function_single_async(remsd->cpu, &remsd->csd);
6257 * net_rps_action_and_irq_enable sends any pending IPI's for rps.
6258 * Note: called with local irq disabled, but exits with local irq enabled.
6260 static void net_rps_action_and_irq_enable(struct softnet_data *sd)
6263 struct softnet_data *remsd = sd->rps_ipi_list;
6266 sd->rps_ipi_list = NULL;
6270 /* Send pending IPI's to kick RPS processing on remote cpus. */
6271 net_rps_send_ipi(remsd);
6277 static bool sd_has_rps_ipi_waiting(struct softnet_data *sd)
6280 return sd->rps_ipi_list != NULL;
6286 static int process_backlog(struct napi_struct *napi, int quota)
6288 struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
6292 /* Check if we have pending ipi, its better to send them now,
6293 * not waiting net_rx_action() end.
6295 if (sd_has_rps_ipi_waiting(sd)) {
6296 local_irq_disable();
6297 net_rps_action_and_irq_enable(sd);
6300 napi->weight = dev_rx_weight;
6302 struct sk_buff *skb;
6304 while ((skb = __skb_dequeue(&sd->process_queue))) {
6306 __netif_receive_skb(skb);
6308 input_queue_head_incr(sd);
6309 if (++work >= quota)
6314 local_irq_disable();
6316 if (skb_queue_empty(&sd->input_pkt_queue)) {
6318 * Inline a custom version of __napi_complete().
6319 * only current cpu owns and manipulates this napi,
6320 * and NAPI_STATE_SCHED is the only possible flag set
6322 * We can use a plain write instead of clear_bit(),
6323 * and we dont need an smp_mb() memory barrier.
6328 skb_queue_splice_tail_init(&sd->input_pkt_queue,
6329 &sd->process_queue);
6339 * __napi_schedule - schedule for receive
6340 * @n: entry to schedule
6342 * The entry's receive function will be scheduled to run.
6343 * Consider using __napi_schedule_irqoff() if hard irqs are masked.
6345 void __napi_schedule(struct napi_struct *n)
6347 unsigned long flags;
6349 local_irq_save(flags);
6350 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
6351 local_irq_restore(flags);
6353 EXPORT_SYMBOL(__napi_schedule);
6356 * napi_schedule_prep - check if napi can be scheduled
6359 * Test if NAPI routine is already running, and if not mark
6360 * it as running. This is used as a condition variable to
6361 * insure only one NAPI poll instance runs. We also make
6362 * sure there is no pending NAPI disable.
6364 bool napi_schedule_prep(struct napi_struct *n)
6366 unsigned long val, new;
6369 val = READ_ONCE(n->state);
6370 if (unlikely(val & NAPIF_STATE_DISABLE))
6372 new = val | NAPIF_STATE_SCHED;
6374 /* Sets STATE_MISSED bit if STATE_SCHED was already set
6375 * This was suggested by Alexander Duyck, as compiler
6376 * emits better code than :
6377 * if (val & NAPIF_STATE_SCHED)
6378 * new |= NAPIF_STATE_MISSED;
6380 new |= (val & NAPIF_STATE_SCHED) / NAPIF_STATE_SCHED *
6382 } while (cmpxchg(&n->state, val, new) != val);
6384 return !(val & NAPIF_STATE_SCHED);
6386 EXPORT_SYMBOL(napi_schedule_prep);
6389 * __napi_schedule_irqoff - schedule for receive
6390 * @n: entry to schedule
6392 * Variant of __napi_schedule() assuming hard irqs are masked
6394 void __napi_schedule_irqoff(struct napi_struct *n)
6396 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
6398 EXPORT_SYMBOL(__napi_schedule_irqoff);
6400 bool napi_complete_done(struct napi_struct *n, int work_done)
6402 unsigned long flags, val, new, timeout = 0;
6406 * 1) Don't let napi dequeue from the cpu poll list
6407 * just in case its running on a different cpu.
6408 * 2) If we are busy polling, do nothing here, we have
6409 * the guarantee we will be called later.
6411 if (unlikely(n->state & (NAPIF_STATE_NPSVC |
6412 NAPIF_STATE_IN_BUSY_POLL)))
6417 timeout = READ_ONCE(n->dev->gro_flush_timeout);
6418 n->defer_hard_irqs_count = READ_ONCE(n->dev->napi_defer_hard_irqs);
6420 if (n->defer_hard_irqs_count > 0) {
6421 n->defer_hard_irqs_count--;
6422 timeout = READ_ONCE(n->dev->gro_flush_timeout);
6426 if (n->gro_bitmask) {
6427 /* When the NAPI instance uses a timeout and keeps postponing
6428 * it, we need to bound somehow the time packets are kept in
6431 napi_gro_flush(n, !!timeout);
6436 if (unlikely(!list_empty(&n->poll_list))) {
6437 /* If n->poll_list is not empty, we need to mask irqs */
6438 local_irq_save(flags);
6439 list_del_init(&n->poll_list);
6440 local_irq_restore(flags);
6444 val = READ_ONCE(n->state);
6446 WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED));
6448 new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED);
6450 /* If STATE_MISSED was set, leave STATE_SCHED set,
6451 * because we will call napi->poll() one more time.
6452 * This C code was suggested by Alexander Duyck to help gcc.
6454 new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED *
6456 } while (cmpxchg(&n->state, val, new) != val);
6458 if (unlikely(val & NAPIF_STATE_MISSED)) {
6464 hrtimer_start(&n->timer, ns_to_ktime(timeout),
6465 HRTIMER_MODE_REL_PINNED);
6468 EXPORT_SYMBOL(napi_complete_done);
6470 /* must be called under rcu_read_lock(), as we dont take a reference */
6471 static struct napi_struct *napi_by_id(unsigned int napi_id)
6473 unsigned int hash = napi_id % HASH_SIZE(napi_hash);
6474 struct napi_struct *napi;
6476 hlist_for_each_entry_rcu(napi, &napi_hash[hash], napi_hash_node)
6477 if (napi->napi_id == napi_id)
6483 #if defined(CONFIG_NET_RX_BUSY_POLL)
6485 #define BUSY_POLL_BUDGET 8
6487 static void busy_poll_stop(struct napi_struct *napi, void *have_poll_lock)
6491 /* Busy polling means there is a high chance device driver hard irq
6492 * could not grab NAPI_STATE_SCHED, and that NAPI_STATE_MISSED was
6493 * set in napi_schedule_prep().
6494 * Since we are about to call napi->poll() once more, we can safely
6495 * clear NAPI_STATE_MISSED.
6497 * Note: x86 could use a single "lock and ..." instruction
6498 * to perform these two clear_bit()
6500 clear_bit(NAPI_STATE_MISSED, &napi->state);
6501 clear_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state);
6505 /* All we really want here is to re-enable device interrupts.
6506 * Ideally, a new ndo_busy_poll_stop() could avoid another round.
6508 rc = napi->poll(napi, BUSY_POLL_BUDGET);
6509 /* We can't gro_normal_list() here, because napi->poll() might have
6510 * rearmed the napi (napi_complete_done()) in which case it could
6511 * already be running on another CPU.
6513 trace_napi_poll(napi, rc, BUSY_POLL_BUDGET);
6514 netpoll_poll_unlock(have_poll_lock);
6515 if (rc == BUSY_POLL_BUDGET) {
6516 /* As the whole budget was spent, we still own the napi so can
6517 * safely handle the rx_list.
6519 gro_normal_list(napi);
6520 __napi_schedule(napi);
6525 void napi_busy_loop(unsigned int napi_id,
6526 bool (*loop_end)(void *, unsigned long),
6529 unsigned long start_time = loop_end ? busy_loop_current_time() : 0;
6530 int (*napi_poll)(struct napi_struct *napi, int budget);
6531 void *have_poll_lock = NULL;
6532 struct napi_struct *napi;
6539 napi = napi_by_id(napi_id);
6549 unsigned long val = READ_ONCE(napi->state);
6551 /* If multiple threads are competing for this napi,
6552 * we avoid dirtying napi->state as much as we can.
6554 if (val & (NAPIF_STATE_DISABLE | NAPIF_STATE_SCHED |
6555 NAPIF_STATE_IN_BUSY_POLL))
6557 if (cmpxchg(&napi->state, val,
6558 val | NAPIF_STATE_IN_BUSY_POLL |
6559 NAPIF_STATE_SCHED) != val)
6561 have_poll_lock = netpoll_poll_lock(napi);
6562 napi_poll = napi->poll;
6564 work = napi_poll(napi, BUSY_POLL_BUDGET);
6565 trace_napi_poll(napi, work, BUSY_POLL_BUDGET);
6566 gro_normal_list(napi);
6569 __NET_ADD_STATS(dev_net(napi->dev),
6570 LINUX_MIB_BUSYPOLLRXPACKETS, work);
6573 if (!loop_end || loop_end(loop_end_arg, start_time))
6576 if (unlikely(need_resched())) {
6578 busy_poll_stop(napi, have_poll_lock);
6582 if (loop_end(loop_end_arg, start_time))
6589 busy_poll_stop(napi, have_poll_lock);
6594 EXPORT_SYMBOL(napi_busy_loop);
6596 #endif /* CONFIG_NET_RX_BUSY_POLL */
6598 static void napi_hash_add(struct napi_struct *napi)
6600 if (test_bit(NAPI_STATE_NO_BUSY_POLL, &napi->state))
6603 spin_lock(&napi_hash_lock);
6605 /* 0..NR_CPUS range is reserved for sender_cpu use */
6607 if (unlikely(++napi_gen_id < MIN_NAPI_ID))
6608 napi_gen_id = MIN_NAPI_ID;
6609 } while (napi_by_id(napi_gen_id));
6610 napi->napi_id = napi_gen_id;
6612 hlist_add_head_rcu(&napi->napi_hash_node,
6613 &napi_hash[napi->napi_id % HASH_SIZE(napi_hash)]);
6615 spin_unlock(&napi_hash_lock);
6618 /* Warning : caller is responsible to make sure rcu grace period
6619 * is respected before freeing memory containing @napi
6621 static void napi_hash_del(struct napi_struct *napi)
6623 spin_lock(&napi_hash_lock);
6625 hlist_del_init_rcu(&napi->napi_hash_node);
6627 spin_unlock(&napi_hash_lock);
6630 static enum hrtimer_restart napi_watchdog(struct hrtimer *timer)
6632 struct napi_struct *napi;
6634 napi = container_of(timer, struct napi_struct, timer);
6636 /* Note : we use a relaxed variant of napi_schedule_prep() not setting
6637 * NAPI_STATE_MISSED, since we do not react to a device IRQ.
6639 if (!napi_disable_pending(napi) &&
6640 !test_and_set_bit(NAPI_STATE_SCHED, &napi->state))
6641 __napi_schedule_irqoff(napi);
6643 return HRTIMER_NORESTART;
6646 static void init_gro_hash(struct napi_struct *napi)
6650 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6651 INIT_LIST_HEAD(&napi->gro_hash[i].list);
6652 napi->gro_hash[i].count = 0;
6654 napi->gro_bitmask = 0;
6657 void netif_napi_add(struct net_device *dev, struct napi_struct *napi,
6658 int (*poll)(struct napi_struct *, int), int weight)
6660 if (WARN_ON(test_and_set_bit(NAPI_STATE_LISTED, &napi->state)))
6663 INIT_LIST_HEAD(&napi->poll_list);
6664 INIT_HLIST_NODE(&napi->napi_hash_node);
6665 hrtimer_init(&napi->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
6666 napi->timer.function = napi_watchdog;
6667 init_gro_hash(napi);
6669 INIT_LIST_HEAD(&napi->rx_list);
6672 if (weight > NAPI_POLL_WEIGHT)
6673 netdev_err_once(dev, "%s() called with weight %d\n", __func__,
6675 napi->weight = weight;
6677 #ifdef CONFIG_NETPOLL
6678 napi->poll_owner = -1;
6680 set_bit(NAPI_STATE_SCHED, &napi->state);
6681 set_bit(NAPI_STATE_NPSVC, &napi->state);
6682 list_add_rcu(&napi->dev_list, &dev->napi_list);
6683 napi_hash_add(napi);
6685 EXPORT_SYMBOL(netif_napi_add);
6687 void napi_disable(struct napi_struct *n)
6690 set_bit(NAPI_STATE_DISABLE, &n->state);
6692 while (test_and_set_bit(NAPI_STATE_SCHED, &n->state))
6694 while (test_and_set_bit(NAPI_STATE_NPSVC, &n->state))
6697 hrtimer_cancel(&n->timer);
6699 clear_bit(NAPI_STATE_DISABLE, &n->state);
6701 EXPORT_SYMBOL(napi_disable);
6703 static void flush_gro_hash(struct napi_struct *napi)
6707 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6708 struct sk_buff *skb, *n;
6710 list_for_each_entry_safe(skb, n, &napi->gro_hash[i].list, list)
6712 napi->gro_hash[i].count = 0;
6716 /* Must be called in process context */
6717 void __netif_napi_del(struct napi_struct *napi)
6719 if (!test_and_clear_bit(NAPI_STATE_LISTED, &napi->state))
6722 napi_hash_del(napi);
6723 list_del_rcu(&napi->dev_list);
6724 napi_free_frags(napi);
6726 flush_gro_hash(napi);
6727 napi->gro_bitmask = 0;
6729 EXPORT_SYMBOL(__netif_napi_del);
6731 static int napi_poll(struct napi_struct *n, struct list_head *repoll)
6736 list_del_init(&n->poll_list);
6738 have = netpoll_poll_lock(n);
6742 /* This NAPI_STATE_SCHED test is for avoiding a race
6743 * with netpoll's poll_napi(). Only the entity which
6744 * obtains the lock and sees NAPI_STATE_SCHED set will
6745 * actually make the ->poll() call. Therefore we avoid
6746 * accidentally calling ->poll() when NAPI is not scheduled.
6749 if (test_bit(NAPI_STATE_SCHED, &n->state)) {
6750 work = n->poll(n, weight);
6751 trace_napi_poll(n, work, weight);
6754 if (unlikely(work > weight))
6755 pr_err_once("NAPI poll function %pS returned %d, exceeding its budget of %d.\n",
6756 n->poll, work, weight);
6758 if (likely(work < weight))
6761 /* Drivers must not modify the NAPI state if they
6762 * consume the entire weight. In such cases this code
6763 * still "owns" the NAPI instance and therefore can
6764 * move the instance around on the list at-will.
6766 if (unlikely(napi_disable_pending(n))) {
6771 if (n->gro_bitmask) {
6772 /* flush too old packets
6773 * If HZ < 1000, flush all packets.
6775 napi_gro_flush(n, HZ >= 1000);
6780 /* Some drivers may have called napi_schedule
6781 * prior to exhausting their budget.
6783 if (unlikely(!list_empty(&n->poll_list))) {
6784 pr_warn_once("%s: Budget exhausted after napi rescheduled\n",
6785 n->dev ? n->dev->name : "backlog");
6789 list_add_tail(&n->poll_list, repoll);
6792 netpoll_poll_unlock(have);
6797 static __latent_entropy void net_rx_action(struct softirq_action *h)
6799 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
6800 unsigned long time_limit = jiffies +
6801 usecs_to_jiffies(netdev_budget_usecs);
6802 int budget = netdev_budget;
6806 local_irq_disable();
6807 list_splice_init(&sd->poll_list, &list);
6811 struct napi_struct *n;
6813 if (list_empty(&list)) {
6814 if (!sd_has_rps_ipi_waiting(sd) && list_empty(&repoll))
6819 n = list_first_entry(&list, struct napi_struct, poll_list);
6820 budget -= napi_poll(n, &repoll);
6822 /* If softirq window is exhausted then punt.
6823 * Allow this to run for 2 jiffies since which will allow
6824 * an average latency of 1.5/HZ.
6826 if (unlikely(budget <= 0 ||
6827 time_after_eq(jiffies, time_limit))) {
6833 local_irq_disable();
6835 list_splice_tail_init(&sd->poll_list, &list);
6836 list_splice_tail(&repoll, &list);
6837 list_splice(&list, &sd->poll_list);
6838 if (!list_empty(&sd->poll_list))
6839 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
6841 net_rps_action_and_irq_enable(sd);
6843 __kfree_skb_flush();
6846 struct netdev_adjacent {
6847 struct net_device *dev;
6849 /* upper master flag, there can only be one master device per list */
6852 /* lookup ignore flag */
6855 /* counter for the number of times this device was added to us */
6858 /* private field for the users */
6861 struct list_head list;
6862 struct rcu_head rcu;
6865 static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev,
6866 struct list_head *adj_list)
6868 struct netdev_adjacent *adj;
6870 list_for_each_entry(adj, adj_list, list) {
6871 if (adj->dev == adj_dev)
6877 static int ____netdev_has_upper_dev(struct net_device *upper_dev,
6878 struct netdev_nested_priv *priv)
6880 struct net_device *dev = (struct net_device *)priv->data;
6882 return upper_dev == dev;
6886 * netdev_has_upper_dev - Check if device is linked to an upper device
6888 * @upper_dev: upper device to check
6890 * Find out if a device is linked to specified upper device and return true
6891 * in case it is. Note that this checks only immediate upper device,
6892 * not through a complete stack of devices. The caller must hold the RTNL lock.
6894 bool netdev_has_upper_dev(struct net_device *dev,
6895 struct net_device *upper_dev)
6897 struct netdev_nested_priv priv = {
6898 .data = (void *)upper_dev,
6903 return netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
6906 EXPORT_SYMBOL(netdev_has_upper_dev);
6909 * netdev_has_upper_dev_all - Check if device is linked to an upper device
6911 * @upper_dev: upper device to check
6913 * Find out if a device is linked to specified upper device and return true
6914 * in case it is. Note that this checks the entire upper device chain.
6915 * The caller must hold rcu lock.
6918 bool netdev_has_upper_dev_all_rcu(struct net_device *dev,
6919 struct net_device *upper_dev)
6921 struct netdev_nested_priv priv = {
6922 .data = (void *)upper_dev,
6925 return !!netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
6928 EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu);
6931 * netdev_has_any_upper_dev - Check if device is linked to some device
6934 * Find out if a device is linked to an upper device and return true in case
6935 * it is. The caller must hold the RTNL lock.
6937 bool netdev_has_any_upper_dev(struct net_device *dev)
6941 return !list_empty(&dev->adj_list.upper);
6943 EXPORT_SYMBOL(netdev_has_any_upper_dev);
6946 * netdev_master_upper_dev_get - Get master upper device
6949 * Find a master upper device and return pointer to it or NULL in case
6950 * it's not there. The caller must hold the RTNL lock.
6952 struct net_device *netdev_master_upper_dev_get(struct net_device *dev)
6954 struct netdev_adjacent *upper;
6958 if (list_empty(&dev->adj_list.upper))
6961 upper = list_first_entry(&dev->adj_list.upper,
6962 struct netdev_adjacent, list);
6963 if (likely(upper->master))
6967 EXPORT_SYMBOL(netdev_master_upper_dev_get);
6969 static struct net_device *__netdev_master_upper_dev_get(struct net_device *dev)
6971 struct netdev_adjacent *upper;
6975 if (list_empty(&dev->adj_list.upper))
6978 upper = list_first_entry(&dev->adj_list.upper,
6979 struct netdev_adjacent, list);
6980 if (likely(upper->master) && !upper->ignore)
6986 * netdev_has_any_lower_dev - Check if device is linked to some device
6989 * Find out if a device is linked to a lower device and return true in case
6990 * it is. The caller must hold the RTNL lock.
6992 static bool netdev_has_any_lower_dev(struct net_device *dev)
6996 return !list_empty(&dev->adj_list.lower);
6999 void *netdev_adjacent_get_private(struct list_head *adj_list)
7001 struct netdev_adjacent *adj;
7003 adj = list_entry(adj_list, struct netdev_adjacent, list);
7005 return adj->private;
7007 EXPORT_SYMBOL(netdev_adjacent_get_private);
7010 * netdev_upper_get_next_dev_rcu - Get the next dev from upper list
7012 * @iter: list_head ** of the current position
7014 * Gets the next device from the dev's upper list, starting from iter
7015 * position. The caller must hold RCU read lock.
7017 struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev,
7018 struct list_head **iter)
7020 struct netdev_adjacent *upper;
7022 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
7024 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7026 if (&upper->list == &dev->adj_list.upper)
7029 *iter = &upper->list;
7033 EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu);
7035 static struct net_device *__netdev_next_upper_dev(struct net_device *dev,
7036 struct list_head **iter,
7039 struct netdev_adjacent *upper;
7041 upper = list_entry((*iter)->next, struct netdev_adjacent, list);
7043 if (&upper->list == &dev->adj_list.upper)
7046 *iter = &upper->list;
7047 *ignore = upper->ignore;
7052 static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev,
7053 struct list_head **iter)
7055 struct netdev_adjacent *upper;
7057 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
7059 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7061 if (&upper->list == &dev->adj_list.upper)
7064 *iter = &upper->list;
7069 static int __netdev_walk_all_upper_dev(struct net_device *dev,
7070 int (*fn)(struct net_device *dev,
7071 struct netdev_nested_priv *priv),
7072 struct netdev_nested_priv *priv)
7074 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7075 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7080 iter = &dev->adj_list.upper;
7084 ret = fn(now, priv);
7091 udev = __netdev_next_upper_dev(now, &iter, &ignore);
7098 niter = &udev->adj_list.upper;
7099 dev_stack[cur] = now;
7100 iter_stack[cur++] = iter;
7107 next = dev_stack[--cur];
7108 niter = iter_stack[cur];
7118 int netdev_walk_all_upper_dev_rcu(struct net_device *dev,
7119 int (*fn)(struct net_device *dev,
7120 struct netdev_nested_priv *priv),
7121 struct netdev_nested_priv *priv)
7123 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7124 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7128 iter = &dev->adj_list.upper;
7132 ret = fn(now, priv);
7139 udev = netdev_next_upper_dev_rcu(now, &iter);
7144 niter = &udev->adj_list.upper;
7145 dev_stack[cur] = now;
7146 iter_stack[cur++] = iter;
7153 next = dev_stack[--cur];
7154 niter = iter_stack[cur];
7163 EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu);
7165 static bool __netdev_has_upper_dev(struct net_device *dev,
7166 struct net_device *upper_dev)
7168 struct netdev_nested_priv priv = {
7170 .data = (void *)upper_dev,
7175 return __netdev_walk_all_upper_dev(dev, ____netdev_has_upper_dev,
7180 * netdev_lower_get_next_private - Get the next ->private from the
7181 * lower neighbour list
7183 * @iter: list_head ** of the current position
7185 * Gets the next netdev_adjacent->private from the dev's lower neighbour
7186 * list, starting from iter position. The caller must hold either hold the
7187 * RTNL lock or its own locking that guarantees that the neighbour lower
7188 * list will remain unchanged.
7190 void *netdev_lower_get_next_private(struct net_device *dev,
7191 struct list_head **iter)
7193 struct netdev_adjacent *lower;
7195 lower = list_entry(*iter, struct netdev_adjacent, list);
7197 if (&lower->list == &dev->adj_list.lower)
7200 *iter = lower->list.next;
7202 return lower->private;
7204 EXPORT_SYMBOL(netdev_lower_get_next_private);
7207 * netdev_lower_get_next_private_rcu - Get the next ->private from the
7208 * lower neighbour list, RCU
7211 * @iter: list_head ** of the current position
7213 * Gets the next netdev_adjacent->private from the dev's lower neighbour
7214 * list, starting from iter position. The caller must hold RCU read lock.
7216 void *netdev_lower_get_next_private_rcu(struct net_device *dev,
7217 struct list_head **iter)
7219 struct netdev_adjacent *lower;
7221 WARN_ON_ONCE(!rcu_read_lock_held());
7223 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7225 if (&lower->list == &dev->adj_list.lower)
7228 *iter = &lower->list;
7230 return lower->private;
7232 EXPORT_SYMBOL(netdev_lower_get_next_private_rcu);
7235 * netdev_lower_get_next - Get the next device from the lower neighbour
7238 * @iter: list_head ** of the current position
7240 * Gets the next netdev_adjacent from the dev's lower neighbour
7241 * list, starting from iter position. The caller must hold RTNL lock or
7242 * its own locking that guarantees that the neighbour lower
7243 * list will remain unchanged.
7245 void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter)
7247 struct netdev_adjacent *lower;
7249 lower = list_entry(*iter, struct netdev_adjacent, list);
7251 if (&lower->list == &dev->adj_list.lower)
7254 *iter = lower->list.next;
7258 EXPORT_SYMBOL(netdev_lower_get_next);
7260 static struct net_device *netdev_next_lower_dev(struct net_device *dev,
7261 struct list_head **iter)
7263 struct netdev_adjacent *lower;
7265 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7267 if (&lower->list == &dev->adj_list.lower)
7270 *iter = &lower->list;
7275 static struct net_device *__netdev_next_lower_dev(struct net_device *dev,
7276 struct list_head **iter,
7279 struct netdev_adjacent *lower;
7281 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7283 if (&lower->list == &dev->adj_list.lower)
7286 *iter = &lower->list;
7287 *ignore = lower->ignore;
7292 int netdev_walk_all_lower_dev(struct net_device *dev,
7293 int (*fn)(struct net_device *dev,
7294 struct netdev_nested_priv *priv),
7295 struct netdev_nested_priv *priv)
7297 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7298 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7302 iter = &dev->adj_list.lower;
7306 ret = fn(now, priv);
7313 ldev = netdev_next_lower_dev(now, &iter);
7318 niter = &ldev->adj_list.lower;
7319 dev_stack[cur] = now;
7320 iter_stack[cur++] = iter;
7327 next = dev_stack[--cur];
7328 niter = iter_stack[cur];
7337 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev);
7339 static int __netdev_walk_all_lower_dev(struct net_device *dev,
7340 int (*fn)(struct net_device *dev,
7341 struct netdev_nested_priv *priv),
7342 struct netdev_nested_priv *priv)
7344 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7345 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7350 iter = &dev->adj_list.lower;
7354 ret = fn(now, priv);
7361 ldev = __netdev_next_lower_dev(now, &iter, &ignore);
7368 niter = &ldev->adj_list.lower;
7369 dev_stack[cur] = now;
7370 iter_stack[cur++] = iter;
7377 next = dev_stack[--cur];
7378 niter = iter_stack[cur];
7388 struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev,
7389 struct list_head **iter)
7391 struct netdev_adjacent *lower;
7393 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7394 if (&lower->list == &dev->adj_list.lower)
7397 *iter = &lower->list;
7401 EXPORT_SYMBOL(netdev_next_lower_dev_rcu);
7403 static u8 __netdev_upper_depth(struct net_device *dev)
7405 struct net_device *udev;
7406 struct list_head *iter;
7410 for (iter = &dev->adj_list.upper,
7411 udev = __netdev_next_upper_dev(dev, &iter, &ignore);
7413 udev = __netdev_next_upper_dev(dev, &iter, &ignore)) {
7416 if (max_depth < udev->upper_level)
7417 max_depth = udev->upper_level;
7423 static u8 __netdev_lower_depth(struct net_device *dev)
7425 struct net_device *ldev;
7426 struct list_head *iter;
7430 for (iter = &dev->adj_list.lower,
7431 ldev = __netdev_next_lower_dev(dev, &iter, &ignore);
7433 ldev = __netdev_next_lower_dev(dev, &iter, &ignore)) {
7436 if (max_depth < ldev->lower_level)
7437 max_depth = ldev->lower_level;
7443 static int __netdev_update_upper_level(struct net_device *dev,
7444 struct netdev_nested_priv *__unused)
7446 dev->upper_level = __netdev_upper_depth(dev) + 1;
7450 static int __netdev_update_lower_level(struct net_device *dev,
7451 struct netdev_nested_priv *priv)
7453 dev->lower_level = __netdev_lower_depth(dev) + 1;
7455 #ifdef CONFIG_LOCKDEP
7459 if (priv->flags & NESTED_SYNC_IMM)
7460 dev->nested_level = dev->lower_level - 1;
7461 if (priv->flags & NESTED_SYNC_TODO)
7462 net_unlink_todo(dev);
7467 int netdev_walk_all_lower_dev_rcu(struct net_device *dev,
7468 int (*fn)(struct net_device *dev,
7469 struct netdev_nested_priv *priv),
7470 struct netdev_nested_priv *priv)
7472 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7473 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7477 iter = &dev->adj_list.lower;
7481 ret = fn(now, priv);
7488 ldev = netdev_next_lower_dev_rcu(now, &iter);
7493 niter = &ldev->adj_list.lower;
7494 dev_stack[cur] = now;
7495 iter_stack[cur++] = iter;
7502 next = dev_stack[--cur];
7503 niter = iter_stack[cur];
7512 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu);
7515 * netdev_lower_get_first_private_rcu - Get the first ->private from the
7516 * lower neighbour list, RCU
7520 * Gets the first netdev_adjacent->private from the dev's lower neighbour
7521 * list. The caller must hold RCU read lock.
7523 void *netdev_lower_get_first_private_rcu(struct net_device *dev)
7525 struct netdev_adjacent *lower;
7527 lower = list_first_or_null_rcu(&dev->adj_list.lower,
7528 struct netdev_adjacent, list);
7530 return lower->private;
7533 EXPORT_SYMBOL(netdev_lower_get_first_private_rcu);
7536 * netdev_master_upper_dev_get_rcu - Get master upper device
7539 * Find a master upper device and return pointer to it or NULL in case
7540 * it's not there. The caller must hold the RCU read lock.
7542 struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev)
7544 struct netdev_adjacent *upper;
7546 upper = list_first_or_null_rcu(&dev->adj_list.upper,
7547 struct netdev_adjacent, list);
7548 if (upper && likely(upper->master))
7552 EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu);
7554 static int netdev_adjacent_sysfs_add(struct net_device *dev,
7555 struct net_device *adj_dev,
7556 struct list_head *dev_list)
7558 char linkname[IFNAMSIZ+7];
7560 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7561 "upper_%s" : "lower_%s", adj_dev->name);
7562 return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj),
7565 static void netdev_adjacent_sysfs_del(struct net_device *dev,
7567 struct list_head *dev_list)
7569 char linkname[IFNAMSIZ+7];
7571 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7572 "upper_%s" : "lower_%s", name);
7573 sysfs_remove_link(&(dev->dev.kobj), linkname);
7576 static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev,
7577 struct net_device *adj_dev,
7578 struct list_head *dev_list)
7580 return (dev_list == &dev->adj_list.upper ||
7581 dev_list == &dev->adj_list.lower) &&
7582 net_eq(dev_net(dev), dev_net(adj_dev));
7585 static int __netdev_adjacent_dev_insert(struct net_device *dev,
7586 struct net_device *adj_dev,
7587 struct list_head *dev_list,
7588 void *private, bool master)
7590 struct netdev_adjacent *adj;
7593 adj = __netdev_find_adj(adj_dev, dev_list);
7597 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n",
7598 dev->name, adj_dev->name, adj->ref_nr);
7603 adj = kmalloc(sizeof(*adj), GFP_KERNEL);
7608 adj->master = master;
7610 adj->private = private;
7611 adj->ignore = false;
7614 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n",
7615 dev->name, adj_dev->name, adj->ref_nr, adj_dev->name);
7617 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) {
7618 ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list);
7623 /* Ensure that master link is always the first item in list. */
7625 ret = sysfs_create_link(&(dev->dev.kobj),
7626 &(adj_dev->dev.kobj), "master");
7628 goto remove_symlinks;
7630 list_add_rcu(&adj->list, dev_list);
7632 list_add_tail_rcu(&adj->list, dev_list);
7638 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7639 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7647 static void __netdev_adjacent_dev_remove(struct net_device *dev,
7648 struct net_device *adj_dev,
7650 struct list_head *dev_list)
7652 struct netdev_adjacent *adj;
7654 pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n",
7655 dev->name, adj_dev->name, ref_nr);
7657 adj = __netdev_find_adj(adj_dev, dev_list);
7660 pr_err("Adjacency does not exist for device %s from %s\n",
7661 dev->name, adj_dev->name);
7666 if (adj->ref_nr > ref_nr) {
7667 pr_debug("adjacency: %s to %s ref_nr - %d = %d\n",
7668 dev->name, adj_dev->name, ref_nr,
7669 adj->ref_nr - ref_nr);
7670 adj->ref_nr -= ref_nr;
7675 sysfs_remove_link(&(dev->dev.kobj), "master");
7677 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7678 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7680 list_del_rcu(&adj->list);
7681 pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n",
7682 adj_dev->name, dev->name, adj_dev->name);
7684 kfree_rcu(adj, rcu);
7687 static int __netdev_adjacent_dev_link_lists(struct net_device *dev,
7688 struct net_device *upper_dev,
7689 struct list_head *up_list,
7690 struct list_head *down_list,
7691 void *private, bool master)
7695 ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list,
7700 ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list,
7703 __netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list);
7710 static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev,
7711 struct net_device *upper_dev,
7713 struct list_head *up_list,
7714 struct list_head *down_list)
7716 __netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list);
7717 __netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list);
7720 static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev,
7721 struct net_device *upper_dev,
7722 void *private, bool master)
7724 return __netdev_adjacent_dev_link_lists(dev, upper_dev,
7725 &dev->adj_list.upper,
7726 &upper_dev->adj_list.lower,
7730 static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev,
7731 struct net_device *upper_dev)
7733 __netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1,
7734 &dev->adj_list.upper,
7735 &upper_dev->adj_list.lower);
7738 static int __netdev_upper_dev_link(struct net_device *dev,
7739 struct net_device *upper_dev, bool master,
7740 void *upper_priv, void *upper_info,
7741 struct netdev_nested_priv *priv,
7742 struct netlink_ext_ack *extack)
7744 struct netdev_notifier_changeupper_info changeupper_info = {
7749 .upper_dev = upper_dev,
7752 .upper_info = upper_info,
7754 struct net_device *master_dev;
7759 if (dev == upper_dev)
7762 /* To prevent loops, check if dev is not upper device to upper_dev. */
7763 if (__netdev_has_upper_dev(upper_dev, dev))
7766 if ((dev->lower_level + upper_dev->upper_level) > MAX_NEST_DEV)
7770 if (__netdev_has_upper_dev(dev, upper_dev))
7773 master_dev = __netdev_master_upper_dev_get(dev);
7775 return master_dev == upper_dev ? -EEXIST : -EBUSY;
7778 ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7779 &changeupper_info.info);
7780 ret = notifier_to_errno(ret);
7784 ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv,
7789 ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7790 &changeupper_info.info);
7791 ret = notifier_to_errno(ret);
7795 __netdev_update_upper_level(dev, NULL);
7796 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7798 __netdev_update_lower_level(upper_dev, priv);
7799 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
7805 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7811 * netdev_upper_dev_link - Add a link to the upper device
7813 * @upper_dev: new upper device
7814 * @extack: netlink extended ack
7816 * Adds a link to device which is upper to this one. The caller must hold
7817 * the RTNL lock. On a failure a negative errno code is returned.
7818 * On success the reference counts are adjusted and the function
7821 int netdev_upper_dev_link(struct net_device *dev,
7822 struct net_device *upper_dev,
7823 struct netlink_ext_ack *extack)
7825 struct netdev_nested_priv priv = {
7826 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7830 return __netdev_upper_dev_link(dev, upper_dev, false,
7831 NULL, NULL, &priv, extack);
7833 EXPORT_SYMBOL(netdev_upper_dev_link);
7836 * netdev_master_upper_dev_link - Add a master link to the upper device
7838 * @upper_dev: new upper device
7839 * @upper_priv: upper device private
7840 * @upper_info: upper info to be passed down via notifier
7841 * @extack: netlink extended ack
7843 * Adds a link to device which is upper to this one. In this case, only
7844 * one master upper device can be linked, although other non-master devices
7845 * might be linked as well. The caller must hold the RTNL lock.
7846 * On a failure a negative errno code is returned. On success the reference
7847 * counts are adjusted and the function returns zero.
7849 int netdev_master_upper_dev_link(struct net_device *dev,
7850 struct net_device *upper_dev,
7851 void *upper_priv, void *upper_info,
7852 struct netlink_ext_ack *extack)
7854 struct netdev_nested_priv priv = {
7855 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7859 return __netdev_upper_dev_link(dev, upper_dev, true,
7860 upper_priv, upper_info, &priv, extack);
7862 EXPORT_SYMBOL(netdev_master_upper_dev_link);
7864 static void __netdev_upper_dev_unlink(struct net_device *dev,
7865 struct net_device *upper_dev,
7866 struct netdev_nested_priv *priv)
7868 struct netdev_notifier_changeupper_info changeupper_info = {
7872 .upper_dev = upper_dev,
7878 changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev;
7880 call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7881 &changeupper_info.info);
7883 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7885 call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7886 &changeupper_info.info);
7888 __netdev_update_upper_level(dev, NULL);
7889 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7891 __netdev_update_lower_level(upper_dev, priv);
7892 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
7897 * netdev_upper_dev_unlink - Removes a link to upper device
7899 * @upper_dev: new upper device
7901 * Removes a link to device which is upper to this one. The caller must hold
7904 void netdev_upper_dev_unlink(struct net_device *dev,
7905 struct net_device *upper_dev)
7907 struct netdev_nested_priv priv = {
7908 .flags = NESTED_SYNC_TODO,
7912 __netdev_upper_dev_unlink(dev, upper_dev, &priv);
7914 EXPORT_SYMBOL(netdev_upper_dev_unlink);
7916 static void __netdev_adjacent_dev_set(struct net_device *upper_dev,
7917 struct net_device *lower_dev,
7920 struct netdev_adjacent *adj;
7922 adj = __netdev_find_adj(lower_dev, &upper_dev->adj_list.lower);
7926 adj = __netdev_find_adj(upper_dev, &lower_dev->adj_list.upper);
7931 static void netdev_adjacent_dev_disable(struct net_device *upper_dev,
7932 struct net_device *lower_dev)
7934 __netdev_adjacent_dev_set(upper_dev, lower_dev, true);
7937 static void netdev_adjacent_dev_enable(struct net_device *upper_dev,
7938 struct net_device *lower_dev)
7940 __netdev_adjacent_dev_set(upper_dev, lower_dev, false);
7943 int netdev_adjacent_change_prepare(struct net_device *old_dev,
7944 struct net_device *new_dev,
7945 struct net_device *dev,
7946 struct netlink_ext_ack *extack)
7948 struct netdev_nested_priv priv = {
7957 if (old_dev && new_dev != old_dev)
7958 netdev_adjacent_dev_disable(dev, old_dev);
7959 err = __netdev_upper_dev_link(new_dev, dev, false, NULL, NULL, &priv,
7962 if (old_dev && new_dev != old_dev)
7963 netdev_adjacent_dev_enable(dev, old_dev);
7969 EXPORT_SYMBOL(netdev_adjacent_change_prepare);
7971 void netdev_adjacent_change_commit(struct net_device *old_dev,
7972 struct net_device *new_dev,
7973 struct net_device *dev)
7975 struct netdev_nested_priv priv = {
7976 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7980 if (!new_dev || !old_dev)
7983 if (new_dev == old_dev)
7986 netdev_adjacent_dev_enable(dev, old_dev);
7987 __netdev_upper_dev_unlink(old_dev, dev, &priv);
7989 EXPORT_SYMBOL(netdev_adjacent_change_commit);
7991 void netdev_adjacent_change_abort(struct net_device *old_dev,
7992 struct net_device *new_dev,
7993 struct net_device *dev)
7995 struct netdev_nested_priv priv = {
8003 if (old_dev && new_dev != old_dev)
8004 netdev_adjacent_dev_enable(dev, old_dev);
8006 __netdev_upper_dev_unlink(new_dev, dev, &priv);
8008 EXPORT_SYMBOL(netdev_adjacent_change_abort);
8011 * netdev_bonding_info_change - Dispatch event about slave change
8013 * @bonding_info: info to dispatch
8015 * Send NETDEV_BONDING_INFO to netdev notifiers with info.
8016 * The caller must hold the RTNL lock.
8018 void netdev_bonding_info_change(struct net_device *dev,
8019 struct netdev_bonding_info *bonding_info)
8021 struct netdev_notifier_bonding_info info = {
8025 memcpy(&info.bonding_info, bonding_info,
8026 sizeof(struct netdev_bonding_info));
8027 call_netdevice_notifiers_info(NETDEV_BONDING_INFO,
8030 EXPORT_SYMBOL(netdev_bonding_info_change);
8033 * netdev_get_xmit_slave - Get the xmit slave of master device
8036 * @all_slaves: assume all the slaves are active
8038 * The reference counters are not incremented so the caller must be
8039 * careful with locks. The caller must hold RCU lock.
8040 * %NULL is returned if no slave is found.
8043 struct net_device *netdev_get_xmit_slave(struct net_device *dev,
8044 struct sk_buff *skb,
8047 const struct net_device_ops *ops = dev->netdev_ops;
8049 if (!ops->ndo_get_xmit_slave)
8051 return ops->ndo_get_xmit_slave(dev, skb, all_slaves);
8053 EXPORT_SYMBOL(netdev_get_xmit_slave);
8055 static void netdev_adjacent_add_links(struct net_device *dev)
8057 struct netdev_adjacent *iter;
8059 struct net *net = dev_net(dev);
8061 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8062 if (!net_eq(net, dev_net(iter->dev)))
8064 netdev_adjacent_sysfs_add(iter->dev, dev,
8065 &iter->dev->adj_list.lower);
8066 netdev_adjacent_sysfs_add(dev, iter->dev,
8067 &dev->adj_list.upper);
8070 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8071 if (!net_eq(net, dev_net(iter->dev)))
8073 netdev_adjacent_sysfs_add(iter->dev, dev,
8074 &iter->dev->adj_list.upper);
8075 netdev_adjacent_sysfs_add(dev, iter->dev,
8076 &dev->adj_list.lower);
8080 static void netdev_adjacent_del_links(struct net_device *dev)
8082 struct netdev_adjacent *iter;
8084 struct net *net = dev_net(dev);
8086 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8087 if (!net_eq(net, dev_net(iter->dev)))
8089 netdev_adjacent_sysfs_del(iter->dev, dev->name,
8090 &iter->dev->adj_list.lower);
8091 netdev_adjacent_sysfs_del(dev, iter->dev->name,
8092 &dev->adj_list.upper);
8095 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8096 if (!net_eq(net, dev_net(iter->dev)))
8098 netdev_adjacent_sysfs_del(iter->dev, dev->name,
8099 &iter->dev->adj_list.upper);
8100 netdev_adjacent_sysfs_del(dev, iter->dev->name,
8101 &dev->adj_list.lower);
8105 void netdev_adjacent_rename_links(struct net_device *dev, char *oldname)
8107 struct netdev_adjacent *iter;
8109 struct net *net = dev_net(dev);
8111 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8112 if (!net_eq(net, dev_net(iter->dev)))
8114 netdev_adjacent_sysfs_del(iter->dev, oldname,
8115 &iter->dev->adj_list.lower);
8116 netdev_adjacent_sysfs_add(iter->dev, dev,
8117 &iter->dev->adj_list.lower);
8120 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8121 if (!net_eq(net, dev_net(iter->dev)))
8123 netdev_adjacent_sysfs_del(iter->dev, oldname,
8124 &iter->dev->adj_list.upper);
8125 netdev_adjacent_sysfs_add(iter->dev, dev,
8126 &iter->dev->adj_list.upper);
8130 void *netdev_lower_dev_get_private(struct net_device *dev,
8131 struct net_device *lower_dev)
8133 struct netdev_adjacent *lower;
8137 lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower);
8141 return lower->private;
8143 EXPORT_SYMBOL(netdev_lower_dev_get_private);
8147 * netdev_lower_change - Dispatch event about lower device state change
8148 * @lower_dev: device
8149 * @lower_state_info: state to dispatch
8151 * Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info.
8152 * The caller must hold the RTNL lock.
8154 void netdev_lower_state_changed(struct net_device *lower_dev,
8155 void *lower_state_info)
8157 struct netdev_notifier_changelowerstate_info changelowerstate_info = {
8158 .info.dev = lower_dev,
8162 changelowerstate_info.lower_state_info = lower_state_info;
8163 call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE,
8164 &changelowerstate_info.info);
8166 EXPORT_SYMBOL(netdev_lower_state_changed);
8168 static void dev_change_rx_flags(struct net_device *dev, int flags)
8170 const struct net_device_ops *ops = dev->netdev_ops;
8172 if (ops->ndo_change_rx_flags)
8173 ops->ndo_change_rx_flags(dev, flags);
8176 static int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify)
8178 unsigned int old_flags = dev->flags;
8184 dev->flags |= IFF_PROMISC;
8185 dev->promiscuity += inc;
8186 if (dev->promiscuity == 0) {
8189 * If inc causes overflow, untouch promisc and return error.
8192 dev->flags &= ~IFF_PROMISC;
8194 dev->promiscuity -= inc;
8195 pr_warn("%s: promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n",
8200 if (dev->flags != old_flags) {
8201 pr_info("device %s %s promiscuous mode\n",
8203 dev->flags & IFF_PROMISC ? "entered" : "left");
8204 if (audit_enabled) {
8205 current_uid_gid(&uid, &gid);
8206 audit_log(audit_context(), GFP_ATOMIC,
8207 AUDIT_ANOM_PROMISCUOUS,
8208 "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u",
8209 dev->name, (dev->flags & IFF_PROMISC),
8210 (old_flags & IFF_PROMISC),
8211 from_kuid(&init_user_ns, audit_get_loginuid(current)),
8212 from_kuid(&init_user_ns, uid),
8213 from_kgid(&init_user_ns, gid),
8214 audit_get_sessionid(current));
8217 dev_change_rx_flags(dev, IFF_PROMISC);
8220 __dev_notify_flags(dev, old_flags, IFF_PROMISC);
8225 * dev_set_promiscuity - update promiscuity count on a device
8229 * Add or remove promiscuity from a device. While the count in the device
8230 * remains above zero the interface remains promiscuous. Once it hits zero
8231 * the device reverts back to normal filtering operation. A negative inc
8232 * value is used to drop promiscuity on the device.
8233 * Return 0 if successful or a negative errno code on error.
8235 int dev_set_promiscuity(struct net_device *dev, int inc)
8237 unsigned int old_flags = dev->flags;
8240 err = __dev_set_promiscuity(dev, inc, true);
8243 if (dev->flags != old_flags)
8244 dev_set_rx_mode(dev);
8247 EXPORT_SYMBOL(dev_set_promiscuity);
8249 static int __dev_set_allmulti(struct net_device *dev, int inc, bool notify)
8251 unsigned int old_flags = dev->flags, old_gflags = dev->gflags;
8255 dev->flags |= IFF_ALLMULTI;
8256 dev->allmulti += inc;
8257 if (dev->allmulti == 0) {
8260 * If inc causes overflow, untouch allmulti and return error.
8263 dev->flags &= ~IFF_ALLMULTI;
8265 dev->allmulti -= inc;
8266 pr_warn("%s: allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n",
8271 if (dev->flags ^ old_flags) {
8272 dev_change_rx_flags(dev, IFF_ALLMULTI);
8273 dev_set_rx_mode(dev);
8275 __dev_notify_flags(dev, old_flags,
8276 dev->gflags ^ old_gflags);
8282 * dev_set_allmulti - update allmulti count on a device
8286 * Add or remove reception of all multicast frames to a device. While the
8287 * count in the device remains above zero the interface remains listening
8288 * to all interfaces. Once it hits zero the device reverts back to normal
8289 * filtering operation. A negative @inc value is used to drop the counter
8290 * when releasing a resource needing all multicasts.
8291 * Return 0 if successful or a negative errno code on error.
8294 int dev_set_allmulti(struct net_device *dev, int inc)
8296 return __dev_set_allmulti(dev, inc, true);
8298 EXPORT_SYMBOL(dev_set_allmulti);
8301 * Upload unicast and multicast address lists to device and
8302 * configure RX filtering. When the device doesn't support unicast
8303 * filtering it is put in promiscuous mode while unicast addresses
8306 void __dev_set_rx_mode(struct net_device *dev)
8308 const struct net_device_ops *ops = dev->netdev_ops;
8310 /* dev_open will call this function so the list will stay sane. */
8311 if (!(dev->flags&IFF_UP))
8314 if (!netif_device_present(dev))
8317 if (!(dev->priv_flags & IFF_UNICAST_FLT)) {
8318 /* Unicast addresses changes may only happen under the rtnl,
8319 * therefore calling __dev_set_promiscuity here is safe.
8321 if (!netdev_uc_empty(dev) && !dev->uc_promisc) {
8322 __dev_set_promiscuity(dev, 1, false);
8323 dev->uc_promisc = true;
8324 } else if (netdev_uc_empty(dev) && dev->uc_promisc) {
8325 __dev_set_promiscuity(dev, -1, false);
8326 dev->uc_promisc = false;
8330 if (ops->ndo_set_rx_mode)
8331 ops->ndo_set_rx_mode(dev);
8334 void dev_set_rx_mode(struct net_device *dev)
8336 netif_addr_lock_bh(dev);
8337 __dev_set_rx_mode(dev);
8338 netif_addr_unlock_bh(dev);
8342 * dev_get_flags - get flags reported to userspace
8345 * Get the combination of flag bits exported through APIs to userspace.
8347 unsigned int dev_get_flags(const struct net_device *dev)
8351 flags = (dev->flags & ~(IFF_PROMISC |
8356 (dev->gflags & (IFF_PROMISC |
8359 if (netif_running(dev)) {
8360 if (netif_oper_up(dev))
8361 flags |= IFF_RUNNING;
8362 if (netif_carrier_ok(dev))
8363 flags |= IFF_LOWER_UP;
8364 if (netif_dormant(dev))
8365 flags |= IFF_DORMANT;
8370 EXPORT_SYMBOL(dev_get_flags);
8372 int __dev_change_flags(struct net_device *dev, unsigned int flags,
8373 struct netlink_ext_ack *extack)
8375 unsigned int old_flags = dev->flags;
8381 * Set the flags on our device.
8384 dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
8385 IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
8387 (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
8391 * Load in the correct multicast list now the flags have changed.
8394 if ((old_flags ^ flags) & IFF_MULTICAST)
8395 dev_change_rx_flags(dev, IFF_MULTICAST);
8397 dev_set_rx_mode(dev);
8400 * Have we downed the interface. We handle IFF_UP ourselves
8401 * according to user attempts to set it, rather than blindly
8406 if ((old_flags ^ flags) & IFF_UP) {
8407 if (old_flags & IFF_UP)
8410 ret = __dev_open(dev, extack);
8413 if ((flags ^ dev->gflags) & IFF_PROMISC) {
8414 int inc = (flags & IFF_PROMISC) ? 1 : -1;
8415 unsigned int old_flags = dev->flags;
8417 dev->gflags ^= IFF_PROMISC;
8419 if (__dev_set_promiscuity(dev, inc, false) >= 0)
8420 if (dev->flags != old_flags)
8421 dev_set_rx_mode(dev);
8424 /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
8425 * is important. Some (broken) drivers set IFF_PROMISC, when
8426 * IFF_ALLMULTI is requested not asking us and not reporting.
8428 if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
8429 int inc = (flags & IFF_ALLMULTI) ? 1 : -1;
8431 dev->gflags ^= IFF_ALLMULTI;
8432 __dev_set_allmulti(dev, inc, false);
8438 void __dev_notify_flags(struct net_device *dev, unsigned int old_flags,
8439 unsigned int gchanges)
8441 unsigned int changes = dev->flags ^ old_flags;
8444 rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC);
8446 if (changes & IFF_UP) {
8447 if (dev->flags & IFF_UP)
8448 call_netdevice_notifiers(NETDEV_UP, dev);
8450 call_netdevice_notifiers(NETDEV_DOWN, dev);
8453 if (dev->flags & IFF_UP &&
8454 (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) {
8455 struct netdev_notifier_change_info change_info = {
8459 .flags_changed = changes,
8462 call_netdevice_notifiers_info(NETDEV_CHANGE, &change_info.info);
8467 * dev_change_flags - change device settings
8469 * @flags: device state flags
8470 * @extack: netlink extended ack
8472 * Change settings on device based state flags. The flags are
8473 * in the userspace exported format.
8475 int dev_change_flags(struct net_device *dev, unsigned int flags,
8476 struct netlink_ext_ack *extack)
8479 unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags;
8481 ret = __dev_change_flags(dev, flags, extack);
8485 changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags);
8486 __dev_notify_flags(dev, old_flags, changes);
8489 EXPORT_SYMBOL(dev_change_flags);
8491 int __dev_set_mtu(struct net_device *dev, int new_mtu)
8493 const struct net_device_ops *ops = dev->netdev_ops;
8495 if (ops->ndo_change_mtu)
8496 return ops->ndo_change_mtu(dev, new_mtu);
8498 /* Pairs with all the lockless reads of dev->mtu in the stack */
8499 WRITE_ONCE(dev->mtu, new_mtu);
8502 EXPORT_SYMBOL(__dev_set_mtu);
8504 int dev_validate_mtu(struct net_device *dev, int new_mtu,
8505 struct netlink_ext_ack *extack)
8507 /* MTU must be positive, and in range */
8508 if (new_mtu < 0 || new_mtu < dev->min_mtu) {
8509 NL_SET_ERR_MSG(extack, "mtu less than device minimum");
8513 if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) {
8514 NL_SET_ERR_MSG(extack, "mtu greater than device maximum");
8521 * dev_set_mtu_ext - Change maximum transfer unit
8523 * @new_mtu: new transfer unit
8524 * @extack: netlink extended ack
8526 * Change the maximum transfer size of the network device.
8528 int dev_set_mtu_ext(struct net_device *dev, int new_mtu,
8529 struct netlink_ext_ack *extack)
8533 if (new_mtu == dev->mtu)
8536 err = dev_validate_mtu(dev, new_mtu, extack);
8540 if (!netif_device_present(dev))
8543 err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev);
8544 err = notifier_to_errno(err);
8548 orig_mtu = dev->mtu;
8549 err = __dev_set_mtu(dev, new_mtu);
8552 err = call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8554 err = notifier_to_errno(err);
8556 /* setting mtu back and notifying everyone again,
8557 * so that they have a chance to revert changes.
8559 __dev_set_mtu(dev, orig_mtu);
8560 call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8567 int dev_set_mtu(struct net_device *dev, int new_mtu)
8569 struct netlink_ext_ack extack;
8572 memset(&extack, 0, sizeof(extack));
8573 err = dev_set_mtu_ext(dev, new_mtu, &extack);
8574 if (err && extack._msg)
8575 net_err_ratelimited("%s: %s\n", dev->name, extack._msg);
8578 EXPORT_SYMBOL(dev_set_mtu);
8581 * dev_change_tx_queue_len - Change TX queue length of a netdevice
8583 * @new_len: new tx queue length
8585 int dev_change_tx_queue_len(struct net_device *dev, unsigned long new_len)
8587 unsigned int orig_len = dev->tx_queue_len;
8590 if (new_len != (unsigned int)new_len)
8593 if (new_len != orig_len) {
8594 dev->tx_queue_len = new_len;
8595 res = call_netdevice_notifiers(NETDEV_CHANGE_TX_QUEUE_LEN, dev);
8596 res = notifier_to_errno(res);
8599 res = dev_qdisc_change_tx_queue_len(dev);
8607 netdev_err(dev, "refused to change device tx_queue_len\n");
8608 dev->tx_queue_len = orig_len;
8613 * dev_set_group - Change group this device belongs to
8615 * @new_group: group this device should belong to
8617 void dev_set_group(struct net_device *dev, int new_group)
8619 dev->group = new_group;
8621 EXPORT_SYMBOL(dev_set_group);
8624 * dev_pre_changeaddr_notify - Call NETDEV_PRE_CHANGEADDR.
8626 * @addr: new address
8627 * @extack: netlink extended ack
8629 int dev_pre_changeaddr_notify(struct net_device *dev, const char *addr,
8630 struct netlink_ext_ack *extack)
8632 struct netdev_notifier_pre_changeaddr_info info = {
8634 .info.extack = extack,
8639 rc = call_netdevice_notifiers_info(NETDEV_PRE_CHANGEADDR, &info.info);
8640 return notifier_to_errno(rc);
8642 EXPORT_SYMBOL(dev_pre_changeaddr_notify);
8645 * dev_set_mac_address - Change Media Access Control Address
8648 * @extack: netlink extended ack
8650 * Change the hardware (MAC) address of the device
8652 int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa,
8653 struct netlink_ext_ack *extack)
8655 const struct net_device_ops *ops = dev->netdev_ops;
8658 if (!ops->ndo_set_mac_address)
8660 if (sa->sa_family != dev->type)
8662 if (!netif_device_present(dev))
8664 err = dev_pre_changeaddr_notify(dev, sa->sa_data, extack);
8667 err = ops->ndo_set_mac_address(dev, sa);
8670 dev->addr_assign_type = NET_ADDR_SET;
8671 call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
8672 add_device_randomness(dev->dev_addr, dev->addr_len);
8675 EXPORT_SYMBOL(dev_set_mac_address);
8678 * dev_change_carrier - Change device carrier
8680 * @new_carrier: new value
8682 * Change device carrier
8684 int dev_change_carrier(struct net_device *dev, bool new_carrier)
8686 const struct net_device_ops *ops = dev->netdev_ops;
8688 if (!ops->ndo_change_carrier)
8690 if (!netif_device_present(dev))
8692 return ops->ndo_change_carrier(dev, new_carrier);
8694 EXPORT_SYMBOL(dev_change_carrier);
8697 * dev_get_phys_port_id - Get device physical port ID
8701 * Get device physical port ID
8703 int dev_get_phys_port_id(struct net_device *dev,
8704 struct netdev_phys_item_id *ppid)
8706 const struct net_device_ops *ops = dev->netdev_ops;
8708 if (!ops->ndo_get_phys_port_id)
8710 return ops->ndo_get_phys_port_id(dev, ppid);
8712 EXPORT_SYMBOL(dev_get_phys_port_id);
8715 * dev_get_phys_port_name - Get device physical port name
8718 * @len: limit of bytes to copy to name
8720 * Get device physical port name
8722 int dev_get_phys_port_name(struct net_device *dev,
8723 char *name, size_t len)
8725 const struct net_device_ops *ops = dev->netdev_ops;
8728 if (ops->ndo_get_phys_port_name) {
8729 err = ops->ndo_get_phys_port_name(dev, name, len);
8730 if (err != -EOPNOTSUPP)
8733 return devlink_compat_phys_port_name_get(dev, name, len);
8735 EXPORT_SYMBOL(dev_get_phys_port_name);
8738 * dev_get_port_parent_id - Get the device's port parent identifier
8739 * @dev: network device
8740 * @ppid: pointer to a storage for the port's parent identifier
8741 * @recurse: allow/disallow recursion to lower devices
8743 * Get the devices's port parent identifier
8745 int dev_get_port_parent_id(struct net_device *dev,
8746 struct netdev_phys_item_id *ppid,
8749 const struct net_device_ops *ops = dev->netdev_ops;
8750 struct netdev_phys_item_id first = { };
8751 struct net_device *lower_dev;
8752 struct list_head *iter;
8755 if (ops->ndo_get_port_parent_id) {
8756 err = ops->ndo_get_port_parent_id(dev, ppid);
8757 if (err != -EOPNOTSUPP)
8761 err = devlink_compat_switch_id_get(dev, ppid);
8762 if (!err || err != -EOPNOTSUPP)
8768 netdev_for_each_lower_dev(dev, lower_dev, iter) {
8769 err = dev_get_port_parent_id(lower_dev, ppid, recurse);
8774 else if (memcmp(&first, ppid, sizeof(*ppid)))
8780 EXPORT_SYMBOL(dev_get_port_parent_id);
8783 * netdev_port_same_parent_id - Indicate if two network devices have
8784 * the same port parent identifier
8785 * @a: first network device
8786 * @b: second network device
8788 bool netdev_port_same_parent_id(struct net_device *a, struct net_device *b)
8790 struct netdev_phys_item_id a_id = { };
8791 struct netdev_phys_item_id b_id = { };
8793 if (dev_get_port_parent_id(a, &a_id, true) ||
8794 dev_get_port_parent_id(b, &b_id, true))
8797 return netdev_phys_item_id_same(&a_id, &b_id);
8799 EXPORT_SYMBOL(netdev_port_same_parent_id);
8802 * dev_change_proto_down - update protocol port state information
8804 * @proto_down: new value
8806 * This info can be used by switch drivers to set the phys state of the
8809 int dev_change_proto_down(struct net_device *dev, bool proto_down)
8811 const struct net_device_ops *ops = dev->netdev_ops;
8813 if (!ops->ndo_change_proto_down)
8815 if (!netif_device_present(dev))
8817 return ops->ndo_change_proto_down(dev, proto_down);
8819 EXPORT_SYMBOL(dev_change_proto_down);
8822 * dev_change_proto_down_generic - generic implementation for
8823 * ndo_change_proto_down that sets carrier according to
8827 * @proto_down: new value
8829 int dev_change_proto_down_generic(struct net_device *dev, bool proto_down)
8832 netif_carrier_off(dev);
8834 netif_carrier_on(dev);
8835 dev->proto_down = proto_down;
8838 EXPORT_SYMBOL(dev_change_proto_down_generic);
8841 * dev_change_proto_down_reason - proto down reason
8844 * @mask: proto down mask
8845 * @value: proto down value
8847 void dev_change_proto_down_reason(struct net_device *dev, unsigned long mask,
8853 dev->proto_down_reason = value;
8855 for_each_set_bit(b, &mask, 32) {
8856 if (value & (1 << b))
8857 dev->proto_down_reason |= BIT(b);
8859 dev->proto_down_reason &= ~BIT(b);
8863 EXPORT_SYMBOL(dev_change_proto_down_reason);
8865 struct bpf_xdp_link {
8866 struct bpf_link link;
8867 struct net_device *dev; /* protected by rtnl_lock, no refcnt held */
8871 static enum bpf_xdp_mode dev_xdp_mode(struct net_device *dev, u32 flags)
8873 if (flags & XDP_FLAGS_HW_MODE)
8875 if (flags & XDP_FLAGS_DRV_MODE)
8876 return XDP_MODE_DRV;
8877 if (flags & XDP_FLAGS_SKB_MODE)
8878 return XDP_MODE_SKB;
8879 return dev->netdev_ops->ndo_bpf ? XDP_MODE_DRV : XDP_MODE_SKB;
8882 static bpf_op_t dev_xdp_bpf_op(struct net_device *dev, enum bpf_xdp_mode mode)
8886 return generic_xdp_install;
8889 return dev->netdev_ops->ndo_bpf;
8895 static struct bpf_xdp_link *dev_xdp_link(struct net_device *dev,
8896 enum bpf_xdp_mode mode)
8898 return dev->xdp_state[mode].link;
8901 static struct bpf_prog *dev_xdp_prog(struct net_device *dev,
8902 enum bpf_xdp_mode mode)
8904 struct bpf_xdp_link *link = dev_xdp_link(dev, mode);
8907 return link->link.prog;
8908 return dev->xdp_state[mode].prog;
8911 u32 dev_xdp_prog_id(struct net_device *dev, enum bpf_xdp_mode mode)
8913 struct bpf_prog *prog = dev_xdp_prog(dev, mode);
8915 return prog ? prog->aux->id : 0;
8918 static void dev_xdp_set_link(struct net_device *dev, enum bpf_xdp_mode mode,
8919 struct bpf_xdp_link *link)
8921 dev->xdp_state[mode].link = link;
8922 dev->xdp_state[mode].prog = NULL;
8925 static void dev_xdp_set_prog(struct net_device *dev, enum bpf_xdp_mode mode,
8926 struct bpf_prog *prog)
8928 dev->xdp_state[mode].link = NULL;
8929 dev->xdp_state[mode].prog = prog;
8932 static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,
8933 bpf_op_t bpf_op, struct netlink_ext_ack *extack,
8934 u32 flags, struct bpf_prog *prog)
8936 struct netdev_bpf xdp;
8939 memset(&xdp, 0, sizeof(xdp));
8940 xdp.command = mode == XDP_MODE_HW ? XDP_SETUP_PROG_HW : XDP_SETUP_PROG;
8941 xdp.extack = extack;
8945 /* Drivers assume refcnt is already incremented (i.e, prog pointer is
8946 * "moved" into driver), so they don't increment it on their own, but
8947 * they do decrement refcnt when program is detached or replaced.
8948 * Given net_device also owns link/prog, we need to bump refcnt here
8949 * to prevent drivers from underflowing it.
8953 err = bpf_op(dev, &xdp);
8960 if (mode != XDP_MODE_HW)
8961 bpf_prog_change_xdp(dev_xdp_prog(dev, mode), prog);
8966 static void dev_xdp_uninstall(struct net_device *dev)
8968 struct bpf_xdp_link *link;
8969 struct bpf_prog *prog;
8970 enum bpf_xdp_mode mode;
8975 for (mode = XDP_MODE_SKB; mode < __MAX_XDP_MODE; mode++) {
8976 prog = dev_xdp_prog(dev, mode);
8980 bpf_op = dev_xdp_bpf_op(dev, mode);
8984 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
8986 /* auto-detach link from net device */
8987 link = dev_xdp_link(dev, mode);
8993 dev_xdp_set_link(dev, mode, NULL);
8997 static int dev_xdp_attach(struct net_device *dev, struct netlink_ext_ack *extack,
8998 struct bpf_xdp_link *link, struct bpf_prog *new_prog,
8999 struct bpf_prog *old_prog, u32 flags)
9001 struct bpf_prog *cur_prog;
9002 enum bpf_xdp_mode mode;
9008 /* either link or prog attachment, never both */
9009 if (link && (new_prog || old_prog))
9011 /* link supports only XDP mode flags */
9012 if (link && (flags & ~XDP_FLAGS_MODES)) {
9013 NL_SET_ERR_MSG(extack, "Invalid XDP flags for BPF link attachment");
9016 /* just one XDP mode bit should be set, zero defaults to SKB mode */
9017 if (hweight32(flags & XDP_FLAGS_MODES) > 1) {
9018 NL_SET_ERR_MSG(extack, "Only one XDP mode flag can be set");
9021 /* old_prog != NULL implies XDP_FLAGS_REPLACE is set */
9022 if (old_prog && !(flags & XDP_FLAGS_REPLACE)) {
9023 NL_SET_ERR_MSG(extack, "XDP_FLAGS_REPLACE is not specified");
9027 mode = dev_xdp_mode(dev, flags);
9028 /* can't replace attached link */
9029 if (dev_xdp_link(dev, mode)) {
9030 NL_SET_ERR_MSG(extack, "Can't replace active BPF XDP link");
9034 cur_prog = dev_xdp_prog(dev, mode);
9035 /* can't replace attached prog with link */
9036 if (link && cur_prog) {
9037 NL_SET_ERR_MSG(extack, "Can't replace active XDP program with BPF link");
9040 if ((flags & XDP_FLAGS_REPLACE) && cur_prog != old_prog) {
9041 NL_SET_ERR_MSG(extack, "Active program does not match expected");
9045 /* put effective new program into new_prog */
9047 new_prog = link->link.prog;
9050 bool offload = mode == XDP_MODE_HW;
9051 enum bpf_xdp_mode other_mode = mode == XDP_MODE_SKB
9052 ? XDP_MODE_DRV : XDP_MODE_SKB;
9054 if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) && cur_prog) {
9055 NL_SET_ERR_MSG(extack, "XDP program already attached");
9058 if (!offload && dev_xdp_prog(dev, other_mode)) {
9059 NL_SET_ERR_MSG(extack, "Native and generic XDP can't be active at the same time");
9062 if (!offload && bpf_prog_is_dev_bound(new_prog->aux)) {
9063 NL_SET_ERR_MSG(extack, "Using device-bound program without HW_MODE flag is not supported");
9066 if (new_prog->expected_attach_type == BPF_XDP_DEVMAP) {
9067 NL_SET_ERR_MSG(extack, "BPF_XDP_DEVMAP programs can not be attached to a device");
9070 if (new_prog->expected_attach_type == BPF_XDP_CPUMAP) {
9071 NL_SET_ERR_MSG(extack, "BPF_XDP_CPUMAP programs can not be attached to a device");
9076 /* don't call drivers if the effective program didn't change */
9077 if (new_prog != cur_prog) {
9078 bpf_op = dev_xdp_bpf_op(dev, mode);
9080 NL_SET_ERR_MSG(extack, "Underlying driver does not support XDP in native mode");
9084 err = dev_xdp_install(dev, mode, bpf_op, extack, flags, new_prog);
9090 dev_xdp_set_link(dev, mode, link);
9092 dev_xdp_set_prog(dev, mode, new_prog);
9094 bpf_prog_put(cur_prog);
9099 static int dev_xdp_attach_link(struct net_device *dev,
9100 struct netlink_ext_ack *extack,
9101 struct bpf_xdp_link *link)
9103 return dev_xdp_attach(dev, extack, link, NULL, NULL, link->flags);
9106 static int dev_xdp_detach_link(struct net_device *dev,
9107 struct netlink_ext_ack *extack,
9108 struct bpf_xdp_link *link)
9110 enum bpf_xdp_mode mode;
9115 mode = dev_xdp_mode(dev, link->flags);
9116 if (dev_xdp_link(dev, mode) != link)
9119 bpf_op = dev_xdp_bpf_op(dev, mode);
9120 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
9121 dev_xdp_set_link(dev, mode, NULL);
9125 static void bpf_xdp_link_release(struct bpf_link *link)
9127 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9131 /* if racing with net_device's tear down, xdp_link->dev might be
9132 * already NULL, in which case link was already auto-detached
9134 if (xdp_link->dev) {
9135 WARN_ON(dev_xdp_detach_link(xdp_link->dev, NULL, xdp_link));
9136 xdp_link->dev = NULL;
9142 static int bpf_xdp_link_detach(struct bpf_link *link)
9144 bpf_xdp_link_release(link);
9148 static void bpf_xdp_link_dealloc(struct bpf_link *link)
9150 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9155 static void bpf_xdp_link_show_fdinfo(const struct bpf_link *link,
9156 struct seq_file *seq)
9158 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9163 ifindex = xdp_link->dev->ifindex;
9166 seq_printf(seq, "ifindex:\t%u\n", ifindex);
9169 static int bpf_xdp_link_fill_link_info(const struct bpf_link *link,
9170 struct bpf_link_info *info)
9172 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9177 ifindex = xdp_link->dev->ifindex;
9180 info->xdp.ifindex = ifindex;
9184 static int bpf_xdp_link_update(struct bpf_link *link, struct bpf_prog *new_prog,
9185 struct bpf_prog *old_prog)
9187 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9188 enum bpf_xdp_mode mode;
9194 /* link might have been auto-released already, so fail */
9195 if (!xdp_link->dev) {
9200 if (old_prog && link->prog != old_prog) {
9204 old_prog = link->prog;
9205 if (old_prog == new_prog) {
9206 /* no-op, don't disturb drivers */
9207 bpf_prog_put(new_prog);
9211 mode = dev_xdp_mode(xdp_link->dev, xdp_link->flags);
9212 bpf_op = dev_xdp_bpf_op(xdp_link->dev, mode);
9213 err = dev_xdp_install(xdp_link->dev, mode, bpf_op, NULL,
9214 xdp_link->flags, new_prog);
9218 old_prog = xchg(&link->prog, new_prog);
9219 bpf_prog_put(old_prog);
9226 static const struct bpf_link_ops bpf_xdp_link_lops = {
9227 .release = bpf_xdp_link_release,
9228 .dealloc = bpf_xdp_link_dealloc,
9229 .detach = bpf_xdp_link_detach,
9230 .show_fdinfo = bpf_xdp_link_show_fdinfo,
9231 .fill_link_info = bpf_xdp_link_fill_link_info,
9232 .update_prog = bpf_xdp_link_update,
9235 int bpf_xdp_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
9237 struct net *net = current->nsproxy->net_ns;
9238 struct bpf_link_primer link_primer;
9239 struct bpf_xdp_link *link;
9240 struct net_device *dev;
9243 dev = dev_get_by_index(net, attr->link_create.target_ifindex);
9247 link = kzalloc(sizeof(*link), GFP_USER);
9253 bpf_link_init(&link->link, BPF_LINK_TYPE_XDP, &bpf_xdp_link_lops, prog);
9255 link->flags = attr->link_create.flags;
9257 err = bpf_link_prime(&link->link, &link_primer);
9264 err = dev_xdp_attach_link(dev, NULL, link);
9268 bpf_link_cleanup(&link_primer);
9272 fd = bpf_link_settle(&link_primer);
9273 /* link itself doesn't hold dev's refcnt to not complicate shutdown */
9283 * dev_change_xdp_fd - set or clear a bpf program for a device rx path
9285 * @extack: netlink extended ack
9286 * @fd: new program fd or negative value to clear
9287 * @expected_fd: old program fd that userspace expects to replace or clear
9288 * @flags: xdp-related flags
9290 * Set or clear a bpf program for a device
9292 int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack,
9293 int fd, int expected_fd, u32 flags)
9295 enum bpf_xdp_mode mode = dev_xdp_mode(dev, flags);
9296 struct bpf_prog *new_prog = NULL, *old_prog = NULL;
9302 new_prog = bpf_prog_get_type_dev(fd, BPF_PROG_TYPE_XDP,
9303 mode != XDP_MODE_SKB);
9304 if (IS_ERR(new_prog))
9305 return PTR_ERR(new_prog);
9308 if (expected_fd >= 0) {
9309 old_prog = bpf_prog_get_type_dev(expected_fd, BPF_PROG_TYPE_XDP,
9310 mode != XDP_MODE_SKB);
9311 if (IS_ERR(old_prog)) {
9312 err = PTR_ERR(old_prog);
9318 err = dev_xdp_attach(dev, extack, NULL, new_prog, old_prog, flags);
9321 if (err && new_prog)
9322 bpf_prog_put(new_prog);
9324 bpf_prog_put(old_prog);
9329 * dev_new_index - allocate an ifindex
9330 * @net: the applicable net namespace
9332 * Returns a suitable unique value for a new device interface
9333 * number. The caller must hold the rtnl semaphore or the
9334 * dev_base_lock to be sure it remains unique.
9336 static int dev_new_index(struct net *net)
9338 int ifindex = net->ifindex;
9343 if (!__dev_get_by_index(net, ifindex))
9344 return net->ifindex = ifindex;
9348 /* Delayed registration/unregisteration */
9349 static LIST_HEAD(net_todo_list);
9350 DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq);
9352 static void net_set_todo(struct net_device *dev)
9354 list_add_tail(&dev->todo_list, &net_todo_list);
9355 dev_net(dev)->dev_unreg_count++;
9358 static void rollback_registered_many(struct list_head *head)
9360 struct net_device *dev, *tmp;
9361 LIST_HEAD(close_head);
9363 BUG_ON(dev_boot_phase);
9366 list_for_each_entry_safe(dev, tmp, head, unreg_list) {
9367 /* Some devices call without registering
9368 * for initialization unwind. Remove those
9369 * devices and proceed with the remaining.
9371 if (dev->reg_state == NETREG_UNINITIALIZED) {
9372 pr_debug("unregister_netdevice: device %s/%p never was registered\n",
9376 list_del(&dev->unreg_list);
9379 dev->dismantle = true;
9380 BUG_ON(dev->reg_state != NETREG_REGISTERED);
9383 /* If device is running, close it first. */
9384 list_for_each_entry(dev, head, unreg_list)
9385 list_add_tail(&dev->close_list, &close_head);
9386 dev_close_many(&close_head, true);
9388 list_for_each_entry(dev, head, unreg_list) {
9389 /* And unlink it from device chain. */
9390 unlist_netdevice(dev);
9392 dev->reg_state = NETREG_UNREGISTERING;
9394 flush_all_backlogs();
9398 list_for_each_entry(dev, head, unreg_list) {
9399 struct sk_buff *skb = NULL;
9401 /* Shutdown queueing discipline. */
9404 dev_xdp_uninstall(dev);
9406 /* Notify protocols, that we are about to destroy
9407 * this device. They should clean all the things.
9409 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
9411 if (!dev->rtnl_link_ops ||
9412 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
9413 skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0,
9414 GFP_KERNEL, NULL, 0);
9417 * Flush the unicast and multicast chains
9422 netdev_name_node_alt_flush(dev);
9423 netdev_name_node_free(dev->name_node);
9425 if (dev->netdev_ops->ndo_uninit)
9426 dev->netdev_ops->ndo_uninit(dev);
9429 rtmsg_ifinfo_send(skb, dev, GFP_KERNEL);
9431 /* Notifier chain MUST detach us all upper devices. */
9432 WARN_ON(netdev_has_any_upper_dev(dev));
9433 WARN_ON(netdev_has_any_lower_dev(dev));
9435 /* Remove entries from kobject tree */
9436 netdev_unregister_kobject(dev);
9438 /* Remove XPS queueing entries */
9439 netif_reset_xps_queues_gt(dev, 0);
9445 list_for_each_entry(dev, head, unreg_list)
9449 static void rollback_registered(struct net_device *dev)
9453 list_add(&dev->unreg_list, &single);
9454 rollback_registered_many(&single);
9458 static netdev_features_t netdev_sync_upper_features(struct net_device *lower,
9459 struct net_device *upper, netdev_features_t features)
9461 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
9462 netdev_features_t feature;
9465 for_each_netdev_feature(upper_disables, feature_bit) {
9466 feature = __NETIF_F_BIT(feature_bit);
9467 if (!(upper->wanted_features & feature)
9468 && (features & feature)) {
9469 netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n",
9470 &feature, upper->name);
9471 features &= ~feature;
9478 static void netdev_sync_lower_features(struct net_device *upper,
9479 struct net_device *lower, netdev_features_t features)
9481 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
9482 netdev_features_t feature;
9485 for_each_netdev_feature(upper_disables, feature_bit) {
9486 feature = __NETIF_F_BIT(feature_bit);
9487 if (!(features & feature) && (lower->features & feature)) {
9488 netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n",
9489 &feature, lower->name);
9490 lower->wanted_features &= ~feature;
9491 __netdev_update_features(lower);
9493 if (unlikely(lower->features & feature))
9494 netdev_WARN(upper, "failed to disable %pNF on %s!\n",
9495 &feature, lower->name);
9497 netdev_features_change(lower);
9502 static netdev_features_t netdev_fix_features(struct net_device *dev,
9503 netdev_features_t features)
9505 /* Fix illegal checksum combinations */
9506 if ((features & NETIF_F_HW_CSUM) &&
9507 (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
9508 netdev_warn(dev, "mixed HW and IP checksum settings.\n");
9509 features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM);
9512 /* TSO requires that SG is present as well. */
9513 if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) {
9514 netdev_dbg(dev, "Dropping TSO features since no SG feature.\n");
9515 features &= ~NETIF_F_ALL_TSO;
9518 if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) &&
9519 !(features & NETIF_F_IP_CSUM)) {
9520 netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n");
9521 features &= ~NETIF_F_TSO;
9522 features &= ~NETIF_F_TSO_ECN;
9525 if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) &&
9526 !(features & NETIF_F_IPV6_CSUM)) {
9527 netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n");
9528 features &= ~NETIF_F_TSO6;
9531 /* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */
9532 if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO))
9533 features &= ~NETIF_F_TSO_MANGLEID;
9535 /* TSO ECN requires that TSO is present as well. */
9536 if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN)
9537 features &= ~NETIF_F_TSO_ECN;
9539 /* Software GSO depends on SG. */
9540 if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) {
9541 netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n");
9542 features &= ~NETIF_F_GSO;
9545 /* GSO partial features require GSO partial be set */
9546 if ((features & dev->gso_partial_features) &&
9547 !(features & NETIF_F_GSO_PARTIAL)) {
9549 "Dropping partially supported GSO features since no GSO partial.\n");
9550 features &= ~dev->gso_partial_features;
9553 if (!(features & NETIF_F_RXCSUM)) {
9554 /* NETIF_F_GRO_HW implies doing RXCSUM since every packet
9555 * successfully merged by hardware must also have the
9556 * checksum verified by hardware. If the user does not
9557 * want to enable RXCSUM, logically, we should disable GRO_HW.
9559 if (features & NETIF_F_GRO_HW) {
9560 netdev_dbg(dev, "Dropping NETIF_F_GRO_HW since no RXCSUM feature.\n");
9561 features &= ~NETIF_F_GRO_HW;
9565 /* LRO/HW-GRO features cannot be combined with RX-FCS */
9566 if (features & NETIF_F_RXFCS) {
9567 if (features & NETIF_F_LRO) {
9568 netdev_dbg(dev, "Dropping LRO feature since RX-FCS is requested.\n");
9569 features &= ~NETIF_F_LRO;
9572 if (features & NETIF_F_GRO_HW) {
9573 netdev_dbg(dev, "Dropping HW-GRO feature since RX-FCS is requested.\n");
9574 features &= ~NETIF_F_GRO_HW;
9581 int __netdev_update_features(struct net_device *dev)
9583 struct net_device *upper, *lower;
9584 netdev_features_t features;
9585 struct list_head *iter;
9590 features = netdev_get_wanted_features(dev);
9592 if (dev->netdev_ops->ndo_fix_features)
9593 features = dev->netdev_ops->ndo_fix_features(dev, features);
9595 /* driver might be less strict about feature dependencies */
9596 features = netdev_fix_features(dev, features);
9598 /* some features can't be enabled if they're off on an upper device */
9599 netdev_for_each_upper_dev_rcu(dev, upper, iter)
9600 features = netdev_sync_upper_features(dev, upper, features);
9602 if (dev->features == features)
9605 netdev_dbg(dev, "Features changed: %pNF -> %pNF\n",
9606 &dev->features, &features);
9608 if (dev->netdev_ops->ndo_set_features)
9609 err = dev->netdev_ops->ndo_set_features(dev, features);
9613 if (unlikely(err < 0)) {
9615 "set_features() failed (%d); wanted %pNF, left %pNF\n",
9616 err, &features, &dev->features);
9617 /* return non-0 since some features might have changed and
9618 * it's better to fire a spurious notification than miss it
9624 /* some features must be disabled on lower devices when disabled
9625 * on an upper device (think: bonding master or bridge)
9627 netdev_for_each_lower_dev(dev, lower, iter)
9628 netdev_sync_lower_features(dev, lower, features);
9631 netdev_features_t diff = features ^ dev->features;
9633 if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) {
9634 /* udp_tunnel_{get,drop}_rx_info both need
9635 * NETIF_F_RX_UDP_TUNNEL_PORT enabled on the
9636 * device, or they won't do anything.
9637 * Thus we need to update dev->features
9638 * *before* calling udp_tunnel_get_rx_info,
9639 * but *after* calling udp_tunnel_drop_rx_info.
9641 if (features & NETIF_F_RX_UDP_TUNNEL_PORT) {
9642 dev->features = features;
9643 udp_tunnel_get_rx_info(dev);
9645 udp_tunnel_drop_rx_info(dev);
9649 if (diff & NETIF_F_HW_VLAN_CTAG_FILTER) {
9650 if (features & NETIF_F_HW_VLAN_CTAG_FILTER) {
9651 dev->features = features;
9652 err |= vlan_get_rx_ctag_filter_info(dev);
9654 vlan_drop_rx_ctag_filter_info(dev);
9658 if (diff & NETIF_F_HW_VLAN_STAG_FILTER) {
9659 if (features & NETIF_F_HW_VLAN_STAG_FILTER) {
9660 dev->features = features;
9661 err |= vlan_get_rx_stag_filter_info(dev);
9663 vlan_drop_rx_stag_filter_info(dev);
9667 dev->features = features;
9670 return err < 0 ? 0 : 1;
9674 * netdev_update_features - recalculate device features
9675 * @dev: the device to check
9677 * Recalculate dev->features set and send notifications if it
9678 * has changed. Should be called after driver or hardware dependent
9679 * conditions might have changed that influence the features.
9681 void netdev_update_features(struct net_device *dev)
9683 if (__netdev_update_features(dev))
9684 netdev_features_change(dev);
9686 EXPORT_SYMBOL(netdev_update_features);
9689 * netdev_change_features - recalculate device features
9690 * @dev: the device to check
9692 * Recalculate dev->features set and send notifications even
9693 * if they have not changed. Should be called instead of
9694 * netdev_update_features() if also dev->vlan_features might
9695 * have changed to allow the changes to be propagated to stacked
9698 void netdev_change_features(struct net_device *dev)
9700 __netdev_update_features(dev);
9701 netdev_features_change(dev);
9703 EXPORT_SYMBOL(netdev_change_features);
9706 * netif_stacked_transfer_operstate - transfer operstate
9707 * @rootdev: the root or lower level device to transfer state from
9708 * @dev: the device to transfer operstate to
9710 * Transfer operational state from root to device. This is normally
9711 * called when a stacking relationship exists between the root
9712 * device and the device(a leaf device).
9714 void netif_stacked_transfer_operstate(const struct net_device *rootdev,
9715 struct net_device *dev)
9717 if (rootdev->operstate == IF_OPER_DORMANT)
9718 netif_dormant_on(dev);
9720 netif_dormant_off(dev);
9722 if (rootdev->operstate == IF_OPER_TESTING)
9723 netif_testing_on(dev);
9725 netif_testing_off(dev);
9727 if (netif_carrier_ok(rootdev))
9728 netif_carrier_on(dev);
9730 netif_carrier_off(dev);
9732 EXPORT_SYMBOL(netif_stacked_transfer_operstate);
9734 static int netif_alloc_rx_queues(struct net_device *dev)
9736 unsigned int i, count = dev->num_rx_queues;
9737 struct netdev_rx_queue *rx;
9738 size_t sz = count * sizeof(*rx);
9743 rx = kvzalloc(sz, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
9749 for (i = 0; i < count; i++) {
9752 /* XDP RX-queue setup */
9753 err = xdp_rxq_info_reg(&rx[i].xdp_rxq, dev, i);
9760 /* Rollback successful reg's and free other resources */
9762 xdp_rxq_info_unreg(&rx[i].xdp_rxq);
9768 static void netif_free_rx_queues(struct net_device *dev)
9770 unsigned int i, count = dev->num_rx_queues;
9772 /* netif_alloc_rx_queues alloc failed, resources have been unreg'ed */
9776 for (i = 0; i < count; i++)
9777 xdp_rxq_info_unreg(&dev->_rx[i].xdp_rxq);
9782 static void netdev_init_one_queue(struct net_device *dev,
9783 struct netdev_queue *queue, void *_unused)
9785 /* Initialize queue lock */
9786 spin_lock_init(&queue->_xmit_lock);
9787 netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type);
9788 queue->xmit_lock_owner = -1;
9789 netdev_queue_numa_node_write(queue, NUMA_NO_NODE);
9792 dql_init(&queue->dql, HZ);
9796 static void netif_free_tx_queues(struct net_device *dev)
9801 static int netif_alloc_netdev_queues(struct net_device *dev)
9803 unsigned int count = dev->num_tx_queues;
9804 struct netdev_queue *tx;
9805 size_t sz = count * sizeof(*tx);
9807 if (count < 1 || count > 0xffff)
9810 tx = kvzalloc(sz, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
9816 netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL);
9817 spin_lock_init(&dev->tx_global_lock);
9822 void netif_tx_stop_all_queues(struct net_device *dev)
9826 for (i = 0; i < dev->num_tx_queues; i++) {
9827 struct netdev_queue *txq = netdev_get_tx_queue(dev, i);
9829 netif_tx_stop_queue(txq);
9832 EXPORT_SYMBOL(netif_tx_stop_all_queues);
9835 * register_netdevice - register a network device
9836 * @dev: device to register
9838 * Take a completed network device structure and add it to the kernel
9839 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
9840 * chain. 0 is returned on success. A negative errno code is returned
9841 * on a failure to set up the device, or if the name is a duplicate.
9843 * Callers must hold the rtnl semaphore. You may want
9844 * register_netdev() instead of this.
9847 * The locking appears insufficient to guarantee two parallel registers
9848 * will not get the same name.
9851 int register_netdevice(struct net_device *dev)
9854 struct net *net = dev_net(dev);
9856 BUILD_BUG_ON(sizeof(netdev_features_t) * BITS_PER_BYTE <
9857 NETDEV_FEATURE_COUNT);
9858 BUG_ON(dev_boot_phase);
9863 /* When net_device's are persistent, this will be fatal. */
9864 BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
9867 ret = ethtool_check_ops(dev->ethtool_ops);
9871 spin_lock_init(&dev->addr_list_lock);
9872 netdev_set_addr_lockdep_class(dev);
9874 ret = dev_get_valid_name(net, dev, dev->name);
9879 dev->name_node = netdev_name_node_head_alloc(dev);
9880 if (!dev->name_node)
9883 /* Init, if this function is available */
9884 if (dev->netdev_ops->ndo_init) {
9885 ret = dev->netdev_ops->ndo_init(dev);
9893 if (((dev->hw_features | dev->features) &
9894 NETIF_F_HW_VLAN_CTAG_FILTER) &&
9895 (!dev->netdev_ops->ndo_vlan_rx_add_vid ||
9896 !dev->netdev_ops->ndo_vlan_rx_kill_vid)) {
9897 netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n");
9904 dev->ifindex = dev_new_index(net);
9905 else if (__dev_get_by_index(net, dev->ifindex))
9908 /* Transfer changeable features to wanted_features and enable
9909 * software offloads (GSO and GRO).
9911 dev->hw_features |= (NETIF_F_SOFT_FEATURES | NETIF_F_SOFT_FEATURES_OFF);
9912 dev->features |= NETIF_F_SOFT_FEATURES;
9914 if (dev->netdev_ops->ndo_udp_tunnel_add) {
9915 dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT;
9916 dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT;
9919 dev->wanted_features = dev->features & dev->hw_features;
9921 if (!(dev->flags & IFF_LOOPBACK))
9922 dev->hw_features |= NETIF_F_NOCACHE_COPY;
9924 /* If IPv4 TCP segmentation offload is supported we should also
9925 * allow the device to enable segmenting the frame with the option
9926 * of ignoring a static IP ID value. This doesn't enable the
9927 * feature itself but allows the user to enable it later.
9929 if (dev->hw_features & NETIF_F_TSO)
9930 dev->hw_features |= NETIF_F_TSO_MANGLEID;
9931 if (dev->vlan_features & NETIF_F_TSO)
9932 dev->vlan_features |= NETIF_F_TSO_MANGLEID;
9933 if (dev->mpls_features & NETIF_F_TSO)
9934 dev->mpls_features |= NETIF_F_TSO_MANGLEID;
9935 if (dev->hw_enc_features & NETIF_F_TSO)
9936 dev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
9938 /* Make NETIF_F_HIGHDMA inheritable to VLAN devices.
9940 dev->vlan_features |= NETIF_F_HIGHDMA;
9942 /* Make NETIF_F_SG inheritable to tunnel devices.
9944 dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL;
9946 /* Make NETIF_F_SG inheritable to MPLS.
9948 dev->mpls_features |= NETIF_F_SG;
9950 ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev);
9951 ret = notifier_to_errno(ret);
9955 ret = netdev_register_kobject(dev);
9957 dev->reg_state = NETREG_UNREGISTERED;
9960 dev->reg_state = NETREG_REGISTERED;
9962 __netdev_update_features(dev);
9965 * Default initial state at registry is that the
9966 * device is present.
9969 set_bit(__LINK_STATE_PRESENT, &dev->state);
9971 linkwatch_init_dev(dev);
9973 dev_init_scheduler(dev);
9975 list_netdevice(dev);
9976 add_device_randomness(dev->dev_addr, dev->addr_len);
9978 /* If the device has permanent device address, driver should
9979 * set dev_addr and also addr_assign_type should be set to
9980 * NET_ADDR_PERM (default value).
9982 if (dev->addr_assign_type == NET_ADDR_PERM)
9983 memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
9985 /* Notify protocols, that a new device appeared. */
9986 ret = call_netdevice_notifiers(NETDEV_REGISTER, dev);
9987 ret = notifier_to_errno(ret);
9989 rollback_registered(dev);
9992 dev->reg_state = NETREG_UNREGISTERED;
9993 /* We should put the kobject that hold in
9994 * netdev_unregister_kobject(), otherwise
9995 * the net device cannot be freed when
9996 * driver calls free_netdev(), because the
9997 * kobject is being hold.
9999 kobject_put(&dev->dev.kobj);
10002 * Prevent userspace races by waiting until the network
10003 * device is fully setup before sending notifications.
10005 if (!dev->rtnl_link_ops ||
10006 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
10007 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL);
10013 if (dev->netdev_ops->ndo_uninit)
10014 dev->netdev_ops->ndo_uninit(dev);
10015 if (dev->priv_destructor)
10016 dev->priv_destructor(dev);
10018 netdev_name_node_free(dev->name_node);
10021 EXPORT_SYMBOL(register_netdevice);
10024 * init_dummy_netdev - init a dummy network device for NAPI
10025 * @dev: device to init
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.
10033 int init_dummy_netdev(struct net_device *dev)
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
10040 memset(dev, 0, sizeof(struct net_device));
10042 /* make sure we BUG if trying to hit standard
10043 * register/unregister code path
10045 dev->reg_state = NETREG_DUMMY;
10047 /* NAPI wants this */
10048 INIT_LIST_HEAD(&dev->napi_list);
10050 /* a dummy interface is started by default */
10051 set_bit(__LINK_STATE_PRESENT, &dev->state);
10052 set_bit(__LINK_STATE_START, &dev->state);
10054 /* napi_busy_loop stats accounting wants this */
10055 dev_net_set(dev, &init_net);
10057 /* Note : We dont allocate pcpu_refcnt for dummy devices,
10058 * because users of this 'device' dont need to change
10064 EXPORT_SYMBOL_GPL(init_dummy_netdev);
10068 * register_netdev - register a network device
10069 * @dev: device to register
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.
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
10080 int register_netdev(struct net_device *dev)
10084 if (rtnl_lock_killable())
10086 err = register_netdevice(dev);
10090 EXPORT_SYMBOL(register_netdev);
10092 int netdev_refcnt_read(const struct net_device *dev)
10096 for_each_possible_cpu(i)
10097 refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i);
10100 EXPORT_SYMBOL(netdev_refcnt_read);
10102 #define WAIT_REFS_MIN_MSECS 1
10103 #define WAIT_REFS_MAX_MSECS 250
10105 * netdev_wait_allrefs - wait until all references are gone.
10106 * @dev: target net_device
10108 * This is called when unregistering network devices.
10110 * Any protocol or device that holds a reference should register
10111 * for netdevice notification, and cleanup and put back the
10112 * reference if they receive an UNREGISTER event.
10113 * We can get stuck here if buggy protocols don't correctly
10116 static void netdev_wait_allrefs(struct net_device *dev)
10118 unsigned long rebroadcast_time, warning_time;
10119 int wait = 0, refcnt;
10121 linkwatch_forget_dev(dev);
10123 rebroadcast_time = warning_time = jiffies;
10124 refcnt = netdev_refcnt_read(dev);
10126 while (refcnt != 0) {
10127 if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
10130 /* Rebroadcast unregister notification */
10131 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10137 if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
10139 /* We must not have linkwatch events
10140 * pending on unregister. If this
10141 * happens, we simply run the queue
10142 * unscheduled, resulting in a noop
10145 linkwatch_run_queue();
10150 rebroadcast_time = jiffies;
10155 wait = WAIT_REFS_MIN_MSECS;
10158 wait = min(wait << 1, WAIT_REFS_MAX_MSECS);
10161 refcnt = netdev_refcnt_read(dev);
10163 if (refcnt && time_after(jiffies, warning_time + 10 * HZ)) {
10164 pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n",
10165 dev->name, refcnt);
10166 warning_time = jiffies;
10171 /* The sequence is:
10175 * register_netdevice(x1);
10176 * register_netdevice(x2);
10178 * unregister_netdevice(y1);
10179 * unregister_netdevice(y2);
10185 * We are invoked by rtnl_unlock().
10186 * This allows us to deal with problems:
10187 * 1) We can delete sysfs objects which invoke hotplug
10188 * without deadlocking with linkwatch via keventd.
10189 * 2) Since we run with the RTNL semaphore not held, we can sleep
10190 * safely in order to wait for the netdev refcnt to drop to zero.
10192 * We must not return until all unregister events added during
10193 * the interval the lock was held have been completed.
10195 void netdev_run_todo(void)
10197 struct list_head list;
10198 #ifdef CONFIG_LOCKDEP
10199 struct list_head unlink_list;
10201 list_replace_init(&net_unlink_list, &unlink_list);
10203 while (!list_empty(&unlink_list)) {
10204 struct net_device *dev = list_first_entry(&unlink_list,
10207 list_del(&dev->unlink_list);
10208 dev->nested_level = dev->lower_level - 1;
10212 /* Snapshot list, allow later requests */
10213 list_replace_init(&net_todo_list, &list);
10218 /* Wait for rcu callbacks to finish before next phase */
10219 if (!list_empty(&list))
10222 while (!list_empty(&list)) {
10223 struct net_device *dev
10224 = list_first_entry(&list, struct net_device, todo_list);
10225 list_del(&dev->todo_list);
10227 if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) {
10228 pr_err("network todo '%s' but state %d\n",
10229 dev->name, dev->reg_state);
10234 dev->reg_state = NETREG_UNREGISTERED;
10236 netdev_wait_allrefs(dev);
10239 BUG_ON(netdev_refcnt_read(dev));
10240 BUG_ON(!list_empty(&dev->ptype_all));
10241 BUG_ON(!list_empty(&dev->ptype_specific));
10242 WARN_ON(rcu_access_pointer(dev->ip_ptr));
10243 WARN_ON(rcu_access_pointer(dev->ip6_ptr));
10244 #if IS_ENABLED(CONFIG_DECNET)
10245 WARN_ON(dev->dn_ptr);
10247 if (dev->priv_destructor)
10248 dev->priv_destructor(dev);
10249 if (dev->needs_free_netdev)
10252 /* Report a network device has been unregistered */
10254 dev_net(dev)->dev_unreg_count--;
10256 wake_up(&netdev_unregistering_wq);
10258 /* Free network device */
10259 kobject_put(&dev->dev.kobj);
10263 /* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has
10264 * all the same fields in the same order as net_device_stats, with only
10265 * the type differing, but rtnl_link_stats64 may have additional fields
10266 * at the end for newer counters.
10268 void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64,
10269 const struct net_device_stats *netdev_stats)
10271 #if BITS_PER_LONG == 64
10272 BUILD_BUG_ON(sizeof(*stats64) < sizeof(*netdev_stats));
10273 memcpy(stats64, netdev_stats, sizeof(*netdev_stats));
10274 /* zero out counters that only exist in rtnl_link_stats64 */
10275 memset((char *)stats64 + sizeof(*netdev_stats), 0,
10276 sizeof(*stats64) - sizeof(*netdev_stats));
10278 size_t i, n = sizeof(*netdev_stats) / sizeof(unsigned long);
10279 const unsigned long *src = (const unsigned long *)netdev_stats;
10280 u64 *dst = (u64 *)stats64;
10282 BUILD_BUG_ON(n > sizeof(*stats64) / sizeof(u64));
10283 for (i = 0; i < n; i++)
10285 /* zero out counters that only exist in rtnl_link_stats64 */
10286 memset((char *)stats64 + n * sizeof(u64), 0,
10287 sizeof(*stats64) - n * sizeof(u64));
10290 EXPORT_SYMBOL(netdev_stats_to_stats64);
10293 * dev_get_stats - get network device statistics
10294 * @dev: device to get statistics from
10295 * @storage: place to store stats
10297 * Get network statistics from device. Return @storage.
10298 * The device driver may provide its own method by setting
10299 * dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats;
10300 * otherwise the internal statistics structure is used.
10302 struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev,
10303 struct rtnl_link_stats64 *storage)
10305 const struct net_device_ops *ops = dev->netdev_ops;
10307 if (ops->ndo_get_stats64) {
10308 memset(storage, 0, sizeof(*storage));
10309 ops->ndo_get_stats64(dev, storage);
10310 } else if (ops->ndo_get_stats) {
10311 netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev));
10313 netdev_stats_to_stats64(storage, &dev->stats);
10315 storage->rx_dropped += (unsigned long)atomic_long_read(&dev->rx_dropped);
10316 storage->tx_dropped += (unsigned long)atomic_long_read(&dev->tx_dropped);
10317 storage->rx_nohandler += (unsigned long)atomic_long_read(&dev->rx_nohandler);
10320 EXPORT_SYMBOL(dev_get_stats);
10322 struct netdev_queue *dev_ingress_queue_create(struct net_device *dev)
10324 struct netdev_queue *queue = dev_ingress_queue(dev);
10326 #ifdef CONFIG_NET_CLS_ACT
10329 queue = kzalloc(sizeof(*queue), GFP_KERNEL);
10332 netdev_init_one_queue(dev, queue, NULL);
10333 RCU_INIT_POINTER(queue->qdisc, &noop_qdisc);
10334 queue->qdisc_sleeping = &noop_qdisc;
10335 rcu_assign_pointer(dev->ingress_queue, queue);
10340 static const struct ethtool_ops default_ethtool_ops;
10342 void netdev_set_default_ethtool_ops(struct net_device *dev,
10343 const struct ethtool_ops *ops)
10345 if (dev->ethtool_ops == &default_ethtool_ops)
10346 dev->ethtool_ops = ops;
10348 EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops);
10350 void netdev_freemem(struct net_device *dev)
10352 char *addr = (char *)dev - dev->padded;
10358 * alloc_netdev_mqs - allocate network device
10359 * @sizeof_priv: size of private data to allocate space for
10360 * @name: device name format string
10361 * @name_assign_type: origin of device name
10362 * @setup: callback to initialize device
10363 * @txqs: the number of TX subqueues to allocate
10364 * @rxqs: the number of RX subqueues to allocate
10366 * Allocates a struct net_device with private data area for driver use
10367 * and performs basic initialization. Also allocates subqueue structs
10368 * for each queue on the device.
10370 struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name,
10371 unsigned char name_assign_type,
10372 void (*setup)(struct net_device *),
10373 unsigned int txqs, unsigned int rxqs)
10375 struct net_device *dev;
10376 unsigned int alloc_size;
10377 struct net_device *p;
10379 BUG_ON(strlen(name) >= sizeof(dev->name));
10382 pr_err("alloc_netdev: Unable to allocate device with zero queues\n");
10387 pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n");
10391 alloc_size = sizeof(struct net_device);
10393 /* ensure 32-byte alignment of private area */
10394 alloc_size = ALIGN(alloc_size, NETDEV_ALIGN);
10395 alloc_size += sizeof_priv;
10397 /* ensure 32-byte alignment of whole construct */
10398 alloc_size += NETDEV_ALIGN - 1;
10400 p = kvzalloc(alloc_size, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
10404 dev = PTR_ALIGN(p, NETDEV_ALIGN);
10405 dev->padded = (char *)dev - (char *)p;
10407 dev->pcpu_refcnt = alloc_percpu(int);
10408 if (!dev->pcpu_refcnt)
10411 if (dev_addr_init(dev))
10417 dev_net_set(dev, &init_net);
10419 dev->gso_max_size = GSO_MAX_SIZE;
10420 dev->gso_max_segs = GSO_MAX_SEGS;
10421 dev->upper_level = 1;
10422 dev->lower_level = 1;
10423 #ifdef CONFIG_LOCKDEP
10424 dev->nested_level = 0;
10425 INIT_LIST_HEAD(&dev->unlink_list);
10428 INIT_LIST_HEAD(&dev->napi_list);
10429 INIT_LIST_HEAD(&dev->unreg_list);
10430 INIT_LIST_HEAD(&dev->close_list);
10431 INIT_LIST_HEAD(&dev->link_watch_list);
10432 INIT_LIST_HEAD(&dev->adj_list.upper);
10433 INIT_LIST_HEAD(&dev->adj_list.lower);
10434 INIT_LIST_HEAD(&dev->ptype_all);
10435 INIT_LIST_HEAD(&dev->ptype_specific);
10436 INIT_LIST_HEAD(&dev->net_notifier_list);
10437 #ifdef CONFIG_NET_SCHED
10438 hash_init(dev->qdisc_hash);
10440 dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM;
10443 if (!dev->tx_queue_len) {
10444 dev->priv_flags |= IFF_NO_QUEUE;
10445 dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN;
10448 dev->num_tx_queues = txqs;
10449 dev->real_num_tx_queues = txqs;
10450 if (netif_alloc_netdev_queues(dev))
10453 dev->num_rx_queues = rxqs;
10454 dev->real_num_rx_queues = rxqs;
10455 if (netif_alloc_rx_queues(dev))
10458 strcpy(dev->name, name);
10459 dev->name_assign_type = name_assign_type;
10460 dev->group = INIT_NETDEV_GROUP;
10461 if (!dev->ethtool_ops)
10462 dev->ethtool_ops = &default_ethtool_ops;
10464 nf_hook_ingress_init(dev);
10473 free_percpu(dev->pcpu_refcnt);
10475 netdev_freemem(dev);
10478 EXPORT_SYMBOL(alloc_netdev_mqs);
10481 * free_netdev - free network device
10484 * This function does the last stage of destroying an allocated device
10485 * interface. The reference to the device object is released. If this
10486 * is the last reference then it will be freed.Must be called in process
10489 void free_netdev(struct net_device *dev)
10491 struct napi_struct *p, *n;
10494 netif_free_tx_queues(dev);
10495 netif_free_rx_queues(dev);
10497 kfree(rcu_dereference_protected(dev->ingress_queue, 1));
10499 /* Flush device addresses */
10500 dev_addr_flush(dev);
10502 list_for_each_entry_safe(p, n, &dev->napi_list, dev_list)
10505 free_percpu(dev->pcpu_refcnt);
10506 dev->pcpu_refcnt = NULL;
10507 free_percpu(dev->xdp_bulkq);
10508 dev->xdp_bulkq = NULL;
10510 /* Compatibility with error handling in drivers */
10511 if (dev->reg_state == NETREG_UNINITIALIZED) {
10512 netdev_freemem(dev);
10516 BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
10517 dev->reg_state = NETREG_RELEASED;
10519 /* will free via device release */
10520 put_device(&dev->dev);
10522 EXPORT_SYMBOL(free_netdev);
10525 * synchronize_net - Synchronize with packet receive processing
10527 * Wait for packets currently being received to be done.
10528 * Does not block later packets from starting.
10530 void synchronize_net(void)
10533 if (rtnl_is_locked())
10534 synchronize_rcu_expedited();
10538 EXPORT_SYMBOL(synchronize_net);
10541 * unregister_netdevice_queue - remove device from the kernel
10545 * This function shuts down a device interface and removes it
10546 * from the kernel tables.
10547 * If head not NULL, device is queued to be unregistered later.
10549 * Callers must hold the rtnl semaphore. You may want
10550 * unregister_netdev() instead of this.
10553 void unregister_netdevice_queue(struct net_device *dev, struct list_head *head)
10558 list_move_tail(&dev->unreg_list, head);
10560 rollback_registered(dev);
10561 /* Finish processing unregister after unlock */
10565 EXPORT_SYMBOL(unregister_netdevice_queue);
10568 * unregister_netdevice_many - unregister many devices
10569 * @head: list of devices
10571 * Note: As most callers use a stack allocated list_head,
10572 * we force a list_del() to make sure stack wont be corrupted later.
10574 void unregister_netdevice_many(struct list_head *head)
10576 struct net_device *dev;
10578 if (!list_empty(head)) {
10579 rollback_registered_many(head);
10580 list_for_each_entry(dev, head, unreg_list)
10585 EXPORT_SYMBOL(unregister_netdevice_many);
10588 * unregister_netdev - remove device from the kernel
10591 * This function shuts down a device interface and removes it
10592 * from the kernel tables.
10594 * This is just a wrapper for unregister_netdevice that takes
10595 * the rtnl semaphore. In general you want to use this and not
10596 * unregister_netdevice.
10598 void unregister_netdev(struct net_device *dev)
10601 unregister_netdevice(dev);
10604 EXPORT_SYMBOL(unregister_netdev);
10607 * dev_change_net_namespace - move device to different nethost namespace
10609 * @net: network namespace
10610 * @pat: If not NULL name pattern to try if the current device name
10611 * is already taken in the destination network namespace.
10613 * This function shuts down a device interface and moves it
10614 * to a new network namespace. On success 0 is returned, on
10615 * a failure a netagive errno code is returned.
10617 * Callers must hold the rtnl semaphore.
10620 int dev_change_net_namespace(struct net_device *dev, struct net *net, const char *pat)
10622 struct net *net_old = dev_net(dev);
10623 int err, new_nsid, new_ifindex;
10627 /* Don't allow namespace local devices to be moved. */
10629 if (dev->features & NETIF_F_NETNS_LOCAL)
10632 /* Ensure the device has been registrered */
10633 if (dev->reg_state != NETREG_REGISTERED)
10636 /* Get out if there is nothing todo */
10638 if (net_eq(net_old, net))
10641 /* Pick the destination device name, and ensure
10642 * we can use it in the destination network namespace.
10645 if (__dev_get_by_name(net, dev->name)) {
10646 /* We get here if we can't use the current device name */
10649 err = dev_get_valid_name(net, dev, pat);
10655 * And now a mini version of register_netdevice unregister_netdevice.
10658 /* If device is running close it first. */
10661 /* And unlink it from device chain */
10662 unlist_netdevice(dev);
10666 /* Shutdown queueing discipline. */
10669 /* Notify protocols, that we are about to destroy
10670 * this device. They should clean all the things.
10672 * Note that dev->reg_state stays at NETREG_REGISTERED.
10673 * This is wanted because this way 8021q and macvlan know
10674 * the device is just moving and can keep their slaves up.
10676 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10679 new_nsid = peernet2id_alloc(dev_net(dev), net, GFP_KERNEL);
10680 /* If there is an ifindex conflict assign a new one */
10681 if (__dev_get_by_index(net, dev->ifindex))
10682 new_ifindex = dev_new_index(net);
10684 new_ifindex = dev->ifindex;
10686 rtmsg_ifinfo_newnet(RTM_DELLINK, dev, ~0U, GFP_KERNEL, &new_nsid,
10690 * Flush the unicast and multicast chains
10695 /* Send a netdev-removed uevent to the old namespace */
10696 kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE);
10697 netdev_adjacent_del_links(dev);
10699 /* Move per-net netdevice notifiers that are following the netdevice */
10700 move_netdevice_notifiers_dev_net(dev, net);
10702 /* Actually switch the network namespace */
10703 dev_net_set(dev, net);
10704 dev->ifindex = new_ifindex;
10706 /* Send a netdev-add uevent to the new namespace */
10707 kobject_uevent(&dev->dev.kobj, KOBJ_ADD);
10708 netdev_adjacent_add_links(dev);
10710 /* Fixup kobjects */
10711 err = device_rename(&dev->dev, dev->name);
10714 /* Adapt owner in case owning user namespace of target network
10715 * namespace is different from the original one.
10717 err = netdev_change_owner(dev, net_old, net);
10720 /* Add the device back in the hashes */
10721 list_netdevice(dev);
10723 /* Notify protocols, that a new device appeared. */
10724 call_netdevice_notifiers(NETDEV_REGISTER, dev);
10727 * Prevent userspace races by waiting until the network
10728 * device is fully setup before sending notifications.
10730 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL);
10737 EXPORT_SYMBOL_GPL(dev_change_net_namespace);
10739 static int dev_cpu_dead(unsigned int oldcpu)
10741 struct sk_buff **list_skb;
10742 struct sk_buff *skb;
10744 struct softnet_data *sd, *oldsd, *remsd = NULL;
10746 local_irq_disable();
10747 cpu = smp_processor_id();
10748 sd = &per_cpu(softnet_data, cpu);
10749 oldsd = &per_cpu(softnet_data, oldcpu);
10751 /* Find end of our completion_queue. */
10752 list_skb = &sd->completion_queue;
10754 list_skb = &(*list_skb)->next;
10755 /* Append completion queue from offline CPU. */
10756 *list_skb = oldsd->completion_queue;
10757 oldsd->completion_queue = NULL;
10759 /* Append output queue from offline CPU. */
10760 if (oldsd->output_queue) {
10761 *sd->output_queue_tailp = oldsd->output_queue;
10762 sd->output_queue_tailp = oldsd->output_queue_tailp;
10763 oldsd->output_queue = NULL;
10764 oldsd->output_queue_tailp = &oldsd->output_queue;
10766 /* Append NAPI poll list from offline CPU, with one exception :
10767 * process_backlog() must be called by cpu owning percpu backlog.
10768 * We properly handle process_queue & input_pkt_queue later.
10770 while (!list_empty(&oldsd->poll_list)) {
10771 struct napi_struct *napi = list_first_entry(&oldsd->poll_list,
10772 struct napi_struct,
10775 list_del_init(&napi->poll_list);
10776 if (napi->poll == process_backlog)
10779 ____napi_schedule(sd, napi);
10782 raise_softirq_irqoff(NET_TX_SOFTIRQ);
10783 local_irq_enable();
10786 remsd = oldsd->rps_ipi_list;
10787 oldsd->rps_ipi_list = NULL;
10789 /* send out pending IPI's on offline CPU */
10790 net_rps_send_ipi(remsd);
10792 /* Process offline CPU's input_pkt_queue */
10793 while ((skb = __skb_dequeue(&oldsd->process_queue))) {
10795 input_queue_head_incr(oldsd);
10797 while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) {
10799 input_queue_head_incr(oldsd);
10806 * netdev_increment_features - increment feature set by one
10807 * @all: current feature set
10808 * @one: new feature set
10809 * @mask: mask feature set
10811 * Computes a new feature set after adding a device with feature set
10812 * @one to the master device with current feature set @all. Will not
10813 * enable anything that is off in @mask. Returns the new feature set.
10815 netdev_features_t netdev_increment_features(netdev_features_t all,
10816 netdev_features_t one, netdev_features_t mask)
10818 if (mask & NETIF_F_HW_CSUM)
10819 mask |= NETIF_F_CSUM_MASK;
10820 mask |= NETIF_F_VLAN_CHALLENGED;
10822 all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask;
10823 all &= one | ~NETIF_F_ALL_FOR_ALL;
10825 /* If one device supports hw checksumming, set for all. */
10826 if (all & NETIF_F_HW_CSUM)
10827 all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM);
10831 EXPORT_SYMBOL(netdev_increment_features);
10833 static struct hlist_head * __net_init netdev_create_hash(void)
10836 struct hlist_head *hash;
10838 hash = kmalloc_array(NETDEV_HASHENTRIES, sizeof(*hash), GFP_KERNEL);
10840 for (i = 0; i < NETDEV_HASHENTRIES; i++)
10841 INIT_HLIST_HEAD(&hash[i]);
10846 /* Initialize per network namespace state */
10847 static int __net_init netdev_init(struct net *net)
10849 BUILD_BUG_ON(GRO_HASH_BUCKETS >
10850 8 * sizeof_field(struct napi_struct, gro_bitmask));
10852 if (net != &init_net)
10853 INIT_LIST_HEAD(&net->dev_base_head);
10855 net->dev_name_head = netdev_create_hash();
10856 if (net->dev_name_head == NULL)
10859 net->dev_index_head = netdev_create_hash();
10860 if (net->dev_index_head == NULL)
10863 RAW_INIT_NOTIFIER_HEAD(&net->netdev_chain);
10868 kfree(net->dev_name_head);
10874 * netdev_drivername - network driver for the device
10875 * @dev: network device
10877 * Determine network driver for device.
10879 const char *netdev_drivername(const struct net_device *dev)
10881 const struct device_driver *driver;
10882 const struct device *parent;
10883 const char *empty = "";
10885 parent = dev->dev.parent;
10889 driver = parent->driver;
10890 if (driver && driver->name)
10891 return driver->name;
10895 static void __netdev_printk(const char *level, const struct net_device *dev,
10896 struct va_format *vaf)
10898 if (dev && dev->dev.parent) {
10899 dev_printk_emit(level[1] - '0',
10902 dev_driver_string(dev->dev.parent),
10903 dev_name(dev->dev.parent),
10904 netdev_name(dev), netdev_reg_state(dev),
10907 printk("%s%s%s: %pV",
10908 level, netdev_name(dev), netdev_reg_state(dev), vaf);
10910 printk("%s(NULL net_device): %pV", level, vaf);
10914 void netdev_printk(const char *level, const struct net_device *dev,
10915 const char *format, ...)
10917 struct va_format vaf;
10920 va_start(args, format);
10925 __netdev_printk(level, dev, &vaf);
10929 EXPORT_SYMBOL(netdev_printk);
10931 #define define_netdev_printk_level(func, level) \
10932 void func(const struct net_device *dev, const char *fmt, ...) \
10934 struct va_format vaf; \
10937 va_start(args, fmt); \
10942 __netdev_printk(level, dev, &vaf); \
10946 EXPORT_SYMBOL(func);
10948 define_netdev_printk_level(netdev_emerg, KERN_EMERG);
10949 define_netdev_printk_level(netdev_alert, KERN_ALERT);
10950 define_netdev_printk_level(netdev_crit, KERN_CRIT);
10951 define_netdev_printk_level(netdev_err, KERN_ERR);
10952 define_netdev_printk_level(netdev_warn, KERN_WARNING);
10953 define_netdev_printk_level(netdev_notice, KERN_NOTICE);
10954 define_netdev_printk_level(netdev_info, KERN_INFO);
10956 static void __net_exit netdev_exit(struct net *net)
10958 kfree(net->dev_name_head);
10959 kfree(net->dev_index_head);
10960 if (net != &init_net)
10961 WARN_ON_ONCE(!list_empty(&net->dev_base_head));
10964 static struct pernet_operations __net_initdata netdev_net_ops = {
10965 .init = netdev_init,
10966 .exit = netdev_exit,
10969 static void __net_exit default_device_exit(struct net *net)
10971 struct net_device *dev, *aux;
10973 * Push all migratable network devices back to the
10974 * initial network namespace
10977 for_each_netdev_safe(net, dev, aux) {
10979 char fb_name[IFNAMSIZ];
10981 /* Ignore unmoveable devices (i.e. loopback) */
10982 if (dev->features & NETIF_F_NETNS_LOCAL)
10985 /* Leave virtual devices for the generic cleanup */
10986 if (dev->rtnl_link_ops)
10989 /* Push remaining network devices to init_net */
10990 snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex);
10991 if (__dev_get_by_name(&init_net, fb_name))
10992 snprintf(fb_name, IFNAMSIZ, "dev%%d");
10993 err = dev_change_net_namespace(dev, &init_net, fb_name);
10995 pr_emerg("%s: failed to move %s to init_net: %d\n",
10996 __func__, dev->name, err);
11003 static void __net_exit rtnl_lock_unregistering(struct list_head *net_list)
11005 /* Return with the rtnl_lock held when there are no network
11006 * devices unregistering in any network namespace in net_list.
11009 bool unregistering;
11010 DEFINE_WAIT_FUNC(wait, woken_wake_function);
11012 add_wait_queue(&netdev_unregistering_wq, &wait);
11014 unregistering = false;
11016 list_for_each_entry(net, net_list, exit_list) {
11017 if (net->dev_unreg_count > 0) {
11018 unregistering = true;
11022 if (!unregistering)
11026 wait_woken(&wait, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
11028 remove_wait_queue(&netdev_unregistering_wq, &wait);
11031 static void __net_exit default_device_exit_batch(struct list_head *net_list)
11033 /* At exit all network devices most be removed from a network
11034 * namespace. Do this in the reverse order of registration.
11035 * Do this across as many network namespaces as possible to
11036 * improve batching efficiency.
11038 struct net_device *dev;
11040 LIST_HEAD(dev_kill_list);
11042 /* To prevent network device cleanup code from dereferencing
11043 * loopback devices or network devices that have been freed
11044 * wait here for all pending unregistrations to complete,
11045 * before unregistring the loopback device and allowing the
11046 * network namespace be freed.
11048 * The netdev todo list containing all network devices
11049 * unregistrations that happen in default_device_exit_batch
11050 * will run in the rtnl_unlock() at the end of
11051 * default_device_exit_batch.
11053 rtnl_lock_unregistering(net_list);
11054 list_for_each_entry(net, net_list, exit_list) {
11055 for_each_netdev_reverse(net, dev) {
11056 if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink)
11057 dev->rtnl_link_ops->dellink(dev, &dev_kill_list);
11059 unregister_netdevice_queue(dev, &dev_kill_list);
11062 unregister_netdevice_many(&dev_kill_list);
11066 static struct pernet_operations __net_initdata default_device_ops = {
11067 .exit = default_device_exit,
11068 .exit_batch = default_device_exit_batch,
11072 * Initialize the DEV module. At boot time this walks the device list and
11073 * unhooks any devices that fail to initialise (normally hardware not
11074 * present) and leaves us with a valid list of present and active devices.
11079 * This is called single threaded during boot, so no need
11080 * to take the rtnl semaphore.
11082 static int __init net_dev_init(void)
11084 int i, rc = -ENOMEM;
11086 BUG_ON(!dev_boot_phase);
11088 if (dev_proc_init())
11091 if (netdev_kobject_init())
11094 INIT_LIST_HEAD(&ptype_all);
11095 for (i = 0; i < PTYPE_HASH_SIZE; i++)
11096 INIT_LIST_HEAD(&ptype_base[i]);
11098 INIT_LIST_HEAD(&offload_base);
11100 if (register_pernet_subsys(&netdev_net_ops))
11104 * Initialise the packet receive queues.
11107 for_each_possible_cpu(i) {
11108 struct work_struct *flush = per_cpu_ptr(&flush_works, i);
11109 struct softnet_data *sd = &per_cpu(softnet_data, i);
11111 INIT_WORK(flush, flush_backlog);
11113 skb_queue_head_init(&sd->input_pkt_queue);
11114 skb_queue_head_init(&sd->process_queue);
11115 #ifdef CONFIG_XFRM_OFFLOAD
11116 skb_queue_head_init(&sd->xfrm_backlog);
11118 INIT_LIST_HEAD(&sd->poll_list);
11119 sd->output_queue_tailp = &sd->output_queue;
11121 sd->csd.func = rps_trigger_softirq;
11126 init_gro_hash(&sd->backlog);
11127 sd->backlog.poll = process_backlog;
11128 sd->backlog.weight = weight_p;
11131 dev_boot_phase = 0;
11133 /* The loopback device is special if any other network devices
11134 * is present in a network namespace the loopback device must
11135 * be present. Since we now dynamically allocate and free the
11136 * loopback device ensure this invariant is maintained by
11137 * keeping the loopback device as the first device on the
11138 * list of network devices. Ensuring the loopback devices
11139 * is the first device that appears and the last network device
11142 if (register_pernet_device(&loopback_net_ops))
11145 if (register_pernet_device(&default_device_ops))
11148 open_softirq(NET_TX_SOFTIRQ, net_tx_action);
11149 open_softirq(NET_RX_SOFTIRQ, net_rx_action);
11151 rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead",
11152 NULL, dev_cpu_dead);
11159 subsys_initcall(net_dev_init);