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