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