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