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