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