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