~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/net/core/dev.c

Version: ~ [ linux-5.15-rc1 ] ~ [ linux-5.14.5 ] ~ [ linux-5.13.18 ] ~ [ linux-5.12.19 ] ~ [ linux-5.11.22 ] ~ [ linux-5.10.66 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.147 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.206 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.246 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.282 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.283 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.18.140 ] ~ [ linux-3.16.85 ] ~ [ linux-3.14.79 ] ~ [ linux-3.12.74 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

  1 // SPDX-License-Identifier: GPL-2.0-or-later
  2 /*
  3  *      NET3    Protocol independent device support routines.
  4  *
  5  *      Derived from the non IP parts of dev.c 1.0.19
  6  *              Authors:        Ross Biro
  7  *                              Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
  8  *                              Mark Evans, <evansmp@uhura.aston.ac.uk>
  9  *
 10  *      Additional Authors:
 11  *              Florian la Roche <rzsfl@rz.uni-sb.de>
 12  *              Alan Cox <gw4pts@gw4pts.ampr.org>
 13  *              David Hinds <dahinds@users.sourceforge.net>
 14  *              Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
 15  *              Adam Sulmicki <adam@cfar.umd.edu>
 16  *              Pekka Riikonen <priikone@poesidon.pspt.fi>
 17  *
 18  *      Changes:
 19  *              D.J. Barrow     :       Fixed bug where dev->refcnt gets set
 20  *                                      to 2 if register_netdev gets called
 21  *                                      before net_dev_init & also removed a
 22  *                                      few lines of code in the process.
 23  *              Alan Cox        :       device private ioctl copies fields back.
 24  *              Alan Cox        :       Transmit queue code does relevant
 25  *                                      stunts to keep the queue safe.
 26  *              Alan Cox        :       Fixed double lock.
 27  *              Alan Cox        :       Fixed promisc NULL pointer trap
 28  *              ????????        :       Support the full private ioctl range
 29  *              Alan Cox        :       Moved ioctl permission check into
 30  *                                      drivers
 31  *              Tim Kordas      :       SIOCADDMULTI/SIOCDELMULTI
 32  *              Alan Cox        :       100 backlog just doesn't cut it when
 33  *                                      you start doing multicast video 8)
 34  *              Alan Cox        :       Rewrote net_bh and list manager.
 35  *              Alan Cox        :       Fix ETH_P_ALL echoback lengths.
 36  *              Alan Cox        :       Took out transmit every packet pass
 37  *                                      Saved a few bytes in the ioctl handler
 38  *              Alan Cox        :       Network driver sets packet type before
 39  *                                      calling netif_rx. Saves a function
 40  *                                      call a packet.
 41  *              Alan Cox        :       Hashed net_bh()
 42  *              Richard Kooijman:       Timestamp fixes.
 43  *              Alan Cox        :       Wrong field in SIOCGIFDSTADDR
 44  *              Alan Cox        :       Device lock protection.
 45  *              Alan Cox        :       Fixed nasty side effect of device close
 46  *                                      changes.
 47  *              Rudi Cilibrasi  :       Pass the right thing to
 48  *                                      set_mac_address()
 49  *              Dave Miller     :       32bit quantity for the device lock to
 50  *                                      make it work out on a Sparc.
 51  *              Bjorn Ekwall    :       Added KERNELD hack.
 52  *              Alan Cox        :       Cleaned up the backlog initialise.
 53  *              Craig Metz      :       SIOCGIFCONF fix if space for under
 54  *                                      1 device.
 55  *          Thomas Bogendoerfer :       Return ENODEV for dev_open, if there
 56  *                                      is no device open function.
 57  *              Andi Kleen      :       Fix error reporting for SIOCGIFCONF
 58  *          Michael Chastain    :       Fix signed/unsigned for SIOCGIFCONF
 59  *              Cyrus Durgin    :       Cleaned for KMOD
 60  *              Adam Sulmicki   :       Bug Fix : Network Device Unload
 61  *                                      A network device unload needs to purge
 62  *                                      the backlog queue.
 63  *      Paul Rusty Russell      :       SIOCSIFNAME
 64  *              Pekka Riikonen  :       Netdev boot-time settings code
 65  *              Andrew Morton   :       Make unregister_netdevice wait
 66  *                                      indefinitely on dev->refcnt
 67  *              J Hadi Salim    :       - Backlog queue sampling
 68  *                                      - netif_rx() feedback
 69  */
 70 
 71 #include <linux/uaccess.h>
 72 #include <linux/bitops.h>
 73 #include <linux/capability.h>
 74 #include <linux/cpu.h>
 75 #include <linux/types.h>
 76 #include <linux/kernel.h>
 77 #include <linux/hash.h>
 78 #include <linux/slab.h>
 79 #include <linux/sched.h>
 80 #include <linux/sched/mm.h>
 81 #include <linux/mutex.h>
 82 #include <linux/rwsem.h>
 83 #include <linux/string.h>
 84 #include <linux/mm.h>
 85 #include <linux/socket.h>
 86 #include <linux/sockios.h>
 87 #include <linux/errno.h>
 88 #include <linux/interrupt.h>
 89 #include <linux/if_ether.h>
 90 #include <linux/netdevice.h>
 91 #include <linux/etherdevice.h>
 92 #include <linux/ethtool.h>
 93 #include <linux/skbuff.h>
 94 #include <linux/bpf.h>
 95 #include <linux/bpf_trace.h>
 96 #include <net/net_namespace.h>
 97 #include <net/sock.h>
 98 #include <net/busy_poll.h>
 99 #include <linux/rtnetlink.h>
100 #include <linux/stat.h>
101 #include <net/dsa.h>
102 #include <net/dst.h>
103 #include <net/dst_metadata.h>
104 #include <net/pkt_sched.h>
105 #include <net/pkt_cls.h>
106 #include <net/checksum.h>
107 #include <net/xfrm.h>
108 #include <linux/highmem.h>
109 #include <linux/init.h>
110 #include <linux/module.h>
111 #include <linux/netpoll.h>
112 #include <linux/rcupdate.h>
113 #include <linux/delay.h>
114 #include <net/iw_handler.h>
115 #include <asm/current.h>
116 #include <linux/audit.h>
117 #include <linux/dmaengine.h>
118 #include <linux/err.h>
119 #include <linux/ctype.h>
120 #include <linux/if_arp.h>
121 #include <linux/if_vlan.h>
122 #include <linux/ip.h>
123 #include <net/ip.h>
124 #include <net/mpls.h>
125 #include <linux/ipv6.h>
126 #include <linux/in.h>
127 #include <linux/jhash.h>
128 #include <linux/random.h>
129 #include <trace/events/napi.h>
130 #include <trace/events/net.h>
131 #include <trace/events/skb.h>
132 #include <linux/inetdevice.h>
133 #include <linux/cpu_rmap.h>
134 #include <linux/static_key.h>
135 #include <linux/hashtable.h>
136 #include <linux/vmalloc.h>
137 #include <linux/if_macvlan.h>
138 #include <linux/errqueue.h>
139 #include <linux/hrtimer.h>
140 #include <linux/netfilter_ingress.h>
141 #include <linux/crash_dump.h>
142 #include <linux/sctp.h>
143 #include <net/udp_tunnel.h>
144 #include <linux/net_namespace.h>
145 #include <linux/indirect_call_wrapper.h>
146 #include <net/devlink.h>
147 #include <linux/pm_runtime.h>
148 #include <linux/prandom.h>
149 
150 #include "net-sysfs.h"
151 
152 #define MAX_GRO_SKBS 8
153 
154 /* This should be increased if a protocol with a bigger head is added. */
155 #define GRO_MAX_HEAD (MAX_HEADER + 128)
156 
157 static DEFINE_SPINLOCK(ptype_lock);
158 static DEFINE_SPINLOCK(offload_lock);
159 struct list_head ptype_base[PTYPE_HASH_SIZE] __read_mostly;
160 struct list_head ptype_all __read_mostly;       /* Taps */
161 static struct list_head offload_base __read_mostly;
162 
163 static int netif_rx_internal(struct sk_buff *skb);
164 static int call_netdevice_notifiers_info(unsigned long val,
165                                          struct netdev_notifier_info *info);
166 static int call_netdevice_notifiers_extack(unsigned long val,
167                                            struct net_device *dev,
168                                            struct netlink_ext_ack *extack);
169 static struct napi_struct *napi_by_id(unsigned int napi_id);
170 
171 /*
172  * The @dev_base_head list is protected by @dev_base_lock and the rtnl
173  * semaphore.
174  *
175  * Pure readers hold dev_base_lock for reading, or rcu_read_lock()
176  *
177  * Writers must hold the rtnl semaphore while they loop through the
178  * dev_base_head list, and hold dev_base_lock for writing when they do the
179  * actual updates.  This allows pure readers to access the list even
180  * while a writer is preparing to update it.
181  *
182  * To put it another way, dev_base_lock is held for writing only to
183  * protect against pure readers; the rtnl semaphore provides the
184  * protection against other writers.
185  *
186  * See, for example usages, register_netdevice() and
187  * unregister_netdevice(), which must be called with the rtnl
188  * semaphore held.
189  */
190 DEFINE_RWLOCK(dev_base_lock);
191 EXPORT_SYMBOL(dev_base_lock);
192 
193 static DEFINE_MUTEX(ifalias_mutex);
194 
195 /* protects napi_hash addition/deletion and napi_gen_id */
196 static DEFINE_SPINLOCK(napi_hash_lock);
197 
198 static unsigned int napi_gen_id = NR_CPUS;
199 static DEFINE_READ_MOSTLY_HASHTABLE(napi_hash, 8);
200 
201 static DECLARE_RWSEM(devnet_rename_sem);
202 
203 static inline void dev_base_seq_inc(struct net *net)
204 {
205         while (++net->dev_base_seq == 0)
206                 ;
207 }
208 
209 static inline struct hlist_head *dev_name_hash(struct net *net, const char *name)
210 {
211         unsigned int hash = full_name_hash(net, name, strnlen(name, IFNAMSIZ));
212 
213         return &net->dev_name_head[hash_32(hash, NETDEV_HASHBITS)];
214 }
215 
216 static inline struct hlist_head *dev_index_hash(struct net *net, int ifindex)
217 {
218         return &net->dev_index_head[ifindex & (NETDEV_HASHENTRIES - 1)];
219 }
220 
221 static inline void rps_lock(struct softnet_data *sd)
222 {
223 #ifdef CONFIG_RPS
224         spin_lock(&sd->input_pkt_queue.lock);
225 #endif
226 }
227 
228 static inline void rps_unlock(struct softnet_data *sd)
229 {
230 #ifdef CONFIG_RPS
231         spin_unlock(&sd->input_pkt_queue.lock);
232 #endif
233 }
234 
235 static struct netdev_name_node *netdev_name_node_alloc(struct net_device *dev,
236                                                        const char *name)
237 {
238         struct netdev_name_node *name_node;
239 
240         name_node = kmalloc(sizeof(*name_node), GFP_KERNEL);
241         if (!name_node)
242                 return NULL;
243         INIT_HLIST_NODE(&name_node->hlist);
244         name_node->dev = dev;
245         name_node->name = name;
246         return name_node;
247 }
248 
249 static struct netdev_name_node *
250 netdev_name_node_head_alloc(struct net_device *dev)
251 {
252         struct netdev_name_node *name_node;
253 
254         name_node = netdev_name_node_alloc(dev, dev->name);
255         if (!name_node)
256                 return NULL;
257         INIT_LIST_HEAD(&name_node->list);
258         return name_node;
259 }
260 
261 static void netdev_name_node_free(struct netdev_name_node *name_node)
262 {
263         kfree(name_node);
264 }
265 
266 static void netdev_name_node_add(struct net *net,
267                                  struct netdev_name_node *name_node)
268 {
269         hlist_add_head_rcu(&name_node->hlist,
270                            dev_name_hash(net, name_node->name));
271 }
272 
273 static void netdev_name_node_del(struct netdev_name_node *name_node)
274 {
275         hlist_del_rcu(&name_node->hlist);
276 }
277 
278 static struct netdev_name_node *netdev_name_node_lookup(struct net *net,
279                                                         const char *name)
280 {
281         struct hlist_head *head = dev_name_hash(net, name);
282         struct netdev_name_node *name_node;
283 
284         hlist_for_each_entry(name_node, head, hlist)
285                 if (!strcmp(name_node->name, name))
286                         return name_node;
287         return NULL;
288 }
289 
290 static struct netdev_name_node *netdev_name_node_lookup_rcu(struct net *net,
291                                                             const char *name)
292 {
293         struct hlist_head *head = dev_name_hash(net, name);
294         struct netdev_name_node *name_node;
295 
296         hlist_for_each_entry_rcu(name_node, head, hlist)
297                 if (!strcmp(name_node->name, name))
298                         return name_node;
299         return NULL;
300 }
301 
302 int netdev_name_node_alt_create(struct net_device *dev, const char *name)
303 {
304         struct netdev_name_node *name_node;
305         struct net *net = dev_net(dev);
306 
307         name_node = netdev_name_node_lookup(net, name);
308         if (name_node)
309                 return -EEXIST;
310         name_node = netdev_name_node_alloc(dev, name);
311         if (!name_node)
312                 return -ENOMEM;
313         netdev_name_node_add(net, name_node);
314         /* The node that holds dev->name acts as a head of per-device list. */
315         list_add_tail(&name_node->list, &dev->name_node->list);
316 
317         return 0;
318 }
319 EXPORT_SYMBOL(netdev_name_node_alt_create);
320 
321 static void __netdev_name_node_alt_destroy(struct netdev_name_node *name_node)
322 {
323         list_del(&name_node->list);
324         netdev_name_node_del(name_node);
325         kfree(name_node->name);
326         netdev_name_node_free(name_node);
327 }
328 
329 int netdev_name_node_alt_destroy(struct net_device *dev, const char *name)
330 {
331         struct netdev_name_node *name_node;
332         struct net *net = dev_net(dev);
333 
334         name_node = netdev_name_node_lookup(net, name);
335         if (!name_node)
336                 return -ENOENT;
337         /* lookup might have found our primary name or a name belonging
338          * to another device.
339          */
340         if (name_node == dev->name_node || name_node->dev != dev)
341                 return -EINVAL;
342 
343         __netdev_name_node_alt_destroy(name_node);
344 
345         return 0;
346 }
347 EXPORT_SYMBOL(netdev_name_node_alt_destroy);
348 
349 static void netdev_name_node_alt_flush(struct net_device *dev)
350 {
351         struct netdev_name_node *name_node, *tmp;
352 
353         list_for_each_entry_safe(name_node, tmp, &dev->name_node->list, list)
354                 __netdev_name_node_alt_destroy(name_node);
355 }
356 
357 /* Device list insertion */
358 static void list_netdevice(struct net_device *dev)
359 {
360         struct net *net = dev_net(dev);
361 
362         ASSERT_RTNL();
363 
364         write_lock_bh(&dev_base_lock);
365         list_add_tail_rcu(&dev->dev_list, &net->dev_base_head);
366         netdev_name_node_add(net, dev->name_node);
367         hlist_add_head_rcu(&dev->index_hlist,
368                            dev_index_hash(net, dev->ifindex));
369         write_unlock_bh(&dev_base_lock);
370 
371         dev_base_seq_inc(net);
372 }
373 
374 /* Device list removal
375  * caller must respect a RCU grace period before freeing/reusing dev
376  */
377 static void unlist_netdevice(struct net_device *dev)
378 {
379         ASSERT_RTNL();
380 
381         /* Unlink dev from the device chain */
382         write_lock_bh(&dev_base_lock);
383         list_del_rcu(&dev->dev_list);
384         netdev_name_node_del(dev->name_node);
385         hlist_del_rcu(&dev->index_hlist);
386         write_unlock_bh(&dev_base_lock);
387 
388         dev_base_seq_inc(dev_net(dev));
389 }
390 
391 /*
392  *      Our notifier list
393  */
394 
395 static RAW_NOTIFIER_HEAD(netdev_chain);
396 
397 /*
398  *      Device drivers call our routines to queue packets here. We empty the
399  *      queue in the local softnet handler.
400  */
401 
402 DEFINE_PER_CPU_ALIGNED(struct softnet_data, softnet_data);
403 EXPORT_PER_CPU_SYMBOL(softnet_data);
404 
405 #ifdef CONFIG_LOCKDEP
406 /*
407  * register_netdevice() inits txq->_xmit_lock and sets lockdep class
408  * according to dev->type
409  */
410 static const unsigned short netdev_lock_type[] = {
411          ARPHRD_NETROM, ARPHRD_ETHER, ARPHRD_EETHER, ARPHRD_AX25,
412          ARPHRD_PRONET, ARPHRD_CHAOS, ARPHRD_IEEE802, ARPHRD_ARCNET,
413          ARPHRD_APPLETLK, ARPHRD_DLCI, ARPHRD_ATM, ARPHRD_METRICOM,
414          ARPHRD_IEEE1394, ARPHRD_EUI64, ARPHRD_INFINIBAND, ARPHRD_SLIP,
415          ARPHRD_CSLIP, ARPHRD_SLIP6, ARPHRD_CSLIP6, ARPHRD_RSRVD,
416          ARPHRD_ADAPT, ARPHRD_ROSE, ARPHRD_X25, ARPHRD_HWX25,
417          ARPHRD_PPP, ARPHRD_CISCO, ARPHRD_LAPB, ARPHRD_DDCMP,
418          ARPHRD_RAWHDLC, ARPHRD_TUNNEL, ARPHRD_TUNNEL6, ARPHRD_FRAD,
419          ARPHRD_SKIP, ARPHRD_LOOPBACK, ARPHRD_LOCALTLK, ARPHRD_FDDI,
420          ARPHRD_BIF, ARPHRD_SIT, ARPHRD_IPDDP, ARPHRD_IPGRE,
421          ARPHRD_PIMREG, ARPHRD_HIPPI, ARPHRD_ASH, ARPHRD_ECONET,
422          ARPHRD_IRDA, ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL,
423          ARPHRD_FCFABRIC, ARPHRD_IEEE80211, ARPHRD_IEEE80211_PRISM,
424          ARPHRD_IEEE80211_RADIOTAP, ARPHRD_PHONET, ARPHRD_PHONET_PIPE,
425          ARPHRD_IEEE802154, ARPHRD_VOID, ARPHRD_NONE};
426 
427 static const char *const netdev_lock_name[] = {
428         "_xmit_NETROM", "_xmit_ETHER", "_xmit_EETHER", "_xmit_AX25",
429         "_xmit_PRONET", "_xmit_CHAOS", "_xmit_IEEE802", "_xmit_ARCNET",
430         "_xmit_APPLETLK", "_xmit_DLCI", "_xmit_ATM", "_xmit_METRICOM",
431         "_xmit_IEEE1394", "_xmit_EUI64", "_xmit_INFINIBAND", "_xmit_SLIP",
432         "_xmit_CSLIP", "_xmit_SLIP6", "_xmit_CSLIP6", "_xmit_RSRVD",
433         "_xmit_ADAPT", "_xmit_ROSE", "_xmit_X25", "_xmit_HWX25",
434         "_xmit_PPP", "_xmit_CISCO", "_xmit_LAPB", "_xmit_DDCMP",
435         "_xmit_RAWHDLC", "_xmit_TUNNEL", "_xmit_TUNNEL6", "_xmit_FRAD",
436         "_xmit_SKIP", "_xmit_LOOPBACK", "_xmit_LOCALTLK", "_xmit_FDDI",
437         "_xmit_BIF", "_xmit_SIT", "_xmit_IPDDP", "_xmit_IPGRE",
438         "_xmit_PIMREG", "_xmit_HIPPI", "_xmit_ASH", "_xmit_ECONET",
439         "_xmit_IRDA", "_xmit_FCPP", "_xmit_FCAL", "_xmit_FCPL",
440         "_xmit_FCFABRIC", "_xmit_IEEE80211", "_xmit_IEEE80211_PRISM",
441         "_xmit_IEEE80211_RADIOTAP", "_xmit_PHONET", "_xmit_PHONET_PIPE",
442         "_xmit_IEEE802154", "_xmit_VOID", "_xmit_NONE"};
443 
444 static struct lock_class_key netdev_xmit_lock_key[ARRAY_SIZE(netdev_lock_type)];
445 static struct lock_class_key netdev_addr_lock_key[ARRAY_SIZE(netdev_lock_type)];
446 
447 static inline unsigned short netdev_lock_pos(unsigned short dev_type)
448 {
449         int i;
450 
451         for (i = 0; i < ARRAY_SIZE(netdev_lock_type); i++)
452                 if (netdev_lock_type[i] == dev_type)
453                         return i;
454         /* the last key is used by default */
455         return ARRAY_SIZE(netdev_lock_type) - 1;
456 }
457 
458 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
459                                                  unsigned short dev_type)
460 {
461         int i;
462 
463         i = netdev_lock_pos(dev_type);
464         lockdep_set_class_and_name(lock, &netdev_xmit_lock_key[i],
465                                    netdev_lock_name[i]);
466 }
467 
468 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
469 {
470         int i;
471 
472         i = netdev_lock_pos(dev->type);
473         lockdep_set_class_and_name(&dev->addr_list_lock,
474                                    &netdev_addr_lock_key[i],
475                                    netdev_lock_name[i]);
476 }
477 #else
478 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
479                                                  unsigned short dev_type)
480 {
481 }
482 
483 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
484 {
485 }
486 #endif
487 
488 /*******************************************************************************
489  *
490  *              Protocol management and registration routines
491  *
492  *******************************************************************************/
493 
494 
495 /*
496  *      Add a protocol ID to the list. Now that the input handler is
497  *      smarter we can dispense with all the messy stuff that used to be
498  *      here.
499  *
500  *      BEWARE!!! Protocol handlers, mangling input packets,
501  *      MUST BE last in hash buckets and checking protocol handlers
502  *      MUST start from promiscuous ptype_all chain in net_bh.
503  *      It is true now, do not change it.
504  *      Explanation follows: if protocol handler, mangling packet, will
505  *      be the first on list, it is not able to sense, that packet
506  *      is cloned and should be copied-on-write, so that it will
507  *      change it and subsequent readers will get broken packet.
508  *                                                      --ANK (980803)
509  */
510 
511 static inline struct list_head *ptype_head(const struct packet_type *pt)
512 {
513         if (pt->type == htons(ETH_P_ALL))
514                 return pt->dev ? &pt->dev->ptype_all : &ptype_all;
515         else
516                 return pt->dev ? &pt->dev->ptype_specific :
517                                  &ptype_base[ntohs(pt->type) & PTYPE_HASH_MASK];
518 }
519 
520 /**
521  *      dev_add_pack - add packet handler
522  *      @pt: packet type declaration
523  *
524  *      Add a protocol handler to the networking stack. The passed &packet_type
525  *      is linked into kernel lists and may not be freed until it has been
526  *      removed from the kernel lists.
527  *
528  *      This call does not sleep therefore it can not
529  *      guarantee all CPU's that are in middle of receiving packets
530  *      will see the new packet type (until the next received packet).
531  */
532 
533 void dev_add_pack(struct packet_type *pt)
534 {
535         struct list_head *head = ptype_head(pt);
536 
537         spin_lock(&ptype_lock);
538         list_add_rcu(&pt->list, head);
539         spin_unlock(&ptype_lock);
540 }
541 EXPORT_SYMBOL(dev_add_pack);
542 
543 /**
544  *      __dev_remove_pack        - remove packet handler
545  *      @pt: packet type declaration
546  *
547  *      Remove a protocol handler that was previously added to the kernel
548  *      protocol handlers by dev_add_pack(). The passed &packet_type is removed
549  *      from the kernel lists and can be freed or reused once this function
550  *      returns.
551  *
552  *      The packet type might still be in use by receivers
553  *      and must not be freed until after all the CPU's have gone
554  *      through a quiescent state.
555  */
556 void __dev_remove_pack(struct packet_type *pt)
557 {
558         struct list_head *head = ptype_head(pt);
559         struct packet_type *pt1;
560 
561         spin_lock(&ptype_lock);
562 
563         list_for_each_entry(pt1, head, list) {
564                 if (pt == pt1) {
565                         list_del_rcu(&pt->list);
566                         goto out;
567                 }
568         }
569 
570         pr_warn("dev_remove_pack: %p not found\n", pt);
571 out:
572         spin_unlock(&ptype_lock);
573 }
574 EXPORT_SYMBOL(__dev_remove_pack);
575 
576 /**
577  *      dev_remove_pack  - remove packet handler
578  *      @pt: packet type declaration
579  *
580  *      Remove a protocol handler that was previously added to the kernel
581  *      protocol handlers by dev_add_pack(). The passed &packet_type is removed
582  *      from the kernel lists and can be freed or reused once this function
583  *      returns.
584  *
585  *      This call sleeps to guarantee that no CPU is looking at the packet
586  *      type after return.
587  */
588 void dev_remove_pack(struct packet_type *pt)
589 {
590         __dev_remove_pack(pt);
591 
592         synchronize_net();
593 }
594 EXPORT_SYMBOL(dev_remove_pack);
595 
596 
597 /**
598  *      dev_add_offload - register offload handlers
599  *      @po: protocol offload declaration
600  *
601  *      Add protocol offload handlers to the networking stack. The passed
602  *      &proto_offload is linked into kernel lists and may not be freed until
603  *      it has been removed from the kernel lists.
604  *
605  *      This call does not sleep therefore it can not
606  *      guarantee all CPU's that are in middle of receiving packets
607  *      will see the new offload handlers (until the next received packet).
608  */
609 void dev_add_offload(struct packet_offload *po)
610 {
611         struct packet_offload *elem;
612 
613         spin_lock(&offload_lock);
614         list_for_each_entry(elem, &offload_base, list) {
615                 if (po->priority < elem->priority)
616                         break;
617         }
618         list_add_rcu(&po->list, elem->list.prev);
619         spin_unlock(&offload_lock);
620 }
621 EXPORT_SYMBOL(dev_add_offload);
622 
623 /**
624  *      __dev_remove_offload     - remove offload handler
625  *      @po: packet offload declaration
626  *
627  *      Remove a protocol offload handler that was previously added to the
628  *      kernel offload handlers by dev_add_offload(). The passed &offload_type
629  *      is removed from the kernel lists and can be freed or reused once this
630  *      function returns.
631  *
632  *      The packet type might still be in use by receivers
633  *      and must not be freed until after all the CPU's have gone
634  *      through a quiescent state.
635  */
636 static void __dev_remove_offload(struct packet_offload *po)
637 {
638         struct list_head *head = &offload_base;
639         struct packet_offload *po1;
640 
641         spin_lock(&offload_lock);
642 
643         list_for_each_entry(po1, head, list) {
644                 if (po == po1) {
645                         list_del_rcu(&po->list);
646                         goto out;
647                 }
648         }
649 
650         pr_warn("dev_remove_offload: %p not found\n", po);
651 out:
652         spin_unlock(&offload_lock);
653 }
654 
655 /**
656  *      dev_remove_offload       - remove packet offload handler
657  *      @po: packet offload declaration
658  *
659  *      Remove a packet offload handler that was previously added to the kernel
660  *      offload handlers by dev_add_offload(). The passed &offload_type is
661  *      removed from the kernel lists and can be freed or reused once this
662  *      function returns.
663  *
664  *      This call sleeps to guarantee that no CPU is looking at the packet
665  *      type after return.
666  */
667 void dev_remove_offload(struct packet_offload *po)
668 {
669         __dev_remove_offload(po);
670 
671         synchronize_net();
672 }
673 EXPORT_SYMBOL(dev_remove_offload);
674 
675 /******************************************************************************
676  *
677  *                    Device Boot-time Settings Routines
678  *
679  ******************************************************************************/
680 
681 /* Boot time configuration table */
682 static struct netdev_boot_setup dev_boot_setup[NETDEV_BOOT_SETUP_MAX];
683 
684 /**
685  *      netdev_boot_setup_add   - add new setup entry
686  *      @name: name of the device
687  *      @map: configured settings for the device
688  *
689  *      Adds new setup entry to the dev_boot_setup list.  The function
690  *      returns 0 on error and 1 on success.  This is a generic routine to
691  *      all netdevices.
692  */
693 static int netdev_boot_setup_add(char *name, struct ifmap *map)
694 {
695         struct netdev_boot_setup *s;
696         int i;
697 
698         s = dev_boot_setup;
699         for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
700                 if (s[i].name[0] == '\0' || s[i].name[0] == ' ') {
701                         memset(s[i].name, 0, sizeof(s[i].name));
702                         strlcpy(s[i].name, name, IFNAMSIZ);
703                         memcpy(&s[i].map, map, sizeof(s[i].map));
704                         break;
705                 }
706         }
707 
708         return i >= NETDEV_BOOT_SETUP_MAX ? 0 : 1;
709 }
710 
711 /**
712  * netdev_boot_setup_check      - check boot time settings
713  * @dev: the netdevice
714  *
715  * Check boot time settings for the device.
716  * The found settings are set for the device to be used
717  * later in the device probing.
718  * Returns 0 if no settings found, 1 if they are.
719  */
720 int netdev_boot_setup_check(struct net_device *dev)
721 {
722         struct netdev_boot_setup *s = dev_boot_setup;
723         int i;
724 
725         for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
726                 if (s[i].name[0] != '\0' && s[i].name[0] != ' ' &&
727                     !strcmp(dev->name, s[i].name)) {
728                         dev->irq = s[i].map.irq;
729                         dev->base_addr = s[i].map.base_addr;
730                         dev->mem_start = s[i].map.mem_start;
731                         dev->mem_end = s[i].map.mem_end;
732                         return 1;
733                 }
734         }
735         return 0;
736 }
737 EXPORT_SYMBOL(netdev_boot_setup_check);
738 
739 
740 /**
741  * netdev_boot_base     - get address from boot time settings
742  * @prefix: prefix for network device
743  * @unit: id for network device
744  *
745  * Check boot time settings for the base address of device.
746  * The found settings are set for the device to be used
747  * later in the device probing.
748  * Returns 0 if no settings found.
749  */
750 unsigned long netdev_boot_base(const char *prefix, int unit)
751 {
752         const struct netdev_boot_setup *s = dev_boot_setup;
753         char name[IFNAMSIZ];
754         int i;
755 
756         sprintf(name, "%s%d", prefix, unit);
757 
758         /*
759          * If device already registered then return base of 1
760          * to indicate not to probe for this interface
761          */
762         if (__dev_get_by_name(&init_net, name))
763                 return 1;
764 
765         for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++)
766                 if (!strcmp(name, s[i].name))
767                         return s[i].map.base_addr;
768         return 0;
769 }
770 
771 /*
772  * Saves at boot time configured settings for any netdevice.
773  */
774 int __init netdev_boot_setup(char *str)
775 {
776         int ints[5];
777         struct ifmap map;
778 
779         str = get_options(str, ARRAY_SIZE(ints), ints);
780         if (!str || !*str)
781                 return 0;
782 
783         /* Save settings */
784         memset(&map, 0, sizeof(map));
785         if (ints[0] > 0)
786                 map.irq = ints[1];
787         if (ints[0] > 1)
788                 map.base_addr = ints[2];
789         if (ints[0] > 2)
790                 map.mem_start = ints[3];
791         if (ints[0] > 3)
792                 map.mem_end = ints[4];
793 
794         /* Add new entry to the list */
795         return netdev_boot_setup_add(str, &map);
796 }
797 
798 __setup("netdev=", netdev_boot_setup);
799 
800 /*******************************************************************************
801  *
802  *                          Device Interface Subroutines
803  *
804  *******************************************************************************/
805 
806 /**
807  *      dev_get_iflink  - get 'iflink' value of a interface
808  *      @dev: targeted interface
809  *
810  *      Indicates the ifindex the interface is linked to.
811  *      Physical interfaces have the same 'ifindex' and 'iflink' values.
812  */
813 
814 int dev_get_iflink(const struct net_device *dev)
815 {
816         if (dev->netdev_ops && dev->netdev_ops->ndo_get_iflink)
817                 return dev->netdev_ops->ndo_get_iflink(dev);
818 
819         return dev->ifindex;
820 }
821 EXPORT_SYMBOL(dev_get_iflink);
822 
823 /**
824  *      dev_fill_metadata_dst - Retrieve tunnel egress information.
825  *      @dev: targeted interface
826  *      @skb: The packet.
827  *
828  *      For better visibility of tunnel traffic OVS needs to retrieve
829  *      egress tunnel information for a packet. Following API allows
830  *      user to get this info.
831  */
832 int dev_fill_metadata_dst(struct net_device *dev, struct sk_buff *skb)
833 {
834         struct ip_tunnel_info *info;
835 
836         if (!dev->netdev_ops  || !dev->netdev_ops->ndo_fill_metadata_dst)
837                 return -EINVAL;
838 
839         info = skb_tunnel_info_unclone(skb);
840         if (!info)
841                 return -ENOMEM;
842         if (unlikely(!(info->mode & IP_TUNNEL_INFO_TX)))
843                 return -EINVAL;
844 
845         return dev->netdev_ops->ndo_fill_metadata_dst(dev, skb);
846 }
847 EXPORT_SYMBOL_GPL(dev_fill_metadata_dst);
848 
849 /**
850  *      __dev_get_by_name       - find a device by its name
851  *      @net: the applicable net namespace
852  *      @name: name to find
853  *
854  *      Find an interface by name. Must be called under RTNL semaphore
855  *      or @dev_base_lock. If the name is found a pointer to the device
856  *      is returned. If the name is not found then %NULL is returned. The
857  *      reference counters are not incremented so the caller must be
858  *      careful with locks.
859  */
860 
861 struct net_device *__dev_get_by_name(struct net *net, const char *name)
862 {
863         struct netdev_name_node *node_name;
864 
865         node_name = netdev_name_node_lookup(net, name);
866         return node_name ? node_name->dev : NULL;
867 }
868 EXPORT_SYMBOL(__dev_get_by_name);
869 
870 /**
871  * dev_get_by_name_rcu  - find a device by its name
872  * @net: the applicable net namespace
873  * @name: name to find
874  *
875  * Find an interface by name.
876  * If the name is found a pointer to the device is returned.
877  * If the name is not found then %NULL is returned.
878  * The reference counters are not incremented so the caller must be
879  * careful with locks. The caller must hold RCU lock.
880  */
881 
882 struct net_device *dev_get_by_name_rcu(struct net *net, const char *name)
883 {
884         struct netdev_name_node *node_name;
885 
886         node_name = netdev_name_node_lookup_rcu(net, name);
887         return node_name ? node_name->dev : NULL;
888 }
889 EXPORT_SYMBOL(dev_get_by_name_rcu);
890 
891 /**
892  *      dev_get_by_name         - find a device by its name
893  *      @net: the applicable net namespace
894  *      @name: name to find
895  *
896  *      Find an interface by name. This can be called from any
897  *      context and does its own locking. The returned handle has
898  *      the usage count incremented and the caller must use dev_put() to
899  *      release it when it is no longer needed. %NULL is returned if no
900  *      matching device is found.
901  */
902 
903 struct net_device *dev_get_by_name(struct net *net, const char *name)
904 {
905         struct net_device *dev;
906 
907         rcu_read_lock();
908         dev = dev_get_by_name_rcu(net, name);
909         if (dev)
910                 dev_hold(dev);
911         rcu_read_unlock();
912         return dev;
913 }
914 EXPORT_SYMBOL(dev_get_by_name);
915 
916 /**
917  *      __dev_get_by_index - find a device by its ifindex
918  *      @net: the applicable net namespace
919  *      @ifindex: index of device
920  *
921  *      Search for an interface by index. Returns %NULL if the device
922  *      is not found or a pointer to the device. The device has not
923  *      had its reference counter increased so the caller must be careful
924  *      about locking. The caller must hold either the RTNL semaphore
925  *      or @dev_base_lock.
926  */
927 
928 struct net_device *__dev_get_by_index(struct net *net, int ifindex)
929 {
930         struct net_device *dev;
931         struct hlist_head *head = dev_index_hash(net, ifindex);
932 
933         hlist_for_each_entry(dev, head, index_hlist)
934                 if (dev->ifindex == ifindex)
935                         return dev;
936 
937         return NULL;
938 }
939 EXPORT_SYMBOL(__dev_get_by_index);
940 
941 /**
942  *      dev_get_by_index_rcu - find a device by its ifindex
943  *      @net: the applicable net namespace
944  *      @ifindex: index of device
945  *
946  *      Search for an interface by index. Returns %NULL if the device
947  *      is not found or a pointer to the device. The device has not
948  *      had its reference counter increased so the caller must be careful
949  *      about locking. The caller must hold RCU lock.
950  */
951 
952 struct net_device *dev_get_by_index_rcu(struct net *net, int ifindex)
953 {
954         struct net_device *dev;
955         struct hlist_head *head = dev_index_hash(net, ifindex);
956 
957         hlist_for_each_entry_rcu(dev, head, index_hlist)
958                 if (dev->ifindex == ifindex)
959                         return dev;
960 
961         return NULL;
962 }
963 EXPORT_SYMBOL(dev_get_by_index_rcu);
964 
965 
966 /**
967  *      dev_get_by_index - find a device by its ifindex
968  *      @net: the applicable net namespace
969  *      @ifindex: index of device
970  *
971  *      Search for an interface by index. Returns NULL if the device
972  *      is not found or a pointer to the device. The device returned has
973  *      had a reference added and the pointer is safe until the user calls
974  *      dev_put to indicate they have finished with it.
975  */
976 
977 struct net_device *dev_get_by_index(struct net *net, int ifindex)
978 {
979         struct net_device *dev;
980 
981         rcu_read_lock();
982         dev = dev_get_by_index_rcu(net, ifindex);
983         if (dev)
984                 dev_hold(dev);
985         rcu_read_unlock();
986         return dev;
987 }
988 EXPORT_SYMBOL(dev_get_by_index);
989 
990 /**
991  *      dev_get_by_napi_id - find a device by napi_id
992  *      @napi_id: ID of the NAPI struct
993  *
994  *      Search for an interface by NAPI ID. Returns %NULL if the device
995  *      is not found or a pointer to the device. The device has not had
996  *      its reference counter increased so the caller must be careful
997  *      about locking. The caller must hold RCU lock.
998  */
999 
1000 struct net_device *dev_get_by_napi_id(unsigned int napi_id)
1001 {
1002         struct napi_struct *napi;
1003 
1004         WARN_ON_ONCE(!rcu_read_lock_held());
1005 
1006         if (napi_id < MIN_NAPI_ID)
1007                 return NULL;
1008 
1009         napi = napi_by_id(napi_id);
1010 
1011         return napi ? napi->dev : NULL;
1012 }
1013 EXPORT_SYMBOL(dev_get_by_napi_id);
1014 
1015 /**
1016  *      netdev_get_name - get a netdevice name, knowing its ifindex.
1017  *      @net: network namespace
1018  *      @name: a pointer to the buffer where the name will be stored.
1019  *      @ifindex: the ifindex of the interface to get the name from.
1020  */
1021 int netdev_get_name(struct net *net, char *name, int ifindex)
1022 {
1023         struct net_device *dev;
1024         int ret;
1025 
1026         down_read(&devnet_rename_sem);
1027         rcu_read_lock();
1028 
1029         dev = dev_get_by_index_rcu(net, ifindex);
1030         if (!dev) {
1031                 ret = -ENODEV;
1032                 goto out;
1033         }
1034 
1035         strcpy(name, dev->name);
1036 
1037         ret = 0;
1038 out:
1039         rcu_read_unlock();
1040         up_read(&devnet_rename_sem);
1041         return ret;
1042 }
1043 
1044 /**
1045  *      dev_getbyhwaddr_rcu - find a device by its hardware address
1046  *      @net: the applicable net namespace
1047  *      @type: media type of device
1048  *      @ha: hardware address
1049  *
1050  *      Search for an interface by MAC address. Returns NULL if the device
1051  *      is not found or a pointer to the device.
1052  *      The caller must hold RCU or RTNL.
1053  *      The returned device has not had its ref count increased
1054  *      and the caller must therefore be careful about locking
1055  *
1056  */
1057 
1058 struct net_device *dev_getbyhwaddr_rcu(struct net *net, unsigned short type,
1059                                        const char *ha)
1060 {
1061         struct net_device *dev;
1062 
1063         for_each_netdev_rcu(net, dev)
1064                 if (dev->type == type &&
1065                     !memcmp(dev->dev_addr, ha, dev->addr_len))
1066                         return dev;
1067 
1068         return NULL;
1069 }
1070 EXPORT_SYMBOL(dev_getbyhwaddr_rcu);
1071 
1072 struct net_device *dev_getfirstbyhwtype(struct net *net, unsigned short type)
1073 {
1074         struct net_device *dev, *ret = NULL;
1075 
1076         rcu_read_lock();
1077         for_each_netdev_rcu(net, dev)
1078                 if (dev->type == type) {
1079                         dev_hold(dev);
1080                         ret = dev;
1081                         break;
1082                 }
1083         rcu_read_unlock();
1084         return ret;
1085 }
1086 EXPORT_SYMBOL(dev_getfirstbyhwtype);
1087 
1088 /**
1089  *      __dev_get_by_flags - find any device with given flags
1090  *      @net: the applicable net namespace
1091  *      @if_flags: IFF_* values
1092  *      @mask: bitmask of bits in if_flags to check
1093  *
1094  *      Search for any interface with the given flags. Returns NULL if a device
1095  *      is not found or a pointer to the device. Must be called inside
1096  *      rtnl_lock(), and result refcount is unchanged.
1097  */
1098 
1099 struct net_device *__dev_get_by_flags(struct net *net, unsigned short if_flags,
1100                                       unsigned short mask)
1101 {
1102         struct net_device *dev, *ret;
1103 
1104         ASSERT_RTNL();
1105 
1106         ret = NULL;
1107         for_each_netdev(net, dev) {
1108                 if (((dev->flags ^ if_flags) & mask) == 0) {
1109                         ret = dev;
1110                         break;
1111                 }
1112         }
1113         return ret;
1114 }
1115 EXPORT_SYMBOL(__dev_get_by_flags);
1116 
1117 /**
1118  *      dev_valid_name - check if name is okay for network device
1119  *      @name: name string
1120  *
1121  *      Network device names need to be valid file names to
1122  *      allow sysfs to work.  We also disallow any kind of
1123  *      whitespace.
1124  */
1125 bool dev_valid_name(const char *name)
1126 {
1127         if (*name == '\0')
1128                 return false;
1129         if (strnlen(name, IFNAMSIZ) == IFNAMSIZ)
1130                 return false;
1131         if (!strcmp(name, ".") || !strcmp(name, ".."))
1132                 return false;
1133 
1134         while (*name) {
1135                 if (*name == '/' || *name == ':' || isspace(*name))
1136                         return false;
1137                 name++;
1138         }
1139         return true;
1140 }
1141 EXPORT_SYMBOL(dev_valid_name);
1142 
1143 /**
1144  *      __dev_alloc_name - allocate a name for a device
1145  *      @net: network namespace to allocate the device name in
1146  *      @name: name format string
1147  *      @buf:  scratch buffer and result name string
1148  *
1149  *      Passed a format string - eg "lt%d" it will try and find a suitable
1150  *      id. It scans list of devices to build up a free map, then chooses
1151  *      the first empty slot. The caller must hold the dev_base or rtnl lock
1152  *      while allocating the name and adding the device in order to avoid
1153  *      duplicates.
1154  *      Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1155  *      Returns the number of the unit assigned or a negative errno code.
1156  */
1157 
1158 static int __dev_alloc_name(struct net *net, const char *name, char *buf)
1159 {
1160         int i = 0;
1161         const char *p;
1162         const int max_netdevices = 8*PAGE_SIZE;
1163         unsigned long *inuse;
1164         struct net_device *d;
1165 
1166         if (!dev_valid_name(name))
1167                 return -EINVAL;
1168 
1169         p = strchr(name, '%');
1170         if (p) {
1171                 /*
1172                  * Verify the string as this thing may have come from
1173                  * the user.  There must be either one "%d" and no other "%"
1174                  * characters.
1175                  */
1176                 if (p[1] != 'd' || strchr(p + 2, '%'))
1177                         return -EINVAL;
1178 
1179                 /* Use one page as a bit array of possible slots */
1180                 inuse = (unsigned long *) get_zeroed_page(GFP_ATOMIC);
1181                 if (!inuse)
1182                         return -ENOMEM;
1183 
1184                 for_each_netdev(net, d) {
1185                         struct netdev_name_node *name_node;
1186                         list_for_each_entry(name_node, &d->name_node->list, list) {
1187                                 if (!sscanf(name_node->name, name, &i))
1188                                         continue;
1189                                 if (i < 0 || i >= max_netdevices)
1190                                         continue;
1191 
1192                                 /*  avoid cases where sscanf is not exact inverse of printf */
1193                                 snprintf(buf, IFNAMSIZ, name, i);
1194                                 if (!strncmp(buf, name_node->name, IFNAMSIZ))
1195                                         set_bit(i, inuse);
1196                         }
1197                         if (!sscanf(d->name, name, &i))
1198                                 continue;
1199                         if (i < 0 || i >= max_netdevices)
1200                                 continue;
1201 
1202                         /*  avoid cases where sscanf is not exact inverse of printf */
1203                         snprintf(buf, IFNAMSIZ, name, i);
1204                         if (!strncmp(buf, d->name, IFNAMSIZ))
1205                                 set_bit(i, inuse);
1206                 }
1207 
1208                 i = find_first_zero_bit(inuse, max_netdevices);
1209                 free_page((unsigned long) inuse);
1210         }
1211 
1212         snprintf(buf, IFNAMSIZ, name, i);
1213         if (!__dev_get_by_name(net, buf))
1214                 return i;
1215 
1216         /* It is possible to run out of possible slots
1217          * when the name is long and there isn't enough space left
1218          * for the digits, or if all bits are used.
1219          */
1220         return -ENFILE;
1221 }
1222 
1223 static int dev_alloc_name_ns(struct net *net,
1224                              struct net_device *dev,
1225                              const char *name)
1226 {
1227         char buf[IFNAMSIZ];
1228         int ret;
1229 
1230         BUG_ON(!net);
1231         ret = __dev_alloc_name(net, name, buf);
1232         if (ret >= 0)
1233                 strlcpy(dev->name, buf, IFNAMSIZ);
1234         return ret;
1235 }
1236 
1237 /**
1238  *      dev_alloc_name - allocate a name for a device
1239  *      @dev: device
1240  *      @name: name format string
1241  *
1242  *      Passed a format string - eg "lt%d" it will try and find a suitable
1243  *      id. It scans list of devices to build up a free map, then chooses
1244  *      the first empty slot. The caller must hold the dev_base or rtnl lock
1245  *      while allocating the name and adding the device in order to avoid
1246  *      duplicates.
1247  *      Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1248  *      Returns the number of the unit assigned or a negative errno code.
1249  */
1250 
1251 int dev_alloc_name(struct net_device *dev, const char *name)
1252 {
1253         return dev_alloc_name_ns(dev_net(dev), dev, name);
1254 }
1255 EXPORT_SYMBOL(dev_alloc_name);
1256 
1257 static int dev_get_valid_name(struct net *net, struct net_device *dev,
1258                               const char *name)
1259 {
1260         BUG_ON(!net);
1261 
1262         if (!dev_valid_name(name))
1263                 return -EINVAL;
1264 
1265         if (strchr(name, '%'))
1266                 return dev_alloc_name_ns(net, dev, name);
1267         else if (__dev_get_by_name(net, name))
1268                 return -EEXIST;
1269         else if (dev->name != name)
1270                 strlcpy(dev->name, name, IFNAMSIZ);
1271 
1272         return 0;
1273 }
1274 
1275 /**
1276  *      dev_change_name - change name of a device
1277  *      @dev: device
1278  *      @newname: name (or format string) must be at least IFNAMSIZ
1279  *
1280  *      Change name of a device, can pass format strings "eth%d".
1281  *      for wildcarding.
1282  */
1283 int dev_change_name(struct net_device *dev, const char *newname)
1284 {
1285         unsigned char old_assign_type;
1286         char oldname[IFNAMSIZ];
1287         int err = 0;
1288         int ret;
1289         struct net *net;
1290 
1291         ASSERT_RTNL();
1292         BUG_ON(!dev_net(dev));
1293 
1294         net = dev_net(dev);
1295 
1296         /* Some auto-enslaved devices e.g. failover slaves are
1297          * special, as userspace might rename the device after
1298          * the interface had been brought up and running since
1299          * the point kernel initiated auto-enslavement. Allow
1300          * live name change even when these slave devices are
1301          * up and running.
1302          *
1303          * Typically, users of these auto-enslaving devices
1304          * don't actually care about slave name change, as
1305          * they are supposed to operate on master interface
1306          * directly.
1307          */
1308         if (dev->flags & IFF_UP &&
1309             likely(!(dev->priv_flags & IFF_LIVE_RENAME_OK)))
1310                 return -EBUSY;
1311 
1312         down_write(&devnet_rename_sem);
1313 
1314         if (strncmp(newname, dev->name, IFNAMSIZ) == 0) {
1315                 up_write(&devnet_rename_sem);
1316                 return 0;
1317         }
1318 
1319         memcpy(oldname, dev->name, IFNAMSIZ);
1320 
1321         err = dev_get_valid_name(net, dev, newname);
1322         if (err < 0) {
1323                 up_write(&devnet_rename_sem);
1324                 return err;
1325         }
1326 
1327         if (oldname[0] && !strchr(oldname, '%'))
1328                 netdev_info(dev, "renamed from %s\n", oldname);
1329 
1330         old_assign_type = dev->name_assign_type;
1331         dev->name_assign_type = NET_NAME_RENAMED;
1332 
1333 rollback:
1334         ret = device_rename(&dev->dev, dev->name);
1335         if (ret) {
1336                 memcpy(dev->name, oldname, IFNAMSIZ);
1337                 dev->name_assign_type = old_assign_type;
1338                 up_write(&devnet_rename_sem);
1339                 return ret;
1340         }
1341 
1342         up_write(&devnet_rename_sem);
1343 
1344         netdev_adjacent_rename_links(dev, oldname);
1345 
1346         write_lock_bh(&dev_base_lock);
1347         netdev_name_node_del(dev->name_node);
1348         write_unlock_bh(&dev_base_lock);
1349 
1350         synchronize_rcu();
1351 
1352         write_lock_bh(&dev_base_lock);
1353         netdev_name_node_add(net, dev->name_node);
1354         write_unlock_bh(&dev_base_lock);
1355 
1356         ret = call_netdevice_notifiers(NETDEV_CHANGENAME, dev);
1357         ret = notifier_to_errno(ret);
1358 
1359         if (ret) {
1360                 /* err >= 0 after dev_alloc_name() or stores the first errno */
1361                 if (err >= 0) {
1362                         err = ret;
1363                         down_write(&devnet_rename_sem);
1364                         memcpy(dev->name, oldname, IFNAMSIZ);
1365                         memcpy(oldname, newname, IFNAMSIZ);
1366                         dev->name_assign_type = old_assign_type;
1367                         old_assign_type = NET_NAME_RENAMED;
1368                         goto rollback;
1369                 } else {
1370                         pr_err("%s: name change rollback failed: %d\n",
1371                                dev->name, ret);
1372                 }
1373         }
1374 
1375         return err;
1376 }
1377 
1378 /**
1379  *      dev_set_alias - change ifalias of a device
1380  *      @dev: device
1381  *      @alias: name up to IFALIASZ
1382  *      @len: limit of bytes to copy from info
1383  *
1384  *      Set ifalias for a device,
1385  */
1386 int dev_set_alias(struct net_device *dev, const char *alias, size_t len)
1387 {
1388         struct dev_ifalias *new_alias = NULL;
1389 
1390         if (len >= IFALIASZ)
1391                 return -EINVAL;
1392 
1393         if (len) {
1394                 new_alias = kmalloc(sizeof(*new_alias) + len + 1, GFP_KERNEL);
1395                 if (!new_alias)
1396                         return -ENOMEM;
1397 
1398                 memcpy(new_alias->ifalias, alias, len);
1399                 new_alias->ifalias[len] = 0;
1400         }
1401 
1402         mutex_lock(&ifalias_mutex);
1403         new_alias = rcu_replace_pointer(dev->ifalias, new_alias,
1404                                         mutex_is_locked(&ifalias_mutex));
1405         mutex_unlock(&ifalias_mutex);
1406 
1407         if (new_alias)
1408                 kfree_rcu(new_alias, rcuhead);
1409 
1410         return len;
1411 }
1412 EXPORT_SYMBOL(dev_set_alias);
1413 
1414 /**
1415  *      dev_get_alias - get ifalias of a device
1416  *      @dev: device
1417  *      @name: buffer to store name of ifalias
1418  *      @len: size of buffer
1419  *
1420  *      get ifalias for a device.  Caller must make sure dev cannot go
1421  *      away,  e.g. rcu read lock or own a reference count to device.
1422  */
1423 int dev_get_alias(const struct net_device *dev, char *name, size_t len)
1424 {
1425         const struct dev_ifalias *alias;
1426         int ret = 0;
1427 
1428         rcu_read_lock();
1429         alias = rcu_dereference(dev->ifalias);
1430         if (alias)
1431                 ret = snprintf(name, len, "%s", alias->ifalias);
1432         rcu_read_unlock();
1433 
1434         return ret;
1435 }
1436 
1437 /**
1438  *      netdev_features_change - device changes features
1439  *      @dev: device to cause notification
1440  *
1441  *      Called to indicate a device has changed features.
1442  */
1443 void netdev_features_change(struct net_device *dev)
1444 {
1445         call_netdevice_notifiers(NETDEV_FEAT_CHANGE, dev);
1446 }
1447 EXPORT_SYMBOL(netdev_features_change);
1448 
1449 /**
1450  *      netdev_state_change - device changes state
1451  *      @dev: device to cause notification
1452  *
1453  *      Called to indicate a device has changed state. This function calls
1454  *      the notifier chains for netdev_chain and sends a NEWLINK message
1455  *      to the routing socket.
1456  */
1457 void netdev_state_change(struct net_device *dev)
1458 {
1459         if (dev->flags & IFF_UP) {
1460                 struct netdev_notifier_change_info change_info = {
1461                         .info.dev = dev,
1462                 };
1463 
1464                 call_netdevice_notifiers_info(NETDEV_CHANGE,
1465                                               &change_info.info);
1466                 rtmsg_ifinfo(RTM_NEWLINK, dev, 0, GFP_KERNEL);
1467         }
1468 }
1469 EXPORT_SYMBOL(netdev_state_change);
1470 
1471 /**
1472  * __netdev_notify_peers - notify network peers about existence of @dev,
1473  * to be called when rtnl lock is already held.
1474  * @dev: network device
1475  *
1476  * Generate traffic such that interested network peers are aware of
1477  * @dev, such as by generating a gratuitous ARP. This may be used when
1478  * a device wants to inform the rest of the network about some sort of
1479  * reconfiguration such as a failover event or virtual machine
1480  * migration.
1481  */
1482 void __netdev_notify_peers(struct net_device *dev)
1483 {
1484         ASSERT_RTNL();
1485         call_netdevice_notifiers(NETDEV_NOTIFY_PEERS, dev);
1486         call_netdevice_notifiers(NETDEV_RESEND_IGMP, dev);
1487 }
1488 EXPORT_SYMBOL(__netdev_notify_peers);
1489 
1490 /**
1491  * netdev_notify_peers - notify network peers about existence of @dev
1492  * @dev: network device
1493  *
1494  * Generate traffic such that interested network peers are aware of
1495  * @dev, such as by generating a gratuitous ARP. This may be used when
1496  * a device wants to inform the rest of the network about some sort of
1497  * reconfiguration such as a failover event or virtual machine
1498  * migration.
1499  */
1500 void netdev_notify_peers(struct net_device *dev)
1501 {
1502         rtnl_lock();
1503         __netdev_notify_peers(dev);
1504         rtnl_unlock();
1505 }
1506 EXPORT_SYMBOL(netdev_notify_peers);
1507 
1508 static int __dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1509 {
1510         const struct net_device_ops *ops = dev->netdev_ops;
1511         int ret;
1512 
1513         ASSERT_RTNL();
1514 
1515         if (!netif_device_present(dev)) {
1516                 /* may be detached because parent is runtime-suspended */
1517                 if (dev->dev.parent)
1518                         pm_runtime_resume(dev->dev.parent);
1519                 if (!netif_device_present(dev))
1520                         return -ENODEV;
1521         }
1522 
1523         /* Block netpoll from trying to do any rx path servicing.
1524          * If we don't do this there is a chance ndo_poll_controller
1525          * or ndo_poll may be running while we open the device
1526          */
1527         netpoll_poll_disable(dev);
1528 
1529         ret = call_netdevice_notifiers_extack(NETDEV_PRE_UP, dev, extack);
1530         ret = notifier_to_errno(ret);
1531         if (ret)
1532                 return ret;
1533 
1534         set_bit(__LINK_STATE_START, &dev->state);
1535 
1536         if (ops->ndo_validate_addr)
1537                 ret = ops->ndo_validate_addr(dev);
1538 
1539         if (!ret && ops->ndo_open)
1540                 ret = ops->ndo_open(dev);
1541 
1542         netpoll_poll_enable(dev);
1543 
1544         if (ret)
1545                 clear_bit(__LINK_STATE_START, &dev->state);
1546         else {
1547                 dev->flags |= IFF_UP;
1548                 dev_set_rx_mode(dev);
1549                 dev_activate(dev);
1550                 add_device_randomness(dev->dev_addr, dev->addr_len);
1551         }
1552 
1553         return ret;
1554 }
1555 
1556 /**
1557  *      dev_open        - prepare an interface for use.
1558  *      @dev: device to open
1559  *      @extack: netlink extended ack
1560  *
1561  *      Takes a device from down to up state. The device's private open
1562  *      function is invoked and then the multicast lists are loaded. Finally
1563  *      the device is moved into the up state and a %NETDEV_UP message is
1564  *      sent to the netdev notifier chain.
1565  *
1566  *      Calling this function on an active interface is a nop. On a failure
1567  *      a negative errno code is returned.
1568  */
1569 int dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1570 {
1571         int ret;
1572 
1573         if (dev->flags & IFF_UP)
1574                 return 0;
1575 
1576         ret = __dev_open(dev, extack);
1577         if (ret < 0)
1578                 return ret;
1579 
1580         rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING, GFP_KERNEL);
1581         call_netdevice_notifiers(NETDEV_UP, dev);
1582 
1583         return ret;
1584 }
1585 EXPORT_SYMBOL(dev_open);
1586 
1587 static void __dev_close_many(struct list_head *head)
1588 {
1589         struct net_device *dev;
1590 
1591         ASSERT_RTNL();
1592         might_sleep();
1593 
1594         list_for_each_entry(dev, head, close_list) {
1595                 /* Temporarily disable netpoll until the interface is down */
1596                 netpoll_poll_disable(dev);
1597 
1598                 call_netdevice_notifiers(NETDEV_GOING_DOWN, dev);
1599 
1600                 clear_bit(__LINK_STATE_START, &dev->state);
1601 
1602                 /* Synchronize to scheduled poll. We cannot touch poll list, it
1603                  * can be even on different cpu. So just clear netif_running().
1604                  *
1605                  * dev->stop() will invoke napi_disable() on all of it's
1606                  * napi_struct instances on this device.
1607                  */
1608                 smp_mb__after_atomic(); /* Commit netif_running(). */
1609         }
1610 
1611         dev_deactivate_many(head);
1612 
1613         list_for_each_entry(dev, head, close_list) {
1614                 const struct net_device_ops *ops = dev->netdev_ops;
1615 
1616                 /*
1617                  *      Call the device specific close. This cannot fail.
1618                  *      Only if device is UP
1619                  *
1620                  *      We allow it to be called even after a DETACH hot-plug
1621                  *      event.
1622                  */
1623                 if (ops->ndo_stop)
1624                         ops->ndo_stop(dev);
1625 
1626                 dev->flags &= ~IFF_UP;
1627                 netpoll_poll_enable(dev);
1628         }
1629 }
1630 
1631 static void __dev_close(struct net_device *dev)
1632 {
1633         LIST_HEAD(single);
1634 
1635         list_add(&dev->close_list, &single);
1636         __dev_close_many(&single);
1637         list_del(&single);
1638 }
1639 
1640 void dev_close_many(struct list_head *head, bool unlink)
1641 {
1642         struct net_device *dev, *tmp;
1643 
1644         /* Remove the devices that don't need to be closed */
1645         list_for_each_entry_safe(dev, tmp, head, close_list)
1646                 if (!(dev->flags & IFF_UP))
1647                         list_del_init(&dev->close_list);
1648 
1649         __dev_close_many(head);
1650 
1651         list_for_each_entry_safe(dev, tmp, head, close_list) {
1652                 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING, GFP_KERNEL);
1653                 call_netdevice_notifiers(NETDEV_DOWN, dev);
1654                 if (unlink)
1655                         list_del_init(&dev->close_list);
1656         }
1657 }
1658 EXPORT_SYMBOL(dev_close_many);
1659 
1660 /**
1661  *      dev_close - shutdown an interface.
1662  *      @dev: device to shutdown
1663  *
1664  *      This function moves an active device into down state. A
1665  *      %NETDEV_GOING_DOWN is sent to the netdev notifier chain. The device
1666  *      is then deactivated and finally a %NETDEV_DOWN is sent to the notifier
1667  *      chain.
1668  */
1669 void dev_close(struct net_device *dev)
1670 {
1671         if (dev->flags & IFF_UP) {
1672                 LIST_HEAD(single);
1673 
1674                 list_add(&dev->close_list, &single);
1675                 dev_close_many(&single, true);
1676                 list_del(&single);
1677         }
1678 }
1679 EXPORT_SYMBOL(dev_close);
1680 
1681 
1682 /**
1683  *      dev_disable_lro - disable Large Receive Offload on a device
1684  *      @dev: device
1685  *
1686  *      Disable Large Receive Offload (LRO) on a net device.  Must be
1687  *      called under RTNL.  This is needed if received packets may be
1688  *      forwarded to another interface.
1689  */
1690 void dev_disable_lro(struct net_device *dev)
1691 {
1692         struct net_device *lower_dev;
1693         struct list_head *iter;
1694 
1695         dev->wanted_features &= ~NETIF_F_LRO;
1696         netdev_update_features(dev);
1697 
1698         if (unlikely(dev->features & NETIF_F_LRO))
1699                 netdev_WARN(dev, "failed to disable LRO!\n");
1700 
1701         netdev_for_each_lower_dev(dev, lower_dev, iter)
1702                 dev_disable_lro(lower_dev);
1703 }
1704 EXPORT_SYMBOL(dev_disable_lro);
1705 
1706 /**
1707  *      dev_disable_gro_hw - disable HW Generic Receive Offload on a device
1708  *      @dev: device
1709  *
1710  *      Disable HW Generic Receive Offload (GRO_HW) on a net device.  Must be
1711  *      called under RTNL.  This is needed if Generic XDP is installed on
1712  *      the device.
1713  */
1714 static void dev_disable_gro_hw(struct net_device *dev)
1715 {
1716         dev->wanted_features &= ~NETIF_F_GRO_HW;
1717         netdev_update_features(dev);
1718 
1719         if (unlikely(dev->features & NETIF_F_GRO_HW))
1720                 netdev_WARN(dev, "failed to disable GRO_HW!\n");
1721 }
1722 
1723 const char *netdev_cmd_to_name(enum netdev_cmd cmd)
1724 {
1725 #define N(val)                                          \
1726         case NETDEV_##val:                              \
1727                 return "NETDEV_" __stringify(val);
1728         switch (cmd) {
1729         N(UP) N(DOWN) N(REBOOT) N(CHANGE) N(REGISTER) N(UNREGISTER)
1730         N(CHANGEMTU) N(CHANGEADDR) N(GOING_DOWN) N(CHANGENAME) N(FEAT_CHANGE)
1731         N(BONDING_FAILOVER) N(PRE_UP) N(PRE_TYPE_CHANGE) N(POST_TYPE_CHANGE)
1732         N(POST_INIT) N(RELEASE) N(NOTIFY_PEERS) N(JOIN) N(CHANGEUPPER)
1733         N(RESEND_IGMP) N(PRECHANGEMTU) N(CHANGEINFODATA) N(BONDING_INFO)
1734         N(PRECHANGEUPPER) N(CHANGELOWERSTATE) N(UDP_TUNNEL_PUSH_INFO)
1735         N(UDP_TUNNEL_DROP_INFO) N(CHANGE_TX_QUEUE_LEN)
1736         N(CVLAN_FILTER_PUSH_INFO) N(CVLAN_FILTER_DROP_INFO)
1737         N(SVLAN_FILTER_PUSH_INFO) N(SVLAN_FILTER_DROP_INFO)
1738         N(PRE_CHANGEADDR)
1739         }
1740 #undef N
1741         return "UNKNOWN_NETDEV_EVENT";
1742 }
1743 EXPORT_SYMBOL_GPL(netdev_cmd_to_name);
1744 
1745 static int call_netdevice_notifier(struct notifier_block *nb, unsigned long val,
1746                                    struct net_device *dev)
1747 {
1748         struct netdev_notifier_info info = {
1749                 .dev = dev,
1750         };
1751 
1752         return nb->notifier_call(nb, val, &info);
1753 }
1754 
1755 static int call_netdevice_register_notifiers(struct notifier_block *nb,
1756                                              struct net_device *dev)
1757 {
1758         int err;
1759 
1760         err = call_netdevice_notifier(nb, NETDEV_REGISTER, dev);
1761         err = notifier_to_errno(err);
1762         if (err)
1763                 return err;
1764 
1765         if (!(dev->flags & IFF_UP))
1766                 return 0;
1767 
1768         call_netdevice_notifier(nb, NETDEV_UP, dev);
1769         return 0;
1770 }
1771 
1772 static void call_netdevice_unregister_notifiers(struct notifier_block *nb,
1773                                                 struct net_device *dev)
1774 {
1775         if (dev->flags & IFF_UP) {
1776                 call_netdevice_notifier(nb, NETDEV_GOING_DOWN,
1777                                         dev);
1778                 call_netdevice_notifier(nb, NETDEV_DOWN, dev);
1779         }
1780         call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev);
1781 }
1782 
1783 static int call_netdevice_register_net_notifiers(struct notifier_block *nb,
1784                                                  struct net *net)
1785 {
1786         struct net_device *dev;
1787         int err;
1788 
1789         for_each_netdev(net, dev) {
1790                 err = call_netdevice_register_notifiers(nb, dev);
1791                 if (err)
1792                         goto rollback;
1793         }
1794         return 0;
1795 
1796 rollback:
1797         for_each_netdev_continue_reverse(net, dev)
1798                 call_netdevice_unregister_notifiers(nb, dev);
1799         return err;
1800 }
1801 
1802 static void call_netdevice_unregister_net_notifiers(struct notifier_block *nb,
1803                                                     struct net *net)
1804 {
1805         struct net_device *dev;
1806 
1807         for_each_netdev(net, dev)
1808                 call_netdevice_unregister_notifiers(nb, dev);
1809 }
1810 
1811 static int dev_boot_phase = 1;
1812 
1813 /**
1814  * register_netdevice_notifier - register a network notifier block
1815  * @nb: notifier
1816  *
1817  * Register a notifier to be called when network device events occur.
1818  * The notifier passed is linked into the kernel structures and must
1819  * not be reused until it has been unregistered. A negative errno code
1820  * is returned on a failure.
1821  *
1822  * When registered all registration and up events are replayed
1823  * to the new notifier to allow device to have a race free
1824  * view of the network device list.
1825  */
1826 
1827 int register_netdevice_notifier(struct notifier_block *nb)
1828 {
1829         struct net *net;
1830         int err;
1831 
1832         /* Close race with setup_net() and cleanup_net() */
1833         down_write(&pernet_ops_rwsem);
1834         rtnl_lock();
1835         err = raw_notifier_chain_register(&netdev_chain, nb);
1836         if (err)
1837                 goto unlock;
1838         if (dev_boot_phase)
1839                 goto unlock;
1840         for_each_net(net) {
1841                 err = call_netdevice_register_net_notifiers(nb, net);
1842                 if (err)
1843                         goto rollback;
1844         }
1845 
1846 unlock:
1847         rtnl_unlock();
1848         up_write(&pernet_ops_rwsem);
1849         return err;
1850 
1851 rollback:
1852         for_each_net_continue_reverse(net)
1853                 call_netdevice_unregister_net_notifiers(nb, net);
1854 
1855         raw_notifier_chain_unregister(&netdev_chain, nb);
1856         goto unlock;
1857 }
1858 EXPORT_SYMBOL(register_netdevice_notifier);
1859 
1860 /**
1861  * unregister_netdevice_notifier - unregister a network notifier block
1862  * @nb: notifier
1863  *
1864  * Unregister a notifier previously registered by
1865  * register_netdevice_notifier(). The notifier is unlinked into the
1866  * kernel structures and may then be reused. A negative errno code
1867  * is returned on a failure.
1868  *
1869  * After unregistering unregister and down device events are synthesized
1870  * for all devices on the device list to the removed notifier to remove
1871  * the need for special case cleanup code.
1872  */
1873 
1874 int unregister_netdevice_notifier(struct notifier_block *nb)
1875 {
1876         struct net *net;
1877         int err;
1878 
1879         /* Close race with setup_net() and cleanup_net() */
1880         down_write(&pernet_ops_rwsem);
1881         rtnl_lock();
1882         err = raw_notifier_chain_unregister(&netdev_chain, nb);
1883         if (err)
1884                 goto unlock;
1885 
1886         for_each_net(net)
1887                 call_netdevice_unregister_net_notifiers(nb, net);
1888 
1889 unlock:
1890         rtnl_unlock();
1891         up_write(&pernet_ops_rwsem);
1892         return err;
1893 }
1894 EXPORT_SYMBOL(unregister_netdevice_notifier);
1895 
1896 static int __register_netdevice_notifier_net(struct net *net,
1897                                              struct notifier_block *nb,
1898                                              bool ignore_call_fail)
1899 {
1900         int err;
1901 
1902         err = raw_notifier_chain_register(&net->netdev_chain, nb);
1903         if (err)
1904                 return err;
1905         if (dev_boot_phase)
1906                 return 0;
1907 
1908         err = call_netdevice_register_net_notifiers(nb, net);
1909         if (err && !ignore_call_fail)
1910                 goto chain_unregister;
1911 
1912         return 0;
1913 
1914 chain_unregister:
1915         raw_notifier_chain_unregister(&net->netdev_chain, nb);
1916         return err;
1917 }
1918 
1919 static int __unregister_netdevice_notifier_net(struct net *net,
1920                                                struct notifier_block *nb)
1921 {
1922         int err;
1923 
1924         err = raw_notifier_chain_unregister(&net->netdev_chain, nb);
1925         if (err)
1926                 return err;
1927 
1928         call_netdevice_unregister_net_notifiers(nb, net);
1929         return 0;
1930 }
1931 
1932 /**
1933  * register_netdevice_notifier_net - register a per-netns network notifier block
1934  * @net: network namespace
1935  * @nb: notifier
1936  *
1937  * Register a notifier to be called when network device events occur.
1938  * The notifier passed is linked into the kernel structures and must
1939  * not be reused until it has been unregistered. A negative errno code
1940  * is returned on a failure.
1941  *
1942  * When registered all registration and up events are replayed
1943  * to the new notifier to allow device to have a race free
1944  * view of the network device list.
1945  */
1946 
1947 int register_netdevice_notifier_net(struct net *net, struct notifier_block *nb)
1948 {
1949         int err;
1950 
1951         rtnl_lock();
1952         err = __register_netdevice_notifier_net(net, nb, false);
1953         rtnl_unlock();
1954         return err;
1955 }
1956 EXPORT_SYMBOL(register_netdevice_notifier_net);
1957 
1958 /**
1959  * unregister_netdevice_notifier_net - unregister a per-netns
1960  *                                     network notifier block
1961  * @net: network namespace
1962  * @nb: notifier
1963  *
1964  * Unregister a notifier previously registered by
1965  * register_netdevice_notifier(). The notifier is unlinked into the
1966  * kernel structures and may then be reused. A negative errno code
1967  * is returned on a failure.
1968  *
1969  * After unregistering unregister and down device events are synthesized
1970  * for all devices on the device list to the removed notifier to remove
1971  * the need for special case cleanup code.
1972  */
1973 
1974 int unregister_netdevice_notifier_net(struct net *net,
1975                                       struct notifier_block *nb)
1976 {
1977         int err;
1978 
1979         rtnl_lock();
1980         err = __unregister_netdevice_notifier_net(net, nb);
1981         rtnl_unlock();
1982         return err;
1983 }
1984 EXPORT_SYMBOL(unregister_netdevice_notifier_net);
1985 
1986 int register_netdevice_notifier_dev_net(struct net_device *dev,
1987                                         struct notifier_block *nb,
1988                                         struct netdev_net_notifier *nn)
1989 {
1990         int err;
1991 
1992         rtnl_lock();
1993         err = __register_netdevice_notifier_net(dev_net(dev), nb, false);
1994         if (!err) {
1995                 nn->nb = nb;
1996                 list_add(&nn->list, &dev->net_notifier_list);
1997         }
1998         rtnl_unlock();
1999         return err;
2000 }
2001 EXPORT_SYMBOL(register_netdevice_notifier_dev_net);
2002 
2003 int unregister_netdevice_notifier_dev_net(struct net_device *dev,
2004                                           struct notifier_block *nb,
2005                                           struct netdev_net_notifier *nn)
2006 {
2007         int err;
2008 
2009         rtnl_lock();
2010         list_del(&nn->list);
2011         err = __unregister_netdevice_notifier_net(dev_net(dev), nb);
2012         rtnl_unlock();
2013         return err;
2014 }
2015 EXPORT_SYMBOL(unregister_netdevice_notifier_dev_net);
2016 
2017 static void move_netdevice_notifiers_dev_net(struct net_device *dev,
2018                                              struct net *net)
2019 {
2020         struct netdev_net_notifier *nn;
2021 
2022         list_for_each_entry(nn, &dev->net_notifier_list, list) {
2023                 __unregister_netdevice_notifier_net(dev_net(dev), nn->nb);
2024                 __register_netdevice_notifier_net(net, nn->nb, true);
2025         }
2026 }
2027 
2028 /**
2029  *      call_netdevice_notifiers_info - call all network notifier blocks
2030  *      @val: value passed unmodified to notifier function
2031  *      @info: notifier information data
2032  *
2033  *      Call all network notifier blocks.  Parameters and return value
2034  *      are as for raw_notifier_call_chain().
2035  */
2036 
2037 static int call_netdevice_notifiers_info(unsigned long val,
2038                                          struct netdev_notifier_info *info)
2039 {
2040         struct net *net = dev_net(info->dev);
2041         int ret;
2042 
2043         ASSERT_RTNL();
2044 
2045         /* Run per-netns notifier block chain first, then run the global one.
2046          * Hopefully, one day, the global one is going to be removed after
2047          * all notifier block registrators get converted to be per-netns.
2048          */
2049         ret = raw_notifier_call_chain(&net->netdev_chain, val, info);
2050         if (ret & NOTIFY_STOP_MASK)
2051                 return ret;
2052         return raw_notifier_call_chain(&netdev_chain, val, info);
2053 }
2054 
2055 static int call_netdevice_notifiers_extack(unsigned long val,
2056                                            struct net_device *dev,
2057                                            struct netlink_ext_ack *extack)
2058 {
2059         struct netdev_notifier_info info = {
2060                 .dev = dev,
2061                 .extack = extack,
2062         };
2063 
2064         return call_netdevice_notifiers_info(val, &info);
2065 }
2066 
2067 /**
2068  *      call_netdevice_notifiers - call all network notifier blocks
2069  *      @val: value passed unmodified to notifier function
2070  *      @dev: net_device pointer passed unmodified to notifier function
2071  *
2072  *      Call all network notifier blocks.  Parameters and return value
2073  *      are as for raw_notifier_call_chain().
2074  */
2075 
2076 int call_netdevice_notifiers(unsigned long val, struct net_device *dev)
2077 {
2078         return call_netdevice_notifiers_extack(val, dev, NULL);
2079 }
2080 EXPORT_SYMBOL(call_netdevice_notifiers);
2081 
2082 /**
2083  *      call_netdevice_notifiers_mtu - call all network notifier blocks
2084  *      @val: value passed unmodified to notifier function
2085  *      @dev: net_device pointer passed unmodified to notifier function
2086  *      @arg: additional u32 argument passed to the notifier function
2087  *
2088  *      Call all network notifier blocks.  Parameters and return value
2089  *      are as for raw_notifier_call_chain().
2090  */
2091 static int call_netdevice_notifiers_mtu(unsigned long val,
2092                                         struct net_device *dev, u32 arg)
2093 {
2094         struct netdev_notifier_info_ext info = {
2095                 .info.dev = dev,
2096                 .ext.mtu = arg,
2097         };
2098 
2099         BUILD_BUG_ON(offsetof(struct netdev_notifier_info_ext, info) != 0);
2100 
2101         return call_netdevice_notifiers_info(val, &info.info);
2102 }
2103 
2104 #ifdef CONFIG_NET_INGRESS
2105 static DEFINE_STATIC_KEY_FALSE(ingress_needed_key);
2106 
2107 void net_inc_ingress_queue(void)
2108 {
2109         static_branch_inc(&ingress_needed_key);
2110 }
2111 EXPORT_SYMBOL_GPL(net_inc_ingress_queue);
2112 
2113 void net_dec_ingress_queue(void)
2114 {
2115         static_branch_dec(&ingress_needed_key);
2116 }
2117 EXPORT_SYMBOL_GPL(net_dec_ingress_queue);
2118 #endif
2119 
2120 #ifdef CONFIG_NET_EGRESS
2121 static DEFINE_STATIC_KEY_FALSE(egress_needed_key);
2122 
2123 void net_inc_egress_queue(void)
2124 {
2125         static_branch_inc(&egress_needed_key);
2126 }
2127 EXPORT_SYMBOL_GPL(net_inc_egress_queue);
2128 
2129 void net_dec_egress_queue(void)
2130 {
2131         static_branch_dec(&egress_needed_key);
2132 }
2133 EXPORT_SYMBOL_GPL(net_dec_egress_queue);
2134 #endif
2135 
2136 static DEFINE_STATIC_KEY_FALSE(netstamp_needed_key);
2137 #ifdef CONFIG_JUMP_LABEL
2138 static atomic_t netstamp_needed_deferred;
2139 static atomic_t netstamp_wanted;
2140 static void netstamp_clear(struct work_struct *work)
2141 {
2142         int deferred = atomic_xchg(&netstamp_needed_deferred, 0);
2143         int wanted;
2144 
2145         wanted = atomic_add_return(deferred, &netstamp_wanted);
2146         if (wanted > 0)
2147                 static_branch_enable(&netstamp_needed_key);
2148         else
2149                 static_branch_disable(&netstamp_needed_key);
2150 }
2151 static DECLARE_WORK(netstamp_work, netstamp_clear);
2152 #endif
2153 
2154 void net_enable_timestamp(void)
2155 {
2156 #ifdef CONFIG_JUMP_LABEL
2157         int wanted;
2158 
2159         while (1) {
2160                 wanted = atomic_read(&netstamp_wanted);
2161                 if (wanted <= 0)
2162                         break;
2163                 if (atomic_cmpxchg(&netstamp_wanted, wanted, wanted + 1) == wanted)
2164                         return;
2165         }
2166         atomic_inc(&netstamp_needed_deferred);
2167         schedule_work(&netstamp_work);
2168 #else
2169         static_branch_inc(&netstamp_needed_key);
2170 #endif
2171 }
2172 EXPORT_SYMBOL(net_enable_timestamp);
2173 
2174 void net_disable_timestamp(void)
2175 {
2176 #ifdef CONFIG_JUMP_LABEL
2177         int wanted;
2178 
2179         while (1) {
2180                 wanted = atomic_read(&netstamp_wanted);
2181                 if (wanted <= 1)
2182                         break;
2183                 if (atomic_cmpxchg(&netstamp_wanted, wanted, wanted - 1) == wanted)
2184                         return;
2185         }
2186         atomic_dec(&netstamp_needed_deferred);
2187         schedule_work(&netstamp_work);
2188 #else
2189         static_branch_dec(&netstamp_needed_key);
2190 #endif
2191 }
2192 EXPORT_SYMBOL(net_disable_timestamp);
2193 
2194 static inline void net_timestamp_set(struct sk_buff *skb)
2195 {
2196         skb->tstamp = 0;
2197         if (static_branch_unlikely(&netstamp_needed_key))
2198                 __net_timestamp(skb);
2199 }
2200 
2201 #define net_timestamp_check(COND, SKB)                          \
2202         if (static_branch_unlikely(&netstamp_needed_key)) {     \
2203                 if ((COND) && !(SKB)->tstamp)                   \
2204                         __net_timestamp(SKB);                   \
2205         }                                                       \
2206 
2207 bool is_skb_forwardable(const struct net_device *dev, const struct sk_buff *skb)
2208 {
2209         unsigned int len;
2210 
2211         if (!(dev->flags & IFF_UP))
2212                 return false;
2213 
2214         len = dev->mtu + dev->hard_header_len + VLAN_HLEN;
2215         if (skb->len <= len)
2216                 return true;
2217 
2218         /* if TSO is enabled, we don't care about the length as the packet
2219          * could be forwarded without being segmented before
2220          */
2221         if (skb_is_gso(skb))
2222                 return true;
2223 
2224         return false;
2225 }
2226 EXPORT_SYMBOL_GPL(is_skb_forwardable);
2227 
2228 int __dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
2229 {
2230         int ret = ____dev_forward_skb(dev, skb);
2231 
2232         if (likely(!ret)) {
2233                 skb->protocol = eth_type_trans(skb, dev);
2234                 skb_postpull_rcsum(skb, eth_hdr(skb), ETH_HLEN);
2235         }
2236 
2237         return ret;
2238 }
2239 EXPORT_SYMBOL_GPL(__dev_forward_skb);
2240 
2241 /**
2242  * dev_forward_skb - loopback an skb to another netif
2243  *
2244  * @dev: destination network device
2245  * @skb: buffer to forward
2246  *
2247  * return values:
2248  *      NET_RX_SUCCESS  (no congestion)
2249  *      NET_RX_DROP     (packet was dropped, but freed)
2250  *
2251  * dev_forward_skb can be used for injecting an skb from the
2252  * start_xmit function of one device into the receive queue
2253  * of another device.
2254  *
2255  * The receiving device may be in another namespace, so
2256  * we have to clear all information in the skb that could
2257  * impact namespace isolation.
2258  */
2259 int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
2260 {
2261         return __dev_forward_skb(dev, skb) ?: netif_rx_internal(skb);
2262 }
2263 EXPORT_SYMBOL_GPL(dev_forward_skb);
2264 
2265 static inline int deliver_skb(struct sk_buff *skb,
2266                               struct packet_type *pt_prev,
2267                               struct net_device *orig_dev)
2268 {
2269         if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
2270                 return -ENOMEM;
2271         refcount_inc(&skb->users);
2272         return pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
2273 }
2274 
2275 static inline void deliver_ptype_list_skb(struct sk_buff *skb,
2276                                           struct packet_type **pt,
2277                                           struct net_device *orig_dev,
2278                                           __be16 type,
2279                                           struct list_head *ptype_list)
2280 {
2281         struct packet_type *ptype, *pt_prev = *pt;
2282 
2283         list_for_each_entry_rcu(ptype, ptype_list, list) {
2284                 if (ptype->type != type)
2285                         continue;
2286                 if (pt_prev)
2287                         deliver_skb(skb, pt_prev, orig_dev);
2288                 pt_prev = ptype;
2289         }
2290         *pt = pt_prev;
2291 }
2292 
2293 static inline bool skb_loop_sk(struct packet_type *ptype, struct sk_buff *skb)
2294 {
2295         if (!ptype->af_packet_priv || !skb->sk)
2296                 return false;
2297 
2298         if (ptype->id_match)
2299                 return ptype->id_match(ptype, skb->sk);
2300         else if ((struct sock *)ptype->af_packet_priv == skb->sk)
2301                 return true;
2302 
2303         return false;
2304 }
2305 
2306 /**
2307  * dev_nit_active - return true if any network interface taps are in use
2308  *
2309  * @dev: network device to check for the presence of taps
2310  */
2311 bool dev_nit_active(struct net_device *dev)
2312 {
2313         return !list_empty(&ptype_all) || !list_empty(&dev->ptype_all);
2314 }
2315 EXPORT_SYMBOL_GPL(dev_nit_active);
2316 
2317 /*
2318  *      Support routine. Sends outgoing frames to any network
2319  *      taps currently in use.
2320  */
2321 
2322 void dev_queue_xmit_nit(struct sk_buff *skb, struct net_device *dev)
2323 {
2324         struct packet_type *ptype;
2325         struct sk_buff *skb2 = NULL;
2326         struct packet_type *pt_prev = NULL;
2327         struct list_head *ptype_list = &ptype_all;
2328 
2329         rcu_read_lock();
2330 again:
2331         list_for_each_entry_rcu(ptype, ptype_list, list) {
2332                 if (ptype->ignore_outgoing)
2333                         continue;
2334 
2335                 /* Never send packets back to the socket
2336                  * they originated from - MvS (miquels@drinkel.ow.org)
2337                  */
2338                 if (skb_loop_sk(ptype, skb))
2339                         continue;
2340 
2341                 if (pt_prev) {
2342                         deliver_skb(skb2, pt_prev, skb->dev);
2343                         pt_prev = ptype;
2344                         continue;
2345                 }
2346 
2347                 /* need to clone skb, done only once */
2348                 skb2 = skb_clone(skb, GFP_ATOMIC);
2349                 if (!skb2)
2350                         goto out_unlock;
2351 
2352                 net_timestamp_set(skb2);
2353 
2354                 /* skb->nh should be correctly
2355                  * set by sender, so that the second statement is
2356                  * just protection against buggy protocols.
2357                  */
2358                 skb_reset_mac_header(skb2);
2359 
2360                 if (skb_network_header(skb2) < skb2->data ||
2361                     skb_network_header(skb2) > skb_tail_pointer(skb2)) {
2362                         net_crit_ratelimited("protocol %04x is buggy, dev %s\n",
2363                                              ntohs(skb2->protocol),
2364                                              dev->name);
2365                         skb_reset_network_header(skb2);
2366                 }
2367 
2368                 skb2->transport_header = skb2->network_header;
2369                 skb2->pkt_type = PACKET_OUTGOING;
2370                 pt_prev = ptype;
2371         }
2372 
2373         if (ptype_list == &ptype_all) {
2374                 ptype_list = &dev->ptype_all;
2375                 goto again;
2376         }
2377 out_unlock:
2378         if (pt_prev) {
2379                 if (!skb_orphan_frags_rx(skb2, GFP_ATOMIC))
2380                         pt_prev->func(skb2, skb->dev, pt_prev, skb->dev);
2381                 else
2382                         kfree_skb(skb2);
2383         }
2384         rcu_read_unlock();
2385 }
2386 EXPORT_SYMBOL_GPL(dev_queue_xmit_nit);
2387 
2388 /**
2389  * netif_setup_tc - Handle tc mappings on real_num_tx_queues change
2390  * @dev: Network device
2391  * @txq: number of queues available
2392  *
2393  * If real_num_tx_queues is changed the tc mappings may no longer be
2394  * valid. To resolve this verify the tc mapping remains valid and if
2395  * not NULL the mapping. With no priorities mapping to this
2396  * offset/count pair it will no longer be used. In the worst case TC0
2397  * is invalid nothing can be done so disable priority mappings. If is
2398  * expected that drivers will fix this mapping if they can before
2399  * calling netif_set_real_num_tx_queues.
2400  */
2401 static void netif_setup_tc(struct net_device *dev, unsigned int txq)
2402 {
2403         int i;
2404         struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2405 
2406         /* If TC0 is invalidated disable TC mapping */
2407         if (tc->offset + tc->count > txq) {
2408                 pr_warn("Number of in use tx queues changed invalidating tc mappings. Priority traffic classification disabled!\n");
2409                 dev->num_tc = 0;
2410                 return;
2411         }
2412 
2413         /* Invalidated prio to tc mappings set to TC0 */
2414         for (i = 1; i < TC_BITMASK + 1; i++) {
2415                 int q = netdev_get_prio_tc_map(dev, i);
2416 
2417                 tc = &dev->tc_to_txq[q];
2418                 if (tc->offset + tc->count > txq) {
2419                         pr_warn("Number of in use tx queues changed. Priority %i to tc mapping %i is no longer valid. Setting map to 0\n",
2420                                 i, q);
2421                         netdev_set_prio_tc_map(dev, i, 0);
2422                 }
2423         }
2424 }
2425 
2426 int netdev_txq_to_tc(struct net_device *dev, unsigned int txq)
2427 {
2428         if (dev->num_tc) {
2429                 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2430                 int i;
2431 
2432                 /* walk through the TCs and see if it falls into any of them */
2433                 for (i = 0; i < TC_MAX_QUEUE; i++, tc++) {
2434                         if ((txq - tc->offset) < tc->count)
2435                                 return i;
2436                 }
2437 
2438                 /* didn't find it, just return -1 to indicate no match */
2439                 return -1;
2440         }
2441 
2442         return 0;
2443 }
2444 EXPORT_SYMBOL(netdev_txq_to_tc);
2445 
2446 #ifdef CONFIG_XPS
2447 struct static_key xps_needed __read_mostly;
2448 EXPORT_SYMBOL(xps_needed);
2449 struct static_key xps_rxqs_needed __read_mostly;
2450 EXPORT_SYMBOL(xps_rxqs_needed);
2451 static DEFINE_MUTEX(xps_map_mutex);
2452 #define xmap_dereference(P)             \
2453         rcu_dereference_protected((P), lockdep_is_held(&xps_map_mutex))
2454 
2455 static bool remove_xps_queue(struct xps_dev_maps *dev_maps,
2456                              int tci, u16 index)
2457 {
2458         struct xps_map *map = NULL;
2459         int pos;
2460 
2461         if (dev_maps)
2462                 map = xmap_dereference(dev_maps->attr_map[tci]);
2463         if (!map)
2464                 return false;
2465 
2466         for (pos = map->len; pos--;) {
2467                 if (map->queues[pos] != index)
2468                         continue;
2469 
2470                 if (map->len > 1) {
2471                         map->queues[pos] = map->queues[--map->len];
2472                         break;
2473                 }
2474 
2475                 RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
2476                 kfree_rcu(map, rcu);
2477                 return false;
2478         }
2479 
2480         return true;
2481 }
2482 
2483 static bool remove_xps_queue_cpu(struct net_device *dev,
2484                                  struct xps_dev_maps *dev_maps,
2485                                  int cpu, u16 offset, u16 count)
2486 {
2487         int num_tc = dev->num_tc ? : 1;
2488         bool active = false;
2489         int tci;
2490 
2491         for (tci = cpu * num_tc; num_tc--; tci++) {
2492                 int i, j;
2493 
2494                 for (i = count, j = offset; i--; j++) {
2495                         if (!remove_xps_queue(dev_maps, tci, j))
2496                                 break;
2497                 }
2498 
2499                 active |= i < 0;
2500         }
2501 
2502         return active;
2503 }
2504 
2505 static void reset_xps_maps(struct net_device *dev,
2506                            struct xps_dev_maps *dev_maps,
2507                            bool is_rxqs_map)
2508 {
2509         if (is_rxqs_map) {
2510                 static_key_slow_dec_cpuslocked(&xps_rxqs_needed);
2511                 RCU_INIT_POINTER(dev->xps_rxqs_map, NULL);
2512         } else {
2513                 RCU_INIT_POINTER(dev->xps_cpus_map, NULL);
2514         }
2515         static_key_slow_dec_cpuslocked(&xps_needed);
2516         kfree_rcu(dev_maps, rcu);
2517 }
2518 
2519 static void clean_xps_maps(struct net_device *dev, const unsigned long *mask,
2520                            struct xps_dev_maps *dev_maps, unsigned int nr_ids,
2521                            u16 offset, u16 count, bool is_rxqs_map)
2522 {
2523         bool active = false;
2524         int i, j;
2525 
2526         for (j = -1; j = netif_attrmask_next(j, mask, nr_ids),
2527              j < nr_ids;)
2528                 active |= remove_xps_queue_cpu(dev, dev_maps, j, offset,
2529                                                count);
2530         if (!active)
2531                 reset_xps_maps(dev, dev_maps, is_rxqs_map);
2532 
2533         if (!is_rxqs_map) {
2534                 for (i = offset + (count - 1); count--; i--) {
2535                         netdev_queue_numa_node_write(
2536                                 netdev_get_tx_queue(dev, i),
2537                                 NUMA_NO_NODE);
2538                 }
2539         }
2540 }
2541 
2542 static void netif_reset_xps_queues(struct net_device *dev, u16 offset,
2543                                    u16 count)
2544 {
2545         const unsigned long *possible_mask = NULL;
2546         struct xps_dev_maps *dev_maps;
2547         unsigned int nr_ids;
2548 
2549         if (!static_key_false(&xps_needed))
2550                 return;
2551 
2552         cpus_read_lock();
2553         mutex_lock(&xps_map_mutex);
2554 
2555         if (static_key_false(&xps_rxqs_needed)) {
2556                 dev_maps = xmap_dereference(dev->xps_rxqs_map);
2557                 if (dev_maps) {
2558                         nr_ids = dev->num_rx_queues;
2559                         clean_xps_maps(dev, possible_mask, dev_maps, nr_ids,
2560                                        offset, count, true);
2561                 }
2562         }
2563 
2564         dev_maps = xmap_dereference(dev->xps_cpus_map);
2565         if (!dev_maps)
2566                 goto out_no_maps;
2567 
2568         if (num_possible_cpus() > 1)
2569                 possible_mask = cpumask_bits(cpu_possible_mask);
2570         nr_ids = nr_cpu_ids;
2571         clean_xps_maps(dev, possible_mask, dev_maps, nr_ids, offset, count,
2572                        false);
2573 
2574 out_no_maps:
2575         mutex_unlock(&xps_map_mutex);
2576         cpus_read_unlock();
2577 }
2578 
2579 static void netif_reset_xps_queues_gt(struct net_device *dev, u16 index)
2580 {
2581         netif_reset_xps_queues(dev, index, dev->num_tx_queues - index);
2582 }
2583 
2584 static struct xps_map *expand_xps_map(struct xps_map *map, int attr_index,
2585                                       u16 index, bool is_rxqs_map)
2586 {
2587         struct xps_map *new_map;
2588         int alloc_len = XPS_MIN_MAP_ALLOC;
2589         int i, pos;
2590 
2591         for (pos = 0; map && pos < map->len; pos++) {
2592                 if (map->queues[pos] != index)
2593                         continue;
2594                 return map;
2595         }
2596 
2597         /* Need to add tx-queue to this CPU's/rx-queue's existing map */
2598         if (map) {
2599                 if (pos < map->alloc_len)
2600                         return map;
2601 
2602                 alloc_len = map->alloc_len * 2;
2603         }
2604 
2605         /* Need to allocate new map to store tx-queue on this CPU's/rx-queue's
2606          *  map
2607          */
2608         if (is_rxqs_map)
2609                 new_map = kzalloc(XPS_MAP_SIZE(alloc_len), GFP_KERNEL);
2610         else
2611                 new_map = kzalloc_node(XPS_MAP_SIZE(alloc_len), GFP_KERNEL,
2612                                        cpu_to_node(attr_index));
2613         if (!new_map)
2614                 return NULL;
2615 
2616         for (i = 0; i < pos; i++)
2617                 new_map->queues[i] = map->queues[i];
2618         new_map->alloc_len = alloc_len;
2619         new_map->len = pos;
2620 
2621         return new_map;
2622 }
2623 
2624 /* Must be called under cpus_read_lock */
2625 int __netif_set_xps_queue(struct net_device *dev, const unsigned long *mask,
2626                           u16 index, bool is_rxqs_map)
2627 {
2628         const unsigned long *online_mask = NULL, *possible_mask = NULL;
2629         struct xps_dev_maps *dev_maps, *new_dev_maps = NULL;
2630         int i, j, tci, numa_node_id = -2;
2631         int maps_sz, num_tc = 1, tc = 0;
2632         struct xps_map *map, *new_map;
2633         bool active = false;
2634         unsigned int nr_ids;
2635 
2636         if (dev->num_tc) {
2637                 /* Do not allow XPS on subordinate device directly */
2638                 num_tc = dev->num_tc;
2639                 if (num_tc < 0)
2640                         return -EINVAL;
2641 
2642                 /* If queue belongs to subordinate dev use its map */
2643                 dev = netdev_get_tx_queue(dev, index)->sb_dev ? : dev;
2644 
2645                 tc = netdev_txq_to_tc(dev, index);
2646                 if (tc < 0)
2647                         return -EINVAL;
2648         }
2649 
2650         mutex_lock(&xps_map_mutex);
2651         if (is_rxqs_map) {
2652                 maps_sz = XPS_RXQ_DEV_MAPS_SIZE(num_tc, dev->num_rx_queues);
2653                 dev_maps = xmap_dereference(dev->xps_rxqs_map);
2654                 nr_ids = dev->num_rx_queues;
2655         } else {
2656                 maps_sz = XPS_CPU_DEV_MAPS_SIZE(num_tc);
2657                 if (num_possible_cpus() > 1) {
2658                         online_mask = cpumask_bits(cpu_online_mask);
2659                         possible_mask = cpumask_bits(cpu_possible_mask);
2660                 }
2661                 dev_maps = xmap_dereference(dev->xps_cpus_map);
2662                 nr_ids = nr_cpu_ids;
2663         }
2664 
2665         if (maps_sz < L1_CACHE_BYTES)
2666                 maps_sz = L1_CACHE_BYTES;
2667 
2668         /* allocate memory for queue storage */
2669         for (j = -1; j = netif_attrmask_next_and(j, online_mask, mask, nr_ids),
2670              j < nr_ids;) {
2671                 if (!new_dev_maps)
2672                         new_dev_maps = kzalloc(maps_sz, GFP_KERNEL);
2673                 if (!new_dev_maps) {
2674                         mutex_unlock(&xps_map_mutex);
2675                         return -ENOMEM;
2676                 }
2677 
2678                 tci = j * num_tc + tc;
2679                 map = dev_maps ? xmap_dereference(dev_maps->attr_map[tci]) :
2680                                  NULL;
2681 
2682                 map = expand_xps_map(map, j, index, is_rxqs_map);
2683                 if (!map)
2684                         goto error;
2685 
2686                 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2687         }
2688 
2689         if (!new_dev_maps)
2690                 goto out_no_new_maps;
2691 
2692         if (!dev_maps) {
2693                 /* Increment static keys at most once per type */
2694                 static_key_slow_inc_cpuslocked(&xps_needed);
2695                 if (is_rxqs_map)
2696                         static_key_slow_inc_cpuslocked(&xps_rxqs_needed);
2697         }
2698 
2699         for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2700              j < nr_ids;) {
2701                 /* copy maps belonging to foreign traffic classes */
2702                 for (i = tc, tci = j * num_tc; dev_maps && i--; tci++) {
2703                         /* fill in the new device map from the old device map */
2704                         map = xmap_dereference(dev_maps->attr_map[tci]);
2705                         RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2706                 }
2707 
2708                 /* We need to explicitly update tci as prevous loop
2709                  * could break out early if dev_maps is NULL.
2710                  */
2711                 tci = j * num_tc + tc;
2712 
2713                 if (netif_attr_test_mask(j, mask, nr_ids) &&
2714                     netif_attr_test_online(j, online_mask, nr_ids)) {
2715                         /* add tx-queue to CPU/rx-queue maps */
2716                         int pos = 0;
2717 
2718                         map = xmap_dereference(new_dev_maps->attr_map[tci]);
2719                         while ((pos < map->len) && (map->queues[pos] != index))
2720                                 pos++;
2721 
2722                         if (pos == map->len)
2723                                 map->queues[map->len++] = index;
2724 #ifdef CONFIG_NUMA
2725                         if (!is_rxqs_map) {
2726                                 if (numa_node_id == -2)
2727                                         numa_node_id = cpu_to_node(j);
2728                                 else if (numa_node_id != cpu_to_node(j))
2729                                         numa_node_id = -1;
2730                         }
2731 #endif
2732                 } else if (dev_maps) {
2733                         /* fill in the new device map from the old device map */
2734                         map = xmap_dereference(dev_maps->attr_map[tci]);
2735                         RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2736                 }
2737 
2738                 /* copy maps belonging to foreign traffic classes */
2739                 for (i = num_tc - tc, tci++; dev_maps && --i; tci++) {
2740                         /* fill in the new device map from the old device map */
2741                         map = xmap_dereference(dev_maps->attr_map[tci]);
2742                         RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2743                 }
2744         }
2745 
2746         if (is_rxqs_map)
2747                 rcu_assign_pointer(dev->xps_rxqs_map, new_dev_maps);
2748         else
2749                 rcu_assign_pointer(dev->xps_cpus_map, new_dev_maps);
2750 
2751         /* Cleanup old maps */
2752         if (!dev_maps)
2753                 goto out_no_old_maps;
2754 
2755         for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2756              j < nr_ids;) {
2757                 for (i = num_tc, tci = j * num_tc; i--; tci++) {
2758                         new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2759                         map = xmap_dereference(dev_maps->attr_map[tci]);
2760                         if (map && map != new_map)
2761                                 kfree_rcu(map, rcu);
2762                 }
2763         }
2764 
2765         kfree_rcu(dev_maps, rcu);
2766 
2767 out_no_old_maps:
2768         dev_maps = new_dev_maps;
2769         active = true;
2770 
2771 out_no_new_maps:
2772         if (!is_rxqs_map) {
2773                 /* update Tx queue numa node */
2774                 netdev_queue_numa_node_write(netdev_get_tx_queue(dev, index),
2775                                              (numa_node_id >= 0) ?
2776                                              numa_node_id : NUMA_NO_NODE);
2777         }
2778 
2779         if (!dev_maps)
2780                 goto out_no_maps;
2781 
2782         /* removes tx-queue from unused CPUs/rx-queues */
2783         for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2784              j < nr_ids;) {
2785                 for (i = tc, tci = j * num_tc; i--; tci++)
2786                         active |= remove_xps_queue(dev_maps, tci, index);
2787                 if (!netif_attr_test_mask(j, mask, nr_ids) ||
2788                     !netif_attr_test_online(j, online_mask, nr_ids))
2789                         active |= remove_xps_queue(dev_maps, tci, index);
2790                 for (i = num_tc - tc, tci++; --i; tci++)
2791                         active |= remove_xps_queue(dev_maps, tci, index);
2792         }
2793 
2794         /* free map if not active */
2795         if (!active)
2796                 reset_xps_maps(dev, dev_maps, is_rxqs_map);
2797 
2798 out_no_maps:
2799         mutex_unlock(&xps_map_mutex);
2800 
2801         return 0;
2802 error:
2803         /* remove any maps that we added */
2804         for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2805              j < nr_ids;) {
2806                 for (i = num_tc, tci = j * num_tc; i--; tci++) {
2807                         new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2808                         map = dev_maps ?
2809                               xmap_dereference(dev_maps->attr_map[tci]) :
2810                               NULL;
2811                         if (new_map && new_map != map)
2812                                 kfree(new_map);
2813                 }
2814         }
2815 
2816         mutex_unlock(&xps_map_mutex);
2817 
2818         kfree(new_dev_maps);
2819         return -ENOMEM;
2820 }
2821 EXPORT_SYMBOL_GPL(__netif_set_xps_queue);
2822 
2823 int netif_set_xps_queue(struct net_device *dev, const struct cpumask *mask,
2824                         u16 index)
2825 {
2826         int ret;
2827 
2828         cpus_read_lock();
2829         ret =  __netif_set_xps_queue(dev, cpumask_bits(mask), index, false);
2830         cpus_read_unlock();
2831 
2832         return ret;
2833 }
2834 EXPORT_SYMBOL(netif_set_xps_queue);
2835 
2836 #endif
2837 static void netdev_unbind_all_sb_channels(struct net_device *dev)
2838 {
2839         struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2840 
2841         /* Unbind any subordinate channels */
2842         while (txq-- != &dev->_tx[0]) {
2843                 if (txq->sb_dev)
2844                         netdev_unbind_sb_channel(dev, txq->sb_dev);
2845         }
2846 }
2847 
2848 void netdev_reset_tc(struct net_device *dev)
2849 {
2850 #ifdef CONFIG_XPS
2851         netif_reset_xps_queues_gt(dev, 0);
2852 #endif
2853         netdev_unbind_all_sb_channels(dev);
2854 
2855         /* Reset TC configuration of device */
2856         dev->num_tc = 0;
2857         memset(dev->tc_to_txq, 0, sizeof(dev->tc_to_txq));
2858         memset(dev->prio_tc_map, 0, sizeof(dev->prio_tc_map));
2859 }
2860 EXPORT_SYMBOL(netdev_reset_tc);
2861 
2862 int netdev_set_tc_queue(struct net_device *dev, u8 tc, u16 count, u16 offset)
2863 {
2864         if (tc >= dev->num_tc)
2865                 return -EINVAL;
2866 
2867 #ifdef CONFIG_XPS
2868         netif_reset_xps_queues(dev, offset, count);
2869 #endif
2870         dev->tc_to_txq[tc].count = count;
2871         dev->tc_to_txq[tc].offset = offset;
2872         return 0;
2873 }
2874 EXPORT_SYMBOL(netdev_set_tc_queue);
2875 
2876 int netdev_set_num_tc(struct net_device *dev, u8 num_tc)
2877 {
2878         if (num_tc > TC_MAX_QUEUE)
2879                 return -EINVAL;
2880 
2881 #ifdef CONFIG_XPS
2882         netif_reset_xps_queues_gt(dev, 0);
2883 #endif
2884         netdev_unbind_all_sb_channels(dev);
2885 
2886         dev->num_tc = num_tc;
2887         return 0;
2888 }
2889 EXPORT_SYMBOL(netdev_set_num_tc);
2890 
2891 void netdev_unbind_sb_channel(struct net_device *dev,
2892                               struct net_device *sb_dev)
2893 {
2894         struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2895 
2896 #ifdef CONFIG_XPS
2897         netif_reset_xps_queues_gt(sb_dev, 0);
2898 #endif
2899         memset(sb_dev->tc_to_txq, 0, sizeof(sb_dev->tc_to_txq));
2900         memset(sb_dev->prio_tc_map, 0, sizeof(sb_dev->prio_tc_map));
2901 
2902         while (txq-- != &dev->_tx[0]) {
2903                 if (txq->sb_dev == sb_dev)
2904                         txq->sb_dev = NULL;
2905         }
2906 }
2907 EXPORT_SYMBOL(netdev_unbind_sb_channel);
2908 
2909 int netdev_bind_sb_channel_queue(struct net_device *dev,
2910                                  struct net_device *sb_dev,
2911                                  u8 tc, u16 count, u16 offset)
2912 {
2913         /* Make certain the sb_dev and dev are already configured */
2914         if (sb_dev->num_tc >= 0 || tc >= dev->num_tc)
2915                 return -EINVAL;
2916 
2917         /* We cannot hand out queues we don't have */
2918         if ((offset + count) > dev->real_num_tx_queues)
2919                 return -EINVAL;
2920 
2921         /* Record the mapping */
2922         sb_dev->tc_to_txq[tc].count = count;
2923         sb_dev->tc_to_txq[tc].offset = offset;
2924 
2925         /* Provide a way for Tx queue to find the tc_to_txq map or
2926          * XPS map for itself.
2927          */
2928         while (count--)
2929                 netdev_get_tx_queue(dev, count + offset)->sb_dev = sb_dev;
2930 
2931         return 0;
2932 }
2933 EXPORT_SYMBOL(netdev_bind_sb_channel_queue);
2934 
2935 int netdev_set_sb_channel(struct net_device *dev, u16 channel)
2936 {
2937         /* Do not use a multiqueue device to represent a subordinate channel */
2938         if (netif_is_multiqueue(dev))
2939                 return -ENODEV;
2940 
2941         /* We allow channels 1 - 32767 to be used for subordinate channels.
2942          * Channel 0 is meant to be "native" mode and used only to represent
2943          * the main root device. We allow writing 0 to reset the device back
2944          * to normal mode after being used as a subordinate channel.
2945          */
2946         if (channel > S16_MAX)
2947                 return -EINVAL;
2948 
2949         dev->num_tc = -channel;
2950 
2951         return 0;
2952 }
2953 EXPORT_SYMBOL(netdev_set_sb_channel);
2954 
2955 /*
2956  * Routine to help set real_num_tx_queues. To avoid skbs mapped to queues
2957  * greater than real_num_tx_queues stale skbs on the qdisc must be flushed.
2958  */
2959 int netif_set_real_num_tx_queues(struct net_device *dev, unsigned int txq)
2960 {
2961         bool disabling;
2962         int rc;
2963 
2964         disabling = txq < dev->real_num_tx_queues;
2965 
2966         if (txq < 1 || txq > dev->num_tx_queues)
2967                 return -EINVAL;
2968 
2969         if (dev->reg_state == NETREG_REGISTERED ||
2970             dev->reg_state == NETREG_UNREGISTERING) {
2971                 ASSERT_RTNL();
2972 
2973                 rc = netdev_queue_update_kobjects(dev, dev->real_num_tx_queues,
2974                                                   txq);
2975                 if (rc)
2976                         return rc;
2977 
2978                 if (dev->num_tc)
2979                         netif_setup_tc(dev, txq);
2980 
2981                 dev->real_num_tx_queues = txq;
2982 
2983                 if (disabling) {
2984                         synchronize_net();
2985                         qdisc_reset_all_tx_gt(dev, txq);
2986 #ifdef CONFIG_XPS
2987                         netif_reset_xps_queues_gt(dev, txq);
2988 #endif
2989                 }
2990         } else {
2991                 dev->real_num_tx_queues = txq;
2992         }
2993 
2994         return 0;
2995 }
2996 EXPORT_SYMBOL(netif_set_real_num_tx_queues);
2997 
2998 #ifdef CONFIG_SYSFS
2999 /**
3000  *      netif_set_real_num_rx_queues - set actual number of RX queues used
3001  *      @dev: Network device
3002  *      @rxq: Actual number of RX queues
3003  *
3004  *      This must be called either with the rtnl_lock held or before
3005  *      registration of the net device.  Returns 0 on success, or a
3006  *      negative error code.  If called before registration, it always
3007  *      succeeds.
3008  */
3009 int netif_set_real_num_rx_queues(struct net_device *dev, unsigned int rxq)
3010 {
3011         int rc;
3012 
3013         if (rxq < 1 || rxq > dev->num_rx_queues)
3014                 return -EINVAL;
3015 
3016         if (dev->reg_state == NETREG_REGISTERED) {
3017                 ASSERT_RTNL();
3018 
3019                 rc = net_rx_queue_update_kobjects(dev, dev->real_num_rx_queues,
3020                                                   rxq);
3021                 if (rc)
3022                         return rc;
3023         }
3024 
3025         dev->real_num_rx_queues = rxq;
3026         return 0;
3027 }
3028 EXPORT_SYMBOL(netif_set_real_num_rx_queues);
3029 #endif
3030 
3031 /**
3032  * netif_get_num_default_rss_queues - default number of RSS queues
3033  *
3034  * This routine should set an upper limit on the number of RSS queues
3035  * used by default by multiqueue devices.
3036  */
3037 int netif_get_num_default_rss_queues(void)
3038 {
3039         return is_kdump_kernel() ?
3040                 1 : min_t(int, DEFAULT_MAX_NUM_RSS_QUEUES, num_online_cpus());
3041 }
3042 EXPORT_SYMBOL(netif_get_num_default_rss_queues);
3043 
3044 static void __netif_reschedule(struct Qdisc *q)
3045 {
3046         struct softnet_data *sd;
3047         unsigned long flags;
3048 
3049         local_irq_save(flags);
3050         sd = this_cpu_ptr(&softnet_data);
3051         q->next_sched = NULL;
3052         *sd->output_queue_tailp = q;
3053         sd->output_queue_tailp = &q->next_sched;
3054         raise_softirq_irqoff(NET_TX_SOFTIRQ);
3055         local_irq_restore(flags);
3056 }
3057 
3058 void __netif_schedule(struct Qdisc *q)
3059 {
3060         if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state))
3061                 __netif_reschedule(q);
3062 }
3063 EXPORT_SYMBOL(__netif_schedule);
3064 
3065 struct dev_kfree_skb_cb {
3066         enum skb_free_reason reason;
3067 };
3068 
3069 static struct dev_kfree_skb_cb *get_kfree_skb_cb(const struct sk_buff *skb)
3070 {
3071         return (struct dev_kfree_skb_cb *)skb->cb;
3072 }
3073 
3074 void netif_schedule_queue(struct netdev_queue *txq)
3075 {
3076         rcu_read_lock();
3077         if (!netif_xmit_stopped(txq)) {
3078                 struct Qdisc *q = rcu_dereference(txq->qdisc);
3079 
3080                 __netif_schedule(q);
3081         }
3082         rcu_read_unlock();
3083 }
3084 EXPORT_SYMBOL(netif_schedule_queue);
3085 
3086 void netif_tx_wake_queue(struct netdev_queue *dev_queue)
3087 {
3088         if (test_and_clear_bit(__QUEUE_STATE_DRV_XOFF, &dev_queue->state)) {
3089                 struct Qdisc *q;
3090 
3091                 rcu_read_lock();
3092                 q = rcu_dereference(dev_queue->qdisc);
3093                 __netif_schedule(q);
3094                 rcu_read_unlock();
3095         }
3096 }
3097 EXPORT_SYMBOL(netif_tx_wake_queue);
3098 
3099 void __dev_kfree_skb_irq(struct sk_buff *skb, enum skb_free_reason reason)
3100 {
3101         unsigned long flags;
3102 
3103         if (unlikely(!skb))
3104                 return;
3105 
3106         if (likely(refcount_read(&skb->users) == 1)) {
3107                 smp_rmb();
3108                 refcount_set(&skb->users, 0);
3109         } else if (likely(!refcount_dec_and_test(&skb->users))) {
3110                 return;
3111         }
3112         get_kfree_skb_cb(skb)->reason = reason;
3113         local_irq_save(flags);
3114         skb->next = __this_cpu_read(softnet_data.completion_queue);
3115         __this_cpu_write(softnet_data.completion_queue, skb);
3116         raise_softirq_irqoff(NET_TX_SOFTIRQ);
3117         local_irq_restore(flags);
3118 }
3119 EXPORT_SYMBOL(__dev_kfree_skb_irq);
3120 
3121 void __dev_kfree_skb_any(struct sk_buff *skb, enum skb_free_reason reason)
3122 {
3123         if (in_irq() || irqs_disabled())
3124                 __dev_kfree_skb_irq(skb, reason);
3125         else
3126                 dev_kfree_skb(skb);
3127 }
3128 EXPORT_SYMBOL(__dev_kfree_skb_any);
3129 
3130 
3131 /**
3132  * netif_device_detach - mark device as removed
3133  * @dev: network device
3134  *
3135  * Mark device as removed from system and therefore no longer available.
3136  */
3137 void netif_device_detach(struct net_device *dev)
3138 {
3139         if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) &&
3140             netif_running(dev)) {
3141                 netif_tx_stop_all_queues(dev);
3142         }
3143 }
3144 EXPORT_SYMBOL(netif_device_detach);
3145 
3146 /**
3147  * netif_device_attach - mark device as attached
3148  * @dev: network device
3149  *
3150  * Mark device as attached from system and restart if needed.
3151  */
3152 void netif_device_attach(struct net_device *dev)
3153 {
3154         if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) &&
3155             netif_running(dev)) {
3156                 netif_tx_wake_all_queues(dev);
3157                 __netdev_watchdog_up(dev);
3158         }
3159 }
3160 EXPORT_SYMBOL(netif_device_attach);
3161 
3162 /*
3163  * Returns a Tx hash based on the given packet descriptor a Tx queues' number
3164  * to be used as a distribution range.
3165  */
3166 static u16 skb_tx_hash(const struct net_device *dev,
3167                        const struct net_device *sb_dev,
3168                        struct sk_buff *skb)
3169 {
3170         u32 hash;
3171         u16 qoffset = 0;
3172         u16 qcount = dev->real_num_tx_queues;
3173 
3174         if (dev->num_tc) {
3175                 u8 tc = netdev_get_prio_tc_map(dev, skb->priority);
3176 
3177                 qoffset = sb_dev->tc_to_txq[tc].offset;
3178                 qcount = sb_dev->tc_to_txq[tc].count;
3179         }
3180 
3181         if (skb_rx_queue_recorded(skb)) {
3182                 hash = skb_get_rx_queue(skb);
3183                 if (hash >= qoffset)
3184                         hash -= qoffset;
3185                 while (unlikely(hash >= qcount))
3186                         hash -= qcount;
3187                 return hash + qoffset;
3188         }
3189 
3190         return (u16) reciprocal_scale(skb_get_hash(skb), qcount) + qoffset;
3191 }
3192 
3193 static void skb_warn_bad_offload(const struct sk_buff *skb)
3194 {
3195         static const netdev_features_t null_features;
3196         struct net_device *dev = skb->dev;
3197         const char *name = "";
3198 
3199         if (!net_ratelimit())
3200                 return;
3201 
3202         if (dev) {
3203                 if (dev->dev.parent)
3204                         name = dev_driver_string(dev->dev.parent);
3205                 else
3206                         name = netdev_name(dev);
3207         }
3208         skb_dump(KERN_WARNING, skb, false);
3209         WARN(1, "%s: caps=(%pNF, %pNF)\n",
3210              name, dev ? &dev->features : &null_features,
3211              skb->sk ? &skb->sk->sk_route_caps : &null_features);
3212 }
3213 
3214 /*
3215  * Invalidate hardware checksum when packet is to be mangled, and
3216  * complete checksum manually on outgoing path.
3217  */
3218 int skb_checksum_help(struct sk_buff *skb)
3219 {
3220         __wsum csum;
3221         int ret = 0, offset;
3222 
3223         if (skb->ip_summed == CHECKSUM_COMPLETE)
3224                 goto out_set_summed;
3225 
3226         if (unlikely(skb_is_gso(skb))) {
3227                 skb_warn_bad_offload(skb);
3228                 return -EINVAL;
3229         }
3230 
3231         /* Before computing a checksum, we should make sure no frag could
3232          * be modified by an external entity : checksum could be wrong.
3233          */
3234         if (skb_has_shared_frag(skb)) {
3235                 ret = __skb_linearize(skb);
3236                 if (ret)
3237                         goto out;
3238         }
3239 
3240         offset = skb_checksum_start_offset(skb);
3241         BUG_ON(offset >= skb_headlen(skb));
3242         csum = skb_checksum(skb, offset, skb->len - offset, 0);
3243 
3244         offset += skb->csum_offset;
3245         BUG_ON(offset + sizeof(__sum16) > skb_headlen(skb));
3246 
3247         ret = skb_ensure_writable(skb, offset + sizeof(__sum16));
3248         if (ret)
3249                 goto out;
3250 
3251         *(__sum16 *)(skb->data + offset) = csum_fold(csum) ?: CSUM_MANGLED_0;
3252 out_set_summed:
3253         skb->ip_summed = CHECKSUM_NONE;
3254 out:
3255         return ret;
3256 }
3257 EXPORT_SYMBOL(skb_checksum_help);
3258 
3259 int skb_crc32c_csum_help(struct sk_buff *skb)
3260 {
3261         __le32 crc32c_csum;
3262         int ret = 0, offset, start;
3263 
3264         if (skb->ip_summed != CHECKSUM_PARTIAL)
3265                 goto out;
3266 
3267         if (unlikely(skb_is_gso(skb)))
3268                 goto out;
3269 
3270         /* Before computing a checksum, we should make sure no frag could
3271          * be modified by an external entity : checksum could be wrong.
3272          */
3273         if (unlikely(skb_has_shared_frag(skb))) {
3274                 ret = __skb_linearize(skb);
3275                 if (ret)
3276                         goto out;
3277         }
3278         start = skb_checksum_start_offset(skb);
3279         offset = start + offsetof(struct sctphdr, checksum);
3280         if (WARN_ON_ONCE(offset >= skb_headlen(skb))) {
3281                 ret = -EINVAL;
3282                 goto out;
3283         }
3284 
3285         ret = skb_ensure_writable(skb, offset + sizeof(__le32));
3286         if (ret)
3287                 goto out;
3288 
3289         crc32c_csum = cpu_to_le32(~__skb_checksum(skb, start,
3290                                                   skb->len - start, ~(__u32)0,
3291                                                   crc32c_csum_stub));
3292         *(__le32 *)(skb->data + offset) = crc32c_csum;
3293         skb->ip_summed = CHECKSUM_NONE;
3294         skb->csum_not_inet = 0;
3295 out:
3296         return ret;
3297 }
3298 
3299 __be16 skb_network_protocol(struct sk_buff *skb, int *depth)
3300 {
3301         __be16 type = skb->protocol;
3302 
3303         /* Tunnel gso handlers can set protocol to ethernet. */
3304         if (type == htons(ETH_P_TEB)) {
3305                 struct ethhdr *eth;
3306 
3307                 if (unlikely(!pskb_may_pull(skb, sizeof(struct ethhdr))))
3308                         return 0;
3309 
3310                 eth = (struct ethhdr *)skb->data;
3311                 type = eth->h_proto;
3312         }
3313 
3314         return __vlan_get_protocol(skb, type, depth);
3315 }
3316 
3317 /**
3318  *      skb_mac_gso_segment - mac layer segmentation handler.
3319  *      @skb: buffer to segment
3320  *      @features: features for the output path (see dev->features)
3321  */
3322 struct sk_buff *skb_mac_gso_segment(struct sk_buff *skb,
3323                                     netdev_features_t features)
3324 {
3325         struct sk_buff *segs = ERR_PTR(-EPROTONOSUPPORT);
3326         struct packet_offload *ptype;
3327         int vlan_depth = skb->mac_len;
3328         __be16 type = skb_network_protocol(skb, &vlan_depth);
3329 
3330         if (unlikely(!type))
3331                 return ERR_PTR(-EINVAL);
3332 
3333         __skb_pull(skb, vlan_depth);
3334 
3335         rcu_read_lock();
3336         list_for_each_entry_rcu(ptype, &offload_base, list) {
3337                 if (ptype->type == type && ptype->callbacks.gso_segment) {
3338                         segs = ptype->callbacks.gso_segment(skb, features);
3339                         break;
3340                 }
3341         }
3342         rcu_read_unlock();
3343 
3344         __skb_push(skb, skb->data - skb_mac_header(skb));
3345 
3346         return segs;
3347 }
3348 EXPORT_SYMBOL(skb_mac_gso_segment);
3349 
3350 
3351 /* openvswitch calls this on rx path, so we need a different check.
3352  */
3353 static inline bool skb_needs_check(struct sk_buff *skb, bool tx_path)
3354 {
3355         if (tx_path)
3356                 return skb->ip_summed != CHECKSUM_PARTIAL &&
3357                        skb->ip_summed != CHECKSUM_UNNECESSARY;
3358 
3359         return skb->ip_summed == CHECKSUM_NONE;
3360 }
3361 
3362 /**
3363  *      __skb_gso_segment - Perform segmentation on skb.
3364  *      @skb: buffer to segment
3365  *      @features: features for the output path (see dev->features)
3366  *      @tx_path: whether it is called in TX path
3367  *
3368  *      This function segments the given skb and returns a list of segments.
3369  *
3370  *      It may return NULL if the skb requires no segmentation.  This is
3371  *      only possible when GSO is used for verifying header integrity.
3372  *
3373  *      Segmentation preserves SKB_GSO_CB_OFFSET bytes of previous skb cb.
3374  */
3375 struct sk_buff *__skb_gso_segment(struct sk_buff *skb,
3376                                   netdev_features_t features, bool tx_path)
3377 {
3378         struct sk_buff *segs;
3379 
3380         if (unlikely(skb_needs_check(skb, tx_path))) {
3381                 int err;
3382 
3383                 /* We're going to init ->check field in TCP or UDP header */
3384                 err = skb_cow_head(skb, 0);
3385                 if (err < 0)
3386                         return ERR_PTR(err);
3387         }
3388 
3389         /* Only report GSO partial support if it will enable us to
3390          * support segmentation on this frame without needing additional
3391          * work.
3392          */
3393         if (features & NETIF_F_GSO_PARTIAL) {
3394                 netdev_features_t partial_features = NETIF_F_GSO_ROBUST;
3395                 struct net_device *dev = skb->dev;
3396 
3397                 partial_features |= dev->features & dev->gso_partial_features;
3398                 if (!skb_gso_ok(skb, features | partial_features))
3399                         features &= ~NETIF_F_GSO_PARTIAL;
3400         }
3401 
3402         BUILD_BUG_ON(SKB_GSO_CB_OFFSET +
3403                      sizeof(*SKB_GSO_CB(skb)) > sizeof(skb->cb));
3404 
3405         SKB_GSO_CB(skb)->mac_offset = skb_headroom(skb);
3406         SKB_GSO_CB(skb)->encap_level = 0;
3407 
3408         skb_reset_mac_header(skb);
3409         skb_reset_mac_len(skb);
3410 
3411         segs = skb_mac_gso_segment(skb, features);
3412 
3413         if (segs != skb && unlikely(skb_needs_check(skb, tx_path) && !IS_ERR(segs)))
3414                 skb_warn_bad_offload(skb);
3415 
3416         return segs;
3417 }
3418 EXPORT_SYMBOL(__skb_gso_segment);
3419 
3420 /* Take action when hardware reception checksum errors are detected. */
3421 #ifdef CONFIG_BUG
3422 void netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
3423 {
3424         if (net_ratelimit()) {
3425                 pr_err("%s: hw csum failure\n", dev ? dev->name : "<unknown>");
3426                 skb_dump(KERN_ERR, skb, true);
3427                 dump_stack();
3428         }
3429 }
3430 EXPORT_SYMBOL(netdev_rx_csum_fault);
3431 #endif
3432 
3433 /* XXX: check that highmem exists at all on the given machine. */
3434 static int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
3435 {
3436 #ifdef CONFIG_HIGHMEM
3437         int i;
3438 
3439         if (!(dev->features & NETIF_F_HIGHDMA)) {
3440                 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3441                         skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3442 
3443                         if (PageHighMem(skb_frag_page(frag)))
3444                                 return 1;
3445                 }
3446         }
3447 #endif
3448         return 0;
3449 }
3450 
3451 /* If MPLS offload request, verify we are testing hardware MPLS features
3452  * instead of standard features for the netdev.
3453  */
3454 #if IS_ENABLED(CONFIG_NET_MPLS_GSO)
3455 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3456                                            netdev_features_t features,
3457                                            __be16 type)
3458 {
3459         if (eth_p_mpls(type))
3460                 features &= skb->dev->mpls_features;
3461 
3462         return features;
3463 }
3464 #else
3465 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3466                                            netdev_features_t features,
3467                                            __be16 type)
3468 {
3469         return features;
3470 }
3471 #endif
3472 
3473 static netdev_features_t harmonize_features(struct sk_buff *skb,
3474         netdev_features_t features)
3475 {
3476         __be16 type;
3477 
3478         type = skb_network_protocol(skb, NULL);
3479         features = net_mpls_features(skb, features, type);
3480 
3481         if (skb->ip_summed != CHECKSUM_NONE &&
3482             !can_checksum_protocol(features, type)) {
3483                 features &= ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
3484         }
3485         if (illegal_highdma(skb->dev, skb))
3486                 features &= ~NETIF_F_SG;
3487 
3488         return features;
3489 }
3490 
3491 netdev_features_t passthru_features_check(struct sk_buff *skb,
3492                                           struct net_device *dev,
3493                                           netdev_features_t features)
3494 {
3495         return features;
3496 }
3497 EXPORT_SYMBOL(passthru_features_check);
3498 
3499 static netdev_features_t dflt_features_check(struct sk_buff *skb,
3500                                              struct net_device *dev,
3501                                              netdev_features_t features)
3502 {
3503         return vlan_features_check(skb, features);
3504 }
3505 
3506 static netdev_features_t gso_features_check(const struct sk_buff *skb,
3507                                             struct net_device *dev,
3508                                             netdev_features_t features)
3509 {
3510         u16 gso_segs = skb_shinfo(skb)->gso_segs;
3511 
3512         if (gso_segs > dev->gso_max_segs)
3513                 return features & ~NETIF_F_GSO_MASK;
3514 
3515         if (!skb_shinfo(skb)->gso_type) {
3516                 skb_warn_bad_offload(skb);
3517                 return features & ~NETIF_F_GSO_MASK;
3518         }
3519 
3520         /* Support for GSO partial features requires software
3521          * intervention before we can actually process the packets
3522          * so we need to strip support for any partial features now
3523          * and we can pull them back in after we have partially
3524          * segmented the frame.
3525          */
3526         if (!(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL))
3527                 features &= ~dev->gso_partial_features;
3528 
3529         /* Make sure to clear the IPv4 ID mangling feature if the
3530          * IPv4 header has the potential to be fragmented.
3531          */
3532         if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) {
3533                 struct iphdr *iph = skb->encapsulation ?
3534                                     inner_ip_hdr(skb) : ip_hdr(skb);
3535 
3536                 if (!(iph->frag_off & htons(IP_DF)))
3537                         features &= ~NETIF_F_TSO_MANGLEID;
3538         }
3539 
3540         return features;
3541 }
3542 
3543 netdev_features_t netif_skb_features(struct sk_buff *skb)
3544 {
3545         struct net_device *dev = skb->dev;
3546         netdev_features_t features = dev->features;
3547 
3548         if (skb_is_gso(skb))
3549                 features = gso_features_check(skb, dev, features);
3550 
3551         /* If encapsulation offload request, verify we are testing
3552          * hardware encapsulation features instead of standard
3553          * features for the netdev
3554          */
3555         if (skb->encapsulation)
3556                 features &= dev->hw_enc_features;
3557 
3558         if (skb_vlan_tagged(skb))
3559                 features = netdev_intersect_features(features,
3560                                                      dev->vlan_features |
3561                                                      NETIF_F_HW_VLAN_CTAG_TX |
3562                                                      NETIF_F_HW_VLAN_STAG_TX);
3563 
3564         if (dev->netdev_ops->ndo_features_check)
3565                 features &= dev->netdev_ops->ndo_features_check(skb, dev,
3566                                                                 features);
3567         else
3568                 features &= dflt_features_check(skb, dev, features);
3569 
3570         return harmonize_features(skb, features);
3571 }
3572 EXPORT_SYMBOL(netif_skb_features);
3573 
3574 static int xmit_one(struct sk_buff *skb, struct net_device *dev,
3575                     struct netdev_queue *txq, bool more)
3576 {
3577         unsigned int len;
3578         int rc;
3579 
3580         if (dev_nit_active(dev))
3581                 dev_queue_xmit_nit(skb, dev);
3582 
3583         len = skb->len;
3584         PRANDOM_ADD_NOISE(skb, dev, txq, len + jiffies);
3585         trace_net_dev_start_xmit(skb, dev);
3586         rc = netdev_start_xmit(skb, dev, txq, more);
3587         trace_net_dev_xmit(skb, rc, dev, len);
3588 
3589         return rc;
3590 }
3591 
3592 struct sk_buff *dev_hard_start_xmit(struct sk_buff *first, struct net_device *dev,
3593                                     struct netdev_queue *txq, int *ret)
3594 {
3595         struct sk_buff *skb = first;
3596         int rc = NETDEV_TX_OK;
3597 
3598         while (skb) {
3599                 struct sk_buff *next = skb->next;
3600 
3601                 skb_mark_not_on_list(skb);
3602                 rc = xmit_one(skb, dev, txq, next != NULL);
3603                 if (unlikely(!dev_xmit_complete(rc))) {
3604                         skb->next = next;
3605                         goto out;
3606                 }
3607 
3608                 skb = next;
3609                 if (netif_tx_queue_stopped(txq) && skb) {
3610                         rc = NETDEV_TX_BUSY;
3611                         break;
3612                 }
3613         }
3614 
3615 out:
3616         *ret = rc;
3617         return skb;
3618 }
3619 
3620 static struct sk_buff *validate_xmit_vlan(struct sk_buff *skb,
3621                                           netdev_features_t features)
3622 {
3623         if (skb_vlan_tag_present(skb) &&
3624             !vlan_hw_offload_capable(features, skb->vlan_proto))
3625                 skb = __vlan_hwaccel_push_inside(skb);
3626         return skb;
3627 }
3628 
3629 int skb_csum_hwoffload_help(struct sk_buff *skb,
3630                             const netdev_features_t features)
3631 {
3632         if (unlikely(skb->csum_not_inet))
3633                 return !!(features & NETIF_F_SCTP_CRC) ? 0 :
3634                         skb_crc32c_csum_help(skb);
3635 
3636         return !!(features & NETIF_F_CSUM_MASK) ? 0 : skb_checksum_help(skb);
3637 }
3638 EXPORT_SYMBOL(skb_csum_hwoffload_help);
3639 
3640 static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device *dev, bool *again)
3641 {
3642         netdev_features_t features;
3643 
3644         features = netif_skb_features(skb);
3645         skb = validate_xmit_vlan(skb, features);
3646         if (unlikely(!skb))
3647                 goto out_null;
3648 
3649         skb = sk_validate_xmit_skb(skb, dev);
3650         if (unlikely(!skb))
3651                 goto out_null;
3652 
3653         if (netif_needs_gso(skb, features)) {
3654                 struct sk_buff *segs;
3655 
3656                 segs = skb_gso_segment(skb, features);
3657                 if (IS_ERR(segs)) {
3658                         goto out_kfree_skb;
3659                 } else if (segs) {
3660                         consume_skb(skb);
3661                         skb = segs;
3662                 }
3663         } else {
3664                 if (skb_needs_linearize(skb, features) &&
3665                     __skb_linearize(skb))
3666                         goto out_kfree_skb;
3667 
3668                 /* If packet is not checksummed and device does not
3669                  * support checksumming for this protocol, complete
3670                  * checksumming here.
3671                  */
3672                 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3673                         if (skb->encapsulation)
3674                                 skb_set_inner_transport_header(skb,
3675                                                                skb_checksum_start_offset(skb));
3676                         else
3677                                 skb_set_transport_header(skb,
3678                                                          skb_checksum_start_offset(skb));
3679                         if (skb_csum_hwoffload_help(skb, features))
3680                                 goto out_kfree_skb;
3681                 }
3682         }
3683 
3684         skb = validate_xmit_xfrm(skb, features, again);
3685 
3686         return skb;
3687 
3688 out_kfree_skb:
3689         kfree_skb(skb);
3690 out_null:
3691         atomic_long_inc(&dev->tx_dropped);
3692         return NULL;
3693 }
3694 
3695 struct sk_buff *validate_xmit_skb_list(struct sk_buff *skb, struct net_device *dev, bool *again)
3696 {
3697         struct sk_buff *next, *head = NULL, *tail;
3698 
3699         for (; skb != NULL; skb = next) {
3700                 next = skb->next;
3701                 skb_mark_not_on_list(skb);
3702 
3703                 /* in case skb wont be segmented, point to itself */
3704                 skb->prev = skb;
3705 
3706                 skb = validate_xmit_skb(skb, dev, again);
3707                 if (!skb)
3708                         continue;
3709 
3710                 if (!head)
3711                         head = skb;
3712                 else
3713                         tail->next = skb;
3714                 /* If skb was segmented, skb->prev points to
3715                  * the last segment. If not, it still contains skb.
3716                  */
3717                 tail = skb->prev;
3718         }
3719         return head;
3720 }
3721 EXPORT_SYMBOL_GPL(validate_xmit_skb_list);
3722 
3723 static void qdisc_pkt_len_init(struct sk_buff *skb)
3724 {
3725         const struct skb_shared_info *shinfo = skb_shinfo(skb);
3726 
3727         qdisc_skb_cb(skb)->pkt_len = skb->len;
3728 
3729         /* To get more precise estimation of bytes sent on wire,
3730          * we add to pkt_len the headers size of all segments
3731          */
3732         if (shinfo->gso_size && skb_transport_header_was_set(skb)) {
3733                 unsigned int hdr_len;
3734                 u16 gso_segs = shinfo->gso_segs;
3735 
3736                 /* mac layer + network layer */
3737                 hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
3738 
3739                 /* + transport layer */
3740                 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
3741                         const struct tcphdr *th;
3742                         struct tcphdr _tcphdr;
3743 
3744                         th = skb_header_pointer(skb, skb_transport_offset(skb),
3745                                                 sizeof(_tcphdr), &_tcphdr);
3746                         if (likely(th))
3747                                 hdr_len += __tcp_hdrlen(th);
3748                 } else {
3749                         struct udphdr _udphdr;
3750 
3751                         if (skb_header_pointer(skb, skb_transport_offset(skb),
3752                                                sizeof(_udphdr), &_udphdr))
3753                                 hdr_len += sizeof(struct udphdr);
3754                 }
3755 
3756                 if (shinfo->gso_type & SKB_GSO_DODGY)
3757                         gso_segs = DIV_ROUND_UP(skb->len - hdr_len,
3758                                                 shinfo->gso_size);
3759 
3760                 qdisc_skb_cb(skb)->pkt_len += (gso_segs - 1) * hdr_len;
3761         }
3762 }
3763 
3764 static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q,
3765                                  struct net_device *dev,
3766                                  struct netdev_queue *txq)
3767 {
3768         spinlock_t *root_lock = qdisc_lock(q);
3769         struct sk_buff *to_free = NULL;
3770         bool contended;
3771         int rc;
3772 
3773         qdisc_calculate_pkt_len(skb, q);
3774 
3775         if (q->flags & TCQ_F_NOLOCK) {
3776                 rc = q->enqueue(skb, q, &to_free) & NET_XMIT_MASK;
3777                 qdisc_run(q);
3778 
3779                 if (unlikely(to_free))
3780                         kfree_skb_list(to_free);
3781                 return rc;
3782         }
3783 
3784         /*
3785          * Heuristic to force contended enqueues to serialize on a
3786          * separate lock before trying to get qdisc main lock.
3787          * This permits qdisc->running owner to get the lock more
3788          * often and dequeue packets faster.
3789          */
3790         contended = qdisc_is_running(q);
3791         if (unlikely(contended))
3792                 spin_lock(&q->busylock);
3793 
3794         spin_lock(root_lock);
3795         if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) {
3796                 __qdisc_drop(skb, &to_free);
3797                 rc = NET_XMIT_DROP;
3798         } else if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) &&
3799                    qdisc_run_begin(q)) {
3800                 /*
3801                  * This is a work-conserving queue; there are no old skbs
3802                  * waiting to be sent out; and the qdisc is not running -
3803                  * xmit the skb directly.
3804                  */
3805 
3806                 qdisc_bstats_update(q, skb);
3807 
3808                 if (sch_direct_xmit(skb, q, dev, txq, root_lock, true)) {
3809                         if (unlikely(contended)) {
3810                                 spin_unlock(&q->busylock);
3811                                 contended = false;
3812                         }
3813                         __qdisc_run(q);
3814                 }
3815 
3816                 qdisc_run_end(q);
3817                 rc = NET_XMIT_SUCCESS;
3818         } else {
3819                 rc = q->enqueue(skb, q, &to_free) & NET_XMIT_MASK;
3820                 if (qdisc_run_begin(q)) {
3821                         if (unlikely(contended)) {
3822                                 spin_unlock(&q->busylock);
3823                                 contended = false;
3824                         }
3825                         __qdisc_run(q);
3826                         qdisc_run_end(q);
3827                 }
3828         }
3829         spin_unlock(root_lock);
3830         if (unlikely(to_free))
3831                 kfree_skb_list(to_free);
3832         if (unlikely(contended))
3833                 spin_unlock(&q->busylock);
3834         return rc;
3835 }
3836 
3837 #if IS_ENABLED(CONFIG_CGROUP_NET_PRIO)
3838 static void skb_update_prio(struct sk_buff *skb)
3839 {
3840         const struct netprio_map *map;
3841         const struct sock *sk;
3842         unsigned int prioidx;
3843 
3844         if (skb->priority)
3845                 return;
3846         map = rcu_dereference_bh(skb->dev->priomap);
3847         if (!map)
3848                 return;
3849         sk = skb_to_full_sk(skb);
3850         if (!sk)
3851                 return;
3852 
3853         prioidx = sock_cgroup_prioidx(&sk->sk_cgrp_data);
3854 
3855         if (prioidx < map->priomap_len)
3856                 skb->priority = map->priomap[prioidx];
3857 }
3858 #else
3859 #define skb_update_prio(skb)
3860 #endif
3861 
3862 /**
3863  *      dev_loopback_xmit - loop back @skb
3864  *      @net: network namespace this loopback is happening in
3865  *      @sk:  sk needed to be a netfilter okfn
3866  *      @skb: buffer to transmit
3867  */
3868 int dev_loopback_xmit(struct net *net, struct sock *sk, struct sk_buff *skb)
3869 {
3870         skb_reset_mac_header(skb);
3871         __skb_pull(skb, skb_network_offset(skb));
3872         skb->pkt_type = PACKET_LOOPBACK;
3873         skb->ip_summed = CHECKSUM_UNNECESSARY;
3874         WARN_ON(!skb_dst(skb));
3875         skb_dst_force(skb);
3876         netif_rx_ni(skb);
3877         return 0;
3878 }
3879 EXPORT_SYMBOL(dev_loopback_xmit);
3880 
3881 #ifdef CONFIG_NET_EGRESS
3882 static struct sk_buff *
3883 sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
3884 {
3885         struct mini_Qdisc *miniq = rcu_dereference_bh(dev->miniq_egress);
3886         struct tcf_result cl_res;
3887 
3888         if (!miniq)
3889                 return skb;
3890 
3891         /* qdisc_skb_cb(skb)->pkt_len was already set by the caller. */
3892         qdisc_skb_cb(skb)->mru = 0;
3893         mini_qdisc_bstats_cpu_update(miniq, skb);
3894 
3895         switch (tcf_classify(skb, miniq->filter_list, &cl_res, false)) {
3896         case TC_ACT_OK:
3897         case TC_ACT_RECLASSIFY:
3898                 skb->tc_index = TC_H_MIN(cl_res.classid);
3899                 break;
3900         case TC_ACT_SHOT:
3901                 mini_qdisc_qstats_cpu_drop(miniq);
3902                 *ret = NET_XMIT_DROP;
3903                 kfree_skb(skb);
3904                 return NULL;
3905         case TC_ACT_STOLEN:
3906         case TC_ACT_QUEUED:
3907         case TC_ACT_TRAP:
3908                 *ret = NET_XMIT_SUCCESS;
3909                 consume_skb(skb);
3910                 return NULL;
3911         case TC_ACT_REDIRECT:
3912                 /* No need to push/pop skb's mac_header here on egress! */
3913                 skb_do_redirect(skb);
3914                 *ret = NET_XMIT_SUCCESS;
3915                 return NULL;
3916         default:
3917                 break;
3918         }
3919 
3920         return skb;
3921 }
3922 #endif /* CONFIG_NET_EGRESS */
3923 
3924 #ifdef CONFIG_XPS
3925 static int __get_xps_queue_idx(struct net_device *dev, struct sk_buff *skb,
3926                                struct xps_dev_maps *dev_maps, unsigned int tci)
3927 {
3928         struct xps_map *map;
3929         int queue_index = -1;
3930 
3931         if (dev->num_tc) {
3932                 tci *= dev->num_tc;
3933                 tci += netdev_get_prio_tc_map(dev, skb->priority);
3934         }
3935 
3936         map = rcu_dereference(dev_maps->attr_map[tci]);
3937         if (map) {
3938                 if (map->len == 1)
3939                         queue_index = map->queues[0];
3940                 else
3941                         queue_index = map->queues[reciprocal_scale(
3942                                                 skb_get_hash(skb), map->len)];
3943                 if (unlikely(queue_index >= dev->real_num_tx_queues))
3944                         queue_index = -1;
3945         }
3946         return queue_index;
3947 }
3948 #endif
3949 
3950 static int get_xps_queue(struct net_device *dev, struct net_device *sb_dev,
3951                          struct sk_buff *skb)
3952 {
3953 #ifdef CONFIG_XPS
3954         struct xps_dev_maps *dev_maps;
3955         struct sock *sk = skb->sk;
3956         int queue_index = -1;
3957 
3958         if (!static_key_false(&xps_needed))
3959                 return -1;
3960 
3961         rcu_read_lock();
3962         if (!static_key_false(&xps_rxqs_needed))
3963                 goto get_cpus_map;
3964 
3965         dev_maps = rcu_dereference(sb_dev->xps_rxqs_map);
3966         if (dev_maps) {
3967                 int tci = sk_rx_queue_get(sk);
3968 
3969                 if (tci >= 0 && tci < dev->num_rx_queues)
3970                         queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
3971                                                           tci);
3972         }
3973 
3974 get_cpus_map:
3975         if (queue_index < 0) {
3976                 dev_maps = rcu_dereference(sb_dev->xps_cpus_map);
3977                 if (dev_maps) {
3978                         unsigned int tci = skb->sender_cpu - 1;
3979 
3980                         queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
3981                                                           tci);
3982                 }
3983         }
3984         rcu_read_unlock();
3985 
3986         return queue_index;
3987 #else
3988         return -1;
3989 #endif
3990 }
3991 
3992 u16 dev_pick_tx_zero(struct net_device *dev, struct sk_buff *skb,
3993                      struct net_device *sb_dev)
3994 {
3995         return 0;
3996 }
3997 EXPORT_SYMBOL(dev_pick_tx_zero);
3998 
3999 u16 dev_pick_tx_cpu_id(struct net_device *dev, struct sk_buff *skb,
4000                        struct net_device *sb_dev)
4001 {
4002         return (u16)raw_smp_processor_id() % dev->real_num_tx_queues;
4003 }
4004 EXPORT_SYMBOL(dev_pick_tx_cpu_id);
4005 
4006 u16 netdev_pick_tx(struct net_device *dev, struct sk_buff *skb,
4007                      struct net_device *sb_dev)
4008 {
4009         struct sock *sk = skb->sk;
4010         int queue_index = sk_tx_queue_get(sk);
4011 
4012         sb_dev = sb_dev ? : dev;
4013 
4014         if (queue_index < 0 || skb->ooo_okay ||
4015             queue_index >= dev->real_num_tx_queues) {
4016                 int new_index = get_xps_queue(dev, sb_dev, skb);
4017 
4018                 if (new_index < 0)
4019                         new_index = skb_tx_hash(dev, sb_dev, skb);
4020 
4021                 if (queue_index != new_index && sk &&
4022                     sk_fullsock(sk) &&
4023                     rcu_access_pointer(sk->sk_dst_cache))
4024                         sk_tx_queue_set(sk, new_index);
4025 
4026                 queue_index = new_index;
4027         }
4028 
4029         return queue_index;
4030 }
4031 EXPORT_SYMBOL(netdev_pick_tx);
4032 
4033 struct netdev_queue *netdev_core_pick_tx(struct net_device *dev,
4034                                          struct sk_buff *skb,
4035                                          struct net_device *sb_dev)
4036 {
4037         int queue_index = 0;
4038 
4039 #ifdef CONFIG_XPS
4040         u32 sender_cpu = skb->sender_cpu - 1;
4041 
4042         if (sender_cpu >= (u32)NR_CPUS)
4043                 skb->sender_cpu = raw_smp_processor_id() + 1;
4044 #endif
4045 
4046         if (dev->real_num_tx_queues != 1) {
4047                 const struct net_device_ops *ops = dev->netdev_ops;
4048 
4049                 if (ops->ndo_select_queue)
4050                         queue_index = ops->ndo_select_queue(dev, skb, sb_dev);
4051                 else
4052                         queue_index = netdev_pick_tx(dev, skb, sb_dev);
4053 
4054                 queue_index = netdev_cap_txqueue(dev, queue_index);
4055         }
4056 
4057         skb_set_queue_mapping(skb, queue_index);
4058         return netdev_get_tx_queue(dev, queue_index);
4059 }
4060 
4061 /**
4062  *      __dev_queue_xmit - transmit a buffer
4063  *      @skb: buffer to transmit
4064  *      @sb_dev: suboordinate device used for L2 forwarding offload
4065  *
4066  *      Queue a buffer for transmission to a network device. The caller must
4067  *      have set the device and priority and built the buffer before calling
4068  *      this function. The function can be called from an interrupt.
4069  *
4070  *      A negative errno code is returned on a failure. A success does not
4071  *      guarantee the frame will be transmitted as it may be dropped due
4072  *      to congestion or traffic shaping.
4073  *
4074  * -----------------------------------------------------------------------------------
4075  *      I notice this method can also return errors from the queue disciplines,
4076  *      including NET_XMIT_DROP, which is a positive value.  So, errors can also
4077  *      be positive.
4078  *
4079  *      Regardless of the return value, the skb is consumed, so it is currently
4080  *      difficult to retry a send to this method.  (You can bump the ref count
4081  *      before sending to hold a reference for retry if you are careful.)
4082  *
4083  *      When calling this method, interrupts MUST be enabled.  This is because
4084  *      the BH enable code must have IRQs enabled so that it will not deadlock.
4085  *          --BLG
4086  */
4087 static int __dev_queue_xmit(struct sk_buff *skb, struct net_device *sb_dev)
4088 {
4089         struct net_device *dev = skb->dev;
4090         struct netdev_queue *txq;
4091         struct Qdisc *q;
4092         int rc = -ENOMEM;
4093         bool again = false;
4094 
4095         skb_reset_mac_header(skb);
4096 
4097         if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_SCHED_TSTAMP))
4098                 __skb_tstamp_tx(skb, NULL, skb->sk, SCM_TSTAMP_SCHED);
4099 
4100         /* Disable soft irqs for various locks below. Also
4101          * stops preemption for RCU.
4102          */
4103         rcu_read_lock_bh();
4104 
4105         skb_update_prio(skb);
4106 
4107         qdisc_pkt_len_init(skb);
4108 #ifdef CONFIG_NET_CLS_ACT
4109         skb->tc_at_ingress = 0;
4110 # ifdef CONFIG_NET_EGRESS
4111         if (static_branch_unlikely(&egress_needed_key)) {
4112                 skb = sch_handle_egress(skb, &rc, dev);
4113                 if (!skb)
4114                         goto out;
4115         }
4116 # endif
4117 #endif
4118         /* If device/qdisc don't need skb->dst, release it right now while
4119          * its hot in this cpu cache.
4120          */
4121         if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
4122                 skb_dst_drop(skb);
4123         else
4124                 skb_dst_force(skb);
4125 
4126         txq = netdev_core_pick_tx(dev, skb, sb_dev);
4127         q = rcu_dereference_bh(txq->qdisc);
4128 
4129         trace_net_dev_queue(skb);
4130         if (q->enqueue) {
4131                 rc = __dev_xmit_skb(skb, q, dev, txq);
4132                 goto out;
4133         }
4134 
4135         /* The device has no queue. Common case for software devices:
4136          * loopback, all the sorts of tunnels...
4137 
4138          * Really, it is unlikely that netif_tx_lock protection is necessary
4139          * here.  (f.e. loopback and IP tunnels are clean ignoring statistics
4140          * counters.)
4141          * However, it is possible, that they rely on protection
4142          * made by us here.
4143 
4144          * Check this and shot the lock. It is not prone from deadlocks.
4145          *Either shot noqueue qdisc, it is even simpler 8)
4146          */
4147         if (dev->flags & IFF_UP) {
4148                 int cpu = smp_processor_id(); /* ok because BHs are off */
4149 
4150                 if (txq->xmit_lock_owner != cpu) {
4151                         if (dev_xmit_recursion())
4152                                 goto recursion_alert;
4153 
4154                         skb = validate_xmit_skb(skb, dev, &again);
4155                         if (!skb)
4156                                 goto out;
4157 
4158                         PRANDOM_ADD_NOISE(skb, dev, txq, jiffies);
4159                         HARD_TX_LOCK(dev, txq, cpu);
4160 
4161                         if (!netif_xmit_stopped(txq)) {
4162                                 dev_xmit_recursion_inc();
4163                                 skb = dev_hard_start_xmit(skb, dev, txq, &rc);
4164                                 dev_xmit_recursion_dec();
4165                                 if (dev_xmit_complete(rc)) {
4166                                         HARD_TX_UNLOCK(dev, txq);
4167                                         goto out;
4168                                 }
4169                         }
4170                         HARD_TX_UNLOCK(dev, txq);
4171                         net_crit_ratelimited("Virtual device %s asks to queue packet!\n",
4172                                              dev->name);
4173                 } else {
4174                         /* Recursion is detected! It is possible,
4175                          * unfortunately
4176                          */
4177 recursion_alert:
4178                         net_crit_ratelimited("Dead loop on virtual device %s, fix it urgently!\n",
4179                                              dev->name);
4180                 }
4181         }
4182 
4183         rc = -ENETDOWN;
4184         rcu_read_unlock_bh();
4185 
4186         atomic_long_inc(&dev->tx_dropped);
4187         kfree_skb_list(skb);
4188         return rc;
4189 out:
4190         rcu_read_unlock_bh();
4191         return rc;
4192 }
4193 
4194 int dev_queue_xmit(struct sk_buff *skb)
4195 {
4196         return __dev_queue_xmit(skb, NULL);
4197 }
4198 EXPORT_SYMBOL(dev_queue_xmit);
4199 
4200 int dev_queue_xmit_accel(struct sk_buff *skb, struct net_device *sb_dev)
4201 {
4202         return __dev_queue_xmit(skb, sb_dev);
4203 }
4204 EXPORT_SYMBOL(dev_queue_xmit_accel);
4205 
4206 int __dev_direct_xmit(struct sk_buff *skb, u16 queue_id)
4207 {
4208         struct net_device *dev = skb->dev;
4209         struct sk_buff *orig_skb = skb;
4210         struct netdev_queue *txq;
4211         int ret = NETDEV_TX_BUSY;
4212         bool again = false;
4213 
4214         if (unlikely(!netif_running(dev) ||
4215                      !netif_carrier_ok(dev)))
4216                 goto drop;
4217 
4218         skb = validate_xmit_skb_list(skb, dev, &again);
4219         if (skb != orig_skb)
4220                 goto drop;
4221 
4222         skb_set_queue_mapping(skb, queue_id);
4223         txq = skb_get_tx_queue(dev, skb);
4224         PRANDOM_ADD_NOISE(skb, dev, txq, jiffies);
4225 
4226         local_bh_disable();
4227 
4228         dev_xmit_recursion_inc();
4229         HARD_TX_LOCK(dev, txq, smp_processor_id());
4230         if (!netif_xmit_frozen_or_drv_stopped(txq))
4231                 ret = netdev_start_xmit(skb, dev, txq, false);
4232         HARD_TX_UNLOCK(dev, txq);
4233         dev_xmit_recursion_dec();
4234 
4235         local_bh_enable();
4236         return ret;
4237 drop:
4238         atomic_long_inc(&dev->tx_dropped);
4239         kfree_skb_list(skb);
4240         return NET_XMIT_DROP;
4241 }
4242 EXPORT_SYMBOL(__dev_direct_xmit);
4243 
4244 /*************************************************************************
4245  *                      Receiver routines
4246  *************************************************************************/
4247 
4248 int netdev_max_backlog __read_mostly = 1000;
4249 EXPORT_SYMBOL(netdev_max_backlog);
4250 
4251 int netdev_tstamp_prequeue __read_mostly = 1;
4252 int netdev_budget __read_mostly = 300;
4253 /* Must be at least 2 jiffes to guarantee 1 jiffy timeout */
4254 unsigned int __read_mostly netdev_budget_usecs = 2 * USEC_PER_SEC / HZ;
4255 int weight_p __read_mostly = 64;           /* old backlog weight */
4256 int dev_weight_rx_bias __read_mostly = 1;  /* bias for backlog weight */
4257 int dev_weight_tx_bias __read_mostly = 1;  /* bias for output_queue quota */
4258 int dev_rx_weight __read_mostly = 64;
4259 int dev_tx_weight __read_mostly = 64;
4260 /* Maximum number of GRO_NORMAL skbs to batch up for list-RX */
4261 int gro_normal_batch __read_mostly = 8;
4262 
4263 /* Called with irq disabled */
4264 static inline void ____napi_schedule(struct softnet_data *sd,
4265                                      struct napi_struct *napi)
4266 {
4267         list_add_tail(&napi->poll_list, &sd->poll_list);
4268         __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4269 }
4270 
4271 #ifdef CONFIG_RPS
4272 
4273 /* One global table that all flow-based protocols share. */
4274 struct rps_sock_flow_table __rcu *rps_sock_flow_table __read_mostly;
4275 EXPORT_SYMBOL(rps_sock_flow_table);
4276 u32 rps_cpu_mask __read_mostly;
4277 EXPORT_SYMBOL(rps_cpu_mask);
4278 
4279 struct static_key_false rps_needed __read_mostly;
4280 EXPORT_SYMBOL(rps_needed);
4281 struct static_key_false rfs_needed __read_mostly;
4282 EXPORT_SYMBOL(rfs_needed);
4283 
4284 static struct rps_dev_flow *
4285 set_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4286             struct rps_dev_flow *rflow, u16 next_cpu)
4287 {
4288         if (next_cpu < nr_cpu_ids) {
4289 #ifdef CONFIG_RFS_ACCEL
4290                 struct netdev_rx_queue *rxqueue;
4291                 struct rps_dev_flow_table *flow_table;
4292                 struct rps_dev_flow *old_rflow;
4293                 u32 flow_id;
4294                 u16 rxq_index;
4295                 int rc;
4296 
4297                 /* Should we steer this flow to a different hardware queue? */
4298                 if (!skb_rx_queue_recorded(skb) || !dev->rx_cpu_rmap ||
4299                     !(dev->features & NETIF_F_NTUPLE))
4300                         goto out;
4301                 rxq_index = cpu_rmap_lookup_index(dev->rx_cpu_rmap, next_cpu);
4302                 if (rxq_index == skb_get_rx_queue(skb))
4303                         goto out;
4304 
4305                 rxqueue = dev->_rx + rxq_index;
4306                 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4307                 if (!flow_table)
4308                         goto out;
4309                 flow_id = skb_get_hash(skb) & flow_table->mask;
4310                 rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb,
4311                                                         rxq_index, flow_id);
4312                 if (rc < 0)
4313                         goto out;
4314                 old_rflow = rflow;
4315                 rflow = &flow_table->flows[flow_id];
4316                 rflow->filter = rc;
4317                 if (old_rflow->filter == rflow->filter)
4318                         old_rflow->filter = RPS_NO_FILTER;
4319         out:
4320 #endif
4321                 rflow->last_qtail =
4322                         per_cpu(softnet_data, next_cpu).input_queue_head;
4323         }
4324 
4325         rflow->cpu = next_cpu;
4326         return rflow;
4327 }
4328 
4329 /*
4330  * get_rps_cpu is called from netif_receive_skb and returns the target
4331  * CPU from the RPS map of the receiving queue for a given skb.
4332  * rcu_read_lock must be held on entry.
4333  */
4334 static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4335                        struct rps_dev_flow **rflowp)
4336 {
4337         const struct rps_sock_flow_table *sock_flow_table;
4338         struct netdev_rx_queue *rxqueue = dev->_rx;
4339         struct rps_dev_flow_table *flow_table;
4340         struct rps_map *map;
4341         int cpu = -1;
4342         u32 tcpu;
4343         u32 hash;
4344 
4345         if (skb_rx_queue_recorded(skb)) {
4346                 u16 index = skb_get_rx_queue(skb);
4347 
4348                 if (unlikely(index >= dev->real_num_rx_queues)) {
4349                         WARN_ONCE(dev->real_num_rx_queues > 1,
4350                                   "%s received packet on queue %u, but number "
4351                                   "of RX queues is %u\n",
4352                                   dev->name, index, dev->real_num_rx_queues);
4353                         goto done;
4354                 }
4355                 rxqueue += index;
4356         }
4357 
4358         /* Avoid computing hash if RFS/RPS is not active for this rxqueue */
4359 
4360         flow_table = rcu_dereference(rxqueue->rps_flow_table);
4361         map = rcu_dereference(rxqueue->rps_map);
4362         if (!flow_table && !map)
4363                 goto done;
4364 
4365         skb_reset_network_header(skb);
4366         hash = skb_get_hash(skb);
4367         if (!hash)
4368                 goto done;
4369 
4370         sock_flow_table = rcu_dereference(rps_sock_flow_table);
4371         if (flow_table && sock_flow_table) {
4372                 struct rps_dev_flow *rflow;
4373                 u32 next_cpu;
4374                 u32 ident;
4375 
4376                 /* First check into global flow table if there is a match */
4377                 ident = sock_flow_table->ents[hash & sock_flow_table->mask];
4378                 if ((ident ^ hash) & ~rps_cpu_mask)
4379                         goto try_rps;
4380 
4381                 next_cpu = ident & rps_cpu_mask;
4382 
4383                 /* OK, now we know there is a match,
4384                  * we can look at the local (per receive queue) flow table
4385                  */
4386                 rflow = &flow_table->flows[hash & flow_table->mask];
4387                 tcpu = rflow->cpu;
4388 
4389                 /*
4390                  * If the desired CPU (where last recvmsg was done) is
4391                  * different from current CPU (one in the rx-queue flow
4392                  * table entry), switch if one of the following holds:
4393                  *   - Current CPU is unset (>= nr_cpu_ids).
4394                  *   - Current CPU is offline.
4395                  *   - The current CPU's queue tail has advanced beyond the
4396                  *     last packet that was enqueued using this table entry.
4397                  *     This guarantees that all previous packets for the flow
4398                  *     have been dequeued, thus preserving in order delivery.
4399                  */
4400                 if (unlikely(tcpu != next_cpu) &&
4401                     (tcpu >= nr_cpu_ids || !cpu_online(tcpu) ||
4402                      ((int)(per_cpu(softnet_data, tcpu).input_queue_head -
4403                       rflow->last_qtail)) >= 0)) {
4404                         tcpu = next_cpu;
4405                         rflow = set_rps_cpu(dev, skb, rflow, next_cpu);
4406                 }
4407 
4408                 if (tcpu < nr_cpu_ids && cpu_online(tcpu)) {
4409                         *rflowp = rflow;
4410                         cpu = tcpu;
4411                         goto done;
4412                 }
4413         }
4414 
4415 try_rps:
4416 
4417         if (map) {
4418                 tcpu = map->cpus[reciprocal_scale(hash, map->len)];
4419                 if (cpu_online(tcpu)) {
4420                         cpu = tcpu;
4421                         goto done;
4422                 }
4423         }
4424 
4425 done:
4426         return cpu;
4427 }
4428 
4429 #ifdef CONFIG_RFS_ACCEL
4430 
4431 /**
4432  * rps_may_expire_flow - check whether an RFS hardware filter may be removed
4433  * @dev: Device on which the filter was set
4434  * @rxq_index: RX queue index
4435  * @flow_id: Flow ID passed to ndo_rx_flow_steer()
4436  * @filter_id: Filter ID returned by ndo_rx_flow_steer()
4437  *
4438  * Drivers that implement ndo_rx_flow_steer() should periodically call
4439  * this function for each installed filter and remove the filters for
4440  * which it returns %true.
4441  */
4442 bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index,
4443                          u32 flow_id, u16 filter_id)
4444 {
4445         struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index;
4446         struct rps_dev_flow_table *flow_table;
4447         struct rps_dev_flow *rflow;
4448         bool expire = true;
4449         unsigned int cpu;
4450 
4451         rcu_read_lock();
4452         flow_table = rcu_dereference(rxqueue->rps_flow_table);
4453         if (flow_table && flow_id <= flow_table->mask) {
4454                 rflow = &flow_table->flows[flow_id];
4455                 cpu = READ_ONCE(rflow->cpu);
4456                 if (rflow->filter == filter_id && cpu < nr_cpu_ids &&
4457                     ((int)(per_cpu(softnet_data, cpu).input_queue_head -
4458                            rflow->last_qtail) <
4459                      (int)(10 * flow_table->mask)))
4460                         expire = false;
4461         }
4462         rcu_read_unlock();
4463         return expire;
4464 }
4465 EXPORT_SYMBOL(rps_may_expire_flow);
4466 
4467 #endif /* CONFIG_RFS_ACCEL */
4468 
4469 /* Called from hardirq (IPI) context */
4470 static void rps_trigger_softirq(void *data)
4471 {
4472         struct softnet_data *sd = data;
4473 
4474         ____napi_schedule(sd, &sd->backlog);
4475         sd->received_rps++;
4476 }
4477 
4478 #endif /* CONFIG_RPS */
4479 
4480 /*
4481  * Check if this softnet_data structure is another cpu one
4482  * If yes, queue it to our IPI list and return 1
4483  * If no, return 0
4484  */
4485 static int rps_ipi_queued(struct softnet_data *sd)
4486 {
4487 #ifdef CONFIG_RPS
4488         struct softnet_data *mysd = this_cpu_ptr(&softnet_data);
4489 
4490         if (sd != mysd) {
4491                 sd->rps_ipi_next = mysd->rps_ipi_list;
4492                 mysd->rps_ipi_list = sd;
4493 
4494                 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4495                 return 1;
4496         }
4497 #endif /* CONFIG_RPS */
4498         return 0;
4499 }
4500 
4501 #ifdef CONFIG_NET_FLOW_LIMIT
4502 int netdev_flow_limit_table_len __read_mostly = (1 << 12);
4503 #endif
4504 
4505 static bool skb_flow_limit(struct sk_buff *skb, unsigned int qlen)
4506 {
4507 #ifdef CONFIG_NET_FLOW_LIMIT
4508         struct sd_flow_limit *fl;
4509         struct softnet_data *sd;
4510         unsigned int old_flow, new_flow;
4511 
4512         if (qlen < (netdev_max_backlog >> 1))
4513                 return false;
4514 
4515         sd = this_cpu_ptr(&softnet_data);
4516 
4517         rcu_read_lock();
4518         fl = rcu_dereference(sd->flow_limit);
4519         if (fl) {
4520                 new_flow = skb_get_hash(skb) & (fl->num_buckets - 1);
4521                 old_flow = fl->history[fl->history_head];
4522                 fl->history[fl->history_head] = new_flow;
4523 
4524                 fl->history_head++;
4525                 fl->history_head &= FLOW_LIMIT_HISTORY - 1;
4526 
4527                 if (likely(fl->buckets[old_flow]))
4528                         fl->buckets[old_flow]--;
4529 
4530                 if (++fl->buckets[new_flow] > (FLOW_LIMIT_HISTORY >> 1)) {
4531                         fl->count++;
4532                         rcu_read_unlock();
4533                         return true;
4534                 }
4535         }
4536         rcu_read_unlock();
4537 #endif
4538         return false;
4539 }
4540 
4541 /*
4542  * enqueue_to_backlog is called to queue an skb to a per CPU backlog
4543  * queue (may be a remote CPU queue).
4544  */
4545 static int enqueue_to_backlog(struct sk_buff *skb, int cpu,
4546                               unsigned int *qtail)
4547 {
4548         struct softnet_data *sd;
4549         unsigned long flags;
4550         unsigned int qlen;
4551 
4552         sd = &per_cpu(softnet_data, cpu);
4553 
4554         local_irq_save(flags);
4555 
4556         rps_lock(sd);
4557         if (!netif_running(skb->dev))
4558                 goto drop;
4559         qlen = skb_queue_len(&sd->input_pkt_queue);
4560         if (qlen <= netdev_max_backlog && !skb_flow_limit(skb, qlen)) {
4561                 if (qlen) {
4562 enqueue:
4563                         __skb_queue_tail(&sd->input_pkt_queue, skb);
4564                         input_queue_tail_incr_save(sd, qtail);
4565                         rps_unlock(sd);
4566                         local_irq_restore(flags);
4567                         return NET_RX_SUCCESS;
4568                 }
4569 
4570                 /* Schedule NAPI for backlog device
4571                  * We can use non atomic operation since we own the queue lock
4572                  */
4573                 if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state)) {
4574                         if (!rps_ipi_queued(sd))
4575                                 ____napi_schedule(sd, &sd->backlog);
4576                 }
4577                 goto enqueue;
4578         }
4579 
4580 drop:
4581         sd->dropped++;
4582         rps_unlock(sd);
4583 
4584         local_irq_restore(flags);
4585 
4586         atomic_long_inc(&skb->dev->rx_dropped);
4587         kfree_skb(skb);
4588         return NET_RX_DROP;
4589 }
4590 
4591 static struct netdev_rx_queue *netif_get_rxqueue(struct sk_buff *skb)
4592 {
4593         struct net_device *dev = skb->dev;
4594         struct netdev_rx_queue *rxqueue;
4595 
4596         rxqueue = dev->_rx;
4597 
4598         if (skb_rx_queue_recorded(skb)) {
4599                 u16 index = skb_get_rx_queue(skb);
4600 
4601                 if (unlikely(index >= dev->real_num_rx_queues)) {
4602                         WARN_ONCE(dev->real_num_rx_queues > 1,
4603                                   "%s received packet on queue %u, but number "
4604                                   "of RX queues is %u\n",
4605                                   dev->name, index, dev->real_num_rx_queues);
4606 
4607                         return rxqueue; /* Return first rxqueue */
4608                 }
4609                 rxqueue += index;
4610         }
4611         return rxqueue;
4612 }
4613 
4614 static u32 netif_receive_generic_xdp(struct sk_buff *skb,
4615                                      struct xdp_buff *xdp,
4616                                      struct bpf_prog *xdp_prog)
4617 {
4618         struct netdev_rx_queue *rxqueue;
4619         void *orig_data, *orig_data_end;
4620         u32 metalen, act = XDP_DROP;
4621         __be16 orig_eth_type;
4622         struct ethhdr *eth;
4623         bool orig_bcast;
4624         int hlen, off;
4625         u32 mac_len;
4626 
4627         /* Reinjected packets coming from act_mirred or similar should
4628          * not get XDP generic processing.
4629          */
4630         if (skb_is_redirected(skb))
4631                 return XDP_PASS;
4632 
4633         /* XDP packets must be linear and must have sufficient headroom
4634          * of XDP_PACKET_HEADROOM bytes. This is the guarantee that also
4635          * native XDP provides, thus we need to do it here as well.
4636          */
4637         if (skb_cloned(skb) || skb_is_nonlinear(skb) ||
4638             skb_headroom(skb) < XDP_PACKET_HEADROOM) {
4639                 int hroom = XDP_PACKET_HEADROOM - skb_headroom(skb);
4640                 int troom = skb->tail + skb->data_len - skb->end;
4641 
4642                 /* In case we have to go down the path and also linearize,
4643                  * then lets do the pskb_expand_head() work just once here.
4644                  */
4645                 if (pskb_expand_head(skb,
4646                                      hroom > 0 ? ALIGN(hroom, NET_SKB_PAD) : 0,
4647                                      troom > 0 ? troom + 128 : 0, GFP_ATOMIC))
4648                         goto do_drop;
4649                 if (skb_linearize(skb))
4650                         goto do_drop;
4651         }
4652 
4653         /* The XDP program wants to see the packet starting at the MAC
4654          * header.
4655          */
4656         mac_len = skb->data - skb_mac_header(skb);
4657         hlen = skb_headlen(skb) + mac_len;
4658         xdp->data = skb->data - mac_len;
4659         xdp->data_meta = xdp->data;
4660         xdp->data_end = xdp->data + hlen;
4661         xdp->data_hard_start = skb->data - skb_headroom(skb);
4662 
4663         /* SKB "head" area always have tailroom for skb_shared_info */
4664         xdp->frame_sz  = (void *)skb_end_pointer(skb) - xdp->data_hard_start;
4665         xdp->frame_sz += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
4666 
4667         orig_data_end = xdp->data_end;
4668         orig_data = xdp->data;
4669         eth = (struct ethhdr *)xdp->data;
4670         orig_bcast = is_multicast_ether_addr_64bits(eth->h_dest);
4671         orig_eth_type = eth->h_proto;
4672 
4673         rxqueue = netif_get_rxqueue(skb);
4674         xdp->rxq = &rxqueue->xdp_rxq;
4675 
4676         act = bpf_prog_run_xdp(xdp_prog, xdp);
4677 
4678         /* check if bpf_xdp_adjust_head was used */
4679         off = xdp->data - orig_data;
4680         if (off) {
4681                 if (off > 0)
4682                         __skb_pull(skb, off);
4683                 else if (off < 0)
4684                         __skb_push(skb, -off);
4685 
4686                 skb->mac_header += off;
4687                 skb_reset_network_header(skb);
4688         }
4689 
4690         /* check if bpf_xdp_adjust_tail was used */
4691         off = xdp->data_end - orig_data_end;
4692         if (off != 0) {
4693                 skb_set_tail_pointer(skb, xdp->data_end - xdp->data);
4694                 skb->len += off; /* positive on grow, negative on shrink */
4695         }
4696 
4697         /* check if XDP changed eth hdr such SKB needs update */
4698         eth = (struct ethhdr *)xdp->data;
4699         if ((orig_eth_type != eth->h_proto) ||
4700             (orig_bcast != is_multicast_ether_addr_64bits(eth->h_dest))) {
4701                 __skb_push(skb, ETH_HLEN);
4702                 skb->protocol = eth_type_trans(skb, skb->dev);
4703         }
4704 
4705         switch (act) {
4706         case XDP_REDIRECT:
4707         case XDP_TX:
4708                 __skb_push(skb, mac_len);
4709                 break;
4710         case XDP_PASS:
4711                 metalen = xdp->data - xdp->data_meta;
4712                 if (metalen)
4713                         skb_metadata_set(skb, metalen);
4714                 break;
4715         default:
4716                 bpf_warn_invalid_xdp_action(act);
4717                 fallthrough;
4718         case XDP_ABORTED:
4719                 trace_xdp_exception(skb->dev, xdp_prog, act);
4720                 fallthrough;
4721         case XDP_DROP:
4722         do_drop:
4723                 kfree_skb(skb);
4724                 break;
4725         }
4726 
4727         return act;
4728 }
4729 
4730 /* When doing generic XDP we have to bypass the qdisc layer and the
4731  * network taps in order to match in-driver-XDP behavior.
4732  */
4733 void generic_xdp_tx(struct sk_buff *skb, struct bpf_prog *xdp_prog)
4734 {
4735         struct net_device *dev = skb->dev;
4736         struct netdev_queue *txq;
4737         bool free_skb = true;
4738         int cpu, rc;
4739 
4740         txq = netdev_core_pick_tx(dev, skb, NULL);
4741         cpu = smp_processor_id();
4742         HARD_TX_LOCK(dev, txq, cpu);
4743         if (!netif_xmit_stopped(txq)) {
4744                 rc = netdev_start_xmit(skb, dev, txq, 0);
4745                 if (dev_xmit_complete(rc))
4746                         free_skb = false;
4747         }
4748         HARD_TX_UNLOCK(dev, txq);
4749         if (free_skb) {
4750                 trace_xdp_exception(dev, xdp_prog, XDP_TX);
4751                 kfree_skb(skb);
4752         }
4753 }
4754 
4755 static DEFINE_STATIC_KEY_FALSE(generic_xdp_needed_key);
4756 
4757 int do_xdp_generic(struct bpf_prog *xdp_prog, struct sk_buff *skb)
4758 {
4759         if (xdp_prog) {
4760                 struct xdp_buff xdp;
4761                 u32 act;
4762                 int err;
4763 
4764                 act = netif_receive_generic_xdp(skb, &xdp, xdp_prog);
4765                 if (act != XDP_PASS) {
4766                         switch (act) {
4767                         case XDP_REDIRECT:
4768                                 err = xdp_do_generic_redirect(skb->dev, skb,
4769                                                               &xdp, xdp_prog);
4770                                 if (err)
4771                                         goto out_redir;
4772                                 break;
4773                         case XDP_TX:
4774                                 generic_xdp_tx(skb, xdp_prog);
4775                                 break;
4776                         }
4777                         return XDP_DROP;
4778                 }
4779         }
4780         return XDP_PASS;
4781 out_redir:
4782         kfree_skb(skb);
4783         return XDP_DROP;
4784 }
4785 EXPORT_SYMBOL_GPL(do_xdp_generic);
4786 
4787 static int netif_rx_internal(struct sk_buff *skb)
4788 {
4789         int ret;
4790 
4791         net_timestamp_check(netdev_tstamp_prequeue, skb);
4792 
4793         trace_netif_rx(skb);
4794 
4795 #ifdef CONFIG_RPS
4796         if (static_branch_unlikely(&rps_needed)) {
4797                 struct rps_dev_flow voidflow, *rflow = &voidflow;
4798                 int cpu;
4799 
4800                 preempt_disable();
4801                 rcu_read_lock();
4802 
4803                 cpu = get_rps_cpu(skb->dev, skb, &rflow);
4804                 if (cpu < 0)
4805                         cpu = smp_processor_id();
4806 
4807                 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
4808 
4809                 rcu_read_unlock();
4810                 preempt_enable();
4811         } else
4812 #endif
4813         {
4814                 unsigned int qtail;
4815 
4816                 ret = enqueue_to_backlog(skb, get_cpu(), &qtail);
4817                 put_cpu();
4818         }
4819         return ret;
4820 }
4821 
4822 /**
4823  *      netif_rx        -       post buffer to the network code
4824  *      @skb: buffer to post
4825  *
4826  *      This function receives a packet from a device driver and queues it for
4827  *      the upper (protocol) levels to process.  It always succeeds. The buffer
4828  *      may be dropped during processing for congestion control or by the
4829  *      protocol layers.
4830  *
4831  *      return values:
4832  *      NET_RX_SUCCESS  (no congestion)
4833  *      NET_RX_DROP     (packet was dropped)
4834  *
4835  */
4836 
4837 int netif_rx(struct sk_buff *skb)
4838 {
4839         int ret;
4840 
4841         trace_netif_rx_entry(skb);
4842 
4843         ret = netif_rx_internal(skb);
4844         trace_netif_rx_exit(ret);
4845 
4846         return ret;
4847 }
4848 EXPORT_SYMBOL(netif_rx);
4849 
4850 int netif_rx_ni(struct sk_buff *skb)
4851 {
4852         int err;
4853 
4854         trace_netif_rx_ni_entry(skb);
4855 
4856         preempt_disable();
4857         err = netif_rx_internal(skb);
4858         if (local_softirq_pending())
4859                 do_softirq();
4860         preempt_enable();
4861         trace_netif_rx_ni_exit(err);
4862 
4863         return err;
4864 }
4865 EXPORT_SYMBOL(netif_rx_ni);
4866 
4867 int netif_rx_any_context(struct sk_buff *skb)
4868 {
4869         /*
4870          * If invoked from contexts which do not invoke bottom half
4871          * processing either at return from interrupt or when softrqs are
4872          * reenabled, use netif_rx_ni() which invokes bottomhalf processing
4873          * directly.
4874          */
4875         if (in_interrupt())
4876                 return netif_rx(skb);
4877         else
4878                 return netif_rx_ni(skb);
4879 }
4880 EXPORT_SYMBOL(netif_rx_any_context);
4881 
4882 static __latent_entropy void net_tx_action(struct softirq_action *h)
4883 {
4884         struct softnet_data *sd = this_cpu_ptr(&softnet_data);
4885 
4886         if (sd->completion_queue) {
4887                 struct sk_buff *clist;
4888 
4889                 local_irq_disable();
4890                 clist = sd->completion_queue;
4891                 sd->completion_queue = NULL;
4892                 local_irq_enable();
4893 
4894                 while (clist) {
4895                         struct sk_buff *skb = clist;
4896 
4897                         clist = clist->next;
4898 
4899                         WARN_ON(refcount_read(&skb->users));
4900                         if (likely(get_kfree_skb_cb(skb)->reason == SKB_REASON_CONSUMED))
4901                                 trace_consume_skb(skb);
4902                         else
4903                                 trace_kfree_skb(skb, net_tx_action);
4904 
4905                         if (skb->fclone != SKB_FCLONE_UNAVAILABLE)
4906                                 __kfree_skb(skb);
4907                         else
4908                                 __kfree_skb_defer(skb);
4909                 }
4910 
4911                 __kfree_skb_flush();
4912         }
4913 
4914         if (sd->output_queue) {
4915                 struct Qdisc *head;
4916 
4917                 local_irq_disable();
4918                 head = sd->output_queue;
4919                 sd->output_queue = NULL;
4920                 sd->output_queue_tailp = &sd->output_queue;
4921                 local_irq_enable();
4922 
4923                 while (head) {
4924                         struct Qdisc *q = head;
4925                         spinlock_t *root_lock = NULL;
4926 
4927                         head = head->next_sched;
4928 
4929                         if (!(q->flags & TCQ_F_NOLOCK)) {
4930                                 root_lock = qdisc_lock(q);
4931                                 spin_lock(root_lock);
4932                         }
4933                         /* We need to make sure head->next_sched is read
4934                          * before clearing __QDISC_STATE_SCHED
4935                          */
4936                         smp_mb__before_atomic();
4937                         clear_bit(__QDISC_STATE_SCHED, &q->state);
4938                         qdisc_run(q);
4939                         if (root_lock)
4940                                 spin_unlock(root_lock);
4941                 }
4942         }
4943 
4944         xfrm_dev_backlog(sd);
4945 }
4946 
4947 #if IS_ENABLED(CONFIG_BRIDGE) && IS_ENABLED(CONFIG_ATM_LANE)
4948 /* This hook is defined here for ATM LANE */
4949 int (*br_fdb_test_addr_hook)(struct net_device *dev,
4950                              unsigned char *addr) __read_mostly;
4951 EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook);
4952 #endif
4953 
4954 static inline struct sk_buff *
4955 sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
4956                    struct net_device *orig_dev, bool *another)
4957 {
4958 #ifdef CONFIG_NET_CLS_ACT
4959         struct mini_Qdisc *miniq = rcu_dereference_bh(skb->dev->miniq_ingress);
4960         struct tcf_result cl_res;
4961 
4962         /* If there's at least one ingress present somewhere (so
4963          * we get here via enabled static key), remaining devices
4964          * that are not configured with an ingress qdisc will bail
4965          * out here.
4966          */
4967         if (!miniq)
4968                 return skb;
4969 
4970         if (*pt_prev) {
4971                 *ret = deliver_skb(skb, *pt_prev, orig_dev);
4972                 *pt_prev = NULL;
4973         }
4974 
4975         qdisc_skb_cb(skb)->pkt_len = skb->len;
4976         qdisc_skb_cb(skb)->mru = 0;
4977         skb->tc_at_ingress = 1;
4978         mini_qdisc_bstats_cpu_update(miniq, skb);
4979 
4980         switch (tcf_classify_ingress(skb, miniq->block, miniq->filter_list,
4981                                      &cl_res, false)) {
4982         case TC_ACT_OK:
4983         case TC_ACT_RECLASSIFY:
4984                 skb->tc_index = TC_H_MIN(cl_res.classid);
4985                 break;
4986         case TC_ACT_SHOT:
4987                 mini_qdisc_qstats_cpu_drop(miniq);
4988                 kfree_skb(skb);
4989                 return NULL;
4990         case TC_ACT_STOLEN:
4991         case TC_ACT_QUEUED:
4992         case TC_ACT_TRAP:
4993                 consume_skb(skb);
4994                 return NULL;
4995         case TC_ACT_REDIRECT:
4996                 /* skb_mac_header check was done by cls/act_bpf, so
4997                  * we can safely push the L2 header back before
4998                  * redirecting to another netdev
4999                  */
5000                 __skb_push(skb, skb->mac_len);
5001                 if (skb_do_redirect(skb) == -EAGAIN) {
5002                         __skb_pull(skb, skb->mac_len);
5003                         *another = true;
5004                         break;
5005                 }
5006                 return NULL;
5007         case TC_ACT_CONSUMED:
5008                 return NULL;
5009         default:
5010                 break;
5011         }
5012 #endif /* CONFIG_NET_CLS_ACT */
5013         return skb;
5014 }
5015 
5016 /**
5017  *      netdev_is_rx_handler_busy - check if receive handler is registered
5018  *      @dev: device to check
5019  *
5020  *      Check if a receive handler is already registered for a given device.
5021  *      Return true if there one.
5022  *
5023  *      The caller must hold the rtnl_mutex.
5024  */
5025 bool netdev_is_rx_handler_busy(struct net_device *dev)
5026 {
5027         ASSERT_RTNL();
5028         return dev && rtnl_dereference(dev->rx_handler);
5029 }
5030 EXPORT_SYMBOL_GPL(netdev_is_rx_handler_busy);
5031 
5032 /**
5033  *      netdev_rx_handler_register - register receive handler
5034  *      @dev: device to register a handler for
5035  *      @rx_handler: receive handler to register
5036  *      @rx_handler_data: data pointer that is used by rx handler
5037  *
5038  *      Register a receive handler for a device. This handler will then be
5039  *      called from __netif_receive_skb. A negative errno code is returned
5040  *      on a failure.
5041  *
5042  *      The caller must hold the rtnl_mutex.
5043  *
5044  *      For a general description of rx_handler, see enum rx_handler_result.
5045  */
5046 int netdev_rx_handler_register(struct net_device *dev,
5047                                rx_handler_func_t *rx_handler,
5048                                void *rx_handler_data)
5049 {
5050         if (netdev_is_rx_handler_busy(dev))
5051                 return -EBUSY;
5052 
5053         if (dev->priv_flags & IFF_NO_RX_HANDLER)
5054                 return -EINVAL;
5055 
5056         /* Note: rx_handler_data must be set before rx_handler */
5057         rcu_assign_pointer(dev->rx_handler_data, rx_handler_data);
5058         rcu_assign_pointer(dev->rx_handler, rx_handler);
5059 
5060         return 0;
5061 }
5062 EXPORT_SYMBOL_GPL(netdev_rx_handler_register);
5063 
5064 /**
5065  *      netdev_rx_handler_unregister - unregister receive handler
5066  *      @dev: device to unregister a handler from
5067  *
5068  *      Unregister a receive handler from a device.
5069  *
5070  *      The caller must hold the rtnl_mutex.
5071  */
5072 void netdev_rx_handler_unregister(struct net_device *dev)
5073 {
5074 
5075         ASSERT_RTNL();
5076         RCU_INIT_POINTER(dev->rx_handler, NULL);
5077         /* a reader seeing a non NULL rx_handler in a rcu_read_lock()
5078          * section has a guarantee to see a non NULL rx_handler_data
5079          * as well.
5080          */
5081         synchronize_net();
5082         RCU_INIT_POINTER(dev->rx_handler_data, NULL);
5083 }
5084 EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister);
5085 
5086 /*
5087  * Limit the use of PFMEMALLOC reserves to those protocols that implement
5088  * the special handling of PFMEMALLOC skbs.
5089  */
5090 static bool skb_pfmemalloc_protocol(struct sk_buff *skb)
5091 {
5092         switch (skb->protocol) {
5093         case htons(ETH_P_ARP):
5094         case htons(ETH_P_IP):
5095         case htons(ETH_P_IPV6):
5096         case htons(ETH_P_8021Q):
5097         case htons(ETH_P_8021AD):
5098                 return true;
5099         default:
5100                 return false;
5101         }
5102 }
5103 
5104 static inline int nf_ingress(struct sk_buff *skb, struct packet_type **pt_prev,
5105                              int *ret, struct net_device *orig_dev)
5106 {
5107         if (nf_hook_ingress_active(skb)) {
5108                 int ingress_retval;
5109 
5110                 if (*pt_prev) {
5111                         *ret = deliver_skb(skb, *pt_prev, orig_dev);
5112                         *pt_prev = NULL;
5113                 }
5114 
5115                 rcu_read_lock();
5116                 ingress_retval = nf_hook_ingress(skb);
5117                 rcu_read_unlock();
5118                 return ingress_retval;
5119         }
5120         return 0;
5121 }
5122 
5123 static int __netif_receive_skb_core(struct sk_buff **pskb, bool pfmemalloc,
5124                                     struct packet_type **ppt_prev)
5125 {
5126         struct packet_type *ptype, *pt_prev;
5127         rx_handler_func_t *rx_handler;
5128         struct sk_buff *skb = *pskb;
5129         struct net_device *orig_dev;
5130         bool deliver_exact = false;
5131         int ret = NET_RX_DROP;
5132         __be16 type;
5133 
5134         net_timestamp_check(!netdev_tstamp_prequeue, skb);
5135 
5136         trace_netif_receive_skb(skb);
5137 
5138         orig_dev = skb->dev;
5139 
5140         skb_reset_network_header(skb);
5141         if (!skb_transport_header_was_set(skb))
5142                 skb_reset_transport_header(skb);
5143         skb_reset_mac_len(skb);
5144 
5145         pt_prev = NULL;
5146 
5147 another_round:
5148         skb->skb_iif = skb->dev->ifindex;
5149 
5150         __this_cpu_inc(softnet_data.processed);
5151 
5152         if (static_branch_unlikely(&generic_xdp_needed_key)) {
5153                 int ret2;
5154 
5155                 preempt_disable();
5156                 ret2 = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog), skb);
5157                 preempt_enable();
5158 
5159                 if (ret2 != XDP_PASS) {
5160                         ret = NET_RX_DROP;
5161                         goto out;
5162                 }
5163                 skb_reset_mac_len(skb);
5164         }
5165 
5166         if (skb->protocol == cpu_to_be16(ETH_P_8021Q) ||
5167             skb->protocol == cpu_to_be16(ETH_P_8021AD)) {
5168                 skb = skb_vlan_untag(skb);
5169                 if (unlikely(!skb))
5170                         goto out;
5171         }
5172 
5173         if (skb_skip_tc_classify(skb))
5174                 goto skip_classify;
5175 
5176         if (pfmemalloc)
5177                 goto skip_taps;
5178 
5179         list_for_each_entry_rcu(ptype, &ptype_all, list) {
5180                 if (pt_prev)
5181                         ret = deliver_skb(skb, pt_prev, orig_dev);
5182                 pt_prev = ptype;
5183         }
5184 
5185         list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) {
5186                 if (pt_prev)
5187                         ret = deliver_skb(skb, pt_prev, orig_dev);
5188                 pt_prev = ptype;
5189         }
5190 
5191 skip_taps:
5192 #ifdef CONFIG_NET_INGRESS
5193         if (static_branch_unlikely(&ingress_needed_key)) {
5194                 bool another = false;
5195 
5196                 skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev,
5197                                          &another);
5198                 if (another)
5199                         goto another_round;
5200                 if (!skb)
5201                         goto out;
5202 
5203                 if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0)
5204                         goto out;
5205         }
5206 #endif
5207         skb_reset_redirect(skb);
5208 skip_classify:
5209         if (pfmemalloc && !skb_pfmemalloc_protocol(skb))
5210                 goto drop;
5211 
5212         if (skb_vlan_tag_present(skb)) {
5213                 if (pt_prev) {
5214                         ret = deliver_skb(skb, pt_prev, orig_dev);
5215                         pt_prev = NULL;
5216                 }
5217                 if (vlan_do_receive(&skb))
5218                         goto another_round;
5219                 else if (unlikely(!skb))
5220                         goto out;
5221         }
5222 
5223         rx_handler = rcu_dereference(skb->dev->rx_handler);
5224         if (rx_handler) {
5225                 if (pt_prev) {
5226                         ret = deliver_skb(skb, pt_prev, orig_dev);
5227                         pt_prev = NULL;
5228                 }
5229                 switch (rx_handler(&skb)) {
5230                 case RX_HANDLER_CONSUMED:
5231                         ret = NET_RX_SUCCESS;
5232                         goto out;
5233                 case RX_HANDLER_ANOTHER:
5234                         goto another_round;
5235                 case RX_HANDLER_EXACT:
5236                         deliver_exact = true;
5237                 case RX_HANDLER_PASS:
5238                         break;
5239                 default:
5240                         BUG();
5241                 }
5242         }
5243 
5244         if (unlikely(skb_vlan_tag_present(skb)) && !netdev_uses_dsa(skb->dev)) {
5245 check_vlan_id:
5246                 if (skb_vlan_tag_get_id(skb)) {
5247                         /* Vlan id is non 0 and vlan_do_receive() above couldn't
5248                          * find vlan device.
5249                          */
5250                         skb->pkt_type = PACKET_OTHERHOST;
5251                 } else if (skb->protocol == cpu_to_be16(ETH_P_8021Q) ||
5252                            skb->protocol == cpu_to_be16(ETH_P_8021AD)) {
5253                         /* Outer header is 802.1P with vlan 0, inner header is
5254                          * 802.1Q or 802.1AD and vlan_do_receive() above could
5255                          * not find vlan dev for vlan id 0.
5256                          */
5257                         __vlan_hwaccel_clear_tag(skb);
5258                         skb = skb_vlan_untag(skb);
5259                         if (unlikely(!skb))
5260                                 goto out;
5261                         if (vlan_do_receive(&skb))
5262                                 /* After stripping off 802.1P header with vlan 0
5263                                  * vlan dev is found for inner header.
5264                                  */
5265                                 goto another_round;
5266                         else if (unlikely(!skb))
5267                                 goto out;
5268                         else
5269                                 /* We have stripped outer 802.1P vlan 0 header.
5270                                  * But could not find vlan dev.
5271                                  * check again for vlan id to set OTHERHOST.
5272                                  */
5273                                 goto check_vlan_id;
5274                 }
5275                 /* Note: we might in the future use prio bits
5276                  * and set skb->priority like in vlan_do_receive()
5277                  * For the time being, just ignore Priority Code Point
5278                  */
5279                 __vlan_hwaccel_clear_tag(skb);
5280         }
5281 
5282         type = skb->protocol;
5283 
5284         /* deliver only exact match when indicated */
5285         if (likely(!deliver_exact)) {
5286                 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5287                                        &ptype_base[ntohs(type) &
5288                                                    PTYPE_HASH_MASK]);
5289         }
5290 
5291         deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5292                                &orig_dev->ptype_specific);
5293 
5294         if (unlikely(skb->dev != orig_dev)) {
5295                 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5296                                        &skb->dev->ptype_specific);
5297         }
5298 
5299         if (pt_prev) {
5300                 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
5301                         goto drop;
5302                 *ppt_prev = pt_prev;
5303         } else {
5304 drop:
5305                 if (!deliver_exact)
5306                         atomic_long_inc(&skb->dev->rx_dropped);
5307                 else
5308                         atomic_long_inc(&skb->dev->rx_nohandler);
5309                 kfree_skb(skb);
5310                 /* Jamal, now you will not able to escape explaining
5311                  * me how you were going to use this. :-)
5312                  */
5313                 ret = NET_RX_DROP;
5314         }
5315 
5316 out:
5317         /* The invariant here is that if *ppt_prev is not NULL
5318          * then skb should also be non-NULL.
5319          *
5320          * Apparently *ppt_prev assignment above holds this invariant due to
5321          * skb dereferencing near it.
5322          */
5323         *pskb = skb;
5324         return ret;
5325 }
5326 
5327 static int __netif_receive_skb_one_core(struct sk_buff *skb, bool pfmemalloc)
5328 {
5329         struct net_device *orig_dev = skb->dev;
5330         struct packet_type *pt_prev = NULL;
5331         int ret;
5332 
5333         ret = __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5334         if (pt_prev)
5335                 ret = INDIRECT_CALL_INET(pt_prev->func, ipv6_rcv, ip_rcv, skb,
5336                                          skb->dev, pt_prev, orig_dev);
5337         return ret;
5338 }
5339 
5340 /**
5341  *      netif_receive_skb_core - special purpose version of netif_receive_skb
5342  *      @skb: buffer to process
5343  *
5344  *      More direct receive version of netif_receive_skb().  It should
5345  *      only be used by callers that have a need to skip RPS and Generic XDP.
5346  *      Caller must also take care of handling if ``(page_is_)pfmemalloc``.
5347  *
5348  *      This function may only be called from softirq context and interrupts
5349  *      should be enabled.
5350  *
5351  *      Return values (usually ignored):
5352  *      NET_RX_SUCCESS: no congestion
5353  *      NET_RX_DROP: packet was dropped
5354  */
5355 int netif_receive_skb_core(struct sk_buff *skb)
5356 {
5357         int ret;
5358 
5359         rcu_read_lock();
5360         ret = __netif_receive_skb_one_core(skb, false);
5361         rcu_read_unlock();
5362 
5363         return ret;
5364 }
5365 EXPORT_SYMBOL(netif_receive_skb_core);
5366 
5367 static inline void __netif_receive_skb_list_ptype(struct list_head *head,
5368                                                   struct packet_type *pt_prev,
5369                                                   struct net_device *orig_dev)
5370 {
5371         struct sk_buff *skb, *next;
5372 
5373         if (!pt_prev)
5374                 return;
5375         if (list_empty(head))
5376                 return;
5377         if (pt_prev->list_func != NULL)
5378                 INDIRECT_CALL_INET(pt_prev->list_func, ipv6_list_rcv,
5379                                    ip_list_rcv, head, pt_prev, orig_dev);
5380         else
5381                 list_for_each_entry_safe(skb, next, head, list) {
5382                         skb_list_del_init(skb);
5383                         pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
5384                 }
5385 }
5386 
5387 static void __netif_receive_skb_list_core(struct list_head *head, bool pfmemalloc)
5388 {
5389         /* Fast-path assumptions:
5390          * - There is no RX handler.
5391          * - Only one packet_type matches.
5392          * If either of these fails, we will end up doing some per-packet
5393          * processing in-line, then handling the 'last ptype' for the whole
5394          * sublist.  This can't cause out-of-order delivery to any single ptype,
5395          * because the 'last ptype' must be constant across the sublist, and all
5396          * other ptypes are handled per-packet.
5397          */
5398         /* Current (common) ptype of sublist */
5399         struct packet_type *pt_curr = NULL;
5400         /* Current (common) orig_dev of sublist */
5401         struct net_device *od_curr = NULL;
5402         struct list_head sublist;
5403         struct sk_buff *skb, *next;
5404 
5405         INIT_LIST_HEAD(&sublist);
5406         list_for_each_entry_safe(skb, next, head, list) {
5407                 struct net_device *orig_dev = skb->dev;
5408                 struct packet_type *pt_prev = NULL;
5409 
5410                 skb_list_del_init(skb);
5411                 __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5412                 if (!pt_prev)
5413                         continue;
5414                 if (pt_curr != pt_prev || od_curr != orig_dev) {
5415                         /* dispatch old sublist */
5416                         __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5417                         /* start new sublist */
5418                         INIT_LIST_HEAD(&sublist);
5419                         pt_curr = pt_prev;
5420                         od_curr = orig_dev;
5421                 }
5422                 list_add_tail(&skb->list, &sublist);
5423         }
5424 
5425         /* dispatch final sublist */
5426         __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5427 }
5428 
5429 static int __netif_receive_skb(struct sk_buff *skb)
5430 {
5431         int ret;
5432 
5433         if (sk_memalloc_socks() && skb_pfmemalloc(skb)) {
5434                 unsigned int noreclaim_flag;
5435 
5436                 /*
5437                  * PFMEMALLOC skbs are special, they should
5438                  * - be delivered to SOCK_MEMALLOC sockets only
5439                  * - stay away from userspace
5440                  * - have bounded memory usage
5441                  *
5442                  * Use PF_MEMALLOC as this saves us from propagating the allocation
5443                  * context down to all allocation sites.
5444                  */
5445                 noreclaim_flag = memalloc_noreclaim_save();
5446                 ret = __netif_receive_skb_one_core(skb, true);
5447                 memalloc_noreclaim_restore(noreclaim_flag);
5448         } else
5449                 ret = __netif_receive_skb_one_core(skb, false);
5450 
5451         return ret;
5452 }
5453 
5454 static void __netif_receive_skb_list(struct list_head *head)
5455 {
5456         unsigned long noreclaim_flag = 0;
5457         struct sk_buff *skb, *next;
5458         bool pfmemalloc = false; /* Is current sublist PF_MEMALLOC? */
5459 
5460         list_for_each_entry_safe(skb, next, head, list) {
5461                 if ((sk_memalloc_socks() && skb_pfmemalloc(skb)) != pfmemalloc) {
5462                         struct list_head sublist;
5463 
5464                         /* Handle the previous sublist */
5465                         list_cut_before(&sublist, head, &skb->list);
5466                         if (!list_empty(&sublist))
5467                                 __netif_receive_skb_list_core(&sublist, pfmemalloc);
5468                         pfmemalloc = !pfmemalloc;
5469                         /* See comments in __netif_receive_skb */
5470                         if (pfmemalloc)
5471                                 noreclaim_flag = memalloc_noreclaim_save();
5472                         else
5473                                 memalloc_noreclaim_restore(noreclaim_flag);
5474                 }
5475         }
5476         /* Handle the remaining sublist */
5477         if (!list_empty(head))
5478                 __netif_receive_skb_list_core(head, pfmemalloc);
5479         /* Restore pflags */
5480         if (pfmemalloc)
5481                 memalloc_noreclaim_restore(noreclaim_flag);
5482 }
5483 
5484 static int generic_xdp_install(struct net_device *dev, struct netdev_bpf *xdp)
5485 {
5486         struct bpf_prog *old = rtnl_dereference(dev->xdp_prog);
5487         struct bpf_prog *new = xdp->prog;
5488         int ret = 0;
5489 
5490         if (new) {
5491                 u32 i;
5492 
5493                 mutex_lock(&new->aux->used_maps_mutex);
5494 
5495                 /* generic XDP does not work with DEVMAPs that can
5496                  * have a bpf_prog installed on an entry
5497                  */
5498                 for (i = 0; i < new->aux->used_map_cnt; i++) {
5499                         if (dev_map_can_have_prog(new->aux->used_maps[i]) ||
5500                             cpu_map_prog_allowed(new->aux->used_maps[i])) {
5501                                 mutex_unlock(&new->aux->used_maps_mutex);
5502                                 return -EINVAL;
5503                         }
5504                 }
5505 
5506                 mutex_unlock(&new->aux->used_maps_mutex);
5507         }
5508 
5509         switch (xdp->command) {
5510         case XDP_SETUP_PROG:
5511                 rcu_assign_pointer(dev->xdp_prog, new);
5512                 if (old)
5513                         bpf_prog_put(old);
5514 
5515                 if (old && !new) {
5516                         static_branch_dec(&generic_xdp_needed_key);
5517                 } else if (new && !old) {
5518                         static_branch_inc(&generic_xdp_needed_key);
5519                         dev_disable_lro(dev);
5520                         dev_disable_gro_hw(dev);
5521                 }
5522                 break;
5523 
5524         default:
5525                 ret = -EINVAL;
5526                 break;
5527         }
5528 
5529         return ret;
5530 }
5531 
5532 static int netif_receive_skb_internal(struct sk_buff *skb)
5533 {
5534         int ret;
5535 
5536         net_timestamp_check(netdev_tstamp_prequeue, skb);
5537 
5538         if (skb_defer_rx_timestamp(skb))
5539                 return NET_RX_SUCCESS;
5540 
5541         rcu_read_lock();
5542 #ifdef CONFIG_RPS
5543         if (static_branch_unlikely(&rps_needed)) {
5544                 struct rps_dev_flow voidflow, *rflow = &voidflow;
5545                 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5546 
5547                 if (cpu >= 0) {
5548                         ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5549                         rcu_read_unlock();
5550                         return ret;
5551                 }
5552         }
5553 #endif
5554         ret = __netif_receive_skb(skb);
5555         rcu_read_unlock();
5556         return ret;
5557 }
5558 
5559 static void netif_receive_skb_list_internal(struct list_head *head)
5560 {
5561         struct sk_buff *skb, *next;
5562         struct list_head sublist;
5563 
5564         INIT_LIST_HEAD(&sublist);
5565         list_for_each_entry_safe(skb, next, head, list) {
5566                 net_timestamp_check(netdev_tstamp_prequeue, skb);
5567                 skb_list_del_init(skb);
5568                 if (!skb_defer_rx_timestamp(skb))
5569                         list_add_tail(&skb->list, &sublist);
5570         }
5571         list_splice_init(&sublist, head);
5572 
5573         rcu_read_lock();
5574 #ifdef CONFIG_RPS
5575         if (static_branch_unlikely(&rps_needed)) {
5576                 list_for_each_entry_safe(skb, next, head, list) {
5577                         struct rps_dev_flow voidflow, *rflow = &voidflow;
5578                         int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5579 
5580                         if (cpu >= 0) {
5581                                 /* Will be handled, remove from list */
5582                                 skb_list_del_init(skb);
5583                                 enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5584                         }
5585                 }
5586         }
5587 #endif
5588         __netif_receive_skb_list(head);
5589         rcu_read_unlock();
5590 }
5591 
5592 /**
5593  *      netif_receive_skb - process receive buffer from network
5594  *      @skb: buffer to process
5595  *
5596  *      netif_receive_skb() is the main receive data processing function.
5597  *      It always succeeds. The buffer may be dropped during processing
5598  *      for congestion control or by the protocol layers.
5599  *
5600  *      This function may only be called from softirq context and interrupts
5601  *      should be enabled.
5602  *
5603  *      Return values (usually ignored):
5604  *      NET_RX_SUCCESS: no congestion
5605  *      NET_RX_DROP: packet was dropped
5606  */
5607 int netif_receive_skb(struct sk_buff *skb)
5608 {
5609         int ret;
5610 
5611         trace_netif_receive_skb_entry(skb);
5612 
5613         ret = netif_receive_skb_internal(skb);
5614         trace_netif_receive_skb_exit(ret);
5615 
5616         return ret;
5617 }
5618 EXPORT_SYMBOL(netif_receive_skb);
5619 
5620 /**
5621  *      netif_receive_skb_list - process many receive buffers from network
5622  *      @head: list of skbs to process.
5623  *
5624  *      Since return value of netif_receive_skb() is normally ignored, and
5625  *      wouldn't be meaningful for a list, this function returns void.
5626  *
5627  *      This function may only be called from softirq context and interrupts
5628  *      should be enabled.
5629  */
5630 void netif_receive_skb_list(struct list_head *head)
5631 {
5632         struct sk_buff *skb;
5633 
5634         if (list_empty(head))
5635                 return;
5636         if (trace_netif_receive_skb_list_entry_enabled()) {
5637                 list_for_each_entry(skb, head, list)
5638                         trace_netif_receive_skb_list_entry(skb);
5639         }
5640         netif_receive_skb_list_internal(head);
5641         trace_netif_receive_skb_list_exit(0);
5642 }
5643 EXPORT_SYMBOL(netif_receive_skb_list);
5644 
5645 static DEFINE_PER_CPU(struct work_struct, flush_works);
5646 
5647 /* Network device is going away, flush any packets still pending */
5648 static void flush_backlog(struct work_struct *work)
5649 {
5650         struct sk_buff *skb, *tmp;
5651         struct softnet_data *sd;
5652 
5653         local_bh_disable();
5654         sd = this_cpu_ptr(&softnet_data);
5655 
5656         local_irq_disable();
5657         rps_lock(sd);
5658         skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) {
5659                 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5660                         __skb_unlink(skb, &sd->input_pkt_queue);
5661                         dev_kfree_skb_irq(skb);
5662                         input_queue_head_incr(sd);
5663                 }
5664         }
5665         rps_unlock(sd);
5666         local_irq_enable();
5667 
5668         skb_queue_walk_safe(&sd->process_queue, skb, tmp) {
5669                 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5670                         __skb_unlink(skb, &sd->process_queue);
5671                         kfree_skb(skb);
5672                         input_queue_head_incr(sd);
5673                 }
5674         }
5675         local_bh_enable();
5676 }
5677 
5678 static bool flush_required(int cpu)
5679 {
5680 #if IS_ENABLED(CONFIG_RPS)
5681         struct softnet_data *sd = &per_cpu(softnet_data, cpu);
5682         bool do_flush;
5683 
5684         local_irq_disable();
5685         rps_lock(sd);
5686 
5687         /* as insertion into process_queue happens with the rps lock held,
5688          * process_queue access may race only with dequeue
5689          */
5690         do_flush = !skb_queue_empty(&sd->input_pkt_queue) ||
5691                    !skb_queue_empty_lockless(&sd->process_queue);
5692         rps_unlock(sd);
5693         local_irq_enable();
5694 
5695         return do_flush;
5696 #endif
5697         /* without RPS we can't safely check input_pkt_queue: during a
5698          * concurrent remote skb_queue_splice() we can detect as empty both
5699          * input_pkt_queue and process_queue even if the latter could end-up
5700          * containing a lot of packets.
5701          */
5702         return true;
5703 }
5704 
5705 static void flush_all_backlogs(void)
5706 {
5707         static cpumask_t flush_cpus;
5708         unsigned int cpu;
5709 
5710         /* since we are under rtnl lock protection we can use static data
5711          * for the cpumask and avoid allocating on stack the possibly
5712          * large mask
5713          */
5714         ASSERT_RTNL();
5715 
5716         get_online_cpus();
5717 
5718         cpumask_clear(&flush_cpus);
5719         for_each_online_cpu(cpu) {
5720                 if (flush_required(cpu)) {
5721                         queue_work_on(cpu, system_highpri_wq,
5722                                       per_cpu_ptr(&flush_works, cpu));
5723                         cpumask_set_cpu(cpu, &flush_cpus);
5724                 }
5725         }
5726 
5727         /* we can have in flight packet[s] on the cpus we are not flushing,
5728          * synchronize_net() in rollback_registered_many() will take care of
5729          * them
5730          */
5731         for_each_cpu(cpu, &flush_cpus)
5732                 flush_work(per_cpu_ptr(&flush_works, cpu));
5733 
5734         put_online_cpus();
5735 }
5736 
5737 /* Pass the currently batched GRO_NORMAL SKBs up to the stack. */
5738 static void gro_normal_list(struct napi_struct *napi)
5739 {
5740         if (!napi->rx_count)
5741                 return;
5742         netif_receive_skb_list_internal(&napi->rx_list);
5743         INIT_LIST_HEAD(&napi->rx_list);
5744         napi->rx_count = 0;
5745 }
5746 
5747 /* Queue one GRO_NORMAL SKB up for list processing. If batch size exceeded,
5748  * pass the whole batch up to the stack.
5749  */
5750 static void gro_normal_one(struct napi_struct *napi, struct sk_buff *skb, int segs)
5751 {
5752         list_add_tail(&skb->list, &napi->rx_list);
5753         napi->rx_count += segs;
5754         if (napi->rx_count >= gro_normal_batch)
5755                 gro_normal_list(napi);
5756 }
5757 
5758 INDIRECT_CALLABLE_DECLARE(int inet_gro_complete(struct sk_buff *, int));
5759 INDIRECT_CALLABLE_DECLARE(int ipv6_gro_complete(struct sk_buff *, int));
5760 static int napi_gro_complete(struct napi_struct *napi, struct sk_buff *skb)
5761 {
5762         struct packet_offload *ptype;
5763         __be16 type = skb->protocol;
5764         struct list_head *head = &offload_base;
5765         int err = -ENOENT;
5766 
5767         BUILD_BUG_ON(sizeof(struct napi_gro_cb) > sizeof(skb->cb));
5768 
5769         if (NAPI_GRO_CB(skb)->count == 1) {
5770                 skb_shinfo(skb)->gso_size = 0;
5771                 goto out;
5772         }
5773 
5774         rcu_read_lock();
5775         list_for_each_entry_rcu(ptype, head, list) {
5776                 if (ptype->type != type || !ptype->callbacks.gro_complete)
5777                         continue;
5778 
5779                 err = INDIRECT_CALL_INET(ptype->callbacks.gro_complete,
5780                                          ipv6_gro_complete, inet_gro_complete,
5781                                          skb, 0);
5782                 break;
5783         }
5784         rcu_read_unlock();
5785 
5786         if (err) {
5787                 WARN_ON(&ptype->list == head);
5788                 kfree_skb(skb);
5789                 return NET_RX_SUCCESS;
5790         }
5791 
5792 out:
5793         gro_normal_one(napi, skb, NAPI_GRO_CB(skb)->count);
5794         return NET_RX_SUCCESS;
5795 }
5796 
5797 static void __napi_gro_flush_chain(struct napi_struct *napi, u32 index,
5798                                    bool flush_old)
5799 {
5800         struct list_head *head = &napi->gro_hash[index].list;
5801         struct sk_buff *skb, *p;
5802 
5803         list_for_each_entry_safe_reverse(skb, p, head, list) {
5804                 if (flush_old && NAPI_GRO_CB(skb)->age == jiffies)
5805                         return;
5806                 skb_list_del_init(skb);
5807                 napi_gro_complete(napi, skb);
5808                 napi->gro_hash[index].count--;
5809         }
5810 
5811         if (!napi->gro_hash[index].count)
5812                 __clear_bit(index, &napi->gro_bitmask);
5813 }
5814 
5815 /* napi->gro_hash[].list contains packets ordered by age.
5816  * youngest packets at the head of it.
5817  * Complete skbs in reverse order to reduce latencies.
5818  */
5819 void napi_gro_flush(struct napi_struct *napi, bool flush_old)
5820 {
5821         unsigned long bitmask = napi->gro_bitmask;
5822         unsigned int i, base = ~0U;
5823 
5824         while ((i = ffs(bitmask)) != 0) {
5825                 bitmask >>= i;
5826                 base += i;
5827                 __napi_gro_flush_chain(napi, base, flush_old);
5828         }
5829 }
5830 EXPORT_SYMBOL(napi_gro_flush);
5831 
5832 static struct list_head *gro_list_prepare(struct napi_struct *napi,
5833                                           struct sk_buff *skb)
5834 {
5835         unsigned int maclen = skb->dev->hard_header_len;
5836         u32 hash = skb_get_hash_raw(skb);
5837         struct list_head *head;
5838         struct sk_buff *p;
5839 
5840         head = &napi->gro_hash[hash & (GRO_HASH_BUCKETS - 1)].list;
5841         list_for_each_entry(p, head, list) {
5842                 unsigned long diffs;
5843 
5844                 NAPI_GRO_CB(p)->flush = 0;
5845 
5846                 if (hash != skb_get_hash_raw(p)) {
5847                         NAPI_GRO_CB(p)->same_flow = 0;
5848                         continue;
5849                 }
5850 
5851                 diffs = (unsigned long)p->dev ^ (unsigned long)skb->dev;
5852                 diffs |= skb_vlan_tag_present(p) ^ skb_vlan_tag_present(skb);
5853                 if (skb_vlan_tag_present(p))
5854                         diffs |= skb_vlan_tag_get(p) ^ skb_vlan_tag_get(skb);
5855                 diffs |= skb_metadata_dst_cmp(p, skb);
5856                 diffs |= skb_metadata_differs(p, skb);
5857                 if (maclen == ETH_HLEN)
5858                         diffs |= compare_ether_header(skb_mac_header(p),
5859                                                       skb_mac_header(skb));
5860                 else if (!diffs)
5861                         diffs = memcmp(skb_mac_header(p),
5862                                        skb_mac_header(skb),
5863                                        maclen);
5864                 NAPI_GRO_CB(p)->same_flow = !diffs;
5865         }
5866 
5867         return head;
5868 }
5869 
5870 static inline void skb_gro_reset_offset(struct sk_buff *skb, u32 nhoff)
5871 {
5872         const struct skb_shared_info *pinfo = skb_shinfo(skb);
5873         const skb_frag_t *frag0 = &pinfo->frags[0];
5874 
5875         NAPI_GRO_CB(skb)->data_offset = 0;
5876         NAPI_GRO_CB(skb)->frag0 = NULL;
5877         NAPI_GRO_CB(skb)->frag0_len = 0;
5878 
5879         if (!skb_headlen(skb) && pinfo->nr_frags &&
5880             !PageHighMem(skb_frag_page(frag0)) &&
5881             (!NET_IP_ALIGN || !((skb_frag_off(frag0) + nhoff) & 3))) {
5882                 NAPI_GRO_CB(skb)->frag0 = skb_frag_address(frag0);
5883                 NAPI_GRO_CB(skb)->frag0_len = min_t(unsigned int,
5884                                                     skb_frag_size(frag0),
5885                                                     skb->end - skb->tail);
5886         }
5887 }
5888 
5889 static void gro_pull_from_frag0(struct sk_buff *skb, int grow)
5890 {
5891         struct skb_shared_info *pinfo = skb_shinfo(skb);
5892 
5893         BUG_ON(skb->end - skb->tail < grow);
5894 
5895         memcpy(skb_tail_pointer(skb), NAPI_GRO_CB(skb)->frag0, grow);
5896 
5897         skb->data_len -= grow;
5898         skb->tail += grow;
5899 
5900         skb_frag_off_add(&pinfo->frags[0], grow);
5901         skb_frag_size_sub(&pinfo->frags[0], grow);
5902 
5903         if (unlikely(!skb_frag_size(&pinfo->frags[0]))) {
5904                 skb_frag_unref(skb, 0);
5905                 memmove(pinfo->frags, pinfo->frags + 1,
5906                         --pinfo->nr_frags * sizeof(pinfo->frags[0]));
5907         }
5908 }
5909 
5910 static void gro_flush_oldest(struct napi_struct *napi, struct list_head *head)
5911 {
5912         struct sk_buff *oldest;
5913 
5914         oldest = list_last_entry(head, struct sk_buff, list);
5915 
5916         /* We are called with head length >= MAX_GRO_SKBS, so this is
5917          * impossible.
5918          */
5919         if (WARN_ON_ONCE(!oldest))
5920                 return;
5921 
5922         /* Do not adjust napi->gro_hash[].count, caller is adding a new
5923          * SKB to the chain.
5924          */
5925         skb_list_del_init(oldest);
5926         napi_gro_complete(napi, oldest);
5927 }
5928 
5929 INDIRECT_CALLABLE_DECLARE(struct sk_buff *inet_gro_receive(struct list_head *,
5930                                                            struct sk_buff *));
5931 INDIRECT_CALLABLE_DECLARE(struct sk_buff *ipv6_gro_receive(struct list_head *,
5932                                                            struct sk_buff *));
5933 static enum gro_result dev_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
5934 {
5935         u32 hash = skb_get_hash_raw(skb) & (GRO_HASH_BUCKETS - 1);
5936         struct list_head *head = &offload_base;
5937         struct packet_offload *ptype;
5938         __be16 type = skb->protocol;
5939         struct list_head *gro_head;
5940         struct sk_buff *pp = NULL;
5941         enum gro_result ret;
5942         int same_flow;
5943         int grow;
5944 
5945         if (netif_elide_gro(skb->dev))
5946                 goto normal;
5947 
5948         gro_head = gro_list_prepare(napi, skb);
5949 
5950         rcu_read_lock();
5951         list_for_each_entry_rcu(ptype, head, list) {
5952                 if (ptype->type != type || !ptype->callbacks.gro_receive)
5953                         continue;
5954 
5955                 skb_set_network_header(skb, skb_gro_offset(skb));
5956                 skb_reset_mac_len(skb);
5957                 NAPI_GRO_CB(skb)->same_flow = 0;
5958                 NAPI_GRO_CB(skb)->flush = skb_is_gso(skb) || skb_has_frag_list(skb);
5959                 NAPI_GRO_CB(skb)->free = 0;
5960                 NAPI_GRO_CB(skb)->encap_mark = 0;
5961                 NAPI_GRO_CB(skb)->recursion_counter = 0;
5962                 NAPI_GRO_CB(skb)->is_fou = 0;
5963                 NAPI_GRO_CB(skb)->is_atomic = 1;
5964                 NAPI_GRO_CB(skb)->gro_remcsum_start = 0;
5965 
5966                 /* Setup for GRO checksum validation */
5967                 switch (skb->ip_summed) {
5968                 case CHECKSUM_COMPLETE:
5969                         NAPI_GRO_CB(skb)->csum = skb->csum;
5970                         NAPI_GRO_CB(skb)->csum_valid = 1;
5971                         NAPI_GRO_CB(skb)->csum_cnt = 0;
5972                         break;
5973                 case CHECKSUM_UNNECESSARY:
5974                         NAPI_GRO_CB(skb)->csum_cnt = skb->csum_level + 1;
5975                         NAPI_GRO_CB(skb)->csum_valid = 0;
5976                         break;
5977                 default:
5978                         NAPI_GRO_CB(skb)->csum_cnt = 0;
5979                         NAPI_GRO_CB(skb)->csum_valid = 0;
5980                 }
5981 
5982                 pp = INDIRECT_CALL_INET(ptype->callbacks.gro_receive,
5983                                         ipv6_gro_receive, inet_gro_receive,
5984                                         gro_head, skb);
5985                 break;
5986         }
5987         rcu_read_unlock();
5988 
5989         if (&ptype->list == head)
5990                 goto normal;
5991 
5992         if (PTR_ERR(pp) == -EINPROGRESS) {
5993                 ret = GRO_CONSUMED;
5994                 goto ok;
5995         }
5996 
5997         same_flow = NAPI_GRO_CB(skb)->same_flow;
5998         ret = NAPI_GRO_CB(skb)->free ? GRO_MERGED_FREE : GRO_MERGED;
5999 
6000         if (pp) {
6001                 skb_list_del_init(pp);
6002                 napi_gro_complete(napi, pp);
6003                 napi->gro_hash[hash].count--;
6004         }
6005 
6006         if (same_flow)
6007                 goto ok;
6008 
6009         if (NAPI_GRO_CB(skb)->flush)
6010                 goto normal;
6011 
6012         if (unlikely(napi->gro_hash[hash].count >= MAX_GRO_SKBS)) {
6013                 gro_flush_oldest(napi, gro_head);
6014         } else {
6015                 napi->gro_hash[hash].count++;
6016         }
6017         NAPI_GRO_CB(skb)->count = 1;
6018         NAPI_GRO_CB(skb)->age = jiffies;
6019         NAPI_GRO_CB(skb)->last = skb;
6020         skb_shinfo(skb)->gso_size = skb_gro_len(skb);
6021         list_add(&skb->list, gro_head);
6022         ret = GRO_HELD;
6023 
6024 pull:
6025         grow = skb_gro_offset(skb) - skb_headlen(skb);
6026         if (grow > 0)
6027                 gro_pull_from_frag0(skb, grow);
6028 ok:
6029         if (napi->gro_hash[hash].count) {
6030                 if (!test_bit(hash, &napi->gro_bitmask))
6031                         __set_bit(hash, &napi->gro_bitmask);
6032         } else if (test_bit(hash, &napi->gro_bitmask)) {
6033                 __clear_bit(hash, &napi->gro_bitmask);
6034         }
6035 
6036         return ret;
6037 
6038 normal:
6039         ret = GRO_NORMAL;
6040         goto pull;
6041 }
6042 
6043 struct packet_offload *gro_find_receive_by_type(__be16 type)
6044 {
6045         struct list_head *offload_head = &offload_base;
6046         struct packet_offload *ptype;
6047 
6048         list_for_each_entry_rcu(ptype, offload_head, list) {
6049                 if (ptype->type != type || !ptype->callbacks.gro_receive)
6050                         continue;
6051                 return ptype;
6052         }
6053         return NULL;
6054 }
6055 EXPORT_SYMBOL(gro_find_receive_by_type);
6056 
6057 struct packet_offload *gro_find_complete_by_type(__be16 type)
6058 {
6059         struct list_head *offload_head = &offload_base;
6060         struct packet_offload *ptype;
6061 
6062         list_for_each_entry_rcu(ptype, offload_head, list) {
6063                 if (ptype->type != type || !ptype->callbacks.gro_complete)
6064                         continue;
6065                 return ptype;
6066         }
6067         return NULL;
6068 }
6069 EXPORT_SYMBOL(gro_find_complete_by_type);
6070 
6071 static void napi_skb_free_stolen_head(struct sk_buff *skb)
6072 {
6073         skb_dst_drop(skb);
6074         skb_ext_put(skb);
6075         kmem_cache_free(skbuff_head_cache, skb);
6076 }
6077 
6078 static gro_result_t napi_skb_finish(struct napi_struct *napi,
6079                                     struct sk_buff *skb,
6080                                     gro_result_t ret)
6081 {
6082         switch (ret) {
6083         case GRO_NORMAL:
6084                 gro_normal_one(napi, skb, 1);
6085                 break;
6086 
6087         case GRO_DROP:
6088                 kfree_skb(skb);
6089                 break;
6090 
6091         case GRO_MERGED_FREE:
6092                 if (NAPI_GRO_CB(skb)->free == NAPI_GRO_FREE_STOLEN_HEAD)
6093                         napi_skb_free_stolen_head(skb);
6094                 else
6095                         __kfree_skb(skb);
6096                 break;
6097 
6098         case GRO_HELD:
6099         case GRO_MERGED:
6100         case GRO_CONSUMED:
6101                 break;
6102         }
6103 
6104         return ret;
6105 }
6106 
6107 gro_result_t napi_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
6108 {
6109         gro_result_t ret;
6110 
6111         skb_mark_napi_id(skb, napi);
6112         trace_napi_gro_receive_entry(skb);
6113 
6114         skb_gro_reset_offset(skb, 0);
6115 
6116         ret = napi_skb_finish(napi, skb, dev_gro_receive(napi, skb));
6117         trace_napi_gro_receive_exit(ret);
6118 
6119         return ret;
6120 }
6121 EXPORT_SYMBOL(napi_gro_receive);
6122 
6123 static void napi_reuse_skb(struct napi_struct *napi, struct sk_buff *skb)
6124 {
6125         if (unlikely(skb->pfmemalloc)) {
6126                 consume_skb(skb);
6127                 return;
6128         }
6129         __skb_pull(skb, skb_headlen(skb));
6130         /* restore the reserve we had after netdev_alloc_skb_ip_align() */
6131         skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN - skb_headroom(skb));
6132         __vlan_hwaccel_clear_tag(skb);
6133         skb->dev = napi->dev;
6134         skb->skb_iif = 0;
6135 
6136         /* eth_type_trans() assumes pkt_type is PACKET_HOST */
6137         skb->pkt_type = PACKET_HOST;
6138 
6139         skb->encapsulation = 0;
6140         skb_shinfo(skb)->gso_type = 0;
6141         skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
6142         skb_ext_reset(skb);
6143 
6144         napi->skb = skb;
6145 }
6146 
6147 struct sk_buff *napi_get_frags(struct napi_struct *napi)
6148 {
6149         struct sk_buff *skb = napi->skb;
6150 
6151         if (!skb) {
6152                 skb = napi_alloc_skb(napi, GRO_MAX_HEAD);
6153                 if (skb) {
6154                         napi->skb = skb;
6155                         skb_mark_napi_id(skb, napi);
6156                 }
6157         }
6158         return skb;
6159 }
6160 EXPORT_SYMBOL(napi_get_frags);
6161 
6162 static gro_result_t napi_frags_finish(struct napi_struct *napi,
6163                                       struct sk_buff *skb,
6164                                       gro_result_t ret)
6165 {
6166         switch (ret) {
6167         case GRO_NORMAL:
6168         case GRO_HELD:
6169                 __skb_push(skb, ETH_HLEN);
6170                 skb->protocol = eth_type_trans(skb, skb->dev);
6171                 if (ret == GRO_NORMAL)
6172                         gro_normal_one(napi, skb, 1);
6173                 break;
6174 
6175         case GRO_DROP:
6176                 napi_reuse_skb(napi, skb);
6177                 break;
6178 
6179         case GRO_MERGED_FREE:
6180                 if (NAPI_GRO_CB(skb)->free == NAPI_GRO_FREE_STOLEN_HEAD)
6181                         napi_skb_free_stolen_head(skb);
6182                 else
6183                         napi_reuse_skb(napi, skb);
6184                 break;
6185 
6186         case GRO_MERGED:
6187         case GRO_CONSUMED:
6188                 break;
6189         }
6190 
6191         return ret;
6192 }
6193 
6194 /* Upper GRO stack assumes network header starts at gro_offset=0
6195  * Drivers could call both napi_gro_frags() and napi_gro_receive()
6196  * We copy ethernet header into skb->data to have a common layout.
6197  */
6198 static struct sk_buff *napi_frags_skb(struct napi_struct *napi)
6199 {
6200         struct sk_buff *skb = napi->skb;
6201         const struct ethhdr *eth;
6202         unsigned int hlen = sizeof(*eth);
6203 
6204         napi->skb = NULL;
6205 
6206         skb_reset_mac_header(skb);
6207         skb_gro_reset_offset(skb, hlen);
6208 
6209         if (unlikely(skb_gro_header_hard(skb, hlen))) {
6210                 eth = skb_gro_header_slow(skb, hlen, 0);
6211                 if (unlikely(!eth)) {
6212                         net_warn_ratelimited("%s: dropping impossible skb from %s\n",
6213                                              __func__, napi->dev->name);
6214                         napi_reuse_skb(napi, skb);
6215                         return NULL;
6216                 }
6217         } else {
6218                 eth = (const struct ethhdr *)skb->data;
6219                 gro_pull_from_frag0(skb, hlen);
6220                 NAPI_GRO_CB(skb)->frag0 += hlen;
6221                 NAPI_GRO_CB(skb)->frag0_len -= hlen;
6222         }
6223         __skb_pull(skb, hlen);
6224 
6225         /*
6226          * This works because the only protocols we care about don't require
6227          * special handling.
6228          * We'll fix it up properly in napi_frags_finish()
6229          */
6230         skb->protocol = eth->h_proto;
6231 
6232         return skb;
6233 }
6234 
6235 gro_result_t napi_gro_frags(struct napi_struct *napi)
6236 {
6237         gro_result_t ret;
6238         struct sk_buff *skb = napi_frags_skb(napi);
6239 
6240         if (!skb)
6241                 return GRO_DROP;
6242 
6243         trace_napi_gro_frags_entry(skb);
6244 
6245         ret = napi_frags_finish(napi, skb, dev_gro_receive(napi, skb));
6246         trace_napi_gro_frags_exit(ret);
6247 
6248         return ret;
6249 }
6250 EXPORT_SYMBOL(napi_gro_frags);
6251 
6252 /* Compute the checksum from gro_offset and return the folded value
6253  * after adding in any pseudo checksum.
6254  */
6255 __sum16 __skb_gro_checksum_complete(struct sk_buff *skb)
6256 {
6257         __wsum wsum;
6258         __sum16 sum;
6259 
6260         wsum = skb_checksum(skb, skb_gro_offset(skb), skb_gro_len(skb), 0);
6261 
6262         /* NAPI_GRO_CB(skb)->csum holds pseudo checksum */
6263         sum = csum_fold(csum_add(NAPI_GRO_CB(skb)->csum, wsum));
6264         /* See comments in __skb_checksum_complete(). */
6265         if (likely(!sum)) {
6266                 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
6267                     !skb->csum_complete_sw)
6268                         netdev_rx_csum_fault(skb->dev, skb);
6269         }
6270 
6271         NAPI_GRO_CB(skb)->csum = wsum;
6272         NAPI_GRO_CB(skb)->csum_valid = 1;
6273 
6274         return sum;
6275 }
6276 EXPORT_SYMBOL(__skb_gro_checksum_complete);
6277 
6278 static void net_rps_send_ipi(struct softnet_data *remsd)
6279 {
6280 #ifdef CONFIG_RPS
6281         while (remsd) {
6282                 struct softnet_data *next = remsd->rps_ipi_next;
6283 
6284                 if (cpu_online(remsd->cpu))
6285                         smp_call_function_single_async(remsd->cpu, &remsd->csd);
6286                 remsd = next;
6287         }
6288 #endif
6289 }
6290 
6291 /*
6292  * net_rps_action_and_irq_enable sends any pending IPI's for rps.
6293  * Note: called with local irq disabled, but exits with local irq enabled.
6294  */
6295 static void net_rps_action_and_irq_enable(struct softnet_data *sd)
6296 {
6297 #ifdef CONFIG_RPS
6298         struct softnet_data *remsd = sd->rps_ipi_list;
6299 
6300         if (remsd) {
6301                 sd->rps_ipi_list = NULL;
6302 
6303                 local_irq_enable();
6304 
6305                 /* Send pending IPI's to kick RPS processing on remote cpus. */
6306                 net_rps_send_ipi(remsd);
6307         } else
6308 #endif
6309                 local_irq_enable();
6310 }
6311 
6312 static bool sd_has_rps_ipi_waiting(struct softnet_data *sd)
6313 {
6314 #ifdef CONFIG_RPS
6315         return sd->rps_ipi_list != NULL;
6316 #else
6317         return false;
6318 #endif
6319 }
6320 
6321 static int process_backlog(struct napi_struct *napi, int quota)
6322 {
6323         struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
6324         bool again = true;
6325         int work = 0;
6326 
6327         /* Check if we have pending ipi, its better to send them now,
6328          * not waiting net_rx_action() end.
6329          */
6330         if (sd_has_rps_ipi_waiting(sd)) {
6331                 local_irq_disable();
6332                 net_rps_action_and_irq_enable(sd);
6333         }
6334 
6335         napi->weight = dev_rx_weight;
6336         while (again) {
6337                 struct sk_buff *skb;
6338 
6339                 while ((skb = __skb_dequeue(&sd->process_queue))) {
6340                         rcu_read_lock();
6341                         __netif_receive_skb(skb);
6342                         rcu_read_unlock();
6343                         input_queue_head_incr(sd);
6344                         if (++work >= quota)
6345                                 return work;
6346 
6347                 }
6348 
6349                 local_irq_disable();
6350                 rps_lock(sd);
6351                 if (skb_queue_empty(&sd->input_pkt_queue)) {
6352                         /*
6353                          * Inline a custom version of __napi_complete().
6354                          * only current cpu owns and manipulates this napi,
6355                          * and NAPI_STATE_SCHED is the only possible flag set
6356                          * on backlog.
6357                          * We can use a plain write instead of clear_bit(),
6358                          * and we dont need an smp_mb() memory barrier.
6359                          */
6360                         napi->state = 0;
6361                         again = false;
6362                 } else {
6363                         skb_queue_splice_tail_init(&sd->input_pkt_queue,
6364                                                    &sd->process_queue);
6365                 }
6366                 rps_unlock(sd);
6367                 local_irq_enable();
6368         }
6369 
6370         return work;
6371 }
6372 
6373 /**
6374  * __napi_schedule - schedule for receive
6375  * @n: entry to schedule
6376  *
6377  * The entry's receive function will be scheduled to run.
6378  * Consider using __napi_schedule_irqoff() if hard irqs are masked.
6379  */
6380 void __napi_schedule(struct napi_struct *n)
6381 {
6382         unsigned long flags;
6383 
6384         local_irq_save(flags);
6385         ____napi_schedule(this_cpu_ptr(&softnet_data), n);
6386         local_irq_restore(flags);
6387 }
6388 EXPORT_SYMBOL(__napi_schedule);
6389 
6390 /**
6391  *      napi_schedule_prep - check if napi can be scheduled
6392  *      @n: napi context
6393  *
6394  * Test if NAPI routine is already running, and if not mark
6395  * it as running.  This is used as a condition variable to
6396  * insure only one NAPI poll instance runs.  We also make
6397  * sure there is no pending NAPI disable.
6398  */
6399 bool napi_schedule_prep(struct napi_struct *n)
6400 {
6401         unsigned long val, new;
6402 
6403         do {
6404                 val = READ_ONCE(n->state);
6405                 if (unlikely(val & NAPIF_STATE_DISABLE))
6406                         return false;
6407                 new = val | NAPIF_STATE_SCHED;
6408 
6409                 /* Sets STATE_MISSED bit if STATE_SCHED was already set
6410                  * This was suggested by Alexander Duyck, as compiler
6411                  * emits better code than :
6412                  * if (val & NAPIF_STATE_SCHED)
6413                  *     new |= NAPIF_STATE_MISSED;
6414                  */
6415                 new |= (val & NAPIF_STATE_SCHED) / NAPIF_STATE_SCHED *
6416                                                    NAPIF_STATE_MISSED;
6417         } while (cmpxchg(&n->state, val, new) != val);
6418 
6419         return !(val & NAPIF_STATE_SCHED);
6420 }
6421 EXPORT_SYMBOL(napi_schedule_prep);
6422 
6423 /**
6424  * __napi_schedule_irqoff - schedule for receive
6425  * @n: entry to schedule
6426  *
6427  * Variant of __napi_schedule() assuming hard irqs are masked
6428  */
6429 void __napi_schedule_irqoff(struct napi_struct *n)
6430 {
6431         ____napi_schedule(this_cpu_ptr(&softnet_data), n);
6432 }
6433 EXPORT_SYMBOL(__napi_schedule_irqoff);
6434 
6435 bool napi_complete_done(struct napi_struct *n, int work_done)
6436 {
6437         unsigned long flags, val, new, timeout = 0;
6438         bool ret = true;
6439 
6440         /*
6441          * 1) Don't let napi dequeue from the cpu poll list
6442          *    just in case its running on a different cpu.
6443          * 2) If we are busy polling, do nothing here, we have
6444          *    the guarantee we will be called later.
6445          */
6446         if (unlikely(n->state & (NAPIF_STATE_NPSVC |
6447                                  NAPIF_STATE_IN_BUSY_POLL)))
6448                 return false;
6449 
6450         if (work_done) {
6451                 if (n->gro_bitmask)
6452                         timeout = READ_ONCE(n->dev->gro_flush_timeout);
6453                 n->defer_hard_irqs_count = READ_ONCE(n->dev->napi_defer_hard_irqs);
6454         }
6455         if (n->defer_hard_irqs_count > 0) {
6456                 n->defer_hard_irqs_count--;
6457                 timeout = READ_ONCE(n->dev->gro_flush_timeout);
6458                 if (timeout)
6459                         ret = false;
6460         }
6461         if (n->gro_bitmask) {
6462                 /* When the NAPI instance uses a timeout and keeps postponing
6463                  * it, we need to bound somehow the time packets are kept in
6464                  * the GRO layer
6465                  */
6466                 napi_gro_flush(n, !!timeout);
6467         }
6468 
6469         gro_normal_list(n);
6470 
6471         if (unlikely(!list_empty(&n->poll_list))) {
6472                 /* If n->poll_list is not empty, we need to mask irqs */
6473                 local_irq_save(flags);
6474                 list_del_init(&n->poll_list);
6475                 local_irq_restore(flags);
6476         }
6477 
6478         do {
6479                 val = READ_ONCE(n->state);
6480 
6481                 WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED));
6482 
6483                 new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED |
6484                               NAPIF_STATE_PREFER_BUSY_POLL);
6485 
6486                 /* If STATE_MISSED was set, leave STATE_SCHED set,
6487                  * because we will call napi->poll() one more time.
6488                  * This C code was suggested by Alexander Duyck to help gcc.
6489                  */
6490                 new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED *
6491                                                     NAPIF_STATE_SCHED;
6492         } while (cmpxchg(&n->state, val, new) != val);
6493 
6494         if (unlikely(val & NAPIF_STATE_MISSED)) {
6495                 __napi_schedule(n);
6496                 return false;
6497         }
6498 
6499         if (timeout)
6500                 hrtimer_start(&n->timer, ns_to_ktime(timeout),
6501                               HRTIMER_MODE_REL_PINNED);
6502         return ret;
6503 }
6504 EXPORT_SYMBOL(napi_complete_done);
6505 
6506 /* must be called under rcu_read_lock(), as we dont take a reference */
6507 static struct napi_struct *napi_by_id(unsigned int napi_id)
6508 {
6509         unsigned int hash = napi_id % HASH_SIZE(napi_hash);
6510         struct napi_struct *napi;
6511 
6512         hlist_for_each_entry_rcu(napi, &napi_hash[hash], napi_hash_node)
6513                 if (napi->napi_id == napi_id)
6514                         return napi;
6515 
6516         return NULL;
6517 }
6518 
6519 #if defined(CONFIG_NET_RX_BUSY_POLL)
6520 
6521 static void __busy_poll_stop(struct napi_struct *napi, bool skip_schedule)
6522 {
6523         if (!skip_schedule) {
6524                 gro_normal_list(napi);
6525                 __napi_schedule(napi);
6526                 return;
6527         }
6528 
6529         if (napi->gro_bitmask) {
6530                 /* flush too old packets
6531                  * If HZ < 1000, flush all packets.
6532                  */
6533                 napi_gro_flush(napi, HZ >= 1000);
6534         }
6535 
6536         gro_normal_list(napi);
6537         clear_bit(NAPI_STATE_SCHED, &napi->state);
6538 }
6539 
6540 static void busy_poll_stop(struct napi_struct *napi, void *have_poll_lock, bool prefer_busy_poll,
6541                            u16 budget)
6542 {
6543         bool skip_schedule = false;
6544         unsigned long timeout;
6545         int rc;
6546 
6547         /* Busy polling means there is a high chance device driver hard irq
6548          * could not grab NAPI_STATE_SCHED, and that NAPI_STATE_MISSED was
6549          * set in napi_schedule_prep().
6550          * Since we are about to call napi->poll() once more, we can safely
6551          * clear NAPI_STATE_MISSED.
6552          *
6553          * Note: x86 could use a single "lock and ..." instruction
6554          * to perform these two clear_bit()
6555          */
6556         clear_bit(NAPI_STATE_MISSED, &napi->state);
6557         clear_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state);
6558 
6559         local_bh_disable();
6560 
6561         if (prefer_busy_poll) {
6562                 napi->defer_hard_irqs_count = READ_ONCE(napi->dev->napi_defer_hard_irqs);
6563                 timeout = READ_ONCE(napi->dev->gro_flush_timeout);
6564                 if (napi->defer_hard_irqs_count && timeout) {
6565                         hrtimer_start(&napi->timer, ns_to_ktime(timeout), HRTIMER_MODE_REL_PINNED);
6566                         skip_schedule = true;
6567                 }
6568         }
6569 
6570         /* All we really want here is to re-enable device interrupts.
6571          * Ideally, a new ndo_busy_poll_stop() could avoid another round.
6572          */
6573         rc = napi->poll(napi, budget);
6574         /* We can't gro_normal_list() here, because napi->poll() might have
6575          * rearmed the napi (napi_complete_done()) in which case it could
6576          * already be running on another CPU.
6577          */
6578         trace_napi_poll(napi, rc, budget);
6579         netpoll_poll_unlock(have_poll_lock);
6580         if (rc == budget)
6581                 __busy_poll_stop(napi, skip_schedule);
6582         local_bh_enable();
6583 }
6584 
6585 void napi_busy_loop(unsigned int napi_id,
6586                     bool (*loop_end)(void *, unsigned long),
6587                     void *loop_end_arg, bool prefer_busy_poll, u16 budget)
6588 {
6589         unsigned long start_time = loop_end ? busy_loop_current_time() : 0;
6590         int (*napi_poll)(struct napi_struct *napi, int budget);
6591         void *have_poll_lock = NULL;
6592         struct napi_struct *napi;
6593 
6594 restart:
6595         napi_poll = NULL;
6596 
6597         rcu_read_lock();
6598 
6599         napi = napi_by_id(napi_id);
6600         if (!napi)
6601                 goto out;
6602 
6603         preempt_disable();
6604         for (;;) {
6605                 int work = 0;
6606 
6607                 local_bh_disable();
6608                 if (!napi_poll) {
6609                         unsigned long val = READ_ONCE(napi->state);
6610 
6611                         /* If multiple threads are competing for this napi,
6612                          * we avoid dirtying napi->state as much as we can.
6613                          */
6614                         if (val & (NAPIF_STATE_DISABLE | NAPIF_STATE_SCHED |
6615                                    NAPIF_STATE_IN_BUSY_POLL)) {
6616                                 if (prefer_busy_poll)
6617                                         set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6618                                 goto count;
6619                         }
6620                         if (cmpxchg(&napi->state, val,
6621                                     val | NAPIF_STATE_IN_BUSY_POLL |
6622                                           NAPIF_STATE_SCHED) != val) {
6623                                 if (prefer_busy_poll)
6624                                         set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6625                                 goto count;
6626                         }
6627                         have_poll_lock = netpoll_poll_lock(napi);
6628                         napi_poll = napi->poll;
6629                 }