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