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