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