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