ia64/xen-unstable

view linux-2.6-xen-sparse/net/core/dev.c @ 6726:0c7379b702e5

common/kernel.o contains changeset/compiler info.
Blow away on every build.
author kaf24@firebug.cl.cam.ac.uk
date Fri Sep 09 16:26:20 2005 +0000 (2005-09-09)
parents dd668f7527cb
children b2f4823b6ff0 b35215021b32 9af349b055e5 3233e7ecfa9f
line source
1 /*
2 * NET3 Protocol independent device support routines.
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version
7 * 2 of the License, or (at your option) any later version.
8 *
9 * Derived from the non IP parts of dev.c 1.0.19
10 * Authors: Ross Biro
11 * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
12 * Mark Evans, <evansmp@uhura.aston.ac.uk>
13 *
14 * Additional Authors:
15 * Florian la Roche <rzsfl@rz.uni-sb.de>
16 * Alan Cox <gw4pts@gw4pts.ampr.org>
17 * David Hinds <dahinds@users.sourceforge.net>
18 * Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
19 * Adam Sulmicki <adam@cfar.umd.edu>
20 * Pekka Riikonen <priikone@poesidon.pspt.fi>
21 *
22 * Changes:
23 * D.J. Barrow : Fixed bug where dev->refcnt gets set
24 * to 2 if register_netdev gets called
25 * before net_dev_init & also removed a
26 * few lines of code in the process.
27 * Alan Cox : device private ioctl copies fields back.
28 * Alan Cox : Transmit queue code does relevant
29 * stunts to keep the queue safe.
30 * Alan Cox : Fixed double lock.
31 * Alan Cox : Fixed promisc NULL pointer trap
32 * ???????? : Support the full private ioctl range
33 * Alan Cox : Moved ioctl permission check into
34 * drivers
35 * Tim Kordas : SIOCADDMULTI/SIOCDELMULTI
36 * Alan Cox : 100 backlog just doesn't cut it when
37 * you start doing multicast video 8)
38 * Alan Cox : Rewrote net_bh and list manager.
39 * Alan Cox : Fix ETH_P_ALL echoback lengths.
40 * Alan Cox : Took out transmit every packet pass
41 * Saved a few bytes in the ioctl handler
42 * Alan Cox : Network driver sets packet type before
43 * calling netif_rx. Saves a function
44 * call a packet.
45 * Alan Cox : Hashed net_bh()
46 * Richard Kooijman: Timestamp fixes.
47 * Alan Cox : Wrong field in SIOCGIFDSTADDR
48 * Alan Cox : Device lock protection.
49 * Alan Cox : Fixed nasty side effect of device close
50 * changes.
51 * Rudi Cilibrasi : Pass the right thing to
52 * set_mac_address()
53 * Dave Miller : 32bit quantity for the device lock to
54 * make it work out on a Sparc.
55 * Bjorn Ekwall : Added KERNELD hack.
56 * Alan Cox : Cleaned up the backlog initialise.
57 * Craig Metz : SIOCGIFCONF fix if space for under
58 * 1 device.
59 * Thomas Bogendoerfer : Return ENODEV for dev_open, if there
60 * is no device open function.
61 * Andi Kleen : Fix error reporting for SIOCGIFCONF
62 * Michael Chastain : Fix signed/unsigned for SIOCGIFCONF
63 * Cyrus Durgin : Cleaned for KMOD
64 * Adam Sulmicki : Bug Fix : Network Device Unload
65 * A network device unload needs to purge
66 * the backlog queue.
67 * Paul Rusty Russell : SIOCSIFNAME
68 * Pekka Riikonen : Netdev boot-time settings code
69 * Andrew Morton : Make unregister_netdevice wait
70 * indefinitely on dev->refcnt
71 * J Hadi Salim : - Backlog queue sampling
72 * - netif_rx() feedback
73 */
75 #include <asm/uaccess.h>
76 #include <asm/system.h>
77 #include <linux/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 #include <linux/delay.h>
112 #ifdef CONFIG_NET_RADIO
113 #include <linux/wireless.h> /* Note : will define WIRELESS_EXT */
114 #include <net/iw_handler.h>
115 #endif /* CONFIG_NET_RADIO */
116 #include <asm/current.h>
118 #include <net/ip.h>
119 #include <linux/tcp.h>
120 #include <linux/udp.h>
123 /* This define, if set, will randomly drop a packet when congestion
124 * is more than moderate. It helps fairness in the multi-interface
125 * case when one of them is a hog, but it kills performance for the
126 * single interface case so it is off now by default.
127 */
128 #undef RAND_LIE
130 /* Setting this will sample the queue lengths and thus congestion
131 * via a timer instead of as each packet is received.
132 */
133 #undef OFFLINE_SAMPLE
135 /*
136 * The list of packet types we will receive (as opposed to discard)
137 * and the routines to invoke.
138 *
139 * Why 16. Because with 16 the only overlap we get on a hash of the
140 * low nibble of the protocol value is RARP/SNAP/X.25.
141 *
142 * NOTE: That is no longer true with the addition of VLAN tags. Not
143 * sure which should go first, but I bet it won't make much
144 * difference if we are running VLANs. The good news is that
145 * this protocol won't be in the list unless compiled in, so
146 * the average user (w/out VLANs) will not be adversly affected.
147 * --BLG
148 *
149 * 0800 IP
150 * 8100 802.1Q VLAN
151 * 0001 802.3
152 * 0002 AX.25
153 * 0004 802.2
154 * 8035 RARP
155 * 0005 SNAP
156 * 0805 X.25
157 * 0806 ARP
158 * 8137 IPX
159 * 0009 Localtalk
160 * 86DD IPv6
161 */
163 static DEFINE_SPINLOCK(ptype_lock);
164 static struct list_head ptype_base[16]; /* 16 way hashed list */
165 static struct list_head ptype_all; /* Taps */
167 #ifdef OFFLINE_SAMPLE
168 static void sample_queue(unsigned long dummy);
169 static struct timer_list samp_timer = TIMER_INITIALIZER(sample_queue, 0, 0);
170 #endif
172 /*
173 * The @dev_base list is protected by @dev_base_lock and the rtln
174 * semaphore.
175 *
176 * Pure readers hold dev_base_lock for reading.
177 *
178 * Writers must hold the rtnl semaphore while they loop through the
179 * dev_base list, and hold dev_base_lock for writing when they do the
180 * actual updates. This allows pure readers to access the list even
181 * while a writer is preparing to update it.
182 *
183 * To put it another way, dev_base_lock is held for writing only to
184 * protect against pure readers; the rtnl semaphore provides the
185 * protection against other writers.
186 *
187 * See, for example usages, register_netdevice() and
188 * unregister_netdevice(), which must be called with the rtnl
189 * semaphore held.
190 */
191 struct net_device *dev_base;
192 static struct net_device **dev_tail = &dev_base;
193 DEFINE_RWLOCK(dev_base_lock);
195 EXPORT_SYMBOL(dev_base);
196 EXPORT_SYMBOL(dev_base_lock);
198 #define NETDEV_HASHBITS 8
199 static struct hlist_head dev_name_head[1<<NETDEV_HASHBITS];
200 static struct hlist_head dev_index_head[1<<NETDEV_HASHBITS];
202 static inline struct hlist_head *dev_name_hash(const char *name)
203 {
204 unsigned hash = full_name_hash(name, strnlen(name, IFNAMSIZ));
205 return &dev_name_head[hash & ((1<<NETDEV_HASHBITS)-1)];
206 }
208 static inline struct hlist_head *dev_index_hash(int ifindex)
209 {
210 return &dev_index_head[ifindex & ((1<<NETDEV_HASHBITS)-1)];
211 }
213 /*
214 * Our notifier list
215 */
217 static struct notifier_block *netdev_chain;
219 /*
220 * Device drivers call our routines to queue packets here. We empty the
221 * queue in the local softnet handler.
222 */
223 DEFINE_PER_CPU(struct softnet_data, softnet_data) = { 0, };
225 #ifdef CONFIG_SYSFS
226 extern int netdev_sysfs_init(void);
227 extern int netdev_register_sysfs(struct net_device *);
228 extern void netdev_unregister_sysfs(struct net_device *);
229 #else
230 #define netdev_sysfs_init() (0)
231 #define netdev_register_sysfs(dev) (0)
232 #define netdev_unregister_sysfs(dev) do { } while(0)
233 #endif
236 /*******************************************************************************
238 Protocol management and registration routines
240 *******************************************************************************/
242 /*
243 * For efficiency
244 */
246 int netdev_nit;
248 /*
249 * Add a protocol ID to the list. Now that the input handler is
250 * smarter we can dispense with all the messy stuff that used to be
251 * here.
252 *
253 * BEWARE!!! Protocol handlers, mangling input packets,
254 * MUST BE last in hash buckets and checking protocol handlers
255 * MUST start from promiscuous ptype_all chain in net_bh.
256 * It is true now, do not change it.
257 * Explanation follows: if protocol handler, mangling packet, will
258 * be the first on list, it is not able to sense, that packet
259 * is cloned and should be copied-on-write, so that it will
260 * change it and subsequent readers will get broken packet.
261 * --ANK (980803)
262 */
264 /**
265 * dev_add_pack - add packet handler
266 * @pt: packet type declaration
267 *
268 * Add a protocol handler to the networking stack. The passed &packet_type
269 * is linked into kernel lists and may not be freed until it has been
270 * removed from the kernel lists.
271 *
272 * This call does not sleep therefore it can not
273 * guarantee all CPU's that are in middle of receiving packets
274 * will see the new packet type (until the next received packet).
275 */
277 void dev_add_pack(struct packet_type *pt)
278 {
279 int hash;
281 spin_lock_bh(&ptype_lock);
282 if (pt->type == htons(ETH_P_ALL)) {
283 netdev_nit++;
284 list_add_rcu(&pt->list, &ptype_all);
285 } else {
286 hash = ntohs(pt->type) & 15;
287 list_add_rcu(&pt->list, &ptype_base[hash]);
288 }
289 spin_unlock_bh(&ptype_lock);
290 }
292 extern void linkwatch_run_queue(void);
296 /**
297 * __dev_remove_pack - remove packet handler
298 * @pt: packet type declaration
299 *
300 * Remove a protocol handler that was previously added to the kernel
301 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
302 * from the kernel lists and can be freed or reused once this function
303 * returns.
304 *
305 * The packet type might still be in use by receivers
306 * and must not be freed until after all the CPU's have gone
307 * through a quiescent state.
308 */
309 void __dev_remove_pack(struct packet_type *pt)
310 {
311 struct list_head *head;
312 struct packet_type *pt1;
314 spin_lock_bh(&ptype_lock);
316 if (pt->type == htons(ETH_P_ALL)) {
317 netdev_nit--;
318 head = &ptype_all;
319 } else
320 head = &ptype_base[ntohs(pt->type) & 15];
322 list_for_each_entry(pt1, head, list) {
323 if (pt == pt1) {
324 list_del_rcu(&pt->list);
325 goto out;
326 }
327 }
329 printk(KERN_WARNING "dev_remove_pack: %p not found.\n", pt);
330 out:
331 spin_unlock_bh(&ptype_lock);
332 }
333 /**
334 * dev_remove_pack - remove packet handler
335 * @pt: packet type declaration
336 *
337 * Remove a protocol handler that was previously added to the kernel
338 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
339 * from the kernel lists and can be freed or reused once this function
340 * returns.
341 *
342 * This call sleeps to guarantee that no CPU is looking at the packet
343 * type after return.
344 */
345 void dev_remove_pack(struct packet_type *pt)
346 {
347 __dev_remove_pack(pt);
349 synchronize_net();
350 }
352 /******************************************************************************
354 Device Boot-time Settings Routines
356 *******************************************************************************/
358 /* Boot time configuration table */
359 static struct netdev_boot_setup dev_boot_setup[NETDEV_BOOT_SETUP_MAX];
361 /**
362 * netdev_boot_setup_add - add new setup entry
363 * @name: name of the device
364 * @map: configured settings for the device
365 *
366 * Adds new setup entry to the dev_boot_setup list. The function
367 * returns 0 on error and 1 on success. This is a generic routine to
368 * all netdevices.
369 */
370 static int netdev_boot_setup_add(char *name, struct ifmap *map)
371 {
372 struct netdev_boot_setup *s;
373 int i;
375 s = dev_boot_setup;
376 for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
377 if (s[i].name[0] == '\0' || s[i].name[0] == ' ') {
378 memset(s[i].name, 0, sizeof(s[i].name));
379 strcpy(s[i].name, name);
380 memcpy(&s[i].map, map, sizeof(s[i].map));
381 break;
382 }
383 }
385 return i >= NETDEV_BOOT_SETUP_MAX ? 0 : 1;
386 }
388 /**
389 * netdev_boot_setup_check - check boot time settings
390 * @dev: the netdevice
391 *
392 * Check boot time settings for the device.
393 * The found settings are set for the device to be used
394 * later in the device probing.
395 * Returns 0 if no settings found, 1 if they are.
396 */
397 int netdev_boot_setup_check(struct net_device *dev)
398 {
399 struct netdev_boot_setup *s = dev_boot_setup;
400 int i;
402 for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
403 if (s[i].name[0] != '\0' && s[i].name[0] != ' ' &&
404 !strncmp(dev->name, s[i].name, strlen(s[i].name))) {
405 dev->irq = s[i].map.irq;
406 dev->base_addr = s[i].map.base_addr;
407 dev->mem_start = s[i].map.mem_start;
408 dev->mem_end = s[i].map.mem_end;
409 return 1;
410 }
411 }
412 return 0;
413 }
416 /**
417 * netdev_boot_base - get address from boot time settings
418 * @prefix: prefix for network device
419 * @unit: id for network device
420 *
421 * Check boot time settings for the base address of device.
422 * The found settings are set for the device to be used
423 * later in the device probing.
424 * Returns 0 if no settings found.
425 */
426 unsigned long netdev_boot_base(const char *prefix, int unit)
427 {
428 const struct netdev_boot_setup *s = dev_boot_setup;
429 char name[IFNAMSIZ];
430 int i;
432 sprintf(name, "%s%d", prefix, unit);
434 /*
435 * If device already registered then return base of 1
436 * to indicate not to probe for this interface
437 */
438 if (__dev_get_by_name(name))
439 return 1;
441 for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++)
442 if (!strcmp(name, s[i].name))
443 return s[i].map.base_addr;
444 return 0;
445 }
447 /*
448 * Saves at boot time configured settings for any netdevice.
449 */
450 int __init netdev_boot_setup(char *str)
451 {
452 int ints[5];
453 struct ifmap map;
455 str = get_options(str, ARRAY_SIZE(ints), ints);
456 if (!str || !*str)
457 return 0;
459 /* Save settings */
460 memset(&map, 0, sizeof(map));
461 if (ints[0] > 0)
462 map.irq = ints[1];
463 if (ints[0] > 1)
464 map.base_addr = ints[2];
465 if (ints[0] > 2)
466 map.mem_start = ints[3];
467 if (ints[0] > 3)
468 map.mem_end = ints[4];
470 /* Add new entry to the list */
471 return netdev_boot_setup_add(str, &map);
472 }
474 __setup("netdev=", netdev_boot_setup);
476 /*******************************************************************************
478 Device Interface Subroutines
480 *******************************************************************************/
482 /**
483 * __dev_get_by_name - find a device by its name
484 * @name: name to find
485 *
486 * Find an interface by name. Must be called under RTNL semaphore
487 * or @dev_base_lock. If the name is found a pointer to the device
488 * is returned. If the name is not found then %NULL is returned. The
489 * reference counters are not incremented so the caller must be
490 * careful with locks.
491 */
493 struct net_device *__dev_get_by_name(const char *name)
494 {
495 struct hlist_node *p;
497 hlist_for_each(p, dev_name_hash(name)) {
498 struct net_device *dev
499 = hlist_entry(p, struct net_device, name_hlist);
500 if (!strncmp(dev->name, name, IFNAMSIZ))
501 return dev;
502 }
503 return NULL;
504 }
506 /**
507 * dev_get_by_name - find a device by its name
508 * @name: name to find
509 *
510 * Find an interface by name. This can be called from any
511 * context and does its own locking. The returned handle has
512 * the usage count incremented and the caller must use dev_put() to
513 * release it when it is no longer needed. %NULL is returned if no
514 * matching device is found.
515 */
517 struct net_device *dev_get_by_name(const char *name)
518 {
519 struct net_device *dev;
521 read_lock(&dev_base_lock);
522 dev = __dev_get_by_name(name);
523 if (dev)
524 dev_hold(dev);
525 read_unlock(&dev_base_lock);
526 return dev;
527 }
529 /**
530 * __dev_get_by_index - find a device by its ifindex
531 * @ifindex: index of device
532 *
533 * Search for an interface by index. Returns %NULL if the device
534 * is not found or a pointer to the device. The device has not
535 * had its reference counter increased so the caller must be careful
536 * about locking. The caller must hold either the RTNL semaphore
537 * or @dev_base_lock.
538 */
540 struct net_device *__dev_get_by_index(int ifindex)
541 {
542 struct hlist_node *p;
544 hlist_for_each(p, dev_index_hash(ifindex)) {
545 struct net_device *dev
546 = hlist_entry(p, struct net_device, index_hlist);
547 if (dev->ifindex == ifindex)
548 return dev;
549 }
550 return NULL;
551 }
554 /**
555 * dev_get_by_index - find a device by its ifindex
556 * @ifindex: index of device
557 *
558 * Search for an interface by index. Returns NULL if the device
559 * is not found or a pointer to the device. The device returned has
560 * had a reference added and the pointer is safe until the user calls
561 * dev_put to indicate they have finished with it.
562 */
564 struct net_device *dev_get_by_index(int ifindex)
565 {
566 struct net_device *dev;
568 read_lock(&dev_base_lock);
569 dev = __dev_get_by_index(ifindex);
570 if (dev)
571 dev_hold(dev);
572 read_unlock(&dev_base_lock);
573 return dev;
574 }
576 /**
577 * dev_getbyhwaddr - find a device by its hardware address
578 * @type: media type of device
579 * @ha: hardware address
580 *
581 * Search for an interface by MAC address. Returns NULL if the device
582 * is not found or a pointer to the device. The caller must hold the
583 * rtnl semaphore. The returned device has not had its ref count increased
584 * and the caller must therefore be careful about locking
585 *
586 * BUGS:
587 * If the API was consistent this would be __dev_get_by_hwaddr
588 */
590 struct net_device *dev_getbyhwaddr(unsigned short type, char *ha)
591 {
592 struct net_device *dev;
594 ASSERT_RTNL();
596 for (dev = dev_base; dev; dev = dev->next)
597 if (dev->type == type &&
598 !memcmp(dev->dev_addr, ha, dev->addr_len))
599 break;
600 return dev;
601 }
603 struct net_device *dev_getfirstbyhwtype(unsigned short type)
604 {
605 struct net_device *dev;
607 rtnl_lock();
608 for (dev = dev_base; dev; dev = dev->next) {
609 if (dev->type == type) {
610 dev_hold(dev);
611 break;
612 }
613 }
614 rtnl_unlock();
615 return dev;
616 }
618 EXPORT_SYMBOL(dev_getfirstbyhwtype);
620 /**
621 * dev_get_by_flags - find any device with given flags
622 * @if_flags: IFF_* values
623 * @mask: bitmask of bits in if_flags to check
624 *
625 * Search for any interface with the given flags. Returns NULL if a device
626 * is not found or a pointer to the device. The device returned has
627 * had a reference added and the pointer is safe until the user calls
628 * dev_put to indicate they have finished with it.
629 */
631 struct net_device * dev_get_by_flags(unsigned short if_flags, unsigned short mask)
632 {
633 struct net_device *dev;
635 read_lock(&dev_base_lock);
636 for (dev = dev_base; dev != NULL; dev = dev->next) {
637 if (((dev->flags ^ if_flags) & mask) == 0) {
638 dev_hold(dev);
639 break;
640 }
641 }
642 read_unlock(&dev_base_lock);
643 return dev;
644 }
646 /**
647 * dev_valid_name - check if name is okay for network device
648 * @name: name string
649 *
650 * Network device names need to be valid file names to
651 * to allow sysfs to work
652 */
653 static int dev_valid_name(const char *name)
654 {
655 return !(*name == '\0'
656 || !strcmp(name, ".")
657 || !strcmp(name, "..")
658 || strchr(name, '/'));
659 }
661 /**
662 * dev_alloc_name - allocate a name for a device
663 * @dev: device
664 * @name: name format string
665 *
666 * Passed a format string - eg "lt%d" it will try and find a suitable
667 * id. Not efficient for many devices, not called a lot. The caller
668 * must hold the dev_base or rtnl lock while allocating the name and
669 * adding the device in order to avoid duplicates. Returns the number
670 * of the unit assigned or a negative errno code.
671 */
673 int dev_alloc_name(struct net_device *dev, const char *name)
674 {
675 int i = 0;
676 char buf[IFNAMSIZ];
677 const char *p;
678 const int max_netdevices = 8*PAGE_SIZE;
679 long *inuse;
680 struct net_device *d;
682 p = strnchr(name, IFNAMSIZ-1, '%');
683 if (p) {
684 /*
685 * Verify the string as this thing may have come from
686 * the user. There must be either one "%d" and no other "%"
687 * characters.
688 */
689 if (p[1] != 'd' || strchr(p + 2, '%'))
690 return -EINVAL;
692 /* Use one page as a bit array of possible slots */
693 inuse = (long *) get_zeroed_page(GFP_ATOMIC);
694 if (!inuse)
695 return -ENOMEM;
697 for (d = dev_base; d; d = d->next) {
698 if (!sscanf(d->name, name, &i))
699 continue;
700 if (i < 0 || i >= max_netdevices)
701 continue;
703 /* avoid cases where sscanf is not exact inverse of printf */
704 snprintf(buf, sizeof(buf), name, i);
705 if (!strncmp(buf, d->name, IFNAMSIZ))
706 set_bit(i, inuse);
707 }
709 i = find_first_zero_bit(inuse, max_netdevices);
710 free_page((unsigned long) inuse);
711 }
713 snprintf(buf, sizeof(buf), name, i);
714 if (!__dev_get_by_name(buf)) {
715 strlcpy(dev->name, buf, IFNAMSIZ);
716 return i;
717 }
719 /* It is possible to run out of possible slots
720 * when the name is long and there isn't enough space left
721 * for the digits, or if all bits are used.
722 */
723 return -ENFILE;
724 }
727 /**
728 * dev_change_name - change name of a device
729 * @dev: device
730 * @newname: name (or format string) must be at least IFNAMSIZ
731 *
732 * Change name of a device, can pass format strings "eth%d".
733 * for wildcarding.
734 */
735 int dev_change_name(struct net_device *dev, char *newname)
736 {
737 int err = 0;
739 ASSERT_RTNL();
741 if (dev->flags & IFF_UP)
742 return -EBUSY;
744 if (!dev_valid_name(newname))
745 return -EINVAL;
747 if (strchr(newname, '%')) {
748 err = dev_alloc_name(dev, newname);
749 if (err < 0)
750 return err;
751 strcpy(newname, dev->name);
752 }
753 else if (__dev_get_by_name(newname))
754 return -EEXIST;
755 else
756 strlcpy(dev->name, newname, IFNAMSIZ);
758 err = class_device_rename(&dev->class_dev, dev->name);
759 if (!err) {
760 hlist_del(&dev->name_hlist);
761 hlist_add_head(&dev->name_hlist, dev_name_hash(dev->name));
762 notifier_call_chain(&netdev_chain, NETDEV_CHANGENAME, dev);
763 }
765 return err;
766 }
768 /**
769 * netdev_features_change - device changes fatures
770 * @dev: device to cause notification
771 *
772 * Called to indicate a device has changed features.
773 */
774 void netdev_features_change(struct net_device *dev)
775 {
776 notifier_call_chain(&netdev_chain, NETDEV_FEAT_CHANGE, dev);
777 }
778 EXPORT_SYMBOL(netdev_features_change);
780 /**
781 * netdev_state_change - device changes state
782 * @dev: device to cause notification
783 *
784 * Called to indicate a device has changed state. This function calls
785 * the notifier chains for netdev_chain and sends a NEWLINK message
786 * to the routing socket.
787 */
788 void netdev_state_change(struct net_device *dev)
789 {
790 if (dev->flags & IFF_UP) {
791 notifier_call_chain(&netdev_chain, NETDEV_CHANGE, dev);
792 rtmsg_ifinfo(RTM_NEWLINK, dev, 0);
793 }
794 }
796 /**
797 * dev_load - load a network module
798 * @name: name of interface
799 *
800 * If a network interface is not present and the process has suitable
801 * privileges this function loads the module. If module loading is not
802 * available in this kernel then it becomes a nop.
803 */
805 void dev_load(const char *name)
806 {
807 struct net_device *dev;
809 read_lock(&dev_base_lock);
810 dev = __dev_get_by_name(name);
811 read_unlock(&dev_base_lock);
813 if (!dev && capable(CAP_SYS_MODULE))
814 request_module("%s", name);
815 }
817 static int default_rebuild_header(struct sk_buff *skb)
818 {
819 printk(KERN_DEBUG "%s: default_rebuild_header called -- BUG!\n",
820 skb->dev ? skb->dev->name : "NULL!!!");
821 kfree_skb(skb);
822 return 1;
823 }
826 /**
827 * dev_open - prepare an interface for use.
828 * @dev: device to open
829 *
830 * Takes a device from down to up state. The device's private open
831 * function is invoked and then the multicast lists are loaded. Finally
832 * the device is moved into the up state and a %NETDEV_UP message is
833 * sent to the netdev notifier chain.
834 *
835 * Calling this function on an active interface is a nop. On a failure
836 * a negative errno code is returned.
837 */
838 int dev_open(struct net_device *dev)
839 {
840 int ret = 0;
842 /*
843 * Is it already up?
844 */
846 if (dev->flags & IFF_UP)
847 return 0;
849 /*
850 * Is it even present?
851 */
852 if (!netif_device_present(dev))
853 return -ENODEV;
855 /*
856 * Call device private open method
857 */
858 set_bit(__LINK_STATE_START, &dev->state);
859 if (dev->open) {
860 ret = dev->open(dev);
861 if (ret)
862 clear_bit(__LINK_STATE_START, &dev->state);
863 }
865 /*
866 * If it went open OK then:
867 */
869 if (!ret) {
870 /*
871 * Set the flags.
872 */
873 dev->flags |= IFF_UP;
875 /*
876 * Initialize multicasting status
877 */
878 dev_mc_upload(dev);
880 /*
881 * Wakeup transmit queue engine
882 */
883 dev_activate(dev);
885 /*
886 * ... and announce new interface.
887 */
888 notifier_call_chain(&netdev_chain, NETDEV_UP, dev);
889 }
890 return ret;
891 }
893 /**
894 * dev_close - shutdown an interface.
895 * @dev: device to shutdown
896 *
897 * This function moves an active device into down state. A
898 * %NETDEV_GOING_DOWN is sent to the netdev notifier chain. The device
899 * is then deactivated and finally a %NETDEV_DOWN is sent to the notifier
900 * chain.
901 */
902 int dev_close(struct net_device *dev)
903 {
904 if (!(dev->flags & IFF_UP))
905 return 0;
907 /*
908 * Tell people we are going down, so that they can
909 * prepare to death, when device is still operating.
910 */
911 notifier_call_chain(&netdev_chain, NETDEV_GOING_DOWN, dev);
913 dev_deactivate(dev);
915 clear_bit(__LINK_STATE_START, &dev->state);
917 /* Synchronize to scheduled poll. We cannot touch poll list,
918 * it can be even on different cpu. So just clear netif_running(),
919 * and wait when poll really will happen. Actually, the best place
920 * for this is inside dev->stop() after device stopped its irq
921 * engine, but this requires more changes in devices. */
923 smp_mb__after_clear_bit(); /* Commit netif_running(). */
924 while (test_bit(__LINK_STATE_RX_SCHED, &dev->state)) {
925 /* No hurry. */
926 current->state = TASK_INTERRUPTIBLE;
927 schedule_timeout(1);
928 }
930 /*
931 * Call the device specific close. This cannot fail.
932 * Only if device is UP
933 *
934 * We allow it to be called even after a DETACH hot-plug
935 * event.
936 */
937 if (dev->stop)
938 dev->stop(dev);
940 /*
941 * Device is now down.
942 */
944 dev->flags &= ~IFF_UP;
946 /*
947 * Tell people we are down
948 */
949 notifier_call_chain(&netdev_chain, NETDEV_DOWN, dev);
951 return 0;
952 }
955 /*
956 * Device change register/unregister. These are not inline or static
957 * as we export them to the world.
958 */
960 /**
961 * register_netdevice_notifier - register a network notifier block
962 * @nb: notifier
963 *
964 * Register a notifier to be called when network device events occur.
965 * The notifier passed is linked into the kernel structures and must
966 * not be reused until it has been unregistered. A negative errno code
967 * is returned on a failure.
968 *
969 * When registered all registration and up events are replayed
970 * to the new notifier to allow device to have a race free
971 * view of the network device list.
972 */
974 int register_netdevice_notifier(struct notifier_block *nb)
975 {
976 struct net_device *dev;
977 int err;
979 rtnl_lock();
980 err = notifier_chain_register(&netdev_chain, nb);
981 if (!err) {
982 for (dev = dev_base; dev; dev = dev->next) {
983 nb->notifier_call(nb, NETDEV_REGISTER, dev);
985 if (dev->flags & IFF_UP)
986 nb->notifier_call(nb, NETDEV_UP, dev);
987 }
988 }
989 rtnl_unlock();
990 return err;
991 }
993 /**
994 * unregister_netdevice_notifier - unregister a network notifier block
995 * @nb: notifier
996 *
997 * Unregister a notifier previously registered by
998 * register_netdevice_notifier(). The notifier is unlinked into the
999 * kernel structures and may then be reused. A negative errno code
1000 * is returned on a failure.
1001 */
1003 int unregister_netdevice_notifier(struct notifier_block *nb)
1005 return notifier_chain_unregister(&netdev_chain, nb);
1008 /**
1009 * call_netdevice_notifiers - call all network notifier blocks
1010 * @val: value passed unmodified to notifier function
1011 * @v: pointer passed unmodified to notifier function
1013 * Call all network notifier blocks. Parameters and return value
1014 * are as for notifier_call_chain().
1015 */
1017 int call_netdevice_notifiers(unsigned long val, void *v)
1019 return notifier_call_chain(&netdev_chain, val, v);
1022 /* When > 0 there are consumers of rx skb time stamps */
1023 static atomic_t netstamp_needed = ATOMIC_INIT(0);
1025 void net_enable_timestamp(void)
1027 atomic_inc(&netstamp_needed);
1030 void net_disable_timestamp(void)
1032 atomic_dec(&netstamp_needed);
1035 static inline void net_timestamp(struct timeval *stamp)
1037 if (atomic_read(&netstamp_needed))
1038 do_gettimeofday(stamp);
1039 else {
1040 stamp->tv_sec = 0;
1041 stamp->tv_usec = 0;
1045 /*
1046 * Support routine. Sends outgoing frames to any network
1047 * taps currently in use.
1048 */
1050 void dev_queue_xmit_nit(struct sk_buff *skb, struct net_device *dev)
1052 struct packet_type *ptype;
1053 net_timestamp(&skb->stamp);
1055 rcu_read_lock();
1056 list_for_each_entry_rcu(ptype, &ptype_all, list) {
1057 /* Never send packets back to the socket
1058 * they originated from - MvS (miquels@drinkel.ow.org)
1059 */
1060 if ((ptype->dev == dev || !ptype->dev) &&
1061 (ptype->af_packet_priv == NULL ||
1062 (struct sock *)ptype->af_packet_priv != skb->sk)) {
1063 struct sk_buff *skb2= skb_clone(skb, GFP_ATOMIC);
1064 if (!skb2)
1065 break;
1067 /* skb->nh should be correctly
1068 set by sender, so that the second statement is
1069 just protection against buggy protocols.
1070 */
1071 skb2->mac.raw = skb2->data;
1073 if (skb2->nh.raw < skb2->data ||
1074 skb2->nh.raw > skb2->tail) {
1075 if (net_ratelimit())
1076 printk(KERN_CRIT "protocol %04x is "
1077 "buggy, dev %s\n",
1078 skb2->protocol, dev->name);
1079 skb2->nh.raw = skb2->data;
1082 skb2->h.raw = skb2->nh.raw;
1083 skb2->pkt_type = PACKET_OUTGOING;
1084 ptype->func(skb2, skb->dev, ptype);
1087 rcu_read_unlock();
1090 /*
1091 * Invalidate hardware checksum when packet is to be mangled, and
1092 * complete checksum manually on outgoing path.
1093 */
1094 int skb_checksum_help(struct sk_buff *skb, int inward)
1096 unsigned int csum;
1097 int ret = 0, offset = skb->h.raw - skb->data;
1099 if (inward) {
1100 skb->ip_summed = CHECKSUM_NONE;
1101 goto out;
1104 if (skb_cloned(skb)) {
1105 ret = pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
1106 if (ret)
1107 goto out;
1110 if (offset > (int)skb->len)
1111 BUG();
1112 csum = skb_checksum(skb, offset, skb->len-offset, 0);
1114 offset = skb->tail - skb->h.raw;
1115 if (offset <= 0)
1116 BUG();
1117 if (skb->csum + 2 > offset)
1118 BUG();
1120 *(u16*)(skb->h.raw + skb->csum) = csum_fold(csum);
1121 skb->ip_summed = CHECKSUM_NONE;
1122 out:
1123 return ret;
1126 #ifdef CONFIG_HIGHMEM
1127 /* Actually, we should eliminate this check as soon as we know, that:
1128 * 1. IOMMU is present and allows to map all the memory.
1129 * 2. No high memory really exists on this machine.
1130 */
1132 static inline int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
1134 int i;
1136 if (dev->features & NETIF_F_HIGHDMA)
1137 return 0;
1139 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1140 if (PageHighMem(skb_shinfo(skb)->frags[i].page))
1141 return 1;
1143 return 0;
1145 #else
1146 #define illegal_highdma(dev, skb) (0)
1147 #endif
1149 extern void skb_release_data(struct sk_buff *);
1151 /* Keep head the same: replace data */
1152 int __skb_linearize(struct sk_buff *skb, int gfp_mask)
1154 unsigned int size;
1155 u8 *data;
1156 long offset;
1157 struct skb_shared_info *ninfo;
1158 int headerlen = skb->data - skb->head;
1159 int expand = (skb->tail + skb->data_len) - skb->end;
1161 if (skb_shared(skb))
1162 BUG();
1164 if (expand <= 0)
1165 expand = 0;
1167 size = skb->end - skb->head + expand;
1168 size = SKB_DATA_ALIGN(size);
1169 data = kmalloc(size + sizeof(struct skb_shared_info), gfp_mask);
1170 if (!data)
1171 return -ENOMEM;
1173 /* Copy entire thing */
1174 if (skb_copy_bits(skb, -headerlen, data, headerlen + skb->len))
1175 BUG();
1177 /* Set up shinfo */
1178 ninfo = (struct skb_shared_info*)(data + size);
1179 atomic_set(&ninfo->dataref, 1);
1180 ninfo->tso_size = skb_shinfo(skb)->tso_size;
1181 ninfo->tso_segs = skb_shinfo(skb)->tso_segs;
1182 ninfo->nr_frags = 0;
1183 ninfo->frag_list = NULL;
1185 /* Offset between the two in bytes */
1186 offset = data - skb->head;
1188 /* Free old data. */
1189 skb_release_data(skb);
1191 skb->head = data;
1192 skb->end = data + size;
1194 /* Set up new pointers */
1195 skb->h.raw += offset;
1196 skb->nh.raw += offset;
1197 skb->mac.raw += offset;
1198 skb->tail += offset;
1199 skb->data += offset;
1201 /* We are no longer a clone, even if we were. */
1202 skb->cloned = 0;
1204 skb->tail += skb->data_len;
1205 skb->data_len = 0;
1206 return 0;
1209 #define HARD_TX_LOCK(dev, cpu) { \
1210 if ((dev->features & NETIF_F_LLTX) == 0) { \
1211 spin_lock(&dev->xmit_lock); \
1212 dev->xmit_lock_owner = cpu; \
1213 } \
1216 #define HARD_TX_UNLOCK(dev) { \
1217 if ((dev->features & NETIF_F_LLTX) == 0) { \
1218 dev->xmit_lock_owner = -1; \
1219 spin_unlock(&dev->xmit_lock); \
1220 } \
1223 /**
1224 * dev_queue_xmit - transmit a buffer
1225 * @skb: buffer to transmit
1227 * Queue a buffer for transmission to a network device. The caller must
1228 * have set the device and priority and built the buffer before calling
1229 * this function. The function can be called from an interrupt.
1231 * A negative errno code is returned on a failure. A success does not
1232 * guarantee the frame will be transmitted as it may be dropped due
1233 * to congestion or traffic shaping.
1235 * -----------------------------------------------------------------------------------
1236 * I notice this method can also return errors from the queue disciplines,
1237 * including NET_XMIT_DROP, which is a positive value. So, errors can also
1238 * be positive.
1240 * Regardless of the return value, the skb is consumed, so it is currently
1241 * difficult to retry a send to this method. (You can bump the ref count
1242 * before sending to hold a reference for retry if you are careful.)
1244 * When calling this method, interrupts MUST be enabled. This is because
1245 * the BH enable code must have IRQs enabled so that it will not deadlock.
1246 * --BLG
1247 */
1249 int dev_queue_xmit(struct sk_buff *skb)
1251 struct net_device *dev = skb->dev;
1252 struct Qdisc *q;
1253 int rc = -ENOMEM;
1255 if (skb_shinfo(skb)->frag_list &&
1256 !(dev->features & NETIF_F_FRAGLIST) &&
1257 __skb_linearize(skb, GFP_ATOMIC))
1258 goto out_kfree_skb;
1260 /* Fragmented skb is linearized if device does not support SG,
1261 * or if at least one of fragments is in highmem and device
1262 * does not support DMA from it.
1263 */
1264 if (skb_shinfo(skb)->nr_frags &&
1265 (!(dev->features & NETIF_F_SG) || illegal_highdma(dev, skb)) &&
1266 __skb_linearize(skb, GFP_ATOMIC))
1267 goto out_kfree_skb;
1269 /* If a checksum-deferred packet is forwarded to a device that needs a
1270 * checksum, correct the pointers and force checksumming.
1271 */
1272 if (skb->proto_csum_blank) {
1273 if (skb->protocol != htons(ETH_P_IP))
1274 goto out_kfree_skb;
1275 skb->h.raw = (unsigned char *)skb->nh.iph + 4*skb->nh.iph->ihl;
1276 if (skb->h.raw >= skb->tail)
1277 goto out_kfree_skb;
1278 switch (skb->nh.iph->protocol) {
1279 case IPPROTO_TCP:
1280 skb->csum = offsetof(struct tcphdr, check);
1281 break;
1282 case IPPROTO_UDP:
1283 skb->csum = offsetof(struct udphdr, check);
1284 break;
1285 default:
1286 goto out_kfree_skb;
1288 if ((skb->h.raw + skb->csum + 2) > skb->tail)
1289 goto out_kfree_skb;
1290 skb->ip_summed = CHECKSUM_HW;
1293 /* If packet is not checksummed and device does not support
1294 * checksumming for this protocol, complete checksumming here.
1295 */
1296 if (skb->ip_summed == CHECKSUM_HW &&
1297 (!(dev->features & (NETIF_F_HW_CSUM | NETIF_F_NO_CSUM)) &&
1298 (!(dev->features & NETIF_F_IP_CSUM) ||
1299 skb->protocol != htons(ETH_P_IP))))
1300 if (skb_checksum_help(skb, 0))
1301 goto out_kfree_skb;
1303 /* Disable soft irqs for various locks below. Also
1304 * stops preemption for RCU.
1305 */
1306 local_bh_disable();
1308 /* Updates of qdisc are serialized by queue_lock.
1309 * The struct Qdisc which is pointed to by qdisc is now a
1310 * rcu structure - it may be accessed without acquiring
1311 * a lock (but the structure may be stale.) The freeing of the
1312 * qdisc will be deferred until it's known that there are no
1313 * more references to it.
1315 * If the qdisc has an enqueue function, we still need to
1316 * hold the queue_lock before calling it, since queue_lock
1317 * also serializes access to the device queue.
1318 */
1320 q = rcu_dereference(dev->qdisc);
1321 #ifdef CONFIG_NET_CLS_ACT
1322 skb->tc_verd = SET_TC_AT(skb->tc_verd,AT_EGRESS);
1323 #endif
1324 if (q->enqueue) {
1325 /* Grab device queue */
1326 spin_lock(&dev->queue_lock);
1328 rc = q->enqueue(skb, q);
1330 qdisc_run(dev);
1332 spin_unlock(&dev->queue_lock);
1333 rc = rc == NET_XMIT_BYPASS ? NET_XMIT_SUCCESS : rc;
1334 goto out;
1337 /* The device has no queue. Common case for software devices:
1338 loopback, all the sorts of tunnels...
1340 Really, it is unlikely that xmit_lock protection is necessary here.
1341 (f.e. loopback and IP tunnels are clean ignoring statistics
1342 counters.)
1343 However, it is possible, that they rely on protection
1344 made by us here.
1346 Check this and shot the lock. It is not prone from deadlocks.
1347 Either shot noqueue qdisc, it is even simpler 8)
1348 */
1349 if (dev->flags & IFF_UP) {
1350 int cpu = smp_processor_id(); /* ok because BHs are off */
1352 if (dev->xmit_lock_owner != cpu) {
1354 HARD_TX_LOCK(dev, cpu);
1356 if (!netif_queue_stopped(dev)) {
1357 if (netdev_nit)
1358 dev_queue_xmit_nit(skb, dev);
1360 rc = 0;
1361 if (!dev->hard_start_xmit(skb, dev)) {
1362 HARD_TX_UNLOCK(dev);
1363 goto out;
1366 HARD_TX_UNLOCK(dev);
1367 if (net_ratelimit())
1368 printk(KERN_CRIT "Virtual device %s asks to "
1369 "queue packet!\n", dev->name);
1370 } else {
1371 /* Recursion is detected! It is possible,
1372 * unfortunately */
1373 if (net_ratelimit())
1374 printk(KERN_CRIT "Dead loop on virtual device "
1375 "%s, fix it urgently!\n", dev->name);
1379 rc = -ENETDOWN;
1380 local_bh_enable();
1382 out_kfree_skb:
1383 kfree_skb(skb);
1384 return rc;
1385 out:
1386 local_bh_enable();
1387 return rc;
1391 /*=======================================================================
1392 Receiver routines
1393 =======================================================================*/
1395 int netdev_max_backlog = 300;
1396 int weight_p = 64; /* old backlog weight */
1397 /* These numbers are selected based on intuition and some
1398 * experimentatiom, if you have more scientific way of doing this
1399 * please go ahead and fix things.
1400 */
1401 int no_cong_thresh = 10;
1402 int no_cong = 20;
1403 int lo_cong = 100;
1404 int mod_cong = 290;
1406 DEFINE_PER_CPU(struct netif_rx_stats, netdev_rx_stat) = { 0, };
1409 static void get_sample_stats(int cpu)
1411 #ifdef RAND_LIE
1412 unsigned long rd;
1413 int rq;
1414 #endif
1415 struct softnet_data *sd = &per_cpu(softnet_data, cpu);
1416 int blog = sd->input_pkt_queue.qlen;
1417 int avg_blog = sd->avg_blog;
1419 avg_blog = (avg_blog >> 1) + (blog >> 1);
1421 if (avg_blog > mod_cong) {
1422 /* Above moderate congestion levels. */
1423 sd->cng_level = NET_RX_CN_HIGH;
1424 #ifdef RAND_LIE
1425 rd = net_random();
1426 rq = rd % netdev_max_backlog;
1427 if (rq < avg_blog) /* unlucky bastard */
1428 sd->cng_level = NET_RX_DROP;
1429 #endif
1430 } else if (avg_blog > lo_cong) {
1431 sd->cng_level = NET_RX_CN_MOD;
1432 #ifdef RAND_LIE
1433 rd = net_random();
1434 rq = rd % netdev_max_backlog;
1435 if (rq < avg_blog) /* unlucky bastard */
1436 sd->cng_level = NET_RX_CN_HIGH;
1437 #endif
1438 } else if (avg_blog > no_cong)
1439 sd->cng_level = NET_RX_CN_LOW;
1440 else /* no congestion */
1441 sd->cng_level = NET_RX_SUCCESS;
1443 sd->avg_blog = avg_blog;
1446 #ifdef OFFLINE_SAMPLE
1447 static void sample_queue(unsigned long dummy)
1449 /* 10 ms 0r 1ms -- i don't care -- JHS */
1450 int next_tick = 1;
1451 int cpu = smp_processor_id();
1453 get_sample_stats(cpu);
1454 next_tick += jiffies;
1455 mod_timer(&samp_timer, next_tick);
1457 #endif
1460 /**
1461 * netif_rx - post buffer to the network code
1462 * @skb: buffer to post
1464 * This function receives a packet from a device driver and queues it for
1465 * the upper (protocol) levels to process. It always succeeds. The buffer
1466 * may be dropped during processing for congestion control or by the
1467 * protocol layers.
1469 * return values:
1470 * NET_RX_SUCCESS (no congestion)
1471 * NET_RX_CN_LOW (low congestion)
1472 * NET_RX_CN_MOD (moderate congestion)
1473 * NET_RX_CN_HIGH (high congestion)
1474 * NET_RX_DROP (packet was dropped)
1476 */
1478 int netif_rx(struct sk_buff *skb)
1480 int this_cpu;
1481 struct softnet_data *queue;
1482 unsigned long flags;
1484 /* if netpoll wants it, pretend we never saw it */
1485 if (netpoll_rx(skb))
1486 return NET_RX_DROP;
1488 if (!skb->stamp.tv_sec)
1489 net_timestamp(&skb->stamp);
1491 /*
1492 * The code is rearranged so that the path is the most
1493 * short when CPU is congested, but is still operating.
1494 */
1495 local_irq_save(flags);
1496 this_cpu = smp_processor_id();
1497 queue = &__get_cpu_var(softnet_data);
1499 __get_cpu_var(netdev_rx_stat).total++;
1500 if (queue->input_pkt_queue.qlen <= netdev_max_backlog) {
1501 if (queue->input_pkt_queue.qlen) {
1502 if (queue->throttle)
1503 goto drop;
1505 enqueue:
1506 dev_hold(skb->dev);
1507 __skb_queue_tail(&queue->input_pkt_queue, skb);
1508 #ifndef OFFLINE_SAMPLE
1509 get_sample_stats(this_cpu);
1510 #endif
1511 local_irq_restore(flags);
1512 return queue->cng_level;
1515 if (queue->throttle)
1516 queue->throttle = 0;
1518 netif_rx_schedule(&queue->backlog_dev);
1519 goto enqueue;
1522 if (!queue->throttle) {
1523 queue->throttle = 1;
1524 __get_cpu_var(netdev_rx_stat).throttled++;
1527 drop:
1528 __get_cpu_var(netdev_rx_stat).dropped++;
1529 local_irq_restore(flags);
1531 kfree_skb(skb);
1532 return NET_RX_DROP;
1535 int netif_rx_ni(struct sk_buff *skb)
1537 int err;
1539 preempt_disable();
1540 err = netif_rx(skb);
1541 if (local_softirq_pending())
1542 do_softirq();
1543 preempt_enable();
1545 return err;
1548 EXPORT_SYMBOL(netif_rx_ni);
1550 static __inline__ void skb_bond(struct sk_buff *skb)
1552 struct net_device *dev = skb->dev;
1554 if (dev->master) {
1555 skb->real_dev = skb->dev;
1556 skb->dev = dev->master;
1560 static void net_tx_action(struct softirq_action *h)
1562 struct softnet_data *sd = &__get_cpu_var(softnet_data);
1564 if (sd->completion_queue) {
1565 struct sk_buff *clist;
1567 local_irq_disable();
1568 clist = sd->completion_queue;
1569 sd->completion_queue = NULL;
1570 local_irq_enable();
1572 while (clist) {
1573 struct sk_buff *skb = clist;
1574 clist = clist->next;
1576 BUG_TRAP(!atomic_read(&skb->users));
1577 __kfree_skb(skb);
1581 if (sd->output_queue) {
1582 struct net_device *head;
1584 local_irq_disable();
1585 head = sd->output_queue;
1586 sd->output_queue = NULL;
1587 local_irq_enable();
1589 while (head) {
1590 struct net_device *dev = head;
1591 head = head->next_sched;
1593 smp_mb__before_clear_bit();
1594 clear_bit(__LINK_STATE_SCHED, &dev->state);
1596 if (spin_trylock(&dev->queue_lock)) {
1597 qdisc_run(dev);
1598 spin_unlock(&dev->queue_lock);
1599 } else {
1600 netif_schedule(dev);
1606 static __inline__ int deliver_skb(struct sk_buff *skb,
1607 struct packet_type *pt_prev)
1609 atomic_inc(&skb->users);
1610 return pt_prev->func(skb, skb->dev, pt_prev);
1613 #if defined(CONFIG_BRIDGE) || defined (CONFIG_BRIDGE_MODULE)
1614 int (*br_handle_frame_hook)(struct net_bridge_port *p, struct sk_buff **pskb);
1615 struct net_bridge;
1616 struct net_bridge_fdb_entry *(*br_fdb_get_hook)(struct net_bridge *br,
1617 unsigned char *addr);
1618 void (*br_fdb_put_hook)(struct net_bridge_fdb_entry *ent);
1620 static __inline__ int handle_bridge(struct sk_buff **pskb,
1621 struct packet_type **pt_prev, int *ret)
1623 struct net_bridge_port *port;
1625 if ((*pskb)->pkt_type == PACKET_LOOPBACK ||
1626 (port = rcu_dereference((*pskb)->dev->br_port)) == NULL)
1627 return 0;
1629 if (*pt_prev) {
1630 *ret = deliver_skb(*pskb, *pt_prev);
1631 *pt_prev = NULL;
1634 return br_handle_frame_hook(port, pskb);
1636 #else
1637 #define handle_bridge(skb, pt_prev, ret) (0)
1638 #endif
1640 #ifdef CONFIG_NET_CLS_ACT
1641 /* TODO: Maybe we should just force sch_ingress to be compiled in
1642 * when CONFIG_NET_CLS_ACT is? otherwise some useless instructions
1643 * a compare and 2 stores extra right now if we dont have it on
1644 * but have CONFIG_NET_CLS_ACT
1645 * NOTE: This doesnt stop any functionality; if you dont have
1646 * the ingress scheduler, you just cant add policies on ingress.
1648 */
1649 static int ing_filter(struct sk_buff *skb)
1651 struct Qdisc *q;
1652 struct net_device *dev = skb->dev;
1653 int result = TC_ACT_OK;
1655 if (dev->qdisc_ingress) {
1656 __u32 ttl = (__u32) G_TC_RTTL(skb->tc_verd);
1657 if (MAX_RED_LOOP < ttl++) {
1658 printk("Redir loop detected Dropping packet (%s->%s)\n",
1659 skb->input_dev?skb->input_dev->name:"??",skb->dev->name);
1660 return TC_ACT_SHOT;
1663 skb->tc_verd = SET_TC_RTTL(skb->tc_verd,ttl);
1665 skb->tc_verd = SET_TC_AT(skb->tc_verd,AT_INGRESS);
1666 if (NULL == skb->input_dev) {
1667 skb->input_dev = skb->dev;
1668 printk("ing_filter: fixed %s out %s\n",skb->input_dev->name,skb->dev->name);
1670 spin_lock(&dev->ingress_lock);
1671 if ((q = dev->qdisc_ingress) != NULL)
1672 result = q->enqueue(skb, q);
1673 spin_unlock(&dev->ingress_lock);
1677 return result;
1679 #endif
1681 int netif_receive_skb(struct sk_buff *skb)
1683 struct packet_type *ptype, *pt_prev;
1684 int ret = NET_RX_DROP;
1685 unsigned short type;
1687 /* if we've gotten here through NAPI, check netpoll */
1688 if (skb->dev->poll && netpoll_rx(skb))
1689 return NET_RX_DROP;
1691 if (!skb->stamp.tv_sec)
1692 net_timestamp(&skb->stamp);
1694 skb_bond(skb);
1696 __get_cpu_var(netdev_rx_stat).total++;
1698 skb->h.raw = skb->nh.raw = skb->data;
1699 skb->mac_len = skb->nh.raw - skb->mac.raw;
1701 pt_prev = NULL;
1703 rcu_read_lock();
1705 #ifdef CONFIG_NET_CLS_ACT
1706 if (skb->tc_verd & TC_NCLS) {
1707 skb->tc_verd = CLR_TC_NCLS(skb->tc_verd);
1708 goto ncls;
1710 #endif
1712 switch (skb->ip_summed) {
1713 case CHECKSUM_UNNECESSARY:
1714 skb->proto_csum_valid = 1;
1715 break;
1716 case CHECKSUM_HW:
1717 /* XXX Implement me. */
1718 default:
1719 skb->proto_csum_valid = 0;
1720 break;
1723 list_for_each_entry_rcu(ptype, &ptype_all, list) {
1724 if (!ptype->dev || ptype->dev == skb->dev) {
1725 if (pt_prev)
1726 ret = deliver_skb(skb, pt_prev);
1727 pt_prev = ptype;
1731 #ifdef CONFIG_NET_CLS_ACT
1732 if (pt_prev) {
1733 ret = deliver_skb(skb, pt_prev);
1734 pt_prev = NULL; /* noone else should process this after*/
1735 } else {
1736 skb->tc_verd = SET_TC_OK2MUNGE(skb->tc_verd);
1739 ret = ing_filter(skb);
1741 if (ret == TC_ACT_SHOT || (ret == TC_ACT_STOLEN)) {
1742 kfree_skb(skb);
1743 goto out;
1746 skb->tc_verd = 0;
1747 ncls:
1748 #endif
1750 handle_diverter(skb);
1752 if (handle_bridge(&skb, &pt_prev, &ret))
1753 goto out;
1755 type = skb->protocol;
1756 list_for_each_entry_rcu(ptype, &ptype_base[ntohs(type)&15], list) {
1757 if (ptype->type == type &&
1758 (!ptype->dev || ptype->dev == skb->dev)) {
1759 if (pt_prev)
1760 ret = deliver_skb(skb, pt_prev);
1761 pt_prev = ptype;
1765 if (pt_prev) {
1766 ret = pt_prev->func(skb, skb->dev, pt_prev);
1767 } else {
1768 kfree_skb(skb);
1769 /* Jamal, now you will not able to escape explaining
1770 * me how you were going to use this. :-)
1771 */
1772 ret = NET_RX_DROP;
1775 out:
1776 rcu_read_unlock();
1777 return ret;
1780 static int process_backlog(struct net_device *backlog_dev, int *budget)
1782 int work = 0;
1783 int quota = min(backlog_dev->quota, *budget);
1784 struct softnet_data *queue = &__get_cpu_var(softnet_data);
1785 unsigned long start_time = jiffies;
1787 backlog_dev->weight = weight_p;
1788 for (;;) {
1789 struct sk_buff *skb;
1790 struct net_device *dev;
1792 local_irq_disable();
1793 skb = __skb_dequeue(&queue->input_pkt_queue);
1794 if (!skb)
1795 goto job_done;
1796 local_irq_enable();
1798 dev = skb->dev;
1800 netif_receive_skb(skb);
1802 dev_put(dev);
1804 work++;
1806 if (work >= quota || jiffies - start_time > 1)
1807 break;
1811 backlog_dev->quota -= work;
1812 *budget -= work;
1813 return -1;
1815 job_done:
1816 backlog_dev->quota -= work;
1817 *budget -= work;
1819 list_del(&backlog_dev->poll_list);
1820 smp_mb__before_clear_bit();
1821 netif_poll_enable(backlog_dev);
1823 if (queue->throttle)
1824 queue->throttle = 0;
1825 local_irq_enable();
1826 return 0;
1829 static void net_rx_action(struct softirq_action *h)
1831 struct softnet_data *queue = &__get_cpu_var(softnet_data);
1832 unsigned long start_time = jiffies;
1833 int budget = netdev_max_backlog;
1836 local_irq_disable();
1838 while (!list_empty(&queue->poll_list)) {
1839 struct net_device *dev;
1841 if (budget <= 0 || jiffies - start_time > 1)
1842 goto softnet_break;
1844 local_irq_enable();
1846 dev = list_entry(queue->poll_list.next,
1847 struct net_device, poll_list);
1848 netpoll_poll_lock(dev);
1850 if (dev->quota <= 0 || dev->poll(dev, &budget)) {
1851 netpoll_poll_unlock(dev);
1852 local_irq_disable();
1853 list_del(&dev->poll_list);
1854 list_add_tail(&dev->poll_list, &queue->poll_list);
1855 if (dev->quota < 0)
1856 dev->quota += dev->weight;
1857 else
1858 dev->quota = dev->weight;
1859 } else {
1860 netpoll_poll_unlock(dev);
1861 dev_put(dev);
1862 local_irq_disable();
1865 out:
1866 local_irq_enable();
1867 return;
1869 softnet_break:
1870 __get_cpu_var(netdev_rx_stat).time_squeeze++;
1871 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
1872 goto out;
1875 static gifconf_func_t * gifconf_list [NPROTO];
1877 /**
1878 * register_gifconf - register a SIOCGIF handler
1879 * @family: Address family
1880 * @gifconf: Function handler
1882 * Register protocol dependent address dumping routines. The handler
1883 * that is passed must not be freed or reused until it has been replaced
1884 * by another handler.
1885 */
1886 int register_gifconf(unsigned int family, gifconf_func_t * gifconf)
1888 if (family >= NPROTO)
1889 return -EINVAL;
1890 gifconf_list[family] = gifconf;
1891 return 0;
1895 /*
1896 * Map an interface index to its name (SIOCGIFNAME)
1897 */
1899 /*
1900 * We need this ioctl for efficient implementation of the
1901 * if_indextoname() function required by the IPv6 API. Without
1902 * it, we would have to search all the interfaces to find a
1903 * match. --pb
1904 */
1906 static int dev_ifname(struct ifreq __user *arg)
1908 struct net_device *dev;
1909 struct ifreq ifr;
1911 /*
1912 * Fetch the caller's info block.
1913 */
1915 if (copy_from_user(&ifr, arg, sizeof(struct ifreq)))
1916 return -EFAULT;
1918 read_lock(&dev_base_lock);
1919 dev = __dev_get_by_index(ifr.ifr_ifindex);
1920 if (!dev) {
1921 read_unlock(&dev_base_lock);
1922 return -ENODEV;
1925 strcpy(ifr.ifr_name, dev->name);
1926 read_unlock(&dev_base_lock);
1928 if (copy_to_user(arg, &ifr, sizeof(struct ifreq)))
1929 return -EFAULT;
1930 return 0;
1933 /*
1934 * Perform a SIOCGIFCONF call. This structure will change
1935 * size eventually, and there is nothing I can do about it.
1936 * Thus we will need a 'compatibility mode'.
1937 */
1939 static int dev_ifconf(char __user *arg)
1941 struct ifconf ifc;
1942 struct net_device *dev;
1943 char __user *pos;
1944 int len;
1945 int total;
1946 int i;
1948 /*
1949 * Fetch the caller's info block.
1950 */
1952 if (copy_from_user(&ifc, arg, sizeof(struct ifconf)))
1953 return -EFAULT;
1955 pos = ifc.ifc_buf;
1956 len = ifc.ifc_len;
1958 /*
1959 * Loop over the interfaces, and write an info block for each.
1960 */
1962 total = 0;
1963 for (dev = dev_base; dev; dev = dev->next) {
1964 for (i = 0; i < NPROTO; i++) {
1965 if (gifconf_list[i]) {
1966 int done;
1967 if (!pos)
1968 done = gifconf_list[i](dev, NULL, 0);
1969 else
1970 done = gifconf_list[i](dev, pos + total,
1971 len - total);
1972 if (done < 0)
1973 return -EFAULT;
1974 total += done;
1979 /*
1980 * All done. Write the updated control block back to the caller.
1981 */
1982 ifc.ifc_len = total;
1984 /*
1985 * Both BSD and Solaris return 0 here, so we do too.
1986 */
1987 return copy_to_user(arg, &ifc, sizeof(struct ifconf)) ? -EFAULT : 0;
1990 #ifdef CONFIG_PROC_FS
1991 /*
1992 * This is invoked by the /proc filesystem handler to display a device
1993 * in detail.
1994 */
1995 static __inline__ struct net_device *dev_get_idx(loff_t pos)
1997 struct net_device *dev;
1998 loff_t i;
2000 for (i = 0, dev = dev_base; dev && i < pos; ++i, dev = dev->next);
2002 return i == pos ? dev : NULL;
2005 void *dev_seq_start(struct seq_file *seq, loff_t *pos)
2007 read_lock(&dev_base_lock);
2008 return *pos ? dev_get_idx(*pos - 1) : SEQ_START_TOKEN;
2011 void *dev_seq_next(struct seq_file *seq, void *v, loff_t *pos)
2013 ++*pos;
2014 return v == SEQ_START_TOKEN ? dev_base : ((struct net_device *)v)->next;
2017 void dev_seq_stop(struct seq_file *seq, void *v)
2019 read_unlock(&dev_base_lock);
2022 static void dev_seq_printf_stats(struct seq_file *seq, struct net_device *dev)
2024 if (dev->get_stats) {
2025 struct net_device_stats *stats = dev->get_stats(dev);
2027 seq_printf(seq, "%6s:%8lu %7lu %4lu %4lu %4lu %5lu %10lu %9lu "
2028 "%8lu %7lu %4lu %4lu %4lu %5lu %7lu %10lu\n",
2029 dev->name, stats->rx_bytes, stats->rx_packets,
2030 stats->rx_errors,
2031 stats->rx_dropped + stats->rx_missed_errors,
2032 stats->rx_fifo_errors,
2033 stats->rx_length_errors + stats->rx_over_errors +
2034 stats->rx_crc_errors + stats->rx_frame_errors,
2035 stats->rx_compressed, stats->multicast,
2036 stats->tx_bytes, stats->tx_packets,
2037 stats->tx_errors, stats->tx_dropped,
2038 stats->tx_fifo_errors, stats->collisions,
2039 stats->tx_carrier_errors +
2040 stats->tx_aborted_errors +
2041 stats->tx_window_errors +
2042 stats->tx_heartbeat_errors,
2043 stats->tx_compressed);
2044 } else
2045 seq_printf(seq, "%6s: No statistics available.\n", dev->name);
2048 /*
2049 * Called from the PROCfs module. This now uses the new arbitrary sized
2050 * /proc/net interface to create /proc/net/dev
2051 */
2052 static int dev_seq_show(struct seq_file *seq, void *v)
2054 if (v == SEQ_START_TOKEN)
2055 seq_puts(seq, "Inter-| Receive "
2056 " | Transmit\n"
2057 " face |bytes packets errs drop fifo frame "
2058 "compressed multicast|bytes packets errs "
2059 "drop fifo colls carrier compressed\n");
2060 else
2061 dev_seq_printf_stats(seq, v);
2062 return 0;
2065 static struct netif_rx_stats *softnet_get_online(loff_t *pos)
2067 struct netif_rx_stats *rc = NULL;
2069 while (*pos < NR_CPUS)
2070 if (cpu_online(*pos)) {
2071 rc = &per_cpu(netdev_rx_stat, *pos);
2072 break;
2073 } else
2074 ++*pos;
2075 return rc;
2078 static void *softnet_seq_start(struct seq_file *seq, loff_t *pos)
2080 return softnet_get_online(pos);
2083 static void *softnet_seq_next(struct seq_file *seq, void *v, loff_t *pos)
2085 ++*pos;
2086 return softnet_get_online(pos);
2089 static void softnet_seq_stop(struct seq_file *seq, void *v)
2093 static int softnet_seq_show(struct seq_file *seq, void *v)
2095 struct netif_rx_stats *s = v;
2097 seq_printf(seq, "%08x %08x %08x %08x %08x %08x %08x %08x %08x\n",
2098 s->total, s->dropped, s->time_squeeze, s->throttled,
2099 s->fastroute_hit, s->fastroute_success, s->fastroute_defer,
2100 s->fastroute_deferred_out,
2101 #if 0
2102 s->fastroute_latency_reduction
2103 #else
2104 s->cpu_collision
2105 #endif
2106 );
2107 return 0;
2110 static struct seq_operations dev_seq_ops = {
2111 .start = dev_seq_start,
2112 .next = dev_seq_next,
2113 .stop = dev_seq_stop,
2114 .show = dev_seq_show,
2115 };
2117 static int dev_seq_open(struct inode *inode, struct file *file)
2119 return seq_open(file, &dev_seq_ops);
2122 static struct file_operations dev_seq_fops = {
2123 .owner = THIS_MODULE,
2124 .open = dev_seq_open,
2125 .read = seq_read,
2126 .llseek = seq_lseek,
2127 .release = seq_release,
2128 };
2130 static struct seq_operations softnet_seq_ops = {
2131 .start = softnet_seq_start,
2132 .next = softnet_seq_next,
2133 .stop = softnet_seq_stop,
2134 .show = softnet_seq_show,
2135 };
2137 static int softnet_seq_open(struct inode *inode, struct file *file)
2139 return seq_open(file, &softnet_seq_ops);
2142 static struct file_operations softnet_seq_fops = {
2143 .owner = THIS_MODULE,
2144 .open = softnet_seq_open,
2145 .read = seq_read,
2146 .llseek = seq_lseek,
2147 .release = seq_release,
2148 };
2150 #ifdef WIRELESS_EXT
2151 extern int wireless_proc_init(void);
2152 #else
2153 #define wireless_proc_init() 0
2154 #endif
2156 static int __init dev_proc_init(void)
2158 int rc = -ENOMEM;
2160 if (!proc_net_fops_create("dev", S_IRUGO, &dev_seq_fops))
2161 goto out;
2162 if (!proc_net_fops_create("softnet_stat", S_IRUGO, &softnet_seq_fops))
2163 goto out_dev;
2164 if (wireless_proc_init())
2165 goto out_softnet;
2166 rc = 0;
2167 out:
2168 return rc;
2169 out_softnet:
2170 proc_net_remove("softnet_stat");
2171 out_dev:
2172 proc_net_remove("dev");
2173 goto out;
2175 #else
2176 #define dev_proc_init() 0
2177 #endif /* CONFIG_PROC_FS */
2180 /**
2181 * netdev_set_master - set up master/slave pair
2182 * @slave: slave device
2183 * @master: new master device
2185 * Changes the master device of the slave. Pass %NULL to break the
2186 * bonding. The caller must hold the RTNL semaphore. On a failure
2187 * a negative errno code is returned. On success the reference counts
2188 * are adjusted, %RTM_NEWLINK is sent to the routing socket and the
2189 * function returns zero.
2190 */
2191 int netdev_set_master(struct net_device *slave, struct net_device *master)
2193 struct net_device *old = slave->master;
2195 ASSERT_RTNL();
2197 if (master) {
2198 if (old)
2199 return -EBUSY;
2200 dev_hold(master);
2203 slave->master = master;
2205 synchronize_net();
2207 if (old)
2208 dev_put(old);
2210 if (master)
2211 slave->flags |= IFF_SLAVE;
2212 else
2213 slave->flags &= ~IFF_SLAVE;
2215 rtmsg_ifinfo(RTM_NEWLINK, slave, IFF_SLAVE);
2216 return 0;
2219 /**
2220 * dev_set_promiscuity - update promiscuity count on a device
2221 * @dev: device
2222 * @inc: modifier
2224 * Add or remove promsicuity from a device. While the count in the device
2225 * remains above zero the interface remains promiscuous. Once it hits zero
2226 * the device reverts back to normal filtering operation. A negative inc
2227 * value is used to drop promiscuity on the device.
2228 */
2229 void dev_set_promiscuity(struct net_device *dev, int inc)
2231 unsigned short old_flags = dev->flags;
2233 dev->flags |= IFF_PROMISC;
2234 if ((dev->promiscuity += inc) == 0)
2235 dev->flags &= ~IFF_PROMISC;
2236 if (dev->flags ^ old_flags) {
2237 dev_mc_upload(dev);
2238 printk(KERN_INFO "device %s %s promiscuous mode\n",
2239 dev->name, (dev->flags & IFF_PROMISC) ? "entered" :
2240 "left");
2244 /**
2245 * dev_set_allmulti - update allmulti count on a device
2246 * @dev: device
2247 * @inc: modifier
2249 * Add or remove reception of all multicast frames to a device. While the
2250 * count in the device remains above zero the interface remains listening
2251 * to all interfaces. Once it hits zero the device reverts back to normal
2252 * filtering operation. A negative @inc value is used to drop the counter
2253 * when releasing a resource needing all multicasts.
2254 */
2256 void dev_set_allmulti(struct net_device *dev, int inc)
2258 unsigned short old_flags = dev->flags;
2260 dev->flags |= IFF_ALLMULTI;
2261 if ((dev->allmulti += inc) == 0)
2262 dev->flags &= ~IFF_ALLMULTI;
2263 if (dev->flags ^ old_flags)
2264 dev_mc_upload(dev);
2267 unsigned dev_get_flags(const struct net_device *dev)
2269 unsigned flags;
2271 flags = (dev->flags & ~(IFF_PROMISC |
2272 IFF_ALLMULTI |
2273 IFF_RUNNING)) |
2274 (dev->gflags & (IFF_PROMISC |
2275 IFF_ALLMULTI));
2277 if (netif_running(dev) && netif_carrier_ok(dev))
2278 flags |= IFF_RUNNING;
2280 return flags;
2283 int dev_change_flags(struct net_device *dev, unsigned flags)
2285 int ret;
2286 int old_flags = dev->flags;
2288 /*
2289 * Set the flags on our device.
2290 */
2292 dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
2293 IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
2294 IFF_AUTOMEDIA)) |
2295 (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
2296 IFF_ALLMULTI));
2298 /*
2299 * Load in the correct multicast list now the flags have changed.
2300 */
2302 dev_mc_upload(dev);
2304 /*
2305 * Have we downed the interface. We handle IFF_UP ourselves
2306 * according to user attempts to set it, rather than blindly
2307 * setting it.
2308 */
2310 ret = 0;
2311 if ((old_flags ^ flags) & IFF_UP) { /* Bit is different ? */
2312 ret = ((old_flags & IFF_UP) ? dev_close : dev_open)(dev);
2314 if (!ret)
2315 dev_mc_upload(dev);
2318 if (dev->flags & IFF_UP &&
2319 ((old_flags ^ dev->flags) &~ (IFF_UP | IFF_PROMISC | IFF_ALLMULTI |
2320 IFF_VOLATILE)))
2321 notifier_call_chain(&netdev_chain, NETDEV_CHANGE, dev);
2323 if ((flags ^ dev->gflags) & IFF_PROMISC) {
2324 int inc = (flags & IFF_PROMISC) ? +1 : -1;
2325 dev->gflags ^= IFF_PROMISC;
2326 dev_set_promiscuity(dev, inc);
2329 /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
2330 is important. Some (broken) drivers set IFF_PROMISC, when
2331 IFF_ALLMULTI is requested not asking us and not reporting.
2332 */
2333 if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
2334 int inc = (flags & IFF_ALLMULTI) ? +1 : -1;
2335 dev->gflags ^= IFF_ALLMULTI;
2336 dev_set_allmulti(dev, inc);
2339 if (old_flags ^ dev->flags)
2340 rtmsg_ifinfo(RTM_NEWLINK, dev, old_flags ^ dev->flags);
2342 return ret;
2345 int dev_set_mtu(struct net_device *dev, int new_mtu)
2347 int err;
2349 if (new_mtu == dev->mtu)
2350 return 0;
2352 /* MTU must be positive. */
2353 if (new_mtu < 0)
2354 return -EINVAL;
2356 if (!netif_device_present(dev))
2357 return -ENODEV;
2359 err = 0;
2360 if (dev->change_mtu)
2361 err = dev->change_mtu(dev, new_mtu);
2362 else
2363 dev->mtu = new_mtu;
2364 if (!err && dev->flags & IFF_UP)
2365 notifier_call_chain(&netdev_chain,
2366 NETDEV_CHANGEMTU, dev);
2367 return err;
2370 int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa)
2372 int err;
2374 if (!dev->set_mac_address)
2375 return -EOPNOTSUPP;
2376 if (sa->sa_family != dev->type)
2377 return -EINVAL;
2378 if (!netif_device_present(dev))
2379 return -ENODEV;
2380 err = dev->set_mac_address(dev, sa);
2381 if (!err)
2382 notifier_call_chain(&netdev_chain, NETDEV_CHANGEADDR, dev);
2383 return err;
2386 /*
2387 * Perform the SIOCxIFxxx calls.
2388 */
2389 static int dev_ifsioc(struct ifreq *ifr, unsigned int cmd)
2391 int err;
2392 struct net_device *dev = __dev_get_by_name(ifr->ifr_name);
2394 if (!dev)
2395 return -ENODEV;
2397 switch (cmd) {
2398 case SIOCGIFFLAGS: /* Get interface flags */
2399 ifr->ifr_flags = dev_get_flags(dev);
2400 return 0;
2402 case SIOCSIFFLAGS: /* Set interface flags */
2403 return dev_change_flags(dev, ifr->ifr_flags);
2405 case SIOCGIFMETRIC: /* Get the metric on the interface
2406 (currently unused) */
2407 ifr->ifr_metric = 0;
2408 return 0;
2410 case SIOCSIFMETRIC: /* Set the metric on the interface
2411 (currently unused) */
2412 return -EOPNOTSUPP;
2414 case SIOCGIFMTU: /* Get the MTU of a device */
2415 ifr->ifr_mtu = dev->mtu;
2416 return 0;
2418 case SIOCSIFMTU: /* Set the MTU of a device */
2419 return dev_set_mtu(dev, ifr->ifr_mtu);
2421 case SIOCGIFHWADDR:
2422 if (!dev->addr_len)
2423 memset(ifr->ifr_hwaddr.sa_data, 0, sizeof ifr->ifr_hwaddr.sa_data);
2424 else
2425 memcpy(ifr->ifr_hwaddr.sa_data, dev->dev_addr,
2426 min(sizeof ifr->ifr_hwaddr.sa_data, (size_t) dev->addr_len));
2427 ifr->ifr_hwaddr.sa_family = dev->type;
2428 return 0;
2430 case SIOCSIFHWADDR:
2431 return dev_set_mac_address(dev, &ifr->ifr_hwaddr);
2433 case SIOCSIFHWBROADCAST:
2434 if (ifr->ifr_hwaddr.sa_family != dev->type)
2435 return -EINVAL;
2436 memcpy(dev->broadcast, ifr->ifr_hwaddr.sa_data,
2437 min(sizeof ifr->ifr_hwaddr.sa_data, (size_t) dev->addr_len));
2438 notifier_call_chain(&netdev_chain,
2439 NETDEV_CHANGEADDR, dev);
2440 return 0;
2442 case SIOCGIFMAP:
2443 ifr->ifr_map.mem_start = dev->mem_start;
2444 ifr->ifr_map.mem_end = dev->mem_end;
2445 ifr->ifr_map.base_addr = dev->base_addr;
2446 ifr->ifr_map.irq = dev->irq;
2447 ifr->ifr_map.dma = dev->dma;
2448 ifr->ifr_map.port = dev->if_port;
2449 return 0;
2451 case SIOCSIFMAP:
2452 if (dev->set_config) {
2453 if (!netif_device_present(dev))
2454 return -ENODEV;
2455 return dev->set_config(dev, &ifr->ifr_map);
2457 return -EOPNOTSUPP;
2459 case SIOCADDMULTI:
2460 if (!dev->set_multicast_list ||
2461 ifr->ifr_hwaddr.sa_family != AF_UNSPEC)
2462 return -EINVAL;
2463 if (!netif_device_present(dev))
2464 return -ENODEV;
2465 return dev_mc_add(dev, ifr->ifr_hwaddr.sa_data,
2466 dev->addr_len, 1);
2468 case SIOCDELMULTI:
2469 if (!dev->set_multicast_list ||
2470 ifr->ifr_hwaddr.sa_family != AF_UNSPEC)
2471 return -EINVAL;
2472 if (!netif_device_present(dev))
2473 return -ENODEV;
2474 return dev_mc_delete(dev, ifr->ifr_hwaddr.sa_data,
2475 dev->addr_len, 1);
2477 case SIOCGIFINDEX:
2478 ifr->ifr_ifindex = dev->ifindex;
2479 return 0;
2481 case SIOCGIFTXQLEN:
2482 ifr->ifr_qlen = dev->tx_queue_len;
2483 return 0;
2485 case SIOCSIFTXQLEN:
2486 if (ifr->ifr_qlen < 0)
2487 return -EINVAL;
2488 dev->tx_queue_len = ifr->ifr_qlen;
2489 return 0;
2491 case SIOCSIFNAME:
2492 ifr->ifr_newname[IFNAMSIZ-1] = '\0';
2493 return dev_change_name(dev, ifr->ifr_newname);
2495 /*
2496 * Unknown or private ioctl
2497 */
2499 default:
2500 if ((cmd >= SIOCDEVPRIVATE &&
2501 cmd <= SIOCDEVPRIVATE + 15) ||
2502 cmd == SIOCBONDENSLAVE ||
2503 cmd == SIOCBONDRELEASE ||
2504 cmd == SIOCBONDSETHWADDR ||
2505 cmd == SIOCBONDSLAVEINFOQUERY ||
2506 cmd == SIOCBONDINFOQUERY ||
2507 cmd == SIOCBONDCHANGEACTIVE ||
2508 cmd == SIOCGMIIPHY ||
2509 cmd == SIOCGMIIREG ||
2510 cmd == SIOCSMIIREG ||
2511 cmd == SIOCBRADDIF ||
2512 cmd == SIOCBRDELIF ||
2513 cmd == SIOCWANDEV) {
2514 err = -EOPNOTSUPP;
2515 if (dev->do_ioctl) {
2516 if (netif_device_present(dev))
2517 err = dev->do_ioctl(dev, ifr,
2518 cmd);
2519 else
2520 err = -ENODEV;
2522 } else
2523 err = -EINVAL;
2526 return err;
2529 /*
2530 * This function handles all "interface"-type I/O control requests. The actual
2531 * 'doing' part of this is dev_ifsioc above.
2532 */
2534 /**
2535 * dev_ioctl - network device ioctl
2536 * @cmd: command to issue
2537 * @arg: pointer to a struct ifreq in user space
2539 * Issue ioctl functions to devices. This is normally called by the
2540 * user space syscall interfaces but can sometimes be useful for
2541 * other purposes. The return value is the return from the syscall if
2542 * positive or a negative errno code on error.
2543 */
2545 int dev_ioctl(unsigned int cmd, void __user *arg)
2547 struct ifreq ifr;
2548 int ret;
2549 char *colon;
2551 /* One special case: SIOCGIFCONF takes ifconf argument
2552 and requires shared lock, because it sleeps writing
2553 to user space.
2554 */
2556 if (cmd == SIOCGIFCONF) {
2557 rtnl_shlock();
2558 ret = dev_ifconf((char __user *) arg);
2559 rtnl_shunlock();
2560 return ret;
2562 if (cmd == SIOCGIFNAME)
2563 return dev_ifname((struct ifreq __user *)arg);
2565 if (copy_from_user(&ifr, arg, sizeof(struct ifreq)))
2566 return -EFAULT;
2568 ifr.ifr_name[IFNAMSIZ-1] = 0;
2570 colon = strchr(ifr.ifr_name, ':');
2571 if (colon)
2572 *colon = 0;
2574 /*
2575 * See which interface the caller is talking about.
2576 */
2578 switch (cmd) {
2579 /*
2580 * These ioctl calls:
2581 * - can be done by all.
2582 * - atomic and do not require locking.
2583 * - return a value
2584 */
2585 case SIOCGIFFLAGS:
2586 case SIOCGIFMETRIC:
2587 case SIOCGIFMTU:
2588 case SIOCGIFHWADDR:
2589 case SIOCGIFSLAVE:
2590 case SIOCGIFMAP:
2591 case SIOCGIFINDEX:
2592 case SIOCGIFTXQLEN:
2593 dev_load(ifr.ifr_name);
2594 read_lock(&dev_base_lock);
2595 ret = dev_ifsioc(&ifr, cmd);
2596 read_unlock(&dev_base_lock);
2597 if (!ret) {
2598 if (colon)
2599 *colon = ':';
2600 if (copy_to_user(arg, &ifr,
2601 sizeof(struct ifreq)))
2602 ret = -EFAULT;
2604 return ret;
2606 case SIOCETHTOOL:
2607 dev_load(ifr.ifr_name);
2608 rtnl_lock();
2609 ret = dev_ethtool(&ifr);
2610 rtnl_unlock();
2611 if (!ret) {
2612 if (colon)
2613 *colon = ':';
2614 if (copy_to_user(arg, &ifr,
2615 sizeof(struct ifreq)))
2616 ret = -EFAULT;
2618 return ret;
2620 /*
2621 * These ioctl calls:
2622 * - require superuser power.
2623 * - require strict serialization.
2624 * - return a value
2625 */
2626 case SIOCGMIIPHY:
2627 case SIOCGMIIREG:
2628 case SIOCSIFNAME:
2629 if (!capable(CAP_NET_ADMIN))
2630 return -EPERM;
2631 dev_load(ifr.ifr_name);
2632 rtnl_lock();
2633 ret = dev_ifsioc(&ifr, cmd);
2634 rtnl_unlock();
2635 if (!ret) {
2636 if (colon)
2637 *colon = ':';
2638 if (copy_to_user(arg, &ifr,
2639 sizeof(struct ifreq)))
2640 ret = -EFAULT;
2642 return ret;
2644 /*
2645 * These ioctl calls:
2646 * - require superuser power.
2647 * - require strict serialization.
2648 * - do not return a value
2649 */
2650 case SIOCSIFFLAGS:
2651 case SIOCSIFMETRIC:
2652 case SIOCSIFMTU:
2653 case SIOCSIFMAP:
2654 case SIOCSIFHWADDR:
2655 case SIOCSIFSLAVE:
2656 case SIOCADDMULTI:
2657 case SIOCDELMULTI:
2658 case SIOCSIFHWBROADCAST:
2659 case SIOCSIFTXQLEN:
2660 case SIOCSMIIREG:
2661 case SIOCBONDENSLAVE:
2662 case SIOCBONDRELEASE:
2663 case SIOCBONDSETHWADDR:
2664 case SIOCBONDSLAVEINFOQUERY:
2665 case SIOCBONDINFOQUERY:
2666 case SIOCBONDCHANGEACTIVE:
2667 case SIOCBRADDIF:
2668 case SIOCBRDELIF:
2669 if (!capable(CAP_NET_ADMIN))
2670 return -EPERM;
2671 dev_load(ifr.ifr_name);
2672 rtnl_lock();
2673 ret = dev_ifsioc(&ifr, cmd);
2674 rtnl_unlock();
2675 return ret;
2677 case SIOCGIFMEM:
2678 /* Get the per device memory space. We can add this but
2679 * currently do not support it */
2680 case SIOCSIFMEM:
2681 /* Set the per device memory buffer space.
2682 * Not applicable in our case */
2683 case SIOCSIFLINK:
2684 return -EINVAL;
2686 /*
2687 * Unknown or private ioctl.
2688 */
2689 default:
2690 if (cmd == SIOCWANDEV ||
2691 (cmd >= SIOCDEVPRIVATE &&
2692 cmd <= SIOCDEVPRIVATE + 15)) {
2693 dev_load(ifr.ifr_name);
2694 rtnl_lock();
2695 ret = dev_ifsioc(&ifr, cmd);
2696 rtnl_unlock();
2697 if (!ret && copy_to_user(arg, &ifr,
2698 sizeof(struct ifreq)))
2699 ret = -EFAULT;
2700 return ret;
2702 #ifdef WIRELESS_EXT
2703 /* Take care of Wireless Extensions */
2704 if (cmd >= SIOCIWFIRST && cmd <= SIOCIWLAST) {
2705 /* If command is `set a parameter', or
2706 * `get the encoding parameters', check if
2707 * the user has the right to do it */
2708 if (IW_IS_SET(cmd) || cmd == SIOCGIWENCODE) {
2709 if (!capable(CAP_NET_ADMIN))
2710 return -EPERM;
2712 dev_load(ifr.ifr_name);
2713 rtnl_lock();
2714 /* Follow me in net/core/wireless.c */
2715 ret = wireless_process_ioctl(&ifr, cmd);
2716 rtnl_unlock();
2717 if (IW_IS_GET(cmd) &&
2718 copy_to_user(arg, &ifr,
2719 sizeof(struct ifreq)))
2720 ret = -EFAULT;
2721 return ret;
2723 #endif /* WIRELESS_EXT */
2724 return -EINVAL;
2729 /**
2730 * dev_new_index - allocate an ifindex
2732 * Returns a suitable unique value for a new device interface
2733 * number. The caller must hold the rtnl semaphore or the
2734 * dev_base_lock to be sure it remains unique.
2735 */
2736 static int dev_new_index(void)
2738 static int ifindex;
2739 for (;;) {
2740 if (++ifindex <= 0)
2741 ifindex = 1;
2742 if (!__dev_get_by_index(ifindex))
2743 return ifindex;
2747 static int dev_boot_phase = 1;
2749 /* Delayed registration/unregisteration */
2750 static DEFINE_SPINLOCK(net_todo_list_lock);
2751 static struct list_head net_todo_list = LIST_HEAD_INIT(net_todo_list);
2753 static inline void net_set_todo(struct net_device *dev)
2755 spin_lock(&net_todo_list_lock);
2756 list_add_tail(&dev->todo_list, &net_todo_list);
2757 spin_unlock(&net_todo_list_lock);
2760 /**
2761 * register_netdevice - register a network device
2762 * @dev: device to register
2764 * Take a completed network device structure and add it to the kernel
2765 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
2766 * chain. 0 is returned on success. A negative errno code is returned
2767 * on a failure to set up the device, or if the name is a duplicate.
2769 * Callers must hold the rtnl semaphore. You may want
2770 * register_netdev() instead of this.
2772 * BUGS:
2773 * The locking appears insufficient to guarantee two parallel registers
2774 * will not get the same name.
2775 */
2777 int register_netdevice(struct net_device *dev)
2779 struct hlist_head *head;
2780 struct hlist_node *p;
2781 int ret;
2783 BUG_ON(dev_boot_phase);
2784 ASSERT_RTNL();
2786 /* When net_device's are persistent, this will be fatal. */
2787 BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
2789 spin_lock_init(&dev->queue_lock);
2790 spin_lock_init(&dev->xmit_lock);
2791 dev->xmit_lock_owner = -1;
2792 #ifdef CONFIG_NET_CLS_ACT
2793 spin_lock_init(&dev->ingress_lock);
2794 #endif
2796 ret = alloc_divert_blk(dev);
2797 if (ret)
2798 goto out;
2800 dev->iflink = -1;
2802 /* Init, if this function is available */
2803 if (dev->init) {
2804 ret = dev->init(dev);
2805 if (ret) {
2806 if (ret > 0)
2807 ret = -EIO;
2808 goto out_err;
2812 if (!dev_valid_name(dev->name)) {
2813 ret = -EINVAL;
2814 goto out_err;
2817 dev->ifindex = dev_new_index();
2818 if (dev->iflink == -1)
2819 dev->iflink = dev->ifindex;
2821 /* Check for existence of name */
2822 head = dev_name_hash(dev->name);
2823 hlist_for_each(p, head) {
2824 struct net_device *d
2825 = hlist_entry(p, struct net_device, name_hlist);
2826 if (!strncmp(d->name, dev->name, IFNAMSIZ)) {
2827 ret = -EEXIST;
2828 goto out_err;
2832 /* Fix illegal SG+CSUM combinations. */
2833 if ((dev->features & NETIF_F_SG) &&
2834 !(dev->features & (NETIF_F_IP_CSUM |
2835 NETIF_F_NO_CSUM |
2836 NETIF_F_HW_CSUM))) {
2837 printk("%s: Dropping NETIF_F_SG since no checksum feature.\n",
2838 dev->name);
2839 dev->features &= ~NETIF_F_SG;
2842 /* TSO requires that SG is present as well. */
2843 if ((dev->features & NETIF_F_TSO) &&
2844 !(dev->features & NETIF_F_SG)) {
2845 printk("%s: Dropping NETIF_F_TSO since no SG feature.\n",
2846 dev->name);
2847 dev->features &= ~NETIF_F_TSO;
2850 /*
2851 * nil rebuild_header routine,
2852 * that should be never called and used as just bug trap.
2853 */
2855 if (!dev->rebuild_header)
2856 dev->rebuild_header = default_rebuild_header;
2858 /*
2859 * Default initial state at registry is that the
2860 * device is present.
2861 */
2863 set_bit(__LINK_STATE_PRESENT, &dev->state);
2865 dev->next = NULL;
2866 dev_init_scheduler(dev);
2867 write_lock_bh(&dev_base_lock);
2868 *dev_tail = dev;
2869 dev_tail = &dev->next;
2870 hlist_add_head(&dev->name_hlist, head);
2871 hlist_add_head(&dev->index_hlist, dev_index_hash(dev->ifindex));
2872 dev_hold(dev);
2873 dev->reg_state = NETREG_REGISTERING;
2874 write_unlock_bh(&dev_base_lock);
2876 /* Notify protocols, that a new device appeared. */
2877 notifier_call_chain(&netdev_chain, NETDEV_REGISTER, dev);
2879 /* Finish registration after unlock */
2880 net_set_todo(dev);
2881 ret = 0;
2883 out:
2884 return ret;
2885 out_err:
2886 free_divert_blk(dev);
2887 goto out;
2890 /**
2891 * register_netdev - register a network device
2892 * @dev: device to register
2894 * Take a completed network device structure and add it to the kernel
2895 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
2896 * chain. 0 is returned on success. A negative errno code is returned
2897 * on a failure to set up the device, or if the name is a duplicate.
2899 * This is a wrapper around register_netdev that takes the rtnl semaphore
2900 * and expands the device name if you passed a format string to
2901 * alloc_netdev.
2902 */
2903 int register_netdev(struct net_device *dev)
2905 int err;
2907 rtnl_lock();
2909 /*
2910 * If the name is a format string the caller wants us to do a
2911 * name allocation.
2912 */
2913 if (strchr(dev->name, '%')) {
2914 err = dev_alloc_name(dev, dev->name);
2915 if (err < 0)
2916 goto out;
2919 /*
2920 * Back compatibility hook. Kill this one in 2.5
2921 */
2922 if (dev->name[0] == 0 || dev->name[0] == ' ') {
2923 err = dev_alloc_name(dev, "eth%d");
2924 if (err < 0)
2925 goto out;
2928 err = register_netdevice(dev);
2929 out:
2930 rtnl_unlock();
2931 return err;
2933 EXPORT_SYMBOL(register_netdev);
2935 /*
2936 * netdev_wait_allrefs - wait until all references are gone.
2938 * This is called when unregistering network devices.
2940 * Any protocol or device that holds a reference should register
2941 * for netdevice notification, and cleanup and put back the
2942 * reference if they receive an UNREGISTER event.
2943 * We can get stuck here if buggy protocols don't correctly
2944 * call dev_put.
2945 */
2946 static void netdev_wait_allrefs(struct net_device *dev)
2948 unsigned long rebroadcast_time, warning_time;
2950 rebroadcast_time = warning_time = jiffies;
2951 while (atomic_read(&dev->refcnt) != 0) {
2952 if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
2953 rtnl_shlock();
2955 /* Rebroadcast unregister notification */
2956 notifier_call_chain(&netdev_chain,
2957 NETDEV_UNREGISTER, dev);
2959 if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
2960 &dev->state)) {
2961 /* We must not have linkwatch events
2962 * pending on unregister. If this
2963 * happens, we simply run the queue
2964 * unscheduled, resulting in a noop
2965 * for this device.
2966 */
2967 linkwatch_run_queue();
2970 rtnl_shunlock();
2972 rebroadcast_time = jiffies;
2975 msleep(250);
2977 if (time_after(jiffies, warning_time + 10 * HZ)) {
2978 printk(KERN_EMERG "unregister_netdevice: "
2979 "waiting for %s to become free. Usage "
2980 "count = %d\n",
2981 dev->name, atomic_read(&dev->refcnt));
2982 warning_time = jiffies;
2987 /* The sequence is:
2989 * rtnl_lock();
2990 * ...
2991 * register_netdevice(x1);
2992 * register_netdevice(x2);
2993 * ...
2994 * unregister_netdevice(y1);
2995 * unregister_netdevice(y2);
2996 * ...
2997 * rtnl_unlock();
2998 * free_netdev(y1);
2999 * free_netdev(y2);
3001 * We are invoked by rtnl_unlock() after it drops the semaphore.
3002 * This allows us to deal with problems:
3003 * 1) We can create/delete sysfs objects which invoke hotplug
3004 * without deadlocking with linkwatch via keventd.
3005 * 2) Since we run with the RTNL semaphore not held, we can sleep
3006 * safely in order to wait for the netdev refcnt to drop to zero.
3007 */
3008 static DECLARE_MUTEX(net_todo_run_mutex);
3009 void netdev_run_todo(void)
3011 struct list_head list = LIST_HEAD_INIT(list);
3012 int err;
3015 /* Need to guard against multiple cpu's getting out of order. */
3016 down(&net_todo_run_mutex);
3018 /* Not safe to do outside the semaphore. We must not return
3019 * until all unregister events invoked by the local processor
3020 * have been completed (either by this todo run, or one on
3021 * another cpu).
3022 */
3023 if (list_empty(&net_todo_list))
3024 goto out;
3026 /* Snapshot list, allow later requests */
3027 spin_lock(&net_todo_list_lock);
3028 list_splice_init(&net_todo_list, &list);
3029 spin_unlock(&net_todo_list_lock);
3031 while (!list_empty(&list)) {
3032 struct net_device *dev
3033 = list_entry(list.next, struct net_device, todo_list);
3034 list_del(&dev->todo_list);
3036 switch(dev->reg_state) {
3037 case NETREG_REGISTERING:
3038 err = netdev_register_sysfs(dev);
3039 if (err)
3040 printk(KERN_ERR "%s: failed sysfs registration (%d)\n",
3041 dev->name, err);
3042 dev->reg_state = NETREG_REGISTERED;
3043 break;
3045 case NETREG_UNREGISTERING:
3046 netdev_unregister_sysfs(dev);
3047 dev->reg_state = NETREG_UNREGISTERED;
3049 netdev_wait_allrefs(dev);
3051 /* paranoia */
3052 BUG_ON(atomic_read(&dev->refcnt));
3053 BUG_TRAP(!dev->ip_ptr);
3054 BUG_TRAP(!dev->ip6_ptr);
3055 BUG_TRAP(!dev->dn_ptr);
3058 /* It must be the very last action,
3059 * after this 'dev' may point to freed up memory.
3060 */
3061 if (dev->destructor)
3062 dev->destructor(dev);
3063 break;
3065 default:
3066 printk(KERN_ERR "network todo '%s' but state %d\n",
3067 dev->name, dev->reg_state);
3068 break;
3072 out:
3073 up(&net_todo_run_mutex);
3076 /**
3077 * alloc_netdev - allocate network device
3078 * @sizeof_priv: size of private data to allocate space for
3079 * @name: device name format string
3080 * @setup: callback to initialize device
3082 * Allocates a struct net_device with private data area for driver use
3083 * and performs basic initialization.
3084 */
3085 struct net_device *alloc_netdev(int sizeof_priv, const char *name,
3086 void (*setup)(struct net_device *))
3088 void *p;
3089 struct net_device *dev;
3090 int alloc_size;
3092 /* ensure 32-byte alignment of both the device and private area */
3093 alloc_size = (sizeof(*dev) + NETDEV_ALIGN_CONST) & ~NETDEV_ALIGN_CONST;
3094 alloc_size += sizeof_priv + NETDEV_ALIGN_CONST;
3096 p = kmalloc(alloc_size, GFP_KERNEL);
3097 if (!p) {
3098 printk(KERN_ERR "alloc_dev: Unable to allocate device.\n");
3099 return NULL;
3101 memset(p, 0, alloc_size);
3103 dev = (struct net_device *)
3104 (((long)p + NETDEV_ALIGN_CONST) & ~NETDEV_ALIGN_CONST);
3105 dev->padded = (char *)dev - (char *)p;
3107 if (sizeof_priv)
3108 dev->priv = netdev_priv(dev);
3110 setup(dev);
3111 strcpy(dev->name, name);
3112 return dev;
3114 EXPORT_SYMBOL(alloc_netdev);
3116 /**
3117 * free_netdev - free network device
3118 * @dev: device
3120 * This function does the last stage of destroying an allocated device
3121 * interface. The reference to the device object is released.
3122 * If this is the last reference then it will be freed.
3123 */
3124 void free_netdev(struct net_device *dev)
3126 #ifdef CONFIG_SYSFS
3127 /* Compatiablity with error handling in drivers */
3128 if (dev->reg_state == NETREG_UNINITIALIZED) {
3129 kfree((char *)dev - dev->padded);
3130 return;
3133 BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
3134 dev->reg_state = NETREG_RELEASED;
3136 /* will free via class release */
3137 class_device_put(&dev->class_dev);
3138 #else
3139 kfree((char *)dev - dev->padded);
3140 #endif
3143 /* Synchronize with packet receive processing. */
3144 void synchronize_net(void)
3146 might_sleep();
3147 synchronize_rcu();
3150 /**
3151 * unregister_netdevice - remove device from the kernel
3152 * @dev: device
3154 * This function shuts down a device interface and removes it
3155 * from the kernel tables. On success 0 is returned, on a failure
3156 * a negative errno code is returned.
3158 * Callers must hold the rtnl semaphore. You may want
3159 * unregister_netdev() instead of this.
3160 */
3162 int unregister_netdevice(struct net_device *dev)
3164 struct net_device *d, **dp;
3166 BUG_ON(dev_boot_phase);
3167 ASSERT_RTNL();
3169 /* Some devices call without registering for initialization unwind. */
3170 if (dev->reg_state == NETREG_UNINITIALIZED) {
3171 printk(KERN_DEBUG "unregister_netdevice: device %s/%p never "
3172 "was registered\n", dev->name, dev);
3173 return -ENODEV;
3176 BUG_ON(dev->reg_state != NETREG_REGISTERED);
3178 /* If device is running, close it first. */
3179 if (dev->flags & IFF_UP)
3180 dev_close(dev);
3182 /* And unlink it from device chain. */
3183 for (dp = &dev_base; (d = *dp) != NULL; dp = &d->next) {
3184 if (d == dev) {
3185 write_lock_bh(&dev_base_lock);
3186 hlist_del(&dev->name_hlist);
3187 hlist_del(&dev->index_hlist);
3188 if (dev_tail == &dev->next)
3189 dev_tail = dp;
3190 *dp = d->next;
3191 write_unlock_bh(&dev_base_lock);
3192 break;
3195 if (!d) {
3196 printk(KERN_ERR "unregister net_device: '%s' not found\n",
3197 dev->name);
3198 return -ENODEV;
3201 dev->reg_state = NETREG_UNREGISTERING;
3203 synchronize_net();
3205 /* Shutdown queueing discipline. */
3206 dev_shutdown(dev);
3209 /* Notify protocols, that we are about to destroy
3210 this device. They should clean all the things.
3211 */
3212 notifier_call_chain(&netdev_chain, NETDEV_UNREGISTER, dev);
3214 /*
3215 * Flush the multicast chain
3216 */
3217 dev_mc_discard(dev);
3219 if (dev->uninit)
3220 dev->uninit(dev);
3222 /* Notifier chain MUST detach us from master device. */
3223 BUG_TRAP(!dev->master);
3225 free_divert_blk(dev);
3227 /* Finish processing unregister after unlock */
3228 net_set_todo(dev);
3230 synchronize_net();
3232 dev_put(dev);
3233 return 0;
3236 /**
3237 * unregister_netdev - remove device from the kernel
3238 * @dev: device
3240 * This function shuts down a device interface and removes it
3241 * from the kernel tables. On success 0 is returned, on a failure
3242 * a negative errno code is returned.
3244 * This is just a wrapper for unregister_netdevice that takes
3245 * the rtnl semaphore. In general you want to use this and not
3246 * unregister_netdevice.
3247 */
3248 void unregister_netdev(struct net_device *dev)
3250 rtnl_lock();
3251 unregister_netdevice(dev);
3252 rtnl_unlock();
3255 EXPORT_SYMBOL(unregister_netdev);
3257 #ifdef CONFIG_HOTPLUG_CPU
3258 static int dev_cpu_callback(struct notifier_block *nfb,
3259 unsigned long action,
3260 void *ocpu)
3262 struct sk_buff **list_skb;
3263 struct net_device **list_net;
3264 struct sk_buff *skb;
3265 unsigned int cpu, oldcpu = (unsigned long)ocpu;
3266 struct softnet_data *sd, *oldsd;
3268 if (action != CPU_DEAD)
3269 return NOTIFY_OK;
3271 local_irq_disable();
3272 cpu = smp_processor_id();
3273 sd = &per_cpu(softnet_data, cpu);
3274 oldsd = &per_cpu(softnet_data, oldcpu);
3276 /* Find end of our completion_queue. */
3277 list_skb = &sd->completion_queue;
3278 while (*list_skb)
3279 list_skb = &(*list_skb)->next;
3280 /* Append completion queue from offline CPU. */
3281 *list_skb = oldsd->completion_queue;
3282 oldsd->completion_queue = NULL;
3284 /* Find end of our output_queue. */
3285 list_net = &sd->output_queue;
3286 while (*list_net)
3287 list_net = &(*list_net)->next_sched;
3288 /* Append output queue from offline CPU. */
3289 *list_net = oldsd->output_queue;
3290 oldsd->output_queue = NULL;
3292 raise_softirq_irqoff(NET_TX_SOFTIRQ);
3293 local_irq_enable();
3295 /* Process offline CPU's input_pkt_queue */
3296 while ((skb = __skb_dequeue(&oldsd->input_pkt_queue)))
3297 netif_rx(skb);
3299 return NOTIFY_OK;
3301 #endif /* CONFIG_HOTPLUG_CPU */
3304 /*
3305 * Initialize the DEV module. At boot time this walks the device list and
3306 * unhooks any devices that fail to initialise (normally hardware not
3307 * present) and leaves us with a valid list of present and active devices.
3309 */
3311 /*
3312 * This is called single threaded during boot, so no need
3313 * to take the rtnl semaphore.
3314 */
3315 static int __init net_dev_init(void)
3317 int i, rc = -ENOMEM;
3319 BUG_ON(!dev_boot_phase);
3321 net_random_init();
3323 if (dev_proc_init())
3324 goto out;
3326 if (netdev_sysfs_init())
3327 goto out;
3329 INIT_LIST_HEAD(&ptype_all);
3330 for (i = 0; i < 16; i++)
3331 INIT_LIST_HEAD(&ptype_base[i]);
3333 for (i = 0; i < ARRAY_SIZE(dev_name_head); i++)
3334 INIT_HLIST_HEAD(&dev_name_head[i]);
3336 for (i = 0; i < ARRAY_SIZE(dev_index_head); i++)
3337 INIT_HLIST_HEAD(&dev_index_head[i]);
3339 /*
3340 * Initialise the packet receive queues.
3341 */
3343 for (i = 0; i < NR_CPUS; i++) {
3344 struct softnet_data *queue;
3346 queue = &per_cpu(softnet_data, i);
3347 skb_queue_head_init(&queue->input_pkt_queue);
3348 queue->throttle = 0;
3349 queue->cng_level = 0;
3350 queue->avg_blog = 10; /* arbitrary non-zero */
3351 queue->completion_queue = NULL;
3352 INIT_LIST_HEAD(&queue->poll_list);
3353 set_bit(__LINK_STATE_START, &queue->backlog_dev.state);
3354 queue->backlog_dev.weight = weight_p;
3355 queue->backlog_dev.poll = process_backlog;
3356 atomic_set(&queue->backlog_dev.refcnt, 1);
3359 #ifdef OFFLINE_SAMPLE
3360 samp_timer.expires = jiffies + (10 * HZ);
3361 add_timer(&samp_timer);
3362 #endif
3364 dev_boot_phase = 0;
3366 open_softirq(NET_TX_SOFTIRQ, net_tx_action, NULL);
3367 open_softirq(NET_RX_SOFTIRQ, net_rx_action, NULL);
3369 hotcpu_notifier(dev_cpu_callback, 0);
3370 dst_init();
3371 dev_mcast_init();
3372 rc = 0;
3373 out:
3374 return rc;
3377 subsys_initcall(net_dev_init);
3379 EXPORT_SYMBOL(__dev_get_by_index);
3380 EXPORT_SYMBOL(__dev_get_by_name);
3381 EXPORT_SYMBOL(__dev_remove_pack);
3382 EXPORT_SYMBOL(__skb_linearize);
3383 EXPORT_SYMBOL(dev_add_pack);
3384 EXPORT_SYMBOL(dev_alloc_name);
3385 EXPORT_SYMBOL(dev_close);
3386 EXPORT_SYMBOL(dev_get_by_flags);
3387 EXPORT_SYMBOL(dev_get_by_index);
3388 EXPORT_SYMBOL(dev_get_by_name);
3389 EXPORT_SYMBOL(dev_ioctl);
3390 EXPORT_SYMBOL(dev_open);
3391 EXPORT_SYMBOL(dev_queue_xmit);
3392 EXPORT_SYMBOL(dev_remove_pack);
3393 EXPORT_SYMBOL(dev_set_allmulti);
3394 EXPORT_SYMBOL(dev_set_promiscuity);
3395 EXPORT_SYMBOL(dev_change_flags);
3396 EXPORT_SYMBOL(dev_set_mtu);
3397 EXPORT_SYMBOL(dev_set_mac_address);
3398 EXPORT_SYMBOL(free_netdev);
3399 EXPORT_SYMBOL(netdev_boot_setup_check);
3400 EXPORT_SYMBOL(netdev_set_master);
3401 EXPORT_SYMBOL(netdev_state_change);
3402 EXPORT_SYMBOL(netif_receive_skb);
3403 EXPORT_SYMBOL(netif_rx);
3404 EXPORT_SYMBOL(register_gifconf);
3405 EXPORT_SYMBOL(register_netdevice);
3406 EXPORT_SYMBOL(register_netdevice_notifier);
3407 EXPORT_SYMBOL(skb_checksum_help);
3408 EXPORT_SYMBOL(synchronize_net);
3409 EXPORT_SYMBOL(unregister_netdevice);
3410 EXPORT_SYMBOL(unregister_netdevice_notifier);
3411 EXPORT_SYMBOL(net_enable_timestamp);
3412 EXPORT_SYMBOL(net_disable_timestamp);
3413 EXPORT_SYMBOL(dev_get_flags);
3415 #if defined(CONFIG_BRIDGE) || defined(CONFIG_BRIDGE_MODULE)
3416 EXPORT_SYMBOL(br_handle_frame_hook);
3417 EXPORT_SYMBOL(br_fdb_get_hook);
3418 EXPORT_SYMBOL(br_fdb_put_hook);
3419 #endif
3421 #ifdef CONFIG_KMOD
3422 EXPORT_SYMBOL(dev_load);
3423 #endif
3425 EXPORT_PER_CPU_SYMBOL(softnet_data);