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