VServer 1.9.2 (patch-2.6.8.1-vs1.9.2.diff)
[linux-2.6.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, <bir7@leland.Stanford.Edu>
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 <asm/bitops.h>
78 #include <linux/config.h>
79 #include <linux/cpu.h>
80 #include <linux/types.h>
81 #include <linux/kernel.h>
82 #include <linux/sched.h>
83 #include <linux/string.h>
84 #include <linux/mm.h>
85 #include <linux/socket.h>
86 #include <linux/sockios.h>
87 #include <linux/errno.h>
88 #include <linux/interrupt.h>
89 #include <linux/if_ether.h>
90 #include <linux/netdevice.h>
91 #include <linux/etherdevice.h>
92 #include <linux/notifier.h>
93 #include <linux/skbuff.h>
94 #include <net/sock.h>
95 #include <linux/rtnetlink.h>
96 #include <linux/proc_fs.h>
97 #include <linux/seq_file.h>
98 #include <linux/stat.h>
99 #include <linux/if_bridge.h>
100 #include <linux/divert.h>
101 #include <net/dst.h>
102 #include <net/pkt_sched.h>
103 #include <net/checksum.h>
104 #include <linux/highmem.h>
105 #include <linux/init.h>
106 #include <linux/kmod.h>
107 #include <linux/module.h>
108 #include <linux/kallsyms.h>
109 #include <linux/netpoll.h>
110 #include <linux/rcupdate.h>
111 #ifdef CONFIG_NET_RADIO
112 #include <linux/wireless.h>             /* Note : will define WIRELESS_EXT */
113 #include <net/iw_handler.h>
114 #endif  /* CONFIG_NET_RADIO */
115 #include <asm/current.h>
116 #include <linux/vs_network.h>
117
118 /* This define, if set, will randomly drop a packet when congestion
119  * is more than moderate.  It helps fairness in the multi-interface
120  * case when one of them is a hog, but it kills performance for the
121  * single interface case so it is off now by default.
122  */
123 #undef RAND_LIE
124
125 /* Setting this will sample the queue lengths and thus congestion
126  * via a timer instead of as each packet is received.
127  */
128 #undef OFFLINE_SAMPLE
129
130 /*
131  *      The list of packet types we will receive (as opposed to discard)
132  *      and the routines to invoke.
133  *
134  *      Why 16. Because with 16 the only overlap we get on a hash of the
135  *      low nibble of the protocol value is RARP/SNAP/X.25.
136  *
137  *      NOTE:  That is no longer true with the addition of VLAN tags.  Not
138  *             sure which should go first, but I bet it won't make much
139  *             difference if we are running VLANs.  The good news is that
140  *             this protocol won't be in the list unless compiled in, so
141  *             the average user (w/out VLANs) will not be adversly affected.
142  *             --BLG
143  *
144  *              0800    IP
145  *              8100    802.1Q VLAN
146  *              0001    802.3
147  *              0002    AX.25
148  *              0004    802.2
149  *              8035    RARP
150  *              0005    SNAP
151  *              0805    X.25
152  *              0806    ARP
153  *              8137    IPX
154  *              0009    Localtalk
155  *              86DD    IPv6
156  */
157
158 static spinlock_t ptype_lock = SPIN_LOCK_UNLOCKED;
159 static struct list_head ptype_base[16]; /* 16 way hashed list */
160 static struct list_head ptype_all;              /* Taps */
161
162 #ifdef OFFLINE_SAMPLE
163 static void sample_queue(unsigned long dummy);
164 static struct timer_list samp_timer = TIMER_INITIALIZER(sample_queue, 0, 0);
165 #endif
166
167 /*
168  * The @dev_base list is protected by @dev_base_lock and the rtln
169  * semaphore.
170  *
171  * Pure readers hold dev_base_lock for reading.
172  *
173  * Writers must hold the rtnl semaphore while they loop through the
174  * dev_base list, and hold dev_base_lock for writing when they do the
175  * actual updates.  This allows pure readers to access the list even
176  * while a writer is preparing to update it.
177  *
178  * To put it another way, dev_base_lock is held for writing only to
179  * protect against pure readers; the rtnl semaphore provides the
180  * protection against other writers.
181  *
182  * See, for example usages, register_netdevice() and
183  * unregister_netdevice(), which must be called with the rtnl
184  * semaphore held.
185  */
186 struct net_device *dev_base;
187 struct net_device **dev_tail = &dev_base;
188 rwlock_t dev_base_lock = RW_LOCK_UNLOCKED;
189
190 EXPORT_SYMBOL(dev_base);
191 EXPORT_SYMBOL(dev_base_lock);
192
193 #define NETDEV_HASHBITS 8
194 static struct hlist_head dev_name_head[1<<NETDEV_HASHBITS];
195 static struct hlist_head dev_index_head[1<<NETDEV_HASHBITS];
196
197 static inline struct hlist_head *dev_name_hash(const char *name)
198 {
199         unsigned hash = full_name_hash(name, strnlen(name, IFNAMSIZ));
200         return &dev_name_head[hash & ((1<<NETDEV_HASHBITS)-1)];
201 }
202
203 static inline struct hlist_head *dev_index_hash(int ifindex)
204 {
205         return &dev_index_head[ifindex & ((1<<NETDEV_HASHBITS)-1)];
206 }
207
208 /*
209  *      Our notifier list
210  */
211
212 static struct notifier_block *netdev_chain;
213
214 /*
215  *      Device drivers call our routines to queue packets here. We empty the
216  *      queue in the local softnet handler.
217  */
218 DEFINE_PER_CPU(struct softnet_data, softnet_data) = { 0, };
219
220 #ifdef CONFIG_SYSFS
221 extern int netdev_sysfs_init(void);
222 extern int netdev_register_sysfs(struct net_device *);
223 extern void netdev_unregister_sysfs(struct net_device *);
224 #else
225 #define netdev_sysfs_init()             (0)
226 #define netdev_register_sysfs(dev)      (0)
227 #define netdev_unregister_sysfs(dev)    do { } while(0)
228 #endif
229
230
231 /*******************************************************************************
232
233                 Protocol management and registration routines
234
235 *******************************************************************************/
236
237 /*
238  *      For efficiency
239  */
240
241 int netdev_nit;
242
243 /*
244  *      Add a protocol ID to the list. Now that the input handler is
245  *      smarter we can dispense with all the messy stuff that used to be
246  *      here.
247  *
248  *      BEWARE!!! Protocol handlers, mangling input packets,
249  *      MUST BE last in hash buckets and checking protocol handlers
250  *      MUST start from promiscuous ptype_all chain in net_bh.
251  *      It is true now, do not change it.
252  *      Explanation follows: if protocol handler, mangling packet, will
253  *      be the first on list, it is not able to sense, that packet
254  *      is cloned and should be copied-on-write, so that it will
255  *      change it and subsequent readers will get broken packet.
256  *                                                      --ANK (980803)
257  */
258
259 /**
260  *      dev_add_pack - add packet handler
261  *      @pt: packet type declaration
262  *
263  *      Add a protocol handler to the networking stack. The passed &packet_type
264  *      is linked into kernel lists and may not be freed until it has been
265  *      removed from the kernel lists.
266  *
267  *      This call does not sleep therefore it can not 
268  *      guarantee all CPU's that are in middle of receiving packets
269  *      will see the new packet type (until the next received packet).
270  */
271
272 void dev_add_pack(struct packet_type *pt)
273 {
274         int hash;
275
276         spin_lock_bh(&ptype_lock);
277         if (pt->type == htons(ETH_P_ALL)) {
278                 netdev_nit++;
279                 list_add_rcu(&pt->list, &ptype_all);
280         } else {
281                 hash = ntohs(pt->type) & 15;
282                 list_add_rcu(&pt->list, &ptype_base[hash]);
283         }
284         spin_unlock_bh(&ptype_lock);
285 }
286
287 extern void linkwatch_run_queue(void);
288
289
290
291 /**
292  *      __dev_remove_pack        - remove packet handler
293  *      @pt: packet type declaration
294  *
295  *      Remove a protocol handler that was previously added to the kernel
296  *      protocol handlers by dev_add_pack(). The passed &packet_type is removed
297  *      from the kernel lists and can be freed or reused once this function
298  *      returns. 
299  *
300  *      The packet type might still be in use by receivers
301  *      and must not be freed until after all the CPU's have gone
302  *      through a quiescent state.
303  */
304 void __dev_remove_pack(struct packet_type *pt)
305 {
306         struct list_head *head;
307         struct packet_type *pt1;
308
309         spin_lock_bh(&ptype_lock);
310
311         if (pt->type == htons(ETH_P_ALL)) {
312                 netdev_nit--;
313                 head = &ptype_all;
314         } else
315                 head = &ptype_base[ntohs(pt->type) & 15];
316
317         list_for_each_entry(pt1, head, list) {
318                 if (pt == pt1) {
319                         list_del_rcu(&pt->list);
320                         goto out;
321                 }
322         }
323
324         printk(KERN_WARNING "dev_remove_pack: %p not found.\n", pt);
325 out:
326         spin_unlock_bh(&ptype_lock);
327 }
328 /**
329  *      dev_remove_pack  - remove packet handler
330  *      @pt: packet type declaration
331  *
332  *      Remove a protocol handler that was previously added to the kernel
333  *      protocol handlers by dev_add_pack(). The passed &packet_type is removed
334  *      from the kernel lists and can be freed or reused once this function
335  *      returns.
336  *
337  *      This call sleeps to guarantee that no CPU is looking at the packet
338  *      type after return.
339  */
340 void dev_remove_pack(struct packet_type *pt)
341 {
342         __dev_remove_pack(pt);
343         
344         synchronize_net();
345 }
346
347 /******************************************************************************
348
349                       Device Boot-time Settings Routines
350
351 *******************************************************************************/
352
353 /* Boot time configuration table */
354 static struct netdev_boot_setup dev_boot_setup[NETDEV_BOOT_SETUP_MAX];
355
356 /**
357  *      netdev_boot_setup_add   - add new setup entry
358  *      @name: name of the device
359  *      @map: configured settings for the device
360  *
361  *      Adds new setup entry to the dev_boot_setup list.  The function
362  *      returns 0 on error and 1 on success.  This is a generic routine to
363  *      all netdevices.
364  */
365 int netdev_boot_setup_add(char *name, struct ifmap *map)
366 {
367         struct netdev_boot_setup *s;
368         int i;
369
370         s = dev_boot_setup;
371         for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
372                 if (s[i].name[0] == '\0' || s[i].name[0] == ' ') {
373                         memset(s[i].name, 0, sizeof(s[i].name));
374                         strcpy(s[i].name, name);
375                         memcpy(&s[i].map, map, sizeof(s[i].map));
376                         break;
377                 }
378         }
379
380         return i >= NETDEV_BOOT_SETUP_MAX ? 0 : 1;
381 }
382
383 /**
384  *      netdev_boot_setup_check - check boot time settings
385  *      @dev: the netdevice
386  *
387  *      Check boot time settings for the device.
388  *      The found settings are set for the device to be used
389  *      later in the device probing.
390  *      Returns 0 if no settings found, 1 if they are.
391  */
392 int netdev_boot_setup_check(struct net_device *dev)
393 {
394         struct netdev_boot_setup *s = dev_boot_setup;
395         int i;
396
397         for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
398                 if (s[i].name[0] != '\0' && s[i].name[0] != ' ' &&
399                     !strncmp(dev->name, s[i].name, strlen(s[i].name))) {
400                         dev->irq        = s[i].map.irq;
401                         dev->base_addr  = s[i].map.base_addr;
402                         dev->mem_start  = s[i].map.mem_start;
403                         dev->mem_end    = s[i].map.mem_end;
404                         return 1;
405                 }
406         }
407         return 0;
408 }
409
410
411 /**
412  *      netdev_boot_base        - get address from boot time settings
413  *      @prefix: prefix for network device
414  *      @unit: id for network device
415  *
416  *      Check boot time settings for the base address of device.
417  *      The found settings are set for the device to be used
418  *      later in the device probing.
419  *      Returns 0 if no settings found.
420  */
421 unsigned long netdev_boot_base(const char *prefix, int unit)
422 {
423         const struct netdev_boot_setup *s = dev_boot_setup;
424         char name[IFNAMSIZ];
425         int i;
426
427         sprintf(name, "%s%d", prefix, unit);
428
429         /*
430          * If device already registered then return base of 1
431          * to indicate not to probe for this interface
432          */
433         if (__dev_get_by_name(name))
434                 return 1;
435
436         for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++)
437                 if (!strcmp(name, s[i].name))
438                         return s[i].map.base_addr;
439         return 0;
440 }
441
442 /*
443  * Saves at boot time configured settings for any netdevice.
444  */
445 int __init netdev_boot_setup(char *str)
446 {
447         int ints[5];
448         struct ifmap map;
449
450         str = get_options(str, ARRAY_SIZE(ints), ints);
451         if (!str || !*str)
452                 return 0;
453
454         /* Save settings */
455         memset(&map, 0, sizeof(map));
456         if (ints[0] > 0)
457                 map.irq = ints[1];
458         if (ints[0] > 1)
459                 map.base_addr = ints[2];
460         if (ints[0] > 2)
461                 map.mem_start = ints[3];
462         if (ints[0] > 3)
463                 map.mem_end = ints[4];
464
465         /* Add new entry to the list */
466         return netdev_boot_setup_add(str, &map);
467 }
468
469 __setup("netdev=", netdev_boot_setup);
470
471 /*******************************************************************************
472
473                             Device Interface Subroutines
474
475 *******************************************************************************/
476
477 /**
478  *      __dev_get_by_name       - find a device by its name
479  *      @name: name to find
480  *
481  *      Find an interface by name. Must be called under RTNL semaphore
482  *      or @dev_base_lock. If the name is found a pointer to the device
483  *      is returned. If the name is not found then %NULL is returned. The
484  *      reference counters are not incremented so the caller must be
485  *      careful with locks.
486  */
487
488 struct net_device *__dev_get_by_name(const char *name)
489 {
490         struct hlist_node *p;
491
492         hlist_for_each(p, dev_name_hash(name)) {
493                 struct net_device *dev
494                         = hlist_entry(p, struct net_device, name_hlist);
495                 if (!strncmp(dev->name, name, IFNAMSIZ))
496                         return dev;
497         }
498         return NULL;
499 }
500
501 /**
502  *      dev_get_by_name         - find a device by its name
503  *      @name: name to find
504  *
505  *      Find an interface by name. This can be called from any
506  *      context and does its own locking. The returned handle has
507  *      the usage count incremented and the caller must use dev_put() to
508  *      release it when it is no longer needed. %NULL is returned if no
509  *      matching device is found.
510  */
511
512 struct net_device *dev_get_by_name(const char *name)
513 {
514         struct net_device *dev;
515
516         read_lock(&dev_base_lock);
517         dev = __dev_get_by_name(name);
518         if (dev)
519                 dev_hold(dev);
520         read_unlock(&dev_base_lock);
521         return dev;
522 }
523
524 /*
525    Return value is changed to int to prevent illegal usage in future.
526    It is still legal to use to check for device existence.
527
528    User should understand, that the result returned by this function
529    is meaningless, if it was not issued under rtnl semaphore.
530  */
531
532 /**
533  *      dev_get -       test if a device exists
534  *      @name:  name to test for
535  *
536  *      Test if a name exists. Returns true if the name is found. In order
537  *      to be sure the name is not allocated or removed during the test the
538  *      caller must hold the rtnl semaphore.
539  *
540  *      This function exists only for back compatibility with older
541  *      drivers.
542  */
543 int __dev_get(const char *name)
544 {
545         struct net_device *dev;
546
547         read_lock(&dev_base_lock);
548         dev = __dev_get_by_name(name);
549         read_unlock(&dev_base_lock);
550         return dev != NULL;
551 }
552
553 /**
554  *      __dev_get_by_index - find a device by its ifindex
555  *      @ifindex: index of device
556  *
557  *      Search for an interface by index. Returns %NULL if the device
558  *      is not found or a pointer to the device. The device has not
559  *      had its reference counter increased so the caller must be careful
560  *      about locking. The caller must hold either the RTNL semaphore
561  *      or @dev_base_lock.
562  */
563
564 struct net_device *__dev_get_by_index(int ifindex)
565 {
566         struct hlist_node *p;
567
568         hlist_for_each(p, dev_index_hash(ifindex)) {
569                 struct net_device *dev
570                         = hlist_entry(p, struct net_device, index_hlist);
571                 if (dev->ifindex == ifindex)
572                         return dev;
573         }
574         return NULL;
575 }
576
577
578 /**
579  *      dev_get_by_index - find a device by its ifindex
580  *      @ifindex: index of device
581  *
582  *      Search for an interface by index. Returns NULL if the device
583  *      is not found or a pointer to the device. The device returned has
584  *      had a reference added and the pointer is safe until the user calls
585  *      dev_put to indicate they have finished with it.
586  */
587
588 struct net_device *dev_get_by_index(int ifindex)
589 {
590         struct net_device *dev;
591
592         read_lock(&dev_base_lock);
593         dev = __dev_get_by_index(ifindex);
594         if (dev)
595                 dev_hold(dev);
596         read_unlock(&dev_base_lock);
597         return dev;
598 }
599
600 /**
601  *      dev_getbyhwaddr - find a device by its hardware address
602  *      @type: media type of device
603  *      @ha: hardware address
604  *
605  *      Search for an interface by MAC address. Returns NULL if the device
606  *      is not found or a pointer to the device. The caller must hold the
607  *      rtnl semaphore. The returned device has not had its ref count increased
608  *      and the caller must therefore be careful about locking
609  *
610  *      BUGS:
611  *      If the API was consistent this would be __dev_get_by_hwaddr
612  */
613
614 struct net_device *dev_getbyhwaddr(unsigned short type, char *ha)
615 {
616         struct net_device *dev;
617
618         ASSERT_RTNL();
619
620         for (dev = dev_base; dev; dev = dev->next)
621                 if (dev->type == type &&
622                     !memcmp(dev->dev_addr, ha, dev->addr_len))
623                         break;
624         return dev;
625 }
626
627 struct net_device *__dev_getfirstbyhwtype(unsigned short type)
628 {
629         struct net_device *dev;
630
631         for (dev = dev_base; dev; dev = dev->next)
632                 if (dev->type == type)
633                         break;
634         return dev;
635 }
636
637 EXPORT_SYMBOL(__dev_getfirstbyhwtype);
638
639 struct net_device *dev_getfirstbyhwtype(unsigned short type)
640 {
641         struct net_device *dev;
642
643         rtnl_lock();
644         dev = __dev_getfirstbyhwtype(type);
645         if (dev)
646                 dev_hold(dev);
647         rtnl_unlock();
648         return dev;
649 }
650
651 EXPORT_SYMBOL(dev_getfirstbyhwtype);
652
653 /**
654  *      dev_get_by_flags - find any device with given flags
655  *      @if_flags: IFF_* values
656  *      @mask: bitmask of bits in if_flags to check
657  *
658  *      Search for any interface with the given flags. Returns NULL if a device
659  *      is not found or a pointer to the device. The device returned has 
660  *      had a reference added and the pointer is safe until the user calls
661  *      dev_put to indicate they have finished with it.
662  */
663
664 struct net_device * dev_get_by_flags(unsigned short if_flags, unsigned short mask)
665 {
666         struct net_device *dev;
667
668         read_lock(&dev_base_lock);
669         dev = __dev_get_by_flags(if_flags, mask);
670         if (dev)
671                 dev_hold(dev);
672         read_unlock(&dev_base_lock);
673         return dev;
674 }
675
676 /**
677  *      __dev_get_by_flags - find any device with given flags
678  *      @if_flags: IFF_* values
679  *      @mask: bitmask of bits in if_flags to check
680  *
681  *      Search for any interface with the given flags. Returns NULL if a device
682  *      is not found or a pointer to the device. The caller must hold either
683  *      the RTNL semaphore or @dev_base_lock.
684  */
685
686 struct net_device *__dev_get_by_flags(unsigned short if_flags, unsigned short mask)
687 {
688         struct net_device *dev;
689
690         for (dev = dev_base; dev != NULL; dev = dev->next) {
691                 if (((dev->flags ^ if_flags) & mask) == 0)
692                         return dev;
693         }
694         return NULL;
695 }
696
697 /**
698  *      dev_valid_name - check if name is okay for network device
699  *      @name: name string
700  *
701  *      Network device names need to be valid file names to
702  *      to allow sysfs to work
703  */
704 int dev_valid_name(const char *name)
705 {
706         return !(*name == '\0' 
707                  || !strcmp(name, ".")
708                  || !strcmp(name, "..")
709                  || strchr(name, '/'));
710 }
711
712 /**
713  *      dev_alloc_name - allocate a name for a device
714  *      @dev: device
715  *      @name: name format string
716  *
717  *      Passed a format string - eg "lt%d" it will try and find a suitable
718  *      id. Not efficient for many devices, not called a lot. The caller
719  *      must hold the dev_base or rtnl lock while allocating the name and
720  *      adding the device in order to avoid duplicates. Returns the number
721  *      of the unit assigned or a negative errno code.
722  */
723
724 int dev_alloc_name(struct net_device *dev, const char *name)
725 {
726         int i = 0;
727         char buf[IFNAMSIZ];
728         const char *p;
729         const int max_netdevices = 8*PAGE_SIZE;
730         long *inuse;
731         struct net_device *d;
732
733         p = strnchr(name, IFNAMSIZ-1, '%');
734         if (p) {
735                 /*
736                  * Verify the string as this thing may have come from
737                  * the user.  There must be either one "%d" and no other "%"
738                  * characters.
739                  */
740                 if (p[1] != 'd' || strchr(p + 2, '%'))
741                         return -EINVAL;
742
743                 /* Use one page as a bit array of possible slots */
744                 inuse = (long *) get_zeroed_page(GFP_ATOMIC);
745                 if (!inuse)
746                         return -ENOMEM;
747
748                 for (d = dev_base; d; d = d->next) {
749                         if (!sscanf(d->name, name, &i))
750                                 continue;
751                         if (i < 0 || i >= max_netdevices)
752                                 continue;
753
754                         /*  avoid cases where sscanf is not exact inverse of printf */
755                         snprintf(buf, sizeof(buf), name, i);
756                         if (!strncmp(buf, d->name, IFNAMSIZ))
757                                 set_bit(i, inuse);
758                 }
759
760                 i = find_first_zero_bit(inuse, max_netdevices);
761                 free_page((unsigned long) inuse);
762         }
763
764         snprintf(buf, sizeof(buf), name, i);
765         if (!__dev_get_by_name(buf)) {
766                 strlcpy(dev->name, buf, IFNAMSIZ);
767                 return i;
768         }
769
770         /* It is possible to run out of possible slots
771          * when the name is long and there isn't enough space left
772          * for the digits, or if all bits are used.
773          */
774         return -ENFILE;
775 }
776
777
778 /**
779  *      dev_change_name - change name of a device
780  *      @dev: device
781  *      @newname: name (or format string) must be at least IFNAMSIZ
782  *
783  *      Change name of a device, can pass format strings "eth%d".
784  *      for wildcarding.
785  */
786 int dev_change_name(struct net_device *dev, char *newname)
787 {
788         int err = 0;
789
790         ASSERT_RTNL();
791
792         if (dev->flags & IFF_UP)
793                 return -EBUSY;
794
795         if (!dev_valid_name(newname))
796                 return -EINVAL;
797
798         if (strchr(newname, '%')) {
799                 err = dev_alloc_name(dev, newname);
800                 if (err < 0)
801                         return err;
802                 strcpy(newname, dev->name);
803         }
804         else if (__dev_get_by_name(newname))
805                 return -EEXIST;
806         else
807                 strlcpy(dev->name, newname, IFNAMSIZ);
808
809         err = class_device_rename(&dev->class_dev, dev->name);
810         if (!err) {
811                 hlist_del(&dev->name_hlist);
812                 hlist_add_head(&dev->name_hlist, dev_name_hash(dev->name));
813                 notifier_call_chain(&netdev_chain, NETDEV_CHANGENAME, dev);
814         }
815
816         return err;
817 }
818
819 /**
820  *      netdev_state_change - device changes state
821  *      @dev: device to cause notification
822  *
823  *      Called to indicate a device has changed state. This function calls
824  *      the notifier chains for netdev_chain and sends a NEWLINK message
825  *      to the routing socket.
826  */
827 void netdev_state_change(struct net_device *dev)
828 {
829         if (dev->flags & IFF_UP) {
830                 notifier_call_chain(&netdev_chain, NETDEV_CHANGE, dev);
831                 rtmsg_ifinfo(RTM_NEWLINK, dev, 0);
832         }
833 }
834
835 /**
836  *      dev_load        - load a network module
837  *      @name: name of interface
838  *
839  *      If a network interface is not present and the process has suitable
840  *      privileges this function loads the module. If module loading is not
841  *      available in this kernel then it becomes a nop.
842  */
843
844 void dev_load(const char *name)
845 {
846         struct net_device *dev;  
847
848         read_lock(&dev_base_lock);
849         dev = __dev_get_by_name(name);
850         read_unlock(&dev_base_lock);
851
852         if (!dev && capable(CAP_SYS_MODULE))
853                 request_module("%s", name);
854 }
855
856 static int default_rebuild_header(struct sk_buff *skb)
857 {
858         printk(KERN_DEBUG "%s: default_rebuild_header called -- BUG!\n",
859                skb->dev ? skb->dev->name : "NULL!!!");
860         kfree_skb(skb);
861         return 1;
862 }
863
864
865 /*
866  * Some old buggy device drivers change get_stats after registering
867  * the device.  Try and trap them here.
868  * This can be elimnated when all devices are known fixed.
869  */
870 static inline int get_stats_changed(struct net_device *dev)
871 {
872         int changed = dev->last_stats != dev->get_stats;
873         dev->last_stats = dev->get_stats;
874         return changed;
875 }
876
877 /**
878  *      dev_open        - prepare an interface for use.
879  *      @dev:   device to open
880  *
881  *      Takes a device from down to up state. The device's private open
882  *      function is invoked and then the multicast lists are loaded. Finally
883  *      the device is moved into the up state and a %NETDEV_UP message is
884  *      sent to the netdev notifier chain.
885  *
886  *      Calling this function on an active interface is a nop. On a failure
887  *      a negative errno code is returned.
888  */
889 int dev_open(struct net_device *dev)
890 {
891         int ret = 0;
892
893         /*
894          *      Is it already up?
895          */
896
897         if (dev->flags & IFF_UP)
898                 return 0;
899
900         /*
901          *       Check for broken device drivers.
902          */
903         if (get_stats_changed(dev) && net_ratelimit()) {
904                 printk(KERN_ERR "%s: driver changed get_stats after register\n",
905                        dev->name);
906         }
907
908         /*
909          *      Is it even present?
910          */
911         if (!netif_device_present(dev))
912                 return -ENODEV;
913
914         /*
915          *      Call device private open method
916          */
917         set_bit(__LINK_STATE_START, &dev->state);
918         if (dev->open) {
919                 ret = dev->open(dev);
920                 if (ret)
921                         clear_bit(__LINK_STATE_START, &dev->state);
922         }
923
924         /*
925          *      Check for more broken device drivers.
926          */
927         if (get_stats_changed(dev) && net_ratelimit()) {
928                 printk(KERN_ERR "%s: driver changed get_stats in open\n",
929                        dev->name);
930         }
931
932         /*
933          *      If it went open OK then:
934          */
935
936         if (!ret) {
937                 /*
938                  *      Set the flags.
939                  */
940                 dev->flags |= IFF_UP;
941
942                 /*
943                  *      Initialize multicasting status
944                  */
945                 dev_mc_upload(dev);
946
947                 /*
948                  *      Wakeup transmit queue engine
949                  */
950                 dev_activate(dev);
951
952                 /*
953                  *      ... and announce new interface.
954                  */
955                 notifier_call_chain(&netdev_chain, NETDEV_UP, dev);
956         }
957         return ret;
958 }
959
960 /**
961  *      dev_close - shutdown an interface.
962  *      @dev: device to shutdown
963  *
964  *      This function moves an active device into down state. A
965  *      %NETDEV_GOING_DOWN is sent to the netdev notifier chain. The device
966  *      is then deactivated and finally a %NETDEV_DOWN is sent to the notifier
967  *      chain.
968  */
969 int dev_close(struct net_device *dev)
970 {
971         if (!(dev->flags & IFF_UP))
972                 return 0;
973
974         /*
975          *      Tell people we are going down, so that they can
976          *      prepare to death, when device is still operating.
977          */
978         notifier_call_chain(&netdev_chain, NETDEV_GOING_DOWN, dev);
979
980         dev_deactivate(dev);
981
982         clear_bit(__LINK_STATE_START, &dev->state);
983
984         /* Synchronize to scheduled poll. We cannot touch poll list,
985          * it can be even on different cpu. So just clear netif_running(),
986          * and wait when poll really will happen. Actually, the best place
987          * for this is inside dev->stop() after device stopped its irq
988          * engine, but this requires more changes in devices. */
989
990         smp_mb__after_clear_bit(); /* Commit netif_running(). */
991         while (test_bit(__LINK_STATE_RX_SCHED, &dev->state)) {
992                 /* No hurry. */
993                 current->state = TASK_INTERRUPTIBLE;
994                 schedule_timeout(1);
995         }
996
997         /*
998          *      Call the device specific close. This cannot fail.
999          *      Only if device is UP
1000          *
1001          *      We allow it to be called even after a DETACH hot-plug
1002          *      event.
1003          */
1004         if (dev->stop)
1005                 dev->stop(dev);
1006
1007         /*
1008          *      Device is now down.
1009          */
1010
1011         dev->flags &= ~IFF_UP;
1012
1013         /*
1014          * Tell people we are down
1015          */
1016         notifier_call_chain(&netdev_chain, NETDEV_DOWN, dev);
1017
1018         return 0;
1019 }
1020
1021
1022 /*
1023  *      Device change register/unregister. These are not inline or static
1024  *      as we export them to the world.
1025  */
1026
1027 /**
1028  *      register_netdevice_notifier - register a network notifier block
1029  *      @nb: notifier
1030  *
1031  *      Register a notifier to be called when network device events occur.
1032  *      The notifier passed is linked into the kernel structures and must
1033  *      not be reused until it has been unregistered. A negative errno code
1034  *      is returned on a failure.
1035  *
1036  *      When registered all registration and up events are replayed
1037  *      to the new notifier to allow device to have a race free 
1038  *      view of the network device list.
1039  */
1040
1041 int register_netdevice_notifier(struct notifier_block *nb)
1042 {
1043         struct net_device *dev;
1044         int err;
1045
1046         rtnl_lock();
1047         err = notifier_chain_register(&netdev_chain, nb);
1048         if (!err) {
1049                 for (dev = dev_base; dev; dev = dev->next) {
1050                         nb->notifier_call(nb, NETDEV_REGISTER, dev);
1051
1052                         if (dev->flags & IFF_UP) 
1053                                 nb->notifier_call(nb, NETDEV_UP, dev);
1054                 }
1055         }
1056         rtnl_unlock();
1057         return err;
1058 }
1059
1060 /**
1061  *      unregister_netdevice_notifier - unregister a network notifier block
1062  *      @nb: notifier
1063  *
1064  *      Unregister a notifier previously registered by
1065  *      register_netdevice_notifier(). The notifier is unlinked into the
1066  *      kernel structures and may then be reused. A negative errno code
1067  *      is returned on a failure.
1068  */
1069
1070 int unregister_netdevice_notifier(struct notifier_block *nb)
1071 {
1072         return notifier_chain_unregister(&netdev_chain, nb);
1073 }
1074
1075 /**
1076  *      call_netdevice_notifiers - call all network notifier blocks
1077  *      @val: value passed unmodified to notifier function
1078  *      @v:   pointer passed unmodified to notifier function
1079  *
1080  *      Call all network notifier blocks.  Parameters and return value
1081  *      are as for notifier_call_chain().
1082  */
1083
1084 int call_netdevice_notifiers(unsigned long val, void *v)
1085 {
1086         return notifier_call_chain(&netdev_chain, val, v);
1087 }
1088
1089 /*
1090  *      Support routine. Sends outgoing frames to any network
1091  *      taps currently in use.
1092  */
1093
1094 void dev_queue_xmit_nit(struct sk_buff *skb, struct net_device *dev)
1095 {
1096         struct packet_type *ptype;
1097         net_timestamp(&skb->stamp);
1098
1099         rcu_read_lock();
1100         list_for_each_entry_rcu(ptype, &ptype_all, list) {
1101                 /* Never send packets back to the socket
1102                  * they originated from - MvS (miquels@drinkel.ow.org)
1103                  */
1104                 if ((ptype->dev == dev || !ptype->dev) &&
1105                     (ptype->af_packet_priv == NULL ||
1106                      (struct sock *)ptype->af_packet_priv != skb->sk)) {
1107                         struct sk_buff *skb2= skb_clone(skb, GFP_ATOMIC);
1108                         if (!skb2)
1109                                 break;
1110
1111                         /* skb->nh should be correctly
1112                            set by sender, so that the second statement is
1113                            just protection against buggy protocols.
1114                          */
1115                         skb2->mac.raw = skb2->data;
1116
1117                         if (skb2->nh.raw < skb2->data ||
1118                             skb2->nh.raw > skb2->tail) {
1119                                 if (net_ratelimit())
1120                                         printk(KERN_CRIT "protocol %04x is "
1121                                                "buggy, dev %s\n",
1122                                                skb2->protocol, dev->name);
1123                                 skb2->nh.raw = skb2->data;
1124                         }
1125
1126                         skb2->h.raw = skb2->nh.raw;
1127                         skb2->pkt_type = PACKET_OUTGOING;
1128                         ptype->func(skb2, skb->dev, ptype);
1129                 }
1130         }
1131         rcu_read_unlock();
1132 }
1133
1134 /*
1135  * Invalidate hardware checksum when packet is to be mangled, and
1136  * complete checksum manually on outgoing path.
1137  */
1138 int skb_checksum_help(struct sk_buff **pskb, int inward)
1139 {
1140         unsigned int csum;
1141         int ret = 0, offset = (*pskb)->h.raw - (*pskb)->data;
1142
1143         if (inward) {
1144                 (*pskb)->ip_summed = CHECKSUM_NONE;
1145                 goto out;
1146         }
1147
1148         if (skb_shared(*pskb)  || skb_cloned(*pskb)) {
1149                 struct sk_buff *newskb = skb_copy(*pskb, GFP_ATOMIC);
1150                 if (!newskb) {
1151                         ret = -ENOMEM;
1152                         goto out;
1153                 }
1154                 if ((*pskb)->sk)
1155                         skb_set_owner_w(newskb, (*pskb)->sk);
1156                 kfree_skb(*pskb);
1157                 *pskb = newskb;
1158         }
1159
1160         if (offset > (int)(*pskb)->len)
1161                 BUG();
1162         csum = skb_checksum(*pskb, offset, (*pskb)->len-offset, 0);
1163
1164         offset = (*pskb)->tail - (*pskb)->h.raw;
1165         if (offset <= 0)
1166                 BUG();
1167         if ((*pskb)->csum + 2 > offset)
1168                 BUG();
1169
1170         *(u16*)((*pskb)->h.raw + (*pskb)->csum) = csum_fold(csum);
1171         (*pskb)->ip_summed = CHECKSUM_NONE;
1172 out:    
1173         return ret;
1174 }
1175
1176 #ifdef CONFIG_HIGHMEM
1177 /* Actually, we should eliminate this check as soon as we know, that:
1178  * 1. IOMMU is present and allows to map all the memory.
1179  * 2. No high memory really exists on this machine.
1180  */
1181
1182 static inline int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
1183 {
1184         int i;
1185
1186         if (dev->features & NETIF_F_HIGHDMA)
1187                 return 0;
1188
1189         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1190                 if (skb_shinfo(skb)->frags[i].page >= highmem_start_page)
1191                         return 1;
1192
1193         return 0;
1194 }
1195 #else
1196 #define illegal_highdma(dev, skb)       (0)
1197 #endif
1198
1199 extern void skb_release_data(struct sk_buff *);
1200
1201 /* Keep head the same: replace data */
1202 int __skb_linearize(struct sk_buff *skb, int gfp_mask)
1203 {
1204         unsigned int size;
1205         u8 *data;
1206         long offset;
1207         struct skb_shared_info *ninfo;
1208         int headerlen = skb->data - skb->head;
1209         int expand = (skb->tail + skb->data_len) - skb->end;
1210
1211         if (skb_shared(skb))
1212                 BUG();
1213
1214         if (expand <= 0)
1215                 expand = 0;
1216
1217         size = skb->end - skb->head + expand;
1218         size = SKB_DATA_ALIGN(size);
1219         data = kmalloc(size + sizeof(struct skb_shared_info), gfp_mask);
1220         if (!data)
1221                 return -ENOMEM;
1222
1223         /* Copy entire thing */
1224         if (skb_copy_bits(skb, -headerlen, data, headerlen + skb->len))
1225                 BUG();
1226
1227         /* Set up shinfo */
1228         ninfo = (struct skb_shared_info*)(data + size);
1229         atomic_set(&ninfo->dataref, 1);
1230         ninfo->tso_size = skb_shinfo(skb)->tso_size;
1231         ninfo->tso_segs = skb_shinfo(skb)->tso_segs;
1232         ninfo->nr_frags = 0;
1233         ninfo->frag_list = NULL;
1234
1235         /* Offset between the two in bytes */
1236         offset = data - skb->head;
1237
1238         /* Free old data. */
1239         skb_release_data(skb);
1240
1241         skb->head = data;
1242         skb->end  = data + size;
1243
1244         /* Set up new pointers */
1245         skb->h.raw   += offset;
1246         skb->nh.raw  += offset;
1247         skb->mac.raw += offset;
1248         skb->tail    += offset;
1249         skb->data    += offset;
1250
1251         /* We are no longer a clone, even if we were. */
1252         skb->cloned    = 0;
1253
1254         skb->tail     += skb->data_len;
1255         skb->data_len  = 0;
1256         return 0;
1257 }
1258
1259 #define HARD_TX_LOCK_BH(dev, cpu) {                     \
1260         if ((dev->features & NETIF_F_LLTX) == 0) {      \
1261                 spin_lock_bh(&dev->xmit_lock);          \
1262                 dev->xmit_lock_owner = cpu;             \
1263         }                                               \
1264 }
1265
1266 #define HARD_TX_UNLOCK_BH(dev) {                        \
1267         if ((dev->features & NETIF_F_LLTX) == 0) {      \
1268                 dev->xmit_lock_owner = -1;              \
1269                 spin_unlock_bh(&dev->xmit_lock);        \
1270         }                                               \
1271 }
1272
1273 static inline void qdisc_run(struct net_device *dev)
1274 {
1275         while (!netif_queue_stopped(dev) &&
1276                qdisc_restart(dev)<0)
1277                 /* NOTHING */;
1278 }
1279
1280 /**
1281  *      dev_queue_xmit - transmit a buffer
1282  *      @skb: buffer to transmit
1283  *
1284  *      Queue a buffer for transmission to a network device. The caller must
1285  *      have set the device and priority and built the buffer before calling
1286  *      this function. The function can be called from an interrupt.
1287  *
1288  *      A negative errno code is returned on a failure. A success does not
1289  *      guarantee the frame will be transmitted as it may be dropped due
1290  *      to congestion or traffic shaping.
1291  */
1292
1293 int dev_queue_xmit(struct sk_buff *skb)
1294 {
1295         struct net_device *dev = skb->dev;
1296         struct Qdisc *q;
1297         int rc = -ENOMEM;
1298
1299         if (skb_shinfo(skb)->frag_list &&
1300             !(dev->features & NETIF_F_FRAGLIST) &&
1301             __skb_linearize(skb, GFP_ATOMIC))
1302                 goto out_kfree_skb;
1303
1304         /* Fragmented skb is linearized if device does not support SG,
1305          * or if at least one of fragments is in highmem and device
1306          * does not support DMA from it.
1307          */
1308         if (skb_shinfo(skb)->nr_frags &&
1309             (!(dev->features & NETIF_F_SG) || illegal_highdma(dev, skb)) &&
1310             __skb_linearize(skb, GFP_ATOMIC))
1311                 goto out_kfree_skb;
1312
1313         /* If packet is not checksummed and device does not support
1314          * checksumming for this protocol, complete checksumming here.
1315          */
1316         if (skb->ip_summed == CHECKSUM_HW &&
1317             (!(dev->features & (NETIF_F_HW_CSUM | NETIF_F_NO_CSUM)) &&
1318              (!(dev->features & NETIF_F_IP_CSUM) ||
1319               skb->protocol != htons(ETH_P_IP))))
1320                 if (skb_checksum_help(&skb, 0))
1321                         goto out_kfree_skb;
1322
1323         rcu_read_lock();
1324         /* Updates of qdisc are serialized by queue_lock. 
1325          * The struct Qdisc which is pointed to by qdisc is now a 
1326          * rcu structure - it may be accessed without acquiring 
1327          * a lock (but the structure may be stale.) The freeing of the
1328          * qdisc will be deferred until it's known that there are no 
1329          * more references to it.
1330          * 
1331          * If the qdisc has an enqueue function, we still need to 
1332          * hold the queue_lock before calling it, since queue_lock
1333          * also serializes access to the device queue.
1334          */
1335
1336         q = dev->qdisc;
1337         smp_read_barrier_depends();
1338 #ifdef CONFIG_NET_CLS_ACT
1339         skb->tc_verd = SET_TC_AT(skb->tc_verd,AT_EGRESS);
1340 #endif
1341         if (q->enqueue) {
1342                 /* Grab device queue */
1343                 spin_lock_bh(&dev->queue_lock);
1344
1345                 rc = q->enqueue(skb, q);
1346
1347                 qdisc_run(dev);
1348
1349                 spin_unlock_bh(&dev->queue_lock);
1350                 rcu_read_unlock();
1351                 rc = rc == NET_XMIT_BYPASS ? NET_XMIT_SUCCESS : rc;
1352                 goto out;
1353         }
1354         rcu_read_unlock();
1355
1356         /* The device has no queue. Common case for software devices:
1357            loopback, all the sorts of tunnels...
1358
1359            Really, it is unlikely that xmit_lock protection is necessary here.
1360            (f.e. loopback and IP tunnels are clean ignoring statistics
1361            counters.)
1362            However, it is possible, that they rely on protection
1363            made by us here.
1364
1365            Check this and shot the lock. It is not prone from deadlocks.
1366            Either shot noqueue qdisc, it is even simpler 8)
1367          */
1368         if (dev->flags & IFF_UP) {
1369                 int cpu = get_cpu();
1370
1371                 if (dev->xmit_lock_owner != cpu) {
1372
1373                         HARD_TX_LOCK_BH(dev, cpu);
1374                         put_cpu();
1375
1376                         if (!netif_queue_stopped(dev)) {
1377                                 if (netdev_nit)
1378                                         dev_queue_xmit_nit(skb, dev);
1379
1380                                 rc = 0;
1381                                 if (!dev->hard_start_xmit(skb, dev)) {
1382                                         HARD_TX_UNLOCK_BH(dev);
1383                                         goto out;
1384                                 }
1385                         }
1386                         HARD_TX_UNLOCK_BH(dev);
1387                         if (net_ratelimit())
1388                                 printk(KERN_CRIT "Virtual device %s asks to "
1389                                        "queue packet!\n", dev->name);
1390                         goto out_enetdown;
1391                 } else {
1392                         put_cpu();
1393                         /* Recursion is detected! It is possible,
1394                          * unfortunately */
1395                         if (net_ratelimit())
1396                                 printk(KERN_CRIT "Dead loop on virtual device "
1397                                        "%s, fix it urgently!\n", dev->name);
1398                 }
1399         }
1400 out_enetdown:
1401         rc = -ENETDOWN;
1402 out_kfree_skb:
1403         kfree_skb(skb);
1404 out:
1405         return rc;
1406 }
1407
1408
1409 /*=======================================================================
1410                         Receiver routines
1411   =======================================================================*/
1412
1413 int netdev_max_backlog = 300;
1414 int weight_p = 64;            /* old backlog weight */
1415 /* These numbers are selected based on intuition and some
1416  * experimentatiom, if you have more scientific way of doing this
1417  * please go ahead and fix things.
1418  */
1419 int no_cong_thresh = 10;
1420 int no_cong = 20;
1421 int lo_cong = 100;
1422 int mod_cong = 290;
1423
1424 DEFINE_PER_CPU(struct netif_rx_stats, netdev_rx_stat) = { 0, };
1425
1426
1427 #ifdef CONFIG_NET_HW_FLOWCONTROL
1428 atomic_t netdev_dropping = ATOMIC_INIT(0);
1429 static unsigned long netdev_fc_mask = 1;
1430 unsigned long netdev_fc_xoff;
1431 spinlock_t netdev_fc_lock = SPIN_LOCK_UNLOCKED;
1432
1433 static struct
1434 {
1435         void (*stimul)(struct net_device *);
1436         struct net_device *dev;
1437 } netdev_fc_slots[BITS_PER_LONG];
1438
1439 int netdev_register_fc(struct net_device *dev,
1440                        void (*stimul)(struct net_device *dev))
1441 {
1442         int bit = 0;
1443         unsigned long flags;
1444
1445         spin_lock_irqsave(&netdev_fc_lock, flags);
1446         if (netdev_fc_mask != ~0UL) {
1447                 bit = ffz(netdev_fc_mask);
1448                 netdev_fc_slots[bit].stimul = stimul;
1449                 netdev_fc_slots[bit].dev = dev;
1450                 set_bit(bit, &netdev_fc_mask);
1451                 clear_bit(bit, &netdev_fc_xoff);
1452         }
1453         spin_unlock_irqrestore(&netdev_fc_lock, flags);
1454         return bit;
1455 }
1456
1457 void netdev_unregister_fc(int bit)
1458 {
1459         unsigned long flags;
1460
1461         spin_lock_irqsave(&netdev_fc_lock, flags);
1462         if (bit > 0) {
1463                 netdev_fc_slots[bit].stimul = NULL;
1464                 netdev_fc_slots[bit].dev = NULL;
1465                 clear_bit(bit, &netdev_fc_mask);
1466                 clear_bit(bit, &netdev_fc_xoff);
1467         }
1468         spin_unlock_irqrestore(&netdev_fc_lock, flags);
1469 }
1470
1471 static void netdev_wakeup(void)
1472 {
1473         unsigned long xoff;
1474
1475         spin_lock(&netdev_fc_lock);
1476         xoff = netdev_fc_xoff;
1477         netdev_fc_xoff = 0;
1478         while (xoff) {
1479                 int i = ffz(~xoff);
1480                 xoff &= ~(1 << i);
1481                 netdev_fc_slots[i].stimul(netdev_fc_slots[i].dev);
1482         }
1483         spin_unlock(&netdev_fc_lock);
1484 }
1485 #endif
1486
1487 static void get_sample_stats(int cpu)
1488 {
1489 #ifdef RAND_LIE
1490         unsigned long rd;
1491         int rq;
1492 #endif
1493         struct softnet_data *sd = &per_cpu(softnet_data, cpu);
1494         int blog = sd->input_pkt_queue.qlen;
1495         int avg_blog = sd->avg_blog;
1496
1497         avg_blog = (avg_blog >> 1) + (blog >> 1);
1498
1499         if (avg_blog > mod_cong) {
1500                 /* Above moderate congestion levels. */
1501                 sd->cng_level = NET_RX_CN_HIGH;
1502 #ifdef RAND_LIE
1503                 rd = net_random();
1504                 rq = rd % netdev_max_backlog;
1505                 if (rq < avg_blog) /* unlucky bastard */
1506                         sd->cng_level = NET_RX_DROP;
1507 #endif
1508         } else if (avg_blog > lo_cong) {
1509                 sd->cng_level = NET_RX_CN_MOD;
1510 #ifdef RAND_LIE
1511                 rd = net_random();
1512                 rq = rd % netdev_max_backlog;
1513                         if (rq < avg_blog) /* unlucky bastard */
1514                                 sd->cng_level = NET_RX_CN_HIGH;
1515 #endif
1516         } else if (avg_blog > no_cong)
1517                 sd->cng_level = NET_RX_CN_LOW;
1518         else  /* no congestion */
1519                 sd->cng_level = NET_RX_SUCCESS;
1520
1521         sd->avg_blog = avg_blog;
1522 }
1523
1524 #ifdef OFFLINE_SAMPLE
1525 static void sample_queue(unsigned long dummy)
1526 {
1527 /* 10 ms 0r 1ms -- i don't care -- JHS */
1528         int next_tick = 1;
1529         int cpu = smp_processor_id();
1530
1531         get_sample_stats(cpu);
1532         next_tick += jiffies;
1533         mod_timer(&samp_timer, next_tick);
1534 }
1535 #endif
1536
1537
1538 /**
1539  *      netif_rx        -       post buffer to the network code
1540  *      @skb: buffer to post
1541  *
1542  *      This function receives a packet from a device driver and queues it for
1543  *      the upper (protocol) levels to process.  It always succeeds. The buffer
1544  *      may be dropped during processing for congestion control or by the
1545  *      protocol layers.
1546  *
1547  *      return values:
1548  *      NET_RX_SUCCESS  (no congestion)
1549  *      NET_RX_CN_LOW   (low congestion)
1550  *      NET_RX_CN_MOD   (moderate congestion)
1551  *      NET_RX_CN_HIGH  (high congestion)
1552  *      NET_RX_DROP     (packet was dropped)
1553  *
1554  */
1555
1556 int netif_rx(struct sk_buff *skb)
1557 {
1558         int this_cpu;
1559         struct softnet_data *queue;
1560         unsigned long flags;
1561
1562 #ifdef CONFIG_NETPOLL_RX
1563         if (skb->dev->netpoll_rx && netpoll_rx(skb)) {
1564                 kfree_skb(skb);
1565                 return NET_RX_DROP;
1566         }
1567 #endif
1568         
1569         if (!skb->stamp.tv_sec)
1570                 net_timestamp(&skb->stamp);
1571
1572         /*
1573          * The code is rearranged so that the path is the most
1574          * short when CPU is congested, but is still operating.
1575          */
1576         local_irq_save(flags);
1577         this_cpu = smp_processor_id();
1578         queue = &__get_cpu_var(softnet_data);
1579
1580         __get_cpu_var(netdev_rx_stat).total++;
1581         if (queue->input_pkt_queue.qlen <= netdev_max_backlog) {
1582                 if (queue->input_pkt_queue.qlen) {
1583                         if (queue->throttle)
1584                                 goto drop;
1585
1586 enqueue:
1587                         dev_hold(skb->dev);
1588                         __skb_queue_tail(&queue->input_pkt_queue, skb);
1589 #ifndef OFFLINE_SAMPLE
1590                         get_sample_stats(this_cpu);
1591 #endif
1592                         local_irq_restore(flags);
1593                         return queue->cng_level;
1594                 }
1595
1596                 if (queue->throttle) {
1597                         queue->throttle = 0;
1598 #ifdef CONFIG_NET_HW_FLOWCONTROL
1599                         if (atomic_dec_and_test(&netdev_dropping))
1600                                 netdev_wakeup();
1601 #endif
1602                 }
1603
1604                 netif_rx_schedule(&queue->backlog_dev);
1605                 goto enqueue;
1606         }
1607
1608         if (!queue->throttle) {
1609                 queue->throttle = 1;
1610                 __get_cpu_var(netdev_rx_stat).throttled++;
1611 #ifdef CONFIG_NET_HW_FLOWCONTROL
1612                 atomic_inc(&netdev_dropping);
1613 #endif
1614         }
1615
1616 drop:
1617         __get_cpu_var(netdev_rx_stat).dropped++;
1618         local_irq_restore(flags);
1619
1620         kfree_skb(skb);
1621         return NET_RX_DROP;
1622 }
1623
1624 static __inline__ void skb_bond(struct sk_buff *skb)
1625 {
1626         struct net_device *dev = skb->dev;
1627
1628         if (dev->master) {
1629                 skb->real_dev = skb->dev;
1630                 skb->dev = dev->master;
1631         }
1632 }
1633
1634 static void net_tx_action(struct softirq_action *h)
1635 {
1636         struct softnet_data *sd = &__get_cpu_var(softnet_data);
1637
1638         if (sd->completion_queue) {
1639                 struct sk_buff *clist;
1640
1641                 local_irq_disable();
1642                 clist = sd->completion_queue;
1643                 sd->completion_queue = NULL;
1644                 local_irq_enable();
1645
1646                 while (clist) {
1647                         struct sk_buff *skb = clist;
1648                         clist = clist->next;
1649
1650                         BUG_TRAP(!atomic_read(&skb->users));
1651                         __kfree_skb(skb);
1652                 }
1653         }
1654
1655         if (sd->output_queue) {
1656                 struct net_device *head;
1657
1658                 local_irq_disable();
1659                 head = sd->output_queue;
1660                 sd->output_queue = NULL;
1661                 local_irq_enable();
1662
1663                 while (head) {
1664                         struct net_device *dev = head;
1665                         head = head->next_sched;
1666
1667                         smp_mb__before_clear_bit();
1668                         clear_bit(__LINK_STATE_SCHED, &dev->state);
1669
1670                         if (spin_trylock(&dev->queue_lock)) {
1671                                 qdisc_run(dev);
1672                                 spin_unlock(&dev->queue_lock);
1673                         } else {
1674                                 netif_schedule(dev);
1675                         }
1676                 }
1677         }
1678 }
1679
1680 static __inline__ int deliver_skb(struct sk_buff *skb,
1681                                   struct packet_type *pt_prev, int last)
1682 {
1683         atomic_inc(&skb->users);
1684         return pt_prev->func(skb, skb->dev, pt_prev);
1685 }
1686
1687
1688 #if defined(CONFIG_BRIDGE) || defined (CONFIG_BRIDGE_MODULE)
1689 int (*br_handle_frame_hook)(struct sk_buff *skb);
1690
1691 static __inline__ int handle_bridge(struct sk_buff *skb,
1692                                      struct packet_type *pt_prev)
1693 {
1694         int ret = NET_RX_DROP;
1695         if (pt_prev)
1696                 ret = deliver_skb(skb, pt_prev, 0);
1697
1698         return ret;
1699 }
1700
1701 #endif
1702
1703 static inline int __handle_bridge(struct sk_buff *skb,
1704                         struct packet_type **pt_prev, int *ret)
1705 {
1706 #if defined(CONFIG_BRIDGE) || defined(CONFIG_BRIDGE_MODULE)
1707         if (skb->dev->br_port && skb->pkt_type != PACKET_LOOPBACK) {
1708                 *ret = handle_bridge(skb, *pt_prev);
1709                 if (br_handle_frame_hook(skb) == 0)
1710                         return 1;
1711
1712                 *pt_prev = NULL;
1713         }
1714 #endif
1715         return 0;
1716 }
1717
1718
1719 #ifdef CONFIG_NET_CLS_ACT
1720 /* TODO: Maybe we should just force sch_ingress to be compiled in
1721  * when CONFIG_NET_CLS_ACT is? otherwise some useless instructions
1722  * a compare and 2 stores extra right now if we dont have it on
1723  * but have CONFIG_NET_CLS_ACT
1724  * NOTE: This doesnt stop any functionality; if you dont have 
1725  * the ingress scheduler, you just cant add policies on ingress.
1726  *
1727  */
1728 int ing_filter(struct sk_buff *skb) 
1729 {
1730         struct Qdisc *q;
1731         struct net_device *dev = skb->dev;
1732         int result = TC_ACT_OK;
1733         
1734         if (dev->qdisc_ingress) {
1735                 __u32 ttl = (__u32) G_TC_RTTL(skb->tc_verd);
1736                 if (MAX_RED_LOOP < ttl++) {
1737                         printk("Redir loop detected Dropping packet (%s->%s)\n",
1738                                 skb->input_dev?skb->input_dev->name:"??",skb->dev->name);
1739                         return TC_ACT_SHOT;
1740                 }
1741
1742                 skb->tc_verd = SET_TC_RTTL(skb->tc_verd,ttl);
1743
1744                 skb->tc_verd = SET_TC_AT(skb->tc_verd,AT_INGRESS);
1745                 if (NULL == skb->input_dev) {
1746                         skb->input_dev = skb->dev;
1747                         printk("ing_filter:  fixed  %s out %s\n",skb->input_dev->name,skb->dev->name);
1748                 }
1749                 spin_lock(&dev->ingress_lock);
1750                 if ((q = dev->qdisc_ingress) != NULL)
1751                         result = q->enqueue(skb, q);
1752                 spin_unlock(&dev->ingress_lock);
1753
1754         }
1755
1756         return result;
1757 }
1758 #endif
1759
1760 int netif_receive_skb(struct sk_buff *skb)
1761 {
1762         struct packet_type *ptype, *pt_prev;
1763         int ret = NET_RX_DROP;
1764         unsigned short type;
1765
1766 #ifdef CONFIG_NETPOLL_RX
1767         if (skb->dev->netpoll_rx && skb->dev->poll && netpoll_rx(skb)) {
1768                 kfree_skb(skb);
1769                 return NET_RX_DROP;
1770         }
1771 #endif
1772
1773         if (!skb->stamp.tv_sec)
1774                 net_timestamp(&skb->stamp);
1775
1776         skb_bond(skb);
1777
1778         __get_cpu_var(netdev_rx_stat).total++;
1779
1780         skb->h.raw = skb->nh.raw = skb->data;
1781         skb->mac_len = skb->nh.raw - skb->mac.raw;
1782
1783         pt_prev = NULL;
1784 #ifdef CONFIG_NET_CLS_ACT
1785         if (skb->tc_verd & TC_NCLS) {
1786                 skb->tc_verd = CLR_TC_NCLS(skb->tc_verd);
1787                 rcu_read_lock();
1788                 goto ncls;
1789         }
1790  #endif
1791
1792         rcu_read_lock();
1793         list_for_each_entry_rcu(ptype, &ptype_all, list) {
1794                 if (!ptype->dev || ptype->dev == skb->dev) {
1795                         if (pt_prev) 
1796                                 ret = deliver_skb(skb, pt_prev, 0);
1797                         pt_prev = ptype;
1798                 }
1799         }
1800
1801 #ifdef CONFIG_NET_CLS_ACT
1802         if (pt_prev) {
1803                 atomic_inc(&skb->users);
1804                 ret = pt_prev->func(skb, skb->dev, pt_prev);
1805                 pt_prev = NULL; /* noone else should process this after*/
1806         } else {
1807                 skb->tc_verd = SET_TC_OK2MUNGE(skb->tc_verd);
1808         }
1809
1810         ret = ing_filter(skb);
1811
1812         if (ret == TC_ACT_SHOT || (ret == TC_ACT_STOLEN)) {
1813                 kfree_skb(skb);
1814                 goto out;
1815         }
1816
1817         skb->tc_verd = 0;
1818 ncls:
1819 #endif
1820
1821         handle_diverter(skb);
1822
1823         if (__handle_bridge(skb, &pt_prev, &ret))
1824                 goto out;
1825
1826         type = skb->protocol;
1827         list_for_each_entry_rcu(ptype, &ptype_base[ntohs(type)&15], list) {
1828                 if (ptype->type == type &&
1829                     (!ptype->dev || ptype->dev == skb->dev)) {
1830                         if (pt_prev) 
1831                                 ret = deliver_skb(skb, pt_prev, 0);
1832                         pt_prev = ptype;
1833                 }
1834         }
1835
1836         if (pt_prev) {
1837                 ret = pt_prev->func(skb, skb->dev, pt_prev);
1838         } else {
1839                 kfree_skb(skb);
1840                 /* Jamal, now you will not able to escape explaining
1841                  * me how you were going to use this. :-)
1842                  */
1843                 ret = NET_RX_DROP;
1844         }
1845
1846 out:
1847         rcu_read_unlock();
1848         return ret;
1849 }
1850
1851 static int process_backlog(struct net_device *backlog_dev, int *budget)
1852 {
1853         int work = 0;
1854         int quota = min(backlog_dev->quota, *budget);
1855         struct softnet_data *queue = &__get_cpu_var(softnet_data);
1856         unsigned long start_time = jiffies;
1857
1858         for (;;) {
1859                 struct sk_buff *skb;
1860                 struct net_device *dev;
1861
1862                 local_irq_disable();
1863                 skb = __skb_dequeue(&queue->input_pkt_queue);
1864                 if (!skb)
1865                         goto job_done;
1866                 local_irq_enable();
1867
1868                 dev = skb->dev;
1869
1870                 netif_receive_skb(skb);
1871
1872                 dev_put(dev);
1873
1874                 work++;
1875
1876                 if (work >= quota || jiffies - start_time > 1)
1877                         break;
1878
1879 #ifdef CONFIG_NET_HW_FLOWCONTROL
1880                 if (queue->throttle &&
1881                     queue->input_pkt_queue.qlen < no_cong_thresh ) {
1882                         queue->throttle = 0;
1883                         if (atomic_dec_and_test(&netdev_dropping)) {
1884                                 netdev_wakeup();
1885                                 break;
1886                         }
1887                 }
1888 #endif
1889         }
1890
1891         backlog_dev->quota -= work;
1892         *budget -= work;
1893         return -1;
1894
1895 job_done:
1896         backlog_dev->quota -= work;
1897         *budget -= work;
1898
1899         list_del(&backlog_dev->poll_list);
1900         smp_mb__before_clear_bit();
1901         netif_poll_enable(backlog_dev);
1902
1903         if (queue->throttle) {
1904                 queue->throttle = 0;
1905 #ifdef CONFIG_NET_HW_FLOWCONTROL
1906                 if (atomic_dec_and_test(&netdev_dropping))
1907                         netdev_wakeup();
1908 #endif
1909         }
1910         local_irq_enable();
1911         return 0;
1912 }
1913
1914 static void net_rx_action(struct softirq_action *h)
1915 {
1916         struct softnet_data *queue = &__get_cpu_var(softnet_data);
1917         unsigned long start_time = jiffies;
1918         int budget = netdev_max_backlog;
1919
1920         
1921         local_irq_disable();
1922
1923         while (!list_empty(&queue->poll_list)) {
1924                 struct net_device *dev;
1925
1926                 if (budget <= 0 || jiffies - start_time > 1)
1927                         goto softnet_break;
1928
1929                 local_irq_enable();
1930
1931                 dev = list_entry(queue->poll_list.next,
1932                                  struct net_device, poll_list);
1933
1934                 if (dev->quota <= 0 || dev->poll(dev, &budget)) {
1935                         local_irq_disable();
1936                         list_del(&dev->poll_list);
1937                         list_add_tail(&dev->poll_list, &queue->poll_list);
1938                         if (dev->quota < 0)
1939                                 dev->quota += dev->weight;
1940                         else
1941                                 dev->quota = dev->weight;
1942                 } else {
1943                         dev_put(dev);
1944                         local_irq_disable();
1945                 }
1946         }
1947 out:
1948         local_irq_enable();
1949         return;
1950
1951 softnet_break:
1952         __get_cpu_var(netdev_rx_stat).time_squeeze++;
1953         __raise_softirq_irqoff(NET_RX_SOFTIRQ);
1954         goto out;
1955 }
1956
1957 static gifconf_func_t * gifconf_list [NPROTO];
1958
1959 /**
1960  *      register_gifconf        -       register a SIOCGIF handler
1961  *      @family: Address family
1962  *      @gifconf: Function handler
1963  *
1964  *      Register protocol dependent address dumping routines. The handler
1965  *      that is passed must not be freed or reused until it has been replaced
1966  *      by another handler.
1967  */
1968 int register_gifconf(unsigned int family, gifconf_func_t * gifconf)
1969 {
1970         if (family >= NPROTO)
1971                 return -EINVAL;
1972         gifconf_list[family] = gifconf;
1973         return 0;
1974 }
1975
1976
1977 /*
1978  *      Map an interface index to its name (SIOCGIFNAME)
1979  */
1980
1981 /*
1982  *      We need this ioctl for efficient implementation of the
1983  *      if_indextoname() function required by the IPv6 API.  Without
1984  *      it, we would have to search all the interfaces to find a
1985  *      match.  --pb
1986  */
1987
1988 static int dev_ifname(struct ifreq __user *arg)
1989 {
1990         struct net_device *dev;
1991         struct ifreq ifr;
1992
1993         /*
1994          *      Fetch the caller's info block.
1995          */
1996
1997         if (copy_from_user(&ifr, arg, sizeof(struct ifreq)))
1998                 return -EFAULT;
1999
2000         read_lock(&dev_base_lock);
2001         dev = __dev_get_by_index(ifr.ifr_ifindex);
2002         if (!dev) {
2003                 read_unlock(&dev_base_lock);
2004                 return -ENODEV;
2005         }
2006
2007         strcpy(ifr.ifr_name, dev->name);
2008         read_unlock(&dev_base_lock);
2009
2010         if (copy_to_user(arg, &ifr, sizeof(struct ifreq)))
2011                 return -EFAULT;
2012         return 0;
2013 }
2014
2015 /*
2016  *      Perform a SIOCGIFCONF call. This structure will change
2017  *      size eventually, and there is nothing I can do about it.
2018  *      Thus we will need a 'compatibility mode'.
2019  */
2020
2021 static int dev_ifconf(char __user *arg)
2022 {
2023         struct ifconf ifc;
2024         struct net_device *dev;
2025         char __user *pos;
2026         int len;
2027         int total;
2028         int i;
2029
2030         /*
2031          *      Fetch the caller's info block.
2032          */
2033
2034         if (copy_from_user(&ifc, arg, sizeof(struct ifconf)))
2035                 return -EFAULT;
2036
2037         pos = ifc.ifc_buf;
2038         len = ifc.ifc_len;
2039
2040         /*
2041          *      Loop over the interfaces, and write an info block for each.
2042          */
2043
2044         total = 0;
2045         for (dev = dev_base; dev; dev = dev->next) {
2046                 if (!dev_in_nx_info(dev, current->nx_info))
2047                         continue;
2048                 for (i = 0; i < NPROTO; i++) {
2049                         if (gifconf_list[i]) {
2050                                 int done;
2051                                 if (!pos)
2052                                         done = gifconf_list[i](dev, NULL, 0);
2053                                 else
2054                                         done = gifconf_list[i](dev, pos + total,
2055                                                                len - total);
2056                                 if (done < 0)
2057                                         return -EFAULT;
2058                                 total += done;
2059                         }
2060                 }
2061         }
2062
2063         /*
2064          *      All done.  Write the updated control block back to the caller.
2065          */
2066         ifc.ifc_len = total;
2067
2068         /*
2069          *      Both BSD and Solaris return 0 here, so we do too.
2070          */
2071         return copy_to_user(arg, &ifc, sizeof(struct ifconf)) ? -EFAULT : 0;
2072 }
2073
2074 #ifdef CONFIG_PROC_FS
2075 /*
2076  *      This is invoked by the /proc filesystem handler to display a device
2077  *      in detail.
2078  */
2079 static __inline__ struct net_device *dev_get_idx(loff_t pos)
2080 {
2081         struct net_device *dev;
2082         loff_t i;
2083
2084         for (i = 0, dev = dev_base; dev && i < pos; ++i, dev = dev->next);
2085
2086         return i == pos ? dev : NULL;
2087 }
2088
2089 void *dev_seq_start(struct seq_file *seq, loff_t *pos)
2090 {
2091         read_lock(&dev_base_lock);
2092         return *pos ? dev_get_idx(*pos - 1) : SEQ_START_TOKEN;
2093 }
2094
2095 void *dev_seq_next(struct seq_file *seq, void *v, loff_t *pos)
2096 {
2097         ++*pos;
2098         return v == SEQ_START_TOKEN ? dev_base : ((struct net_device *)v)->next;
2099 }
2100
2101 void dev_seq_stop(struct seq_file *seq, void *v)
2102 {
2103         read_unlock(&dev_base_lock);
2104 }
2105
2106 static void dev_seq_printf_stats(struct seq_file *seq, struct net_device *dev)
2107 {
2108         struct nx_info *nxi = current->nx_info;
2109
2110         if (!dev_in_nx_info(dev, nxi))
2111                 return;
2112         if (dev->get_stats) {
2113                 struct net_device_stats *stats = dev->get_stats(dev);
2114
2115                 seq_printf(seq, "%6s:%8lu %7lu %4lu %4lu %4lu %5lu %10lu %9lu "
2116                                 "%8lu %7lu %4lu %4lu %4lu %5lu %7lu %10lu\n",
2117                            dev->name, stats->rx_bytes, stats->rx_packets,
2118                            stats->rx_errors,
2119                            stats->rx_dropped + stats->rx_missed_errors,
2120                            stats->rx_fifo_errors,
2121                            stats->rx_length_errors + stats->rx_over_errors +
2122                              stats->rx_crc_errors + stats->rx_frame_errors,
2123                            stats->rx_compressed, stats->multicast,
2124                            stats->tx_bytes, stats->tx_packets,
2125                            stats->tx_errors, stats->tx_dropped,
2126                            stats->tx_fifo_errors, stats->collisions,
2127                            stats->tx_carrier_errors +
2128                              stats->tx_aborted_errors +
2129                              stats->tx_window_errors +
2130                              stats->tx_heartbeat_errors,
2131                            stats->tx_compressed);
2132         } else
2133                 seq_printf(seq, "%6s: No statistics available.\n", dev->name);
2134 }
2135
2136 /*
2137  *      Called from the PROCfs module. This now uses the new arbitrary sized
2138  *      /proc/net interface to create /proc/net/dev
2139  */
2140 static int dev_seq_show(struct seq_file *seq, void *v)
2141 {
2142         if (v == SEQ_START_TOKEN)
2143                 seq_puts(seq, "Inter-|   Receive                            "
2144                               "                    |  Transmit\n"
2145                               " face |bytes    packets errs drop fifo frame "
2146                               "compressed multicast|bytes    packets errs "
2147                               "drop fifo colls carrier compressed\n");
2148         else
2149                 dev_seq_printf_stats(seq, v);
2150         return 0;
2151 }
2152
2153 static struct netif_rx_stats *softnet_get_online(loff_t *pos)
2154 {
2155         struct netif_rx_stats *rc = NULL;
2156
2157         while (*pos < NR_CPUS)
2158                 if (cpu_online(*pos)) {
2159                         rc = &per_cpu(netdev_rx_stat, *pos);
2160                         break;
2161                 } else
2162                         ++*pos;
2163         return rc;
2164 }
2165
2166 static void *softnet_seq_start(struct seq_file *seq, loff_t *pos)
2167 {
2168         return softnet_get_online(pos);
2169 }
2170
2171 static void *softnet_seq_next(struct seq_file *seq, void *v, loff_t *pos)
2172 {
2173         ++*pos;
2174         return softnet_get_online(pos);
2175 }
2176
2177 static void softnet_seq_stop(struct seq_file *seq, void *v)
2178 {
2179 }
2180
2181 static int softnet_seq_show(struct seq_file *seq, void *v)
2182 {
2183         struct netif_rx_stats *s = v;
2184
2185         seq_printf(seq, "%08x %08x %08x %08x %08x %08x %08x %08x %08x\n",
2186                    s->total, s->dropped, s->time_squeeze, s->throttled,
2187                    s->fastroute_hit, s->fastroute_success, s->fastroute_defer,
2188                    s->fastroute_deferred_out,
2189 #if 0
2190                    s->fastroute_latency_reduction
2191 #else
2192                    s->cpu_collision
2193 #endif
2194                   );
2195         return 0;
2196 }
2197
2198 static struct seq_operations dev_seq_ops = {
2199         .start = dev_seq_start,
2200         .next  = dev_seq_next,
2201         .stop  = dev_seq_stop,
2202         .show  = dev_seq_show,
2203 };
2204
2205 static int dev_seq_open(struct inode *inode, struct file *file)
2206 {
2207         return seq_open(file, &dev_seq_ops);
2208 }
2209
2210 static struct file_operations dev_seq_fops = {
2211         .owner   = THIS_MODULE,
2212         .open    = dev_seq_open,
2213         .read    = seq_read,
2214         .llseek  = seq_lseek,
2215         .release = seq_release,
2216 };
2217
2218 static struct seq_operations softnet_seq_ops = {
2219         .start = softnet_seq_start,
2220         .next  = softnet_seq_next,
2221         .stop  = softnet_seq_stop,
2222         .show  = softnet_seq_show,
2223 };
2224
2225 static int softnet_seq_open(struct inode *inode, struct file *file)
2226 {
2227         return seq_open(file, &softnet_seq_ops);
2228 }
2229
2230 static struct file_operations softnet_seq_fops = {
2231         .owner   = THIS_MODULE,
2232         .open    = softnet_seq_open,
2233         .read    = seq_read,
2234         .llseek  = seq_lseek,
2235         .release = seq_release,
2236 };
2237
2238 #ifdef WIRELESS_EXT
2239 extern int wireless_proc_init(void);
2240 #else
2241 #define wireless_proc_init() 0
2242 #endif
2243
2244 static int __init dev_proc_init(void)
2245 {
2246         int rc = -ENOMEM;
2247
2248         if (!proc_net_fops_create("dev", S_IRUGO, &dev_seq_fops))
2249                 goto out;
2250         if (!proc_net_fops_create("softnet_stat", S_IRUGO, &softnet_seq_fops))
2251                 goto out_dev;
2252         if (wireless_proc_init())
2253                 goto out_softnet;
2254         rc = 0;
2255 out:
2256         return rc;
2257 out_softnet:
2258         proc_net_remove("softnet_stat");
2259 out_dev:
2260         proc_net_remove("dev");
2261         goto out;
2262 }
2263 #else
2264 #define dev_proc_init() 0
2265 #endif  /* CONFIG_PROC_FS */
2266
2267
2268 /**
2269  *      netdev_set_master       -       set up master/slave pair
2270  *      @slave: slave device
2271  *      @master: new master device
2272  *
2273  *      Changes the master device of the slave. Pass %NULL to break the
2274  *      bonding. The caller must hold the RTNL semaphore. On a failure
2275  *      a negative errno code is returned. On success the reference counts
2276  *      are adjusted, %RTM_NEWLINK is sent to the routing socket and the
2277  *      function returns zero.
2278  */
2279 int netdev_set_master(struct net_device *slave, struct net_device *master)
2280 {
2281         struct net_device *old = slave->master;
2282
2283         ASSERT_RTNL();
2284
2285         if (master) {
2286                 if (old)
2287                         return -EBUSY;
2288                 dev_hold(master);
2289         }
2290
2291         slave->master = master;
2292         
2293         synchronize_net();
2294
2295         if (old)
2296                 dev_put(old);
2297
2298         if (master)
2299                 slave->flags |= IFF_SLAVE;
2300         else
2301                 slave->flags &= ~IFF_SLAVE;
2302
2303         rtmsg_ifinfo(RTM_NEWLINK, slave, IFF_SLAVE);
2304         return 0;
2305 }
2306
2307 /**
2308  *      dev_set_promiscuity     - update promiscuity count on a device
2309  *      @dev: device
2310  *      @inc: modifier
2311  *
2312  *      Add or remove promsicuity from a device. While the count in the device
2313  *      remains above zero the interface remains promiscuous. Once it hits zero
2314  *      the device reverts back to normal filtering operation. A negative inc
2315  *      value is used to drop promiscuity on the device.
2316  */
2317 void dev_set_promiscuity(struct net_device *dev, int inc)
2318 {
2319         unsigned short old_flags = dev->flags;
2320
2321         dev->flags |= IFF_PROMISC;
2322         if ((dev->promiscuity += inc) == 0)
2323                 dev->flags &= ~IFF_PROMISC;
2324         if (dev->flags ^ old_flags) {
2325                 dev_mc_upload(dev);
2326                 printk(KERN_INFO "device %s %s promiscuous mode\n",
2327                        dev->name, (dev->flags & IFF_PROMISC) ? "entered" :
2328                                                                "left");
2329         }
2330 }
2331
2332 /**
2333  *      dev_set_allmulti        - update allmulti count on a device
2334  *      @dev: device
2335  *      @inc: modifier
2336  *
2337  *      Add or remove reception of all multicast frames to a device. While the
2338  *      count in the device remains above zero the interface remains listening
2339  *      to all interfaces. Once it hits zero the device reverts back to normal
2340  *      filtering operation. A negative @inc value is used to drop the counter
2341  *      when releasing a resource needing all multicasts.
2342  */
2343
2344 void dev_set_allmulti(struct net_device *dev, int inc)
2345 {
2346         unsigned short old_flags = dev->flags;
2347
2348         dev->flags |= IFF_ALLMULTI;
2349         if ((dev->allmulti += inc) == 0)
2350                 dev->flags &= ~IFF_ALLMULTI;
2351         if (dev->flags ^ old_flags)
2352                 dev_mc_upload(dev);
2353 }
2354
2355 unsigned dev_get_flags(const struct net_device *dev)
2356 {
2357         unsigned flags;
2358
2359         flags = (dev->flags & ~(IFF_PROMISC |
2360                                 IFF_ALLMULTI |
2361                                 IFF_RUNNING)) | 
2362                 (dev->gflags & (IFF_PROMISC |
2363                                 IFF_ALLMULTI));
2364
2365         if (netif_running(dev) && netif_carrier_ok(dev))
2366                 flags |= IFF_RUNNING;
2367
2368         return flags;
2369 }
2370
2371 int dev_change_flags(struct net_device *dev, unsigned flags)
2372 {
2373         int ret;
2374         int old_flags = dev->flags;
2375
2376         /*
2377          *      Set the flags on our device.
2378          */
2379
2380         dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
2381                                IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
2382                                IFF_AUTOMEDIA)) |
2383                      (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
2384                                     IFF_ALLMULTI));
2385
2386         /*
2387          *      Load in the correct multicast list now the flags have changed.
2388          */
2389
2390         dev_mc_upload(dev);
2391
2392         /*
2393          *      Have we downed the interface. We handle IFF_UP ourselves
2394          *      according to user attempts to set it, rather than blindly
2395          *      setting it.
2396          */
2397
2398         ret = 0;
2399         if ((old_flags ^ flags) & IFF_UP) {     /* Bit is different  ? */
2400                 ret = ((old_flags & IFF_UP) ? dev_close : dev_open)(dev);
2401
2402                 if (!ret)
2403                         dev_mc_upload(dev);
2404         }
2405
2406         if (dev->flags & IFF_UP &&
2407             ((old_flags ^ dev->flags) &~ (IFF_UP | IFF_PROMISC | IFF_ALLMULTI |
2408                                           IFF_VOLATILE)))
2409                 notifier_call_chain(&netdev_chain, NETDEV_CHANGE, dev);
2410
2411         if ((flags ^ dev->gflags) & IFF_PROMISC) {
2412                 int inc = (flags & IFF_PROMISC) ? +1 : -1;
2413                 dev->gflags ^= IFF_PROMISC;
2414                 dev_set_promiscuity(dev, inc);
2415         }
2416
2417         /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
2418            is important. Some (broken) drivers set IFF_PROMISC, when
2419            IFF_ALLMULTI is requested not asking us and not reporting.
2420          */
2421         if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
2422                 int inc = (flags & IFF_ALLMULTI) ? +1 : -1;
2423                 dev->gflags ^= IFF_ALLMULTI;
2424                 dev_set_allmulti(dev, inc);
2425         }
2426
2427         if (old_flags ^ dev->flags)
2428                 rtmsg_ifinfo(RTM_NEWLINK, dev, old_flags ^ dev->flags);
2429
2430         return ret;
2431 }
2432
2433 int dev_set_mtu(struct net_device *dev, int new_mtu)
2434 {
2435         int err;
2436
2437         if (new_mtu == dev->mtu)
2438                 return 0;
2439
2440         /*      MTU must be positive.    */
2441         if (new_mtu < 0)
2442                 return -EINVAL;
2443
2444         if (!netif_device_present(dev))
2445                 return -ENODEV;
2446
2447         err = 0;
2448         if (dev->change_mtu)
2449                 err = dev->change_mtu(dev, new_mtu);
2450         else
2451                 dev->mtu = new_mtu;
2452         if (!err && dev->flags & IFF_UP)
2453                 notifier_call_chain(&netdev_chain,
2454                                     NETDEV_CHANGEMTU, dev);
2455         return err;
2456 }
2457
2458
2459 /*
2460  *      Perform the SIOCxIFxxx calls.
2461  */
2462 static int dev_ifsioc(struct ifreq *ifr, unsigned int cmd)
2463 {
2464         int err;
2465         struct net_device *dev = __dev_get_by_name(ifr->ifr_name);
2466
2467         if (!dev)
2468                 return -ENODEV;
2469
2470         switch (cmd) {
2471                 case SIOCGIFFLAGS:      /* Get interface flags */
2472                         ifr->ifr_flags = dev_get_flags(dev);
2473                         return 0;
2474
2475                 case SIOCSIFFLAGS:      /* Set interface flags */
2476                         return dev_change_flags(dev, ifr->ifr_flags);
2477
2478                 case SIOCGIFMETRIC:     /* Get the metric on the interface
2479                                            (currently unused) */
2480                         ifr->ifr_metric = 0;
2481                         return 0;
2482
2483                 case SIOCSIFMETRIC:     /* Set the metric on the interface
2484                                            (currently unused) */
2485                         return -EOPNOTSUPP;
2486
2487                 case SIOCGIFMTU:        /* Get the MTU of a device */
2488                         ifr->ifr_mtu = dev->mtu;
2489                         return 0;
2490
2491                 case SIOCSIFMTU:        /* Set the MTU of a device */
2492                         return dev_set_mtu(dev, ifr->ifr_mtu);
2493
2494                 case SIOCGIFHWADDR:
2495                         memcpy(ifr->ifr_hwaddr.sa_data, dev->dev_addr,
2496                                min(sizeof ifr->ifr_hwaddr.sa_data, (size_t) dev->addr_len));
2497                         ifr->ifr_hwaddr.sa_family = dev->type;
2498                         return 0;
2499
2500                 case SIOCSIFHWADDR:
2501                         if (!dev->set_mac_address)
2502                                 return -EOPNOTSUPP;
2503                         if (ifr->ifr_hwaddr.sa_family != dev->type)
2504                                 return -EINVAL;
2505                         if (!netif_device_present(dev))
2506                                 return -ENODEV;
2507                         err = dev->set_mac_address(dev, &ifr->ifr_hwaddr);
2508                         if (!err)
2509                                 notifier_call_chain(&netdev_chain,
2510                                                     NETDEV_CHANGEADDR, dev);
2511                         return err;
2512
2513                 case SIOCSIFHWBROADCAST:
2514                         if (ifr->ifr_hwaddr.sa_family != dev->type)
2515                                 return -EINVAL;
2516                         memcpy(dev->broadcast, ifr->ifr_hwaddr.sa_data,
2517                                min(sizeof ifr->ifr_hwaddr.sa_data, (size_t) dev->addr_len));
2518                         notifier_call_chain(&netdev_chain,
2519                                             NETDEV_CHANGEADDR, dev);
2520                         return 0;
2521
2522                 case SIOCGIFMAP:
2523                         ifr->ifr_map.mem_start = dev->mem_start;
2524                         ifr->ifr_map.mem_end   = dev->mem_end;
2525                         ifr->ifr_map.base_addr = dev->base_addr;
2526                         ifr->ifr_map.irq       = dev->irq;
2527                         ifr->ifr_map.dma       = dev->dma;
2528                         ifr->ifr_map.port      = dev->if_port;
2529                         return 0;
2530
2531                 case SIOCSIFMAP:
2532                         if (dev->set_config) {
2533                                 if (!netif_device_present(dev))
2534                                         return -ENODEV;
2535                                 return dev->set_config(dev, &ifr->ifr_map);
2536                         }
2537                         return -EOPNOTSUPP;
2538
2539                 case SIOCADDMULTI:
2540                         if (!dev->set_multicast_list ||
2541                             ifr->ifr_hwaddr.sa_family != AF_UNSPEC)
2542                                 return -EINVAL;
2543                         if (!netif_device_present(dev))
2544                                 return -ENODEV;
2545                         return dev_mc_add(dev, ifr->ifr_hwaddr.sa_data,
2546                                           dev->addr_len, 1);
2547
2548                 case SIOCDELMULTI:
2549                         if (!dev->set_multicast_list ||
2550                             ifr->ifr_hwaddr.sa_family != AF_UNSPEC)
2551                                 return -EINVAL;
2552                         if (!netif_device_present(dev))
2553                                 return -ENODEV;
2554                         return dev_mc_delete(dev, ifr->ifr_hwaddr.sa_data,
2555                                              dev->addr_len, 1);
2556
2557                 case SIOCGIFINDEX:
2558                         ifr->ifr_ifindex = dev->ifindex;
2559                         return 0;
2560
2561                 case SIOCGIFTXQLEN:
2562                         ifr->ifr_qlen = dev->tx_queue_len;
2563                         return 0;
2564
2565                 case SIOCSIFTXQLEN:
2566                         if (ifr->ifr_qlen < 0)
2567                                 return -EINVAL;
2568                         dev->tx_queue_len = ifr->ifr_qlen;
2569                         return 0;
2570
2571                 case SIOCSIFNAME:
2572                         ifr->ifr_newname[IFNAMSIZ-1] = '\0';
2573                         return dev_change_name(dev, ifr->ifr_newname);
2574
2575                 /*
2576                  *      Unknown or private ioctl
2577                  */
2578
2579                 default:
2580                         if ((cmd >= SIOCDEVPRIVATE &&
2581                             cmd <= SIOCDEVPRIVATE + 15) ||
2582                             cmd == SIOCBONDENSLAVE ||
2583                             cmd == SIOCBONDRELEASE ||
2584                             cmd == SIOCBONDSETHWADDR ||
2585                             cmd == SIOCBONDSLAVEINFOQUERY ||
2586                             cmd == SIOCBONDINFOQUERY ||
2587                             cmd == SIOCBONDCHANGEACTIVE ||
2588                             cmd == SIOCGMIIPHY ||
2589                             cmd == SIOCGMIIREG ||
2590                             cmd == SIOCSMIIREG ||
2591                             cmd == SIOCBRADDIF ||
2592                             cmd == SIOCBRDELIF ||
2593                             cmd == SIOCWANDEV) {
2594                                 err = -EOPNOTSUPP;
2595                                 if (dev->do_ioctl) {
2596                                         if (netif_device_present(dev))
2597                                                 err = dev->do_ioctl(dev, ifr,
2598                                                                     cmd);
2599                                         else
2600                                                 err = -ENODEV;
2601                                 }
2602                         } else
2603                                 err = -EINVAL;
2604
2605         }
2606         return err;
2607 }
2608
2609 /*
2610  *      This function handles all "interface"-type I/O control requests. The actual
2611  *      'doing' part of this is dev_ifsioc above.
2612  */
2613
2614 /**
2615  *      dev_ioctl       -       network device ioctl
2616  *      @cmd: command to issue
2617  *      @arg: pointer to a struct ifreq in user space
2618  *
2619  *      Issue ioctl functions to devices. This is normally called by the
2620  *      user space syscall interfaces but can sometimes be useful for
2621  *      other purposes. The return value is the return from the syscall if
2622  *      positive or a negative errno code on error.
2623  */
2624
2625 int dev_ioctl(unsigned int cmd, void __user *arg)
2626 {
2627         struct ifreq ifr;
2628         int ret;
2629         char *colon;
2630
2631         /* One special case: SIOCGIFCONF takes ifconf argument
2632            and requires shared lock, because it sleeps writing
2633            to user space.
2634          */
2635
2636         if (cmd == SIOCGIFCONF) {
2637                 rtnl_shlock();
2638                 ret = dev_ifconf((char __user *) arg);
2639                 rtnl_shunlock();
2640                 return ret;
2641         }
2642         if (cmd == SIOCGIFNAME)
2643                 return dev_ifname((struct ifreq __user *)arg);
2644
2645         if (copy_from_user(&ifr, arg, sizeof(struct ifreq)))
2646                 return -EFAULT;
2647
2648         ifr.ifr_name[IFNAMSIZ-1] = 0;
2649
2650         colon = strchr(ifr.ifr_name, ':');
2651         if (colon)
2652                 *colon = 0;
2653
2654         /*
2655          *      See which interface the caller is talking about.
2656          */
2657
2658         switch (cmd) {
2659                 /*
2660                  *      These ioctl calls:
2661                  *      - can be done by all.
2662                  *      - atomic and do not require locking.
2663                  *      - return a value
2664                  */
2665                 case SIOCGIFFLAGS:
2666                 case SIOCGIFMETRIC:
2667                 case SIOCGIFMTU:
2668                 case SIOCGIFHWADDR:
2669                 case SIOCGIFSLAVE:
2670                 case SIOCGIFMAP:
2671                 case SIOCGIFINDEX:
2672                 case SIOCGIFTXQLEN:
2673                         dev_load(ifr.ifr_name);
2674                         read_lock(&dev_base_lock);
2675                         ret = dev_ifsioc(&ifr, cmd);
2676                         read_unlock(&dev_base_lock);
2677                         if (!ret) {
2678                                 if (colon)
2679                                         *colon = ':';
2680                                 if (copy_to_user(arg, &ifr,
2681                                                  sizeof(struct ifreq)))
2682                                         ret = -EFAULT;
2683                         }
2684                         return ret;
2685
2686                 case SIOCETHTOOL:
2687                         dev_load(ifr.ifr_name);
2688                         rtnl_lock();
2689                         ret = dev_ethtool(&ifr);
2690                         rtnl_unlock();
2691                         if (!ret) {
2692                                 if (colon)
2693                                         *colon = ':';
2694                                 if (copy_to_user(arg, &ifr,
2695                                                  sizeof(struct ifreq)))
2696                                         ret = -EFAULT;
2697                         }
2698                         return ret;
2699
2700                 /*
2701                  *      These ioctl calls:
2702                  *      - require superuser power.
2703                  *      - require strict serialization.
2704                  *      - return a value
2705                  */
2706                 case SIOCGMIIPHY:
2707                 case SIOCGMIIREG:
2708                 case SIOCSIFNAME:
2709                         if (!capable(CAP_NET_ADMIN))
2710                                 return -EPERM;
2711                         dev_load(ifr.ifr_name);
2712                         rtnl_lock();
2713                         ret = dev_ifsioc(&ifr, cmd);
2714                         rtnl_unlock();
2715                         if (!ret) {
2716                                 if (colon)
2717                                         *colon = ':';
2718                                 if (copy_to_user(arg, &ifr,
2719                                                  sizeof(struct ifreq)))
2720                                         ret = -EFAULT;
2721                         }
2722                         return ret;
2723
2724                 /*
2725                  *      These ioctl calls:
2726                  *      - require superuser power.
2727                  *      - require strict serialization.
2728                  *      - do not return a value
2729                  */
2730                 case SIOCSIFFLAGS:
2731                 case SIOCSIFMETRIC:
2732                 case SIOCSIFMTU:
2733                 case SIOCSIFMAP:
2734                 case SIOCSIFHWADDR:
2735                 case SIOCSIFSLAVE:
2736                 case SIOCADDMULTI:
2737                 case SIOCDELMULTI:
2738                 case SIOCSIFHWBROADCAST:
2739                 case SIOCSIFTXQLEN:
2740                 case SIOCSMIIREG:
2741                 case SIOCBONDENSLAVE:
2742                 case SIOCBONDRELEASE:
2743                 case SIOCBONDSETHWADDR:
2744                 case SIOCBONDSLAVEINFOQUERY:
2745                 case SIOCBONDINFOQUERY:
2746                 case SIOCBONDCHANGEACTIVE:
2747                 case SIOCBRADDIF:
2748                 case SIOCBRDELIF:
2749                         if (!capable(CAP_NET_ADMIN))
2750                                 return -EPERM;
2751                         dev_load(ifr.ifr_name);
2752                         rtnl_lock();
2753                         ret = dev_ifsioc(&ifr, cmd);
2754                         rtnl_unlock();
2755                         return ret;
2756
2757                 case SIOCGIFMEM:
2758                         /* Get the per device memory space. We can add this but
2759                          * currently do not support it */
2760                 case SIOCSIFMEM:
2761                         /* Set the per device memory buffer space.
2762                          * Not applicable in our case */
2763                 case SIOCSIFLINK:
2764                         return -EINVAL;
2765
2766                 /*
2767                  *      Unknown or private ioctl.
2768                  */
2769                 default:
2770                         if (cmd == SIOCWANDEV ||
2771                             (cmd >= SIOCDEVPRIVATE &&
2772                              cmd <= SIOCDEVPRIVATE + 15)) {
2773                                 dev_load(ifr.ifr_name);
2774                                 rtnl_lock();
2775                                 ret = dev_ifsioc(&ifr, cmd);
2776                                 rtnl_unlock();
2777                                 if (!ret && copy_to_user(arg, &ifr,
2778                                                          sizeof(struct ifreq)))
2779                                         ret = -EFAULT;
2780                                 return ret;
2781                         }
2782 #ifdef WIRELESS_EXT
2783                         /* Take care of Wireless Extensions */
2784                         if (cmd >= SIOCIWFIRST && cmd <= SIOCIWLAST) {
2785                                 /* If command is `set a parameter', or
2786                                  * `get the encoding parameters', check if
2787                                  * the user has the right to do it */
2788                                 if (IW_IS_SET(cmd) || cmd == SIOCGIWENCODE) {
2789                                         if (!capable(CAP_NET_ADMIN))
2790                                                 return -EPERM;
2791                                 }
2792                                 dev_load(ifr.ifr_name);
2793                                 rtnl_lock();
2794                                 /* Follow me in net/core/wireless.c */
2795                                 ret = wireless_process_ioctl(&ifr, cmd);
2796                                 rtnl_unlock();
2797                                 if (!ret && IW_IS_GET(cmd) &&
2798                                     copy_to_user(arg, &ifr,
2799                                                  sizeof(struct ifreq)))
2800                                         ret = -EFAULT;
2801                                 return ret;
2802                         }
2803 #endif  /* WIRELESS_EXT */
2804                         return -EINVAL;
2805         }
2806 }
2807
2808
2809 /**
2810  *      dev_new_index   -       allocate an ifindex
2811  *
2812  *      Returns a suitable unique value for a new device interface
2813  *      number.  The caller must hold the rtnl semaphore or the
2814  *      dev_base_lock to be sure it remains unique.
2815  */
2816 int dev_new_index(void)
2817 {
2818         static int ifindex;
2819         for (;;) {
2820                 if (++ifindex <= 0)
2821                         ifindex = 1;
2822                 if (!__dev_get_by_index(ifindex))
2823                         return ifindex;
2824         }
2825 }
2826
2827 static int dev_boot_phase = 1;
2828
2829 /* Delayed registration/unregisteration */
2830 static spinlock_t net_todo_list_lock = SPIN_LOCK_UNLOCKED;
2831 static struct list_head net_todo_list = LIST_HEAD_INIT(net_todo_list);
2832
2833 static inline void net_set_todo(struct net_device *dev)
2834 {
2835         spin_lock(&net_todo_list_lock);
2836         list_add_tail(&dev->todo_list, &net_todo_list);
2837         spin_unlock(&net_todo_list_lock);
2838 }
2839
2840 /**
2841  *      register_netdevice      - register a network device
2842  *      @dev: device to register
2843  *
2844  *      Take a completed network device structure and add it to the kernel
2845  *      interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
2846  *      chain. 0 is returned on success. A negative errno code is returned
2847  *      on a failure to set up the device, or if the name is a duplicate.
2848  *
2849  *      Callers must hold the rtnl semaphore.  See the comment at the
2850  *      end of Space.c for details about the locking.  You may want
2851  *      register_netdev() instead of this.
2852  *
2853  *      BUGS:
2854  *      The locking appears insufficient to guarantee two parallel registers
2855  *      will not get the same name.
2856  */
2857
2858 int register_netdevice(struct net_device *dev)
2859 {
2860         struct hlist_head *head;
2861         struct hlist_node *p;
2862         int ret;
2863
2864         BUG_ON(dev_boot_phase);
2865         ASSERT_RTNL();
2866
2867         /* When net_device's are persistent, this will be fatal. */
2868         BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
2869
2870         spin_lock_init(&dev->queue_lock);
2871         spin_lock_init(&dev->xmit_lock);
2872         dev->xmit_lock_owner = -1;
2873 #ifdef CONFIG_NET_CLS_ACT
2874         spin_lock_init(&dev->ingress_lock);
2875 #endif
2876
2877         ret = alloc_divert_blk(dev);
2878         if (ret)
2879                 goto out;
2880
2881         dev->iflink = -1;
2882
2883         /* Init, if this function is available */
2884         if (dev->init) {
2885                 ret = dev->init(dev);
2886                 if (ret) {
2887                         if (ret > 0)
2888                                 ret = -EIO;
2889                         goto out_err;
2890                 }
2891         }
2892  
2893         if (!dev_valid_name(dev->name)) {
2894                 ret = -EINVAL;
2895                 goto out_err;
2896         }
2897
2898         dev->ifindex = dev_new_index();
2899         if (dev->iflink == -1)
2900                 dev->iflink = dev->ifindex;
2901
2902         /* Check for existence of name */
2903         head = dev_name_hash(dev->name);
2904         hlist_for_each(p, head) {
2905                 struct net_device *d
2906                         = hlist_entry(p, struct net_device, name_hlist);
2907                 if (!strncmp(d->name, dev->name, IFNAMSIZ)) {
2908                         ret = -EEXIST;
2909                         goto out_err;
2910                 }
2911         }
2912
2913         /* Fix illegal SG+CSUM combinations. */
2914         if ((dev->features & NETIF_F_SG) &&
2915             !(dev->features & (NETIF_F_IP_CSUM |
2916                                NETIF_F_NO_CSUM |
2917                                NETIF_F_HW_CSUM))) {
2918                 printk("%s: Dropping NETIF_F_SG since no checksum feature.\n",
2919                        dev->name);
2920                 dev->features &= ~NETIF_F_SG;
2921         }
2922
2923         /*
2924          *      nil rebuild_header routine,
2925          *      that should be never called and used as just bug trap.
2926          */
2927
2928         if (!dev->rebuild_header)
2929                 dev->rebuild_header = default_rebuild_header;
2930
2931         /*
2932          *      Default initial state at registry is that the
2933          *      device is present.
2934          */
2935
2936         set_bit(__LINK_STATE_PRESENT, &dev->state);
2937
2938         dev->next = NULL;
2939         dev_init_scheduler(dev);
2940         write_lock_bh(&dev_base_lock);
2941         *dev_tail = dev;
2942         dev_tail = &dev->next;
2943         hlist_add_head(&dev->name_hlist, head);
2944         hlist_add_head(&dev->index_hlist, dev_index_hash(dev->ifindex));
2945         dev_hold(dev);
2946         dev->reg_state = NETREG_REGISTERING;
2947         write_unlock_bh(&dev_base_lock);
2948
2949         /* Notify protocols, that a new device appeared. */
2950         notifier_call_chain(&netdev_chain, NETDEV_REGISTER, dev);
2951
2952         /* Finish registration after unlock */
2953         net_set_todo(dev);
2954         ret = 0;
2955
2956 out:
2957         return ret;
2958 out_err:
2959         free_divert_blk(dev);
2960         goto out;
2961 }
2962
2963 /*
2964  * netdev_wait_allrefs - wait until all references are gone.
2965  *
2966  * This is called when unregistering network devices.
2967  *
2968  * Any protocol or device that holds a reference should register
2969  * for netdevice notification, and cleanup and put back the
2970  * reference if they receive an UNREGISTER event.
2971  * We can get stuck here if buggy protocols don't correctly
2972  * call dev_put. 
2973  */
2974 static void netdev_wait_allrefs(struct net_device *dev)
2975 {
2976         unsigned long rebroadcast_time, warning_time;
2977
2978         rebroadcast_time = warning_time = jiffies;
2979         while (atomic_read(&dev->refcnt) != 0) {
2980                 if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
2981                         rtnl_shlock();
2982
2983                         /* Rebroadcast unregister notification */
2984                         notifier_call_chain(&netdev_chain,
2985                                             NETDEV_UNREGISTER, dev);
2986
2987                         if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
2988                                      &dev->state)) {
2989                                 /* We must not have linkwatch events
2990                                  * pending on unregister. If this
2991                                  * happens, we simply run the queue
2992                                  * unscheduled, resulting in a noop
2993                                  * for this device.
2994                                  */
2995                                 linkwatch_run_queue();
2996                         }
2997
2998                         rtnl_shunlock();
2999
3000                         rebroadcast_time = jiffies;
3001                 }
3002
3003                 current->state = TASK_INTERRUPTIBLE;
3004                 schedule_timeout(HZ / 4);
3005
3006                 if (time_after(jiffies, warning_time + 10 * HZ)) {
3007                         printk(KERN_EMERG "unregister_netdevice: "
3008                                "waiting for %s to become free. Usage "
3009                                "count = %d\n",
3010                                dev->name, atomic_read(&dev->refcnt));
3011                         warning_time = jiffies;
3012                 }
3013         }
3014 }
3015
3016 /* The sequence is:
3017  *
3018  *      rtnl_lock();
3019  *      ...
3020  *      register_netdevice(x1);
3021  *      register_netdevice(x2);
3022  *      ...
3023  *      unregister_netdevice(y1);
3024  *      unregister_netdevice(y2);
3025  *      ...
3026  *      rtnl_unlock();
3027  *      free_netdev(y1);
3028  *      free_netdev(y2);
3029  *
3030  * We are invoked by rtnl_unlock() after it drops the semaphore.
3031  * This allows us to deal with problems:
3032  * 1) We can create/delete sysfs objects which invoke hotplug
3033  *    without deadlocking with linkwatch via keventd.
3034  * 2) Since we run with the RTNL semaphore not held, we can sleep
3035  *    safely in order to wait for the netdev refcnt to drop to zero.
3036  */
3037 static DECLARE_MUTEX(net_todo_run_mutex);
3038 void netdev_run_todo(void)
3039 {
3040         struct list_head list = LIST_HEAD_INIT(list);
3041         int err;
3042
3043
3044         /* Need to guard against multiple cpu's getting out of order. */
3045         down(&net_todo_run_mutex);
3046
3047         /* Not safe to do outside the semaphore.  We must not return
3048          * until all unregister events invoked by the local processor
3049          * have been completed (either by this todo run, or one on
3050          * another cpu).
3051          */
3052         if (list_empty(&net_todo_list))
3053                 goto out;
3054
3055         /* Snapshot list, allow later requests */
3056         spin_lock(&net_todo_list_lock);
3057         list_splice_init(&net_todo_list, &list);
3058         spin_unlock(&net_todo_list_lock);
3059                 
3060         while (!list_empty(&list)) {
3061                 struct net_device *dev
3062                         = list_entry(list.next, struct net_device, todo_list);
3063                 list_del(&dev->todo_list);
3064
3065                 switch(dev->reg_state) {
3066                 case NETREG_REGISTERING:
3067                         err = netdev_register_sysfs(dev);
3068                         if (err)
3069                                 printk(KERN_ERR "%s: failed sysfs registration (%d)\n",
3070                                        dev->name, err);
3071                         dev->reg_state = NETREG_REGISTERED;
3072                         break;
3073
3074                 case NETREG_UNREGISTERING:
3075                         netdev_unregister_sysfs(dev);
3076                         dev->reg_state = NETREG_UNREGISTERED;
3077
3078                         netdev_wait_allrefs(dev);
3079
3080                         /* paranoia */
3081                         BUG_ON(atomic_read(&dev->refcnt));
3082                         BUG_TRAP(!dev->ip_ptr);
3083                         BUG_TRAP(!dev->ip6_ptr);
3084                         BUG_TRAP(!dev->dn_ptr);
3085
3086
3087                         /* It must be the very last action, 
3088                          * after this 'dev' may point to freed up memory.
3089                          */
3090                         if (dev->destructor)
3091                                 dev->destructor(dev);
3092                         break;
3093
3094                 default:
3095                         printk(KERN_ERR "network todo '%s' but state %d\n",
3096                                dev->name, dev->reg_state);
3097                         break;
3098                 }
3099         }
3100
3101 out:
3102         up(&net_todo_run_mutex);
3103 }
3104
3105 /**
3106  *      free_netdev - free network device
3107  *      @dev: device
3108  *
3109  *      This function does the last stage of destroying an allocated device 
3110  *      interface. The reference to the device object is released.  
3111  *      If this is the last reference then it will be freed.
3112  */
3113 void free_netdev(struct net_device *dev)
3114 {
3115 #ifdef CONFIG_SYSFS
3116         /*  Compatiablity with error handling in drivers */
3117         if (dev->reg_state == NETREG_UNINITIALIZED) {
3118                 kfree((char *)dev - dev->padded);
3119                 return;
3120         }
3121
3122         BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
3123         dev->reg_state = NETREG_RELEASED;
3124
3125         /* will free via class release */
3126         class_device_put(&dev->class_dev);
3127 #else
3128         kfree((char *)dev - dev->padded);
3129 #endif
3130 }
3131  
3132 /* Synchronize with packet receive processing. */
3133 void synchronize_net(void) 
3134 {
3135         might_sleep();
3136         synchronize_kernel();
3137 }
3138
3139 /**
3140  *      unregister_netdevice - remove device from the kernel
3141  *      @dev: device
3142  *
3143  *      This function shuts down a device interface and removes it
3144  *      from the kernel tables. On success 0 is returned, on a failure
3145  *      a negative errno code is returned.
3146  *
3147  *      Callers must hold the rtnl semaphore.  See the comment at the
3148  *      end of Space.c for details about the locking.  You may want
3149  *      unregister_netdev() instead of this.
3150  */
3151
3152 int unregister_netdevice(struct net_device *dev)
3153 {
3154         struct net_device *d, **dp;
3155
3156         BUG_ON(dev_boot_phase);
3157         ASSERT_RTNL();
3158
3159         /* Some devices call without registering for initialization unwind. */
3160         if (dev->reg_state == NETREG_UNINITIALIZED) {
3161                 printk(KERN_DEBUG "unregister_netdevice: device %s/%p never "
3162                                   "was registered\n", dev->name, dev);
3163                 return -ENODEV;
3164         }
3165
3166         BUG_ON(dev->reg_state != NETREG_REGISTERED);
3167
3168         /* If device is running, close it first. */
3169         if (dev->flags & IFF_UP)
3170                 dev_close(dev);
3171
3172         /* And unlink it from device chain. */
3173         for (dp = &dev_base; (d = *dp) != NULL; dp = &d->next) {
3174                 if (d == dev) {
3175                         write_lock_bh(&dev_base_lock);
3176                         hlist_del(&dev->name_hlist);
3177                         hlist_del(&dev->index_hlist);
3178                         if (dev_tail == &dev->next)
3179                                 dev_tail = dp;
3180                         *dp = d->next;
3181                         write_unlock_bh(&dev_base_lock);
3182                         break;
3183                 }
3184         }
3185         if (!d) {
3186                 printk(KERN_ERR "unregister net_device: '%s' not found\n",
3187                        dev->name);
3188                 return -ENODEV;
3189         }
3190
3191         dev->reg_state = NETREG_UNREGISTERING;
3192
3193         synchronize_net();
3194
3195         /* Shutdown queueing discipline. */
3196         dev_shutdown(dev);
3197
3198         
3199         /* Notify protocols, that we are about to destroy
3200            this device. They should clean all the things.
3201         */
3202         notifier_call_chain(&netdev_chain, NETDEV_UNREGISTER, dev);
3203         
3204         /*
3205          *      Flush the multicast chain
3206          */
3207         dev_mc_discard(dev);
3208
3209         if (dev->uninit)
3210                 dev->uninit(dev);
3211
3212         /* Notifier chain MUST detach us from master device. */
3213         BUG_TRAP(!dev->master);
3214
3215         free_divert_blk(dev);
3216
3217         /* Finish processing unregister after unlock */
3218         net_set_todo(dev);
3219
3220         synchronize_net();
3221
3222         dev_put(dev);
3223         return 0;
3224 }
3225
3226 #ifdef CONFIG_HOTPLUG_CPU
3227 static int dev_cpu_callback(struct notifier_block *nfb,
3228                             unsigned long action,
3229                             void *ocpu)
3230 {
3231         struct sk_buff **list_skb;
3232         struct net_device **list_net;
3233         struct sk_buff *skb;
3234         unsigned int cpu, oldcpu = (unsigned long)ocpu;
3235         struct softnet_data *sd, *oldsd;
3236
3237         if (action != CPU_DEAD)
3238                 return NOTIFY_OK;
3239
3240         local_irq_disable();
3241         cpu = smp_processor_id();
3242         sd = &per_cpu(softnet_data, cpu);
3243         oldsd = &per_cpu(softnet_data, oldcpu);
3244
3245         /* Find end of our completion_queue. */
3246         list_skb = &sd->completion_queue;
3247         while (*list_skb)
3248                 list_skb = &(*list_skb)->next;
3249         /* Append completion queue from offline CPU. */
3250         *list_skb = oldsd->completion_queue;
3251         oldsd->completion_queue = NULL;
3252
3253         /* Find end of our output_queue. */
3254         list_net = &sd->output_queue;
3255         while (*list_net)
3256                 list_net = &(*list_net)->next_sched;
3257         /* Append output queue from offline CPU. */
3258         *list_net = oldsd->output_queue;
3259         oldsd->output_queue = NULL;
3260
3261         raise_softirq_irqoff(NET_TX_SOFTIRQ);
3262         local_irq_enable();
3263
3264         /* Process offline CPU's input_pkt_queue */
3265         while ((skb = __skb_dequeue(&oldsd->input_pkt_queue)))
3266                 netif_rx(skb);
3267
3268         return NOTIFY_OK;
3269 }
3270 #endif /* CONFIG_HOTPLUG_CPU */
3271
3272
3273 /*
3274  *      Initialize the DEV module. At boot time this walks the device list and
3275  *      unhooks any devices that fail to initialise (normally hardware not
3276  *      present) and leaves us with a valid list of present and active devices.
3277  *
3278  */
3279
3280 /*
3281  *       This is called single threaded during boot, so no need
3282  *       to take the rtnl semaphore.
3283  */
3284 static int __init net_dev_init(void)
3285 {
3286         int i, rc = -ENOMEM;
3287
3288         BUG_ON(!dev_boot_phase);
3289
3290         if (dev_proc_init())
3291                 goto out;
3292
3293         if (netdev_sysfs_init())
3294                 goto out;
3295
3296         INIT_LIST_HEAD(&ptype_all);
3297         for (i = 0; i < 16; i++) 
3298                 INIT_LIST_HEAD(&ptype_base[i]);
3299
3300         for (i = 0; i < ARRAY_SIZE(dev_name_head); i++)
3301                 INIT_HLIST_HEAD(&dev_name_head[i]);
3302
3303         for (i = 0; i < ARRAY_SIZE(dev_index_head); i++)
3304                 INIT_HLIST_HEAD(&dev_index_head[i]);
3305
3306         /*
3307          *      Initialise the packet receive queues.
3308          */
3309
3310         for (i = 0; i < NR_CPUS; i++) {
3311                 struct softnet_data *queue;
3312
3313                 queue = &per_cpu(softnet_data, i);
3314                 skb_queue_head_init(&queue->input_pkt_queue);
3315                 queue->throttle = 0;
3316                 queue->cng_level = 0;
3317                 queue->avg_blog = 10; /* arbitrary non-zero */
3318                 queue->completion_queue = NULL;
3319                 INIT_LIST_HEAD(&queue->poll_list);
3320                 set_bit(__LINK_STATE_START, &queue->backlog_dev.state);
3321                 queue->backlog_dev.weight = weight_p;
3322                 queue->backlog_dev.poll = process_backlog;
3323                 atomic_set(&queue->backlog_dev.refcnt, 1);
3324         }
3325
3326 #ifdef OFFLINE_SAMPLE
3327         samp_timer.expires = jiffies + (10 * HZ);
3328         add_timer(&samp_timer);
3329 #endif
3330
3331         dev_boot_phase = 0;
3332
3333         open_softirq(NET_TX_SOFTIRQ, net_tx_action, NULL);
3334         open_softirq(NET_RX_SOFTIRQ, net_rx_action, NULL);
3335
3336         hotcpu_notifier(dev_cpu_callback, 0);
3337         dst_init();
3338         dev_mcast_init();
3339         rc = 0;
3340 out:
3341         return rc;
3342 }
3343
3344 subsys_initcall(net_dev_init);
3345
3346 EXPORT_SYMBOL(__dev_get);
3347 EXPORT_SYMBOL(__dev_get_by_flags);
3348 EXPORT_SYMBOL(__dev_get_by_index);
3349 EXPORT_SYMBOL(__dev_get_by_name);
3350 EXPORT_SYMBOL(__dev_remove_pack);
3351 EXPORT_SYMBOL(__skb_linearize);
3352 EXPORT_SYMBOL(call_netdevice_notifiers);
3353 EXPORT_SYMBOL(dev_add_pack);
3354 EXPORT_SYMBOL(dev_alloc_name);
3355 EXPORT_SYMBOL(dev_close);
3356 EXPORT_SYMBOL(dev_get_by_flags);
3357 EXPORT_SYMBOL(dev_get_by_index);
3358 EXPORT_SYMBOL(dev_get_by_name);
3359 EXPORT_SYMBOL(dev_getbyhwaddr);
3360 EXPORT_SYMBOL(dev_ioctl);
3361 EXPORT_SYMBOL(dev_new_index);
3362 EXPORT_SYMBOL(dev_open);
3363 EXPORT_SYMBOL(dev_queue_xmit);
3364 EXPORT_SYMBOL(dev_queue_xmit_nit);
3365 EXPORT_SYMBOL(dev_remove_pack);
3366 EXPORT_SYMBOL(dev_set_allmulti);
3367 EXPORT_SYMBOL(dev_set_promiscuity);
3368 EXPORT_SYMBOL(dev_change_flags);
3369 EXPORT_SYMBOL(dev_set_mtu);
3370 EXPORT_SYMBOL(free_netdev);
3371 EXPORT_SYMBOL(netdev_boot_setup_check);
3372 EXPORT_SYMBOL(netdev_set_master);
3373 EXPORT_SYMBOL(netdev_state_change);
3374 EXPORT_SYMBOL(netif_receive_skb);
3375 EXPORT_SYMBOL(netif_rx);
3376 EXPORT_SYMBOL(register_gifconf);
3377 EXPORT_SYMBOL(register_netdevice);
3378 EXPORT_SYMBOL(register_netdevice_notifier);
3379 EXPORT_SYMBOL(skb_checksum_help);
3380 EXPORT_SYMBOL(synchronize_net);
3381 EXPORT_SYMBOL(unregister_netdevice);
3382 EXPORT_SYMBOL(unregister_netdevice_notifier);
3383
3384 #if defined(CONFIG_BRIDGE) || defined(CONFIG_BRIDGE_MODULE)
3385 EXPORT_SYMBOL(br_handle_frame_hook);
3386 #endif
3387
3388 #ifdef CONFIG_KMOD
3389 EXPORT_SYMBOL(dev_load);
3390 #endif
3391 #ifdef CONFIG_NET_HW_FLOWCONTROL
3392 EXPORT_SYMBOL(netdev_dropping);
3393 EXPORT_SYMBOL(netdev_fc_xoff);
3394 EXPORT_SYMBOL(netdev_register_fc);
3395 EXPORT_SYMBOL(netdev_unregister_fc);
3396 #endif
3397
3398 #ifdef CONFIG_NET_CLS_ACT
3399 EXPORT_SYMBOL(ing_filter);
3400 #endif
3401
3402
3403 EXPORT_PER_CPU_SYMBOL(softnet_data);