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