]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - net/core/dev.c
net: add a synchronize_net() in netdev_rx_handler_unregister()
[karo-tx-linux.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 <asm/uaccess.h>
76 #include <asm/system.h>
77 #include <linux/bitops.h>
78 #include <linux/capability.h>
79 #include <linux/cpu.h>
80 #include <linux/types.h>
81 #include <linux/kernel.h>
82 #include <linux/hash.h>
83 #include <linux/slab.h>
84 #include <linux/sched.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 <net/net_namespace.h>
99 #include <net/sock.h>
100 #include <linux/rtnetlink.h>
101 #include <linux/proc_fs.h>
102 #include <linux/seq_file.h>
103 #include <linux/stat.h>
104 #include <net/dst.h>
105 #include <net/pkt_sched.h>
106 #include <net/checksum.h>
107 #include <net/xfrm.h>
108 #include <linux/highmem.h>
109 #include <linux/init.h>
110 #include <linux/kmod.h>
111 #include <linux/module.h>
112 #include <linux/netpoll.h>
113 #include <linux/rcupdate.h>
114 #include <linux/delay.h>
115 #include <net/wext.h>
116 #include <net/iw_handler.h>
117 #include <asm/current.h>
118 #include <linux/audit.h>
119 #include <linux/dmaengine.h>
120 #include <linux/err.h>
121 #include <linux/ctype.h>
122 #include <linux/if_arp.h>
123 #include <linux/if_vlan.h>
124 #include <linux/ip.h>
125 #include <net/ip.h>
126 #include <linux/ipv6.h>
127 #include <linux/in.h>
128 #include <linux/jhash.h>
129 #include <linux/random.h>
130 #include <trace/events/napi.h>
131 #include <trace/events/net.h>
132 #include <trace/events/skb.h>
133 #include <linux/pci.h>
134 #include <linux/inetdevice.h>
135 #include <linux/cpu_rmap.h>
136
137 #include "net-sysfs.h"
138
139 /* Instead of increasing this, you should create a hash table. */
140 #define MAX_GRO_SKBS 8
141
142 /* This should be increased if a protocol with a bigger head is added. */
143 #define GRO_MAX_HEAD (MAX_HEADER + 128)
144
145 /*
146  *      The list of packet types we will receive (as opposed to discard)
147  *      and the routines to invoke.
148  *
149  *      Why 16. Because with 16 the only overlap we get on a hash of the
150  *      low nibble of the protocol value is RARP/SNAP/X.25.
151  *
152  *      NOTE:  That is no longer true with the addition of VLAN tags.  Not
153  *             sure which should go first, but I bet it won't make much
154  *             difference if we are running VLANs.  The good news is that
155  *             this protocol won't be in the list unless compiled in, so
156  *             the average user (w/out VLANs) will not be adversely affected.
157  *             --BLG
158  *
159  *              0800    IP
160  *              8100    802.1Q VLAN
161  *              0001    802.3
162  *              0002    AX.25
163  *              0004    802.2
164  *              8035    RARP
165  *              0005    SNAP
166  *              0805    X.25
167  *              0806    ARP
168  *              8137    IPX
169  *              0009    Localtalk
170  *              86DD    IPv6
171  */
172
173 #define PTYPE_HASH_SIZE (16)
174 #define PTYPE_HASH_MASK (PTYPE_HASH_SIZE - 1)
175
176 static DEFINE_SPINLOCK(ptype_lock);
177 static struct list_head ptype_base[PTYPE_HASH_SIZE] __read_mostly;
178 static struct list_head ptype_all __read_mostly;        /* Taps */
179
180 /*
181  * The @dev_base_head list is protected by @dev_base_lock and the rtnl
182  * semaphore.
183  *
184  * Pure readers hold dev_base_lock for reading, or rcu_read_lock()
185  *
186  * Writers must hold the rtnl semaphore while they loop through the
187  * dev_base_head list, and hold dev_base_lock for writing when they do the
188  * actual updates.  This allows pure readers to access the list even
189  * while a writer is preparing to update it.
190  *
191  * To put it another way, dev_base_lock is held for writing only to
192  * protect against pure readers; the rtnl semaphore provides the
193  * protection against other writers.
194  *
195  * See, for example usages, register_netdevice() and
196  * unregister_netdevice(), which must be called with the rtnl
197  * semaphore held.
198  */
199 DEFINE_RWLOCK(dev_base_lock);
200 EXPORT_SYMBOL(dev_base_lock);
201
202 static inline struct hlist_head *dev_name_hash(struct net *net, const char *name)
203 {
204         unsigned hash = full_name_hash(name, strnlen(name, IFNAMSIZ));
205         return &net->dev_name_head[hash_32(hash, NETDEV_HASHBITS)];
206 }
207
208 static inline struct hlist_head *dev_index_hash(struct net *net, int ifindex)
209 {
210         return &net->dev_index_head[ifindex & (NETDEV_HASHENTRIES - 1)];
211 }
212
213 static inline void rps_lock(struct softnet_data *sd)
214 {
215 #ifdef CONFIG_RPS
216         spin_lock(&sd->input_pkt_queue.lock);
217 #endif
218 }
219
220 static inline void rps_unlock(struct softnet_data *sd)
221 {
222 #ifdef CONFIG_RPS
223         spin_unlock(&sd->input_pkt_queue.lock);
224 #endif
225 }
226
227 /* Device list insertion */
228 static int list_netdevice(struct net_device *dev)
229 {
230         struct net *net = dev_net(dev);
231
232         ASSERT_RTNL();
233
234         write_lock_bh(&dev_base_lock);
235         list_add_tail_rcu(&dev->dev_list, &net->dev_base_head);
236         hlist_add_head_rcu(&dev->name_hlist, dev_name_hash(net, dev->name));
237         hlist_add_head_rcu(&dev->index_hlist,
238                            dev_index_hash(net, dev->ifindex));
239         write_unlock_bh(&dev_base_lock);
240         return 0;
241 }
242
243 /* Device list removal
244  * caller must respect a RCU grace period before freeing/reusing dev
245  */
246 static void unlist_netdevice(struct net_device *dev)
247 {
248         ASSERT_RTNL();
249
250         /* Unlink dev from the device chain */
251         write_lock_bh(&dev_base_lock);
252         list_del_rcu(&dev->dev_list);
253         hlist_del_rcu(&dev->name_hlist);
254         hlist_del_rcu(&dev->index_hlist);
255         write_unlock_bh(&dev_base_lock);
256 }
257
258 /*
259  *      Our notifier list
260  */
261
262 static RAW_NOTIFIER_HEAD(netdev_chain);
263
264 /*
265  *      Device drivers call our routines to queue packets here. We empty the
266  *      queue in the local softnet handler.
267  */
268
269 DEFINE_PER_CPU_ALIGNED(struct softnet_data, softnet_data);
270 EXPORT_PER_CPU_SYMBOL(softnet_data);
271
272 #ifdef CONFIG_LOCKDEP
273 /*
274  * register_netdevice() inits txq->_xmit_lock and sets lockdep class
275  * according to dev->type
276  */
277 static const unsigned short netdev_lock_type[] =
278         {ARPHRD_NETROM, ARPHRD_ETHER, ARPHRD_EETHER, ARPHRD_AX25,
279          ARPHRD_PRONET, ARPHRD_CHAOS, ARPHRD_IEEE802, ARPHRD_ARCNET,
280          ARPHRD_APPLETLK, ARPHRD_DLCI, ARPHRD_ATM, ARPHRD_METRICOM,
281          ARPHRD_IEEE1394, ARPHRD_EUI64, ARPHRD_INFINIBAND, ARPHRD_SLIP,
282          ARPHRD_CSLIP, ARPHRD_SLIP6, ARPHRD_CSLIP6, ARPHRD_RSRVD,
283          ARPHRD_ADAPT, ARPHRD_ROSE, ARPHRD_X25, ARPHRD_HWX25,
284          ARPHRD_PPP, ARPHRD_CISCO, ARPHRD_LAPB, ARPHRD_DDCMP,
285          ARPHRD_RAWHDLC, ARPHRD_TUNNEL, ARPHRD_TUNNEL6, ARPHRD_FRAD,
286          ARPHRD_SKIP, ARPHRD_LOOPBACK, ARPHRD_LOCALTLK, ARPHRD_FDDI,
287          ARPHRD_BIF, ARPHRD_SIT, ARPHRD_IPDDP, ARPHRD_IPGRE,
288          ARPHRD_PIMREG, ARPHRD_HIPPI, ARPHRD_ASH, ARPHRD_ECONET,
289          ARPHRD_IRDA, ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL,
290          ARPHRD_FCFABRIC, ARPHRD_IEEE802_TR, ARPHRD_IEEE80211,
291          ARPHRD_IEEE80211_PRISM, ARPHRD_IEEE80211_RADIOTAP, ARPHRD_PHONET,
292          ARPHRD_PHONET_PIPE, ARPHRD_IEEE802154,
293          ARPHRD_VOID, ARPHRD_NONE};
294
295 static const char *const netdev_lock_name[] =
296         {"_xmit_NETROM", "_xmit_ETHER", "_xmit_EETHER", "_xmit_AX25",
297          "_xmit_PRONET", "_xmit_CHAOS", "_xmit_IEEE802", "_xmit_ARCNET",
298          "_xmit_APPLETLK", "_xmit_DLCI", "_xmit_ATM", "_xmit_METRICOM",
299          "_xmit_IEEE1394", "_xmit_EUI64", "_xmit_INFINIBAND", "_xmit_SLIP",
300          "_xmit_CSLIP", "_xmit_SLIP6", "_xmit_CSLIP6", "_xmit_RSRVD",
301          "_xmit_ADAPT", "_xmit_ROSE", "_xmit_X25", "_xmit_HWX25",
302          "_xmit_PPP", "_xmit_CISCO", "_xmit_LAPB", "_xmit_DDCMP",
303          "_xmit_RAWHDLC", "_xmit_TUNNEL", "_xmit_TUNNEL6", "_xmit_FRAD",
304          "_xmit_SKIP", "_xmit_LOOPBACK", "_xmit_LOCALTLK", "_xmit_FDDI",
305          "_xmit_BIF", "_xmit_SIT", "_xmit_IPDDP", "_xmit_IPGRE",
306          "_xmit_PIMREG", "_xmit_HIPPI", "_xmit_ASH", "_xmit_ECONET",
307          "_xmit_IRDA", "_xmit_FCPP", "_xmit_FCAL", "_xmit_FCPL",
308          "_xmit_FCFABRIC", "_xmit_IEEE802_TR", "_xmit_IEEE80211",
309          "_xmit_IEEE80211_PRISM", "_xmit_IEEE80211_RADIOTAP", "_xmit_PHONET",
310          "_xmit_PHONET_PIPE", "_xmit_IEEE802154",
311          "_xmit_VOID", "_xmit_NONE"};
312
313 static struct lock_class_key netdev_xmit_lock_key[ARRAY_SIZE(netdev_lock_type)];
314 static struct lock_class_key netdev_addr_lock_key[ARRAY_SIZE(netdev_lock_type)];
315
316 static inline unsigned short netdev_lock_pos(unsigned short dev_type)
317 {
318         int i;
319
320         for (i = 0; i < ARRAY_SIZE(netdev_lock_type); i++)
321                 if (netdev_lock_type[i] == dev_type)
322                         return i;
323         /* the last key is used by default */
324         return ARRAY_SIZE(netdev_lock_type) - 1;
325 }
326
327 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
328                                                  unsigned short dev_type)
329 {
330         int i;
331
332         i = netdev_lock_pos(dev_type);
333         lockdep_set_class_and_name(lock, &netdev_xmit_lock_key[i],
334                                    netdev_lock_name[i]);
335 }
336
337 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
338 {
339         int i;
340
341         i = netdev_lock_pos(dev->type);
342         lockdep_set_class_and_name(&dev->addr_list_lock,
343                                    &netdev_addr_lock_key[i],
344                                    netdev_lock_name[i]);
345 }
346 #else
347 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
348                                                  unsigned short dev_type)
349 {
350 }
351 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
352 {
353 }
354 #endif
355
356 /*******************************************************************************
357
358                 Protocol management and registration routines
359
360 *******************************************************************************/
361
362 /*
363  *      Add a protocol ID to the list. Now that the input handler is
364  *      smarter we can dispense with all the messy stuff that used to be
365  *      here.
366  *
367  *      BEWARE!!! Protocol handlers, mangling input packets,
368  *      MUST BE last in hash buckets and checking protocol handlers
369  *      MUST start from promiscuous ptype_all chain in net_bh.
370  *      It is true now, do not change it.
371  *      Explanation follows: if protocol handler, mangling packet, will
372  *      be the first on list, it is not able to sense, that packet
373  *      is cloned and should be copied-on-write, so that it will
374  *      change it and subsequent readers will get broken packet.
375  *                                                      --ANK (980803)
376  */
377
378 static inline struct list_head *ptype_head(const struct packet_type *pt)
379 {
380         if (pt->type == htons(ETH_P_ALL))
381                 return &ptype_all;
382         else
383                 return &ptype_base[ntohs(pt->type) & PTYPE_HASH_MASK];
384 }
385
386 /**
387  *      dev_add_pack - add packet handler
388  *      @pt: packet type declaration
389  *
390  *      Add a protocol handler to the networking stack. The passed &packet_type
391  *      is linked into kernel lists and may not be freed until it has been
392  *      removed from the kernel lists.
393  *
394  *      This call does not sleep therefore it can not
395  *      guarantee all CPU's that are in middle of receiving packets
396  *      will see the new packet type (until the next received packet).
397  */
398
399 void dev_add_pack(struct packet_type *pt)
400 {
401         struct list_head *head = ptype_head(pt);
402
403         spin_lock(&ptype_lock);
404         list_add_rcu(&pt->list, head);
405         spin_unlock(&ptype_lock);
406 }
407 EXPORT_SYMBOL(dev_add_pack);
408
409 /**
410  *      __dev_remove_pack        - remove packet handler
411  *      @pt: packet type declaration
412  *
413  *      Remove a protocol handler that was previously added to the kernel
414  *      protocol handlers by dev_add_pack(). The passed &packet_type is removed
415  *      from the kernel lists and can be freed or reused once this function
416  *      returns.
417  *
418  *      The packet type might still be in use by receivers
419  *      and must not be freed until after all the CPU's have gone
420  *      through a quiescent state.
421  */
422 void __dev_remove_pack(struct packet_type *pt)
423 {
424         struct list_head *head = ptype_head(pt);
425         struct packet_type *pt1;
426
427         spin_lock(&ptype_lock);
428
429         list_for_each_entry(pt1, head, list) {
430                 if (pt == pt1) {
431                         list_del_rcu(&pt->list);
432                         goto out;
433                 }
434         }
435
436         printk(KERN_WARNING "dev_remove_pack: %p not found.\n", pt);
437 out:
438         spin_unlock(&ptype_lock);
439 }
440 EXPORT_SYMBOL(__dev_remove_pack);
441
442 /**
443  *      dev_remove_pack  - remove packet handler
444  *      @pt: packet type declaration
445  *
446  *      Remove a protocol handler that was previously added to the kernel
447  *      protocol handlers by dev_add_pack(). The passed &packet_type is removed
448  *      from the kernel lists and can be freed or reused once this function
449  *      returns.
450  *
451  *      This call sleeps to guarantee that no CPU is looking at the packet
452  *      type after return.
453  */
454 void dev_remove_pack(struct packet_type *pt)
455 {
456         __dev_remove_pack(pt);
457
458         synchronize_net();
459 }
460 EXPORT_SYMBOL(dev_remove_pack);
461
462 /******************************************************************************
463
464                       Device Boot-time Settings Routines
465
466 *******************************************************************************/
467
468 /* Boot time configuration table */
469 static struct netdev_boot_setup dev_boot_setup[NETDEV_BOOT_SETUP_MAX];
470
471 /**
472  *      netdev_boot_setup_add   - add new setup entry
473  *      @name: name of the device
474  *      @map: configured settings for the device
475  *
476  *      Adds new setup entry to the dev_boot_setup list.  The function
477  *      returns 0 on error and 1 on success.  This is a generic routine to
478  *      all netdevices.
479  */
480 static int netdev_boot_setup_add(char *name, struct ifmap *map)
481 {
482         struct netdev_boot_setup *s;
483         int i;
484
485         s = dev_boot_setup;
486         for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
487                 if (s[i].name[0] == '\0' || s[i].name[0] == ' ') {
488                         memset(s[i].name, 0, sizeof(s[i].name));
489                         strlcpy(s[i].name, name, IFNAMSIZ);
490                         memcpy(&s[i].map, map, sizeof(s[i].map));
491                         break;
492                 }
493         }
494
495         return i >= NETDEV_BOOT_SETUP_MAX ? 0 : 1;
496 }
497
498 /**
499  *      netdev_boot_setup_check - check boot time settings
500  *      @dev: the netdevice
501  *
502  *      Check boot time settings for the device.
503  *      The found settings are set for the device to be used
504  *      later in the device probing.
505  *      Returns 0 if no settings found, 1 if they are.
506  */
507 int netdev_boot_setup_check(struct net_device *dev)
508 {
509         struct netdev_boot_setup *s = dev_boot_setup;
510         int i;
511
512         for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
513                 if (s[i].name[0] != '\0' && s[i].name[0] != ' ' &&
514                     !strcmp(dev->name, s[i].name)) {
515                         dev->irq        = s[i].map.irq;
516                         dev->base_addr  = s[i].map.base_addr;
517                         dev->mem_start  = s[i].map.mem_start;
518                         dev->mem_end    = s[i].map.mem_end;
519                         return 1;
520                 }
521         }
522         return 0;
523 }
524 EXPORT_SYMBOL(netdev_boot_setup_check);
525
526
527 /**
528  *      netdev_boot_base        - get address from boot time settings
529  *      @prefix: prefix for network device
530  *      @unit: id for network device
531  *
532  *      Check boot time settings for the base address of device.
533  *      The found settings are set for the device to be used
534  *      later in the device probing.
535  *      Returns 0 if no settings found.
536  */
537 unsigned long netdev_boot_base(const char *prefix, int unit)
538 {
539         const struct netdev_boot_setup *s = dev_boot_setup;
540         char name[IFNAMSIZ];
541         int i;
542
543         sprintf(name, "%s%d", prefix, unit);
544
545         /*
546          * If device already registered then return base of 1
547          * to indicate not to probe for this interface
548          */
549         if (__dev_get_by_name(&init_net, name))
550                 return 1;
551
552         for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++)
553                 if (!strcmp(name, s[i].name))
554                         return s[i].map.base_addr;
555         return 0;
556 }
557
558 /*
559  * Saves at boot time configured settings for any netdevice.
560  */
561 int __init netdev_boot_setup(char *str)
562 {
563         int ints[5];
564         struct ifmap map;
565
566         str = get_options(str, ARRAY_SIZE(ints), ints);
567         if (!str || !*str)
568                 return 0;
569
570         /* Save settings */
571         memset(&map, 0, sizeof(map));
572         if (ints[0] > 0)
573                 map.irq = ints[1];
574         if (ints[0] > 1)
575                 map.base_addr = ints[2];
576         if (ints[0] > 2)
577                 map.mem_start = ints[3];
578         if (ints[0] > 3)
579                 map.mem_end = ints[4];
580
581         /* Add new entry to the list */
582         return netdev_boot_setup_add(str, &map);
583 }
584
585 __setup("netdev=", netdev_boot_setup);
586
587 /*******************************************************************************
588
589                             Device Interface Subroutines
590
591 *******************************************************************************/
592
593 /**
594  *      __dev_get_by_name       - find a device by its name
595  *      @net: the applicable net namespace
596  *      @name: name to find
597  *
598  *      Find an interface by name. Must be called under RTNL semaphore
599  *      or @dev_base_lock. If the name is found a pointer to the device
600  *      is returned. If the name is not found then %NULL is returned. The
601  *      reference counters are not incremented so the caller must be
602  *      careful with locks.
603  */
604
605 struct net_device *__dev_get_by_name(struct net *net, const char *name)
606 {
607         struct hlist_node *p;
608         struct net_device *dev;
609         struct hlist_head *head = dev_name_hash(net, name);
610
611         hlist_for_each_entry(dev, p, head, name_hlist)
612                 if (!strncmp(dev->name, name, IFNAMSIZ))
613                         return dev;
614
615         return NULL;
616 }
617 EXPORT_SYMBOL(__dev_get_by_name);
618
619 /**
620  *      dev_get_by_name_rcu     - find a device by its name
621  *      @net: the applicable net namespace
622  *      @name: name to find
623  *
624  *      Find an interface by name.
625  *      If the name is found a pointer to the device is returned.
626  *      If the name is not found then %NULL is returned.
627  *      The reference counters are not incremented so the caller must be
628  *      careful with locks. The caller must hold RCU lock.
629  */
630
631 struct net_device *dev_get_by_name_rcu(struct net *net, const char *name)
632 {
633         struct hlist_node *p;
634         struct net_device *dev;
635         struct hlist_head *head = dev_name_hash(net, name);
636
637         hlist_for_each_entry_rcu(dev, p, head, name_hlist)
638                 if (!strncmp(dev->name, name, IFNAMSIZ))
639                         return dev;
640
641         return NULL;
642 }
643 EXPORT_SYMBOL(dev_get_by_name_rcu);
644
645 /**
646  *      dev_get_by_name         - find a device by its name
647  *      @net: the applicable net namespace
648  *      @name: name to find
649  *
650  *      Find an interface by name. This can be called from any
651  *      context and does its own locking. The returned handle has
652  *      the usage count incremented and the caller must use dev_put() to
653  *      release it when it is no longer needed. %NULL is returned if no
654  *      matching device is found.
655  */
656
657 struct net_device *dev_get_by_name(struct net *net, const char *name)
658 {
659         struct net_device *dev;
660
661         rcu_read_lock();
662         dev = dev_get_by_name_rcu(net, name);
663         if (dev)
664                 dev_hold(dev);
665         rcu_read_unlock();
666         return dev;
667 }
668 EXPORT_SYMBOL(dev_get_by_name);
669
670 /**
671  *      __dev_get_by_index - find a device by its ifindex
672  *      @net: the applicable net namespace
673  *      @ifindex: index of device
674  *
675  *      Search for an interface by index. Returns %NULL if the device
676  *      is not found or a pointer to the device. The device has not
677  *      had its reference counter increased so the caller must be careful
678  *      about locking. The caller must hold either the RTNL semaphore
679  *      or @dev_base_lock.
680  */
681
682 struct net_device *__dev_get_by_index(struct net *net, int ifindex)
683 {
684         struct hlist_node *p;
685         struct net_device *dev;
686         struct hlist_head *head = dev_index_hash(net, ifindex);
687
688         hlist_for_each_entry(dev, p, head, index_hlist)
689                 if (dev->ifindex == ifindex)
690                         return dev;
691
692         return NULL;
693 }
694 EXPORT_SYMBOL(__dev_get_by_index);
695
696 /**
697  *      dev_get_by_index_rcu - find a device by its ifindex
698  *      @net: the applicable net namespace
699  *      @ifindex: index of device
700  *
701  *      Search for an interface by index. Returns %NULL if the device
702  *      is not found or a pointer to the device. The device has not
703  *      had its reference counter increased so the caller must be careful
704  *      about locking. The caller must hold RCU lock.
705  */
706
707 struct net_device *dev_get_by_index_rcu(struct net *net, int ifindex)
708 {
709         struct hlist_node *p;
710         struct net_device *dev;
711         struct hlist_head *head = dev_index_hash(net, ifindex);
712
713         hlist_for_each_entry_rcu(dev, p, head, index_hlist)
714                 if (dev->ifindex == ifindex)
715                         return dev;
716
717         return NULL;
718 }
719 EXPORT_SYMBOL(dev_get_by_index_rcu);
720
721
722 /**
723  *      dev_get_by_index - find a device by its ifindex
724  *      @net: the applicable net namespace
725  *      @ifindex: index of device
726  *
727  *      Search for an interface by index. Returns NULL if the device
728  *      is not found or a pointer to the device. The device returned has
729  *      had a reference added and the pointer is safe until the user calls
730  *      dev_put to indicate they have finished with it.
731  */
732
733 struct net_device *dev_get_by_index(struct net *net, int ifindex)
734 {
735         struct net_device *dev;
736
737         rcu_read_lock();
738         dev = dev_get_by_index_rcu(net, ifindex);
739         if (dev)
740                 dev_hold(dev);
741         rcu_read_unlock();
742         return dev;
743 }
744 EXPORT_SYMBOL(dev_get_by_index);
745
746 /**
747  *      dev_getbyhwaddr_rcu - find a device by its hardware address
748  *      @net: the applicable net namespace
749  *      @type: media type of device
750  *      @ha: hardware address
751  *
752  *      Search for an interface by MAC address. Returns NULL if the device
753  *      is not found or a pointer to the device.
754  *      The caller must hold RCU or RTNL.
755  *      The returned device has not had its ref count increased
756  *      and the caller must therefore be careful about locking
757  *
758  */
759
760 struct net_device *dev_getbyhwaddr_rcu(struct net *net, unsigned short type,
761                                        const char *ha)
762 {
763         struct net_device *dev;
764
765         for_each_netdev_rcu(net, dev)
766                 if (dev->type == type &&
767                     !memcmp(dev->dev_addr, ha, dev->addr_len))
768                         return dev;
769
770         return NULL;
771 }
772 EXPORT_SYMBOL(dev_getbyhwaddr_rcu);
773
774 struct net_device *__dev_getfirstbyhwtype(struct net *net, unsigned short type)
775 {
776         struct net_device *dev;
777
778         ASSERT_RTNL();
779         for_each_netdev(net, dev)
780                 if (dev->type == type)
781                         return dev;
782
783         return NULL;
784 }
785 EXPORT_SYMBOL(__dev_getfirstbyhwtype);
786
787 struct net_device *dev_getfirstbyhwtype(struct net *net, unsigned short type)
788 {
789         struct net_device *dev, *ret = NULL;
790
791         rcu_read_lock();
792         for_each_netdev_rcu(net, dev)
793                 if (dev->type == type) {
794                         dev_hold(dev);
795                         ret = dev;
796                         break;
797                 }
798         rcu_read_unlock();
799         return ret;
800 }
801 EXPORT_SYMBOL(dev_getfirstbyhwtype);
802
803 /**
804  *      dev_get_by_flags_rcu - find any device with given flags
805  *      @net: the applicable net namespace
806  *      @if_flags: IFF_* values
807  *      @mask: bitmask of bits in if_flags to check
808  *
809  *      Search for any interface with the given flags. Returns NULL if a device
810  *      is not found or a pointer to the device. Must be called inside
811  *      rcu_read_lock(), and result refcount is unchanged.
812  */
813
814 struct net_device *dev_get_by_flags_rcu(struct net *net, unsigned short if_flags,
815                                     unsigned short mask)
816 {
817         struct net_device *dev, *ret;
818
819         ret = NULL;
820         for_each_netdev_rcu(net, dev) {
821                 if (((dev->flags ^ if_flags) & mask) == 0) {
822                         ret = dev;
823                         break;
824                 }
825         }
826         return ret;
827 }
828 EXPORT_SYMBOL(dev_get_by_flags_rcu);
829
830 /**
831  *      dev_valid_name - check if name is okay for network device
832  *      @name: name string
833  *
834  *      Network device names need to be valid file names to
835  *      to allow sysfs to work.  We also disallow any kind of
836  *      whitespace.
837  */
838 int dev_valid_name(const char *name)
839 {
840         if (*name == '\0')
841                 return 0;
842         if (strlen(name) >= IFNAMSIZ)
843                 return 0;
844         if (!strcmp(name, ".") || !strcmp(name, ".."))
845                 return 0;
846
847         while (*name) {
848                 if (*name == '/' || isspace(*name))
849                         return 0;
850                 name++;
851         }
852         return 1;
853 }
854 EXPORT_SYMBOL(dev_valid_name);
855
856 /**
857  *      __dev_alloc_name - allocate a name for a device
858  *      @net: network namespace to allocate the device name in
859  *      @name: name format string
860  *      @buf:  scratch buffer and result name string
861  *
862  *      Passed a format string - eg "lt%d" it will try and find a suitable
863  *      id. It scans list of devices to build up a free map, then chooses
864  *      the first empty slot. The caller must hold the dev_base or rtnl lock
865  *      while allocating the name and adding the device in order to avoid
866  *      duplicates.
867  *      Limited to bits_per_byte * page size devices (ie 32K on most platforms).
868  *      Returns the number of the unit assigned or a negative errno code.
869  */
870
871 static int __dev_alloc_name(struct net *net, const char *name, char *buf)
872 {
873         int i = 0;
874         const char *p;
875         const int max_netdevices = 8*PAGE_SIZE;
876         unsigned long *inuse;
877         struct net_device *d;
878
879         p = strnchr(name, IFNAMSIZ-1, '%');
880         if (p) {
881                 /*
882                  * Verify the string as this thing may have come from
883                  * the user.  There must be either one "%d" and no other "%"
884                  * characters.
885                  */
886                 if (p[1] != 'd' || strchr(p + 2, '%'))
887                         return -EINVAL;
888
889                 /* Use one page as a bit array of possible slots */
890                 inuse = (unsigned long *) get_zeroed_page(GFP_ATOMIC);
891                 if (!inuse)
892                         return -ENOMEM;
893
894                 for_each_netdev(net, d) {
895                         if (!sscanf(d->name, name, &i))
896                                 continue;
897                         if (i < 0 || i >= max_netdevices)
898                                 continue;
899
900                         /*  avoid cases where sscanf is not exact inverse of printf */
901                         snprintf(buf, IFNAMSIZ, name, i);
902                         if (!strncmp(buf, d->name, IFNAMSIZ))
903                                 set_bit(i, inuse);
904                 }
905
906                 i = find_first_zero_bit(inuse, max_netdevices);
907                 free_page((unsigned long) inuse);
908         }
909
910         if (buf != name)
911                 snprintf(buf, IFNAMSIZ, name, i);
912         if (!__dev_get_by_name(net, buf))
913                 return i;
914
915         /* It is possible to run out of possible slots
916          * when the name is long and there isn't enough space left
917          * for the digits, or if all bits are used.
918          */
919         return -ENFILE;
920 }
921
922 /**
923  *      dev_alloc_name - allocate a name for a device
924  *      @dev: device
925  *      @name: name format string
926  *
927  *      Passed a format string - eg "lt%d" it will try and find a suitable
928  *      id. It scans list of devices to build up a free map, then chooses
929  *      the first empty slot. The caller must hold the dev_base or rtnl lock
930  *      while allocating the name and adding the device in order to avoid
931  *      duplicates.
932  *      Limited to bits_per_byte * page size devices (ie 32K on most platforms).
933  *      Returns the number of the unit assigned or a negative errno code.
934  */
935
936 int dev_alloc_name(struct net_device *dev, const char *name)
937 {
938         char buf[IFNAMSIZ];
939         struct net *net;
940         int ret;
941
942         BUG_ON(!dev_net(dev));
943         net = dev_net(dev);
944         ret = __dev_alloc_name(net, name, buf);
945         if (ret >= 0)
946                 strlcpy(dev->name, buf, IFNAMSIZ);
947         return ret;
948 }
949 EXPORT_SYMBOL(dev_alloc_name);
950
951 static int dev_get_valid_name(struct net_device *dev, const char *name)
952 {
953         struct net *net;
954
955         BUG_ON(!dev_net(dev));
956         net = dev_net(dev);
957
958         if (!dev_valid_name(name))
959                 return -EINVAL;
960
961         if (strchr(name, '%'))
962                 return dev_alloc_name(dev, name);
963         else if (__dev_get_by_name(net, name))
964                 return -EEXIST;
965         else if (dev->name != name)
966                 strlcpy(dev->name, name, IFNAMSIZ);
967
968         return 0;
969 }
970
971 /**
972  *      dev_change_name - change name of a device
973  *      @dev: device
974  *      @newname: name (or format string) must be at least IFNAMSIZ
975  *
976  *      Change name of a device, can pass format strings "eth%d".
977  *      for wildcarding.
978  */
979 int dev_change_name(struct net_device *dev, const char *newname)
980 {
981         char oldname[IFNAMSIZ];
982         int err = 0;
983         int ret;
984         struct net *net;
985
986         ASSERT_RTNL();
987         BUG_ON(!dev_net(dev));
988
989         net = dev_net(dev);
990         if (dev->flags & IFF_UP)
991                 return -EBUSY;
992
993         if (strncmp(newname, dev->name, IFNAMSIZ) == 0)
994                 return 0;
995
996         memcpy(oldname, dev->name, IFNAMSIZ);
997
998         err = dev_get_valid_name(dev, newname);
999         if (err < 0)
1000                 return err;
1001
1002 rollback:
1003         ret = device_rename(&dev->dev, dev->name);
1004         if (ret) {
1005                 memcpy(dev->name, oldname, IFNAMSIZ);
1006                 return ret;
1007         }
1008
1009         write_lock_bh(&dev_base_lock);
1010         hlist_del_rcu(&dev->name_hlist);
1011         write_unlock_bh(&dev_base_lock);
1012
1013         synchronize_rcu();
1014
1015         write_lock_bh(&dev_base_lock);
1016         hlist_add_head_rcu(&dev->name_hlist, dev_name_hash(net, dev->name));
1017         write_unlock_bh(&dev_base_lock);
1018
1019         ret = call_netdevice_notifiers(NETDEV_CHANGENAME, dev);
1020         ret = notifier_to_errno(ret);
1021
1022         if (ret) {
1023                 /* err >= 0 after dev_alloc_name() or stores the first errno */
1024                 if (err >= 0) {
1025                         err = ret;
1026                         memcpy(dev->name, oldname, IFNAMSIZ);
1027                         goto rollback;
1028                 } else {
1029                         printk(KERN_ERR
1030                                "%s: name change rollback failed: %d.\n",
1031                                dev->name, ret);
1032                 }
1033         }
1034
1035         return err;
1036 }
1037
1038 /**
1039  *      dev_set_alias - change ifalias of a device
1040  *      @dev: device
1041  *      @alias: name up to IFALIASZ
1042  *      @len: limit of bytes to copy from info
1043  *
1044  *      Set ifalias for a device,
1045  */
1046 int dev_set_alias(struct net_device *dev, const char *alias, size_t len)
1047 {
1048         char *new_ifalias;
1049
1050         ASSERT_RTNL();
1051
1052         if (len >= IFALIASZ)
1053                 return -EINVAL;
1054
1055         if (!len) {
1056                 if (dev->ifalias) {
1057                         kfree(dev->ifalias);
1058                         dev->ifalias = NULL;
1059                 }
1060                 return 0;
1061         }
1062
1063         new_ifalias = krealloc(dev->ifalias, len + 1, GFP_KERNEL);
1064         if (!new_ifalias)
1065                 return -ENOMEM;
1066         dev->ifalias = new_ifalias;
1067
1068         strlcpy(dev->ifalias, alias, len+1);
1069         return len;
1070 }
1071
1072
1073 /**
1074  *      netdev_features_change - device changes features
1075  *      @dev: device to cause notification
1076  *
1077  *      Called to indicate a device has changed features.
1078  */
1079 void netdev_features_change(struct net_device *dev)
1080 {
1081         call_netdevice_notifiers(NETDEV_FEAT_CHANGE, dev);
1082 }
1083 EXPORT_SYMBOL(netdev_features_change);
1084
1085 /**
1086  *      netdev_state_change - device changes state
1087  *      @dev: device to cause notification
1088  *
1089  *      Called to indicate a device has changed state. This function calls
1090  *      the notifier chains for netdev_chain and sends a NEWLINK message
1091  *      to the routing socket.
1092  */
1093 void netdev_state_change(struct net_device *dev)
1094 {
1095         if (dev->flags & IFF_UP) {
1096                 call_netdevice_notifiers(NETDEV_CHANGE, dev);
1097                 rtmsg_ifinfo(RTM_NEWLINK, dev, 0);
1098         }
1099 }
1100 EXPORT_SYMBOL(netdev_state_change);
1101
1102 int netdev_bonding_change(struct net_device *dev, unsigned long event)
1103 {
1104         return call_netdevice_notifiers(event, dev);
1105 }
1106 EXPORT_SYMBOL(netdev_bonding_change);
1107
1108 /**
1109  *      dev_load        - load a network module
1110  *      @net: the applicable net namespace
1111  *      @name: name of interface
1112  *
1113  *      If a network interface is not present and the process has suitable
1114  *      privileges this function loads the module. If module loading is not
1115  *      available in this kernel then it becomes a nop.
1116  */
1117
1118 void dev_load(struct net *net, const char *name)
1119 {
1120         struct net_device *dev;
1121         int no_module;
1122
1123         rcu_read_lock();
1124         dev = dev_get_by_name_rcu(net, name);
1125         rcu_read_unlock();
1126
1127         no_module = !dev;
1128         if (no_module && capable(CAP_NET_ADMIN))
1129                 no_module = request_module("netdev-%s", name);
1130         if (no_module && capable(CAP_SYS_MODULE)) {
1131                 if (!request_module("%s", name))
1132                         pr_err("Loading kernel module for a network device "
1133 "with CAP_SYS_MODULE (deprecated).  Use CAP_NET_ADMIN and alias netdev-%s "
1134 "instead\n", name);
1135         }
1136 }
1137 EXPORT_SYMBOL(dev_load);
1138
1139 static int __dev_open(struct net_device *dev)
1140 {
1141         const struct net_device_ops *ops = dev->netdev_ops;
1142         int ret;
1143
1144         ASSERT_RTNL();
1145
1146         if (!netif_device_present(dev))
1147                 return -ENODEV;
1148
1149         ret = call_netdevice_notifiers(NETDEV_PRE_UP, dev);
1150         ret = notifier_to_errno(ret);
1151         if (ret)
1152                 return ret;
1153
1154         set_bit(__LINK_STATE_START, &dev->state);
1155
1156         if (ops->ndo_validate_addr)
1157                 ret = ops->ndo_validate_addr(dev);
1158
1159         if (!ret && ops->ndo_open)
1160                 ret = ops->ndo_open(dev);
1161
1162         if (ret)
1163                 clear_bit(__LINK_STATE_START, &dev->state);
1164         else {
1165                 dev->flags |= IFF_UP;
1166                 net_dmaengine_get();
1167                 dev_set_rx_mode(dev);
1168                 dev_activate(dev);
1169                 add_device_randomness(dev->dev_addr, dev->addr_len);
1170         }
1171
1172         return ret;
1173 }
1174
1175 /**
1176  *      dev_open        - prepare an interface for use.
1177  *      @dev:   device to open
1178  *
1179  *      Takes a device from down to up state. The device's private open
1180  *      function is invoked and then the multicast lists are loaded. Finally
1181  *      the device is moved into the up state and a %NETDEV_UP message is
1182  *      sent to the netdev notifier chain.
1183  *
1184  *      Calling this function on an active interface is a nop. On a failure
1185  *      a negative errno code is returned.
1186  */
1187 int dev_open(struct net_device *dev)
1188 {
1189         int ret;
1190
1191         if (dev->flags & IFF_UP)
1192                 return 0;
1193
1194         ret = __dev_open(dev);
1195         if (ret < 0)
1196                 return ret;
1197
1198         rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING);
1199         call_netdevice_notifiers(NETDEV_UP, dev);
1200
1201         return ret;
1202 }
1203 EXPORT_SYMBOL(dev_open);
1204
1205 static int __dev_close_many(struct list_head *head)
1206 {
1207         struct net_device *dev;
1208
1209         ASSERT_RTNL();
1210         might_sleep();
1211
1212         list_for_each_entry(dev, head, unreg_list) {
1213                 call_netdevice_notifiers(NETDEV_GOING_DOWN, dev);
1214
1215                 clear_bit(__LINK_STATE_START, &dev->state);
1216
1217                 /* Synchronize to scheduled poll. We cannot touch poll list, it
1218                  * can be even on different cpu. So just clear netif_running().
1219                  *
1220                  * dev->stop() will invoke napi_disable() on all of it's
1221                  * napi_struct instances on this device.
1222                  */
1223                 smp_mb__after_clear_bit(); /* Commit netif_running(). */
1224         }
1225
1226         dev_deactivate_many(head);
1227
1228         list_for_each_entry(dev, head, unreg_list) {
1229                 const struct net_device_ops *ops = dev->netdev_ops;
1230
1231                 /*
1232                  *      Call the device specific close. This cannot fail.
1233                  *      Only if device is UP
1234                  *
1235                  *      We allow it to be called even after a DETACH hot-plug
1236                  *      event.
1237                  */
1238                 if (ops->ndo_stop)
1239                         ops->ndo_stop(dev);
1240
1241                 dev->flags &= ~IFF_UP;
1242                 net_dmaengine_put();
1243         }
1244
1245         return 0;
1246 }
1247
1248 static int __dev_close(struct net_device *dev)
1249 {
1250         int retval;
1251         LIST_HEAD(single);
1252
1253         list_add(&dev->unreg_list, &single);
1254         retval = __dev_close_many(&single);
1255         list_del(&single);
1256         return retval;
1257 }
1258
1259 static int dev_close_many(struct list_head *head)
1260 {
1261         struct net_device *dev, *tmp;
1262         LIST_HEAD(tmp_list);
1263
1264         list_for_each_entry_safe(dev, tmp, head, unreg_list)
1265                 if (!(dev->flags & IFF_UP))
1266                         list_move(&dev->unreg_list, &tmp_list);
1267
1268         __dev_close_many(head);
1269
1270         list_for_each_entry(dev, head, unreg_list) {
1271                 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING);
1272                 call_netdevice_notifiers(NETDEV_DOWN, dev);
1273         }
1274
1275         /* rollback_registered_many needs the complete original list */
1276         list_splice(&tmp_list, head);
1277         return 0;
1278 }
1279
1280 /**
1281  *      dev_close - shutdown an interface.
1282  *      @dev: device to shutdown
1283  *
1284  *      This function moves an active device into down state. A
1285  *      %NETDEV_GOING_DOWN is sent to the netdev notifier chain. The device
1286  *      is then deactivated and finally a %NETDEV_DOWN is sent to the notifier
1287  *      chain.
1288  */
1289 int dev_close(struct net_device *dev)
1290 {
1291         if (dev->flags & IFF_UP) {
1292                 LIST_HEAD(single);
1293
1294                 list_add(&dev->unreg_list, &single);
1295                 dev_close_many(&single);
1296                 list_del(&single);
1297         }
1298         return 0;
1299 }
1300 EXPORT_SYMBOL(dev_close);
1301
1302
1303 /**
1304  *      dev_disable_lro - disable Large Receive Offload on a device
1305  *      @dev: device
1306  *
1307  *      Disable Large Receive Offload (LRO) on a net device.  Must be
1308  *      called under RTNL.  This is needed if received packets may be
1309  *      forwarded to another interface.
1310  */
1311 void dev_disable_lro(struct net_device *dev)
1312 {
1313         u32 flags;
1314
1315         /*
1316          * If we're trying to disable lro on a vlan device
1317          * use the underlying physical device instead
1318          */
1319         if (is_vlan_dev(dev))
1320                 dev = vlan_dev_real_dev(dev);
1321
1322         if (dev->ethtool_ops && dev->ethtool_ops->get_flags)
1323                 flags = dev->ethtool_ops->get_flags(dev);
1324         else
1325                 flags = ethtool_op_get_flags(dev);
1326
1327         if (!(flags & ETH_FLAG_LRO))
1328                 return;
1329
1330         __ethtool_set_flags(dev, flags & ~ETH_FLAG_LRO);
1331         if (unlikely(dev->features & NETIF_F_LRO))
1332                 netdev_WARN(dev, "failed to disable LRO!\n");
1333 }
1334 EXPORT_SYMBOL(dev_disable_lro);
1335
1336
1337 static int dev_boot_phase = 1;
1338
1339 /**
1340  *      register_netdevice_notifier - register a network notifier block
1341  *      @nb: notifier
1342  *
1343  *      Register a notifier to be called when network device events occur.
1344  *      The notifier passed is linked into the kernel structures and must
1345  *      not be reused until it has been unregistered. A negative errno code
1346  *      is returned on a failure.
1347  *
1348  *      When registered all registration and up events are replayed
1349  *      to the new notifier to allow device to have a race free
1350  *      view of the network device list.
1351  */
1352
1353 int register_netdevice_notifier(struct notifier_block *nb)
1354 {
1355         struct net_device *dev;
1356         struct net_device *last;
1357         struct net *net;
1358         int err;
1359
1360         rtnl_lock();
1361         err = raw_notifier_chain_register(&netdev_chain, nb);
1362         if (err)
1363                 goto unlock;
1364         if (dev_boot_phase)
1365                 goto unlock;
1366         for_each_net(net) {
1367                 for_each_netdev(net, dev) {
1368                         err = nb->notifier_call(nb, NETDEV_REGISTER, dev);
1369                         err = notifier_to_errno(err);
1370                         if (err)
1371                                 goto rollback;
1372
1373                         if (!(dev->flags & IFF_UP))
1374                                 continue;
1375
1376                         nb->notifier_call(nb, NETDEV_UP, dev);
1377                 }
1378         }
1379
1380 unlock:
1381         rtnl_unlock();
1382         return err;
1383
1384 rollback:
1385         last = dev;
1386         for_each_net(net) {
1387                 for_each_netdev(net, dev) {
1388                         if (dev == last)
1389                                 break;
1390
1391                         if (dev->flags & IFF_UP) {
1392                                 nb->notifier_call(nb, NETDEV_GOING_DOWN, dev);
1393                                 nb->notifier_call(nb, NETDEV_DOWN, dev);
1394                         }
1395                         nb->notifier_call(nb, NETDEV_UNREGISTER, dev);
1396                         nb->notifier_call(nb, NETDEV_UNREGISTER_BATCH, dev);
1397                 }
1398         }
1399
1400         raw_notifier_chain_unregister(&netdev_chain, nb);
1401         goto unlock;
1402 }
1403 EXPORT_SYMBOL(register_netdevice_notifier);
1404
1405 /**
1406  *      unregister_netdevice_notifier - unregister a network notifier block
1407  *      @nb: notifier
1408  *
1409  *      Unregister a notifier previously registered by
1410  *      register_netdevice_notifier(). The notifier is unlinked into the
1411  *      kernel structures and may then be reused. A negative errno code
1412  *      is returned on a failure.
1413  *
1414  *      After unregistering unregister and down device events are synthesized
1415  *      for all devices on the device list to the removed notifier to remove
1416  *      the need for special case cleanup code.
1417  */
1418
1419 int unregister_netdevice_notifier(struct notifier_block *nb)
1420 {
1421         struct net_device *dev;
1422         struct net *net;
1423         int err;
1424
1425         rtnl_lock();
1426         err = raw_notifier_chain_unregister(&netdev_chain, nb);
1427         if (err)
1428                 goto unlock;
1429
1430         for_each_net(net) {
1431                 for_each_netdev(net, dev) {
1432                         if (dev->flags & IFF_UP) {
1433                                 nb->notifier_call(nb, NETDEV_GOING_DOWN, dev);
1434                                 nb->notifier_call(nb, NETDEV_DOWN, dev);
1435                         }
1436                         nb->notifier_call(nb, NETDEV_UNREGISTER, dev);
1437                         nb->notifier_call(nb, NETDEV_UNREGISTER_BATCH, dev);
1438                 }
1439         }
1440 unlock:
1441         rtnl_unlock();
1442         return err;
1443 }
1444 EXPORT_SYMBOL(unregister_netdevice_notifier);
1445
1446 /**
1447  *      call_netdevice_notifiers - call all network notifier blocks
1448  *      @val: value passed unmodified to notifier function
1449  *      @dev: net_device pointer passed unmodified to notifier function
1450  *
1451  *      Call all network notifier blocks.  Parameters and return value
1452  *      are as for raw_notifier_call_chain().
1453  */
1454
1455 int call_netdevice_notifiers(unsigned long val, struct net_device *dev)
1456 {
1457         ASSERT_RTNL();
1458         return raw_notifier_call_chain(&netdev_chain, val, dev);
1459 }
1460 EXPORT_SYMBOL(call_netdevice_notifiers);
1461
1462 /* When > 0 there are consumers of rx skb time stamps */
1463 static atomic_t netstamp_needed = ATOMIC_INIT(0);
1464
1465 void net_enable_timestamp(void)
1466 {
1467         atomic_inc(&netstamp_needed);
1468 }
1469 EXPORT_SYMBOL(net_enable_timestamp);
1470
1471 void net_disable_timestamp(void)
1472 {
1473         atomic_dec(&netstamp_needed);
1474 }
1475 EXPORT_SYMBOL(net_disable_timestamp);
1476
1477 static inline void net_timestamp_set(struct sk_buff *skb)
1478 {
1479         if (atomic_read(&netstamp_needed))
1480                 __net_timestamp(skb);
1481         else
1482                 skb->tstamp.tv64 = 0;
1483 }
1484
1485 static inline void net_timestamp_check(struct sk_buff *skb)
1486 {
1487         if (!skb->tstamp.tv64 && atomic_read(&netstamp_needed))
1488                 __net_timestamp(skb);
1489 }
1490
1491 static inline bool is_skb_forwardable(struct net_device *dev,
1492                                       struct sk_buff *skb)
1493 {
1494         unsigned int len;
1495
1496         if (!(dev->flags & IFF_UP))
1497                 return false;
1498
1499         len = dev->mtu + dev->hard_header_len + VLAN_HLEN;
1500         if (skb->len <= len)
1501                 return true;
1502
1503         /* if TSO is enabled, we don't care about the length as the packet
1504          * could be forwarded without being segmented before
1505          */
1506         if (skb_is_gso(skb))
1507                 return true;
1508
1509         return false;
1510 }
1511
1512 /**
1513  * dev_forward_skb - loopback an skb to another netif
1514  *
1515  * @dev: destination network device
1516  * @skb: buffer to forward
1517  *
1518  * return values:
1519  *      NET_RX_SUCCESS  (no congestion)
1520  *      NET_RX_DROP     (packet was dropped, but freed)
1521  *
1522  * dev_forward_skb can be used for injecting an skb from the
1523  * start_xmit function of one device into the receive queue
1524  * of another device.
1525  *
1526  * The receiving device may be in another namespace, so
1527  * we have to clear all information in the skb that could
1528  * impact namespace isolation.
1529  */
1530 int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
1531 {
1532         skb_orphan(skb);
1533         nf_reset(skb);
1534
1535         if (unlikely(!is_skb_forwardable(dev, skb))) {
1536                 atomic_long_inc(&dev->rx_dropped);
1537                 kfree_skb(skb);
1538                 return NET_RX_DROP;
1539         }
1540         skb->dev = dev;
1541         skb_dst_drop(skb);
1542         skb->tstamp.tv64 = 0;
1543         skb->pkt_type = PACKET_HOST;
1544         skb->protocol = eth_type_trans(skb, dev);
1545         skb->mark = 0;
1546         secpath_reset(skb);
1547         nf_reset(skb);
1548         return netif_rx(skb);
1549 }
1550 EXPORT_SYMBOL_GPL(dev_forward_skb);
1551
1552 static inline int deliver_skb(struct sk_buff *skb,
1553                               struct packet_type *pt_prev,
1554                               struct net_device *orig_dev)
1555 {
1556         atomic_inc(&skb->users);
1557         return pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
1558 }
1559
1560 /*
1561  *      Support routine. Sends outgoing frames to any network
1562  *      taps currently in use.
1563  */
1564
1565 static void dev_queue_xmit_nit(struct sk_buff *skb, struct net_device *dev)
1566 {
1567         struct packet_type *ptype;
1568         struct sk_buff *skb2 = NULL;
1569         struct packet_type *pt_prev = NULL;
1570
1571         rcu_read_lock();
1572         list_for_each_entry_rcu(ptype, &ptype_all, list) {
1573                 /* Never send packets back to the socket
1574                  * they originated from - MvS (miquels@drinkel.ow.org)
1575                  */
1576                 if ((ptype->dev == dev || !ptype->dev) &&
1577                     (ptype->af_packet_priv == NULL ||
1578                      (struct sock *)ptype->af_packet_priv != skb->sk)) {
1579                         if (pt_prev) {
1580                                 deliver_skb(skb2, pt_prev, skb->dev);
1581                                 pt_prev = ptype;
1582                                 continue;
1583                         }
1584
1585                         skb2 = skb_clone(skb, GFP_ATOMIC);
1586                         if (!skb2)
1587                                 break;
1588
1589                         net_timestamp_set(skb2);
1590
1591                         /* skb->nh should be correctly
1592                            set by sender, so that the second statement is
1593                            just protection against buggy protocols.
1594                          */
1595                         skb_reset_mac_header(skb2);
1596
1597                         if (skb_network_header(skb2) < skb2->data ||
1598                             skb2->network_header > skb2->tail) {
1599                                 if (net_ratelimit())
1600                                         printk(KERN_CRIT "protocol %04x is "
1601                                                "buggy, dev %s\n",
1602                                                ntohs(skb2->protocol),
1603                                                dev->name);
1604                                 skb_reset_network_header(skb2);
1605                         }
1606
1607                         skb2->transport_header = skb2->network_header;
1608                         skb2->pkt_type = PACKET_OUTGOING;
1609                         pt_prev = ptype;
1610                 }
1611         }
1612         if (pt_prev)
1613                 pt_prev->func(skb2, skb->dev, pt_prev, skb->dev);
1614         rcu_read_unlock();
1615 }
1616
1617 /* netif_setup_tc - Handle tc mappings on real_num_tx_queues change
1618  * @dev: Network device
1619  * @txq: number of queues available
1620  *
1621  * If real_num_tx_queues is changed the tc mappings may no longer be
1622  * valid. To resolve this verify the tc mapping remains valid and if
1623  * not NULL the mapping. With no priorities mapping to this
1624  * offset/count pair it will no longer be used. In the worst case TC0
1625  * is invalid nothing can be done so disable priority mappings. If is
1626  * expected that drivers will fix this mapping if they can before
1627  * calling netif_set_real_num_tx_queues.
1628  */
1629 static void netif_setup_tc(struct net_device *dev, unsigned int txq)
1630 {
1631         int i;
1632         struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
1633
1634         /* If TC0 is invalidated disable TC mapping */
1635         if (tc->offset + tc->count > txq) {
1636                 pr_warning("Number of in use tx queues changed "
1637                            "invalidating tc mappings. Priority "
1638                            "traffic classification disabled!\n");
1639                 dev->num_tc = 0;
1640                 return;
1641         }
1642
1643         /* Invalidated prio to tc mappings set to TC0 */
1644         for (i = 1; i < TC_BITMASK + 1; i++) {
1645                 int q = netdev_get_prio_tc_map(dev, i);
1646
1647                 tc = &dev->tc_to_txq[q];
1648                 if (tc->offset + tc->count > txq) {
1649                         pr_warning("Number of in use tx queues "
1650                                    "changed. Priority %i to tc "
1651                                    "mapping %i is no longer valid "
1652                                    "setting map to 0\n",
1653                                    i, q);
1654                         netdev_set_prio_tc_map(dev, i, 0);
1655                 }
1656         }
1657 }
1658
1659 /*
1660  * Routine to help set real_num_tx_queues. To avoid skbs mapped to queues
1661  * greater then real_num_tx_queues stale skbs on the qdisc must be flushed.
1662  */
1663 int netif_set_real_num_tx_queues(struct net_device *dev, unsigned int txq)
1664 {
1665         int rc;
1666
1667         if (txq < 1 || txq > dev->num_tx_queues)
1668                 return -EINVAL;
1669
1670         if (dev->reg_state == NETREG_REGISTERED ||
1671             dev->reg_state == NETREG_UNREGISTERING) {
1672                 ASSERT_RTNL();
1673
1674                 rc = netdev_queue_update_kobjects(dev, dev->real_num_tx_queues,
1675                                                   txq);
1676                 if (rc)
1677                         return rc;
1678
1679                 if (dev->num_tc)
1680                         netif_setup_tc(dev, txq);
1681
1682                 if (txq < dev->real_num_tx_queues)
1683                         qdisc_reset_all_tx_gt(dev, txq);
1684         }
1685
1686         dev->real_num_tx_queues = txq;
1687         return 0;
1688 }
1689 EXPORT_SYMBOL(netif_set_real_num_tx_queues);
1690
1691 #ifdef CONFIG_RPS
1692 /**
1693  *      netif_set_real_num_rx_queues - set actual number of RX queues used
1694  *      @dev: Network device
1695  *      @rxq: Actual number of RX queues
1696  *
1697  *      This must be called either with the rtnl_lock held or before
1698  *      registration of the net device.  Returns 0 on success, or a
1699  *      negative error code.  If called before registration, it always
1700  *      succeeds.
1701  */
1702 int netif_set_real_num_rx_queues(struct net_device *dev, unsigned int rxq)
1703 {
1704         int rc;
1705
1706         if (rxq < 1 || rxq > dev->num_rx_queues)
1707                 return -EINVAL;
1708
1709         if (dev->reg_state == NETREG_REGISTERED) {
1710                 ASSERT_RTNL();
1711
1712                 rc = net_rx_queue_update_kobjects(dev, dev->real_num_rx_queues,
1713                                                   rxq);
1714                 if (rc)
1715                         return rc;
1716         }
1717
1718         dev->real_num_rx_queues = rxq;
1719         return 0;
1720 }
1721 EXPORT_SYMBOL(netif_set_real_num_rx_queues);
1722 #endif
1723
1724 static inline void __netif_reschedule(struct Qdisc *q)
1725 {
1726         struct softnet_data *sd;
1727         unsigned long flags;
1728
1729         local_irq_save(flags);
1730         sd = &__get_cpu_var(softnet_data);
1731         q->next_sched = NULL;
1732         *sd->output_queue_tailp = q;
1733         sd->output_queue_tailp = &q->next_sched;
1734         raise_softirq_irqoff(NET_TX_SOFTIRQ);
1735         local_irq_restore(flags);
1736 }
1737
1738 void __netif_schedule(struct Qdisc *q)
1739 {
1740         if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state))
1741                 __netif_reschedule(q);
1742 }
1743 EXPORT_SYMBOL(__netif_schedule);
1744
1745 void dev_kfree_skb_irq(struct sk_buff *skb)
1746 {
1747         if (atomic_dec_and_test(&skb->users)) {
1748                 struct softnet_data *sd;
1749                 unsigned long flags;
1750
1751                 local_irq_save(flags);
1752                 sd = &__get_cpu_var(softnet_data);
1753                 skb->next = sd->completion_queue;
1754                 sd->completion_queue = skb;
1755                 raise_softirq_irqoff(NET_TX_SOFTIRQ);
1756                 local_irq_restore(flags);
1757         }
1758 }
1759 EXPORT_SYMBOL(dev_kfree_skb_irq);
1760
1761 void dev_kfree_skb_any(struct sk_buff *skb)
1762 {
1763         if (in_irq() || irqs_disabled())
1764                 dev_kfree_skb_irq(skb);
1765         else
1766                 dev_kfree_skb(skb);
1767 }
1768 EXPORT_SYMBOL(dev_kfree_skb_any);
1769
1770
1771 /**
1772  * netif_device_detach - mark device as removed
1773  * @dev: network device
1774  *
1775  * Mark device as removed from system and therefore no longer available.
1776  */
1777 void netif_device_detach(struct net_device *dev)
1778 {
1779         if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) &&
1780             netif_running(dev)) {
1781                 netif_tx_stop_all_queues(dev);
1782         }
1783 }
1784 EXPORT_SYMBOL(netif_device_detach);
1785
1786 /**
1787  * netif_device_attach - mark device as attached
1788  * @dev: network device
1789  *
1790  * Mark device as attached from system and restart if needed.
1791  */
1792 void netif_device_attach(struct net_device *dev)
1793 {
1794         if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) &&
1795             netif_running(dev)) {
1796                 netif_tx_wake_all_queues(dev);
1797                 __netdev_watchdog_up(dev);
1798         }
1799 }
1800 EXPORT_SYMBOL(netif_device_attach);
1801
1802 /*
1803  * Invalidate hardware checksum when packet is to be mangled, and
1804  * complete checksum manually on outgoing path.
1805  */
1806 int skb_checksum_help(struct sk_buff *skb)
1807 {
1808         __wsum csum;
1809         int ret = 0, offset;
1810
1811         if (skb->ip_summed == CHECKSUM_COMPLETE)
1812                 goto out_set_summed;
1813
1814         if (unlikely(skb_shinfo(skb)->gso_size)) {
1815                 /* Let GSO fix up the checksum. */
1816                 goto out_set_summed;
1817         }
1818
1819         offset = skb_checksum_start_offset(skb);
1820         BUG_ON(offset >= skb_headlen(skb));
1821         csum = skb_checksum(skb, offset, skb->len - offset, 0);
1822
1823         offset += skb->csum_offset;
1824         BUG_ON(offset + sizeof(__sum16) > skb_headlen(skb));
1825
1826         if (skb_cloned(skb) &&
1827             !skb_clone_writable(skb, offset + sizeof(__sum16))) {
1828                 ret = pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
1829                 if (ret)
1830                         goto out;
1831         }
1832
1833         *(__sum16 *)(skb->data + offset) = csum_fold(csum);
1834 out_set_summed:
1835         skb->ip_summed = CHECKSUM_NONE;
1836 out:
1837         return ret;
1838 }
1839 EXPORT_SYMBOL(skb_checksum_help);
1840
1841 /**
1842  *      skb_gso_segment - Perform segmentation on skb.
1843  *      @skb: buffer to segment
1844  *      @features: features for the output path (see dev->features)
1845  *
1846  *      This function segments the given skb and returns a list of segments.
1847  *
1848  *      It may return NULL if the skb requires no segmentation.  This is
1849  *      only possible when GSO is used for verifying header integrity.
1850  */
1851 struct sk_buff *skb_gso_segment(struct sk_buff *skb, u32 features)
1852 {
1853         struct sk_buff *segs = ERR_PTR(-EPROTONOSUPPORT);
1854         struct packet_type *ptype;
1855         __be16 type = skb->protocol;
1856         int vlan_depth = ETH_HLEN;
1857         int err;
1858
1859         while (type == htons(ETH_P_8021Q)) {
1860                 struct vlan_hdr *vh;
1861
1862                 if (unlikely(!pskb_may_pull(skb, vlan_depth + VLAN_HLEN)))
1863                         return ERR_PTR(-EINVAL);
1864
1865                 vh = (struct vlan_hdr *)(skb->data + vlan_depth);
1866                 type = vh->h_vlan_encapsulated_proto;
1867                 vlan_depth += VLAN_HLEN;
1868         }
1869
1870         skb_reset_mac_header(skb);
1871         skb->mac_len = skb->network_header - skb->mac_header;
1872         __skb_pull(skb, skb->mac_len);
1873
1874         if (unlikely(skb->ip_summed != CHECKSUM_PARTIAL)) {
1875                 struct net_device *dev = skb->dev;
1876                 struct ethtool_drvinfo info = {};
1877
1878                 if (dev && dev->ethtool_ops && dev->ethtool_ops->get_drvinfo)
1879                         dev->ethtool_ops->get_drvinfo(dev, &info);
1880
1881                 WARN(1, "%s: caps=(0x%lx, 0x%lx) len=%d data_len=%d ip_summed=%d\n",
1882                      info.driver, dev ? dev->features : 0L,
1883                      skb->sk ? skb->sk->sk_route_caps : 0L,
1884                      skb->len, skb->data_len, skb->ip_summed);
1885
1886                 if (skb_header_cloned(skb) &&
1887                     (err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC)))
1888                         return ERR_PTR(err);
1889         }
1890
1891         rcu_read_lock();
1892         list_for_each_entry_rcu(ptype,
1893                         &ptype_base[ntohs(type) & PTYPE_HASH_MASK], list) {
1894                 if (ptype->type == type && !ptype->dev && ptype->gso_segment) {
1895                         if (unlikely(skb->ip_summed != CHECKSUM_PARTIAL)) {
1896                                 err = ptype->gso_send_check(skb);
1897                                 segs = ERR_PTR(err);
1898                                 if (err || skb_gso_ok(skb, features))
1899                                         break;
1900                                 __skb_push(skb, (skb->data -
1901                                                  skb_network_header(skb)));
1902                         }
1903                         segs = ptype->gso_segment(skb, features);
1904                         break;
1905                 }
1906         }
1907         rcu_read_unlock();
1908
1909         __skb_push(skb, skb->data - skb_mac_header(skb));
1910
1911         return segs;
1912 }
1913 EXPORT_SYMBOL(skb_gso_segment);
1914
1915 /* Take action when hardware reception checksum errors are detected. */
1916 #ifdef CONFIG_BUG
1917 void netdev_rx_csum_fault(struct net_device *dev)
1918 {
1919         if (net_ratelimit()) {
1920                 printk(KERN_ERR "%s: hw csum failure.\n",
1921                         dev ? dev->name : "<unknown>");
1922                 dump_stack();
1923         }
1924 }
1925 EXPORT_SYMBOL(netdev_rx_csum_fault);
1926 #endif
1927
1928 /* Actually, we should eliminate this check as soon as we know, that:
1929  * 1. IOMMU is present and allows to map all the memory.
1930  * 2. No high memory really exists on this machine.
1931  */
1932
1933 static int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
1934 {
1935 #ifdef CONFIG_HIGHMEM
1936         int i;
1937         if (!(dev->features & NETIF_F_HIGHDMA)) {
1938                 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1939                         if (PageHighMem(skb_shinfo(skb)->frags[i].page))
1940                                 return 1;
1941         }
1942
1943         if (PCI_DMA_BUS_IS_PHYS) {
1944                 struct device *pdev = dev->dev.parent;
1945
1946                 if (!pdev)
1947                         return 0;
1948                 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1949                         dma_addr_t addr = page_to_phys(skb_shinfo(skb)->frags[i].page);
1950                         if (!pdev->dma_mask || addr + PAGE_SIZE - 1 > *pdev->dma_mask)
1951                                 return 1;
1952                 }
1953         }
1954 #endif
1955         return 0;
1956 }
1957
1958 struct dev_gso_cb {
1959         void (*destructor)(struct sk_buff *skb);
1960 };
1961
1962 #define DEV_GSO_CB(skb) ((struct dev_gso_cb *)(skb)->cb)
1963
1964 static void dev_gso_skb_destructor(struct sk_buff *skb)
1965 {
1966         struct dev_gso_cb *cb;
1967
1968         do {
1969                 struct sk_buff *nskb = skb->next;
1970
1971                 skb->next = nskb->next;
1972                 nskb->next = NULL;
1973                 kfree_skb(nskb);
1974         } while (skb->next);
1975
1976         cb = DEV_GSO_CB(skb);
1977         if (cb->destructor)
1978                 cb->destructor(skb);
1979 }
1980
1981 /**
1982  *      dev_gso_segment - Perform emulated hardware segmentation on skb.
1983  *      @skb: buffer to segment
1984  *      @features: device features as applicable to this skb
1985  *
1986  *      This function segments the given skb and stores the list of segments
1987  *      in skb->next.
1988  */
1989 static int dev_gso_segment(struct sk_buff *skb, int features)
1990 {
1991         struct sk_buff *segs;
1992
1993         segs = skb_gso_segment(skb, features);
1994
1995         /* Verifying header integrity only. */
1996         if (!segs)
1997                 return 0;
1998
1999         if (IS_ERR(segs))
2000                 return PTR_ERR(segs);
2001
2002         skb->next = segs;
2003         DEV_GSO_CB(skb)->destructor = skb->destructor;
2004         skb->destructor = dev_gso_skb_destructor;
2005
2006         return 0;
2007 }
2008
2009 /*
2010  * Try to orphan skb early, right before transmission by the device.
2011  * We cannot orphan skb if tx timestamp is requested or the sk-reference
2012  * is needed on driver level for other reasons, e.g. see net/can/raw.c
2013  */
2014 static inline void skb_orphan_try(struct sk_buff *skb)
2015 {
2016         struct sock *sk = skb->sk;
2017
2018         if (sk && !skb_shinfo(skb)->tx_flags) {
2019                 /* skb_tx_hash() wont be able to get sk.
2020                  * We copy sk_hash into skb->rxhash
2021                  */
2022                 if (!skb->rxhash)
2023                         skb->rxhash = sk->sk_hash;
2024                 skb_orphan(skb);
2025         }
2026 }
2027
2028 static bool can_checksum_protocol(unsigned long features, __be16 protocol)
2029 {
2030         return ((features & NETIF_F_GEN_CSUM) ||
2031                 ((features & NETIF_F_V4_CSUM) &&
2032                  protocol == htons(ETH_P_IP)) ||
2033                 ((features & NETIF_F_V6_CSUM) &&
2034                  protocol == htons(ETH_P_IPV6)) ||
2035                 ((features & NETIF_F_FCOE_CRC) &&
2036                  protocol == htons(ETH_P_FCOE)));
2037 }
2038
2039 static u32 harmonize_features(struct sk_buff *skb, __be16 protocol, u32 features)
2040 {
2041         if (skb->ip_summed != CHECKSUM_NONE &&
2042             !can_checksum_protocol(features, protocol)) {
2043                 features &= ~NETIF_F_ALL_CSUM;
2044                 features &= ~NETIF_F_SG;
2045         } else if (illegal_highdma(skb->dev, skb)) {
2046                 features &= ~NETIF_F_SG;
2047         }
2048
2049         return features;
2050 }
2051
2052 u32 netif_skb_features(struct sk_buff *skb)
2053 {
2054         __be16 protocol = skb->protocol;
2055         u32 features = skb->dev->features;
2056
2057         if (skb_shinfo(skb)->gso_segs > skb->dev->gso_max_segs)
2058                 features &= ~NETIF_F_GSO_MASK;
2059
2060         if (protocol == htons(ETH_P_8021Q)) {
2061                 struct vlan_ethhdr *veh = (struct vlan_ethhdr *)skb->data;
2062                 protocol = veh->h_vlan_encapsulated_proto;
2063         } else if (!vlan_tx_tag_present(skb)) {
2064                 return harmonize_features(skb, protocol, features);
2065         }
2066
2067         features &= (skb->dev->vlan_features | NETIF_F_HW_VLAN_TX);
2068
2069         if (protocol != htons(ETH_P_8021Q)) {
2070                 return harmonize_features(skb, protocol, features);
2071         } else {
2072                 features &= NETIF_F_SG | NETIF_F_HIGHDMA | NETIF_F_FRAGLIST |
2073                                 NETIF_F_GEN_CSUM | NETIF_F_HW_VLAN_TX;
2074                 return harmonize_features(skb, protocol, features);
2075         }
2076 }
2077 EXPORT_SYMBOL(netif_skb_features);
2078
2079 /*
2080  * Returns true if either:
2081  *      1. skb has frag_list and the device doesn't support FRAGLIST, or
2082  *      2. skb is fragmented and the device does not support SG, or if
2083  *         at least one of fragments is in highmem and device does not
2084  *         support DMA from it.
2085  */
2086 static inline int skb_needs_linearize(struct sk_buff *skb,
2087                                       int features)
2088 {
2089         return skb_is_nonlinear(skb) &&
2090                         ((skb_has_frag_list(skb) &&
2091                                 !(features & NETIF_F_FRAGLIST)) ||
2092                         (skb_shinfo(skb)->nr_frags &&
2093                                 !(features & NETIF_F_SG)));
2094 }
2095
2096 int dev_hard_start_xmit(struct sk_buff *skb, struct net_device *dev,
2097                         struct netdev_queue *txq)
2098 {
2099         const struct net_device_ops *ops = dev->netdev_ops;
2100         int rc = NETDEV_TX_OK;
2101         unsigned int skb_len;
2102
2103         if (likely(!skb->next)) {
2104                 u32 features;
2105
2106                 /*
2107                  * If device doesn't need skb->dst, release it right now while
2108                  * its hot in this cpu cache
2109                  */
2110                 if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
2111                         skb_dst_drop(skb);
2112
2113                 if (!list_empty(&ptype_all))
2114                         dev_queue_xmit_nit(skb, dev);
2115
2116                 skb_orphan_try(skb);
2117
2118                 features = netif_skb_features(skb);
2119
2120                 if (vlan_tx_tag_present(skb) &&
2121                     !(features & NETIF_F_HW_VLAN_TX)) {
2122                         skb = __vlan_put_tag(skb, vlan_tx_tag_get(skb));
2123                         if (unlikely(!skb))
2124                                 goto out;
2125
2126                         skb->vlan_tci = 0;
2127                 }
2128
2129                 if (netif_needs_gso(skb, features)) {
2130                         if (unlikely(dev_gso_segment(skb, features)))
2131                                 goto out_kfree_skb;
2132                         if (skb->next)
2133                                 goto gso;
2134                 } else {
2135                         if (skb_needs_linearize(skb, features) &&
2136                             __skb_linearize(skb))
2137                                 goto out_kfree_skb;
2138
2139                         /* If packet is not checksummed and device does not
2140                          * support checksumming for this protocol, complete
2141                          * checksumming here.
2142                          */
2143                         if (skb->ip_summed == CHECKSUM_PARTIAL) {
2144                                 skb_set_transport_header(skb,
2145                                         skb_checksum_start_offset(skb));
2146                                 if (!(features & NETIF_F_ALL_CSUM) &&
2147                                      skb_checksum_help(skb))
2148                                         goto out_kfree_skb;
2149                         }
2150                 }
2151
2152                 skb_len = skb->len;
2153                 rc = ops->ndo_start_xmit(skb, dev);
2154                 trace_net_dev_xmit(skb, rc, dev, skb_len);
2155                 if (rc == NETDEV_TX_OK)
2156                         txq_trans_update(txq);
2157                 return rc;
2158         }
2159
2160 gso:
2161         do {
2162                 struct sk_buff *nskb = skb->next;
2163
2164                 skb->next = nskb->next;
2165                 nskb->next = NULL;
2166
2167                 /*
2168                  * If device doesn't need nskb->dst, release it right now while
2169                  * its hot in this cpu cache
2170                  */
2171                 if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
2172                         skb_dst_drop(nskb);
2173
2174                 skb_len = nskb->len;
2175                 rc = ops->ndo_start_xmit(nskb, dev);
2176                 trace_net_dev_xmit(nskb, rc, dev, skb_len);
2177                 if (unlikely(rc != NETDEV_TX_OK)) {
2178                         if (rc & ~NETDEV_TX_MASK)
2179                                 goto out_kfree_gso_skb;
2180                         nskb->next = skb->next;
2181                         skb->next = nskb;
2182                         return rc;
2183                 }
2184                 txq_trans_update(txq);
2185                 if (unlikely(netif_tx_queue_stopped(txq) && skb->next))
2186                         return NETDEV_TX_BUSY;
2187         } while (skb->next);
2188
2189 out_kfree_gso_skb:
2190         if (likely(skb->next == NULL))
2191                 skb->destructor = DEV_GSO_CB(skb)->destructor;
2192 out_kfree_skb:
2193         kfree_skb(skb);
2194 out:
2195         return rc;
2196 }
2197
2198 static u32 hashrnd __read_mostly;
2199
2200 /*
2201  * Returns a Tx hash based on the given packet descriptor a Tx queues' number
2202  * to be used as a distribution range.
2203  */
2204 u16 __skb_tx_hash(const struct net_device *dev, const struct sk_buff *skb,
2205                   unsigned int num_tx_queues)
2206 {
2207         u32 hash;
2208         u16 qoffset = 0;
2209         u16 qcount = num_tx_queues;
2210
2211         if (skb_rx_queue_recorded(skb)) {
2212                 hash = skb_get_rx_queue(skb);
2213                 while (unlikely(hash >= num_tx_queues))
2214                         hash -= num_tx_queues;
2215                 return hash;
2216         }
2217
2218         if (dev->num_tc) {
2219                 u8 tc = netdev_get_prio_tc_map(dev, skb->priority);
2220                 qoffset = dev->tc_to_txq[tc].offset;
2221                 qcount = dev->tc_to_txq[tc].count;
2222         }
2223
2224         if (skb->sk && skb->sk->sk_hash)
2225                 hash = skb->sk->sk_hash;
2226         else
2227                 hash = (__force u16) skb->protocol ^ skb->rxhash;
2228         hash = jhash_1word(hash, hashrnd);
2229
2230         return (u16) (((u64) hash * qcount) >> 32) + qoffset;
2231 }
2232 EXPORT_SYMBOL(__skb_tx_hash);
2233
2234 static inline u16 dev_cap_txqueue(struct net_device *dev, u16 queue_index)
2235 {
2236         if (unlikely(queue_index >= dev->real_num_tx_queues)) {
2237                 if (net_ratelimit()) {
2238                         pr_warning("%s selects TX queue %d, but "
2239                                 "real number of TX queues is %d\n",
2240                                 dev->name, queue_index, dev->real_num_tx_queues);
2241                 }
2242                 return 0;
2243         }
2244         return queue_index;
2245 }
2246
2247 static inline int get_xps_queue(struct net_device *dev, struct sk_buff *skb)
2248 {
2249 #ifdef CONFIG_XPS
2250         struct xps_dev_maps *dev_maps;
2251         struct xps_map *map;
2252         int queue_index = -1;
2253
2254         rcu_read_lock();
2255         dev_maps = rcu_dereference(dev->xps_maps);
2256         if (dev_maps) {
2257                 map = rcu_dereference(
2258                     dev_maps->cpu_map[raw_smp_processor_id()]);
2259                 if (map) {
2260                         if (map->len == 1)
2261                                 queue_index = map->queues[0];
2262                         else {
2263                                 u32 hash;
2264                                 if (skb->sk && skb->sk->sk_hash)
2265                                         hash = skb->sk->sk_hash;
2266                                 else
2267                                         hash = (__force u16) skb->protocol ^
2268                                             skb->rxhash;
2269                                 hash = jhash_1word(hash, hashrnd);
2270                                 queue_index = map->queues[
2271                                     ((u64)hash * map->len) >> 32];
2272                         }
2273                         if (unlikely(queue_index >= dev->real_num_tx_queues))
2274                                 queue_index = -1;
2275                 }
2276         }
2277         rcu_read_unlock();
2278
2279         return queue_index;
2280 #else
2281         return -1;
2282 #endif
2283 }
2284
2285 static struct netdev_queue *dev_pick_tx(struct net_device *dev,
2286                                         struct sk_buff *skb)
2287 {
2288         int queue_index;
2289         const struct net_device_ops *ops = dev->netdev_ops;
2290
2291         if (dev->real_num_tx_queues == 1)
2292                 queue_index = 0;
2293         else if (ops->ndo_select_queue) {
2294                 queue_index = ops->ndo_select_queue(dev, skb);
2295                 queue_index = dev_cap_txqueue(dev, queue_index);
2296         } else {
2297                 struct sock *sk = skb->sk;
2298                 queue_index = sk_tx_queue_get(sk);
2299
2300                 if (queue_index < 0 || skb->ooo_okay ||
2301                     queue_index >= dev->real_num_tx_queues) {
2302                         int old_index = queue_index;
2303
2304                         queue_index = get_xps_queue(dev, skb);
2305                         if (queue_index < 0)
2306                                 queue_index = skb_tx_hash(dev, skb);
2307
2308                         if (queue_index != old_index && sk) {
2309                                 struct dst_entry *dst =
2310                                     rcu_dereference_check(sk->sk_dst_cache, 1);
2311
2312                                 if (dst && skb_dst(skb) == dst)
2313                                         sk_tx_queue_set(sk, queue_index);
2314                         }
2315                 }
2316         }
2317
2318         skb_set_queue_mapping(skb, queue_index);
2319         return netdev_get_tx_queue(dev, queue_index);
2320 }
2321
2322 static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q,
2323                                  struct net_device *dev,
2324                                  struct netdev_queue *txq)
2325 {
2326         spinlock_t *root_lock = qdisc_lock(q);
2327         bool contended;
2328         int rc;
2329
2330         qdisc_skb_cb(skb)->pkt_len = skb->len;
2331         qdisc_calculate_pkt_len(skb, q);
2332         /*
2333          * Heuristic to force contended enqueues to serialize on a
2334          * separate lock before trying to get qdisc main lock.
2335          * This permits __QDISC_STATE_RUNNING owner to get the lock more often
2336          * and dequeue packets faster.
2337          */
2338         contended = qdisc_is_running(q);
2339         if (unlikely(contended))
2340                 spin_lock(&q->busylock);
2341
2342         spin_lock(root_lock);
2343         if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) {
2344                 kfree_skb(skb);
2345                 rc = NET_XMIT_DROP;
2346         } else if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) &&
2347                    qdisc_run_begin(q)) {
2348                 /*
2349                  * This is a work-conserving queue; there are no old skbs
2350                  * waiting to be sent out; and the qdisc is not running -
2351                  * xmit the skb directly.
2352                  */
2353                 if (!(dev->priv_flags & IFF_XMIT_DST_RELEASE))
2354                         skb_dst_force(skb);
2355
2356                 qdisc_bstats_update(q, skb);
2357
2358                 if (sch_direct_xmit(skb, q, dev, txq, root_lock)) {
2359                         if (unlikely(contended)) {
2360                                 spin_unlock(&q->busylock);
2361                                 contended = false;
2362                         }
2363                         __qdisc_run(q);
2364                 } else
2365                         qdisc_run_end(q);
2366
2367                 rc = NET_XMIT_SUCCESS;
2368         } else {
2369                 skb_dst_force(skb);
2370                 rc = q->enqueue(skb, q) & NET_XMIT_MASK;
2371                 if (qdisc_run_begin(q)) {
2372                         if (unlikely(contended)) {
2373                                 spin_unlock(&q->busylock);
2374                                 contended = false;
2375                         }
2376                         __qdisc_run(q);
2377                 }
2378         }
2379         spin_unlock(root_lock);
2380         if (unlikely(contended))
2381                 spin_unlock(&q->busylock);
2382         return rc;
2383 }
2384
2385 static DEFINE_PER_CPU(int, xmit_recursion);
2386 #define RECURSION_LIMIT 10
2387
2388 /**
2389  *      dev_queue_xmit - transmit a buffer
2390  *      @skb: buffer to transmit
2391  *
2392  *      Queue a buffer for transmission to a network device. The caller must
2393  *      have set the device and priority and built the buffer before calling
2394  *      this function. The function can be called from an interrupt.
2395  *
2396  *      A negative errno code is returned on a failure. A success does not
2397  *      guarantee the frame will be transmitted as it may be dropped due
2398  *      to congestion or traffic shaping.
2399  *
2400  * -----------------------------------------------------------------------------------
2401  *      I notice this method can also return errors from the queue disciplines,
2402  *      including NET_XMIT_DROP, which is a positive value.  So, errors can also
2403  *      be positive.
2404  *
2405  *      Regardless of the return value, the skb is consumed, so it is currently
2406  *      difficult to retry a send to this method.  (You can bump the ref count
2407  *      before sending to hold a reference for retry if you are careful.)
2408  *
2409  *      When calling this method, interrupts MUST be enabled.  This is because
2410  *      the BH enable code must have IRQs enabled so that it will not deadlock.
2411  *          --BLG
2412  */
2413 int dev_queue_xmit(struct sk_buff *skb)
2414 {
2415         struct net_device *dev = skb->dev;
2416         struct netdev_queue *txq;
2417         struct Qdisc *q;
2418         int rc = -ENOMEM;
2419
2420         /* Disable soft irqs for various locks below. Also
2421          * stops preemption for RCU.
2422          */
2423         rcu_read_lock_bh();
2424
2425         txq = dev_pick_tx(dev, skb);
2426         q = rcu_dereference_bh(txq->qdisc);
2427
2428 #ifdef CONFIG_NET_CLS_ACT
2429         skb->tc_verd = SET_TC_AT(skb->tc_verd, AT_EGRESS);
2430 #endif
2431         trace_net_dev_queue(skb);
2432         if (q->enqueue) {
2433                 rc = __dev_xmit_skb(skb, q, dev, txq);
2434                 goto out;
2435         }
2436
2437         /* The device has no queue. Common case for software devices:
2438            loopback, all the sorts of tunnels...
2439
2440            Really, it is unlikely that netif_tx_lock protection is necessary
2441            here.  (f.e. loopback and IP tunnels are clean ignoring statistics
2442            counters.)
2443            However, it is possible, that they rely on protection
2444            made by us here.
2445
2446            Check this and shot the lock. It is not prone from deadlocks.
2447            Either shot noqueue qdisc, it is even simpler 8)
2448          */
2449         if (dev->flags & IFF_UP) {
2450                 int cpu = smp_processor_id(); /* ok because BHs are off */
2451
2452                 if (txq->xmit_lock_owner != cpu) {
2453
2454                         if (__this_cpu_read(xmit_recursion) > RECURSION_LIMIT)
2455                                 goto recursion_alert;
2456
2457                         HARD_TX_LOCK(dev, txq, cpu);
2458
2459                         if (!netif_tx_queue_stopped(txq)) {
2460                                 __this_cpu_inc(xmit_recursion);
2461                                 rc = dev_hard_start_xmit(skb, dev, txq);
2462                                 __this_cpu_dec(xmit_recursion);
2463                                 if (dev_xmit_complete(rc)) {
2464                                         HARD_TX_UNLOCK(dev, txq);
2465                                         goto out;
2466                                 }
2467                         }
2468                         HARD_TX_UNLOCK(dev, txq);
2469                         if (net_ratelimit())
2470                                 printk(KERN_CRIT "Virtual device %s asks to "
2471                                        "queue packet!\n", dev->name);
2472                 } else {
2473                         /* Recursion is detected! It is possible,
2474                          * unfortunately
2475                          */
2476 recursion_alert:
2477                         if (net_ratelimit())
2478                                 printk(KERN_CRIT "Dead loop on virtual device "
2479                                        "%s, fix it urgently!\n", dev->name);
2480                 }
2481         }
2482
2483         rc = -ENETDOWN;
2484         rcu_read_unlock_bh();
2485
2486         kfree_skb(skb);
2487         return rc;
2488 out:
2489         rcu_read_unlock_bh();
2490         return rc;
2491 }
2492 EXPORT_SYMBOL(dev_queue_xmit);
2493
2494
2495 /*=======================================================================
2496                         Receiver routines
2497   =======================================================================*/
2498
2499 int netdev_max_backlog __read_mostly = 1000;
2500 int netdev_tstamp_prequeue __read_mostly = 1;
2501 int netdev_budget __read_mostly = 300;
2502 int weight_p __read_mostly = 64;            /* old backlog weight */
2503
2504 /* Called with irq disabled */
2505 static inline void ____napi_schedule(struct softnet_data *sd,
2506                                      struct napi_struct *napi)
2507 {
2508         list_add_tail(&napi->poll_list, &sd->poll_list);
2509         __raise_softirq_irqoff(NET_RX_SOFTIRQ);
2510 }
2511
2512 /*
2513  * __skb_get_rxhash: calculate a flow hash based on src/dst addresses
2514  * and src/dst port numbers. Returns a non-zero hash number on success
2515  * and 0 on failure.
2516  */
2517 __u32 __skb_get_rxhash(struct sk_buff *skb)
2518 {
2519         int nhoff, hash = 0, poff;
2520         const struct ipv6hdr *ip6;
2521         const struct iphdr *ip;
2522         u8 ip_proto;
2523         u32 addr1, addr2, ihl;
2524         union {
2525                 u32 v32;
2526                 u16 v16[2];
2527         } ports;
2528
2529         nhoff = skb_network_offset(skb);
2530
2531         switch (skb->protocol) {
2532         case __constant_htons(ETH_P_IP):
2533                 if (!pskb_may_pull(skb, sizeof(*ip) + nhoff))
2534                         goto done;
2535
2536                 ip = (const struct iphdr *) (skb->data + nhoff);
2537                 if (ip->frag_off & htons(IP_MF | IP_OFFSET))
2538                         ip_proto = 0;
2539                 else
2540                         ip_proto = ip->protocol;
2541                 addr1 = (__force u32) ip->saddr;
2542                 addr2 = (__force u32) ip->daddr;
2543                 ihl = ip->ihl;
2544                 break;
2545         case __constant_htons(ETH_P_IPV6):
2546                 if (!pskb_may_pull(skb, sizeof(*ip6) + nhoff))
2547                         goto done;
2548
2549                 ip6 = (const struct ipv6hdr *) (skb->data + nhoff);
2550                 ip_proto = ip6->nexthdr;
2551                 addr1 = (__force u32) ip6->saddr.s6_addr32[3];
2552                 addr2 = (__force u32) ip6->daddr.s6_addr32[3];
2553                 ihl = (40 >> 2);
2554                 break;
2555         default:
2556                 goto done;
2557         }
2558
2559         ports.v32 = 0;
2560         poff = proto_ports_offset(ip_proto);
2561         if (poff >= 0) {
2562                 nhoff += ihl * 4 + poff;
2563                 if (pskb_may_pull(skb, nhoff + 4))
2564                         ports.v32 = * (__force u32 *) (skb->data + nhoff);
2565         }
2566
2567         /* get a consistent hash (same value on both flow directions) */
2568         if (addr2 < addr1 ||
2569             (addr2 == addr1 &&
2570              ports.v16[1] < ports.v16[0])) {
2571                 swap(addr1, addr2);
2572                 swap(ports.v16[0], ports.v16[1]);
2573         }
2574
2575         hash = jhash_3words(addr1, addr2, ports.v32, hashrnd);
2576         if (!hash)
2577                 hash = 1;
2578
2579 done:
2580         return hash;
2581 }
2582 EXPORT_SYMBOL(__skb_get_rxhash);
2583
2584 #ifdef CONFIG_RPS
2585
2586 /* One global table that all flow-based protocols share. */
2587 struct rps_sock_flow_table __rcu *rps_sock_flow_table __read_mostly;
2588 EXPORT_SYMBOL(rps_sock_flow_table);
2589
2590 static struct rps_dev_flow *
2591 set_rps_cpu(struct net_device *dev, struct sk_buff *skb,
2592             struct rps_dev_flow *rflow, u16 next_cpu)
2593 {
2594         u16 tcpu;
2595
2596         tcpu = rflow->cpu = next_cpu;
2597         if (tcpu != RPS_NO_CPU) {
2598 #ifdef CONFIG_RFS_ACCEL
2599                 struct netdev_rx_queue *rxqueue;
2600                 struct rps_dev_flow_table *flow_table;
2601                 struct rps_dev_flow *old_rflow;
2602                 u32 flow_id;
2603                 u16 rxq_index;
2604                 int rc;
2605
2606                 /* Should we steer this flow to a different hardware queue? */
2607                 if (!skb_rx_queue_recorded(skb) || !dev->rx_cpu_rmap ||
2608                     !(dev->features & NETIF_F_NTUPLE))
2609                         goto out;
2610                 rxq_index = cpu_rmap_lookup_index(dev->rx_cpu_rmap, next_cpu);
2611                 if (rxq_index == skb_get_rx_queue(skb))
2612                         goto out;
2613
2614                 rxqueue = dev->_rx + rxq_index;
2615                 flow_table = rcu_dereference(rxqueue->rps_flow_table);
2616                 if (!flow_table)
2617                         goto out;
2618                 flow_id = skb->rxhash & flow_table->mask;
2619                 rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb,
2620                                                         rxq_index, flow_id);
2621                 if (rc < 0)
2622                         goto out;
2623                 old_rflow = rflow;
2624                 rflow = &flow_table->flows[flow_id];
2625                 rflow->cpu = next_cpu;
2626                 rflow->filter = rc;
2627                 if (old_rflow->filter == rflow->filter)
2628                         old_rflow->filter = RPS_NO_FILTER;
2629         out:
2630 #endif
2631                 rflow->last_qtail =
2632                         per_cpu(softnet_data, tcpu).input_queue_head;
2633         }
2634
2635         return rflow;
2636 }
2637
2638 /*
2639  * get_rps_cpu is called from netif_receive_skb and returns the target
2640  * CPU from the RPS map of the receiving queue for a given skb.
2641  * rcu_read_lock must be held on entry.
2642  */
2643 static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb,
2644                        struct rps_dev_flow **rflowp)
2645 {
2646         struct netdev_rx_queue *rxqueue;
2647         struct rps_map *map;
2648         struct rps_dev_flow_table *flow_table;
2649         struct rps_sock_flow_table *sock_flow_table;
2650         int cpu = -1;
2651         u16 tcpu;
2652
2653         if (skb_rx_queue_recorded(skb)) {
2654                 u16 index = skb_get_rx_queue(skb);
2655                 if (unlikely(index >= dev->real_num_rx_queues)) {
2656                         WARN_ONCE(dev->real_num_rx_queues > 1,
2657                                   "%s received packet on queue %u, but number "
2658                                   "of RX queues is %u\n",
2659                                   dev->name, index, dev->real_num_rx_queues);
2660                         goto done;
2661                 }
2662                 rxqueue = dev->_rx + index;
2663         } else
2664                 rxqueue = dev->_rx;
2665
2666         map = rcu_dereference(rxqueue->rps_map);
2667         if (map) {
2668                 if (map->len == 1 &&
2669                     !rcu_dereference_raw(rxqueue->rps_flow_table)) {
2670                         tcpu = map->cpus[0];
2671                         if (cpu_online(tcpu))
2672                                 cpu = tcpu;
2673                         goto done;
2674                 }
2675         } else if (!rcu_dereference_raw(rxqueue->rps_flow_table)) {
2676                 goto done;
2677         }
2678
2679         skb_reset_network_header(skb);
2680         if (!skb_get_rxhash(skb))
2681                 goto done;
2682
2683         flow_table = rcu_dereference(rxqueue->rps_flow_table);
2684         sock_flow_table = rcu_dereference(rps_sock_flow_table);
2685         if (flow_table && sock_flow_table) {
2686                 u16 next_cpu;
2687                 struct rps_dev_flow *rflow;
2688
2689                 rflow = &flow_table->flows[skb->rxhash & flow_table->mask];
2690                 tcpu = rflow->cpu;
2691
2692                 next_cpu = sock_flow_table->ents[skb->rxhash &
2693                     sock_flow_table->mask];
2694
2695                 /*
2696                  * If the desired CPU (where last recvmsg was done) is
2697                  * different from current CPU (one in the rx-queue flow
2698                  * table entry), switch if one of the following holds:
2699                  *   - Current CPU is unset (equal to RPS_NO_CPU).
2700                  *   - Current CPU is offline.
2701                  *   - The current CPU's queue tail has advanced beyond the
2702                  *     last packet that was enqueued using this table entry.
2703                  *     This guarantees that all previous packets for the flow
2704                  *     have been dequeued, thus preserving in order delivery.
2705                  */
2706                 if (unlikely(tcpu != next_cpu) &&
2707                     (tcpu == RPS_NO_CPU || !cpu_online(tcpu) ||
2708                      ((int)(per_cpu(softnet_data, tcpu).input_queue_head -
2709                       rflow->last_qtail)) >= 0)) {
2710                         tcpu = next_cpu;
2711                         rflow = set_rps_cpu(dev, skb, rflow, next_cpu);
2712                 }
2713
2714                 if (tcpu != RPS_NO_CPU && cpu_online(tcpu)) {
2715                         *rflowp = rflow;
2716                         cpu = tcpu;
2717                         goto done;
2718                 }
2719         }
2720
2721         if (map) {
2722                 tcpu = map->cpus[((u64) skb->rxhash * map->len) >> 32];
2723
2724                 if (cpu_online(tcpu)) {
2725                         cpu = tcpu;
2726                         goto done;
2727                 }
2728         }
2729
2730 done:
2731         return cpu;
2732 }
2733
2734 #ifdef CONFIG_RFS_ACCEL
2735
2736 /**
2737  * rps_may_expire_flow - check whether an RFS hardware filter may be removed
2738  * @dev: Device on which the filter was set
2739  * @rxq_index: RX queue index
2740  * @flow_id: Flow ID passed to ndo_rx_flow_steer()
2741  * @filter_id: Filter ID returned by ndo_rx_flow_steer()
2742  *
2743  * Drivers that implement ndo_rx_flow_steer() should periodically call
2744  * this function for each installed filter and remove the filters for
2745  * which it returns %true.
2746  */
2747 bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index,
2748                          u32 flow_id, u16 filter_id)
2749 {
2750         struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index;
2751         struct rps_dev_flow_table *flow_table;
2752         struct rps_dev_flow *rflow;
2753         bool expire = true;
2754         int cpu;
2755
2756         rcu_read_lock();
2757         flow_table = rcu_dereference(rxqueue->rps_flow_table);
2758         if (flow_table && flow_id <= flow_table->mask) {
2759                 rflow = &flow_table->flows[flow_id];
2760                 cpu = ACCESS_ONCE(rflow->cpu);
2761                 if (rflow->filter == filter_id && cpu != RPS_NO_CPU &&
2762                     ((int)(per_cpu(softnet_data, cpu).input_queue_head -
2763                            rflow->last_qtail) <
2764                      (int)(10 * flow_table->mask)))
2765                         expire = false;
2766         }
2767         rcu_read_unlock();
2768         return expire;
2769 }
2770 EXPORT_SYMBOL(rps_may_expire_flow);
2771
2772 #endif /* CONFIG_RFS_ACCEL */
2773
2774 /* Called from hardirq (IPI) context */
2775 static void rps_trigger_softirq(void *data)
2776 {
2777         struct softnet_data *sd = data;
2778
2779         ____napi_schedule(sd, &sd->backlog);
2780         sd->received_rps++;
2781 }
2782
2783 #endif /* CONFIG_RPS */
2784
2785 /*
2786  * Check if this softnet_data structure is another cpu one
2787  * If yes, queue it to our IPI list and return 1
2788  * If no, return 0
2789  */
2790 static int rps_ipi_queued(struct softnet_data *sd)
2791 {
2792 #ifdef CONFIG_RPS
2793         struct softnet_data *mysd = &__get_cpu_var(softnet_data);
2794
2795         if (sd != mysd) {
2796                 sd->rps_ipi_next = mysd->rps_ipi_list;
2797                 mysd->rps_ipi_list = sd;
2798
2799                 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
2800                 return 1;
2801         }
2802 #endif /* CONFIG_RPS */
2803         return 0;
2804 }
2805
2806 /*
2807  * enqueue_to_backlog is called to queue an skb to a per CPU backlog
2808  * queue (may be a remote CPU queue).
2809  */
2810 static int enqueue_to_backlog(struct sk_buff *skb, int cpu,
2811                               unsigned int *qtail)
2812 {
2813         struct softnet_data *sd;
2814         unsigned long flags;
2815
2816         sd = &per_cpu(softnet_data, cpu);
2817
2818         local_irq_save(flags);
2819
2820         rps_lock(sd);
2821         if (skb_queue_len(&sd->input_pkt_queue) <= netdev_max_backlog) {
2822                 if (skb_queue_len(&sd->input_pkt_queue)) {
2823 enqueue:
2824                         __skb_queue_tail(&sd->input_pkt_queue, skb);
2825                         input_queue_tail_incr_save(sd, qtail);
2826                         rps_unlock(sd);
2827                         local_irq_restore(flags);
2828                         return NET_RX_SUCCESS;
2829                 }
2830
2831                 /* Schedule NAPI for backlog device
2832                  * We can use non atomic operation since we own the queue lock
2833                  */
2834                 if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state)) {
2835                         if (!rps_ipi_queued(sd))
2836                                 ____napi_schedule(sd, &sd->backlog);
2837                 }
2838                 goto enqueue;
2839         }
2840
2841         sd->dropped++;
2842         rps_unlock(sd);
2843
2844         local_irq_restore(flags);
2845
2846         atomic_long_inc(&skb->dev->rx_dropped);
2847         kfree_skb(skb);
2848         return NET_RX_DROP;
2849 }
2850
2851 /**
2852  *      netif_rx        -       post buffer to the network code
2853  *      @skb: buffer to post
2854  *
2855  *      This function receives a packet from a device driver and queues it for
2856  *      the upper (protocol) levels to process.  It always succeeds. The buffer
2857  *      may be dropped during processing for congestion control or by the
2858  *      protocol layers.
2859  *
2860  *      return values:
2861  *      NET_RX_SUCCESS  (no congestion)
2862  *      NET_RX_DROP     (packet was dropped)
2863  *
2864  */
2865
2866 int netif_rx(struct sk_buff *skb)
2867 {
2868         int ret;
2869
2870         /* if netpoll wants it, pretend we never saw it */
2871         if (netpoll_rx(skb))
2872                 return NET_RX_DROP;
2873
2874         if (netdev_tstamp_prequeue)
2875                 net_timestamp_check(skb);
2876
2877         trace_netif_rx(skb);
2878 #ifdef CONFIG_RPS
2879         {
2880                 struct rps_dev_flow voidflow, *rflow = &voidflow;
2881                 int cpu;
2882
2883                 preempt_disable();
2884                 rcu_read_lock();
2885
2886                 cpu = get_rps_cpu(skb->dev, skb, &rflow);
2887                 if (cpu < 0)
2888                         cpu = smp_processor_id();
2889
2890                 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
2891
2892                 rcu_read_unlock();
2893                 preempt_enable();
2894         }
2895 #else
2896         {
2897                 unsigned int qtail;
2898                 ret = enqueue_to_backlog(skb, get_cpu(), &qtail);
2899                 put_cpu();
2900         }
2901 #endif
2902         return ret;
2903 }
2904 EXPORT_SYMBOL(netif_rx);
2905
2906 int netif_rx_ni(struct sk_buff *skb)
2907 {
2908         int err;
2909
2910         preempt_disable();
2911         err = netif_rx(skb);
2912         if (local_softirq_pending())
2913                 do_softirq();
2914         preempt_enable();
2915
2916         return err;
2917 }
2918 EXPORT_SYMBOL(netif_rx_ni);
2919
2920 static void net_tx_action(struct softirq_action *h)
2921 {
2922         struct softnet_data *sd = &__get_cpu_var(softnet_data);
2923
2924         if (sd->completion_queue) {
2925                 struct sk_buff *clist;
2926
2927                 local_irq_disable();
2928                 clist = sd->completion_queue;
2929                 sd->completion_queue = NULL;
2930                 local_irq_enable();
2931
2932                 while (clist) {
2933                         struct sk_buff *skb = clist;
2934                         clist = clist->next;
2935
2936                         WARN_ON(atomic_read(&skb->users));
2937                         trace_kfree_skb(skb, net_tx_action);
2938                         __kfree_skb(skb);
2939                 }
2940         }
2941
2942         if (sd->output_queue) {
2943                 struct Qdisc *head;
2944
2945                 local_irq_disable();
2946                 head = sd->output_queue;
2947                 sd->output_queue = NULL;
2948                 sd->output_queue_tailp = &sd->output_queue;
2949                 local_irq_enable();
2950
2951                 while (head) {
2952                         struct Qdisc *q = head;
2953                         spinlock_t *root_lock;
2954
2955                         head = head->next_sched;
2956
2957                         root_lock = qdisc_lock(q);
2958                         if (spin_trylock(root_lock)) {
2959                                 smp_mb__before_clear_bit();
2960                                 clear_bit(__QDISC_STATE_SCHED,
2961                                           &q->state);
2962                                 qdisc_run(q);
2963                                 spin_unlock(root_lock);
2964                         } else {
2965                                 if (!test_bit(__QDISC_STATE_DEACTIVATED,
2966                                               &q->state)) {
2967                                         __netif_reschedule(q);
2968                                 } else {
2969                                         smp_mb__before_clear_bit();
2970                                         clear_bit(__QDISC_STATE_SCHED,
2971                                                   &q->state);
2972                                 }
2973                         }
2974                 }
2975         }
2976 }
2977
2978 #if (defined(CONFIG_BRIDGE) || defined(CONFIG_BRIDGE_MODULE)) && \
2979     (defined(CONFIG_ATM_LANE) || defined(CONFIG_ATM_LANE_MODULE))
2980 /* This hook is defined here for ATM LANE */
2981 int (*br_fdb_test_addr_hook)(struct net_device *dev,
2982                              unsigned char *addr) __read_mostly;
2983 EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook);
2984 #endif
2985
2986 #ifdef CONFIG_NET_CLS_ACT
2987 /* TODO: Maybe we should just force sch_ingress to be compiled in
2988  * when CONFIG_NET_CLS_ACT is? otherwise some useless instructions
2989  * a compare and 2 stores extra right now if we dont have it on
2990  * but have CONFIG_NET_CLS_ACT
2991  * NOTE: This doesn't stop any functionality; if you dont have
2992  * the ingress scheduler, you just can't add policies on ingress.
2993  *
2994  */
2995 static int ing_filter(struct sk_buff *skb, struct netdev_queue *rxq)
2996 {
2997         struct net_device *dev = skb->dev;
2998         u32 ttl = G_TC_RTTL(skb->tc_verd);
2999         int result = TC_ACT_OK;
3000         struct Qdisc *q;
3001
3002         if (unlikely(MAX_RED_LOOP < ttl++)) {
3003                 if (net_ratelimit())
3004                         pr_warning( "Redir loop detected Dropping packet (%d->%d)\n",
3005                                skb->skb_iif, dev->ifindex);
3006                 return TC_ACT_SHOT;
3007         }
3008
3009         skb->tc_verd = SET_TC_RTTL(skb->tc_verd, ttl);
3010         skb->tc_verd = SET_TC_AT(skb->tc_verd, AT_INGRESS);
3011
3012         q = rxq->qdisc;
3013         if (q != &noop_qdisc) {
3014                 spin_lock(qdisc_lock(q));
3015                 if (likely(!test_bit(__QDISC_STATE_DEACTIVATED, &q->state)))
3016                         result = qdisc_enqueue_root(skb, q);
3017                 spin_unlock(qdisc_lock(q));
3018         }
3019
3020         return result;
3021 }
3022
3023 static inline struct sk_buff *handle_ing(struct sk_buff *skb,
3024                                          struct packet_type **pt_prev,
3025                                          int *ret, struct net_device *orig_dev)
3026 {
3027         struct netdev_queue *rxq = rcu_dereference(skb->dev->ingress_queue);
3028
3029         if (!rxq || rxq->qdisc == &noop_qdisc)
3030                 goto out;
3031
3032         if (*pt_prev) {
3033                 *ret = deliver_skb(skb, *pt_prev, orig_dev);
3034                 *pt_prev = NULL;
3035         }
3036
3037         switch (ing_filter(skb, rxq)) {
3038         case TC_ACT_SHOT:
3039         case TC_ACT_STOLEN:
3040                 kfree_skb(skb);
3041                 return NULL;
3042         }
3043
3044 out:
3045         skb->tc_verd = 0;
3046         return skb;
3047 }
3048 #endif
3049
3050 /**
3051  *      netdev_rx_handler_register - register receive handler
3052  *      @dev: device to register a handler for
3053  *      @rx_handler: receive handler to register
3054  *      @rx_handler_data: data pointer that is used by rx handler
3055  *
3056  *      Register a receive hander for a device. This handler will then be
3057  *      called from __netif_receive_skb. A negative errno code is returned
3058  *      on a failure.
3059  *
3060  *      The caller must hold the rtnl_mutex.
3061  *
3062  *      For a general description of rx_handler, see enum rx_handler_result.
3063  */
3064 int netdev_rx_handler_register(struct net_device *dev,
3065                                rx_handler_func_t *rx_handler,
3066                                void *rx_handler_data)
3067 {
3068         ASSERT_RTNL();
3069
3070         if (dev->rx_handler)
3071                 return -EBUSY;
3072
3073         /* Note: rx_handler_data must be set before rx_handler */
3074         rcu_assign_pointer(dev->rx_handler_data, rx_handler_data);
3075         rcu_assign_pointer(dev->rx_handler, rx_handler);
3076
3077         return 0;
3078 }
3079 EXPORT_SYMBOL_GPL(netdev_rx_handler_register);
3080
3081 /**
3082  *      netdev_rx_handler_unregister - unregister receive handler
3083  *      @dev: device to unregister a handler from
3084  *
3085  *      Unregister a receive hander from a device.
3086  *
3087  *      The caller must hold the rtnl_mutex.
3088  */
3089 void netdev_rx_handler_unregister(struct net_device *dev)
3090 {
3091
3092         ASSERT_RTNL();
3093         rcu_assign_pointer(dev->rx_handler, NULL);
3094         /* a reader seeing a non NULL rx_handler in a rcu_read_lock()
3095          * section has a guarantee to see a non NULL rx_handler_data
3096          * as well.
3097          */
3098         synchronize_net();
3099         rcu_assign_pointer(dev->rx_handler_data, NULL);
3100 }
3101 EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister);
3102
3103 static int __netif_receive_skb(struct sk_buff *skb)
3104 {
3105         struct packet_type *ptype, *pt_prev;
3106         rx_handler_func_t *rx_handler;
3107         struct net_device *orig_dev;
3108         struct net_device *null_or_dev;
3109         bool deliver_exact = false;
3110         int ret = NET_RX_DROP;
3111         __be16 type;
3112
3113         if (!netdev_tstamp_prequeue)
3114                 net_timestamp_check(skb);
3115
3116         trace_netif_receive_skb(skb);
3117
3118         /* if we've gotten here through NAPI, check netpoll */
3119         if (netpoll_receive_skb(skb))
3120                 return NET_RX_DROP;
3121
3122         if (!skb->skb_iif)
3123                 skb->skb_iif = skb->dev->ifindex;
3124         orig_dev = skb->dev;
3125
3126         skb_reset_network_header(skb);
3127         skb_reset_transport_header(skb);
3128         skb_reset_mac_len(skb);
3129
3130         pt_prev = NULL;
3131
3132         rcu_read_lock();
3133
3134 another_round:
3135
3136         __this_cpu_inc(softnet_data.processed);
3137
3138         if (skb->protocol == cpu_to_be16(ETH_P_8021Q)) {
3139                 skb = vlan_untag(skb);
3140                 if (unlikely(!skb))
3141                         goto out;
3142         }
3143
3144 #ifdef CONFIG_NET_CLS_ACT
3145         if (skb->tc_verd & TC_NCLS) {
3146                 skb->tc_verd = CLR_TC_NCLS(skb->tc_verd);
3147                 goto ncls;
3148         }
3149 #endif
3150
3151         list_for_each_entry_rcu(ptype, &ptype_all, list) {
3152                 if (!ptype->dev || ptype->dev == skb->dev) {
3153                         if (pt_prev)
3154                                 ret = deliver_skb(skb, pt_prev, orig_dev);
3155                         pt_prev = ptype;
3156                 }
3157         }
3158
3159 #ifdef CONFIG_NET_CLS_ACT
3160         skb = handle_ing(skb, &pt_prev, &ret, orig_dev);
3161         if (!skb)
3162                 goto out;
3163 ncls:
3164 #endif
3165
3166         rx_handler = rcu_dereference(skb->dev->rx_handler);
3167         if (rx_handler) {
3168                 if (pt_prev) {
3169                         ret = deliver_skb(skb, pt_prev, orig_dev);
3170                         pt_prev = NULL;
3171                 }
3172                 switch (rx_handler(&skb)) {
3173                 case RX_HANDLER_CONSUMED:
3174                         ret = NET_RX_SUCCESS;
3175                         goto out;
3176                 case RX_HANDLER_ANOTHER:
3177                         goto another_round;
3178                 case RX_HANDLER_EXACT:
3179                         deliver_exact = true;
3180                 case RX_HANDLER_PASS:
3181                         break;
3182                 default:
3183                         BUG();
3184                 }
3185         }
3186
3187         if (vlan_tx_tag_present(skb)) {
3188                 if (pt_prev) {
3189                         ret = deliver_skb(skb, pt_prev, orig_dev);
3190                         pt_prev = NULL;
3191                 }
3192                 if (vlan_do_receive(&skb)) {
3193                         ret = __netif_receive_skb(skb);
3194                         goto out;
3195                 } else if (unlikely(!skb))
3196                         goto out;
3197         }
3198
3199         /* deliver only exact match when indicated */
3200         null_or_dev = deliver_exact ? skb->dev : NULL;
3201
3202         type = skb->protocol;
3203         list_for_each_entry_rcu(ptype,
3204                         &ptype_base[ntohs(type) & PTYPE_HASH_MASK], list) {
3205                 if (ptype->type == type &&
3206                     (ptype->dev == null_or_dev || ptype->dev == skb->dev ||
3207                      ptype->dev == orig_dev)) {
3208                         if (pt_prev)
3209                                 ret = deliver_skb(skb, pt_prev, orig_dev);
3210                         pt_prev = ptype;
3211                 }
3212         }
3213
3214         if (pt_prev) {
3215                 ret = pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
3216         } else {
3217                 atomic_long_inc(&skb->dev->rx_dropped);
3218                 kfree_skb(skb);
3219                 /* Jamal, now you will not able to escape explaining
3220                  * me how you were going to use this. :-)
3221                  */
3222                 ret = NET_RX_DROP;
3223         }
3224
3225 out:
3226         rcu_read_unlock();
3227         return ret;
3228 }
3229
3230 /**
3231  *      netif_receive_skb - process receive buffer from network
3232  *      @skb: buffer to process
3233  *
3234  *      netif_receive_skb() is the main receive data processing function.
3235  *      It always succeeds. The buffer may be dropped during processing
3236  *      for congestion control or by the protocol layers.
3237  *
3238  *      This function may only be called from softirq context and interrupts
3239  *      should be enabled.
3240  *
3241  *      Return values (usually ignored):
3242  *      NET_RX_SUCCESS: no congestion
3243  *      NET_RX_DROP: packet was dropped
3244  */
3245 int netif_receive_skb(struct sk_buff *skb)
3246 {
3247         if (netdev_tstamp_prequeue)
3248                 net_timestamp_check(skb);
3249
3250         if (skb_defer_rx_timestamp(skb))
3251                 return NET_RX_SUCCESS;
3252
3253 #ifdef CONFIG_RPS
3254         {
3255                 struct rps_dev_flow voidflow, *rflow = &voidflow;
3256                 int cpu, ret;
3257
3258                 rcu_read_lock();
3259
3260                 cpu = get_rps_cpu(skb->dev, skb, &rflow);
3261
3262                 if (cpu >= 0) {
3263                         ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
3264                         rcu_read_unlock();
3265                 } else {
3266                         rcu_read_unlock();
3267                         ret = __netif_receive_skb(skb);
3268                 }
3269
3270                 return ret;
3271         }
3272 #else
3273         return __netif_receive_skb(skb);
3274 #endif
3275 }
3276 EXPORT_SYMBOL(netif_receive_skb);
3277
3278 /* Network device is going away, flush any packets still pending
3279  * Called with irqs disabled.
3280  */
3281 static void flush_backlog(void *arg)
3282 {
3283         struct net_device *dev = arg;
3284         struct softnet_data *sd = &__get_cpu_var(softnet_data);
3285         struct sk_buff *skb, *tmp;
3286
3287         rps_lock(sd);
3288         skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) {
3289                 if (skb->dev == dev) {
3290                         __skb_unlink(skb, &sd->input_pkt_queue);
3291                         kfree_skb(skb);
3292                         input_queue_head_incr(sd);
3293                 }
3294         }
3295         rps_unlock(sd);
3296
3297         skb_queue_walk_safe(&sd->process_queue, skb, tmp) {
3298                 if (skb->dev == dev) {
3299                         __skb_unlink(skb, &sd->process_queue);
3300                         kfree_skb(skb);
3301                         input_queue_head_incr(sd);
3302                 }
3303         }
3304 }
3305
3306 static int napi_gro_complete(struct sk_buff *skb)
3307 {
3308         struct packet_type *ptype;
3309         __be16 type = skb->protocol;
3310         struct list_head *head = &ptype_base[ntohs(type) & PTYPE_HASH_MASK];
3311         int err = -ENOENT;
3312
3313         if (NAPI_GRO_CB(skb)->count == 1) {
3314                 skb_shinfo(skb)->gso_size = 0;
3315                 goto out;
3316         }
3317
3318         rcu_read_lock();
3319         list_for_each_entry_rcu(ptype, head, list) {
3320                 if (ptype->type != type || ptype->dev || !ptype->gro_complete)
3321                         continue;
3322
3323                 err = ptype->gro_complete(skb);
3324                 break;
3325         }
3326         rcu_read_unlock();
3327
3328         if (err) {
3329                 WARN_ON(&ptype->list == head);
3330                 kfree_skb(skb);
3331                 return NET_RX_SUCCESS;
3332         }
3333
3334 out:
3335         return netif_receive_skb(skb);
3336 }
3337
3338 inline void napi_gro_flush(struct napi_struct *napi)
3339 {
3340         struct sk_buff *skb, *next;
3341
3342         for (skb = napi->gro_list; skb; skb = next) {
3343                 next = skb->next;
3344                 skb->next = NULL;
3345                 napi_gro_complete(skb);
3346         }
3347
3348         napi->gro_count = 0;
3349         napi->gro_list = NULL;
3350 }
3351 EXPORT_SYMBOL(napi_gro_flush);
3352
3353 enum gro_result dev_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
3354 {
3355         struct sk_buff **pp = NULL;
3356         struct packet_type *ptype;
3357         __be16 type = skb->protocol;
3358         struct list_head *head = &ptype_base[ntohs(type) & PTYPE_HASH_MASK];
3359         int same_flow;
3360         int mac_len;
3361         enum gro_result ret;
3362
3363         if (!(skb->dev->features & NETIF_F_GRO) || netpoll_rx_on(skb))
3364                 goto normal;
3365
3366         if (skb_is_gso(skb) || skb_has_frag_list(skb))
3367                 goto normal;
3368
3369         rcu_read_lock();
3370         list_for_each_entry_rcu(ptype, head, list) {
3371                 if (ptype->type != type || ptype->dev || !ptype->gro_receive)
3372                         continue;
3373
3374                 skb_set_network_header(skb, skb_gro_offset(skb));
3375                 mac_len = skb->network_header - skb->mac_header;
3376                 skb->mac_len = mac_len;
3377                 NAPI_GRO_CB(skb)->same_flow = 0;
3378                 NAPI_GRO_CB(skb)->flush = 0;
3379                 NAPI_GRO_CB(skb)->free = 0;
3380
3381                 pp = ptype->gro_receive(&napi->gro_list, skb);
3382                 break;
3383         }
3384         rcu_read_unlock();
3385
3386         if (&ptype->list == head)
3387                 goto normal;
3388
3389         same_flow = NAPI_GRO_CB(skb)->same_flow;
3390         ret = NAPI_GRO_CB(skb)->free ? GRO_MERGED_FREE : GRO_MERGED;
3391
3392         if (pp) {
3393                 struct sk_buff *nskb = *pp;
3394
3395                 *pp = nskb->next;
3396                 nskb->next = NULL;
3397                 napi_gro_complete(nskb);
3398                 napi->gro_count--;
3399         }
3400
3401         if (same_flow)
3402                 goto ok;
3403
3404         if (NAPI_GRO_CB(skb)->flush || napi->gro_count >= MAX_GRO_SKBS)
3405                 goto normal;
3406
3407         napi->gro_count++;
3408         NAPI_GRO_CB(skb)->count = 1;
3409         skb_shinfo(skb)->gso_size = skb_gro_len(skb);
3410         skb->next = napi->gro_list;
3411         napi->gro_list = skb;
3412         ret = GRO_HELD;
3413
3414 pull:
3415         if (skb_headlen(skb) < skb_gro_offset(skb)) {
3416                 int grow = skb_gro_offset(skb) - skb_headlen(skb);
3417
3418                 BUG_ON(skb->end - skb->tail < grow);
3419
3420                 memcpy(skb_tail_pointer(skb), NAPI_GRO_CB(skb)->frag0, grow);
3421
3422                 skb->tail += grow;
3423                 skb->data_len -= grow;
3424
3425                 skb_shinfo(skb)->frags[0].page_offset += grow;
3426                 skb_shinfo(skb)->frags[0].size -= grow;
3427
3428                 if (unlikely(!skb_shinfo(skb)->frags[0].size)) {
3429                         put_page(skb_shinfo(skb)->frags[0].page);
3430                         memmove(skb_shinfo(skb)->frags,
3431                                 skb_shinfo(skb)->frags + 1,
3432                                 --skb_shinfo(skb)->nr_frags * sizeof(skb_frag_t));
3433                 }
3434         }
3435
3436 ok:
3437         return ret;
3438
3439 normal:
3440         ret = GRO_NORMAL;
3441         goto pull;
3442 }
3443 EXPORT_SYMBOL(dev_gro_receive);
3444
3445 static inline gro_result_t
3446 __napi_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
3447 {
3448         struct sk_buff *p;
3449         unsigned int maclen = skb->dev->hard_header_len;
3450
3451         for (p = napi->gro_list; p; p = p->next) {
3452                 unsigned long diffs;
3453
3454                 diffs = (unsigned long)p->dev ^ (unsigned long)skb->dev;
3455                 diffs |= p->vlan_tci ^ skb->vlan_tci;
3456                 if (maclen == ETH_HLEN)
3457                         diffs |= compare_ether_header(skb_mac_header(p),
3458                                                       skb_gro_mac_header(skb));
3459                 else if (!diffs)
3460                         diffs = memcmp(skb_mac_header(p),
3461                                        skb_gro_mac_header(skb),
3462                                        maclen);
3463                 NAPI_GRO_CB(p)->same_flow = !diffs;
3464                 NAPI_GRO_CB(p)->flush = 0;
3465         }
3466
3467         return dev_gro_receive(napi, skb);
3468 }
3469
3470 gro_result_t napi_skb_finish(gro_result_t ret, struct sk_buff *skb)
3471 {
3472         switch (ret) {
3473         case GRO_NORMAL:
3474                 if (netif_receive_skb(skb))
3475                         ret = GRO_DROP;
3476                 break;
3477
3478         case GRO_DROP:
3479         case GRO_MERGED_FREE:
3480                 kfree_skb(skb);
3481                 break;
3482
3483         case GRO_HELD:
3484         case GRO_MERGED:
3485                 break;
3486         }
3487
3488         return ret;
3489 }
3490 EXPORT_SYMBOL(napi_skb_finish);
3491
3492 void skb_gro_reset_offset(struct sk_buff *skb)
3493 {
3494         NAPI_GRO_CB(skb)->data_offset = 0;
3495         NAPI_GRO_CB(skb)->frag0 = NULL;
3496         NAPI_GRO_CB(skb)->frag0_len = 0;
3497
3498         if (skb->mac_header == skb->tail &&
3499             !PageHighMem(skb_shinfo(skb)->frags[0].page)) {
3500                 NAPI_GRO_CB(skb)->frag0 =
3501                         page_address(skb_shinfo(skb)->frags[0].page) +
3502                         skb_shinfo(skb)->frags[0].page_offset;
3503                 NAPI_GRO_CB(skb)->frag0_len = skb_shinfo(skb)->frags[0].size;
3504         }
3505 }
3506 EXPORT_SYMBOL(skb_gro_reset_offset);
3507
3508 gro_result_t napi_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
3509 {
3510         skb_gro_reset_offset(skb);
3511
3512         return napi_skb_finish(__napi_gro_receive(napi, skb), skb);
3513 }
3514 EXPORT_SYMBOL(napi_gro_receive);
3515
3516 static void napi_reuse_skb(struct napi_struct *napi, struct sk_buff *skb)
3517 {
3518         __skb_pull(skb, skb_headlen(skb));
3519         /* restore the reserve we had after netdev_alloc_skb_ip_align() */
3520         skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN - skb_headroom(skb));
3521         skb->vlan_tci = 0;
3522         skb->dev = napi->dev;
3523         skb->skb_iif = 0;
3524
3525         napi->skb = skb;
3526 }
3527
3528 struct sk_buff *napi_get_frags(struct napi_struct *napi)
3529 {
3530         struct sk_buff *skb = napi->skb;
3531
3532         if (!skb) {
3533                 skb = netdev_alloc_skb_ip_align(napi->dev, GRO_MAX_HEAD);
3534                 if (skb)
3535                         napi->skb = skb;
3536         }
3537         return skb;
3538 }
3539 EXPORT_SYMBOL(napi_get_frags);
3540
3541 gro_result_t napi_frags_finish(struct napi_struct *napi, struct sk_buff *skb,
3542                                gro_result_t ret)
3543 {
3544         switch (ret) {
3545         case GRO_NORMAL:
3546         case GRO_HELD:
3547                 skb->protocol = eth_type_trans(skb, skb->dev);
3548
3549                 if (ret == GRO_HELD)
3550                         skb_gro_pull(skb, -ETH_HLEN);
3551                 else if (netif_receive_skb(skb))
3552                         ret = GRO_DROP;
3553                 break;
3554
3555         case GRO_DROP:
3556         case GRO_MERGED_FREE:
3557                 napi_reuse_skb(napi, skb);
3558                 break;
3559
3560         case GRO_MERGED:
3561                 break;
3562         }
3563
3564         return ret;
3565 }
3566 EXPORT_SYMBOL(napi_frags_finish);
3567
3568 struct sk_buff *napi_frags_skb(struct napi_struct *napi)
3569 {
3570         struct sk_buff *skb = napi->skb;
3571         struct ethhdr *eth;
3572         unsigned int hlen;
3573         unsigned int off;
3574
3575         napi->skb = NULL;
3576
3577         skb_reset_mac_header(skb);
3578         skb_gro_reset_offset(skb);
3579
3580         off = skb_gro_offset(skb);
3581         hlen = off + sizeof(*eth);
3582         eth = skb_gro_header_fast(skb, off);
3583         if (skb_gro_header_hard(skb, hlen)) {
3584                 eth = skb_gro_header_slow(skb, hlen, off);
3585                 if (unlikely(!eth)) {
3586                         napi_reuse_skb(napi, skb);
3587                         skb = NULL;
3588                         goto out;
3589                 }
3590         }
3591
3592         skb_gro_pull(skb, sizeof(*eth));
3593
3594         /*
3595          * This works because the only protocols we care about don't require
3596          * special handling.  We'll fix it up properly at the end.
3597          */
3598         skb->protocol = eth->h_proto;
3599
3600 out:
3601         return skb;
3602 }
3603 EXPORT_SYMBOL(napi_frags_skb);
3604
3605 gro_result_t napi_gro_frags(struct napi_struct *napi)
3606 {
3607         struct sk_buff *skb = napi_frags_skb(napi);
3608
3609         if (!skb)
3610                 return GRO_DROP;
3611
3612         return napi_frags_finish(napi, skb, __napi_gro_receive(napi, skb));
3613 }
3614 EXPORT_SYMBOL(napi_gro_frags);
3615
3616 /*
3617  * net_rps_action sends any pending IPI's for rps.
3618  * Note: called with local irq disabled, but exits with local irq enabled.
3619  */
3620 static void net_rps_action_and_irq_enable(struct softnet_data *sd)
3621 {
3622 #ifdef CONFIG_RPS
3623         struct softnet_data *remsd = sd->rps_ipi_list;
3624
3625         if (remsd) {
3626                 sd->rps_ipi_list = NULL;
3627
3628                 local_irq_enable();
3629
3630                 /* Send pending IPI's to kick RPS processing on remote cpus. */
3631                 while (remsd) {
3632                         struct softnet_data *next = remsd->rps_ipi_next;
3633
3634                         if (cpu_online(remsd->cpu))
3635                                 __smp_call_function_single(remsd->cpu,
3636                                                            &remsd->csd, 0);
3637                         remsd = next;
3638                 }
3639         } else
3640 #endif
3641                 local_irq_enable();
3642 }
3643
3644 static int process_backlog(struct napi_struct *napi, int quota)
3645 {
3646         int work = 0;
3647         struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
3648
3649 #ifdef CONFIG_RPS
3650         /* Check if we have pending ipi, its better to send them now,
3651          * not waiting net_rx_action() end.
3652          */
3653         if (sd->rps_ipi_list) {
3654                 local_irq_disable();
3655                 net_rps_action_and_irq_enable(sd);
3656         }
3657 #endif
3658         napi->weight = weight_p;
3659         local_irq_disable();
3660         while (work < quota) {
3661                 struct sk_buff *skb;
3662                 unsigned int qlen;
3663
3664                 while ((skb = __skb_dequeue(&sd->process_queue))) {
3665                         local_irq_enable();
3666                         __netif_receive_skb(skb);
3667                         local_irq_disable();
3668                         input_queue_head_incr(sd);
3669                         if (++work >= quota) {
3670                                 local_irq_enable();
3671                                 return work;
3672                         }
3673                 }
3674
3675                 rps_lock(sd);
3676                 qlen = skb_queue_len(&sd->input_pkt_queue);
3677                 if (qlen)
3678                         skb_queue_splice_tail_init(&sd->input_pkt_queue,
3679                                                    &sd->process_queue);
3680
3681                 if (qlen < quota - work) {
3682                         /*
3683                          * Inline a custom version of __napi_complete().
3684                          * only current cpu owns and manipulates this napi,
3685                          * and NAPI_STATE_SCHED is the only possible flag set on backlog.
3686                          * we can use a plain write instead of clear_bit(),
3687                          * and we dont need an smp_mb() memory barrier.
3688                          */
3689                         list_del(&napi->poll_list);
3690                         napi->state = 0;
3691
3692                         quota = work + qlen;
3693                 }
3694                 rps_unlock(sd);
3695         }
3696         local_irq_enable();
3697
3698         return work;
3699 }
3700
3701 /**
3702  * __napi_schedule - schedule for receive
3703  * @n: entry to schedule
3704  *
3705  * The entry's receive function will be scheduled to run
3706  */
3707 void __napi_schedule(struct napi_struct *n)
3708 {
3709         unsigned long flags;
3710
3711         local_irq_save(flags);
3712         ____napi_schedule(&__get_cpu_var(softnet_data), n);
3713         local_irq_restore(flags);
3714 }
3715 EXPORT_SYMBOL(__napi_schedule);
3716
3717 void __napi_complete(struct napi_struct *n)
3718 {
3719         BUG_ON(!test_bit(NAPI_STATE_SCHED, &n->state));
3720         BUG_ON(n->gro_list);
3721
3722         list_del(&n->poll_list);
3723         smp_mb__before_clear_bit();
3724         clear_bit(NAPI_STATE_SCHED, &n->state);
3725 }
3726 EXPORT_SYMBOL(__napi_complete);
3727
3728 void napi_complete(struct napi_struct *n)
3729 {
3730         unsigned long flags;
3731
3732         /*
3733          * don't let napi dequeue from the cpu poll list
3734          * just in case its running on a different cpu
3735          */
3736         if (unlikely(test_bit(NAPI_STATE_NPSVC, &n->state)))
3737                 return;
3738
3739         napi_gro_flush(n);
3740         local_irq_save(flags);
3741         __napi_complete(n);
3742         local_irq_restore(flags);
3743 }
3744 EXPORT_SYMBOL(napi_complete);
3745
3746 void netif_napi_add(struct net_device *dev, struct napi_struct *napi,
3747                     int (*poll)(struct napi_struct *, int), int weight)
3748 {
3749         INIT_LIST_HEAD(&napi->poll_list);
3750         napi->gro_count = 0;
3751         napi->gro_list = NULL;
3752         napi->skb = NULL;
3753         napi->poll = poll;
3754         napi->weight = weight;
3755         list_add(&napi->dev_list, &dev->napi_list);
3756         napi->dev = dev;
3757 #ifdef CONFIG_NETPOLL
3758         spin_lock_init(&napi->poll_lock);
3759         napi->poll_owner = -1;
3760 #endif
3761         set_bit(NAPI_STATE_SCHED, &napi->state);
3762 }
3763 EXPORT_SYMBOL(netif_napi_add);
3764
3765 void netif_napi_del(struct napi_struct *napi)
3766 {
3767         struct sk_buff *skb, *next;
3768
3769         list_del_init(&napi->dev_list);
3770         napi_free_frags(napi);
3771
3772         for (skb = napi->gro_list; skb; skb = next) {
3773                 next = skb->next;
3774                 skb->next = NULL;
3775                 kfree_skb(skb);
3776         }
3777
3778         napi->gro_list = NULL;
3779         napi->gro_count = 0;
3780 }
3781 EXPORT_SYMBOL(netif_napi_del);
3782
3783 static void net_rx_action(struct softirq_action *h)
3784 {
3785         struct softnet_data *sd = &__get_cpu_var(softnet_data);
3786         unsigned long time_limit = jiffies + 2;
3787         int budget = netdev_budget;
3788         void *have;
3789
3790         local_irq_disable();
3791
3792         while (!list_empty(&sd->poll_list)) {
3793                 struct napi_struct *n;
3794                 int work, weight;
3795
3796                 /* If softirq window is exhuasted then punt.
3797                  * Allow this to run for 2 jiffies since which will allow
3798                  * an average latency of 1.5/HZ.
3799                  */
3800                 if (unlikely(budget <= 0 || time_after(jiffies, time_limit)))
3801                         goto softnet_break;
3802
3803                 local_irq_enable();
3804
3805                 /* Even though interrupts have been re-enabled, this
3806                  * access is safe because interrupts can only add new
3807                  * entries to the tail of this list, and only ->poll()
3808                  * calls can remove this head entry from the list.
3809                  */
3810                 n = list_first_entry(&sd->poll_list, struct napi_struct, poll_list);
3811
3812                 have = netpoll_poll_lock(n);
3813
3814                 weight = n->weight;
3815
3816                 /* This NAPI_STATE_SCHED test is for avoiding a race
3817                  * with netpoll's poll_napi().  Only the entity which
3818                  * obtains the lock and sees NAPI_STATE_SCHED set will
3819                  * actually make the ->poll() call.  Therefore we avoid
3820                  * accidentally calling ->poll() when NAPI is not scheduled.
3821                  */
3822                 work = 0;
3823                 if (test_bit(NAPI_STATE_SCHED, &n->state)) {
3824                         work = n->poll(n, weight);
3825                         trace_napi_poll(n);
3826                 }
3827
3828                 WARN_ON_ONCE(work > weight);
3829
3830                 budget -= work;
3831
3832                 local_irq_disable();
3833
3834                 /* Drivers must not modify the NAPI state if they
3835                  * consume the entire weight.  In such cases this code
3836                  * still "owns" the NAPI instance and therefore can
3837                  * move the instance around on the list at-will.
3838                  */
3839                 if (unlikely(work == weight)) {
3840                         if (unlikely(napi_disable_pending(n))) {
3841                                 local_irq_enable();
3842                                 napi_complete(n);
3843                                 local_irq_disable();
3844                         } else
3845                                 list_move_tail(&n->poll_list, &sd->poll_list);
3846                 }
3847
3848                 netpoll_poll_unlock(have);
3849         }
3850 out:
3851         net_rps_action_and_irq_enable(sd);
3852
3853 #ifdef CONFIG_NET_DMA
3854         /*
3855          * There may not be any more sk_buffs coming right now, so push
3856          * any pending DMA copies to hardware
3857          */
3858         dma_issue_pending_all();
3859 #endif
3860
3861         return;
3862
3863 softnet_break:
3864         sd->time_squeeze++;
3865         __raise_softirq_irqoff(NET_RX_SOFTIRQ);
3866         goto out;
3867 }
3868
3869 static gifconf_func_t *gifconf_list[NPROTO];
3870
3871 /**
3872  *      register_gifconf        -       register a SIOCGIF handler
3873  *      @family: Address family
3874  *      @gifconf: Function handler
3875  *
3876  *      Register protocol dependent address dumping routines. The handler
3877  *      that is passed must not be freed or reused until it has been replaced
3878  *      by another handler.
3879  */
3880 int register_gifconf(unsigned int family, gifconf_func_t *gifconf)
3881 {
3882         if (family >= NPROTO)
3883                 return -EINVAL;
3884         gifconf_list[family] = gifconf;
3885         return 0;
3886 }
3887 EXPORT_SYMBOL(register_gifconf);
3888
3889
3890 /*
3891  *      Map an interface index to its name (SIOCGIFNAME)
3892  */
3893
3894 /*
3895  *      We need this ioctl for efficient implementation of the
3896  *      if_indextoname() function required by the IPv6 API.  Without
3897  *      it, we would have to search all the interfaces to find a
3898  *      match.  --pb
3899  */
3900
3901 static int dev_ifname(struct net *net, struct ifreq __user *arg)
3902 {
3903         struct net_device *dev;
3904         struct ifreq ifr;
3905
3906         /*
3907          *      Fetch the caller's info block.
3908          */
3909
3910         if (copy_from_user(&ifr, arg, sizeof(struct ifreq)))
3911                 return -EFAULT;
3912
3913         rcu_read_lock();
3914         dev = dev_get_by_index_rcu(net, ifr.ifr_ifindex);
3915         if (!dev) {
3916                 rcu_read_unlock();
3917                 return -ENODEV;
3918         }
3919
3920         strcpy(ifr.ifr_name, dev->name);
3921         rcu_read_unlock();
3922
3923         if (copy_to_user(arg, &ifr, sizeof(struct ifreq)))
3924                 return -EFAULT;
3925         return 0;
3926 }
3927
3928 /*
3929  *      Perform a SIOCGIFCONF call. This structure will change
3930  *      size eventually, and there is nothing I can do about it.
3931  *      Thus we will need a 'compatibility mode'.
3932  */
3933
3934 static int dev_ifconf(struct net *net, char __user *arg)
3935 {
3936         struct ifconf ifc;
3937         struct net_device *dev;
3938         char __user *pos;
3939         int len;
3940         int total;
3941         int i;
3942
3943         /*
3944          *      Fetch the caller's info block.
3945          */
3946
3947         if (copy_from_user(&ifc, arg, sizeof(struct ifconf)))
3948                 return -EFAULT;
3949
3950         pos = ifc.ifc_buf;
3951         len = ifc.ifc_len;
3952
3953         /*
3954          *      Loop over the interfaces, and write an info block for each.
3955          */
3956
3957         total = 0;
3958         for_each_netdev(net, dev) {
3959                 for (i = 0; i < NPROTO; i++) {
3960                         if (gifconf_list[i]) {
3961                                 int done;
3962                                 if (!pos)
3963                                         done = gifconf_list[i](dev, NULL, 0);
3964                                 else
3965                                         done = gifconf_list[i](dev, pos + total,
3966                                                                len - total);
3967                                 if (done < 0)
3968                                         return -EFAULT;
3969                                 total += done;
3970                         }
3971                 }
3972         }
3973
3974         /*
3975          *      All done.  Write the updated control block back to the caller.
3976          */
3977         ifc.ifc_len = total;
3978
3979         /*
3980          *      Both BSD and Solaris return 0 here, so we do too.
3981          */
3982         return copy_to_user(arg, &ifc, sizeof(struct ifconf)) ? -EFAULT : 0;
3983 }
3984
3985 #ifdef CONFIG_PROC_FS
3986 /*
3987  *      This is invoked by the /proc filesystem handler to display a device
3988  *      in detail.
3989  */
3990 void *dev_seq_start(struct seq_file *seq, loff_t *pos)
3991         __acquires(RCU)
3992 {
3993         struct net *net = seq_file_net(seq);
3994         loff_t off;
3995         struct net_device *dev;
3996
3997         rcu_read_lock();
3998         if (!*pos)
3999                 return SEQ_START_TOKEN;
4000
4001         off = 1;
4002         for_each_netdev_rcu(net, dev)
4003                 if (off++ == *pos)
4004                         return dev;
4005
4006         return NULL;
4007 }
4008
4009 void *dev_seq_next(struct seq_file *seq, void *v, loff_t *pos)
4010 {
4011         struct net_device *dev = v;
4012
4013         if (v == SEQ_START_TOKEN)
4014                 dev = first_net_device_rcu(seq_file_net(seq));
4015         else
4016                 dev = next_net_device_rcu(dev);
4017
4018         ++*pos;
4019         return dev;
4020 }
4021
4022 void dev_seq_stop(struct seq_file *seq, void *v)
4023         __releases(RCU)
4024 {
4025         rcu_read_unlock();
4026 }
4027
4028 static void dev_seq_printf_stats(struct seq_file *seq, struct net_device *dev)
4029 {
4030         struct rtnl_link_stats64 temp;
4031         const struct rtnl_link_stats64 *stats = dev_get_stats(dev, &temp);
4032
4033         seq_printf(seq, "%6s: %7llu %7llu %4llu %4llu %4llu %5llu %10llu %9llu "
4034                    "%8llu %7llu %4llu %4llu %4llu %5llu %7llu %10llu\n",
4035                    dev->name, stats->rx_bytes, stats->rx_packets,
4036                    stats->rx_errors,
4037                    stats->rx_dropped + stats->rx_missed_errors,
4038                    stats->rx_fifo_errors,
4039                    stats->rx_length_errors + stats->rx_over_errors +
4040                     stats->rx_crc_errors + stats->rx_frame_errors,
4041                    stats->rx_compressed, stats->multicast,
4042                    stats->tx_bytes, stats->tx_packets,
4043                    stats->tx_errors, stats->tx_dropped,
4044                    stats->tx_fifo_errors, stats->collisions,
4045                    stats->tx_carrier_errors +
4046                     stats->tx_aborted_errors +
4047                     stats->tx_window_errors +
4048                     stats->tx_heartbeat_errors,
4049                    stats->tx_compressed);
4050 }
4051
4052 /*
4053  *      Called from the PROCfs module. This now uses the new arbitrary sized
4054  *      /proc/net interface to create /proc/net/dev
4055  */
4056 static int dev_seq_show(struct seq_file *seq, void *v)
4057 {
4058         if (v == SEQ_START_TOKEN)
4059                 seq_puts(seq, "Inter-|   Receive                            "
4060                               "                    |  Transmit\n"
4061                               " face |bytes    packets errs drop fifo frame "
4062                               "compressed multicast|bytes    packets errs "
4063                               "drop fifo colls carrier compressed\n");
4064         else
4065                 dev_seq_printf_stats(seq, v);
4066         return 0;
4067 }
4068
4069 static struct softnet_data *softnet_get_online(loff_t *pos)
4070 {
4071         struct softnet_data *sd = NULL;
4072
4073         while (*pos < nr_cpu_ids)
4074                 if (cpu_online(*pos)) {
4075                         sd = &per_cpu(softnet_data, *pos);
4076                         break;
4077                 } else
4078                         ++*pos;
4079         return sd;
4080 }
4081
4082 static void *softnet_seq_start(struct seq_file *seq, loff_t *pos)
4083 {
4084         return softnet_get_online(pos);
4085 }
4086
4087 static void *softnet_seq_next(struct seq_file *seq, void *v, loff_t *pos)
4088 {
4089         ++*pos;
4090         return softnet_get_online(pos);
4091 }
4092
4093 static void softnet_seq_stop(struct seq_file *seq, void *v)
4094 {
4095 }
4096
4097 static int softnet_seq_show(struct seq_file *seq, void *v)
4098 {
4099         struct softnet_data *sd = v;
4100
4101         seq_printf(seq, "%08x %08x %08x %08x %08x %08x %08x %08x %08x %08x\n",
4102                    sd->processed, sd->dropped, sd->time_squeeze, 0,
4103                    0, 0, 0, 0, /* was fastroute */
4104                    sd->cpu_collision, sd->received_rps);
4105         return 0;
4106 }
4107
4108 static const struct seq_operations dev_seq_ops = {
4109         .start = dev_seq_start,
4110         .next  = dev_seq_next,
4111         .stop  = dev_seq_stop,
4112         .show  = dev_seq_show,
4113 };
4114
4115 static int dev_seq_open(struct inode *inode, struct file *file)
4116 {
4117         return seq_open_net(inode, file, &dev_seq_ops,
4118                             sizeof(struct seq_net_private));
4119 }
4120
4121 static const struct file_operations dev_seq_fops = {
4122         .owner   = THIS_MODULE,
4123         .open    = dev_seq_open,
4124         .read    = seq_read,
4125         .llseek  = seq_lseek,
4126         .release = seq_release_net,
4127 };
4128
4129 static const struct seq_operations softnet_seq_ops = {
4130         .start = softnet_seq_start,
4131         .next  = softnet_seq_next,
4132         .stop  = softnet_seq_stop,
4133         .show  = softnet_seq_show,
4134 };
4135
4136 static int softnet_seq_open(struct inode *inode, struct file *file)
4137 {
4138         return seq_open(file, &softnet_seq_ops);
4139 }
4140
4141 static const struct file_operations softnet_seq_fops = {
4142         .owner   = THIS_MODULE,
4143         .open    = softnet_seq_open,
4144         .read    = seq_read,
4145         .llseek  = seq_lseek,
4146         .release = seq_release,
4147 };
4148
4149 static void *ptype_get_idx(loff_t pos)
4150 {
4151         struct packet_type *pt = NULL;
4152         loff_t i = 0;
4153         int t;
4154
4155         list_for_each_entry_rcu(pt, &ptype_all, list) {
4156                 if (i == pos)
4157                         return pt;
4158                 ++i;
4159         }
4160
4161         for (t = 0; t < PTYPE_HASH_SIZE; t++) {
4162                 list_for_each_entry_rcu(pt, &ptype_base[t], list) {
4163                         if (i == pos)
4164                                 return pt;
4165                         ++i;
4166                 }
4167         }
4168         return NULL;
4169 }
4170
4171 static void *ptype_seq_start(struct seq_file *seq, loff_t *pos)
4172         __acquires(RCU)
4173 {
4174         rcu_read_lock();
4175         return *pos ? ptype_get_idx(*pos - 1) : SEQ_START_TOKEN;
4176 }
4177
4178 static void *ptype_seq_next(struct seq_file *seq, void *v, loff_t *pos)
4179 {
4180         struct packet_type *pt;
4181         struct list_head *nxt;
4182         int hash;
4183
4184         ++*pos;
4185         if (v == SEQ_START_TOKEN)
4186                 return ptype_get_idx(0);
4187
4188         pt = v;
4189         nxt = pt->list.next;
4190         if (pt->type == htons(ETH_P_ALL)) {
4191                 if (nxt != &ptype_all)
4192                         goto found;
4193                 hash = 0;
4194                 nxt = ptype_base[0].next;
4195         } else
4196                 hash = ntohs(pt->type) & PTYPE_HASH_MASK;
4197
4198         while (nxt == &ptype_base[hash]) {
4199                 if (++hash >= PTYPE_HASH_SIZE)
4200                         return NULL;
4201                 nxt = ptype_base[hash].next;
4202         }
4203 found:
4204         return list_entry(nxt, struct packet_type, list);
4205 }
4206
4207 static void ptype_seq_stop(struct seq_file *seq, void *v)
4208         __releases(RCU)
4209 {
4210         rcu_read_unlock();
4211 }
4212
4213 static int ptype_seq_show(struct seq_file *seq, void *v)
4214 {
4215         struct packet_type *pt = v;
4216
4217         if (v == SEQ_START_TOKEN)
4218                 seq_puts(seq, "Type Device      Function\n");
4219         else if (pt->dev == NULL || dev_net(pt->dev) == seq_file_net(seq)) {
4220                 if (pt->type == htons(ETH_P_ALL))
4221                         seq_puts(seq, "ALL ");
4222                 else
4223                         seq_printf(seq, "%04x", ntohs(pt->type));
4224
4225                 seq_printf(seq, " %-8s %pF\n",
4226                            pt->dev ? pt->dev->name : "", pt->func);
4227         }
4228
4229         return 0;
4230 }
4231
4232 static const struct seq_operations ptype_seq_ops = {
4233         .start = ptype_seq_start,
4234         .next  = ptype_seq_next,
4235         .stop  = ptype_seq_stop,
4236         .show  = ptype_seq_show,
4237 };
4238
4239 static int ptype_seq_open(struct inode *inode, struct file *file)
4240 {
4241         return seq_open_net(inode, file, &ptype_seq_ops,
4242                         sizeof(struct seq_net_private));
4243 }
4244
4245 static const struct file_operations ptype_seq_fops = {
4246         .owner   = THIS_MODULE,
4247         .open    = ptype_seq_open,
4248         .read    = seq_read,
4249         .llseek  = seq_lseek,
4250         .release = seq_release_net,
4251 };
4252
4253
4254 static int __net_init dev_proc_net_init(struct net *net)
4255 {
4256         int rc = -ENOMEM;
4257
4258         if (!proc_net_fops_create(net, "dev", S_IRUGO, &dev_seq_fops))
4259                 goto out;
4260         if (!proc_net_fops_create(net, "softnet_stat", S_IRUGO, &softnet_seq_fops))
4261                 goto out_dev;
4262         if (!proc_net_fops_create(net, "ptype", S_IRUGO, &ptype_seq_fops))
4263                 goto out_softnet;
4264
4265         if (wext_proc_init(net))
4266                 goto out_ptype;
4267         rc = 0;
4268 out:
4269         return rc;
4270 out_ptype:
4271         proc_net_remove(net, "ptype");
4272 out_softnet:
4273         proc_net_remove(net, "softnet_stat");
4274 out_dev:
4275         proc_net_remove(net, "dev");
4276         goto out;
4277 }
4278
4279 static void __net_exit dev_proc_net_exit(struct net *net)
4280 {
4281         wext_proc_exit(net);
4282
4283         proc_net_remove(net, "ptype");
4284         proc_net_remove(net, "softnet_stat");
4285         proc_net_remove(net, "dev");
4286 }
4287
4288 static struct pernet_operations __net_initdata dev_proc_ops = {
4289         .init = dev_proc_net_init,
4290         .exit = dev_proc_net_exit,
4291 };
4292
4293 static int __init dev_proc_init(void)
4294 {
4295         return register_pernet_subsys(&dev_proc_ops);
4296 }
4297 #else
4298 #define dev_proc_init() 0
4299 #endif  /* CONFIG_PROC_FS */
4300
4301
4302 /**
4303  *      netdev_set_master       -       set up master pointer
4304  *      @slave: slave device
4305  *      @master: new master device
4306  *
4307  *      Changes the master device of the slave. Pass %NULL to break the
4308  *      bonding. The caller must hold the RTNL semaphore. On a failure
4309  *      a negative errno code is returned. On success the reference counts
4310  *      are adjusted and the function returns zero.
4311  */
4312 int netdev_set_master(struct net_device *slave, struct net_device *master)
4313 {
4314         struct net_device *old = slave->master;
4315
4316         ASSERT_RTNL();
4317
4318         if (master) {
4319                 if (old)
4320                         return -EBUSY;
4321                 dev_hold(master);
4322         }
4323
4324         slave->master = master;
4325
4326         if (old)
4327                 dev_put(old);
4328         return 0;
4329 }
4330 EXPORT_SYMBOL(netdev_set_master);
4331
4332 /**
4333  *      netdev_set_bond_master  -       set up bonding master/slave pair
4334  *      @slave: slave device
4335  *      @master: new master device
4336  *
4337  *      Changes the master device of the slave. Pass %NULL to break the
4338  *      bonding. The caller must hold the RTNL semaphore. On a failure
4339  *      a negative errno code is returned. On success %RTM_NEWLINK is sent
4340  *      to the routing socket and the function returns zero.
4341  */
4342 int netdev_set_bond_master(struct net_device *slave, struct net_device *master)
4343 {
4344         int err;
4345
4346         ASSERT_RTNL();
4347
4348         err = netdev_set_master(slave, master);
4349         if (err)
4350                 return err;
4351         if (master)
4352                 slave->flags |= IFF_SLAVE;
4353         else
4354                 slave->flags &= ~IFF_SLAVE;
4355
4356         rtmsg_ifinfo(RTM_NEWLINK, slave, IFF_SLAVE);
4357         return 0;
4358 }
4359 EXPORT_SYMBOL(netdev_set_bond_master);
4360
4361 static void dev_change_rx_flags(struct net_device *dev, int flags)
4362 {
4363         const struct net_device_ops *ops = dev->netdev_ops;
4364
4365         if ((dev->flags & IFF_UP) && ops->ndo_change_rx_flags)
4366                 ops->ndo_change_rx_flags(dev, flags);
4367 }
4368
4369 static int __dev_set_promiscuity(struct net_device *dev, int inc)
4370 {
4371         unsigned short old_flags = dev->flags;
4372         uid_t uid;
4373         gid_t gid;
4374
4375         ASSERT_RTNL();
4376
4377         dev->flags |= IFF_PROMISC;
4378         dev->promiscuity += inc;
4379         if (dev->promiscuity == 0) {
4380                 /*
4381                  * Avoid overflow.
4382                  * If inc causes overflow, untouch promisc and return error.
4383                  */
4384                 if (inc < 0)
4385                         dev->flags &= ~IFF_PROMISC;
4386                 else {
4387                         dev->promiscuity -= inc;
4388                         printk(KERN_WARNING "%s: promiscuity touches roof, "
4389                                 "set promiscuity failed, promiscuity feature "
4390                                 "of device might be broken.\n", dev->name);
4391                         return -EOVERFLOW;
4392                 }
4393         }
4394         if (dev->flags != old_flags) {
4395                 printk(KERN_INFO "device %s %s promiscuous mode\n",
4396                        dev->name, (dev->flags & IFF_PROMISC) ? "entered" :
4397                                                                "left");
4398                 if (audit_enabled) {
4399                         current_uid_gid(&uid, &gid);
4400                         audit_log(current->audit_context, GFP_ATOMIC,
4401                                 AUDIT_ANOM_PROMISCUOUS,
4402                                 "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u",
4403                                 dev->name, (dev->flags & IFF_PROMISC),
4404                                 (old_flags & IFF_PROMISC),
4405                                 audit_get_loginuid(current),
4406                                 uid, gid,
4407                                 audit_get_sessionid(current));
4408                 }
4409
4410                 dev_change_rx_flags(dev, IFF_PROMISC);
4411         }
4412         return 0;
4413 }
4414
4415 /**
4416  *      dev_set_promiscuity     - update promiscuity count on a device
4417  *      @dev: device
4418  *      @inc: modifier
4419  *
4420  *      Add or remove promiscuity from a device. While the count in the device
4421  *      remains above zero the interface remains promiscuous. Once it hits zero
4422  *      the device reverts back to normal filtering operation. A negative inc
4423  *      value is used to drop promiscuity on the device.
4424  *      Return 0 if successful or a negative errno code on error.
4425  */
4426 int dev_set_promiscuity(struct net_device *dev, int inc)
4427 {
4428         unsigned short old_flags = dev->flags;
4429         int err;
4430
4431         err = __dev_set_promiscuity(dev, inc);
4432         if (err < 0)
4433                 return err;
4434         if (dev->flags != old_flags)
4435                 dev_set_rx_mode(dev);
4436         return err;
4437 }
4438 EXPORT_SYMBOL(dev_set_promiscuity);
4439
4440 /**
4441  *      dev_set_allmulti        - update allmulti count on a device
4442  *      @dev: device
4443  *      @inc: modifier
4444  *
4445  *      Add or remove reception of all multicast frames to a device. While the
4446  *      count in the device remains above zero the interface remains listening
4447  *      to all interfaces. Once it hits zero the device reverts back to normal
4448  *      filtering operation. A negative @inc value is used to drop the counter
4449  *      when releasing a resource needing all multicasts.
4450  *      Return 0 if successful or a negative errno code on error.
4451  */
4452
4453 int dev_set_allmulti(struct net_device *dev, int inc)
4454 {
4455         unsigned short old_flags = dev->flags;
4456
4457         ASSERT_RTNL();
4458
4459         dev->flags |= IFF_ALLMULTI;
4460         dev->allmulti += inc;
4461         if (dev->allmulti == 0) {
4462                 /*
4463                  * Avoid overflow.
4464                  * If inc causes overflow, untouch allmulti and return error.
4465                  */
4466                 if (inc < 0)
4467                         dev->flags &= ~IFF_ALLMULTI;
4468                 else {
4469                         dev->allmulti -= inc;
4470                         printk(KERN_WARNING "%s: allmulti touches roof, "
4471                                 "set allmulti failed, allmulti feature of "
4472                                 "device might be broken.\n", dev->name);
4473                         return -EOVERFLOW;
4474                 }
4475         }
4476         if (dev->flags ^ old_flags) {
4477                 dev_change_rx_flags(dev, IFF_ALLMULTI);
4478                 dev_set_rx_mode(dev);
4479         }
4480         return 0;
4481 }
4482 EXPORT_SYMBOL(dev_set_allmulti);
4483
4484 /*
4485  *      Upload unicast and multicast address lists to device and
4486  *      configure RX filtering. When the device doesn't support unicast
4487  *      filtering it is put in promiscuous mode while unicast addresses
4488  *      are present.
4489  */
4490 void __dev_set_rx_mode(struct net_device *dev)
4491 {
4492         const struct net_device_ops *ops = dev->netdev_ops;
4493
4494         /* dev_open will call this function so the list will stay sane. */
4495         if (!(dev->flags&IFF_UP))
4496                 return;
4497
4498         if (!netif_device_present(dev))
4499                 return;
4500
4501         if (ops->ndo_set_rx_mode)
4502                 ops->ndo_set_rx_mode(dev);
4503         else {
4504                 /* Unicast addresses changes may only happen under the rtnl,
4505                  * therefore calling __dev_set_promiscuity here is safe.
4506                  */
4507                 if (!netdev_uc_empty(dev) && !dev->uc_promisc) {
4508                         __dev_set_promiscuity(dev, 1);
4509                         dev->uc_promisc = 1;
4510                 } else if (netdev_uc_empty(dev) && dev->uc_promisc) {
4511                         __dev_set_promiscuity(dev, -1);
4512                         dev->uc_promisc = 0;
4513                 }
4514
4515                 if (ops->ndo_set_multicast_list)
4516                         ops->ndo_set_multicast_list(dev);
4517         }
4518 }
4519
4520 void dev_set_rx_mode(struct net_device *dev)
4521 {
4522         netif_addr_lock_bh(dev);
4523         __dev_set_rx_mode(dev);
4524         netif_addr_unlock_bh(dev);
4525 }
4526
4527 /**
4528  *      dev_ethtool_get_settings - call device's ethtool_ops::get_settings()
4529  *      @dev: device
4530  *      @cmd: memory area for ethtool_ops::get_settings() result
4531  *
4532  *      The cmd arg is initialized properly (cleared and
4533  *      ethtool_cmd::cmd field set to ETHTOOL_GSET).
4534  *
4535  *      Return device's ethtool_ops::get_settings() result value or
4536  *      -EOPNOTSUPP when device doesn't expose
4537  *      ethtool_ops::get_settings() operation.
4538  */
4539 int dev_ethtool_get_settings(struct net_device *dev,
4540                              struct ethtool_cmd *cmd)
4541 {
4542         if (!dev->ethtool_ops || !dev->ethtool_ops->get_settings)
4543                 return -EOPNOTSUPP;
4544
4545         memset(cmd, 0, sizeof(struct ethtool_cmd));
4546         cmd->cmd = ETHTOOL_GSET;
4547         return dev->ethtool_ops->get_settings(dev, cmd);
4548 }
4549 EXPORT_SYMBOL(dev_ethtool_get_settings);
4550
4551 /**
4552  *      dev_get_flags - get flags reported to userspace
4553  *      @dev: device
4554  *
4555  *      Get the combination of flag bits exported through APIs to userspace.
4556  */
4557 unsigned dev_get_flags(const struct net_device *dev)
4558 {
4559         unsigned flags;
4560
4561         flags = (dev->flags & ~(IFF_PROMISC |
4562                                 IFF_ALLMULTI |
4563                                 IFF_RUNNING |
4564                                 IFF_LOWER_UP |
4565                                 IFF_DORMANT)) |
4566                 (dev->gflags & (IFF_PROMISC |
4567                                 IFF_ALLMULTI));
4568
4569         if (netif_running(dev)) {
4570                 if (netif_oper_up(dev))
4571                         flags |= IFF_RUNNING;
4572                 if (netif_carrier_ok(dev))
4573                         flags |= IFF_LOWER_UP;
4574                 if (netif_dormant(dev))
4575                         flags |= IFF_DORMANT;
4576         }
4577
4578         return flags;
4579 }
4580 EXPORT_SYMBOL(dev_get_flags);
4581
4582 int __dev_change_flags(struct net_device *dev, unsigned int flags)
4583 {
4584         int old_flags = dev->flags;
4585         int ret;
4586
4587         ASSERT_RTNL();
4588
4589         /*
4590          *      Set the flags on our device.
4591          */
4592
4593         dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
4594                                IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
4595                                IFF_AUTOMEDIA)) |
4596                      (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
4597                                     IFF_ALLMULTI));
4598
4599         /*
4600          *      Load in the correct multicast list now the flags have changed.
4601          */
4602
4603         if ((old_flags ^ flags) & IFF_MULTICAST)
4604                 dev_change_rx_flags(dev, IFF_MULTICAST);
4605
4606         dev_set_rx_mode(dev);
4607
4608         /*
4609          *      Have we downed the interface. We handle IFF_UP ourselves
4610          *      according to user attempts to set it, rather than blindly
4611          *      setting it.
4612          */
4613
4614         ret = 0;
4615         if ((old_flags ^ flags) & IFF_UP) {     /* Bit is different  ? */
4616                 ret = ((old_flags & IFF_UP) ? __dev_close : __dev_open)(dev);
4617
4618                 if (!ret)
4619                         dev_set_rx_mode(dev);
4620         }
4621
4622         if ((flags ^ dev->gflags) & IFF_PROMISC) {
4623                 int inc = (flags & IFF_PROMISC) ? 1 : -1;
4624
4625                 dev->gflags ^= IFF_PROMISC;
4626                 dev_set_promiscuity(dev, inc);
4627         }
4628
4629         /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
4630            is important. Some (broken) drivers set IFF_PROMISC, when
4631            IFF_ALLMULTI is requested not asking us and not reporting.
4632          */
4633         if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
4634                 int inc = (flags & IFF_ALLMULTI) ? 1 : -1;
4635
4636                 dev->gflags ^= IFF_ALLMULTI;
4637                 dev_set_allmulti(dev, inc);
4638         }
4639
4640         return ret;
4641 }
4642
4643 void __dev_notify_flags(struct net_device *dev, unsigned int old_flags)
4644 {
4645         unsigned int changes = dev->flags ^ old_flags;
4646
4647         if (changes & IFF_UP) {
4648                 if (dev->flags & IFF_UP)
4649                         call_netdevice_notifiers(NETDEV_UP, dev);
4650                 else
4651                         call_netdevice_notifiers(NETDEV_DOWN, dev);
4652         }
4653
4654         if (dev->flags & IFF_UP &&
4655             (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE)))
4656                 call_netdevice_notifiers(NETDEV_CHANGE, dev);
4657 }
4658
4659 /**
4660  *      dev_change_flags - change device settings
4661  *      @dev: device
4662  *      @flags: device state flags
4663  *
4664  *      Change settings on device based state flags. The flags are
4665  *      in the userspace exported format.
4666  */
4667 int dev_change_flags(struct net_device *dev, unsigned flags)
4668 {
4669         int ret, changes;
4670         int old_flags = dev->flags;
4671
4672         ret = __dev_change_flags(dev, flags);
4673         if (ret < 0)
4674                 return ret;
4675
4676         changes = old_flags ^ dev->flags;
4677         if (changes)
4678                 rtmsg_ifinfo(RTM_NEWLINK, dev, changes);
4679
4680         __dev_notify_flags(dev, old_flags);
4681         return ret;
4682 }
4683 EXPORT_SYMBOL(dev_change_flags);
4684
4685 /**
4686  *      dev_set_mtu - Change maximum transfer unit
4687  *      @dev: device
4688  *      @new_mtu: new transfer unit
4689  *
4690  *      Change the maximum transfer size of the network device.
4691  */
4692 int dev_set_mtu(struct net_device *dev, int new_mtu)
4693 {
4694         const struct net_device_ops *ops = dev->netdev_ops;
4695         int err;
4696
4697         if (new_mtu == dev->mtu)
4698                 return 0;
4699
4700         /*      MTU must be positive.    */
4701         if (new_mtu < 0)
4702                 return -EINVAL;
4703
4704         if (!netif_device_present(dev))
4705                 return -ENODEV;
4706
4707         err = 0;
4708         if (ops->ndo_change_mtu)
4709                 err = ops->ndo_change_mtu(dev, new_mtu);
4710         else
4711                 dev->mtu = new_mtu;
4712
4713         if (!err && dev->flags & IFF_UP)
4714                 call_netdevice_notifiers(NETDEV_CHANGEMTU, dev);
4715         return err;
4716 }
4717 EXPORT_SYMBOL(dev_set_mtu);
4718
4719 /**
4720  *      dev_set_group - Change group this device belongs to
4721  *      @dev: device
4722  *      @new_group: group this device should belong to
4723  */
4724 void dev_set_group(struct net_device *dev, int new_group)
4725 {
4726         dev->group = new_group;
4727 }
4728 EXPORT_SYMBOL(dev_set_group);
4729
4730 /**
4731  *      dev_set_mac_address - Change Media Access Control Address
4732  *      @dev: device
4733  *      @sa: new address
4734  *
4735  *      Change the hardware (MAC) address of the device
4736  */
4737 int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa)
4738 {
4739         const struct net_device_ops *ops = dev->netdev_ops;
4740         int err;
4741
4742         if (!ops->ndo_set_mac_address)
4743                 return -EOPNOTSUPP;
4744         if (sa->sa_family != dev->type)
4745                 return -EINVAL;
4746         if (!netif_device_present(dev))
4747                 return -ENODEV;
4748         err = ops->ndo_set_mac_address(dev, sa);
4749         if (!err)
4750                 call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
4751         add_device_randomness(dev->dev_addr, dev->addr_len);
4752         return err;
4753 }
4754 EXPORT_SYMBOL(dev_set_mac_address);
4755
4756 /*
4757  *      Perform the SIOCxIFxxx calls, inside rcu_read_lock()
4758  */
4759 static int dev_ifsioc_locked(struct net *net, struct ifreq *ifr, unsigned int cmd)
4760 {
4761         int err;
4762         struct net_device *dev = dev_get_by_name_rcu(net, ifr->ifr_name);
4763
4764         if (!dev)
4765                 return -ENODEV;
4766
4767         switch (cmd) {
4768         case SIOCGIFFLAGS:      /* Get interface flags */
4769                 ifr->ifr_flags = (short) dev_get_flags(dev);
4770                 return 0;
4771
4772         case SIOCGIFMETRIC:     /* Get the metric on the interface
4773                                    (currently unused) */
4774                 ifr->ifr_metric = 0;
4775                 return 0;
4776
4777         case SIOCGIFMTU:        /* Get the MTU of a device */
4778                 ifr->ifr_mtu = dev->mtu;
4779                 return 0;
4780
4781         case SIOCGIFHWADDR:
4782                 if (!dev->addr_len)
4783                         memset(ifr->ifr_hwaddr.sa_data, 0, sizeof ifr->ifr_hwaddr.sa_data);
4784                 else
4785                         memcpy(ifr->ifr_hwaddr.sa_data, dev->dev_addr,
4786                                min(sizeof ifr->ifr_hwaddr.sa_data, (size_t) dev->addr_len));
4787                 ifr->ifr_hwaddr.sa_family = dev->type;
4788                 return 0;
4789
4790         case SIOCGIFSLAVE:
4791                 err = -EINVAL;
4792                 break;
4793
4794         case SIOCGIFMAP:
4795                 ifr->ifr_map.mem_start = dev->mem_start;
4796                 ifr->ifr_map.mem_end   = dev->mem_end;
4797                 ifr->ifr_map.base_addr = dev->base_addr;
4798                 ifr->ifr_map.irq       = dev->irq;
4799                 ifr->ifr_map.dma       = dev->dma;
4800                 ifr->ifr_map.port      = dev->if_port;
4801                 return 0;
4802
4803         case SIOCGIFINDEX:
4804                 ifr->ifr_ifindex = dev->ifindex;
4805                 return 0;
4806
4807         case SIOCGIFTXQLEN:
4808                 ifr->ifr_qlen = dev->tx_queue_len;
4809                 return 0;
4810
4811         default:
4812                 /* dev_ioctl() should ensure this case
4813                  * is never reached
4814                  */
4815                 WARN_ON(1);
4816                 err = -ENOTTY;
4817                 break;
4818
4819         }
4820         return err;
4821 }
4822
4823 /*
4824  *      Perform the SIOCxIFxxx calls, inside rtnl_lock()
4825  */
4826 static int dev_ifsioc(struct net *net, struct ifreq *ifr, unsigned int cmd)
4827 {
4828         int err;
4829         struct net_device *dev = __dev_get_by_name(net, ifr->ifr_name);
4830         const struct net_device_ops *ops;
4831
4832         if (!dev)
4833                 return -ENODEV;
4834
4835         ops = dev->netdev_ops;
4836
4837         switch (cmd) {
4838         case SIOCSIFFLAGS:      /* Set interface flags */
4839                 return dev_change_flags(dev, ifr->ifr_flags);
4840
4841         case SIOCSIFMETRIC:     /* Set the metric on the interface
4842                                    (currently unused) */
4843                 return -EOPNOTSUPP;
4844
4845         case SIOCSIFMTU:        /* Set the MTU of a device */
4846                 return dev_set_mtu(dev, ifr->ifr_mtu);
4847
4848         case SIOCSIFHWADDR:
4849                 return dev_set_mac_address(dev, &ifr->ifr_hwaddr);
4850
4851         case SIOCSIFHWBROADCAST:
4852                 if (ifr->ifr_hwaddr.sa_family != dev->type)
4853                         return -EINVAL;
4854                 memcpy(dev->broadcast, ifr->ifr_hwaddr.sa_data,
4855                        min(sizeof ifr->ifr_hwaddr.sa_data, (size_t) dev->addr_len));
4856                 call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
4857                 return 0;
4858
4859         case SIOCSIFMAP:
4860                 if (ops->ndo_set_config) {
4861                         if (!netif_device_present(dev))
4862                                 return -ENODEV;
4863                         return ops->ndo_set_config(dev, &ifr->ifr_map);
4864                 }
4865                 return -EOPNOTSUPP;
4866
4867         case SIOCADDMULTI:
4868                 if ((!ops->ndo_set_multicast_list && !ops->ndo_set_rx_mode) ||
4869                     ifr->ifr_hwaddr.sa_family != AF_UNSPEC)
4870                         return -EINVAL;
4871                 if (!netif_device_present(dev))
4872                         return -ENODEV;
4873                 return dev_mc_add_global(dev, ifr->ifr_hwaddr.sa_data);
4874
4875         case SIOCDELMULTI:
4876                 if ((!ops->ndo_set_multicast_list && !ops->ndo_set_rx_mode) ||
4877                     ifr->ifr_hwaddr.sa_family != AF_UNSPEC)
4878                         return -EINVAL;
4879                 if (!netif_device_present(dev))
4880                         return -ENODEV;
4881                 return dev_mc_del_global(dev, ifr->ifr_hwaddr.sa_data);
4882
4883         case SIOCSIFTXQLEN:
4884                 if (ifr->ifr_qlen < 0)
4885                         return -EINVAL;
4886                 dev->tx_queue_len = ifr->ifr_qlen;
4887                 return 0;
4888
4889         case SIOCSIFNAME:
4890                 ifr->ifr_newname[IFNAMSIZ-1] = '\0';
4891                 return dev_change_name(dev, ifr->ifr_newname);
4892
4893         /*
4894          *      Unknown or private ioctl
4895          */
4896         default:
4897                 if ((cmd >= SIOCDEVPRIVATE &&
4898                     cmd <= SIOCDEVPRIVATE + 15) ||
4899                     cmd == SIOCBONDENSLAVE ||
4900                     cmd == SIOCBONDRELEASE ||
4901                     cmd == SIOCBONDSETHWADDR ||
4902                     cmd == SIOCBONDSLAVEINFOQUERY ||
4903                     cmd == SIOCBONDINFOQUERY ||
4904                     cmd == SIOCBONDCHANGEACTIVE ||
4905                     cmd == SIOCGMIIPHY ||
4906                     cmd == SIOCGMIIREG ||
4907                     cmd == SIOCSMIIREG ||
4908                     cmd == SIOCBRADDIF ||
4909                     cmd == SIOCBRDELIF ||
4910                     cmd == SIOCSHWTSTAMP ||
4911                     cmd == SIOCWANDEV) {
4912                         err = -EOPNOTSUPP;
4913                         if (ops->ndo_do_ioctl) {
4914                                 if (netif_device_present(dev))
4915                                         err = ops->ndo_do_ioctl(dev, ifr, cmd);
4916                                 else
4917                                         err = -ENODEV;
4918                         }
4919                 } else
4920                         err = -EINVAL;
4921
4922         }
4923         return err;
4924 }
4925
4926 /*
4927  *      This function handles all "interface"-type I/O control requests. The actual
4928  *      'doing' part of this is dev_ifsioc above.
4929  */
4930
4931 /**
4932  *      dev_ioctl       -       network device ioctl
4933  *      @net: the applicable net namespace
4934  *      @cmd: command to issue
4935  *      @arg: pointer to a struct ifreq in user space
4936  *
4937  *      Issue ioctl functions to devices. This is normally called by the
4938  *      user space syscall interfaces but can sometimes be useful for
4939  *      other purposes. The return value is the return from the syscall if
4940  *      positive or a negative errno code on error.
4941  */
4942
4943 int dev_ioctl(struct net *net, unsigned int cmd, void __user *arg)
4944 {
4945         struct ifreq ifr;
4946         int ret;
4947         char *colon;
4948
4949         /* One special case: SIOCGIFCONF takes ifconf argument
4950            and requires shared lock, because it sleeps writing
4951            to user space.
4952          */
4953
4954         if (cmd == SIOCGIFCONF) {
4955                 rtnl_lock();
4956                 ret = dev_ifconf(net, (char __user *) arg);
4957                 rtnl_unlock();
4958                 return ret;
4959         }
4960         if (cmd == SIOCGIFNAME)
4961                 return dev_ifname(net, (struct ifreq __user *)arg);
4962
4963         if (copy_from_user(&ifr, arg, sizeof(struct ifreq)))
4964                 return -EFAULT;
4965
4966         ifr.ifr_name[IFNAMSIZ-1] = 0;
4967
4968         colon = strchr(ifr.ifr_name, ':');
4969         if (colon)
4970                 *colon = 0;
4971
4972         /*
4973          *      See which interface the caller is talking about.
4974          */
4975
4976         switch (cmd) {
4977         /*
4978          *      These ioctl calls:
4979          *      - can be done by all.
4980          *      - atomic and do not require locking.
4981          *      - return a value
4982          */
4983         case SIOCGIFFLAGS:
4984         case SIOCGIFMETRIC:
4985         case SIOCGIFMTU:
4986         case SIOCGIFHWADDR:
4987         case SIOCGIFSLAVE:
4988         case SIOCGIFMAP:
4989         case SIOCGIFINDEX:
4990         case SIOCGIFTXQLEN:
4991                 dev_load(net, ifr.ifr_name);
4992                 rcu_read_lock();
4993                 ret = dev_ifsioc_locked(net, &ifr, cmd);
4994                 rcu_read_unlock();
4995                 if (!ret) {
4996                         if (colon)
4997                                 *colon = ':';
4998                         if (copy_to_user(arg, &ifr,
4999                                          sizeof(struct ifreq)))
5000                                 ret = -EFAULT;
5001                 }
5002                 return ret;
5003
5004         case SIOCETHTOOL:
5005                 dev_load(net, ifr.ifr_name);
5006                 rtnl_lock();
5007                 ret = dev_ethtool(net, &ifr);
5008                 rtnl_unlock();
5009                 if (!ret) {
5010                         if (colon)
5011                                 *colon = ':';
5012                         if (copy_to_user(arg, &ifr,
5013                                          sizeof(struct ifreq)))
5014                                 ret = -EFAULT;
5015                 }
5016                 return ret;
5017
5018         /*
5019          *      These ioctl calls:
5020          *      - require superuser power.
5021          *      - require strict serialization.
5022          *      - return a value
5023          */
5024         case SIOCGMIIPHY:
5025         case SIOCGMIIREG:
5026         case SIOCSIFNAME:
5027                 if (!capable(CAP_NET_ADMIN))
5028                         return -EPERM;
5029                 dev_load(net, ifr.ifr_name);
5030                 rtnl_lock();
5031                 ret = dev_ifsioc(net, &ifr, cmd);
5032                 rtnl_unlock();
5033                 if (!ret) {
5034                         if (colon)
5035                                 *colon = ':';
5036                         if (copy_to_user(arg, &ifr,
5037                                          sizeof(struct ifreq)))
5038                                 ret = -EFAULT;
5039                 }
5040                 return ret;
5041
5042         /*
5043          *      These ioctl calls:
5044          *      - require superuser power.
5045          *      - require strict serialization.
5046          *      - do not return a value
5047          */
5048         case SIOCSIFFLAGS:
5049         case SIOCSIFMETRIC:
5050         case SIOCSIFMTU:
5051         case SIOCSIFMAP:
5052         case SIOCSIFHWADDR:
5053         case SIOCSIFSLAVE:
5054         case SIOCADDMULTI:
5055         case SIOCDELMULTI:
5056         case SIOCSIFHWBROADCAST:
5057         case SIOCSIFTXQLEN:
5058         case SIOCSMIIREG:
5059         case SIOCBONDENSLAVE:
5060         case SIOCBONDRELEASE:
5061         case SIOCBONDSETHWADDR:
5062         case SIOCBONDCHANGEACTIVE:
5063         case SIOCBRADDIF:
5064         case SIOCBRDELIF:
5065         case SIOCSHWTSTAMP:
5066                 if (!capable(CAP_NET_ADMIN))
5067                         return -EPERM;
5068                 /* fall through */
5069         case SIOCBONDSLAVEINFOQUERY:
5070         case SIOCBONDINFOQUERY:
5071                 dev_load(net, ifr.ifr_name);
5072                 rtnl_lock();
5073                 ret = dev_ifsioc(net, &ifr, cmd);
5074                 rtnl_unlock();
5075                 return ret;
5076
5077         case SIOCGIFMEM:
5078                 /* Get the per device memory space. We can add this but
5079                  * currently do not support it */
5080         case SIOCSIFMEM:
5081                 /* Set the per device memory buffer space.
5082                  * Not applicable in our case */
5083         case SIOCSIFLINK:
5084                 return -ENOTTY;
5085
5086         /*
5087          *      Unknown or private ioctl.
5088          */
5089         default:
5090                 if (cmd == SIOCWANDEV ||
5091                     (cmd >= SIOCDEVPRIVATE &&
5092                      cmd <= SIOCDEVPRIVATE + 15)) {
5093                         dev_load(net, ifr.ifr_name);
5094                         rtnl_lock();
5095                         ret = dev_ifsioc(net, &ifr, cmd);
5096                         rtnl_unlock();
5097                         if (!ret && copy_to_user(arg, &ifr,
5098                                                  sizeof(struct ifreq)))
5099                                 ret = -EFAULT;
5100                         return ret;
5101                 }
5102                 /* Take care of Wireless Extensions */
5103                 if (cmd >= SIOCIWFIRST && cmd <= SIOCIWLAST)
5104                         return wext_handle_ioctl(net, &ifr, cmd, arg);
5105                 return -ENOTTY;
5106         }
5107 }
5108
5109
5110 /**
5111  *      dev_new_index   -       allocate an ifindex
5112  *      @net: the applicable net namespace
5113  *
5114  *      Returns a suitable unique value for a new device interface
5115  *      number.  The caller must hold the rtnl semaphore or the
5116  *      dev_base_lock to be sure it remains unique.
5117  */
5118 static int dev_new_index(struct net *net)
5119 {
5120         static int ifindex;
5121         for (;;) {
5122                 if (++ifindex <= 0)
5123                         ifindex = 1;
5124                 if (!__dev_get_by_index(net, ifindex))
5125                         return ifindex;
5126         }
5127 }
5128
5129 /* Delayed registration/unregisteration */
5130 static LIST_HEAD(net_todo_list);
5131
5132 static void net_set_todo(struct net_device *dev)
5133 {
5134         list_add_tail(&dev->todo_list, &net_todo_list);
5135 }
5136
5137 static void rollback_registered_many(struct list_head *head)
5138 {
5139         struct net_device *dev, *tmp;
5140
5141         BUG_ON(dev_boot_phase);
5142         ASSERT_RTNL();
5143
5144         list_for_each_entry_safe(dev, tmp, head, unreg_list) {
5145                 /* Some devices call without registering
5146                  * for initialization unwind. Remove those
5147                  * devices and proceed with the remaining.
5148                  */
5149                 if (dev->reg_state == NETREG_UNINITIALIZED) {
5150                         pr_debug("unregister_netdevice: device %s/%p never "
5151                                  "was registered\n", dev->name, dev);
5152
5153                         WARN_ON(1);
5154                         list_del(&dev->unreg_list);
5155                         continue;
5156                 }
5157                 dev->dismantle = true;
5158                 BUG_ON(dev->reg_state != NETREG_REGISTERED);
5159         }
5160
5161         /* If device is running, close it first. */
5162         dev_close_many(head);
5163
5164         list_for_each_entry(dev, head, unreg_list) {
5165                 /* And unlink it from device chain. */
5166                 unlist_netdevice(dev);
5167
5168                 dev->reg_state = NETREG_UNREGISTERING;
5169         }
5170
5171         synchronize_net();
5172
5173         list_for_each_entry(dev, head, unreg_list) {
5174                 /* Shutdown queueing discipline. */
5175                 dev_shutdown(dev);
5176
5177
5178                 /* Notify protocols, that we are about to destroy
5179                    this device. They should clean all the things.
5180                 */
5181                 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
5182
5183                 if (!dev->rtnl_link_ops ||
5184                     dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
5185                         rtmsg_ifinfo(RTM_DELLINK, dev, ~0U);
5186
5187                 /*
5188                  *      Flush the unicast and multicast chains
5189                  */
5190                 dev_uc_flush(dev);
5191                 dev_mc_flush(dev);
5192
5193                 if (dev->netdev_ops->ndo_uninit)
5194                         dev->netdev_ops->ndo_uninit(dev);
5195
5196                 /* Notifier chain MUST detach us from master device. */
5197                 WARN_ON(dev->master);
5198
5199                 /* Remove entries from kobject tree */
5200                 netdev_unregister_kobject(dev);
5201         }
5202
5203         /* Process any work delayed until the end of the batch */
5204         dev = list_first_entry(head, struct net_device, unreg_list);
5205         call_netdevice_notifiers(NETDEV_UNREGISTER_BATCH, dev);
5206
5207         rcu_barrier();
5208
5209         list_for_each_entry(dev, head, unreg_list)
5210                 dev_put(dev);
5211 }
5212
5213 static void rollback_registered(struct net_device *dev)
5214 {
5215         LIST_HEAD(single);
5216
5217         list_add(&dev->unreg_list, &single);
5218         rollback_registered_many(&single);
5219         list_del(&single);
5220 }
5221
5222 u32 netdev_fix_features(struct net_device *dev, u32 features)
5223 {
5224         /* Fix illegal checksum combinations */
5225         if ((features & NETIF_F_HW_CSUM) &&
5226             (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
5227                 netdev_warn(dev, "mixed HW and IP checksum settings.\n");
5228                 features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM);
5229         }
5230
5231         if ((features & NETIF_F_NO_CSUM) &&
5232             (features & (NETIF_F_HW_CSUM|NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
5233                 netdev_warn(dev, "mixed no checksumming and other settings.\n");
5234                 features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM|NETIF_F_HW_CSUM);
5235         }
5236
5237         /* Fix illegal SG+CSUM combinations. */
5238         if ((features & NETIF_F_SG) &&
5239             !(features & NETIF_F_ALL_CSUM)) {
5240                 netdev_dbg(dev,
5241                         "Dropping NETIF_F_SG since no checksum feature.\n");
5242                 features &= ~NETIF_F_SG;
5243         }
5244
5245         /* TSO requires that SG is present as well. */
5246         if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) {
5247                 netdev_dbg(dev, "Dropping TSO features since no SG feature.\n");
5248                 features &= ~NETIF_F_ALL_TSO;
5249         }
5250
5251         /* TSO ECN requires that TSO is present as well. */
5252         if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN)
5253                 features &= ~NETIF_F_TSO_ECN;
5254
5255         /* Software GSO depends on SG. */
5256         if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) {
5257                 netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n");
5258                 features &= ~NETIF_F_GSO;
5259         }
5260
5261         /* UFO needs SG and checksumming */
5262         if (features & NETIF_F_UFO) {
5263                 /* maybe split UFO into V4 and V6? */
5264                 if (!((features & NETIF_F_GEN_CSUM) ||
5265                     (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))
5266                             == (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
5267                         netdev_dbg(dev,
5268                                 "Dropping NETIF_F_UFO since no checksum offload features.\n");
5269                         features &= ~NETIF_F_UFO;
5270                 }
5271
5272                 if (!(features & NETIF_F_SG)) {
5273                         netdev_dbg(dev,
5274                                 "Dropping NETIF_F_UFO since no NETIF_F_SG feature.\n");
5275                         features &= ~NETIF_F_UFO;
5276                 }
5277         }
5278
5279         return features;
5280 }
5281 EXPORT_SYMBOL(netdev_fix_features);
5282
5283 int __netdev_update_features(struct net_device *dev)
5284 {
5285         u32 features;
5286         int err = 0;
5287
5288         ASSERT_RTNL();
5289
5290         features = netdev_get_wanted_features(dev);
5291
5292         if (dev->netdev_ops->ndo_fix_features)
5293                 features = dev->netdev_ops->ndo_fix_features(dev, features);
5294
5295         /* driver might be less strict about feature dependencies */
5296         features = netdev_fix_features(dev, features);
5297
5298         if (dev->features == features)
5299                 return 0;
5300
5301         netdev_dbg(dev, "Features changed: 0x%08x -> 0x%08x\n",
5302                 dev->features, features);
5303
5304         if (dev->netdev_ops->ndo_set_features)
5305                 err = dev->netdev_ops->ndo_set_features(dev, features);
5306
5307         if (unlikely(err < 0)) {
5308                 netdev_err(dev,
5309                         "set_features() failed (%d); wanted 0x%08x, left 0x%08x\n",
5310                         err, features, dev->features);
5311                 return -1;
5312         }
5313
5314         if (!err)
5315                 dev->features = features;
5316
5317         return 1;
5318 }
5319
5320 /**
5321  *      netdev_update_features - recalculate device features
5322  *      @dev: the device to check
5323  *
5324  *      Recalculate dev->features set and send notifications if it
5325  *      has changed. Should be called after driver or hardware dependent
5326  *      conditions might have changed that influence the features.
5327  */
5328 void netdev_update_features(struct net_device *dev)
5329 {
5330         if (__netdev_update_features(dev))
5331                 netdev_features_change(dev);
5332 }
5333 EXPORT_SYMBOL(netdev_update_features);
5334
5335 /**
5336  *      netdev_change_features - recalculate device features
5337  *      @dev: the device to check
5338  *
5339  *      Recalculate dev->features set and send notifications even
5340  *      if they have not changed. Should be called instead of
5341  *      netdev_update_features() if also dev->vlan_features might
5342  *      have changed to allow the changes to be propagated to stacked
5343  *      VLAN devices.
5344  */
5345 void netdev_change_features(struct net_device *dev)
5346 {
5347         __netdev_update_features(dev);
5348         netdev_features_change(dev);
5349 }
5350 EXPORT_SYMBOL(netdev_change_features);
5351
5352 /**
5353  *      netif_stacked_transfer_operstate -      transfer operstate
5354  *      @rootdev: the root or lower level device to transfer state from
5355  *      @dev: the device to transfer operstate to
5356  *
5357  *      Transfer operational state from root to device. This is normally
5358  *      called when a stacking relationship exists between the root
5359  *      device and the device(a leaf device).
5360  */
5361 void netif_stacked_transfer_operstate(const struct net_device *rootdev,
5362                                         struct net_device *dev)
5363 {
5364         if (rootdev->operstate == IF_OPER_DORMANT)
5365                 netif_dormant_on(dev);
5366         else
5367                 netif_dormant_off(dev);
5368
5369         if (netif_carrier_ok(rootdev)) {
5370                 if (!netif_carrier_ok(dev))
5371                         netif_carrier_on(dev);
5372         } else {
5373                 if (netif_carrier_ok(dev))
5374                         netif_carrier_off(dev);
5375         }
5376 }
5377 EXPORT_SYMBOL(netif_stacked_transfer_operstate);
5378
5379 #ifdef CONFIG_RPS
5380 static int netif_alloc_rx_queues(struct net_device *dev)
5381 {
5382         unsigned int i, count = dev->num_rx_queues;
5383         struct netdev_rx_queue *rx;
5384
5385         BUG_ON(count < 1);
5386
5387         rx = kcalloc(count, sizeof(struct netdev_rx_queue), GFP_KERNEL);
5388         if (!rx) {
5389                 pr_err("netdev: Unable to allocate %u rx queues.\n", count);
5390                 return -ENOMEM;
5391         }
5392         dev->_rx = rx;
5393
5394         for (i = 0; i < count; i++)
5395                 rx[i].dev = dev;
5396         return 0;
5397 }
5398 #endif
5399
5400 static void netdev_init_one_queue(struct net_device *dev,
5401                                   struct netdev_queue *queue, void *_unused)
5402 {
5403         /* Initialize queue lock */
5404         spin_lock_init(&queue->_xmit_lock);
5405         netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type);
5406         queue->xmit_lock_owner = -1;
5407         netdev_queue_numa_node_write(queue, NUMA_NO_NODE);
5408         queue->dev = dev;
5409 }
5410
5411 static int netif_alloc_netdev_queues(struct net_device *dev)
5412 {
5413         unsigned int count = dev->num_tx_queues;
5414         struct netdev_queue *tx;
5415
5416         BUG_ON(count < 1);
5417
5418         tx = kcalloc(count, sizeof(struct netdev_queue), GFP_KERNEL);
5419         if (!tx) {
5420                 pr_err("netdev: Unable to allocate %u tx queues.\n",
5421                        count);
5422                 return -ENOMEM;
5423         }
5424         dev->_tx = tx;
5425
5426         netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL);
5427         spin_lock_init(&dev->tx_global_lock);
5428
5429         return 0;
5430 }
5431
5432 /**
5433  *      register_netdevice      - register a network device
5434  *      @dev: device to register
5435  *
5436  *      Take a completed network device structure and add it to the kernel
5437  *      interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
5438  *      chain. 0 is returned on success. A negative errno code is returned
5439  *      on a failure to set up the device, or if the name is a duplicate.
5440  *
5441  *      Callers must hold the rtnl semaphore. You may want
5442  *      register_netdev() instead of this.
5443  *
5444  *      BUGS:
5445  *      The locking appears insufficient to guarantee two parallel registers
5446  *      will not get the same name.
5447  */
5448
5449 int register_netdevice(struct net_device *dev)
5450 {
5451         int ret;
5452         struct net *net = dev_net(dev);
5453
5454         BUG_ON(dev_boot_phase);
5455         ASSERT_RTNL();
5456
5457         might_sleep();
5458
5459         /* When net_device's are persistent, this will be fatal. */
5460         BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
5461         BUG_ON(!net);
5462
5463         spin_lock_init(&dev->addr_list_lock);
5464         netdev_set_addr_lockdep_class(dev);
5465
5466         dev->iflink = -1;
5467
5468         ret = dev_get_valid_name(dev, dev->name);
5469         if (ret < 0)
5470                 goto out;
5471
5472         /* Init, if this function is available */
5473         if (dev->netdev_ops->ndo_init) {
5474                 ret = dev->netdev_ops->ndo_init(dev);
5475                 if (ret) {
5476                         if (ret > 0)
5477                                 ret = -EIO;
5478                         goto out;
5479                 }
5480         }
5481
5482         dev->ifindex = dev_new_index(net);
5483         if (dev->iflink == -1)
5484                 dev->iflink = dev->ifindex;
5485
5486         /* Transfer changeable features to wanted_features and enable
5487          * software offloads (GSO and GRO).
5488          */
5489         dev->hw_features |= NETIF_F_SOFT_FEATURES;
5490         dev->features |= NETIF_F_SOFT_FEATURES;
5491         dev->wanted_features = dev->features & dev->hw_features;
5492
5493         /* Turn on no cache copy if HW is doing checksum */
5494         dev->hw_features |= NETIF_F_NOCACHE_COPY;
5495         if ((dev->features & NETIF_F_ALL_CSUM) &&
5496             !(dev->features & NETIF_F_NO_CSUM)) {
5497                 dev->wanted_features |= NETIF_F_NOCACHE_COPY;
5498                 dev->features |= NETIF_F_NOCACHE_COPY;
5499         }
5500
5501         /* Enable GRO and NETIF_F_HIGHDMA for vlans by default,
5502          * vlan_dev_init() will do the dev->features check, so these features
5503          * are enabled only if supported by underlying device.
5504          */
5505         dev->vlan_features |= (NETIF_F_GRO | NETIF_F_HIGHDMA);
5506
5507         ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev);
5508         ret = notifier_to_errno(ret);
5509         if (ret)
5510                 goto err_uninit;
5511
5512         ret = netdev_register_kobject(dev);
5513         if (ret)
5514                 goto err_uninit;
5515         dev->reg_state = NETREG_REGISTERED;
5516
5517         __netdev_update_features(dev);
5518
5519         /*
5520          *      Default initial state at registry is that the
5521          *      device is present.
5522          */
5523
5524         set_bit(__LINK_STATE_PRESENT, &dev->state);
5525
5526         dev_init_scheduler(dev);
5527         dev_hold(dev);
5528         list_netdevice(dev);
5529         add_device_randomness(dev->dev_addr, dev->addr_len);
5530
5531         /* Notify protocols, that a new device appeared. */
5532         ret = call_netdevice_notifiers(NETDEV_REGISTER, dev);
5533         ret = notifier_to_errno(ret);
5534         if (ret) {
5535                 rollback_registered(dev);
5536                 dev->reg_state = NETREG_UNREGISTERED;
5537         }
5538         /*
5539          *      Prevent userspace races by waiting until the network
5540          *      device is fully setup before sending notifications.
5541          */
5542         if (!dev->rtnl_link_ops ||
5543             dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
5544                 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U);
5545
5546 out:
5547         return ret;
5548
5549 err_uninit:
5550         if (dev->netdev_ops->ndo_uninit)
5551                 dev->netdev_ops->ndo_uninit(dev);
5552         goto out;
5553 }
5554 EXPORT_SYMBOL(register_netdevice);
5555
5556 /**
5557  *      init_dummy_netdev       - init a dummy network device for NAPI
5558  *      @dev: device to init
5559  *
5560  *      This takes a network device structure and initialize the minimum
5561  *      amount of fields so it can be used to schedule NAPI polls without
5562  *      registering a full blown interface. This is to be used by drivers
5563  *      that need to tie several hardware interfaces to a single NAPI
5564  *      poll scheduler due to HW limitations.
5565  */
5566 int init_dummy_netdev(struct net_device *dev)
5567 {
5568         /* Clear everything. Note we don't initialize spinlocks
5569          * are they aren't supposed to be taken by any of the
5570          * NAPI code and this dummy netdev is supposed to be
5571          * only ever used for NAPI polls
5572          */
5573         memset(dev, 0, sizeof(struct net_device));
5574
5575         /* make sure we BUG if trying to hit standard
5576          * register/unregister code path
5577          */
5578         dev->reg_state = NETREG_DUMMY;
5579
5580         /* NAPI wants this */
5581         INIT_LIST_HEAD(&dev->napi_list);
5582
5583         /* a dummy interface is started by default */
5584         set_bit(__LINK_STATE_PRESENT, &dev->state);
5585         set_bit(__LINK_STATE_START, &dev->state);
5586
5587         /* Note : We dont allocate pcpu_refcnt for dummy devices,
5588          * because users of this 'device' dont need to change
5589          * its refcount.
5590          */
5591
5592         return 0;
5593 }
5594 EXPORT_SYMBOL_GPL(init_dummy_netdev);
5595
5596
5597 /**
5598  *      register_netdev - register a network device
5599  *      @dev: device to register
5600  *
5601  *      Take a completed network device structure and add it to the kernel
5602  *      interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
5603  *      chain. 0 is returned on success. A negative errno code is returned
5604  *      on a failure to set up the device, or if the name is a duplicate.
5605  *
5606  *      This is a wrapper around register_netdevice that takes the rtnl semaphore
5607  *      and expands the device name if you passed a format string to
5608  *      alloc_netdev.
5609  */
5610 int register_netdev(struct net_device *dev)
5611 {
5612         int err;
5613
5614         rtnl_lock();
5615         err = register_netdevice(dev);
5616         rtnl_unlock();
5617         return err;
5618 }
5619 EXPORT_SYMBOL(register_netdev);
5620
5621 int netdev_refcnt_read(const struct net_device *dev)
5622 {
5623         int i, refcnt = 0;
5624
5625         for_each_possible_cpu(i)
5626                 refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i);
5627         return refcnt;
5628 }
5629 EXPORT_SYMBOL(netdev_refcnt_read);
5630
5631 /*
5632  * netdev_wait_allrefs - wait until all references are gone.
5633  *
5634  * This is called when unregistering network devices.
5635  *
5636  * Any protocol or device that holds a reference should register
5637  * for netdevice notification, and cleanup and put back the
5638  * reference if they receive an UNREGISTER event.
5639  * We can get stuck here if buggy protocols don't correctly
5640  * call dev_put.
5641  */
5642 static void netdev_wait_allrefs(struct net_device *dev)
5643 {
5644         unsigned long rebroadcast_time, warning_time;
5645         int refcnt;
5646
5647         linkwatch_forget_dev(dev);
5648
5649         rebroadcast_time = warning_time = jiffies;
5650         refcnt = netdev_refcnt_read(dev);
5651
5652         while (refcnt != 0) {
5653                 if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
5654                         rtnl_lock();
5655
5656                         /* Rebroadcast unregister notification */
5657                         call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
5658                         /* don't resend NETDEV_UNREGISTER_BATCH, _BATCH users
5659                          * should have already handle it the first time */
5660
5661                         if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
5662                                      &dev->state)) {
5663                                 /* We must not have linkwatch events
5664                                  * pending on unregister. If this
5665                                  * happens, we simply run the queue
5666                                  * unscheduled, resulting in a noop
5667                                  * for this device.
5668                                  */
5669                                 linkwatch_run_queue();
5670                         }
5671
5672                         __rtnl_unlock();
5673
5674                         rebroadcast_time = jiffies;
5675                 }
5676
5677                 msleep(250);
5678
5679                 refcnt = netdev_refcnt_read(dev);
5680
5681                 if (time_after(jiffies, warning_time + 10 * HZ)) {
5682                         printk(KERN_EMERG "unregister_netdevice: "
5683                                "waiting for %s to become free. Usage "
5684                                "count = %d\n",
5685                                dev->name, refcnt);
5686                         warning_time = jiffies;
5687                 }
5688         }
5689 }
5690
5691 /* The sequence is:
5692  *
5693  *      rtnl_lock();
5694  *      ...
5695  *      register_netdevice(x1);
5696  *      register_netdevice(x2);
5697  *      ...
5698  *      unregister_netdevice(y1);
5699  *      unregister_netdevice(y2);
5700  *      ...
5701  *      rtnl_unlock();
5702  *      free_netdev(y1);
5703  *      free_netdev(y2);
5704  *
5705  * We are invoked by rtnl_unlock().
5706  * This allows us to deal with problems:
5707  * 1) We can delete sysfs objects which invoke hotplug
5708  *    without deadlocking with linkwatch via keventd.
5709  * 2) Since we run with the RTNL semaphore not held, we can sleep
5710  *    safely in order to wait for the netdev refcnt to drop to zero.
5711  *
5712  * We must not return until all unregister events added during
5713  * the interval the lock was held have been completed.
5714  */
5715 void netdev_run_todo(void)
5716 {
5717         struct list_head list;
5718
5719         /* Snapshot list, allow later requests */
5720         list_replace_init(&net_todo_list, &list);
5721
5722         __rtnl_unlock();
5723
5724         while (!list_empty(&list)) {
5725                 struct net_device *dev
5726                         = list_first_entry(&list, struct net_device, todo_list);
5727                 list_del(&dev->todo_list);
5728
5729                 if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) {
5730                         printk(KERN_ERR "network todo '%s' but state %d\n",
5731                                dev->name, dev->reg_state);
5732                         dump_stack();
5733                         continue;
5734                 }
5735
5736                 dev->reg_state = NETREG_UNREGISTERED;
5737
5738                 on_each_cpu(flush_backlog, dev, 1);
5739
5740                 netdev_wait_allrefs(dev);
5741
5742                 /* paranoia */
5743                 BUG_ON(netdev_refcnt_read(dev));
5744                 WARN_ON(rcu_dereference_raw(dev->ip_ptr));
5745                 WARN_ON(rcu_dereference_raw(dev->ip6_ptr));
5746                 WARN_ON(dev->dn_ptr);
5747
5748                 if (dev->destructor)
5749                         dev->destructor(dev);
5750
5751                 /* Free network device */
5752                 kobject_put(&dev->dev.kobj);
5753         }
5754 }
5755
5756 /* Convert net_device_stats to rtnl_link_stats64.  They have the same
5757  * fields in the same order, with only the type differing.
5758  */
5759 static void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64,
5760                                     const struct net_device_stats *netdev_stats)
5761 {
5762 #if BITS_PER_LONG == 64
5763         BUILD_BUG_ON(sizeof(*stats64) != sizeof(*netdev_stats));
5764         memcpy(stats64, netdev_stats, sizeof(*stats64));
5765 #else
5766         size_t i, n = sizeof(*stats64) / sizeof(u64);
5767         const unsigned long *src = (const unsigned long *)netdev_stats;
5768         u64 *dst = (u64 *)stats64;
5769
5770         BUILD_BUG_ON(sizeof(*netdev_stats) / sizeof(unsigned long) !=
5771                      sizeof(*stats64) / sizeof(u64));
5772         for (i = 0; i < n; i++)
5773                 dst[i] = src[i];
5774 #endif
5775 }
5776
5777 /**
5778  *      dev_get_stats   - get network device statistics
5779  *      @dev: device to get statistics from
5780  *      @storage: place to store stats
5781  *
5782  *      Get network statistics from device. Return @storage.
5783  *      The device driver may provide its own method by setting
5784  *      dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats;
5785  *      otherwise the internal statistics structure is used.
5786  */
5787 struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev,
5788                                         struct rtnl_link_stats64 *storage)
5789 {
5790         const struct net_device_ops *ops = dev->netdev_ops;
5791
5792         if (ops->ndo_get_stats64) {
5793                 memset(storage, 0, sizeof(*storage));
5794                 ops->ndo_get_stats64(dev, storage);
5795         } else if (ops->ndo_get_stats) {
5796                 netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev));
5797         } else {
5798                 netdev_stats_to_stats64(storage, &dev->stats);
5799         }
5800         storage->rx_dropped += atomic_long_read(&dev->rx_dropped);
5801         return storage;
5802 }
5803 EXPORT_SYMBOL(dev_get_stats);
5804
5805 struct netdev_queue *dev_ingress_queue_create(struct net_device *dev)
5806 {
5807         struct netdev_queue *queue = dev_ingress_queue(dev);
5808
5809 #ifdef CONFIG_NET_CLS_ACT
5810         if (queue)
5811                 return queue;
5812         queue = kzalloc(sizeof(*queue), GFP_KERNEL);
5813         if (!queue)
5814                 return NULL;
5815         netdev_init_one_queue(dev, queue, NULL);
5816         queue->qdisc = &noop_qdisc;
5817         queue->qdisc_sleeping = &noop_qdisc;
5818         rcu_assign_pointer(dev->ingress_queue, queue);
5819 #endif
5820         return queue;
5821 }
5822
5823 /**
5824  *      alloc_netdev_mqs - allocate network device
5825  *      @sizeof_priv:   size of private data to allocate space for
5826  *      @name:          device name format string
5827  *      @setup:         callback to initialize device
5828  *      @txqs:          the number of TX subqueues to allocate
5829  *      @rxqs:          the number of RX subqueues to allocate
5830  *
5831  *      Allocates a struct net_device with private data area for driver use
5832  *      and performs basic initialization.  Also allocates subquue structs
5833  *      for each queue on the device.
5834  */
5835 struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name,
5836                 void (*setup)(struct net_device *),
5837                 unsigned int txqs, unsigned int rxqs)
5838 {
5839         struct net_device *dev;
5840         size_t alloc_size;
5841         struct net_device *p;
5842
5843         BUG_ON(strlen(name) >= sizeof(dev->name));
5844
5845         if (txqs < 1) {
5846                 pr_err("alloc_netdev: Unable to allocate device "
5847                        "with zero queues.\n");
5848                 return NULL;
5849         }
5850
5851 #ifdef CONFIG_RPS
5852         if (rxqs < 1) {
5853                 pr_err("alloc_netdev: Unable to allocate device "
5854                        "with zero RX queues.\n");
5855                 return NULL;
5856         }
5857 #endif
5858
5859         alloc_size = sizeof(struct net_device);
5860         if (sizeof_priv) {
5861                 /* ensure 32-byte alignment of private area */
5862                 alloc_size = ALIGN(alloc_size, NETDEV_ALIGN);
5863                 alloc_size += sizeof_priv;
5864         }
5865         /* ensure 32-byte alignment of whole construct */
5866         alloc_size += NETDEV_ALIGN - 1;
5867
5868         p = kzalloc(alloc_size, GFP_KERNEL);
5869         if (!p) {
5870                 printk(KERN_ERR "alloc_netdev: Unable to allocate device.\n");
5871                 return NULL;
5872         }
5873
5874         dev = PTR_ALIGN(p, NETDEV_ALIGN);
5875         dev->padded = (char *)dev - (char *)p;
5876
5877         dev->pcpu_refcnt = alloc_percpu(int);
5878         if (!dev->pcpu_refcnt)
5879                 goto free_p;
5880
5881         if (dev_addr_init(dev))
5882                 goto free_pcpu;
5883
5884         dev_mc_init(dev);
5885         dev_uc_init(dev);
5886
5887         dev_net_set(dev, &init_net);
5888
5889         dev->gso_max_size = GSO_MAX_SIZE;
5890         dev->gso_max_segs = GSO_MAX_SEGS;
5891
5892         INIT_LIST_HEAD(&dev->ethtool_ntuple_list.list);
5893         dev->ethtool_ntuple_list.count = 0;
5894         INIT_LIST_HEAD(&dev->napi_list);
5895         INIT_LIST_HEAD(&dev->unreg_list);
5896         INIT_LIST_HEAD(&dev->link_watch_list);
5897         dev->priv_flags = IFF_XMIT_DST_RELEASE;
5898         setup(dev);
5899
5900         dev->num_tx_queues = txqs;
5901         dev->real_num_tx_queues = txqs;
5902         if (netif_alloc_netdev_queues(dev))
5903                 goto free_all;
5904
5905 #ifdef CONFIG_RPS
5906         dev->num_rx_queues = rxqs;
5907         dev->real_num_rx_queues = rxqs;
5908         if (netif_alloc_rx_queues(dev))
5909                 goto free_all;
5910 #endif
5911
5912         strcpy(dev->name, name);
5913         dev->group = INIT_NETDEV_GROUP;
5914         return dev;
5915
5916 free_all:
5917         free_netdev(dev);
5918         return NULL;
5919
5920 free_pcpu:
5921         free_percpu(dev->pcpu_refcnt);
5922         kfree(dev->_tx);
5923 #ifdef CONFIG_RPS
5924         kfree(dev->_rx);
5925 #endif
5926
5927 free_p:
5928         kfree(p);
5929         return NULL;
5930 }
5931 EXPORT_SYMBOL(alloc_netdev_mqs);
5932
5933 /**
5934  *      free_netdev - free network device
5935  *      @dev: device
5936  *
5937  *      This function does the last stage of destroying an allocated device
5938  *      interface. The reference to the device object is released.
5939  *      If this is the last reference then it will be freed.
5940  */
5941 void free_netdev(struct net_device *dev)
5942 {
5943         struct napi_struct *p, *n;
5944
5945         release_net(dev_net(dev));
5946
5947         kfree(dev->_tx);
5948 #ifdef CONFIG_RPS
5949         kfree(dev->_rx);
5950 #endif
5951
5952         kfree(rcu_dereference_raw(dev->ingress_queue));
5953
5954         /* Flush device addresses */
5955         dev_addr_flush(dev);
5956
5957         /* Clear ethtool n-tuple list */
5958         ethtool_ntuple_flush(dev);
5959
5960         list_for_each_entry_safe(p, n, &dev->napi_list, dev_list)
5961                 netif_napi_del(p);
5962
5963         free_percpu(dev->pcpu_refcnt);
5964         dev->pcpu_refcnt = NULL;
5965
5966         /*  Compatibility with error handling in drivers */
5967         if (dev->reg_state == NETREG_UNINITIALIZED) {
5968                 kfree((char *)dev - dev->padded);
5969                 return;
5970         }
5971
5972         BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
5973         dev->reg_state = NETREG_RELEASED;
5974
5975         /* will free via device release */
5976         put_device(&dev->dev);
5977 }
5978 EXPORT_SYMBOL(free_netdev);
5979
5980 /**
5981  *      synchronize_net -  Synchronize with packet receive processing
5982  *
5983  *      Wait for packets currently being received to be done.
5984  *      Does not block later packets from starting.
5985  */
5986 void synchronize_net(void)
5987 {
5988         might_sleep();
5989         if (rtnl_is_locked())
5990                 synchronize_rcu_expedited();
5991         else
5992                 synchronize_rcu();
5993 }
5994 EXPORT_SYMBOL(synchronize_net);
5995
5996 /**
5997  *      unregister_netdevice_queue - remove device from the kernel
5998  *      @dev: device
5999  *      @head: list
6000  *
6001  *      This function shuts down a device interface and removes it
6002  *      from the kernel tables.
6003  *      If head not NULL, device is queued to be unregistered later.
6004  *
6005  *      Callers must hold the rtnl semaphore.  You may want
6006  *      unregister_netdev() instead of this.
6007  */
6008
6009 void unregister_netdevice_queue(struct net_device *dev, struct list_head *head)
6010 {
6011         ASSERT_RTNL();
6012
6013         if (head) {
6014                 list_move_tail(&dev->unreg_list, head);
6015         } else {
6016                 rollback_registered(dev);
6017                 /* Finish processing unregister after unlock */
6018                 net_set_todo(dev);
6019         }
6020 }
6021 EXPORT_SYMBOL(unregister_netdevice_queue);
6022
6023 /**
6024  *      unregister_netdevice_many - unregister many devices
6025  *      @head: list of devices
6026  */
6027 void unregister_netdevice_many(struct list_head *head)
6028 {
6029         struct net_device *dev;
6030
6031         if (!list_empty(head)) {
6032                 rollback_registered_many(head);
6033                 list_for_each_entry(dev, head, unreg_list)
6034                         net_set_todo(dev);
6035         }
6036 }
6037 EXPORT_SYMBOL(unregister_netdevice_many);
6038
6039 /**
6040  *      unregister_netdev - remove device from the kernel
6041  *      @dev: device
6042  *
6043  *      This function shuts down a device interface and removes it
6044  *      from the kernel tables.
6045  *
6046  *      This is just a wrapper for unregister_netdevice that takes
6047  *      the rtnl semaphore.  In general you want to use this and not
6048  *      unregister_netdevice.
6049  */
6050 void unregister_netdev(struct net_device *dev)
6051 {
6052         rtnl_lock();
6053         unregister_netdevice(dev);
6054         rtnl_unlock();
6055 }
6056 EXPORT_SYMBOL(unregister_netdev);
6057
6058 /**
6059  *      dev_change_net_namespace - move device to different nethost namespace
6060  *      @dev: device
6061  *      @net: network namespace
6062  *      @pat: If not NULL name pattern to try if the current device name
6063  *            is already taken in the destination network namespace.
6064  *
6065  *      This function shuts down a device interface and moves it
6066  *      to a new network namespace. On success 0 is returned, on
6067  *      a failure a netagive errno code is returned.
6068  *
6069  *      Callers must hold the rtnl semaphore.
6070  */
6071
6072 int dev_change_net_namespace(struct net_device *dev, struct net *net, const char *pat)
6073 {
6074         int err;
6075
6076         ASSERT_RTNL();
6077
6078         /* Don't allow namespace local devices to be moved. */
6079         err = -EINVAL;
6080         if (dev->features & NETIF_F_NETNS_LOCAL)
6081                 goto out;
6082
6083         /* Ensure the device has been registrered */
6084         err = -EINVAL;
6085         if (dev->reg_state != NETREG_REGISTERED)
6086                 goto out;
6087
6088         /* Get out if there is nothing todo */
6089         err = 0;
6090         if (net_eq(dev_net(dev), net))
6091                 goto out;
6092
6093         /* Pick the destination device name, and ensure
6094          * we can use it in the destination network namespace.
6095          */
6096         err = -EEXIST;
6097         if (__dev_get_by_name(net, dev->name)) {
6098                 /* We get here if we can't use the current device name */
6099                 if (!pat)
6100                         goto out;
6101                 if (dev_get_valid_name(dev, pat) < 0)
6102                         goto out;
6103         }
6104
6105         /*
6106          * And now a mini version of register_netdevice unregister_netdevice.
6107          */
6108
6109         /* If device is running close it first. */
6110         dev_close(dev);
6111
6112         /* And unlink it from device chain */
6113         err = -ENODEV;
6114         unlist_netdevice(dev);
6115
6116         synchronize_net();
6117
6118         /* Shutdown queueing discipline. */
6119         dev_shutdown(dev);
6120
6121         /* Notify protocols, that we are about to destroy
6122            this device. They should clean all the things.
6123
6124            Note that dev->reg_state stays at NETREG_REGISTERED.
6125            This is wanted because this way 8021q and macvlan know
6126            the device is just moving and can keep their slaves up.
6127         */
6128         call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
6129         call_netdevice_notifiers(NETDEV_UNREGISTER_BATCH, dev);
6130         rtmsg_ifinfo(RTM_DELLINK, dev, ~0U);
6131
6132         /*
6133          *      Flush the unicast and multicast chains
6134          */
6135         dev_uc_flush(dev);
6136         dev_mc_flush(dev);
6137
6138         /* Actually switch the network namespace */
6139         dev_net_set(dev, net);
6140
6141         /* If there is an ifindex conflict assign a new one */
6142         if (__dev_get_by_index(net, dev->ifindex)) {
6143                 int iflink = (dev->iflink == dev->ifindex);
6144                 dev->ifindex = dev_new_index(net);
6145                 if (iflink)
6146                         dev->iflink = dev->ifindex;
6147         }
6148
6149         /* Fixup kobjects */
6150         err = device_rename(&dev->dev, dev->name);
6151         WARN_ON(err);
6152
6153         /* Add the device back in the hashes */
6154         list_netdevice(dev);
6155
6156         /* Notify protocols, that a new device appeared. */
6157         call_netdevice_notifiers(NETDEV_REGISTER, dev);
6158
6159         /*
6160          *      Prevent userspace races by waiting until the network
6161          *      device is fully setup before sending notifications.
6162          */
6163         rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U);
6164
6165         synchronize_net();
6166         err = 0;
6167 out:
6168         return err;
6169 }
6170 EXPORT_SYMBOL_GPL(dev_change_net_namespace);
6171
6172 static int dev_cpu_callback(struct notifier_block *nfb,
6173                             unsigned long action,
6174                             void *ocpu)
6175 {
6176         struct sk_buff **list_skb;
6177         struct sk_buff *skb;
6178         unsigned int cpu, oldcpu = (unsigned long)ocpu;
6179         struct softnet_data *sd, *oldsd;
6180
6181         if (action != CPU_DEAD && action != CPU_DEAD_FROZEN)
6182                 return NOTIFY_OK;
6183
6184         local_irq_disable();
6185         cpu = smp_processor_id();
6186         sd = &per_cpu(softnet_data, cpu);
6187         oldsd = &per_cpu(softnet_data, oldcpu);
6188
6189         /* Find end of our completion_queue. */
6190         list_skb = &sd->completion_queue;
6191         while (*list_skb)
6192                 list_skb = &(*list_skb)->next;
6193         /* Append completion queue from offline CPU. */
6194         *list_skb = oldsd->completion_queue;
6195         oldsd->completion_queue = NULL;
6196
6197         /* Append output queue from offline CPU. */
6198         if (oldsd->output_queue) {
6199                 *sd->output_queue_tailp = oldsd->output_queue;
6200                 sd->output_queue_tailp = oldsd->output_queue_tailp;
6201                 oldsd->output_queue = NULL;
6202                 oldsd->output_queue_tailp = &oldsd->output_queue;
6203         }
6204         /* Append NAPI poll list from offline CPU. */
6205         if (!list_empty(&oldsd->poll_list)) {
6206                 list_splice_init(&oldsd->poll_list, &sd->poll_list);
6207                 raise_softirq_irqoff(NET_RX_SOFTIRQ);
6208         }
6209
6210         raise_softirq_irqoff(NET_TX_SOFTIRQ);
6211         local_irq_enable();
6212
6213         /* Process offline CPU's input_pkt_queue */
6214         while ((skb = __skb_dequeue(&oldsd->process_queue))) {
6215                 netif_rx(skb);
6216                 input_queue_head_incr(oldsd);
6217         }
6218         while ((skb = __skb_dequeue(&oldsd->input_pkt_queue))) {
6219                 netif_rx(skb);
6220                 input_queue_head_incr(oldsd);
6221         }
6222
6223         return NOTIFY_OK;
6224 }
6225
6226
6227 /**
6228  *      netdev_increment_features - increment feature set by one
6229  *      @all: current feature set
6230  *      @one: new feature set
6231  *      @mask: mask feature set
6232  *
6233  *      Computes a new feature set after adding a device with feature set
6234  *      @one to the master device with current feature set @all.  Will not
6235  *      enable anything that is off in @mask. Returns the new feature set.
6236  */
6237 u32 netdev_increment_features(u32 all, u32 one, u32 mask)
6238 {
6239         if (mask & NETIF_F_GEN_CSUM)
6240                 mask |= NETIF_F_ALL_CSUM;
6241         mask |= NETIF_F_VLAN_CHALLENGED;
6242
6243         all |= one & (NETIF_F_ONE_FOR_ALL|NETIF_F_ALL_CSUM) & mask;
6244         all &= one | ~NETIF_F_ALL_FOR_ALL;
6245
6246         /* If device needs checksumming, downgrade to it. */
6247         if (all & (NETIF_F_ALL_CSUM & ~NETIF_F_NO_CSUM))
6248                 all &= ~NETIF_F_NO_CSUM;
6249
6250         /* If one device supports hw checksumming, set for all. */
6251         if (all & NETIF_F_GEN_CSUM)
6252                 all &= ~(NETIF_F_ALL_CSUM & ~NETIF_F_GEN_CSUM);
6253
6254         return all;
6255 }
6256 EXPORT_SYMBOL(netdev_increment_features);
6257
6258 static struct hlist_head *netdev_create_hash(void)
6259 {
6260         int i;
6261         struct hlist_head *hash;
6262
6263         hash = kmalloc(sizeof(*hash) * NETDEV_HASHENTRIES, GFP_KERNEL);
6264         if (hash != NULL)
6265                 for (i = 0; i < NETDEV_HASHENTRIES; i++)
6266                         INIT_HLIST_HEAD(&hash[i]);
6267
6268         return hash;
6269 }
6270
6271 /* Initialize per network namespace state */
6272 static int __net_init netdev_init(struct net *net)
6273 {
6274         if (net != &init_net)
6275                 INIT_LIST_HEAD(&net->dev_base_head);
6276
6277         net->dev_name_head = netdev_create_hash();
6278         if (net->dev_name_head == NULL)
6279                 goto err_name;
6280
6281         net->dev_index_head = netdev_create_hash();
6282         if (net->dev_index_head == NULL)
6283                 goto err_idx;
6284
6285         return 0;
6286
6287 err_idx:
6288         kfree(net->dev_name_head);
6289 err_name:
6290         return -ENOMEM;
6291 }
6292
6293 /**
6294  *      netdev_drivername - network driver for the device
6295  *      @dev: network device
6296  *
6297  *      Determine network driver for device.
6298  */
6299 const char *netdev_drivername(const struct net_device *dev)
6300 {
6301         const struct device_driver *driver;
6302         const struct device *parent;
6303         const char *empty = "";
6304
6305         parent = dev->dev.parent;
6306         if (!parent)
6307                 return empty;
6308
6309         driver = parent->driver;
6310         if (driver && driver->name)
6311                 return driver->name;
6312         return empty;
6313 }
6314
6315 static int __netdev_printk(const char *level, const struct net_device *dev,
6316                            struct va_format *vaf)
6317 {
6318         int r;
6319
6320         if (dev && dev->dev.parent)
6321                 r = dev_printk(level, dev->dev.parent, "%s: %pV",
6322                                netdev_name(dev), vaf);
6323         else if (dev)
6324                 r = printk("%s%s: %pV", level, netdev_name(dev), vaf);
6325         else
6326                 r = printk("%s(NULL net_device): %pV", level, vaf);
6327
6328         return r;
6329 }
6330
6331 int netdev_printk(const char *level, const struct net_device *dev,
6332                   const char *format, ...)
6333 {
6334         struct va_format vaf;
6335         va_list args;
6336         int r;
6337
6338         va_start(args, format);
6339
6340         vaf.fmt = format;
6341         vaf.va = &args;
6342
6343         r = __netdev_printk(level, dev, &vaf);
6344         va_end(args);
6345
6346         return r;
6347 }
6348 EXPORT_SYMBOL(netdev_printk);
6349
6350 #define define_netdev_printk_level(func, level)                 \
6351 int func(const struct net_device *dev, const char *fmt, ...)    \
6352 {                                                               \
6353         int r;                                                  \
6354         struct va_format vaf;                                   \
6355         va_list args;                                           \
6356                                                                 \
6357         va_start(args, fmt);                                    \
6358                                                                 \
6359         vaf.fmt = fmt;                                          \
6360         vaf.va = &args;                                         \
6361                                                                 \
6362         r = __netdev_printk(level, dev, &vaf);                  \
6363         va_end(args);                                           \
6364                                                                 \
6365         return r;                                               \
6366 }                                                               \
6367 EXPORT_SYMBOL(func);
6368
6369 define_netdev_printk_level(netdev_emerg, KERN_EMERG);
6370 define_netdev_printk_level(netdev_alert, KERN_ALERT);
6371 define_netdev_printk_level(netdev_crit, KERN_CRIT);
6372 define_netdev_printk_level(netdev_err, KERN_ERR);
6373 define_netdev_printk_level(netdev_warn, KERN_WARNING);
6374 define_netdev_printk_level(netdev_notice, KERN_NOTICE);
6375 define_netdev_printk_level(netdev_info, KERN_INFO);
6376
6377 static void __net_exit netdev_exit(struct net *net)
6378 {
6379         kfree(net->dev_name_head);
6380         kfree(net->dev_index_head);
6381 }
6382
6383 static struct pernet_operations __net_initdata netdev_net_ops = {
6384         .init = netdev_init,
6385         .exit = netdev_exit,
6386 };
6387
6388 static void __net_exit default_device_exit(struct net *net)
6389 {
6390         struct net_device *dev, *aux;
6391         /*
6392          * Push all migratable network devices back to the
6393          * initial network namespace
6394          */
6395         rtnl_lock();
6396         for_each_netdev_safe(net, dev, aux) {
6397                 int err;
6398                 char fb_name[IFNAMSIZ];
6399
6400                 /* Ignore unmoveable devices (i.e. loopback) */
6401                 if (dev->features & NETIF_F_NETNS_LOCAL)
6402                         continue;
6403
6404                 /* Leave virtual devices for the generic cleanup */
6405                 if (dev->rtnl_link_ops)
6406                         continue;
6407
6408                 /* Push remaining network devices to init_net */
6409                 snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex);
6410                 err = dev_change_net_namespace(dev, &init_net, fb_name);
6411                 if (err) {
6412                         printk(KERN_EMERG "%s: failed to move %s to init_net: %d\n",
6413                                 __func__, dev->name, err);
6414                         BUG();
6415                 }
6416         }
6417         rtnl_unlock();
6418 }
6419
6420 static void __net_exit default_device_exit_batch(struct list_head *net_list)
6421 {
6422         /* At exit all network devices most be removed from a network
6423          * namespace.  Do this in the reverse order of registration.
6424          * Do this across as many network namespaces as possible to
6425          * improve batching efficiency.
6426          */
6427         struct net_device *dev;
6428         struct net *net;
6429         LIST_HEAD(dev_kill_list);
6430
6431         rtnl_lock();
6432         list_for_each_entry(net, net_list, exit_list) {
6433                 for_each_netdev_reverse(net, dev) {
6434                         if (dev->rtnl_link_ops)
6435                                 dev->rtnl_link_ops->dellink(dev, &dev_kill_list);
6436                         else
6437                                 unregister_netdevice_queue(dev, &dev_kill_list);
6438                 }
6439         }
6440         unregister_netdevice_many(&dev_kill_list);
6441         list_del(&dev_kill_list);
6442         rtnl_unlock();
6443 }
6444
6445 static struct pernet_operations __net_initdata default_device_ops = {
6446         .exit = default_device_exit,
6447         .exit_batch = default_device_exit_batch,
6448 };
6449
6450 /*
6451  *      Initialize the DEV module. At boot time this walks the device list and
6452  *      unhooks any devices that fail to initialise (normally hardware not
6453  *      present) and leaves us with a valid list of present and active devices.
6454  *
6455  */
6456
6457 /*
6458  *       This is called single threaded during boot, so no need
6459  *       to take the rtnl semaphore.
6460  */
6461 static int __init net_dev_init(void)
6462 {
6463         int i, rc = -ENOMEM;
6464
6465         BUG_ON(!dev_boot_phase);
6466
6467         if (dev_proc_init())
6468                 goto out;
6469
6470         if (netdev_kobject_init())
6471                 goto out;
6472
6473         INIT_LIST_HEAD(&ptype_all);
6474         for (i = 0; i < PTYPE_HASH_SIZE; i++)
6475                 INIT_LIST_HEAD(&ptype_base[i]);
6476
6477         if (register_pernet_subsys(&netdev_net_ops))
6478                 goto out;
6479
6480         /*
6481          *      Initialise the packet receive queues.
6482          */
6483
6484         for_each_possible_cpu(i) {
6485                 struct softnet_data *sd = &per_cpu(softnet_data, i);
6486
6487                 memset(sd, 0, sizeof(*sd));
6488                 skb_queue_head_init(&sd->input_pkt_queue);
6489                 skb_queue_head_init(&sd->process_queue);
6490                 sd->completion_queue = NULL;
6491                 INIT_LIST_HEAD(&sd->poll_list);
6492                 sd->output_queue = NULL;
6493                 sd->output_queue_tailp = &sd->output_queue;
6494 #ifdef CONFIG_RPS
6495                 sd->csd.func = rps_trigger_softirq;
6496                 sd->csd.info = sd;
6497                 sd->csd.flags = 0;
6498                 sd->cpu = i;
6499 #endif
6500
6501                 sd->backlog.poll = process_backlog;
6502                 sd->backlog.weight = weight_p;
6503                 sd->backlog.gro_list = NULL;
6504                 sd->backlog.gro_count = 0;
6505         }
6506
6507         dev_boot_phase = 0;
6508
6509         /* The loopback device is special if any other network devices
6510          * is present in a network namespace the loopback device must
6511          * be present. Since we now dynamically allocate and free the
6512          * loopback device ensure this invariant is maintained by
6513          * keeping the loopback device as the first device on the
6514          * list of network devices.  Ensuring the loopback devices
6515          * is the first device that appears and the last network device
6516          * that disappears.
6517          */
6518         if (register_pernet_device(&loopback_net_ops))
6519                 goto out;
6520
6521         if (register_pernet_device(&default_device_ops))
6522                 goto out;
6523
6524         open_softirq(NET_TX_SOFTIRQ, net_tx_action);
6525         open_softirq(NET_RX_SOFTIRQ, net_rx_action);
6526
6527         hotcpu_notifier(dev_cpu_callback, 0);
6528         dst_init();
6529         dev_mcast_init();
6530         rc = 0;
6531 out:
6532         return rc;
6533 }
6534
6535 subsys_initcall(net_dev_init);
6536
6537 static int __init initialize_hashrnd(void)
6538 {
6539         get_random_bytes(&hashrnd, sizeof(hashrnd));
6540         return 0;
6541 }
6542
6543 late_initcall_sync(initialize_hashrnd);
6544