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 (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 if (dev->num_tc) {
2632 /* Do not allow XPS on subordinate device directly */
2633 num_tc = dev->num_tc;
2634 if (num_tc < 0)
2635 return -EINVAL;
2636
2637 /* If queue belongs to subordinate dev use its map */
2638 dev = netdev_get_tx_queue(dev, index)->sb_dev ? : dev;
2639
2640 tc = netdev_txq_to_tc(dev, index);
2641 if (tc < 0)
2642 return -EINVAL;
2643 }
2644
2645 mutex_lock(&xps_map_mutex);
2646 if (is_rxqs_map) {
2647 maps_sz = XPS_RXQ_DEV_MAPS_SIZE(num_tc, dev->num_rx_queues);
2648 dev_maps = xmap_dereference(dev->xps_rxqs_map);
2649 nr_ids = dev->num_rx_queues;
2650 } else {
2651 maps_sz = XPS_CPU_DEV_MAPS_SIZE(num_tc);
2652 if (num_possible_cpus() > 1) {
2653 online_mask = cpumask_bits(cpu_online_mask);
2654 possible_mask = cpumask_bits(cpu_possible_mask);
2655 }
2656 dev_maps = xmap_dereference(dev->xps_cpus_map);
2657 nr_ids = nr_cpu_ids;
2658 }
2659
2660 if (maps_sz < L1_CACHE_BYTES)
2661 maps_sz = L1_CACHE_BYTES;
2662
2663 /* allocate memory for queue storage */
2664 for (j = -1; j = netif_attrmask_next_and(j, online_mask, mask, nr_ids),
2665 j < nr_ids;) {
2666 if (!new_dev_maps)
2667 new_dev_maps = kzalloc(maps_sz, GFP_KERNEL);
2668 if (!new_dev_maps) {
2669 mutex_unlock(&xps_map_mutex);
2670 return -ENOMEM;
2671 }
2672
2673 tci = j * num_tc + tc;
2674 map = dev_maps ? xmap_dereference(dev_maps->attr_map[tci]) :
2675 NULL;
2676
2677 map = expand_xps_map(map, j, index, is_rxqs_map);
2678 if (!map)
2679 goto error;
2680
2681 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2682 }
2683
2684 if (!new_dev_maps)
2685 goto out_no_new_maps;
2686
2687 if (!dev_maps) {
2688 /* Increment static keys at most once per type */
2689 static_key_slow_inc_cpuslocked(&xps_needed);
2690 if (is_rxqs_map)
2691 static_key_slow_inc_cpuslocked(&xps_rxqs_needed);
2692 }
2693
2694 for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2695 j < nr_ids;) {
2696 /* copy maps belonging to foreign traffic classes */
2697 for (i = tc, tci = j * num_tc; dev_maps && i--; tci++) {
2698 /* fill in the new device map from the old device map */
2699 map = xmap_dereference(dev_maps->attr_map[tci]);
2700 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2701 }
2702
2703 /* We need to explicitly update tci as prevous loop
2704 * could break out early if dev_maps is NULL.
2705 */
2706 tci = j * num_tc + tc;
2707
2708 if (netif_attr_test_mask(j, mask, nr_ids) &&
2709 netif_attr_test_online(j, online_mask, nr_ids)) {
2710 /* add tx-queue to CPU/rx-queue maps */
2711 int pos = 0;
2712
2713 map = xmap_dereference(new_dev_maps->attr_map[tci]);
2714 while ((pos < map->len) && (map->queues[pos] != index))
2715 pos++;
2716
2717 if (pos == map->len)
2718 map->queues[map->len++] = index;
2719 #ifdef CONFIG_NUMA
2720 if (!is_rxqs_map) {
2721 if (numa_node_id == -2)
2722 numa_node_id = cpu_to_node(j);
2723 else if (numa_node_id != cpu_to_node(j))
2724 numa_node_id = -1;
2725 }
2726 #endif
2727 } else if (dev_maps) {
2728 /* fill in the new device map from the old device map */
2729 map = xmap_dereference(dev_maps->attr_map[tci]);
2730 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2731 }
2732
2733 /* copy maps belonging to foreign traffic classes */
2734 for (i = num_tc - tc, tci++; dev_maps && --i; tci++) {
2735 /* fill in the new device map from the old device map */
2736 map = xmap_dereference(dev_maps->attr_map[tci]);
2737 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2738 }
2739 }
2740
2741 if (is_rxqs_map)
2742 rcu_assign_pointer(dev->xps_rxqs_map, new_dev_maps);
2743 else
2744 rcu_assign_pointer(dev->xps_cpus_map, new_dev_maps);
2745
2746 /* Cleanup old maps */
2747 if (!dev_maps)
2748 goto out_no_old_maps;
2749
2750 for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2751 j < nr_ids;) {
2752 for (i = num_tc, tci = j * num_tc; i--; tci++) {
2753 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2754 map = xmap_dereference(dev_maps->attr_map[tci]);
2755 if (map && map != new_map)
2756 kfree_rcu(map, rcu);
2757 }
2758 }
2759
2760 kfree_rcu(dev_maps, rcu);
2761
2762 out_no_old_maps:
2763 dev_maps = new_dev_maps;
2764 active = true;
2765
2766 out_no_new_maps:
2767 if (!is_rxqs_map) {
2768 /* update Tx queue numa node */
2769 netdev_queue_numa_node_write(netdev_get_tx_queue(dev, index),
2770 (numa_node_id >= 0) ?
2771 numa_node_id : NUMA_NO_NODE);
2772 }
2773
2774 if (!dev_maps)
2775 goto out_no_maps;
2776
2777 /* removes tx-queue from unused CPUs/rx-queues */
2778 for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2779 j < nr_ids;) {
2780 for (i = tc, tci = j * num_tc; i--; tci++)
2781 active |= remove_xps_queue(dev_maps, tci, index);
2782 if (!netif_attr_test_mask(j, mask, nr_ids) ||
2783 !netif_attr_test_online(j, online_mask, nr_ids))
2784 active |= remove_xps_queue(dev_maps, tci, index);
2785 for (i = num_tc - tc, tci++; --i; tci++)
2786 active |= remove_xps_queue(dev_maps, tci, index);
2787 }
2788
2789 /* free map if not active */
2790 if (!active)
2791 reset_xps_maps(dev, dev_maps, is_rxqs_map);
2792
2793 out_no_maps:
2794 mutex_unlock(&xps_map_mutex);
2795
2796 return 0;
2797 error:
2798 /* remove any maps that we added */
2799 for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2800 j < nr_ids;) {
2801 for (i = num_tc, tci = j * num_tc; i--; tci++) {
2802 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2803 map = dev_maps ?
2804 xmap_dereference(dev_maps->attr_map[tci]) :
2805 NULL;
2806 if (new_map && new_map != map)
2807 kfree(new_map);
2808 }
2809 }
2810
2811 mutex_unlock(&xps_map_mutex);
2812
2813 kfree(new_dev_maps);
2814 return -ENOMEM;
2815 }
2816 EXPORT_SYMBOL_GPL(__netif_set_xps_queue);
2817
netif_set_xps_queue(struct net_device * dev,const struct cpumask * mask,u16 index)2818 int netif_set_xps_queue(struct net_device *dev, const struct cpumask *mask,
2819 u16 index)
2820 {
2821 int ret;
2822
2823 cpus_read_lock();
2824 ret = __netif_set_xps_queue(dev, cpumask_bits(mask), index, false);
2825 cpus_read_unlock();
2826
2827 return ret;
2828 }
2829 EXPORT_SYMBOL(netif_set_xps_queue);
2830
2831 #endif
netdev_unbind_all_sb_channels(struct net_device * dev)2832 static void netdev_unbind_all_sb_channels(struct net_device *dev)
2833 {
2834 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2835
2836 /* Unbind any subordinate channels */
2837 while (txq-- != &dev->_tx[0]) {
2838 if (txq->sb_dev)
2839 netdev_unbind_sb_channel(dev, txq->sb_dev);
2840 }
2841 }
2842
netdev_reset_tc(struct net_device * dev)2843 void netdev_reset_tc(struct net_device *dev)
2844 {
2845 #ifdef CONFIG_XPS
2846 netif_reset_xps_queues_gt(dev, 0);
2847 #endif
2848 netdev_unbind_all_sb_channels(dev);
2849
2850 /* Reset TC configuration of device */
2851 dev->num_tc = 0;
2852 memset(dev->tc_to_txq, 0, sizeof(dev->tc_to_txq));
2853 memset(dev->prio_tc_map, 0, sizeof(dev->prio_tc_map));
2854 }
2855 EXPORT_SYMBOL(netdev_reset_tc);
2856
netdev_set_tc_queue(struct net_device * dev,u8 tc,u16 count,u16 offset)2857 int netdev_set_tc_queue(struct net_device *dev, u8 tc, u16 count, u16 offset)
2858 {
2859 if (tc >= dev->num_tc)
2860 return -EINVAL;
2861
2862 #ifdef CONFIG_XPS
2863 netif_reset_xps_queues(dev, offset, count);
2864 #endif
2865 dev->tc_to_txq[tc].count = count;
2866 dev->tc_to_txq[tc].offset = offset;
2867 return 0;
2868 }
2869 EXPORT_SYMBOL(netdev_set_tc_queue);
2870
netdev_set_num_tc(struct net_device * dev,u8 num_tc)2871 int netdev_set_num_tc(struct net_device *dev, u8 num_tc)
2872 {
2873 if (num_tc > TC_MAX_QUEUE)
2874 return -EINVAL;
2875
2876 #ifdef CONFIG_XPS
2877 netif_reset_xps_queues_gt(dev, 0);
2878 #endif
2879 netdev_unbind_all_sb_channels(dev);
2880
2881 dev->num_tc = num_tc;
2882 return 0;
2883 }
2884 EXPORT_SYMBOL(netdev_set_num_tc);
2885
netdev_unbind_sb_channel(struct net_device * dev,struct net_device * sb_dev)2886 void netdev_unbind_sb_channel(struct net_device *dev,
2887 struct net_device *sb_dev)
2888 {
2889 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2890
2891 #ifdef CONFIG_XPS
2892 netif_reset_xps_queues_gt(sb_dev, 0);
2893 #endif
2894 memset(sb_dev->tc_to_txq, 0, sizeof(sb_dev->tc_to_txq));
2895 memset(sb_dev->prio_tc_map, 0, sizeof(sb_dev->prio_tc_map));
2896
2897 while (txq-- != &dev->_tx[0]) {
2898 if (txq->sb_dev == sb_dev)
2899 txq->sb_dev = NULL;
2900 }
2901 }
2902 EXPORT_SYMBOL(netdev_unbind_sb_channel);
2903
netdev_bind_sb_channel_queue(struct net_device * dev,struct net_device * sb_dev,u8 tc,u16 count,u16 offset)2904 int netdev_bind_sb_channel_queue(struct net_device *dev,
2905 struct net_device *sb_dev,
2906 u8 tc, u16 count, u16 offset)
2907 {
2908 /* Make certain the sb_dev and dev are already configured */
2909 if (sb_dev->num_tc >= 0 || tc >= dev->num_tc)
2910 return -EINVAL;
2911
2912 /* We cannot hand out queues we don't have */
2913 if ((offset + count) > dev->real_num_tx_queues)
2914 return -EINVAL;
2915
2916 /* Record the mapping */
2917 sb_dev->tc_to_txq[tc].count = count;
2918 sb_dev->tc_to_txq[tc].offset = offset;
2919
2920 /* Provide a way for Tx queue to find the tc_to_txq map or
2921 * XPS map for itself.
2922 */
2923 while (count--)
2924 netdev_get_tx_queue(dev, count + offset)->sb_dev = sb_dev;
2925
2926 return 0;
2927 }
2928 EXPORT_SYMBOL(netdev_bind_sb_channel_queue);
2929
netdev_set_sb_channel(struct net_device * dev,u16 channel)2930 int netdev_set_sb_channel(struct net_device *dev, u16 channel)
2931 {
2932 /* Do not use a multiqueue device to represent a subordinate channel */
2933 if (netif_is_multiqueue(dev))
2934 return -ENODEV;
2935
2936 /* We allow channels 1 - 32767 to be used for subordinate channels.
2937 * Channel 0 is meant to be "native" mode and used only to represent
2938 * the main root device. We allow writing 0 to reset the device back
2939 * to normal mode after being used as a subordinate channel.
2940 */
2941 if (channel > S16_MAX)
2942 return -EINVAL;
2943
2944 dev->num_tc = -channel;
2945
2946 return 0;
2947 }
2948 EXPORT_SYMBOL(netdev_set_sb_channel);
2949
2950 /*
2951 * Routine to help set real_num_tx_queues. To avoid skbs mapped to queues
2952 * greater than real_num_tx_queues stale skbs on the qdisc must be flushed.
2953 */
netif_set_real_num_tx_queues(struct net_device * dev,unsigned int txq)2954 int netif_set_real_num_tx_queues(struct net_device *dev, unsigned int txq)
2955 {
2956 bool disabling;
2957 int rc;
2958
2959 disabling = txq < dev->real_num_tx_queues;
2960
2961 if (txq < 1 || txq > dev->num_tx_queues)
2962 return -EINVAL;
2963
2964 if (dev->reg_state == NETREG_REGISTERED ||
2965 dev->reg_state == NETREG_UNREGISTERING) {
2966 ASSERT_RTNL();
2967
2968 rc = netdev_queue_update_kobjects(dev, dev->real_num_tx_queues,
2969 txq);
2970 if (rc)
2971 return rc;
2972
2973 if (dev->num_tc)
2974 netif_setup_tc(dev, txq);
2975
2976 dev->real_num_tx_queues = txq;
2977
2978 if (disabling) {
2979 synchronize_net();
2980 qdisc_reset_all_tx_gt(dev, txq);
2981 #ifdef CONFIG_XPS
2982 netif_reset_xps_queues_gt(dev, txq);
2983 #endif
2984 }
2985 } else {
2986 dev->real_num_tx_queues = txq;
2987 }
2988
2989 return 0;
2990 }
2991 EXPORT_SYMBOL(netif_set_real_num_tx_queues);
2992
2993 #ifdef CONFIG_SYSFS
2994 /**
2995 * netif_set_real_num_rx_queues - set actual number of RX queues used
2996 * @dev: Network device
2997 * @rxq: Actual number of RX queues
2998 *
2999 * This must be called either with the rtnl_lock held or before
3000 * registration of the net device. Returns 0 on success, or a
3001 * negative error code. If called before registration, it always
3002 * succeeds.
3003 */
netif_set_real_num_rx_queues(struct net_device * dev,unsigned int rxq)3004 int netif_set_real_num_rx_queues(struct net_device *dev, unsigned int rxq)
3005 {
3006 int rc;
3007
3008 if (rxq < 1 || rxq > dev->num_rx_queues)
3009 return -EINVAL;
3010
3011 if (dev->reg_state == NETREG_REGISTERED) {
3012 ASSERT_RTNL();
3013
3014 rc = net_rx_queue_update_kobjects(dev, dev->real_num_rx_queues,
3015 rxq);
3016 if (rc)
3017 return rc;
3018 }
3019
3020 dev->real_num_rx_queues = rxq;
3021 return 0;
3022 }
3023 EXPORT_SYMBOL(netif_set_real_num_rx_queues);
3024 #endif
3025
3026 /**
3027 * netif_get_num_default_rss_queues - default number of RSS queues
3028 *
3029 * This routine should set an upper limit on the number of RSS queues
3030 * used by default by multiqueue devices.
3031 */
netif_get_num_default_rss_queues(void)3032 int netif_get_num_default_rss_queues(void)
3033 {
3034 return is_kdump_kernel() ?
3035 1 : min_t(int, DEFAULT_MAX_NUM_RSS_QUEUES, num_online_cpus());
3036 }
3037 EXPORT_SYMBOL(netif_get_num_default_rss_queues);
3038
__netif_reschedule(struct Qdisc * q)3039 static void __netif_reschedule(struct Qdisc *q)
3040 {
3041 struct softnet_data *sd;
3042 unsigned long flags;
3043
3044 local_irq_save(flags);
3045 sd = this_cpu_ptr(&softnet_data);
3046 q->next_sched = NULL;
3047 *sd->output_queue_tailp = q;
3048 sd->output_queue_tailp = &q->next_sched;
3049 raise_softirq_irqoff(NET_TX_SOFTIRQ);
3050 local_irq_restore(flags);
3051 }
3052
__netif_schedule(struct Qdisc * q)3053 void __netif_schedule(struct Qdisc *q)
3054 {
3055 if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state))
3056 __netif_reschedule(q);
3057 }
3058 EXPORT_SYMBOL(__netif_schedule);
3059
3060 struct dev_kfree_skb_cb {
3061 enum skb_free_reason reason;
3062 };
3063
get_kfree_skb_cb(const struct sk_buff * skb)3064 static struct dev_kfree_skb_cb *get_kfree_skb_cb(const struct sk_buff *skb)
3065 {
3066 return (struct dev_kfree_skb_cb *)skb->cb;
3067 }
3068
netif_schedule_queue(struct netdev_queue * txq)3069 void netif_schedule_queue(struct netdev_queue *txq)
3070 {
3071 rcu_read_lock();
3072 if (!netif_xmit_stopped(txq)) {
3073 struct Qdisc *q = rcu_dereference(txq->qdisc);
3074
3075 __netif_schedule(q);
3076 }
3077 rcu_read_unlock();
3078 }
3079 EXPORT_SYMBOL(netif_schedule_queue);
3080
netif_tx_wake_queue(struct netdev_queue * dev_queue)3081 void netif_tx_wake_queue(struct netdev_queue *dev_queue)
3082 {
3083 if (test_and_clear_bit(__QUEUE_STATE_DRV_XOFF, &dev_queue->state)) {
3084 struct Qdisc *q;
3085
3086 rcu_read_lock();
3087 q = rcu_dereference(dev_queue->qdisc);
3088 __netif_schedule(q);
3089 rcu_read_unlock();
3090 }
3091 }
3092 EXPORT_SYMBOL(netif_tx_wake_queue);
3093
__dev_kfree_skb_irq(struct sk_buff * skb,enum skb_free_reason reason)3094 void __dev_kfree_skb_irq(struct sk_buff *skb, enum skb_free_reason reason)
3095 {
3096 unsigned long flags;
3097
3098 if (unlikely(!skb))
3099 return;
3100
3101 if (likely(refcount_read(&skb->users) == 1)) {
3102 smp_rmb();
3103 refcount_set(&skb->users, 0);
3104 } else if (likely(!refcount_dec_and_test(&skb->users))) {
3105 return;
3106 }
3107 get_kfree_skb_cb(skb)->reason = reason;
3108 local_irq_save(flags);
3109 skb->next = __this_cpu_read(softnet_data.completion_queue);
3110 __this_cpu_write(softnet_data.completion_queue, skb);
3111 raise_softirq_irqoff(NET_TX_SOFTIRQ);
3112 local_irq_restore(flags);
3113 }
3114 EXPORT_SYMBOL(__dev_kfree_skb_irq);
3115
__dev_kfree_skb_any(struct sk_buff * skb,enum skb_free_reason reason)3116 void __dev_kfree_skb_any(struct sk_buff *skb, enum skb_free_reason reason)
3117 {
3118 if (in_irq() || irqs_disabled())
3119 __dev_kfree_skb_irq(skb, reason);
3120 else
3121 dev_kfree_skb(skb);
3122 }
3123 EXPORT_SYMBOL(__dev_kfree_skb_any);
3124
3125
3126 /**
3127 * netif_device_detach - mark device as removed
3128 * @dev: network device
3129 *
3130 * Mark device as removed from system and therefore no longer available.
3131 */
netif_device_detach(struct net_device * dev)3132 void netif_device_detach(struct net_device *dev)
3133 {
3134 if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) &&
3135 netif_running(dev)) {
3136 netif_tx_stop_all_queues(dev);
3137 }
3138 }
3139 EXPORT_SYMBOL(netif_device_detach);
3140
3141 /**
3142 * netif_device_attach - mark device as attached
3143 * @dev: network device
3144 *
3145 * Mark device as attached from system and restart if needed.
3146 */
netif_device_attach(struct net_device * dev)3147 void netif_device_attach(struct net_device *dev)
3148 {
3149 if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) &&
3150 netif_running(dev)) {
3151 netif_tx_wake_all_queues(dev);
3152 __netdev_watchdog_up(dev);
3153 }
3154 }
3155 EXPORT_SYMBOL(netif_device_attach);
3156
3157 /*
3158 * Returns a Tx hash based on the given packet descriptor a Tx queues' number
3159 * to be used as a distribution range.
3160 */
skb_tx_hash(const struct net_device * dev,const struct net_device * sb_dev,struct sk_buff * skb)3161 static u16 skb_tx_hash(const struct net_device *dev,
3162 const struct net_device *sb_dev,
3163 struct sk_buff *skb)
3164 {
3165 u32 hash;
3166 u16 qoffset = 0;
3167 u16 qcount = dev->real_num_tx_queues;
3168
3169 if (dev->num_tc) {
3170 u8 tc = netdev_get_prio_tc_map(dev, skb->priority);
3171
3172 qoffset = sb_dev->tc_to_txq[tc].offset;
3173 qcount = sb_dev->tc_to_txq[tc].count;
3174 if (unlikely(!qcount)) {
3175 net_warn_ratelimited("%s: invalid qcount, qoffset %u for tc %u\n",
3176 sb_dev->name, qoffset, tc);
3177 qoffset = 0;
3178 qcount = dev->real_num_tx_queues;
3179 }
3180 }
3181
3182 if (skb_rx_queue_recorded(skb)) {
3183 hash = skb_get_rx_queue(skb);
3184 if (hash >= qoffset)
3185 hash -= qoffset;
3186 while (unlikely(hash >= qcount))
3187 hash -= qcount;
3188 return hash + qoffset;
3189 }
3190
3191 return (u16) reciprocal_scale(skb_get_hash(skb), qcount) + qoffset;
3192 }
3193
skb_warn_bad_offload(const struct sk_buff * skb)3194 static void skb_warn_bad_offload(const struct sk_buff *skb)
3195 {
3196 static const netdev_features_t null_features;
3197 struct net_device *dev = skb->dev;
3198 const char *name = "";
3199
3200 if (!net_ratelimit())
3201 return;
3202
3203 if (dev) {
3204 if (dev->dev.parent)
3205 name = dev_driver_string(dev->dev.parent);
3206 else
3207 name = netdev_name(dev);
3208 }
3209 skb_dump(KERN_WARNING, skb, false);
3210 WARN(1, "%s: caps=(%pNF, %pNF)\n",
3211 name, dev ? &dev->features : &null_features,
3212 skb->sk ? &skb->sk->sk_route_caps : &null_features);
3213 }
3214
3215 /*
3216 * Invalidate hardware checksum when packet is to be mangled, and
3217 * complete checksum manually on outgoing path.
3218 */
skb_checksum_help(struct sk_buff * skb)3219 int skb_checksum_help(struct sk_buff *skb)
3220 {
3221 __wsum csum;
3222 int ret = 0, offset;
3223
3224 if (skb->ip_summed == CHECKSUM_COMPLETE)
3225 goto out_set_summed;
3226
3227 if (unlikely(skb_shinfo(skb)->gso_size)) {
3228 skb_warn_bad_offload(skb);
3229 return -EINVAL;
3230 }
3231
3232 /* Before computing a checksum, we should make sure no frag could
3233 * be modified by an external entity : checksum could be wrong.
3234 */
3235 if (skb_has_shared_frag(skb)) {
3236 ret = __skb_linearize(skb);
3237 if (ret)
3238 goto out;
3239 }
3240
3241 offset = skb_checksum_start_offset(skb);
3242 BUG_ON(offset >= skb_headlen(skb));
3243 csum = skb_checksum(skb, offset, skb->len - offset, 0);
3244
3245 offset += skb->csum_offset;
3246 BUG_ON(offset + sizeof(__sum16) > skb_headlen(skb));
3247
3248 ret = skb_ensure_writable(skb, offset + sizeof(__sum16));
3249 if (ret)
3250 goto out;
3251
3252 *(__sum16 *)(skb->data + offset) = csum_fold(csum) ?: CSUM_MANGLED_0;
3253 out_set_summed:
3254 skb->ip_summed = CHECKSUM_NONE;
3255 out:
3256 return ret;
3257 }
3258 EXPORT_SYMBOL(skb_checksum_help);
3259
skb_crc32c_csum_help(struct sk_buff * skb)3260 int skb_crc32c_csum_help(struct sk_buff *skb)
3261 {
3262 __le32 crc32c_csum;
3263 int ret = 0, offset, start;
3264
3265 if (skb->ip_summed != CHECKSUM_PARTIAL)
3266 goto out;
3267
3268 if (unlikely(skb_is_gso(skb)))
3269 goto out;
3270
3271 /* Before computing a checksum, we should make sure no frag could
3272 * be modified by an external entity : checksum could be wrong.
3273 */
3274 if (unlikely(skb_has_shared_frag(skb))) {
3275 ret = __skb_linearize(skb);
3276 if (ret)
3277 goto out;
3278 }
3279 start = skb_checksum_start_offset(skb);
3280 offset = start + offsetof(struct sctphdr, checksum);
3281 if (WARN_ON_ONCE(offset >= skb_headlen(skb))) {
3282 ret = -EINVAL;
3283 goto out;
3284 }
3285
3286 ret = skb_ensure_writable(skb, offset + sizeof(__le32));
3287 if (ret)
3288 goto out;
3289
3290 crc32c_csum = cpu_to_le32(~__skb_checksum(skb, start,
3291 skb->len - start, ~(__u32)0,
3292 crc32c_csum_stub));
3293 *(__le32 *)(skb->data + offset) = crc32c_csum;
3294 skb->ip_summed = CHECKSUM_NONE;
3295 skb->csum_not_inet = 0;
3296 out:
3297 return ret;
3298 }
3299
skb_network_protocol(struct sk_buff * skb,int * depth)3300 __be16 skb_network_protocol(struct sk_buff *skb, int *depth)
3301 {
3302 __be16 type = skb->protocol;
3303
3304 /* Tunnel gso handlers can set protocol to ethernet. */
3305 if (type == htons(ETH_P_TEB)) {
3306 struct ethhdr *eth;
3307
3308 if (unlikely(!pskb_may_pull(skb, sizeof(struct ethhdr))))
3309 return 0;
3310
3311 eth = (struct ethhdr *)skb->data;
3312 type = eth->h_proto;
3313 }
3314
3315 return __vlan_get_protocol(skb, type, depth);
3316 }
3317
3318 /**
3319 * skb_mac_gso_segment - mac layer segmentation handler.
3320 * @skb: buffer to segment
3321 * @features: features for the output path (see dev->features)
3322 */
skb_mac_gso_segment(struct sk_buff * skb,netdev_features_t features)3323 struct sk_buff *skb_mac_gso_segment(struct sk_buff *skb,
3324 netdev_features_t features)
3325 {
3326 struct sk_buff *segs = ERR_PTR(-EPROTONOSUPPORT);
3327 struct packet_offload *ptype;
3328 int vlan_depth = skb->mac_len;
3329 __be16 type = skb_network_protocol(skb, &vlan_depth);
3330
3331 if (unlikely(!type))
3332 return ERR_PTR(-EINVAL);
3333
3334 __skb_pull(skb, vlan_depth);
3335
3336 rcu_read_lock();
3337 list_for_each_entry_rcu(ptype, &offload_base, list) {
3338 if (ptype->type == type && ptype->callbacks.gso_segment) {
3339 segs = ptype->callbacks.gso_segment(skb, features);
3340 break;
3341 }
3342 }
3343 rcu_read_unlock();
3344
3345 __skb_push(skb, skb->data - skb_mac_header(skb));
3346
3347 return segs;
3348 }
3349 EXPORT_SYMBOL(skb_mac_gso_segment);
3350
3351
3352 /* openvswitch calls this on rx path, so we need a different check.
3353 */
skb_needs_check(struct sk_buff * skb,bool tx_path)3354 static inline bool skb_needs_check(struct sk_buff *skb, bool tx_path)
3355 {
3356 if (tx_path)
3357 return skb->ip_summed != CHECKSUM_PARTIAL &&
3358 skb->ip_summed != CHECKSUM_UNNECESSARY;
3359
3360 return skb->ip_summed == CHECKSUM_NONE;
3361 }
3362
3363 /**
3364 * __skb_gso_segment - Perform segmentation on skb.
3365 * @skb: buffer to segment
3366 * @features: features for the output path (see dev->features)
3367 * @tx_path: whether it is called in TX path
3368 *
3369 * This function segments the given skb and returns a list of segments.
3370 *
3371 * It may return NULL if the skb requires no segmentation. This is
3372 * only possible when GSO is used for verifying header integrity.
3373 *
3374 * Segmentation preserves SKB_GSO_CB_OFFSET bytes of previous skb cb.
3375 */
__skb_gso_segment(struct sk_buff * skb,netdev_features_t features,bool tx_path)3376 struct sk_buff *__skb_gso_segment(struct sk_buff *skb,
3377 netdev_features_t features, bool tx_path)
3378 {
3379 struct sk_buff *segs;
3380
3381 if (unlikely(skb_needs_check(skb, tx_path))) {
3382 int err;
3383
3384 /* We're going to init ->check field in TCP or UDP header */
3385 err = skb_cow_head(skb, 0);
3386 if (err < 0)
3387 return ERR_PTR(err);
3388 }
3389
3390 /* Only report GSO partial support if it will enable us to
3391 * support segmentation on this frame without needing additional
3392 * work.
3393 */
3394 if (features & NETIF_F_GSO_PARTIAL) {
3395 netdev_features_t partial_features = NETIF_F_GSO_ROBUST;
3396 struct net_device *dev = skb->dev;
3397
3398 partial_features |= dev->features & dev->gso_partial_features;
3399 if (!skb_gso_ok(skb, features | partial_features))
3400 features &= ~NETIF_F_GSO_PARTIAL;
3401 }
3402
3403 BUILD_BUG_ON(SKB_GSO_CB_OFFSET +
3404 sizeof(*SKB_GSO_CB(skb)) > sizeof(skb->cb));
3405
3406 SKB_GSO_CB(skb)->mac_offset = skb_headroom(skb);
3407 SKB_GSO_CB(skb)->encap_level = 0;
3408
3409 skb_reset_mac_header(skb);
3410 skb_reset_mac_len(skb);
3411
3412 segs = skb_mac_gso_segment(skb, features);
3413
3414 if (segs != skb && unlikely(skb_needs_check(skb, tx_path) && !IS_ERR(segs)))
3415 skb_warn_bad_offload(skb);
3416
3417 return segs;
3418 }
3419 EXPORT_SYMBOL(__skb_gso_segment);
3420
3421 /* Take action when hardware reception checksum errors are detected. */
3422 #ifdef CONFIG_BUG
netdev_rx_csum_fault(struct net_device * dev,struct sk_buff * skb)3423 void netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
3424 {
3425 if (net_ratelimit()) {
3426 pr_err("%s: hw csum failure\n", dev ? dev->name : "<unknown>");
3427 skb_dump(KERN_ERR, skb, true);
3428 dump_stack();
3429 }
3430 }
3431 EXPORT_SYMBOL(netdev_rx_csum_fault);
3432 #endif
3433
3434 /* XXX: check that highmem exists at all on the given machine. */
illegal_highdma(struct net_device * dev,struct sk_buff * skb)3435 static int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
3436 {
3437 #ifdef CONFIG_HIGHMEM
3438 int i;
3439
3440 if (!(dev->features & NETIF_F_HIGHDMA)) {
3441 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3442 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3443
3444 if (PageHighMem(skb_frag_page(frag)))
3445 return 1;
3446 }
3447 }
3448 #endif
3449 return 0;
3450 }
3451
3452 /* If MPLS offload request, verify we are testing hardware MPLS features
3453 * instead of standard features for the netdev.
3454 */
3455 #if IS_ENABLED(CONFIG_NET_MPLS_GSO)
net_mpls_features(struct sk_buff * skb,netdev_features_t features,__be16 type)3456 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3457 netdev_features_t features,
3458 __be16 type)
3459 {
3460 if (eth_p_mpls(type))
3461 features &= skb->dev->mpls_features;
3462
3463 return features;
3464 }
3465 #else
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 return features;
3471 }
3472 #endif
3473
harmonize_features(struct sk_buff * skb,netdev_features_t features)3474 static netdev_features_t harmonize_features(struct sk_buff *skb,
3475 netdev_features_t features)
3476 {
3477 __be16 type;
3478
3479 type = skb_network_protocol(skb, NULL);
3480 features = net_mpls_features(skb, features, type);
3481
3482 if (skb->ip_summed != CHECKSUM_NONE &&
3483 !can_checksum_protocol(features, type)) {
3484 features &= ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
3485 }
3486 if (illegal_highdma(skb->dev, skb))
3487 features &= ~NETIF_F_SG;
3488
3489 return features;
3490 }
3491
passthru_features_check(struct sk_buff * skb,struct net_device * dev,netdev_features_t features)3492 netdev_features_t passthru_features_check(struct sk_buff *skb,
3493 struct net_device *dev,
3494 netdev_features_t features)
3495 {
3496 return features;
3497 }
3498 EXPORT_SYMBOL(passthru_features_check);
3499
dflt_features_check(struct sk_buff * skb,struct net_device * dev,netdev_features_t features)3500 static netdev_features_t dflt_features_check(struct sk_buff *skb,
3501 struct net_device *dev,
3502 netdev_features_t features)
3503 {
3504 return vlan_features_check(skb, features);
3505 }
3506
gso_features_check(const struct sk_buff * skb,struct net_device * dev,netdev_features_t features)3507 static netdev_features_t gso_features_check(const struct sk_buff *skb,
3508 struct net_device *dev,
3509 netdev_features_t features)
3510 {
3511 u16 gso_segs = skb_shinfo(skb)->gso_segs;
3512
3513 if (gso_segs > dev->gso_max_segs)
3514 return features & ~NETIF_F_GSO_MASK;
3515
3516 /* Support for GSO partial features requires software
3517 * intervention before we can actually process the packets
3518 * so we need to strip support for any partial features now
3519 * and we can pull them back in after we have partially
3520 * segmented the frame.
3521 */
3522 if (!(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL))
3523 features &= ~dev->gso_partial_features;
3524
3525 /* Make sure to clear the IPv4 ID mangling feature if the
3526 * IPv4 header has the potential to be fragmented.
3527 */
3528 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) {
3529 struct iphdr *iph = skb->encapsulation ?
3530 inner_ip_hdr(skb) : ip_hdr(skb);
3531
3532 if (!(iph->frag_off & htons(IP_DF)))
3533 features &= ~NETIF_F_TSO_MANGLEID;
3534 }
3535
3536 return features;
3537 }
3538
netif_skb_features(struct sk_buff * skb)3539 netdev_features_t netif_skb_features(struct sk_buff *skb)
3540 {
3541 struct net_device *dev = skb->dev;
3542 netdev_features_t features = dev->features;
3543
3544 if (skb_is_gso(skb))
3545 features = gso_features_check(skb, dev, features);
3546
3547 /* If encapsulation offload request, verify we are testing
3548 * hardware encapsulation features instead of standard
3549 * features for the netdev
3550 */
3551 if (skb->encapsulation)
3552 features &= dev->hw_enc_features;
3553
3554 if (skb_vlan_tagged(skb))
3555 features = netdev_intersect_features(features,
3556 dev->vlan_features |
3557 NETIF_F_HW_VLAN_CTAG_TX |
3558 NETIF_F_HW_VLAN_STAG_TX);
3559
3560 if (dev->netdev_ops->ndo_features_check)
3561 features &= dev->netdev_ops->ndo_features_check(skb, dev,
3562 features);
3563 else
3564 features &= dflt_features_check(skb, dev, features);
3565
3566 return harmonize_features(skb, features);
3567 }
3568 EXPORT_SYMBOL(netif_skb_features);
3569
xmit_one(struct sk_buff * skb,struct net_device * dev,struct netdev_queue * txq,bool more)3570 static int xmit_one(struct sk_buff *skb, struct net_device *dev,
3571 struct netdev_queue *txq, bool more)
3572 {
3573 unsigned int len;
3574 int rc;
3575
3576 if (dev_nit_active(dev))
3577 dev_queue_xmit_nit(skb, dev);
3578
3579 len = skb->len;
3580 PRANDOM_ADD_NOISE(skb, dev, txq, len + jiffies);
3581 trace_net_dev_start_xmit(skb, dev);
3582 rc = netdev_start_xmit(skb, dev, txq, more);
3583 trace_net_dev_xmit(skb, rc, dev, len);
3584
3585 return rc;
3586 }
3587
dev_hard_start_xmit(struct sk_buff * first,struct net_device * dev,struct netdev_queue * txq,int * ret)3588 struct sk_buff *dev_hard_start_xmit(struct sk_buff *first, struct net_device *dev,
3589 struct netdev_queue *txq, int *ret)
3590 {
3591 struct sk_buff *skb = first;
3592 int rc = NETDEV_TX_OK;
3593
3594 while (skb) {
3595 struct sk_buff *next = skb->next;
3596
3597 skb_mark_not_on_list(skb);
3598 rc = xmit_one(skb, dev, txq, next != NULL);
3599 if (unlikely(!dev_xmit_complete(rc))) {
3600 skb->next = next;
3601 goto out;
3602 }
3603
3604 skb = next;
3605 if (netif_tx_queue_stopped(txq) && skb) {
3606 rc = NETDEV_TX_BUSY;
3607 break;
3608 }
3609 }
3610
3611 out:
3612 *ret = rc;
3613 return skb;
3614 }
3615
validate_xmit_vlan(struct sk_buff * skb,netdev_features_t features)3616 static struct sk_buff *validate_xmit_vlan(struct sk_buff *skb,
3617 netdev_features_t features)
3618 {
3619 if (skb_vlan_tag_present(skb) &&
3620 !vlan_hw_offload_capable(features, skb->vlan_proto))
3621 skb = __vlan_hwaccel_push_inside(skb);
3622 return skb;
3623 }
3624
skb_csum_hwoffload_help(struct sk_buff * skb,const netdev_features_t features)3625 int skb_csum_hwoffload_help(struct sk_buff *skb,
3626 const netdev_features_t features)
3627 {
3628 if (unlikely(skb->csum_not_inet))
3629 return !!(features & NETIF_F_SCTP_CRC) ? 0 :
3630 skb_crc32c_csum_help(skb);
3631
3632 return !!(features & NETIF_F_CSUM_MASK) ? 0 : skb_checksum_help(skb);
3633 }
3634 EXPORT_SYMBOL(skb_csum_hwoffload_help);
3635
validate_xmit_skb(struct sk_buff * skb,struct net_device * dev,bool * again)3636 static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device *dev, bool *again)
3637 {
3638 netdev_features_t features;
3639
3640 features = netif_skb_features(skb);
3641 skb = validate_xmit_vlan(skb, features);
3642 if (unlikely(!skb))
3643 goto out_null;
3644
3645 skb = sk_validate_xmit_skb(skb, dev);
3646 if (unlikely(!skb))
3647 goto out_null;
3648
3649 if (netif_needs_gso(skb, features)) {
3650 struct sk_buff *segs;
3651
3652 segs = skb_gso_segment(skb, features);
3653 if (IS_ERR(segs)) {
3654 goto out_kfree_skb;
3655 } else if (segs) {
3656 consume_skb(skb);
3657 skb = segs;
3658 }
3659 } else {
3660 if (skb_needs_linearize(skb, features) &&
3661 __skb_linearize(skb))
3662 goto out_kfree_skb;
3663
3664 /* If packet is not checksummed and device does not
3665 * support checksumming for this protocol, complete
3666 * checksumming here.
3667 */
3668 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3669 if (skb->encapsulation)
3670 skb_set_inner_transport_header(skb,
3671 skb_checksum_start_offset(skb));
3672 else
3673 skb_set_transport_header(skb,
3674 skb_checksum_start_offset(skb));
3675 if (skb_csum_hwoffload_help(skb, features))
3676 goto out_kfree_skb;
3677 }
3678 }
3679
3680 skb = validate_xmit_xfrm(skb, features, again);
3681
3682 return skb;
3683
3684 out_kfree_skb:
3685 kfree_skb(skb);
3686 out_null:
3687 atomic_long_inc(&dev->tx_dropped);
3688 return NULL;
3689 }
3690
validate_xmit_skb_list(struct sk_buff * skb,struct net_device * dev,bool * again)3691 struct sk_buff *validate_xmit_skb_list(struct sk_buff *skb, struct net_device *dev, bool *again)
3692 {
3693 struct sk_buff *next, *head = NULL, *tail;
3694
3695 for (; skb != NULL; skb = next) {
3696 next = skb->next;
3697 skb_mark_not_on_list(skb);
3698
3699 /* in case skb wont be segmented, point to itself */
3700 skb->prev = skb;
3701
3702 skb = validate_xmit_skb(skb, dev, again);
3703 if (!skb)
3704 continue;
3705
3706 if (!head)
3707 head = skb;
3708 else
3709 tail->next = skb;
3710 /* If skb was segmented, skb->prev points to
3711 * the last segment. If not, it still contains skb.
3712 */
3713 tail = skb->prev;
3714 }
3715 return head;
3716 }
3717 EXPORT_SYMBOL_GPL(validate_xmit_skb_list);
3718
qdisc_pkt_len_init(struct sk_buff * skb)3719 static void qdisc_pkt_len_init(struct sk_buff *skb)
3720 {
3721 const struct skb_shared_info *shinfo = skb_shinfo(skb);
3722
3723 qdisc_skb_cb(skb)->pkt_len = skb->len;
3724
3725 /* To get more precise estimation of bytes sent on wire,
3726 * we add to pkt_len the headers size of all segments
3727 */
3728 if (shinfo->gso_size && skb_transport_header_was_set(skb)) {
3729 unsigned int hdr_len;
3730 u16 gso_segs = shinfo->gso_segs;
3731
3732 /* mac layer + network layer */
3733 hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
3734
3735 /* + transport layer */
3736 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
3737 const struct tcphdr *th;
3738 struct tcphdr _tcphdr;
3739
3740 th = skb_header_pointer(skb, skb_transport_offset(skb),
3741 sizeof(_tcphdr), &_tcphdr);
3742 if (likely(th))
3743 hdr_len += __tcp_hdrlen(th);
3744 } else {
3745 struct udphdr _udphdr;
3746
3747 if (skb_header_pointer(skb, skb_transport_offset(skb),
3748 sizeof(_udphdr), &_udphdr))
3749 hdr_len += sizeof(struct udphdr);
3750 }
3751
3752 if (shinfo->gso_type & SKB_GSO_DODGY)
3753 gso_segs = DIV_ROUND_UP(skb->len - hdr_len,
3754 shinfo->gso_size);
3755
3756 qdisc_skb_cb(skb)->pkt_len += (gso_segs - 1) * hdr_len;
3757 }
3758 }
3759
__dev_xmit_skb(struct sk_buff * skb,struct Qdisc * q,struct net_device * dev,struct netdev_queue * txq)3760 static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q,
3761 struct net_device *dev,
3762 struct netdev_queue *txq)
3763 {
3764 spinlock_t *root_lock = qdisc_lock(q);
3765 struct sk_buff *to_free = NULL;
3766 bool contended;
3767 int rc;
3768
3769 qdisc_calculate_pkt_len(skb, q);
3770
3771 if (q->flags & TCQ_F_NOLOCK) {
3772 rc = q->enqueue(skb, q, &to_free) & NET_XMIT_MASK;
3773 if (likely(!netif_xmit_frozen_or_stopped(txq)))
3774 qdisc_run(q);
3775
3776 if (unlikely(to_free))
3777 kfree_skb_list(to_free);
3778 return rc;
3779 }
3780
3781 /*
3782 * Heuristic to force contended enqueues to serialize on a
3783 * separate lock before trying to get qdisc main lock.
3784 * This permits qdisc->running owner to get the lock more
3785 * often and dequeue packets faster.
3786 */
3787 contended = qdisc_is_running(q);
3788 if (unlikely(contended))
3789 spin_lock(&q->busylock);
3790
3791 spin_lock(root_lock);
3792 if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) {
3793 __qdisc_drop(skb, &to_free);
3794 rc = NET_XMIT_DROP;
3795 } else if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) &&
3796 qdisc_run_begin(q)) {
3797 /*
3798 * This is a work-conserving queue; there are no old skbs
3799 * waiting to be sent out; and the qdisc is not running -
3800 * xmit the skb directly.
3801 */
3802
3803 qdisc_bstats_update(q, skb);
3804
3805 if (sch_direct_xmit(skb, q, dev, txq, root_lock, true)) {
3806 if (unlikely(contended)) {
3807 spin_unlock(&q->busylock);
3808 contended = false;
3809 }
3810 __qdisc_run(q);
3811 }
3812
3813 qdisc_run_end(q);
3814 rc = NET_XMIT_SUCCESS;
3815 } else {
3816 rc = q->enqueue(skb, q, &to_free) & NET_XMIT_MASK;
3817 if (qdisc_run_begin(q)) {
3818 if (unlikely(contended)) {
3819 spin_unlock(&q->busylock);
3820 contended = false;
3821 }
3822 __qdisc_run(q);
3823 qdisc_run_end(q);
3824 }
3825 }
3826 spin_unlock(root_lock);
3827 if (unlikely(to_free))
3828 kfree_skb_list(to_free);
3829 if (unlikely(contended))
3830 spin_unlock(&q->busylock);
3831 return rc;
3832 }
3833
3834 #if IS_ENABLED(CONFIG_CGROUP_NET_PRIO)
skb_update_prio(struct sk_buff * skb)3835 static void skb_update_prio(struct sk_buff *skb)
3836 {
3837 const struct netprio_map *map;
3838 const struct sock *sk;
3839 unsigned int prioidx;
3840
3841 if (skb->priority)
3842 return;
3843 map = rcu_dereference_bh(skb->dev->priomap);
3844 if (!map)
3845 return;
3846 sk = skb_to_full_sk(skb);
3847 if (!sk)
3848 return;
3849
3850 prioidx = sock_cgroup_prioidx(&sk->sk_cgrp_data);
3851
3852 if (prioidx < map->priomap_len)
3853 skb->priority = map->priomap[prioidx];
3854 }
3855 #else
3856 #define skb_update_prio(skb)
3857 #endif
3858
3859 /**
3860 * dev_loopback_xmit - loop back @skb
3861 * @net: network namespace this loopback is happening in
3862 * @sk: sk needed to be a netfilter okfn
3863 * @skb: buffer to transmit
3864 */
dev_loopback_xmit(struct net * net,struct sock * sk,struct sk_buff * skb)3865 int dev_loopback_xmit(struct net *net, struct sock *sk, struct sk_buff *skb)
3866 {
3867 skb_reset_mac_header(skb);
3868 __skb_pull(skb, skb_network_offset(skb));
3869 skb->pkt_type = PACKET_LOOPBACK;
3870 skb->ip_summed = CHECKSUM_UNNECESSARY;
3871 WARN_ON(!skb_dst(skb));
3872 skb_dst_force(skb);
3873 netif_rx_ni(skb);
3874 return 0;
3875 }
3876 EXPORT_SYMBOL(dev_loopback_xmit);
3877
3878 #ifdef CONFIG_NET_EGRESS
3879 static struct sk_buff *
sch_handle_egress(struct sk_buff * skb,int * ret,struct net_device * dev)3880 sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
3881 {
3882 struct mini_Qdisc *miniq = rcu_dereference_bh(dev->miniq_egress);
3883 struct tcf_result cl_res;
3884
3885 if (!miniq)
3886 return skb;
3887
3888 /* qdisc_skb_cb(skb)->pkt_len was already set by the caller. */
3889 qdisc_skb_cb(skb)->mru = 0;
3890 mini_qdisc_bstats_cpu_update(miniq, skb);
3891
3892 switch (tcf_classify(skb, miniq->filter_list, &cl_res, false)) {
3893 case TC_ACT_OK:
3894 case TC_ACT_RECLASSIFY:
3895 skb->tc_index = TC_H_MIN(cl_res.classid);
3896 break;
3897 case TC_ACT_SHOT:
3898 mini_qdisc_qstats_cpu_drop(miniq);
3899 *ret = NET_XMIT_DROP;
3900 kfree_skb(skb);
3901 return NULL;
3902 case TC_ACT_STOLEN:
3903 case TC_ACT_QUEUED:
3904 case TC_ACT_TRAP:
3905 *ret = NET_XMIT_SUCCESS;
3906 consume_skb(skb);
3907 return NULL;
3908 case TC_ACT_REDIRECT:
3909 /* No need to push/pop skb's mac_header here on egress! */
3910 skb_do_redirect(skb);
3911 *ret = NET_XMIT_SUCCESS;
3912 return NULL;
3913 default:
3914 break;
3915 }
3916
3917 return skb;
3918 }
3919 #endif /* CONFIG_NET_EGRESS */
3920
3921 #ifdef CONFIG_XPS
__get_xps_queue_idx(struct net_device * dev,struct sk_buff * skb,struct xps_dev_maps * dev_maps,unsigned int tci)3922 static int __get_xps_queue_idx(struct net_device *dev, struct sk_buff *skb,
3923 struct xps_dev_maps *dev_maps, unsigned int tci)
3924 {
3925 struct xps_map *map;
3926 int queue_index = -1;
3927
3928 if (dev->num_tc) {
3929 tci *= dev->num_tc;
3930 tci += netdev_get_prio_tc_map(dev, skb->priority);
3931 }
3932
3933 map = rcu_dereference(dev_maps->attr_map[tci]);
3934 if (map) {
3935 if (map->len == 1)
3936 queue_index = map->queues[0];
3937 else
3938 queue_index = map->queues[reciprocal_scale(
3939 skb_get_hash(skb), map->len)];
3940 if (unlikely(queue_index >= dev->real_num_tx_queues))
3941 queue_index = -1;
3942 }
3943 return queue_index;
3944 }
3945 #endif
3946
get_xps_queue(struct net_device * dev,struct net_device * sb_dev,struct sk_buff * skb)3947 static int get_xps_queue(struct net_device *dev, struct net_device *sb_dev,
3948 struct sk_buff *skb)
3949 {
3950 #ifdef CONFIG_XPS
3951 struct xps_dev_maps *dev_maps;
3952 struct sock *sk = skb->sk;
3953 int queue_index = -1;
3954
3955 if (!static_key_false(&xps_needed))
3956 return -1;
3957
3958 rcu_read_lock();
3959 if (!static_key_false(&xps_rxqs_needed))
3960 goto get_cpus_map;
3961
3962 dev_maps = rcu_dereference(sb_dev->xps_rxqs_map);
3963 if (dev_maps) {
3964 int tci = sk_rx_queue_get(sk);
3965
3966 if (tci >= 0 && tci < dev->num_rx_queues)
3967 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
3968 tci);
3969 }
3970
3971 get_cpus_map:
3972 if (queue_index < 0) {
3973 dev_maps = rcu_dereference(sb_dev->xps_cpus_map);
3974 if (dev_maps) {
3975 unsigned int tci = skb->sender_cpu - 1;
3976
3977 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
3978 tci);
3979 }
3980 }
3981 rcu_read_unlock();
3982
3983 return queue_index;
3984 #else
3985 return -1;
3986 #endif
3987 }
3988
dev_pick_tx_zero(struct net_device * dev,struct sk_buff * skb,struct net_device * sb_dev)3989 u16 dev_pick_tx_zero(struct net_device *dev, struct sk_buff *skb,
3990 struct net_device *sb_dev)
3991 {
3992 return 0;
3993 }
3994 EXPORT_SYMBOL(dev_pick_tx_zero);
3995
dev_pick_tx_cpu_id(struct net_device * dev,struct sk_buff * skb,struct net_device * sb_dev)3996 u16 dev_pick_tx_cpu_id(struct net_device *dev, struct sk_buff *skb,
3997 struct net_device *sb_dev)
3998 {
3999 return (u16)raw_smp_processor_id() % dev->real_num_tx_queues;
4000 }
4001 EXPORT_SYMBOL(dev_pick_tx_cpu_id);
4002
netdev_pick_tx(struct net_device * dev,struct sk_buff * skb,struct net_device * sb_dev)4003 u16 netdev_pick_tx(struct net_device *dev, struct sk_buff *skb,
4004 struct net_device *sb_dev)
4005 {
4006 struct sock *sk = skb->sk;
4007 int queue_index = sk_tx_queue_get(sk);
4008
4009 sb_dev = sb_dev ? : dev;
4010
4011 if (queue_index < 0 || skb->ooo_okay ||
4012 queue_index >= dev->real_num_tx_queues) {
4013 int new_index = get_xps_queue(dev, sb_dev, skb);
4014
4015 if (new_index < 0)
4016 new_index = skb_tx_hash(dev, sb_dev, skb);
4017
4018 if (queue_index != new_index && sk &&
4019 sk_fullsock(sk) &&
4020 rcu_access_pointer(sk->sk_dst_cache))
4021 sk_tx_queue_set(sk, new_index);
4022
4023 queue_index = new_index;
4024 }
4025
4026 return queue_index;
4027 }
4028 EXPORT_SYMBOL(netdev_pick_tx);
4029
netdev_core_pick_tx(struct net_device * dev,struct sk_buff * skb,struct net_device * sb_dev)4030 struct netdev_queue *netdev_core_pick_tx(struct net_device *dev,
4031 struct sk_buff *skb,
4032 struct net_device *sb_dev)
4033 {
4034 int queue_index = 0;
4035
4036 #ifdef CONFIG_XPS
4037 u32 sender_cpu = skb->sender_cpu - 1;
4038
4039 if (sender_cpu >= (u32)NR_CPUS)
4040 skb->sender_cpu = raw_smp_processor_id() + 1;
4041 #endif
4042
4043 if (dev->real_num_tx_queues != 1) {
4044 const struct net_device_ops *ops = dev->netdev_ops;
4045
4046 if (ops->ndo_select_queue)
4047 queue_index = ops->ndo_select_queue(dev, skb, sb_dev);
4048 else
4049 queue_index = netdev_pick_tx(dev, skb, sb_dev);
4050
4051 queue_index = netdev_cap_txqueue(dev, queue_index);
4052 }
4053
4054 skb_set_queue_mapping(skb, queue_index);
4055 return netdev_get_tx_queue(dev, queue_index);
4056 }
4057
4058 /**
4059 * __dev_queue_xmit - transmit a buffer
4060 * @skb: buffer to transmit
4061 * @sb_dev: suboordinate device used for L2 forwarding offload
4062 *
4063 * Queue a buffer for transmission to a network device. The caller must
4064 * have set the device and priority and built the buffer before calling
4065 * this function. The function can be called from an interrupt.
4066 *
4067 * A negative errno code is returned on a failure. A success does not
4068 * guarantee the frame will be transmitted as it may be dropped due
4069 * to congestion or traffic shaping.
4070 *
4071 * -----------------------------------------------------------------------------------
4072 * I notice this method can also return errors from the queue disciplines,
4073 * including NET_XMIT_DROP, which is a positive value. So, errors can also
4074 * be positive.
4075 *
4076 * Regardless of the return value, the skb is consumed, so it is currently
4077 * difficult to retry a send to this method. (You can bump the ref count
4078 * before sending to hold a reference for retry if you are careful.)
4079 *
4080 * When calling this method, interrupts MUST be enabled. This is because
4081 * the BH enable code must have IRQs enabled so that it will not deadlock.
4082 * --BLG
4083 */
__dev_queue_xmit(struct sk_buff * skb,struct net_device * sb_dev)4084 static int __dev_queue_xmit(struct sk_buff *skb, struct net_device *sb_dev)
4085 {
4086 struct net_device *dev = skb->dev;
4087 struct netdev_queue *txq;
4088 struct Qdisc *q;
4089 int rc = -ENOMEM;
4090 bool again = false;
4091
4092 skb_reset_mac_header(skb);
4093
4094 if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_SCHED_TSTAMP))
4095 __skb_tstamp_tx(skb, NULL, skb->sk, SCM_TSTAMP_SCHED);
4096
4097 /* Disable soft irqs for various locks below. Also
4098 * stops preemption for RCU.
4099 */
4100 rcu_read_lock_bh();
4101
4102 skb_update_prio(skb);
4103
4104 qdisc_pkt_len_init(skb);
4105 #ifdef CONFIG_NET_CLS_ACT
4106 skb->tc_at_ingress = 0;
4107 # ifdef CONFIG_NET_EGRESS
4108 if (static_branch_unlikely(&egress_needed_key)) {
4109 skb = sch_handle_egress(skb, &rc, dev);
4110 if (!skb)
4111 goto out;
4112 }
4113 # endif
4114 #endif
4115 /* If device/qdisc don't need skb->dst, release it right now while
4116 * its hot in this cpu cache.
4117 */
4118 if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
4119 skb_dst_drop(skb);
4120 else
4121 skb_dst_force(skb);
4122
4123 txq = netdev_core_pick_tx(dev, skb, sb_dev);
4124 q = rcu_dereference_bh(txq->qdisc);
4125
4126 trace_net_dev_queue(skb);
4127 if (q->enqueue) {
4128 rc = __dev_xmit_skb(skb, q, dev, txq);
4129 goto out;
4130 }
4131
4132 /* The device has no queue. Common case for software devices:
4133 * loopback, all the sorts of tunnels...
4134
4135 * Really, it is unlikely that netif_tx_lock protection is necessary
4136 * here. (f.e. loopback and IP tunnels are clean ignoring statistics
4137 * counters.)
4138 * However, it is possible, that they rely on protection
4139 * made by us here.
4140
4141 * Check this and shot the lock. It is not prone from deadlocks.
4142 *Either shot noqueue qdisc, it is even simpler 8)
4143 */
4144 if (dev->flags & IFF_UP) {
4145 int cpu = smp_processor_id(); /* ok because BHs are off */
4146
4147 if (txq->xmit_lock_owner != cpu) {
4148 if (dev_xmit_recursion())
4149 goto recursion_alert;
4150
4151 skb = validate_xmit_skb(skb, dev, &again);
4152 if (!skb)
4153 goto out;
4154
4155 PRANDOM_ADD_NOISE(skb, dev, txq, jiffies);
4156 HARD_TX_LOCK(dev, txq, cpu);
4157
4158 if (!netif_xmit_stopped(txq)) {
4159 dev_xmit_recursion_inc();
4160 skb = dev_hard_start_xmit(skb, dev, txq, &rc);
4161 dev_xmit_recursion_dec();
4162 if (dev_xmit_complete(rc)) {
4163 HARD_TX_UNLOCK(dev, txq);
4164 goto out;
4165 }
4166 }
4167 HARD_TX_UNLOCK(dev, txq);
4168 net_crit_ratelimited("Virtual device %s asks to queue packet!\n",
4169 dev->name);
4170 } else {
4171 /* Recursion is detected! It is possible,
4172 * unfortunately
4173 */
4174 recursion_alert:
4175 net_crit_ratelimited("Dead loop on virtual device %s, fix it urgently!\n",
4176 dev->name);
4177 }
4178 }
4179
4180 rc = -ENETDOWN;
4181 rcu_read_unlock_bh();
4182
4183 atomic_long_inc(&dev->tx_dropped);
4184 kfree_skb_list(skb);
4185 return rc;
4186 out:
4187 rcu_read_unlock_bh();
4188 return rc;
4189 }
4190
dev_queue_xmit(struct sk_buff * skb)4191 int dev_queue_xmit(struct sk_buff *skb)
4192 {
4193 return __dev_queue_xmit(skb, NULL);
4194 }
4195 EXPORT_SYMBOL(dev_queue_xmit);
4196
dev_queue_xmit_accel(struct sk_buff * skb,struct net_device * sb_dev)4197 int dev_queue_xmit_accel(struct sk_buff *skb, struct net_device *sb_dev)
4198 {
4199 return __dev_queue_xmit(skb, sb_dev);
4200 }
4201 EXPORT_SYMBOL(dev_queue_xmit_accel);
4202
__dev_direct_xmit(struct sk_buff * skb,u16 queue_id)4203 int __dev_direct_xmit(struct sk_buff *skb, u16 queue_id)
4204 {
4205 struct net_device *dev = skb->dev;
4206 struct sk_buff *orig_skb = skb;
4207 struct netdev_queue *txq;
4208 int ret = NETDEV_TX_BUSY;
4209 bool again = false;
4210
4211 if (unlikely(!netif_running(dev) ||
4212 !netif_carrier_ok(dev)))
4213 goto drop;
4214
4215 skb = validate_xmit_skb_list(skb, dev, &again);
4216 if (skb != orig_skb)
4217 goto drop;
4218
4219 skb_set_queue_mapping(skb, queue_id);
4220 txq = skb_get_tx_queue(dev, skb);
4221 PRANDOM_ADD_NOISE(skb, dev, txq, jiffies);
4222
4223 local_bh_disable();
4224
4225 dev_xmit_recursion_inc();
4226 HARD_TX_LOCK(dev, txq, smp_processor_id());
4227 if (!netif_xmit_frozen_or_drv_stopped(txq))
4228 ret = netdev_start_xmit(skb, dev, txq, false);
4229 HARD_TX_UNLOCK(dev, txq);
4230 dev_xmit_recursion_dec();
4231
4232 local_bh_enable();
4233 return ret;
4234 drop:
4235 atomic_long_inc(&dev->tx_dropped);
4236 kfree_skb_list(skb);
4237 return NET_XMIT_DROP;
4238 }
4239 EXPORT_SYMBOL(__dev_direct_xmit);
4240
4241 /*************************************************************************
4242 * Receiver routines
4243 *************************************************************************/
4244
4245 int netdev_max_backlog __read_mostly = 1000;
4246 EXPORT_SYMBOL(netdev_max_backlog);
4247
4248 int netdev_tstamp_prequeue __read_mostly = 1;
4249 int netdev_budget __read_mostly = 300;
4250 /* Must be at least 2 jiffes to guarantee 1 jiffy timeout */
4251 unsigned int __read_mostly netdev_budget_usecs = 2 * USEC_PER_SEC / HZ;
4252 int weight_p __read_mostly = 64; /* old backlog weight */
4253 int dev_weight_rx_bias __read_mostly = 1; /* bias for backlog weight */
4254 int dev_weight_tx_bias __read_mostly = 1; /* bias for output_queue quota */
4255 int dev_rx_weight __read_mostly = 64;
4256 int dev_tx_weight __read_mostly = 64;
4257 /* Maximum number of GRO_NORMAL skbs to batch up for list-RX */
4258 int gro_normal_batch __read_mostly = 8;
4259
4260 /* Called with irq disabled */
____napi_schedule(struct softnet_data * sd,struct napi_struct * napi)4261 static inline void ____napi_schedule(struct softnet_data *sd,
4262 struct napi_struct *napi)
4263 {
4264 list_add_tail(&napi->poll_list, &sd->poll_list);
4265 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4266 }
4267
4268 #ifdef CONFIG_RPS
4269
4270 /* One global table that all flow-based protocols share. */
4271 struct rps_sock_flow_table __rcu *rps_sock_flow_table __read_mostly;
4272 EXPORT_SYMBOL(rps_sock_flow_table);
4273 u32 rps_cpu_mask __read_mostly;
4274 EXPORT_SYMBOL(rps_cpu_mask);
4275
4276 struct static_key_false rps_needed __read_mostly;
4277 EXPORT_SYMBOL(rps_needed);
4278 struct static_key_false rfs_needed __read_mostly;
4279 EXPORT_SYMBOL(rfs_needed);
4280
4281 static struct rps_dev_flow *
set_rps_cpu(struct net_device * dev,struct sk_buff * skb,struct rps_dev_flow * rflow,u16 next_cpu)4282 set_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4283 struct rps_dev_flow *rflow, u16 next_cpu)
4284 {
4285 if (next_cpu < nr_cpu_ids) {
4286 #ifdef CONFIG_RFS_ACCEL
4287 struct netdev_rx_queue *rxqueue;
4288 struct rps_dev_flow_table *flow_table;
4289 struct rps_dev_flow *old_rflow;
4290 u32 flow_id;
4291 u16 rxq_index;
4292 int rc;
4293
4294 /* Should we steer this flow to a different hardware queue? */
4295 if (!skb_rx_queue_recorded(skb) || !dev->rx_cpu_rmap ||
4296 !(dev->features & NETIF_F_NTUPLE))
4297 goto out;
4298 rxq_index = cpu_rmap_lookup_index(dev->rx_cpu_rmap, next_cpu);
4299 if (rxq_index == skb_get_rx_queue(skb))
4300 goto out;
4301
4302 rxqueue = dev->_rx + rxq_index;
4303 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4304 if (!flow_table)
4305 goto out;
4306 flow_id = skb_get_hash(skb) & flow_table->mask;
4307 rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb,
4308 rxq_index, flow_id);
4309 if (rc < 0)
4310 goto out;
4311 old_rflow = rflow;
4312 rflow = &flow_table->flows[flow_id];
4313 rflow->filter = rc;
4314 if (old_rflow->filter == rflow->filter)
4315 old_rflow->filter = RPS_NO_FILTER;
4316 out:
4317 #endif
4318 rflow->last_qtail =
4319 per_cpu(softnet_data, next_cpu).input_queue_head;
4320 }
4321
4322 rflow->cpu = next_cpu;
4323 return rflow;
4324 }
4325
4326 /*
4327 * get_rps_cpu is called from netif_receive_skb and returns the target
4328 * CPU from the RPS map of the receiving queue for a given skb.
4329 * rcu_read_lock must be held on entry.
4330 */
get_rps_cpu(struct net_device * dev,struct sk_buff * skb,struct rps_dev_flow ** rflowp)4331 static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4332 struct rps_dev_flow **rflowp)
4333 {
4334 const struct rps_sock_flow_table *sock_flow_table;
4335 struct netdev_rx_queue *rxqueue = dev->_rx;
4336 struct rps_dev_flow_table *flow_table;
4337 struct rps_map *map;
4338 int cpu = -1;
4339 u32 tcpu;
4340 u32 hash;
4341
4342 if (skb_rx_queue_recorded(skb)) {
4343 u16 index = skb_get_rx_queue(skb);
4344
4345 if (unlikely(index >= dev->real_num_rx_queues)) {
4346 WARN_ONCE(dev->real_num_rx_queues > 1,
4347 "%s received packet on queue %u, but number "
4348 "of RX queues is %u\n",
4349 dev->name, index, dev->real_num_rx_queues);
4350 goto done;
4351 }
4352 rxqueue += index;
4353 }
4354
4355 /* Avoid computing hash if RFS/RPS is not active for this rxqueue */
4356
4357 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4358 map = rcu_dereference(rxqueue->rps_map);
4359 if (!flow_table && !map)
4360 goto done;
4361
4362 skb_reset_network_header(skb);
4363 hash = skb_get_hash(skb);
4364 if (!hash)
4365 goto done;
4366
4367 sock_flow_table = rcu_dereference(rps_sock_flow_table);
4368 if (flow_table && sock_flow_table) {
4369 struct rps_dev_flow *rflow;
4370 u32 next_cpu;
4371 u32 ident;
4372
4373 /* First check into global flow table if there is a match */
4374 ident = sock_flow_table->ents[hash & sock_flow_table->mask];
4375 if ((ident ^ hash) & ~rps_cpu_mask)
4376 goto try_rps;
4377
4378 next_cpu = ident & rps_cpu_mask;
4379
4380 /* OK, now we know there is a match,
4381 * we can look at the local (per receive queue) flow table
4382 */
4383 rflow = &flow_table->flows[hash & flow_table->mask];
4384 tcpu = rflow->cpu;
4385
4386 /*
4387 * If the desired CPU (where last recvmsg was done) is
4388 * different from current CPU (one in the rx-queue flow
4389 * table entry), switch if one of the following holds:
4390 * - Current CPU is unset (>= nr_cpu_ids).
4391 * - Current CPU is offline.
4392 * - The current CPU's queue tail has advanced beyond the
4393 * last packet that was enqueued using this table entry.
4394 * This guarantees that all previous packets for the flow
4395 * have been dequeued, thus preserving in order delivery.
4396 */
4397 if (unlikely(tcpu != next_cpu) &&
4398 (tcpu >= nr_cpu_ids || !cpu_online(tcpu) ||
4399 ((int)(per_cpu(softnet_data, tcpu).input_queue_head -
4400 rflow->last_qtail)) >= 0)) {
4401 tcpu = next_cpu;
4402 rflow = set_rps_cpu(dev, skb, rflow, next_cpu);
4403 }
4404
4405 if (tcpu < nr_cpu_ids && cpu_online(tcpu)) {
4406 *rflowp = rflow;
4407 cpu = tcpu;
4408 goto done;
4409 }
4410 }
4411
4412 try_rps:
4413
4414 if (map) {
4415 tcpu = map->cpus[reciprocal_scale(hash, map->len)];
4416 if (cpu_online(tcpu)) {
4417 cpu = tcpu;
4418 goto done;
4419 }
4420 }
4421
4422 done:
4423 return cpu;
4424 }
4425
4426 #ifdef CONFIG_RFS_ACCEL
4427
4428 /**
4429 * rps_may_expire_flow - check whether an RFS hardware filter may be removed
4430 * @dev: Device on which the filter was set
4431 * @rxq_index: RX queue index
4432 * @flow_id: Flow ID passed to ndo_rx_flow_steer()
4433 * @filter_id: Filter ID returned by ndo_rx_flow_steer()
4434 *
4435 * Drivers that implement ndo_rx_flow_steer() should periodically call
4436 * this function for each installed filter and remove the filters for
4437 * which it returns %true.
4438 */
rps_may_expire_flow(struct net_device * dev,u16 rxq_index,u32 flow_id,u16 filter_id)4439 bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index,
4440 u32 flow_id, u16 filter_id)
4441 {
4442 struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index;
4443 struct rps_dev_flow_table *flow_table;
4444 struct rps_dev_flow *rflow;
4445 bool expire = true;
4446 unsigned int cpu;
4447
4448 rcu_read_lock();
4449 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4450 if (flow_table && flow_id <= flow_table->mask) {
4451 rflow = &flow_table->flows[flow_id];
4452 cpu = READ_ONCE(rflow->cpu);
4453 if (rflow->filter == filter_id && cpu < nr_cpu_ids &&
4454 ((int)(per_cpu(softnet_data, cpu).input_queue_head -
4455 rflow->last_qtail) <
4456 (int)(10 * flow_table->mask)))
4457 expire = false;
4458 }
4459 rcu_read_unlock();
4460 return expire;
4461 }
4462 EXPORT_SYMBOL(rps_may_expire_flow);
4463
4464 #endif /* CONFIG_RFS_ACCEL */
4465
4466 /* Called from hardirq (IPI) context */
rps_trigger_softirq(void * data)4467 static void rps_trigger_softirq(void *data)
4468 {
4469 struct softnet_data *sd = data;
4470
4471 ____napi_schedule(sd, &sd->backlog);
4472 sd->received_rps++;
4473 }
4474
4475 #endif /* CONFIG_RPS */
4476
4477 /*
4478 * Check if this softnet_data structure is another cpu one
4479 * If yes, queue it to our IPI list and return 1
4480 * If no, return 0
4481 */
rps_ipi_queued(struct softnet_data * sd)4482 static int rps_ipi_queued(struct softnet_data *sd)
4483 {
4484 #ifdef CONFIG_RPS
4485 struct softnet_data *mysd = this_cpu_ptr(&softnet_data);
4486
4487 if (sd != mysd) {
4488 sd->rps_ipi_next = mysd->rps_ipi_list;
4489 mysd->rps_ipi_list = sd;
4490
4491 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4492 return 1;
4493 }
4494 #endif /* CONFIG_RPS */
4495 return 0;
4496 }
4497
4498 #ifdef CONFIG_NET_FLOW_LIMIT
4499 int netdev_flow_limit_table_len __read_mostly = (1 << 12);
4500 #endif
4501
skb_flow_limit(struct sk_buff * skb,unsigned int qlen)4502 static bool skb_flow_limit(struct sk_buff *skb, unsigned int qlen)
4503 {
4504 #ifdef CONFIG_NET_FLOW_LIMIT
4505 struct sd_flow_limit *fl;
4506 struct softnet_data *sd;
4507 unsigned int old_flow, new_flow;
4508
4509 if (qlen < (netdev_max_backlog >> 1))
4510 return false;
4511
4512 sd = this_cpu_ptr(&softnet_data);
4513
4514 rcu_read_lock();
4515 fl = rcu_dereference(sd->flow_limit);
4516 if (fl) {
4517 new_flow = skb_get_hash(skb) & (fl->num_buckets - 1);
4518 old_flow = fl->history[fl->history_head];
4519 fl->history[fl->history_head] = new_flow;
4520
4521 fl->history_head++;
4522 fl->history_head &= FLOW_LIMIT_HISTORY - 1;
4523
4524 if (likely(fl->buckets[old_flow]))
4525 fl->buckets[old_flow]--;
4526
4527 if (++fl->buckets[new_flow] > (FLOW_LIMIT_HISTORY >> 1)) {
4528 fl->count++;
4529 rcu_read_unlock();
4530 return true;
4531 }
4532 }
4533 rcu_read_unlock();
4534 #endif
4535 return false;
4536 }
4537
4538 /*
4539 * enqueue_to_backlog is called to queue an skb to a per CPU backlog
4540 * queue (may be a remote CPU queue).
4541 */
enqueue_to_backlog(struct sk_buff * skb,int cpu,unsigned int * qtail)4542 static int enqueue_to_backlog(struct sk_buff *skb, int cpu,
4543 unsigned int *qtail)
4544 {
4545 struct softnet_data *sd;
4546 unsigned long flags;
4547 unsigned int qlen;
4548
4549 sd = &per_cpu(softnet_data, cpu);
4550
4551 local_irq_save(flags);
4552
4553 rps_lock(sd);
4554 if (!netif_running(skb->dev))
4555 goto drop;
4556 qlen = skb_queue_len(&sd->input_pkt_queue);
4557 if (qlen <= netdev_max_backlog && !skb_flow_limit(skb, qlen)) {
4558 if (qlen) {
4559 enqueue:
4560 __skb_queue_tail(&sd->input_pkt_queue, skb);
4561 input_queue_tail_incr_save(sd, qtail);
4562 rps_unlock(sd);
4563 local_irq_restore(flags);
4564 return NET_RX_SUCCESS;
4565 }
4566
4567 /* Schedule NAPI for backlog device
4568 * We can use non atomic operation since we own the queue lock
4569 */
4570 if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state)) {
4571 if (!rps_ipi_queued(sd))
4572 ____napi_schedule(sd, &sd->backlog);
4573 }
4574 goto enqueue;
4575 }
4576
4577 drop:
4578 sd->dropped++;
4579 rps_unlock(sd);
4580
4581 local_irq_restore(flags);
4582
4583 atomic_long_inc(&skb->dev->rx_dropped);
4584 kfree_skb(skb);
4585 return NET_RX_DROP;
4586 }
4587
netif_get_rxqueue(struct sk_buff * skb)4588 static struct netdev_rx_queue *netif_get_rxqueue(struct sk_buff *skb)
4589 {
4590 struct net_device *dev = skb->dev;
4591 struct netdev_rx_queue *rxqueue;
4592
4593 rxqueue = dev->_rx;
4594
4595 if (skb_rx_queue_recorded(skb)) {
4596 u16 index = skb_get_rx_queue(skb);
4597
4598 if (unlikely(index >= dev->real_num_rx_queues)) {
4599 WARN_ONCE(dev->real_num_rx_queues > 1,
4600 "%s received packet on queue %u, but number "
4601 "of RX queues is %u\n",
4602 dev->name, index, dev->real_num_rx_queues);
4603
4604 return rxqueue; /* Return first rxqueue */
4605 }
4606 rxqueue += index;
4607 }
4608 return rxqueue;
4609 }
4610
netif_receive_generic_xdp(struct sk_buff * skb,struct xdp_buff * xdp,struct bpf_prog * xdp_prog)4611 static u32 netif_receive_generic_xdp(struct sk_buff *skb,
4612 struct xdp_buff *xdp,
4613 struct bpf_prog *xdp_prog)
4614 {
4615 struct netdev_rx_queue *rxqueue;
4616 void *orig_data, *orig_data_end;
4617 u32 metalen, act = XDP_DROP;
4618 __be16 orig_eth_type;
4619 struct ethhdr *eth;
4620 bool orig_bcast;
4621 int hlen, off;
4622 u32 mac_len;
4623
4624 /* Reinjected packets coming from act_mirred or similar should
4625 * not get XDP generic processing.
4626 */
4627 if (skb_is_redirected(skb))
4628 return XDP_PASS;
4629
4630 /* XDP packets must be linear and must have sufficient headroom
4631 * of XDP_PACKET_HEADROOM bytes. This is the guarantee that also
4632 * native XDP provides, thus we need to do it here as well.
4633 */
4634 if (skb_cloned(skb) || skb_is_nonlinear(skb) ||
4635 skb_headroom(skb) < XDP_PACKET_HEADROOM) {
4636 int hroom = XDP_PACKET_HEADROOM - skb_headroom(skb);
4637 int troom = skb->tail + skb->data_len - skb->end;
4638
4639 /* In case we have to go down the path and also linearize,
4640 * then lets do the pskb_expand_head() work just once here.
4641 */
4642 if (pskb_expand_head(skb,
4643 hroom > 0 ? ALIGN(hroom, NET_SKB_PAD) : 0,
4644 troom > 0 ? troom + 128 : 0, GFP_ATOMIC))
4645 goto do_drop;
4646 if (skb_linearize(skb))
4647 goto do_drop;
4648 }
4649
4650 /* The XDP program wants to see the packet starting at the MAC
4651 * header.
4652 */
4653 mac_len = skb->data - skb_mac_header(skb);
4654 hlen = skb_headlen(skb) + mac_len;
4655 xdp->data = skb->data - mac_len;
4656 xdp->data_meta = xdp->data;
4657 xdp->data_end = xdp->data + hlen;
4658 xdp->data_hard_start = skb->data - skb_headroom(skb);
4659
4660 /* SKB "head" area always have tailroom for skb_shared_info */
4661 xdp->frame_sz = (void *)skb_end_pointer(skb) - xdp->data_hard_start;
4662 xdp->frame_sz += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
4663
4664 orig_data_end = xdp->data_end;
4665 orig_data = xdp->data;
4666 eth = (struct ethhdr *)xdp->data;
4667 orig_bcast = is_multicast_ether_addr_64bits(eth->h_dest);
4668 orig_eth_type = eth->h_proto;
4669
4670 rxqueue = netif_get_rxqueue(skb);
4671 xdp->rxq = &rxqueue->xdp_rxq;
4672
4673 act = bpf_prog_run_xdp(xdp_prog, xdp);
4674
4675 /* check if bpf_xdp_adjust_head was used */
4676 off = xdp->data - orig_data;
4677 if (off) {
4678 if (off > 0)
4679 __skb_pull(skb, off);
4680 else if (off < 0)
4681 __skb_push(skb, -off);
4682
4683 skb->mac_header += off;
4684 skb_reset_network_header(skb);
4685 }
4686
4687 /* check if bpf_xdp_adjust_tail was used */
4688 off = xdp->data_end - orig_data_end;
4689 if (off != 0) {
4690 skb_set_tail_pointer(skb, xdp->data_end - xdp->data);
4691 skb->len += off; /* positive on grow, negative on shrink */
4692 }
4693
4694 /* check if XDP changed eth hdr such SKB needs update */
4695 eth = (struct ethhdr *)xdp->data;
4696 if ((orig_eth_type != eth->h_proto) ||
4697 (orig_bcast != is_multicast_ether_addr_64bits(eth->h_dest))) {
4698 __skb_push(skb, ETH_HLEN);
4699 skb->protocol = eth_type_trans(skb, skb->dev);
4700 }
4701
4702 switch (act) {
4703 case XDP_REDIRECT:
4704 case XDP_TX:
4705 __skb_push(skb, mac_len);
4706 break;
4707 case XDP_PASS:
4708 metalen = xdp->data - xdp->data_meta;
4709 if (metalen)
4710 skb_metadata_set(skb, metalen);
4711 break;
4712 default:
4713 bpf_warn_invalid_xdp_action(act);
4714 fallthrough;
4715 case XDP_ABORTED:
4716 trace_xdp_exception(skb->dev, xdp_prog, act);
4717 fallthrough;
4718 case XDP_DROP:
4719 do_drop:
4720 kfree_skb(skb);
4721 break;
4722 }
4723
4724 return act;
4725 }
4726
4727 /* When doing generic XDP we have to bypass the qdisc layer and the
4728 * network taps in order to match in-driver-XDP behavior.
4729 */
generic_xdp_tx(struct sk_buff * skb,struct bpf_prog * xdp_prog)4730 void generic_xdp_tx(struct sk_buff *skb, struct bpf_prog *xdp_prog)
4731 {
4732 struct net_device *dev = skb->dev;
4733 struct netdev_queue *txq;
4734 bool free_skb = true;
4735 int cpu, rc;
4736
4737 txq = netdev_core_pick_tx(dev, skb, NULL);
4738 cpu = smp_processor_id();
4739 HARD_TX_LOCK(dev, txq, cpu);
4740 if (!netif_xmit_stopped(txq)) {
4741 rc = netdev_start_xmit(skb, dev, txq, 0);
4742 if (dev_xmit_complete(rc))
4743 free_skb = false;
4744 }
4745 HARD_TX_UNLOCK(dev, txq);
4746 if (free_skb) {
4747 trace_xdp_exception(dev, xdp_prog, XDP_TX);
4748 kfree_skb(skb);
4749 }
4750 }
4751
4752 static DEFINE_STATIC_KEY_FALSE(generic_xdp_needed_key);
4753
do_xdp_generic(struct bpf_prog * xdp_prog,struct sk_buff * skb)4754 int do_xdp_generic(struct bpf_prog *xdp_prog, struct sk_buff *skb)
4755 {
4756 if (xdp_prog) {
4757 struct xdp_buff xdp;
4758 u32 act;
4759 int err;
4760
4761 act = netif_receive_generic_xdp(skb, &xdp, xdp_prog);
4762 if (act != XDP_PASS) {
4763 switch (act) {
4764 case XDP_REDIRECT:
4765 err = xdp_do_generic_redirect(skb->dev, skb,
4766 &xdp, xdp_prog);
4767 if (err)
4768 goto out_redir;
4769 break;
4770 case XDP_TX:
4771 generic_xdp_tx(skb, xdp_prog);
4772 break;
4773 }
4774 return XDP_DROP;
4775 }
4776 }
4777 return XDP_PASS;
4778 out_redir:
4779 kfree_skb(skb);
4780 return XDP_DROP;
4781 }
4782 EXPORT_SYMBOL_GPL(do_xdp_generic);
4783
netif_rx_internal(struct sk_buff * skb)4784 static int netif_rx_internal(struct sk_buff *skb)
4785 {
4786 int ret;
4787
4788 net_timestamp_check(netdev_tstamp_prequeue, skb);
4789
4790 trace_netif_rx(skb);
4791
4792 #ifdef CONFIG_RPS
4793 if (static_branch_unlikely(&rps_needed)) {
4794 struct rps_dev_flow voidflow, *rflow = &voidflow;
4795 int cpu;
4796
4797 preempt_disable();
4798 rcu_read_lock();
4799
4800 cpu = get_rps_cpu(skb->dev, skb, &rflow);
4801 if (cpu < 0)
4802 cpu = smp_processor_id();
4803
4804 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
4805
4806 rcu_read_unlock();
4807 preempt_enable();
4808 } else
4809 #endif
4810 {
4811 unsigned int qtail;
4812
4813 ret = enqueue_to_backlog(skb, get_cpu(), &qtail);
4814 put_cpu();
4815 }
4816 return ret;
4817 }
4818
4819 /**
4820 * netif_rx - post buffer to the network code
4821 * @skb: buffer to post
4822 *
4823 * This function receives a packet from a device driver and queues it for
4824 * the upper (protocol) levels to process. It always succeeds. The buffer
4825 * may be dropped during processing for congestion control or by the
4826 * protocol layers.
4827 *
4828 * return values:
4829 * NET_RX_SUCCESS (no congestion)
4830 * NET_RX_DROP (packet was dropped)
4831 *
4832 */
4833
netif_rx(struct sk_buff * skb)4834 int netif_rx(struct sk_buff *skb)
4835 {
4836 int ret;
4837
4838 trace_netif_rx_entry(skb);
4839
4840 ret = netif_rx_internal(skb);
4841 trace_netif_rx_exit(ret);
4842
4843 return ret;
4844 }
4845 EXPORT_SYMBOL(netif_rx);
4846
netif_rx_ni(struct sk_buff * skb)4847 int netif_rx_ni(struct sk_buff *skb)
4848 {
4849 int err;
4850
4851 trace_netif_rx_ni_entry(skb);
4852
4853 preempt_disable();
4854 err = netif_rx_internal(skb);
4855 if (local_softirq_pending())
4856 do_softirq();
4857 preempt_enable();
4858 trace_netif_rx_ni_exit(err);
4859
4860 return err;
4861 }
4862 EXPORT_SYMBOL(netif_rx_ni);
4863
netif_rx_any_context(struct sk_buff * skb)4864 int netif_rx_any_context(struct sk_buff *skb)
4865 {
4866 /*
4867 * If invoked from contexts which do not invoke bottom half
4868 * processing either at return from interrupt or when softrqs are
4869 * reenabled, use netif_rx_ni() which invokes bottomhalf processing
4870 * directly.
4871 */
4872 if (in_interrupt())
4873 return netif_rx(skb);
4874 else
4875 return netif_rx_ni(skb);
4876 }
4877 EXPORT_SYMBOL(netif_rx_any_context);
4878
net_tx_action(struct softirq_action * h)4879 static __latent_entropy void net_tx_action(struct softirq_action *h)
4880 {
4881 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
4882
4883 if (sd->completion_queue) {
4884 struct sk_buff *clist;
4885
4886 local_irq_disable();
4887 clist = sd->completion_queue;
4888 sd->completion_queue = NULL;
4889 local_irq_enable();
4890
4891 while (clist) {
4892 struct sk_buff *skb = clist;
4893
4894 clist = clist->next;
4895
4896 WARN_ON(refcount_read(&skb->users));
4897 if (likely(get_kfree_skb_cb(skb)->reason == SKB_REASON_CONSUMED))
4898 trace_consume_skb(skb);
4899 else
4900 trace_kfree_skb(skb, net_tx_action);
4901
4902 if (skb->fclone != SKB_FCLONE_UNAVAILABLE)
4903 __kfree_skb(skb);
4904 else
4905 __kfree_skb_defer(skb);
4906 }
4907
4908 __kfree_skb_flush();
4909 }
4910
4911 if (sd->output_queue) {
4912 struct Qdisc *head;
4913
4914 local_irq_disable();
4915 head = sd->output_queue;
4916 sd->output_queue = NULL;
4917 sd->output_queue_tailp = &sd->output_queue;
4918 local_irq_enable();
4919
4920 rcu_read_lock();
4921
4922 while (head) {
4923 struct Qdisc *q = head;
4924 spinlock_t *root_lock = NULL;
4925
4926 head = head->next_sched;
4927
4928 /* We need to make sure head->next_sched is read
4929 * before clearing __QDISC_STATE_SCHED
4930 */
4931 smp_mb__before_atomic();
4932
4933 if (!(q->flags & TCQ_F_NOLOCK)) {
4934 root_lock = qdisc_lock(q);
4935 spin_lock(root_lock);
4936 } else if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED,
4937 &q->state))) {
4938 /* There is a synchronize_net() between
4939 * STATE_DEACTIVATED flag being set and
4940 * qdisc_reset()/some_qdisc_is_busy() in
4941 * dev_deactivate(), so we can safely bail out
4942 * early here to avoid data race between
4943 * qdisc_deactivate() and some_qdisc_is_busy()
4944 * for lockless qdisc.
4945 */
4946 clear_bit(__QDISC_STATE_SCHED, &q->state);
4947 continue;
4948 }
4949
4950 clear_bit(__QDISC_STATE_SCHED, &q->state);
4951 qdisc_run(q);
4952 if (root_lock)
4953 spin_unlock(root_lock);
4954 }
4955
4956 rcu_read_unlock();
4957 }
4958
4959 xfrm_dev_backlog(sd);
4960 }
4961
4962 #if IS_ENABLED(CONFIG_BRIDGE) && IS_ENABLED(CONFIG_ATM_LANE)
4963 /* This hook is defined here for ATM LANE */
4964 int (*br_fdb_test_addr_hook)(struct net_device *dev,
4965 unsigned char *addr) __read_mostly;
4966 EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook);
4967 #endif
4968
4969 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)4970 sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
4971 struct net_device *orig_dev, bool *another)
4972 {
4973 #ifdef CONFIG_NET_CLS_ACT
4974 struct mini_Qdisc *miniq = rcu_dereference_bh(skb->dev->miniq_ingress);
4975 struct tcf_result cl_res;
4976
4977 /* If there's at least one ingress present somewhere (so
4978 * we get here via enabled static key), remaining devices
4979 * that are not configured with an ingress qdisc will bail
4980 * out here.
4981 */
4982 if (!miniq)
4983 return skb;
4984
4985 if (*pt_prev) {
4986 *ret = deliver_skb(skb, *pt_prev, orig_dev);
4987 *pt_prev = NULL;
4988 }
4989
4990 qdisc_skb_cb(skb)->pkt_len = skb->len;
4991 qdisc_skb_cb(skb)->mru = 0;
4992 skb->tc_at_ingress = 1;
4993 mini_qdisc_bstats_cpu_update(miniq, skb);
4994
4995 switch (tcf_classify_ingress(skb, miniq->block, miniq->filter_list,
4996 &cl_res, false)) {
4997 case TC_ACT_OK:
4998 case TC_ACT_RECLASSIFY:
4999 skb->tc_index = TC_H_MIN(cl_res.classid);
5000 break;
5001 case TC_ACT_SHOT:
5002 mini_qdisc_qstats_cpu_drop(miniq);
5003 kfree_skb(skb);
5004 return NULL;
5005 case TC_ACT_STOLEN:
5006 case TC_ACT_QUEUED:
5007 case TC_ACT_TRAP:
5008 consume_skb(skb);
5009 return NULL;
5010 case TC_ACT_REDIRECT:
5011 /* skb_mac_header check was done by cls/act_bpf, so
5012 * we can safely push the L2 header back before
5013 * redirecting to another netdev
5014 */
5015 __skb_push(skb, skb->mac_len);
5016 if (skb_do_redirect(skb) == -EAGAIN) {
5017 __skb_pull(skb, skb->mac_len);
5018 *another = true;
5019 break;
5020 }
5021 return NULL;
5022 case TC_ACT_CONSUMED:
5023 return NULL;
5024 default:
5025 break;
5026 }
5027 #endif /* CONFIG_NET_CLS_ACT */
5028 return skb;
5029 }
5030
5031 /**
5032 * netdev_is_rx_handler_busy - check if receive handler is registered
5033 * @dev: device to check
5034 *
5035 * Check if a receive handler is already registered for a given device.
5036 * Return true if there one.
5037 *
5038 * The caller must hold the rtnl_mutex.
5039 */
netdev_is_rx_handler_busy(struct net_device * dev)5040 bool netdev_is_rx_handler_busy(struct net_device *dev)
5041 {
5042 ASSERT_RTNL();
5043 return dev && rtnl_dereference(dev->rx_handler);
5044 }
5045 EXPORT_SYMBOL_GPL(netdev_is_rx_handler_busy);
5046
5047 /**
5048 * netdev_rx_handler_register - register receive handler
5049 * @dev: device to register a handler for
5050 * @rx_handler: receive handler to register
5051 * @rx_handler_data: data pointer that is used by rx handler
5052 *
5053 * Register a receive handler for a device. This handler will then be
5054 * called from __netif_receive_skb. A negative errno code is returned
5055 * on a failure.
5056 *
5057 * The caller must hold the rtnl_mutex.
5058 *
5059 * For a general description of rx_handler, see enum rx_handler_result.
5060 */
netdev_rx_handler_register(struct net_device * dev,rx_handler_func_t * rx_handler,void * rx_handler_data)5061 int netdev_rx_handler_register(struct net_device *dev,
5062 rx_handler_func_t *rx_handler,
5063 void *rx_handler_data)
5064 {
5065 if (netdev_is_rx_handler_busy(dev))
5066 return -EBUSY;
5067
5068 if (dev->priv_flags & IFF_NO_RX_HANDLER)
5069 return -EINVAL;
5070
5071 /* Note: rx_handler_data must be set before rx_handler */
5072 rcu_assign_pointer(dev->rx_handler_data, rx_handler_data);
5073 rcu_assign_pointer(dev->rx_handler, rx_handler);
5074
5075 return 0;
5076 }
5077 EXPORT_SYMBOL_GPL(netdev_rx_handler_register);
5078
5079 /**
5080 * netdev_rx_handler_unregister - unregister receive handler
5081 * @dev: device to unregister a handler from
5082 *
5083 * Unregister a receive handler from a device.
5084 *
5085 * The caller must hold the rtnl_mutex.
5086 */
netdev_rx_handler_unregister(struct net_device * dev)5087 void netdev_rx_handler_unregister(struct net_device *dev)
5088 {
5089
5090 ASSERT_RTNL();
5091 RCU_INIT_POINTER(dev->rx_handler, NULL);
5092 /* a reader seeing a non NULL rx_handler in a rcu_read_lock()
5093 * section has a guarantee to see a non NULL rx_handler_data
5094 * as well.
5095 */
5096 synchronize_net();
5097 RCU_INIT_POINTER(dev->rx_handler_data, NULL);
5098 }
5099 EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister);
5100
5101 /*
5102 * Limit the use of PFMEMALLOC reserves to those protocols that implement
5103 * the special handling of PFMEMALLOC skbs.
5104 */
skb_pfmemalloc_protocol(struct sk_buff * skb)5105 static bool skb_pfmemalloc_protocol(struct sk_buff *skb)
5106 {
5107 switch (skb->protocol) {
5108 case htons(ETH_P_ARP):
5109 case htons(ETH_P_IP):
5110 case htons(ETH_P_IPV6):
5111 case htons(ETH_P_8021Q):
5112 case htons(ETH_P_8021AD):
5113 return true;
5114 default:
5115 return false;
5116 }
5117 }
5118
nf_ingress(struct sk_buff * skb,struct packet_type ** pt_prev,int * ret,struct net_device * orig_dev)5119 static inline int nf_ingress(struct sk_buff *skb, struct packet_type **pt_prev,
5120 int *ret, struct net_device *orig_dev)
5121 {
5122 if (nf_hook_ingress_active(skb)) {
5123 int ingress_retval;
5124
5125 if (*pt_prev) {
5126 *ret = deliver_skb(skb, *pt_prev, orig_dev);
5127 *pt_prev = NULL;
5128 }
5129
5130 rcu_read_lock();
5131 ingress_retval = nf_hook_ingress(skb);
5132 rcu_read_unlock();
5133 return ingress_retval;
5134 }
5135 return 0;
5136 }
5137
__netif_receive_skb_core(struct sk_buff ** pskb,bool pfmemalloc,struct packet_type ** ppt_prev)5138 static int __netif_receive_skb_core(struct sk_buff **pskb, bool pfmemalloc,
5139 struct packet_type **ppt_prev)
5140 {
5141 struct packet_type *ptype, *pt_prev;
5142 rx_handler_func_t *rx_handler;
5143 struct sk_buff *skb = *pskb;
5144 struct net_device *orig_dev;
5145 bool deliver_exact = false;
5146 int ret = NET_RX_DROP;
5147 __be16 type;
5148
5149 net_timestamp_check(!netdev_tstamp_prequeue, skb);
5150
5151 trace_netif_receive_skb(skb);
5152
5153 orig_dev = skb->dev;
5154
5155 skb_reset_network_header(skb);
5156 if (!skb_transport_header_was_set(skb))
5157 skb_reset_transport_header(skb);
5158 skb_reset_mac_len(skb);
5159
5160 pt_prev = NULL;
5161
5162 another_round:
5163 skb->skb_iif = skb->dev->ifindex;
5164
5165 __this_cpu_inc(softnet_data.processed);
5166
5167 if (static_branch_unlikely(&generic_xdp_needed_key)) {
5168 int ret2;
5169
5170 preempt_disable();
5171 ret2 = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog), skb);
5172 preempt_enable();
5173
5174 if (ret2 != XDP_PASS) {
5175 ret = NET_RX_DROP;
5176 goto out;
5177 }
5178 skb_reset_mac_len(skb);
5179 }
5180
5181 if (skb->protocol == cpu_to_be16(ETH_P_8021Q) ||
5182 skb->protocol == cpu_to_be16(ETH_P_8021AD)) {
5183 skb = skb_vlan_untag(skb);
5184 if (unlikely(!skb))
5185 goto out;
5186 }
5187
5188 if (skb_skip_tc_classify(skb))
5189 goto skip_classify;
5190
5191 if (pfmemalloc)
5192 goto skip_taps;
5193
5194 list_for_each_entry_rcu(ptype, &ptype_all, list) {
5195 if (pt_prev)
5196 ret = deliver_skb(skb, pt_prev, orig_dev);
5197 pt_prev = ptype;
5198 }
5199
5200 list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) {
5201 if (pt_prev)
5202 ret = deliver_skb(skb, pt_prev, orig_dev);
5203 pt_prev = ptype;
5204 }
5205
5206 skip_taps:
5207 #ifdef CONFIG_NET_INGRESS
5208 if (static_branch_unlikely(&ingress_needed_key)) {
5209 bool another = false;
5210
5211 skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev,
5212 &another);
5213 if (another)
5214 goto another_round;
5215 if (!skb)
5216 goto out;
5217
5218 if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0)
5219 goto out;
5220 }
5221 #endif
5222 skb_reset_redirect(skb);
5223 skip_classify:
5224 if (pfmemalloc && !skb_pfmemalloc_protocol(skb))
5225 goto drop;
5226
5227 if (skb_vlan_tag_present(skb)) {
5228 if (pt_prev) {
5229 ret = deliver_skb(skb, pt_prev, orig_dev);
5230 pt_prev = NULL;
5231 }
5232 if (vlan_do_receive(&skb))
5233 goto another_round;
5234 else if (unlikely(!skb))
5235 goto out;
5236 }
5237
5238 rx_handler = rcu_dereference(skb->dev->rx_handler);
5239 if (rx_handler) {
5240 if (pt_prev) {
5241 ret = deliver_skb(skb, pt_prev, orig_dev);
5242 pt_prev = NULL;
5243 }
5244 switch (rx_handler(&skb)) {
5245 case RX_HANDLER_CONSUMED:
5246 ret = NET_RX_SUCCESS;
5247 goto out;
5248 case RX_HANDLER_ANOTHER:
5249 goto another_round;
5250 case RX_HANDLER_EXACT:
5251 deliver_exact = true;
5252 case RX_HANDLER_PASS:
5253 break;
5254 default:
5255 BUG();
5256 }
5257 }
5258
5259 if (unlikely(skb_vlan_tag_present(skb)) && !netdev_uses_dsa(skb->dev)) {
5260 check_vlan_id:
5261 if (skb_vlan_tag_get_id(skb)) {
5262 /* Vlan id is non 0 and vlan_do_receive() above couldn't
5263 * find vlan device.
5264 */
5265 skb->pkt_type = PACKET_OTHERHOST;
5266 } else if (skb->protocol == cpu_to_be16(ETH_P_8021Q) ||
5267 skb->protocol == cpu_to_be16(ETH_P_8021AD)) {
5268 /* Outer header is 802.1P with vlan 0, inner header is
5269 * 802.1Q or 802.1AD and vlan_do_receive() above could
5270 * not find vlan dev for vlan id 0.
5271 */
5272 __vlan_hwaccel_clear_tag(skb);
5273 skb = skb_vlan_untag(skb);
5274 if (unlikely(!skb))
5275 goto out;
5276 if (vlan_do_receive(&skb))
5277 /* After stripping off 802.1P header with vlan 0
5278 * vlan dev is found for inner header.
5279 */
5280 goto another_round;
5281 else if (unlikely(!skb))
5282 goto out;
5283 else
5284 /* We have stripped outer 802.1P vlan 0 header.
5285 * But could not find vlan dev.
5286 * check again for vlan id to set OTHERHOST.
5287 */
5288 goto check_vlan_id;
5289 }
5290 /* Note: we might in the future use prio bits
5291 * and set skb->priority like in vlan_do_receive()
5292 * For the time being, just ignore Priority Code Point
5293 */
5294 __vlan_hwaccel_clear_tag(skb);
5295 }
5296
5297 type = skb->protocol;
5298
5299 /* deliver only exact match when indicated */
5300 if (likely(!deliver_exact)) {
5301 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5302 &ptype_base[ntohs(type) &
5303 PTYPE_HASH_MASK]);
5304 }
5305
5306 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5307 &orig_dev->ptype_specific);
5308
5309 if (unlikely(skb->dev != orig_dev)) {
5310 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5311 &skb->dev->ptype_specific);
5312 }
5313
5314 if (pt_prev) {
5315 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
5316 goto drop;
5317 *ppt_prev = pt_prev;
5318 } else {
5319 drop:
5320 if (!deliver_exact)
5321 atomic_long_inc(&skb->dev->rx_dropped);
5322 else
5323 atomic_long_inc(&skb->dev->rx_nohandler);
5324 kfree_skb(skb);
5325 /* Jamal, now you will not able to escape explaining
5326 * me how you were going to use this. :-)
5327 */
5328 ret = NET_RX_DROP;
5329 }
5330
5331 out:
5332 /* The invariant here is that if *ppt_prev is not NULL
5333 * then skb should also be non-NULL.
5334 *
5335 * Apparently *ppt_prev assignment above holds this invariant due to
5336 * skb dereferencing near it.
5337 */
5338 *pskb = skb;
5339 return ret;
5340 }
5341
__netif_receive_skb_one_core(struct sk_buff * skb,bool pfmemalloc)5342 static int __netif_receive_skb_one_core(struct sk_buff *skb, bool pfmemalloc)
5343 {
5344 struct net_device *orig_dev = skb->dev;
5345 struct packet_type *pt_prev = NULL;
5346 int ret;
5347
5348 ret = __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5349 if (pt_prev)
5350 ret = INDIRECT_CALL_INET(pt_prev->func, ipv6_rcv, ip_rcv, skb,
5351 skb->dev, pt_prev, orig_dev);
5352 return ret;
5353 }
5354
5355 /**
5356 * netif_receive_skb_core - special purpose version of netif_receive_skb
5357 * @skb: buffer to process
5358 *
5359 * More direct receive version of netif_receive_skb(). It should
5360 * only be used by callers that have a need to skip RPS and Generic XDP.
5361 * Caller must also take care of handling if ``(page_is_)pfmemalloc``.
5362 *
5363 * This function may only be called from softirq context and interrupts
5364 * should be enabled.
5365 *
5366 * Return values (usually ignored):
5367 * NET_RX_SUCCESS: no congestion
5368 * NET_RX_DROP: packet was dropped
5369 */
netif_receive_skb_core(struct sk_buff * skb)5370 int netif_receive_skb_core(struct sk_buff *skb)
5371 {
5372 int ret;
5373
5374 rcu_read_lock();
5375 ret = __netif_receive_skb_one_core(skb, false);
5376 rcu_read_unlock();
5377
5378 return ret;
5379 }
5380 EXPORT_SYMBOL(netif_receive_skb_core);
5381
__netif_receive_skb_list_ptype(struct list_head * head,struct packet_type * pt_prev,struct net_device * orig_dev)5382 static inline void __netif_receive_skb_list_ptype(struct list_head *head,
5383 struct packet_type *pt_prev,
5384 struct net_device *orig_dev)
5385 {
5386 struct sk_buff *skb, *next;
5387
5388 if (!pt_prev)
5389 return;
5390 if (list_empty(head))
5391 return;
5392 if (pt_prev->list_func != NULL)
5393 INDIRECT_CALL_INET(pt_prev->list_func, ipv6_list_rcv,
5394 ip_list_rcv, head, pt_prev, orig_dev);
5395 else
5396 list_for_each_entry_safe(skb, next, head, list) {
5397 skb_list_del_init(skb);
5398 pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
5399 }
5400 }
5401
__netif_receive_skb_list_core(struct list_head * head,bool pfmemalloc)5402 static void __netif_receive_skb_list_core(struct list_head *head, bool pfmemalloc)
5403 {
5404 /* Fast-path assumptions:
5405 * - There is no RX handler.
5406 * - Only one packet_type matches.
5407 * If either of these fails, we will end up doing some per-packet
5408 * processing in-line, then handling the 'last ptype' for the whole
5409 * sublist. This can't cause out-of-order delivery to any single ptype,
5410 * because the 'last ptype' must be constant across the sublist, and all
5411 * other ptypes are handled per-packet.
5412 */
5413 /* Current (common) ptype of sublist */
5414 struct packet_type *pt_curr = NULL;
5415 /* Current (common) orig_dev of sublist */
5416 struct net_device *od_curr = NULL;
5417 struct list_head sublist;
5418 struct sk_buff *skb, *next;
5419
5420 INIT_LIST_HEAD(&sublist);
5421 list_for_each_entry_safe(skb, next, head, list) {
5422 struct net_device *orig_dev = skb->dev;
5423 struct packet_type *pt_prev = NULL;
5424
5425 skb_list_del_init(skb);
5426 __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5427 if (!pt_prev)
5428 continue;
5429 if (pt_curr != pt_prev || od_curr != orig_dev) {
5430 /* dispatch old sublist */
5431 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5432 /* start new sublist */
5433 INIT_LIST_HEAD(&sublist);
5434 pt_curr = pt_prev;
5435 od_curr = orig_dev;
5436 }
5437 list_add_tail(&skb->list, &sublist);
5438 }
5439
5440 /* dispatch final sublist */
5441 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5442 }
5443
__netif_receive_skb(struct sk_buff * skb)5444 static int __netif_receive_skb(struct sk_buff *skb)
5445 {
5446 int ret;
5447
5448 if (sk_memalloc_socks() && skb_pfmemalloc(skb)) {
5449 unsigned int noreclaim_flag;
5450
5451 /*
5452 * PFMEMALLOC skbs are special, they should
5453 * - be delivered to SOCK_MEMALLOC sockets only
5454 * - stay away from userspace
5455 * - have bounded memory usage
5456 *
5457 * Use PF_MEMALLOC as this saves us from propagating the allocation
5458 * context down to all allocation sites.
5459 */
5460 noreclaim_flag = memalloc_noreclaim_save();
5461 ret = __netif_receive_skb_one_core(skb, true);
5462 memalloc_noreclaim_restore(noreclaim_flag);
5463 } else
5464 ret = __netif_receive_skb_one_core(skb, false);
5465
5466 return ret;
5467 }
5468
__netif_receive_skb_list(struct list_head * head)5469 static void __netif_receive_skb_list(struct list_head *head)
5470 {
5471 unsigned long noreclaim_flag = 0;
5472 struct sk_buff *skb, *next;
5473 bool pfmemalloc = false; /* Is current sublist PF_MEMALLOC? */
5474
5475 list_for_each_entry_safe(skb, next, head, list) {
5476 if ((sk_memalloc_socks() && skb_pfmemalloc(skb)) != pfmemalloc) {
5477 struct list_head sublist;
5478
5479 /* Handle the previous sublist */
5480 list_cut_before(&sublist, head, &skb->list);
5481 if (!list_empty(&sublist))
5482 __netif_receive_skb_list_core(&sublist, pfmemalloc);
5483 pfmemalloc = !pfmemalloc;
5484 /* See comments in __netif_receive_skb */
5485 if (pfmemalloc)
5486 noreclaim_flag = memalloc_noreclaim_save();
5487 else
5488 memalloc_noreclaim_restore(noreclaim_flag);
5489 }
5490 }
5491 /* Handle the remaining sublist */
5492 if (!list_empty(head))
5493 __netif_receive_skb_list_core(head, pfmemalloc);
5494 /* Restore pflags */
5495 if (pfmemalloc)
5496 memalloc_noreclaim_restore(noreclaim_flag);
5497 }
5498
generic_xdp_install(struct net_device * dev,struct netdev_bpf * xdp)5499 static int generic_xdp_install(struct net_device *dev, struct netdev_bpf *xdp)
5500 {
5501 struct bpf_prog *old = rtnl_dereference(dev->xdp_prog);
5502 struct bpf_prog *new = xdp->prog;
5503 int ret = 0;
5504
5505 if (new) {
5506 u32 i;
5507
5508 mutex_lock(&new->aux->used_maps_mutex);
5509
5510 /* generic XDP does not work with DEVMAPs that can
5511 * have a bpf_prog installed on an entry
5512 */
5513 for (i = 0; i < new->aux->used_map_cnt; i++) {
5514 if (dev_map_can_have_prog(new->aux->used_maps[i]) ||
5515 cpu_map_prog_allowed(new->aux->used_maps[i])) {
5516 mutex_unlock(&new->aux->used_maps_mutex);
5517 return -EINVAL;
5518 }
5519 }
5520
5521 mutex_unlock(&new->aux->used_maps_mutex);
5522 }
5523
5524 switch (xdp->command) {
5525 case XDP_SETUP_PROG:
5526 rcu_assign_pointer(dev->xdp_prog, new);
5527 if (old)
5528 bpf_prog_put(old);
5529
5530 if (old && !new) {
5531 static_branch_dec(&generic_xdp_needed_key);
5532 } else if (new && !old) {
5533 static_branch_inc(&generic_xdp_needed_key);
5534 dev_disable_lro(dev);
5535 dev_disable_gro_hw(dev);
5536 }
5537 break;
5538
5539 default:
5540 ret = -EINVAL;
5541 break;
5542 }
5543
5544 return ret;
5545 }
5546
netif_receive_skb_internal(struct sk_buff * skb)5547 static int netif_receive_skb_internal(struct sk_buff *skb)
5548 {
5549 int ret;
5550
5551 net_timestamp_check(netdev_tstamp_prequeue, skb);
5552
5553 if (skb_defer_rx_timestamp(skb))
5554 return NET_RX_SUCCESS;
5555
5556 rcu_read_lock();
5557 #ifdef CONFIG_RPS
5558 if (static_branch_unlikely(&rps_needed)) {
5559 struct rps_dev_flow voidflow, *rflow = &voidflow;
5560 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5561
5562 if (cpu >= 0) {
5563 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5564 rcu_read_unlock();
5565 return ret;
5566 }
5567 }
5568 #endif
5569 ret = __netif_receive_skb(skb);
5570 rcu_read_unlock();
5571 return ret;
5572 }
5573
netif_receive_skb_list_internal(struct list_head * head)5574 static void netif_receive_skb_list_internal(struct list_head *head)
5575 {
5576 struct sk_buff *skb, *next;
5577 struct list_head sublist;
5578
5579 INIT_LIST_HEAD(&sublist);
5580 list_for_each_entry_safe(skb, next, head, list) {
5581 net_timestamp_check(netdev_tstamp_prequeue, skb);
5582 skb_list_del_init(skb);
5583 if (!skb_defer_rx_timestamp(skb))
5584 list_add_tail(&skb->list, &sublist);
5585 }
5586 list_splice_init(&sublist, head);
5587
5588 rcu_read_lock();
5589 #ifdef CONFIG_RPS
5590 if (static_branch_unlikely(&rps_needed)) {
5591 list_for_each_entry_safe(skb, next, head, list) {
5592 struct rps_dev_flow voidflow, *rflow = &voidflow;
5593 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5594
5595 if (cpu >= 0) {
5596 /* Will be handled, remove from list */
5597 skb_list_del_init(skb);
5598 enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5599 }
5600 }
5601 }
5602 #endif
5603 __netif_receive_skb_list(head);
5604 rcu_read_unlock();
5605 }
5606
5607 /**
5608 * netif_receive_skb - process receive buffer from network
5609 * @skb: buffer to process
5610 *
5611 * netif_receive_skb() is the main receive data processing function.
5612 * It always succeeds. The buffer may be dropped during processing
5613 * for congestion control or by the protocol layers.
5614 *
5615 * This function may only be called from softirq context and interrupts
5616 * should be enabled.
5617 *
5618 * Return values (usually ignored):
5619 * NET_RX_SUCCESS: no congestion
5620 * NET_RX_DROP: packet was dropped
5621 */
netif_receive_skb(struct sk_buff * skb)5622 int netif_receive_skb(struct sk_buff *skb)
5623 {
5624 int ret;
5625
5626 trace_netif_receive_skb_entry(skb);
5627
5628 ret = netif_receive_skb_internal(skb);
5629 trace_netif_receive_skb_exit(ret);
5630
5631 return ret;
5632 }
5633 EXPORT_SYMBOL(netif_receive_skb);
5634
5635 /**
5636 * netif_receive_skb_list - process many receive buffers from network
5637 * @head: list of skbs to process.
5638 *
5639 * Since return value of netif_receive_skb() is normally ignored, and
5640 * wouldn't be meaningful for a list, this function returns void.
5641 *
5642 * This function may only be called from softirq context and interrupts
5643 * should be enabled.
5644 */
netif_receive_skb_list(struct list_head * head)5645 void netif_receive_skb_list(struct list_head *head)
5646 {
5647 struct sk_buff *skb;
5648
5649 if (list_empty(head))
5650 return;
5651 if (trace_netif_receive_skb_list_entry_enabled()) {
5652 list_for_each_entry(skb, head, list)
5653 trace_netif_receive_skb_list_entry(skb);
5654 }
5655 netif_receive_skb_list_internal(head);
5656 trace_netif_receive_skb_list_exit(0);
5657 }
5658 EXPORT_SYMBOL(netif_receive_skb_list);
5659
5660 static DEFINE_PER_CPU(struct work_struct, flush_works);
5661
5662 /* Network device is going away, flush any packets still pending */
flush_backlog(struct work_struct * work)5663 static void flush_backlog(struct work_struct *work)
5664 {
5665 struct sk_buff *skb, *tmp;
5666 struct softnet_data *sd;
5667
5668 local_bh_disable();
5669 sd = this_cpu_ptr(&softnet_data);
5670
5671 local_irq_disable();
5672 rps_lock(sd);
5673 skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) {
5674 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5675 __skb_unlink(skb, &sd->input_pkt_queue);
5676 dev_kfree_skb_irq(skb);
5677 input_queue_head_incr(sd);
5678 }
5679 }
5680 rps_unlock(sd);
5681 local_irq_enable();
5682
5683 skb_queue_walk_safe(&sd->process_queue, skb, tmp) {
5684 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5685 __skb_unlink(skb, &sd->process_queue);
5686 kfree_skb(skb);
5687 input_queue_head_incr(sd);
5688 }
5689 }
5690 local_bh_enable();
5691 }
5692
flush_required(int cpu)5693 static bool flush_required(int cpu)
5694 {
5695 #if IS_ENABLED(CONFIG_RPS)
5696 struct softnet_data *sd = &per_cpu(softnet_data, cpu);
5697 bool do_flush;
5698
5699 local_irq_disable();
5700 rps_lock(sd);
5701
5702 /* as insertion into process_queue happens with the rps lock held,
5703 * process_queue access may race only with dequeue
5704 */
5705 do_flush = !skb_queue_empty(&sd->input_pkt_queue) ||
5706 !skb_queue_empty_lockless(&sd->process_queue);
5707 rps_unlock(sd);
5708 local_irq_enable();
5709
5710 return do_flush;
5711 #endif
5712 /* without RPS we can't safely check input_pkt_queue: during a
5713 * concurrent remote skb_queue_splice() we can detect as empty both
5714 * input_pkt_queue and process_queue even if the latter could end-up
5715 * containing a lot of packets.
5716 */
5717 return true;
5718 }
5719
flush_all_backlogs(void)5720 static void flush_all_backlogs(void)
5721 {
5722 static cpumask_t flush_cpus;
5723 unsigned int cpu;
5724
5725 /* since we are under rtnl lock protection we can use static data
5726 * for the cpumask and avoid allocating on stack the possibly
5727 * large mask
5728 */
5729 ASSERT_RTNL();
5730
5731 get_online_cpus();
5732
5733 cpumask_clear(&flush_cpus);
5734 for_each_online_cpu(cpu) {
5735 if (flush_required(cpu)) {
5736 queue_work_on(cpu, system_highpri_wq,
5737 per_cpu_ptr(&flush_works, cpu));
5738 cpumask_set_cpu(cpu, &flush_cpus);
5739 }
5740 }
5741
5742 /* we can have in flight packet[s] on the cpus we are not flushing,
5743 * synchronize_net() in rollback_registered_many() will take care of
5744 * them
5745 */
5746 for_each_cpu(cpu, &flush_cpus)
5747 flush_work(per_cpu_ptr(&flush_works, cpu));
5748
5749 put_online_cpus();
5750 }
5751
5752 /* Pass the currently batched GRO_NORMAL SKBs up to the stack. */
gro_normal_list(struct napi_struct * napi)5753 static void gro_normal_list(struct napi_struct *napi)
5754 {
5755 if (!napi->rx_count)
5756 return;
5757 netif_receive_skb_list_internal(&napi->rx_list);
5758 INIT_LIST_HEAD(&napi->rx_list);
5759 napi->rx_count = 0;
5760 }
5761
5762 /* Queue one GRO_NORMAL SKB up for list processing. If batch size exceeded,
5763 * pass the whole batch up to the stack.
5764 */
gro_normal_one(struct napi_struct * napi,struct sk_buff * skb,int segs)5765 static void gro_normal_one(struct napi_struct *napi, struct sk_buff *skb, int segs)
5766 {
5767 list_add_tail(&skb->list, &napi->rx_list);
5768 napi->rx_count += segs;
5769 if (napi->rx_count >= gro_normal_batch)
5770 gro_normal_list(napi);
5771 }
5772
5773 INDIRECT_CALLABLE_DECLARE(int inet_gro_complete(struct sk_buff *, int));
5774 INDIRECT_CALLABLE_DECLARE(int ipv6_gro_complete(struct sk_buff *, int));
napi_gro_complete(struct napi_struct * napi,struct sk_buff * skb)5775 static int napi_gro_complete(struct napi_struct *napi, struct sk_buff *skb)
5776 {
5777 struct packet_offload *ptype;
5778 __be16 type = skb->protocol;
5779 struct list_head *head = &offload_base;
5780 int err = -ENOENT;
5781
5782 BUILD_BUG_ON(sizeof(struct napi_gro_cb) > sizeof(skb->cb));
5783
5784 if (NAPI_GRO_CB(skb)->count == 1) {
5785 skb_shinfo(skb)->gso_size = 0;
5786 goto out;
5787 }
5788
5789 rcu_read_lock();
5790 list_for_each_entry_rcu(ptype, head, list) {
5791 if (ptype->type != type || !ptype->callbacks.gro_complete)
5792 continue;
5793
5794 err = INDIRECT_CALL_INET(ptype->callbacks.gro_complete,
5795 ipv6_gro_complete, inet_gro_complete,
5796 skb, 0);
5797 break;
5798 }
5799 rcu_read_unlock();
5800
5801 if (err) {
5802 WARN_ON(&ptype->list == head);
5803 kfree_skb(skb);
5804 return NET_RX_SUCCESS;
5805 }
5806
5807 out:
5808 gro_normal_one(napi, skb, NAPI_GRO_CB(skb)->count);
5809 return NET_RX_SUCCESS;
5810 }
5811
__napi_gro_flush_chain(struct napi_struct * napi,u32 index,bool flush_old)5812 static void __napi_gro_flush_chain(struct napi_struct *napi, u32 index,
5813 bool flush_old)
5814 {
5815 struct list_head *head = &napi->gro_hash[index].list;
5816 struct sk_buff *skb, *p;
5817
5818 list_for_each_entry_safe_reverse(skb, p, head, list) {
5819 if (flush_old && NAPI_GRO_CB(skb)->age == jiffies)
5820 return;
5821 skb_list_del_init(skb);
5822 napi_gro_complete(napi, skb);
5823 napi->gro_hash[index].count--;
5824 }
5825
5826 if (!napi->gro_hash[index].count)
5827 __clear_bit(index, &napi->gro_bitmask);
5828 }
5829
5830 /* napi->gro_hash[].list contains packets ordered by age.
5831 * youngest packets at the head of it.
5832 * Complete skbs in reverse order to reduce latencies.
5833 */
napi_gro_flush(struct napi_struct * napi,bool flush_old)5834 void napi_gro_flush(struct napi_struct *napi, bool flush_old)
5835 {
5836 unsigned long bitmask = napi->gro_bitmask;
5837 unsigned int i, base = ~0U;
5838
5839 while ((i = ffs(bitmask)) != 0) {
5840 bitmask >>= i;
5841 base += i;
5842 __napi_gro_flush_chain(napi, base, flush_old);
5843 }
5844 }
5845 EXPORT_SYMBOL(napi_gro_flush);
5846
gro_list_prepare(struct napi_struct * napi,struct sk_buff * skb)5847 static struct list_head *gro_list_prepare(struct napi_struct *napi,
5848 struct sk_buff *skb)
5849 {
5850 unsigned int maclen = skb->dev->hard_header_len;
5851 u32 hash = skb_get_hash_raw(skb);
5852 struct list_head *head;
5853 struct sk_buff *p;
5854
5855 head = &napi->gro_hash[hash & (GRO_HASH_BUCKETS - 1)].list;
5856 list_for_each_entry(p, head, list) {
5857 unsigned long diffs;
5858
5859 NAPI_GRO_CB(p)->flush = 0;
5860
5861 if (hash != skb_get_hash_raw(p)) {
5862 NAPI_GRO_CB(p)->same_flow = 0;
5863 continue;
5864 }
5865
5866 diffs = (unsigned long)p->dev ^ (unsigned long)skb->dev;
5867 diffs |= skb_vlan_tag_present(p) ^ skb_vlan_tag_present(skb);
5868 if (skb_vlan_tag_present(p))
5869 diffs |= skb_vlan_tag_get(p) ^ skb_vlan_tag_get(skb);
5870 diffs |= skb_metadata_dst_cmp(p, skb);
5871 diffs |= skb_metadata_differs(p, skb);
5872 if (maclen == ETH_HLEN)
5873 diffs |= compare_ether_header(skb_mac_header(p),
5874 skb_mac_header(skb));
5875 else if (!diffs)
5876 diffs = memcmp(skb_mac_header(p),
5877 skb_mac_header(skb),
5878 maclen);
5879
5880 diffs |= skb_get_nfct(p) ^ skb_get_nfct(skb);
5881 #if IS_ENABLED(CONFIG_SKB_EXTENSIONS) && IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
5882 if (!diffs) {
5883 struct tc_skb_ext *skb_ext = skb_ext_find(skb, TC_SKB_EXT);
5884 struct tc_skb_ext *p_ext = skb_ext_find(p, TC_SKB_EXT);
5885
5886 diffs |= (!!p_ext) ^ (!!skb_ext);
5887 if (!diffs && unlikely(skb_ext))
5888 diffs |= p_ext->chain ^ skb_ext->chain;
5889 }
5890 #endif
5891
5892 NAPI_GRO_CB(p)->same_flow = !diffs;
5893 }
5894
5895 return head;
5896 }
5897
skb_gro_reset_offset(struct sk_buff * skb,u32 nhoff)5898 static inline void skb_gro_reset_offset(struct sk_buff *skb, u32 nhoff)
5899 {
5900 const struct skb_shared_info *pinfo = skb_shinfo(skb);
5901 const skb_frag_t *frag0 = &pinfo->frags[0];
5902
5903 NAPI_GRO_CB(skb)->data_offset = 0;
5904 NAPI_GRO_CB(skb)->frag0 = NULL;
5905 NAPI_GRO_CB(skb)->frag0_len = 0;
5906
5907 if (!skb_headlen(skb) && pinfo->nr_frags &&
5908 !PageHighMem(skb_frag_page(frag0)) &&
5909 (!NET_IP_ALIGN || !((skb_frag_off(frag0) + nhoff) & 3))) {
5910 NAPI_GRO_CB(skb)->frag0 = skb_frag_address(frag0);
5911 NAPI_GRO_CB(skb)->frag0_len = min_t(unsigned int,
5912 skb_frag_size(frag0),
5913 skb->end - skb->tail);
5914 }
5915 }
5916
gro_pull_from_frag0(struct sk_buff * skb,int grow)5917 static void gro_pull_from_frag0(struct sk_buff *skb, int grow)
5918 {
5919 struct skb_shared_info *pinfo = skb_shinfo(skb);
5920
5921 BUG_ON(skb->end - skb->tail < grow);
5922
5923 memcpy(skb_tail_pointer(skb), NAPI_GRO_CB(skb)->frag0, grow);
5924
5925 skb->data_len -= grow;
5926 skb->tail += grow;
5927
5928 skb_frag_off_add(&pinfo->frags[0], grow);
5929 skb_frag_size_sub(&pinfo->frags[0], grow);
5930
5931 if (unlikely(!skb_frag_size(&pinfo->frags[0]))) {
5932 skb_frag_unref(skb, 0);
5933 memmove(pinfo->frags, pinfo->frags + 1,
5934 --pinfo->nr_frags * sizeof(pinfo->frags[0]));
5935 }
5936 }
5937
gro_flush_oldest(struct napi_struct * napi,struct list_head * head)5938 static void gro_flush_oldest(struct napi_struct *napi, struct list_head *head)
5939 {
5940 struct sk_buff *oldest;
5941
5942 oldest = list_last_entry(head, struct sk_buff, list);
5943
5944 /* We are called with head length >= MAX_GRO_SKBS, so this is
5945 * impossible.
5946 */
5947 if (WARN_ON_ONCE(!oldest))
5948 return;
5949
5950 /* Do not adjust napi->gro_hash[].count, caller is adding a new
5951 * SKB to the chain.
5952 */
5953 skb_list_del_init(oldest);
5954 napi_gro_complete(napi, oldest);
5955 }
5956
5957 INDIRECT_CALLABLE_DECLARE(struct sk_buff *inet_gro_receive(struct list_head *,
5958 struct sk_buff *));
5959 INDIRECT_CALLABLE_DECLARE(struct sk_buff *ipv6_gro_receive(struct list_head *,
5960 struct sk_buff *));
dev_gro_receive(struct napi_struct * napi,struct sk_buff * skb)5961 static enum gro_result dev_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
5962 {
5963 u32 hash = skb_get_hash_raw(skb) & (GRO_HASH_BUCKETS - 1);
5964 struct list_head *head = &offload_base;
5965 struct packet_offload *ptype;
5966 __be16 type = skb->protocol;
5967 struct list_head *gro_head;
5968 struct sk_buff *pp = NULL;
5969 enum gro_result ret;
5970 int same_flow;
5971 int grow;
5972
5973 if (netif_elide_gro(skb->dev))
5974 goto normal;
5975
5976 gro_head = gro_list_prepare(napi, skb);
5977
5978 rcu_read_lock();
5979 list_for_each_entry_rcu(ptype, head, list) {
5980 if (ptype->type != type || !ptype->callbacks.gro_receive)
5981 continue;
5982
5983 skb_set_network_header(skb, skb_gro_offset(skb));
5984 skb_reset_mac_len(skb);
5985 NAPI_GRO_CB(skb)->same_flow = 0;
5986 NAPI_GRO_CB(skb)->flush = skb_is_gso(skb) || skb_has_frag_list(skb);
5987 NAPI_GRO_CB(skb)->free = 0;
5988 NAPI_GRO_CB(skb)->encap_mark = 0;
5989 NAPI_GRO_CB(skb)->recursion_counter = 0;
5990 NAPI_GRO_CB(skb)->is_fou = 0;
5991 NAPI_GRO_CB(skb)->is_atomic = 1;
5992 NAPI_GRO_CB(skb)->gro_remcsum_start = 0;
5993
5994 /* Setup for GRO checksum validation */
5995 switch (skb->ip_summed) {
5996 case CHECKSUM_COMPLETE:
5997 NAPI_GRO_CB(skb)->csum = skb->csum;
5998 NAPI_GRO_CB(skb)->csum_valid = 1;
5999 NAPI_GRO_CB(skb)->csum_cnt = 0;
6000 break;
6001 case CHECKSUM_UNNECESSARY:
6002 NAPI_GRO_CB(skb)->csum_cnt = skb->csum_level + 1;
6003 NAPI_GRO_CB(skb)->csum_valid = 0;
6004 break;
6005 default:
6006 NAPI_GRO_CB(skb)->csum_cnt = 0;
6007 NAPI_GRO_CB(skb)->csum_valid = 0;
6008 }
6009
6010 pp = INDIRECT_CALL_INET(ptype->callbacks.gro_receive,
6011 ipv6_gro_receive, inet_gro_receive,
6012 gro_head, skb);
6013 break;
6014 }
6015 rcu_read_unlock();
6016
6017 if (&ptype->list == head)
6018 goto normal;
6019
6020 if (PTR_ERR(pp) == -EINPROGRESS) {
6021 ret = GRO_CONSUMED;
6022 goto ok;
6023 }
6024
6025 same_flow = NAPI_GRO_CB(skb)->same_flow;
6026 ret = NAPI_GRO_CB(skb)->free ? GRO_MERGED_FREE : GRO_MERGED;
6027
6028 if (pp) {
6029 skb_list_del_init(pp);
6030 napi_gro_complete(napi, pp);
6031 napi->gro_hash[hash].count--;
6032 }
6033
6034 if (same_flow)
6035 goto ok;
6036
6037 if (NAPI_GRO_CB(skb)->flush)
6038 goto normal;
6039
6040 if (unlikely(napi->gro_hash[hash].count >= MAX_GRO_SKBS)) {
6041 gro_flush_oldest(napi, gro_head);
6042 } else {
6043 napi->gro_hash[hash].count++;
6044 }
6045 NAPI_GRO_CB(skb)->count = 1;
6046 NAPI_GRO_CB(skb)->age = jiffies;
6047 NAPI_GRO_CB(skb)->last = skb;
6048 skb_shinfo(skb)->gso_size = skb_gro_len(skb);
6049 list_add(&skb->list, gro_head);
6050 ret = GRO_HELD;
6051
6052 pull:
6053 grow = skb_gro_offset(skb) - skb_headlen(skb);
6054 if (grow > 0)
6055 gro_pull_from_frag0(skb, grow);
6056 ok:
6057 if (napi->gro_hash[hash].count) {
6058 if (!test_bit(hash, &napi->gro_bitmask))
6059 __set_bit(hash, &napi->gro_bitmask);
6060 } else if (test_bit(hash, &napi->gro_bitmask)) {
6061 __clear_bit(hash, &napi->gro_bitmask);
6062 }
6063
6064 return ret;
6065
6066 normal:
6067 ret = GRO_NORMAL;
6068 goto pull;
6069 }
6070
gro_find_receive_by_type(__be16 type)6071 struct packet_offload *gro_find_receive_by_type(__be16 type)
6072 {
6073 struct list_head *offload_head = &offload_base;
6074 struct packet_offload *ptype;
6075
6076 list_for_each_entry_rcu(ptype, offload_head, list) {
6077 if (ptype->type != type || !ptype->callbacks.gro_receive)
6078 continue;
6079 return ptype;
6080 }
6081 return NULL;
6082 }
6083 EXPORT_SYMBOL(gro_find_receive_by_type);
6084
gro_find_complete_by_type(__be16 type)6085 struct packet_offload *gro_find_complete_by_type(__be16 type)
6086 {
6087 struct list_head *offload_head = &offload_base;
6088 struct packet_offload *ptype;
6089
6090 list_for_each_entry_rcu(ptype, offload_head, list) {
6091 if (ptype->type != type || !ptype->callbacks.gro_complete)
6092 continue;
6093 return ptype;
6094 }
6095 return NULL;
6096 }
6097 EXPORT_SYMBOL(gro_find_complete_by_type);
6098
napi_skb_free_stolen_head(struct sk_buff * skb)6099 static void napi_skb_free_stolen_head(struct sk_buff *skb)
6100 {
6101 skb_dst_drop(skb);
6102 skb_ext_put(skb);
6103 kmem_cache_free(skbuff_head_cache, skb);
6104 }
6105
napi_skb_finish(struct napi_struct * napi,struct sk_buff * skb,gro_result_t ret)6106 static gro_result_t napi_skb_finish(struct napi_struct *napi,
6107 struct sk_buff *skb,
6108 gro_result_t ret)
6109 {
6110 switch (ret) {
6111 case GRO_NORMAL:
6112 gro_normal_one(napi, skb, 1);
6113 break;
6114
6115 case GRO_DROP:
6116 kfree_skb(skb);
6117 break;
6118
6119 case GRO_MERGED_FREE:
6120 if (NAPI_GRO_CB(skb)->free == NAPI_GRO_FREE_STOLEN_HEAD)
6121 napi_skb_free_stolen_head(skb);
6122 else
6123 __kfree_skb(skb);
6124 break;
6125
6126 case GRO_HELD:
6127 case GRO_MERGED:
6128 case GRO_CONSUMED:
6129 break;
6130 }
6131
6132 return ret;
6133 }
6134
napi_gro_receive(struct napi_struct * napi,struct sk_buff * skb)6135 gro_result_t napi_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
6136 {
6137 gro_result_t ret;
6138
6139 skb_mark_napi_id(skb, napi);
6140 trace_napi_gro_receive_entry(skb);
6141
6142 skb_gro_reset_offset(skb, 0);
6143
6144 ret = napi_skb_finish(napi, skb, dev_gro_receive(napi, skb));
6145 trace_napi_gro_receive_exit(ret);
6146
6147 return ret;
6148 }
6149 EXPORT_SYMBOL(napi_gro_receive);
6150
napi_reuse_skb(struct napi_struct * napi,struct sk_buff * skb)6151 static void napi_reuse_skb(struct napi_struct *napi, struct sk_buff *skb)
6152 {
6153 if (unlikely(skb->pfmemalloc)) {
6154 consume_skb(skb);
6155 return;
6156 }
6157 __skb_pull(skb, skb_headlen(skb));
6158 /* restore the reserve we had after netdev_alloc_skb_ip_align() */
6159 skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN - skb_headroom(skb));
6160 __vlan_hwaccel_clear_tag(skb);
6161 skb->dev = napi->dev;
6162 skb->skb_iif = 0;
6163
6164 /* eth_type_trans() assumes pkt_type is PACKET_HOST */
6165 skb->pkt_type = PACKET_HOST;
6166
6167 skb->encapsulation = 0;
6168 skb_shinfo(skb)->gso_type = 0;
6169 skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
6170 skb_ext_reset(skb);
6171 nf_reset_ct(skb);
6172
6173 napi->skb = skb;
6174 }
6175
napi_get_frags(struct napi_struct * napi)6176 struct sk_buff *napi_get_frags(struct napi_struct *napi)
6177 {
6178 struct sk_buff *skb = napi->skb;
6179
6180 if (!skb) {
6181 skb = napi_alloc_skb(napi, GRO_MAX_HEAD);
6182 if (skb) {
6183 napi->skb = skb;
6184 skb_mark_napi_id(skb, napi);
6185 }
6186 }
6187 return skb;
6188 }
6189 EXPORT_SYMBOL(napi_get_frags);
6190
napi_frags_finish(struct napi_struct * napi,struct sk_buff * skb,gro_result_t ret)6191 static gro_result_t napi_frags_finish(struct napi_struct *napi,
6192 struct sk_buff *skb,
6193 gro_result_t ret)
6194 {
6195 switch (ret) {
6196 case GRO_NORMAL:
6197 case GRO_HELD:
6198 __skb_push(skb, ETH_HLEN);
6199 skb->protocol = eth_type_trans(skb, skb->dev);
6200 if (ret == GRO_NORMAL)
6201 gro_normal_one(napi, skb, 1);
6202 break;
6203
6204 case GRO_DROP:
6205 napi_reuse_skb(napi, skb);
6206 break;
6207
6208 case GRO_MERGED_FREE:
6209 if (NAPI_GRO_CB(skb)->free == NAPI_GRO_FREE_STOLEN_HEAD)
6210 napi_skb_free_stolen_head(skb);
6211 else
6212 napi_reuse_skb(napi, skb);
6213 break;
6214
6215 case GRO_MERGED:
6216 case GRO_CONSUMED:
6217 break;
6218 }
6219
6220 return ret;
6221 }
6222
6223 /* Upper GRO stack assumes network header starts at gro_offset=0
6224 * Drivers could call both napi_gro_frags() and napi_gro_receive()
6225 * We copy ethernet header into skb->data to have a common layout.
6226 */
napi_frags_skb(struct napi_struct * napi)6227 static struct sk_buff *napi_frags_skb(struct napi_struct *napi)
6228 {
6229 struct sk_buff *skb = napi->skb;
6230 const struct ethhdr *eth;
6231 unsigned int hlen = sizeof(*eth);
6232
6233 napi->skb = NULL;
6234
6235 skb_reset_mac_header(skb);
6236 skb_gro_reset_offset(skb, hlen);
6237
6238 if (unlikely(skb_gro_header_hard(skb, hlen))) {
6239 eth = skb_gro_header_slow(skb, hlen, 0);
6240 if (unlikely(!eth)) {
6241 net_warn_ratelimited("%s: dropping impossible skb from %s\n",
6242 __func__, napi->dev->name);
6243 napi_reuse_skb(napi, skb);
6244 return NULL;
6245 }
6246 } else {
6247 eth = (const struct ethhdr *)skb->data;
6248 gro_pull_from_frag0(skb, hlen);
6249 NAPI_GRO_CB(skb)->frag0 += hlen;
6250 NAPI_GRO_CB(skb)->frag0_len -= hlen;
6251 }
6252 __skb_pull(skb, hlen);
6253
6254 /*
6255 * This works because the only protocols we care about don't require
6256 * special handling.
6257 * We'll fix it up properly in napi_frags_finish()
6258 */
6259 skb->protocol = eth->h_proto;
6260
6261 return skb;
6262 }
6263
napi_gro_frags(struct napi_struct * napi)6264 gro_result_t napi_gro_frags(struct napi_struct *napi)
6265 {
6266 gro_result_t ret;
6267 struct sk_buff *skb = napi_frags_skb(napi);
6268
6269 if (!skb)
6270 return GRO_DROP;
6271
6272 trace_napi_gro_frags_entry(skb);
6273
6274 ret = napi_frags_finish(napi, skb, dev_gro_receive(napi, skb));
6275 trace_napi_gro_frags_exit(ret);
6276
6277 return ret;
6278 }
6279 EXPORT_SYMBOL(napi_gro_frags);
6280
6281 /* Compute the checksum from gro_offset and return the folded value
6282 * after adding in any pseudo checksum.
6283 */
__skb_gro_checksum_complete(struct sk_buff * skb)6284 __sum16 __skb_gro_checksum_complete(struct sk_buff *skb)
6285 {
6286 __wsum wsum;
6287 __sum16 sum;
6288
6289 wsum = skb_checksum(skb, skb_gro_offset(skb), skb_gro_len(skb), 0);
6290
6291 /* NAPI_GRO_CB(skb)->csum holds pseudo checksum */
6292 sum = csum_fold(csum_add(NAPI_GRO_CB(skb)->csum, wsum));
6293 /* See comments in __skb_checksum_complete(). */
6294 if (likely(!sum)) {
6295 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
6296 !skb->csum_complete_sw)
6297 netdev_rx_csum_fault(skb->dev, skb);
6298 }
6299
6300 NAPI_GRO_CB(skb)->csum = wsum;
6301 NAPI_GRO_CB(skb)->csum_valid = 1;
6302
6303 return sum;
6304 }
6305 EXPORT_SYMBOL(__skb_gro_checksum_complete);
6306
net_rps_send_ipi(struct softnet_data * remsd)6307 static void net_rps_send_ipi(struct softnet_data *remsd)
6308 {
6309 #ifdef CONFIG_RPS
6310 while (remsd) {
6311 struct softnet_data *next = remsd->rps_ipi_next;
6312
6313 if (cpu_online(remsd->cpu))
6314 smp_call_function_single_async(remsd->cpu, &remsd->csd);
6315 remsd = next;
6316 }
6317 #endif
6318 }
6319
6320 /*
6321 * net_rps_action_and_irq_enable sends any pending IPI's for rps.
6322 * Note: called with local irq disabled, but exits with local irq enabled.
6323 */
net_rps_action_and_irq_enable(struct softnet_data * sd)6324 static void net_rps_action_and_irq_enable(struct softnet_data *sd)
6325 {
6326 #ifdef CONFIG_RPS
6327 struct softnet_data *remsd = sd->rps_ipi_list;
6328
6329 if (remsd) {
6330 sd->rps_ipi_list = NULL;
6331
6332 local_irq_enable();
6333
6334 /* Send pending IPI's to kick RPS processing on remote cpus. */
6335 net_rps_send_ipi(remsd);
6336 } else
6337 #endif
6338 local_irq_enable();
6339 }
6340
sd_has_rps_ipi_waiting(struct softnet_data * sd)6341 static bool sd_has_rps_ipi_waiting(struct softnet_data *sd)
6342 {
6343 #ifdef CONFIG_RPS
6344 return sd->rps_ipi_list != NULL;
6345 #else
6346 return false;
6347 #endif
6348 }
6349
process_backlog(struct napi_struct * napi,int quota)6350 static int process_backlog(struct napi_struct *napi, int quota)
6351 {
6352 struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
6353 bool again = true;
6354 int work = 0;
6355
6356 /* Check if we have pending ipi, its better to send them now,
6357 * not waiting net_rx_action() end.
6358 */
6359 if (sd_has_rps_ipi_waiting(sd)) {
6360 local_irq_disable();
6361 net_rps_action_and_irq_enable(sd);
6362 }
6363
6364 napi->weight = dev_rx_weight;
6365 while (again) {
6366 struct sk_buff *skb;
6367
6368 while ((skb = __skb_dequeue(&sd->process_queue))) {
6369 rcu_read_lock();
6370 __netif_receive_skb(skb);
6371 rcu_read_unlock();
6372 input_queue_head_incr(sd);
6373 if (++work >= quota)
6374 return work;
6375
6376 }
6377
6378 local_irq_disable();
6379 rps_lock(sd);
6380 if (skb_queue_empty(&sd->input_pkt_queue)) {
6381 /*
6382 * Inline a custom version of __napi_complete().
6383 * only current cpu owns and manipulates this napi,
6384 * and NAPI_STATE_SCHED is the only possible flag set
6385 * on backlog.
6386 * We can use a plain write instead of clear_bit(),
6387 * and we dont need an smp_mb() memory barrier.
6388 */
6389 napi->state = 0;
6390 again = false;
6391 } else {
6392 skb_queue_splice_tail_init(&sd->input_pkt_queue,
6393 &sd->process_queue);
6394 }
6395 rps_unlock(sd);
6396 local_irq_enable();
6397 }
6398
6399 return work;
6400 }
6401
6402 /**
6403 * __napi_schedule - schedule for receive
6404 * @n: entry to schedule
6405 *
6406 * The entry's receive function will be scheduled to run.
6407 * Consider using __napi_schedule_irqoff() if hard irqs are masked.
6408 */
__napi_schedule(struct napi_struct * n)6409 void __napi_schedule(struct napi_struct *n)
6410 {
6411 unsigned long flags;
6412
6413 local_irq_save(flags);
6414 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
6415 local_irq_restore(flags);
6416 }
6417 EXPORT_SYMBOL(__napi_schedule);
6418
6419 /**
6420 * napi_schedule_prep - check if napi can be scheduled
6421 * @n: napi context
6422 *
6423 * Test if NAPI routine is already running, and if not mark
6424 * it as running. This is used as a condition variable to
6425 * insure only one NAPI poll instance runs. We also make
6426 * sure there is no pending NAPI disable.
6427 */
napi_schedule_prep(struct napi_struct * n)6428 bool napi_schedule_prep(struct napi_struct *n)
6429 {
6430 unsigned long val, new;
6431
6432 do {
6433 val = READ_ONCE(n->state);
6434 if (unlikely(val & NAPIF_STATE_DISABLE))
6435 return false;
6436 new = val | NAPIF_STATE_SCHED;
6437
6438 /* Sets STATE_MISSED bit if STATE_SCHED was already set
6439 * This was suggested by Alexander Duyck, as compiler
6440 * emits better code than :
6441 * if (val & NAPIF_STATE_SCHED)
6442 * new |= NAPIF_STATE_MISSED;
6443 */
6444 new |= (val & NAPIF_STATE_SCHED) / NAPIF_STATE_SCHED *
6445 NAPIF_STATE_MISSED;
6446 } while (cmpxchg(&n->state, val, new) != val);
6447
6448 return !(val & NAPIF_STATE_SCHED);
6449 }
6450 EXPORT_SYMBOL(napi_schedule_prep);
6451
6452 /**
6453 * __napi_schedule_irqoff - schedule for receive
6454 * @n: entry to schedule
6455 *
6456 * Variant of __napi_schedule() assuming hard irqs are masked.
6457 *
6458 * On PREEMPT_RT enabled kernels this maps to __napi_schedule()
6459 * because the interrupt disabled assumption might not be true
6460 * due to force-threaded interrupts and spinlock substitution.
6461 */
__napi_schedule_irqoff(struct napi_struct * n)6462 void __napi_schedule_irqoff(struct napi_struct *n)
6463 {
6464 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6465 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
6466 else
6467 __napi_schedule(n);
6468 }
6469 EXPORT_SYMBOL(__napi_schedule_irqoff);
6470
napi_complete_done(struct napi_struct * n,int work_done)6471 bool napi_complete_done(struct napi_struct *n, int work_done)
6472 {
6473 unsigned long flags, val, new, timeout = 0;
6474 bool ret = true;
6475
6476 /*
6477 * 1) Don't let napi dequeue from the cpu poll list
6478 * just in case its running on a different cpu.
6479 * 2) If we are busy polling, do nothing here, we have
6480 * the guarantee we will be called later.
6481 */
6482 if (unlikely(n->state & (NAPIF_STATE_NPSVC |
6483 NAPIF_STATE_IN_BUSY_POLL)))
6484 return false;
6485
6486 if (work_done) {
6487 if (n->gro_bitmask)
6488 timeout = READ_ONCE(n->dev->gro_flush_timeout);
6489 n->defer_hard_irqs_count = READ_ONCE(n->dev->napi_defer_hard_irqs);
6490 }
6491 if (n->defer_hard_irqs_count > 0) {
6492 n->defer_hard_irqs_count--;
6493 timeout = READ_ONCE(n->dev->gro_flush_timeout);
6494 if (timeout)
6495 ret = false;
6496 }
6497 if (n->gro_bitmask) {
6498 /* When the NAPI instance uses a timeout and keeps postponing
6499 * it, we need to bound somehow the time packets are kept in
6500 * the GRO layer
6501 */
6502 napi_gro_flush(n, !!timeout);
6503 }
6504
6505 gro_normal_list(n);
6506
6507 if (unlikely(!list_empty(&n->poll_list))) {
6508 /* If n->poll_list is not empty, we need to mask irqs */
6509 local_irq_save(flags);
6510 list_del_init(&n->poll_list);
6511 local_irq_restore(flags);
6512 }
6513
6514 do {
6515 val = READ_ONCE(n->state);
6516
6517 WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED));
6518
6519 new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED);
6520
6521 /* If STATE_MISSED was set, leave STATE_SCHED set,
6522 * because we will call napi->poll() one more time.
6523 * This C code was suggested by Alexander Duyck to help gcc.
6524 */
6525 new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED *
6526 NAPIF_STATE_SCHED;
6527 } while (cmpxchg(&n->state, val, new) != val);
6528
6529 if (unlikely(val & NAPIF_STATE_MISSED)) {
6530 __napi_schedule(n);
6531 return false;
6532 }
6533
6534 if (timeout)
6535 hrtimer_start(&n->timer, ns_to_ktime(timeout),
6536 HRTIMER_MODE_REL_PINNED);
6537 return ret;
6538 }
6539 EXPORT_SYMBOL(napi_complete_done);
6540
6541 /* must be called under rcu_read_lock(), as we dont take a reference */
napi_by_id(unsigned int napi_id)6542 static struct napi_struct *napi_by_id(unsigned int napi_id)
6543 {
6544 unsigned int hash = napi_id % HASH_SIZE(napi_hash);
6545 struct napi_struct *napi;
6546
6547 hlist_for_each_entry_rcu(napi, &napi_hash[hash], napi_hash_node)
6548 if (napi->napi_id == napi_id)
6549 return napi;
6550
6551 return NULL;
6552 }
6553
6554 #if defined(CONFIG_NET_RX_BUSY_POLL)
6555
6556 #define BUSY_POLL_BUDGET 8
6557
busy_poll_stop(struct napi_struct * napi,void * have_poll_lock)6558 static void busy_poll_stop(struct napi_struct *napi, void *have_poll_lock)
6559 {
6560 int rc;
6561
6562 /* Busy polling means there is a high chance device driver hard irq
6563 * could not grab NAPI_STATE_SCHED, and that NAPI_STATE_MISSED was
6564 * set in napi_schedule_prep().
6565 * Since we are about to call napi->poll() once more, we can safely
6566 * clear NAPI_STATE_MISSED.
6567 *
6568 * Note: x86 could use a single "lock and ..." instruction
6569 * to perform these two clear_bit()
6570 */
6571 clear_bit(NAPI_STATE_MISSED, &napi->state);
6572 clear_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state);
6573
6574 local_bh_disable();
6575
6576 /* All we really want here is to re-enable device interrupts.
6577 * Ideally, a new ndo_busy_poll_stop() could avoid another round.
6578 */
6579 rc = napi->poll(napi, BUSY_POLL_BUDGET);
6580 /* We can't gro_normal_list() here, because napi->poll() might have
6581 * rearmed the napi (napi_complete_done()) in which case it could
6582 * already be running on another CPU.
6583 */
6584 trace_napi_poll(napi, rc, BUSY_POLL_BUDGET);
6585 netpoll_poll_unlock(have_poll_lock);
6586 if (rc == BUSY_POLL_BUDGET) {
6587 /* As the whole budget was spent, we still own the napi so can
6588 * safely handle the rx_list.
6589 */
6590 gro_normal_list(napi);
6591 __napi_schedule(napi);
6592 }
6593 local_bh_enable();
6594 }
6595
napi_busy_loop(unsigned int napi_id,bool (* loop_end)(void *,unsigned long),void * loop_end_arg)6596 void napi_busy_loop(unsigned int napi_id,
6597 bool (*loop_end)(void *, unsigned long),
6598 void *loop_end_arg)
6599 {
6600 unsigned long start_time = loop_end ? busy_loop_current_time() : 0;
6601 int (*napi_poll)(struct napi_struct *napi, int budget);
6602 void *have_poll_lock = NULL;
6603 struct napi_struct *napi;
6604
6605 restart:
6606 napi_poll = NULL;
6607
6608 rcu_read_lock();
6609
6610 napi = napi_by_id(napi_id);
6611 if (!napi)
6612 goto out;
6613
6614 preempt_disable();
6615 for (;;) {
6616 int work = 0;
6617
6618 local_bh_disable();
6619 if (!napi_poll) {
6620 unsigned long val = READ_ONCE(napi->state);
6621
6622 /* If multiple threads are competing for this napi,
6623 * we avoid dirtying napi->state as much as we can.
6624 */
6625 if (val & (NAPIF_STATE_DISABLE | NAPIF_STATE_SCHED |
6626 NAPIF_STATE_IN_BUSY_POLL))
6627 goto count;
6628 if (cmpxchg(&napi->state, val,
6629 val | NAPIF_STATE_IN_BUSY_POLL |
6630 NAPIF_STATE_SCHED) != val)
6631 goto count;
6632 have_poll_lock = netpoll_poll_lock(napi);
6633 napi_poll = napi->poll;
6634 }
6635 work = napi_poll(napi, BUSY_POLL_BUDGET);
6636 trace_napi_poll(napi, work, BUSY_POLL_BUDGET);
6637 gro_normal_list(napi);
6638 count:
6639 if (work > 0)
6640 __NET_ADD_STATS(dev_net(napi->dev),
6641 LINUX_MIB_BUSYPOLLRXPACKETS, work);
6642 local_bh_enable();
6643
6644 if (!loop_end || loop_end(loop_end_arg, start_time))
6645 break;
6646
6647 if (unlikely(need_resched())) {
6648 if (napi_poll)
6649 busy_poll_stop(napi, have_poll_lock);
6650 preempt_enable();
6651 rcu_read_unlock();
6652 cond_resched();
6653 if (loop_end(loop_end_arg, start_time))
6654 return;
6655 goto restart;
6656 }
6657 cpu_relax();
6658 }
6659 if (napi_poll)
6660 busy_poll_stop(napi, have_poll_lock);
6661 preempt_enable();
6662 out:
6663 rcu_read_unlock();
6664 }
6665 EXPORT_SYMBOL(napi_busy_loop);
6666
6667 #endif /* CONFIG_NET_RX_BUSY_POLL */
6668
napi_hash_add(struct napi_struct * napi)6669 static void napi_hash_add(struct napi_struct *napi)
6670 {
6671 if (test_bit(NAPI_STATE_NO_BUSY_POLL, &napi->state))
6672 return;
6673
6674 spin_lock(&napi_hash_lock);
6675
6676 /* 0..NR_CPUS range is reserved for sender_cpu use */
6677 do {
6678 if (unlikely(++napi_gen_id < MIN_NAPI_ID))
6679 napi_gen_id = MIN_NAPI_ID;
6680 } while (napi_by_id(napi_gen_id));
6681 napi->napi_id = napi_gen_id;
6682
6683 hlist_add_head_rcu(&napi->napi_hash_node,
6684 &napi_hash[napi->napi_id % HASH_SIZE(napi_hash)]);
6685
6686 spin_unlock(&napi_hash_lock);
6687 }
6688
6689 /* Warning : caller is responsible to make sure rcu grace period
6690 * is respected before freeing memory containing @napi
6691 */
napi_hash_del(struct napi_struct * napi)6692 static void napi_hash_del(struct napi_struct *napi)
6693 {
6694 spin_lock(&napi_hash_lock);
6695
6696 hlist_del_init_rcu(&napi->napi_hash_node);
6697
6698 spin_unlock(&napi_hash_lock);
6699 }
6700
napi_watchdog(struct hrtimer * timer)6701 static enum hrtimer_restart napi_watchdog(struct hrtimer *timer)
6702 {
6703 struct napi_struct *napi;
6704
6705 napi = container_of(timer, struct napi_struct, timer);
6706
6707 /* Note : we use a relaxed variant of napi_schedule_prep() not setting
6708 * NAPI_STATE_MISSED, since we do not react to a device IRQ.
6709 */
6710 if (!napi_disable_pending(napi) &&
6711 !test_and_set_bit(NAPI_STATE_SCHED, &napi->state))
6712 __napi_schedule_irqoff(napi);
6713
6714 return HRTIMER_NORESTART;
6715 }
6716
init_gro_hash(struct napi_struct * napi)6717 static void init_gro_hash(struct napi_struct *napi)
6718 {
6719 int i;
6720
6721 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6722 INIT_LIST_HEAD(&napi->gro_hash[i].list);
6723 napi->gro_hash[i].count = 0;
6724 }
6725 napi->gro_bitmask = 0;
6726 }
6727
netif_napi_add(struct net_device * dev,struct napi_struct * napi,int (* poll)(struct napi_struct *,int),int weight)6728 void netif_napi_add(struct net_device *dev, struct napi_struct *napi,
6729 int (*poll)(struct napi_struct *, int), int weight)
6730 {
6731 if (WARN_ON(test_and_set_bit(NAPI_STATE_LISTED, &napi->state)))
6732 return;
6733
6734 INIT_LIST_HEAD(&napi->poll_list);
6735 INIT_HLIST_NODE(&napi->napi_hash_node);
6736 hrtimer_init(&napi->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
6737 napi->timer.function = napi_watchdog;
6738 init_gro_hash(napi);
6739 napi->skb = NULL;
6740 INIT_LIST_HEAD(&napi->rx_list);
6741 napi->rx_count = 0;
6742 napi->poll = poll;
6743 if (weight > NAPI_POLL_WEIGHT)
6744 netdev_err_once(dev, "%s() called with weight %d\n", __func__,
6745 weight);
6746 napi->weight = weight;
6747 napi->dev = dev;
6748 #ifdef CONFIG_NETPOLL
6749 napi->poll_owner = -1;
6750 #endif
6751 set_bit(NAPI_STATE_SCHED, &napi->state);
6752 set_bit(NAPI_STATE_NPSVC, &napi->state);
6753 list_add_rcu(&napi->dev_list, &dev->napi_list);
6754 napi_hash_add(napi);
6755 }
6756 EXPORT_SYMBOL(netif_napi_add);
6757
napi_disable(struct napi_struct * n)6758 void napi_disable(struct napi_struct *n)
6759 {
6760 might_sleep();
6761 set_bit(NAPI_STATE_DISABLE, &n->state);
6762
6763 while (test_and_set_bit(NAPI_STATE_SCHED, &n->state))
6764 msleep(1);
6765 while (test_and_set_bit(NAPI_STATE_NPSVC, &n->state))
6766 msleep(1);
6767
6768 hrtimer_cancel(&n->timer);
6769
6770 clear_bit(NAPI_STATE_DISABLE, &n->state);
6771 }
6772 EXPORT_SYMBOL(napi_disable);
6773
flush_gro_hash(struct napi_struct * napi)6774 static void flush_gro_hash(struct napi_struct *napi)
6775 {
6776 int i;
6777
6778 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6779 struct sk_buff *skb, *n;
6780
6781 list_for_each_entry_safe(skb, n, &napi->gro_hash[i].list, list)
6782 kfree_skb(skb);
6783 napi->gro_hash[i].count = 0;
6784 }
6785 }
6786
6787 /* Must be called in process context */
__netif_napi_del(struct napi_struct * napi)6788 void __netif_napi_del(struct napi_struct *napi)
6789 {
6790 if (!test_and_clear_bit(NAPI_STATE_LISTED, &napi->state))
6791 return;
6792
6793 napi_hash_del(napi);
6794 list_del_rcu(&napi->dev_list);
6795 napi_free_frags(napi);
6796
6797 flush_gro_hash(napi);
6798 napi->gro_bitmask = 0;
6799 }
6800 EXPORT_SYMBOL(__netif_napi_del);
6801
napi_poll(struct napi_struct * n,struct list_head * repoll)6802 static int napi_poll(struct napi_struct *n, struct list_head *repoll)
6803 {
6804 void *have;
6805 int work, weight;
6806
6807 list_del_init(&n->poll_list);
6808
6809 have = netpoll_poll_lock(n);
6810
6811 weight = n->weight;
6812
6813 /* This NAPI_STATE_SCHED test is for avoiding a race
6814 * with netpoll's poll_napi(). Only the entity which
6815 * obtains the lock and sees NAPI_STATE_SCHED set will
6816 * actually make the ->poll() call. Therefore we avoid
6817 * accidentally calling ->poll() when NAPI is not scheduled.
6818 */
6819 work = 0;
6820 if (test_bit(NAPI_STATE_SCHED, &n->state)) {
6821 work = n->poll(n, weight);
6822 trace_napi_poll(n, work, weight);
6823 }
6824
6825 if (unlikely(work > weight))
6826 pr_err_once("NAPI poll function %pS returned %d, exceeding its budget of %d.\n",
6827 n->poll, work, weight);
6828
6829 if (likely(work < weight))
6830 goto out_unlock;
6831
6832 /* Drivers must not modify the NAPI state if they
6833 * consume the entire weight. In such cases this code
6834 * still "owns" the NAPI instance and therefore can
6835 * move the instance around on the list at-will.
6836 */
6837 if (unlikely(napi_disable_pending(n))) {
6838 napi_complete(n);
6839 goto out_unlock;
6840 }
6841
6842 if (n->gro_bitmask) {
6843 /* flush too old packets
6844 * If HZ < 1000, flush all packets.
6845 */
6846 napi_gro_flush(n, HZ >= 1000);
6847 }
6848
6849 gro_normal_list(n);
6850
6851 /* Some drivers may have called napi_schedule
6852 * prior to exhausting their budget.
6853 */
6854 if (unlikely(!list_empty(&n->poll_list))) {
6855 pr_warn_once("%s: Budget exhausted after napi rescheduled\n",
6856 n->dev ? n->dev->name : "backlog");
6857 goto out_unlock;
6858 }
6859
6860 list_add_tail(&n->poll_list, repoll);
6861
6862 out_unlock:
6863 netpoll_poll_unlock(have);
6864
6865 return work;
6866 }
6867
net_rx_action(struct softirq_action * h)6868 static __latent_entropy void net_rx_action(struct softirq_action *h)
6869 {
6870 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
6871 unsigned long time_limit = jiffies +
6872 usecs_to_jiffies(netdev_budget_usecs);
6873 int budget = netdev_budget;
6874 LIST_HEAD(list);
6875 LIST_HEAD(repoll);
6876
6877 local_irq_disable();
6878 list_splice_init(&sd->poll_list, &list);
6879 local_irq_enable();
6880
6881 for (;;) {
6882 struct napi_struct *n;
6883
6884 if (list_empty(&list)) {
6885 if (!sd_has_rps_ipi_waiting(sd) && list_empty(&repoll))
6886 goto out;
6887 break;
6888 }
6889
6890 n = list_first_entry(&list, struct napi_struct, poll_list);
6891 budget -= napi_poll(n, &repoll);
6892
6893 /* If softirq window is exhausted then punt.
6894 * Allow this to run for 2 jiffies since which will allow
6895 * an average latency of 1.5/HZ.
6896 */
6897 if (unlikely(budget <= 0 ||
6898 time_after_eq(jiffies, time_limit))) {
6899 sd->time_squeeze++;
6900 break;
6901 }
6902 }
6903
6904 local_irq_disable();
6905
6906 list_splice_tail_init(&sd->poll_list, &list);
6907 list_splice_tail(&repoll, &list);
6908 list_splice(&list, &sd->poll_list);
6909 if (!list_empty(&sd->poll_list))
6910 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
6911
6912 net_rps_action_and_irq_enable(sd);
6913 out:
6914 __kfree_skb_flush();
6915 }
6916
6917 struct netdev_adjacent {
6918 struct net_device *dev;
6919
6920 /* upper master flag, there can only be one master device per list */
6921 bool master;
6922
6923 /* lookup ignore flag */
6924 bool ignore;
6925
6926 /* counter for the number of times this device was added to us */
6927 u16 ref_nr;
6928
6929 /* private field for the users */
6930 void *private;
6931
6932 struct list_head list;
6933 struct rcu_head rcu;
6934 };
6935
__netdev_find_adj(struct net_device * adj_dev,struct list_head * adj_list)6936 static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev,
6937 struct list_head *adj_list)
6938 {
6939 struct netdev_adjacent *adj;
6940
6941 list_for_each_entry(adj, adj_list, list) {
6942 if (adj->dev == adj_dev)
6943 return adj;
6944 }
6945 return NULL;
6946 }
6947
____netdev_has_upper_dev(struct net_device * upper_dev,struct netdev_nested_priv * priv)6948 static int ____netdev_has_upper_dev(struct net_device *upper_dev,
6949 struct netdev_nested_priv *priv)
6950 {
6951 struct net_device *dev = (struct net_device *)priv->data;
6952
6953 return upper_dev == dev;
6954 }
6955
6956 /**
6957 * netdev_has_upper_dev - Check if device is linked to an upper device
6958 * @dev: device
6959 * @upper_dev: upper device to check
6960 *
6961 * Find out if a device is linked to specified upper device and return true
6962 * in case it is. Note that this checks only immediate upper device,
6963 * not through a complete stack of devices. The caller must hold the RTNL lock.
6964 */
netdev_has_upper_dev(struct net_device * dev,struct net_device * upper_dev)6965 bool netdev_has_upper_dev(struct net_device *dev,
6966 struct net_device *upper_dev)
6967 {
6968 struct netdev_nested_priv priv = {
6969 .data = (void *)upper_dev,
6970 };
6971
6972 ASSERT_RTNL();
6973
6974 return netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
6975 &priv);
6976 }
6977 EXPORT_SYMBOL(netdev_has_upper_dev);
6978
6979 /**
6980 * netdev_has_upper_dev_all - Check if device is linked to an upper device
6981 * @dev: device
6982 * @upper_dev: upper device to check
6983 *
6984 * Find out if a device is linked to specified upper device and return true
6985 * in case it is. Note that this checks the entire upper device chain.
6986 * The caller must hold rcu lock.
6987 */
6988
netdev_has_upper_dev_all_rcu(struct net_device * dev,struct net_device * upper_dev)6989 bool netdev_has_upper_dev_all_rcu(struct net_device *dev,
6990 struct net_device *upper_dev)
6991 {
6992 struct netdev_nested_priv priv = {
6993 .data = (void *)upper_dev,
6994 };
6995
6996 return !!netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
6997 &priv);
6998 }
6999 EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu);
7000
7001 /**
7002 * netdev_has_any_upper_dev - Check if device is linked to some device
7003 * @dev: device
7004 *
7005 * Find out if a device is linked to an upper device and return true in case
7006 * it is. The caller must hold the RTNL lock.
7007 */
netdev_has_any_upper_dev(struct net_device * dev)7008 bool netdev_has_any_upper_dev(struct net_device *dev)
7009 {
7010 ASSERT_RTNL();
7011
7012 return !list_empty(&dev->adj_list.upper);
7013 }
7014 EXPORT_SYMBOL(netdev_has_any_upper_dev);
7015
7016 /**
7017 * netdev_master_upper_dev_get - Get master upper device
7018 * @dev: device
7019 *
7020 * Find a master upper device and return pointer to it or NULL in case
7021 * it's not there. The caller must hold the RTNL lock.
7022 */
netdev_master_upper_dev_get(struct net_device * dev)7023 struct net_device *netdev_master_upper_dev_get(struct net_device *dev)
7024 {
7025 struct netdev_adjacent *upper;
7026
7027 ASSERT_RTNL();
7028
7029 if (list_empty(&dev->adj_list.upper))
7030 return NULL;
7031
7032 upper = list_first_entry(&dev->adj_list.upper,
7033 struct netdev_adjacent, list);
7034 if (likely(upper->master))
7035 return upper->dev;
7036 return NULL;
7037 }
7038 EXPORT_SYMBOL(netdev_master_upper_dev_get);
7039
__netdev_master_upper_dev_get(struct net_device * dev)7040 static struct net_device *__netdev_master_upper_dev_get(struct net_device *dev)
7041 {
7042 struct netdev_adjacent *upper;
7043
7044 ASSERT_RTNL();
7045
7046 if (list_empty(&dev->adj_list.upper))
7047 return NULL;
7048
7049 upper = list_first_entry(&dev->adj_list.upper,
7050 struct netdev_adjacent, list);
7051 if (likely(upper->master) && !upper->ignore)
7052 return upper->dev;
7053 return NULL;
7054 }
7055
7056 /**
7057 * netdev_has_any_lower_dev - Check if device is linked to some device
7058 * @dev: device
7059 *
7060 * Find out if a device is linked to a lower device and return true in case
7061 * it is. The caller must hold the RTNL lock.
7062 */
netdev_has_any_lower_dev(struct net_device * dev)7063 static bool netdev_has_any_lower_dev(struct net_device *dev)
7064 {
7065 ASSERT_RTNL();
7066
7067 return !list_empty(&dev->adj_list.lower);
7068 }
7069
netdev_adjacent_get_private(struct list_head * adj_list)7070 void *netdev_adjacent_get_private(struct list_head *adj_list)
7071 {
7072 struct netdev_adjacent *adj;
7073
7074 adj = list_entry(adj_list, struct netdev_adjacent, list);
7075
7076 return adj->private;
7077 }
7078 EXPORT_SYMBOL(netdev_adjacent_get_private);
7079
7080 /**
7081 * netdev_upper_get_next_dev_rcu - Get the next dev from upper list
7082 * @dev: device
7083 * @iter: list_head ** of the current position
7084 *
7085 * Gets the next device from the dev's upper list, starting from iter
7086 * position. The caller must hold RCU read lock.
7087 */
netdev_upper_get_next_dev_rcu(struct net_device * dev,struct list_head ** iter)7088 struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev,
7089 struct list_head **iter)
7090 {
7091 struct netdev_adjacent *upper;
7092
7093 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
7094
7095 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7096
7097 if (&upper->list == &dev->adj_list.upper)
7098 return NULL;
7099
7100 *iter = &upper->list;
7101
7102 return upper->dev;
7103 }
7104 EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu);
7105
__netdev_next_upper_dev(struct net_device * dev,struct list_head ** iter,bool * ignore)7106 static struct net_device *__netdev_next_upper_dev(struct net_device *dev,
7107 struct list_head **iter,
7108 bool *ignore)
7109 {
7110 struct netdev_adjacent *upper;
7111
7112 upper = list_entry((*iter)->next, struct netdev_adjacent, list);
7113
7114 if (&upper->list == &dev->adj_list.upper)
7115 return NULL;
7116
7117 *iter = &upper->list;
7118 *ignore = upper->ignore;
7119
7120 return upper->dev;
7121 }
7122
netdev_next_upper_dev_rcu(struct net_device * dev,struct list_head ** iter)7123 static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev,
7124 struct list_head **iter)
7125 {
7126 struct netdev_adjacent *upper;
7127
7128 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
7129
7130 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7131
7132 if (&upper->list == &dev->adj_list.upper)
7133 return NULL;
7134
7135 *iter = &upper->list;
7136
7137 return upper->dev;
7138 }
7139
__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)7140 static int __netdev_walk_all_upper_dev(struct net_device *dev,
7141 int (*fn)(struct net_device *dev,
7142 struct netdev_nested_priv *priv),
7143 struct netdev_nested_priv *priv)
7144 {
7145 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7146 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7147 int ret, cur = 0;
7148 bool ignore;
7149
7150 now = dev;
7151 iter = &dev->adj_list.upper;
7152
7153 while (1) {
7154 if (now != dev) {
7155 ret = fn(now, priv);
7156 if (ret)
7157 return ret;
7158 }
7159
7160 next = NULL;
7161 while (1) {
7162 udev = __netdev_next_upper_dev(now, &iter, &ignore);
7163 if (!udev)
7164 break;
7165 if (ignore)
7166 continue;
7167
7168 next = udev;
7169 niter = &udev->adj_list.upper;
7170 dev_stack[cur] = now;
7171 iter_stack[cur++] = iter;
7172 break;
7173 }
7174
7175 if (!next) {
7176 if (!cur)
7177 return 0;
7178 next = dev_stack[--cur];
7179 niter = iter_stack[cur];
7180 }
7181
7182 now = next;
7183 iter = niter;
7184 }
7185
7186 return 0;
7187 }
7188
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)7189 int netdev_walk_all_upper_dev_rcu(struct net_device *dev,
7190 int (*fn)(struct net_device *dev,
7191 struct netdev_nested_priv *priv),
7192 struct netdev_nested_priv *priv)
7193 {
7194 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7195 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7196 int ret, cur = 0;
7197
7198 now = dev;
7199 iter = &dev->adj_list.upper;
7200
7201 while (1) {
7202 if (now != dev) {
7203 ret = fn(now, priv);
7204 if (ret)
7205 return ret;
7206 }
7207
7208 next = NULL;
7209 while (1) {
7210 udev = netdev_next_upper_dev_rcu(now, &iter);
7211 if (!udev)
7212 break;
7213
7214 next = udev;
7215 niter = &udev->adj_list.upper;
7216 dev_stack[cur] = now;
7217 iter_stack[cur++] = iter;
7218 break;
7219 }
7220
7221 if (!next) {
7222 if (!cur)
7223 return 0;
7224 next = dev_stack[--cur];
7225 niter = iter_stack[cur];
7226 }
7227
7228 now = next;
7229 iter = niter;
7230 }
7231
7232 return 0;
7233 }
7234 EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu);
7235
__netdev_has_upper_dev(struct net_device * dev,struct net_device * upper_dev)7236 static bool __netdev_has_upper_dev(struct net_device *dev,
7237 struct net_device *upper_dev)
7238 {
7239 struct netdev_nested_priv priv = {
7240 .flags = 0,
7241 .data = (void *)upper_dev,
7242 };
7243
7244 ASSERT_RTNL();
7245
7246 return __netdev_walk_all_upper_dev(dev, ____netdev_has_upper_dev,
7247 &priv);
7248 }
7249
7250 /**
7251 * netdev_lower_get_next_private - Get the next ->private from the
7252 * lower neighbour list
7253 * @dev: device
7254 * @iter: list_head ** of the current position
7255 *
7256 * Gets the next netdev_adjacent->private from the dev's lower neighbour
7257 * list, starting from iter position. The caller must hold either hold the
7258 * RTNL lock or its own locking that guarantees that the neighbour lower
7259 * list will remain unchanged.
7260 */
netdev_lower_get_next_private(struct net_device * dev,struct list_head ** iter)7261 void *netdev_lower_get_next_private(struct net_device *dev,
7262 struct list_head **iter)
7263 {
7264 struct netdev_adjacent *lower;
7265
7266 lower = list_entry(*iter, struct netdev_adjacent, list);
7267
7268 if (&lower->list == &dev->adj_list.lower)
7269 return NULL;
7270
7271 *iter = lower->list.next;
7272
7273 return lower->private;
7274 }
7275 EXPORT_SYMBOL(netdev_lower_get_next_private);
7276
7277 /**
7278 * netdev_lower_get_next_private_rcu - Get the next ->private from the
7279 * lower neighbour list, RCU
7280 * variant
7281 * @dev: device
7282 * @iter: list_head ** of the current position
7283 *
7284 * Gets the next netdev_adjacent->private from the dev's lower neighbour
7285 * list, starting from iter position. The caller must hold RCU read lock.
7286 */
netdev_lower_get_next_private_rcu(struct net_device * dev,struct list_head ** iter)7287 void *netdev_lower_get_next_private_rcu(struct net_device *dev,
7288 struct list_head **iter)
7289 {
7290 struct netdev_adjacent *lower;
7291
7292 WARN_ON_ONCE(!rcu_read_lock_held());
7293
7294 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7295
7296 if (&lower->list == &dev->adj_list.lower)
7297 return NULL;
7298
7299 *iter = &lower->list;
7300
7301 return lower->private;
7302 }
7303 EXPORT_SYMBOL(netdev_lower_get_next_private_rcu);
7304
7305 /**
7306 * netdev_lower_get_next - Get the next device from the lower neighbour
7307 * list
7308 * @dev: device
7309 * @iter: list_head ** of the current position
7310 *
7311 * Gets the next netdev_adjacent from the dev's lower neighbour
7312 * list, starting from iter position. The caller must hold RTNL lock or
7313 * its own locking that guarantees that the neighbour lower
7314 * list will remain unchanged.
7315 */
netdev_lower_get_next(struct net_device * dev,struct list_head ** iter)7316 void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter)
7317 {
7318 struct netdev_adjacent *lower;
7319
7320 lower = list_entry(*iter, struct netdev_adjacent, list);
7321
7322 if (&lower->list == &dev->adj_list.lower)
7323 return NULL;
7324
7325 *iter = lower->list.next;
7326
7327 return lower->dev;
7328 }
7329 EXPORT_SYMBOL(netdev_lower_get_next);
7330
netdev_next_lower_dev(struct net_device * dev,struct list_head ** iter)7331 static struct net_device *netdev_next_lower_dev(struct net_device *dev,
7332 struct list_head **iter)
7333 {
7334 struct netdev_adjacent *lower;
7335
7336 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7337
7338 if (&lower->list == &dev->adj_list.lower)
7339 return NULL;
7340
7341 *iter = &lower->list;
7342
7343 return lower->dev;
7344 }
7345
__netdev_next_lower_dev(struct net_device * dev,struct list_head ** iter,bool * ignore)7346 static struct net_device *__netdev_next_lower_dev(struct net_device *dev,
7347 struct list_head **iter,
7348 bool *ignore)
7349 {
7350 struct netdev_adjacent *lower;
7351
7352 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7353
7354 if (&lower->list == &dev->adj_list.lower)
7355 return NULL;
7356
7357 *iter = &lower->list;
7358 *ignore = lower->ignore;
7359
7360 return lower->dev;
7361 }
7362
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)7363 int netdev_walk_all_lower_dev(struct net_device *dev,
7364 int (*fn)(struct net_device *dev,
7365 struct netdev_nested_priv *priv),
7366 struct netdev_nested_priv *priv)
7367 {
7368 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7369 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7370 int ret, cur = 0;
7371
7372 now = dev;
7373 iter = &dev->adj_list.lower;
7374
7375 while (1) {
7376 if (now != dev) {
7377 ret = fn(now, priv);
7378 if (ret)
7379 return ret;
7380 }
7381
7382 next = NULL;
7383 while (1) {
7384 ldev = netdev_next_lower_dev(now, &iter);
7385 if (!ldev)
7386 break;
7387
7388 next = ldev;
7389 niter = &ldev->adj_list.lower;
7390 dev_stack[cur] = now;
7391 iter_stack[cur++] = iter;
7392 break;
7393 }
7394
7395 if (!next) {
7396 if (!cur)
7397 return 0;
7398 next = dev_stack[--cur];
7399 niter = iter_stack[cur];
7400 }
7401
7402 now = next;
7403 iter = niter;
7404 }
7405
7406 return 0;
7407 }
7408 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev);
7409
__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)7410 static int __netdev_walk_all_lower_dev(struct net_device *dev,
7411 int (*fn)(struct net_device *dev,
7412 struct netdev_nested_priv *priv),
7413 struct netdev_nested_priv *priv)
7414 {
7415 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7416 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7417 int ret, cur = 0;
7418 bool ignore;
7419
7420 now = dev;
7421 iter = &dev->adj_list.lower;
7422
7423 while (1) {
7424 if (now != dev) {
7425 ret = fn(now, priv);
7426 if (ret)
7427 return ret;
7428 }
7429
7430 next = NULL;
7431 while (1) {
7432 ldev = __netdev_next_lower_dev(now, &iter, &ignore);
7433 if (!ldev)
7434 break;
7435 if (ignore)
7436 continue;
7437
7438 next = ldev;
7439 niter = &ldev->adj_list.lower;
7440 dev_stack[cur] = now;
7441 iter_stack[cur++] = iter;
7442 break;
7443 }
7444
7445 if (!next) {
7446 if (!cur)
7447 return 0;
7448 next = dev_stack[--cur];
7449 niter = iter_stack[cur];
7450 }
7451
7452 now = next;
7453 iter = niter;
7454 }
7455
7456 return 0;
7457 }
7458
netdev_next_lower_dev_rcu(struct net_device * dev,struct list_head ** iter)7459 struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev,
7460 struct list_head **iter)
7461 {
7462 struct netdev_adjacent *lower;
7463
7464 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7465 if (&lower->list == &dev->adj_list.lower)
7466 return NULL;
7467
7468 *iter = &lower->list;
7469
7470 return lower->dev;
7471 }
7472 EXPORT_SYMBOL(netdev_next_lower_dev_rcu);
7473
__netdev_upper_depth(struct net_device * dev)7474 static u8 __netdev_upper_depth(struct net_device *dev)
7475 {
7476 struct net_device *udev;
7477 struct list_head *iter;
7478 u8 max_depth = 0;
7479 bool ignore;
7480
7481 for (iter = &dev->adj_list.upper,
7482 udev = __netdev_next_upper_dev(dev, &iter, &ignore);
7483 udev;
7484 udev = __netdev_next_upper_dev(dev, &iter, &ignore)) {
7485 if (ignore)
7486 continue;
7487 if (max_depth < udev->upper_level)
7488 max_depth = udev->upper_level;
7489 }
7490
7491 return max_depth;
7492 }
7493
__netdev_lower_depth(struct net_device * dev)7494 static u8 __netdev_lower_depth(struct net_device *dev)
7495 {
7496 struct net_device *ldev;
7497 struct list_head *iter;
7498 u8 max_depth = 0;
7499 bool ignore;
7500
7501 for (iter = &dev->adj_list.lower,
7502 ldev = __netdev_next_lower_dev(dev, &iter, &ignore);
7503 ldev;
7504 ldev = __netdev_next_lower_dev(dev, &iter, &ignore)) {
7505 if (ignore)
7506 continue;
7507 if (max_depth < ldev->lower_level)
7508 max_depth = ldev->lower_level;
7509 }
7510
7511 return max_depth;
7512 }
7513
__netdev_update_upper_level(struct net_device * dev,struct netdev_nested_priv * __unused)7514 static int __netdev_update_upper_level(struct net_device *dev,
7515 struct netdev_nested_priv *__unused)
7516 {
7517 dev->upper_level = __netdev_upper_depth(dev) + 1;
7518 return 0;
7519 }
7520
__netdev_update_lower_level(struct net_device * dev,struct netdev_nested_priv * priv)7521 static int __netdev_update_lower_level(struct net_device *dev,
7522 struct netdev_nested_priv *priv)
7523 {
7524 dev->lower_level = __netdev_lower_depth(dev) + 1;
7525
7526 #ifdef CONFIG_LOCKDEP
7527 if (!priv)
7528 return 0;
7529
7530 if (priv->flags & NESTED_SYNC_IMM)
7531 dev->nested_level = dev->lower_level - 1;
7532 if (priv->flags & NESTED_SYNC_TODO)
7533 net_unlink_todo(dev);
7534 #endif
7535 return 0;
7536 }
7537
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)7538 int netdev_walk_all_lower_dev_rcu(struct net_device *dev,
7539 int (*fn)(struct net_device *dev,
7540 struct netdev_nested_priv *priv),
7541 struct netdev_nested_priv *priv)
7542 {
7543 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7544 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7545 int ret, cur = 0;
7546
7547 now = dev;
7548 iter = &dev->adj_list.lower;
7549
7550 while (1) {
7551 if (now != dev) {
7552 ret = fn(now, priv);
7553 if (ret)
7554 return ret;
7555 }
7556
7557 next = NULL;
7558 while (1) {
7559 ldev = netdev_next_lower_dev_rcu(now, &iter);
7560 if (!ldev)
7561 break;
7562
7563 next = ldev;
7564 niter = &ldev->adj_list.lower;
7565 dev_stack[cur] = now;
7566 iter_stack[cur++] = iter;
7567 break;
7568 }
7569
7570 if (!next) {
7571 if (!cur)
7572 return 0;
7573 next = dev_stack[--cur];
7574 niter = iter_stack[cur];
7575 }
7576
7577 now = next;
7578 iter = niter;
7579 }
7580
7581 return 0;
7582 }
7583 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu);
7584
7585 /**
7586 * netdev_lower_get_first_private_rcu - Get the first ->private from the
7587 * lower neighbour list, RCU
7588 * variant
7589 * @dev: device
7590 *
7591 * Gets the first netdev_adjacent->private from the dev's lower neighbour
7592 * list. The caller must hold RCU read lock.
7593 */
netdev_lower_get_first_private_rcu(struct net_device * dev)7594 void *netdev_lower_get_first_private_rcu(struct net_device *dev)
7595 {
7596 struct netdev_adjacent *lower;
7597
7598 lower = list_first_or_null_rcu(&dev->adj_list.lower,
7599 struct netdev_adjacent, list);
7600 if (lower)
7601 return lower->private;
7602 return NULL;
7603 }
7604 EXPORT_SYMBOL(netdev_lower_get_first_private_rcu);
7605
7606 /**
7607 * netdev_master_upper_dev_get_rcu - Get master upper device
7608 * @dev: device
7609 *
7610 * Find a master upper device and return pointer to it or NULL in case
7611 * it's not there. The caller must hold the RCU read lock.
7612 */
netdev_master_upper_dev_get_rcu(struct net_device * dev)7613 struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev)
7614 {
7615 struct netdev_adjacent *upper;
7616
7617 upper = list_first_or_null_rcu(&dev->adj_list.upper,
7618 struct netdev_adjacent, list);
7619 if (upper && likely(upper->master))
7620 return upper->dev;
7621 return NULL;
7622 }
7623 EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu);
7624
netdev_adjacent_sysfs_add(struct net_device * dev,struct net_device * adj_dev,struct list_head * dev_list)7625 static int netdev_adjacent_sysfs_add(struct net_device *dev,
7626 struct net_device *adj_dev,
7627 struct list_head *dev_list)
7628 {
7629 char linkname[IFNAMSIZ+7];
7630
7631 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7632 "upper_%s" : "lower_%s", adj_dev->name);
7633 return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj),
7634 linkname);
7635 }
netdev_adjacent_sysfs_del(struct net_device * dev,char * name,struct list_head * dev_list)7636 static void netdev_adjacent_sysfs_del(struct net_device *dev,
7637 char *name,
7638 struct list_head *dev_list)
7639 {
7640 char linkname[IFNAMSIZ+7];
7641
7642 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7643 "upper_%s" : "lower_%s", name);
7644 sysfs_remove_link(&(dev->dev.kobj), linkname);
7645 }
7646
netdev_adjacent_is_neigh_list(struct net_device * dev,struct net_device * adj_dev,struct list_head * dev_list)7647 static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev,
7648 struct net_device *adj_dev,
7649 struct list_head *dev_list)
7650 {
7651 return (dev_list == &dev->adj_list.upper ||
7652 dev_list == &dev->adj_list.lower) &&
7653 net_eq(dev_net(dev), dev_net(adj_dev));
7654 }
7655
__netdev_adjacent_dev_insert(struct net_device * dev,struct net_device * adj_dev,struct list_head * dev_list,void * private,bool master)7656 static int __netdev_adjacent_dev_insert(struct net_device *dev,
7657 struct net_device *adj_dev,
7658 struct list_head *dev_list,
7659 void *private, bool master)
7660 {
7661 struct netdev_adjacent *adj;
7662 int ret;
7663
7664 adj = __netdev_find_adj(adj_dev, dev_list);
7665
7666 if (adj) {
7667 adj->ref_nr += 1;
7668 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n",
7669 dev->name, adj_dev->name, adj->ref_nr);
7670
7671 return 0;
7672 }
7673
7674 adj = kmalloc(sizeof(*adj), GFP_KERNEL);
7675 if (!adj)
7676 return -ENOMEM;
7677
7678 adj->dev = adj_dev;
7679 adj->master = master;
7680 adj->ref_nr = 1;
7681 adj->private = private;
7682 adj->ignore = false;
7683 dev_hold(adj_dev);
7684
7685 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n",
7686 dev->name, adj_dev->name, adj->ref_nr, adj_dev->name);
7687
7688 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) {
7689 ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list);
7690 if (ret)
7691 goto free_adj;
7692 }
7693
7694 /* Ensure that master link is always the first item in list. */
7695 if (master) {
7696 ret = sysfs_create_link(&(dev->dev.kobj),
7697 &(adj_dev->dev.kobj), "master");
7698 if (ret)
7699 goto remove_symlinks;
7700
7701 list_add_rcu(&adj->list, dev_list);
7702 } else {
7703 list_add_tail_rcu(&adj->list, dev_list);
7704 }
7705
7706 return 0;
7707
7708 remove_symlinks:
7709 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7710 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7711 free_adj:
7712 kfree(adj);
7713 dev_put(adj_dev);
7714
7715 return ret;
7716 }
7717
__netdev_adjacent_dev_remove(struct net_device * dev,struct net_device * adj_dev,u16 ref_nr,struct list_head * dev_list)7718 static void __netdev_adjacent_dev_remove(struct net_device *dev,
7719 struct net_device *adj_dev,
7720 u16 ref_nr,
7721 struct list_head *dev_list)
7722 {
7723 struct netdev_adjacent *adj;
7724
7725 pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n",
7726 dev->name, adj_dev->name, ref_nr);
7727
7728 adj = __netdev_find_adj(adj_dev, dev_list);
7729
7730 if (!adj) {
7731 pr_err("Adjacency does not exist for device %s from %s\n",
7732 dev->name, adj_dev->name);
7733 WARN_ON(1);
7734 return;
7735 }
7736
7737 if (adj->ref_nr > ref_nr) {
7738 pr_debug("adjacency: %s to %s ref_nr - %d = %d\n",
7739 dev->name, adj_dev->name, ref_nr,
7740 adj->ref_nr - ref_nr);
7741 adj->ref_nr -= ref_nr;
7742 return;
7743 }
7744
7745 if (adj->master)
7746 sysfs_remove_link(&(dev->dev.kobj), "master");
7747
7748 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7749 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7750
7751 list_del_rcu(&adj->list);
7752 pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n",
7753 adj_dev->name, dev->name, adj_dev->name);
7754 dev_put(adj_dev);
7755 kfree_rcu(adj, rcu);
7756 }
7757
__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)7758 static int __netdev_adjacent_dev_link_lists(struct net_device *dev,
7759 struct net_device *upper_dev,
7760 struct list_head *up_list,
7761 struct list_head *down_list,
7762 void *private, bool master)
7763 {
7764 int ret;
7765
7766 ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list,
7767 private, master);
7768 if (ret)
7769 return ret;
7770
7771 ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list,
7772 private, false);
7773 if (ret) {
7774 __netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list);
7775 return ret;
7776 }
7777
7778 return 0;
7779 }
7780
__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)7781 static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev,
7782 struct net_device *upper_dev,
7783 u16 ref_nr,
7784 struct list_head *up_list,
7785 struct list_head *down_list)
7786 {
7787 __netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list);
7788 __netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list);
7789 }
7790
__netdev_adjacent_dev_link_neighbour(struct net_device * dev,struct net_device * upper_dev,void * private,bool master)7791 static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev,
7792 struct net_device *upper_dev,
7793 void *private, bool master)
7794 {
7795 return __netdev_adjacent_dev_link_lists(dev, upper_dev,
7796 &dev->adj_list.upper,
7797 &upper_dev->adj_list.lower,
7798 private, master);
7799 }
7800
__netdev_adjacent_dev_unlink_neighbour(struct net_device * dev,struct net_device * upper_dev)7801 static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev,
7802 struct net_device *upper_dev)
7803 {
7804 __netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1,
7805 &dev->adj_list.upper,
7806 &upper_dev->adj_list.lower);
7807 }
7808
__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)7809 static int __netdev_upper_dev_link(struct net_device *dev,
7810 struct net_device *upper_dev, bool master,
7811 void *upper_priv, void *upper_info,
7812 struct netdev_nested_priv *priv,
7813 struct netlink_ext_ack *extack)
7814 {
7815 struct netdev_notifier_changeupper_info changeupper_info = {
7816 .info = {
7817 .dev = dev,
7818 .extack = extack,
7819 },
7820 .upper_dev = upper_dev,
7821 .master = master,
7822 .linking = true,
7823 .upper_info = upper_info,
7824 };
7825 struct net_device *master_dev;
7826 int ret = 0;
7827
7828 ASSERT_RTNL();
7829
7830 if (dev == upper_dev)
7831 return -EBUSY;
7832
7833 /* To prevent loops, check if dev is not upper device to upper_dev. */
7834 if (__netdev_has_upper_dev(upper_dev, dev))
7835 return -EBUSY;
7836
7837 if ((dev->lower_level + upper_dev->upper_level) > MAX_NEST_DEV)
7838 return -EMLINK;
7839
7840 if (!master) {
7841 if (__netdev_has_upper_dev(dev, upper_dev))
7842 return -EEXIST;
7843 } else {
7844 master_dev = __netdev_master_upper_dev_get(dev);
7845 if (master_dev)
7846 return master_dev == upper_dev ? -EEXIST : -EBUSY;
7847 }
7848
7849 ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7850 &changeupper_info.info);
7851 ret = notifier_to_errno(ret);
7852 if (ret)
7853 return ret;
7854
7855 ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv,
7856 master);
7857 if (ret)
7858 return ret;
7859
7860 ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7861 &changeupper_info.info);
7862 ret = notifier_to_errno(ret);
7863 if (ret)
7864 goto rollback;
7865
7866 __netdev_update_upper_level(dev, NULL);
7867 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7868
7869 __netdev_update_lower_level(upper_dev, priv);
7870 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
7871 priv);
7872
7873 return 0;
7874
7875 rollback:
7876 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7877
7878 return ret;
7879 }
7880
7881 /**
7882 * netdev_upper_dev_link - Add a link to the upper device
7883 * @dev: device
7884 * @upper_dev: new upper device
7885 * @extack: netlink extended ack
7886 *
7887 * Adds a link to device which is upper to this one. The caller must hold
7888 * the RTNL lock. On a failure a negative errno code is returned.
7889 * On success the reference counts are adjusted and the function
7890 * returns zero.
7891 */
netdev_upper_dev_link(struct net_device * dev,struct net_device * upper_dev,struct netlink_ext_ack * extack)7892 int netdev_upper_dev_link(struct net_device *dev,
7893 struct net_device *upper_dev,
7894 struct netlink_ext_ack *extack)
7895 {
7896 struct netdev_nested_priv priv = {
7897 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7898 .data = NULL,
7899 };
7900
7901 return __netdev_upper_dev_link(dev, upper_dev, false,
7902 NULL, NULL, &priv, extack);
7903 }
7904 EXPORT_SYMBOL(netdev_upper_dev_link);
7905
7906 /**
7907 * netdev_master_upper_dev_link - Add a master link to the upper device
7908 * @dev: device
7909 * @upper_dev: new upper device
7910 * @upper_priv: upper device private
7911 * @upper_info: upper info to be passed down via notifier
7912 * @extack: netlink extended ack
7913 *
7914 * Adds a link to device which is upper to this one. In this case, only
7915 * one master upper device can be linked, although other non-master devices
7916 * might be linked as well. The caller must hold the RTNL lock.
7917 * On a failure a negative errno code is returned. On success the reference
7918 * counts are adjusted and the function returns zero.
7919 */
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)7920 int netdev_master_upper_dev_link(struct net_device *dev,
7921 struct net_device *upper_dev,
7922 void *upper_priv, void *upper_info,
7923 struct netlink_ext_ack *extack)
7924 {
7925 struct netdev_nested_priv priv = {
7926 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7927 .data = NULL,
7928 };
7929
7930 return __netdev_upper_dev_link(dev, upper_dev, true,
7931 upper_priv, upper_info, &priv, extack);
7932 }
7933 EXPORT_SYMBOL(netdev_master_upper_dev_link);
7934
__netdev_upper_dev_unlink(struct net_device * dev,struct net_device * upper_dev,struct netdev_nested_priv * priv)7935 static void __netdev_upper_dev_unlink(struct net_device *dev,
7936 struct net_device *upper_dev,
7937 struct netdev_nested_priv *priv)
7938 {
7939 struct netdev_notifier_changeupper_info changeupper_info = {
7940 .info = {
7941 .dev = dev,
7942 },
7943 .upper_dev = upper_dev,
7944 .linking = false,
7945 };
7946
7947 ASSERT_RTNL();
7948
7949 changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev;
7950
7951 call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7952 &changeupper_info.info);
7953
7954 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7955
7956 call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7957 &changeupper_info.info);
7958
7959 __netdev_update_upper_level(dev, NULL);
7960 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7961
7962 __netdev_update_lower_level(upper_dev, priv);
7963 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
7964 priv);
7965 }
7966
7967 /**
7968 * netdev_upper_dev_unlink - Removes a link to upper device
7969 * @dev: device
7970 * @upper_dev: new upper device
7971 *
7972 * Removes a link to device which is upper to this one. The caller must hold
7973 * the RTNL lock.
7974 */
netdev_upper_dev_unlink(struct net_device * dev,struct net_device * upper_dev)7975 void netdev_upper_dev_unlink(struct net_device *dev,
7976 struct net_device *upper_dev)
7977 {
7978 struct netdev_nested_priv priv = {
7979 .flags = NESTED_SYNC_TODO,
7980 .data = NULL,
7981 };
7982
7983 __netdev_upper_dev_unlink(dev, upper_dev, &priv);
7984 }
7985 EXPORT_SYMBOL(netdev_upper_dev_unlink);
7986
__netdev_adjacent_dev_set(struct net_device * upper_dev,struct net_device * lower_dev,bool val)7987 static void __netdev_adjacent_dev_set(struct net_device *upper_dev,
7988 struct net_device *lower_dev,
7989 bool val)
7990 {
7991 struct netdev_adjacent *adj;
7992
7993 adj = __netdev_find_adj(lower_dev, &upper_dev->adj_list.lower);
7994 if (adj)
7995 adj->ignore = val;
7996
7997 adj = __netdev_find_adj(upper_dev, &lower_dev->adj_list.upper);
7998 if (adj)
7999 adj->ignore = val;
8000 }
8001
netdev_adjacent_dev_disable(struct net_device * upper_dev,struct net_device * lower_dev)8002 static void netdev_adjacent_dev_disable(struct net_device *upper_dev,
8003 struct net_device *lower_dev)
8004 {
8005 __netdev_adjacent_dev_set(upper_dev, lower_dev, true);
8006 }
8007
netdev_adjacent_dev_enable(struct net_device * upper_dev,struct net_device * lower_dev)8008 static void netdev_adjacent_dev_enable(struct net_device *upper_dev,
8009 struct net_device *lower_dev)
8010 {
8011 __netdev_adjacent_dev_set(upper_dev, lower_dev, false);
8012 }
8013
netdev_adjacent_change_prepare(struct net_device * old_dev,struct net_device * new_dev,struct net_device * dev,struct netlink_ext_ack * extack)8014 int netdev_adjacent_change_prepare(struct net_device *old_dev,
8015 struct net_device *new_dev,
8016 struct net_device *dev,
8017 struct netlink_ext_ack *extack)
8018 {
8019 struct netdev_nested_priv priv = {
8020 .flags = 0,
8021 .data = NULL,
8022 };
8023 int err;
8024
8025 if (!new_dev)
8026 return 0;
8027
8028 if (old_dev && new_dev != old_dev)
8029 netdev_adjacent_dev_disable(dev, old_dev);
8030 err = __netdev_upper_dev_link(new_dev, dev, false, NULL, NULL, &priv,
8031 extack);
8032 if (err) {
8033 if (old_dev && new_dev != old_dev)
8034 netdev_adjacent_dev_enable(dev, old_dev);
8035 return err;
8036 }
8037
8038 return 0;
8039 }
8040 EXPORT_SYMBOL(netdev_adjacent_change_prepare);
8041
netdev_adjacent_change_commit(struct net_device * old_dev,struct net_device * new_dev,struct net_device * dev)8042 void netdev_adjacent_change_commit(struct net_device *old_dev,
8043 struct net_device *new_dev,
8044 struct net_device *dev)
8045 {
8046 struct netdev_nested_priv priv = {
8047 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
8048 .data = NULL,
8049 };
8050
8051 if (!new_dev || !old_dev)
8052 return;
8053
8054 if (new_dev == old_dev)
8055 return;
8056
8057 netdev_adjacent_dev_enable(dev, old_dev);
8058 __netdev_upper_dev_unlink(old_dev, dev, &priv);
8059 }
8060 EXPORT_SYMBOL(netdev_adjacent_change_commit);
8061
netdev_adjacent_change_abort(struct net_device * old_dev,struct net_device * new_dev,struct net_device * dev)8062 void netdev_adjacent_change_abort(struct net_device *old_dev,
8063 struct net_device *new_dev,
8064 struct net_device *dev)
8065 {
8066 struct netdev_nested_priv priv = {
8067 .flags = 0,
8068 .data = NULL,
8069 };
8070
8071 if (!new_dev)
8072 return;
8073
8074 if (old_dev && new_dev != old_dev)
8075 netdev_adjacent_dev_enable(dev, old_dev);
8076
8077 __netdev_upper_dev_unlink(new_dev, dev, &priv);
8078 }
8079 EXPORT_SYMBOL(netdev_adjacent_change_abort);
8080
8081 /**
8082 * netdev_bonding_info_change - Dispatch event about slave change
8083 * @dev: device
8084 * @bonding_info: info to dispatch
8085 *
8086 * Send NETDEV_BONDING_INFO to netdev notifiers with info.
8087 * The caller must hold the RTNL lock.
8088 */
netdev_bonding_info_change(struct net_device * dev,struct netdev_bonding_info * bonding_info)8089 void netdev_bonding_info_change(struct net_device *dev,
8090 struct netdev_bonding_info *bonding_info)
8091 {
8092 struct netdev_notifier_bonding_info info = {
8093 .info.dev = dev,
8094 };
8095
8096 memcpy(&info.bonding_info, bonding_info,
8097 sizeof(struct netdev_bonding_info));
8098 call_netdevice_notifiers_info(NETDEV_BONDING_INFO,
8099 &info.info);
8100 }
8101 EXPORT_SYMBOL(netdev_bonding_info_change);
8102
8103 /**
8104 * netdev_get_xmit_slave - Get the xmit slave of master device
8105 * @dev: device
8106 * @skb: The packet
8107 * @all_slaves: assume all the slaves are active
8108 *
8109 * The reference counters are not incremented so the caller must be
8110 * careful with locks. The caller must hold RCU lock.
8111 * %NULL is returned if no slave is found.
8112 */
8113
netdev_get_xmit_slave(struct net_device * dev,struct sk_buff * skb,bool all_slaves)8114 struct net_device *netdev_get_xmit_slave(struct net_device *dev,
8115 struct sk_buff *skb,
8116 bool all_slaves)
8117 {
8118 const struct net_device_ops *ops = dev->netdev_ops;
8119
8120 if (!ops->ndo_get_xmit_slave)
8121 return NULL;
8122 return ops->ndo_get_xmit_slave(dev, skb, all_slaves);
8123 }
8124 EXPORT_SYMBOL(netdev_get_xmit_slave);
8125
netdev_adjacent_add_links(struct net_device * dev)8126 static void netdev_adjacent_add_links(struct net_device *dev)
8127 {
8128 struct netdev_adjacent *iter;
8129
8130 struct net *net = dev_net(dev);
8131
8132 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8133 if (!net_eq(net, dev_net(iter->dev)))
8134 continue;
8135 netdev_adjacent_sysfs_add(iter->dev, dev,
8136 &iter->dev->adj_list.lower);
8137 netdev_adjacent_sysfs_add(dev, iter->dev,
8138 &dev->adj_list.upper);
8139 }
8140
8141 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8142 if (!net_eq(net, dev_net(iter->dev)))
8143 continue;
8144 netdev_adjacent_sysfs_add(iter->dev, dev,
8145 &iter->dev->adj_list.upper);
8146 netdev_adjacent_sysfs_add(dev, iter->dev,
8147 &dev->adj_list.lower);
8148 }
8149 }
8150
netdev_adjacent_del_links(struct net_device * dev)8151 static void netdev_adjacent_del_links(struct net_device *dev)
8152 {
8153 struct netdev_adjacent *iter;
8154
8155 struct net *net = dev_net(dev);
8156
8157 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8158 if (!net_eq(net, dev_net(iter->dev)))
8159 continue;
8160 netdev_adjacent_sysfs_del(iter->dev, dev->name,
8161 &iter->dev->adj_list.lower);
8162 netdev_adjacent_sysfs_del(dev, iter->dev->name,
8163 &dev->adj_list.upper);
8164 }
8165
8166 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8167 if (!net_eq(net, dev_net(iter->dev)))
8168 continue;
8169 netdev_adjacent_sysfs_del(iter->dev, dev->name,
8170 &iter->dev->adj_list.upper);
8171 netdev_adjacent_sysfs_del(dev, iter->dev->name,
8172 &dev->adj_list.lower);
8173 }
8174 }
8175
netdev_adjacent_rename_links(struct net_device * dev,char * oldname)8176 void netdev_adjacent_rename_links(struct net_device *dev, char *oldname)
8177 {
8178 struct netdev_adjacent *iter;
8179
8180 struct net *net = dev_net(dev);
8181
8182 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8183 if (!net_eq(net, dev_net(iter->dev)))
8184 continue;
8185 netdev_adjacent_sysfs_del(iter->dev, oldname,
8186 &iter->dev->adj_list.lower);
8187 netdev_adjacent_sysfs_add(iter->dev, dev,
8188 &iter->dev->adj_list.lower);
8189 }
8190
8191 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8192 if (!net_eq(net, dev_net(iter->dev)))
8193 continue;
8194 netdev_adjacent_sysfs_del(iter->dev, oldname,
8195 &iter->dev->adj_list.upper);
8196 netdev_adjacent_sysfs_add(iter->dev, dev,
8197 &iter->dev->adj_list.upper);
8198 }
8199 }
8200
netdev_lower_dev_get_private(struct net_device * dev,struct net_device * lower_dev)8201 void *netdev_lower_dev_get_private(struct net_device *dev,
8202 struct net_device *lower_dev)
8203 {
8204 struct netdev_adjacent *lower;
8205
8206 if (!lower_dev)
8207 return NULL;
8208 lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower);
8209 if (!lower)
8210 return NULL;
8211
8212 return lower->private;
8213 }
8214 EXPORT_SYMBOL(netdev_lower_dev_get_private);
8215
8216
8217 /**
8218 * netdev_lower_change - Dispatch event about lower device state change
8219 * @lower_dev: device
8220 * @lower_state_info: state to dispatch
8221 *
8222 * Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info.
8223 * The caller must hold the RTNL lock.
8224 */
netdev_lower_state_changed(struct net_device * lower_dev,void * lower_state_info)8225 void netdev_lower_state_changed(struct net_device *lower_dev,
8226 void *lower_state_info)
8227 {
8228 struct netdev_notifier_changelowerstate_info changelowerstate_info = {
8229 .info.dev = lower_dev,
8230 };
8231
8232 ASSERT_RTNL();
8233 changelowerstate_info.lower_state_info = lower_state_info;
8234 call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE,
8235 &changelowerstate_info.info);
8236 }
8237 EXPORT_SYMBOL(netdev_lower_state_changed);
8238
dev_change_rx_flags(struct net_device * dev,int flags)8239 static void dev_change_rx_flags(struct net_device *dev, int flags)
8240 {
8241 const struct net_device_ops *ops = dev->netdev_ops;
8242
8243 if (ops->ndo_change_rx_flags)
8244 ops->ndo_change_rx_flags(dev, flags);
8245 }
8246
__dev_set_promiscuity(struct net_device * dev,int inc,bool notify)8247 static int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify)
8248 {
8249 unsigned int old_flags = dev->flags;
8250 kuid_t uid;
8251 kgid_t gid;
8252
8253 ASSERT_RTNL();
8254
8255 dev->flags |= IFF_PROMISC;
8256 dev->promiscuity += inc;
8257 if (dev->promiscuity == 0) {
8258 /*
8259 * Avoid overflow.
8260 * If inc causes overflow, untouch promisc and return error.
8261 */
8262 if (inc < 0)
8263 dev->flags &= ~IFF_PROMISC;
8264 else {
8265 dev->promiscuity -= inc;
8266 pr_warn("%s: promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n",
8267 dev->name);
8268 return -EOVERFLOW;
8269 }
8270 }
8271 if (dev->flags != old_flags) {
8272 pr_info("device %s %s promiscuous mode\n",
8273 dev->name,
8274 dev->flags & IFF_PROMISC ? "entered" : "left");
8275 if (audit_enabled) {
8276 current_uid_gid(&uid, &gid);
8277 audit_log(audit_context(), GFP_ATOMIC,
8278 AUDIT_ANOM_PROMISCUOUS,
8279 "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u",
8280 dev->name, (dev->flags & IFF_PROMISC),
8281 (old_flags & IFF_PROMISC),
8282 from_kuid(&init_user_ns, audit_get_loginuid(current)),
8283 from_kuid(&init_user_ns, uid),
8284 from_kgid(&init_user_ns, gid),
8285 audit_get_sessionid(current));
8286 }
8287
8288 dev_change_rx_flags(dev, IFF_PROMISC);
8289 }
8290 if (notify)
8291 __dev_notify_flags(dev, old_flags, IFF_PROMISC);
8292 return 0;
8293 }
8294
8295 /**
8296 * dev_set_promiscuity - update promiscuity count on a device
8297 * @dev: device
8298 * @inc: modifier
8299 *
8300 * Add or remove promiscuity from a device. While the count in the device
8301 * remains above zero the interface remains promiscuous. Once it hits zero
8302 * the device reverts back to normal filtering operation. A negative inc
8303 * value is used to drop promiscuity on the device.
8304 * Return 0 if successful or a negative errno code on error.
8305 */
dev_set_promiscuity(struct net_device * dev,int inc)8306 int dev_set_promiscuity(struct net_device *dev, int inc)
8307 {
8308 unsigned int old_flags = dev->flags;
8309 int err;
8310
8311 err = __dev_set_promiscuity(dev, inc, true);
8312 if (err < 0)
8313 return err;
8314 if (dev->flags != old_flags)
8315 dev_set_rx_mode(dev);
8316 return err;
8317 }
8318 EXPORT_SYMBOL(dev_set_promiscuity);
8319
__dev_set_allmulti(struct net_device * dev,int inc,bool notify)8320 static int __dev_set_allmulti(struct net_device *dev, int inc, bool notify)
8321 {
8322 unsigned int old_flags = dev->flags, old_gflags = dev->gflags;
8323
8324 ASSERT_RTNL();
8325
8326 dev->flags |= IFF_ALLMULTI;
8327 dev->allmulti += inc;
8328 if (dev->allmulti == 0) {
8329 /*
8330 * Avoid overflow.
8331 * If inc causes overflow, untouch allmulti and return error.
8332 */
8333 if (inc < 0)
8334 dev->flags &= ~IFF_ALLMULTI;
8335 else {
8336 dev->allmulti -= inc;
8337 pr_warn("%s: allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n",
8338 dev->name);
8339 return -EOVERFLOW;
8340 }
8341 }
8342 if (dev->flags ^ old_flags) {
8343 dev_change_rx_flags(dev, IFF_ALLMULTI);
8344 dev_set_rx_mode(dev);
8345 if (notify)
8346 __dev_notify_flags(dev, old_flags,
8347 dev->gflags ^ old_gflags);
8348 }
8349 return 0;
8350 }
8351
8352 /**
8353 * dev_set_allmulti - update allmulti count on a device
8354 * @dev: device
8355 * @inc: modifier
8356 *
8357 * Add or remove reception of all multicast frames to a device. While the
8358 * count in the device remains above zero the interface remains listening
8359 * to all interfaces. Once it hits zero the device reverts back to normal
8360 * filtering operation. A negative @inc value is used to drop the counter
8361 * when releasing a resource needing all multicasts.
8362 * Return 0 if successful or a negative errno code on error.
8363 */
8364
dev_set_allmulti(struct net_device * dev,int inc)8365 int dev_set_allmulti(struct net_device *dev, int inc)
8366 {
8367 return __dev_set_allmulti(dev, inc, true);
8368 }
8369 EXPORT_SYMBOL(dev_set_allmulti);
8370
8371 /*
8372 * Upload unicast and multicast address lists to device and
8373 * configure RX filtering. When the device doesn't support unicast
8374 * filtering it is put in promiscuous mode while unicast addresses
8375 * are present.
8376 */
__dev_set_rx_mode(struct net_device * dev)8377 void __dev_set_rx_mode(struct net_device *dev)
8378 {
8379 const struct net_device_ops *ops = dev->netdev_ops;
8380
8381 /* dev_open will call this function so the list will stay sane. */
8382 if (!(dev->flags&IFF_UP))
8383 return;
8384
8385 if (!netif_device_present(dev))
8386 return;
8387
8388 if (!(dev->priv_flags & IFF_UNICAST_FLT)) {
8389 /* Unicast addresses changes may only happen under the rtnl,
8390 * therefore calling __dev_set_promiscuity here is safe.
8391 */
8392 if (!netdev_uc_empty(dev) && !dev->uc_promisc) {
8393 __dev_set_promiscuity(dev, 1, false);
8394 dev->uc_promisc = true;
8395 } else if (netdev_uc_empty(dev) && dev->uc_promisc) {
8396 __dev_set_promiscuity(dev, -1, false);
8397 dev->uc_promisc = false;
8398 }
8399 }
8400
8401 if (ops->ndo_set_rx_mode)
8402 ops->ndo_set_rx_mode(dev);
8403 }
8404
dev_set_rx_mode(struct net_device * dev)8405 void dev_set_rx_mode(struct net_device *dev)
8406 {
8407 netif_addr_lock_bh(dev);
8408 __dev_set_rx_mode(dev);
8409 netif_addr_unlock_bh(dev);
8410 }
8411
8412 /**
8413 * dev_get_flags - get flags reported to userspace
8414 * @dev: device
8415 *
8416 * Get the combination of flag bits exported through APIs to userspace.
8417 */
dev_get_flags(const struct net_device * dev)8418 unsigned int dev_get_flags(const struct net_device *dev)
8419 {
8420 unsigned int flags;
8421
8422 flags = (dev->flags & ~(IFF_PROMISC |
8423 IFF_ALLMULTI |
8424 IFF_RUNNING |
8425 IFF_LOWER_UP |
8426 IFF_DORMANT)) |
8427 (dev->gflags & (IFF_PROMISC |
8428 IFF_ALLMULTI));
8429
8430 if (netif_running(dev)) {
8431 if (netif_oper_up(dev))
8432 flags |= IFF_RUNNING;
8433 if (netif_carrier_ok(dev))
8434 flags |= IFF_LOWER_UP;
8435 if (netif_dormant(dev))
8436 flags |= IFF_DORMANT;
8437 }
8438
8439 return flags;
8440 }
8441 EXPORT_SYMBOL(dev_get_flags);
8442
__dev_change_flags(struct net_device * dev,unsigned int flags,struct netlink_ext_ack * extack)8443 int __dev_change_flags(struct net_device *dev, unsigned int flags,
8444 struct netlink_ext_ack *extack)
8445 {
8446 unsigned int old_flags = dev->flags;
8447 int ret;
8448
8449 ASSERT_RTNL();
8450
8451 /*
8452 * Set the flags on our device.
8453 */
8454
8455 dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
8456 IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
8457 IFF_AUTOMEDIA)) |
8458 (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
8459 IFF_ALLMULTI));
8460
8461 /*
8462 * Load in the correct multicast list now the flags have changed.
8463 */
8464
8465 if ((old_flags ^ flags) & IFF_MULTICAST)
8466 dev_change_rx_flags(dev, IFF_MULTICAST);
8467
8468 dev_set_rx_mode(dev);
8469
8470 /*
8471 * Have we downed the interface. We handle IFF_UP ourselves
8472 * according to user attempts to set it, rather than blindly
8473 * setting it.
8474 */
8475
8476 ret = 0;
8477 if ((old_flags ^ flags) & IFF_UP) {
8478 if (old_flags & IFF_UP)
8479 __dev_close(dev);
8480 else
8481 ret = __dev_open(dev, extack);
8482 }
8483
8484 if ((flags ^ dev->gflags) & IFF_PROMISC) {
8485 int inc = (flags & IFF_PROMISC) ? 1 : -1;
8486 unsigned int old_flags = dev->flags;
8487
8488 dev->gflags ^= IFF_PROMISC;
8489
8490 if (__dev_set_promiscuity(dev, inc, false) >= 0)
8491 if (dev->flags != old_flags)
8492 dev_set_rx_mode(dev);
8493 }
8494
8495 /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
8496 * is important. Some (broken) drivers set IFF_PROMISC, when
8497 * IFF_ALLMULTI is requested not asking us and not reporting.
8498 */
8499 if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
8500 int inc = (flags & IFF_ALLMULTI) ? 1 : -1;
8501
8502 dev->gflags ^= IFF_ALLMULTI;
8503 __dev_set_allmulti(dev, inc, false);
8504 }
8505
8506 return ret;
8507 }
8508
__dev_notify_flags(struct net_device * dev,unsigned int old_flags,unsigned int gchanges)8509 void __dev_notify_flags(struct net_device *dev, unsigned int old_flags,
8510 unsigned int gchanges)
8511 {
8512 unsigned int changes = dev->flags ^ old_flags;
8513
8514 if (gchanges)
8515 rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC);
8516
8517 if (changes & IFF_UP) {
8518 if (dev->flags & IFF_UP)
8519 call_netdevice_notifiers(NETDEV_UP, dev);
8520 else
8521 call_netdevice_notifiers(NETDEV_DOWN, dev);
8522 }
8523
8524 if (dev->flags & IFF_UP &&
8525 (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) {
8526 struct netdev_notifier_change_info change_info = {
8527 .info = {
8528 .dev = dev,
8529 },
8530 .flags_changed = changes,
8531 };
8532
8533 call_netdevice_notifiers_info(NETDEV_CHANGE, &change_info.info);
8534 }
8535 }
8536
8537 /**
8538 * dev_change_flags - change device settings
8539 * @dev: device
8540 * @flags: device state flags
8541 * @extack: netlink extended ack
8542 *
8543 * Change settings on device based state flags. The flags are
8544 * in the userspace exported format.
8545 */
dev_change_flags(struct net_device * dev,unsigned int flags,struct netlink_ext_ack * extack)8546 int dev_change_flags(struct net_device *dev, unsigned int flags,
8547 struct netlink_ext_ack *extack)
8548 {
8549 int ret;
8550 unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags;
8551
8552 ret = __dev_change_flags(dev, flags, extack);
8553 if (ret < 0)
8554 return ret;
8555
8556 changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags);
8557 __dev_notify_flags(dev, old_flags, changes);
8558 return ret;
8559 }
8560 EXPORT_SYMBOL(dev_change_flags);
8561
__dev_set_mtu(struct net_device * dev,int new_mtu)8562 int __dev_set_mtu(struct net_device *dev, int new_mtu)
8563 {
8564 const struct net_device_ops *ops = dev->netdev_ops;
8565
8566 if (ops->ndo_change_mtu)
8567 return ops->ndo_change_mtu(dev, new_mtu);
8568
8569 /* Pairs with all the lockless reads of dev->mtu in the stack */
8570 WRITE_ONCE(dev->mtu, new_mtu);
8571 return 0;
8572 }
8573 EXPORT_SYMBOL(__dev_set_mtu);
8574
dev_validate_mtu(struct net_device * dev,int new_mtu,struct netlink_ext_ack * extack)8575 int dev_validate_mtu(struct net_device *dev, int new_mtu,
8576 struct netlink_ext_ack *extack)
8577 {
8578 /* MTU must be positive, and in range */
8579 if (new_mtu < 0 || new_mtu < dev->min_mtu) {
8580 NL_SET_ERR_MSG(extack, "mtu less than device minimum");
8581 return -EINVAL;
8582 }
8583
8584 if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) {
8585 NL_SET_ERR_MSG(extack, "mtu greater than device maximum");
8586 return -EINVAL;
8587 }
8588 return 0;
8589 }
8590
8591 /**
8592 * dev_set_mtu_ext - Change maximum transfer unit
8593 * @dev: device
8594 * @new_mtu: new transfer unit
8595 * @extack: netlink extended ack
8596 *
8597 * Change the maximum transfer size of the network device.
8598 */
dev_set_mtu_ext(struct net_device * dev,int new_mtu,struct netlink_ext_ack * extack)8599 int dev_set_mtu_ext(struct net_device *dev, int new_mtu,
8600 struct netlink_ext_ack *extack)
8601 {
8602 int err, orig_mtu;
8603
8604 if (new_mtu == dev->mtu)
8605 return 0;
8606
8607 err = dev_validate_mtu(dev, new_mtu, extack);
8608 if (err)
8609 return err;
8610
8611 if (!netif_device_present(dev))
8612 return -ENODEV;
8613
8614 err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev);
8615 err = notifier_to_errno(err);
8616 if (err)
8617 return err;
8618
8619 orig_mtu = dev->mtu;
8620 err = __dev_set_mtu(dev, new_mtu);
8621
8622 if (!err) {
8623 err = call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8624 orig_mtu);
8625 err = notifier_to_errno(err);
8626 if (err) {
8627 /* setting mtu back and notifying everyone again,
8628 * so that they have a chance to revert changes.
8629 */
8630 __dev_set_mtu(dev, orig_mtu);
8631 call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8632 new_mtu);
8633 }
8634 }
8635 return err;
8636 }
8637
dev_set_mtu(struct net_device * dev,int new_mtu)8638 int dev_set_mtu(struct net_device *dev, int new_mtu)
8639 {
8640 struct netlink_ext_ack extack;
8641 int err;
8642
8643 memset(&extack, 0, sizeof(extack));
8644 err = dev_set_mtu_ext(dev, new_mtu, &extack);
8645 if (err && extack._msg)
8646 net_err_ratelimited("%s: %s\n", dev->name, extack._msg);
8647 return err;
8648 }
8649 EXPORT_SYMBOL(dev_set_mtu);
8650
8651 /**
8652 * dev_change_tx_queue_len - Change TX queue length of a netdevice
8653 * @dev: device
8654 * @new_len: new tx queue length
8655 */
dev_change_tx_queue_len(struct net_device * dev,unsigned long new_len)8656 int dev_change_tx_queue_len(struct net_device *dev, unsigned long new_len)
8657 {
8658 unsigned int orig_len = dev->tx_queue_len;
8659 int res;
8660
8661 if (new_len != (unsigned int)new_len)
8662 return -ERANGE;
8663
8664 if (new_len != orig_len) {
8665 dev->tx_queue_len = new_len;
8666 res = call_netdevice_notifiers(NETDEV_CHANGE_TX_QUEUE_LEN, dev);
8667 res = notifier_to_errno(res);
8668 if (res)
8669 goto err_rollback;
8670 res = dev_qdisc_change_tx_queue_len(dev);
8671 if (res)
8672 goto err_rollback;
8673 }
8674
8675 return 0;
8676
8677 err_rollback:
8678 netdev_err(dev, "refused to change device tx_queue_len\n");
8679 dev->tx_queue_len = orig_len;
8680 return res;
8681 }
8682
8683 /**
8684 * dev_set_group - Change group this device belongs to
8685 * @dev: device
8686 * @new_group: group this device should belong to
8687 */
dev_set_group(struct net_device * dev,int new_group)8688 void dev_set_group(struct net_device *dev, int new_group)
8689 {
8690 dev->group = new_group;
8691 }
8692 EXPORT_SYMBOL(dev_set_group);
8693
8694 /**
8695 * dev_pre_changeaddr_notify - Call NETDEV_PRE_CHANGEADDR.
8696 * @dev: device
8697 * @addr: new address
8698 * @extack: netlink extended ack
8699 */
dev_pre_changeaddr_notify(struct net_device * dev,const char * addr,struct netlink_ext_ack * extack)8700 int dev_pre_changeaddr_notify(struct net_device *dev, const char *addr,
8701 struct netlink_ext_ack *extack)
8702 {
8703 struct netdev_notifier_pre_changeaddr_info info = {
8704 .info.dev = dev,
8705 .info.extack = extack,
8706 .dev_addr = addr,
8707 };
8708 int rc;
8709
8710 rc = call_netdevice_notifiers_info(NETDEV_PRE_CHANGEADDR, &info.info);
8711 return notifier_to_errno(rc);
8712 }
8713 EXPORT_SYMBOL(dev_pre_changeaddr_notify);
8714
8715 /**
8716 * dev_set_mac_address - Change Media Access Control Address
8717 * @dev: device
8718 * @sa: new address
8719 * @extack: netlink extended ack
8720 *
8721 * Change the hardware (MAC) address of the device
8722 */
dev_set_mac_address(struct net_device * dev,struct sockaddr * sa,struct netlink_ext_ack * extack)8723 int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa,
8724 struct netlink_ext_ack *extack)
8725 {
8726 const struct net_device_ops *ops = dev->netdev_ops;
8727 int err;
8728
8729 if (!ops->ndo_set_mac_address)
8730 return -EOPNOTSUPP;
8731 if (sa->sa_family != dev->type)
8732 return -EINVAL;
8733 if (!netif_device_present(dev))
8734 return -ENODEV;
8735 err = dev_pre_changeaddr_notify(dev, sa->sa_data, extack);
8736 if (err)
8737 return err;
8738 err = ops->ndo_set_mac_address(dev, sa);
8739 if (err)
8740 return err;
8741 dev->addr_assign_type = NET_ADDR_SET;
8742 call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
8743 add_device_randomness(dev->dev_addr, dev->addr_len);
8744 return 0;
8745 }
8746 EXPORT_SYMBOL(dev_set_mac_address);
8747
8748 static DECLARE_RWSEM(dev_addr_sem);
8749
dev_set_mac_address_user(struct net_device * dev,struct sockaddr * sa,struct netlink_ext_ack * extack)8750 int dev_set_mac_address_user(struct net_device *dev, struct sockaddr *sa,
8751 struct netlink_ext_ack *extack)
8752 {
8753 int ret;
8754
8755 down_write(&dev_addr_sem);
8756 ret = dev_set_mac_address(dev, sa, extack);
8757 up_write(&dev_addr_sem);
8758 return ret;
8759 }
8760 EXPORT_SYMBOL(dev_set_mac_address_user);
8761
dev_get_mac_address(struct sockaddr * sa,struct net * net,char * dev_name)8762 int dev_get_mac_address(struct sockaddr *sa, struct net *net, char *dev_name)
8763 {
8764 size_t size = sizeof(sa->sa_data);
8765 struct net_device *dev;
8766 int ret = 0;
8767
8768 down_read(&dev_addr_sem);
8769 rcu_read_lock();
8770
8771 dev = dev_get_by_name_rcu(net, dev_name);
8772 if (!dev) {
8773 ret = -ENODEV;
8774 goto unlock;
8775 }
8776 if (!dev->addr_len)
8777 memset(sa->sa_data, 0, size);
8778 else
8779 memcpy(sa->sa_data, dev->dev_addr,
8780 min_t(size_t, size, dev->addr_len));
8781 sa->sa_family = dev->type;
8782
8783 unlock:
8784 rcu_read_unlock();
8785 up_read(&dev_addr_sem);
8786 return ret;
8787 }
8788 EXPORT_SYMBOL(dev_get_mac_address);
8789
8790 /**
8791 * dev_change_carrier - Change device carrier
8792 * @dev: device
8793 * @new_carrier: new value
8794 *
8795 * Change device carrier
8796 */
dev_change_carrier(struct net_device * dev,bool new_carrier)8797 int dev_change_carrier(struct net_device *dev, bool new_carrier)
8798 {
8799 const struct net_device_ops *ops = dev->netdev_ops;
8800
8801 if (!ops->ndo_change_carrier)
8802 return -EOPNOTSUPP;
8803 if (!netif_device_present(dev))
8804 return -ENODEV;
8805 return ops->ndo_change_carrier(dev, new_carrier);
8806 }
8807 EXPORT_SYMBOL(dev_change_carrier);
8808
8809 /**
8810 * dev_get_phys_port_id - Get device physical port ID
8811 * @dev: device
8812 * @ppid: port ID
8813 *
8814 * Get device physical port ID
8815 */
dev_get_phys_port_id(struct net_device * dev,struct netdev_phys_item_id * ppid)8816 int dev_get_phys_port_id(struct net_device *dev,
8817 struct netdev_phys_item_id *ppid)
8818 {
8819 const struct net_device_ops *ops = dev->netdev_ops;
8820
8821 if (!ops->ndo_get_phys_port_id)
8822 return -EOPNOTSUPP;
8823 return ops->ndo_get_phys_port_id(dev, ppid);
8824 }
8825 EXPORT_SYMBOL(dev_get_phys_port_id);
8826
8827 /**
8828 * dev_get_phys_port_name - Get device physical port name
8829 * @dev: device
8830 * @name: port name
8831 * @len: limit of bytes to copy to name
8832 *
8833 * Get device physical port name
8834 */
dev_get_phys_port_name(struct net_device * dev,char * name,size_t len)8835 int dev_get_phys_port_name(struct net_device *dev,
8836 char *name, size_t len)
8837 {
8838 const struct net_device_ops *ops = dev->netdev_ops;
8839 int err;
8840
8841 if (ops->ndo_get_phys_port_name) {
8842 err = ops->ndo_get_phys_port_name(dev, name, len);
8843 if (err != -EOPNOTSUPP)
8844 return err;
8845 }
8846 return devlink_compat_phys_port_name_get(dev, name, len);
8847 }
8848 EXPORT_SYMBOL(dev_get_phys_port_name);
8849
8850 /**
8851 * dev_get_port_parent_id - Get the device's port parent identifier
8852 * @dev: network device
8853 * @ppid: pointer to a storage for the port's parent identifier
8854 * @recurse: allow/disallow recursion to lower devices
8855 *
8856 * Get the devices's port parent identifier
8857 */
dev_get_port_parent_id(struct net_device * dev,struct netdev_phys_item_id * ppid,bool recurse)8858 int dev_get_port_parent_id(struct net_device *dev,
8859 struct netdev_phys_item_id *ppid,
8860 bool recurse)
8861 {
8862 const struct net_device_ops *ops = dev->netdev_ops;
8863 struct netdev_phys_item_id first = { };
8864 struct net_device *lower_dev;
8865 struct list_head *iter;
8866 int err;
8867
8868 if (ops->ndo_get_port_parent_id) {
8869 err = ops->ndo_get_port_parent_id(dev, ppid);
8870 if (err != -EOPNOTSUPP)
8871 return err;
8872 }
8873
8874 err = devlink_compat_switch_id_get(dev, ppid);
8875 if (!err || err != -EOPNOTSUPP)
8876 return err;
8877
8878 if (!recurse)
8879 return -EOPNOTSUPP;
8880
8881 netdev_for_each_lower_dev(dev, lower_dev, iter) {
8882 err = dev_get_port_parent_id(lower_dev, ppid, recurse);
8883 if (err)
8884 break;
8885 if (!first.id_len)
8886 first = *ppid;
8887 else if (memcmp(&first, ppid, sizeof(*ppid)))
8888 return -EOPNOTSUPP;
8889 }
8890
8891 return err;
8892 }
8893 EXPORT_SYMBOL(dev_get_port_parent_id);
8894
8895 /**
8896 * netdev_port_same_parent_id - Indicate if two network devices have
8897 * the same port parent identifier
8898 * @a: first network device
8899 * @b: second network device
8900 */
netdev_port_same_parent_id(struct net_device * a,struct net_device * b)8901 bool netdev_port_same_parent_id(struct net_device *a, struct net_device *b)
8902 {
8903 struct netdev_phys_item_id a_id = { };
8904 struct netdev_phys_item_id b_id = { };
8905
8906 if (dev_get_port_parent_id(a, &a_id, true) ||
8907 dev_get_port_parent_id(b, &b_id, true))
8908 return false;
8909
8910 return netdev_phys_item_id_same(&a_id, &b_id);
8911 }
8912 EXPORT_SYMBOL(netdev_port_same_parent_id);
8913
8914 /**
8915 * dev_change_proto_down - update protocol port state information
8916 * @dev: device
8917 * @proto_down: new value
8918 *
8919 * This info can be used by switch drivers to set the phys state of the
8920 * port.
8921 */
dev_change_proto_down(struct net_device * dev,bool proto_down)8922 int dev_change_proto_down(struct net_device *dev, bool proto_down)
8923 {
8924 const struct net_device_ops *ops = dev->netdev_ops;
8925
8926 if (!ops->ndo_change_proto_down)
8927 return -EOPNOTSUPP;
8928 if (!netif_device_present(dev))
8929 return -ENODEV;
8930 return ops->ndo_change_proto_down(dev, proto_down);
8931 }
8932 EXPORT_SYMBOL(dev_change_proto_down);
8933
8934 /**
8935 * dev_change_proto_down_generic - generic implementation for
8936 * ndo_change_proto_down that sets carrier according to
8937 * proto_down.
8938 *
8939 * @dev: device
8940 * @proto_down: new value
8941 */
dev_change_proto_down_generic(struct net_device * dev,bool proto_down)8942 int dev_change_proto_down_generic(struct net_device *dev, bool proto_down)
8943 {
8944 if (proto_down)
8945 netif_carrier_off(dev);
8946 else
8947 netif_carrier_on(dev);
8948 dev->proto_down = proto_down;
8949 return 0;
8950 }
8951 EXPORT_SYMBOL(dev_change_proto_down_generic);
8952
8953 /**
8954 * dev_change_proto_down_reason - proto down reason
8955 *
8956 * @dev: device
8957 * @mask: proto down mask
8958 * @value: proto down value
8959 */
dev_change_proto_down_reason(struct net_device * dev,unsigned long mask,u32 value)8960 void dev_change_proto_down_reason(struct net_device *dev, unsigned long mask,
8961 u32 value)
8962 {
8963 int b;
8964
8965 if (!mask) {
8966 dev->proto_down_reason = value;
8967 } else {
8968 for_each_set_bit(b, &mask, 32) {
8969 if (value & (1 << b))
8970 dev->proto_down_reason |= BIT(b);
8971 else
8972 dev->proto_down_reason &= ~BIT(b);
8973 }
8974 }
8975 }
8976 EXPORT_SYMBOL(dev_change_proto_down_reason);
8977
8978 struct bpf_xdp_link {
8979 struct bpf_link link;
8980 struct net_device *dev; /* protected by rtnl_lock, no refcnt held */
8981 int flags;
8982 };
8983
dev_xdp_mode(struct net_device * dev,u32 flags)8984 static enum bpf_xdp_mode dev_xdp_mode(struct net_device *dev, u32 flags)
8985 {
8986 if (flags & XDP_FLAGS_HW_MODE)
8987 return XDP_MODE_HW;
8988 if (flags & XDP_FLAGS_DRV_MODE)
8989 return XDP_MODE_DRV;
8990 if (flags & XDP_FLAGS_SKB_MODE)
8991 return XDP_MODE_SKB;
8992 return dev->netdev_ops->ndo_bpf ? XDP_MODE_DRV : XDP_MODE_SKB;
8993 }
8994
dev_xdp_bpf_op(struct net_device * dev,enum bpf_xdp_mode mode)8995 static bpf_op_t dev_xdp_bpf_op(struct net_device *dev, enum bpf_xdp_mode mode)
8996 {
8997 switch (mode) {
8998 case XDP_MODE_SKB:
8999 return generic_xdp_install;
9000 case XDP_MODE_DRV:
9001 case XDP_MODE_HW:
9002 return dev->netdev_ops->ndo_bpf;
9003 default:
9004 return NULL;
9005 };
9006 }
9007
dev_xdp_link(struct net_device * dev,enum bpf_xdp_mode mode)9008 static struct bpf_xdp_link *dev_xdp_link(struct net_device *dev,
9009 enum bpf_xdp_mode mode)
9010 {
9011 return dev->xdp_state[mode].link;
9012 }
9013
dev_xdp_prog(struct net_device * dev,enum bpf_xdp_mode mode)9014 static struct bpf_prog *dev_xdp_prog(struct net_device *dev,
9015 enum bpf_xdp_mode mode)
9016 {
9017 struct bpf_xdp_link *link = dev_xdp_link(dev, mode);
9018
9019 if (link)
9020 return link->link.prog;
9021 return dev->xdp_state[mode].prog;
9022 }
9023
dev_xdp_prog_count(struct net_device * dev)9024 static u8 dev_xdp_prog_count(struct net_device *dev)
9025 {
9026 u8 count = 0;
9027 int i;
9028
9029 for (i = 0; i < __MAX_XDP_MODE; i++)
9030 if (dev->xdp_state[i].prog || dev->xdp_state[i].link)
9031 count++;
9032 return count;
9033 }
9034
dev_xdp_prog_id(struct net_device * dev,enum bpf_xdp_mode mode)9035 u32 dev_xdp_prog_id(struct net_device *dev, enum bpf_xdp_mode mode)
9036 {
9037 struct bpf_prog *prog = dev_xdp_prog(dev, mode);
9038
9039 return prog ? prog->aux->id : 0;
9040 }
9041
dev_xdp_set_link(struct net_device * dev,enum bpf_xdp_mode mode,struct bpf_xdp_link * link)9042 static void dev_xdp_set_link(struct net_device *dev, enum bpf_xdp_mode mode,
9043 struct bpf_xdp_link *link)
9044 {
9045 dev->xdp_state[mode].link = link;
9046 dev->xdp_state[mode].prog = NULL;
9047 }
9048
dev_xdp_set_prog(struct net_device * dev,enum bpf_xdp_mode mode,struct bpf_prog * prog)9049 static void dev_xdp_set_prog(struct net_device *dev, enum bpf_xdp_mode mode,
9050 struct bpf_prog *prog)
9051 {
9052 dev->xdp_state[mode].link = NULL;
9053 dev->xdp_state[mode].prog = prog;
9054 }
9055
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)9056 static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,
9057 bpf_op_t bpf_op, struct netlink_ext_ack *extack,
9058 u32 flags, struct bpf_prog *prog)
9059 {
9060 struct netdev_bpf xdp;
9061 int err;
9062
9063 memset(&xdp, 0, sizeof(xdp));
9064 xdp.command = mode == XDP_MODE_HW ? XDP_SETUP_PROG_HW : XDP_SETUP_PROG;
9065 xdp.extack = extack;
9066 xdp.flags = flags;
9067 xdp.prog = prog;
9068
9069 /* Drivers assume refcnt is already incremented (i.e, prog pointer is
9070 * "moved" into driver), so they don't increment it on their own, but
9071 * they do decrement refcnt when program is detached or replaced.
9072 * Given net_device also owns link/prog, we need to bump refcnt here
9073 * to prevent drivers from underflowing it.
9074 */
9075 if (prog)
9076 bpf_prog_inc(prog);
9077 err = bpf_op(dev, &xdp);
9078 if (err) {
9079 if (prog)
9080 bpf_prog_put(prog);
9081 return err;
9082 }
9083
9084 if (mode != XDP_MODE_HW)
9085 bpf_prog_change_xdp(dev_xdp_prog(dev, mode), prog);
9086
9087 return 0;
9088 }
9089
dev_xdp_uninstall(struct net_device * dev)9090 static void dev_xdp_uninstall(struct net_device *dev)
9091 {
9092 struct bpf_xdp_link *link;
9093 struct bpf_prog *prog;
9094 enum bpf_xdp_mode mode;
9095 bpf_op_t bpf_op;
9096
9097 ASSERT_RTNL();
9098
9099 for (mode = XDP_MODE_SKB; mode < __MAX_XDP_MODE; mode++) {
9100 prog = dev_xdp_prog(dev, mode);
9101 if (!prog)
9102 continue;
9103
9104 bpf_op = dev_xdp_bpf_op(dev, mode);
9105 if (!bpf_op)
9106 continue;
9107
9108 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
9109
9110 /* auto-detach link from net device */
9111 link = dev_xdp_link(dev, mode);
9112 if (link)
9113 link->dev = NULL;
9114 else
9115 bpf_prog_put(prog);
9116
9117 dev_xdp_set_link(dev, mode, NULL);
9118 }
9119 }
9120
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)9121 static int dev_xdp_attach(struct net_device *dev, struct netlink_ext_ack *extack,
9122 struct bpf_xdp_link *link, struct bpf_prog *new_prog,
9123 struct bpf_prog *old_prog, u32 flags)
9124 {
9125 unsigned int num_modes = hweight32(flags & XDP_FLAGS_MODES);
9126 struct bpf_prog *cur_prog;
9127 enum bpf_xdp_mode mode;
9128 bpf_op_t bpf_op;
9129 int err;
9130
9131 ASSERT_RTNL();
9132
9133 /* either link or prog attachment, never both */
9134 if (link && (new_prog || old_prog))
9135 return -EINVAL;
9136 /* link supports only XDP mode flags */
9137 if (link && (flags & ~XDP_FLAGS_MODES)) {
9138 NL_SET_ERR_MSG(extack, "Invalid XDP flags for BPF link attachment");
9139 return -EINVAL;
9140 }
9141 /* just one XDP mode bit should be set, zero defaults to drv/skb mode */
9142 if (num_modes > 1) {
9143 NL_SET_ERR_MSG(extack, "Only one XDP mode flag can be set");
9144 return -EINVAL;
9145 }
9146 /* avoid ambiguity if offload + drv/skb mode progs are both loaded */
9147 if (!num_modes && dev_xdp_prog_count(dev) > 1) {
9148 NL_SET_ERR_MSG(extack,
9149 "More than one program loaded, unset mode is ambiguous");
9150 return -EINVAL;
9151 }
9152 /* old_prog != NULL implies XDP_FLAGS_REPLACE is set */
9153 if (old_prog && !(flags & XDP_FLAGS_REPLACE)) {
9154 NL_SET_ERR_MSG(extack, "XDP_FLAGS_REPLACE is not specified");
9155 return -EINVAL;
9156 }
9157
9158 mode = dev_xdp_mode(dev, flags);
9159 /* can't replace attached link */
9160 if (dev_xdp_link(dev, mode)) {
9161 NL_SET_ERR_MSG(extack, "Can't replace active BPF XDP link");
9162 return -EBUSY;
9163 }
9164
9165 cur_prog = dev_xdp_prog(dev, mode);
9166 /* can't replace attached prog with link */
9167 if (link && cur_prog) {
9168 NL_SET_ERR_MSG(extack, "Can't replace active XDP program with BPF link");
9169 return -EBUSY;
9170 }
9171 if ((flags & XDP_FLAGS_REPLACE) && cur_prog != old_prog) {
9172 NL_SET_ERR_MSG(extack, "Active program does not match expected");
9173 return -EEXIST;
9174 }
9175
9176 /* put effective new program into new_prog */
9177 if (link)
9178 new_prog = link->link.prog;
9179
9180 if (new_prog) {
9181 bool offload = mode == XDP_MODE_HW;
9182 enum bpf_xdp_mode other_mode = mode == XDP_MODE_SKB
9183 ? XDP_MODE_DRV : XDP_MODE_SKB;
9184
9185 if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) && cur_prog) {
9186 NL_SET_ERR_MSG(extack, "XDP program already attached");
9187 return -EBUSY;
9188 }
9189 if (!offload && dev_xdp_prog(dev, other_mode)) {
9190 NL_SET_ERR_MSG(extack, "Native and generic XDP can't be active at the same time");
9191 return -EEXIST;
9192 }
9193 if (!offload && bpf_prog_is_dev_bound(new_prog->aux)) {
9194 NL_SET_ERR_MSG(extack, "Using device-bound program without HW_MODE flag is not supported");
9195 return -EINVAL;
9196 }
9197 if (new_prog->expected_attach_type == BPF_XDP_DEVMAP) {
9198 NL_SET_ERR_MSG(extack, "BPF_XDP_DEVMAP programs can not be attached to a device");
9199 return -EINVAL;
9200 }
9201 if (new_prog->expected_attach_type == BPF_XDP_CPUMAP) {
9202 NL_SET_ERR_MSG(extack, "BPF_XDP_CPUMAP programs can not be attached to a device");
9203 return -EINVAL;
9204 }
9205 }
9206
9207 /* don't call drivers if the effective program didn't change */
9208 if (new_prog != cur_prog) {
9209 bpf_op = dev_xdp_bpf_op(dev, mode);
9210 if (!bpf_op) {
9211 NL_SET_ERR_MSG(extack, "Underlying driver does not support XDP in native mode");
9212 return -EOPNOTSUPP;
9213 }
9214
9215 err = dev_xdp_install(dev, mode, bpf_op, extack, flags, new_prog);
9216 if (err)
9217 return err;
9218 }
9219
9220 if (link)
9221 dev_xdp_set_link(dev, mode, link);
9222 else
9223 dev_xdp_set_prog(dev, mode, new_prog);
9224 if (cur_prog)
9225 bpf_prog_put(cur_prog);
9226
9227 return 0;
9228 }
9229
dev_xdp_attach_link(struct net_device * dev,struct netlink_ext_ack * extack,struct bpf_xdp_link * link)9230 static int dev_xdp_attach_link(struct net_device *dev,
9231 struct netlink_ext_ack *extack,
9232 struct bpf_xdp_link *link)
9233 {
9234 return dev_xdp_attach(dev, extack, link, NULL, NULL, link->flags);
9235 }
9236
dev_xdp_detach_link(struct net_device * dev,struct netlink_ext_ack * extack,struct bpf_xdp_link * link)9237 static int dev_xdp_detach_link(struct net_device *dev,
9238 struct netlink_ext_ack *extack,
9239 struct bpf_xdp_link *link)
9240 {
9241 enum bpf_xdp_mode mode;
9242 bpf_op_t bpf_op;
9243
9244 ASSERT_RTNL();
9245
9246 mode = dev_xdp_mode(dev, link->flags);
9247 if (dev_xdp_link(dev, mode) != link)
9248 return -EINVAL;
9249
9250 bpf_op = dev_xdp_bpf_op(dev, mode);
9251 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
9252 dev_xdp_set_link(dev, mode, NULL);
9253 return 0;
9254 }
9255
bpf_xdp_link_release(struct bpf_link * link)9256 static void bpf_xdp_link_release(struct bpf_link *link)
9257 {
9258 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9259
9260 rtnl_lock();
9261
9262 /* if racing with net_device's tear down, xdp_link->dev might be
9263 * already NULL, in which case link was already auto-detached
9264 */
9265 if (xdp_link->dev) {
9266 WARN_ON(dev_xdp_detach_link(xdp_link->dev, NULL, xdp_link));
9267 xdp_link->dev = NULL;
9268 }
9269
9270 rtnl_unlock();
9271 }
9272
bpf_xdp_link_detach(struct bpf_link * link)9273 static int bpf_xdp_link_detach(struct bpf_link *link)
9274 {
9275 bpf_xdp_link_release(link);
9276 return 0;
9277 }
9278
bpf_xdp_link_dealloc(struct bpf_link * link)9279 static void bpf_xdp_link_dealloc(struct bpf_link *link)
9280 {
9281 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9282
9283 kfree(xdp_link);
9284 }
9285
bpf_xdp_link_show_fdinfo(const struct bpf_link * link,struct seq_file * seq)9286 static void bpf_xdp_link_show_fdinfo(const struct bpf_link *link,
9287 struct seq_file *seq)
9288 {
9289 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9290 u32 ifindex = 0;
9291
9292 rtnl_lock();
9293 if (xdp_link->dev)
9294 ifindex = xdp_link->dev->ifindex;
9295 rtnl_unlock();
9296
9297 seq_printf(seq, "ifindex:\t%u\n", ifindex);
9298 }
9299
bpf_xdp_link_fill_link_info(const struct bpf_link * link,struct bpf_link_info * info)9300 static int bpf_xdp_link_fill_link_info(const struct bpf_link *link,
9301 struct bpf_link_info *info)
9302 {
9303 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9304 u32 ifindex = 0;
9305
9306 rtnl_lock();
9307 if (xdp_link->dev)
9308 ifindex = xdp_link->dev->ifindex;
9309 rtnl_unlock();
9310
9311 info->xdp.ifindex = ifindex;
9312 return 0;
9313 }
9314
bpf_xdp_link_update(struct bpf_link * link,struct bpf_prog * new_prog,struct bpf_prog * old_prog)9315 static int bpf_xdp_link_update(struct bpf_link *link, struct bpf_prog *new_prog,
9316 struct bpf_prog *old_prog)
9317 {
9318 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9319 enum bpf_xdp_mode mode;
9320 bpf_op_t bpf_op;
9321 int err = 0;
9322
9323 rtnl_lock();
9324
9325 /* link might have been auto-released already, so fail */
9326 if (!xdp_link->dev) {
9327 err = -ENOLINK;
9328 goto out_unlock;
9329 }
9330
9331 if (old_prog && link->prog != old_prog) {
9332 err = -EPERM;
9333 goto out_unlock;
9334 }
9335 old_prog = link->prog;
9336 if (old_prog == new_prog) {
9337 /* no-op, don't disturb drivers */
9338 bpf_prog_put(new_prog);
9339 goto out_unlock;
9340 }
9341
9342 mode = dev_xdp_mode(xdp_link->dev, xdp_link->flags);
9343 bpf_op = dev_xdp_bpf_op(xdp_link->dev, mode);
9344 err = dev_xdp_install(xdp_link->dev, mode, bpf_op, NULL,
9345 xdp_link->flags, new_prog);
9346 if (err)
9347 goto out_unlock;
9348
9349 old_prog = xchg(&link->prog, new_prog);
9350 bpf_prog_put(old_prog);
9351
9352 out_unlock:
9353 rtnl_unlock();
9354 return err;
9355 }
9356
9357 static const struct bpf_link_ops bpf_xdp_link_lops = {
9358 .release = bpf_xdp_link_release,
9359 .dealloc = bpf_xdp_link_dealloc,
9360 .detach = bpf_xdp_link_detach,
9361 .show_fdinfo = bpf_xdp_link_show_fdinfo,
9362 .fill_link_info = bpf_xdp_link_fill_link_info,
9363 .update_prog = bpf_xdp_link_update,
9364 };
9365
bpf_xdp_link_attach(const union bpf_attr * attr,struct bpf_prog * prog)9366 int bpf_xdp_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
9367 {
9368 struct net *net = current->nsproxy->net_ns;
9369 struct bpf_link_primer link_primer;
9370 struct bpf_xdp_link *link;
9371 struct net_device *dev;
9372 int err, fd;
9373
9374 rtnl_lock();
9375 dev = dev_get_by_index(net, attr->link_create.target_ifindex);
9376 if (!dev) {
9377 rtnl_unlock();
9378 return -EINVAL;
9379 }
9380
9381 link = kzalloc(sizeof(*link), GFP_USER);
9382 if (!link) {
9383 err = -ENOMEM;
9384 goto unlock;
9385 }
9386
9387 bpf_link_init(&link->link, BPF_LINK_TYPE_XDP, &bpf_xdp_link_lops, prog);
9388 link->dev = dev;
9389 link->flags = attr->link_create.flags;
9390
9391 err = bpf_link_prime(&link->link, &link_primer);
9392 if (err) {
9393 kfree(link);
9394 goto unlock;
9395 }
9396
9397 err = dev_xdp_attach_link(dev, NULL, link);
9398 rtnl_unlock();
9399
9400 if (err) {
9401 link->dev = NULL;
9402 bpf_link_cleanup(&link_primer);
9403 goto out_put_dev;
9404 }
9405
9406 fd = bpf_link_settle(&link_primer);
9407 /* link itself doesn't hold dev's refcnt to not complicate shutdown */
9408 dev_put(dev);
9409 return fd;
9410
9411 unlock:
9412 rtnl_unlock();
9413
9414 out_put_dev:
9415 dev_put(dev);
9416 return err;
9417 }
9418
9419 /**
9420 * dev_change_xdp_fd - set or clear a bpf program for a device rx path
9421 * @dev: device
9422 * @extack: netlink extended ack
9423 * @fd: new program fd or negative value to clear
9424 * @expected_fd: old program fd that userspace expects to replace or clear
9425 * @flags: xdp-related flags
9426 *
9427 * Set or clear a bpf program for a device
9428 */
dev_change_xdp_fd(struct net_device * dev,struct netlink_ext_ack * extack,int fd,int expected_fd,u32 flags)9429 int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack,
9430 int fd, int expected_fd, u32 flags)
9431 {
9432 enum bpf_xdp_mode mode = dev_xdp_mode(dev, flags);
9433 struct bpf_prog *new_prog = NULL, *old_prog = NULL;
9434 int err;
9435
9436 ASSERT_RTNL();
9437
9438 if (fd >= 0) {
9439 new_prog = bpf_prog_get_type_dev(fd, BPF_PROG_TYPE_XDP,
9440 mode != XDP_MODE_SKB);
9441 if (IS_ERR(new_prog))
9442 return PTR_ERR(new_prog);
9443 }
9444
9445 if (expected_fd >= 0) {
9446 old_prog = bpf_prog_get_type_dev(expected_fd, BPF_PROG_TYPE_XDP,
9447 mode != XDP_MODE_SKB);
9448 if (IS_ERR(old_prog)) {
9449 err = PTR_ERR(old_prog);
9450 old_prog = NULL;
9451 goto err_out;
9452 }
9453 }
9454
9455 err = dev_xdp_attach(dev, extack, NULL, new_prog, old_prog, flags);
9456
9457 err_out:
9458 if (err && new_prog)
9459 bpf_prog_put(new_prog);
9460 if (old_prog)
9461 bpf_prog_put(old_prog);
9462 return err;
9463 }
9464
9465 /**
9466 * dev_new_index - allocate an ifindex
9467 * @net: the applicable net namespace
9468 *
9469 * Returns a suitable unique value for a new device interface
9470 * number. The caller must hold the rtnl semaphore or the
9471 * dev_base_lock to be sure it remains unique.
9472 */
dev_new_index(struct net * net)9473 static int dev_new_index(struct net *net)
9474 {
9475 int ifindex = net->ifindex;
9476
9477 for (;;) {
9478 if (++ifindex <= 0)
9479 ifindex = 1;
9480 if (!__dev_get_by_index(net, ifindex))
9481 return net->ifindex = ifindex;
9482 }
9483 }
9484
9485 /* Delayed registration/unregisteration */
9486 static LIST_HEAD(net_todo_list);
9487 DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq);
9488
net_set_todo(struct net_device * dev)9489 static void net_set_todo(struct net_device *dev)
9490 {
9491 list_add_tail(&dev->todo_list, &net_todo_list);
9492 dev_net(dev)->dev_unreg_count++;
9493 }
9494
rollback_registered_many(struct list_head * head)9495 static void rollback_registered_many(struct list_head *head)
9496 {
9497 struct net_device *dev, *tmp;
9498 LIST_HEAD(close_head);
9499
9500 BUG_ON(dev_boot_phase);
9501 ASSERT_RTNL();
9502
9503 list_for_each_entry_safe(dev, tmp, head, unreg_list) {
9504 /* Some devices call without registering
9505 * for initialization unwind. Remove those
9506 * devices and proceed with the remaining.
9507 */
9508 if (dev->reg_state == NETREG_UNINITIALIZED) {
9509 pr_debug("unregister_netdevice: device %s/%p never was registered\n",
9510 dev->name, dev);
9511
9512 WARN_ON(1);
9513 list_del(&dev->unreg_list);
9514 continue;
9515 }
9516 dev->dismantle = true;
9517 BUG_ON(dev->reg_state != NETREG_REGISTERED);
9518 }
9519
9520 /* If device is running, close it first. */
9521 list_for_each_entry(dev, head, unreg_list)
9522 list_add_tail(&dev->close_list, &close_head);
9523 dev_close_many(&close_head, true);
9524
9525 list_for_each_entry(dev, head, unreg_list) {
9526 /* And unlink it from device chain. */
9527 unlist_netdevice(dev);
9528
9529 dev->reg_state = NETREG_UNREGISTERING;
9530 }
9531 flush_all_backlogs();
9532
9533 synchronize_net();
9534
9535 list_for_each_entry(dev, head, unreg_list) {
9536 struct sk_buff *skb = NULL;
9537
9538 /* Shutdown queueing discipline. */
9539 dev_shutdown(dev);
9540
9541 dev_xdp_uninstall(dev);
9542
9543 /* Notify protocols, that we are about to destroy
9544 * this device. They should clean all the things.
9545 */
9546 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
9547
9548 if (!dev->rtnl_link_ops ||
9549 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
9550 skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0,
9551 GFP_KERNEL, NULL, 0);
9552
9553 /*
9554 * Flush the unicast and multicast chains
9555 */
9556 dev_uc_flush(dev);
9557 dev_mc_flush(dev);
9558
9559 netdev_name_node_alt_flush(dev);
9560 netdev_name_node_free(dev->name_node);
9561
9562 if (dev->netdev_ops->ndo_uninit)
9563 dev->netdev_ops->ndo_uninit(dev);
9564
9565 if (skb)
9566 rtmsg_ifinfo_send(skb, dev, GFP_KERNEL);
9567
9568 /* Notifier chain MUST detach us all upper devices. */
9569 WARN_ON(netdev_has_any_upper_dev(dev));
9570 WARN_ON(netdev_has_any_lower_dev(dev));
9571
9572 /* Remove entries from kobject tree */
9573 netdev_unregister_kobject(dev);
9574 #ifdef CONFIG_XPS
9575 /* Remove XPS queueing entries */
9576 netif_reset_xps_queues_gt(dev, 0);
9577 #endif
9578 }
9579
9580 synchronize_net();
9581
9582 list_for_each_entry(dev, head, unreg_list)
9583 dev_put(dev);
9584 }
9585
rollback_registered(struct net_device * dev)9586 static void rollback_registered(struct net_device *dev)
9587 {
9588 LIST_HEAD(single);
9589
9590 list_add(&dev->unreg_list, &single);
9591 rollback_registered_many(&single);
9592 list_del(&single);
9593 }
9594
netdev_sync_upper_features(struct net_device * lower,struct net_device * upper,netdev_features_t features)9595 static netdev_features_t netdev_sync_upper_features(struct net_device *lower,
9596 struct net_device *upper, netdev_features_t features)
9597 {
9598 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
9599 netdev_features_t feature;
9600 int feature_bit;
9601
9602 for_each_netdev_feature(upper_disables, feature_bit) {
9603 feature = __NETIF_F_BIT(feature_bit);
9604 if (!(upper->wanted_features & feature)
9605 && (features & feature)) {
9606 netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n",
9607 &feature, upper->name);
9608 features &= ~feature;
9609 }
9610 }
9611
9612 return features;
9613 }
9614
netdev_sync_lower_features(struct net_device * upper,struct net_device * lower,netdev_features_t features)9615 static void netdev_sync_lower_features(struct net_device *upper,
9616 struct net_device *lower, netdev_features_t features)
9617 {
9618 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
9619 netdev_features_t feature;
9620 int feature_bit;
9621
9622 for_each_netdev_feature(upper_disables, feature_bit) {
9623 feature = __NETIF_F_BIT(feature_bit);
9624 if (!(features & feature) && (lower->features & feature)) {
9625 netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n",
9626 &feature, lower->name);
9627 lower->wanted_features &= ~feature;
9628 __netdev_update_features(lower);
9629
9630 if (unlikely(lower->features & feature))
9631 netdev_WARN(upper, "failed to disable %pNF on %s!\n",
9632 &feature, lower->name);
9633 else
9634 netdev_features_change(lower);
9635 }
9636 }
9637 }
9638
netdev_fix_features(struct net_device * dev,netdev_features_t features)9639 static netdev_features_t netdev_fix_features(struct net_device *dev,
9640 netdev_features_t features)
9641 {
9642 /* Fix illegal checksum combinations */
9643 if ((features & NETIF_F_HW_CSUM) &&
9644 (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
9645 netdev_warn(dev, "mixed HW and IP checksum settings.\n");
9646 features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM);
9647 }
9648
9649 /* TSO requires that SG is present as well. */
9650 if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) {
9651 netdev_dbg(dev, "Dropping TSO features since no SG feature.\n");
9652 features &= ~NETIF_F_ALL_TSO;
9653 }
9654
9655 if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) &&
9656 !(features & NETIF_F_IP_CSUM)) {
9657 netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n");
9658 features &= ~NETIF_F_TSO;
9659 features &= ~NETIF_F_TSO_ECN;
9660 }
9661
9662 if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) &&
9663 !(features & NETIF_F_IPV6_CSUM)) {
9664 netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n");
9665 features &= ~NETIF_F_TSO6;
9666 }
9667
9668 /* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */
9669 if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO))
9670 features &= ~NETIF_F_TSO_MANGLEID;
9671
9672 /* TSO ECN requires that TSO is present as well. */
9673 if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN)
9674 features &= ~NETIF_F_TSO_ECN;
9675
9676 /* Software GSO depends on SG. */
9677 if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) {
9678 netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n");
9679 features &= ~NETIF_F_GSO;
9680 }
9681
9682 /* GSO partial features require GSO partial be set */
9683 if ((features & dev->gso_partial_features) &&
9684 !(features & NETIF_F_GSO_PARTIAL)) {
9685 netdev_dbg(dev,
9686 "Dropping partially supported GSO features since no GSO partial.\n");
9687 features &= ~dev->gso_partial_features;
9688 }
9689
9690 if (!(features & NETIF_F_RXCSUM)) {
9691 /* NETIF_F_GRO_HW implies doing RXCSUM since every packet
9692 * successfully merged by hardware must also have the
9693 * checksum verified by hardware. If the user does not
9694 * want to enable RXCSUM, logically, we should disable GRO_HW.
9695 */
9696 if (features & NETIF_F_GRO_HW) {
9697 netdev_dbg(dev, "Dropping NETIF_F_GRO_HW since no RXCSUM feature.\n");
9698 features &= ~NETIF_F_GRO_HW;
9699 }
9700 }
9701
9702 /* LRO/HW-GRO features cannot be combined with RX-FCS */
9703 if (features & NETIF_F_RXFCS) {
9704 if (features & NETIF_F_LRO) {
9705 netdev_dbg(dev, "Dropping LRO feature since RX-FCS is requested.\n");
9706 features &= ~NETIF_F_LRO;
9707 }
9708
9709 if (features & NETIF_F_GRO_HW) {
9710 netdev_dbg(dev, "Dropping HW-GRO feature since RX-FCS is requested.\n");
9711 features &= ~NETIF_F_GRO_HW;
9712 }
9713 }
9714
9715 if ((features & NETIF_F_HW_TLS_RX) && !(features & NETIF_F_RXCSUM)) {
9716 netdev_dbg(dev, "Dropping TLS RX HW offload feature since no RXCSUM feature.\n");
9717 features &= ~NETIF_F_HW_TLS_RX;
9718 }
9719
9720 return features;
9721 }
9722
__netdev_update_features(struct net_device * dev)9723 int __netdev_update_features(struct net_device *dev)
9724 {
9725 struct net_device *upper, *lower;
9726 netdev_features_t features;
9727 struct list_head *iter;
9728 int err = -1;
9729
9730 ASSERT_RTNL();
9731
9732 features = netdev_get_wanted_features(dev);
9733
9734 if (dev->netdev_ops->ndo_fix_features)
9735 features = dev->netdev_ops->ndo_fix_features(dev, features);
9736
9737 /* driver might be less strict about feature dependencies */
9738 features = netdev_fix_features(dev, features);
9739
9740 /* some features can't be enabled if they're off on an upper device */
9741 netdev_for_each_upper_dev_rcu(dev, upper, iter)
9742 features = netdev_sync_upper_features(dev, upper, features);
9743
9744 if (dev->features == features)
9745 goto sync_lower;
9746
9747 netdev_dbg(dev, "Features changed: %pNF -> %pNF\n",
9748 &dev->features, &features);
9749
9750 if (dev->netdev_ops->ndo_set_features)
9751 err = dev->netdev_ops->ndo_set_features(dev, features);
9752 else
9753 err = 0;
9754
9755 if (unlikely(err < 0)) {
9756 netdev_err(dev,
9757 "set_features() failed (%d); wanted %pNF, left %pNF\n",
9758 err, &features, &dev->features);
9759 /* return non-0 since some features might have changed and
9760 * it's better to fire a spurious notification than miss it
9761 */
9762 return -1;
9763 }
9764
9765 sync_lower:
9766 /* some features must be disabled on lower devices when disabled
9767 * on an upper device (think: bonding master or bridge)
9768 */
9769 netdev_for_each_lower_dev(dev, lower, iter)
9770 netdev_sync_lower_features(dev, lower, features);
9771
9772 if (!err) {
9773 netdev_features_t diff = features ^ dev->features;
9774
9775 if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) {
9776 /* udp_tunnel_{get,drop}_rx_info both need
9777 * NETIF_F_RX_UDP_TUNNEL_PORT enabled on the
9778 * device, or they won't do anything.
9779 * Thus we need to update dev->features
9780 * *before* calling udp_tunnel_get_rx_info,
9781 * but *after* calling udp_tunnel_drop_rx_info.
9782 */
9783 if (features & NETIF_F_RX_UDP_TUNNEL_PORT) {
9784 dev->features = features;
9785 udp_tunnel_get_rx_info(dev);
9786 } else {
9787 udp_tunnel_drop_rx_info(dev);
9788 }
9789 }
9790
9791 if (diff & NETIF_F_HW_VLAN_CTAG_FILTER) {
9792 if (features & NETIF_F_HW_VLAN_CTAG_FILTER) {
9793 dev->features = features;
9794 err |= vlan_get_rx_ctag_filter_info(dev);
9795 } else {
9796 vlan_drop_rx_ctag_filter_info(dev);
9797 }
9798 }
9799
9800 if (diff & NETIF_F_HW_VLAN_STAG_FILTER) {
9801 if (features & NETIF_F_HW_VLAN_STAG_FILTER) {
9802 dev->features = features;
9803 err |= vlan_get_rx_stag_filter_info(dev);
9804 } else {
9805 vlan_drop_rx_stag_filter_info(dev);
9806 }
9807 }
9808
9809 dev->features = features;
9810 }
9811
9812 return err < 0 ? 0 : 1;
9813 }
9814
9815 /**
9816 * netdev_update_features - recalculate device features
9817 * @dev: the device to check
9818 *
9819 * Recalculate dev->features set and send notifications if it
9820 * has changed. Should be called after driver or hardware dependent
9821 * conditions might have changed that influence the features.
9822 */
netdev_update_features(struct net_device * dev)9823 void netdev_update_features(struct net_device *dev)
9824 {
9825 if (__netdev_update_features(dev))
9826 netdev_features_change(dev);
9827 }
9828 EXPORT_SYMBOL(netdev_update_features);
9829
9830 /**
9831 * netdev_change_features - recalculate device features
9832 * @dev: the device to check
9833 *
9834 * Recalculate dev->features set and send notifications even
9835 * if they have not changed. Should be called instead of
9836 * netdev_update_features() if also dev->vlan_features might
9837 * have changed to allow the changes to be propagated to stacked
9838 * VLAN devices.
9839 */
netdev_change_features(struct net_device * dev)9840 void netdev_change_features(struct net_device *dev)
9841 {
9842 __netdev_update_features(dev);
9843 netdev_features_change(dev);
9844 }
9845 EXPORT_SYMBOL(netdev_change_features);
9846
9847 /**
9848 * netif_stacked_transfer_operstate - transfer operstate
9849 * @rootdev: the root or lower level device to transfer state from
9850 * @dev: the device to transfer operstate to
9851 *
9852 * Transfer operational state from root to device. This is normally
9853 * called when a stacking relationship exists between the root
9854 * device and the device(a leaf device).
9855 */
netif_stacked_transfer_operstate(const struct net_device * rootdev,struct net_device * dev)9856 void netif_stacked_transfer_operstate(const struct net_device *rootdev,
9857 struct net_device *dev)
9858 {
9859 if (rootdev->operstate == IF_OPER_DORMANT)
9860 netif_dormant_on(dev);
9861 else
9862 netif_dormant_off(dev);
9863
9864 if (rootdev->operstate == IF_OPER_TESTING)
9865 netif_testing_on(dev);
9866 else
9867 netif_testing_off(dev);
9868
9869 if (netif_carrier_ok(rootdev))
9870 netif_carrier_on(dev);
9871 else
9872 netif_carrier_off(dev);
9873 }
9874 EXPORT_SYMBOL(netif_stacked_transfer_operstate);
9875
netif_alloc_rx_queues(struct net_device * dev)9876 static int netif_alloc_rx_queues(struct net_device *dev)
9877 {
9878 unsigned int i, count = dev->num_rx_queues;
9879 struct netdev_rx_queue *rx;
9880 size_t sz = count * sizeof(*rx);
9881 int err = 0;
9882
9883 BUG_ON(count < 1);
9884
9885 rx = kvzalloc(sz, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
9886 if (!rx)
9887 return -ENOMEM;
9888
9889 dev->_rx = rx;
9890
9891 for (i = 0; i < count; i++) {
9892 rx[i].dev = dev;
9893
9894 /* XDP RX-queue setup */
9895 err = xdp_rxq_info_reg(&rx[i].xdp_rxq, dev, i);
9896 if (err < 0)
9897 goto err_rxq_info;
9898 }
9899 return 0;
9900
9901 err_rxq_info:
9902 /* Rollback successful reg's and free other resources */
9903 while (i--)
9904 xdp_rxq_info_unreg(&rx[i].xdp_rxq);
9905 kvfree(dev->_rx);
9906 dev->_rx = NULL;
9907 return err;
9908 }
9909
netif_free_rx_queues(struct net_device * dev)9910 static void netif_free_rx_queues(struct net_device *dev)
9911 {
9912 unsigned int i, count = dev->num_rx_queues;
9913
9914 /* netif_alloc_rx_queues alloc failed, resources have been unreg'ed */
9915 if (!dev->_rx)
9916 return;
9917
9918 for (i = 0; i < count; i++)
9919 xdp_rxq_info_unreg(&dev->_rx[i].xdp_rxq);
9920
9921 kvfree(dev->_rx);
9922 }
9923
netdev_init_one_queue(struct net_device * dev,struct netdev_queue * queue,void * _unused)9924 static void netdev_init_one_queue(struct net_device *dev,
9925 struct netdev_queue *queue, void *_unused)
9926 {
9927 /* Initialize queue lock */
9928 spin_lock_init(&queue->_xmit_lock);
9929 netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type);
9930 queue->xmit_lock_owner = -1;
9931 netdev_queue_numa_node_write(queue, NUMA_NO_NODE);
9932 queue->dev = dev;
9933 #ifdef CONFIG_BQL
9934 dql_init(&queue->dql, HZ);
9935 #endif
9936 }
9937
netif_free_tx_queues(struct net_device * dev)9938 static void netif_free_tx_queues(struct net_device *dev)
9939 {
9940 kvfree(dev->_tx);
9941 }
9942
netif_alloc_netdev_queues(struct net_device * dev)9943 static int netif_alloc_netdev_queues(struct net_device *dev)
9944 {
9945 unsigned int count = dev->num_tx_queues;
9946 struct netdev_queue *tx;
9947 size_t sz = count * sizeof(*tx);
9948
9949 if (count < 1 || count > 0xffff)
9950 return -EINVAL;
9951
9952 tx = kvzalloc(sz, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
9953 if (!tx)
9954 return -ENOMEM;
9955
9956 dev->_tx = tx;
9957
9958 netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL);
9959 spin_lock_init(&dev->tx_global_lock);
9960
9961 return 0;
9962 }
9963
netif_tx_stop_all_queues(struct net_device * dev)9964 void netif_tx_stop_all_queues(struct net_device *dev)
9965 {
9966 unsigned int i;
9967
9968 for (i = 0; i < dev->num_tx_queues; i++) {
9969 struct netdev_queue *txq = netdev_get_tx_queue(dev, i);
9970
9971 netif_tx_stop_queue(txq);
9972 }
9973 }
9974 EXPORT_SYMBOL(netif_tx_stop_all_queues);
9975
9976 /**
9977 * register_netdevice - register a network device
9978 * @dev: device to register
9979 *
9980 * Take a completed network device structure and add it to the kernel
9981 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
9982 * chain. 0 is returned on success. A negative errno code is returned
9983 * on a failure to set up the device, or if the name is a duplicate.
9984 *
9985 * Callers must hold the rtnl semaphore. You may want
9986 * register_netdev() instead of this.
9987 *
9988 * BUGS:
9989 * The locking appears insufficient to guarantee two parallel registers
9990 * will not get the same name.
9991 */
9992
register_netdevice(struct net_device * dev)9993 int register_netdevice(struct net_device *dev)
9994 {
9995 int ret;
9996 struct net *net = dev_net(dev);
9997
9998 BUILD_BUG_ON(sizeof(netdev_features_t) * BITS_PER_BYTE <
9999 NETDEV_FEATURE_COUNT);
10000 BUG_ON(dev_boot_phase);
10001 ASSERT_RTNL();
10002
10003 might_sleep();
10004
10005 /* When net_device's are persistent, this will be fatal. */
10006 BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
10007 BUG_ON(!net);
10008
10009 ret = ethtool_check_ops(dev->ethtool_ops);
10010 if (ret)
10011 return ret;
10012
10013 spin_lock_init(&dev->addr_list_lock);
10014 netdev_set_addr_lockdep_class(dev);
10015
10016 ret = dev_get_valid_name(net, dev, dev->name);
10017 if (ret < 0)
10018 goto out;
10019
10020 ret = -ENOMEM;
10021 dev->name_node = netdev_name_node_head_alloc(dev);
10022 if (!dev->name_node)
10023 goto out;
10024
10025 /* Init, if this function is available */
10026 if (dev->netdev_ops->ndo_init) {
10027 ret = dev->netdev_ops->ndo_init(dev);
10028 if (ret) {
10029 if (ret > 0)
10030 ret = -EIO;
10031 goto err_free_name;
10032 }
10033 }
10034
10035 if (((dev->hw_features | dev->features) &
10036 NETIF_F_HW_VLAN_CTAG_FILTER) &&
10037 (!dev->netdev_ops->ndo_vlan_rx_add_vid ||
10038 !dev->netdev_ops->ndo_vlan_rx_kill_vid)) {
10039 netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n");
10040 ret = -EINVAL;
10041 goto err_uninit;
10042 }
10043
10044 ret = -EBUSY;
10045 if (!dev->ifindex)
10046 dev->ifindex = dev_new_index(net);
10047 else if (__dev_get_by_index(net, dev->ifindex))
10048 goto err_uninit;
10049
10050 /* Transfer changeable features to wanted_features and enable
10051 * software offloads (GSO and GRO).
10052 */
10053 dev->hw_features |= (NETIF_F_SOFT_FEATURES | NETIF_F_SOFT_FEATURES_OFF);
10054 dev->features |= NETIF_F_SOFT_FEATURES;
10055
10056 if (dev->netdev_ops->ndo_udp_tunnel_add) {
10057 dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT;
10058 dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT;
10059 }
10060
10061 dev->wanted_features = dev->features & dev->hw_features;
10062
10063 if (!(dev->flags & IFF_LOOPBACK))
10064 dev->hw_features |= NETIF_F_NOCACHE_COPY;
10065
10066 /* If IPv4 TCP segmentation offload is supported we should also
10067 * allow the device to enable segmenting the frame with the option
10068 * of ignoring a static IP ID value. This doesn't enable the
10069 * feature itself but allows the user to enable it later.
10070 */
10071 if (dev->hw_features & NETIF_F_TSO)
10072 dev->hw_features |= NETIF_F_TSO_MANGLEID;
10073 if (dev->vlan_features & NETIF_F_TSO)
10074 dev->vlan_features |= NETIF_F_TSO_MANGLEID;
10075 if (dev->mpls_features & NETIF_F_TSO)
10076 dev->mpls_features |= NETIF_F_TSO_MANGLEID;
10077 if (dev->hw_enc_features & NETIF_F_TSO)
10078 dev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
10079
10080 /* Make NETIF_F_HIGHDMA inheritable to VLAN devices.
10081 */
10082 dev->vlan_features |= NETIF_F_HIGHDMA;
10083
10084 /* Make NETIF_F_SG inheritable to tunnel devices.
10085 */
10086 dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL;
10087
10088 /* Make NETIF_F_SG inheritable to MPLS.
10089 */
10090 dev->mpls_features |= NETIF_F_SG;
10091
10092 ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev);
10093 ret = notifier_to_errno(ret);
10094 if (ret)
10095 goto err_uninit;
10096
10097 ret = netdev_register_kobject(dev);
10098 if (ret) {
10099 dev->reg_state = NETREG_UNREGISTERED;
10100 goto err_uninit;
10101 }
10102 dev->reg_state = NETREG_REGISTERED;
10103
10104 __netdev_update_features(dev);
10105
10106 /*
10107 * Default initial state at registry is that the
10108 * device is present.
10109 */
10110
10111 set_bit(__LINK_STATE_PRESENT, &dev->state);
10112
10113 linkwatch_init_dev(dev);
10114
10115 dev_init_scheduler(dev);
10116 dev_hold(dev);
10117 list_netdevice(dev);
10118 add_device_randomness(dev->dev_addr, dev->addr_len);
10119
10120 /* If the device has permanent device address, driver should
10121 * set dev_addr and also addr_assign_type should be set to
10122 * NET_ADDR_PERM (default value).
10123 */
10124 if (dev->addr_assign_type == NET_ADDR_PERM)
10125 memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
10126
10127 /* Notify protocols, that a new device appeared. */
10128 ret = call_netdevice_notifiers(NETDEV_REGISTER, dev);
10129 ret = notifier_to_errno(ret);
10130 if (ret) {
10131 /* Expect explicit free_netdev() on failure */
10132 dev->needs_free_netdev = false;
10133 rollback_registered(dev);
10134 net_set_todo(dev);
10135 goto out;
10136 }
10137 /*
10138 * Prevent userspace races by waiting until the network
10139 * device is fully setup before sending notifications.
10140 */
10141 if (!dev->rtnl_link_ops ||
10142 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
10143 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL);
10144
10145 out:
10146 return ret;
10147
10148 err_uninit:
10149 if (dev->netdev_ops->ndo_uninit)
10150 dev->netdev_ops->ndo_uninit(dev);
10151 if (dev->priv_destructor)
10152 dev->priv_destructor(dev);
10153 err_free_name:
10154 netdev_name_node_free(dev->name_node);
10155 goto out;
10156 }
10157 EXPORT_SYMBOL(register_netdevice);
10158
10159 /**
10160 * init_dummy_netdev - init a dummy network device for NAPI
10161 * @dev: device to init
10162 *
10163 * This takes a network device structure and initialize the minimum
10164 * amount of fields so it can be used to schedule NAPI polls without
10165 * registering a full blown interface. This is to be used by drivers
10166 * that need to tie several hardware interfaces to a single NAPI
10167 * poll scheduler due to HW limitations.
10168 */
init_dummy_netdev(struct net_device * dev)10169 int init_dummy_netdev(struct net_device *dev)
10170 {
10171 /* Clear everything. Note we don't initialize spinlocks
10172 * are they aren't supposed to be taken by any of the
10173 * NAPI code and this dummy netdev is supposed to be
10174 * only ever used for NAPI polls
10175 */
10176 memset(dev, 0, sizeof(struct net_device));
10177
10178 /* make sure we BUG if trying to hit standard
10179 * register/unregister code path
10180 */
10181 dev->reg_state = NETREG_DUMMY;
10182
10183 /* NAPI wants this */
10184 INIT_LIST_HEAD(&dev->napi_list);
10185
10186 /* a dummy interface is started by default */
10187 set_bit(__LINK_STATE_PRESENT, &dev->state);
10188 set_bit(__LINK_STATE_START, &dev->state);
10189
10190 /* napi_busy_loop stats accounting wants this */
10191 dev_net_set(dev, &init_net);
10192
10193 /* Note : We dont allocate pcpu_refcnt for dummy devices,
10194 * because users of this 'device' dont need to change
10195 * its refcount.
10196 */
10197
10198 return 0;
10199 }
10200 EXPORT_SYMBOL_GPL(init_dummy_netdev);
10201
10202
10203 /**
10204 * register_netdev - register a network device
10205 * @dev: device to register
10206 *
10207 * Take a completed network device structure and add it to the kernel
10208 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
10209 * chain. 0 is returned on success. A negative errno code is returned
10210 * on a failure to set up the device, or if the name is a duplicate.
10211 *
10212 * This is a wrapper around register_netdevice that takes the rtnl semaphore
10213 * and expands the device name if you passed a format string to
10214 * alloc_netdev.
10215 */
register_netdev(struct net_device * dev)10216 int register_netdev(struct net_device *dev)
10217 {
10218 int err;
10219
10220 if (rtnl_lock_killable())
10221 return -EINTR;
10222 err = register_netdevice(dev);
10223 rtnl_unlock();
10224 return err;
10225 }
10226 EXPORT_SYMBOL(register_netdev);
10227
netdev_refcnt_read(const struct net_device * dev)10228 int netdev_refcnt_read(const struct net_device *dev)
10229 {
10230 int i, refcnt = 0;
10231
10232 for_each_possible_cpu(i)
10233 refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i);
10234 return refcnt;
10235 }
10236 EXPORT_SYMBOL(netdev_refcnt_read);
10237
10238 #define WAIT_REFS_MIN_MSECS 1
10239 #define WAIT_REFS_MAX_MSECS 250
10240 /**
10241 * netdev_wait_allrefs - wait until all references are gone.
10242 * @dev: target net_device
10243 *
10244 * This is called when unregistering network devices.
10245 *
10246 * Any protocol or device that holds a reference should register
10247 * for netdevice notification, and cleanup and put back the
10248 * reference if they receive an UNREGISTER event.
10249 * We can get stuck here if buggy protocols don't correctly
10250 * call dev_put.
10251 */
netdev_wait_allrefs(struct net_device * dev)10252 static void netdev_wait_allrefs(struct net_device *dev)
10253 {
10254 unsigned long rebroadcast_time, warning_time;
10255 int wait = 0, refcnt;
10256
10257 linkwatch_forget_dev(dev);
10258
10259 rebroadcast_time = warning_time = jiffies;
10260 refcnt = netdev_refcnt_read(dev);
10261
10262 while (refcnt != 0) {
10263 if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
10264 rtnl_lock();
10265
10266 /* Rebroadcast unregister notification */
10267 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10268
10269 __rtnl_unlock();
10270 rcu_barrier();
10271 rtnl_lock();
10272
10273 if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
10274 &dev->state)) {
10275 /* We must not have linkwatch events
10276 * pending on unregister. If this
10277 * happens, we simply run the queue
10278 * unscheduled, resulting in a noop
10279 * for this device.
10280 */
10281 linkwatch_run_queue();
10282 }
10283
10284 __rtnl_unlock();
10285
10286 rebroadcast_time = jiffies;
10287 }
10288
10289 if (!wait) {
10290 rcu_barrier();
10291 wait = WAIT_REFS_MIN_MSECS;
10292 } else {
10293 msleep(wait);
10294 wait = min(wait << 1, WAIT_REFS_MAX_MSECS);
10295 }
10296
10297 refcnt = netdev_refcnt_read(dev);
10298
10299 if (refcnt && time_after(jiffies, warning_time + 10 * HZ)) {
10300 pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n",
10301 dev->name, refcnt);
10302 warning_time = jiffies;
10303 }
10304 }
10305 }
10306
10307 /* The sequence is:
10308 *
10309 * rtnl_lock();
10310 * ...
10311 * register_netdevice(x1);
10312 * register_netdevice(x2);
10313 * ...
10314 * unregister_netdevice(y1);
10315 * unregister_netdevice(y2);
10316 * ...
10317 * rtnl_unlock();
10318 * free_netdev(y1);
10319 * free_netdev(y2);
10320 *
10321 * We are invoked by rtnl_unlock().
10322 * This allows us to deal with problems:
10323 * 1) We can delete sysfs objects which invoke hotplug
10324 * without deadlocking with linkwatch via keventd.
10325 * 2) Since we run with the RTNL semaphore not held, we can sleep
10326 * safely in order to wait for the netdev refcnt to drop to zero.
10327 *
10328 * We must not return until all unregister events added during
10329 * the interval the lock was held have been completed.
10330 */
netdev_run_todo(void)10331 void netdev_run_todo(void)
10332 {
10333 struct list_head list;
10334 #ifdef CONFIG_LOCKDEP
10335 struct list_head unlink_list;
10336
10337 list_replace_init(&net_unlink_list, &unlink_list);
10338
10339 while (!list_empty(&unlink_list)) {
10340 struct net_device *dev = list_first_entry(&unlink_list,
10341 struct net_device,
10342 unlink_list);
10343 list_del_init(&dev->unlink_list);
10344 dev->nested_level = dev->lower_level - 1;
10345 }
10346 #endif
10347
10348 /* Snapshot list, allow later requests */
10349 list_replace_init(&net_todo_list, &list);
10350
10351 __rtnl_unlock();
10352
10353
10354 /* Wait for rcu callbacks to finish before next phase */
10355 if (!list_empty(&list))
10356 rcu_barrier();
10357
10358 while (!list_empty(&list)) {
10359 struct net_device *dev
10360 = list_first_entry(&list, struct net_device, todo_list);
10361 list_del(&dev->todo_list);
10362
10363 if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) {
10364 pr_err("network todo '%s' but state %d\n",
10365 dev->name, dev->reg_state);
10366 dump_stack();
10367 continue;
10368 }
10369
10370 dev->reg_state = NETREG_UNREGISTERED;
10371
10372 netdev_wait_allrefs(dev);
10373
10374 /* paranoia */
10375 BUG_ON(netdev_refcnt_read(dev));
10376 BUG_ON(!list_empty(&dev->ptype_all));
10377 BUG_ON(!list_empty(&dev->ptype_specific));
10378 WARN_ON(rcu_access_pointer(dev->ip_ptr));
10379 WARN_ON(rcu_access_pointer(dev->ip6_ptr));
10380 #if IS_ENABLED(CONFIG_DECNET)
10381 WARN_ON(dev->dn_ptr);
10382 #endif
10383 if (dev->priv_destructor)
10384 dev->priv_destructor(dev);
10385 if (dev->needs_free_netdev)
10386 free_netdev(dev);
10387
10388 /* Report a network device has been unregistered */
10389 rtnl_lock();
10390 dev_net(dev)->dev_unreg_count--;
10391 __rtnl_unlock();
10392 wake_up(&netdev_unregistering_wq);
10393
10394 /* Free network device */
10395 kobject_put(&dev->dev.kobj);
10396 }
10397 }
10398
10399 /* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has
10400 * all the same fields in the same order as net_device_stats, with only
10401 * the type differing, but rtnl_link_stats64 may have additional fields
10402 * at the end for newer counters.
10403 */
netdev_stats_to_stats64(struct rtnl_link_stats64 * stats64,const struct net_device_stats * netdev_stats)10404 void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64,
10405 const struct net_device_stats *netdev_stats)
10406 {
10407 #if BITS_PER_LONG == 64
10408 BUILD_BUG_ON(sizeof(*stats64) < sizeof(*netdev_stats));
10409 memcpy(stats64, netdev_stats, sizeof(*netdev_stats));
10410 /* zero out counters that only exist in rtnl_link_stats64 */
10411 memset((char *)stats64 + sizeof(*netdev_stats), 0,
10412 sizeof(*stats64) - sizeof(*netdev_stats));
10413 #else
10414 size_t i, n = sizeof(*netdev_stats) / sizeof(unsigned long);
10415 const unsigned long *src = (const unsigned long *)netdev_stats;
10416 u64 *dst = (u64 *)stats64;
10417
10418 BUILD_BUG_ON(n > sizeof(*stats64) / sizeof(u64));
10419 for (i = 0; i < n; i++)
10420 dst[i] = src[i];
10421 /* zero out counters that only exist in rtnl_link_stats64 */
10422 memset((char *)stats64 + n * sizeof(u64), 0,
10423 sizeof(*stats64) - n * sizeof(u64));
10424 #endif
10425 }
10426 EXPORT_SYMBOL(netdev_stats_to_stats64);
10427
10428 /**
10429 * dev_get_stats - get network device statistics
10430 * @dev: device to get statistics from
10431 * @storage: place to store stats
10432 *
10433 * Get network statistics from device. Return @storage.
10434 * The device driver may provide its own method by setting
10435 * dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats;
10436 * otherwise the internal statistics structure is used.
10437 */
dev_get_stats(struct net_device * dev,struct rtnl_link_stats64 * storage)10438 struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev,
10439 struct rtnl_link_stats64 *storage)
10440 {
10441 const struct net_device_ops *ops = dev->netdev_ops;
10442
10443 if (ops->ndo_get_stats64) {
10444 memset(storage, 0, sizeof(*storage));
10445 ops->ndo_get_stats64(dev, storage);
10446 } else if (ops->ndo_get_stats) {
10447 netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev));
10448 } else {
10449 netdev_stats_to_stats64(storage, &dev->stats);
10450 }
10451 storage->rx_dropped += (unsigned long)atomic_long_read(&dev->rx_dropped);
10452 storage->tx_dropped += (unsigned long)atomic_long_read(&dev->tx_dropped);
10453 storage->rx_nohandler += (unsigned long)atomic_long_read(&dev->rx_nohandler);
10454 return storage;
10455 }
10456 EXPORT_SYMBOL(dev_get_stats);
10457
10458 /**
10459 * dev_fetch_sw_netstats - get per-cpu network device statistics
10460 * @s: place to store stats
10461 * @netstats: per-cpu network stats to read from
10462 *
10463 * Read per-cpu network statistics and populate the related fields in @s.
10464 */
dev_fetch_sw_netstats(struct rtnl_link_stats64 * s,const struct pcpu_sw_netstats __percpu * netstats)10465 void dev_fetch_sw_netstats(struct rtnl_link_stats64 *s,
10466 const struct pcpu_sw_netstats __percpu *netstats)
10467 {
10468 int cpu;
10469
10470 for_each_possible_cpu(cpu) {
10471 const struct pcpu_sw_netstats *stats;
10472 struct pcpu_sw_netstats tmp;
10473 unsigned int start;
10474
10475 stats = per_cpu_ptr(netstats, cpu);
10476 do {
10477 start = u64_stats_fetch_begin_irq(&stats->syncp);
10478 tmp.rx_packets = stats->rx_packets;
10479 tmp.rx_bytes = stats->rx_bytes;
10480 tmp.tx_packets = stats->tx_packets;
10481 tmp.tx_bytes = stats->tx_bytes;
10482 } while (u64_stats_fetch_retry_irq(&stats->syncp, start));
10483
10484 s->rx_packets += tmp.rx_packets;
10485 s->rx_bytes += tmp.rx_bytes;
10486 s->tx_packets += tmp.tx_packets;
10487 s->tx_bytes += tmp.tx_bytes;
10488 }
10489 }
10490 EXPORT_SYMBOL_GPL(dev_fetch_sw_netstats);
10491
dev_ingress_queue_create(struct net_device * dev)10492 struct netdev_queue *dev_ingress_queue_create(struct net_device *dev)
10493 {
10494 struct netdev_queue *queue = dev_ingress_queue(dev);
10495
10496 #ifdef CONFIG_NET_CLS_ACT
10497 if (queue)
10498 return queue;
10499 queue = kzalloc(sizeof(*queue), GFP_KERNEL);
10500 if (!queue)
10501 return NULL;
10502 netdev_init_one_queue(dev, queue, NULL);
10503 RCU_INIT_POINTER(queue->qdisc, &noop_qdisc);
10504 queue->qdisc_sleeping = &noop_qdisc;
10505 rcu_assign_pointer(dev->ingress_queue, queue);
10506 #endif
10507 return queue;
10508 }
10509
10510 static const struct ethtool_ops default_ethtool_ops;
10511
netdev_set_default_ethtool_ops(struct net_device * dev,const struct ethtool_ops * ops)10512 void netdev_set_default_ethtool_ops(struct net_device *dev,
10513 const struct ethtool_ops *ops)
10514 {
10515 if (dev->ethtool_ops == &default_ethtool_ops)
10516 dev->ethtool_ops = ops;
10517 }
10518 EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops);
10519
netdev_freemem(struct net_device * dev)10520 void netdev_freemem(struct net_device *dev)
10521 {
10522 char *addr = (char *)dev - dev->padded;
10523
10524 kvfree(addr);
10525 }
10526
10527 /**
10528 * alloc_netdev_mqs - allocate network device
10529 * @sizeof_priv: size of private data to allocate space for
10530 * @name: device name format string
10531 * @name_assign_type: origin of device name
10532 * @setup: callback to initialize device
10533 * @txqs: the number of TX subqueues to allocate
10534 * @rxqs: the number of RX subqueues to allocate
10535 *
10536 * Allocates a struct net_device with private data area for driver use
10537 * and performs basic initialization. Also allocates subqueue structs
10538 * for each queue on the device.
10539 */
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)10540 struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name,
10541 unsigned char name_assign_type,
10542 void (*setup)(struct net_device *),
10543 unsigned int txqs, unsigned int rxqs)
10544 {
10545 struct net_device *dev;
10546 unsigned int alloc_size;
10547 struct net_device *p;
10548
10549 BUG_ON(strlen(name) >= sizeof(dev->name));
10550
10551 if (txqs < 1) {
10552 pr_err("alloc_netdev: Unable to allocate device with zero queues\n");
10553 return NULL;
10554 }
10555
10556 if (rxqs < 1) {
10557 pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n");
10558 return NULL;
10559 }
10560
10561 alloc_size = sizeof(struct net_device);
10562 if (sizeof_priv) {
10563 /* ensure 32-byte alignment of private area */
10564 alloc_size = ALIGN(alloc_size, NETDEV_ALIGN);
10565 alloc_size += sizeof_priv;
10566 }
10567 /* ensure 32-byte alignment of whole construct */
10568 alloc_size += NETDEV_ALIGN - 1;
10569
10570 p = kvzalloc(alloc_size, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
10571 if (!p)
10572 return NULL;
10573
10574 dev = PTR_ALIGN(p, NETDEV_ALIGN);
10575 dev->padded = (char *)dev - (char *)p;
10576
10577 dev->pcpu_refcnt = alloc_percpu(int);
10578 if (!dev->pcpu_refcnt)
10579 goto free_dev;
10580
10581 if (dev_addr_init(dev))
10582 goto free_pcpu;
10583
10584 dev_mc_init(dev);
10585 dev_uc_init(dev);
10586
10587 dev_net_set(dev, &init_net);
10588
10589 dev->gso_max_size = GSO_MAX_SIZE;
10590 dev->gso_max_segs = GSO_MAX_SEGS;
10591 dev->upper_level = 1;
10592 dev->lower_level = 1;
10593 #ifdef CONFIG_LOCKDEP
10594 dev->nested_level = 0;
10595 INIT_LIST_HEAD(&dev->unlink_list);
10596 #endif
10597
10598 INIT_LIST_HEAD(&dev->napi_list);
10599 INIT_LIST_HEAD(&dev->unreg_list);
10600 INIT_LIST_HEAD(&dev->close_list);
10601 INIT_LIST_HEAD(&dev->link_watch_list);
10602 INIT_LIST_HEAD(&dev->adj_list.upper);
10603 INIT_LIST_HEAD(&dev->adj_list.lower);
10604 INIT_LIST_HEAD(&dev->ptype_all);
10605 INIT_LIST_HEAD(&dev->ptype_specific);
10606 INIT_LIST_HEAD(&dev->net_notifier_list);
10607 #ifdef CONFIG_NET_SCHED
10608 hash_init(dev->qdisc_hash);
10609 #endif
10610 dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM;
10611 setup(dev);
10612
10613 if (!dev->tx_queue_len) {
10614 dev->priv_flags |= IFF_NO_QUEUE;
10615 dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN;
10616 }
10617
10618 dev->num_tx_queues = txqs;
10619 dev->real_num_tx_queues = txqs;
10620 if (netif_alloc_netdev_queues(dev))
10621 goto free_all;
10622
10623 dev->num_rx_queues = rxqs;
10624 dev->real_num_rx_queues = rxqs;
10625 if (netif_alloc_rx_queues(dev))
10626 goto free_all;
10627
10628 strcpy(dev->name, name);
10629 dev->name_assign_type = name_assign_type;
10630 dev->group = INIT_NETDEV_GROUP;
10631 if (!dev->ethtool_ops)
10632 dev->ethtool_ops = &default_ethtool_ops;
10633
10634 nf_hook_ingress_init(dev);
10635
10636 return dev;
10637
10638 free_all:
10639 free_netdev(dev);
10640 return NULL;
10641
10642 free_pcpu:
10643 free_percpu(dev->pcpu_refcnt);
10644 free_dev:
10645 netdev_freemem(dev);
10646 return NULL;
10647 }
10648 EXPORT_SYMBOL(alloc_netdev_mqs);
10649
10650 /**
10651 * free_netdev - free network device
10652 * @dev: device
10653 *
10654 * This function does the last stage of destroying an allocated device
10655 * interface. The reference to the device object is released. If this
10656 * is the last reference then it will be freed.Must be called in process
10657 * context.
10658 */
free_netdev(struct net_device * dev)10659 void free_netdev(struct net_device *dev)
10660 {
10661 struct napi_struct *p, *n;
10662
10663 might_sleep();
10664
10665 /* When called immediately after register_netdevice() failed the unwind
10666 * handling may still be dismantling the device. Handle that case by
10667 * deferring the free.
10668 */
10669 if (dev->reg_state == NETREG_UNREGISTERING) {
10670 ASSERT_RTNL();
10671 dev->needs_free_netdev = true;
10672 return;
10673 }
10674
10675 netif_free_tx_queues(dev);
10676 netif_free_rx_queues(dev);
10677
10678 kfree(rcu_dereference_protected(dev->ingress_queue, 1));
10679
10680 /* Flush device addresses */
10681 dev_addr_flush(dev);
10682
10683 list_for_each_entry_safe(p, n, &dev->napi_list, dev_list)
10684 netif_napi_del(p);
10685
10686 free_percpu(dev->pcpu_refcnt);
10687 dev->pcpu_refcnt = NULL;
10688 free_percpu(dev->xdp_bulkq);
10689 dev->xdp_bulkq = NULL;
10690
10691 /* Compatibility with error handling in drivers */
10692 if (dev->reg_state == NETREG_UNINITIALIZED) {
10693 netdev_freemem(dev);
10694 return;
10695 }
10696
10697 BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
10698 dev->reg_state = NETREG_RELEASED;
10699
10700 /* will free via device release */
10701 put_device(&dev->dev);
10702 }
10703 EXPORT_SYMBOL(free_netdev);
10704
10705 /**
10706 * synchronize_net - Synchronize with packet receive processing
10707 *
10708 * Wait for packets currently being received to be done.
10709 * Does not block later packets from starting.
10710 */
synchronize_net(void)10711 void synchronize_net(void)
10712 {
10713 might_sleep();
10714 if (rtnl_is_locked())
10715 synchronize_rcu_expedited();
10716 else
10717 synchronize_rcu();
10718 }
10719 EXPORT_SYMBOL(synchronize_net);
10720
10721 /**
10722 * unregister_netdevice_queue - remove device from the kernel
10723 * @dev: device
10724 * @head: list
10725 *
10726 * This function shuts down a device interface and removes it
10727 * from the kernel tables.
10728 * If head not NULL, device is queued to be unregistered later.
10729 *
10730 * Callers must hold the rtnl semaphore. You may want
10731 * unregister_netdev() instead of this.
10732 */
10733
unregister_netdevice_queue(struct net_device * dev,struct list_head * head)10734 void unregister_netdevice_queue(struct net_device *dev, struct list_head *head)
10735 {
10736 ASSERT_RTNL();
10737
10738 if (head) {
10739 list_move_tail(&dev->unreg_list, head);
10740 } else {
10741 rollback_registered(dev);
10742 /* Finish processing unregister after unlock */
10743 net_set_todo(dev);
10744 }
10745 }
10746 EXPORT_SYMBOL(unregister_netdevice_queue);
10747
10748 /**
10749 * unregister_netdevice_many - unregister many devices
10750 * @head: list of devices
10751 *
10752 * Note: As most callers use a stack allocated list_head,
10753 * we force a list_del() to make sure stack wont be corrupted later.
10754 */
unregister_netdevice_many(struct list_head * head)10755 void unregister_netdevice_many(struct list_head *head)
10756 {
10757 struct net_device *dev;
10758
10759 if (!list_empty(head)) {
10760 rollback_registered_many(head);
10761 list_for_each_entry(dev, head, unreg_list)
10762 net_set_todo(dev);
10763 list_del(head);
10764 }
10765 }
10766 EXPORT_SYMBOL(unregister_netdevice_many);
10767
10768 /**
10769 * unregister_netdev - remove device from the kernel
10770 * @dev: device
10771 *
10772 * This function shuts down a device interface and removes it
10773 * from the kernel tables.
10774 *
10775 * This is just a wrapper for unregister_netdevice that takes
10776 * the rtnl semaphore. In general you want to use this and not
10777 * unregister_netdevice.
10778 */
unregister_netdev(struct net_device * dev)10779 void unregister_netdev(struct net_device *dev)
10780 {
10781 rtnl_lock();
10782 unregister_netdevice(dev);
10783 rtnl_unlock();
10784 }
10785 EXPORT_SYMBOL(unregister_netdev);
10786
10787 /**
10788 * dev_change_net_namespace - move device to different nethost namespace
10789 * @dev: device
10790 * @net: network namespace
10791 * @pat: If not NULL name pattern to try if the current device name
10792 * is already taken in the destination network namespace.
10793 *
10794 * This function shuts down a device interface and moves it
10795 * to a new network namespace. On success 0 is returned, on
10796 * a failure a netagive errno code is returned.
10797 *
10798 * Callers must hold the rtnl semaphore.
10799 */
10800
dev_change_net_namespace(struct net_device * dev,struct net * net,const char * pat)10801 int dev_change_net_namespace(struct net_device *dev, struct net *net, const char *pat)
10802 {
10803 struct net *net_old = dev_net(dev);
10804 int err, new_nsid, new_ifindex;
10805
10806 ASSERT_RTNL();
10807
10808 /* Don't allow namespace local devices to be moved. */
10809 err = -EINVAL;
10810 if (dev->features & NETIF_F_NETNS_LOCAL)
10811 goto out;
10812
10813 /* Ensure the device has been registrered */
10814 if (dev->reg_state != NETREG_REGISTERED)
10815 goto out;
10816
10817 /* Get out if there is nothing todo */
10818 err = 0;
10819 if (net_eq(net_old, net))
10820 goto out;
10821
10822 /* Pick the destination device name, and ensure
10823 * we can use it in the destination network namespace.
10824 */
10825 err = -EEXIST;
10826 if (__dev_get_by_name(net, dev->name)) {
10827 /* We get here if we can't use the current device name */
10828 if (!pat)
10829 goto out;
10830 err = dev_get_valid_name(net, dev, pat);
10831 if (err < 0)
10832 goto out;
10833 }
10834
10835 /*
10836 * And now a mini version of register_netdevice unregister_netdevice.
10837 */
10838
10839 /* If device is running close it first. */
10840 dev_close(dev);
10841
10842 /* And unlink it from device chain */
10843 unlist_netdevice(dev);
10844
10845 synchronize_net();
10846
10847 /* Shutdown queueing discipline. */
10848 dev_shutdown(dev);
10849
10850 /* Notify protocols, that we are about to destroy
10851 * this device. They should clean all the things.
10852 *
10853 * Note that dev->reg_state stays at NETREG_REGISTERED.
10854 * This is wanted because this way 8021q and macvlan know
10855 * the device is just moving and can keep their slaves up.
10856 */
10857 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10858 rcu_barrier();
10859
10860 new_nsid = peernet2id_alloc(dev_net(dev), net, GFP_KERNEL);
10861 /* If there is an ifindex conflict assign a new one */
10862 if (__dev_get_by_index(net, dev->ifindex))
10863 new_ifindex = dev_new_index(net);
10864 else
10865 new_ifindex = dev->ifindex;
10866
10867 rtmsg_ifinfo_newnet(RTM_DELLINK, dev, ~0U, GFP_KERNEL, &new_nsid,
10868 new_ifindex);
10869
10870 /*
10871 * Flush the unicast and multicast chains
10872 */
10873 dev_uc_flush(dev);
10874 dev_mc_flush(dev);
10875
10876 /* Send a netdev-removed uevent to the old namespace */
10877 kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE);
10878 netdev_adjacent_del_links(dev);
10879
10880 /* Move per-net netdevice notifiers that are following the netdevice */
10881 move_netdevice_notifiers_dev_net(dev, net);
10882
10883 /* Actually switch the network namespace */
10884 dev_net_set(dev, net);
10885 dev->ifindex = new_ifindex;
10886
10887 /* Send a netdev-add uevent to the new namespace */
10888 kobject_uevent(&dev->dev.kobj, KOBJ_ADD);
10889 netdev_adjacent_add_links(dev);
10890
10891 /* Fixup kobjects */
10892 err = device_rename(&dev->dev, dev->name);
10893 WARN_ON(err);
10894
10895 /* Adapt owner in case owning user namespace of target network
10896 * namespace is different from the original one.
10897 */
10898 err = netdev_change_owner(dev, net_old, net);
10899 WARN_ON(err);
10900
10901 /* Add the device back in the hashes */
10902 list_netdevice(dev);
10903
10904 /* Notify protocols, that a new device appeared. */
10905 call_netdevice_notifiers(NETDEV_REGISTER, dev);
10906
10907 /*
10908 * Prevent userspace races by waiting until the network
10909 * device is fully setup before sending notifications.
10910 */
10911 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL);
10912
10913 synchronize_net();
10914 err = 0;
10915 out:
10916 return err;
10917 }
10918 EXPORT_SYMBOL_GPL(dev_change_net_namespace);
10919
dev_cpu_dead(unsigned int oldcpu)10920 static int dev_cpu_dead(unsigned int oldcpu)
10921 {
10922 struct sk_buff **list_skb;
10923 struct sk_buff *skb;
10924 unsigned int cpu;
10925 struct softnet_data *sd, *oldsd, *remsd = NULL;
10926
10927 local_irq_disable();
10928 cpu = smp_processor_id();
10929 sd = &per_cpu(softnet_data, cpu);
10930 oldsd = &per_cpu(softnet_data, oldcpu);
10931
10932 /* Find end of our completion_queue. */
10933 list_skb = &sd->completion_queue;
10934 while (*list_skb)
10935 list_skb = &(*list_skb)->next;
10936 /* Append completion queue from offline CPU. */
10937 *list_skb = oldsd->completion_queue;
10938 oldsd->completion_queue = NULL;
10939
10940 /* Append output queue from offline CPU. */
10941 if (oldsd->output_queue) {
10942 *sd->output_queue_tailp = oldsd->output_queue;
10943 sd->output_queue_tailp = oldsd->output_queue_tailp;
10944 oldsd->output_queue = NULL;
10945 oldsd->output_queue_tailp = &oldsd->output_queue;
10946 }
10947 /* Append NAPI poll list from offline CPU, with one exception :
10948 * process_backlog() must be called by cpu owning percpu backlog.
10949 * We properly handle process_queue & input_pkt_queue later.
10950 */
10951 while (!list_empty(&oldsd->poll_list)) {
10952 struct napi_struct *napi = list_first_entry(&oldsd->poll_list,
10953 struct napi_struct,
10954 poll_list);
10955
10956 list_del_init(&napi->poll_list);
10957 if (napi->poll == process_backlog)
10958 napi->state = 0;
10959 else
10960 ____napi_schedule(sd, napi);
10961 }
10962
10963 raise_softirq_irqoff(NET_TX_SOFTIRQ);
10964 local_irq_enable();
10965
10966 #ifdef CONFIG_RPS
10967 remsd = oldsd->rps_ipi_list;
10968 oldsd->rps_ipi_list = NULL;
10969 #endif
10970 /* send out pending IPI's on offline CPU */
10971 net_rps_send_ipi(remsd);
10972
10973 /* Process offline CPU's input_pkt_queue */
10974 while ((skb = __skb_dequeue(&oldsd->process_queue))) {
10975 netif_rx_ni(skb);
10976 input_queue_head_incr(oldsd);
10977 }
10978 while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) {
10979 netif_rx_ni(skb);
10980 input_queue_head_incr(oldsd);
10981 }
10982
10983 return 0;
10984 }
10985
10986 /**
10987 * netdev_increment_features - increment feature set by one
10988 * @all: current feature set
10989 * @one: new feature set
10990 * @mask: mask feature set
10991 *
10992 * Computes a new feature set after adding a device with feature set
10993 * @one to the master device with current feature set @all. Will not
10994 * enable anything that is off in @mask. Returns the new feature set.
10995 */
netdev_increment_features(netdev_features_t all,netdev_features_t one,netdev_features_t mask)10996 netdev_features_t netdev_increment_features(netdev_features_t all,
10997 netdev_features_t one, netdev_features_t mask)
10998 {
10999 if (mask & NETIF_F_HW_CSUM)
11000 mask |= NETIF_F_CSUM_MASK;
11001 mask |= NETIF_F_VLAN_CHALLENGED;
11002
11003 all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask;
11004 all &= one | ~NETIF_F_ALL_FOR_ALL;
11005
11006 /* If one device supports hw checksumming, set for all. */
11007 if (all & NETIF_F_HW_CSUM)
11008 all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM);
11009
11010 return all;
11011 }
11012 EXPORT_SYMBOL(netdev_increment_features);
11013
netdev_create_hash(void)11014 static struct hlist_head * __net_init netdev_create_hash(void)
11015 {
11016 int i;
11017 struct hlist_head *hash;
11018
11019 hash = kmalloc_array(NETDEV_HASHENTRIES, sizeof(*hash), GFP_KERNEL);
11020 if (hash != NULL)
11021 for (i = 0; i < NETDEV_HASHENTRIES; i++)
11022 INIT_HLIST_HEAD(&hash[i]);
11023
11024 return hash;
11025 }
11026
11027 /* Initialize per network namespace state */
netdev_init(struct net * net)11028 static int __net_init netdev_init(struct net *net)
11029 {
11030 BUILD_BUG_ON(GRO_HASH_BUCKETS >
11031 8 * sizeof_field(struct napi_struct, gro_bitmask));
11032
11033 if (net != &init_net)
11034 INIT_LIST_HEAD(&net->dev_base_head);
11035
11036 net->dev_name_head = netdev_create_hash();
11037 if (net->dev_name_head == NULL)
11038 goto err_name;
11039
11040 net->dev_index_head = netdev_create_hash();
11041 if (net->dev_index_head == NULL)
11042 goto err_idx;
11043
11044 RAW_INIT_NOTIFIER_HEAD(&net->netdev_chain);
11045
11046 return 0;
11047
11048 err_idx:
11049 kfree(net->dev_name_head);
11050 err_name:
11051 return -ENOMEM;
11052 }
11053
11054 /**
11055 * netdev_drivername - network driver for the device
11056 * @dev: network device
11057 *
11058 * Determine network driver for device.
11059 */
netdev_drivername(const struct net_device * dev)11060 const char *netdev_drivername(const struct net_device *dev)
11061 {
11062 const struct device_driver *driver;
11063 const struct device *parent;
11064 const char *empty = "";
11065
11066 parent = dev->dev.parent;
11067 if (!parent)
11068 return empty;
11069
11070 driver = parent->driver;
11071 if (driver && driver->name)
11072 return driver->name;
11073 return empty;
11074 }
11075
__netdev_printk(const char * level,const struct net_device * dev,struct va_format * vaf)11076 static void __netdev_printk(const char *level, const struct net_device *dev,
11077 struct va_format *vaf)
11078 {
11079 if (dev && dev->dev.parent) {
11080 dev_printk_emit(level[1] - '0',
11081 dev->dev.parent,
11082 "%s %s %s%s: %pV",
11083 dev_driver_string(dev->dev.parent),
11084 dev_name(dev->dev.parent),
11085 netdev_name(dev), netdev_reg_state(dev),
11086 vaf);
11087 } else if (dev) {
11088 printk("%s%s%s: %pV",
11089 level, netdev_name(dev), netdev_reg_state(dev), vaf);
11090 } else {
11091 printk("%s(NULL net_device): %pV", level, vaf);
11092 }
11093 }
11094
netdev_printk(const char * level,const struct net_device * dev,const char * format,...)11095 void netdev_printk(const char *level, const struct net_device *dev,
11096 const char *format, ...)
11097 {
11098 struct va_format vaf;
11099 va_list args;
11100
11101 va_start(args, format);
11102
11103 vaf.fmt = format;
11104 vaf.va = &args;
11105
11106 __netdev_printk(level, dev, &vaf);
11107
11108 va_end(args);
11109 }
11110 EXPORT_SYMBOL(netdev_printk);
11111
11112 #define define_netdev_printk_level(func, level) \
11113 void func(const struct net_device *dev, const char *fmt, ...) \
11114 { \
11115 struct va_format vaf; \
11116 va_list args; \
11117 \
11118 va_start(args, fmt); \
11119 \
11120 vaf.fmt = fmt; \
11121 vaf.va = &args; \
11122 \
11123 __netdev_printk(level, dev, &vaf); \
11124 \
11125 va_end(args); \
11126 } \
11127 EXPORT_SYMBOL(func);
11128
11129 define_netdev_printk_level(netdev_emerg, KERN_EMERG);
11130 define_netdev_printk_level(netdev_alert, KERN_ALERT);
11131 define_netdev_printk_level(netdev_crit, KERN_CRIT);
11132 define_netdev_printk_level(netdev_err, KERN_ERR);
11133 define_netdev_printk_level(netdev_warn, KERN_WARNING);
11134 define_netdev_printk_level(netdev_notice, KERN_NOTICE);
11135 define_netdev_printk_level(netdev_info, KERN_INFO);
11136
netdev_exit(struct net * net)11137 static void __net_exit netdev_exit(struct net *net)
11138 {
11139 kfree(net->dev_name_head);
11140 kfree(net->dev_index_head);
11141 if (net != &init_net)
11142 WARN_ON_ONCE(!list_empty(&net->dev_base_head));
11143 }
11144
11145 static struct pernet_operations __net_initdata netdev_net_ops = {
11146 .init = netdev_init,
11147 .exit = netdev_exit,
11148 };
11149
default_device_exit(struct net * net)11150 static void __net_exit default_device_exit(struct net *net)
11151 {
11152 struct net_device *dev, *aux;
11153 /*
11154 * Push all migratable network devices back to the
11155 * initial network namespace
11156 */
11157 rtnl_lock();
11158 for_each_netdev_safe(net, dev, aux) {
11159 int err;
11160 char fb_name[IFNAMSIZ];
11161
11162 /* Ignore unmoveable devices (i.e. loopback) */
11163 if (dev->features & NETIF_F_NETNS_LOCAL)
11164 continue;
11165
11166 /* Leave virtual devices for the generic cleanup */
11167 if (dev->rtnl_link_ops && !dev->rtnl_link_ops->netns_refund)
11168 continue;
11169
11170 /* Push remaining network devices to init_net */
11171 snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex);
11172 if (__dev_get_by_name(&init_net, fb_name))
11173 snprintf(fb_name, IFNAMSIZ, "dev%%d");
11174 err = dev_change_net_namespace(dev, &init_net, fb_name);
11175 if (err) {
11176 pr_emerg("%s: failed to move %s to init_net: %d\n",
11177 __func__, dev->name, err);
11178 BUG();
11179 }
11180 }
11181 rtnl_unlock();
11182 }
11183
rtnl_lock_unregistering(struct list_head * net_list)11184 static void __net_exit rtnl_lock_unregistering(struct list_head *net_list)
11185 {
11186 /* Return with the rtnl_lock held when there are no network
11187 * devices unregistering in any network namespace in net_list.
11188 */
11189 struct net *net;
11190 bool unregistering;
11191 DEFINE_WAIT_FUNC(wait, woken_wake_function);
11192
11193 add_wait_queue(&netdev_unregistering_wq, &wait);
11194 for (;;) {
11195 unregistering = false;
11196 rtnl_lock();
11197 list_for_each_entry(net, net_list, exit_list) {
11198 if (net->dev_unreg_count > 0) {
11199 unregistering = true;
11200 break;
11201 }
11202 }
11203 if (!unregistering)
11204 break;
11205 __rtnl_unlock();
11206
11207 wait_woken(&wait, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
11208 }
11209 remove_wait_queue(&netdev_unregistering_wq, &wait);
11210 }
11211
default_device_exit_batch(struct list_head * net_list)11212 static void __net_exit default_device_exit_batch(struct list_head *net_list)
11213 {
11214 /* At exit all network devices most be removed from a network
11215 * namespace. Do this in the reverse order of registration.
11216 * Do this across as many network namespaces as possible to
11217 * improve batching efficiency.
11218 */
11219 struct net_device *dev;
11220 struct net *net;
11221 LIST_HEAD(dev_kill_list);
11222
11223 /* To prevent network device cleanup code from dereferencing
11224 * loopback devices or network devices that have been freed
11225 * wait here for all pending unregistrations to complete,
11226 * before unregistring the loopback device and allowing the
11227 * network namespace be freed.
11228 *
11229 * The netdev todo list containing all network devices
11230 * unregistrations that happen in default_device_exit_batch
11231 * will run in the rtnl_unlock() at the end of
11232 * default_device_exit_batch.
11233 */
11234 rtnl_lock_unregistering(net_list);
11235 list_for_each_entry(net, net_list, exit_list) {
11236 for_each_netdev_reverse(net, dev) {
11237 if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink)
11238 dev->rtnl_link_ops->dellink(dev, &dev_kill_list);
11239 else
11240 unregister_netdevice_queue(dev, &dev_kill_list);
11241 }
11242 }
11243 unregister_netdevice_many(&dev_kill_list);
11244 rtnl_unlock();
11245 }
11246
11247 static struct pernet_operations __net_initdata default_device_ops = {
11248 .exit = default_device_exit,
11249 .exit_batch = default_device_exit_batch,
11250 };
11251
11252 /*
11253 * Initialize the DEV module. At boot time this walks the device list and
11254 * unhooks any devices that fail to initialise (normally hardware not
11255 * present) and leaves us with a valid list of present and active devices.
11256 *
11257 */
11258
11259 /*
11260 * This is called single threaded during boot, so no need
11261 * to take the rtnl semaphore.
11262 */
net_dev_init(void)11263 static int __init net_dev_init(void)
11264 {
11265 int i, rc = -ENOMEM;
11266
11267 BUG_ON(!dev_boot_phase);
11268
11269 if (dev_proc_init())
11270 goto out;
11271
11272 if (netdev_kobject_init())
11273 goto out;
11274
11275 INIT_LIST_HEAD(&ptype_all);
11276 for (i = 0; i < PTYPE_HASH_SIZE; i++)
11277 INIT_LIST_HEAD(&ptype_base[i]);
11278
11279 INIT_LIST_HEAD(&offload_base);
11280
11281 if (register_pernet_subsys(&netdev_net_ops))
11282 goto out;
11283
11284 /*
11285 * Initialise the packet receive queues.
11286 */
11287
11288 for_each_possible_cpu(i) {
11289 struct work_struct *flush = per_cpu_ptr(&flush_works, i);
11290 struct softnet_data *sd = &per_cpu(softnet_data, i);
11291
11292 INIT_WORK(flush, flush_backlog);
11293
11294 skb_queue_head_init(&sd->input_pkt_queue);
11295 skb_queue_head_init(&sd->process_queue);
11296 #ifdef CONFIG_XFRM_OFFLOAD
11297 skb_queue_head_init(&sd->xfrm_backlog);
11298 #endif
11299 INIT_LIST_HEAD(&sd->poll_list);
11300 sd->output_queue_tailp = &sd->output_queue;
11301 #ifdef CONFIG_RPS
11302 sd->csd.func = rps_trigger_softirq;
11303 sd->csd.info = sd;
11304 sd->cpu = i;
11305 #endif
11306
11307 init_gro_hash(&sd->backlog);
11308 sd->backlog.poll = process_backlog;
11309 sd->backlog.weight = weight_p;
11310 }
11311
11312 dev_boot_phase = 0;
11313
11314 /* The loopback device is special if any other network devices
11315 * is present in a network namespace the loopback device must
11316 * be present. Since we now dynamically allocate and free the
11317 * loopback device ensure this invariant is maintained by
11318 * keeping the loopback device as the first device on the
11319 * list of network devices. Ensuring the loopback devices
11320 * is the first device that appears and the last network device
11321 * that disappears.
11322 */
11323 if (register_pernet_device(&loopback_net_ops))
11324 goto out;
11325
11326 if (register_pernet_device(&default_device_ops))
11327 goto out;
11328
11329 open_softirq(NET_TX_SOFTIRQ, net_tx_action);
11330 open_softirq(NET_RX_SOFTIRQ, net_rx_action);
11331
11332 rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead",
11333 NULL, dev_cpu_dead);
11334 WARN_ON(rc < 0);
11335 rc = 0;
11336 out:
11337 return rc;
11338 }
11339
11340 subsys_initcall(net_dev_init);
11341