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