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