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