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