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