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