]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blob - net/core/dev.c
UBUNTU: Ubuntu-4.15.0-96.97
[mirror_ubuntu-bionic-kernel.git] / net / core / dev.c
1 /*
2 * NET3 Protocol independent device support routines.
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version
7 * 2 of the License, or (at your option) any later version.
8 *
9 * Derived from the non IP parts of dev.c 1.0.19
10 * Authors: Ross Biro
11 * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
12 * Mark Evans, <evansmp@uhura.aston.ac.uk>
13 *
14 * Additional Authors:
15 * Florian la Roche <rzsfl@rz.uni-sb.de>
16 * Alan Cox <gw4pts@gw4pts.ampr.org>
17 * David Hinds <dahinds@users.sourceforge.net>
18 * Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
19 * Adam Sulmicki <adam@cfar.umd.edu>
20 * Pekka Riikonen <priikone@poesidon.pspt.fi>
21 *
22 * Changes:
23 * D.J. Barrow : Fixed bug where dev->refcnt gets set
24 * to 2 if register_netdev gets called
25 * before net_dev_init & also removed a
26 * few lines of code in the process.
27 * Alan Cox : device private ioctl copies fields back.
28 * Alan Cox : Transmit queue code does relevant
29 * stunts to keep the queue safe.
30 * Alan Cox : Fixed double lock.
31 * Alan Cox : Fixed promisc NULL pointer trap
32 * ???????? : Support the full private ioctl range
33 * Alan Cox : Moved ioctl permission check into
34 * drivers
35 * Tim Kordas : SIOCADDMULTI/SIOCDELMULTI
36 * Alan Cox : 100 backlog just doesn't cut it when
37 * you start doing multicast video 8)
38 * Alan Cox : Rewrote net_bh and list manager.
39 * Alan Cox : Fix ETH_P_ALL echoback lengths.
40 * Alan Cox : Took out transmit every packet pass
41 * Saved a few bytes in the ioctl handler
42 * Alan Cox : Network driver sets packet type before
43 * calling netif_rx. Saves a function
44 * call a packet.
45 * Alan Cox : Hashed net_bh()
46 * Richard Kooijman: Timestamp fixes.
47 * Alan Cox : Wrong field in SIOCGIFDSTADDR
48 * Alan Cox : Device lock protection.
49 * Alan Cox : Fixed nasty side effect of device close
50 * changes.
51 * Rudi Cilibrasi : Pass the right thing to
52 * set_mac_address()
53 * Dave Miller : 32bit quantity for the device lock to
54 * make it work out on a Sparc.
55 * Bjorn Ekwall : Added KERNELD hack.
56 * Alan Cox : Cleaned up the backlog initialise.
57 * Craig Metz : SIOCGIFCONF fix if space for under
58 * 1 device.
59 * Thomas Bogendoerfer : Return ENODEV for dev_open, if there
60 * is no device open function.
61 * Andi Kleen : Fix error reporting for SIOCGIFCONF
62 * Michael Chastain : Fix signed/unsigned for SIOCGIFCONF
63 * Cyrus Durgin : Cleaned for KMOD
64 * Adam Sulmicki : Bug Fix : Network Device Unload
65 * A network device unload needs to purge
66 * the backlog queue.
67 * Paul Rusty Russell : SIOCSIFNAME
68 * Pekka Riikonen : Netdev boot-time settings code
69 * Andrew Morton : Make unregister_netdevice wait
70 * indefinitely on dev->refcnt
71 * J Hadi Salim : - Backlog queue sampling
72 * - netif_rx() feedback
73 */
74
75 #include <linux/uaccess.h>
76 #include <linux/bitops.h>
77 #include <linux/capability.h>
78 #include <linux/cpu.h>
79 #include <linux/types.h>
80 #include <linux/kernel.h>
81 #include <linux/hash.h>
82 #include <linux/slab.h>
83 #include <linux/sched.h>
84 #include <linux/sched/mm.h>
85 #include <linux/mutex.h>
86 #include <linux/string.h>
87 #include <linux/mm.h>
88 #include <linux/socket.h>
89 #include <linux/sockios.h>
90 #include <linux/errno.h>
91 #include <linux/interrupt.h>
92 #include <linux/if_ether.h>
93 #include <linux/netdevice.h>
94 #include <linux/etherdevice.h>
95 #include <linux/ethtool.h>
96 #include <linux/notifier.h>
97 #include <linux/skbuff.h>
98 #include <linux/bpf.h>
99 #include <linux/bpf_trace.h>
100 #include <net/net_namespace.h>
101 #include <net/sock.h>
102 #include <net/busy_poll.h>
103 #include <linux/rtnetlink.h>
104 #include <linux/stat.h>
105 #include <net/dst.h>
106 #include <net/dst_metadata.h>
107 #include <net/pkt_sched.h>
108 #include <net/pkt_cls.h>
109 #include <net/checksum.h>
110 #include <net/xfrm.h>
111 #include <linux/highmem.h>
112 #include <linux/init.h>
113 #include <linux/module.h>
114 #include <linux/netpoll.h>
115 #include <linux/rcupdate.h>
116 #include <linux/delay.h>
117 #include <net/iw_handler.h>
118 #include <asm/current.h>
119 #include <linux/audit.h>
120 #include <linux/dmaengine.h>
121 #include <linux/err.h>
122 #include <linux/ctype.h>
123 #include <linux/if_arp.h>
124 #include <linux/if_vlan.h>
125 #include <linux/ip.h>
126 #include <net/ip.h>
127 #include <net/mpls.h>
128 #include <linux/ipv6.h>
129 #include <linux/in.h>
130 #include <linux/jhash.h>
131 #include <linux/random.h>
132 #include <trace/events/napi.h>
133 #include <trace/events/net.h>
134 #include <trace/events/skb.h>
135 #include <linux/pci.h>
136 #include <linux/inetdevice.h>
137 #include <linux/cpu_rmap.h>
138 #include <linux/static_key.h>
139 #include <linux/hashtable.h>
140 #include <linux/vmalloc.h>
141 #include <linux/if_macvlan.h>
142 #include <linux/errqueue.h>
143 #include <linux/hrtimer.h>
144 #include <linux/netfilter_ingress.h>
145 #include <linux/crash_dump.h>
146 #include <linux/sctp.h>
147 #include <net/udp_tunnel.h>
148 #include <linux/net_namespace.h>
149
150 #include "net-sysfs.h"
151
152 /* Instead of increasing this, you should create a hash table. */
153 #define MAX_GRO_SKBS 8
154 #define MAX_NEST_DEV 8
155
156 /* This should be increased if a protocol with a bigger head is added. */
157 #define GRO_MAX_HEAD (MAX_HEADER + 128)
158
159 static DEFINE_SPINLOCK(ptype_lock);
160 static DEFINE_SPINLOCK(offload_lock);
161 struct list_head ptype_base[PTYPE_HASH_SIZE] __read_mostly;
162 struct list_head ptype_all __read_mostly; /* Taps */
163 static struct list_head offload_base __read_mostly;
164
165 static int netif_rx_internal(struct sk_buff *skb);
166 static int call_netdevice_notifiers_info(unsigned long val,
167 struct netdev_notifier_info *info);
168 static struct napi_struct *napi_by_id(unsigned int napi_id);
169
170 /*
171 * The @dev_base_head list is protected by @dev_base_lock and the rtnl
172 * semaphore.
173 *
174 * Pure readers hold dev_base_lock for reading, or rcu_read_lock()
175 *
176 * Writers must hold the rtnl semaphore while they loop through the
177 * dev_base_head list, and hold dev_base_lock for writing when they do the
178 * actual updates. This allows pure readers to access the list even
179 * while a writer is preparing to update it.
180 *
181 * To put it another way, dev_base_lock is held for writing only to
182 * protect against pure readers; the rtnl semaphore provides the
183 * protection against other writers.
184 *
185 * See, for example usages, register_netdevice() and
186 * unregister_netdevice(), which must be called with the rtnl
187 * semaphore held.
188 */
189 DEFINE_RWLOCK(dev_base_lock);
190 EXPORT_SYMBOL(dev_base_lock);
191
192 static DEFINE_MUTEX(ifalias_mutex);
193
194 /* protects napi_hash addition/deletion and napi_gen_id */
195 static DEFINE_SPINLOCK(napi_hash_lock);
196
197 static unsigned int napi_gen_id = NR_CPUS;
198 static DEFINE_READ_MOSTLY_HASHTABLE(napi_hash, 8);
199
200 static seqcount_t devnet_rename_seq;
201
202 static inline void dev_base_seq_inc(struct net *net)
203 {
204 while (++net->dev_base_seq == 0)
205 ;
206 }
207
208 static inline struct hlist_head *dev_name_hash(struct net *net, const char *name)
209 {
210 unsigned int hash = full_name_hash(net, name, strnlen(name, IFNAMSIZ));
211
212 return &net->dev_name_head[hash_32(hash, NETDEV_HASHBITS)];
213 }
214
215 static inline struct hlist_head *dev_index_hash(struct net *net, int ifindex)
216 {
217 return &net->dev_index_head[ifindex & (NETDEV_HASHENTRIES - 1)];
218 }
219
220 static inline void rps_lock(struct softnet_data *sd)
221 {
222 #ifdef CONFIG_RPS
223 spin_lock(&sd->input_pkt_queue.lock);
224 #endif
225 }
226
227 static inline void rps_unlock(struct softnet_data *sd)
228 {
229 #ifdef CONFIG_RPS
230 spin_unlock(&sd->input_pkt_queue.lock);
231 #endif
232 }
233
234 /* Device list insertion */
235 static void list_netdevice(struct net_device *dev)
236 {
237 struct net *net = dev_net(dev);
238
239 ASSERT_RTNL();
240
241 write_lock_bh(&dev_base_lock);
242 list_add_tail_rcu(&dev->dev_list, &net->dev_base_head);
243 hlist_add_head_rcu(&dev->name_hlist, dev_name_hash(net, dev->name));
244 hlist_add_head_rcu(&dev->index_hlist,
245 dev_index_hash(net, dev->ifindex));
246 write_unlock_bh(&dev_base_lock);
247
248 dev_base_seq_inc(net);
249 }
250
251 /* Device list removal
252 * caller must respect a RCU grace period before freeing/reusing dev
253 */
254 static void unlist_netdevice(struct net_device *dev)
255 {
256 ASSERT_RTNL();
257
258 /* Unlink dev from the device chain */
259 write_lock_bh(&dev_base_lock);
260 list_del_rcu(&dev->dev_list);
261 hlist_del_rcu(&dev->name_hlist);
262 hlist_del_rcu(&dev->index_hlist);
263 write_unlock_bh(&dev_base_lock);
264
265 dev_base_seq_inc(dev_net(dev));
266 }
267
268 /*
269 * Our notifier list
270 */
271
272 static RAW_NOTIFIER_HEAD(netdev_chain);
273
274 /*
275 * Device drivers call our routines to queue packets here. We empty the
276 * queue in the local softnet handler.
277 */
278
279 DEFINE_PER_CPU_ALIGNED(struct softnet_data, softnet_data);
280 EXPORT_PER_CPU_SYMBOL(softnet_data);
281
282 #ifdef CONFIG_LOCKDEP
283 /*
284 * register_netdevice() inits txq->_xmit_lock and sets lockdep class
285 * according to dev->type
286 */
287 static const unsigned short netdev_lock_type[] = {
288 ARPHRD_NETROM, ARPHRD_ETHER, ARPHRD_EETHER, ARPHRD_AX25,
289 ARPHRD_PRONET, ARPHRD_CHAOS, ARPHRD_IEEE802, ARPHRD_ARCNET,
290 ARPHRD_APPLETLK, ARPHRD_DLCI, ARPHRD_ATM, ARPHRD_METRICOM,
291 ARPHRD_IEEE1394, ARPHRD_EUI64, ARPHRD_INFINIBAND, ARPHRD_SLIP,
292 ARPHRD_CSLIP, ARPHRD_SLIP6, ARPHRD_CSLIP6, ARPHRD_RSRVD,
293 ARPHRD_ADAPT, ARPHRD_ROSE, ARPHRD_X25, ARPHRD_HWX25,
294 ARPHRD_PPP, ARPHRD_CISCO, ARPHRD_LAPB, ARPHRD_DDCMP,
295 ARPHRD_RAWHDLC, ARPHRD_TUNNEL, ARPHRD_TUNNEL6, ARPHRD_FRAD,
296 ARPHRD_SKIP, ARPHRD_LOOPBACK, ARPHRD_LOCALTLK, ARPHRD_FDDI,
297 ARPHRD_BIF, ARPHRD_SIT, ARPHRD_IPDDP, ARPHRD_IPGRE,
298 ARPHRD_PIMREG, ARPHRD_HIPPI, ARPHRD_ASH, ARPHRD_ECONET,
299 ARPHRD_IRDA, ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL,
300 ARPHRD_FCFABRIC, ARPHRD_IEEE80211, ARPHRD_IEEE80211_PRISM,
301 ARPHRD_IEEE80211_RADIOTAP, ARPHRD_PHONET, ARPHRD_PHONET_PIPE,
302 ARPHRD_IEEE802154, ARPHRD_VOID, ARPHRD_NONE};
303
304 static const char *const netdev_lock_name[] = {
305 "_xmit_NETROM", "_xmit_ETHER", "_xmit_EETHER", "_xmit_AX25",
306 "_xmit_PRONET", "_xmit_CHAOS", "_xmit_IEEE802", "_xmit_ARCNET",
307 "_xmit_APPLETLK", "_xmit_DLCI", "_xmit_ATM", "_xmit_METRICOM",
308 "_xmit_IEEE1394", "_xmit_EUI64", "_xmit_INFINIBAND", "_xmit_SLIP",
309 "_xmit_CSLIP", "_xmit_SLIP6", "_xmit_CSLIP6", "_xmit_RSRVD",
310 "_xmit_ADAPT", "_xmit_ROSE", "_xmit_X25", "_xmit_HWX25",
311 "_xmit_PPP", "_xmit_CISCO", "_xmit_LAPB", "_xmit_DDCMP",
312 "_xmit_RAWHDLC", "_xmit_TUNNEL", "_xmit_TUNNEL6", "_xmit_FRAD",
313 "_xmit_SKIP", "_xmit_LOOPBACK", "_xmit_LOCALTLK", "_xmit_FDDI",
314 "_xmit_BIF", "_xmit_SIT", "_xmit_IPDDP", "_xmit_IPGRE",
315 "_xmit_PIMREG", "_xmit_HIPPI", "_xmit_ASH", "_xmit_ECONET",
316 "_xmit_IRDA", "_xmit_FCPP", "_xmit_FCAL", "_xmit_FCPL",
317 "_xmit_FCFABRIC", "_xmit_IEEE80211", "_xmit_IEEE80211_PRISM",
318 "_xmit_IEEE80211_RADIOTAP", "_xmit_PHONET", "_xmit_PHONET_PIPE",
319 "_xmit_IEEE802154", "_xmit_VOID", "_xmit_NONE"};
320
321 static struct lock_class_key netdev_xmit_lock_key[ARRAY_SIZE(netdev_lock_type)];
322 static struct lock_class_key netdev_addr_lock_key[ARRAY_SIZE(netdev_lock_type)];
323
324 static inline unsigned short netdev_lock_pos(unsigned short dev_type)
325 {
326 int i;
327
328 for (i = 0; i < ARRAY_SIZE(netdev_lock_type); i++)
329 if (netdev_lock_type[i] == dev_type)
330 return i;
331 /* the last key is used by default */
332 return ARRAY_SIZE(netdev_lock_type) - 1;
333 }
334
335 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
336 unsigned short dev_type)
337 {
338 int i;
339
340 i = netdev_lock_pos(dev_type);
341 lockdep_set_class_and_name(lock, &netdev_xmit_lock_key[i],
342 netdev_lock_name[i]);
343 }
344
345 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
346 {
347 int i;
348
349 i = netdev_lock_pos(dev->type);
350 lockdep_set_class_and_name(&dev->addr_list_lock,
351 &netdev_addr_lock_key[i],
352 netdev_lock_name[i]);
353 }
354 #else
355 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
356 unsigned short dev_type)
357 {
358 }
359 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
360 {
361 }
362 #endif
363
364 /*******************************************************************************
365 *
366 * Protocol management and registration routines
367 *
368 *******************************************************************************/
369
370
371 /*
372 * Add a protocol ID to the list. Now that the input handler is
373 * smarter we can dispense with all the messy stuff that used to be
374 * here.
375 *
376 * BEWARE!!! Protocol handlers, mangling input packets,
377 * MUST BE last in hash buckets and checking protocol handlers
378 * MUST start from promiscuous ptype_all chain in net_bh.
379 * It is true now, do not change it.
380 * Explanation follows: if protocol handler, mangling packet, will
381 * be the first on list, it is not able to sense, that packet
382 * is cloned and should be copied-on-write, so that it will
383 * change it and subsequent readers will get broken packet.
384 * --ANK (980803)
385 */
386
387 static inline struct list_head *ptype_head(const struct packet_type *pt)
388 {
389 if (pt->type == htons(ETH_P_ALL))
390 return pt->dev ? &pt->dev->ptype_all : &ptype_all;
391 else
392 return pt->dev ? &pt->dev->ptype_specific :
393 &ptype_base[ntohs(pt->type) & PTYPE_HASH_MASK];
394 }
395
396 /**
397 * dev_add_pack - add packet handler
398 * @pt: packet type declaration
399 *
400 * Add a protocol handler to the networking stack. The passed &packet_type
401 * is linked into kernel lists and may not be freed until it has been
402 * removed from the kernel lists.
403 *
404 * This call does not sleep therefore it can not
405 * guarantee all CPU's that are in middle of receiving packets
406 * will see the new packet type (until the next received packet).
407 */
408
409 void dev_add_pack(struct packet_type *pt)
410 {
411 struct list_head *head = ptype_head(pt);
412
413 spin_lock(&ptype_lock);
414 list_add_rcu(&pt->list, head);
415 spin_unlock(&ptype_lock);
416 }
417 EXPORT_SYMBOL(dev_add_pack);
418
419 /**
420 * __dev_remove_pack - remove packet handler
421 * @pt: packet type declaration
422 *
423 * Remove a protocol handler that was previously added to the kernel
424 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
425 * from the kernel lists and can be freed or reused once this function
426 * returns.
427 *
428 * The packet type might still be in use by receivers
429 * and must not be freed until after all the CPU's have gone
430 * through a quiescent state.
431 */
432 void __dev_remove_pack(struct packet_type *pt)
433 {
434 struct list_head *head = ptype_head(pt);
435 struct packet_type *pt1;
436
437 spin_lock(&ptype_lock);
438
439 list_for_each_entry(pt1, head, list) {
440 if (pt == pt1) {
441 list_del_rcu(&pt->list);
442 goto out;
443 }
444 }
445
446 pr_warn("dev_remove_pack: %p not found\n", pt);
447 out:
448 spin_unlock(&ptype_lock);
449 }
450 EXPORT_SYMBOL(__dev_remove_pack);
451
452 /**
453 * dev_remove_pack - remove packet handler
454 * @pt: packet type declaration
455 *
456 * Remove a protocol handler that was previously added to the kernel
457 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
458 * from the kernel lists and can be freed or reused once this function
459 * returns.
460 *
461 * This call sleeps to guarantee that no CPU is looking at the packet
462 * type after return.
463 */
464 void dev_remove_pack(struct packet_type *pt)
465 {
466 __dev_remove_pack(pt);
467
468 synchronize_net();
469 }
470 EXPORT_SYMBOL(dev_remove_pack);
471
472
473 /**
474 * dev_add_offload - register offload handlers
475 * @po: protocol offload declaration
476 *
477 * Add protocol offload handlers to the networking stack. The passed
478 * &proto_offload is linked into kernel lists and may not be freed until
479 * it has been removed from the kernel lists.
480 *
481 * This call does not sleep therefore it can not
482 * guarantee all CPU's that are in middle of receiving packets
483 * will see the new offload handlers (until the next received packet).
484 */
485 void dev_add_offload(struct packet_offload *po)
486 {
487 struct packet_offload *elem;
488
489 spin_lock(&offload_lock);
490 list_for_each_entry(elem, &offload_base, list) {
491 if (po->priority < elem->priority)
492 break;
493 }
494 list_add_rcu(&po->list, elem->list.prev);
495 spin_unlock(&offload_lock);
496 }
497 EXPORT_SYMBOL(dev_add_offload);
498
499 /**
500 * __dev_remove_offload - remove offload handler
501 * @po: packet offload declaration
502 *
503 * Remove a protocol offload handler that was previously added to the
504 * kernel offload handlers by dev_add_offload(). The passed &offload_type
505 * is removed from the kernel lists and can be freed or reused once this
506 * function returns.
507 *
508 * The packet type might still be in use by receivers
509 * and must not be freed until after all the CPU's have gone
510 * through a quiescent state.
511 */
512 static void __dev_remove_offload(struct packet_offload *po)
513 {
514 struct list_head *head = &offload_base;
515 struct packet_offload *po1;
516
517 spin_lock(&offload_lock);
518
519 list_for_each_entry(po1, head, list) {
520 if (po == po1) {
521 list_del_rcu(&po->list);
522 goto out;
523 }
524 }
525
526 pr_warn("dev_remove_offload: %p not found\n", po);
527 out:
528 spin_unlock(&offload_lock);
529 }
530
531 /**
532 * dev_remove_offload - remove packet offload handler
533 * @po: packet offload declaration
534 *
535 * Remove a packet offload handler that was previously added to the kernel
536 * offload handlers by dev_add_offload(). The passed &offload_type is
537 * removed from the kernel lists and can be freed or reused once this
538 * function returns.
539 *
540 * This call sleeps to guarantee that no CPU is looking at the packet
541 * type after return.
542 */
543 void dev_remove_offload(struct packet_offload *po)
544 {
545 __dev_remove_offload(po);
546
547 synchronize_net();
548 }
549 EXPORT_SYMBOL(dev_remove_offload);
550
551 /******************************************************************************
552 *
553 * Device Boot-time Settings Routines
554 *
555 ******************************************************************************/
556
557 /* Boot time configuration table */
558 static struct netdev_boot_setup dev_boot_setup[NETDEV_BOOT_SETUP_MAX];
559
560 /**
561 * netdev_boot_setup_add - add new setup entry
562 * @name: name of the device
563 * @map: configured settings for the device
564 *
565 * Adds new setup entry to the dev_boot_setup list. The function
566 * returns 0 on error and 1 on success. This is a generic routine to
567 * all netdevices.
568 */
569 static int netdev_boot_setup_add(char *name, struct ifmap *map)
570 {
571 struct netdev_boot_setup *s;
572 int i;
573
574 s = dev_boot_setup;
575 for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
576 if (s[i].name[0] == '\0' || s[i].name[0] == ' ') {
577 memset(s[i].name, 0, sizeof(s[i].name));
578 strlcpy(s[i].name, name, IFNAMSIZ);
579 memcpy(&s[i].map, map, sizeof(s[i].map));
580 break;
581 }
582 }
583
584 return i >= NETDEV_BOOT_SETUP_MAX ? 0 : 1;
585 }
586
587 /**
588 * netdev_boot_setup_check - check boot time settings
589 * @dev: the netdevice
590 *
591 * Check boot time settings for the device.
592 * The found settings are set for the device to be used
593 * later in the device probing.
594 * Returns 0 if no settings found, 1 if they are.
595 */
596 int netdev_boot_setup_check(struct net_device *dev)
597 {
598 struct netdev_boot_setup *s = dev_boot_setup;
599 int i;
600
601 for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
602 if (s[i].name[0] != '\0' && s[i].name[0] != ' ' &&
603 !strcmp(dev->name, s[i].name)) {
604 dev->irq = s[i].map.irq;
605 dev->base_addr = s[i].map.base_addr;
606 dev->mem_start = s[i].map.mem_start;
607 dev->mem_end = s[i].map.mem_end;
608 return 1;
609 }
610 }
611 return 0;
612 }
613 EXPORT_SYMBOL(netdev_boot_setup_check);
614
615
616 /**
617 * netdev_boot_base - get address from boot time settings
618 * @prefix: prefix for network device
619 * @unit: id for network device
620 *
621 * Check boot time settings for the base address of device.
622 * The found settings are set for the device to be used
623 * later in the device probing.
624 * Returns 0 if no settings found.
625 */
626 unsigned long netdev_boot_base(const char *prefix, int unit)
627 {
628 const struct netdev_boot_setup *s = dev_boot_setup;
629 char name[IFNAMSIZ];
630 int i;
631
632 sprintf(name, "%s%d", prefix, unit);
633
634 /*
635 * If device already registered then return base of 1
636 * to indicate not to probe for this interface
637 */
638 if (__dev_get_by_name(&init_net, name))
639 return 1;
640
641 for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++)
642 if (!strcmp(name, s[i].name))
643 return s[i].map.base_addr;
644 return 0;
645 }
646
647 /*
648 * Saves at boot time configured settings for any netdevice.
649 */
650 int __init netdev_boot_setup(char *str)
651 {
652 int ints[5];
653 struct ifmap map;
654
655 str = get_options(str, ARRAY_SIZE(ints), ints);
656 if (!str || !*str)
657 return 0;
658
659 /* Save settings */
660 memset(&map, 0, sizeof(map));
661 if (ints[0] > 0)
662 map.irq = ints[1];
663 if (ints[0] > 1)
664 map.base_addr = ints[2];
665 if (ints[0] > 2)
666 map.mem_start = ints[3];
667 if (ints[0] > 3)
668 map.mem_end = ints[4];
669
670 /* Add new entry to the list */
671 return netdev_boot_setup_add(str, &map);
672 }
673
674 __setup("netdev=", netdev_boot_setup);
675
676 /*******************************************************************************
677 *
678 * Device Interface Subroutines
679 *
680 *******************************************************************************/
681
682 /**
683 * dev_get_iflink - get 'iflink' value of a interface
684 * @dev: targeted interface
685 *
686 * Indicates the ifindex the interface is linked to.
687 * Physical interfaces have the same 'ifindex' and 'iflink' values.
688 */
689
690 int dev_get_iflink(const struct net_device *dev)
691 {
692 if (dev->netdev_ops && dev->netdev_ops->ndo_get_iflink)
693 return dev->netdev_ops->ndo_get_iflink(dev);
694
695 return dev->ifindex;
696 }
697 EXPORT_SYMBOL(dev_get_iflink);
698
699 /**
700 * dev_fill_metadata_dst - Retrieve tunnel egress information.
701 * @dev: targeted interface
702 * @skb: The packet.
703 *
704 * For better visibility of tunnel traffic OVS needs to retrieve
705 * egress tunnel information for a packet. Following API allows
706 * user to get this info.
707 */
708 int dev_fill_metadata_dst(struct net_device *dev, struct sk_buff *skb)
709 {
710 struct ip_tunnel_info *info;
711
712 if (!dev->netdev_ops || !dev->netdev_ops->ndo_fill_metadata_dst)
713 return -EINVAL;
714
715 info = skb_tunnel_info_unclone(skb);
716 if (!info)
717 return -ENOMEM;
718 if (unlikely(!(info->mode & IP_TUNNEL_INFO_TX)))
719 return -EINVAL;
720
721 return dev->netdev_ops->ndo_fill_metadata_dst(dev, skb);
722 }
723 EXPORT_SYMBOL_GPL(dev_fill_metadata_dst);
724
725 /**
726 * __dev_get_by_name - find a device by its name
727 * @net: the applicable net namespace
728 * @name: name to find
729 *
730 * Find an interface by name. Must be called under RTNL semaphore
731 * or @dev_base_lock. If the name is found a pointer to the device
732 * is returned. If the name is not found then %NULL is returned. The
733 * reference counters are not incremented so the caller must be
734 * careful with locks.
735 */
736
737 struct net_device *__dev_get_by_name(struct net *net, const char *name)
738 {
739 struct net_device *dev;
740 struct hlist_head *head = dev_name_hash(net, name);
741
742 hlist_for_each_entry(dev, head, name_hlist)
743 if (!strncmp(dev->name, name, IFNAMSIZ))
744 return dev;
745
746 return NULL;
747 }
748 EXPORT_SYMBOL(__dev_get_by_name);
749
750 /**
751 * dev_get_by_name_rcu - find a device by its name
752 * @net: the applicable net namespace
753 * @name: name to find
754 *
755 * Find an interface by name.
756 * If the name is found a pointer to the device is returned.
757 * If the name is not found then %NULL is returned.
758 * The reference counters are not incremented so the caller must be
759 * careful with locks. The caller must hold RCU lock.
760 */
761
762 struct net_device *dev_get_by_name_rcu(struct net *net, const char *name)
763 {
764 struct net_device *dev;
765 struct hlist_head *head = dev_name_hash(net, name);
766
767 hlist_for_each_entry_rcu(dev, head, name_hlist)
768 if (!strncmp(dev->name, name, IFNAMSIZ))
769 return dev;
770
771 return NULL;
772 }
773 EXPORT_SYMBOL(dev_get_by_name_rcu);
774
775 /**
776 * dev_get_by_name - find a device by its name
777 * @net: the applicable net namespace
778 * @name: name to find
779 *
780 * Find an interface by name. This can be called from any
781 * context and does its own locking. The returned handle has
782 * the usage count incremented and the caller must use dev_put() to
783 * release it when it is no longer needed. %NULL is returned if no
784 * matching device is found.
785 */
786
787 struct net_device *dev_get_by_name(struct net *net, const char *name)
788 {
789 struct net_device *dev;
790
791 rcu_read_lock();
792 dev = dev_get_by_name_rcu(net, name);
793 if (dev)
794 dev_hold(dev);
795 rcu_read_unlock();
796 return dev;
797 }
798 EXPORT_SYMBOL(dev_get_by_name);
799
800 /**
801 * __dev_get_by_index - find a device by its ifindex
802 * @net: the applicable net namespace
803 * @ifindex: index of device
804 *
805 * Search for an interface by index. Returns %NULL if the device
806 * is not found or a pointer to the device. The device has not
807 * had its reference counter increased so the caller must be careful
808 * about locking. The caller must hold either the RTNL semaphore
809 * or @dev_base_lock.
810 */
811
812 struct net_device *__dev_get_by_index(struct net *net, int ifindex)
813 {
814 struct net_device *dev;
815 struct hlist_head *head = dev_index_hash(net, ifindex);
816
817 hlist_for_each_entry(dev, head, index_hlist)
818 if (dev->ifindex == ifindex)
819 return dev;
820
821 return NULL;
822 }
823 EXPORT_SYMBOL(__dev_get_by_index);
824
825 /**
826 * dev_get_by_index_rcu - find a device by its ifindex
827 * @net: the applicable net namespace
828 * @ifindex: index of device
829 *
830 * Search for an interface by index. Returns %NULL if the device
831 * is not found or a pointer to the device. The device has not
832 * had its reference counter increased so the caller must be careful
833 * about locking. The caller must hold RCU lock.
834 */
835
836 struct net_device *dev_get_by_index_rcu(struct net *net, int ifindex)
837 {
838 struct net_device *dev;
839 struct hlist_head *head = dev_index_hash(net, ifindex);
840
841 hlist_for_each_entry_rcu(dev, head, index_hlist)
842 if (dev->ifindex == ifindex)
843 return dev;
844
845 return NULL;
846 }
847 EXPORT_SYMBOL(dev_get_by_index_rcu);
848
849
850 /**
851 * dev_get_by_index - find a device by its ifindex
852 * @net: the applicable net namespace
853 * @ifindex: index of device
854 *
855 * Search for an interface by index. Returns NULL if the device
856 * is not found or a pointer to the device. The device returned has
857 * had a reference added and the pointer is safe until the user calls
858 * dev_put to indicate they have finished with it.
859 */
860
861 struct net_device *dev_get_by_index(struct net *net, int ifindex)
862 {
863 struct net_device *dev;
864
865 rcu_read_lock();
866 dev = dev_get_by_index_rcu(net, ifindex);
867 if (dev)
868 dev_hold(dev);
869 rcu_read_unlock();
870 return dev;
871 }
872 EXPORT_SYMBOL(dev_get_by_index);
873
874 /**
875 * dev_get_by_napi_id - find a device by napi_id
876 * @napi_id: ID of the NAPI struct
877 *
878 * Search for an interface by NAPI ID. Returns %NULL if the device
879 * is not found or a pointer to the device. The device has not had
880 * its reference counter increased so the caller must be careful
881 * about locking. The caller must hold RCU lock.
882 */
883
884 struct net_device *dev_get_by_napi_id(unsigned int napi_id)
885 {
886 struct napi_struct *napi;
887
888 WARN_ON_ONCE(!rcu_read_lock_held());
889
890 if (napi_id < MIN_NAPI_ID)
891 return NULL;
892
893 napi = napi_by_id(napi_id);
894
895 return napi ? napi->dev : NULL;
896 }
897 EXPORT_SYMBOL(dev_get_by_napi_id);
898
899 /**
900 * netdev_get_name - get a netdevice name, knowing its ifindex.
901 * @net: network namespace
902 * @name: a pointer to the buffer where the name will be stored.
903 * @ifindex: the ifindex of the interface to get the name from.
904 *
905 * The use of raw_seqcount_begin() and cond_resched() before
906 * retrying is required as we want to give the writers a chance
907 * to complete when CONFIG_PREEMPT is not set.
908 */
909 int netdev_get_name(struct net *net, char *name, int ifindex)
910 {
911 struct net_device *dev;
912 unsigned int seq;
913
914 retry:
915 seq = raw_seqcount_begin(&devnet_rename_seq);
916 rcu_read_lock();
917 dev = dev_get_by_index_rcu(net, ifindex);
918 if (!dev) {
919 rcu_read_unlock();
920 return -ENODEV;
921 }
922
923 strcpy(name, dev->name);
924 rcu_read_unlock();
925 if (read_seqcount_retry(&devnet_rename_seq, seq)) {
926 cond_resched();
927 goto retry;
928 }
929
930 return 0;
931 }
932
933 /**
934 * dev_getbyhwaddr_rcu - find a device by its hardware address
935 * @net: the applicable net namespace
936 * @type: media type of device
937 * @ha: hardware address
938 *
939 * Search for an interface by MAC address. Returns NULL if the device
940 * is not found or a pointer to the device.
941 * The caller must hold RCU or RTNL.
942 * The returned device has not had its ref count increased
943 * and the caller must therefore be careful about locking
944 *
945 */
946
947 struct net_device *dev_getbyhwaddr_rcu(struct net *net, unsigned short type,
948 const char *ha)
949 {
950 struct net_device *dev;
951
952 for_each_netdev_rcu(net, dev)
953 if (dev->type == type &&
954 !memcmp(dev->dev_addr, ha, dev->addr_len))
955 return dev;
956
957 return NULL;
958 }
959 EXPORT_SYMBOL(dev_getbyhwaddr_rcu);
960
961 struct net_device *__dev_getfirstbyhwtype(struct net *net, unsigned short type)
962 {
963 struct net_device *dev;
964
965 ASSERT_RTNL();
966 for_each_netdev(net, dev)
967 if (dev->type == type)
968 return dev;
969
970 return NULL;
971 }
972 EXPORT_SYMBOL(__dev_getfirstbyhwtype);
973
974 struct net_device *dev_getfirstbyhwtype(struct net *net, unsigned short type)
975 {
976 struct net_device *dev, *ret = NULL;
977
978 rcu_read_lock();
979 for_each_netdev_rcu(net, dev)
980 if (dev->type == type) {
981 dev_hold(dev);
982 ret = dev;
983 break;
984 }
985 rcu_read_unlock();
986 return ret;
987 }
988 EXPORT_SYMBOL(dev_getfirstbyhwtype);
989
990 /**
991 * __dev_get_by_flags - find any device with given flags
992 * @net: the applicable net namespace
993 * @if_flags: IFF_* values
994 * @mask: bitmask of bits in if_flags to check
995 *
996 * Search for any interface with the given flags. Returns NULL if a device
997 * is not found or a pointer to the device. Must be called inside
998 * rtnl_lock(), and result refcount is unchanged.
999 */
1000
1001 struct net_device *__dev_get_by_flags(struct net *net, unsigned short if_flags,
1002 unsigned short mask)
1003 {
1004 struct net_device *dev, *ret;
1005
1006 ASSERT_RTNL();
1007
1008 ret = NULL;
1009 for_each_netdev(net, dev) {
1010 if (((dev->flags ^ if_flags) & mask) == 0) {
1011 ret = dev;
1012 break;
1013 }
1014 }
1015 return ret;
1016 }
1017 EXPORT_SYMBOL(__dev_get_by_flags);
1018
1019 /**
1020 * dev_valid_name - check if name is okay for network device
1021 * @name: name string
1022 *
1023 * Network device names need to be valid file names to
1024 * to allow sysfs to work. We also disallow any kind of
1025 * whitespace.
1026 */
1027 bool dev_valid_name(const char *name)
1028 {
1029 if (*name == '\0')
1030 return false;
1031 if (strnlen(name, IFNAMSIZ) == IFNAMSIZ)
1032 return false;
1033 if (!strcmp(name, ".") || !strcmp(name, ".."))
1034 return false;
1035
1036 while (*name) {
1037 if (*name == '/' || *name == ':' || isspace(*name))
1038 return false;
1039 name++;
1040 }
1041 return true;
1042 }
1043 EXPORT_SYMBOL(dev_valid_name);
1044
1045 /**
1046 * __dev_alloc_name - allocate a name for a device
1047 * @net: network namespace to allocate the device name in
1048 * @name: name format string
1049 * @buf: scratch buffer and result name string
1050 *
1051 * Passed a format string - eg "lt%d" it will try and find a suitable
1052 * id. It scans list of devices to build up a free map, then chooses
1053 * the first empty slot. The caller must hold the dev_base or rtnl lock
1054 * while allocating the name and adding the device in order to avoid
1055 * duplicates.
1056 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1057 * Returns the number of the unit assigned or a negative errno code.
1058 */
1059
1060 static int __dev_alloc_name(struct net *net, const char *name, char *buf)
1061 {
1062 int i = 0;
1063 const char *p;
1064 const int max_netdevices = 8*PAGE_SIZE;
1065 unsigned long *inuse;
1066 struct net_device *d;
1067
1068 if (!dev_valid_name(name))
1069 return -EINVAL;
1070
1071 p = strchr(name, '%');
1072 if (p) {
1073 /*
1074 * Verify the string as this thing may have come from
1075 * the user. There must be either one "%d" and no other "%"
1076 * characters.
1077 */
1078 if (p[1] != 'd' || strchr(p + 2, '%'))
1079 return -EINVAL;
1080
1081 /* Use one page as a bit array of possible slots */
1082 inuse = (unsigned long *) get_zeroed_page(GFP_ATOMIC);
1083 if (!inuse)
1084 return -ENOMEM;
1085
1086 for_each_netdev(net, d) {
1087 if (!sscanf(d->name, name, &i))
1088 continue;
1089 if (i < 0 || i >= max_netdevices)
1090 continue;
1091
1092 /* avoid cases where sscanf is not exact inverse of printf */
1093 snprintf(buf, IFNAMSIZ, name, i);
1094 if (!strncmp(buf, d->name, IFNAMSIZ))
1095 set_bit(i, inuse);
1096 }
1097
1098 i = find_first_zero_bit(inuse, max_netdevices);
1099 free_page((unsigned long) inuse);
1100 }
1101
1102 snprintf(buf, IFNAMSIZ, name, i);
1103 if (!__dev_get_by_name(net, buf))
1104 return i;
1105
1106 /* It is possible to run out of possible slots
1107 * when the name is long and there isn't enough space left
1108 * for the digits, or if all bits are used.
1109 */
1110 return -ENFILE;
1111 }
1112
1113 static int dev_alloc_name_ns(struct net *net,
1114 struct net_device *dev,
1115 const char *name)
1116 {
1117 char buf[IFNAMSIZ];
1118 int ret;
1119
1120 BUG_ON(!net);
1121 ret = __dev_alloc_name(net, name, buf);
1122 if (ret >= 0)
1123 strlcpy(dev->name, buf, IFNAMSIZ);
1124 return ret;
1125 }
1126
1127 /**
1128 * dev_alloc_name - allocate a name for a device
1129 * @dev: device
1130 * @name: name format string
1131 *
1132 * Passed a format string - eg "lt%d" it will try and find a suitable
1133 * id. It scans list of devices to build up a free map, then chooses
1134 * the first empty slot. The caller must hold the dev_base or rtnl lock
1135 * while allocating the name and adding the device in order to avoid
1136 * duplicates.
1137 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1138 * Returns the number of the unit assigned or a negative errno code.
1139 */
1140
1141 int dev_alloc_name(struct net_device *dev, const char *name)
1142 {
1143 return dev_alloc_name_ns(dev_net(dev), dev, name);
1144 }
1145 EXPORT_SYMBOL(dev_alloc_name);
1146
1147 int dev_get_valid_name(struct net *net, struct net_device *dev,
1148 const char *name)
1149 {
1150 BUG_ON(!net);
1151
1152 if (!dev_valid_name(name))
1153 return -EINVAL;
1154
1155 if (strchr(name, '%'))
1156 return dev_alloc_name_ns(net, dev, name);
1157 else if (__dev_get_by_name(net, name))
1158 return -EEXIST;
1159 else if (dev->name != name)
1160 strlcpy(dev->name, name, IFNAMSIZ);
1161
1162 return 0;
1163 }
1164 EXPORT_SYMBOL(dev_get_valid_name);
1165
1166 /**
1167 * dev_change_name - change name of a device
1168 * @dev: device
1169 * @newname: name (or format string) must be at least IFNAMSIZ
1170 *
1171 * Change name of a device, can pass format strings "eth%d".
1172 * for wildcarding.
1173 */
1174 int dev_change_name(struct net_device *dev, const char *newname)
1175 {
1176 unsigned char old_assign_type;
1177 char oldname[IFNAMSIZ];
1178 int err = 0;
1179 int ret;
1180 struct net *net;
1181
1182 ASSERT_RTNL();
1183 BUG_ON(!dev_net(dev));
1184
1185 net = dev_net(dev);
1186 if (dev->flags & IFF_UP)
1187 return -EBUSY;
1188
1189 write_seqcount_begin(&devnet_rename_seq);
1190
1191 if (strncmp(newname, dev->name, IFNAMSIZ) == 0) {
1192 write_seqcount_end(&devnet_rename_seq);
1193 return 0;
1194 }
1195
1196 memcpy(oldname, dev->name, IFNAMSIZ);
1197
1198 err = dev_get_valid_name(net, dev, newname);
1199 if (err < 0) {
1200 write_seqcount_end(&devnet_rename_seq);
1201 return err;
1202 }
1203
1204 if (oldname[0] && !strchr(oldname, '%'))
1205 netdev_info(dev, "renamed from %s\n", oldname);
1206
1207 old_assign_type = dev->name_assign_type;
1208 dev->name_assign_type = NET_NAME_RENAMED;
1209
1210 rollback:
1211 ret = device_rename(&dev->dev, dev->name);
1212 if (ret) {
1213 memcpy(dev->name, oldname, IFNAMSIZ);
1214 dev->name_assign_type = old_assign_type;
1215 write_seqcount_end(&devnet_rename_seq);
1216 return ret;
1217 }
1218
1219 write_seqcount_end(&devnet_rename_seq);
1220
1221 netdev_adjacent_rename_links(dev, oldname);
1222
1223 write_lock_bh(&dev_base_lock);
1224 hlist_del_rcu(&dev->name_hlist);
1225 write_unlock_bh(&dev_base_lock);
1226
1227 synchronize_rcu();
1228
1229 write_lock_bh(&dev_base_lock);
1230 hlist_add_head_rcu(&dev->name_hlist, dev_name_hash(net, dev->name));
1231 write_unlock_bh(&dev_base_lock);
1232
1233 ret = call_netdevice_notifiers(NETDEV_CHANGENAME, dev);
1234 ret = notifier_to_errno(ret);
1235
1236 if (ret) {
1237 /* err >= 0 after dev_alloc_name() or stores the first errno */
1238 if (err >= 0) {
1239 err = ret;
1240 write_seqcount_begin(&devnet_rename_seq);
1241 memcpy(dev->name, oldname, IFNAMSIZ);
1242 memcpy(oldname, newname, IFNAMSIZ);
1243 dev->name_assign_type = old_assign_type;
1244 old_assign_type = NET_NAME_RENAMED;
1245 goto rollback;
1246 } else {
1247 pr_err("%s: name change rollback failed: %d\n",
1248 dev->name, ret);
1249 }
1250 }
1251
1252 return err;
1253 }
1254
1255 /**
1256 * dev_set_alias - change ifalias of a device
1257 * @dev: device
1258 * @alias: name up to IFALIASZ
1259 * @len: limit of bytes to copy from info
1260 *
1261 * Set ifalias for a device,
1262 */
1263 int dev_set_alias(struct net_device *dev, const char *alias, size_t len)
1264 {
1265 struct dev_ifalias *new_alias = NULL;
1266
1267 if (len >= IFALIASZ)
1268 return -EINVAL;
1269
1270 if (len) {
1271 new_alias = kmalloc(sizeof(*new_alias) + len + 1, GFP_KERNEL);
1272 if (!new_alias)
1273 return -ENOMEM;
1274
1275 memcpy(new_alias->ifalias, alias, len);
1276 new_alias->ifalias[len] = 0;
1277 }
1278
1279 mutex_lock(&ifalias_mutex);
1280 rcu_swap_protected(dev->ifalias, new_alias,
1281 mutex_is_locked(&ifalias_mutex));
1282 mutex_unlock(&ifalias_mutex);
1283
1284 if (new_alias)
1285 kfree_rcu(new_alias, rcuhead);
1286
1287 return len;
1288 }
1289
1290 /**
1291 * dev_get_alias - get ifalias of a device
1292 * @dev: device
1293 * @name: buffer to store name of ifalias
1294 * @len: size of buffer
1295 *
1296 * get ifalias for a device. Caller must make sure dev cannot go
1297 * away, e.g. rcu read lock or own a reference count to device.
1298 */
1299 int dev_get_alias(const struct net_device *dev, char *name, size_t len)
1300 {
1301 const struct dev_ifalias *alias;
1302 int ret = 0;
1303
1304 rcu_read_lock();
1305 alias = rcu_dereference(dev->ifalias);
1306 if (alias)
1307 ret = snprintf(name, len, "%s", alias->ifalias);
1308 rcu_read_unlock();
1309
1310 return ret;
1311 }
1312
1313 /**
1314 * netdev_features_change - device changes features
1315 * @dev: device to cause notification
1316 *
1317 * Called to indicate a device has changed features.
1318 */
1319 void netdev_features_change(struct net_device *dev)
1320 {
1321 call_netdevice_notifiers(NETDEV_FEAT_CHANGE, dev);
1322 }
1323 EXPORT_SYMBOL(netdev_features_change);
1324
1325 /**
1326 * netdev_state_change - device changes state
1327 * @dev: device to cause notification
1328 *
1329 * Called to indicate a device has changed state. This function calls
1330 * the notifier chains for netdev_chain and sends a NEWLINK message
1331 * to the routing socket.
1332 */
1333 void netdev_state_change(struct net_device *dev)
1334 {
1335 if (dev->flags & IFF_UP) {
1336 struct netdev_notifier_change_info change_info = {
1337 .info.dev = dev,
1338 };
1339
1340 call_netdevice_notifiers_info(NETDEV_CHANGE,
1341 &change_info.info);
1342 rtmsg_ifinfo(RTM_NEWLINK, dev, 0, GFP_KERNEL);
1343 }
1344 }
1345 EXPORT_SYMBOL(netdev_state_change);
1346
1347 /**
1348 * netdev_notify_peers - notify network peers about existence of @dev
1349 * @dev: network device
1350 *
1351 * Generate traffic such that interested network peers are aware of
1352 * @dev, such as by generating a gratuitous ARP. This may be used when
1353 * a device wants to inform the rest of the network about some sort of
1354 * reconfiguration such as a failover event or virtual machine
1355 * migration.
1356 */
1357 void netdev_notify_peers(struct net_device *dev)
1358 {
1359 rtnl_lock();
1360 call_netdevice_notifiers(NETDEV_NOTIFY_PEERS, dev);
1361 call_netdevice_notifiers(NETDEV_RESEND_IGMP, dev);
1362 rtnl_unlock();
1363 }
1364 EXPORT_SYMBOL(netdev_notify_peers);
1365
1366 static int __dev_open(struct net_device *dev)
1367 {
1368 const struct net_device_ops *ops = dev->netdev_ops;
1369 int ret;
1370
1371 ASSERT_RTNL();
1372
1373 if (!netif_device_present(dev))
1374 return -ENODEV;
1375
1376 /* Block netpoll from trying to do any rx path servicing.
1377 * If we don't do this there is a chance ndo_poll_controller
1378 * or ndo_poll may be running while we open the device
1379 */
1380 netpoll_poll_disable(dev);
1381
1382 ret = call_netdevice_notifiers(NETDEV_PRE_UP, dev);
1383 ret = notifier_to_errno(ret);
1384 if (ret)
1385 return ret;
1386
1387 set_bit(__LINK_STATE_START, &dev->state);
1388
1389 if (ops->ndo_validate_addr)
1390 ret = ops->ndo_validate_addr(dev);
1391
1392 if (!ret && ops->ndo_open)
1393 ret = ops->ndo_open(dev);
1394
1395 netpoll_poll_enable(dev);
1396
1397 if (ret)
1398 clear_bit(__LINK_STATE_START, &dev->state);
1399 else {
1400 dev->flags |= IFF_UP;
1401 dev_set_rx_mode(dev);
1402 dev_activate(dev);
1403 add_device_randomness(dev->dev_addr, dev->addr_len);
1404 }
1405
1406 return ret;
1407 }
1408
1409 /**
1410 * dev_open - prepare an interface for use.
1411 * @dev: device to open
1412 *
1413 * Takes a device from down to up state. The device's private open
1414 * function is invoked and then the multicast lists are loaded. Finally
1415 * the device is moved into the up state and a %NETDEV_UP message is
1416 * sent to the netdev notifier chain.
1417 *
1418 * Calling this function on an active interface is a nop. On a failure
1419 * a negative errno code is returned.
1420 */
1421 int dev_open(struct net_device *dev)
1422 {
1423 int ret;
1424
1425 if (dev->flags & IFF_UP)
1426 return 0;
1427
1428 ret = __dev_open(dev);
1429 if (ret < 0)
1430 return ret;
1431
1432 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING, GFP_KERNEL);
1433 call_netdevice_notifiers(NETDEV_UP, dev);
1434
1435 return ret;
1436 }
1437 EXPORT_SYMBOL(dev_open);
1438
1439 static void __dev_close_many(struct list_head *head)
1440 {
1441 struct net_device *dev;
1442
1443 ASSERT_RTNL();
1444 might_sleep();
1445
1446 list_for_each_entry(dev, head, close_list) {
1447 /* Temporarily disable netpoll until the interface is down */
1448 netpoll_poll_disable(dev);
1449
1450 call_netdevice_notifiers(NETDEV_GOING_DOWN, dev);
1451
1452 clear_bit(__LINK_STATE_START, &dev->state);
1453
1454 /* Synchronize to scheduled poll. We cannot touch poll list, it
1455 * can be even on different cpu. So just clear netif_running().
1456 *
1457 * dev->stop() will invoke napi_disable() on all of it's
1458 * napi_struct instances on this device.
1459 */
1460 smp_mb__after_atomic(); /* Commit netif_running(). */
1461 }
1462
1463 dev_deactivate_many(head);
1464
1465 list_for_each_entry(dev, head, close_list) {
1466 const struct net_device_ops *ops = dev->netdev_ops;
1467
1468 /*
1469 * Call the device specific close. This cannot fail.
1470 * Only if device is UP
1471 *
1472 * We allow it to be called even after a DETACH hot-plug
1473 * event.
1474 */
1475 if (ops->ndo_stop)
1476 ops->ndo_stop(dev);
1477
1478 dev->flags &= ~IFF_UP;
1479 netpoll_poll_enable(dev);
1480 }
1481 }
1482
1483 static void __dev_close(struct net_device *dev)
1484 {
1485 LIST_HEAD(single);
1486
1487 list_add(&dev->close_list, &single);
1488 __dev_close_many(&single);
1489 list_del(&single);
1490 }
1491
1492 void dev_close_many(struct list_head *head, bool unlink)
1493 {
1494 struct net_device *dev, *tmp;
1495
1496 /* Remove the devices that don't need to be closed */
1497 list_for_each_entry_safe(dev, tmp, head, close_list)
1498 if (!(dev->flags & IFF_UP))
1499 list_del_init(&dev->close_list);
1500
1501 __dev_close_many(head);
1502
1503 list_for_each_entry_safe(dev, tmp, head, close_list) {
1504 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING, GFP_KERNEL);
1505 call_netdevice_notifiers(NETDEV_DOWN, dev);
1506 if (unlink)
1507 list_del_init(&dev->close_list);
1508 }
1509 }
1510 EXPORT_SYMBOL(dev_close_many);
1511
1512 /**
1513 * dev_close - shutdown an interface.
1514 * @dev: device to shutdown
1515 *
1516 * This function moves an active device into down state. A
1517 * %NETDEV_GOING_DOWN is sent to the netdev notifier chain. The device
1518 * is then deactivated and finally a %NETDEV_DOWN is sent to the notifier
1519 * chain.
1520 */
1521 void dev_close(struct net_device *dev)
1522 {
1523 if (dev->flags & IFF_UP) {
1524 LIST_HEAD(single);
1525
1526 list_add(&dev->close_list, &single);
1527 dev_close_many(&single, true);
1528 list_del(&single);
1529 }
1530 }
1531 EXPORT_SYMBOL(dev_close);
1532
1533
1534 /**
1535 * dev_disable_lro - disable Large Receive Offload on a device
1536 * @dev: device
1537 *
1538 * Disable Large Receive Offload (LRO) on a net device. Must be
1539 * called under RTNL. This is needed if received packets may be
1540 * forwarded to another interface.
1541 */
1542 void dev_disable_lro(struct net_device *dev)
1543 {
1544 struct net_device *lower_dev;
1545 struct list_head *iter;
1546
1547 dev->wanted_features &= ~NETIF_F_LRO;
1548 netdev_update_features(dev);
1549
1550 if (unlikely(dev->features & NETIF_F_LRO))
1551 netdev_WARN(dev, "failed to disable LRO!\n");
1552
1553 netdev_for_each_lower_dev(dev, lower_dev, iter)
1554 dev_disable_lro(lower_dev);
1555 }
1556 EXPORT_SYMBOL(dev_disable_lro);
1557
1558 static int call_netdevice_notifier(struct notifier_block *nb, unsigned long val,
1559 struct net_device *dev)
1560 {
1561 struct netdev_notifier_info info = {
1562 .dev = dev,
1563 };
1564
1565 return nb->notifier_call(nb, val, &info);
1566 }
1567
1568 static int dev_boot_phase = 1;
1569
1570 /**
1571 * register_netdevice_notifier - register a network notifier block
1572 * @nb: notifier
1573 *
1574 * Register a notifier to be called when network device events occur.
1575 * The notifier passed is linked into the kernel structures and must
1576 * not be reused until it has been unregistered. A negative errno code
1577 * is returned on a failure.
1578 *
1579 * When registered all registration and up events are replayed
1580 * to the new notifier to allow device to have a race free
1581 * view of the network device list.
1582 */
1583
1584 int register_netdevice_notifier(struct notifier_block *nb)
1585 {
1586 struct net_device *dev;
1587 struct net_device *last;
1588 struct net *net;
1589 int err;
1590
1591 rtnl_lock();
1592 err = raw_notifier_chain_register(&netdev_chain, nb);
1593 if (err)
1594 goto unlock;
1595 if (dev_boot_phase)
1596 goto unlock;
1597 for_each_net(net) {
1598 for_each_netdev(net, dev) {
1599 err = call_netdevice_notifier(nb, NETDEV_REGISTER, dev);
1600 err = notifier_to_errno(err);
1601 if (err)
1602 goto rollback;
1603
1604 if (!(dev->flags & IFF_UP))
1605 continue;
1606
1607 call_netdevice_notifier(nb, NETDEV_UP, dev);
1608 }
1609 }
1610
1611 unlock:
1612 rtnl_unlock();
1613 return err;
1614
1615 rollback:
1616 last = dev;
1617 for_each_net(net) {
1618 for_each_netdev(net, dev) {
1619 if (dev == last)
1620 goto outroll;
1621
1622 if (dev->flags & IFF_UP) {
1623 call_netdevice_notifier(nb, NETDEV_GOING_DOWN,
1624 dev);
1625 call_netdevice_notifier(nb, NETDEV_DOWN, dev);
1626 }
1627 call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev);
1628 }
1629 }
1630
1631 outroll:
1632 raw_notifier_chain_unregister(&netdev_chain, nb);
1633 goto unlock;
1634 }
1635 EXPORT_SYMBOL(register_netdevice_notifier);
1636
1637 /**
1638 * unregister_netdevice_notifier - unregister a network notifier block
1639 * @nb: notifier
1640 *
1641 * Unregister a notifier previously registered by
1642 * register_netdevice_notifier(). The notifier is unlinked into the
1643 * kernel structures and may then be reused. A negative errno code
1644 * is returned on a failure.
1645 *
1646 * After unregistering unregister and down device events are synthesized
1647 * for all devices on the device list to the removed notifier to remove
1648 * the need for special case cleanup code.
1649 */
1650
1651 int unregister_netdevice_notifier(struct notifier_block *nb)
1652 {
1653 struct net_device *dev;
1654 struct net *net;
1655 int err;
1656
1657 rtnl_lock();
1658 err = raw_notifier_chain_unregister(&netdev_chain, nb);
1659 if (err)
1660 goto unlock;
1661
1662 for_each_net(net) {
1663 for_each_netdev(net, dev) {
1664 if (dev->flags & IFF_UP) {
1665 call_netdevice_notifier(nb, NETDEV_GOING_DOWN,
1666 dev);
1667 call_netdevice_notifier(nb, NETDEV_DOWN, dev);
1668 }
1669 call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev);
1670 }
1671 }
1672 unlock:
1673 rtnl_unlock();
1674 return err;
1675 }
1676 EXPORT_SYMBOL(unregister_netdevice_notifier);
1677
1678 /**
1679 * call_netdevice_notifiers_info - call all network notifier blocks
1680 * @val: value passed unmodified to notifier function
1681 * @dev: net_device pointer passed unmodified to notifier function
1682 * @info: notifier information data
1683 *
1684 * Call all network notifier blocks. Parameters and return value
1685 * are as for raw_notifier_call_chain().
1686 */
1687
1688 static int call_netdevice_notifiers_info(unsigned long val,
1689 struct netdev_notifier_info *info)
1690 {
1691 ASSERT_RTNL();
1692 return raw_notifier_call_chain(&netdev_chain, val, info);
1693 }
1694
1695 /**
1696 * call_netdevice_notifiers - call all network notifier blocks
1697 * @val: value passed unmodified to notifier function
1698 * @dev: net_device pointer passed unmodified to notifier function
1699 *
1700 * Call all network notifier blocks. Parameters and return value
1701 * are as for raw_notifier_call_chain().
1702 */
1703
1704 int call_netdevice_notifiers(unsigned long val, struct net_device *dev)
1705 {
1706 struct netdev_notifier_info info = {
1707 .dev = dev,
1708 };
1709
1710 return call_netdevice_notifiers_info(val, &info);
1711 }
1712 EXPORT_SYMBOL(call_netdevice_notifiers);
1713
1714 /**
1715 * call_netdevice_notifiers_mtu - call all network notifier blocks
1716 * @val: value passed unmodified to notifier function
1717 * @dev: net_device pointer passed unmodified to notifier function
1718 * @arg: additional u32 argument passed to the notifier function
1719 *
1720 * Call all network notifier blocks. Parameters and return value
1721 * are as for raw_notifier_call_chain().
1722 */
1723 static int call_netdevice_notifiers_mtu(unsigned long val,
1724 struct net_device *dev, u32 arg)
1725 {
1726 struct netdev_notifier_info_ext info = {
1727 .info.dev = dev,
1728 .ext.mtu = arg,
1729 };
1730
1731 BUILD_BUG_ON(offsetof(struct netdev_notifier_info_ext, info) != 0);
1732
1733 return call_netdevice_notifiers_info(val, &info.info);
1734 }
1735
1736 #ifdef CONFIG_NET_INGRESS
1737 static struct static_key ingress_needed __read_mostly;
1738
1739 void net_inc_ingress_queue(void)
1740 {
1741 static_key_slow_inc(&ingress_needed);
1742 }
1743 EXPORT_SYMBOL_GPL(net_inc_ingress_queue);
1744
1745 void net_dec_ingress_queue(void)
1746 {
1747 static_key_slow_dec(&ingress_needed);
1748 }
1749 EXPORT_SYMBOL_GPL(net_dec_ingress_queue);
1750 #endif
1751
1752 #ifdef CONFIG_NET_EGRESS
1753 static struct static_key egress_needed __read_mostly;
1754
1755 void net_inc_egress_queue(void)
1756 {
1757 static_key_slow_inc(&egress_needed);
1758 }
1759 EXPORT_SYMBOL_GPL(net_inc_egress_queue);
1760
1761 void net_dec_egress_queue(void)
1762 {
1763 static_key_slow_dec(&egress_needed);
1764 }
1765 EXPORT_SYMBOL_GPL(net_dec_egress_queue);
1766 #endif
1767
1768 static struct static_key netstamp_needed __read_mostly;
1769 #ifdef HAVE_JUMP_LABEL
1770 static atomic_t netstamp_needed_deferred;
1771 static atomic_t netstamp_wanted;
1772 static void netstamp_clear(struct work_struct *work)
1773 {
1774 int deferred = atomic_xchg(&netstamp_needed_deferred, 0);
1775 int wanted;
1776
1777 wanted = atomic_add_return(deferred, &netstamp_wanted);
1778 if (wanted > 0)
1779 static_key_enable(&netstamp_needed);
1780 else
1781 static_key_disable(&netstamp_needed);
1782 }
1783 static DECLARE_WORK(netstamp_work, netstamp_clear);
1784 #endif
1785
1786 void net_enable_timestamp(void)
1787 {
1788 #ifdef HAVE_JUMP_LABEL
1789 int wanted;
1790
1791 while (1) {
1792 wanted = atomic_read(&netstamp_wanted);
1793 if (wanted <= 0)
1794 break;
1795 if (atomic_cmpxchg(&netstamp_wanted, wanted, wanted + 1) == wanted)
1796 return;
1797 }
1798 atomic_inc(&netstamp_needed_deferred);
1799 schedule_work(&netstamp_work);
1800 #else
1801 static_key_slow_inc(&netstamp_needed);
1802 #endif
1803 }
1804 EXPORT_SYMBOL(net_enable_timestamp);
1805
1806 void net_disable_timestamp(void)
1807 {
1808 #ifdef HAVE_JUMP_LABEL
1809 int wanted;
1810
1811 while (1) {
1812 wanted = atomic_read(&netstamp_wanted);
1813 if (wanted <= 1)
1814 break;
1815 if (atomic_cmpxchg(&netstamp_wanted, wanted, wanted - 1) == wanted)
1816 return;
1817 }
1818 atomic_dec(&netstamp_needed_deferred);
1819 schedule_work(&netstamp_work);
1820 #else
1821 static_key_slow_dec(&netstamp_needed);
1822 #endif
1823 }
1824 EXPORT_SYMBOL(net_disable_timestamp);
1825
1826 static inline void net_timestamp_set(struct sk_buff *skb)
1827 {
1828 skb->tstamp = 0;
1829 if (static_key_false(&netstamp_needed))
1830 __net_timestamp(skb);
1831 }
1832
1833 #define net_timestamp_check(COND, SKB) \
1834 if (static_key_false(&netstamp_needed)) { \
1835 if ((COND) && !(SKB)->tstamp) \
1836 __net_timestamp(SKB); \
1837 } \
1838
1839 bool is_skb_forwardable(const struct net_device *dev, const struct sk_buff *skb)
1840 {
1841 unsigned int len;
1842
1843 if (!(dev->flags & IFF_UP))
1844 return false;
1845
1846 len = dev->mtu + dev->hard_header_len + VLAN_HLEN;
1847 if (skb->len <= len)
1848 return true;
1849
1850 /* if TSO is enabled, we don't care about the length as the packet
1851 * could be forwarded without being segmented before
1852 */
1853 if (skb_is_gso(skb))
1854 return true;
1855
1856 return false;
1857 }
1858 EXPORT_SYMBOL_GPL(is_skb_forwardable);
1859
1860 int __dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
1861 {
1862 int ret = ____dev_forward_skb(dev, skb);
1863
1864 if (likely(!ret)) {
1865 skb->protocol = eth_type_trans(skb, dev);
1866 skb_postpull_rcsum(skb, eth_hdr(skb), ETH_HLEN);
1867 }
1868
1869 return ret;
1870 }
1871 EXPORT_SYMBOL_GPL(__dev_forward_skb);
1872
1873 /**
1874 * dev_forward_skb - loopback an skb to another netif
1875 *
1876 * @dev: destination network device
1877 * @skb: buffer to forward
1878 *
1879 * return values:
1880 * NET_RX_SUCCESS (no congestion)
1881 * NET_RX_DROP (packet was dropped, but freed)
1882 *
1883 * dev_forward_skb can be used for injecting an skb from the
1884 * start_xmit function of one device into the receive queue
1885 * of another device.
1886 *
1887 * The receiving device may be in another namespace, so
1888 * we have to clear all information in the skb that could
1889 * impact namespace isolation.
1890 */
1891 int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
1892 {
1893 return __dev_forward_skb(dev, skb) ?: netif_rx_internal(skb);
1894 }
1895 EXPORT_SYMBOL_GPL(dev_forward_skb);
1896
1897 static inline int deliver_skb(struct sk_buff *skb,
1898 struct packet_type *pt_prev,
1899 struct net_device *orig_dev)
1900 {
1901 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
1902 return -ENOMEM;
1903 refcount_inc(&skb->users);
1904 return pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
1905 }
1906
1907 static inline void deliver_ptype_list_skb(struct sk_buff *skb,
1908 struct packet_type **pt,
1909 struct net_device *orig_dev,
1910 __be16 type,
1911 struct list_head *ptype_list)
1912 {
1913 struct packet_type *ptype, *pt_prev = *pt;
1914
1915 list_for_each_entry_rcu(ptype, ptype_list, list) {
1916 if (ptype->type != type)
1917 continue;
1918 if (pt_prev)
1919 deliver_skb(skb, pt_prev, orig_dev);
1920 pt_prev = ptype;
1921 }
1922 *pt = pt_prev;
1923 }
1924
1925 static inline bool skb_loop_sk(struct packet_type *ptype, struct sk_buff *skb)
1926 {
1927 if (!ptype->af_packet_priv || !skb->sk)
1928 return false;
1929
1930 if (ptype->id_match)
1931 return ptype->id_match(ptype, skb->sk);
1932 else if ((struct sock *)ptype->af_packet_priv == skb->sk)
1933 return true;
1934
1935 return false;
1936 }
1937
1938 /*
1939 * Support routine. Sends outgoing frames to any network
1940 * taps currently in use.
1941 */
1942
1943 void dev_queue_xmit_nit(struct sk_buff *skb, struct net_device *dev)
1944 {
1945 struct packet_type *ptype;
1946 struct sk_buff *skb2 = NULL;
1947 struct packet_type *pt_prev = NULL;
1948 struct list_head *ptype_list = &ptype_all;
1949
1950 rcu_read_lock();
1951 again:
1952 list_for_each_entry_rcu(ptype, ptype_list, list) {
1953 /* Never send packets back to the socket
1954 * they originated from - MvS (miquels@drinkel.ow.org)
1955 */
1956 if (skb_loop_sk(ptype, skb))
1957 continue;
1958
1959 if (pt_prev) {
1960 deliver_skb(skb2, pt_prev, skb->dev);
1961 pt_prev = ptype;
1962 continue;
1963 }
1964
1965 /* need to clone skb, done only once */
1966 skb2 = skb_clone(skb, GFP_ATOMIC);
1967 if (!skb2)
1968 goto out_unlock;
1969
1970 net_timestamp_set(skb2);
1971
1972 /* skb->nh should be correctly
1973 * set by sender, so that the second statement is
1974 * just protection against buggy protocols.
1975 */
1976 skb_reset_mac_header(skb2);
1977
1978 if (skb_network_header(skb2) < skb2->data ||
1979 skb_network_header(skb2) > skb_tail_pointer(skb2)) {
1980 net_crit_ratelimited("protocol %04x is buggy, dev %s\n",
1981 ntohs(skb2->protocol),
1982 dev->name);
1983 skb_reset_network_header(skb2);
1984 }
1985
1986 skb2->transport_header = skb2->network_header;
1987 skb2->pkt_type = PACKET_OUTGOING;
1988 pt_prev = ptype;
1989 }
1990
1991 if (ptype_list == &ptype_all) {
1992 ptype_list = &dev->ptype_all;
1993 goto again;
1994 }
1995 out_unlock:
1996 if (pt_prev) {
1997 if (!skb_orphan_frags_rx(skb2, GFP_ATOMIC))
1998 pt_prev->func(skb2, skb->dev, pt_prev, skb->dev);
1999 else
2000 kfree_skb(skb2);
2001 }
2002 rcu_read_unlock();
2003 }
2004 EXPORT_SYMBOL_GPL(dev_queue_xmit_nit);
2005
2006 /**
2007 * netif_setup_tc - Handle tc mappings on real_num_tx_queues change
2008 * @dev: Network device
2009 * @txq: number of queues available
2010 *
2011 * If real_num_tx_queues is changed the tc mappings may no longer be
2012 * valid. To resolve this verify the tc mapping remains valid and if
2013 * not NULL the mapping. With no priorities mapping to this
2014 * offset/count pair it will no longer be used. In the worst case TC0
2015 * is invalid nothing can be done so disable priority mappings. If is
2016 * expected that drivers will fix this mapping if they can before
2017 * calling netif_set_real_num_tx_queues.
2018 */
2019 static void netif_setup_tc(struct net_device *dev, unsigned int txq)
2020 {
2021 int i;
2022 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2023
2024 /* If TC0 is invalidated disable TC mapping */
2025 if (tc->offset + tc->count > txq) {
2026 pr_warn("Number of in use tx queues changed invalidating tc mappings. Priority traffic classification disabled!\n");
2027 dev->num_tc = 0;
2028 return;
2029 }
2030
2031 /* Invalidated prio to tc mappings set to TC0 */
2032 for (i = 1; i < TC_BITMASK + 1; i++) {
2033 int q = netdev_get_prio_tc_map(dev, i);
2034
2035 tc = &dev->tc_to_txq[q];
2036 if (tc->offset + tc->count > txq) {
2037 pr_warn("Number of in use tx queues changed. Priority %i to tc mapping %i is no longer valid. Setting map to 0\n",
2038 i, q);
2039 netdev_set_prio_tc_map(dev, i, 0);
2040 }
2041 }
2042 }
2043
2044 int netdev_txq_to_tc(struct net_device *dev, unsigned int txq)
2045 {
2046 if (dev->num_tc) {
2047 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2048 int i;
2049
2050 for (i = 0; i < TC_MAX_QUEUE; i++, tc++) {
2051 if ((txq - tc->offset) < tc->count)
2052 return i;
2053 }
2054
2055 return -1;
2056 }
2057
2058 return 0;
2059 }
2060 EXPORT_SYMBOL(netdev_txq_to_tc);
2061
2062 #ifdef CONFIG_XPS
2063 static DEFINE_MUTEX(xps_map_mutex);
2064 #define xmap_dereference(P) \
2065 rcu_dereference_protected((P), lockdep_is_held(&xps_map_mutex))
2066
2067 static bool remove_xps_queue(struct xps_dev_maps *dev_maps,
2068 int tci, u16 index)
2069 {
2070 struct xps_map *map = NULL;
2071 int pos;
2072
2073 if (dev_maps)
2074 map = xmap_dereference(dev_maps->cpu_map[tci]);
2075 if (!map)
2076 return false;
2077
2078 for (pos = map->len; pos--;) {
2079 if (map->queues[pos] != index)
2080 continue;
2081
2082 if (map->len > 1) {
2083 map->queues[pos] = map->queues[--map->len];
2084 break;
2085 }
2086
2087 RCU_INIT_POINTER(dev_maps->cpu_map[tci], NULL);
2088 kfree_rcu(map, rcu);
2089 return false;
2090 }
2091
2092 return true;
2093 }
2094
2095 static bool remove_xps_queue_cpu(struct net_device *dev,
2096 struct xps_dev_maps *dev_maps,
2097 int cpu, u16 offset, u16 count)
2098 {
2099 int num_tc = dev->num_tc ? : 1;
2100 bool active = false;
2101 int tci;
2102
2103 for (tci = cpu * num_tc; num_tc--; tci++) {
2104 int i, j;
2105
2106 for (i = count, j = offset; i--; j++) {
2107 if (!remove_xps_queue(dev_maps, tci, j))
2108 break;
2109 }
2110
2111 active |= i < 0;
2112 }
2113
2114 return active;
2115 }
2116
2117 static void netif_reset_xps_queues(struct net_device *dev, u16 offset,
2118 u16 count)
2119 {
2120 struct xps_dev_maps *dev_maps;
2121 int cpu, i;
2122 bool active = false;
2123
2124 mutex_lock(&xps_map_mutex);
2125 dev_maps = xmap_dereference(dev->xps_maps);
2126
2127 if (!dev_maps)
2128 goto out_no_maps;
2129
2130 for_each_possible_cpu(cpu)
2131 active |= remove_xps_queue_cpu(dev, dev_maps, cpu,
2132 offset, count);
2133
2134 if (!active) {
2135 RCU_INIT_POINTER(dev->xps_maps, NULL);
2136 kfree_rcu(dev_maps, rcu);
2137 }
2138
2139 for (i = offset + (count - 1); count--; i--)
2140 netdev_queue_numa_node_write(netdev_get_tx_queue(dev, i),
2141 NUMA_NO_NODE);
2142
2143 out_no_maps:
2144 mutex_unlock(&xps_map_mutex);
2145 }
2146
2147 static void netif_reset_xps_queues_gt(struct net_device *dev, u16 index)
2148 {
2149 netif_reset_xps_queues(dev, index, dev->num_tx_queues - index);
2150 }
2151
2152 static struct xps_map *expand_xps_map(struct xps_map *map,
2153 int cpu, u16 index)
2154 {
2155 struct xps_map *new_map;
2156 int alloc_len = XPS_MIN_MAP_ALLOC;
2157 int i, pos;
2158
2159 for (pos = 0; map && pos < map->len; pos++) {
2160 if (map->queues[pos] != index)
2161 continue;
2162 return map;
2163 }
2164
2165 /* Need to add queue to this CPU's existing map */
2166 if (map) {
2167 if (pos < map->alloc_len)
2168 return map;
2169
2170 alloc_len = map->alloc_len * 2;
2171 }
2172
2173 /* Need to allocate new map to store queue on this CPU's map */
2174 new_map = kzalloc_node(XPS_MAP_SIZE(alloc_len), GFP_KERNEL,
2175 cpu_to_node(cpu));
2176 if (!new_map)
2177 return NULL;
2178
2179 for (i = 0; i < pos; i++)
2180 new_map->queues[i] = map->queues[i];
2181 new_map->alloc_len = alloc_len;
2182 new_map->len = pos;
2183
2184 return new_map;
2185 }
2186
2187 int netif_set_xps_queue(struct net_device *dev, const struct cpumask *mask,
2188 u16 index)
2189 {
2190 struct xps_dev_maps *dev_maps, *new_dev_maps = NULL;
2191 int i, cpu, tci, numa_node_id = -2;
2192 int maps_sz, num_tc = 1, tc = 0;
2193 struct xps_map *map, *new_map;
2194 bool active = false;
2195
2196 if (dev->num_tc) {
2197 num_tc = dev->num_tc;
2198 tc = netdev_txq_to_tc(dev, index);
2199 if (tc < 0)
2200 return -EINVAL;
2201 }
2202
2203 maps_sz = XPS_DEV_MAPS_SIZE(num_tc);
2204 if (maps_sz < L1_CACHE_BYTES)
2205 maps_sz = L1_CACHE_BYTES;
2206
2207 mutex_lock(&xps_map_mutex);
2208
2209 dev_maps = xmap_dereference(dev->xps_maps);
2210
2211 /* allocate memory for queue storage */
2212 for_each_cpu_and(cpu, cpu_online_mask, mask) {
2213 if (!new_dev_maps)
2214 new_dev_maps = kzalloc(maps_sz, GFP_KERNEL);
2215 if (!new_dev_maps) {
2216 mutex_unlock(&xps_map_mutex);
2217 return -ENOMEM;
2218 }
2219
2220 tci = cpu * num_tc + tc;
2221 map = dev_maps ? xmap_dereference(dev_maps->cpu_map[tci]) :
2222 NULL;
2223
2224 map = expand_xps_map(map, cpu, index);
2225 if (!map)
2226 goto error;
2227
2228 RCU_INIT_POINTER(new_dev_maps->cpu_map[tci], map);
2229 }
2230
2231 if (!new_dev_maps)
2232 goto out_no_new_maps;
2233
2234 for_each_possible_cpu(cpu) {
2235 /* copy maps belonging to foreign traffic classes */
2236 for (i = tc, tci = cpu * num_tc; dev_maps && i--; tci++) {
2237 /* fill in the new device map from the old device map */
2238 map = xmap_dereference(dev_maps->cpu_map[tci]);
2239 RCU_INIT_POINTER(new_dev_maps->cpu_map[tci], map);
2240 }
2241
2242 /* We need to explicitly update tci as prevous loop
2243 * could break out early if dev_maps is NULL.
2244 */
2245 tci = cpu * num_tc + tc;
2246
2247 if (cpumask_test_cpu(cpu, mask) && cpu_online(cpu)) {
2248 /* add queue to CPU maps */
2249 int pos = 0;
2250
2251 map = xmap_dereference(new_dev_maps->cpu_map[tci]);
2252 while ((pos < map->len) && (map->queues[pos] != index))
2253 pos++;
2254
2255 if (pos == map->len)
2256 map->queues[map->len++] = index;
2257 #ifdef CONFIG_NUMA
2258 if (numa_node_id == -2)
2259 numa_node_id = cpu_to_node(cpu);
2260 else if (numa_node_id != cpu_to_node(cpu))
2261 numa_node_id = -1;
2262 #endif
2263 } else if (dev_maps) {
2264 /* fill in the new device map from the old device map */
2265 map = xmap_dereference(dev_maps->cpu_map[tci]);
2266 RCU_INIT_POINTER(new_dev_maps->cpu_map[tci], map);
2267 }
2268
2269 /* copy maps belonging to foreign traffic classes */
2270 for (i = num_tc - tc, tci++; dev_maps && --i; tci++) {
2271 /* fill in the new device map from the old device map */
2272 map = xmap_dereference(dev_maps->cpu_map[tci]);
2273 RCU_INIT_POINTER(new_dev_maps->cpu_map[tci], map);
2274 }
2275 }
2276
2277 rcu_assign_pointer(dev->xps_maps, new_dev_maps);
2278
2279 /* Cleanup old maps */
2280 if (!dev_maps)
2281 goto out_no_old_maps;
2282
2283 for_each_possible_cpu(cpu) {
2284 for (i = num_tc, tci = cpu * num_tc; i--; tci++) {
2285 new_map = xmap_dereference(new_dev_maps->cpu_map[tci]);
2286 map = xmap_dereference(dev_maps->cpu_map[tci]);
2287 if (map && map != new_map)
2288 kfree_rcu(map, rcu);
2289 }
2290 }
2291
2292 kfree_rcu(dev_maps, rcu);
2293
2294 out_no_old_maps:
2295 dev_maps = new_dev_maps;
2296 active = true;
2297
2298 out_no_new_maps:
2299 /* update Tx queue numa node */
2300 netdev_queue_numa_node_write(netdev_get_tx_queue(dev, index),
2301 (numa_node_id >= 0) ? numa_node_id :
2302 NUMA_NO_NODE);
2303
2304 if (!dev_maps)
2305 goto out_no_maps;
2306
2307 /* removes queue from unused CPUs */
2308 for_each_possible_cpu(cpu) {
2309 for (i = tc, tci = cpu * num_tc; i--; tci++)
2310 active |= remove_xps_queue(dev_maps, tci, index);
2311 if (!cpumask_test_cpu(cpu, mask) || !cpu_online(cpu))
2312 active |= remove_xps_queue(dev_maps, tci, index);
2313 for (i = num_tc - tc, tci++; --i; tci++)
2314 active |= remove_xps_queue(dev_maps, tci, index);
2315 }
2316
2317 /* free map if not active */
2318 if (!active) {
2319 RCU_INIT_POINTER(dev->xps_maps, NULL);
2320 kfree_rcu(dev_maps, rcu);
2321 }
2322
2323 out_no_maps:
2324 mutex_unlock(&xps_map_mutex);
2325
2326 return 0;
2327 error:
2328 /* remove any maps that we added */
2329 for_each_possible_cpu(cpu) {
2330 for (i = num_tc, tci = cpu * num_tc; i--; tci++) {
2331 new_map = xmap_dereference(new_dev_maps->cpu_map[tci]);
2332 map = dev_maps ?
2333 xmap_dereference(dev_maps->cpu_map[tci]) :
2334 NULL;
2335 if (new_map && new_map != map)
2336 kfree(new_map);
2337 }
2338 }
2339
2340 mutex_unlock(&xps_map_mutex);
2341
2342 kfree(new_dev_maps);
2343 return -ENOMEM;
2344 }
2345 EXPORT_SYMBOL(netif_set_xps_queue);
2346
2347 #endif
2348 void netdev_reset_tc(struct net_device *dev)
2349 {
2350 #ifdef CONFIG_XPS
2351 netif_reset_xps_queues_gt(dev, 0);
2352 #endif
2353 dev->num_tc = 0;
2354 memset(dev->tc_to_txq, 0, sizeof(dev->tc_to_txq));
2355 memset(dev->prio_tc_map, 0, sizeof(dev->prio_tc_map));
2356 }
2357 EXPORT_SYMBOL(netdev_reset_tc);
2358
2359 int netdev_set_tc_queue(struct net_device *dev, u8 tc, u16 count, u16 offset)
2360 {
2361 if (tc >= dev->num_tc)
2362 return -EINVAL;
2363
2364 #ifdef CONFIG_XPS
2365 netif_reset_xps_queues(dev, offset, count);
2366 #endif
2367 dev->tc_to_txq[tc].count = count;
2368 dev->tc_to_txq[tc].offset = offset;
2369 return 0;
2370 }
2371 EXPORT_SYMBOL(netdev_set_tc_queue);
2372
2373 int netdev_set_num_tc(struct net_device *dev, u8 num_tc)
2374 {
2375 if (num_tc > TC_MAX_QUEUE)
2376 return -EINVAL;
2377
2378 #ifdef CONFIG_XPS
2379 netif_reset_xps_queues_gt(dev, 0);
2380 #endif
2381 dev->num_tc = num_tc;
2382 return 0;
2383 }
2384 EXPORT_SYMBOL(netdev_set_num_tc);
2385
2386 /*
2387 * Routine to help set real_num_tx_queues. To avoid skbs mapped to queues
2388 * greater then real_num_tx_queues stale skbs on the qdisc must be flushed.
2389 */
2390 int netif_set_real_num_tx_queues(struct net_device *dev, unsigned int txq)
2391 {
2392 bool disabling;
2393 int rc;
2394
2395 disabling = txq < dev->real_num_tx_queues;
2396
2397 if (txq < 1 || txq > dev->num_tx_queues)
2398 return -EINVAL;
2399
2400 if (dev->reg_state == NETREG_REGISTERED ||
2401 dev->reg_state == NETREG_UNREGISTERING) {
2402 ASSERT_RTNL();
2403
2404 rc = netdev_queue_update_kobjects(dev, dev->real_num_tx_queues,
2405 txq);
2406 if (rc)
2407 return rc;
2408
2409 if (dev->num_tc)
2410 netif_setup_tc(dev, txq);
2411
2412 dev->real_num_tx_queues = txq;
2413
2414 if (disabling) {
2415 synchronize_net();
2416 qdisc_reset_all_tx_gt(dev, txq);
2417 #ifdef CONFIG_XPS
2418 netif_reset_xps_queues_gt(dev, txq);
2419 #endif
2420 }
2421 } else {
2422 dev->real_num_tx_queues = txq;
2423 }
2424
2425 return 0;
2426 }
2427 EXPORT_SYMBOL(netif_set_real_num_tx_queues);
2428
2429 #ifdef CONFIG_SYSFS
2430 /**
2431 * netif_set_real_num_rx_queues - set actual number of RX queues used
2432 * @dev: Network device
2433 * @rxq: Actual number of RX queues
2434 *
2435 * This must be called either with the rtnl_lock held or before
2436 * registration of the net device. Returns 0 on success, or a
2437 * negative error code. If called before registration, it always
2438 * succeeds.
2439 */
2440 int netif_set_real_num_rx_queues(struct net_device *dev, unsigned int rxq)
2441 {
2442 int rc;
2443
2444 if (rxq < 1 || rxq > dev->num_rx_queues)
2445 return -EINVAL;
2446
2447 if (dev->reg_state == NETREG_REGISTERED) {
2448 ASSERT_RTNL();
2449
2450 rc = net_rx_queue_update_kobjects(dev, dev->real_num_rx_queues,
2451 rxq);
2452 if (rc)
2453 return rc;
2454 }
2455
2456 dev->real_num_rx_queues = rxq;
2457 return 0;
2458 }
2459 EXPORT_SYMBOL(netif_set_real_num_rx_queues);
2460 #endif
2461
2462 /**
2463 * netif_get_num_default_rss_queues - default number of RSS queues
2464 *
2465 * This routine should set an upper limit on the number of RSS queues
2466 * used by default by multiqueue devices.
2467 */
2468 int netif_get_num_default_rss_queues(void)
2469 {
2470 return is_kdump_kernel() ?
2471 1 : min_t(int, DEFAULT_MAX_NUM_RSS_QUEUES, num_online_cpus());
2472 }
2473 EXPORT_SYMBOL(netif_get_num_default_rss_queues);
2474
2475 static void __netif_reschedule(struct Qdisc *q)
2476 {
2477 struct softnet_data *sd;
2478 unsigned long flags;
2479
2480 local_irq_save(flags);
2481 sd = this_cpu_ptr(&softnet_data);
2482 q->next_sched = NULL;
2483 *sd->output_queue_tailp = q;
2484 sd->output_queue_tailp = &q->next_sched;
2485 raise_softirq_irqoff(NET_TX_SOFTIRQ);
2486 local_irq_restore(flags);
2487 }
2488
2489 void __netif_schedule(struct Qdisc *q)
2490 {
2491 if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state))
2492 __netif_reschedule(q);
2493 }
2494 EXPORT_SYMBOL(__netif_schedule);
2495
2496 struct dev_kfree_skb_cb {
2497 enum skb_free_reason reason;
2498 };
2499
2500 static struct dev_kfree_skb_cb *get_kfree_skb_cb(const struct sk_buff *skb)
2501 {
2502 return (struct dev_kfree_skb_cb *)skb->cb;
2503 }
2504
2505 void netif_schedule_queue(struct netdev_queue *txq)
2506 {
2507 rcu_read_lock();
2508 if (!(txq->state & QUEUE_STATE_ANY_XOFF)) {
2509 struct Qdisc *q = rcu_dereference(txq->qdisc);
2510
2511 __netif_schedule(q);
2512 }
2513 rcu_read_unlock();
2514 }
2515 EXPORT_SYMBOL(netif_schedule_queue);
2516
2517 void netif_tx_wake_queue(struct netdev_queue *dev_queue)
2518 {
2519 if (test_and_clear_bit(__QUEUE_STATE_DRV_XOFF, &dev_queue->state)) {
2520 struct Qdisc *q;
2521
2522 rcu_read_lock();
2523 q = rcu_dereference(dev_queue->qdisc);
2524 __netif_schedule(q);
2525 rcu_read_unlock();
2526 }
2527 }
2528 EXPORT_SYMBOL(netif_tx_wake_queue);
2529
2530 void __dev_kfree_skb_irq(struct sk_buff *skb, enum skb_free_reason reason)
2531 {
2532 unsigned long flags;
2533
2534 if (unlikely(!skb))
2535 return;
2536
2537 if (likely(refcount_read(&skb->users) == 1)) {
2538 smp_rmb();
2539 refcount_set(&skb->users, 0);
2540 } else if (likely(!refcount_dec_and_test(&skb->users))) {
2541 return;
2542 }
2543 get_kfree_skb_cb(skb)->reason = reason;
2544 local_irq_save(flags);
2545 skb->next = __this_cpu_read(softnet_data.completion_queue);
2546 __this_cpu_write(softnet_data.completion_queue, skb);
2547 raise_softirq_irqoff(NET_TX_SOFTIRQ);
2548 local_irq_restore(flags);
2549 }
2550 EXPORT_SYMBOL(__dev_kfree_skb_irq);
2551
2552 void __dev_kfree_skb_any(struct sk_buff *skb, enum skb_free_reason reason)
2553 {
2554 if (in_irq() || irqs_disabled())
2555 __dev_kfree_skb_irq(skb, reason);
2556 else
2557 dev_kfree_skb(skb);
2558 }
2559 EXPORT_SYMBOL(__dev_kfree_skb_any);
2560
2561
2562 /**
2563 * netif_device_detach - mark device as removed
2564 * @dev: network device
2565 *
2566 * Mark device as removed from system and therefore no longer available.
2567 */
2568 void netif_device_detach(struct net_device *dev)
2569 {
2570 if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) &&
2571 netif_running(dev)) {
2572 netif_tx_stop_all_queues(dev);
2573 }
2574 }
2575 EXPORT_SYMBOL(netif_device_detach);
2576
2577 /**
2578 * netif_device_attach - mark device as attached
2579 * @dev: network device
2580 *
2581 * Mark device as attached from system and restart if needed.
2582 */
2583 void netif_device_attach(struct net_device *dev)
2584 {
2585 if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) &&
2586 netif_running(dev)) {
2587 netif_tx_wake_all_queues(dev);
2588 __netdev_watchdog_up(dev);
2589 }
2590 }
2591 EXPORT_SYMBOL(netif_device_attach);
2592
2593 /*
2594 * Returns a Tx hash based on the given packet descriptor a Tx queues' number
2595 * to be used as a distribution range.
2596 */
2597 u16 __skb_tx_hash(const struct net_device *dev, struct sk_buff *skb,
2598 unsigned int num_tx_queues)
2599 {
2600 u32 hash;
2601 u16 qoffset = 0;
2602 u16 qcount = num_tx_queues;
2603
2604 if (skb_rx_queue_recorded(skb)) {
2605 hash = skb_get_rx_queue(skb);
2606 while (unlikely(hash >= num_tx_queues))
2607 hash -= num_tx_queues;
2608 return hash;
2609 }
2610
2611 if (dev->num_tc) {
2612 u8 tc = netdev_get_prio_tc_map(dev, skb->priority);
2613
2614 qoffset = dev->tc_to_txq[tc].offset;
2615 qcount = dev->tc_to_txq[tc].count;
2616 }
2617
2618 return (u16) reciprocal_scale(skb_get_hash(skb), qcount) + qoffset;
2619 }
2620 EXPORT_SYMBOL(__skb_tx_hash);
2621
2622 static void skb_warn_bad_offload(const struct sk_buff *skb)
2623 {
2624 static const netdev_features_t null_features;
2625 struct net_device *dev = skb->dev;
2626 const char *name = "";
2627
2628 if (!net_ratelimit())
2629 return;
2630
2631 if (dev) {
2632 if (dev->dev.parent)
2633 name = dev_driver_string(dev->dev.parent);
2634 else
2635 name = netdev_name(dev);
2636 }
2637 WARN(1, "%s: caps=(%pNF, %pNF) len=%d data_len=%d gso_size=%d "
2638 "gso_type=%d ip_summed=%d\n",
2639 name, dev ? &dev->features : &null_features,
2640 skb->sk ? &skb->sk->sk_route_caps : &null_features,
2641 skb->len, skb->data_len, skb_shinfo(skb)->gso_size,
2642 skb_shinfo(skb)->gso_type, skb->ip_summed);
2643 }
2644
2645 /*
2646 * Invalidate hardware checksum when packet is to be mangled, and
2647 * complete checksum manually on outgoing path.
2648 */
2649 int skb_checksum_help(struct sk_buff *skb)
2650 {
2651 __wsum csum;
2652 int ret = 0, offset;
2653
2654 if (skb->ip_summed == CHECKSUM_COMPLETE)
2655 goto out_set_summed;
2656
2657 if (unlikely(skb_shinfo(skb)->gso_size)) {
2658 skb_warn_bad_offload(skb);
2659 return -EINVAL;
2660 }
2661
2662 /* Before computing a checksum, we should make sure no frag could
2663 * be modified by an external entity : checksum could be wrong.
2664 */
2665 if (skb_has_shared_frag(skb)) {
2666 ret = __skb_linearize(skb);
2667 if (ret)
2668 goto out;
2669 }
2670
2671 offset = skb_checksum_start_offset(skb);
2672 BUG_ON(offset >= skb_headlen(skb));
2673 csum = skb_checksum(skb, offset, skb->len - offset, 0);
2674
2675 offset += skb->csum_offset;
2676 BUG_ON(offset + sizeof(__sum16) > skb_headlen(skb));
2677
2678 if (skb_cloned(skb) &&
2679 !skb_clone_writable(skb, offset + sizeof(__sum16))) {
2680 ret = pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
2681 if (ret)
2682 goto out;
2683 }
2684
2685 *(__sum16 *)(skb->data + offset) = csum_fold(csum) ?: CSUM_MANGLED_0;
2686 out_set_summed:
2687 skb->ip_summed = CHECKSUM_NONE;
2688 out:
2689 return ret;
2690 }
2691 EXPORT_SYMBOL(skb_checksum_help);
2692
2693 int skb_crc32c_csum_help(struct sk_buff *skb)
2694 {
2695 __le32 crc32c_csum;
2696 int ret = 0, offset, start;
2697
2698 if (skb->ip_summed != CHECKSUM_PARTIAL)
2699 goto out;
2700
2701 if (unlikely(skb_is_gso(skb)))
2702 goto out;
2703
2704 /* Before computing a checksum, we should make sure no frag could
2705 * be modified by an external entity : checksum could be wrong.
2706 */
2707 if (unlikely(skb_has_shared_frag(skb))) {
2708 ret = __skb_linearize(skb);
2709 if (ret)
2710 goto out;
2711 }
2712 start = skb_checksum_start_offset(skb);
2713 offset = start + offsetof(struct sctphdr, checksum);
2714 if (WARN_ON_ONCE(offset >= skb_headlen(skb))) {
2715 ret = -EINVAL;
2716 goto out;
2717 }
2718 if (skb_cloned(skb) &&
2719 !skb_clone_writable(skb, offset + sizeof(__le32))) {
2720 ret = pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
2721 if (ret)
2722 goto out;
2723 }
2724 crc32c_csum = cpu_to_le32(~__skb_checksum(skb, start,
2725 skb->len - start, ~(__u32)0,
2726 crc32c_csum_stub));
2727 *(__le32 *)(skb->data + offset) = crc32c_csum;
2728 skb->ip_summed = CHECKSUM_NONE;
2729 skb->csum_not_inet = 0;
2730 out:
2731 return ret;
2732 }
2733
2734 __be16 skb_network_protocol(struct sk_buff *skb, int *depth)
2735 {
2736 __be16 type = skb->protocol;
2737
2738 /* Tunnel gso handlers can set protocol to ethernet. */
2739 if (type == htons(ETH_P_TEB)) {
2740 struct ethhdr *eth;
2741
2742 if (unlikely(!pskb_may_pull(skb, sizeof(struct ethhdr))))
2743 return 0;
2744
2745 eth = (struct ethhdr *)skb->data;
2746 type = eth->h_proto;
2747 }
2748
2749 return __vlan_get_protocol(skb, type, depth);
2750 }
2751
2752 /**
2753 * skb_mac_gso_segment - mac layer segmentation handler.
2754 * @skb: buffer to segment
2755 * @features: features for the output path (see dev->features)
2756 */
2757 struct sk_buff *skb_mac_gso_segment(struct sk_buff *skb,
2758 netdev_features_t features)
2759 {
2760 struct sk_buff *segs = ERR_PTR(-EPROTONOSUPPORT);
2761 struct packet_offload *ptype;
2762 int vlan_depth = skb->mac_len;
2763 __be16 type = skb_network_protocol(skb, &vlan_depth);
2764
2765 if (unlikely(!type))
2766 return ERR_PTR(-EINVAL);
2767
2768 __skb_pull(skb, vlan_depth);
2769
2770 rcu_read_lock();
2771 list_for_each_entry_rcu(ptype, &offload_base, list) {
2772 if (ptype->type == type && ptype->callbacks.gso_segment) {
2773 segs = ptype->callbacks.gso_segment(skb, features);
2774 break;
2775 }
2776 }
2777 rcu_read_unlock();
2778
2779 __skb_push(skb, skb->data - skb_mac_header(skb));
2780
2781 return segs;
2782 }
2783 EXPORT_SYMBOL(skb_mac_gso_segment);
2784
2785
2786 /* openvswitch calls this on rx path, so we need a different check.
2787 */
2788 static inline bool skb_needs_check(struct sk_buff *skb, bool tx_path)
2789 {
2790 if (tx_path)
2791 return skb->ip_summed != CHECKSUM_PARTIAL &&
2792 skb->ip_summed != CHECKSUM_UNNECESSARY;
2793
2794 return skb->ip_summed == CHECKSUM_NONE;
2795 }
2796
2797 /**
2798 * __skb_gso_segment - Perform segmentation on skb.
2799 * @skb: buffer to segment
2800 * @features: features for the output path (see dev->features)
2801 * @tx_path: whether it is called in TX path
2802 *
2803 * This function segments the given skb and returns a list of segments.
2804 *
2805 * It may return NULL if the skb requires no segmentation. This is
2806 * only possible when GSO is used for verifying header integrity.
2807 *
2808 * Segmentation preserves SKB_SGO_CB_OFFSET bytes of previous skb cb.
2809 */
2810 struct sk_buff *__skb_gso_segment(struct sk_buff *skb,
2811 netdev_features_t features, bool tx_path)
2812 {
2813 struct sk_buff *segs;
2814
2815 if (unlikely(skb_needs_check(skb, tx_path))) {
2816 int err;
2817
2818 /* We're going to init ->check field in TCP or UDP header */
2819 err = skb_cow_head(skb, 0);
2820 if (err < 0)
2821 return ERR_PTR(err);
2822 }
2823
2824 /* Only report GSO partial support if it will enable us to
2825 * support segmentation on this frame without needing additional
2826 * work.
2827 */
2828 if (features & NETIF_F_GSO_PARTIAL) {
2829 netdev_features_t partial_features = NETIF_F_GSO_ROBUST;
2830 struct net_device *dev = skb->dev;
2831
2832 partial_features |= dev->features & dev->gso_partial_features;
2833 if (!skb_gso_ok(skb, features | partial_features))
2834 features &= ~NETIF_F_GSO_PARTIAL;
2835 }
2836
2837 BUILD_BUG_ON(SKB_SGO_CB_OFFSET +
2838 sizeof(*SKB_GSO_CB(skb)) > sizeof(skb->cb));
2839
2840 SKB_GSO_CB(skb)->mac_offset = skb_headroom(skb);
2841 SKB_GSO_CB(skb)->encap_level = 0;
2842
2843 skb_reset_mac_header(skb);
2844 skb_reset_mac_len(skb);
2845
2846 segs = skb_mac_gso_segment(skb, features);
2847
2848 if (unlikely(skb_needs_check(skb, tx_path) && !IS_ERR(segs)))
2849 skb_warn_bad_offload(skb);
2850
2851 return segs;
2852 }
2853 EXPORT_SYMBOL(__skb_gso_segment);
2854
2855 /* Take action when hardware reception checksum errors are detected. */
2856 #ifdef CONFIG_BUG
2857 void netdev_rx_csum_fault(struct net_device *dev)
2858 {
2859 if (net_ratelimit()) {
2860 pr_err("%s: hw csum failure\n", dev ? dev->name : "<unknown>");
2861 dump_stack();
2862 }
2863 }
2864 EXPORT_SYMBOL(netdev_rx_csum_fault);
2865 #endif
2866
2867 /* Actually, we should eliminate this check as soon as we know, that:
2868 * 1. IOMMU is present and allows to map all the memory.
2869 * 2. No high memory really exists on this machine.
2870 */
2871
2872 static int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
2873 {
2874 #ifdef CONFIG_HIGHMEM
2875 int i;
2876
2877 if (!(dev->features & NETIF_F_HIGHDMA)) {
2878 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2879 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2880
2881 if (PageHighMem(skb_frag_page(frag)))
2882 return 1;
2883 }
2884 }
2885
2886 if (PCI_DMA_BUS_IS_PHYS) {
2887 struct device *pdev = dev->dev.parent;
2888
2889 if (!pdev)
2890 return 0;
2891 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2892 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2893 dma_addr_t addr = page_to_phys(skb_frag_page(frag));
2894
2895 if (!pdev->dma_mask || addr + PAGE_SIZE - 1 > *pdev->dma_mask)
2896 return 1;
2897 }
2898 }
2899 #endif
2900 return 0;
2901 }
2902
2903 /* If MPLS offload request, verify we are testing hardware MPLS features
2904 * instead of standard features for the netdev.
2905 */
2906 #if IS_ENABLED(CONFIG_NET_MPLS_GSO)
2907 static netdev_features_t net_mpls_features(struct sk_buff *skb,
2908 netdev_features_t features,
2909 __be16 type)
2910 {
2911 if (eth_p_mpls(type))
2912 features &= skb->dev->mpls_features;
2913
2914 return features;
2915 }
2916 #else
2917 static netdev_features_t net_mpls_features(struct sk_buff *skb,
2918 netdev_features_t features,
2919 __be16 type)
2920 {
2921 return features;
2922 }
2923 #endif
2924
2925 static netdev_features_t harmonize_features(struct sk_buff *skb,
2926 netdev_features_t features)
2927 {
2928 int tmp;
2929 __be16 type;
2930
2931 type = skb_network_protocol(skb, &tmp);
2932 features = net_mpls_features(skb, features, type);
2933
2934 if (skb->ip_summed != CHECKSUM_NONE &&
2935 !can_checksum_protocol(features, type)) {
2936 features &= ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
2937 }
2938 if (illegal_highdma(skb->dev, skb))
2939 features &= ~NETIF_F_SG;
2940
2941 return features;
2942 }
2943
2944 netdev_features_t passthru_features_check(struct sk_buff *skb,
2945 struct net_device *dev,
2946 netdev_features_t features)
2947 {
2948 return features;
2949 }
2950 EXPORT_SYMBOL(passthru_features_check);
2951
2952 static netdev_features_t dflt_features_check(struct sk_buff *skb,
2953 struct net_device *dev,
2954 netdev_features_t features)
2955 {
2956 return vlan_features_check(skb, features);
2957 }
2958
2959 static netdev_features_t gso_features_check(const struct sk_buff *skb,
2960 struct net_device *dev,
2961 netdev_features_t features)
2962 {
2963 u16 gso_segs = skb_shinfo(skb)->gso_segs;
2964
2965 if (gso_segs > dev->gso_max_segs)
2966 return features & ~NETIF_F_GSO_MASK;
2967
2968 /* Support for GSO partial features requires software
2969 * intervention before we can actually process the packets
2970 * so we need to strip support for any partial features now
2971 * and we can pull them back in after we have partially
2972 * segmented the frame.
2973 */
2974 if (!(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL))
2975 features &= ~dev->gso_partial_features;
2976
2977 /* Make sure to clear the IPv4 ID mangling feature if the
2978 * IPv4 header has the potential to be fragmented.
2979 */
2980 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) {
2981 struct iphdr *iph = skb->encapsulation ?
2982 inner_ip_hdr(skb) : ip_hdr(skb);
2983
2984 if (!(iph->frag_off & htons(IP_DF)))
2985 features &= ~NETIF_F_TSO_MANGLEID;
2986 }
2987
2988 return features;
2989 }
2990
2991 netdev_features_t netif_skb_features(struct sk_buff *skb)
2992 {
2993 struct net_device *dev = skb->dev;
2994 netdev_features_t features = dev->features;
2995
2996 if (skb_is_gso(skb))
2997 features = gso_features_check(skb, dev, features);
2998
2999 /* If encapsulation offload request, verify we are testing
3000 * hardware encapsulation features instead of standard
3001 * features for the netdev
3002 */
3003 if (skb->encapsulation)
3004 features &= dev->hw_enc_features;
3005
3006 if (skb_vlan_tagged(skb))
3007 features = netdev_intersect_features(features,
3008 dev->vlan_features |
3009 NETIF_F_HW_VLAN_CTAG_TX |
3010 NETIF_F_HW_VLAN_STAG_TX);
3011
3012 if (dev->netdev_ops->ndo_features_check)
3013 features &= dev->netdev_ops->ndo_features_check(skb, dev,
3014 features);
3015 else
3016 features &= dflt_features_check(skb, dev, features);
3017
3018 return harmonize_features(skb, features);
3019 }
3020 EXPORT_SYMBOL(netif_skb_features);
3021
3022 static int xmit_one(struct sk_buff *skb, struct net_device *dev,
3023 struct netdev_queue *txq, bool more)
3024 {
3025 unsigned int len;
3026 int rc;
3027
3028 if (!list_empty(&ptype_all) || !list_empty(&dev->ptype_all))
3029 dev_queue_xmit_nit(skb, dev);
3030
3031 len = skb->len;
3032 trace_net_dev_start_xmit(skb, dev);
3033 rc = netdev_start_xmit(skb, dev, txq, more);
3034 trace_net_dev_xmit(skb, rc, dev, len);
3035
3036 return rc;
3037 }
3038
3039 struct sk_buff *dev_hard_start_xmit(struct sk_buff *first, struct net_device *dev,
3040 struct netdev_queue *txq, int *ret)
3041 {
3042 struct sk_buff *skb = first;
3043 int rc = NETDEV_TX_OK;
3044
3045 while (skb) {
3046 struct sk_buff *next = skb->next;
3047
3048 skb->next = NULL;
3049 rc = xmit_one(skb, dev, txq, next != NULL);
3050 if (unlikely(!dev_xmit_complete(rc))) {
3051 skb->next = next;
3052 goto out;
3053 }
3054
3055 skb = next;
3056 if (netif_tx_queue_stopped(txq) && skb) {
3057 rc = NETDEV_TX_BUSY;
3058 break;
3059 }
3060 }
3061
3062 out:
3063 *ret = rc;
3064 return skb;
3065 }
3066
3067 static struct sk_buff *validate_xmit_vlan(struct sk_buff *skb,
3068 netdev_features_t features)
3069 {
3070 if (skb_vlan_tag_present(skb) &&
3071 !vlan_hw_offload_capable(features, skb->vlan_proto))
3072 skb = __vlan_hwaccel_push_inside(skb);
3073 return skb;
3074 }
3075
3076 int skb_csum_hwoffload_help(struct sk_buff *skb,
3077 const netdev_features_t features)
3078 {
3079 if (unlikely(skb->csum_not_inet))
3080 return !!(features & NETIF_F_SCTP_CRC) ? 0 :
3081 skb_crc32c_csum_help(skb);
3082
3083 return !!(features & NETIF_F_CSUM_MASK) ? 0 : skb_checksum_help(skb);
3084 }
3085 EXPORT_SYMBOL(skb_csum_hwoffload_help);
3086
3087 static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device *dev)
3088 {
3089 netdev_features_t features;
3090
3091 features = netif_skb_features(skb);
3092 skb = validate_xmit_vlan(skb, features);
3093 if (unlikely(!skb))
3094 goto out_null;
3095
3096 if (netif_needs_gso(skb, features)) {
3097 struct sk_buff *segs;
3098
3099 segs = skb_gso_segment(skb, features);
3100 if (IS_ERR(segs)) {
3101 goto out_kfree_skb;
3102 } else if (segs) {
3103 consume_skb(skb);
3104 skb = segs;
3105 }
3106 } else {
3107 if (skb_needs_linearize(skb, features) &&
3108 __skb_linearize(skb))
3109 goto out_kfree_skb;
3110
3111 if (validate_xmit_xfrm(skb, features))
3112 goto out_kfree_skb;
3113
3114 /* If packet is not checksummed and device does not
3115 * support checksumming for this protocol, complete
3116 * checksumming here.
3117 */
3118 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3119 if (skb->encapsulation)
3120 skb_set_inner_transport_header(skb,
3121 skb_checksum_start_offset(skb));
3122 else
3123 skb_set_transport_header(skb,
3124 skb_checksum_start_offset(skb));
3125 if (skb_csum_hwoffload_help(skb, features))
3126 goto out_kfree_skb;
3127 }
3128 }
3129
3130 return skb;
3131
3132 out_kfree_skb:
3133 kfree_skb(skb);
3134 out_null:
3135 atomic_long_inc(&dev->tx_dropped);
3136 return NULL;
3137 }
3138
3139 struct sk_buff *validate_xmit_skb_list(struct sk_buff *skb, struct net_device *dev)
3140 {
3141 struct sk_buff *next, *head = NULL, *tail;
3142
3143 for (; skb != NULL; skb = next) {
3144 next = skb->next;
3145 skb->next = NULL;
3146
3147 /* in case skb wont be segmented, point to itself */
3148 skb->prev = skb;
3149
3150 skb = validate_xmit_skb(skb, dev);
3151 if (!skb)
3152 continue;
3153
3154 if (!head)
3155 head = skb;
3156 else
3157 tail->next = skb;
3158 /* If skb was segmented, skb->prev points to
3159 * the last segment. If not, it still contains skb.
3160 */
3161 tail = skb->prev;
3162 }
3163 return head;
3164 }
3165 EXPORT_SYMBOL_GPL(validate_xmit_skb_list);
3166
3167 static void qdisc_pkt_len_init(struct sk_buff *skb)
3168 {
3169 const struct skb_shared_info *shinfo = skb_shinfo(skb);
3170
3171 qdisc_skb_cb(skb)->pkt_len = skb->len;
3172
3173 /* To get more precise estimation of bytes sent on wire,
3174 * we add to pkt_len the headers size of all segments
3175 */
3176 if (shinfo->gso_size) {
3177 unsigned int hdr_len;
3178 u16 gso_segs = shinfo->gso_segs;
3179
3180 /* mac layer + network layer */
3181 hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
3182
3183 /* + transport layer */
3184 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
3185 const struct tcphdr *th;
3186 struct tcphdr _tcphdr;
3187
3188 th = skb_header_pointer(skb, skb_transport_offset(skb),
3189 sizeof(_tcphdr), &_tcphdr);
3190 if (likely(th))
3191 hdr_len += __tcp_hdrlen(th);
3192 } else {
3193 struct udphdr _udphdr;
3194
3195 if (skb_header_pointer(skb, skb_transport_offset(skb),
3196 sizeof(_udphdr), &_udphdr))
3197 hdr_len += sizeof(struct udphdr);
3198 }
3199
3200 if (shinfo->gso_type & SKB_GSO_DODGY)
3201 gso_segs = DIV_ROUND_UP(skb->len - hdr_len,
3202 shinfo->gso_size);
3203
3204 qdisc_skb_cb(skb)->pkt_len += (gso_segs - 1) * hdr_len;
3205 }
3206 }
3207
3208 static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q,
3209 struct net_device *dev,
3210 struct netdev_queue *txq)
3211 {
3212 spinlock_t *root_lock = qdisc_lock(q);
3213 struct sk_buff *to_free = NULL;
3214 bool contended;
3215 int rc;
3216
3217 qdisc_calculate_pkt_len(skb, q);
3218 /*
3219 * Heuristic to force contended enqueues to serialize on a
3220 * separate lock before trying to get qdisc main lock.
3221 * This permits qdisc->running owner to get the lock more
3222 * often and dequeue packets faster.
3223 */
3224 contended = qdisc_is_running(q);
3225 if (unlikely(contended))
3226 spin_lock(&q->busylock);
3227
3228 spin_lock(root_lock);
3229 if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) {
3230 __qdisc_drop(skb, &to_free);
3231 rc = NET_XMIT_DROP;
3232 } else if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) &&
3233 qdisc_run_begin(q)) {
3234 /*
3235 * This is a work-conserving queue; there are no old skbs
3236 * waiting to be sent out; and the qdisc is not running -
3237 * xmit the skb directly.
3238 */
3239
3240 qdisc_bstats_update(q, skb);
3241
3242 if (sch_direct_xmit(skb, q, dev, txq, root_lock, true)) {
3243 if (unlikely(contended)) {
3244 spin_unlock(&q->busylock);
3245 contended = false;
3246 }
3247 __qdisc_run(q);
3248 } else
3249 qdisc_run_end(q);
3250
3251 rc = NET_XMIT_SUCCESS;
3252 } else {
3253 rc = q->enqueue(skb, q, &to_free) & NET_XMIT_MASK;
3254 if (qdisc_run_begin(q)) {
3255 if (unlikely(contended)) {
3256 spin_unlock(&q->busylock);
3257 contended = false;
3258 }
3259 __qdisc_run(q);
3260 }
3261 }
3262 spin_unlock(root_lock);
3263 if (unlikely(to_free))
3264 kfree_skb_list(to_free);
3265 if (unlikely(contended))
3266 spin_unlock(&q->busylock);
3267 return rc;
3268 }
3269
3270 #if IS_ENABLED(CONFIG_CGROUP_NET_PRIO)
3271 static void skb_update_prio(struct sk_buff *skb)
3272 {
3273 const struct netprio_map *map;
3274 const struct sock *sk;
3275 unsigned int prioidx;
3276
3277 if (skb->priority)
3278 return;
3279 map = rcu_dereference_bh(skb->dev->priomap);
3280 if (!map)
3281 return;
3282 sk = skb_to_full_sk(skb);
3283 if (!sk)
3284 return;
3285
3286 prioidx = sock_cgroup_prioidx(&sk->sk_cgrp_data);
3287
3288 if (prioidx < map->priomap_len)
3289 skb->priority = map->priomap[prioidx];
3290 }
3291 #else
3292 #define skb_update_prio(skb)
3293 #endif
3294
3295 DEFINE_PER_CPU(int, xmit_recursion);
3296 EXPORT_SYMBOL(xmit_recursion);
3297
3298 /**
3299 * dev_loopback_xmit - loop back @skb
3300 * @net: network namespace this loopback is happening in
3301 * @sk: sk needed to be a netfilter okfn
3302 * @skb: buffer to transmit
3303 */
3304 int dev_loopback_xmit(struct net *net, struct sock *sk, struct sk_buff *skb)
3305 {
3306 skb_reset_mac_header(skb);
3307 __skb_pull(skb, skb_network_offset(skb));
3308 skb->pkt_type = PACKET_LOOPBACK;
3309 skb->ip_summed = CHECKSUM_UNNECESSARY;
3310 WARN_ON(!skb_dst(skb));
3311 skb_dst_force(skb);
3312 netif_rx_ni(skb);
3313 return 0;
3314 }
3315 EXPORT_SYMBOL(dev_loopback_xmit);
3316
3317 #ifdef CONFIG_NET_EGRESS
3318 static struct sk_buff *
3319 sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
3320 {
3321 struct mini_Qdisc *miniq = rcu_dereference_bh(dev->miniq_egress);
3322 struct tcf_result cl_res;
3323
3324 if (!miniq)
3325 return skb;
3326
3327 /* qdisc_skb_cb(skb)->pkt_len was already set by the caller. */
3328 mini_qdisc_bstats_cpu_update(miniq, skb);
3329
3330 switch (tcf_classify(skb, miniq->filter_list, &cl_res, false)) {
3331 case TC_ACT_OK:
3332 case TC_ACT_RECLASSIFY:
3333 skb->tc_index = TC_H_MIN(cl_res.classid);
3334 break;
3335 case TC_ACT_SHOT:
3336 mini_qdisc_qstats_cpu_drop(miniq);
3337 *ret = NET_XMIT_DROP;
3338 kfree_skb(skb);
3339 return NULL;
3340 case TC_ACT_STOLEN:
3341 case TC_ACT_QUEUED:
3342 case TC_ACT_TRAP:
3343 *ret = NET_XMIT_SUCCESS;
3344 consume_skb(skb);
3345 return NULL;
3346 case TC_ACT_REDIRECT:
3347 /* No need to push/pop skb's mac_header here on egress! */
3348 skb_do_redirect(skb);
3349 *ret = NET_XMIT_SUCCESS;
3350 return NULL;
3351 default:
3352 break;
3353 }
3354
3355 return skb;
3356 }
3357 #endif /* CONFIG_NET_EGRESS */
3358
3359 static inline int get_xps_queue(struct net_device *dev, struct sk_buff *skb)
3360 {
3361 #ifdef CONFIG_XPS
3362 struct xps_dev_maps *dev_maps;
3363 struct xps_map *map;
3364 int queue_index = -1;
3365
3366 rcu_read_lock();
3367 dev_maps = rcu_dereference(dev->xps_maps);
3368 if (dev_maps) {
3369 unsigned int tci = skb->sender_cpu - 1;
3370
3371 if (dev->num_tc) {
3372 tci *= dev->num_tc;
3373 tci += netdev_get_prio_tc_map(dev, skb->priority);
3374 }
3375
3376 map = rcu_dereference(dev_maps->cpu_map[tci]);
3377 if (map) {
3378 if (map->len == 1)
3379 queue_index = map->queues[0];
3380 else
3381 queue_index = map->queues[reciprocal_scale(skb_get_hash(skb),
3382 map->len)];
3383 if (unlikely(queue_index >= dev->real_num_tx_queues))
3384 queue_index = -1;
3385 }
3386 }
3387 rcu_read_unlock();
3388
3389 return queue_index;
3390 #else
3391 return -1;
3392 #endif
3393 }
3394
3395 static u16 __netdev_pick_tx(struct net_device *dev, struct sk_buff *skb)
3396 {
3397 struct sock *sk = skb->sk;
3398 int queue_index = sk_tx_queue_get(sk);
3399
3400 if (queue_index < 0 || skb->ooo_okay ||
3401 queue_index >= dev->real_num_tx_queues) {
3402 int new_index = get_xps_queue(dev, skb);
3403
3404 if (new_index < 0)
3405 new_index = skb_tx_hash(dev, skb);
3406
3407 if (queue_index != new_index && sk &&
3408 sk_fullsock(sk) &&
3409 rcu_access_pointer(sk->sk_dst_cache))
3410 sk_tx_queue_set(sk, new_index);
3411
3412 queue_index = new_index;
3413 }
3414
3415 return queue_index;
3416 }
3417
3418 struct netdev_queue *netdev_pick_tx(struct net_device *dev,
3419 struct sk_buff *skb,
3420 void *accel_priv)
3421 {
3422 int queue_index = 0;
3423
3424 #ifdef CONFIG_XPS
3425 u32 sender_cpu = skb->sender_cpu - 1;
3426
3427 if (sender_cpu >= (u32)NR_CPUS)
3428 skb->sender_cpu = raw_smp_processor_id() + 1;
3429 #endif
3430
3431 if (dev->real_num_tx_queues != 1) {
3432 const struct net_device_ops *ops = dev->netdev_ops;
3433
3434 if (ops->ndo_select_queue)
3435 queue_index = ops->ndo_select_queue(dev, skb, accel_priv,
3436 __netdev_pick_tx);
3437 else
3438 queue_index = __netdev_pick_tx(dev, skb);
3439
3440 if (!accel_priv)
3441 queue_index = netdev_cap_txqueue(dev, queue_index);
3442 }
3443
3444 skb_set_queue_mapping(skb, queue_index);
3445 return netdev_get_tx_queue(dev, queue_index);
3446 }
3447
3448 /**
3449 * __dev_queue_xmit - transmit a buffer
3450 * @skb: buffer to transmit
3451 * @accel_priv: private data used for L2 forwarding offload
3452 *
3453 * Queue a buffer for transmission to a network device. The caller must
3454 * have set the device and priority and built the buffer before calling
3455 * this function. The function can be called from an interrupt.
3456 *
3457 * A negative errno code is returned on a failure. A success does not
3458 * guarantee the frame will be transmitted as it may be dropped due
3459 * to congestion or traffic shaping.
3460 *
3461 * -----------------------------------------------------------------------------------
3462 * I notice this method can also return errors from the queue disciplines,
3463 * including NET_XMIT_DROP, which is a positive value. So, errors can also
3464 * be positive.
3465 *
3466 * Regardless of the return value, the skb is consumed, so it is currently
3467 * difficult to retry a send to this method. (You can bump the ref count
3468 * before sending to hold a reference for retry if you are careful.)
3469 *
3470 * When calling this method, interrupts MUST be enabled. This is because
3471 * the BH enable code must have IRQs enabled so that it will not deadlock.
3472 * --BLG
3473 */
3474 static int __dev_queue_xmit(struct sk_buff *skb, void *accel_priv)
3475 {
3476 struct net_device *dev = skb->dev;
3477 struct netdev_queue *txq;
3478 struct Qdisc *q;
3479 int rc = -ENOMEM;
3480
3481 skb_reset_mac_header(skb);
3482
3483 if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_SCHED_TSTAMP))
3484 __skb_tstamp_tx(skb, NULL, skb->sk, SCM_TSTAMP_SCHED);
3485
3486 /* Disable soft irqs for various locks below. Also
3487 * stops preemption for RCU.
3488 */
3489 rcu_read_lock_bh();
3490
3491 skb_update_prio(skb);
3492
3493 qdisc_pkt_len_init(skb);
3494 #ifdef CONFIG_NET_CLS_ACT
3495 skb->tc_at_ingress = 0;
3496 # ifdef CONFIG_NET_EGRESS
3497 if (static_key_false(&egress_needed)) {
3498 skb = sch_handle_egress(skb, &rc, dev);
3499 if (!skb)
3500 goto out;
3501 }
3502 # endif
3503 #endif
3504 /* If device/qdisc don't need skb->dst, release it right now while
3505 * its hot in this cpu cache.
3506 */
3507 if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
3508 skb_dst_drop(skb);
3509 else
3510 skb_dst_force(skb);
3511
3512 txq = netdev_pick_tx(dev, skb, accel_priv);
3513 q = rcu_dereference_bh(txq->qdisc);
3514
3515 trace_net_dev_queue(skb);
3516 if (q->enqueue) {
3517 rc = __dev_xmit_skb(skb, q, dev, txq);
3518 goto out;
3519 }
3520
3521 /* The device has no queue. Common case for software devices:
3522 * loopback, all the sorts of tunnels...
3523
3524 * Really, it is unlikely that netif_tx_lock protection is necessary
3525 * here. (f.e. loopback and IP tunnels are clean ignoring statistics
3526 * counters.)
3527 * However, it is possible, that they rely on protection
3528 * made by us here.
3529
3530 * Check this and shot the lock. It is not prone from deadlocks.
3531 *Either shot noqueue qdisc, it is even simpler 8)
3532 */
3533 if (dev->flags & IFF_UP) {
3534 int cpu = smp_processor_id(); /* ok because BHs are off */
3535
3536 if (txq->xmit_lock_owner != cpu) {
3537 if (unlikely(__this_cpu_read(xmit_recursion) >
3538 XMIT_RECURSION_LIMIT))
3539 goto recursion_alert;
3540
3541 skb = validate_xmit_skb(skb, dev);
3542 if (!skb)
3543 goto out;
3544
3545 HARD_TX_LOCK(dev, txq, cpu);
3546
3547 if (!netif_xmit_stopped(txq)) {
3548 __this_cpu_inc(xmit_recursion);
3549 skb = dev_hard_start_xmit(skb, dev, txq, &rc);
3550 __this_cpu_dec(xmit_recursion);
3551 if (dev_xmit_complete(rc)) {
3552 HARD_TX_UNLOCK(dev, txq);
3553 goto out;
3554 }
3555 }
3556 HARD_TX_UNLOCK(dev, txq);
3557 net_crit_ratelimited("Virtual device %s asks to queue packet!\n",
3558 dev->name);
3559 } else {
3560 /* Recursion is detected! It is possible,
3561 * unfortunately
3562 */
3563 recursion_alert:
3564 net_crit_ratelimited("Dead loop on virtual device %s, fix it urgently!\n",
3565 dev->name);
3566 }
3567 }
3568
3569 rc = -ENETDOWN;
3570 rcu_read_unlock_bh();
3571
3572 atomic_long_inc(&dev->tx_dropped);
3573 kfree_skb_list(skb);
3574 return rc;
3575 out:
3576 rcu_read_unlock_bh();
3577 return rc;
3578 }
3579
3580 int dev_queue_xmit(struct sk_buff *skb)
3581 {
3582 return __dev_queue_xmit(skb, NULL);
3583 }
3584 EXPORT_SYMBOL(dev_queue_xmit);
3585
3586 int dev_queue_xmit_accel(struct sk_buff *skb, void *accel_priv)
3587 {
3588 return __dev_queue_xmit(skb, accel_priv);
3589 }
3590 EXPORT_SYMBOL(dev_queue_xmit_accel);
3591
3592
3593 /*************************************************************************
3594 * Receiver routines
3595 *************************************************************************/
3596
3597 int netdev_max_backlog __read_mostly = 1000;
3598 EXPORT_SYMBOL(netdev_max_backlog);
3599
3600 int netdev_tstamp_prequeue __read_mostly = 1;
3601 int netdev_budget __read_mostly = 300;
3602 unsigned int __read_mostly netdev_budget_usecs = 2000;
3603 int weight_p __read_mostly = 64; /* old backlog weight */
3604 int dev_weight_rx_bias __read_mostly = 1; /* bias for backlog weight */
3605 int dev_weight_tx_bias __read_mostly = 1; /* bias for output_queue quota */
3606 int dev_rx_weight __read_mostly = 64;
3607 int dev_tx_weight __read_mostly = 64;
3608
3609 /* Called with irq disabled */
3610 static inline void ____napi_schedule(struct softnet_data *sd,
3611 struct napi_struct *napi)
3612 {
3613 list_add_tail(&napi->poll_list, &sd->poll_list);
3614 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
3615 }
3616
3617 #ifdef CONFIG_RPS
3618
3619 /* One global table that all flow-based protocols share. */
3620 struct rps_sock_flow_table __rcu *rps_sock_flow_table __read_mostly;
3621 EXPORT_SYMBOL(rps_sock_flow_table);
3622 u32 rps_cpu_mask __read_mostly;
3623 EXPORT_SYMBOL(rps_cpu_mask);
3624
3625 struct static_key rps_needed __read_mostly;
3626 EXPORT_SYMBOL(rps_needed);
3627 struct static_key rfs_needed __read_mostly;
3628 EXPORT_SYMBOL(rfs_needed);
3629
3630 static struct rps_dev_flow *
3631 set_rps_cpu(struct net_device *dev, struct sk_buff *skb,
3632 struct rps_dev_flow *rflow, u16 next_cpu)
3633 {
3634 if (next_cpu < nr_cpu_ids) {
3635 #ifdef CONFIG_RFS_ACCEL
3636 struct netdev_rx_queue *rxqueue;
3637 struct rps_dev_flow_table *flow_table;
3638 struct rps_dev_flow *old_rflow;
3639 u32 flow_id;
3640 u16 rxq_index;
3641 int rc;
3642
3643 /* Should we steer this flow to a different hardware queue? */
3644 if (!skb_rx_queue_recorded(skb) || !dev->rx_cpu_rmap ||
3645 !(dev->features & NETIF_F_NTUPLE))
3646 goto out;
3647 rxq_index = cpu_rmap_lookup_index(dev->rx_cpu_rmap, next_cpu);
3648 if (rxq_index == skb_get_rx_queue(skb))
3649 goto out;
3650
3651 rxqueue = dev->_rx + rxq_index;
3652 flow_table = rcu_dereference(rxqueue->rps_flow_table);
3653 if (!flow_table)
3654 goto out;
3655 flow_id = skb_get_hash(skb) & flow_table->mask;
3656 rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb,
3657 rxq_index, flow_id);
3658 if (rc < 0)
3659 goto out;
3660 old_rflow = rflow;
3661 rflow = &flow_table->flows[flow_id];
3662 rflow->filter = rc;
3663 if (old_rflow->filter == rflow->filter)
3664 old_rflow->filter = RPS_NO_FILTER;
3665 out:
3666 #endif
3667 rflow->last_qtail =
3668 per_cpu(softnet_data, next_cpu).input_queue_head;
3669 }
3670
3671 rflow->cpu = next_cpu;
3672 return rflow;
3673 }
3674
3675 /*
3676 * get_rps_cpu is called from netif_receive_skb and returns the target
3677 * CPU from the RPS map of the receiving queue for a given skb.
3678 * rcu_read_lock must be held on entry.
3679 */
3680 static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb,
3681 struct rps_dev_flow **rflowp)
3682 {
3683 const struct rps_sock_flow_table *sock_flow_table;
3684 struct netdev_rx_queue *rxqueue = dev->_rx;
3685 struct rps_dev_flow_table *flow_table;
3686 struct rps_map *map;
3687 int cpu = -1;
3688 u32 tcpu;
3689 u32 hash;
3690
3691 if (skb_rx_queue_recorded(skb)) {
3692 u16 index = skb_get_rx_queue(skb);
3693
3694 if (unlikely(index >= dev->real_num_rx_queues)) {
3695 WARN_ONCE(dev->real_num_rx_queues > 1,
3696 "%s received packet on queue %u, but number "
3697 "of RX queues is %u\n",
3698 dev->name, index, dev->real_num_rx_queues);
3699 goto done;
3700 }
3701 rxqueue += index;
3702 }
3703
3704 /* Avoid computing hash if RFS/RPS is not active for this rxqueue */
3705
3706 flow_table = rcu_dereference(rxqueue->rps_flow_table);
3707 map = rcu_dereference(rxqueue->rps_map);
3708 if (!flow_table && !map)
3709 goto done;
3710
3711 skb_reset_network_header(skb);
3712 hash = skb_get_hash(skb);
3713 if (!hash)
3714 goto done;
3715
3716 sock_flow_table = rcu_dereference(rps_sock_flow_table);
3717 if (flow_table && sock_flow_table) {
3718 struct rps_dev_flow *rflow;
3719 u32 next_cpu;
3720 u32 ident;
3721
3722 /* First check into global flow table if there is a match */
3723 ident = sock_flow_table->ents[hash & sock_flow_table->mask];
3724 if ((ident ^ hash) & ~rps_cpu_mask)
3725 goto try_rps;
3726
3727 next_cpu = ident & rps_cpu_mask;
3728
3729 /* OK, now we know there is a match,
3730 * we can look at the local (per receive queue) flow table
3731 */
3732 rflow = &flow_table->flows[hash & flow_table->mask];
3733 tcpu = rflow->cpu;
3734
3735 /*
3736 * If the desired CPU (where last recvmsg was done) is
3737 * different from current CPU (one in the rx-queue flow
3738 * table entry), switch if one of the following holds:
3739 * - Current CPU is unset (>= nr_cpu_ids).
3740 * - Current CPU is offline.
3741 * - The current CPU's queue tail has advanced beyond the
3742 * last packet that was enqueued using this table entry.
3743 * This guarantees that all previous packets for the flow
3744 * have been dequeued, thus preserving in order delivery.
3745 */
3746 if (unlikely(tcpu != next_cpu) &&
3747 (tcpu >= nr_cpu_ids || !cpu_online(tcpu) ||
3748 ((int)(per_cpu(softnet_data, tcpu).input_queue_head -
3749 rflow->last_qtail)) >= 0)) {
3750 tcpu = next_cpu;
3751 rflow = set_rps_cpu(dev, skb, rflow, next_cpu);
3752 }
3753
3754 if (tcpu < nr_cpu_ids && cpu_online(tcpu)) {
3755 *rflowp = rflow;
3756 cpu = tcpu;
3757 goto done;
3758 }
3759 }
3760
3761 try_rps:
3762
3763 if (map) {
3764 tcpu = map->cpus[reciprocal_scale(hash, map->len)];
3765 if (cpu_online(tcpu)) {
3766 cpu = tcpu;
3767 goto done;
3768 }
3769 }
3770
3771 done:
3772 return cpu;
3773 }
3774
3775 #ifdef CONFIG_RFS_ACCEL
3776
3777 /**
3778 * rps_may_expire_flow - check whether an RFS hardware filter may be removed
3779 * @dev: Device on which the filter was set
3780 * @rxq_index: RX queue index
3781 * @flow_id: Flow ID passed to ndo_rx_flow_steer()
3782 * @filter_id: Filter ID returned by ndo_rx_flow_steer()
3783 *
3784 * Drivers that implement ndo_rx_flow_steer() should periodically call
3785 * this function for each installed filter and remove the filters for
3786 * which it returns %true.
3787 */
3788 bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index,
3789 u32 flow_id, u16 filter_id)
3790 {
3791 struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index;
3792 struct rps_dev_flow_table *flow_table;
3793 struct rps_dev_flow *rflow;
3794 bool expire = true;
3795 unsigned int cpu;
3796
3797 rcu_read_lock();
3798 flow_table = rcu_dereference(rxqueue->rps_flow_table);
3799 if (flow_table && flow_id <= flow_table->mask) {
3800 rflow = &flow_table->flows[flow_id];
3801 cpu = READ_ONCE(rflow->cpu);
3802 if (rflow->filter == filter_id && cpu < nr_cpu_ids &&
3803 ((int)(per_cpu(softnet_data, cpu).input_queue_head -
3804 rflow->last_qtail) <
3805 (int)(10 * flow_table->mask)))
3806 expire = false;
3807 }
3808 rcu_read_unlock();
3809 return expire;
3810 }
3811 EXPORT_SYMBOL(rps_may_expire_flow);
3812
3813 #endif /* CONFIG_RFS_ACCEL */
3814
3815 /* Called from hardirq (IPI) context */
3816 static void rps_trigger_softirq(void *data)
3817 {
3818 struct softnet_data *sd = data;
3819
3820 ____napi_schedule(sd, &sd->backlog);
3821 sd->received_rps++;
3822 }
3823
3824 #endif /* CONFIG_RPS */
3825
3826 /*
3827 * Check if this softnet_data structure is another cpu one
3828 * If yes, queue it to our IPI list and return 1
3829 * If no, return 0
3830 */
3831 static int rps_ipi_queued(struct softnet_data *sd)
3832 {
3833 #ifdef CONFIG_RPS
3834 struct softnet_data *mysd = this_cpu_ptr(&softnet_data);
3835
3836 if (sd != mysd) {
3837 sd->rps_ipi_next = mysd->rps_ipi_list;
3838 mysd->rps_ipi_list = sd;
3839
3840 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
3841 return 1;
3842 }
3843 #endif /* CONFIG_RPS */
3844 return 0;
3845 }
3846
3847 #ifdef CONFIG_NET_FLOW_LIMIT
3848 int netdev_flow_limit_table_len __read_mostly = (1 << 12);
3849 #endif
3850
3851 static bool skb_flow_limit(struct sk_buff *skb, unsigned int qlen)
3852 {
3853 #ifdef CONFIG_NET_FLOW_LIMIT
3854 struct sd_flow_limit *fl;
3855 struct softnet_data *sd;
3856 unsigned int old_flow, new_flow;
3857
3858 if (qlen < (netdev_max_backlog >> 1))
3859 return false;
3860
3861 sd = this_cpu_ptr(&softnet_data);
3862
3863 rcu_read_lock();
3864 fl = rcu_dereference(sd->flow_limit);
3865 if (fl) {
3866 new_flow = skb_get_hash(skb) & (fl->num_buckets - 1);
3867 old_flow = fl->history[fl->history_head];
3868 fl->history[fl->history_head] = new_flow;
3869
3870 fl->history_head++;
3871 fl->history_head &= FLOW_LIMIT_HISTORY - 1;
3872
3873 if (likely(fl->buckets[old_flow]))
3874 fl->buckets[old_flow]--;
3875
3876 if (++fl->buckets[new_flow] > (FLOW_LIMIT_HISTORY >> 1)) {
3877 fl->count++;
3878 rcu_read_unlock();
3879 return true;
3880 }
3881 }
3882 rcu_read_unlock();
3883 #endif
3884 return false;
3885 }
3886
3887 /*
3888 * enqueue_to_backlog is called to queue an skb to a per CPU backlog
3889 * queue (may be a remote CPU queue).
3890 */
3891 static int enqueue_to_backlog(struct sk_buff *skb, int cpu,
3892 unsigned int *qtail)
3893 {
3894 struct softnet_data *sd;
3895 unsigned long flags;
3896 unsigned int qlen;
3897
3898 sd = &per_cpu(softnet_data, cpu);
3899
3900 local_irq_save(flags);
3901
3902 rps_lock(sd);
3903 if (!netif_running(skb->dev))
3904 goto drop;
3905 qlen = skb_queue_len(&sd->input_pkt_queue);
3906 if (qlen <= netdev_max_backlog && !skb_flow_limit(skb, qlen)) {
3907 if (qlen) {
3908 enqueue:
3909 __skb_queue_tail(&sd->input_pkt_queue, skb);
3910 input_queue_tail_incr_save(sd, qtail);
3911 rps_unlock(sd);
3912 local_irq_restore(flags);
3913 return NET_RX_SUCCESS;
3914 }
3915
3916 /* Schedule NAPI for backlog device
3917 * We can use non atomic operation since we own the queue lock
3918 */
3919 if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state)) {
3920 if (!rps_ipi_queued(sd))
3921 ____napi_schedule(sd, &sd->backlog);
3922 }
3923 goto enqueue;
3924 }
3925
3926 drop:
3927 sd->dropped++;
3928 rps_unlock(sd);
3929
3930 local_irq_restore(flags);
3931
3932 atomic_long_inc(&skb->dev->rx_dropped);
3933 kfree_skb(skb);
3934 return NET_RX_DROP;
3935 }
3936
3937 static u32 netif_receive_generic_xdp(struct sk_buff *skb,
3938 struct bpf_prog *xdp_prog)
3939 {
3940 u32 metalen, act = XDP_DROP;
3941 struct xdp_buff xdp;
3942 void *orig_data;
3943 int hlen, off;
3944 u32 mac_len;
3945
3946 /* Reinjected packets coming from act_mirred or similar should
3947 * not get XDP generic processing.
3948 */
3949 if (skb_cloned(skb))
3950 return XDP_PASS;
3951
3952 /* XDP packets must be linear and must have sufficient headroom
3953 * of XDP_PACKET_HEADROOM bytes. This is the guarantee that also
3954 * native XDP provides, thus we need to do it here as well.
3955 */
3956 if (skb_is_nonlinear(skb) ||
3957 skb_headroom(skb) < XDP_PACKET_HEADROOM) {
3958 int hroom = XDP_PACKET_HEADROOM - skb_headroom(skb);
3959 int troom = skb->tail + skb->data_len - skb->end;
3960
3961 /* In case we have to go down the path and also linearize,
3962 * then lets do the pskb_expand_head() work just once here.
3963 */
3964 if (pskb_expand_head(skb,
3965 hroom > 0 ? ALIGN(hroom, NET_SKB_PAD) : 0,
3966 troom > 0 ? troom + 128 : 0, GFP_ATOMIC))
3967 goto do_drop;
3968 if (skb_linearize(skb))
3969 goto do_drop;
3970 }
3971
3972 /* The XDP program wants to see the packet starting at the MAC
3973 * header.
3974 */
3975 mac_len = skb->data - skb_mac_header(skb);
3976 hlen = skb_headlen(skb) + mac_len;
3977 xdp.data = skb->data - mac_len;
3978 xdp.data_meta = xdp.data;
3979 xdp.data_end = xdp.data + hlen;
3980 xdp.data_hard_start = skb->data - skb_headroom(skb);
3981 orig_data = xdp.data;
3982
3983 act = bpf_prog_run_xdp(xdp_prog, &xdp);
3984
3985 off = xdp.data - orig_data;
3986 if (off > 0)
3987 __skb_pull(skb, off);
3988 else if (off < 0)
3989 __skb_push(skb, -off);
3990 skb->mac_header += off;
3991
3992 switch (act) {
3993 case XDP_REDIRECT:
3994 case XDP_TX:
3995 __skb_push(skb, mac_len);
3996 break;
3997 case XDP_PASS:
3998 metalen = xdp.data - xdp.data_meta;
3999 if (metalen)
4000 skb_metadata_set(skb, metalen);
4001 break;
4002 default:
4003 bpf_warn_invalid_xdp_action(act);
4004 /* fall through */
4005 case XDP_ABORTED:
4006 trace_xdp_exception(skb->dev, xdp_prog, act);
4007 /* fall through */
4008 case XDP_DROP:
4009 do_drop:
4010 kfree_skb(skb);
4011 break;
4012 }
4013
4014 return act;
4015 }
4016
4017 /* When doing generic XDP we have to bypass the qdisc layer and the
4018 * network taps in order to match in-driver-XDP behavior.
4019 */
4020 void generic_xdp_tx(struct sk_buff *skb, struct bpf_prog *xdp_prog)
4021 {
4022 struct net_device *dev = skb->dev;
4023 struct netdev_queue *txq;
4024 bool free_skb = true;
4025 int cpu, rc;
4026
4027 txq = netdev_pick_tx(dev, skb, NULL);
4028 cpu = smp_processor_id();
4029 HARD_TX_LOCK(dev, txq, cpu);
4030 if (!netif_xmit_stopped(txq)) {
4031 rc = netdev_start_xmit(skb, dev, txq, 0);
4032 if (dev_xmit_complete(rc))
4033 free_skb = false;
4034 }
4035 HARD_TX_UNLOCK(dev, txq);
4036 if (free_skb) {
4037 trace_xdp_exception(dev, xdp_prog, XDP_TX);
4038 kfree_skb(skb);
4039 }
4040 }
4041 EXPORT_SYMBOL_GPL(generic_xdp_tx);
4042
4043 static struct static_key generic_xdp_needed __read_mostly;
4044
4045 int do_xdp_generic(struct bpf_prog *xdp_prog, struct sk_buff *skb)
4046 {
4047 if (xdp_prog) {
4048 u32 act = netif_receive_generic_xdp(skb, xdp_prog);
4049 int err;
4050
4051 if (act != XDP_PASS) {
4052 switch (act) {
4053 case XDP_REDIRECT:
4054 err = xdp_do_generic_redirect(skb->dev, skb,
4055 xdp_prog);
4056 if (err)
4057 goto out_redir;
4058 /* fallthru to submit skb */
4059 case XDP_TX:
4060 generic_xdp_tx(skb, xdp_prog);
4061 break;
4062 }
4063 return XDP_DROP;
4064 }
4065 }
4066 return XDP_PASS;
4067 out_redir:
4068 kfree_skb(skb);
4069 return XDP_DROP;
4070 }
4071 EXPORT_SYMBOL_GPL(do_xdp_generic);
4072
4073 static int netif_rx_internal(struct sk_buff *skb)
4074 {
4075 int ret;
4076
4077 net_timestamp_check(netdev_tstamp_prequeue, skb);
4078
4079 trace_netif_rx(skb);
4080
4081 if (static_key_false(&generic_xdp_needed)) {
4082 int ret;
4083
4084 preempt_disable();
4085 rcu_read_lock();
4086 ret = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog), skb);
4087 rcu_read_unlock();
4088 preempt_enable();
4089
4090 /* Consider XDP consuming the packet a success from
4091 * the netdev point of view we do not want to count
4092 * this as an error.
4093 */
4094 if (ret != XDP_PASS)
4095 return NET_RX_SUCCESS;
4096 }
4097
4098 #ifdef CONFIG_RPS
4099 if (static_key_false(&rps_needed)) {
4100 struct rps_dev_flow voidflow, *rflow = &voidflow;
4101 int cpu;
4102
4103 preempt_disable();
4104 rcu_read_lock();
4105
4106 cpu = get_rps_cpu(skb->dev, skb, &rflow);
4107 if (cpu < 0)
4108 cpu = smp_processor_id();
4109
4110 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
4111
4112 rcu_read_unlock();
4113 preempt_enable();
4114 } else
4115 #endif
4116 {
4117 unsigned int qtail;
4118
4119 ret = enqueue_to_backlog(skb, get_cpu(), &qtail);
4120 put_cpu();
4121 }
4122 return ret;
4123 }
4124
4125 /**
4126 * netif_rx - post buffer to the network code
4127 * @skb: buffer to post
4128 *
4129 * This function receives a packet from a device driver and queues it for
4130 * the upper (protocol) levels to process. It always succeeds. The buffer
4131 * may be dropped during processing for congestion control or by the
4132 * protocol layers.
4133 *
4134 * return values:
4135 * NET_RX_SUCCESS (no congestion)
4136 * NET_RX_DROP (packet was dropped)
4137 *
4138 */
4139
4140 int netif_rx(struct sk_buff *skb)
4141 {
4142 trace_netif_rx_entry(skb);
4143
4144 return netif_rx_internal(skb);
4145 }
4146 EXPORT_SYMBOL(netif_rx);
4147
4148 int netif_rx_ni(struct sk_buff *skb)
4149 {
4150 int err;
4151
4152 trace_netif_rx_ni_entry(skb);
4153
4154 preempt_disable();
4155 err = netif_rx_internal(skb);
4156 if (local_softirq_pending())
4157 do_softirq();
4158 preempt_enable();
4159
4160 return err;
4161 }
4162 EXPORT_SYMBOL(netif_rx_ni);
4163
4164 static __latent_entropy void net_tx_action(struct softirq_action *h)
4165 {
4166 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
4167
4168 if (sd->completion_queue) {
4169 struct sk_buff *clist;
4170
4171 local_irq_disable();
4172 clist = sd->completion_queue;
4173 sd->completion_queue = NULL;
4174 local_irq_enable();
4175
4176 while (clist) {
4177 struct sk_buff *skb = clist;
4178
4179 clist = clist->next;
4180
4181 WARN_ON(refcount_read(&skb->users));
4182 if (likely(get_kfree_skb_cb(skb)->reason == SKB_REASON_CONSUMED))
4183 trace_consume_skb(skb);
4184 else
4185 trace_kfree_skb(skb, net_tx_action);
4186
4187 if (skb->fclone != SKB_FCLONE_UNAVAILABLE)
4188 __kfree_skb(skb);
4189 else
4190 __kfree_skb_defer(skb);
4191 }
4192
4193 __kfree_skb_flush();
4194 }
4195
4196 if (sd->output_queue) {
4197 struct Qdisc *head;
4198
4199 local_irq_disable();
4200 head = sd->output_queue;
4201 sd->output_queue = NULL;
4202 sd->output_queue_tailp = &sd->output_queue;
4203 local_irq_enable();
4204
4205 while (head) {
4206 struct Qdisc *q = head;
4207 spinlock_t *root_lock;
4208
4209 head = head->next_sched;
4210
4211 root_lock = qdisc_lock(q);
4212 spin_lock(root_lock);
4213 /* We need to make sure head->next_sched is read
4214 * before clearing __QDISC_STATE_SCHED
4215 */
4216 smp_mb__before_atomic();
4217 clear_bit(__QDISC_STATE_SCHED, &q->state);
4218 qdisc_run(q);
4219 spin_unlock(root_lock);
4220 }
4221 }
4222 }
4223
4224 #if IS_ENABLED(CONFIG_BRIDGE) && IS_ENABLED(CONFIG_ATM_LANE)
4225 /* This hook is defined here for ATM LANE */
4226 int (*br_fdb_test_addr_hook)(struct net_device *dev,
4227 unsigned char *addr) __read_mostly;
4228 EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook);
4229 #endif
4230
4231 static inline struct sk_buff *
4232 sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
4233 struct net_device *orig_dev)
4234 {
4235 #ifdef CONFIG_NET_CLS_ACT
4236 struct mini_Qdisc *miniq = rcu_dereference_bh(skb->dev->miniq_ingress);
4237 struct tcf_result cl_res;
4238
4239 /* If there's at least one ingress present somewhere (so
4240 * we get here via enabled static key), remaining devices
4241 * that are not configured with an ingress qdisc will bail
4242 * out here.
4243 */
4244 if (!miniq)
4245 return skb;
4246
4247 if (*pt_prev) {
4248 *ret = deliver_skb(skb, *pt_prev, orig_dev);
4249 *pt_prev = NULL;
4250 }
4251
4252 qdisc_skb_cb(skb)->pkt_len = skb->len;
4253 skb->tc_at_ingress = 1;
4254 mini_qdisc_bstats_cpu_update(miniq, skb);
4255
4256 switch (tcf_classify(skb, miniq->filter_list, &cl_res, false)) {
4257 case TC_ACT_OK:
4258 case TC_ACT_RECLASSIFY:
4259 skb->tc_index = TC_H_MIN(cl_res.classid);
4260 break;
4261 case TC_ACT_SHOT:
4262 mini_qdisc_qstats_cpu_drop(miniq);
4263 kfree_skb(skb);
4264 return NULL;
4265 case TC_ACT_STOLEN:
4266 case TC_ACT_QUEUED:
4267 case TC_ACT_TRAP:
4268 consume_skb(skb);
4269 return NULL;
4270 case TC_ACT_REDIRECT:
4271 /* skb_mac_header check was done by cls/act_bpf, so
4272 * we can safely push the L2 header back before
4273 * redirecting to another netdev
4274 */
4275 __skb_push(skb, skb->mac_len);
4276 skb_do_redirect(skb);
4277 return NULL;
4278 default:
4279 break;
4280 }
4281 #endif /* CONFIG_NET_CLS_ACT */
4282 return skb;
4283 }
4284
4285 /**
4286 * netdev_is_rx_handler_busy - check if receive handler is registered
4287 * @dev: device to check
4288 *
4289 * Check if a receive handler is already registered for a given device.
4290 * Return true if there one.
4291 *
4292 * The caller must hold the rtnl_mutex.
4293 */
4294 bool netdev_is_rx_handler_busy(struct net_device *dev)
4295 {
4296 ASSERT_RTNL();
4297 return dev && rtnl_dereference(dev->rx_handler);
4298 }
4299 EXPORT_SYMBOL_GPL(netdev_is_rx_handler_busy);
4300
4301 /**
4302 * netdev_rx_handler_register - register receive handler
4303 * @dev: device to register a handler for
4304 * @rx_handler: receive handler to register
4305 * @rx_handler_data: data pointer that is used by rx handler
4306 *
4307 * Register a receive handler for a device. This handler will then be
4308 * called from __netif_receive_skb. A negative errno code is returned
4309 * on a failure.
4310 *
4311 * The caller must hold the rtnl_mutex.
4312 *
4313 * For a general description of rx_handler, see enum rx_handler_result.
4314 */
4315 int netdev_rx_handler_register(struct net_device *dev,
4316 rx_handler_func_t *rx_handler,
4317 void *rx_handler_data)
4318 {
4319 if (netdev_is_rx_handler_busy(dev))
4320 return -EBUSY;
4321
4322 /* Note: rx_handler_data must be set before rx_handler */
4323 rcu_assign_pointer(dev->rx_handler_data, rx_handler_data);
4324 rcu_assign_pointer(dev->rx_handler, rx_handler);
4325
4326 return 0;
4327 }
4328 EXPORT_SYMBOL_GPL(netdev_rx_handler_register);
4329
4330 /**
4331 * netdev_rx_handler_unregister - unregister receive handler
4332 * @dev: device to unregister a handler from
4333 *
4334 * Unregister a receive handler from a device.
4335 *
4336 * The caller must hold the rtnl_mutex.
4337 */
4338 void netdev_rx_handler_unregister(struct net_device *dev)
4339 {
4340
4341 ASSERT_RTNL();
4342 RCU_INIT_POINTER(dev->rx_handler, NULL);
4343 /* a reader seeing a non NULL rx_handler in a rcu_read_lock()
4344 * section has a guarantee to see a non NULL rx_handler_data
4345 * as well.
4346 */
4347 synchronize_net();
4348 RCU_INIT_POINTER(dev->rx_handler_data, NULL);
4349 }
4350 EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister);
4351
4352 /*
4353 * Limit the use of PFMEMALLOC reserves to those protocols that implement
4354 * the special handling of PFMEMALLOC skbs.
4355 */
4356 static bool skb_pfmemalloc_protocol(struct sk_buff *skb)
4357 {
4358 switch (skb->protocol) {
4359 case htons(ETH_P_ARP):
4360 case htons(ETH_P_IP):
4361 case htons(ETH_P_IPV6):
4362 case htons(ETH_P_8021Q):
4363 case htons(ETH_P_8021AD):
4364 return true;
4365 default:
4366 return false;
4367 }
4368 }
4369
4370 static inline int nf_ingress(struct sk_buff *skb, struct packet_type **pt_prev,
4371 int *ret, struct net_device *orig_dev)
4372 {
4373 #ifdef CONFIG_NETFILTER_INGRESS
4374 if (nf_hook_ingress_active(skb)) {
4375 int ingress_retval;
4376
4377 if (*pt_prev) {
4378 *ret = deliver_skb(skb, *pt_prev, orig_dev);
4379 *pt_prev = NULL;
4380 }
4381
4382 rcu_read_lock();
4383 ingress_retval = nf_hook_ingress(skb);
4384 rcu_read_unlock();
4385 return ingress_retval;
4386 }
4387 #endif /* CONFIG_NETFILTER_INGRESS */
4388 return 0;
4389 }
4390
4391 static int __netif_receive_skb_core(struct sk_buff *skb, bool pfmemalloc)
4392 {
4393 struct packet_type *ptype, *pt_prev;
4394 rx_handler_func_t *rx_handler;
4395 struct net_device *orig_dev;
4396 bool deliver_exact = false;
4397 int ret = NET_RX_DROP;
4398 __be16 type;
4399
4400 net_timestamp_check(!netdev_tstamp_prequeue, skb);
4401
4402 trace_netif_receive_skb(skb);
4403
4404 orig_dev = skb->dev;
4405
4406 skb_reset_network_header(skb);
4407 if (!skb_transport_header_was_set(skb))
4408 skb_reset_transport_header(skb);
4409 skb_reset_mac_len(skb);
4410
4411 pt_prev = NULL;
4412
4413 another_round:
4414 skb->skb_iif = skb->dev->ifindex;
4415
4416 __this_cpu_inc(softnet_data.processed);
4417
4418 if (skb->protocol == cpu_to_be16(ETH_P_8021Q) ||
4419 skb->protocol == cpu_to_be16(ETH_P_8021AD)) {
4420 skb = skb_vlan_untag(skb);
4421 if (unlikely(!skb))
4422 goto out;
4423 }
4424
4425 if (skb_skip_tc_classify(skb))
4426 goto skip_classify;
4427
4428 if (pfmemalloc)
4429 goto skip_taps;
4430
4431 list_for_each_entry_rcu(ptype, &ptype_all, list) {
4432 if (pt_prev)
4433 ret = deliver_skb(skb, pt_prev, orig_dev);
4434 pt_prev = ptype;
4435 }
4436
4437 list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) {
4438 if (pt_prev)
4439 ret = deliver_skb(skb, pt_prev, orig_dev);
4440 pt_prev = ptype;
4441 }
4442
4443 skip_taps:
4444 #ifdef CONFIG_NET_INGRESS
4445 if (static_key_false(&ingress_needed)) {
4446 skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev);
4447 if (!skb)
4448 goto out;
4449
4450 if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0)
4451 goto out;
4452 }
4453 #endif
4454 skb_reset_tc(skb);
4455 skip_classify:
4456 if (pfmemalloc && !skb_pfmemalloc_protocol(skb))
4457 goto drop;
4458
4459 if (skb_vlan_tag_present(skb)) {
4460 if (pt_prev) {
4461 ret = deliver_skb(skb, pt_prev, orig_dev);
4462 pt_prev = NULL;
4463 }
4464 if (vlan_do_receive(&skb))
4465 goto another_round;
4466 else if (unlikely(!skb))
4467 goto out;
4468 }
4469
4470 rx_handler = rcu_dereference(skb->dev->rx_handler);
4471 if (rx_handler) {
4472 if (pt_prev) {
4473 ret = deliver_skb(skb, pt_prev, orig_dev);
4474 pt_prev = NULL;
4475 }
4476 switch (rx_handler(&skb)) {
4477 case RX_HANDLER_CONSUMED:
4478 ret = NET_RX_SUCCESS;
4479 goto out;
4480 case RX_HANDLER_ANOTHER:
4481 goto another_round;
4482 case RX_HANDLER_EXACT:
4483 deliver_exact = true;
4484 case RX_HANDLER_PASS:
4485 break;
4486 default:
4487 BUG();
4488 }
4489 }
4490
4491 if (unlikely(skb_vlan_tag_present(skb))) {
4492 if (skb_vlan_tag_get_id(skb))
4493 skb->pkt_type = PACKET_OTHERHOST;
4494 /* Note: we might in the future use prio bits
4495 * and set skb->priority like in vlan_do_receive()
4496 * For the time being, just ignore Priority Code Point
4497 */
4498 skb->vlan_tci = 0;
4499 }
4500
4501 type = skb->protocol;
4502
4503 /* deliver only exact match when indicated */
4504 if (likely(!deliver_exact)) {
4505 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
4506 &ptype_base[ntohs(type) &
4507 PTYPE_HASH_MASK]);
4508 }
4509
4510 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
4511 &orig_dev->ptype_specific);
4512
4513 if (unlikely(skb->dev != orig_dev)) {
4514 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
4515 &skb->dev->ptype_specific);
4516 }
4517
4518 if (pt_prev) {
4519 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
4520 goto drop;
4521 else
4522 ret = pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
4523 } else {
4524 drop:
4525 if (!deliver_exact)
4526 atomic_long_inc(&skb->dev->rx_dropped);
4527 else
4528 atomic_long_inc(&skb->dev->rx_nohandler);
4529 kfree_skb(skb);
4530 /* Jamal, now you will not able to escape explaining
4531 * me how you were going to use this. :-)
4532 */
4533 ret = NET_RX_DROP;
4534 }
4535
4536 out:
4537 return ret;
4538 }
4539
4540 /**
4541 * netif_receive_skb_core - special purpose version of netif_receive_skb
4542 * @skb: buffer to process
4543 *
4544 * More direct receive version of netif_receive_skb(). It should
4545 * only be used by callers that have a need to skip RPS and Generic XDP.
4546 * Caller must also take care of handling if (page_is_)pfmemalloc.
4547 *
4548 * This function may only be called from softirq context and interrupts
4549 * should be enabled.
4550 *
4551 * Return values (usually ignored):
4552 * NET_RX_SUCCESS: no congestion
4553 * NET_RX_DROP: packet was dropped
4554 */
4555 int netif_receive_skb_core(struct sk_buff *skb)
4556 {
4557 int ret;
4558
4559 rcu_read_lock();
4560 ret = __netif_receive_skb_core(skb, false);
4561 rcu_read_unlock();
4562
4563 return ret;
4564 }
4565 EXPORT_SYMBOL(netif_receive_skb_core);
4566
4567 static int __netif_receive_skb(struct sk_buff *skb)
4568 {
4569 int ret;
4570
4571 if (sk_memalloc_socks() && skb_pfmemalloc(skb)) {
4572 unsigned int noreclaim_flag;
4573
4574 /*
4575 * PFMEMALLOC skbs are special, they should
4576 * - be delivered to SOCK_MEMALLOC sockets only
4577 * - stay away from userspace
4578 * - have bounded memory usage
4579 *
4580 * Use PF_MEMALLOC as this saves us from propagating the allocation
4581 * context down to all allocation sites.
4582 */
4583 noreclaim_flag = memalloc_noreclaim_save();
4584 ret = __netif_receive_skb_core(skb, true);
4585 memalloc_noreclaim_restore(noreclaim_flag);
4586 } else
4587 ret = __netif_receive_skb_core(skb, false);
4588
4589 return ret;
4590 }
4591
4592 static int generic_xdp_install(struct net_device *dev, struct netdev_bpf *xdp)
4593 {
4594 struct bpf_prog *old = rtnl_dereference(dev->xdp_prog);
4595 struct bpf_prog *new = xdp->prog;
4596 int ret = 0;
4597
4598 switch (xdp->command) {
4599 case XDP_SETUP_PROG:
4600 rcu_assign_pointer(dev->xdp_prog, new);
4601 if (old)
4602 bpf_prog_put(old);
4603
4604 if (old && !new) {
4605 static_key_slow_dec(&generic_xdp_needed);
4606 } else if (new && !old) {
4607 static_key_slow_inc(&generic_xdp_needed);
4608 dev_disable_lro(dev);
4609 }
4610 break;
4611
4612 case XDP_QUERY_PROG:
4613 xdp->prog_attached = !!old;
4614 xdp->prog_id = old ? old->aux->id : 0;
4615 break;
4616
4617 default:
4618 ret = -EINVAL;
4619 break;
4620 }
4621
4622 return ret;
4623 }
4624
4625 static int netif_receive_skb_internal(struct sk_buff *skb)
4626 {
4627 int ret;
4628
4629 net_timestamp_check(netdev_tstamp_prequeue, skb);
4630
4631 if (skb_defer_rx_timestamp(skb))
4632 return NET_RX_SUCCESS;
4633
4634 if (static_key_false(&generic_xdp_needed)) {
4635 int ret;
4636
4637 preempt_disable();
4638 rcu_read_lock();
4639 ret = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog), skb);
4640 rcu_read_unlock();
4641 preempt_enable();
4642
4643 if (ret != XDP_PASS)
4644 return NET_RX_DROP;
4645 }
4646
4647 rcu_read_lock();
4648 #ifdef CONFIG_RPS
4649 if (static_key_false(&rps_needed)) {
4650 struct rps_dev_flow voidflow, *rflow = &voidflow;
4651 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
4652
4653 if (cpu >= 0) {
4654 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
4655 rcu_read_unlock();
4656 return ret;
4657 }
4658 }
4659 #endif
4660 ret = __netif_receive_skb(skb);
4661 rcu_read_unlock();
4662 return ret;
4663 }
4664
4665 /**
4666 * netif_receive_skb - process receive buffer from network
4667 * @skb: buffer to process
4668 *
4669 * netif_receive_skb() is the main receive data processing function.
4670 * It always succeeds. The buffer may be dropped during processing
4671 * for congestion control or by the protocol layers.
4672 *
4673 * This function may only be called from softirq context and interrupts
4674 * should be enabled.
4675 *
4676 * Return values (usually ignored):
4677 * NET_RX_SUCCESS: no congestion
4678 * NET_RX_DROP: packet was dropped
4679 */
4680 int netif_receive_skb(struct sk_buff *skb)
4681 {
4682 trace_netif_receive_skb_entry(skb);
4683
4684 return netif_receive_skb_internal(skb);
4685 }
4686 EXPORT_SYMBOL(netif_receive_skb);
4687
4688 DEFINE_PER_CPU(struct work_struct, flush_works);
4689
4690 /* Network device is going away, flush any packets still pending */
4691 static void flush_backlog(struct work_struct *work)
4692 {
4693 struct sk_buff *skb, *tmp;
4694 struct softnet_data *sd;
4695
4696 local_bh_disable();
4697 sd = this_cpu_ptr(&softnet_data);
4698
4699 local_irq_disable();
4700 rps_lock(sd);
4701 skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) {
4702 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
4703 __skb_unlink(skb, &sd->input_pkt_queue);
4704 kfree_skb(skb);
4705 input_queue_head_incr(sd);
4706 }
4707 }
4708 rps_unlock(sd);
4709 local_irq_enable();
4710
4711 skb_queue_walk_safe(&sd->process_queue, skb, tmp) {
4712 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
4713 __skb_unlink(skb, &sd->process_queue);
4714 kfree_skb(skb);
4715 input_queue_head_incr(sd);
4716 }
4717 }
4718 local_bh_enable();
4719 }
4720
4721 static void flush_all_backlogs(void)
4722 {
4723 unsigned int cpu;
4724
4725 get_online_cpus();
4726
4727 for_each_online_cpu(cpu)
4728 queue_work_on(cpu, system_highpri_wq,
4729 per_cpu_ptr(&flush_works, cpu));
4730
4731 for_each_online_cpu(cpu)
4732 flush_work(per_cpu_ptr(&flush_works, cpu));
4733
4734 put_online_cpus();
4735 }
4736
4737 static int napi_gro_complete(struct sk_buff *skb)
4738 {
4739 struct packet_offload *ptype;
4740 __be16 type = skb->protocol;
4741 struct list_head *head = &offload_base;
4742 int err = -ENOENT;
4743
4744 BUILD_BUG_ON(sizeof(struct napi_gro_cb) > sizeof(skb->cb));
4745
4746 if (NAPI_GRO_CB(skb)->count == 1) {
4747 skb_shinfo(skb)->gso_size = 0;
4748 goto out;
4749 }
4750
4751 rcu_read_lock();
4752 list_for_each_entry_rcu(ptype, head, list) {
4753 if (ptype->type != type || !ptype->callbacks.gro_complete)
4754 continue;
4755
4756 err = ptype->callbacks.gro_complete(skb, 0);
4757 break;
4758 }
4759 rcu_read_unlock();
4760
4761 if (err) {
4762 WARN_ON(&ptype->list == head);
4763 kfree_skb(skb);
4764 return NET_RX_SUCCESS;
4765 }
4766
4767 out:
4768 return netif_receive_skb_internal(skb);
4769 }
4770
4771 /* napi->gro_list contains packets ordered by age.
4772 * youngest packets at the head of it.
4773 * Complete skbs in reverse order to reduce latencies.
4774 */
4775 void napi_gro_flush(struct napi_struct *napi, bool flush_old)
4776 {
4777 struct sk_buff *skb, *prev = NULL;
4778
4779 /* scan list and build reverse chain */
4780 for (skb = napi->gro_list; skb != NULL; skb = skb->next) {
4781 skb->prev = prev;
4782 prev = skb;
4783 }
4784
4785 for (skb = prev; skb; skb = prev) {
4786 skb->next = NULL;
4787
4788 if (flush_old && NAPI_GRO_CB(skb)->age == jiffies)
4789 return;
4790
4791 prev = skb->prev;
4792 napi_gro_complete(skb);
4793 napi->gro_count--;
4794 }
4795
4796 napi->gro_list = NULL;
4797 }
4798 EXPORT_SYMBOL(napi_gro_flush);
4799
4800 static void gro_list_prepare(struct napi_struct *napi, struct sk_buff *skb)
4801 {
4802 struct sk_buff *p;
4803 unsigned int maclen = skb->dev->hard_header_len;
4804 u32 hash = skb_get_hash_raw(skb);
4805
4806 for (p = napi->gro_list; p; p = p->next) {
4807 unsigned long diffs;
4808
4809 NAPI_GRO_CB(p)->flush = 0;
4810
4811 if (hash != skb_get_hash_raw(p)) {
4812 NAPI_GRO_CB(p)->same_flow = 0;
4813 continue;
4814 }
4815
4816 diffs = (unsigned long)p->dev ^ (unsigned long)skb->dev;
4817 diffs |= p->vlan_tci ^ skb->vlan_tci;
4818 diffs |= skb_metadata_dst_cmp(p, skb);
4819 diffs |= skb_metadata_differs(p, skb);
4820 if (maclen == ETH_HLEN)
4821 diffs |= compare_ether_header(skb_mac_header(p),
4822 skb_mac_header(skb));
4823 else if (!diffs)
4824 diffs = memcmp(skb_mac_header(p),
4825 skb_mac_header(skb),
4826 maclen);
4827 NAPI_GRO_CB(p)->same_flow = !diffs;
4828 }
4829 }
4830
4831 static void skb_gro_reset_offset(struct sk_buff *skb)
4832 {
4833 const struct skb_shared_info *pinfo = skb_shinfo(skb);
4834 const skb_frag_t *frag0 = &pinfo->frags[0];
4835
4836 NAPI_GRO_CB(skb)->data_offset = 0;
4837 NAPI_GRO_CB(skb)->frag0 = NULL;
4838 NAPI_GRO_CB(skb)->frag0_len = 0;
4839
4840 if (skb_mac_header(skb) == skb_tail_pointer(skb) &&
4841 pinfo->nr_frags &&
4842 !PageHighMem(skb_frag_page(frag0))) {
4843 NAPI_GRO_CB(skb)->frag0 = skb_frag_address(frag0);
4844 NAPI_GRO_CB(skb)->frag0_len = min_t(unsigned int,
4845 skb_frag_size(frag0),
4846 skb->end - skb->tail);
4847 }
4848 }
4849
4850 static void gro_pull_from_frag0(struct sk_buff *skb, int grow)
4851 {
4852 struct skb_shared_info *pinfo = skb_shinfo(skb);
4853
4854 BUG_ON(skb->end - skb->tail < grow);
4855
4856 memcpy(skb_tail_pointer(skb), NAPI_GRO_CB(skb)->frag0, grow);
4857
4858 skb->data_len -= grow;
4859 skb->tail += grow;
4860
4861 pinfo->frags[0].page_offset += grow;
4862 skb_frag_size_sub(&pinfo->frags[0], grow);
4863
4864 if (unlikely(!skb_frag_size(&pinfo->frags[0]))) {
4865 skb_frag_unref(skb, 0);
4866 memmove(pinfo->frags, pinfo->frags + 1,
4867 --pinfo->nr_frags * sizeof(pinfo->frags[0]));
4868 }
4869 }
4870
4871 static enum gro_result dev_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
4872 {
4873 struct sk_buff **pp = NULL;
4874 struct packet_offload *ptype;
4875 __be16 type = skb->protocol;
4876 struct list_head *head = &offload_base;
4877 int same_flow;
4878 enum gro_result ret;
4879 int grow;
4880
4881 if (netif_elide_gro(skb->dev))
4882 goto normal;
4883
4884 gro_list_prepare(napi, skb);
4885
4886 rcu_read_lock();
4887 list_for_each_entry_rcu(ptype, head, list) {
4888 if (ptype->type != type || !ptype->callbacks.gro_receive)
4889 continue;
4890
4891 skb_set_network_header(skb, skb_gro_offset(skb));
4892 skb_reset_mac_len(skb);
4893 NAPI_GRO_CB(skb)->same_flow = 0;
4894 NAPI_GRO_CB(skb)->flush = skb_is_gso(skb) || skb_has_frag_list(skb);
4895 NAPI_GRO_CB(skb)->free = 0;
4896 NAPI_GRO_CB(skb)->encap_mark = 0;
4897 NAPI_GRO_CB(skb)->recursion_counter = 0;
4898 NAPI_GRO_CB(skb)->is_fou = 0;
4899 NAPI_GRO_CB(skb)->is_atomic = 1;
4900 NAPI_GRO_CB(skb)->gro_remcsum_start = 0;
4901
4902 /* Setup for GRO checksum validation */
4903 switch (skb->ip_summed) {
4904 case CHECKSUM_COMPLETE:
4905 NAPI_GRO_CB(skb)->csum = skb->csum;
4906 NAPI_GRO_CB(skb)->csum_valid = 1;
4907 NAPI_GRO_CB(skb)->csum_cnt = 0;
4908 break;
4909 case CHECKSUM_UNNECESSARY:
4910 NAPI_GRO_CB(skb)->csum_cnt = skb->csum_level + 1;
4911 NAPI_GRO_CB(skb)->csum_valid = 0;
4912 break;
4913 default:
4914 NAPI_GRO_CB(skb)->csum_cnt = 0;
4915 NAPI_GRO_CB(skb)->csum_valid = 0;
4916 }
4917
4918 pp = ptype->callbacks.gro_receive(&napi->gro_list, skb);
4919 break;
4920 }
4921 rcu_read_unlock();
4922
4923 if (&ptype->list == head)
4924 goto normal;
4925
4926 if (IS_ERR(pp) && PTR_ERR(pp) == -EINPROGRESS) {
4927 ret = GRO_CONSUMED;
4928 goto ok;
4929 }
4930
4931 same_flow = NAPI_GRO_CB(skb)->same_flow;
4932 ret = NAPI_GRO_CB(skb)->free ? GRO_MERGED_FREE : GRO_MERGED;
4933
4934 if (pp) {
4935 struct sk_buff *nskb = *pp;
4936
4937 *pp = nskb->next;
4938 nskb->next = NULL;
4939 napi_gro_complete(nskb);
4940 napi->gro_count--;
4941 }
4942
4943 if (same_flow)
4944 goto ok;
4945
4946 if (NAPI_GRO_CB(skb)->flush)
4947 goto normal;
4948
4949 if (unlikely(napi->gro_count >= MAX_GRO_SKBS)) {
4950 struct sk_buff *nskb = napi->gro_list;
4951
4952 /* locate the end of the list to select the 'oldest' flow */
4953 while (nskb->next) {
4954 pp = &nskb->next;
4955 nskb = *pp;
4956 }
4957 *pp = NULL;
4958 nskb->next = NULL;
4959 napi_gro_complete(nskb);
4960 } else {
4961 napi->gro_count++;
4962 }
4963 NAPI_GRO_CB(skb)->count = 1;
4964 NAPI_GRO_CB(skb)->age = jiffies;
4965 NAPI_GRO_CB(skb)->last = skb;
4966 skb_shinfo(skb)->gso_size = skb_gro_len(skb);
4967 skb->next = napi->gro_list;
4968 napi->gro_list = skb;
4969 ret = GRO_HELD;
4970
4971 pull:
4972 grow = skb_gro_offset(skb) - skb_headlen(skb);
4973 if (grow > 0)
4974 gro_pull_from_frag0(skb, grow);
4975 ok:
4976 return ret;
4977
4978 normal:
4979 ret = GRO_NORMAL;
4980 goto pull;
4981 }
4982
4983 struct packet_offload *gro_find_receive_by_type(__be16 type)
4984 {
4985 struct list_head *offload_head = &offload_base;
4986 struct packet_offload *ptype;
4987
4988 list_for_each_entry_rcu(ptype, offload_head, list) {
4989 if (ptype->type != type || !ptype->callbacks.gro_receive)
4990 continue;
4991 return ptype;
4992 }
4993 return NULL;
4994 }
4995 EXPORT_SYMBOL(gro_find_receive_by_type);
4996
4997 struct packet_offload *gro_find_complete_by_type(__be16 type)
4998 {
4999 struct list_head *offload_head = &offload_base;
5000 struct packet_offload *ptype;
5001
5002 list_for_each_entry_rcu(ptype, offload_head, list) {
5003 if (ptype->type != type || !ptype->callbacks.gro_complete)
5004 continue;
5005 return ptype;
5006 }
5007 return NULL;
5008 }
5009 EXPORT_SYMBOL(gro_find_complete_by_type);
5010
5011 static void napi_skb_free_stolen_head(struct sk_buff *skb)
5012 {
5013 skb_dst_drop(skb);
5014 secpath_reset(skb);
5015 kmem_cache_free(skbuff_head_cache, skb);
5016 }
5017
5018 static gro_result_t napi_skb_finish(gro_result_t ret, struct sk_buff *skb)
5019 {
5020 switch (ret) {
5021 case GRO_NORMAL:
5022 if (netif_receive_skb_internal(skb))
5023 ret = GRO_DROP;
5024 break;
5025
5026 case GRO_DROP:
5027 kfree_skb(skb);
5028 break;
5029
5030 case GRO_MERGED_FREE:
5031 if (NAPI_GRO_CB(skb)->free == NAPI_GRO_FREE_STOLEN_HEAD)
5032 napi_skb_free_stolen_head(skb);
5033 else
5034 __kfree_skb(skb);
5035 break;
5036
5037 case GRO_HELD:
5038 case GRO_MERGED:
5039 case GRO_CONSUMED:
5040 break;
5041 }
5042
5043 return ret;
5044 }
5045
5046 gro_result_t napi_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
5047 {
5048 skb_mark_napi_id(skb, napi);
5049 trace_napi_gro_receive_entry(skb);
5050
5051 skb_gro_reset_offset(skb);
5052
5053 return napi_skb_finish(dev_gro_receive(napi, skb), skb);
5054 }
5055 EXPORT_SYMBOL(napi_gro_receive);
5056
5057 static void napi_reuse_skb(struct napi_struct *napi, struct sk_buff *skb)
5058 {
5059 if (unlikely(skb->pfmemalloc)) {
5060 consume_skb(skb);
5061 return;
5062 }
5063 __skb_pull(skb, skb_headlen(skb));
5064 /* restore the reserve we had after netdev_alloc_skb_ip_align() */
5065 skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN - skb_headroom(skb));
5066 skb->vlan_tci = 0;
5067 skb->dev = napi->dev;
5068 skb->skb_iif = 0;
5069
5070 /* eth_type_trans() assumes pkt_type is PACKET_HOST */
5071 skb->pkt_type = PACKET_HOST;
5072
5073 skb->encapsulation = 0;
5074 skb_shinfo(skb)->gso_type = 0;
5075 skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
5076 secpath_reset(skb);
5077
5078 napi->skb = skb;
5079 }
5080
5081 struct sk_buff *napi_get_frags(struct napi_struct *napi)
5082 {
5083 struct sk_buff *skb = napi->skb;
5084
5085 if (!skb) {
5086 skb = napi_alloc_skb(napi, GRO_MAX_HEAD);
5087 if (skb) {
5088 napi->skb = skb;
5089 skb_mark_napi_id(skb, napi);
5090 }
5091 }
5092 return skb;
5093 }
5094 EXPORT_SYMBOL(napi_get_frags);
5095
5096 static gro_result_t napi_frags_finish(struct napi_struct *napi,
5097 struct sk_buff *skb,
5098 gro_result_t ret)
5099 {
5100 switch (ret) {
5101 case GRO_NORMAL:
5102 case GRO_HELD:
5103 __skb_push(skb, ETH_HLEN);
5104 skb->protocol = eth_type_trans(skb, skb->dev);
5105 if (ret == GRO_NORMAL && netif_receive_skb_internal(skb))
5106 ret = GRO_DROP;
5107 break;
5108
5109 case GRO_DROP:
5110 napi_reuse_skb(napi, skb);
5111 break;
5112
5113 case GRO_MERGED_FREE:
5114 if (NAPI_GRO_CB(skb)->free == NAPI_GRO_FREE_STOLEN_HEAD)
5115 napi_skb_free_stolen_head(skb);
5116 else
5117 napi_reuse_skb(napi, skb);
5118 break;
5119
5120 case GRO_MERGED:
5121 case GRO_CONSUMED:
5122 break;
5123 }
5124
5125 return ret;
5126 }
5127
5128 /* Upper GRO stack assumes network header starts at gro_offset=0
5129 * Drivers could call both napi_gro_frags() and napi_gro_receive()
5130 * We copy ethernet header into skb->data to have a common layout.
5131 */
5132 static struct sk_buff *napi_frags_skb(struct napi_struct *napi)
5133 {
5134 struct sk_buff *skb = napi->skb;
5135 const struct ethhdr *eth;
5136 unsigned int hlen = sizeof(*eth);
5137
5138 napi->skb = NULL;
5139
5140 skb_reset_mac_header(skb);
5141 skb_gro_reset_offset(skb);
5142
5143 if (unlikely(skb_gro_header_hard(skb, hlen))) {
5144 eth = skb_gro_header_slow(skb, hlen, 0);
5145 if (unlikely(!eth)) {
5146 net_warn_ratelimited("%s: dropping impossible skb from %s\n",
5147 __func__, napi->dev->name);
5148 napi_reuse_skb(napi, skb);
5149 return NULL;
5150 }
5151 } else {
5152 eth = (const struct ethhdr *)skb->data;
5153 gro_pull_from_frag0(skb, hlen);
5154 NAPI_GRO_CB(skb)->frag0 += hlen;
5155 NAPI_GRO_CB(skb)->frag0_len -= hlen;
5156 }
5157 __skb_pull(skb, hlen);
5158
5159 /*
5160 * This works because the only protocols we care about don't require
5161 * special handling.
5162 * We'll fix it up properly in napi_frags_finish()
5163 */
5164 skb->protocol = eth->h_proto;
5165
5166 return skb;
5167 }
5168
5169 gro_result_t napi_gro_frags(struct napi_struct *napi)
5170 {
5171 struct sk_buff *skb = napi_frags_skb(napi);
5172
5173 if (!skb)
5174 return GRO_DROP;
5175
5176 trace_napi_gro_frags_entry(skb);
5177
5178 return napi_frags_finish(napi, skb, dev_gro_receive(napi, skb));
5179 }
5180 EXPORT_SYMBOL(napi_gro_frags);
5181
5182 /* Compute the checksum from gro_offset and return the folded value
5183 * after adding in any pseudo checksum.
5184 */
5185 __sum16 __skb_gro_checksum_complete(struct sk_buff *skb)
5186 {
5187 __wsum wsum;
5188 __sum16 sum;
5189
5190 wsum = skb_checksum(skb, skb_gro_offset(skb), skb_gro_len(skb), 0);
5191
5192 /* NAPI_GRO_CB(skb)->csum holds pseudo checksum */
5193 sum = csum_fold(csum_add(NAPI_GRO_CB(skb)->csum, wsum));
5194 if (likely(!sum)) {
5195 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
5196 !skb->csum_complete_sw)
5197 netdev_rx_csum_fault(skb->dev);
5198 }
5199
5200 NAPI_GRO_CB(skb)->csum = wsum;
5201 NAPI_GRO_CB(skb)->csum_valid = 1;
5202
5203 return sum;
5204 }
5205 EXPORT_SYMBOL(__skb_gro_checksum_complete);
5206
5207 static void net_rps_send_ipi(struct softnet_data *remsd)
5208 {
5209 #ifdef CONFIG_RPS
5210 while (remsd) {
5211 struct softnet_data *next = remsd->rps_ipi_next;
5212
5213 if (cpu_online(remsd->cpu))
5214 smp_call_function_single_async(remsd->cpu, &remsd->csd);
5215 remsd = next;
5216 }
5217 #endif
5218 }
5219
5220 /*
5221 * net_rps_action_and_irq_enable sends any pending IPI's for rps.
5222 * Note: called with local irq disabled, but exits with local irq enabled.
5223 */
5224 static void net_rps_action_and_irq_enable(struct softnet_data *sd)
5225 {
5226 #ifdef CONFIG_RPS
5227 struct softnet_data *remsd = sd->rps_ipi_list;
5228
5229 if (remsd) {
5230 sd->rps_ipi_list = NULL;
5231
5232 local_irq_enable();
5233
5234 /* Send pending IPI's to kick RPS processing on remote cpus. */
5235 net_rps_send_ipi(remsd);
5236 } else
5237 #endif
5238 local_irq_enable();
5239 }
5240
5241 static bool sd_has_rps_ipi_waiting(struct softnet_data *sd)
5242 {
5243 #ifdef CONFIG_RPS
5244 return sd->rps_ipi_list != NULL;
5245 #else
5246 return false;
5247 #endif
5248 }
5249
5250 static int process_backlog(struct napi_struct *napi, int quota)
5251 {
5252 struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
5253 bool again = true;
5254 int work = 0;
5255
5256 /* Check if we have pending ipi, its better to send them now,
5257 * not waiting net_rx_action() end.
5258 */
5259 if (sd_has_rps_ipi_waiting(sd)) {
5260 local_irq_disable();
5261 net_rps_action_and_irq_enable(sd);
5262 }
5263
5264 napi->weight = dev_rx_weight;
5265 while (again) {
5266 struct sk_buff *skb;
5267
5268 while ((skb = __skb_dequeue(&sd->process_queue))) {
5269 rcu_read_lock();
5270 __netif_receive_skb(skb);
5271 rcu_read_unlock();
5272 input_queue_head_incr(sd);
5273 if (++work >= quota)
5274 return work;
5275
5276 }
5277
5278 local_irq_disable();
5279 rps_lock(sd);
5280 if (skb_queue_empty(&sd->input_pkt_queue)) {
5281 /*
5282 * Inline a custom version of __napi_complete().
5283 * only current cpu owns and manipulates this napi,
5284 * and NAPI_STATE_SCHED is the only possible flag set
5285 * on backlog.
5286 * We can use a plain write instead of clear_bit(),
5287 * and we dont need an smp_mb() memory barrier.
5288 */
5289 napi->state = 0;
5290 again = false;
5291 } else {
5292 skb_queue_splice_tail_init(&sd->input_pkt_queue,
5293 &sd->process_queue);
5294 }
5295 rps_unlock(sd);
5296 local_irq_enable();
5297 }
5298
5299 return work;
5300 }
5301
5302 /**
5303 * __napi_schedule - schedule for receive
5304 * @n: entry to schedule
5305 *
5306 * The entry's receive function will be scheduled to run.
5307 * Consider using __napi_schedule_irqoff() if hard irqs are masked.
5308 */
5309 void __napi_schedule(struct napi_struct *n)
5310 {
5311 unsigned long flags;
5312
5313 local_irq_save(flags);
5314 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
5315 local_irq_restore(flags);
5316 }
5317 EXPORT_SYMBOL(__napi_schedule);
5318
5319 /**
5320 * napi_schedule_prep - check if napi can be scheduled
5321 * @n: napi context
5322 *
5323 * Test if NAPI routine is already running, and if not mark
5324 * it as running. This is used as a condition variable
5325 * insure only one NAPI poll instance runs. We also make
5326 * sure there is no pending NAPI disable.
5327 */
5328 bool napi_schedule_prep(struct napi_struct *n)
5329 {
5330 unsigned long val, new;
5331
5332 do {
5333 val = READ_ONCE(n->state);
5334 if (unlikely(val & NAPIF_STATE_DISABLE))
5335 return false;
5336 new = val | NAPIF_STATE_SCHED;
5337
5338 /* Sets STATE_MISSED bit if STATE_SCHED was already set
5339 * This was suggested by Alexander Duyck, as compiler
5340 * emits better code than :
5341 * if (val & NAPIF_STATE_SCHED)
5342 * new |= NAPIF_STATE_MISSED;
5343 */
5344 new |= (val & NAPIF_STATE_SCHED) / NAPIF_STATE_SCHED *
5345 NAPIF_STATE_MISSED;
5346 } while (cmpxchg(&n->state, val, new) != val);
5347
5348 return !(val & NAPIF_STATE_SCHED);
5349 }
5350 EXPORT_SYMBOL(napi_schedule_prep);
5351
5352 /**
5353 * __napi_schedule_irqoff - schedule for receive
5354 * @n: entry to schedule
5355 *
5356 * Variant of __napi_schedule() assuming hard irqs are masked
5357 */
5358 void __napi_schedule_irqoff(struct napi_struct *n)
5359 {
5360 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
5361 }
5362 EXPORT_SYMBOL(__napi_schedule_irqoff);
5363
5364 bool napi_complete_done(struct napi_struct *n, int work_done)
5365 {
5366 unsigned long flags, val, new;
5367
5368 /*
5369 * 1) Don't let napi dequeue from the cpu poll list
5370 * just in case its running on a different cpu.
5371 * 2) If we are busy polling, do nothing here, we have
5372 * the guarantee we will be called later.
5373 */
5374 if (unlikely(n->state & (NAPIF_STATE_NPSVC |
5375 NAPIF_STATE_IN_BUSY_POLL)))
5376 return false;
5377
5378 if (n->gro_list) {
5379 unsigned long timeout = 0;
5380
5381 if (work_done)
5382 timeout = n->dev->gro_flush_timeout;
5383
5384 /* When the NAPI instance uses a timeout and keeps postponing
5385 * it, we need to bound somehow the time packets are kept in
5386 * the GRO layer
5387 */
5388 napi_gro_flush(n, !!timeout);
5389 if (timeout)
5390 hrtimer_start(&n->timer, ns_to_ktime(timeout),
5391 HRTIMER_MODE_REL_PINNED);
5392 }
5393 if (unlikely(!list_empty(&n->poll_list))) {
5394 /* If n->poll_list is not empty, we need to mask irqs */
5395 local_irq_save(flags);
5396 list_del_init(&n->poll_list);
5397 local_irq_restore(flags);
5398 }
5399
5400 do {
5401 val = READ_ONCE(n->state);
5402
5403 WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED));
5404
5405 new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED);
5406
5407 /* If STATE_MISSED was set, leave STATE_SCHED set,
5408 * because we will call napi->poll() one more time.
5409 * This C code was suggested by Alexander Duyck to help gcc.
5410 */
5411 new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED *
5412 NAPIF_STATE_SCHED;
5413 } while (cmpxchg(&n->state, val, new) != val);
5414
5415 if (unlikely(val & NAPIF_STATE_MISSED)) {
5416 __napi_schedule(n);
5417 return false;
5418 }
5419
5420 return true;
5421 }
5422 EXPORT_SYMBOL(napi_complete_done);
5423
5424 /* must be called under rcu_read_lock(), as we dont take a reference */
5425 static struct napi_struct *napi_by_id(unsigned int napi_id)
5426 {
5427 unsigned int hash = napi_id % HASH_SIZE(napi_hash);
5428 struct napi_struct *napi;
5429
5430 hlist_for_each_entry_rcu(napi, &napi_hash[hash], napi_hash_node)
5431 if (napi->napi_id == napi_id)
5432 return napi;
5433
5434 return NULL;
5435 }
5436
5437 #if defined(CONFIG_NET_RX_BUSY_POLL)
5438
5439 #define BUSY_POLL_BUDGET 8
5440
5441 static void busy_poll_stop(struct napi_struct *napi, void *have_poll_lock)
5442 {
5443 int rc;
5444
5445 /* Busy polling means there is a high chance device driver hard irq
5446 * could not grab NAPI_STATE_SCHED, and that NAPI_STATE_MISSED was
5447 * set in napi_schedule_prep().
5448 * Since we are about to call napi->poll() once more, we can safely
5449 * clear NAPI_STATE_MISSED.
5450 *
5451 * Note: x86 could use a single "lock and ..." instruction
5452 * to perform these two clear_bit()
5453 */
5454 clear_bit(NAPI_STATE_MISSED, &napi->state);
5455 clear_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state);
5456
5457 local_bh_disable();
5458
5459 /* All we really want here is to re-enable device interrupts.
5460 * Ideally, a new ndo_busy_poll_stop() could avoid another round.
5461 */
5462 rc = napi->poll(napi, BUSY_POLL_BUDGET);
5463 trace_napi_poll(napi, rc, BUSY_POLL_BUDGET);
5464 netpoll_poll_unlock(have_poll_lock);
5465 if (rc == BUSY_POLL_BUDGET)
5466 __napi_schedule(napi);
5467 local_bh_enable();
5468 }
5469
5470 void napi_busy_loop(unsigned int napi_id,
5471 bool (*loop_end)(void *, unsigned long),
5472 void *loop_end_arg)
5473 {
5474 unsigned long start_time = loop_end ? busy_loop_current_time() : 0;
5475 int (*napi_poll)(struct napi_struct *napi, int budget);
5476 void *have_poll_lock = NULL;
5477 struct napi_struct *napi;
5478
5479 restart:
5480 napi_poll = NULL;
5481
5482 rcu_read_lock();
5483
5484 napi = napi_by_id(napi_id);
5485 if (!napi)
5486 goto out;
5487
5488 preempt_disable();
5489 for (;;) {
5490 int work = 0;
5491
5492 local_bh_disable();
5493 if (!napi_poll) {
5494 unsigned long val = READ_ONCE(napi->state);
5495
5496 /* If multiple threads are competing for this napi,
5497 * we avoid dirtying napi->state as much as we can.
5498 */
5499 if (val & (NAPIF_STATE_DISABLE | NAPIF_STATE_SCHED |
5500 NAPIF_STATE_IN_BUSY_POLL))
5501 goto count;
5502 if (cmpxchg(&napi->state, val,
5503 val | NAPIF_STATE_IN_BUSY_POLL |
5504 NAPIF_STATE_SCHED) != val)
5505 goto count;
5506 have_poll_lock = netpoll_poll_lock(napi);
5507 napi_poll = napi->poll;
5508 }
5509 work = napi_poll(napi, BUSY_POLL_BUDGET);
5510 trace_napi_poll(napi, work, BUSY_POLL_BUDGET);
5511 count:
5512 if (work > 0)
5513 __NET_ADD_STATS(dev_net(napi->dev),
5514 LINUX_MIB_BUSYPOLLRXPACKETS, work);
5515 local_bh_enable();
5516
5517 if (!loop_end || loop_end(loop_end_arg, start_time))
5518 break;
5519
5520 if (unlikely(need_resched())) {
5521 if (napi_poll)
5522 busy_poll_stop(napi, have_poll_lock);
5523 preempt_enable();
5524 rcu_read_unlock();
5525 cond_resched();
5526 if (loop_end(loop_end_arg, start_time))
5527 return;
5528 goto restart;
5529 }
5530 cpu_relax();
5531 }
5532 if (napi_poll)
5533 busy_poll_stop(napi, have_poll_lock);
5534 preempt_enable();
5535 out:
5536 rcu_read_unlock();
5537 }
5538 EXPORT_SYMBOL(napi_busy_loop);
5539
5540 #endif /* CONFIG_NET_RX_BUSY_POLL */
5541
5542 static void napi_hash_add(struct napi_struct *napi)
5543 {
5544 if (test_bit(NAPI_STATE_NO_BUSY_POLL, &napi->state) ||
5545 test_and_set_bit(NAPI_STATE_HASHED, &napi->state))
5546 return;
5547
5548 spin_lock(&napi_hash_lock);
5549
5550 /* 0..NR_CPUS range is reserved for sender_cpu use */
5551 do {
5552 if (unlikely(++napi_gen_id < MIN_NAPI_ID))
5553 napi_gen_id = MIN_NAPI_ID;
5554 } while (napi_by_id(napi_gen_id));
5555 napi->napi_id = napi_gen_id;
5556
5557 hlist_add_head_rcu(&napi->napi_hash_node,
5558 &napi_hash[napi->napi_id % HASH_SIZE(napi_hash)]);
5559
5560 spin_unlock(&napi_hash_lock);
5561 }
5562
5563 /* Warning : caller is responsible to make sure rcu grace period
5564 * is respected before freeing memory containing @napi
5565 */
5566 bool napi_hash_del(struct napi_struct *napi)
5567 {
5568 bool rcu_sync_needed = false;
5569
5570 spin_lock(&napi_hash_lock);
5571
5572 if (test_and_clear_bit(NAPI_STATE_HASHED, &napi->state)) {
5573 rcu_sync_needed = true;
5574 hlist_del_rcu(&napi->napi_hash_node);
5575 }
5576 spin_unlock(&napi_hash_lock);
5577 return rcu_sync_needed;
5578 }
5579 EXPORT_SYMBOL_GPL(napi_hash_del);
5580
5581 static enum hrtimer_restart napi_watchdog(struct hrtimer *timer)
5582 {
5583 struct napi_struct *napi;
5584
5585 napi = container_of(timer, struct napi_struct, timer);
5586
5587 /* Note : we use a relaxed variant of napi_schedule_prep() not setting
5588 * NAPI_STATE_MISSED, since we do not react to a device IRQ.
5589 */
5590 if (napi->gro_list && !napi_disable_pending(napi) &&
5591 !test_and_set_bit(NAPI_STATE_SCHED, &napi->state))
5592 __napi_schedule_irqoff(napi);
5593
5594 return HRTIMER_NORESTART;
5595 }
5596
5597 void netif_napi_add(struct net_device *dev, struct napi_struct *napi,
5598 int (*poll)(struct napi_struct *, int), int weight)
5599 {
5600 INIT_LIST_HEAD(&napi->poll_list);
5601 hrtimer_init(&napi->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
5602 napi->timer.function = napi_watchdog;
5603 napi->gro_count = 0;
5604 napi->gro_list = NULL;
5605 napi->skb = NULL;
5606 napi->poll = poll;
5607 if (weight > NAPI_POLL_WEIGHT)
5608 pr_err_once("netif_napi_add() called with weight %d on device %s\n",
5609 weight, dev->name);
5610 napi->weight = weight;
5611 list_add(&napi->dev_list, &dev->napi_list);
5612 napi->dev = dev;
5613 #ifdef CONFIG_NETPOLL
5614 napi->poll_owner = -1;
5615 #endif
5616 set_bit(NAPI_STATE_SCHED, &napi->state);
5617 napi_hash_add(napi);
5618 }
5619 EXPORT_SYMBOL(netif_napi_add);
5620
5621 void napi_disable(struct napi_struct *n)
5622 {
5623 might_sleep();
5624 set_bit(NAPI_STATE_DISABLE, &n->state);
5625
5626 while (test_and_set_bit(NAPI_STATE_SCHED, &n->state))
5627 msleep(1);
5628 while (test_and_set_bit(NAPI_STATE_NPSVC, &n->state))
5629 msleep(1);
5630
5631 hrtimer_cancel(&n->timer);
5632
5633 clear_bit(NAPI_STATE_DISABLE, &n->state);
5634 }
5635 EXPORT_SYMBOL(napi_disable);
5636
5637 /* Must be called in process context */
5638 void netif_napi_del(struct napi_struct *napi)
5639 {
5640 might_sleep();
5641 if (napi_hash_del(napi))
5642 synchronize_net();
5643 list_del_init(&napi->dev_list);
5644 napi_free_frags(napi);
5645
5646 kfree_skb_list(napi->gro_list);
5647 napi->gro_list = NULL;
5648 napi->gro_count = 0;
5649 }
5650 EXPORT_SYMBOL(netif_napi_del);
5651
5652 static int napi_poll(struct napi_struct *n, struct list_head *repoll)
5653 {
5654 void *have;
5655 int work, weight;
5656
5657 list_del_init(&n->poll_list);
5658
5659 have = netpoll_poll_lock(n);
5660
5661 weight = n->weight;
5662
5663 /* This NAPI_STATE_SCHED test is for avoiding a race
5664 * with netpoll's poll_napi(). Only the entity which
5665 * obtains the lock and sees NAPI_STATE_SCHED set will
5666 * actually make the ->poll() call. Therefore we avoid
5667 * accidentally calling ->poll() when NAPI is not scheduled.
5668 */
5669 work = 0;
5670 if (test_bit(NAPI_STATE_SCHED, &n->state)) {
5671 work = n->poll(n, weight);
5672 trace_napi_poll(n, work, weight);
5673 }
5674
5675 WARN_ON_ONCE(work > weight);
5676
5677 if (likely(work < weight))
5678 goto out_unlock;
5679
5680 /* Drivers must not modify the NAPI state if they
5681 * consume the entire weight. In such cases this code
5682 * still "owns" the NAPI instance and therefore can
5683 * move the instance around on the list at-will.
5684 */
5685 if (unlikely(napi_disable_pending(n))) {
5686 napi_complete(n);
5687 goto out_unlock;
5688 }
5689
5690 if (n->gro_list) {
5691 /* flush too old packets
5692 * If HZ < 1000, flush all packets.
5693 */
5694 napi_gro_flush(n, HZ >= 1000);
5695 }
5696
5697 /* Some drivers may have called napi_schedule
5698 * prior to exhausting their budget.
5699 */
5700 if (unlikely(!list_empty(&n->poll_list))) {
5701 pr_warn_once("%s: Budget exhausted after napi rescheduled\n",
5702 n->dev ? n->dev->name : "backlog");
5703 goto out_unlock;
5704 }
5705
5706 list_add_tail(&n->poll_list, repoll);
5707
5708 out_unlock:
5709 netpoll_poll_unlock(have);
5710
5711 return work;
5712 }
5713
5714 static __latent_entropy void net_rx_action(struct softirq_action *h)
5715 {
5716 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
5717 unsigned long time_limit = jiffies +
5718 usecs_to_jiffies(netdev_budget_usecs);
5719 int budget = netdev_budget;
5720 LIST_HEAD(list);
5721 LIST_HEAD(repoll);
5722
5723 local_irq_disable();
5724 list_splice_init(&sd->poll_list, &list);
5725 local_irq_enable();
5726
5727 for (;;) {
5728 struct napi_struct *n;
5729
5730 if (list_empty(&list)) {
5731 if (!sd_has_rps_ipi_waiting(sd) && list_empty(&repoll))
5732 goto out;
5733 break;
5734 }
5735
5736 n = list_first_entry(&list, struct napi_struct, poll_list);
5737 budget -= napi_poll(n, &repoll);
5738
5739 /* If softirq window is exhausted then punt.
5740 * Allow this to run for 2 jiffies since which will allow
5741 * an average latency of 1.5/HZ.
5742 */
5743 if (unlikely(budget <= 0 ||
5744 time_after_eq(jiffies, time_limit))) {
5745 sd->time_squeeze++;
5746 break;
5747 }
5748 }
5749
5750 local_irq_disable();
5751
5752 list_splice_tail_init(&sd->poll_list, &list);
5753 list_splice_tail(&repoll, &list);
5754 list_splice(&list, &sd->poll_list);
5755 if (!list_empty(&sd->poll_list))
5756 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
5757
5758 net_rps_action_and_irq_enable(sd);
5759 out:
5760 __kfree_skb_flush();
5761 }
5762
5763 struct netdev_adjacent {
5764 struct net_device *dev;
5765
5766 /* upper master flag, there can only be one master device per list */
5767 bool master;
5768
5769 /* counter for the number of times this device was added to us */
5770 u16 ref_nr;
5771
5772 /* private field for the users */
5773 void *private;
5774
5775 struct list_head list;
5776 struct rcu_head rcu;
5777 };
5778
5779 static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev,
5780 struct list_head *adj_list)
5781 {
5782 struct netdev_adjacent *adj;
5783
5784 list_for_each_entry(adj, adj_list, list) {
5785 if (adj->dev == adj_dev)
5786 return adj;
5787 }
5788 return NULL;
5789 }
5790
5791 static int __netdev_has_upper_dev(struct net_device *upper_dev, void *data)
5792 {
5793 struct net_device *dev = data;
5794
5795 return upper_dev == dev;
5796 }
5797
5798 /**
5799 * netdev_has_upper_dev - Check if device is linked to an upper device
5800 * @dev: device
5801 * @upper_dev: upper device to check
5802 *
5803 * Find out if a device is linked to specified upper device and return true
5804 * in case it is. Note that this checks only immediate upper device,
5805 * not through a complete stack of devices. The caller must hold the RTNL lock.
5806 */
5807 bool netdev_has_upper_dev(struct net_device *dev,
5808 struct net_device *upper_dev)
5809 {
5810 ASSERT_RTNL();
5811
5812 return netdev_walk_all_upper_dev_rcu(dev, __netdev_has_upper_dev,
5813 upper_dev);
5814 }
5815 EXPORT_SYMBOL(netdev_has_upper_dev);
5816
5817 /**
5818 * netdev_has_upper_dev_all - Check if device is linked to an upper device
5819 * @dev: device
5820 * @upper_dev: upper device to check
5821 *
5822 * Find out if a device is linked to specified upper device and return true
5823 * in case it is. Note that this checks the entire upper device chain.
5824 * The caller must hold rcu lock.
5825 */
5826
5827 bool netdev_has_upper_dev_all_rcu(struct net_device *dev,
5828 struct net_device *upper_dev)
5829 {
5830 return !!netdev_walk_all_upper_dev_rcu(dev, __netdev_has_upper_dev,
5831 upper_dev);
5832 }
5833 EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu);
5834
5835 /**
5836 * netdev_has_any_upper_dev - Check if device is linked to some device
5837 * @dev: device
5838 *
5839 * Find out if a device is linked to an upper device and return true in case
5840 * it is. The caller must hold the RTNL lock.
5841 */
5842 bool netdev_has_any_upper_dev(struct net_device *dev)
5843 {
5844 ASSERT_RTNL();
5845
5846 return !list_empty(&dev->adj_list.upper);
5847 }
5848 EXPORT_SYMBOL(netdev_has_any_upper_dev);
5849
5850 /**
5851 * netdev_master_upper_dev_get - Get master upper device
5852 * @dev: device
5853 *
5854 * Find a master upper device and return pointer to it or NULL in case
5855 * it's not there. The caller must hold the RTNL lock.
5856 */
5857 struct net_device *netdev_master_upper_dev_get(struct net_device *dev)
5858 {
5859 struct netdev_adjacent *upper;
5860
5861 ASSERT_RTNL();
5862
5863 if (list_empty(&dev->adj_list.upper))
5864 return NULL;
5865
5866 upper = list_first_entry(&dev->adj_list.upper,
5867 struct netdev_adjacent, list);
5868 if (likely(upper->master))
5869 return upper->dev;
5870 return NULL;
5871 }
5872 EXPORT_SYMBOL(netdev_master_upper_dev_get);
5873
5874 /**
5875 * netdev_has_any_lower_dev - Check if device is linked to some device
5876 * @dev: device
5877 *
5878 * Find out if a device is linked to a lower device and return true in case
5879 * it is. The caller must hold the RTNL lock.
5880 */
5881 static bool netdev_has_any_lower_dev(struct net_device *dev)
5882 {
5883 ASSERT_RTNL();
5884
5885 return !list_empty(&dev->adj_list.lower);
5886 }
5887
5888 void *netdev_adjacent_get_private(struct list_head *adj_list)
5889 {
5890 struct netdev_adjacent *adj;
5891
5892 adj = list_entry(adj_list, struct netdev_adjacent, list);
5893
5894 return adj->private;
5895 }
5896 EXPORT_SYMBOL(netdev_adjacent_get_private);
5897
5898 /**
5899 * netdev_upper_get_next_dev_rcu - Get the next dev from upper list
5900 * @dev: device
5901 * @iter: list_head ** of the current position
5902 *
5903 * Gets the next device from the dev's upper list, starting from iter
5904 * position. The caller must hold RCU read lock.
5905 */
5906 struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev,
5907 struct list_head **iter)
5908 {
5909 struct netdev_adjacent *upper;
5910
5911 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
5912
5913 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
5914
5915 if (&upper->list == &dev->adj_list.upper)
5916 return NULL;
5917
5918 *iter = &upper->list;
5919
5920 return upper->dev;
5921 }
5922 EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu);
5923
5924 static struct net_device *netdev_next_upper_dev(struct net_device *dev,
5925 struct list_head **iter)
5926 {
5927 struct netdev_adjacent *upper;
5928
5929 upper = list_entry((*iter)->next, struct netdev_adjacent, list);
5930
5931 if (&upper->list == &dev->adj_list.upper)
5932 return NULL;
5933
5934 *iter = &upper->list;
5935
5936 return upper->dev;
5937 }
5938
5939 static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev,
5940 struct list_head **iter)
5941 {
5942 struct netdev_adjacent *upper;
5943
5944 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
5945
5946 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
5947
5948 if (&upper->list == &dev->adj_list.upper)
5949 return NULL;
5950
5951 *iter = &upper->list;
5952
5953 return upper->dev;
5954 }
5955
5956 static int netdev_walk_all_upper_dev(struct net_device *dev,
5957 int (*fn)(struct net_device *dev,
5958 void *data),
5959 void *data)
5960 {
5961 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
5962 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
5963 int ret, cur = 0;
5964
5965 now = dev;
5966 iter = &dev->adj_list.upper;
5967
5968 while (1) {
5969 if (now != dev) {
5970 ret = fn(now, data);
5971 if (ret)
5972 return ret;
5973 }
5974
5975 next = NULL;
5976 while (1) {
5977 udev = netdev_next_upper_dev(now, &iter);
5978 if (!udev)
5979 break;
5980
5981 next = udev;
5982 niter = &udev->adj_list.upper;
5983 dev_stack[cur] = now;
5984 iter_stack[cur++] = iter;
5985 break;
5986 }
5987
5988 if (!next) {
5989 if (!cur)
5990 return 0;
5991 next = dev_stack[--cur];
5992 niter = iter_stack[cur];
5993 }
5994
5995 now = next;
5996 iter = niter;
5997 }
5998
5999 return 0;
6000 }
6001
6002 int netdev_walk_all_upper_dev_rcu(struct net_device *dev,
6003 int (*fn)(struct net_device *dev,
6004 void *data),
6005 void *data)
6006 {
6007 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
6008 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
6009 int ret, cur = 0;
6010
6011 now = dev;
6012 iter = &dev->adj_list.upper;
6013
6014 while (1) {
6015 if (now != dev) {
6016 ret = fn(now, data);
6017 if (ret)
6018 return ret;
6019 }
6020
6021 next = NULL;
6022 while (1) {
6023 udev = netdev_next_upper_dev_rcu(now, &iter);
6024 if (!udev)
6025 break;
6026
6027 next = udev;
6028 niter = &udev->adj_list.upper;
6029 dev_stack[cur] = now;
6030 iter_stack[cur++] = iter;
6031 break;
6032 }
6033
6034 if (!next) {
6035 if (!cur)
6036 return 0;
6037 next = dev_stack[--cur];
6038 niter = iter_stack[cur];
6039 }
6040
6041 now = next;
6042 iter = niter;
6043 }
6044
6045 return 0;
6046 }
6047 EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu);
6048
6049 /**
6050 * netdev_lower_get_next_private - Get the next ->private from the
6051 * lower neighbour list
6052 * @dev: device
6053 * @iter: list_head ** of the current position
6054 *
6055 * Gets the next netdev_adjacent->private from the dev's lower neighbour
6056 * list, starting from iter position. The caller must hold either hold the
6057 * RTNL lock or its own locking that guarantees that the neighbour lower
6058 * list will remain unchanged.
6059 */
6060 void *netdev_lower_get_next_private(struct net_device *dev,
6061 struct list_head **iter)
6062 {
6063 struct netdev_adjacent *lower;
6064
6065 lower = list_entry(*iter, struct netdev_adjacent, list);
6066
6067 if (&lower->list == &dev->adj_list.lower)
6068 return NULL;
6069
6070 *iter = lower->list.next;
6071
6072 return lower->private;
6073 }
6074 EXPORT_SYMBOL(netdev_lower_get_next_private);
6075
6076 /**
6077 * netdev_lower_get_next_private_rcu - Get the next ->private from the
6078 * lower neighbour list, RCU
6079 * variant
6080 * @dev: device
6081 * @iter: list_head ** of the current position
6082 *
6083 * Gets the next netdev_adjacent->private from the dev's lower neighbour
6084 * list, starting from iter position. The caller must hold RCU read lock.
6085 */
6086 void *netdev_lower_get_next_private_rcu(struct net_device *dev,
6087 struct list_head **iter)
6088 {
6089 struct netdev_adjacent *lower;
6090
6091 WARN_ON_ONCE(!rcu_read_lock_held());
6092
6093 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6094
6095 if (&lower->list == &dev->adj_list.lower)
6096 return NULL;
6097
6098 *iter = &lower->list;
6099
6100 return lower->private;
6101 }
6102 EXPORT_SYMBOL(netdev_lower_get_next_private_rcu);
6103
6104 /**
6105 * netdev_lower_get_next - Get the next device from the lower neighbour
6106 * list
6107 * @dev: device
6108 * @iter: list_head ** of the current position
6109 *
6110 * Gets the next netdev_adjacent from the dev's lower neighbour
6111 * list, starting from iter position. The caller must hold RTNL lock or
6112 * its own locking that guarantees that the neighbour lower
6113 * list will remain unchanged.
6114 */
6115 void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter)
6116 {
6117 struct netdev_adjacent *lower;
6118
6119 lower = list_entry(*iter, struct netdev_adjacent, list);
6120
6121 if (&lower->list == &dev->adj_list.lower)
6122 return NULL;
6123
6124 *iter = lower->list.next;
6125
6126 return lower->dev;
6127 }
6128 EXPORT_SYMBOL(netdev_lower_get_next);
6129
6130 static struct net_device *netdev_next_lower_dev(struct net_device *dev,
6131 struct list_head **iter)
6132 {
6133 struct netdev_adjacent *lower;
6134
6135 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
6136
6137 if (&lower->list == &dev->adj_list.lower)
6138 return NULL;
6139
6140 *iter = &lower->list;
6141
6142 return lower->dev;
6143 }
6144
6145 int netdev_walk_all_lower_dev(struct net_device *dev,
6146 int (*fn)(struct net_device *dev,
6147 void *data),
6148 void *data)
6149 {
6150 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
6151 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
6152 int ret, cur = 0;
6153
6154 now = dev;
6155 iter = &dev->adj_list.lower;
6156
6157 while (1) {
6158 if (now != dev) {
6159 ret = fn(now, data);
6160 if (ret)
6161 return ret;
6162 }
6163
6164 next = NULL;
6165 while (1) {
6166 ldev = netdev_next_lower_dev(now, &iter);
6167 if (!ldev)
6168 break;
6169
6170 next = ldev;
6171 niter = &ldev->adj_list.lower;
6172 dev_stack[cur] = now;
6173 iter_stack[cur++] = iter;
6174 break;
6175 }
6176
6177 if (!next) {
6178 if (!cur)
6179 return 0;
6180 next = dev_stack[--cur];
6181 niter = iter_stack[cur];
6182 }
6183
6184 now = next;
6185 iter = niter;
6186 }
6187
6188 return 0;
6189 }
6190 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev);
6191
6192 static struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev,
6193 struct list_head **iter)
6194 {
6195 struct netdev_adjacent *lower;
6196
6197 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6198 if (&lower->list == &dev->adj_list.lower)
6199 return NULL;
6200
6201 *iter = &lower->list;
6202
6203 return lower->dev;
6204 }
6205
6206 static u8 __netdev_upper_depth(struct net_device *dev)
6207 {
6208 struct net_device *udev;
6209 struct list_head *iter;
6210 u8 max_depth = 0;
6211
6212 for (iter = &dev->adj_list.upper,
6213 udev = netdev_next_upper_dev(dev, &iter);
6214 udev;
6215 udev = netdev_next_upper_dev(dev, &iter)) {
6216 if (max_depth < udev->upper_level)
6217 max_depth = udev->upper_level;
6218 }
6219
6220 return max_depth;
6221 }
6222
6223 static u8 __netdev_lower_depth(struct net_device *dev)
6224 {
6225 struct net_device *ldev;
6226 struct list_head *iter;
6227 u8 max_depth = 0;
6228
6229 for (iter = &dev->adj_list.lower,
6230 ldev = netdev_next_lower_dev(dev, &iter);
6231 ldev;
6232 ldev = netdev_next_lower_dev(dev, &iter)) {
6233 if (max_depth < ldev->lower_level)
6234 max_depth = ldev->lower_level;
6235 }
6236
6237 return max_depth;
6238 }
6239
6240 static int __netdev_update_upper_level(struct net_device *dev, void *data)
6241 {
6242 dev->upper_level = __netdev_upper_depth(dev) + 1;
6243 return 0;
6244 }
6245
6246 static int __netdev_update_lower_level(struct net_device *dev, void *data)
6247 {
6248 dev->lower_level = __netdev_lower_depth(dev) + 1;
6249 return 0;
6250 }
6251
6252 int netdev_walk_all_lower_dev_rcu(struct net_device *dev,
6253 int (*fn)(struct net_device *dev,
6254 void *data),
6255 void *data)
6256 {
6257 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
6258 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
6259 int ret, cur = 0;
6260
6261 now = dev;
6262 iter = &dev->adj_list.lower;
6263
6264 while (1) {
6265 if (now != dev) {
6266 ret = fn(now, data);
6267 if (ret)
6268 return ret;
6269 }
6270
6271 next = NULL;
6272 while (1) {
6273 ldev = netdev_next_lower_dev_rcu(now, &iter);
6274 if (!ldev)
6275 break;
6276
6277 next = ldev;
6278 niter = &ldev->adj_list.lower;
6279 dev_stack[cur] = now;
6280 iter_stack[cur++] = iter;
6281 break;
6282 }
6283
6284 if (!next) {
6285 if (!cur)
6286 return 0;
6287 next = dev_stack[--cur];
6288 niter = iter_stack[cur];
6289 }
6290
6291 now = next;
6292 iter = niter;
6293 }
6294
6295 return 0;
6296 }
6297 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu);
6298
6299 /**
6300 * netdev_lower_get_first_private_rcu - Get the first ->private from the
6301 * lower neighbour list, RCU
6302 * variant
6303 * @dev: device
6304 *
6305 * Gets the first netdev_adjacent->private from the dev's lower neighbour
6306 * list. The caller must hold RCU read lock.
6307 */
6308 void *netdev_lower_get_first_private_rcu(struct net_device *dev)
6309 {
6310 struct netdev_adjacent *lower;
6311
6312 lower = list_first_or_null_rcu(&dev->adj_list.lower,
6313 struct netdev_adjacent, list);
6314 if (lower)
6315 return lower->private;
6316 return NULL;
6317 }
6318 EXPORT_SYMBOL(netdev_lower_get_first_private_rcu);
6319
6320 /**
6321 * netdev_master_upper_dev_get_rcu - Get master upper device
6322 * @dev: device
6323 *
6324 * Find a master upper device and return pointer to it or NULL in case
6325 * it's not there. The caller must hold the RCU read lock.
6326 */
6327 struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev)
6328 {
6329 struct netdev_adjacent *upper;
6330
6331 upper = list_first_or_null_rcu(&dev->adj_list.upper,
6332 struct netdev_adjacent, list);
6333 if (upper && likely(upper->master))
6334 return upper->dev;
6335 return NULL;
6336 }
6337 EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu);
6338
6339 static int netdev_adjacent_sysfs_add(struct net_device *dev,
6340 struct net_device *adj_dev,
6341 struct list_head *dev_list)
6342 {
6343 char linkname[IFNAMSIZ+7];
6344
6345 sprintf(linkname, dev_list == &dev->adj_list.upper ?
6346 "upper_%s" : "lower_%s", adj_dev->name);
6347 return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj),
6348 linkname);
6349 }
6350 static void netdev_adjacent_sysfs_del(struct net_device *dev,
6351 char *name,
6352 struct list_head *dev_list)
6353 {
6354 char linkname[IFNAMSIZ+7];
6355
6356 sprintf(linkname, dev_list == &dev->adj_list.upper ?
6357 "upper_%s" : "lower_%s", name);
6358 sysfs_remove_link(&(dev->dev.kobj), linkname);
6359 }
6360
6361 static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev,
6362 struct net_device *adj_dev,
6363 struct list_head *dev_list)
6364 {
6365 return (dev_list == &dev->adj_list.upper ||
6366 dev_list == &dev->adj_list.lower) &&
6367 net_eq(dev_net(dev), dev_net(adj_dev));
6368 }
6369
6370 static int __netdev_adjacent_dev_insert(struct net_device *dev,
6371 struct net_device *adj_dev,
6372 struct list_head *dev_list,
6373 void *private, bool master)
6374 {
6375 struct netdev_adjacent *adj;
6376 int ret;
6377
6378 adj = __netdev_find_adj(adj_dev, dev_list);
6379
6380 if (adj) {
6381 adj->ref_nr += 1;
6382 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n",
6383 dev->name, adj_dev->name, adj->ref_nr);
6384
6385 return 0;
6386 }
6387
6388 adj = kmalloc(sizeof(*adj), GFP_KERNEL);
6389 if (!adj)
6390 return -ENOMEM;
6391
6392 adj->dev = adj_dev;
6393 adj->master = master;
6394 adj->ref_nr = 1;
6395 adj->private = private;
6396 dev_hold(adj_dev);
6397
6398 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n",
6399 dev->name, adj_dev->name, adj->ref_nr, adj_dev->name);
6400
6401 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) {
6402 ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list);
6403 if (ret)
6404 goto free_adj;
6405 }
6406
6407 /* Ensure that master link is always the first item in list. */
6408 if (master) {
6409 ret = sysfs_create_link(&(dev->dev.kobj),
6410 &(adj_dev->dev.kobj), "master");
6411 if (ret)
6412 goto remove_symlinks;
6413
6414 list_add_rcu(&adj->list, dev_list);
6415 } else {
6416 list_add_tail_rcu(&adj->list, dev_list);
6417 }
6418
6419 return 0;
6420
6421 remove_symlinks:
6422 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
6423 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
6424 free_adj:
6425 kfree(adj);
6426 dev_put(adj_dev);
6427
6428 return ret;
6429 }
6430
6431 static void __netdev_adjacent_dev_remove(struct net_device *dev,
6432 struct net_device *adj_dev,
6433 u16 ref_nr,
6434 struct list_head *dev_list)
6435 {
6436 struct netdev_adjacent *adj;
6437
6438 pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n",
6439 dev->name, adj_dev->name, ref_nr);
6440
6441 adj = __netdev_find_adj(adj_dev, dev_list);
6442
6443 if (!adj) {
6444 pr_err("Adjacency does not exist for device %s from %s\n",
6445 dev->name, adj_dev->name);
6446 WARN_ON(1);
6447 return;
6448 }
6449
6450 if (adj->ref_nr > ref_nr) {
6451 pr_debug("adjacency: %s to %s ref_nr - %d = %d\n",
6452 dev->name, adj_dev->name, ref_nr,
6453 adj->ref_nr - ref_nr);
6454 adj->ref_nr -= ref_nr;
6455 return;
6456 }
6457
6458 if (adj->master)
6459 sysfs_remove_link(&(dev->dev.kobj), "master");
6460
6461 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
6462 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
6463
6464 list_del_rcu(&adj->list);
6465 pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n",
6466 adj_dev->name, dev->name, adj_dev->name);
6467 dev_put(adj_dev);
6468 kfree_rcu(adj, rcu);
6469 }
6470
6471 static int __netdev_adjacent_dev_link_lists(struct net_device *dev,
6472 struct net_device *upper_dev,
6473 struct list_head *up_list,
6474 struct list_head *down_list,
6475 void *private, bool master)
6476 {
6477 int ret;
6478
6479 ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list,
6480 private, master);
6481 if (ret)
6482 return ret;
6483
6484 ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list,
6485 private, false);
6486 if (ret) {
6487 __netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list);
6488 return ret;
6489 }
6490
6491 return 0;
6492 }
6493
6494 static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev,
6495 struct net_device *upper_dev,
6496 u16 ref_nr,
6497 struct list_head *up_list,
6498 struct list_head *down_list)
6499 {
6500 __netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list);
6501 __netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list);
6502 }
6503
6504 static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev,
6505 struct net_device *upper_dev,
6506 void *private, bool master)
6507 {
6508 return __netdev_adjacent_dev_link_lists(dev, upper_dev,
6509 &dev->adj_list.upper,
6510 &upper_dev->adj_list.lower,
6511 private, master);
6512 }
6513
6514 static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev,
6515 struct net_device *upper_dev)
6516 {
6517 __netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1,
6518 &dev->adj_list.upper,
6519 &upper_dev->adj_list.lower);
6520 }
6521
6522 static int __netdev_upper_dev_link(struct net_device *dev,
6523 struct net_device *upper_dev, bool master,
6524 void *upper_priv, void *upper_info,
6525 struct netlink_ext_ack *extack)
6526 {
6527 struct netdev_notifier_changeupper_info changeupper_info = {
6528 .info = {
6529 .dev = dev,
6530 .extack = extack,
6531 },
6532 .upper_dev = upper_dev,
6533 .master = master,
6534 .linking = true,
6535 .upper_info = upper_info,
6536 };
6537 int ret = 0;
6538
6539 ASSERT_RTNL();
6540
6541 if (dev == upper_dev)
6542 return -EBUSY;
6543
6544 /* To prevent loops, check if dev is not upper device to upper_dev. */
6545 if (netdev_has_upper_dev(upper_dev, dev))
6546 return -EBUSY;
6547
6548 if (netdev_has_upper_dev(dev, upper_dev))
6549 return -EEXIST;
6550
6551 if ((dev->lower_level + upper_dev->upper_level) > MAX_NEST_DEV)
6552 return -EMLINK;
6553
6554 if (master && netdev_master_upper_dev_get(dev))
6555 return -EBUSY;
6556
6557 ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
6558 &changeupper_info.info);
6559 ret = notifier_to_errno(ret);
6560 if (ret)
6561 return ret;
6562
6563 ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv,
6564 master);
6565 if (ret)
6566 return ret;
6567
6568 ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
6569 &changeupper_info.info);
6570 ret = notifier_to_errno(ret);
6571 if (ret)
6572 goto rollback;
6573
6574 __netdev_update_upper_level(dev, NULL);
6575 netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
6576
6577 __netdev_update_lower_level(upper_dev, NULL);
6578 netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level, NULL);
6579
6580 return 0;
6581
6582 rollback:
6583 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
6584
6585 return ret;
6586 }
6587
6588 /**
6589 * netdev_upper_dev_link - Add a link to the upper device
6590 * @dev: device
6591 * @upper_dev: new upper device
6592 *
6593 * Adds a link to device which is upper to this one. The caller must hold
6594 * the RTNL lock. On a failure a negative errno code is returned.
6595 * On success the reference counts are adjusted and the function
6596 * returns zero.
6597 */
6598 int netdev_upper_dev_link(struct net_device *dev,
6599 struct net_device *upper_dev,
6600 struct netlink_ext_ack *extack)
6601 {
6602 return __netdev_upper_dev_link(dev, upper_dev, false,
6603 NULL, NULL, extack);
6604 }
6605 EXPORT_SYMBOL(netdev_upper_dev_link);
6606
6607 /**
6608 * netdev_master_upper_dev_link - Add a master link to the upper device
6609 * @dev: device
6610 * @upper_dev: new upper device
6611 * @upper_priv: upper device private
6612 * @upper_info: upper info to be passed down via notifier
6613 *
6614 * Adds a link to device which is upper to this one. In this case, only
6615 * one master upper device can be linked, although other non-master devices
6616 * might be linked as well. The caller must hold the RTNL lock.
6617 * On a failure a negative errno code is returned. On success the reference
6618 * counts are adjusted and the function returns zero.
6619 */
6620 int netdev_master_upper_dev_link(struct net_device *dev,
6621 struct net_device *upper_dev,
6622 void *upper_priv, void *upper_info,
6623 struct netlink_ext_ack *extack)
6624 {
6625 return __netdev_upper_dev_link(dev, upper_dev, true,
6626 upper_priv, upper_info, extack);
6627 }
6628 EXPORT_SYMBOL(netdev_master_upper_dev_link);
6629
6630 /**
6631 * netdev_upper_dev_unlink - Removes a link to upper device
6632 * @dev: device
6633 * @upper_dev: new upper device
6634 *
6635 * Removes a link to device which is upper to this one. The caller must hold
6636 * the RTNL lock.
6637 */
6638 void netdev_upper_dev_unlink(struct net_device *dev,
6639 struct net_device *upper_dev)
6640 {
6641 struct netdev_notifier_changeupper_info changeupper_info = {
6642 .info = {
6643 .dev = dev,
6644 },
6645 .upper_dev = upper_dev,
6646 .linking = false,
6647 };
6648
6649 ASSERT_RTNL();
6650
6651 changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev;
6652
6653 call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
6654 &changeupper_info.info);
6655
6656 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
6657
6658 call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
6659 &changeupper_info.info);
6660
6661 __netdev_update_upper_level(dev, NULL);
6662 netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
6663
6664 __netdev_update_lower_level(upper_dev, NULL);
6665 netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level, NULL);
6666 }
6667 EXPORT_SYMBOL(netdev_upper_dev_unlink);
6668
6669 /**
6670 * netdev_bonding_info_change - Dispatch event about slave change
6671 * @dev: device
6672 * @bonding_info: info to dispatch
6673 *
6674 * Send NETDEV_BONDING_INFO to netdev notifiers with info.
6675 * The caller must hold the RTNL lock.
6676 */
6677 void netdev_bonding_info_change(struct net_device *dev,
6678 struct netdev_bonding_info *bonding_info)
6679 {
6680 struct netdev_notifier_bonding_info info = {
6681 .info.dev = dev,
6682 };
6683
6684 memcpy(&info.bonding_info, bonding_info,
6685 sizeof(struct netdev_bonding_info));
6686 call_netdevice_notifiers_info(NETDEV_BONDING_INFO,
6687 &info.info);
6688 }
6689 EXPORT_SYMBOL(netdev_bonding_info_change);
6690
6691 static void netdev_adjacent_add_links(struct net_device *dev)
6692 {
6693 struct netdev_adjacent *iter;
6694
6695 struct net *net = dev_net(dev);
6696
6697 list_for_each_entry(iter, &dev->adj_list.upper, list) {
6698 if (!net_eq(net, dev_net(iter->dev)))
6699 continue;
6700 netdev_adjacent_sysfs_add(iter->dev, dev,
6701 &iter->dev->adj_list.lower);
6702 netdev_adjacent_sysfs_add(dev, iter->dev,
6703 &dev->adj_list.upper);
6704 }
6705
6706 list_for_each_entry(iter, &dev->adj_list.lower, list) {
6707 if (!net_eq(net, dev_net(iter->dev)))
6708 continue;
6709 netdev_adjacent_sysfs_add(iter->dev, dev,
6710 &iter->dev->adj_list.upper);
6711 netdev_adjacent_sysfs_add(dev, iter->dev,
6712 &dev->adj_list.lower);
6713 }
6714 }
6715
6716 static void netdev_adjacent_del_links(struct net_device *dev)
6717 {
6718 struct netdev_adjacent *iter;
6719
6720 struct net *net = dev_net(dev);
6721
6722 list_for_each_entry(iter, &dev->adj_list.upper, list) {
6723 if (!net_eq(net, dev_net(iter->dev)))
6724 continue;
6725 netdev_adjacent_sysfs_del(iter->dev, dev->name,
6726 &iter->dev->adj_list.lower);
6727 netdev_adjacent_sysfs_del(dev, iter->dev->name,
6728 &dev->adj_list.upper);
6729 }
6730
6731 list_for_each_entry(iter, &dev->adj_list.lower, list) {
6732 if (!net_eq(net, dev_net(iter->dev)))
6733 continue;
6734 netdev_adjacent_sysfs_del(iter->dev, dev->name,
6735 &iter->dev->adj_list.upper);
6736 netdev_adjacent_sysfs_del(dev, iter->dev->name,
6737 &dev->adj_list.lower);
6738 }
6739 }
6740
6741 void netdev_adjacent_rename_links(struct net_device *dev, char *oldname)
6742 {
6743 struct netdev_adjacent *iter;
6744
6745 struct net *net = dev_net(dev);
6746
6747 list_for_each_entry(iter, &dev->adj_list.upper, list) {
6748 if (!net_eq(net, dev_net(iter->dev)))
6749 continue;
6750 netdev_adjacent_sysfs_del(iter->dev, oldname,
6751 &iter->dev->adj_list.lower);
6752 netdev_adjacent_sysfs_add(iter->dev, dev,
6753 &iter->dev->adj_list.lower);
6754 }
6755
6756 list_for_each_entry(iter, &dev->adj_list.lower, list) {
6757 if (!net_eq(net, dev_net(iter->dev)))
6758 continue;
6759 netdev_adjacent_sysfs_del(iter->dev, oldname,
6760 &iter->dev->adj_list.upper);
6761 netdev_adjacent_sysfs_add(iter->dev, dev,
6762 &iter->dev->adj_list.upper);
6763 }
6764 }
6765
6766 void *netdev_lower_dev_get_private(struct net_device *dev,
6767 struct net_device *lower_dev)
6768 {
6769 struct netdev_adjacent *lower;
6770
6771 if (!lower_dev)
6772 return NULL;
6773 lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower);
6774 if (!lower)
6775 return NULL;
6776
6777 return lower->private;
6778 }
6779 EXPORT_SYMBOL(netdev_lower_dev_get_private);
6780
6781
6782 int dev_get_nest_level(struct net_device *dev)
6783 {
6784 struct net_device *lower = NULL;
6785 struct list_head *iter;
6786 int max_nest = -1;
6787 int nest;
6788
6789 ASSERT_RTNL();
6790
6791 netdev_for_each_lower_dev(dev, lower, iter) {
6792 nest = dev_get_nest_level(lower);
6793 if (max_nest < nest)
6794 max_nest = nest;
6795 }
6796
6797 return max_nest + 1;
6798 }
6799 EXPORT_SYMBOL(dev_get_nest_level);
6800
6801 /**
6802 * netdev_lower_change - Dispatch event about lower device state change
6803 * @lower_dev: device
6804 * @lower_state_info: state to dispatch
6805 *
6806 * Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info.
6807 * The caller must hold the RTNL lock.
6808 */
6809 void netdev_lower_state_changed(struct net_device *lower_dev,
6810 void *lower_state_info)
6811 {
6812 struct netdev_notifier_changelowerstate_info changelowerstate_info = {
6813 .info.dev = lower_dev,
6814 };
6815
6816 ASSERT_RTNL();
6817 changelowerstate_info.lower_state_info = lower_state_info;
6818 call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE,
6819 &changelowerstate_info.info);
6820 }
6821 EXPORT_SYMBOL(netdev_lower_state_changed);
6822
6823 static void dev_change_rx_flags(struct net_device *dev, int flags)
6824 {
6825 const struct net_device_ops *ops = dev->netdev_ops;
6826
6827 if (ops->ndo_change_rx_flags)
6828 ops->ndo_change_rx_flags(dev, flags);
6829 }
6830
6831 static int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify)
6832 {
6833 unsigned int old_flags = dev->flags;
6834 kuid_t uid;
6835 kgid_t gid;
6836
6837 ASSERT_RTNL();
6838
6839 dev->flags |= IFF_PROMISC;
6840 dev->promiscuity += inc;
6841 if (dev->promiscuity == 0) {
6842 /*
6843 * Avoid overflow.
6844 * If inc causes overflow, untouch promisc and return error.
6845 */
6846 if (inc < 0)
6847 dev->flags &= ~IFF_PROMISC;
6848 else {
6849 dev->promiscuity -= inc;
6850 pr_warn("%s: promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n",
6851 dev->name);
6852 return -EOVERFLOW;
6853 }
6854 }
6855 if (dev->flags != old_flags) {
6856 pr_info("device %s %s promiscuous mode\n",
6857 dev->name,
6858 dev->flags & IFF_PROMISC ? "entered" : "left");
6859 if (audit_enabled) {
6860 current_uid_gid(&uid, &gid);
6861 audit_log(current->audit_context, GFP_ATOMIC,
6862 AUDIT_ANOM_PROMISCUOUS,
6863 "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u",
6864 dev->name, (dev->flags & IFF_PROMISC),
6865 (old_flags & IFF_PROMISC),
6866 from_kuid(&init_user_ns, audit_get_loginuid(current)),
6867 from_kuid(&init_user_ns, uid),
6868 from_kgid(&init_user_ns, gid),
6869 audit_get_sessionid(current));
6870 }
6871
6872 dev_change_rx_flags(dev, IFF_PROMISC);
6873 }
6874 if (notify)
6875 __dev_notify_flags(dev, old_flags, IFF_PROMISC);
6876 return 0;
6877 }
6878
6879 /**
6880 * dev_set_promiscuity - update promiscuity count on a device
6881 * @dev: device
6882 * @inc: modifier
6883 *
6884 * Add or remove promiscuity from a device. While the count in the device
6885 * remains above zero the interface remains promiscuous. Once it hits zero
6886 * the device reverts back to normal filtering operation. A negative inc
6887 * value is used to drop promiscuity on the device.
6888 * Return 0 if successful or a negative errno code on error.
6889 */
6890 int dev_set_promiscuity(struct net_device *dev, int inc)
6891 {
6892 unsigned int old_flags = dev->flags;
6893 int err;
6894
6895 err = __dev_set_promiscuity(dev, inc, true);
6896 if (err < 0)
6897 return err;
6898 if (dev->flags != old_flags)
6899 dev_set_rx_mode(dev);
6900 return err;
6901 }
6902 EXPORT_SYMBOL(dev_set_promiscuity);
6903
6904 static int __dev_set_allmulti(struct net_device *dev, int inc, bool notify)
6905 {
6906 unsigned int old_flags = dev->flags, old_gflags = dev->gflags;
6907
6908 ASSERT_RTNL();
6909
6910 dev->flags |= IFF_ALLMULTI;
6911 dev->allmulti += inc;
6912 if (dev->allmulti == 0) {
6913 /*
6914 * Avoid overflow.
6915 * If inc causes overflow, untouch allmulti and return error.
6916 */
6917 if (inc < 0)
6918 dev->flags &= ~IFF_ALLMULTI;
6919 else {
6920 dev->allmulti -= inc;
6921 pr_warn("%s: allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n",
6922 dev->name);
6923 return -EOVERFLOW;
6924 }
6925 }
6926 if (dev->flags ^ old_flags) {
6927 dev_change_rx_flags(dev, IFF_ALLMULTI);
6928 dev_set_rx_mode(dev);
6929 if (notify)
6930 __dev_notify_flags(dev, old_flags,
6931 dev->gflags ^ old_gflags);
6932 }
6933 return 0;
6934 }
6935
6936 /**
6937 * dev_set_allmulti - update allmulti count on a device
6938 * @dev: device
6939 * @inc: modifier
6940 *
6941 * Add or remove reception of all multicast frames to a device. While the
6942 * count in the device remains above zero the interface remains listening
6943 * to all interfaces. Once it hits zero the device reverts back to normal
6944 * filtering operation. A negative @inc value is used to drop the counter
6945 * when releasing a resource needing all multicasts.
6946 * Return 0 if successful or a negative errno code on error.
6947 */
6948
6949 int dev_set_allmulti(struct net_device *dev, int inc)
6950 {
6951 return __dev_set_allmulti(dev, inc, true);
6952 }
6953 EXPORT_SYMBOL(dev_set_allmulti);
6954
6955 /*
6956 * Upload unicast and multicast address lists to device and
6957 * configure RX filtering. When the device doesn't support unicast
6958 * filtering it is put in promiscuous mode while unicast addresses
6959 * are present.
6960 */
6961 void __dev_set_rx_mode(struct net_device *dev)
6962 {
6963 const struct net_device_ops *ops = dev->netdev_ops;
6964
6965 /* dev_open will call this function so the list will stay sane. */
6966 if (!(dev->flags&IFF_UP))
6967 return;
6968
6969 if (!netif_device_present(dev))
6970 return;
6971
6972 if (!(dev->priv_flags & IFF_UNICAST_FLT)) {
6973 /* Unicast addresses changes may only happen under the rtnl,
6974 * therefore calling __dev_set_promiscuity here is safe.
6975 */
6976 if (!netdev_uc_empty(dev) && !dev->uc_promisc) {
6977 __dev_set_promiscuity(dev, 1, false);
6978 dev->uc_promisc = true;
6979 } else if (netdev_uc_empty(dev) && dev->uc_promisc) {
6980 __dev_set_promiscuity(dev, -1, false);
6981 dev->uc_promisc = false;
6982 }
6983 }
6984
6985 if (ops->ndo_set_rx_mode)
6986 ops->ndo_set_rx_mode(dev);
6987 }
6988
6989 void dev_set_rx_mode(struct net_device *dev)
6990 {
6991 netif_addr_lock_bh(dev);
6992 __dev_set_rx_mode(dev);
6993 netif_addr_unlock_bh(dev);
6994 }
6995
6996 /**
6997 * dev_get_flags - get flags reported to userspace
6998 * @dev: device
6999 *
7000 * Get the combination of flag bits exported through APIs to userspace.
7001 */
7002 unsigned int dev_get_flags(const struct net_device *dev)
7003 {
7004 unsigned int flags;
7005
7006 flags = (dev->flags & ~(IFF_PROMISC |
7007 IFF_ALLMULTI |
7008 IFF_RUNNING |
7009 IFF_LOWER_UP |
7010 IFF_DORMANT)) |
7011 (dev->gflags & (IFF_PROMISC |
7012 IFF_ALLMULTI));
7013
7014 if (netif_running(dev)) {
7015 if (netif_oper_up(dev))
7016 flags |= IFF_RUNNING;
7017 if (netif_carrier_ok(dev))
7018 flags |= IFF_LOWER_UP;
7019 if (netif_dormant(dev))
7020 flags |= IFF_DORMANT;
7021 }
7022
7023 return flags;
7024 }
7025 EXPORT_SYMBOL(dev_get_flags);
7026
7027 int __dev_change_flags(struct net_device *dev, unsigned int flags)
7028 {
7029 unsigned int old_flags = dev->flags;
7030 int ret;
7031
7032 ASSERT_RTNL();
7033
7034 /*
7035 * Set the flags on our device.
7036 */
7037
7038 dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
7039 IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
7040 IFF_AUTOMEDIA)) |
7041 (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
7042 IFF_ALLMULTI));
7043
7044 /*
7045 * Load in the correct multicast list now the flags have changed.
7046 */
7047
7048 if ((old_flags ^ flags) & IFF_MULTICAST)
7049 dev_change_rx_flags(dev, IFF_MULTICAST);
7050
7051 dev_set_rx_mode(dev);
7052
7053 /*
7054 * Have we downed the interface. We handle IFF_UP ourselves
7055 * according to user attempts to set it, rather than blindly
7056 * setting it.
7057 */
7058
7059 ret = 0;
7060 if ((old_flags ^ flags) & IFF_UP) {
7061 if (old_flags & IFF_UP)
7062 __dev_close(dev);
7063 else
7064 ret = __dev_open(dev);
7065 }
7066
7067 if ((flags ^ dev->gflags) & IFF_PROMISC) {
7068 int inc = (flags & IFF_PROMISC) ? 1 : -1;
7069 unsigned int old_flags = dev->flags;
7070
7071 dev->gflags ^= IFF_PROMISC;
7072
7073 if (__dev_set_promiscuity(dev, inc, false) >= 0)
7074 if (dev->flags != old_flags)
7075 dev_set_rx_mode(dev);
7076 }
7077
7078 /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
7079 * is important. Some (broken) drivers set IFF_PROMISC, when
7080 * IFF_ALLMULTI is requested not asking us and not reporting.
7081 */
7082 if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
7083 int inc = (flags & IFF_ALLMULTI) ? 1 : -1;
7084
7085 dev->gflags ^= IFF_ALLMULTI;
7086 __dev_set_allmulti(dev, inc, false);
7087 }
7088
7089 return ret;
7090 }
7091
7092 void __dev_notify_flags(struct net_device *dev, unsigned int old_flags,
7093 unsigned int gchanges)
7094 {
7095 unsigned int changes = dev->flags ^ old_flags;
7096
7097 if (gchanges)
7098 rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC);
7099
7100 if (changes & IFF_UP) {
7101 if (dev->flags & IFF_UP)
7102 call_netdevice_notifiers(NETDEV_UP, dev);
7103 else
7104 call_netdevice_notifiers(NETDEV_DOWN, dev);
7105 }
7106
7107 if (dev->flags & IFF_UP &&
7108 (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) {
7109 struct netdev_notifier_change_info change_info = {
7110 .info = {
7111 .dev = dev,
7112 },
7113 .flags_changed = changes,
7114 };
7115
7116 call_netdevice_notifiers_info(NETDEV_CHANGE, &change_info.info);
7117 }
7118 }
7119
7120 /**
7121 * dev_change_flags - change device settings
7122 * @dev: device
7123 * @flags: device state flags
7124 *
7125 * Change settings on device based state flags. The flags are
7126 * in the userspace exported format.
7127 */
7128 int dev_change_flags(struct net_device *dev, unsigned int flags)
7129 {
7130 int ret;
7131 unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags;
7132
7133 ret = __dev_change_flags(dev, flags);
7134 if (ret < 0)
7135 return ret;
7136
7137 changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags);
7138 __dev_notify_flags(dev, old_flags, changes);
7139 return ret;
7140 }
7141 EXPORT_SYMBOL(dev_change_flags);
7142
7143 int __dev_set_mtu(struct net_device *dev, int new_mtu)
7144 {
7145 const struct net_device_ops *ops = dev->netdev_ops;
7146
7147 if (ops->ndo_change_mtu)
7148 return ops->ndo_change_mtu(dev, new_mtu);
7149
7150 /* Pairs with all the lockless reads of dev->mtu in the stack */
7151 WRITE_ONCE(dev->mtu, new_mtu);
7152 return 0;
7153 }
7154 EXPORT_SYMBOL(__dev_set_mtu);
7155
7156 /**
7157 * dev_set_mtu - Change maximum transfer unit
7158 * @dev: device
7159 * @new_mtu: new transfer unit
7160 *
7161 * Change the maximum transfer size of the network device.
7162 */
7163 int dev_set_mtu(struct net_device *dev, int new_mtu)
7164 {
7165 int err, orig_mtu;
7166
7167 if (new_mtu == dev->mtu)
7168 return 0;
7169
7170 err = dev_validate_mtu(dev, new_mtu);
7171 if (err)
7172 return err;
7173
7174 if (!netif_device_present(dev))
7175 return -ENODEV;
7176
7177 err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev);
7178 err = notifier_to_errno(err);
7179 if (err)
7180 return err;
7181
7182 orig_mtu = dev->mtu;
7183 err = __dev_set_mtu(dev, new_mtu);
7184
7185 if (!err) {
7186 err = call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
7187 orig_mtu);
7188 err = notifier_to_errno(err);
7189 if (err) {
7190 /* setting mtu back and notifying everyone again,
7191 * so that they have a chance to revert changes.
7192 */
7193 __dev_set_mtu(dev, orig_mtu);
7194 call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
7195 new_mtu);
7196 }
7197 }
7198 return err;
7199 }
7200 EXPORT_SYMBOL(dev_set_mtu);
7201
7202 /**
7203 * dev_set_group - Change group this device belongs to
7204 * @dev: device
7205 * @new_group: group this device should belong to
7206 */
7207 void dev_set_group(struct net_device *dev, int new_group)
7208 {
7209 dev->group = new_group;
7210 }
7211 EXPORT_SYMBOL(dev_set_group);
7212
7213 /**
7214 * dev_set_mac_address - Change Media Access Control Address
7215 * @dev: device
7216 * @sa: new address
7217 *
7218 * Change the hardware (MAC) address of the device
7219 */
7220 int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa)
7221 {
7222 const struct net_device_ops *ops = dev->netdev_ops;
7223 int err;
7224
7225 if (!ops->ndo_set_mac_address)
7226 return -EOPNOTSUPP;
7227 if (sa->sa_family != dev->type)
7228 return -EINVAL;
7229 if (!netif_device_present(dev))
7230 return -ENODEV;
7231 err = ops->ndo_set_mac_address(dev, sa);
7232 if (err)
7233 return err;
7234 dev->addr_assign_type = NET_ADDR_SET;
7235 call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
7236 add_device_randomness(dev->dev_addr, dev->addr_len);
7237 return 0;
7238 }
7239 EXPORT_SYMBOL(dev_set_mac_address);
7240
7241 /**
7242 * dev_change_carrier - Change device carrier
7243 * @dev: device
7244 * @new_carrier: new value
7245 *
7246 * Change device carrier
7247 */
7248 int dev_change_carrier(struct net_device *dev, bool new_carrier)
7249 {
7250 const struct net_device_ops *ops = dev->netdev_ops;
7251
7252 if (!ops->ndo_change_carrier)
7253 return -EOPNOTSUPP;
7254 if (!netif_device_present(dev))
7255 return -ENODEV;
7256 return ops->ndo_change_carrier(dev, new_carrier);
7257 }
7258 EXPORT_SYMBOL(dev_change_carrier);
7259
7260 /**
7261 * dev_get_phys_port_id - Get device physical port ID
7262 * @dev: device
7263 * @ppid: port ID
7264 *
7265 * Get device physical port ID
7266 */
7267 int dev_get_phys_port_id(struct net_device *dev,
7268 struct netdev_phys_item_id *ppid)
7269 {
7270 const struct net_device_ops *ops = dev->netdev_ops;
7271
7272 if (!ops->ndo_get_phys_port_id)
7273 return -EOPNOTSUPP;
7274 return ops->ndo_get_phys_port_id(dev, ppid);
7275 }
7276 EXPORT_SYMBOL(dev_get_phys_port_id);
7277
7278 /**
7279 * dev_get_phys_port_name - Get device physical port name
7280 * @dev: device
7281 * @name: port name
7282 * @len: limit of bytes to copy to name
7283 *
7284 * Get device physical port name
7285 */
7286 int dev_get_phys_port_name(struct net_device *dev,
7287 char *name, size_t len)
7288 {
7289 const struct net_device_ops *ops = dev->netdev_ops;
7290
7291 if (!ops->ndo_get_phys_port_name)
7292 return -EOPNOTSUPP;
7293 return ops->ndo_get_phys_port_name(dev, name, len);
7294 }
7295 EXPORT_SYMBOL(dev_get_phys_port_name);
7296
7297 /**
7298 * dev_change_proto_down - update protocol port state information
7299 * @dev: device
7300 * @proto_down: new value
7301 *
7302 * This info can be used by switch drivers to set the phys state of the
7303 * port.
7304 */
7305 int dev_change_proto_down(struct net_device *dev, bool proto_down)
7306 {
7307 const struct net_device_ops *ops = dev->netdev_ops;
7308
7309 if (!ops->ndo_change_proto_down)
7310 return -EOPNOTSUPP;
7311 if (!netif_device_present(dev))
7312 return -ENODEV;
7313 return ops->ndo_change_proto_down(dev, proto_down);
7314 }
7315 EXPORT_SYMBOL(dev_change_proto_down);
7316
7317 u8 __dev_xdp_attached(struct net_device *dev, bpf_op_t bpf_op, u32 *prog_id)
7318 {
7319 struct netdev_bpf xdp;
7320
7321 memset(&xdp, 0, sizeof(xdp));
7322 xdp.command = XDP_QUERY_PROG;
7323
7324 /* Query must always succeed. */
7325 WARN_ON(bpf_op(dev, &xdp) < 0);
7326 if (prog_id)
7327 *prog_id = xdp.prog_id;
7328
7329 return xdp.prog_attached;
7330 }
7331
7332 static int dev_xdp_install(struct net_device *dev, bpf_op_t bpf_op,
7333 struct netlink_ext_ack *extack, u32 flags,
7334 struct bpf_prog *prog)
7335 {
7336 struct netdev_bpf xdp;
7337
7338 memset(&xdp, 0, sizeof(xdp));
7339 if (flags & XDP_FLAGS_HW_MODE)
7340 xdp.command = XDP_SETUP_PROG_HW;
7341 else
7342 xdp.command = XDP_SETUP_PROG;
7343 xdp.extack = extack;
7344 xdp.flags = flags;
7345 xdp.prog = prog;
7346
7347 return bpf_op(dev, &xdp);
7348 }
7349
7350 /**
7351 * dev_change_xdp_fd - set or clear a bpf program for a device rx path
7352 * @dev: device
7353 * @extack: netlink extended ack
7354 * @fd: new program fd or negative value to clear
7355 * @flags: xdp-related flags
7356 *
7357 * Set or clear a bpf program for a device
7358 */
7359 int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack,
7360 int fd, u32 flags)
7361 {
7362 const struct net_device_ops *ops = dev->netdev_ops;
7363 struct bpf_prog *prog = NULL;
7364 bpf_op_t bpf_op, bpf_chk;
7365 int err;
7366
7367 ASSERT_RTNL();
7368
7369 bpf_op = bpf_chk = ops->ndo_bpf;
7370 if (!bpf_op && (flags & (XDP_FLAGS_DRV_MODE | XDP_FLAGS_HW_MODE)))
7371 return -EOPNOTSUPP;
7372 if (!bpf_op || (flags & XDP_FLAGS_SKB_MODE))
7373 bpf_op = generic_xdp_install;
7374 if (bpf_op == bpf_chk)
7375 bpf_chk = generic_xdp_install;
7376
7377 if (fd >= 0) {
7378 if (bpf_chk && __dev_xdp_attached(dev, bpf_chk, NULL))
7379 return -EEXIST;
7380 if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) &&
7381 __dev_xdp_attached(dev, bpf_op, NULL))
7382 return -EBUSY;
7383
7384 prog = bpf_prog_get_type_dev(fd, BPF_PROG_TYPE_XDP,
7385 bpf_op == ops->ndo_bpf);
7386 if (IS_ERR(prog))
7387 return PTR_ERR(prog);
7388
7389 if (!(flags & XDP_FLAGS_HW_MODE) &&
7390 bpf_prog_is_dev_bound(prog->aux)) {
7391 NL_SET_ERR_MSG(extack, "using device-bound program without HW_MODE flag is not supported");
7392 bpf_prog_put(prog);
7393 return -EINVAL;
7394 }
7395 }
7396
7397 err = dev_xdp_install(dev, bpf_op, extack, flags, prog);
7398 if (err < 0 && prog)
7399 bpf_prog_put(prog);
7400
7401 return err;
7402 }
7403
7404 /**
7405 * dev_new_index - allocate an ifindex
7406 * @net: the applicable net namespace
7407 *
7408 * Returns a suitable unique value for a new device interface
7409 * number. The caller must hold the rtnl semaphore or the
7410 * dev_base_lock to be sure it remains unique.
7411 */
7412 static int dev_new_index(struct net *net)
7413 {
7414 int ifindex = net->ifindex;
7415
7416 for (;;) {
7417 if (++ifindex <= 0)
7418 ifindex = 1;
7419 if (!__dev_get_by_index(net, ifindex))
7420 return net->ifindex = ifindex;
7421 }
7422 }
7423
7424 /* Delayed registration/unregisteration */
7425 static LIST_HEAD(net_todo_list);
7426 DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq);
7427
7428 static void net_set_todo(struct net_device *dev)
7429 {
7430 list_add_tail(&dev->todo_list, &net_todo_list);
7431 dev_net(dev)->dev_unreg_count++;
7432 }
7433
7434 static void rollback_registered_many(struct list_head *head)
7435 {
7436 struct net_device *dev, *tmp;
7437 LIST_HEAD(close_head);
7438
7439 BUG_ON(dev_boot_phase);
7440 ASSERT_RTNL();
7441
7442 list_for_each_entry_safe(dev, tmp, head, unreg_list) {
7443 /* Some devices call without registering
7444 * for initialization unwind. Remove those
7445 * devices and proceed with the remaining.
7446 */
7447 if (dev->reg_state == NETREG_UNINITIALIZED) {
7448 pr_debug("unregister_netdevice: device %s/%p never was registered\n",
7449 dev->name, dev);
7450
7451 WARN_ON(1);
7452 list_del(&dev->unreg_list);
7453 continue;
7454 }
7455 dev->dismantle = true;
7456 BUG_ON(dev->reg_state != NETREG_REGISTERED);
7457 }
7458
7459 /* If device is running, close it first. */
7460 list_for_each_entry(dev, head, unreg_list)
7461 list_add_tail(&dev->close_list, &close_head);
7462 dev_close_many(&close_head, true);
7463
7464 list_for_each_entry(dev, head, unreg_list) {
7465 /* And unlink it from device chain. */
7466 unlist_netdevice(dev);
7467
7468 dev->reg_state = NETREG_UNREGISTERING;
7469 }
7470 flush_all_backlogs();
7471
7472 synchronize_net();
7473
7474 list_for_each_entry(dev, head, unreg_list) {
7475 struct sk_buff *skb = NULL;
7476
7477 /* Shutdown queueing discipline. */
7478 dev_shutdown(dev);
7479
7480
7481 /* Notify protocols, that we are about to destroy
7482 * this device. They should clean all the things.
7483 */
7484 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
7485
7486 if (!dev->rtnl_link_ops ||
7487 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
7488 skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0,
7489 GFP_KERNEL, NULL, 0);
7490
7491 /*
7492 * Flush the unicast and multicast chains
7493 */
7494 dev_uc_flush(dev);
7495 dev_mc_flush(dev);
7496
7497 if (dev->netdev_ops->ndo_uninit)
7498 dev->netdev_ops->ndo_uninit(dev);
7499
7500 if (skb)
7501 rtmsg_ifinfo_send(skb, dev, GFP_KERNEL);
7502
7503 /* Notifier chain MUST detach us all upper devices. */
7504 WARN_ON(netdev_has_any_upper_dev(dev));
7505 WARN_ON(netdev_has_any_lower_dev(dev));
7506
7507 /* Remove entries from kobject tree */
7508 netdev_unregister_kobject(dev);
7509 #ifdef CONFIG_XPS
7510 /* Remove XPS queueing entries */
7511 netif_reset_xps_queues_gt(dev, 0);
7512 #endif
7513 }
7514
7515 synchronize_net();
7516
7517 list_for_each_entry(dev, head, unreg_list)
7518 dev_put(dev);
7519 }
7520
7521 static void rollback_registered(struct net_device *dev)
7522 {
7523 LIST_HEAD(single);
7524
7525 list_add(&dev->unreg_list, &single);
7526 rollback_registered_many(&single);
7527 list_del(&single);
7528 }
7529
7530 static netdev_features_t netdev_sync_upper_features(struct net_device *lower,
7531 struct net_device *upper, netdev_features_t features)
7532 {
7533 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
7534 netdev_features_t feature;
7535 int feature_bit;
7536
7537 for_each_netdev_feature(upper_disables, feature_bit) {
7538 feature = __NETIF_F_BIT(feature_bit);
7539 if (!(upper->wanted_features & feature)
7540 && (features & feature)) {
7541 netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n",
7542 &feature, upper->name);
7543 features &= ~feature;
7544 }
7545 }
7546
7547 return features;
7548 }
7549
7550 static void netdev_sync_lower_features(struct net_device *upper,
7551 struct net_device *lower, netdev_features_t features)
7552 {
7553 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
7554 netdev_features_t feature;
7555 int feature_bit;
7556
7557 for_each_netdev_feature(upper_disables, feature_bit) {
7558 feature = __NETIF_F_BIT(feature_bit);
7559 if (!(features & feature) && (lower->features & feature)) {
7560 netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n",
7561 &feature, lower->name);
7562 lower->wanted_features &= ~feature;
7563 netdev_update_features(lower);
7564
7565 if (unlikely(lower->features & feature))
7566 netdev_WARN(upper, "failed to disable %pNF on %s!\n",
7567 &feature, lower->name);
7568 }
7569 }
7570 }
7571
7572 static netdev_features_t netdev_fix_features(struct net_device *dev,
7573 netdev_features_t features)
7574 {
7575 /* Fix illegal checksum combinations */
7576 if ((features & NETIF_F_HW_CSUM) &&
7577 (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
7578 netdev_warn(dev, "mixed HW and IP checksum settings.\n");
7579 features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM);
7580 }
7581
7582 /* TSO requires that SG is present as well. */
7583 if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) {
7584 netdev_dbg(dev, "Dropping TSO features since no SG feature.\n");
7585 features &= ~NETIF_F_ALL_TSO;
7586 }
7587
7588 if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) &&
7589 !(features & NETIF_F_IP_CSUM)) {
7590 netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n");
7591 features &= ~NETIF_F_TSO;
7592 features &= ~NETIF_F_TSO_ECN;
7593 }
7594
7595 if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) &&
7596 !(features & NETIF_F_IPV6_CSUM)) {
7597 netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n");
7598 features &= ~NETIF_F_TSO6;
7599 }
7600
7601 /* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */
7602 if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO))
7603 features &= ~NETIF_F_TSO_MANGLEID;
7604
7605 /* TSO ECN requires that TSO is present as well. */
7606 if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN)
7607 features &= ~NETIF_F_TSO_ECN;
7608
7609 /* Software GSO depends on SG. */
7610 if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) {
7611 netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n");
7612 features &= ~NETIF_F_GSO;
7613 }
7614
7615 /* GSO partial features require GSO partial be set */
7616 if ((features & dev->gso_partial_features) &&
7617 !(features & NETIF_F_GSO_PARTIAL)) {
7618 netdev_dbg(dev,
7619 "Dropping partially supported GSO features since no GSO partial.\n");
7620 features &= ~dev->gso_partial_features;
7621 }
7622
7623 return features;
7624 }
7625
7626 int __netdev_update_features(struct net_device *dev)
7627 {
7628 struct net_device *upper, *lower;
7629 netdev_features_t features;
7630 struct list_head *iter;
7631 int err = -1;
7632
7633 ASSERT_RTNL();
7634
7635 features = netdev_get_wanted_features(dev);
7636
7637 if (dev->netdev_ops->ndo_fix_features)
7638 features = dev->netdev_ops->ndo_fix_features(dev, features);
7639
7640 /* driver might be less strict about feature dependencies */
7641 features = netdev_fix_features(dev, features);
7642
7643 /* some features can't be enabled if they're off an an upper device */
7644 netdev_for_each_upper_dev_rcu(dev, upper, iter)
7645 features = netdev_sync_upper_features(dev, upper, features);
7646
7647 if (dev->features == features)
7648 goto sync_lower;
7649
7650 netdev_dbg(dev, "Features changed: %pNF -> %pNF\n",
7651 &dev->features, &features);
7652
7653 if (dev->netdev_ops->ndo_set_features)
7654 err = dev->netdev_ops->ndo_set_features(dev, features);
7655 else
7656 err = 0;
7657
7658 if (unlikely(err < 0)) {
7659 netdev_err(dev,
7660 "set_features() failed (%d); wanted %pNF, left %pNF\n",
7661 err, &features, &dev->features);
7662 /* return non-0 since some features might have changed and
7663 * it's better to fire a spurious notification than miss it
7664 */
7665 return -1;
7666 }
7667
7668 sync_lower:
7669 /* some features must be disabled on lower devices when disabled
7670 * on an upper device (think: bonding master or bridge)
7671 */
7672 netdev_for_each_lower_dev(dev, lower, iter)
7673 netdev_sync_lower_features(dev, lower, features);
7674
7675 if (!err) {
7676 netdev_features_t diff = features ^ dev->features;
7677
7678 if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) {
7679 /* udp_tunnel_{get,drop}_rx_info both need
7680 * NETIF_F_RX_UDP_TUNNEL_PORT enabled on the
7681 * device, or they won't do anything.
7682 * Thus we need to update dev->features
7683 * *before* calling udp_tunnel_get_rx_info,
7684 * but *after* calling udp_tunnel_drop_rx_info.
7685 */
7686 if (features & NETIF_F_RX_UDP_TUNNEL_PORT) {
7687 dev->features = features;
7688 udp_tunnel_get_rx_info(dev);
7689 } else {
7690 udp_tunnel_drop_rx_info(dev);
7691 }
7692 }
7693
7694 dev->features = features;
7695 }
7696
7697 return err < 0 ? 0 : 1;
7698 }
7699
7700 /**
7701 * netdev_update_features - recalculate device features
7702 * @dev: the device to check
7703 *
7704 * Recalculate dev->features set and send notifications if it
7705 * has changed. Should be called after driver or hardware dependent
7706 * conditions might have changed that influence the features.
7707 */
7708 void netdev_update_features(struct net_device *dev)
7709 {
7710 if (__netdev_update_features(dev))
7711 netdev_features_change(dev);
7712 }
7713 EXPORT_SYMBOL(netdev_update_features);
7714
7715 /**
7716 * netdev_change_features - recalculate device features
7717 * @dev: the device to check
7718 *
7719 * Recalculate dev->features set and send notifications even
7720 * if they have not changed. Should be called instead of
7721 * netdev_update_features() if also dev->vlan_features might
7722 * have changed to allow the changes to be propagated to stacked
7723 * VLAN devices.
7724 */
7725 void netdev_change_features(struct net_device *dev)
7726 {
7727 __netdev_update_features(dev);
7728 netdev_features_change(dev);
7729 }
7730 EXPORT_SYMBOL(netdev_change_features);
7731
7732 /**
7733 * netif_stacked_transfer_operstate - transfer operstate
7734 * @rootdev: the root or lower level device to transfer state from
7735 * @dev: the device to transfer operstate to
7736 *
7737 * Transfer operational state from root to device. This is normally
7738 * called when a stacking relationship exists between the root
7739 * device and the device(a leaf device).
7740 */
7741 void netif_stacked_transfer_operstate(const struct net_device *rootdev,
7742 struct net_device *dev)
7743 {
7744 if (rootdev->operstate == IF_OPER_DORMANT)
7745 netif_dormant_on(dev);
7746 else
7747 netif_dormant_off(dev);
7748
7749 if (netif_carrier_ok(rootdev))
7750 netif_carrier_on(dev);
7751 else
7752 netif_carrier_off(dev);
7753 }
7754 EXPORT_SYMBOL(netif_stacked_transfer_operstate);
7755
7756 #ifdef CONFIG_SYSFS
7757 static int netif_alloc_rx_queues(struct net_device *dev)
7758 {
7759 unsigned int i, count = dev->num_rx_queues;
7760 struct netdev_rx_queue *rx;
7761 size_t sz = count * sizeof(*rx);
7762
7763 BUG_ON(count < 1);
7764
7765 rx = kvzalloc(sz, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
7766 if (!rx)
7767 return -ENOMEM;
7768
7769 dev->_rx = rx;
7770
7771 for (i = 0; i < count; i++)
7772 rx[i].dev = dev;
7773 return 0;
7774 }
7775 #endif
7776
7777 static void netdev_init_one_queue(struct net_device *dev,
7778 struct netdev_queue *queue, void *_unused)
7779 {
7780 /* Initialize queue lock */
7781 spin_lock_init(&queue->_xmit_lock);
7782 netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type);
7783 queue->xmit_lock_owner = -1;
7784 netdev_queue_numa_node_write(queue, NUMA_NO_NODE);
7785 queue->dev = dev;
7786 #ifdef CONFIG_BQL
7787 dql_init(&queue->dql, HZ);
7788 #endif
7789 }
7790
7791 static void netif_free_tx_queues(struct net_device *dev)
7792 {
7793 kvfree(dev->_tx);
7794 }
7795
7796 static int netif_alloc_netdev_queues(struct net_device *dev)
7797 {
7798 unsigned int count = dev->num_tx_queues;
7799 struct netdev_queue *tx;
7800 size_t sz = count * sizeof(*tx);
7801
7802 if (count < 1 || count > 0xffff)
7803 return -EINVAL;
7804
7805 tx = kvzalloc(sz, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
7806 if (!tx)
7807 return -ENOMEM;
7808
7809 dev->_tx = tx;
7810
7811 netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL);
7812 spin_lock_init(&dev->tx_global_lock);
7813
7814 return 0;
7815 }
7816
7817 void netif_tx_stop_all_queues(struct net_device *dev)
7818 {
7819 unsigned int i;
7820
7821 for (i = 0; i < dev->num_tx_queues; i++) {
7822 struct netdev_queue *txq = netdev_get_tx_queue(dev, i);
7823
7824 netif_tx_stop_queue(txq);
7825 }
7826 }
7827 EXPORT_SYMBOL(netif_tx_stop_all_queues);
7828
7829 /**
7830 * register_netdevice - register a network device
7831 * @dev: device to register
7832 *
7833 * Take a completed network device structure and add it to the kernel
7834 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
7835 * chain. 0 is returned on success. A negative errno code is returned
7836 * on a failure to set up the device, or if the name is a duplicate.
7837 *
7838 * Callers must hold the rtnl semaphore. You may want
7839 * register_netdev() instead of this.
7840 *
7841 * BUGS:
7842 * The locking appears insufficient to guarantee two parallel registers
7843 * will not get the same name.
7844 */
7845
7846 int register_netdevice(struct net_device *dev)
7847 {
7848 int ret;
7849 struct net *net = dev_net(dev);
7850
7851 BUG_ON(dev_boot_phase);
7852 ASSERT_RTNL();
7853
7854 might_sleep();
7855
7856 /* When net_device's are persistent, this will be fatal. */
7857 BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
7858 BUG_ON(!net);
7859
7860 spin_lock_init(&dev->addr_list_lock);
7861 netdev_set_addr_lockdep_class(dev);
7862
7863 ret = dev_get_valid_name(net, dev, dev->name);
7864 if (ret < 0)
7865 goto out;
7866
7867 /* Init, if this function is available */
7868 if (dev->netdev_ops->ndo_init) {
7869 ret = dev->netdev_ops->ndo_init(dev);
7870 if (ret) {
7871 if (ret > 0)
7872 ret = -EIO;
7873 goto out;
7874 }
7875 }
7876
7877 if (((dev->hw_features | dev->features) &
7878 NETIF_F_HW_VLAN_CTAG_FILTER) &&
7879 (!dev->netdev_ops->ndo_vlan_rx_add_vid ||
7880 !dev->netdev_ops->ndo_vlan_rx_kill_vid)) {
7881 netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n");
7882 ret = -EINVAL;
7883 goto err_uninit;
7884 }
7885
7886 ret = -EBUSY;
7887 if (!dev->ifindex)
7888 dev->ifindex = dev_new_index(net);
7889 else if (__dev_get_by_index(net, dev->ifindex))
7890 goto err_uninit;
7891
7892 /* Transfer changeable features to wanted_features and enable
7893 * software offloads (GSO and GRO).
7894 */
7895 dev->hw_features |= NETIF_F_SOFT_FEATURES;
7896 dev->features |= NETIF_F_SOFT_FEATURES;
7897
7898 if (dev->netdev_ops->ndo_udp_tunnel_add) {
7899 dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT;
7900 dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT;
7901 }
7902
7903 dev->wanted_features = dev->features & dev->hw_features;
7904
7905 if (!(dev->flags & IFF_LOOPBACK))
7906 dev->hw_features |= NETIF_F_NOCACHE_COPY;
7907
7908 /* If IPv4 TCP segmentation offload is supported we should also
7909 * allow the device to enable segmenting the frame with the option
7910 * of ignoring a static IP ID value. This doesn't enable the
7911 * feature itself but allows the user to enable it later.
7912 */
7913 if (dev->hw_features & NETIF_F_TSO)
7914 dev->hw_features |= NETIF_F_TSO_MANGLEID;
7915 if (dev->vlan_features & NETIF_F_TSO)
7916 dev->vlan_features |= NETIF_F_TSO_MANGLEID;
7917 if (dev->mpls_features & NETIF_F_TSO)
7918 dev->mpls_features |= NETIF_F_TSO_MANGLEID;
7919 if (dev->hw_enc_features & NETIF_F_TSO)
7920 dev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
7921
7922 /* Make NETIF_F_HIGHDMA inheritable to VLAN devices.
7923 */
7924 dev->vlan_features |= NETIF_F_HIGHDMA;
7925
7926 /* Make NETIF_F_SG inheritable to tunnel devices.
7927 */
7928 dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL;
7929
7930 /* Make NETIF_F_SG inheritable to MPLS.
7931 */
7932 dev->mpls_features |= NETIF_F_SG;
7933
7934 ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev);
7935 ret = notifier_to_errno(ret);
7936 if (ret)
7937 goto err_uninit;
7938
7939 ret = netdev_register_kobject(dev);
7940 if (ret) {
7941 dev->reg_state = NETREG_UNREGISTERED;
7942 goto err_uninit;
7943 }
7944 dev->reg_state = NETREG_REGISTERED;
7945
7946 __netdev_update_features(dev);
7947
7948 /*
7949 * Default initial state at registry is that the
7950 * device is present.
7951 */
7952
7953 set_bit(__LINK_STATE_PRESENT, &dev->state);
7954
7955 linkwatch_init_dev(dev);
7956
7957 dev_init_scheduler(dev);
7958 dev_hold(dev);
7959 list_netdevice(dev);
7960 add_device_randomness(dev->dev_addr, dev->addr_len);
7961
7962 /* If the device has permanent device address, driver should
7963 * set dev_addr and also addr_assign_type should be set to
7964 * NET_ADDR_PERM (default value).
7965 */
7966 if (dev->addr_assign_type == NET_ADDR_PERM)
7967 memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
7968
7969 /* Notify protocols, that a new device appeared. */
7970 ret = call_netdevice_notifiers(NETDEV_REGISTER, dev);
7971 ret = notifier_to_errno(ret);
7972 if (ret) {
7973 rollback_registered(dev);
7974 rcu_barrier();
7975
7976 dev->reg_state = NETREG_UNREGISTERED;
7977 }
7978 /*
7979 * Prevent userspace races by waiting until the network
7980 * device is fully setup before sending notifications.
7981 */
7982 if (!dev->rtnl_link_ops ||
7983 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
7984 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL);
7985
7986 out:
7987 return ret;
7988
7989 err_uninit:
7990 if (dev->netdev_ops->ndo_uninit)
7991 dev->netdev_ops->ndo_uninit(dev);
7992 if (dev->priv_destructor)
7993 dev->priv_destructor(dev);
7994 goto out;
7995 }
7996 EXPORT_SYMBOL(register_netdevice);
7997
7998 /**
7999 * init_dummy_netdev - init a dummy network device for NAPI
8000 * @dev: device to init
8001 *
8002 * This takes a network device structure and initialize the minimum
8003 * amount of fields so it can be used to schedule NAPI polls without
8004 * registering a full blown interface. This is to be used by drivers
8005 * that need to tie several hardware interfaces to a single NAPI
8006 * poll scheduler due to HW limitations.
8007 */
8008 int init_dummy_netdev(struct net_device *dev)
8009 {
8010 /* Clear everything. Note we don't initialize spinlocks
8011 * are they aren't supposed to be taken by any of the
8012 * NAPI code and this dummy netdev is supposed to be
8013 * only ever used for NAPI polls
8014 */
8015 memset(dev, 0, sizeof(struct net_device));
8016
8017 /* make sure we BUG if trying to hit standard
8018 * register/unregister code path
8019 */
8020 dev->reg_state = NETREG_DUMMY;
8021
8022 /* NAPI wants this */
8023 INIT_LIST_HEAD(&dev->napi_list);
8024
8025 /* a dummy interface is started by default */
8026 set_bit(__LINK_STATE_PRESENT, &dev->state);
8027 set_bit(__LINK_STATE_START, &dev->state);
8028
8029 /* napi_busy_loop stats accounting wants this */
8030 dev_net_set(dev, &init_net);
8031
8032 /* Note : We dont allocate pcpu_refcnt for dummy devices,
8033 * because users of this 'device' dont need to change
8034 * its refcount.
8035 */
8036
8037 return 0;
8038 }
8039 EXPORT_SYMBOL_GPL(init_dummy_netdev);
8040
8041
8042 int dev_validate_mtu(struct net_device *dev, int new_mtu)
8043 {
8044 /* MTU must be positive, and in range */
8045 if (new_mtu < 0 || new_mtu < dev->min_mtu) {
8046 net_err_ratelimited("%s: Invalid MTU %d requested, hw min %d\n",
8047 dev->name, new_mtu, dev->min_mtu);
8048 return -EINVAL;
8049 }
8050
8051 if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) {
8052 net_err_ratelimited("%s: Invalid MTU %d requested, hw max %d\n",
8053 dev->name, new_mtu, dev->max_mtu);
8054 return -EINVAL;
8055 }
8056 return 0;
8057 }
8058
8059 /**
8060 * register_netdev - register a network device
8061 * @dev: device to register
8062 *
8063 * Take a completed network device structure and add it to the kernel
8064 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
8065 * chain. 0 is returned on success. A negative errno code is returned
8066 * on a failure to set up the device, or if the name is a duplicate.
8067 *
8068 * This is a wrapper around register_netdevice that takes the rtnl semaphore
8069 * and expands the device name if you passed a format string to
8070 * alloc_netdev.
8071 */
8072 int register_netdev(struct net_device *dev)
8073 {
8074 int err;
8075
8076 rtnl_lock();
8077 err = register_netdevice(dev);
8078 rtnl_unlock();
8079 return err;
8080 }
8081 EXPORT_SYMBOL(register_netdev);
8082
8083 int netdev_refcnt_read(const struct net_device *dev)
8084 {
8085 int i, refcnt = 0;
8086
8087 for_each_possible_cpu(i)
8088 refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i);
8089 return refcnt;
8090 }
8091 EXPORT_SYMBOL(netdev_refcnt_read);
8092
8093 /**
8094 * netdev_wait_allrefs - wait until all references are gone.
8095 * @dev: target net_device
8096 *
8097 * This is called when unregistering network devices.
8098 *
8099 * Any protocol or device that holds a reference should register
8100 * for netdevice notification, and cleanup and put back the
8101 * reference if they receive an UNREGISTER event.
8102 * We can get stuck here if buggy protocols don't correctly
8103 * call dev_put.
8104 */
8105 static void netdev_wait_allrefs(struct net_device *dev)
8106 {
8107 unsigned long rebroadcast_time, warning_time;
8108 int refcnt;
8109
8110 linkwatch_forget_dev(dev);
8111
8112 rebroadcast_time = warning_time = jiffies;
8113 refcnt = netdev_refcnt_read(dev);
8114
8115 while (refcnt != 0) {
8116 if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
8117 rtnl_lock();
8118
8119 /* Rebroadcast unregister notification */
8120 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
8121
8122 __rtnl_unlock();
8123 rcu_barrier();
8124 rtnl_lock();
8125
8126 call_netdevice_notifiers(NETDEV_UNREGISTER_FINAL, dev);
8127 if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
8128 &dev->state)) {
8129 /* We must not have linkwatch events
8130 * pending on unregister. If this
8131 * happens, we simply run the queue
8132 * unscheduled, resulting in a noop
8133 * for this device.
8134 */
8135 linkwatch_run_queue();
8136 }
8137
8138 __rtnl_unlock();
8139
8140 rebroadcast_time = jiffies;
8141 }
8142
8143 msleep(250);
8144
8145 refcnt = netdev_refcnt_read(dev);
8146
8147 if (refcnt && time_after(jiffies, warning_time + 10 * HZ)) {
8148 pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n",
8149 dev->name, refcnt);
8150 warning_time = jiffies;
8151 }
8152 }
8153 }
8154
8155 /* The sequence is:
8156 *
8157 * rtnl_lock();
8158 * ...
8159 * register_netdevice(x1);
8160 * register_netdevice(x2);
8161 * ...
8162 * unregister_netdevice(y1);
8163 * unregister_netdevice(y2);
8164 * ...
8165 * rtnl_unlock();
8166 * free_netdev(y1);
8167 * free_netdev(y2);
8168 *
8169 * We are invoked by rtnl_unlock().
8170 * This allows us to deal with problems:
8171 * 1) We can delete sysfs objects which invoke hotplug
8172 * without deadlocking with linkwatch via keventd.
8173 * 2) Since we run with the RTNL semaphore not held, we can sleep
8174 * safely in order to wait for the netdev refcnt to drop to zero.
8175 *
8176 * We must not return until all unregister events added during
8177 * the interval the lock was held have been completed.
8178 */
8179 void netdev_run_todo(void)
8180 {
8181 struct list_head list;
8182
8183 /* Snapshot list, allow later requests */
8184 list_replace_init(&net_todo_list, &list);
8185
8186 __rtnl_unlock();
8187
8188
8189 /* Wait for rcu callbacks to finish before next phase */
8190 if (!list_empty(&list))
8191 rcu_barrier();
8192
8193 while (!list_empty(&list)) {
8194 struct net_device *dev
8195 = list_first_entry(&list, struct net_device, todo_list);
8196 list_del(&dev->todo_list);
8197
8198 rtnl_lock();
8199 call_netdevice_notifiers(NETDEV_UNREGISTER_FINAL, dev);
8200 __rtnl_unlock();
8201
8202 if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) {
8203 pr_err("network todo '%s' but state %d\n",
8204 dev->name, dev->reg_state);
8205 dump_stack();
8206 continue;
8207 }
8208
8209 dev->reg_state = NETREG_UNREGISTERED;
8210
8211 netdev_wait_allrefs(dev);
8212
8213 /* paranoia */
8214 BUG_ON(netdev_refcnt_read(dev));
8215 BUG_ON(!list_empty(&dev->ptype_all));
8216 BUG_ON(!list_empty(&dev->ptype_specific));
8217 WARN_ON(rcu_access_pointer(dev->ip_ptr));
8218 WARN_ON(rcu_access_pointer(dev->ip6_ptr));
8219 WARN_ON(dev->dn_ptr);
8220
8221 if (dev->priv_destructor)
8222 dev->priv_destructor(dev);
8223 if (dev->needs_free_netdev)
8224 free_netdev(dev);
8225
8226 /* Report a network device has been unregistered */
8227 rtnl_lock();
8228 dev_net(dev)->dev_unreg_count--;
8229 __rtnl_unlock();
8230 wake_up(&netdev_unregistering_wq);
8231
8232 /* Free network device */
8233 kobject_put(&dev->dev.kobj);
8234 }
8235 }
8236
8237 /* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has
8238 * all the same fields in the same order as net_device_stats, with only
8239 * the type differing, but rtnl_link_stats64 may have additional fields
8240 * at the end for newer counters.
8241 */
8242 void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64,
8243 const struct net_device_stats *netdev_stats)
8244 {
8245 #if BITS_PER_LONG == 64
8246 BUILD_BUG_ON(sizeof(*stats64) < sizeof(*netdev_stats));
8247 memcpy(stats64, netdev_stats, sizeof(*netdev_stats));
8248 /* zero out counters that only exist in rtnl_link_stats64 */
8249 memset((char *)stats64 + sizeof(*netdev_stats), 0,
8250 sizeof(*stats64) - sizeof(*netdev_stats));
8251 #else
8252 size_t i, n = sizeof(*netdev_stats) / sizeof(unsigned long);
8253 const unsigned long *src = (const unsigned long *)netdev_stats;
8254 u64 *dst = (u64 *)stats64;
8255
8256 BUILD_BUG_ON(n > sizeof(*stats64) / sizeof(u64));
8257 for (i = 0; i < n; i++)
8258 dst[i] = src[i];
8259 /* zero out counters that only exist in rtnl_link_stats64 */
8260 memset((char *)stats64 + n * sizeof(u64), 0,
8261 sizeof(*stats64) - n * sizeof(u64));
8262 #endif
8263 }
8264 EXPORT_SYMBOL(netdev_stats_to_stats64);
8265
8266 /**
8267 * dev_get_stats - get network device statistics
8268 * @dev: device to get statistics from
8269 * @storage: place to store stats
8270 *
8271 * Get network statistics from device. Return @storage.
8272 * The device driver may provide its own method by setting
8273 * dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats;
8274 * otherwise the internal statistics structure is used.
8275 */
8276 struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev,
8277 struct rtnl_link_stats64 *storage)
8278 {
8279 const struct net_device_ops *ops = dev->netdev_ops;
8280
8281 if (ops->ndo_get_stats64) {
8282 memset(storage, 0, sizeof(*storage));
8283 ops->ndo_get_stats64(dev, storage);
8284 } else if (ops->ndo_get_stats) {
8285 netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev));
8286 } else {
8287 netdev_stats_to_stats64(storage, &dev->stats);
8288 }
8289 storage->rx_dropped += (unsigned long)atomic_long_read(&dev->rx_dropped);
8290 storage->tx_dropped += (unsigned long)atomic_long_read(&dev->tx_dropped);
8291 storage->rx_nohandler += (unsigned long)atomic_long_read(&dev->rx_nohandler);
8292 return storage;
8293 }
8294 EXPORT_SYMBOL(dev_get_stats);
8295
8296 struct netdev_queue *dev_ingress_queue_create(struct net_device *dev)
8297 {
8298 struct netdev_queue *queue = dev_ingress_queue(dev);
8299
8300 #ifdef CONFIG_NET_CLS_ACT
8301 if (queue)
8302 return queue;
8303 queue = kzalloc(sizeof(*queue), GFP_KERNEL);
8304 if (!queue)
8305 return NULL;
8306 netdev_init_one_queue(dev, queue, NULL);
8307 RCU_INIT_POINTER(queue->qdisc, &noop_qdisc);
8308 queue->qdisc_sleeping = &noop_qdisc;
8309 rcu_assign_pointer(dev->ingress_queue, queue);
8310 #endif
8311 return queue;
8312 }
8313
8314 static const struct ethtool_ops default_ethtool_ops;
8315
8316 void netdev_set_default_ethtool_ops(struct net_device *dev,
8317 const struct ethtool_ops *ops)
8318 {
8319 if (dev->ethtool_ops == &default_ethtool_ops)
8320 dev->ethtool_ops = ops;
8321 }
8322 EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops);
8323
8324 void netdev_freemem(struct net_device *dev)
8325 {
8326 char *addr = (char *)dev - dev->padded;
8327
8328 kvfree(addr);
8329 }
8330
8331 /**
8332 * alloc_netdev_mqs - allocate network device
8333 * @sizeof_priv: size of private data to allocate space for
8334 * @name: device name format string
8335 * @name_assign_type: origin of device name
8336 * @setup: callback to initialize device
8337 * @txqs: the number of TX subqueues to allocate
8338 * @rxqs: the number of RX subqueues to allocate
8339 *
8340 * Allocates a struct net_device with private data area for driver use
8341 * and performs basic initialization. Also allocates subqueue structs
8342 * for each queue on the device.
8343 */
8344 struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name,
8345 unsigned char name_assign_type,
8346 void (*setup)(struct net_device *),
8347 unsigned int txqs, unsigned int rxqs)
8348 {
8349 struct net_device *dev;
8350 unsigned int alloc_size;
8351 struct net_device *p;
8352
8353 BUG_ON(strlen(name) >= sizeof(dev->name));
8354
8355 if (txqs < 1) {
8356 pr_err("alloc_netdev: Unable to allocate device with zero queues\n");
8357 return NULL;
8358 }
8359
8360 #ifdef CONFIG_SYSFS
8361 if (rxqs < 1) {
8362 pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n");
8363 return NULL;
8364 }
8365 #endif
8366
8367 alloc_size = sizeof(struct net_device);
8368 if (sizeof_priv) {
8369 /* ensure 32-byte alignment of private area */
8370 alloc_size = ALIGN(alloc_size, NETDEV_ALIGN);
8371 alloc_size += sizeof_priv;
8372 }
8373 /* ensure 32-byte alignment of whole construct */
8374 alloc_size += NETDEV_ALIGN - 1;
8375
8376 p = kvzalloc(alloc_size, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
8377 if (!p)
8378 return NULL;
8379
8380 dev = PTR_ALIGN(p, NETDEV_ALIGN);
8381 dev->padded = (char *)dev - (char *)p;
8382
8383 dev->pcpu_refcnt = alloc_percpu(int);
8384 if (!dev->pcpu_refcnt)
8385 goto free_dev;
8386
8387 if (dev_addr_init(dev))
8388 goto free_pcpu;
8389
8390 dev_mc_init(dev);
8391 dev_uc_init(dev);
8392
8393 dev_net_set(dev, &init_net);
8394
8395 dev->gso_max_size = GSO_MAX_SIZE;
8396 dev->gso_max_segs = GSO_MAX_SEGS;
8397 dev->upper_level = 1;
8398 dev->lower_level = 1;
8399
8400 INIT_LIST_HEAD(&dev->napi_list);
8401 INIT_LIST_HEAD(&dev->unreg_list);
8402 INIT_LIST_HEAD(&dev->close_list);
8403 INIT_LIST_HEAD(&dev->link_watch_list);
8404 INIT_LIST_HEAD(&dev->adj_list.upper);
8405 INIT_LIST_HEAD(&dev->adj_list.lower);
8406 INIT_LIST_HEAD(&dev->ptype_all);
8407 INIT_LIST_HEAD(&dev->ptype_specific);
8408 #ifdef CONFIG_NET_SCHED
8409 hash_init(dev->qdisc_hash);
8410 #endif
8411 dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM;
8412 setup(dev);
8413
8414 if (!dev->tx_queue_len) {
8415 dev->priv_flags |= IFF_NO_QUEUE;
8416 dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN;
8417 }
8418
8419 dev->num_tx_queues = txqs;
8420 dev->real_num_tx_queues = txqs;
8421 if (netif_alloc_netdev_queues(dev))
8422 goto free_all;
8423
8424 #ifdef CONFIG_SYSFS
8425 dev->num_rx_queues = rxqs;
8426 dev->real_num_rx_queues = rxqs;
8427 if (netif_alloc_rx_queues(dev))
8428 goto free_all;
8429 #endif
8430
8431 strcpy(dev->name, name);
8432 dev->name_assign_type = name_assign_type;
8433 dev->group = INIT_NETDEV_GROUP;
8434 if (!dev->ethtool_ops)
8435 dev->ethtool_ops = &default_ethtool_ops;
8436
8437 nf_hook_ingress_init(dev);
8438
8439 return dev;
8440
8441 free_all:
8442 free_netdev(dev);
8443 return NULL;
8444
8445 free_pcpu:
8446 free_percpu(dev->pcpu_refcnt);
8447 free_dev:
8448 netdev_freemem(dev);
8449 return NULL;
8450 }
8451 EXPORT_SYMBOL(alloc_netdev_mqs);
8452
8453 /**
8454 * free_netdev - free network device
8455 * @dev: device
8456 *
8457 * This function does the last stage of destroying an allocated device
8458 * interface. The reference to the device object is released. If this
8459 * is the last reference then it will be freed.Must be called in process
8460 * context.
8461 */
8462 void free_netdev(struct net_device *dev)
8463 {
8464 struct napi_struct *p, *n;
8465 struct bpf_prog *prog;
8466
8467 might_sleep();
8468 netif_free_tx_queues(dev);
8469 #ifdef CONFIG_SYSFS
8470 kvfree(dev->_rx);
8471 #endif
8472
8473 kfree(rcu_dereference_protected(dev->ingress_queue, 1));
8474
8475 /* Flush device addresses */
8476 dev_addr_flush(dev);
8477
8478 list_for_each_entry_safe(p, n, &dev->napi_list, dev_list)
8479 netif_napi_del(p);
8480
8481 free_percpu(dev->pcpu_refcnt);
8482 dev->pcpu_refcnt = NULL;
8483
8484 prog = rcu_dereference_protected(dev->xdp_prog, 1);
8485 if (prog) {
8486 bpf_prog_put(prog);
8487 static_key_slow_dec(&generic_xdp_needed);
8488 }
8489
8490 /* Compatibility with error handling in drivers */
8491 if (dev->reg_state == NETREG_UNINITIALIZED) {
8492 netdev_freemem(dev);
8493 return;
8494 }
8495
8496 BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
8497 dev->reg_state = NETREG_RELEASED;
8498
8499 /* will free via device release */
8500 put_device(&dev->dev);
8501 }
8502 EXPORT_SYMBOL(free_netdev);
8503
8504 /**
8505 * synchronize_net - Synchronize with packet receive processing
8506 *
8507 * Wait for packets currently being received to be done.
8508 * Does not block later packets from starting.
8509 */
8510 void synchronize_net(void)
8511 {
8512 might_sleep();
8513 if (rtnl_is_locked())
8514 synchronize_rcu_expedited();
8515 else
8516 synchronize_rcu();
8517 }
8518 EXPORT_SYMBOL(synchronize_net);
8519
8520 /**
8521 * unregister_netdevice_queue - remove device from the kernel
8522 * @dev: device
8523 * @head: list
8524 *
8525 * This function shuts down a device interface and removes it
8526 * from the kernel tables.
8527 * If head not NULL, device is queued to be unregistered later.
8528 *
8529 * Callers must hold the rtnl semaphore. You may want
8530 * unregister_netdev() instead of this.
8531 */
8532
8533 void unregister_netdevice_queue(struct net_device *dev, struct list_head *head)
8534 {
8535 ASSERT_RTNL();
8536
8537 if (head) {
8538 list_move_tail(&dev->unreg_list, head);
8539 } else {
8540 rollback_registered(dev);
8541 /* Finish processing unregister after unlock */
8542 net_set_todo(dev);
8543 }
8544 }
8545 EXPORT_SYMBOL(unregister_netdevice_queue);
8546
8547 /**
8548 * unregister_netdevice_many - unregister many devices
8549 * @head: list of devices
8550 *
8551 * Note: As most callers use a stack allocated list_head,
8552 * we force a list_del() to make sure stack wont be corrupted later.
8553 */
8554 void unregister_netdevice_many(struct list_head *head)
8555 {
8556 struct net_device *dev;
8557
8558 if (!list_empty(head)) {
8559 rollback_registered_many(head);
8560 list_for_each_entry(dev, head, unreg_list)
8561 net_set_todo(dev);
8562 list_del(head);
8563 }
8564 }
8565 EXPORT_SYMBOL(unregister_netdevice_many);
8566
8567 /**
8568 * unregister_netdev - remove device from the kernel
8569 * @dev: device
8570 *
8571 * This function shuts down a device interface and removes it
8572 * from the kernel tables.
8573 *
8574 * This is just a wrapper for unregister_netdevice that takes
8575 * the rtnl semaphore. In general you want to use this and not
8576 * unregister_netdevice.
8577 */
8578 void unregister_netdev(struct net_device *dev)
8579 {
8580 rtnl_lock();
8581 unregister_netdevice(dev);
8582 rtnl_unlock();
8583 }
8584 EXPORT_SYMBOL(unregister_netdev);
8585
8586 /**
8587 * dev_change_net_namespace - move device to different nethost namespace
8588 * @dev: device
8589 * @net: network namespace
8590 * @pat: If not NULL name pattern to try if the current device name
8591 * is already taken in the destination network namespace.
8592 *
8593 * This function shuts down a device interface and moves it
8594 * to a new network namespace. On success 0 is returned, on
8595 * a failure a netagive errno code is returned.
8596 *
8597 * Callers must hold the rtnl semaphore.
8598 */
8599
8600 int dev_change_net_namespace(struct net_device *dev, struct net *net, const char *pat)
8601 {
8602 int err, new_nsid, new_ifindex;
8603
8604 ASSERT_RTNL();
8605
8606 /* Don't allow namespace local devices to be moved. */
8607 err = -EINVAL;
8608 if (dev->features & NETIF_F_NETNS_LOCAL)
8609 goto out;
8610
8611 /* Ensure the device has been registrered */
8612 if (dev->reg_state != NETREG_REGISTERED)
8613 goto out;
8614
8615 /* Get out if there is nothing todo */
8616 err = 0;
8617 if (net_eq(dev_net(dev), net))
8618 goto out;
8619
8620 /* Pick the destination device name, and ensure
8621 * we can use it in the destination network namespace.
8622 */
8623 err = -EEXIST;
8624 if (__dev_get_by_name(net, dev->name)) {
8625 /* We get here if we can't use the current device name */
8626 if (!pat)
8627 goto out;
8628 err = dev_get_valid_name(net, dev, pat);
8629 if (err < 0)
8630 goto out;
8631 }
8632
8633 /*
8634 * And now a mini version of register_netdevice unregister_netdevice.
8635 */
8636
8637 /* If device is running close it first. */
8638 dev_close(dev);
8639
8640 /* And unlink it from device chain */
8641 unlist_netdevice(dev);
8642
8643 synchronize_net();
8644
8645 /* Shutdown queueing discipline. */
8646 dev_shutdown(dev);
8647
8648 /* Notify protocols, that we are about to destroy
8649 * this device. They should clean all the things.
8650 *
8651 * Note that dev->reg_state stays at NETREG_REGISTERED.
8652 * This is wanted because this way 8021q and macvlan know
8653 * the device is just moving and can keep their slaves up.
8654 */
8655 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
8656 rcu_barrier();
8657 call_netdevice_notifiers(NETDEV_UNREGISTER_FINAL, dev);
8658
8659 new_nsid = peernet2id_alloc(dev_net(dev), net, GFP_KERNEL);
8660 /* If there is an ifindex conflict assign a new one */
8661 if (__dev_get_by_index(net, dev->ifindex))
8662 new_ifindex = dev_new_index(net);
8663 else
8664 new_ifindex = dev->ifindex;
8665
8666 rtmsg_ifinfo_newnet(RTM_DELLINK, dev, ~0U, GFP_KERNEL, &new_nsid,
8667 new_ifindex);
8668
8669 /*
8670 * Flush the unicast and multicast chains
8671 */
8672 dev_uc_flush(dev);
8673 dev_mc_flush(dev);
8674
8675 /* Send a netdev-removed uevent to the old namespace */
8676 kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE);
8677 netdev_adjacent_del_links(dev);
8678
8679 /* Actually switch the network namespace */
8680 dev_net_set(dev, net);
8681 dev->ifindex = new_ifindex;
8682
8683 /* Send a netdev-add uevent to the new namespace */
8684 kobject_uevent(&dev->dev.kobj, KOBJ_ADD);
8685 netdev_adjacent_add_links(dev);
8686
8687 /* Fixup kobjects */
8688 err = device_rename(&dev->dev, dev->name);
8689 WARN_ON(err);
8690
8691 /* Add the device back in the hashes */
8692 list_netdevice(dev);
8693
8694 /* Notify protocols, that a new device appeared. */
8695 call_netdevice_notifiers(NETDEV_REGISTER, dev);
8696
8697 /*
8698 * Prevent userspace races by waiting until the network
8699 * device is fully setup before sending notifications.
8700 */
8701 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL);
8702
8703 synchronize_net();
8704 err = 0;
8705 out:
8706 return err;
8707 }
8708 EXPORT_SYMBOL_GPL(dev_change_net_namespace);
8709
8710 static int dev_cpu_dead(unsigned int oldcpu)
8711 {
8712 struct sk_buff **list_skb;
8713 struct sk_buff *skb;
8714 unsigned int cpu;
8715 struct softnet_data *sd, *oldsd, *remsd = NULL;
8716
8717 local_irq_disable();
8718 cpu = smp_processor_id();
8719 sd = &per_cpu(softnet_data, cpu);
8720 oldsd = &per_cpu(softnet_data, oldcpu);
8721
8722 /* Find end of our completion_queue. */
8723 list_skb = &sd->completion_queue;
8724 while (*list_skb)
8725 list_skb = &(*list_skb)->next;
8726 /* Append completion queue from offline CPU. */
8727 *list_skb = oldsd->completion_queue;
8728 oldsd->completion_queue = NULL;
8729
8730 /* Append output queue from offline CPU. */
8731 if (oldsd->output_queue) {
8732 *sd->output_queue_tailp = oldsd->output_queue;
8733 sd->output_queue_tailp = oldsd->output_queue_tailp;
8734 oldsd->output_queue = NULL;
8735 oldsd->output_queue_tailp = &oldsd->output_queue;
8736 }
8737 /* Append NAPI poll list from offline CPU, with one exception :
8738 * process_backlog() must be called by cpu owning percpu backlog.
8739 * We properly handle process_queue & input_pkt_queue later.
8740 */
8741 while (!list_empty(&oldsd->poll_list)) {
8742 struct napi_struct *napi = list_first_entry(&oldsd->poll_list,
8743 struct napi_struct,
8744 poll_list);
8745
8746 list_del_init(&napi->poll_list);
8747 if (napi->poll == process_backlog)
8748 napi->state = 0;
8749 else
8750 ____napi_schedule(sd, napi);
8751 }
8752
8753 raise_softirq_irqoff(NET_TX_SOFTIRQ);
8754 local_irq_enable();
8755
8756 #ifdef CONFIG_RPS
8757 remsd = oldsd->rps_ipi_list;
8758 oldsd->rps_ipi_list = NULL;
8759 #endif
8760 /* send out pending IPI's on offline CPU */
8761 net_rps_send_ipi(remsd);
8762
8763 /* Process offline CPU's input_pkt_queue */
8764 while ((skb = __skb_dequeue(&oldsd->process_queue))) {
8765 netif_rx_ni(skb);
8766 input_queue_head_incr(oldsd);
8767 }
8768 while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) {
8769 netif_rx_ni(skb);
8770 input_queue_head_incr(oldsd);
8771 }
8772
8773 return 0;
8774 }
8775
8776 /**
8777 * netdev_increment_features - increment feature set by one
8778 * @all: current feature set
8779 * @one: new feature set
8780 * @mask: mask feature set
8781 *
8782 * Computes a new feature set after adding a device with feature set
8783 * @one to the master device with current feature set @all. Will not
8784 * enable anything that is off in @mask. Returns the new feature set.
8785 */
8786 netdev_features_t netdev_increment_features(netdev_features_t all,
8787 netdev_features_t one, netdev_features_t mask)
8788 {
8789 if (mask & NETIF_F_HW_CSUM)
8790 mask |= NETIF_F_CSUM_MASK;
8791 mask |= NETIF_F_VLAN_CHALLENGED;
8792
8793 all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask;
8794 all &= one | ~NETIF_F_ALL_FOR_ALL;
8795
8796 /* If one device supports hw checksumming, set for all. */
8797 if (all & NETIF_F_HW_CSUM)
8798 all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM);
8799
8800 return all;
8801 }
8802 EXPORT_SYMBOL(netdev_increment_features);
8803
8804 static struct hlist_head * __net_init netdev_create_hash(void)
8805 {
8806 int i;
8807 struct hlist_head *hash;
8808
8809 hash = kmalloc(sizeof(*hash) * NETDEV_HASHENTRIES, GFP_KERNEL);
8810 if (hash != NULL)
8811 for (i = 0; i < NETDEV_HASHENTRIES; i++)
8812 INIT_HLIST_HEAD(&hash[i]);
8813
8814 return hash;
8815 }
8816
8817 /* Initialize per network namespace state */
8818 static int __net_init netdev_init(struct net *net)
8819 {
8820 if (net != &init_net)
8821 INIT_LIST_HEAD(&net->dev_base_head);
8822
8823 net->dev_name_head = netdev_create_hash();
8824 if (net->dev_name_head == NULL)
8825 goto err_name;
8826
8827 net->dev_index_head = netdev_create_hash();
8828 if (net->dev_index_head == NULL)
8829 goto err_idx;
8830
8831 return 0;
8832
8833 err_idx:
8834 kfree(net->dev_name_head);
8835 err_name:
8836 return -ENOMEM;
8837 }
8838
8839 /**
8840 * netdev_drivername - network driver for the device
8841 * @dev: network device
8842 *
8843 * Determine network driver for device.
8844 */
8845 const char *netdev_drivername(const struct net_device *dev)
8846 {
8847 const struct device_driver *driver;
8848 const struct device *parent;
8849 const char *empty = "";
8850
8851 parent = dev->dev.parent;
8852 if (!parent)
8853 return empty;
8854
8855 driver = parent->driver;
8856 if (driver && driver->name)
8857 return driver->name;
8858 return empty;
8859 }
8860
8861 static void __netdev_printk(const char *level, const struct net_device *dev,
8862 struct va_format *vaf)
8863 {
8864 if (dev && dev->dev.parent) {
8865 dev_printk_emit(level[1] - '0',
8866 dev->dev.parent,
8867 "%s %s %s%s: %pV",
8868 dev_driver_string(dev->dev.parent),
8869 dev_name(dev->dev.parent),
8870 netdev_name(dev), netdev_reg_state(dev),
8871 vaf);
8872 } else if (dev) {
8873 printk("%s%s%s: %pV",
8874 level, netdev_name(dev), netdev_reg_state(dev), vaf);
8875 } else {
8876 printk("%s(NULL net_device): %pV", level, vaf);
8877 }
8878 }
8879
8880 void netdev_printk(const char *level, const struct net_device *dev,
8881 const char *format, ...)
8882 {
8883 struct va_format vaf;
8884 va_list args;
8885
8886 va_start(args, format);
8887
8888 vaf.fmt = format;
8889 vaf.va = &args;
8890
8891 __netdev_printk(level, dev, &vaf);
8892
8893 va_end(args);
8894 }
8895 EXPORT_SYMBOL(netdev_printk);
8896
8897 #define define_netdev_printk_level(func, level) \
8898 void func(const struct net_device *dev, const char *fmt, ...) \
8899 { \
8900 struct va_format vaf; \
8901 va_list args; \
8902 \
8903 va_start(args, fmt); \
8904 \
8905 vaf.fmt = fmt; \
8906 vaf.va = &args; \
8907 \
8908 __netdev_printk(level, dev, &vaf); \
8909 \
8910 va_end(args); \
8911 } \
8912 EXPORT_SYMBOL(func);
8913
8914 define_netdev_printk_level(netdev_emerg, KERN_EMERG);
8915 define_netdev_printk_level(netdev_alert, KERN_ALERT);
8916 define_netdev_printk_level(netdev_crit, KERN_CRIT);
8917 define_netdev_printk_level(netdev_err, KERN_ERR);
8918 define_netdev_printk_level(netdev_warn, KERN_WARNING);
8919 define_netdev_printk_level(netdev_notice, KERN_NOTICE);
8920 define_netdev_printk_level(netdev_info, KERN_INFO);
8921
8922 static void __net_exit netdev_exit(struct net *net)
8923 {
8924 kfree(net->dev_name_head);
8925 kfree(net->dev_index_head);
8926 if (net != &init_net)
8927 WARN_ON_ONCE(!list_empty(&net->dev_base_head));
8928 }
8929
8930 static struct pernet_operations __net_initdata netdev_net_ops = {
8931 .init = netdev_init,
8932 .exit = netdev_exit,
8933 };
8934
8935 static void __net_exit default_device_exit(struct net *net)
8936 {
8937 struct net_device *dev, *aux;
8938 /*
8939 * Push all migratable network devices back to the
8940 * initial network namespace
8941 */
8942 rtnl_lock();
8943 for_each_netdev_safe(net, dev, aux) {
8944 int err;
8945 char fb_name[IFNAMSIZ];
8946
8947 /* Ignore unmoveable devices (i.e. loopback) */
8948 if (dev->features & NETIF_F_NETNS_LOCAL)
8949 continue;
8950
8951 /* Leave virtual devices for the generic cleanup */
8952 if (dev->rtnl_link_ops)
8953 continue;
8954
8955 /* Push remaining network devices to init_net */
8956 snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex);
8957 if (__dev_get_by_name(&init_net, fb_name))
8958 snprintf(fb_name, IFNAMSIZ, "dev%%d");
8959 err = dev_change_net_namespace(dev, &init_net, fb_name);
8960 if (err) {
8961 pr_emerg("%s: failed to move %s to init_net: %d\n",
8962 __func__, dev->name, err);
8963 BUG();
8964 }
8965 }
8966 rtnl_unlock();
8967 }
8968
8969 static void __net_exit rtnl_lock_unregistering(struct list_head *net_list)
8970 {
8971 /* Return with the rtnl_lock held when there are no network
8972 * devices unregistering in any network namespace in net_list.
8973 */
8974 struct net *net;
8975 bool unregistering;
8976 DEFINE_WAIT_FUNC(wait, woken_wake_function);
8977
8978 add_wait_queue(&netdev_unregistering_wq, &wait);
8979 for (;;) {
8980 unregistering = false;
8981 rtnl_lock();
8982 list_for_each_entry(net, net_list, exit_list) {
8983 if (net->dev_unreg_count > 0) {
8984 unregistering = true;
8985 break;
8986 }
8987 }
8988 if (!unregistering)
8989 break;
8990 __rtnl_unlock();
8991
8992 wait_woken(&wait, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
8993 }
8994 remove_wait_queue(&netdev_unregistering_wq, &wait);
8995 }
8996
8997 static void __net_exit default_device_exit_batch(struct list_head *net_list)
8998 {
8999 /* At exit all network devices most be removed from a network
9000 * namespace. Do this in the reverse order of registration.
9001 * Do this across as many network namespaces as possible to
9002 * improve batching efficiency.
9003 */
9004 struct net_device *dev;
9005 struct net *net;
9006 LIST_HEAD(dev_kill_list);
9007
9008 /* To prevent network device cleanup code from dereferencing
9009 * loopback devices or network devices that have been freed
9010 * wait here for all pending unregistrations to complete,
9011 * before unregistring the loopback device and allowing the
9012 * network namespace be freed.
9013 *
9014 * The netdev todo list containing all network devices
9015 * unregistrations that happen in default_device_exit_batch
9016 * will run in the rtnl_unlock() at the end of
9017 * default_device_exit_batch.
9018 */
9019 rtnl_lock_unregistering(net_list);
9020 list_for_each_entry(net, net_list, exit_list) {
9021 for_each_netdev_reverse(net, dev) {
9022 if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink)
9023 dev->rtnl_link_ops->dellink(dev, &dev_kill_list);
9024 else
9025 unregister_netdevice_queue(dev, &dev_kill_list);
9026 }
9027 }
9028 unregister_netdevice_many(&dev_kill_list);
9029 rtnl_unlock();
9030 }
9031
9032 static struct pernet_operations __net_initdata default_device_ops = {
9033 .exit = default_device_exit,
9034 .exit_batch = default_device_exit_batch,
9035 };
9036
9037 /*
9038 * Initialize the DEV module. At boot time this walks the device list and
9039 * unhooks any devices that fail to initialise (normally hardware not
9040 * present) and leaves us with a valid list of present and active devices.
9041 *
9042 */
9043
9044 /*
9045 * This is called single threaded during boot, so no need
9046 * to take the rtnl semaphore.
9047 */
9048 static int __init net_dev_init(void)
9049 {
9050 int i, rc = -ENOMEM;
9051
9052 BUG_ON(!dev_boot_phase);
9053
9054 if (dev_proc_init())
9055 goto out;
9056
9057 if (netdev_kobject_init())
9058 goto out;
9059
9060 INIT_LIST_HEAD(&ptype_all);
9061 for (i = 0; i < PTYPE_HASH_SIZE; i++)
9062 INIT_LIST_HEAD(&ptype_base[i]);
9063
9064 INIT_LIST_HEAD(&offload_base);
9065
9066 if (register_pernet_subsys(&netdev_net_ops))
9067 goto out;
9068
9069 /*
9070 * Initialise the packet receive queues.
9071 */
9072
9073 for_each_possible_cpu(i) {
9074 struct work_struct *flush = per_cpu_ptr(&flush_works, i);
9075 struct softnet_data *sd = &per_cpu(softnet_data, i);
9076
9077 INIT_WORK(flush, flush_backlog);
9078
9079 skb_queue_head_init(&sd->input_pkt_queue);
9080 skb_queue_head_init(&sd->process_queue);
9081 INIT_LIST_HEAD(&sd->poll_list);
9082 sd->output_queue_tailp = &sd->output_queue;
9083 #ifdef CONFIG_RPS
9084 sd->csd.func = rps_trigger_softirq;
9085 sd->csd.info = sd;
9086 sd->cpu = i;
9087 #endif
9088
9089 sd->backlog.poll = process_backlog;
9090 sd->backlog.weight = weight_p;
9091 }
9092
9093 dev_boot_phase = 0;
9094
9095 /* The loopback device is special if any other network devices
9096 * is present in a network namespace the loopback device must
9097 * be present. Since we now dynamically allocate and free the
9098 * loopback device ensure this invariant is maintained by
9099 * keeping the loopback device as the first device on the
9100 * list of network devices. Ensuring the loopback devices
9101 * is the first device that appears and the last network device
9102 * that disappears.
9103 */
9104 if (register_pernet_device(&loopback_net_ops))
9105 goto out;
9106
9107 if (register_pernet_device(&default_device_ops))
9108 goto out;
9109
9110 open_softirq(NET_TX_SOFTIRQ, net_tx_action);
9111 open_softirq(NET_RX_SOFTIRQ, net_rx_action);
9112
9113 rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead",
9114 NULL, dev_cpu_dead);
9115 WARN_ON(rc < 0);
9116 rc = 0;
9117 out:
9118 return rc;
9119 }
9120
9121 subsys_initcall(net_dev_init);