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