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