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