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