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