2 * NET3 Protocol independent device support routines.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version
7 * 2 of the License, or (at your option) any later version.
9 * Derived from the non IP parts of dev.c 1.0.19
23 * D.J. Barrow : Fixed bug where dev->refcnt gets set
24 * to 2 if register_netdev gets called
25 * before net_dev_init & also removed a
26 * few lines of code in the process.
27 * Alan Cox : device private ioctl copies fields back.
28 * Alan Cox : Transmit queue code does relevant
29 * stunts to keep the queue safe.
30 * Alan Cox : Fixed double lock.
31 * Alan Cox : Fixed promisc NULL pointer trap
32 * ???????? : Support the full private ioctl range
33 * Alan Cox : Moved ioctl permission check into
35 * Tim Kordas : SIOCADDMULTI/SIOCDELMULTI
36 * Alan Cox : 100 backlog just doesn't cut it when
37 * you start doing multicast video 8)
38 * Alan Cox : Rewrote net_bh and list manager.
39 * Alan Cox : Fix ETH_P_ALL echoback lengths.
40 * Alan Cox : Took out transmit every packet pass
41 * Saved a few bytes in the ioctl handler
42 * Alan Cox : Network driver sets packet type before
43 * calling netif_rx. Saves a function
45 * Alan Cox : Hashed net_bh()
46 * Richard Kooijman: Timestamp fixes.
47 * Alan Cox : Wrong field in SIOCGIFDSTADDR
48 * Alan Cox : Device lock protection.
49 * Alan Cox : Fixed nasty side effect of device close
51 * Rudi Cilibrasi : Pass the right thing to
53 * Dave Miller : 32bit quantity for the device lock to
54 * make it work out on a Sparc.
55 * Bjorn Ekwall : Added KERNELD hack.
56 * Alan Cox : Cleaned up the backlog initialise.
57 * Craig Metz : SIOCGIFCONF fix if space for under
59 * Thomas Bogendoerfer : Return ENODEV for dev_open, if there
60 * is no device open function.
61 * Andi Kleen : Fix error reporting for SIOCGIFCONF
62 * Michael Chastain : Fix signed/unsigned for SIOCGIFCONF
63 * Cyrus Durgin : Cleaned for KMOD
64 * Adam Sulmicki : Bug Fix : Network Device Unload
65 * A network device unload needs to purge
67 * Paul Rusty Russell : SIOCSIFNAME
68 * Pekka Riikonen : Netdev boot-time settings code
69 * Andrew Morton : Make unregister_netdevice wait
70 * indefinitely on dev->refcnt
71 * J Hadi Salim : - Backlog queue sampling
72 * - netif_rx() feedback
75 #include <asm/uaccess.h>
76 #include <linux/bitops.h>
77 #include <linux/capability.h>
78 #include <linux/cpu.h>
79 #include <linux/types.h>
80 #include <linux/kernel.h>
81 #include <linux/hash.h>
82 #include <linux/slab.h>
83 #include <linux/sched.h>
84 #include <linux/mutex.h>
85 #include <linux/string.h>
87 #include <linux/socket.h>
88 #include <linux/sockios.h>
89 #include <linux/errno.h>
90 #include <linux/interrupt.h>
91 #include <linux/if_ether.h>
92 #include <linux/netdevice.h>
93 #include <linux/etherdevice.h>
94 #include <linux/ethtool.h>
95 #include <linux/notifier.h>
96 #include <linux/skbuff.h>
97 #include <net/net_namespace.h>
99 #include <linux/rtnetlink.h>
100 #include <linux/stat.h>
102 #include <net/pkt_sched.h>
103 #include <net/checksum.h>
104 #include <net/xfrm.h>
105 #include <linux/highmem.h>
106 #include <linux/init.h>
107 #include <linux/module.h>
108 #include <linux/netpoll.h>
109 #include <linux/rcupdate.h>
110 #include <linux/delay.h>
111 #include <net/iw_handler.h>
112 #include <asm/current.h>
113 #include <linux/audit.h>
114 #include <linux/dmaengine.h>
115 #include <linux/err.h>
116 #include <linux/ctype.h>
117 #include <linux/if_arp.h>
118 #include <linux/if_vlan.h>
119 #include <linux/ip.h>
121 #include <linux/ipv6.h>
122 #include <linux/in.h>
123 #include <linux/jhash.h>
124 #include <linux/random.h>
125 #include <trace/events/napi.h>
126 #include <trace/events/net.h>
127 #include <trace/events/skb.h>
128 #include <linux/pci.h>
129 #include <linux/inetdevice.h>
130 #include <linux/cpu_rmap.h>
131 #include <linux/static_key.h>
132 #include <linux/hashtable.h>
133 #include <linux/vmalloc.h>
135 #include "net-sysfs.h"
137 /* Instead of increasing this, you should create a hash table. */
138 #define MAX_GRO_SKBS 8
140 /* This should be increased if a protocol with a bigger head is added. */
141 #define GRO_MAX_HEAD (MAX_HEADER + 128)
143 static DEFINE_SPINLOCK(ptype_lock);
144 static DEFINE_SPINLOCK(offload_lock);
145 struct list_head ptype_base[PTYPE_HASH_SIZE] __read_mostly;
146 struct list_head ptype_all __read_mostly; /* Taps */
147 static struct list_head offload_base __read_mostly;
150 * The @dev_base_head list is protected by @dev_base_lock and the rtnl
153 * Pure readers hold dev_base_lock for reading, or rcu_read_lock()
155 * Writers must hold the rtnl semaphore while they loop through the
156 * dev_base_head list, and hold dev_base_lock for writing when they do the
157 * actual updates. This allows pure readers to access the list even
158 * while a writer is preparing to update it.
160 * To put it another way, dev_base_lock is held for writing only to
161 * protect against pure readers; the rtnl semaphore provides the
162 * protection against other writers.
164 * See, for example usages, register_netdevice() and
165 * unregister_netdevice(), which must be called with the rtnl
168 DEFINE_RWLOCK(dev_base_lock);
169 EXPORT_SYMBOL(dev_base_lock);
171 /* protects napi_hash addition/deletion and napi_gen_id */
172 static DEFINE_SPINLOCK(napi_hash_lock);
174 static unsigned int napi_gen_id;
175 static DEFINE_HASHTABLE(napi_hash, 8);
177 seqcount_t devnet_rename_seq;
179 static inline void dev_base_seq_inc(struct net *net)
181 while (++net->dev_base_seq == 0);
184 static inline struct hlist_head *dev_name_hash(struct net *net, const char *name)
186 unsigned int hash = full_name_hash(name, strnlen(name, IFNAMSIZ));
188 return &net->dev_name_head[hash_32(hash, NETDEV_HASHBITS)];
191 static inline struct hlist_head *dev_index_hash(struct net *net, int ifindex)
193 return &net->dev_index_head[ifindex & (NETDEV_HASHENTRIES - 1)];
196 static inline void rps_lock(struct softnet_data *sd)
199 spin_lock(&sd->input_pkt_queue.lock);
203 static inline void rps_unlock(struct softnet_data *sd)
206 spin_unlock(&sd->input_pkt_queue.lock);
210 /* Device list insertion */
211 static void list_netdevice(struct net_device *dev)
213 struct net *net = dev_net(dev);
217 write_lock_bh(&dev_base_lock);
218 list_add_tail_rcu(&dev->dev_list, &net->dev_base_head);
219 hlist_add_head_rcu(&dev->name_hlist, dev_name_hash(net, dev->name));
220 hlist_add_head_rcu(&dev->index_hlist,
221 dev_index_hash(net, dev->ifindex));
222 write_unlock_bh(&dev_base_lock);
224 dev_base_seq_inc(net);
227 /* Device list removal
228 * caller must respect a RCU grace period before freeing/reusing dev
230 static void unlist_netdevice(struct net_device *dev)
234 /* Unlink dev from the device chain */
235 write_lock_bh(&dev_base_lock);
236 list_del_rcu(&dev->dev_list);
237 hlist_del_rcu(&dev->name_hlist);
238 hlist_del_rcu(&dev->index_hlist);
239 write_unlock_bh(&dev_base_lock);
241 dev_base_seq_inc(dev_net(dev));
248 static RAW_NOTIFIER_HEAD(netdev_chain);
251 * Device drivers call our routines to queue packets here. We empty the
252 * queue in the local softnet handler.
255 DEFINE_PER_CPU_ALIGNED(struct softnet_data, softnet_data);
256 EXPORT_PER_CPU_SYMBOL(softnet_data);
258 #ifdef CONFIG_LOCKDEP
260 * register_netdevice() inits txq->_xmit_lock and sets lockdep class
261 * according to dev->type
263 static const unsigned short netdev_lock_type[] =
264 {ARPHRD_NETROM, ARPHRD_ETHER, ARPHRD_EETHER, ARPHRD_AX25,
265 ARPHRD_PRONET, ARPHRD_CHAOS, ARPHRD_IEEE802, ARPHRD_ARCNET,
266 ARPHRD_APPLETLK, ARPHRD_DLCI, ARPHRD_ATM, ARPHRD_METRICOM,
267 ARPHRD_IEEE1394, ARPHRD_EUI64, ARPHRD_INFINIBAND, ARPHRD_SLIP,
268 ARPHRD_CSLIP, ARPHRD_SLIP6, ARPHRD_CSLIP6, ARPHRD_RSRVD,
269 ARPHRD_ADAPT, ARPHRD_ROSE, ARPHRD_X25, ARPHRD_HWX25,
270 ARPHRD_PPP, ARPHRD_CISCO, ARPHRD_LAPB, ARPHRD_DDCMP,
271 ARPHRD_RAWHDLC, ARPHRD_TUNNEL, ARPHRD_TUNNEL6, ARPHRD_FRAD,
272 ARPHRD_SKIP, ARPHRD_LOOPBACK, ARPHRD_LOCALTLK, ARPHRD_FDDI,
273 ARPHRD_BIF, ARPHRD_SIT, ARPHRD_IPDDP, ARPHRD_IPGRE,
274 ARPHRD_PIMREG, ARPHRD_HIPPI, ARPHRD_ASH, ARPHRD_ECONET,
275 ARPHRD_IRDA, ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL,
276 ARPHRD_FCFABRIC, ARPHRD_IEEE80211, ARPHRD_IEEE80211_PRISM,
277 ARPHRD_IEEE80211_RADIOTAP, ARPHRD_PHONET, ARPHRD_PHONET_PIPE,
278 ARPHRD_IEEE802154, ARPHRD_VOID, ARPHRD_NONE};
280 static const char *const netdev_lock_name[] =
281 {"_xmit_NETROM", "_xmit_ETHER", "_xmit_EETHER", "_xmit_AX25",
282 "_xmit_PRONET", "_xmit_CHAOS", "_xmit_IEEE802", "_xmit_ARCNET",
283 "_xmit_APPLETLK", "_xmit_DLCI", "_xmit_ATM", "_xmit_METRICOM",
284 "_xmit_IEEE1394", "_xmit_EUI64", "_xmit_INFINIBAND", "_xmit_SLIP",
285 "_xmit_CSLIP", "_xmit_SLIP6", "_xmit_CSLIP6", "_xmit_RSRVD",
286 "_xmit_ADAPT", "_xmit_ROSE", "_xmit_X25", "_xmit_HWX25",
287 "_xmit_PPP", "_xmit_CISCO", "_xmit_LAPB", "_xmit_DDCMP",
288 "_xmit_RAWHDLC", "_xmit_TUNNEL", "_xmit_TUNNEL6", "_xmit_FRAD",
289 "_xmit_SKIP", "_xmit_LOOPBACK", "_xmit_LOCALTLK", "_xmit_FDDI",
290 "_xmit_BIF", "_xmit_SIT", "_xmit_IPDDP", "_xmit_IPGRE",
291 "_xmit_PIMREG", "_xmit_HIPPI", "_xmit_ASH", "_xmit_ECONET",
292 "_xmit_IRDA", "_xmit_FCPP", "_xmit_FCAL", "_xmit_FCPL",
293 "_xmit_FCFABRIC", "_xmit_IEEE80211", "_xmit_IEEE80211_PRISM",
294 "_xmit_IEEE80211_RADIOTAP", "_xmit_PHONET", "_xmit_PHONET_PIPE",
295 "_xmit_IEEE802154", "_xmit_VOID", "_xmit_NONE"};
297 static struct lock_class_key netdev_xmit_lock_key[ARRAY_SIZE(netdev_lock_type)];
298 static struct lock_class_key netdev_addr_lock_key[ARRAY_SIZE(netdev_lock_type)];
300 static inline unsigned short netdev_lock_pos(unsigned short dev_type)
304 for (i = 0; i < ARRAY_SIZE(netdev_lock_type); i++)
305 if (netdev_lock_type[i] == dev_type)
307 /* the last key is used by default */
308 return ARRAY_SIZE(netdev_lock_type) - 1;
311 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
312 unsigned short dev_type)
316 i = netdev_lock_pos(dev_type);
317 lockdep_set_class_and_name(lock, &netdev_xmit_lock_key[i],
318 netdev_lock_name[i]);
321 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
325 i = netdev_lock_pos(dev->type);
326 lockdep_set_class_and_name(&dev->addr_list_lock,
327 &netdev_addr_lock_key[i],
328 netdev_lock_name[i]);
331 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
332 unsigned short dev_type)
335 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
340 /*******************************************************************************
342 Protocol management and registration routines
344 *******************************************************************************/
347 * Add a protocol ID to the list. Now that the input handler is
348 * smarter we can dispense with all the messy stuff that used to be
351 * BEWARE!!! Protocol handlers, mangling input packets,
352 * MUST BE last in hash buckets and checking protocol handlers
353 * MUST start from promiscuous ptype_all chain in net_bh.
354 * It is true now, do not change it.
355 * Explanation follows: if protocol handler, mangling packet, will
356 * be the first on list, it is not able to sense, that packet
357 * is cloned and should be copied-on-write, so that it will
358 * change it and subsequent readers will get broken packet.
362 static inline struct list_head *ptype_head(const struct packet_type *pt)
364 if (pt->type == htons(ETH_P_ALL))
367 return &ptype_base[ntohs(pt->type) & PTYPE_HASH_MASK];
371 * dev_add_pack - add packet handler
372 * @pt: packet type declaration
374 * Add a protocol handler to the networking stack. The passed &packet_type
375 * is linked into kernel lists and may not be freed until it has been
376 * removed from the kernel lists.
378 * This call does not sleep therefore it can not
379 * guarantee all CPU's that are in middle of receiving packets
380 * will see the new packet type (until the next received packet).
383 void dev_add_pack(struct packet_type *pt)
385 struct list_head *head = ptype_head(pt);
387 spin_lock(&ptype_lock);
388 list_add_rcu(&pt->list, head);
389 spin_unlock(&ptype_lock);
391 EXPORT_SYMBOL(dev_add_pack);
394 * __dev_remove_pack - remove packet handler
395 * @pt: packet type declaration
397 * Remove a protocol handler that was previously added to the kernel
398 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
399 * from the kernel lists and can be freed or reused once this function
402 * The packet type might still be in use by receivers
403 * and must not be freed until after all the CPU's have gone
404 * through a quiescent state.
406 void __dev_remove_pack(struct packet_type *pt)
408 struct list_head *head = ptype_head(pt);
409 struct packet_type *pt1;
411 spin_lock(&ptype_lock);
413 list_for_each_entry(pt1, head, list) {
415 list_del_rcu(&pt->list);
420 pr_warn("dev_remove_pack: %p not found\n", pt);
422 spin_unlock(&ptype_lock);
424 EXPORT_SYMBOL(__dev_remove_pack);
427 * dev_remove_pack - remove packet handler
428 * @pt: packet type declaration
430 * Remove a protocol handler that was previously added to the kernel
431 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
432 * from the kernel lists and can be freed or reused once this function
435 * This call sleeps to guarantee that no CPU is looking at the packet
438 void dev_remove_pack(struct packet_type *pt)
440 __dev_remove_pack(pt);
444 EXPORT_SYMBOL(dev_remove_pack);
448 * dev_add_offload - register offload handlers
449 * @po: protocol offload declaration
451 * Add protocol offload handlers to the networking stack. The passed
452 * &proto_offload is linked into kernel lists and may not be freed until
453 * it has been removed from the kernel lists.
455 * This call does not sleep therefore it can not
456 * guarantee all CPU's that are in middle of receiving packets
457 * will see the new offload handlers (until the next received packet).
459 void dev_add_offload(struct packet_offload *po)
461 struct list_head *head = &offload_base;
463 spin_lock(&offload_lock);
464 list_add_rcu(&po->list, head);
465 spin_unlock(&offload_lock);
467 EXPORT_SYMBOL(dev_add_offload);
470 * __dev_remove_offload - remove offload handler
471 * @po: packet offload declaration
473 * Remove a protocol offload handler that was previously added to the
474 * kernel offload handlers by dev_add_offload(). The passed &offload_type
475 * is removed from the kernel lists and can be freed or reused once this
478 * The packet type might still be in use by receivers
479 * and must not be freed until after all the CPU's have gone
480 * through a quiescent state.
482 void __dev_remove_offload(struct packet_offload *po)
484 struct list_head *head = &offload_base;
485 struct packet_offload *po1;
487 spin_lock(&offload_lock);
489 list_for_each_entry(po1, head, list) {
491 list_del_rcu(&po->list);
496 pr_warn("dev_remove_offload: %p not found\n", po);
498 spin_unlock(&offload_lock);
500 EXPORT_SYMBOL(__dev_remove_offload);
503 * dev_remove_offload - remove packet offload handler
504 * @po: packet offload declaration
506 * Remove a packet offload handler that was previously added to the kernel
507 * offload handlers by dev_add_offload(). The passed &offload_type is
508 * removed from the kernel lists and can be freed or reused once this
511 * This call sleeps to guarantee that no CPU is looking at the packet
514 void dev_remove_offload(struct packet_offload *po)
516 __dev_remove_offload(po);
520 EXPORT_SYMBOL(dev_remove_offload);
522 /******************************************************************************
524 Device Boot-time Settings Routines
526 *******************************************************************************/
528 /* Boot time configuration table */
529 static struct netdev_boot_setup dev_boot_setup[NETDEV_BOOT_SETUP_MAX];
532 * netdev_boot_setup_add - add new setup entry
533 * @name: name of the device
534 * @map: configured settings for the device
536 * Adds new setup entry to the dev_boot_setup list. The function
537 * returns 0 on error and 1 on success. This is a generic routine to
540 static int netdev_boot_setup_add(char *name, struct ifmap *map)
542 struct netdev_boot_setup *s;
546 for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
547 if (s[i].name[0] == '\0' || s[i].name[0] == ' ') {
548 memset(s[i].name, 0, sizeof(s[i].name));
549 strlcpy(s[i].name, name, IFNAMSIZ);
550 memcpy(&s[i].map, map, sizeof(s[i].map));
555 return i >= NETDEV_BOOT_SETUP_MAX ? 0 : 1;
559 * netdev_boot_setup_check - check boot time settings
560 * @dev: the netdevice
562 * Check boot time settings for the device.
563 * The found settings are set for the device to be used
564 * later in the device probing.
565 * Returns 0 if no settings found, 1 if they are.
567 int netdev_boot_setup_check(struct net_device *dev)
569 struct netdev_boot_setup *s = dev_boot_setup;
572 for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
573 if (s[i].name[0] != '\0' && s[i].name[0] != ' ' &&
574 !strcmp(dev->name, s[i].name)) {
575 dev->irq = s[i].map.irq;
576 dev->base_addr = s[i].map.base_addr;
577 dev->mem_start = s[i].map.mem_start;
578 dev->mem_end = s[i].map.mem_end;
584 EXPORT_SYMBOL(netdev_boot_setup_check);
588 * netdev_boot_base - get address from boot time settings
589 * @prefix: prefix for network device
590 * @unit: id for network device
592 * Check boot time settings for the base address of device.
593 * The found settings are set for the device to be used
594 * later in the device probing.
595 * Returns 0 if no settings found.
597 unsigned long netdev_boot_base(const char *prefix, int unit)
599 const struct netdev_boot_setup *s = dev_boot_setup;
603 sprintf(name, "%s%d", prefix, unit);
606 * If device already registered then return base of 1
607 * to indicate not to probe for this interface
609 if (__dev_get_by_name(&init_net, name))
612 for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++)
613 if (!strcmp(name, s[i].name))
614 return s[i].map.base_addr;
619 * Saves at boot time configured settings for any netdevice.
621 int __init netdev_boot_setup(char *str)
626 str = get_options(str, ARRAY_SIZE(ints), ints);
631 memset(&map, 0, sizeof(map));
635 map.base_addr = ints[2];
637 map.mem_start = ints[3];
639 map.mem_end = ints[4];
641 /* Add new entry to the list */
642 return netdev_boot_setup_add(str, &map);
645 __setup("netdev=", netdev_boot_setup);
647 /*******************************************************************************
649 Device Interface Subroutines
651 *******************************************************************************/
654 * __dev_get_by_name - find a device by its name
655 * @net: the applicable net namespace
656 * @name: name to find
658 * Find an interface by name. Must be called under RTNL semaphore
659 * or @dev_base_lock. If the name is found a pointer to the device
660 * is returned. If the name is not found then %NULL is returned. The
661 * reference counters are not incremented so the caller must be
662 * careful with locks.
665 struct net_device *__dev_get_by_name(struct net *net, const char *name)
667 struct net_device *dev;
668 struct hlist_head *head = dev_name_hash(net, name);
670 hlist_for_each_entry(dev, head, name_hlist)
671 if (!strncmp(dev->name, name, IFNAMSIZ))
676 EXPORT_SYMBOL(__dev_get_by_name);
679 * dev_get_by_name_rcu - find a device by its name
680 * @net: the applicable net namespace
681 * @name: name to find
683 * Find an interface by name.
684 * If the name is found a pointer to the device is returned.
685 * If the name is not found then %NULL is returned.
686 * The reference counters are not incremented so the caller must be
687 * careful with locks. The caller must hold RCU lock.
690 struct net_device *dev_get_by_name_rcu(struct net *net, const char *name)
692 struct net_device *dev;
693 struct hlist_head *head = dev_name_hash(net, name);
695 hlist_for_each_entry_rcu(dev, head, name_hlist)
696 if (!strncmp(dev->name, name, IFNAMSIZ))
701 EXPORT_SYMBOL(dev_get_by_name_rcu);
704 * dev_get_by_name - find a device by its name
705 * @net: the applicable net namespace
706 * @name: name to find
708 * Find an interface by name. This can be called from any
709 * context and does its own locking. The returned handle has
710 * the usage count incremented and the caller must use dev_put() to
711 * release it when it is no longer needed. %NULL is returned if no
712 * matching device is found.
715 struct net_device *dev_get_by_name(struct net *net, const char *name)
717 struct net_device *dev;
720 dev = dev_get_by_name_rcu(net, name);
726 EXPORT_SYMBOL(dev_get_by_name);
729 * __dev_get_by_index - find a device by its ifindex
730 * @net: the applicable net namespace
731 * @ifindex: index of device
733 * Search for an interface by index. Returns %NULL if the device
734 * is not found or a pointer to the device. The device has not
735 * had its reference counter increased so the caller must be careful
736 * about locking. The caller must hold either the RTNL semaphore
740 struct net_device *__dev_get_by_index(struct net *net, int ifindex)
742 struct net_device *dev;
743 struct hlist_head *head = dev_index_hash(net, ifindex);
745 hlist_for_each_entry(dev, head, index_hlist)
746 if (dev->ifindex == ifindex)
751 EXPORT_SYMBOL(__dev_get_by_index);
754 * dev_get_by_index_rcu - find a device by its ifindex
755 * @net: the applicable net namespace
756 * @ifindex: index of device
758 * Search for an interface by index. Returns %NULL if the device
759 * is not found or a pointer to the device. The device has not
760 * had its reference counter increased so the caller must be careful
761 * about locking. The caller must hold RCU lock.
764 struct net_device *dev_get_by_index_rcu(struct net *net, int ifindex)
766 struct net_device *dev;
767 struct hlist_head *head = dev_index_hash(net, ifindex);
769 hlist_for_each_entry_rcu(dev, head, index_hlist)
770 if (dev->ifindex == ifindex)
775 EXPORT_SYMBOL(dev_get_by_index_rcu);
779 * dev_get_by_index - find a device by its ifindex
780 * @net: the applicable net namespace
781 * @ifindex: index of device
783 * Search for an interface by index. Returns NULL if the device
784 * is not found or a pointer to the device. The device returned has
785 * had a reference added and the pointer is safe until the user calls
786 * dev_put to indicate they have finished with it.
789 struct net_device *dev_get_by_index(struct net *net, int ifindex)
791 struct net_device *dev;
794 dev = dev_get_by_index_rcu(net, ifindex);
800 EXPORT_SYMBOL(dev_get_by_index);
803 * dev_getbyhwaddr_rcu - find a device by its hardware address
804 * @net: the applicable net namespace
805 * @type: media type of device
806 * @ha: hardware address
808 * Search for an interface by MAC address. Returns NULL if the device
809 * is not found or a pointer to the device.
810 * The caller must hold RCU or RTNL.
811 * The returned device has not had its ref count increased
812 * and the caller must therefore be careful about locking
816 struct net_device *dev_getbyhwaddr_rcu(struct net *net, unsigned short type,
819 struct net_device *dev;
821 for_each_netdev_rcu(net, dev)
822 if (dev->type == type &&
823 !memcmp(dev->dev_addr, ha, dev->addr_len))
828 EXPORT_SYMBOL(dev_getbyhwaddr_rcu);
830 struct net_device *__dev_getfirstbyhwtype(struct net *net, unsigned short type)
832 struct net_device *dev;
835 for_each_netdev(net, dev)
836 if (dev->type == type)
841 EXPORT_SYMBOL(__dev_getfirstbyhwtype);
843 struct net_device *dev_getfirstbyhwtype(struct net *net, unsigned short type)
845 struct net_device *dev, *ret = NULL;
848 for_each_netdev_rcu(net, dev)
849 if (dev->type == type) {
857 EXPORT_SYMBOL(dev_getfirstbyhwtype);
860 * dev_get_by_flags_rcu - find any device with given flags
861 * @net: the applicable net namespace
862 * @if_flags: IFF_* values
863 * @mask: bitmask of bits in if_flags to check
865 * Search for any interface with the given flags. Returns NULL if a device
866 * is not found or a pointer to the device. Must be called inside
867 * rcu_read_lock(), and result refcount is unchanged.
870 struct net_device *dev_get_by_flags_rcu(struct net *net, unsigned short if_flags,
873 struct net_device *dev, *ret;
876 for_each_netdev_rcu(net, dev) {
877 if (((dev->flags ^ if_flags) & mask) == 0) {
884 EXPORT_SYMBOL(dev_get_by_flags_rcu);
887 * dev_valid_name - check if name is okay for network device
890 * Network device names need to be valid file names to
891 * to allow sysfs to work. We also disallow any kind of
894 bool dev_valid_name(const char *name)
898 if (strlen(name) >= IFNAMSIZ)
900 if (!strcmp(name, ".") || !strcmp(name, ".."))
904 if (*name == '/' || isspace(*name))
910 EXPORT_SYMBOL(dev_valid_name);
913 * __dev_alloc_name - allocate a name for a device
914 * @net: network namespace to allocate the device name in
915 * @name: name format string
916 * @buf: scratch buffer and result name string
918 * Passed a format string - eg "lt%d" it will try and find a suitable
919 * id. It scans list of devices to build up a free map, then chooses
920 * the first empty slot. The caller must hold the dev_base or rtnl lock
921 * while allocating the name and adding the device in order to avoid
923 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
924 * Returns the number of the unit assigned or a negative errno code.
927 static int __dev_alloc_name(struct net *net, const char *name, char *buf)
931 const int max_netdevices = 8*PAGE_SIZE;
932 unsigned long *inuse;
933 struct net_device *d;
935 p = strnchr(name, IFNAMSIZ-1, '%');
938 * Verify the string as this thing may have come from
939 * the user. There must be either one "%d" and no other "%"
942 if (p[1] != 'd' || strchr(p + 2, '%'))
945 /* Use one page as a bit array of possible slots */
946 inuse = (unsigned long *) get_zeroed_page(GFP_ATOMIC);
950 for_each_netdev(net, d) {
951 if (!sscanf(d->name, name, &i))
953 if (i < 0 || i >= max_netdevices)
956 /* avoid cases where sscanf is not exact inverse of printf */
957 snprintf(buf, IFNAMSIZ, name, i);
958 if (!strncmp(buf, d->name, IFNAMSIZ))
962 i = find_first_zero_bit(inuse, max_netdevices);
963 free_page((unsigned long) inuse);
967 snprintf(buf, IFNAMSIZ, name, i);
968 if (!__dev_get_by_name(net, buf))
971 /* It is possible to run out of possible slots
972 * when the name is long and there isn't enough space left
973 * for the digits, or if all bits are used.
979 * dev_alloc_name - allocate a name for a device
981 * @name: name format string
983 * Passed a format string - eg "lt%d" it will try and find a suitable
984 * id. It scans list of devices to build up a free map, then chooses
985 * the first empty slot. The caller must hold the dev_base or rtnl lock
986 * while allocating the name and adding the device in order to avoid
988 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
989 * Returns the number of the unit assigned or a negative errno code.
992 int dev_alloc_name(struct net_device *dev, const char *name)
998 BUG_ON(!dev_net(dev));
1000 ret = __dev_alloc_name(net, name, buf);
1002 strlcpy(dev->name, buf, IFNAMSIZ);
1005 EXPORT_SYMBOL(dev_alloc_name);
1007 static int dev_alloc_name_ns(struct net *net,
1008 struct net_device *dev,
1014 ret = __dev_alloc_name(net, name, buf);
1016 strlcpy(dev->name, buf, IFNAMSIZ);
1020 static int dev_get_valid_name(struct net *net,
1021 struct net_device *dev,
1026 if (!dev_valid_name(name))
1029 if (strchr(name, '%'))
1030 return dev_alloc_name_ns(net, dev, name);
1031 else if (__dev_get_by_name(net, name))
1033 else if (dev->name != name)
1034 strlcpy(dev->name, name, IFNAMSIZ);
1040 * dev_change_name - change name of a device
1042 * @newname: name (or format string) must be at least IFNAMSIZ
1044 * Change name of a device, can pass format strings "eth%d".
1047 int dev_change_name(struct net_device *dev, const char *newname)
1049 char oldname[IFNAMSIZ];
1055 BUG_ON(!dev_net(dev));
1058 if (dev->flags & IFF_UP)
1061 write_seqcount_begin(&devnet_rename_seq);
1063 if (strncmp(newname, dev->name, IFNAMSIZ) == 0) {
1064 write_seqcount_end(&devnet_rename_seq);
1068 memcpy(oldname, dev->name, IFNAMSIZ);
1070 err = dev_get_valid_name(net, dev, newname);
1072 write_seqcount_end(&devnet_rename_seq);
1077 ret = device_rename(&dev->dev, dev->name);
1079 memcpy(dev->name, oldname, IFNAMSIZ);
1080 write_seqcount_end(&devnet_rename_seq);
1084 write_seqcount_end(&devnet_rename_seq);
1086 write_lock_bh(&dev_base_lock);
1087 hlist_del_rcu(&dev->name_hlist);
1088 write_unlock_bh(&dev_base_lock);
1092 write_lock_bh(&dev_base_lock);
1093 hlist_add_head_rcu(&dev->name_hlist, dev_name_hash(net, dev->name));
1094 write_unlock_bh(&dev_base_lock);
1096 ret = call_netdevice_notifiers(NETDEV_CHANGENAME, dev);
1097 ret = notifier_to_errno(ret);
1100 /* err >= 0 after dev_alloc_name() or stores the first errno */
1103 write_seqcount_begin(&devnet_rename_seq);
1104 memcpy(dev->name, oldname, IFNAMSIZ);
1107 pr_err("%s: name change rollback failed: %d\n",
1116 * dev_set_alias - change ifalias of a device
1118 * @alias: name up to IFALIASZ
1119 * @len: limit of bytes to copy from info
1121 * Set ifalias for a device,
1123 int dev_set_alias(struct net_device *dev, const char *alias, size_t len)
1129 if (len >= IFALIASZ)
1133 kfree(dev->ifalias);
1134 dev->ifalias = NULL;
1138 new_ifalias = krealloc(dev->ifalias, len + 1, GFP_KERNEL);
1141 dev->ifalias = new_ifalias;
1143 strlcpy(dev->ifalias, alias, len+1);
1149 * netdev_features_change - device changes features
1150 * @dev: device to cause notification
1152 * Called to indicate a device has changed features.
1154 void netdev_features_change(struct net_device *dev)
1156 call_netdevice_notifiers(NETDEV_FEAT_CHANGE, dev);
1158 EXPORT_SYMBOL(netdev_features_change);
1161 * netdev_state_change - device changes state
1162 * @dev: device to cause notification
1164 * Called to indicate a device has changed state. This function calls
1165 * the notifier chains for netdev_chain and sends a NEWLINK message
1166 * to the routing socket.
1168 void netdev_state_change(struct net_device *dev)
1170 if (dev->flags & IFF_UP) {
1171 call_netdevice_notifiers(NETDEV_CHANGE, dev);
1172 rtmsg_ifinfo(RTM_NEWLINK, dev, 0);
1175 EXPORT_SYMBOL(netdev_state_change);
1178 * netdev_notify_peers - notify network peers about existence of @dev
1179 * @dev: network device
1181 * Generate traffic such that interested network peers are aware of
1182 * @dev, such as by generating a gratuitous ARP. This may be used when
1183 * a device wants to inform the rest of the network about some sort of
1184 * reconfiguration such as a failover event or virtual machine
1187 void netdev_notify_peers(struct net_device *dev)
1190 call_netdevice_notifiers(NETDEV_NOTIFY_PEERS, dev);
1193 EXPORT_SYMBOL(netdev_notify_peers);
1195 static int __dev_open(struct net_device *dev)
1197 const struct net_device_ops *ops = dev->netdev_ops;
1202 if (!netif_device_present(dev))
1205 /* Block netpoll from trying to do any rx path servicing.
1206 * If we don't do this there is a chance ndo_poll_controller
1207 * or ndo_poll may be running while we open the device
1209 netpoll_rx_disable(dev);
1211 ret = call_netdevice_notifiers(NETDEV_PRE_UP, dev);
1212 ret = notifier_to_errno(ret);
1216 set_bit(__LINK_STATE_START, &dev->state);
1218 if (ops->ndo_validate_addr)
1219 ret = ops->ndo_validate_addr(dev);
1221 if (!ret && ops->ndo_open)
1222 ret = ops->ndo_open(dev);
1224 netpoll_rx_enable(dev);
1227 clear_bit(__LINK_STATE_START, &dev->state);
1229 dev->flags |= IFF_UP;
1230 net_dmaengine_get();
1231 dev_set_rx_mode(dev);
1233 add_device_randomness(dev->dev_addr, dev->addr_len);
1240 * dev_open - prepare an interface for use.
1241 * @dev: device to open
1243 * Takes a device from down to up state. The device's private open
1244 * function is invoked and then the multicast lists are loaded. Finally
1245 * the device is moved into the up state and a %NETDEV_UP message is
1246 * sent to the netdev notifier chain.
1248 * Calling this function on an active interface is a nop. On a failure
1249 * a negative errno code is returned.
1251 int dev_open(struct net_device *dev)
1255 if (dev->flags & IFF_UP)
1258 ret = __dev_open(dev);
1262 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING);
1263 call_netdevice_notifiers(NETDEV_UP, dev);
1267 EXPORT_SYMBOL(dev_open);
1269 static int __dev_close_many(struct list_head *head)
1271 struct net_device *dev;
1276 list_for_each_entry(dev, head, unreg_list) {
1277 call_netdevice_notifiers(NETDEV_GOING_DOWN, dev);
1279 clear_bit(__LINK_STATE_START, &dev->state);
1281 /* Synchronize to scheduled poll. We cannot touch poll list, it
1282 * can be even on different cpu. So just clear netif_running().
1284 * dev->stop() will invoke napi_disable() on all of it's
1285 * napi_struct instances on this device.
1287 smp_mb__after_clear_bit(); /* Commit netif_running(). */
1290 dev_deactivate_many(head);
1292 list_for_each_entry(dev, head, unreg_list) {
1293 const struct net_device_ops *ops = dev->netdev_ops;
1296 * Call the device specific close. This cannot fail.
1297 * Only if device is UP
1299 * We allow it to be called even after a DETACH hot-plug
1305 dev->flags &= ~IFF_UP;
1306 net_dmaengine_put();
1312 static int __dev_close(struct net_device *dev)
1317 /* Temporarily disable netpoll until the interface is down */
1318 netpoll_rx_disable(dev);
1320 list_add(&dev->unreg_list, &single);
1321 retval = __dev_close_many(&single);
1324 netpoll_rx_enable(dev);
1328 static int dev_close_many(struct list_head *head)
1330 struct net_device *dev, *tmp;
1331 LIST_HEAD(tmp_list);
1333 list_for_each_entry_safe(dev, tmp, head, unreg_list)
1334 if (!(dev->flags & IFF_UP))
1335 list_move(&dev->unreg_list, &tmp_list);
1337 __dev_close_many(head);
1339 list_for_each_entry(dev, head, unreg_list) {
1340 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING);
1341 call_netdevice_notifiers(NETDEV_DOWN, dev);
1344 /* rollback_registered_many needs the complete original list */
1345 list_splice(&tmp_list, head);
1350 * dev_close - shutdown an interface.
1351 * @dev: device to shutdown
1353 * This function moves an active device into down state. A
1354 * %NETDEV_GOING_DOWN is sent to the netdev notifier chain. The device
1355 * is then deactivated and finally a %NETDEV_DOWN is sent to the notifier
1358 int dev_close(struct net_device *dev)
1360 if (dev->flags & IFF_UP) {
1363 /* Block netpoll rx while the interface is going down */
1364 netpoll_rx_disable(dev);
1366 list_add(&dev->unreg_list, &single);
1367 dev_close_many(&single);
1370 netpoll_rx_enable(dev);
1374 EXPORT_SYMBOL(dev_close);
1378 * dev_disable_lro - disable Large Receive Offload on a device
1381 * Disable Large Receive Offload (LRO) on a net device. Must be
1382 * called under RTNL. This is needed if received packets may be
1383 * forwarded to another interface.
1385 void dev_disable_lro(struct net_device *dev)
1388 * If we're trying to disable lro on a vlan device
1389 * use the underlying physical device instead
1391 if (is_vlan_dev(dev))
1392 dev = vlan_dev_real_dev(dev);
1394 dev->wanted_features &= ~NETIF_F_LRO;
1395 netdev_update_features(dev);
1397 if (unlikely(dev->features & NETIF_F_LRO))
1398 netdev_WARN(dev, "failed to disable LRO!\n");
1400 EXPORT_SYMBOL(dev_disable_lro);
1402 static int call_netdevice_notifier(struct notifier_block *nb, unsigned long val,
1403 struct net_device *dev)
1405 struct netdev_notifier_info info;
1407 netdev_notifier_info_init(&info, dev);
1408 return nb->notifier_call(nb, val, &info);
1411 static int dev_boot_phase = 1;
1414 * register_netdevice_notifier - register a network notifier block
1417 * Register a notifier to be called when network device events occur.
1418 * The notifier passed is linked into the kernel structures and must
1419 * not be reused until it has been unregistered. A negative errno code
1420 * is returned on a failure.
1422 * When registered all registration and up events are replayed
1423 * to the new notifier to allow device to have a race free
1424 * view of the network device list.
1427 int register_netdevice_notifier(struct notifier_block *nb)
1429 struct net_device *dev;
1430 struct net_device *last;
1435 err = raw_notifier_chain_register(&netdev_chain, nb);
1441 for_each_netdev(net, dev) {
1442 err = call_netdevice_notifier(nb, NETDEV_REGISTER, dev);
1443 err = notifier_to_errno(err);
1447 if (!(dev->flags & IFF_UP))
1450 call_netdevice_notifier(nb, NETDEV_UP, dev);
1461 for_each_netdev(net, dev) {
1465 if (dev->flags & IFF_UP) {
1466 call_netdevice_notifier(nb, NETDEV_GOING_DOWN,
1468 call_netdevice_notifier(nb, NETDEV_DOWN, dev);
1470 call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev);
1475 raw_notifier_chain_unregister(&netdev_chain, nb);
1478 EXPORT_SYMBOL(register_netdevice_notifier);
1481 * unregister_netdevice_notifier - unregister a network notifier block
1484 * Unregister a notifier previously registered by
1485 * register_netdevice_notifier(). The notifier is unlinked into the
1486 * kernel structures and may then be reused. A negative errno code
1487 * is returned on a failure.
1489 * After unregistering unregister and down device events are synthesized
1490 * for all devices on the device list to the removed notifier to remove
1491 * the need for special case cleanup code.
1494 int unregister_netdevice_notifier(struct notifier_block *nb)
1496 struct net_device *dev;
1501 err = raw_notifier_chain_unregister(&netdev_chain, nb);
1506 for_each_netdev(net, dev) {
1507 if (dev->flags & IFF_UP) {
1508 call_netdevice_notifier(nb, NETDEV_GOING_DOWN,
1510 call_netdevice_notifier(nb, NETDEV_DOWN, dev);
1512 call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev);
1519 EXPORT_SYMBOL(unregister_netdevice_notifier);
1522 * call_netdevice_notifiers_info - call all network notifier blocks
1523 * @val: value passed unmodified to notifier function
1524 * @dev: net_device pointer passed unmodified to notifier function
1525 * @info: notifier information data
1527 * Call all network notifier blocks. Parameters and return value
1528 * are as for raw_notifier_call_chain().
1531 int call_netdevice_notifiers_info(unsigned long val, struct net_device *dev,
1532 struct netdev_notifier_info *info)
1535 netdev_notifier_info_init(info, dev);
1536 return raw_notifier_call_chain(&netdev_chain, val, info);
1538 EXPORT_SYMBOL(call_netdevice_notifiers_info);
1541 * call_netdevice_notifiers - call all network notifier blocks
1542 * @val: value passed unmodified to notifier function
1543 * @dev: net_device pointer passed unmodified to notifier function
1545 * Call all network notifier blocks. Parameters and return value
1546 * are as for raw_notifier_call_chain().
1549 int call_netdevice_notifiers(unsigned long val, struct net_device *dev)
1551 struct netdev_notifier_info info;
1553 return call_netdevice_notifiers_info(val, dev, &info);
1555 EXPORT_SYMBOL(call_netdevice_notifiers);
1557 static struct static_key netstamp_needed __read_mostly;
1558 #ifdef HAVE_JUMP_LABEL
1559 /* We are not allowed to call static_key_slow_dec() from irq context
1560 * If net_disable_timestamp() is called from irq context, defer the
1561 * static_key_slow_dec() calls.
1563 static atomic_t netstamp_needed_deferred;
1566 void net_enable_timestamp(void)
1568 #ifdef HAVE_JUMP_LABEL
1569 int deferred = atomic_xchg(&netstamp_needed_deferred, 0);
1573 static_key_slow_dec(&netstamp_needed);
1577 static_key_slow_inc(&netstamp_needed);
1579 EXPORT_SYMBOL(net_enable_timestamp);
1581 void net_disable_timestamp(void)
1583 #ifdef HAVE_JUMP_LABEL
1584 if (in_interrupt()) {
1585 atomic_inc(&netstamp_needed_deferred);
1589 static_key_slow_dec(&netstamp_needed);
1591 EXPORT_SYMBOL(net_disable_timestamp);
1593 static inline void net_timestamp_set(struct sk_buff *skb)
1595 skb->tstamp.tv64 = 0;
1596 if (static_key_false(&netstamp_needed))
1597 __net_timestamp(skb);
1600 #define net_timestamp_check(COND, SKB) \
1601 if (static_key_false(&netstamp_needed)) { \
1602 if ((COND) && !(SKB)->tstamp.tv64) \
1603 __net_timestamp(SKB); \
1606 static inline bool is_skb_forwardable(struct net_device *dev,
1607 struct sk_buff *skb)
1611 if (!(dev->flags & IFF_UP))
1614 len = dev->mtu + dev->hard_header_len + VLAN_HLEN;
1615 if (skb->len <= len)
1618 /* if TSO is enabled, we don't care about the length as the packet
1619 * could be forwarded without being segmented before
1621 if (skb_is_gso(skb))
1628 * dev_forward_skb - loopback an skb to another netif
1630 * @dev: destination network device
1631 * @skb: buffer to forward
1634 * NET_RX_SUCCESS (no congestion)
1635 * NET_RX_DROP (packet was dropped, but freed)
1637 * dev_forward_skb can be used for injecting an skb from the
1638 * start_xmit function of one device into the receive queue
1639 * of another device.
1641 * The receiving device may be in another namespace, so
1642 * we have to clear all information in the skb that could
1643 * impact namespace isolation.
1645 int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
1647 if (skb_shinfo(skb)->tx_flags & SKBTX_DEV_ZEROCOPY) {
1648 if (skb_copy_ubufs(skb, GFP_ATOMIC)) {
1649 atomic_long_inc(&dev->rx_dropped);
1655 if (unlikely(!is_skb_forwardable(dev, skb))) {
1656 atomic_long_inc(&dev->rx_dropped);
1660 skb_scrub_packet(skb);
1661 skb->protocol = eth_type_trans(skb, dev);
1663 /* eth_type_trans() can set pkt_type.
1664 * clear pkt_type _after_ calling eth_type_trans()
1666 skb->pkt_type = PACKET_HOST;
1668 return netif_rx(skb);
1670 EXPORT_SYMBOL_GPL(dev_forward_skb);
1672 static inline int deliver_skb(struct sk_buff *skb,
1673 struct packet_type *pt_prev,
1674 struct net_device *orig_dev)
1676 if (unlikely(skb_orphan_frags(skb, GFP_ATOMIC)))
1678 atomic_inc(&skb->users);
1679 return pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
1682 static inline bool skb_loop_sk(struct packet_type *ptype, struct sk_buff *skb)
1684 if (!ptype->af_packet_priv || !skb->sk)
1687 if (ptype->id_match)
1688 return ptype->id_match(ptype, skb->sk);
1689 else if ((struct sock *)ptype->af_packet_priv == skb->sk)
1696 * Support routine. Sends outgoing frames to any network
1697 * taps currently in use.
1700 static void dev_queue_xmit_nit(struct sk_buff *skb, struct net_device *dev)
1702 struct packet_type *ptype;
1703 struct sk_buff *skb2 = NULL;
1704 struct packet_type *pt_prev = NULL;
1707 list_for_each_entry_rcu(ptype, &ptype_all, list) {
1708 /* Never send packets back to the socket
1711 if ((ptype->dev == dev || !ptype->dev) &&
1712 (!skb_loop_sk(ptype, skb))) {
1714 deliver_skb(skb2, pt_prev, skb->dev);
1719 skb2 = skb_clone(skb, GFP_ATOMIC);
1723 net_timestamp_set(skb2);
1725 /* skb->nh should be correctly
1726 set by sender, so that the second statement is
1727 just protection against buggy protocols.
1729 skb_reset_mac_header(skb2);
1731 if (skb_network_header(skb2) < skb2->data ||
1732 skb_network_header(skb2) > skb_tail_pointer(skb2)) {
1733 net_crit_ratelimited("protocol %04x is buggy, dev %s\n",
1734 ntohs(skb2->protocol),
1736 skb_reset_network_header(skb2);
1739 skb2->transport_header = skb2->network_header;
1740 skb2->pkt_type = PACKET_OUTGOING;
1745 pt_prev->func(skb2, skb->dev, pt_prev, skb->dev);
1750 * netif_setup_tc - Handle tc mappings on real_num_tx_queues change
1751 * @dev: Network device
1752 * @txq: number of queues available
1754 * If real_num_tx_queues is changed the tc mappings may no longer be
1755 * valid. To resolve this verify the tc mapping remains valid and if
1756 * not NULL the mapping. With no priorities mapping to this
1757 * offset/count pair it will no longer be used. In the worst case TC0
1758 * is invalid nothing can be done so disable priority mappings. If is
1759 * expected that drivers will fix this mapping if they can before
1760 * calling netif_set_real_num_tx_queues.
1762 static void netif_setup_tc(struct net_device *dev, unsigned int txq)
1765 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
1767 /* If TC0 is invalidated disable TC mapping */
1768 if (tc->offset + tc->count > txq) {
1769 pr_warn("Number of in use tx queues changed invalidating tc mappings. Priority traffic classification disabled!\n");
1774 /* Invalidated prio to tc mappings set to TC0 */
1775 for (i = 1; i < TC_BITMASK + 1; i++) {
1776 int q = netdev_get_prio_tc_map(dev, i);
1778 tc = &dev->tc_to_txq[q];
1779 if (tc->offset + tc->count > txq) {
1780 pr_warn("Number of in use tx queues changed. Priority %i to tc mapping %i is no longer valid. Setting map to 0\n",
1782 netdev_set_prio_tc_map(dev, i, 0);
1788 static DEFINE_MUTEX(xps_map_mutex);
1789 #define xmap_dereference(P) \
1790 rcu_dereference_protected((P), lockdep_is_held(&xps_map_mutex))
1792 static struct xps_map *remove_xps_queue(struct xps_dev_maps *dev_maps,
1795 struct xps_map *map = NULL;
1799 map = xmap_dereference(dev_maps->cpu_map[cpu]);
1801 for (pos = 0; map && pos < map->len; pos++) {
1802 if (map->queues[pos] == index) {
1804 map->queues[pos] = map->queues[--map->len];
1806 RCU_INIT_POINTER(dev_maps->cpu_map[cpu], NULL);
1807 kfree_rcu(map, rcu);
1817 static void netif_reset_xps_queues_gt(struct net_device *dev, u16 index)
1819 struct xps_dev_maps *dev_maps;
1821 bool active = false;
1823 mutex_lock(&xps_map_mutex);
1824 dev_maps = xmap_dereference(dev->xps_maps);
1829 for_each_possible_cpu(cpu) {
1830 for (i = index; i < dev->num_tx_queues; i++) {
1831 if (!remove_xps_queue(dev_maps, cpu, i))
1834 if (i == dev->num_tx_queues)
1839 RCU_INIT_POINTER(dev->xps_maps, NULL);
1840 kfree_rcu(dev_maps, rcu);
1843 for (i = index; i < dev->num_tx_queues; i++)
1844 netdev_queue_numa_node_write(netdev_get_tx_queue(dev, i),
1848 mutex_unlock(&xps_map_mutex);
1851 static struct xps_map *expand_xps_map(struct xps_map *map,
1854 struct xps_map *new_map;
1855 int alloc_len = XPS_MIN_MAP_ALLOC;
1858 for (pos = 0; map && pos < map->len; pos++) {
1859 if (map->queues[pos] != index)
1864 /* Need to add queue to this CPU's existing map */
1866 if (pos < map->alloc_len)
1869 alloc_len = map->alloc_len * 2;
1872 /* Need to allocate new map to store queue on this CPU's map */
1873 new_map = kzalloc_node(XPS_MAP_SIZE(alloc_len), GFP_KERNEL,
1878 for (i = 0; i < pos; i++)
1879 new_map->queues[i] = map->queues[i];
1880 new_map->alloc_len = alloc_len;
1886 int netif_set_xps_queue(struct net_device *dev, struct cpumask *mask, u16 index)
1888 struct xps_dev_maps *dev_maps, *new_dev_maps = NULL;
1889 struct xps_map *map, *new_map;
1890 int maps_sz = max_t(unsigned int, XPS_DEV_MAPS_SIZE, L1_CACHE_BYTES);
1891 int cpu, numa_node_id = -2;
1892 bool active = false;
1894 mutex_lock(&xps_map_mutex);
1896 dev_maps = xmap_dereference(dev->xps_maps);
1898 /* allocate memory for queue storage */
1899 for_each_online_cpu(cpu) {
1900 if (!cpumask_test_cpu(cpu, mask))
1904 new_dev_maps = kzalloc(maps_sz, GFP_KERNEL);
1905 if (!new_dev_maps) {
1906 mutex_unlock(&xps_map_mutex);
1910 map = dev_maps ? xmap_dereference(dev_maps->cpu_map[cpu]) :
1913 map = expand_xps_map(map, cpu, index);
1917 RCU_INIT_POINTER(new_dev_maps->cpu_map[cpu], map);
1921 goto out_no_new_maps;
1923 for_each_possible_cpu(cpu) {
1924 if (cpumask_test_cpu(cpu, mask) && cpu_online(cpu)) {
1925 /* add queue to CPU maps */
1928 map = xmap_dereference(new_dev_maps->cpu_map[cpu]);
1929 while ((pos < map->len) && (map->queues[pos] != index))
1932 if (pos == map->len)
1933 map->queues[map->len++] = index;
1935 if (numa_node_id == -2)
1936 numa_node_id = cpu_to_node(cpu);
1937 else if (numa_node_id != cpu_to_node(cpu))
1940 } else if (dev_maps) {
1941 /* fill in the new device map from the old device map */
1942 map = xmap_dereference(dev_maps->cpu_map[cpu]);
1943 RCU_INIT_POINTER(new_dev_maps->cpu_map[cpu], map);
1948 rcu_assign_pointer(dev->xps_maps, new_dev_maps);
1950 /* Cleanup old maps */
1952 for_each_possible_cpu(cpu) {
1953 new_map = xmap_dereference(new_dev_maps->cpu_map[cpu]);
1954 map = xmap_dereference(dev_maps->cpu_map[cpu]);
1955 if (map && map != new_map)
1956 kfree_rcu(map, rcu);
1959 kfree_rcu(dev_maps, rcu);
1962 dev_maps = new_dev_maps;
1966 /* update Tx queue numa node */
1967 netdev_queue_numa_node_write(netdev_get_tx_queue(dev, index),
1968 (numa_node_id >= 0) ? numa_node_id :
1974 /* removes queue from unused CPUs */
1975 for_each_possible_cpu(cpu) {
1976 if (cpumask_test_cpu(cpu, mask) && cpu_online(cpu))
1979 if (remove_xps_queue(dev_maps, cpu, index))
1983 /* free map if not active */
1985 RCU_INIT_POINTER(dev->xps_maps, NULL);
1986 kfree_rcu(dev_maps, rcu);
1990 mutex_unlock(&xps_map_mutex);
1994 /* remove any maps that we added */
1995 for_each_possible_cpu(cpu) {
1996 new_map = xmap_dereference(new_dev_maps->cpu_map[cpu]);
1997 map = dev_maps ? xmap_dereference(dev_maps->cpu_map[cpu]) :
1999 if (new_map && new_map != map)
2003 mutex_unlock(&xps_map_mutex);
2005 kfree(new_dev_maps);
2008 EXPORT_SYMBOL(netif_set_xps_queue);
2012 * Routine to help set real_num_tx_queues. To avoid skbs mapped to queues
2013 * greater then real_num_tx_queues stale skbs on the qdisc must be flushed.
2015 int netif_set_real_num_tx_queues(struct net_device *dev, unsigned int txq)
2019 if (txq < 1 || txq > dev->num_tx_queues)
2022 if (dev->reg_state == NETREG_REGISTERED ||
2023 dev->reg_state == NETREG_UNREGISTERING) {
2026 rc = netdev_queue_update_kobjects(dev, dev->real_num_tx_queues,
2032 netif_setup_tc(dev, txq);
2034 if (txq < dev->real_num_tx_queues) {
2035 qdisc_reset_all_tx_gt(dev, txq);
2037 netif_reset_xps_queues_gt(dev, txq);
2042 dev->real_num_tx_queues = txq;
2045 EXPORT_SYMBOL(netif_set_real_num_tx_queues);
2049 * netif_set_real_num_rx_queues - set actual number of RX queues used
2050 * @dev: Network device
2051 * @rxq: Actual number of RX queues
2053 * This must be called either with the rtnl_lock held or before
2054 * registration of the net device. Returns 0 on success, or a
2055 * negative error code. If called before registration, it always
2058 int netif_set_real_num_rx_queues(struct net_device *dev, unsigned int rxq)
2062 if (rxq < 1 || rxq > dev->num_rx_queues)
2065 if (dev->reg_state == NETREG_REGISTERED) {
2068 rc = net_rx_queue_update_kobjects(dev, dev->real_num_rx_queues,
2074 dev->real_num_rx_queues = rxq;
2077 EXPORT_SYMBOL(netif_set_real_num_rx_queues);
2081 * netif_get_num_default_rss_queues - default number of RSS queues
2083 * This routine should set an upper limit on the number of RSS queues
2084 * used by default by multiqueue devices.
2086 int netif_get_num_default_rss_queues(void)
2088 return min_t(int, DEFAULT_MAX_NUM_RSS_QUEUES, num_online_cpus());
2090 EXPORT_SYMBOL(netif_get_num_default_rss_queues);
2092 static inline void __netif_reschedule(struct Qdisc *q)
2094 struct softnet_data *sd;
2095 unsigned long flags;
2097 local_irq_save(flags);
2098 sd = &__get_cpu_var(softnet_data);
2099 q->next_sched = NULL;
2100 *sd->output_queue_tailp = q;
2101 sd->output_queue_tailp = &q->next_sched;
2102 raise_softirq_irqoff(NET_TX_SOFTIRQ);
2103 local_irq_restore(flags);
2106 void __netif_schedule(struct Qdisc *q)
2108 if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state))
2109 __netif_reschedule(q);
2111 EXPORT_SYMBOL(__netif_schedule);
2113 void dev_kfree_skb_irq(struct sk_buff *skb)
2115 if (atomic_dec_and_test(&skb->users)) {
2116 struct softnet_data *sd;
2117 unsigned long flags;
2119 local_irq_save(flags);
2120 sd = &__get_cpu_var(softnet_data);
2121 skb->next = sd->completion_queue;
2122 sd->completion_queue = skb;
2123 raise_softirq_irqoff(NET_TX_SOFTIRQ);
2124 local_irq_restore(flags);
2127 EXPORT_SYMBOL(dev_kfree_skb_irq);
2129 void dev_kfree_skb_any(struct sk_buff *skb)
2131 if (in_irq() || irqs_disabled())
2132 dev_kfree_skb_irq(skb);
2136 EXPORT_SYMBOL(dev_kfree_skb_any);
2140 * netif_device_detach - mark device as removed
2141 * @dev: network device
2143 * Mark device as removed from system and therefore no longer available.
2145 void netif_device_detach(struct net_device *dev)
2147 if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) &&
2148 netif_running(dev)) {
2149 netif_tx_stop_all_queues(dev);
2152 EXPORT_SYMBOL(netif_device_detach);
2155 * netif_device_attach - mark device as attached
2156 * @dev: network device
2158 * Mark device as attached from system and restart if needed.
2160 void netif_device_attach(struct net_device *dev)
2162 if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) &&
2163 netif_running(dev)) {
2164 netif_tx_wake_all_queues(dev);
2165 __netdev_watchdog_up(dev);
2168 EXPORT_SYMBOL(netif_device_attach);
2170 static void skb_warn_bad_offload(const struct sk_buff *skb)
2172 static const netdev_features_t null_features = 0;
2173 struct net_device *dev = skb->dev;
2174 const char *driver = "";
2176 if (!net_ratelimit())
2179 if (dev && dev->dev.parent)
2180 driver = dev_driver_string(dev->dev.parent);
2182 WARN(1, "%s: caps=(%pNF, %pNF) len=%d data_len=%d gso_size=%d "
2183 "gso_type=%d ip_summed=%d\n",
2184 driver, dev ? &dev->features : &null_features,
2185 skb->sk ? &skb->sk->sk_route_caps : &null_features,
2186 skb->len, skb->data_len, skb_shinfo(skb)->gso_size,
2187 skb_shinfo(skb)->gso_type, skb->ip_summed);
2191 * Invalidate hardware checksum when packet is to be mangled, and
2192 * complete checksum manually on outgoing path.
2194 int skb_checksum_help(struct sk_buff *skb)
2197 int ret = 0, offset;
2199 if (skb->ip_summed == CHECKSUM_COMPLETE)
2200 goto out_set_summed;
2202 if (unlikely(skb_shinfo(skb)->gso_size)) {
2203 skb_warn_bad_offload(skb);
2207 /* Before computing a checksum, we should make sure no frag could
2208 * be modified by an external entity : checksum could be wrong.
2210 if (skb_has_shared_frag(skb)) {
2211 ret = __skb_linearize(skb);
2216 offset = skb_checksum_start_offset(skb);
2217 BUG_ON(offset >= skb_headlen(skb));
2218 csum = skb_checksum(skb, offset, skb->len - offset, 0);
2220 offset += skb->csum_offset;
2221 BUG_ON(offset + sizeof(__sum16) > skb_headlen(skb));
2223 if (skb_cloned(skb) &&
2224 !skb_clone_writable(skb, offset + sizeof(__sum16))) {
2225 ret = pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
2230 *(__sum16 *)(skb->data + offset) = csum_fold(csum);
2232 skb->ip_summed = CHECKSUM_NONE;
2236 EXPORT_SYMBOL(skb_checksum_help);
2238 __be16 skb_network_protocol(struct sk_buff *skb)
2240 __be16 type = skb->protocol;
2241 int vlan_depth = ETH_HLEN;
2243 /* Tunnel gso handlers can set protocol to ethernet. */
2244 if (type == htons(ETH_P_TEB)) {
2247 if (unlikely(!pskb_may_pull(skb, sizeof(struct ethhdr))))
2250 eth = (struct ethhdr *)skb_mac_header(skb);
2251 type = eth->h_proto;
2254 while (type == htons(ETH_P_8021Q) || type == htons(ETH_P_8021AD)) {
2255 struct vlan_hdr *vh;
2257 if (unlikely(!pskb_may_pull(skb, vlan_depth + VLAN_HLEN)))
2260 vh = (struct vlan_hdr *)(skb->data + vlan_depth);
2261 type = vh->h_vlan_encapsulated_proto;
2262 vlan_depth += VLAN_HLEN;
2269 * skb_mac_gso_segment - mac layer segmentation handler.
2270 * @skb: buffer to segment
2271 * @features: features for the output path (see dev->features)
2273 struct sk_buff *skb_mac_gso_segment(struct sk_buff *skb,
2274 netdev_features_t features)
2276 struct sk_buff *segs = ERR_PTR(-EPROTONOSUPPORT);
2277 struct packet_offload *ptype;
2278 __be16 type = skb_network_protocol(skb);
2280 if (unlikely(!type))
2281 return ERR_PTR(-EINVAL);
2283 __skb_pull(skb, skb->mac_len);
2286 list_for_each_entry_rcu(ptype, &offload_base, list) {
2287 if (ptype->type == type && ptype->callbacks.gso_segment) {
2288 if (unlikely(skb->ip_summed != CHECKSUM_PARTIAL)) {
2291 err = ptype->callbacks.gso_send_check(skb);
2292 segs = ERR_PTR(err);
2293 if (err || skb_gso_ok(skb, features))
2295 __skb_push(skb, (skb->data -
2296 skb_network_header(skb)));
2298 segs = ptype->callbacks.gso_segment(skb, features);
2304 __skb_push(skb, skb->data - skb_mac_header(skb));
2308 EXPORT_SYMBOL(skb_mac_gso_segment);
2311 /* openvswitch calls this on rx path, so we need a different check.
2313 static inline bool skb_needs_check(struct sk_buff *skb, bool tx_path)
2316 return skb->ip_summed != CHECKSUM_PARTIAL;
2318 return skb->ip_summed == CHECKSUM_NONE;
2322 * __skb_gso_segment - Perform segmentation on skb.
2323 * @skb: buffer to segment
2324 * @features: features for the output path (see dev->features)
2325 * @tx_path: whether it is called in TX path
2327 * This function segments the given skb and returns a list of segments.
2329 * It may return NULL if the skb requires no segmentation. This is
2330 * only possible when GSO is used for verifying header integrity.
2332 struct sk_buff *__skb_gso_segment(struct sk_buff *skb,
2333 netdev_features_t features, bool tx_path)
2335 if (unlikely(skb_needs_check(skb, tx_path))) {
2338 skb_warn_bad_offload(skb);
2340 if (skb_header_cloned(skb) &&
2341 (err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC)))
2342 return ERR_PTR(err);
2345 SKB_GSO_CB(skb)->mac_offset = skb_headroom(skb);
2346 skb_reset_mac_header(skb);
2347 skb_reset_mac_len(skb);
2349 return skb_mac_gso_segment(skb, features);
2351 EXPORT_SYMBOL(__skb_gso_segment);
2353 /* Take action when hardware reception checksum errors are detected. */
2355 void netdev_rx_csum_fault(struct net_device *dev)
2357 if (net_ratelimit()) {
2358 pr_err("%s: hw csum failure\n", dev ? dev->name : "<unknown>");
2362 EXPORT_SYMBOL(netdev_rx_csum_fault);
2365 /* Actually, we should eliminate this check as soon as we know, that:
2366 * 1. IOMMU is present and allows to map all the memory.
2367 * 2. No high memory really exists on this machine.
2370 static int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
2372 #ifdef CONFIG_HIGHMEM
2374 if (!(dev->features & NETIF_F_HIGHDMA)) {
2375 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2376 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2377 if (PageHighMem(skb_frag_page(frag)))
2382 if (PCI_DMA_BUS_IS_PHYS) {
2383 struct device *pdev = dev->dev.parent;
2387 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2388 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2389 dma_addr_t addr = page_to_phys(skb_frag_page(frag));
2390 if (!pdev->dma_mask || addr + PAGE_SIZE - 1 > *pdev->dma_mask)
2399 void (*destructor)(struct sk_buff *skb);
2402 #define DEV_GSO_CB(skb) ((struct dev_gso_cb *)(skb)->cb)
2404 static void dev_gso_skb_destructor(struct sk_buff *skb)
2406 struct dev_gso_cb *cb;
2409 struct sk_buff *nskb = skb->next;
2411 skb->next = nskb->next;
2414 } while (skb->next);
2416 cb = DEV_GSO_CB(skb);
2418 cb->destructor(skb);
2422 * dev_gso_segment - Perform emulated hardware segmentation on skb.
2423 * @skb: buffer to segment
2424 * @features: device features as applicable to this skb
2426 * This function segments the given skb and stores the list of segments
2429 static int dev_gso_segment(struct sk_buff *skb, netdev_features_t features)
2431 struct sk_buff *segs;
2433 segs = skb_gso_segment(skb, features);
2435 /* Verifying header integrity only. */
2440 return PTR_ERR(segs);
2443 DEV_GSO_CB(skb)->destructor = skb->destructor;
2444 skb->destructor = dev_gso_skb_destructor;
2449 static netdev_features_t harmonize_features(struct sk_buff *skb,
2450 __be16 protocol, netdev_features_t features)
2452 if (skb->ip_summed != CHECKSUM_NONE &&
2453 !can_checksum_protocol(features, protocol)) {
2454 features &= ~NETIF_F_ALL_CSUM;
2455 } else if (illegal_highdma(skb->dev, skb)) {
2456 features &= ~NETIF_F_SG;
2462 netdev_features_t netif_skb_features(struct sk_buff *skb)
2464 __be16 protocol = skb->protocol;
2465 netdev_features_t features = skb->dev->features;
2467 if (skb_shinfo(skb)->gso_segs > skb->dev->gso_max_segs)
2468 features &= ~NETIF_F_GSO_MASK;
2470 if (protocol == htons(ETH_P_8021Q) || protocol == htons(ETH_P_8021AD)) {
2471 struct vlan_ethhdr *veh = (struct vlan_ethhdr *)skb->data;
2472 protocol = veh->h_vlan_encapsulated_proto;
2473 } else if (!vlan_tx_tag_present(skb)) {
2474 return harmonize_features(skb, protocol, features);
2477 features &= (skb->dev->vlan_features | NETIF_F_HW_VLAN_CTAG_TX |
2478 NETIF_F_HW_VLAN_STAG_TX);
2480 if (protocol != htons(ETH_P_8021Q) && protocol != htons(ETH_P_8021AD)) {
2481 return harmonize_features(skb, protocol, features);
2483 features &= NETIF_F_SG | NETIF_F_HIGHDMA | NETIF_F_FRAGLIST |
2484 NETIF_F_GEN_CSUM | NETIF_F_HW_VLAN_CTAG_TX |
2485 NETIF_F_HW_VLAN_STAG_TX;
2486 return harmonize_features(skb, protocol, features);
2489 EXPORT_SYMBOL(netif_skb_features);
2492 * Returns true if either:
2493 * 1. skb has frag_list and the device doesn't support FRAGLIST, or
2494 * 2. skb is fragmented and the device does not support SG.
2496 static inline int skb_needs_linearize(struct sk_buff *skb,
2497 netdev_features_t features)
2499 return skb_is_nonlinear(skb) &&
2500 ((skb_has_frag_list(skb) &&
2501 !(features & NETIF_F_FRAGLIST)) ||
2502 (skb_shinfo(skb)->nr_frags &&
2503 !(features & NETIF_F_SG)));
2506 int dev_hard_start_xmit(struct sk_buff *skb, struct net_device *dev,
2507 struct netdev_queue *txq)
2509 const struct net_device_ops *ops = dev->netdev_ops;
2510 int rc = NETDEV_TX_OK;
2511 unsigned int skb_len;
2513 if (likely(!skb->next)) {
2514 netdev_features_t features;
2517 * If device doesn't need skb->dst, release it right now while
2518 * its hot in this cpu cache
2520 if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
2523 features = netif_skb_features(skb);
2525 if (vlan_tx_tag_present(skb) &&
2526 !vlan_hw_offload_capable(features, skb->vlan_proto)) {
2527 skb = __vlan_put_tag(skb, skb->vlan_proto,
2528 vlan_tx_tag_get(skb));
2535 /* If encapsulation offload request, verify we are testing
2536 * hardware encapsulation features instead of standard
2537 * features for the netdev
2539 if (skb->encapsulation)
2540 features &= dev->hw_enc_features;
2542 if (netif_needs_gso(skb, features)) {
2543 if (unlikely(dev_gso_segment(skb, features)))
2548 if (skb_needs_linearize(skb, features) &&
2549 __skb_linearize(skb))
2552 /* If packet is not checksummed and device does not
2553 * support checksumming for this protocol, complete
2554 * checksumming here.
2556 if (skb->ip_summed == CHECKSUM_PARTIAL) {
2557 if (skb->encapsulation)
2558 skb_set_inner_transport_header(skb,
2559 skb_checksum_start_offset(skb));
2561 skb_set_transport_header(skb,
2562 skb_checksum_start_offset(skb));
2563 if (!(features & NETIF_F_ALL_CSUM) &&
2564 skb_checksum_help(skb))
2569 if (!list_empty(&ptype_all))
2570 dev_queue_xmit_nit(skb, dev);
2573 rc = ops->ndo_start_xmit(skb, dev);
2574 trace_net_dev_xmit(skb, rc, dev, skb_len);
2575 if (rc == NETDEV_TX_OK)
2576 txq_trans_update(txq);
2582 struct sk_buff *nskb = skb->next;
2584 skb->next = nskb->next;
2587 if (!list_empty(&ptype_all))
2588 dev_queue_xmit_nit(nskb, dev);
2590 skb_len = nskb->len;
2591 rc = ops->ndo_start_xmit(nskb, dev);
2592 trace_net_dev_xmit(nskb, rc, dev, skb_len);
2593 if (unlikely(rc != NETDEV_TX_OK)) {
2594 if (rc & ~NETDEV_TX_MASK)
2595 goto out_kfree_gso_skb;
2596 nskb->next = skb->next;
2600 txq_trans_update(txq);
2601 if (unlikely(netif_xmit_stopped(txq) && skb->next))
2602 return NETDEV_TX_BUSY;
2603 } while (skb->next);
2606 if (likely(skb->next == NULL)) {
2607 skb->destructor = DEV_GSO_CB(skb)->destructor;
2617 static void qdisc_pkt_len_init(struct sk_buff *skb)
2619 const struct skb_shared_info *shinfo = skb_shinfo(skb);
2621 qdisc_skb_cb(skb)->pkt_len = skb->len;
2623 /* To get more precise estimation of bytes sent on wire,
2624 * we add to pkt_len the headers size of all segments
2626 if (shinfo->gso_size) {
2627 unsigned int hdr_len;
2628 u16 gso_segs = shinfo->gso_segs;
2630 /* mac layer + network layer */
2631 hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
2633 /* + transport layer */
2634 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6)))
2635 hdr_len += tcp_hdrlen(skb);
2637 hdr_len += sizeof(struct udphdr);
2639 if (shinfo->gso_type & SKB_GSO_DODGY)
2640 gso_segs = DIV_ROUND_UP(skb->len - hdr_len,
2643 qdisc_skb_cb(skb)->pkt_len += (gso_segs - 1) * hdr_len;
2647 static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q,
2648 struct net_device *dev,
2649 struct netdev_queue *txq)
2651 spinlock_t *root_lock = qdisc_lock(q);
2655 qdisc_pkt_len_init(skb);
2656 qdisc_calculate_pkt_len(skb, q);
2658 * Heuristic to force contended enqueues to serialize on a
2659 * separate lock before trying to get qdisc main lock.
2660 * This permits __QDISC_STATE_RUNNING owner to get the lock more often
2661 * and dequeue packets faster.
2663 contended = qdisc_is_running(q);
2664 if (unlikely(contended))
2665 spin_lock(&q->busylock);
2667 spin_lock(root_lock);
2668 if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) {
2671 } else if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) &&
2672 qdisc_run_begin(q)) {
2674 * This is a work-conserving queue; there are no old skbs
2675 * waiting to be sent out; and the qdisc is not running -
2676 * xmit the skb directly.
2678 if (!(dev->priv_flags & IFF_XMIT_DST_RELEASE))
2681 qdisc_bstats_update(q, skb);
2683 if (sch_direct_xmit(skb, q, dev, txq, root_lock)) {
2684 if (unlikely(contended)) {
2685 spin_unlock(&q->busylock);
2692 rc = NET_XMIT_SUCCESS;
2695 rc = q->enqueue(skb, q) & NET_XMIT_MASK;
2696 if (qdisc_run_begin(q)) {
2697 if (unlikely(contended)) {
2698 spin_unlock(&q->busylock);
2704 spin_unlock(root_lock);
2705 if (unlikely(contended))
2706 spin_unlock(&q->busylock);
2710 #if IS_ENABLED(CONFIG_NETPRIO_CGROUP)
2711 static void skb_update_prio(struct sk_buff *skb)
2713 struct netprio_map *map = rcu_dereference_bh(skb->dev->priomap);
2715 if (!skb->priority && skb->sk && map) {
2716 unsigned int prioidx = skb->sk->sk_cgrp_prioidx;
2718 if (prioidx < map->priomap_len)
2719 skb->priority = map->priomap[prioidx];
2723 #define skb_update_prio(skb)
2726 static DEFINE_PER_CPU(int, xmit_recursion);
2727 #define RECURSION_LIMIT 10
2730 * dev_loopback_xmit - loop back @skb
2731 * @skb: buffer to transmit
2733 int dev_loopback_xmit(struct sk_buff *skb)
2735 skb_reset_mac_header(skb);
2736 __skb_pull(skb, skb_network_offset(skb));
2737 skb->pkt_type = PACKET_LOOPBACK;
2738 skb->ip_summed = CHECKSUM_UNNECESSARY;
2739 WARN_ON(!skb_dst(skb));
2744 EXPORT_SYMBOL(dev_loopback_xmit);
2747 * dev_queue_xmit - transmit a buffer
2748 * @skb: buffer to transmit
2750 * Queue a buffer for transmission to a network device. The caller must
2751 * have set the device and priority and built the buffer before calling
2752 * this function. The function can be called from an interrupt.
2754 * A negative errno code is returned on a failure. A success does not
2755 * guarantee the frame will be transmitted as it may be dropped due
2756 * to congestion or traffic shaping.
2758 * -----------------------------------------------------------------------------------
2759 * I notice this method can also return errors from the queue disciplines,
2760 * including NET_XMIT_DROP, which is a positive value. So, errors can also
2763 * Regardless of the return value, the skb is consumed, so it is currently
2764 * difficult to retry a send to this method. (You can bump the ref count
2765 * before sending to hold a reference for retry if you are careful.)
2767 * When calling this method, interrupts MUST be enabled. This is because
2768 * the BH enable code must have IRQs enabled so that it will not deadlock.
2771 int dev_queue_xmit(struct sk_buff *skb)
2773 struct net_device *dev = skb->dev;
2774 struct netdev_queue *txq;
2778 skb_reset_mac_header(skb);
2780 /* Disable soft irqs for various locks below. Also
2781 * stops preemption for RCU.
2785 skb_update_prio(skb);
2787 txq = netdev_pick_tx(dev, skb);
2788 q = rcu_dereference_bh(txq->qdisc);
2790 #ifdef CONFIG_NET_CLS_ACT
2791 skb->tc_verd = SET_TC_AT(skb->tc_verd, AT_EGRESS);
2793 trace_net_dev_queue(skb);
2795 rc = __dev_xmit_skb(skb, q, dev, txq);
2799 /* The device has no queue. Common case for software devices:
2800 loopback, all the sorts of tunnels...
2802 Really, it is unlikely that netif_tx_lock protection is necessary
2803 here. (f.e. loopback and IP tunnels are clean ignoring statistics
2805 However, it is possible, that they rely on protection
2808 Check this and shot the lock. It is not prone from deadlocks.
2809 Either shot noqueue qdisc, it is even simpler 8)
2811 if (dev->flags & IFF_UP) {
2812 int cpu = smp_processor_id(); /* ok because BHs are off */
2814 if (txq->xmit_lock_owner != cpu) {
2816 if (__this_cpu_read(xmit_recursion) > RECURSION_LIMIT)
2817 goto recursion_alert;
2819 HARD_TX_LOCK(dev, txq, cpu);
2821 if (!netif_xmit_stopped(txq)) {
2822 __this_cpu_inc(xmit_recursion);
2823 rc = dev_hard_start_xmit(skb, dev, txq);
2824 __this_cpu_dec(xmit_recursion);
2825 if (dev_xmit_complete(rc)) {
2826 HARD_TX_UNLOCK(dev, txq);
2830 HARD_TX_UNLOCK(dev, txq);
2831 net_crit_ratelimited("Virtual device %s asks to queue packet!\n",
2834 /* Recursion is detected! It is possible,
2838 net_crit_ratelimited("Dead loop on virtual device %s, fix it urgently!\n",
2844 rcu_read_unlock_bh();
2849 rcu_read_unlock_bh();
2852 EXPORT_SYMBOL(dev_queue_xmit);
2855 /*=======================================================================
2857 =======================================================================*/
2859 int netdev_max_backlog __read_mostly = 1000;
2860 EXPORT_SYMBOL(netdev_max_backlog);
2862 int netdev_tstamp_prequeue __read_mostly = 1;
2863 int netdev_budget __read_mostly = 300;
2864 int weight_p __read_mostly = 64; /* old backlog weight */
2866 /* Called with irq disabled */
2867 static inline void ____napi_schedule(struct softnet_data *sd,
2868 struct napi_struct *napi)
2870 list_add_tail(&napi->poll_list, &sd->poll_list);
2871 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
2876 /* One global table that all flow-based protocols share. */
2877 struct rps_sock_flow_table __rcu *rps_sock_flow_table __read_mostly;
2878 EXPORT_SYMBOL(rps_sock_flow_table);
2880 struct static_key rps_needed __read_mostly;
2882 static struct rps_dev_flow *
2883 set_rps_cpu(struct net_device *dev, struct sk_buff *skb,
2884 struct rps_dev_flow *rflow, u16 next_cpu)
2886 if (next_cpu != RPS_NO_CPU) {
2887 #ifdef CONFIG_RFS_ACCEL
2888 struct netdev_rx_queue *rxqueue;
2889 struct rps_dev_flow_table *flow_table;
2890 struct rps_dev_flow *old_rflow;
2895 /* Should we steer this flow to a different hardware queue? */
2896 if (!skb_rx_queue_recorded(skb) || !dev->rx_cpu_rmap ||
2897 !(dev->features & NETIF_F_NTUPLE))
2899 rxq_index = cpu_rmap_lookup_index(dev->rx_cpu_rmap, next_cpu);
2900 if (rxq_index == skb_get_rx_queue(skb))
2903 rxqueue = dev->_rx + rxq_index;
2904 flow_table = rcu_dereference(rxqueue->rps_flow_table);
2907 flow_id = skb->rxhash & flow_table->mask;
2908 rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb,
2909 rxq_index, flow_id);
2913 rflow = &flow_table->flows[flow_id];
2915 if (old_rflow->filter == rflow->filter)
2916 old_rflow->filter = RPS_NO_FILTER;
2920 per_cpu(softnet_data, next_cpu).input_queue_head;
2923 rflow->cpu = next_cpu;
2928 * get_rps_cpu is called from netif_receive_skb and returns the target
2929 * CPU from the RPS map of the receiving queue for a given skb.
2930 * rcu_read_lock must be held on entry.
2932 static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb,
2933 struct rps_dev_flow **rflowp)
2935 struct netdev_rx_queue *rxqueue;
2936 struct rps_map *map;
2937 struct rps_dev_flow_table *flow_table;
2938 struct rps_sock_flow_table *sock_flow_table;
2942 if (skb_rx_queue_recorded(skb)) {
2943 u16 index = skb_get_rx_queue(skb);
2944 if (unlikely(index >= dev->real_num_rx_queues)) {
2945 WARN_ONCE(dev->real_num_rx_queues > 1,
2946 "%s received packet on queue %u, but number "
2947 "of RX queues is %u\n",
2948 dev->name, index, dev->real_num_rx_queues);
2951 rxqueue = dev->_rx + index;
2955 map = rcu_dereference(rxqueue->rps_map);
2957 if (map->len == 1 &&
2958 !rcu_access_pointer(rxqueue->rps_flow_table)) {
2959 tcpu = map->cpus[0];
2960 if (cpu_online(tcpu))
2964 } else if (!rcu_access_pointer(rxqueue->rps_flow_table)) {
2968 skb_reset_network_header(skb);
2969 if (!skb_get_rxhash(skb))
2972 flow_table = rcu_dereference(rxqueue->rps_flow_table);
2973 sock_flow_table = rcu_dereference(rps_sock_flow_table);
2974 if (flow_table && sock_flow_table) {
2976 struct rps_dev_flow *rflow;
2978 rflow = &flow_table->flows[skb->rxhash & flow_table->mask];
2981 next_cpu = sock_flow_table->ents[skb->rxhash &
2982 sock_flow_table->mask];
2985 * If the desired CPU (where last recvmsg was done) is
2986 * different from current CPU (one in the rx-queue flow
2987 * table entry), switch if one of the following holds:
2988 * - Current CPU is unset (equal to RPS_NO_CPU).
2989 * - Current CPU is offline.
2990 * - The current CPU's queue tail has advanced beyond the
2991 * last packet that was enqueued using this table entry.
2992 * This guarantees that all previous packets for the flow
2993 * have been dequeued, thus preserving in order delivery.
2995 if (unlikely(tcpu != next_cpu) &&
2996 (tcpu == RPS_NO_CPU || !cpu_online(tcpu) ||
2997 ((int)(per_cpu(softnet_data, tcpu).input_queue_head -
2998 rflow->last_qtail)) >= 0)) {
3000 rflow = set_rps_cpu(dev, skb, rflow, next_cpu);
3003 if (tcpu != RPS_NO_CPU && cpu_online(tcpu)) {
3011 tcpu = map->cpus[((u64) skb->rxhash * map->len) >> 32];
3013 if (cpu_online(tcpu)) {
3023 #ifdef CONFIG_RFS_ACCEL
3026 * rps_may_expire_flow - check whether an RFS hardware filter may be removed
3027 * @dev: Device on which the filter was set
3028 * @rxq_index: RX queue index
3029 * @flow_id: Flow ID passed to ndo_rx_flow_steer()
3030 * @filter_id: Filter ID returned by ndo_rx_flow_steer()
3032 * Drivers that implement ndo_rx_flow_steer() should periodically call
3033 * this function for each installed filter and remove the filters for
3034 * which it returns %true.
3036 bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index,
3037 u32 flow_id, u16 filter_id)
3039 struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index;
3040 struct rps_dev_flow_table *flow_table;
3041 struct rps_dev_flow *rflow;
3046 flow_table = rcu_dereference(rxqueue->rps_flow_table);
3047 if (flow_table && flow_id <= flow_table->mask) {
3048 rflow = &flow_table->flows[flow_id];
3049 cpu = ACCESS_ONCE(rflow->cpu);
3050 if (rflow->filter == filter_id && cpu != RPS_NO_CPU &&
3051 ((int)(per_cpu(softnet_data, cpu).input_queue_head -
3052 rflow->last_qtail) <
3053 (int)(10 * flow_table->mask)))
3059 EXPORT_SYMBOL(rps_may_expire_flow);
3061 #endif /* CONFIG_RFS_ACCEL */
3063 /* Called from hardirq (IPI) context */
3064 static void rps_trigger_softirq(void *data)
3066 struct softnet_data *sd = data;
3068 ____napi_schedule(sd, &sd->backlog);
3072 #endif /* CONFIG_RPS */
3075 * Check if this softnet_data structure is another cpu one
3076 * If yes, queue it to our IPI list and return 1
3079 static int rps_ipi_queued(struct softnet_data *sd)
3082 struct softnet_data *mysd = &__get_cpu_var(softnet_data);
3085 sd->rps_ipi_next = mysd->rps_ipi_list;
3086 mysd->rps_ipi_list = sd;
3088 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
3091 #endif /* CONFIG_RPS */
3095 #ifdef CONFIG_NET_FLOW_LIMIT
3096 int netdev_flow_limit_table_len __read_mostly = (1 << 12);
3099 static bool skb_flow_limit(struct sk_buff *skb, unsigned int qlen)
3101 #ifdef CONFIG_NET_FLOW_LIMIT
3102 struct sd_flow_limit *fl;
3103 struct softnet_data *sd;
3104 unsigned int old_flow, new_flow;
3106 if (qlen < (netdev_max_backlog >> 1))
3109 sd = &__get_cpu_var(softnet_data);
3112 fl = rcu_dereference(sd->flow_limit);
3114 new_flow = skb_get_rxhash(skb) & (fl->num_buckets - 1);
3115 old_flow = fl->history[fl->history_head];
3116 fl->history[fl->history_head] = new_flow;
3119 fl->history_head &= FLOW_LIMIT_HISTORY - 1;
3121 if (likely(fl->buckets[old_flow]))
3122 fl->buckets[old_flow]--;
3124 if (++fl->buckets[new_flow] > (FLOW_LIMIT_HISTORY >> 1)) {
3136 * enqueue_to_backlog is called to queue an skb to a per CPU backlog
3137 * queue (may be a remote CPU queue).
3139 static int enqueue_to_backlog(struct sk_buff *skb, int cpu,
3140 unsigned int *qtail)
3142 struct softnet_data *sd;
3143 unsigned long flags;
3146 sd = &per_cpu(softnet_data, cpu);
3148 local_irq_save(flags);
3151 qlen = skb_queue_len(&sd->input_pkt_queue);
3152 if (qlen <= netdev_max_backlog && !skb_flow_limit(skb, qlen)) {
3153 if (skb_queue_len(&sd->input_pkt_queue)) {
3155 __skb_queue_tail(&sd->input_pkt_queue, skb);
3156 input_queue_tail_incr_save(sd, qtail);
3158 local_irq_restore(flags);
3159 return NET_RX_SUCCESS;
3162 /* Schedule NAPI for backlog device
3163 * We can use non atomic operation since we own the queue lock
3165 if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state)) {
3166 if (!rps_ipi_queued(sd))
3167 ____napi_schedule(sd, &sd->backlog);
3175 local_irq_restore(flags);
3177 atomic_long_inc(&skb->dev->rx_dropped);
3183 * netif_rx - post buffer to the network code
3184 * @skb: buffer to post
3186 * This function receives a packet from a device driver and queues it for
3187 * the upper (protocol) levels to process. It always succeeds. The buffer
3188 * may be dropped during processing for congestion control or by the
3192 * NET_RX_SUCCESS (no congestion)
3193 * NET_RX_DROP (packet was dropped)
3197 int netif_rx(struct sk_buff *skb)
3201 /* if netpoll wants it, pretend we never saw it */
3202 if (netpoll_rx(skb))
3205 net_timestamp_check(netdev_tstamp_prequeue, skb);
3207 trace_netif_rx(skb);
3209 if (static_key_false(&rps_needed)) {
3210 struct rps_dev_flow voidflow, *rflow = &voidflow;
3216 cpu = get_rps_cpu(skb->dev, skb, &rflow);
3218 cpu = smp_processor_id();
3220 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
3228 ret = enqueue_to_backlog(skb, get_cpu(), &qtail);
3233 EXPORT_SYMBOL(netif_rx);
3235 int netif_rx_ni(struct sk_buff *skb)
3240 err = netif_rx(skb);
3241 if (local_softirq_pending())
3247 EXPORT_SYMBOL(netif_rx_ni);
3249 static void net_tx_action(struct softirq_action *h)
3251 struct softnet_data *sd = &__get_cpu_var(softnet_data);
3253 if (sd->completion_queue) {
3254 struct sk_buff *clist;
3256 local_irq_disable();
3257 clist = sd->completion_queue;
3258 sd->completion_queue = NULL;
3262 struct sk_buff *skb = clist;
3263 clist = clist->next;
3265 WARN_ON(atomic_read(&skb->users));
3266 trace_kfree_skb(skb, net_tx_action);
3271 if (sd->output_queue) {
3274 local_irq_disable();
3275 head = sd->output_queue;
3276 sd->output_queue = NULL;
3277 sd->output_queue_tailp = &sd->output_queue;
3281 struct Qdisc *q = head;
3282 spinlock_t *root_lock;
3284 head = head->next_sched;
3286 root_lock = qdisc_lock(q);
3287 if (spin_trylock(root_lock)) {
3288 smp_mb__before_clear_bit();
3289 clear_bit(__QDISC_STATE_SCHED,
3292 spin_unlock(root_lock);
3294 if (!test_bit(__QDISC_STATE_DEACTIVATED,
3296 __netif_reschedule(q);
3298 smp_mb__before_clear_bit();
3299 clear_bit(__QDISC_STATE_SCHED,
3307 #if (defined(CONFIG_BRIDGE) || defined(CONFIG_BRIDGE_MODULE)) && \
3308 (defined(CONFIG_ATM_LANE) || defined(CONFIG_ATM_LANE_MODULE))
3309 /* This hook is defined here for ATM LANE */
3310 int (*br_fdb_test_addr_hook)(struct net_device *dev,
3311 unsigned char *addr) __read_mostly;
3312 EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook);
3315 #ifdef CONFIG_NET_CLS_ACT
3316 /* TODO: Maybe we should just force sch_ingress to be compiled in
3317 * when CONFIG_NET_CLS_ACT is? otherwise some useless instructions
3318 * a compare and 2 stores extra right now if we dont have it on
3319 * but have CONFIG_NET_CLS_ACT
3320 * NOTE: This doesn't stop any functionality; if you dont have
3321 * the ingress scheduler, you just can't add policies on ingress.
3324 static int ing_filter(struct sk_buff *skb, struct netdev_queue *rxq)
3326 struct net_device *dev = skb->dev;
3327 u32 ttl = G_TC_RTTL(skb->tc_verd);
3328 int result = TC_ACT_OK;
3331 if (unlikely(MAX_RED_LOOP < ttl++)) {
3332 net_warn_ratelimited("Redir loop detected Dropping packet (%d->%d)\n",
3333 skb->skb_iif, dev->ifindex);
3337 skb->tc_verd = SET_TC_RTTL(skb->tc_verd, ttl);
3338 skb->tc_verd = SET_TC_AT(skb->tc_verd, AT_INGRESS);
3341 if (q != &noop_qdisc) {
3342 spin_lock(qdisc_lock(q));
3343 if (likely(!test_bit(__QDISC_STATE_DEACTIVATED, &q->state)))
3344 result = qdisc_enqueue_root(skb, q);
3345 spin_unlock(qdisc_lock(q));
3351 static inline struct sk_buff *handle_ing(struct sk_buff *skb,
3352 struct packet_type **pt_prev,
3353 int *ret, struct net_device *orig_dev)
3355 struct netdev_queue *rxq = rcu_dereference(skb->dev->ingress_queue);
3357 if (!rxq || rxq->qdisc == &noop_qdisc)
3361 *ret = deliver_skb(skb, *pt_prev, orig_dev);
3365 switch (ing_filter(skb, rxq)) {
3379 * netdev_rx_handler_register - register receive handler
3380 * @dev: device to register a handler for
3381 * @rx_handler: receive handler to register
3382 * @rx_handler_data: data pointer that is used by rx handler
3384 * Register a receive hander for a device. This handler will then be
3385 * called from __netif_receive_skb. A negative errno code is returned
3388 * The caller must hold the rtnl_mutex.
3390 * For a general description of rx_handler, see enum rx_handler_result.
3392 int netdev_rx_handler_register(struct net_device *dev,
3393 rx_handler_func_t *rx_handler,
3394 void *rx_handler_data)
3398 if (dev->rx_handler)
3401 /* Note: rx_handler_data must be set before rx_handler */
3402 rcu_assign_pointer(dev->rx_handler_data, rx_handler_data);
3403 rcu_assign_pointer(dev->rx_handler, rx_handler);
3407 EXPORT_SYMBOL_GPL(netdev_rx_handler_register);
3410 * netdev_rx_handler_unregister - unregister receive handler
3411 * @dev: device to unregister a handler from
3413 * Unregister a receive handler from a device.
3415 * The caller must hold the rtnl_mutex.
3417 void netdev_rx_handler_unregister(struct net_device *dev)
3421 RCU_INIT_POINTER(dev->rx_handler, NULL);
3422 /* a reader seeing a non NULL rx_handler in a rcu_read_lock()
3423 * section has a guarantee to see a non NULL rx_handler_data
3427 RCU_INIT_POINTER(dev->rx_handler_data, NULL);
3429 EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister);
3432 * Limit the use of PFMEMALLOC reserves to those protocols that implement
3433 * the special handling of PFMEMALLOC skbs.
3435 static bool skb_pfmemalloc_protocol(struct sk_buff *skb)
3437 switch (skb->protocol) {
3438 case __constant_htons(ETH_P_ARP):
3439 case __constant_htons(ETH_P_IP):
3440 case __constant_htons(ETH_P_IPV6):
3441 case __constant_htons(ETH_P_8021Q):
3442 case __constant_htons(ETH_P_8021AD):
3449 static int __netif_receive_skb_core(struct sk_buff *skb, bool pfmemalloc)
3451 struct packet_type *ptype, *pt_prev;
3452 rx_handler_func_t *rx_handler;
3453 struct net_device *orig_dev;
3454 struct net_device *null_or_dev;
3455 bool deliver_exact = false;
3456 int ret = NET_RX_DROP;
3459 net_timestamp_check(!netdev_tstamp_prequeue, skb);
3461 trace_netif_receive_skb(skb);
3463 /* if we've gotten here through NAPI, check netpoll */
3464 if (netpoll_receive_skb(skb))
3467 orig_dev = skb->dev;
3469 skb_reset_network_header(skb);
3470 if (!skb_transport_header_was_set(skb))
3471 skb_reset_transport_header(skb);
3472 skb_reset_mac_len(skb);
3479 skb->skb_iif = skb->dev->ifindex;
3481 __this_cpu_inc(softnet_data.processed);
3483 if (skb->protocol == cpu_to_be16(ETH_P_8021Q) ||
3484 skb->protocol == cpu_to_be16(ETH_P_8021AD)) {
3485 skb = vlan_untag(skb);
3490 #ifdef CONFIG_NET_CLS_ACT
3491 if (skb->tc_verd & TC_NCLS) {
3492 skb->tc_verd = CLR_TC_NCLS(skb->tc_verd);
3500 list_for_each_entry_rcu(ptype, &ptype_all, list) {
3501 if (!ptype->dev || ptype->dev == skb->dev) {
3503 ret = deliver_skb(skb, pt_prev, orig_dev);
3509 #ifdef CONFIG_NET_CLS_ACT
3510 skb = handle_ing(skb, &pt_prev, &ret, orig_dev);
3516 if (pfmemalloc && !skb_pfmemalloc_protocol(skb))
3519 if (vlan_tx_tag_present(skb)) {
3521 ret = deliver_skb(skb, pt_prev, orig_dev);
3524 if (vlan_do_receive(&skb))
3526 else if (unlikely(!skb))
3530 rx_handler = rcu_dereference(skb->dev->rx_handler);
3533 ret = deliver_skb(skb, pt_prev, orig_dev);
3536 switch (rx_handler(&skb)) {
3537 case RX_HANDLER_CONSUMED:
3538 ret = NET_RX_SUCCESS;
3540 case RX_HANDLER_ANOTHER:
3542 case RX_HANDLER_EXACT:
3543 deliver_exact = true;
3544 case RX_HANDLER_PASS:
3551 if (vlan_tx_nonzero_tag_present(skb))
3552 skb->pkt_type = PACKET_OTHERHOST;
3554 /* deliver only exact match when indicated */
3555 null_or_dev = deliver_exact ? skb->dev : NULL;
3557 type = skb->protocol;
3558 list_for_each_entry_rcu(ptype,
3559 &ptype_base[ntohs(type) & PTYPE_HASH_MASK], list) {
3560 if (ptype->type == type &&
3561 (ptype->dev == null_or_dev || ptype->dev == skb->dev ||
3562 ptype->dev == orig_dev)) {
3564 ret = deliver_skb(skb, pt_prev, orig_dev);
3570 if (unlikely(skb_orphan_frags(skb, GFP_ATOMIC)))
3573 ret = pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
3576 atomic_long_inc(&skb->dev->rx_dropped);
3578 /* Jamal, now you will not able to escape explaining
3579 * me how you were going to use this. :-)
3590 static int __netif_receive_skb(struct sk_buff *skb)
3594 if (sk_memalloc_socks() && skb_pfmemalloc(skb)) {
3595 unsigned long pflags = current->flags;
3598 * PFMEMALLOC skbs are special, they should
3599 * - be delivered to SOCK_MEMALLOC sockets only
3600 * - stay away from userspace
3601 * - have bounded memory usage
3603 * Use PF_MEMALLOC as this saves us from propagating the allocation
3604 * context down to all allocation sites.
3606 current->flags |= PF_MEMALLOC;
3607 ret = __netif_receive_skb_core(skb, true);
3608 tsk_restore_flags(current, pflags, PF_MEMALLOC);
3610 ret = __netif_receive_skb_core(skb, false);
3616 * netif_receive_skb - process receive buffer from network
3617 * @skb: buffer to process
3619 * netif_receive_skb() is the main receive data processing function.
3620 * It always succeeds. The buffer may be dropped during processing
3621 * for congestion control or by the protocol layers.
3623 * This function may only be called from softirq context and interrupts
3624 * should be enabled.
3626 * Return values (usually ignored):
3627 * NET_RX_SUCCESS: no congestion
3628 * NET_RX_DROP: packet was dropped
3630 int netif_receive_skb(struct sk_buff *skb)
3632 net_timestamp_check(netdev_tstamp_prequeue, skb);
3634 if (skb_defer_rx_timestamp(skb))
3635 return NET_RX_SUCCESS;
3638 if (static_key_false(&rps_needed)) {
3639 struct rps_dev_flow voidflow, *rflow = &voidflow;
3644 cpu = get_rps_cpu(skb->dev, skb, &rflow);
3647 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
3654 return __netif_receive_skb(skb);
3656 EXPORT_SYMBOL(netif_receive_skb);
3658 /* Network device is going away, flush any packets still pending
3659 * Called with irqs disabled.
3661 static void flush_backlog(void *arg)
3663 struct net_device *dev = arg;
3664 struct softnet_data *sd = &__get_cpu_var(softnet_data);
3665 struct sk_buff *skb, *tmp;
3668 skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) {
3669 if (skb->dev == dev) {
3670 __skb_unlink(skb, &sd->input_pkt_queue);
3672 input_queue_head_incr(sd);
3677 skb_queue_walk_safe(&sd->process_queue, skb, tmp) {
3678 if (skb->dev == dev) {
3679 __skb_unlink(skb, &sd->process_queue);
3681 input_queue_head_incr(sd);
3686 static int napi_gro_complete(struct sk_buff *skb)
3688 struct packet_offload *ptype;
3689 __be16 type = skb->protocol;
3690 struct list_head *head = &offload_base;
3693 BUILD_BUG_ON(sizeof(struct napi_gro_cb) > sizeof(skb->cb));
3695 if (NAPI_GRO_CB(skb)->count == 1) {
3696 skb_shinfo(skb)->gso_size = 0;
3701 list_for_each_entry_rcu(ptype, head, list) {
3702 if (ptype->type != type || !ptype->callbacks.gro_complete)
3705 err = ptype->callbacks.gro_complete(skb);
3711 WARN_ON(&ptype->list == head);
3713 return NET_RX_SUCCESS;
3717 return netif_receive_skb(skb);
3720 /* napi->gro_list contains packets ordered by age.
3721 * youngest packets at the head of it.
3722 * Complete skbs in reverse order to reduce latencies.
3724 void napi_gro_flush(struct napi_struct *napi, bool flush_old)
3726 struct sk_buff *skb, *prev = NULL;
3728 /* scan list and build reverse chain */
3729 for (skb = napi->gro_list; skb != NULL; skb = skb->next) {
3734 for (skb = prev; skb; skb = prev) {
3737 if (flush_old && NAPI_GRO_CB(skb)->age == jiffies)
3741 napi_gro_complete(skb);
3745 napi->gro_list = NULL;
3747 EXPORT_SYMBOL(napi_gro_flush);
3749 static void gro_list_prepare(struct napi_struct *napi, struct sk_buff *skb)
3752 unsigned int maclen = skb->dev->hard_header_len;
3754 for (p = napi->gro_list; p; p = p->next) {
3755 unsigned long diffs;
3757 diffs = (unsigned long)p->dev ^ (unsigned long)skb->dev;
3758 diffs |= p->vlan_tci ^ skb->vlan_tci;
3759 if (maclen == ETH_HLEN)
3760 diffs |= compare_ether_header(skb_mac_header(p),
3761 skb_gro_mac_header(skb));
3763 diffs = memcmp(skb_mac_header(p),
3764 skb_gro_mac_header(skb),
3766 NAPI_GRO_CB(p)->same_flow = !diffs;
3767 NAPI_GRO_CB(p)->flush = 0;
3771 static enum gro_result dev_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
3773 struct sk_buff **pp = NULL;
3774 struct packet_offload *ptype;
3775 __be16 type = skb->protocol;
3776 struct list_head *head = &offload_base;
3778 enum gro_result ret;
3780 if (!(skb->dev->features & NETIF_F_GRO) || netpoll_rx_on(skb))
3783 if (skb_is_gso(skb) || skb_has_frag_list(skb))
3786 gro_list_prepare(napi, skb);
3789 list_for_each_entry_rcu(ptype, head, list) {
3790 if (ptype->type != type || !ptype->callbacks.gro_receive)
3793 skb_set_network_header(skb, skb_gro_offset(skb));
3794 skb_reset_mac_len(skb);
3795 NAPI_GRO_CB(skb)->same_flow = 0;
3796 NAPI_GRO_CB(skb)->flush = 0;
3797 NAPI_GRO_CB(skb)->free = 0;
3799 pp = ptype->callbacks.gro_receive(&napi->gro_list, skb);
3804 if (&ptype->list == head)
3807 same_flow = NAPI_GRO_CB(skb)->same_flow;
3808 ret = NAPI_GRO_CB(skb)->free ? GRO_MERGED_FREE : GRO_MERGED;
3811 struct sk_buff *nskb = *pp;
3815 napi_gro_complete(nskb);
3822 if (NAPI_GRO_CB(skb)->flush || napi->gro_count >= MAX_GRO_SKBS)
3826 NAPI_GRO_CB(skb)->count = 1;
3827 NAPI_GRO_CB(skb)->age = jiffies;
3828 skb_shinfo(skb)->gso_size = skb_gro_len(skb);
3829 skb->next = napi->gro_list;
3830 napi->gro_list = skb;
3834 if (skb_headlen(skb) < skb_gro_offset(skb)) {
3835 int grow = skb_gro_offset(skb) - skb_headlen(skb);
3837 BUG_ON(skb->end - skb->tail < grow);
3839 memcpy(skb_tail_pointer(skb), NAPI_GRO_CB(skb)->frag0, grow);
3842 skb->data_len -= grow;
3844 skb_shinfo(skb)->frags[0].page_offset += grow;
3845 skb_frag_size_sub(&skb_shinfo(skb)->frags[0], grow);
3847 if (unlikely(!skb_frag_size(&skb_shinfo(skb)->frags[0]))) {
3848 skb_frag_unref(skb, 0);
3849 memmove(skb_shinfo(skb)->frags,
3850 skb_shinfo(skb)->frags + 1,
3851 --skb_shinfo(skb)->nr_frags * sizeof(skb_frag_t));
3864 static gro_result_t napi_skb_finish(gro_result_t ret, struct sk_buff *skb)
3868 if (netif_receive_skb(skb))
3876 case GRO_MERGED_FREE:
3877 if (NAPI_GRO_CB(skb)->free == NAPI_GRO_FREE_STOLEN_HEAD)
3878 kmem_cache_free(skbuff_head_cache, skb);
3891 static void skb_gro_reset_offset(struct sk_buff *skb)
3893 const struct skb_shared_info *pinfo = skb_shinfo(skb);
3894 const skb_frag_t *frag0 = &pinfo->frags[0];
3896 NAPI_GRO_CB(skb)->data_offset = 0;
3897 NAPI_GRO_CB(skb)->frag0 = NULL;
3898 NAPI_GRO_CB(skb)->frag0_len = 0;
3900 if (skb_mac_header(skb) == skb_tail_pointer(skb) &&
3902 !PageHighMem(skb_frag_page(frag0))) {
3903 NAPI_GRO_CB(skb)->frag0 = skb_frag_address(frag0);
3904 NAPI_GRO_CB(skb)->frag0_len = skb_frag_size(frag0);
3908 gro_result_t napi_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
3910 skb_gro_reset_offset(skb);
3912 return napi_skb_finish(dev_gro_receive(napi, skb), skb);
3914 EXPORT_SYMBOL(napi_gro_receive);
3916 static void napi_reuse_skb(struct napi_struct *napi, struct sk_buff *skb)
3918 __skb_pull(skb, skb_headlen(skb));
3919 /* restore the reserve we had after netdev_alloc_skb_ip_align() */
3920 skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN - skb_headroom(skb));
3922 skb->dev = napi->dev;
3928 struct sk_buff *napi_get_frags(struct napi_struct *napi)
3930 struct sk_buff *skb = napi->skb;
3933 skb = netdev_alloc_skb_ip_align(napi->dev, GRO_MAX_HEAD);
3939 EXPORT_SYMBOL(napi_get_frags);
3941 static gro_result_t napi_frags_finish(struct napi_struct *napi, struct sk_buff *skb,
3947 skb->protocol = eth_type_trans(skb, skb->dev);
3949 if (ret == GRO_HELD)
3950 skb_gro_pull(skb, -ETH_HLEN);
3951 else if (netif_receive_skb(skb))
3956 case GRO_MERGED_FREE:
3957 napi_reuse_skb(napi, skb);
3967 static struct sk_buff *napi_frags_skb(struct napi_struct *napi)
3969 struct sk_buff *skb = napi->skb;
3976 skb_reset_mac_header(skb);
3977 skb_gro_reset_offset(skb);
3979 off = skb_gro_offset(skb);
3980 hlen = off + sizeof(*eth);
3981 eth = skb_gro_header_fast(skb, off);
3982 if (skb_gro_header_hard(skb, hlen)) {
3983 eth = skb_gro_header_slow(skb, hlen, off);
3984 if (unlikely(!eth)) {
3985 napi_reuse_skb(napi, skb);
3991 skb_gro_pull(skb, sizeof(*eth));
3994 * This works because the only protocols we care about don't require
3995 * special handling. We'll fix it up properly at the end.
3997 skb->protocol = eth->h_proto;
4003 gro_result_t napi_gro_frags(struct napi_struct *napi)
4005 struct sk_buff *skb = napi_frags_skb(napi);
4010 return napi_frags_finish(napi, skb, dev_gro_receive(napi, skb));
4012 EXPORT_SYMBOL(napi_gro_frags);
4015 * net_rps_action sends any pending IPI's for rps.
4016 * Note: called with local irq disabled, but exits with local irq enabled.
4018 static void net_rps_action_and_irq_enable(struct softnet_data *sd)
4021 struct softnet_data *remsd = sd->rps_ipi_list;
4024 sd->rps_ipi_list = NULL;
4028 /* Send pending IPI's to kick RPS processing on remote cpus. */
4030 struct softnet_data *next = remsd->rps_ipi_next;
4032 if (cpu_online(remsd->cpu))
4033 __smp_call_function_single(remsd->cpu,
4042 static int process_backlog(struct napi_struct *napi, int quota)
4045 struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
4048 /* Check if we have pending ipi, its better to send them now,
4049 * not waiting net_rx_action() end.
4051 if (sd->rps_ipi_list) {
4052 local_irq_disable();
4053 net_rps_action_and_irq_enable(sd);
4056 napi->weight = weight_p;
4057 local_irq_disable();
4058 while (work < quota) {
4059 struct sk_buff *skb;
4062 while ((skb = __skb_dequeue(&sd->process_queue))) {
4064 __netif_receive_skb(skb);
4065 local_irq_disable();
4066 input_queue_head_incr(sd);
4067 if (++work >= quota) {
4074 qlen = skb_queue_len(&sd->input_pkt_queue);
4076 skb_queue_splice_tail_init(&sd->input_pkt_queue,
4077 &sd->process_queue);
4079 if (qlen < quota - work) {
4081 * Inline a custom version of __napi_complete().
4082 * only current cpu owns and manipulates this napi,
4083 * and NAPI_STATE_SCHED is the only possible flag set on backlog.
4084 * we can use a plain write instead of clear_bit(),
4085 * and we dont need an smp_mb() memory barrier.
4087 list_del(&napi->poll_list);
4090 quota = work + qlen;
4100 * __napi_schedule - schedule for receive
4101 * @n: entry to schedule
4103 * The entry's receive function will be scheduled to run
4105 void __napi_schedule(struct napi_struct *n)
4107 unsigned long flags;
4109 local_irq_save(flags);
4110 ____napi_schedule(&__get_cpu_var(softnet_data), n);
4111 local_irq_restore(flags);
4113 EXPORT_SYMBOL(__napi_schedule);
4115 void __napi_complete(struct napi_struct *n)
4117 BUG_ON(!test_bit(NAPI_STATE_SCHED, &n->state));
4118 BUG_ON(n->gro_list);
4120 list_del(&n->poll_list);
4121 smp_mb__before_clear_bit();
4122 clear_bit(NAPI_STATE_SCHED, &n->state);
4124 EXPORT_SYMBOL(__napi_complete);
4126 void napi_complete(struct napi_struct *n)
4128 unsigned long flags;
4131 * don't let napi dequeue from the cpu poll list
4132 * just in case its running on a different cpu
4134 if (unlikely(test_bit(NAPI_STATE_NPSVC, &n->state)))
4137 napi_gro_flush(n, false);
4138 local_irq_save(flags);
4140 local_irq_restore(flags);
4142 EXPORT_SYMBOL(napi_complete);
4144 /* must be called under rcu_read_lock(), as we dont take a reference */
4145 struct napi_struct *napi_by_id(unsigned int napi_id)
4147 unsigned int hash = napi_id % HASH_SIZE(napi_hash);
4148 struct napi_struct *napi;
4150 hlist_for_each_entry_rcu(napi, &napi_hash[hash], napi_hash_node)
4151 if (napi->napi_id == napi_id)
4156 EXPORT_SYMBOL_GPL(napi_by_id);
4158 void napi_hash_add(struct napi_struct *napi)
4160 if (!test_and_set_bit(NAPI_STATE_HASHED, &napi->state)) {
4162 spin_lock(&napi_hash_lock);
4164 /* 0 is not a valid id, we also skip an id that is taken
4165 * we expect both events to be extremely rare
4168 while (!napi->napi_id) {
4169 napi->napi_id = ++napi_gen_id;
4170 if (napi_by_id(napi->napi_id))
4174 hlist_add_head_rcu(&napi->napi_hash_node,
4175 &napi_hash[napi->napi_id % HASH_SIZE(napi_hash)]);
4177 spin_unlock(&napi_hash_lock);
4180 EXPORT_SYMBOL_GPL(napi_hash_add);
4182 /* Warning : caller is responsible to make sure rcu grace period
4183 * is respected before freeing memory containing @napi
4185 void napi_hash_del(struct napi_struct *napi)
4187 spin_lock(&napi_hash_lock);
4189 if (test_and_clear_bit(NAPI_STATE_HASHED, &napi->state))
4190 hlist_del_rcu(&napi->napi_hash_node);
4192 spin_unlock(&napi_hash_lock);
4194 EXPORT_SYMBOL_GPL(napi_hash_del);
4196 void netif_napi_add(struct net_device *dev, struct napi_struct *napi,
4197 int (*poll)(struct napi_struct *, int), int weight)
4199 INIT_LIST_HEAD(&napi->poll_list);
4200 napi->gro_count = 0;
4201 napi->gro_list = NULL;
4204 if (weight > NAPI_POLL_WEIGHT)
4205 pr_err_once("netif_napi_add() called with weight %d on device %s\n",
4207 napi->weight = weight;
4208 list_add(&napi->dev_list, &dev->napi_list);
4210 #ifdef CONFIG_NETPOLL
4211 spin_lock_init(&napi->poll_lock);
4212 napi->poll_owner = -1;
4214 set_bit(NAPI_STATE_SCHED, &napi->state);
4216 EXPORT_SYMBOL(netif_napi_add);
4218 void netif_napi_del(struct napi_struct *napi)
4220 struct sk_buff *skb, *next;
4222 list_del_init(&napi->dev_list);
4223 napi_free_frags(napi);
4225 for (skb = napi->gro_list; skb; skb = next) {
4231 napi->gro_list = NULL;
4232 napi->gro_count = 0;
4234 EXPORT_SYMBOL(netif_napi_del);
4236 static void net_rx_action(struct softirq_action *h)
4238 struct softnet_data *sd = &__get_cpu_var(softnet_data);
4239 unsigned long time_limit = jiffies + 2;
4240 int budget = netdev_budget;
4243 local_irq_disable();
4245 while (!list_empty(&sd->poll_list)) {
4246 struct napi_struct *n;
4249 /* If softirq window is exhuasted then punt.
4250 * Allow this to run for 2 jiffies since which will allow
4251 * an average latency of 1.5/HZ.
4253 if (unlikely(budget <= 0 || time_after_eq(jiffies, time_limit)))
4258 /* Even though interrupts have been re-enabled, this
4259 * access is safe because interrupts can only add new
4260 * entries to the tail of this list, and only ->poll()
4261 * calls can remove this head entry from the list.
4263 n = list_first_entry(&sd->poll_list, struct napi_struct, poll_list);
4265 have = netpoll_poll_lock(n);
4269 /* This NAPI_STATE_SCHED test is for avoiding a race
4270 * with netpoll's poll_napi(). Only the entity which
4271 * obtains the lock and sees NAPI_STATE_SCHED set will
4272 * actually make the ->poll() call. Therefore we avoid
4273 * accidentally calling ->poll() when NAPI is not scheduled.
4276 if (test_bit(NAPI_STATE_SCHED, &n->state)) {
4277 work = n->poll(n, weight);
4281 WARN_ON_ONCE(work > weight);
4285 local_irq_disable();
4287 /* Drivers must not modify the NAPI state if they
4288 * consume the entire weight. In such cases this code
4289 * still "owns" the NAPI instance and therefore can
4290 * move the instance around on the list at-will.
4292 if (unlikely(work == weight)) {
4293 if (unlikely(napi_disable_pending(n))) {
4296 local_irq_disable();
4299 /* flush too old packets
4300 * If HZ < 1000, flush all packets.
4303 napi_gro_flush(n, HZ >= 1000);
4304 local_irq_disable();
4306 list_move_tail(&n->poll_list, &sd->poll_list);
4310 netpoll_poll_unlock(have);
4313 net_rps_action_and_irq_enable(sd);
4315 #ifdef CONFIG_NET_DMA
4317 * There may not be any more sk_buffs coming right now, so push
4318 * any pending DMA copies to hardware
4320 dma_issue_pending_all();
4327 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4331 struct netdev_upper {
4332 struct net_device *dev;
4334 struct list_head list;
4335 struct rcu_head rcu;
4336 struct list_head search_list;
4339 static void __append_search_uppers(struct list_head *search_list,
4340 struct net_device *dev)
4342 struct netdev_upper *upper;
4344 list_for_each_entry(upper, &dev->upper_dev_list, list) {
4345 /* check if this upper is not already in search list */
4346 if (list_empty(&upper->search_list))
4347 list_add_tail(&upper->search_list, search_list);
4351 static bool __netdev_search_upper_dev(struct net_device *dev,
4352 struct net_device *upper_dev)
4354 LIST_HEAD(search_list);
4355 struct netdev_upper *upper;
4356 struct netdev_upper *tmp;
4359 __append_search_uppers(&search_list, dev);
4360 list_for_each_entry(upper, &search_list, search_list) {
4361 if (upper->dev == upper_dev) {
4365 __append_search_uppers(&search_list, upper->dev);
4367 list_for_each_entry_safe(upper, tmp, &search_list, search_list)
4368 INIT_LIST_HEAD(&upper->search_list);
4372 static struct netdev_upper *__netdev_find_upper(struct net_device *dev,
4373 struct net_device *upper_dev)
4375 struct netdev_upper *upper;
4377 list_for_each_entry(upper, &dev->upper_dev_list, list) {
4378 if (upper->dev == upper_dev)
4385 * netdev_has_upper_dev - Check if device is linked to an upper device
4387 * @upper_dev: upper device to check
4389 * Find out if a device is linked to specified upper device and return true
4390 * in case it is. Note that this checks only immediate upper device,
4391 * not through a complete stack of devices. The caller must hold the RTNL lock.
4393 bool netdev_has_upper_dev(struct net_device *dev,
4394 struct net_device *upper_dev)
4398 return __netdev_find_upper(dev, upper_dev);
4400 EXPORT_SYMBOL(netdev_has_upper_dev);
4403 * netdev_has_any_upper_dev - Check if device is linked to some device
4406 * Find out if a device is linked to an upper device and return true in case
4407 * it is. The caller must hold the RTNL lock.
4409 bool netdev_has_any_upper_dev(struct net_device *dev)
4413 return !list_empty(&dev->upper_dev_list);
4415 EXPORT_SYMBOL(netdev_has_any_upper_dev);
4418 * netdev_master_upper_dev_get - Get master upper device
4421 * Find a master upper device and return pointer to it or NULL in case
4422 * it's not there. The caller must hold the RTNL lock.
4424 struct net_device *netdev_master_upper_dev_get(struct net_device *dev)
4426 struct netdev_upper *upper;
4430 if (list_empty(&dev->upper_dev_list))
4433 upper = list_first_entry(&dev->upper_dev_list,
4434 struct netdev_upper, list);
4435 if (likely(upper->master))
4439 EXPORT_SYMBOL(netdev_master_upper_dev_get);
4442 * netdev_master_upper_dev_get_rcu - Get master upper device
4445 * Find a master upper device and return pointer to it or NULL in case
4446 * it's not there. The caller must hold the RCU read lock.
4448 struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev)
4450 struct netdev_upper *upper;
4452 upper = list_first_or_null_rcu(&dev->upper_dev_list,
4453 struct netdev_upper, list);
4454 if (upper && likely(upper->master))
4458 EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu);
4460 static int __netdev_upper_dev_link(struct net_device *dev,
4461 struct net_device *upper_dev, bool master)
4463 struct netdev_upper *upper;
4467 if (dev == upper_dev)
4470 /* To prevent loops, check if dev is not upper device to upper_dev. */
4471 if (__netdev_search_upper_dev(upper_dev, dev))
4474 if (__netdev_find_upper(dev, upper_dev))
4477 if (master && netdev_master_upper_dev_get(dev))
4480 upper = kmalloc(sizeof(*upper), GFP_KERNEL);
4484 upper->dev = upper_dev;
4485 upper->master = master;
4486 INIT_LIST_HEAD(&upper->search_list);
4488 /* Ensure that master upper link is always the first item in list. */
4490 list_add_rcu(&upper->list, &dev->upper_dev_list);
4492 list_add_tail_rcu(&upper->list, &dev->upper_dev_list);
4493 dev_hold(upper_dev);
4494 call_netdevice_notifiers(NETDEV_CHANGEUPPER, dev);
4499 * netdev_upper_dev_link - Add a link to the upper device
4501 * @upper_dev: new upper device
4503 * Adds a link to device which is upper to this one. The caller must hold
4504 * the RTNL lock. On a failure a negative errno code is returned.
4505 * On success the reference counts are adjusted and the function
4508 int netdev_upper_dev_link(struct net_device *dev,
4509 struct net_device *upper_dev)
4511 return __netdev_upper_dev_link(dev, upper_dev, false);
4513 EXPORT_SYMBOL(netdev_upper_dev_link);
4516 * netdev_master_upper_dev_link - Add a master link to the upper device
4518 * @upper_dev: new upper device
4520 * Adds a link to device which is upper to this one. In this case, only
4521 * one master upper device can be linked, although other non-master devices
4522 * might be linked as well. The caller must hold the RTNL lock.
4523 * On a failure a negative errno code is returned. On success the reference
4524 * counts are adjusted and the function returns zero.
4526 int netdev_master_upper_dev_link(struct net_device *dev,
4527 struct net_device *upper_dev)
4529 return __netdev_upper_dev_link(dev, upper_dev, true);
4531 EXPORT_SYMBOL(netdev_master_upper_dev_link);
4534 * netdev_upper_dev_unlink - Removes a link to upper device
4536 * @upper_dev: new upper device
4538 * Removes a link to device which is upper to this one. The caller must hold
4541 void netdev_upper_dev_unlink(struct net_device *dev,
4542 struct net_device *upper_dev)
4544 struct netdev_upper *upper;
4548 upper = __netdev_find_upper(dev, upper_dev);
4551 list_del_rcu(&upper->list);
4553 kfree_rcu(upper, rcu);
4554 call_netdevice_notifiers(NETDEV_CHANGEUPPER, dev);
4556 EXPORT_SYMBOL(netdev_upper_dev_unlink);
4558 static void dev_change_rx_flags(struct net_device *dev, int flags)
4560 const struct net_device_ops *ops = dev->netdev_ops;
4562 if ((dev->flags & IFF_UP) && ops->ndo_change_rx_flags)
4563 ops->ndo_change_rx_flags(dev, flags);
4566 static int __dev_set_promiscuity(struct net_device *dev, int inc)
4568 unsigned int old_flags = dev->flags;
4574 dev->flags |= IFF_PROMISC;
4575 dev->promiscuity += inc;
4576 if (dev->promiscuity == 0) {
4579 * If inc causes overflow, untouch promisc and return error.
4582 dev->flags &= ~IFF_PROMISC;
4584 dev->promiscuity -= inc;
4585 pr_warn("%s: promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n",
4590 if (dev->flags != old_flags) {
4591 pr_info("device %s %s promiscuous mode\n",
4593 dev->flags & IFF_PROMISC ? "entered" : "left");
4594 if (audit_enabled) {
4595 current_uid_gid(&uid, &gid);
4596 audit_log(current->audit_context, GFP_ATOMIC,
4597 AUDIT_ANOM_PROMISCUOUS,
4598 "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u",
4599 dev->name, (dev->flags & IFF_PROMISC),
4600 (old_flags & IFF_PROMISC),
4601 from_kuid(&init_user_ns, audit_get_loginuid(current)),
4602 from_kuid(&init_user_ns, uid),
4603 from_kgid(&init_user_ns, gid),
4604 audit_get_sessionid(current));
4607 dev_change_rx_flags(dev, IFF_PROMISC);
4613 * dev_set_promiscuity - update promiscuity count on a device
4617 * Add or remove promiscuity from a device. While the count in the device
4618 * remains above zero the interface remains promiscuous. Once it hits zero
4619 * the device reverts back to normal filtering operation. A negative inc
4620 * value is used to drop promiscuity on the device.
4621 * Return 0 if successful or a negative errno code on error.
4623 int dev_set_promiscuity(struct net_device *dev, int inc)
4625 unsigned int old_flags = dev->flags;
4628 err = __dev_set_promiscuity(dev, inc);
4631 if (dev->flags != old_flags)
4632 dev_set_rx_mode(dev);
4635 EXPORT_SYMBOL(dev_set_promiscuity);
4638 * dev_set_allmulti - update allmulti count on a device
4642 * Add or remove reception of all multicast frames to a device. While the
4643 * count in the device remains above zero the interface remains listening
4644 * to all interfaces. Once it hits zero the device reverts back to normal
4645 * filtering operation. A negative @inc value is used to drop the counter
4646 * when releasing a resource needing all multicasts.
4647 * Return 0 if successful or a negative errno code on error.
4650 int dev_set_allmulti(struct net_device *dev, int inc)
4652 unsigned int old_flags = dev->flags;
4656 dev->flags |= IFF_ALLMULTI;
4657 dev->allmulti += inc;
4658 if (dev->allmulti == 0) {
4661 * If inc causes overflow, untouch allmulti and return error.
4664 dev->flags &= ~IFF_ALLMULTI;
4666 dev->allmulti -= inc;
4667 pr_warn("%s: allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n",
4672 if (dev->flags ^ old_flags) {
4673 dev_change_rx_flags(dev, IFF_ALLMULTI);
4674 dev_set_rx_mode(dev);
4678 EXPORT_SYMBOL(dev_set_allmulti);
4681 * Upload unicast and multicast address lists to device and
4682 * configure RX filtering. When the device doesn't support unicast
4683 * filtering it is put in promiscuous mode while unicast addresses
4686 void __dev_set_rx_mode(struct net_device *dev)
4688 const struct net_device_ops *ops = dev->netdev_ops;
4690 /* dev_open will call this function so the list will stay sane. */
4691 if (!(dev->flags&IFF_UP))
4694 if (!netif_device_present(dev))
4697 if (!(dev->priv_flags & IFF_UNICAST_FLT)) {
4698 /* Unicast addresses changes may only happen under the rtnl,
4699 * therefore calling __dev_set_promiscuity here is safe.
4701 if (!netdev_uc_empty(dev) && !dev->uc_promisc) {
4702 __dev_set_promiscuity(dev, 1);
4703 dev->uc_promisc = true;
4704 } else if (netdev_uc_empty(dev) && dev->uc_promisc) {
4705 __dev_set_promiscuity(dev, -1);
4706 dev->uc_promisc = false;
4710 if (ops->ndo_set_rx_mode)
4711 ops->ndo_set_rx_mode(dev);
4714 void dev_set_rx_mode(struct net_device *dev)
4716 netif_addr_lock_bh(dev);
4717 __dev_set_rx_mode(dev);
4718 netif_addr_unlock_bh(dev);
4722 * dev_get_flags - get flags reported to userspace
4725 * Get the combination of flag bits exported through APIs to userspace.
4727 unsigned int dev_get_flags(const struct net_device *dev)
4731 flags = (dev->flags & ~(IFF_PROMISC |
4736 (dev->gflags & (IFF_PROMISC |
4739 if (netif_running(dev)) {
4740 if (netif_oper_up(dev))
4741 flags |= IFF_RUNNING;
4742 if (netif_carrier_ok(dev))
4743 flags |= IFF_LOWER_UP;
4744 if (netif_dormant(dev))
4745 flags |= IFF_DORMANT;
4750 EXPORT_SYMBOL(dev_get_flags);
4752 int __dev_change_flags(struct net_device *dev, unsigned int flags)
4754 unsigned int old_flags = dev->flags;
4760 * Set the flags on our device.
4763 dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
4764 IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
4766 (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
4770 * Load in the correct multicast list now the flags have changed.
4773 if ((old_flags ^ flags) & IFF_MULTICAST)
4774 dev_change_rx_flags(dev, IFF_MULTICAST);
4776 dev_set_rx_mode(dev);
4779 * Have we downed the interface. We handle IFF_UP ourselves
4780 * according to user attempts to set it, rather than blindly
4785 if ((old_flags ^ flags) & IFF_UP) { /* Bit is different ? */
4786 ret = ((old_flags & IFF_UP) ? __dev_close : __dev_open)(dev);
4789 dev_set_rx_mode(dev);
4792 if ((flags ^ dev->gflags) & IFF_PROMISC) {
4793 int inc = (flags & IFF_PROMISC) ? 1 : -1;
4795 dev->gflags ^= IFF_PROMISC;
4796 dev_set_promiscuity(dev, inc);
4799 /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
4800 is important. Some (broken) drivers set IFF_PROMISC, when
4801 IFF_ALLMULTI is requested not asking us and not reporting.
4803 if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
4804 int inc = (flags & IFF_ALLMULTI) ? 1 : -1;
4806 dev->gflags ^= IFF_ALLMULTI;
4807 dev_set_allmulti(dev, inc);
4813 void __dev_notify_flags(struct net_device *dev, unsigned int old_flags)
4815 unsigned int changes = dev->flags ^ old_flags;
4817 if (changes & IFF_UP) {
4818 if (dev->flags & IFF_UP)
4819 call_netdevice_notifiers(NETDEV_UP, dev);
4821 call_netdevice_notifiers(NETDEV_DOWN, dev);
4824 if (dev->flags & IFF_UP &&
4825 (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) {
4826 struct netdev_notifier_change_info change_info;
4828 change_info.flags_changed = changes;
4829 call_netdevice_notifiers_info(NETDEV_CHANGE, dev,
4835 * dev_change_flags - change device settings
4837 * @flags: device state flags
4839 * Change settings on device based state flags. The flags are
4840 * in the userspace exported format.
4842 int dev_change_flags(struct net_device *dev, unsigned int flags)
4845 unsigned int changes, old_flags = dev->flags;
4847 ret = __dev_change_flags(dev, flags);
4851 changes = old_flags ^ dev->flags;
4853 rtmsg_ifinfo(RTM_NEWLINK, dev, changes);
4855 __dev_notify_flags(dev, old_flags);
4858 EXPORT_SYMBOL(dev_change_flags);
4861 * dev_set_mtu - Change maximum transfer unit
4863 * @new_mtu: new transfer unit
4865 * Change the maximum transfer size of the network device.
4867 int dev_set_mtu(struct net_device *dev, int new_mtu)
4869 const struct net_device_ops *ops = dev->netdev_ops;
4872 if (new_mtu == dev->mtu)
4875 /* MTU must be positive. */
4879 if (!netif_device_present(dev))
4883 if (ops->ndo_change_mtu)
4884 err = ops->ndo_change_mtu(dev, new_mtu);
4889 call_netdevice_notifiers(NETDEV_CHANGEMTU, dev);
4892 EXPORT_SYMBOL(dev_set_mtu);
4895 * dev_set_group - Change group this device belongs to
4897 * @new_group: group this device should belong to
4899 void dev_set_group(struct net_device *dev, int new_group)
4901 dev->group = new_group;
4903 EXPORT_SYMBOL(dev_set_group);
4906 * dev_set_mac_address - Change Media Access Control Address
4910 * Change the hardware (MAC) address of the device
4912 int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa)
4914 const struct net_device_ops *ops = dev->netdev_ops;
4917 if (!ops->ndo_set_mac_address)
4919 if (sa->sa_family != dev->type)
4921 if (!netif_device_present(dev))
4923 err = ops->ndo_set_mac_address(dev, sa);
4926 dev->addr_assign_type = NET_ADDR_SET;
4927 call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
4928 add_device_randomness(dev->dev_addr, dev->addr_len);
4931 EXPORT_SYMBOL(dev_set_mac_address);
4934 * dev_change_carrier - Change device carrier
4936 * @new_carrier: new value
4938 * Change device carrier
4940 int dev_change_carrier(struct net_device *dev, bool new_carrier)
4942 const struct net_device_ops *ops = dev->netdev_ops;
4944 if (!ops->ndo_change_carrier)
4946 if (!netif_device_present(dev))
4948 return ops->ndo_change_carrier(dev, new_carrier);
4950 EXPORT_SYMBOL(dev_change_carrier);
4953 * dev_new_index - allocate an ifindex
4954 * @net: the applicable net namespace
4956 * Returns a suitable unique value for a new device interface
4957 * number. The caller must hold the rtnl semaphore or the
4958 * dev_base_lock to be sure it remains unique.
4960 static int dev_new_index(struct net *net)
4962 int ifindex = net->ifindex;
4966 if (!__dev_get_by_index(net, ifindex))
4967 return net->ifindex = ifindex;
4971 /* Delayed registration/unregisteration */
4972 static LIST_HEAD(net_todo_list);
4974 static void net_set_todo(struct net_device *dev)
4976 list_add_tail(&dev->todo_list, &net_todo_list);
4979 static void rollback_registered_many(struct list_head *head)
4981 struct net_device *dev, *tmp;
4983 BUG_ON(dev_boot_phase);
4986 list_for_each_entry_safe(dev, tmp, head, unreg_list) {
4987 /* Some devices call without registering
4988 * for initialization unwind. Remove those
4989 * devices and proceed with the remaining.
4991 if (dev->reg_state == NETREG_UNINITIALIZED) {
4992 pr_debug("unregister_netdevice: device %s/%p never was registered\n",
4996 list_del(&dev->unreg_list);
4999 dev->dismantle = true;
5000 BUG_ON(dev->reg_state != NETREG_REGISTERED);
5003 /* If device is running, close it first. */
5004 dev_close_many(head);
5006 list_for_each_entry(dev, head, unreg_list) {
5007 /* And unlink it from device chain. */
5008 unlist_netdevice(dev);
5010 dev->reg_state = NETREG_UNREGISTERING;
5015 list_for_each_entry(dev, head, unreg_list) {
5016 /* Shutdown queueing discipline. */
5020 /* Notify protocols, that we are about to destroy
5021 this device. They should clean all the things.
5023 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
5025 if (!dev->rtnl_link_ops ||
5026 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
5027 rtmsg_ifinfo(RTM_DELLINK, dev, ~0U);
5030 * Flush the unicast and multicast chains
5035 if (dev->netdev_ops->ndo_uninit)
5036 dev->netdev_ops->ndo_uninit(dev);
5038 /* Notifier chain MUST detach us all upper devices. */
5039 WARN_ON(netdev_has_any_upper_dev(dev));
5041 /* Remove entries from kobject tree */
5042 netdev_unregister_kobject(dev);
5044 /* Remove XPS queueing entries */
5045 netif_reset_xps_queues_gt(dev, 0);
5051 list_for_each_entry(dev, head, unreg_list)
5055 static void rollback_registered(struct net_device *dev)
5059 list_add(&dev->unreg_list, &single);
5060 rollback_registered_many(&single);
5064 static netdev_features_t netdev_fix_features(struct net_device *dev,
5065 netdev_features_t features)
5067 /* Fix illegal checksum combinations */
5068 if ((features & NETIF_F_HW_CSUM) &&
5069 (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
5070 netdev_warn(dev, "mixed HW and IP checksum settings.\n");
5071 features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM);
5074 /* TSO requires that SG is present as well. */
5075 if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) {
5076 netdev_dbg(dev, "Dropping TSO features since no SG feature.\n");
5077 features &= ~NETIF_F_ALL_TSO;
5080 if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) &&
5081 !(features & NETIF_F_IP_CSUM)) {
5082 netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n");
5083 features &= ~NETIF_F_TSO;
5084 features &= ~NETIF_F_TSO_ECN;
5087 if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) &&
5088 !(features & NETIF_F_IPV6_CSUM)) {
5089 netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n");
5090 features &= ~NETIF_F_TSO6;
5093 /* TSO ECN requires that TSO is present as well. */
5094 if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN)
5095 features &= ~NETIF_F_TSO_ECN;
5097 /* Software GSO depends on SG. */
5098 if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) {
5099 netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n");
5100 features &= ~NETIF_F_GSO;
5103 /* UFO needs SG and checksumming */
5104 if (features & NETIF_F_UFO) {
5105 /* maybe split UFO into V4 and V6? */
5106 if (!((features & NETIF_F_GEN_CSUM) ||
5107 (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))
5108 == (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
5110 "Dropping NETIF_F_UFO since no checksum offload features.\n");
5111 features &= ~NETIF_F_UFO;
5114 if (!(features & NETIF_F_SG)) {
5116 "Dropping NETIF_F_UFO since no NETIF_F_SG feature.\n");
5117 features &= ~NETIF_F_UFO;
5124 int __netdev_update_features(struct net_device *dev)
5126 netdev_features_t features;
5131 features = netdev_get_wanted_features(dev);
5133 if (dev->netdev_ops->ndo_fix_features)
5134 features = dev->netdev_ops->ndo_fix_features(dev, features);
5136 /* driver might be less strict about feature dependencies */
5137 features = netdev_fix_features(dev, features);
5139 if (dev->features == features)
5142 netdev_dbg(dev, "Features changed: %pNF -> %pNF\n",
5143 &dev->features, &features);
5145 if (dev->netdev_ops->ndo_set_features)
5146 err = dev->netdev_ops->ndo_set_features(dev, features);
5148 if (unlikely(err < 0)) {
5150 "set_features() failed (%d); wanted %pNF, left %pNF\n",
5151 err, &features, &dev->features);
5156 dev->features = features;
5162 * netdev_update_features - recalculate device features
5163 * @dev: the device to check
5165 * Recalculate dev->features set and send notifications if it
5166 * has changed. Should be called after driver or hardware dependent
5167 * conditions might have changed that influence the features.
5169 void netdev_update_features(struct net_device *dev)
5171 if (__netdev_update_features(dev))
5172 netdev_features_change(dev);
5174 EXPORT_SYMBOL(netdev_update_features);
5177 * netdev_change_features - recalculate device features
5178 * @dev: the device to check
5180 * Recalculate dev->features set and send notifications even
5181 * if they have not changed. Should be called instead of
5182 * netdev_update_features() if also dev->vlan_features might
5183 * have changed to allow the changes to be propagated to stacked
5186 void netdev_change_features(struct net_device *dev)
5188 __netdev_update_features(dev);
5189 netdev_features_change(dev);
5191 EXPORT_SYMBOL(netdev_change_features);
5194 * netif_stacked_transfer_operstate - transfer operstate
5195 * @rootdev: the root or lower level device to transfer state from
5196 * @dev: the device to transfer operstate to
5198 * Transfer operational state from root to device. This is normally
5199 * called when a stacking relationship exists between the root
5200 * device and the device(a leaf device).
5202 void netif_stacked_transfer_operstate(const struct net_device *rootdev,
5203 struct net_device *dev)
5205 if (rootdev->operstate == IF_OPER_DORMANT)
5206 netif_dormant_on(dev);
5208 netif_dormant_off(dev);
5210 if (netif_carrier_ok(rootdev)) {
5211 if (!netif_carrier_ok(dev))
5212 netif_carrier_on(dev);
5214 if (netif_carrier_ok(dev))
5215 netif_carrier_off(dev);
5218 EXPORT_SYMBOL(netif_stacked_transfer_operstate);
5221 static int netif_alloc_rx_queues(struct net_device *dev)
5223 unsigned int i, count = dev->num_rx_queues;
5224 struct netdev_rx_queue *rx;
5228 rx = kcalloc(count, sizeof(struct netdev_rx_queue), GFP_KERNEL);
5234 for (i = 0; i < count; i++)
5240 static void netdev_init_one_queue(struct net_device *dev,
5241 struct netdev_queue *queue, void *_unused)
5243 /* Initialize queue lock */
5244 spin_lock_init(&queue->_xmit_lock);
5245 netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type);
5246 queue->xmit_lock_owner = -1;
5247 netdev_queue_numa_node_write(queue, NUMA_NO_NODE);
5250 dql_init(&queue->dql, HZ);
5254 static void netif_free_tx_queues(struct net_device *dev)
5256 if (is_vmalloc_addr(dev->_tx))
5262 static int netif_alloc_netdev_queues(struct net_device *dev)
5264 unsigned int count = dev->num_tx_queues;
5265 struct netdev_queue *tx;
5266 size_t sz = count * sizeof(*tx);
5268 BUG_ON(count < 1 || count > 0xffff);
5270 tx = kzalloc(sz, GFP_KERNEL | __GFP_NOWARN | __GFP_REPEAT);
5278 netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL);
5279 spin_lock_init(&dev->tx_global_lock);
5285 * register_netdevice - register a network device
5286 * @dev: device to register
5288 * Take a completed network device structure and add it to the kernel
5289 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
5290 * chain. 0 is returned on success. A negative errno code is returned
5291 * on a failure to set up the device, or if the name is a duplicate.
5293 * Callers must hold the rtnl semaphore. You may want
5294 * register_netdev() instead of this.
5297 * The locking appears insufficient to guarantee two parallel registers
5298 * will not get the same name.
5301 int register_netdevice(struct net_device *dev)
5304 struct net *net = dev_net(dev);
5306 BUG_ON(dev_boot_phase);
5311 /* When net_device's are persistent, this will be fatal. */
5312 BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
5315 spin_lock_init(&dev->addr_list_lock);
5316 netdev_set_addr_lockdep_class(dev);
5320 ret = dev_get_valid_name(net, dev, dev->name);
5324 /* Init, if this function is available */
5325 if (dev->netdev_ops->ndo_init) {
5326 ret = dev->netdev_ops->ndo_init(dev);
5334 if (((dev->hw_features | dev->features) &
5335 NETIF_F_HW_VLAN_CTAG_FILTER) &&
5336 (!dev->netdev_ops->ndo_vlan_rx_add_vid ||
5337 !dev->netdev_ops->ndo_vlan_rx_kill_vid)) {
5338 netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n");
5345 dev->ifindex = dev_new_index(net);
5346 else if (__dev_get_by_index(net, dev->ifindex))
5349 if (dev->iflink == -1)
5350 dev->iflink = dev->ifindex;
5352 /* Transfer changeable features to wanted_features and enable
5353 * software offloads (GSO and GRO).
5355 dev->hw_features |= NETIF_F_SOFT_FEATURES;
5356 dev->features |= NETIF_F_SOFT_FEATURES;
5357 dev->wanted_features = dev->features & dev->hw_features;
5359 /* Turn on no cache copy if HW is doing checksum */
5360 if (!(dev->flags & IFF_LOOPBACK)) {
5361 dev->hw_features |= NETIF_F_NOCACHE_COPY;
5362 if (dev->features & NETIF_F_ALL_CSUM) {
5363 dev->wanted_features |= NETIF_F_NOCACHE_COPY;
5364 dev->features |= NETIF_F_NOCACHE_COPY;
5368 /* Make NETIF_F_HIGHDMA inheritable to VLAN devices.
5370 dev->vlan_features |= NETIF_F_HIGHDMA;
5372 /* Make NETIF_F_SG inheritable to tunnel devices.
5374 dev->hw_enc_features |= NETIF_F_SG;
5376 /* Make NETIF_F_SG inheritable to MPLS.
5378 dev->mpls_features |= NETIF_F_SG;
5380 ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev);
5381 ret = notifier_to_errno(ret);
5385 ret = netdev_register_kobject(dev);
5388 dev->reg_state = NETREG_REGISTERED;
5390 __netdev_update_features(dev);
5393 * Default initial state at registry is that the
5394 * device is present.
5397 set_bit(__LINK_STATE_PRESENT, &dev->state);
5399 linkwatch_init_dev(dev);
5401 dev_init_scheduler(dev);
5403 list_netdevice(dev);
5404 add_device_randomness(dev->dev_addr, dev->addr_len);
5406 /* If the device has permanent device address, driver should
5407 * set dev_addr and also addr_assign_type should be set to
5408 * NET_ADDR_PERM (default value).
5410 if (dev->addr_assign_type == NET_ADDR_PERM)
5411 memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
5413 /* Notify protocols, that a new device appeared. */
5414 ret = call_netdevice_notifiers(NETDEV_REGISTER, dev);
5415 ret = notifier_to_errno(ret);
5417 rollback_registered(dev);
5418 dev->reg_state = NETREG_UNREGISTERED;
5421 * Prevent userspace races by waiting until the network
5422 * device is fully setup before sending notifications.
5424 if (!dev->rtnl_link_ops ||
5425 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
5426 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U);
5432 if (dev->netdev_ops->ndo_uninit)
5433 dev->netdev_ops->ndo_uninit(dev);
5436 EXPORT_SYMBOL(register_netdevice);
5439 * init_dummy_netdev - init a dummy network device for NAPI
5440 * @dev: device to init
5442 * This takes a network device structure and initialize the minimum
5443 * amount of fields so it can be used to schedule NAPI polls without
5444 * registering a full blown interface. This is to be used by drivers
5445 * that need to tie several hardware interfaces to a single NAPI
5446 * poll scheduler due to HW limitations.
5448 int init_dummy_netdev(struct net_device *dev)
5450 /* Clear everything. Note we don't initialize spinlocks
5451 * are they aren't supposed to be taken by any of the
5452 * NAPI code and this dummy netdev is supposed to be
5453 * only ever used for NAPI polls
5455 memset(dev, 0, sizeof(struct net_device));
5457 /* make sure we BUG if trying to hit standard
5458 * register/unregister code path
5460 dev->reg_state = NETREG_DUMMY;
5462 /* NAPI wants this */
5463 INIT_LIST_HEAD(&dev->napi_list);
5465 /* a dummy interface is started by default */
5466 set_bit(__LINK_STATE_PRESENT, &dev->state);
5467 set_bit(__LINK_STATE_START, &dev->state);
5469 /* Note : We dont allocate pcpu_refcnt for dummy devices,
5470 * because users of this 'device' dont need to change
5476 EXPORT_SYMBOL_GPL(init_dummy_netdev);
5480 * register_netdev - register a network device
5481 * @dev: device to register
5483 * Take a completed network device structure and add it to the kernel
5484 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
5485 * chain. 0 is returned on success. A negative errno code is returned
5486 * on a failure to set up the device, or if the name is a duplicate.
5488 * This is a wrapper around register_netdevice that takes the rtnl semaphore
5489 * and expands the device name if you passed a format string to
5492 int register_netdev(struct net_device *dev)
5497 err = register_netdevice(dev);
5501 EXPORT_SYMBOL(register_netdev);
5503 int netdev_refcnt_read(const struct net_device *dev)
5507 for_each_possible_cpu(i)
5508 refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i);
5511 EXPORT_SYMBOL(netdev_refcnt_read);
5514 * netdev_wait_allrefs - wait until all references are gone.
5515 * @dev: target net_device
5517 * This is called when unregistering network devices.
5519 * Any protocol or device that holds a reference should register
5520 * for netdevice notification, and cleanup and put back the
5521 * reference if they receive an UNREGISTER event.
5522 * We can get stuck here if buggy protocols don't correctly
5525 static void netdev_wait_allrefs(struct net_device *dev)
5527 unsigned long rebroadcast_time, warning_time;
5530 linkwatch_forget_dev(dev);
5532 rebroadcast_time = warning_time = jiffies;
5533 refcnt = netdev_refcnt_read(dev);
5535 while (refcnt != 0) {
5536 if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
5539 /* Rebroadcast unregister notification */
5540 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
5546 call_netdevice_notifiers(NETDEV_UNREGISTER_FINAL, dev);
5547 if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
5549 /* We must not have linkwatch events
5550 * pending on unregister. If this
5551 * happens, we simply run the queue
5552 * unscheduled, resulting in a noop
5555 linkwatch_run_queue();
5560 rebroadcast_time = jiffies;
5565 refcnt = netdev_refcnt_read(dev);
5567 if (time_after(jiffies, warning_time + 10 * HZ)) {
5568 pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n",
5570 warning_time = jiffies;
5579 * register_netdevice(x1);
5580 * register_netdevice(x2);
5582 * unregister_netdevice(y1);
5583 * unregister_netdevice(y2);
5589 * We are invoked by rtnl_unlock().
5590 * This allows us to deal with problems:
5591 * 1) We can delete sysfs objects which invoke hotplug
5592 * without deadlocking with linkwatch via keventd.
5593 * 2) Since we run with the RTNL semaphore not held, we can sleep
5594 * safely in order to wait for the netdev refcnt to drop to zero.
5596 * We must not return until all unregister events added during
5597 * the interval the lock was held have been completed.
5599 void netdev_run_todo(void)
5601 struct list_head list;
5603 /* Snapshot list, allow later requests */
5604 list_replace_init(&net_todo_list, &list);
5609 /* Wait for rcu callbacks to finish before next phase */
5610 if (!list_empty(&list))
5613 while (!list_empty(&list)) {
5614 struct net_device *dev
5615 = list_first_entry(&list, struct net_device, todo_list);
5616 list_del(&dev->todo_list);
5619 call_netdevice_notifiers(NETDEV_UNREGISTER_FINAL, dev);
5622 if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) {
5623 pr_err("network todo '%s' but state %d\n",
5624 dev->name, dev->reg_state);
5629 dev->reg_state = NETREG_UNREGISTERED;
5631 on_each_cpu(flush_backlog, dev, 1);
5633 netdev_wait_allrefs(dev);
5636 BUG_ON(netdev_refcnt_read(dev));
5637 WARN_ON(rcu_access_pointer(dev->ip_ptr));
5638 WARN_ON(rcu_access_pointer(dev->ip6_ptr));
5639 WARN_ON(dev->dn_ptr);
5641 if (dev->destructor)
5642 dev->destructor(dev);
5644 /* Free network device */
5645 kobject_put(&dev->dev.kobj);
5649 /* Convert net_device_stats to rtnl_link_stats64. They have the same
5650 * fields in the same order, with only the type differing.
5652 void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64,
5653 const struct net_device_stats *netdev_stats)
5655 #if BITS_PER_LONG == 64
5656 BUILD_BUG_ON(sizeof(*stats64) != sizeof(*netdev_stats));
5657 memcpy(stats64, netdev_stats, sizeof(*stats64));
5659 size_t i, n = sizeof(*stats64) / sizeof(u64);
5660 const unsigned long *src = (const unsigned long *)netdev_stats;
5661 u64 *dst = (u64 *)stats64;
5663 BUILD_BUG_ON(sizeof(*netdev_stats) / sizeof(unsigned long) !=
5664 sizeof(*stats64) / sizeof(u64));
5665 for (i = 0; i < n; i++)
5669 EXPORT_SYMBOL(netdev_stats_to_stats64);
5672 * dev_get_stats - get network device statistics
5673 * @dev: device to get statistics from
5674 * @storage: place to store stats
5676 * Get network statistics from device. Return @storage.
5677 * The device driver may provide its own method by setting
5678 * dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats;
5679 * otherwise the internal statistics structure is used.
5681 struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev,
5682 struct rtnl_link_stats64 *storage)
5684 const struct net_device_ops *ops = dev->netdev_ops;
5686 if (ops->ndo_get_stats64) {
5687 memset(storage, 0, sizeof(*storage));
5688 ops->ndo_get_stats64(dev, storage);
5689 } else if (ops->ndo_get_stats) {
5690 netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev));
5692 netdev_stats_to_stats64(storage, &dev->stats);
5694 storage->rx_dropped += atomic_long_read(&dev->rx_dropped);
5697 EXPORT_SYMBOL(dev_get_stats);
5699 struct netdev_queue *dev_ingress_queue_create(struct net_device *dev)
5701 struct netdev_queue *queue = dev_ingress_queue(dev);
5703 #ifdef CONFIG_NET_CLS_ACT
5706 queue = kzalloc(sizeof(*queue), GFP_KERNEL);
5709 netdev_init_one_queue(dev, queue, NULL);
5710 queue->qdisc = &noop_qdisc;
5711 queue->qdisc_sleeping = &noop_qdisc;
5712 rcu_assign_pointer(dev->ingress_queue, queue);
5717 static const struct ethtool_ops default_ethtool_ops;
5719 void netdev_set_default_ethtool_ops(struct net_device *dev,
5720 const struct ethtool_ops *ops)
5722 if (dev->ethtool_ops == &default_ethtool_ops)
5723 dev->ethtool_ops = ops;
5725 EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops);
5728 * alloc_netdev_mqs - allocate network device
5729 * @sizeof_priv: size of private data to allocate space for
5730 * @name: device name format string
5731 * @setup: callback to initialize device
5732 * @txqs: the number of TX subqueues to allocate
5733 * @rxqs: the number of RX subqueues to allocate
5735 * Allocates a struct net_device with private data area for driver use
5736 * and performs basic initialization. Also allocates subquue structs
5737 * for each queue on the device.
5739 struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name,
5740 void (*setup)(struct net_device *),
5741 unsigned int txqs, unsigned int rxqs)
5743 struct net_device *dev;
5745 struct net_device *p;
5747 BUG_ON(strlen(name) >= sizeof(dev->name));
5750 pr_err("alloc_netdev: Unable to allocate device with zero queues\n");
5756 pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n");
5761 alloc_size = sizeof(struct net_device);
5763 /* ensure 32-byte alignment of private area */
5764 alloc_size = ALIGN(alloc_size, NETDEV_ALIGN);
5765 alloc_size += sizeof_priv;
5767 /* ensure 32-byte alignment of whole construct */
5768 alloc_size += NETDEV_ALIGN - 1;
5770 p = kzalloc(alloc_size, GFP_KERNEL);
5774 dev = PTR_ALIGN(p, NETDEV_ALIGN);
5775 dev->padded = (char *)dev - (char *)p;
5777 dev->pcpu_refcnt = alloc_percpu(int);
5778 if (!dev->pcpu_refcnt)
5781 if (dev_addr_init(dev))
5787 dev_net_set(dev, &init_net);
5789 dev->gso_max_size = GSO_MAX_SIZE;
5790 dev->gso_max_segs = GSO_MAX_SEGS;
5792 INIT_LIST_HEAD(&dev->napi_list);
5793 INIT_LIST_HEAD(&dev->unreg_list);
5794 INIT_LIST_HEAD(&dev->link_watch_list);
5795 INIT_LIST_HEAD(&dev->upper_dev_list);
5796 dev->priv_flags = IFF_XMIT_DST_RELEASE;
5799 dev->num_tx_queues = txqs;
5800 dev->real_num_tx_queues = txqs;
5801 if (netif_alloc_netdev_queues(dev))
5805 dev->num_rx_queues = rxqs;
5806 dev->real_num_rx_queues = rxqs;
5807 if (netif_alloc_rx_queues(dev))
5811 strcpy(dev->name, name);
5812 dev->group = INIT_NETDEV_GROUP;
5813 if (!dev->ethtool_ops)
5814 dev->ethtool_ops = &default_ethtool_ops;
5822 free_percpu(dev->pcpu_refcnt);
5823 netif_free_tx_queues(dev);
5832 EXPORT_SYMBOL(alloc_netdev_mqs);
5835 * free_netdev - free network device
5838 * This function does the last stage of destroying an allocated device
5839 * interface. The reference to the device object is released.
5840 * If this is the last reference then it will be freed.
5842 void free_netdev(struct net_device *dev)
5844 struct napi_struct *p, *n;
5846 release_net(dev_net(dev));
5848 netif_free_tx_queues(dev);
5853 kfree(rcu_dereference_protected(dev->ingress_queue, 1));
5855 /* Flush device addresses */
5856 dev_addr_flush(dev);
5858 list_for_each_entry_safe(p, n, &dev->napi_list, dev_list)
5861 free_percpu(dev->pcpu_refcnt);
5862 dev->pcpu_refcnt = NULL;
5864 /* Compatibility with error handling in drivers */
5865 if (dev->reg_state == NETREG_UNINITIALIZED) {
5866 kfree((char *)dev - dev->padded);
5870 BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
5871 dev->reg_state = NETREG_RELEASED;
5873 /* will free via device release */
5874 put_device(&dev->dev);
5876 EXPORT_SYMBOL(free_netdev);
5879 * synchronize_net - Synchronize with packet receive processing
5881 * Wait for packets currently being received to be done.
5882 * Does not block later packets from starting.
5884 void synchronize_net(void)
5887 if (rtnl_is_locked())
5888 synchronize_rcu_expedited();
5892 EXPORT_SYMBOL(synchronize_net);
5895 * unregister_netdevice_queue - remove device from the kernel
5899 * This function shuts down a device interface and removes it
5900 * from the kernel tables.
5901 * If head not NULL, device is queued to be unregistered later.
5903 * Callers must hold the rtnl semaphore. You may want
5904 * unregister_netdev() instead of this.
5907 void unregister_netdevice_queue(struct net_device *dev, struct list_head *head)
5912 list_move_tail(&dev->unreg_list, head);
5914 rollback_registered(dev);
5915 /* Finish processing unregister after unlock */
5919 EXPORT_SYMBOL(unregister_netdevice_queue);
5922 * unregister_netdevice_many - unregister many devices
5923 * @head: list of devices
5925 void unregister_netdevice_many(struct list_head *head)
5927 struct net_device *dev;
5929 if (!list_empty(head)) {
5930 rollback_registered_many(head);
5931 list_for_each_entry(dev, head, unreg_list)
5935 EXPORT_SYMBOL(unregister_netdevice_many);
5938 * unregister_netdev - remove device from the kernel
5941 * This function shuts down a device interface and removes it
5942 * from the kernel tables.
5944 * This is just a wrapper for unregister_netdevice that takes
5945 * the rtnl semaphore. In general you want to use this and not
5946 * unregister_netdevice.
5948 void unregister_netdev(struct net_device *dev)
5951 unregister_netdevice(dev);
5954 EXPORT_SYMBOL(unregister_netdev);
5957 * dev_change_net_namespace - move device to different nethost namespace
5959 * @net: network namespace
5960 * @pat: If not NULL name pattern to try if the current device name
5961 * is already taken in the destination network namespace.
5963 * This function shuts down a device interface and moves it
5964 * to a new network namespace. On success 0 is returned, on
5965 * a failure a netagive errno code is returned.
5967 * Callers must hold the rtnl semaphore.
5970 int dev_change_net_namespace(struct net_device *dev, struct net *net, const char *pat)
5976 /* Don't allow namespace local devices to be moved. */
5978 if (dev->features & NETIF_F_NETNS_LOCAL)
5981 /* Ensure the device has been registrered */
5982 if (dev->reg_state != NETREG_REGISTERED)
5985 /* Get out if there is nothing todo */
5987 if (net_eq(dev_net(dev), net))
5990 /* Pick the destination device name, and ensure
5991 * we can use it in the destination network namespace.
5994 if (__dev_get_by_name(net, dev->name)) {
5995 /* We get here if we can't use the current device name */
5998 if (dev_get_valid_name(net, dev, pat) < 0)
6003 * And now a mini version of register_netdevice unregister_netdevice.
6006 /* If device is running close it first. */
6009 /* And unlink it from device chain */
6011 unlist_netdevice(dev);
6015 /* Shutdown queueing discipline. */
6018 /* Notify protocols, that we are about to destroy
6019 this device. They should clean all the things.
6021 Note that dev->reg_state stays at NETREG_REGISTERED.
6022 This is wanted because this way 8021q and macvlan know
6023 the device is just moving and can keep their slaves up.
6025 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
6027 call_netdevice_notifiers(NETDEV_UNREGISTER_FINAL, dev);
6028 rtmsg_ifinfo(RTM_DELLINK, dev, ~0U);
6031 * Flush the unicast and multicast chains
6036 /* Send a netdev-removed uevent to the old namespace */
6037 kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE);
6039 /* Actually switch the network namespace */
6040 dev_net_set(dev, net);
6042 /* If there is an ifindex conflict assign a new one */
6043 if (__dev_get_by_index(net, dev->ifindex)) {
6044 int iflink = (dev->iflink == dev->ifindex);
6045 dev->ifindex = dev_new_index(net);
6047 dev->iflink = dev->ifindex;
6050 /* Send a netdev-add uevent to the new namespace */
6051 kobject_uevent(&dev->dev.kobj, KOBJ_ADD);
6053 /* Fixup kobjects */
6054 err = device_rename(&dev->dev, dev->name);
6057 /* Add the device back in the hashes */
6058 list_netdevice(dev);
6060 /* Notify protocols, that a new device appeared. */
6061 call_netdevice_notifiers(NETDEV_REGISTER, dev);
6064 * Prevent userspace races by waiting until the network
6065 * device is fully setup before sending notifications.
6067 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U);
6074 EXPORT_SYMBOL_GPL(dev_change_net_namespace);
6076 static int dev_cpu_callback(struct notifier_block *nfb,
6077 unsigned long action,
6080 struct sk_buff **list_skb;
6081 struct sk_buff *skb;
6082 unsigned int cpu, oldcpu = (unsigned long)ocpu;
6083 struct softnet_data *sd, *oldsd;
6085 if (action != CPU_DEAD && action != CPU_DEAD_FROZEN)
6088 local_irq_disable();
6089 cpu = smp_processor_id();
6090 sd = &per_cpu(softnet_data, cpu);
6091 oldsd = &per_cpu(softnet_data, oldcpu);
6093 /* Find end of our completion_queue. */
6094 list_skb = &sd->completion_queue;
6096 list_skb = &(*list_skb)->next;
6097 /* Append completion queue from offline CPU. */
6098 *list_skb = oldsd->completion_queue;
6099 oldsd->completion_queue = NULL;
6101 /* Append output queue from offline CPU. */
6102 if (oldsd->output_queue) {
6103 *sd->output_queue_tailp = oldsd->output_queue;
6104 sd->output_queue_tailp = oldsd->output_queue_tailp;
6105 oldsd->output_queue = NULL;
6106 oldsd->output_queue_tailp = &oldsd->output_queue;
6108 /* Append NAPI poll list from offline CPU. */
6109 if (!list_empty(&oldsd->poll_list)) {
6110 list_splice_init(&oldsd->poll_list, &sd->poll_list);
6111 raise_softirq_irqoff(NET_RX_SOFTIRQ);
6114 raise_softirq_irqoff(NET_TX_SOFTIRQ);
6117 /* Process offline CPU's input_pkt_queue */
6118 while ((skb = __skb_dequeue(&oldsd->process_queue))) {
6120 input_queue_head_incr(oldsd);
6122 while ((skb = __skb_dequeue(&oldsd->input_pkt_queue))) {
6124 input_queue_head_incr(oldsd);
6132 * netdev_increment_features - increment feature set by one
6133 * @all: current feature set
6134 * @one: new feature set
6135 * @mask: mask feature set
6137 * Computes a new feature set after adding a device with feature set
6138 * @one to the master device with current feature set @all. Will not
6139 * enable anything that is off in @mask. Returns the new feature set.
6141 netdev_features_t netdev_increment_features(netdev_features_t all,
6142 netdev_features_t one, netdev_features_t mask)
6144 if (mask & NETIF_F_GEN_CSUM)
6145 mask |= NETIF_F_ALL_CSUM;
6146 mask |= NETIF_F_VLAN_CHALLENGED;
6148 all |= one & (NETIF_F_ONE_FOR_ALL|NETIF_F_ALL_CSUM) & mask;
6149 all &= one | ~NETIF_F_ALL_FOR_ALL;
6151 /* If one device supports hw checksumming, set for all. */
6152 if (all & NETIF_F_GEN_CSUM)
6153 all &= ~(NETIF_F_ALL_CSUM & ~NETIF_F_GEN_CSUM);
6157 EXPORT_SYMBOL(netdev_increment_features);
6159 static struct hlist_head * __net_init netdev_create_hash(void)
6162 struct hlist_head *hash;
6164 hash = kmalloc(sizeof(*hash) * NETDEV_HASHENTRIES, GFP_KERNEL);
6166 for (i = 0; i < NETDEV_HASHENTRIES; i++)
6167 INIT_HLIST_HEAD(&hash[i]);
6172 /* Initialize per network namespace state */
6173 static int __net_init netdev_init(struct net *net)
6175 if (net != &init_net)
6176 INIT_LIST_HEAD(&net->dev_base_head);
6178 net->dev_name_head = netdev_create_hash();
6179 if (net->dev_name_head == NULL)
6182 net->dev_index_head = netdev_create_hash();
6183 if (net->dev_index_head == NULL)
6189 kfree(net->dev_name_head);
6195 * netdev_drivername - network driver for the device
6196 * @dev: network device
6198 * Determine network driver for device.
6200 const char *netdev_drivername(const struct net_device *dev)
6202 const struct device_driver *driver;
6203 const struct device *parent;
6204 const char *empty = "";
6206 parent = dev->dev.parent;
6210 driver = parent->driver;
6211 if (driver && driver->name)
6212 return driver->name;
6216 static int __netdev_printk(const char *level, const struct net_device *dev,
6217 struct va_format *vaf)
6221 if (dev && dev->dev.parent) {
6222 r = dev_printk_emit(level[1] - '0',
6225 dev_driver_string(dev->dev.parent),
6226 dev_name(dev->dev.parent),
6227 netdev_name(dev), vaf);
6229 r = printk("%s%s: %pV", level, netdev_name(dev), vaf);
6231 r = printk("%s(NULL net_device): %pV", level, vaf);
6237 int netdev_printk(const char *level, const struct net_device *dev,
6238 const char *format, ...)
6240 struct va_format vaf;
6244 va_start(args, format);
6249 r = __netdev_printk(level, dev, &vaf);
6255 EXPORT_SYMBOL(netdev_printk);
6257 #define define_netdev_printk_level(func, level) \
6258 int func(const struct net_device *dev, const char *fmt, ...) \
6261 struct va_format vaf; \
6264 va_start(args, fmt); \
6269 r = __netdev_printk(level, dev, &vaf); \
6275 EXPORT_SYMBOL(func);
6277 define_netdev_printk_level(netdev_emerg, KERN_EMERG);
6278 define_netdev_printk_level(netdev_alert, KERN_ALERT);
6279 define_netdev_printk_level(netdev_crit, KERN_CRIT);
6280 define_netdev_printk_level(netdev_err, KERN_ERR);
6281 define_netdev_printk_level(netdev_warn, KERN_WARNING);
6282 define_netdev_printk_level(netdev_notice, KERN_NOTICE);
6283 define_netdev_printk_level(netdev_info, KERN_INFO);
6285 static void __net_exit netdev_exit(struct net *net)
6287 kfree(net->dev_name_head);
6288 kfree(net->dev_index_head);
6291 static struct pernet_operations __net_initdata netdev_net_ops = {
6292 .init = netdev_init,
6293 .exit = netdev_exit,
6296 static void __net_exit default_device_exit(struct net *net)
6298 struct net_device *dev, *aux;
6300 * Push all migratable network devices back to the
6301 * initial network namespace
6304 for_each_netdev_safe(net, dev, aux) {
6306 char fb_name[IFNAMSIZ];
6308 /* Ignore unmoveable devices (i.e. loopback) */
6309 if (dev->features & NETIF_F_NETNS_LOCAL)
6312 /* Leave virtual devices for the generic cleanup */
6313 if (dev->rtnl_link_ops)
6316 /* Push remaining network devices to init_net */
6317 snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex);
6318 err = dev_change_net_namespace(dev, &init_net, fb_name);
6320 pr_emerg("%s: failed to move %s to init_net: %d\n",
6321 __func__, dev->name, err);
6328 static void __net_exit default_device_exit_batch(struct list_head *net_list)
6330 /* At exit all network devices most be removed from a network
6331 * namespace. Do this in the reverse order of registration.
6332 * Do this across as many network namespaces as possible to
6333 * improve batching efficiency.
6335 struct net_device *dev;
6337 LIST_HEAD(dev_kill_list);
6340 list_for_each_entry(net, net_list, exit_list) {
6341 for_each_netdev_reverse(net, dev) {
6342 if (dev->rtnl_link_ops)
6343 dev->rtnl_link_ops->dellink(dev, &dev_kill_list);
6345 unregister_netdevice_queue(dev, &dev_kill_list);
6348 unregister_netdevice_many(&dev_kill_list);
6349 list_del(&dev_kill_list);
6353 static struct pernet_operations __net_initdata default_device_ops = {
6354 .exit = default_device_exit,
6355 .exit_batch = default_device_exit_batch,
6359 * Initialize the DEV module. At boot time this walks the device list and
6360 * unhooks any devices that fail to initialise (normally hardware not
6361 * present) and leaves us with a valid list of present and active devices.
6366 * This is called single threaded during boot, so no need
6367 * to take the rtnl semaphore.
6369 static int __init net_dev_init(void)
6371 int i, rc = -ENOMEM;
6373 BUG_ON(!dev_boot_phase);
6375 if (dev_proc_init())
6378 if (netdev_kobject_init())
6381 INIT_LIST_HEAD(&ptype_all);
6382 for (i = 0; i < PTYPE_HASH_SIZE; i++)
6383 INIT_LIST_HEAD(&ptype_base[i]);
6385 INIT_LIST_HEAD(&offload_base);
6387 if (register_pernet_subsys(&netdev_net_ops))
6391 * Initialise the packet receive queues.
6394 for_each_possible_cpu(i) {
6395 struct softnet_data *sd = &per_cpu(softnet_data, i);
6397 memset(sd, 0, sizeof(*sd));
6398 skb_queue_head_init(&sd->input_pkt_queue);
6399 skb_queue_head_init(&sd->process_queue);
6400 sd->completion_queue = NULL;
6401 INIT_LIST_HEAD(&sd->poll_list);
6402 sd->output_queue = NULL;
6403 sd->output_queue_tailp = &sd->output_queue;
6405 sd->csd.func = rps_trigger_softirq;
6411 sd->backlog.poll = process_backlog;
6412 sd->backlog.weight = weight_p;
6413 sd->backlog.gro_list = NULL;
6414 sd->backlog.gro_count = 0;
6416 #ifdef CONFIG_NET_FLOW_LIMIT
6417 sd->flow_limit = NULL;
6423 /* The loopback device is special if any other network devices
6424 * is present in a network namespace the loopback device must
6425 * be present. Since we now dynamically allocate and free the
6426 * loopback device ensure this invariant is maintained by
6427 * keeping the loopback device as the first device on the
6428 * list of network devices. Ensuring the loopback devices
6429 * is the first device that appears and the last network device
6432 if (register_pernet_device(&loopback_net_ops))
6435 if (register_pernet_device(&default_device_ops))
6438 open_softirq(NET_TX_SOFTIRQ, net_tx_action);
6439 open_softirq(NET_RX_SOFTIRQ, net_rx_action);
6441 hotcpu_notifier(dev_cpu_callback, 0);
6448 subsys_initcall(net_dev_init);