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