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