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