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