]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/net/wireless/orinoco.c
[PATCH] orinoco: scanning support
[karo-tx-linux.git] / drivers / net / wireless / orinoco.c
1 /* orinoco.c - (formerly known as dldwd_cs.c and orinoco_cs.c)
2  *
3  * A driver for Hermes or Prism 2 chipset based PCMCIA wireless
4  * adaptors, with Lucent/Agere, Intersil or Symbol firmware.
5  *
6  * Current maintainers (as of 29 September 2003) are:
7  *      Pavel Roskin <proski AT gnu.org>
8  * and  David Gibson <hermes AT gibson.dropbear.id.au>
9  *
10  * (C) Copyright David Gibson, IBM Corporation 2001-2003.
11  * Copyright (C) 2000 David Gibson, Linuxcare Australia.
12  *      With some help from :
13  * Copyright (C) 2001 Jean Tourrilhes, HP Labs
14  * Copyright (C) 2001 Benjamin Herrenschmidt
15  *
16  * Based on dummy_cs.c 1.27 2000/06/12 21:27:25
17  *
18  * Portions based on wvlan_cs.c 1.0.6, Copyright Andreas Neuhaus <andy
19  * AT fasta.fh-dortmund.de>
20  *      http://www.stud.fh-dortmund.de/~andy/wvlan/
21  *
22  * The contents of this file are subject to the Mozilla Public License
23  * Version 1.1 (the "License"); you may not use this file except in
24  * compliance with the License. You may obtain a copy of the License
25  * at http://www.mozilla.org/MPL/
26  *
27  * Software distributed under the License is distributed on an "AS IS"
28  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
29  * the License for the specific language governing rights and
30  * limitations under the License.
31  *
32  * The initial developer of the original code is David A. Hinds
33  * <dahinds AT users.sourceforge.net>.  Portions created by David
34  * A. Hinds are Copyright (C) 1999 David A. Hinds.  All Rights
35  * Reserved.
36  *
37  * Alternatively, the contents of this file may be used under the
38  * terms of the GNU General Public License version 2 (the "GPL"), in
39  * which case the provisions of the GPL are applicable instead of the
40  * above.  If you wish to allow the use of your version of this file
41  * only under the terms of the GPL and not to allow others to use your
42  * version of this file under the MPL, indicate your decision by
43  * deleting the provisions above and replace them with the notice and
44  * other provisions required by the GPL.  If you do not delete the
45  * provisions above, a recipient may use your version of this file
46  * under either the MPL or the GPL.  */
47
48 /*
49  * v0.01 -> v0.02 - 21/3/2001 - Jean II
50  *      o Allow to use regular ethX device name instead of dldwdX
51  *      o Warning on IBSS with ESSID=any for firmware 6.06
52  *      o Put proper range.throughput values (optimistic)
53  *      o IWSPY support (IOCTL and stat gather in Rx path)
54  *      o Allow setting frequency in Ad-Hoc mode
55  *      o Disable WEP setting if !has_wep to work on old firmware
56  *      o Fix txpower range
57  *      o Start adding support for Samsung/Compaq firmware
58  *
59  * v0.02 -> v0.03 - 23/3/2001 - Jean II
60  *      o Start adding Symbol support - need to check all that
61  *      o Fix Prism2/Symbol WEP to accept 128 bits keys
62  *      o Add Symbol WEP (add authentication type)
63  *      o Add Prism2/Symbol rate
64  *      o Add PM timeout (holdover duration)
65  *      o Enable "iwconfig eth0 key off" and friends (toggle flags)
66  *      o Enable "iwconfig eth0 power unicast/all" (toggle flags)
67  *      o Try with an Intel card. It report firmware 1.01, behave like
68  *        an antiquated firmware, however on windows it says 2.00. Yuck !
69  *      o Workaround firmware bug in allocate buffer (Intel 1.01)
70  *      o Finish external renaming to orinoco...
71  *      o Testing with various Wavelan firmwares
72  *
73  * v0.03 -> v0.04 - 30/3/2001 - Jean II
74  *      o Update to Wireless 11 -> add retry limit/lifetime support
75  *      o Tested with a D-Link DWL 650 card, fill in firmware support
76  *      o Warning on Vcc mismatch (D-Link 3.3v card in Lucent 5v only slot)
77  *      o Fixed the Prism2 WEP bugs that I introduced in v0.03 :-(
78  *        It works on D-Link *only* after a tcpdump. Weird...
79  *        And still doesn't work on Intel card. Grrrr...
80  *      o Update the mode after a setport3
81  *      o Add preamble setting for Symbol cards (not yet enabled)
82  *      o Don't complain as much about Symbol cards...
83  *
84  * v0.04 -> v0.04b - 22/4/2001 - David Gibson
85  *      o Removed the 'eth' parameter - always use ethXX as the
86  *        interface name instead of dldwdXX.  The other was racy
87  *        anyway.
88  *      o Clean up RID definitions in hermes.h, other cleanups
89  *
90  * v0.04b -> v0.04c - 24/4/2001 - Jean II
91  *      o Tim Hurley <timster AT seiki.bliztech.com> reported a D-Link card
92  *        with vendor 02 and firmware 0.08. Added in the capabilities...
93  *      o Tested Lucent firmware 7.28, everything works...
94  *
95  * v0.04c -> v0.05 - 3/5/2001 - Benjamin Herrenschmidt
96  *      o Spin-off Pcmcia code. This file is renamed orinoco.c,
97  *        and orinoco_cs.c now contains only the Pcmcia specific stuff
98  *      o Add Airport driver support on top of orinoco.c (see airport.c)
99  *
100  * v0.05 -> v0.05a - 4/5/2001 - Jean II
101  *      o Revert to old Pcmcia code to fix breakage of Ben's changes...
102  *
103  * v0.05a -> v0.05b - 4/5/2001 - Jean II
104  *      o add module parameter 'ignore_cis_vcc' for D-Link @ 5V
105  *      o D-Link firmware doesn't support multicast. We just print a few
106  *        error messages, but otherwise everything works...
107  *      o For David : set/getport3 works fine, just upgrade iwpriv...
108  *
109  * v0.05b -> v0.05c - 5/5/2001 - Benjamin Herrenschmidt
110  *      o Adapt airport.c to latest changes in orinoco.c
111  *      o Remove deferred power enabling code
112  *
113  * v0.05c -> v0.05d - 5/5/2001 - Jean II
114  *      o Workaround to SNAP decapsulate frame from Linksys AP
115  *        original patch from : Dong Liu <dliu AT research.bell-labs.com>
116  *        (note : the memcmp bug was mine - fixed)
117  *      o Remove set_retry stuff, no firmware support it (bloat--).
118  *
119  * v0.05d -> v0.06 - 25/5/2001 - Jean II
120  *              Original patch from "Hong Lin" <alin AT redhat.com>,
121  *              "Ian Kinner" <ikinner AT redhat.com>
122  *              and "David Smith" <dsmith AT redhat.com>
123  *      o Init of priv->tx_rate_ctrl in firmware specific section.
124  *      o Prism2/Symbol rate, upto should be 0xF and not 0x15. Doh !
125  *      o Spectrum card always need cor_reset (for every reset)
126  *      o Fix cor_reset to not lose bit 7 in the register
127  *      o flush_stale_links to remove zombie Pcmcia instances
128  *      o Ack previous hermes event before reset
129  *              Me (with my little hands)
130  *      o Allow orinoco.c to call cor_reset via priv->card_reset_handler
131  *      o Add priv->need_card_reset to toggle this feature
132  *      o Fix various buglets when setting WEP in Symbol firmware
133  *        Now, encryption is fully functional on Symbol cards. Youpi !
134  *
135  * v0.06 -> v0.06b - 25/5/2001 - Jean II
136  *      o IBSS on Symbol use port_mode = 4. Please don't ask...
137  *
138  * v0.06b -> v0.06c - 29/5/2001 - Jean II
139  *      o Show first spy address in /proc/net/wireless for IBSS mode as well
140  *
141  * v0.06c -> v0.06d - 6/7/2001 - David Gibson
142  *      o Change a bunch of KERN_INFO messages to KERN_DEBUG, as per Linus'
143  *        wishes to reduce the number of unnecessary messages.
144  *      o Removed bogus message on CRC error.
145  *      o Merged fixes for v0.08 Prism 2 firmware from William Waghorn
146  *        <willwaghorn AT yahoo.co.uk>
147  *      o Slight cleanup/re-arrangement of firmware detection code.
148  *
149  * v0.06d -> v0.06e - 1/8/2001 - David Gibson
150  *      o Removed some redundant global initializers (orinoco_cs.c).
151  *      o Added some module metadata
152  *
153  * v0.06e -> v0.06f - 14/8/2001 - David Gibson
154  *      o Wording fix to license
155  *      o Added a 'use_alternate_encaps' module parameter for APs which need an
156  *        oui of 00:00:00.  We really need a better way of handling this, but
157  *        the module flag is better than nothing for now.
158  *
159  * v0.06f -> v0.07 - 20/8/2001 - David Gibson
160  *      o Removed BAP error retries from hermes_bap_seek().  For Tx we now
161  *        let the upper layers handle the retry, we retry explicitly in the
162  *        Rx path, but don't make as much noise about it.
163  *      o Firmware detection cleanups.
164  *
165  * v0.07 -> v0.07a - 1/10/3001 - Jean II
166  *      o Add code to read Symbol firmware revision, inspired by latest code
167  *        in Spectrum24 by Lee John Keyser-Allen - Thanks Lee !
168  *      o Thanks to Jared Valentine <hidden AT xmission.com> for "providing" me
169  *        a 3Com card with a recent firmware, fill out Symbol firmware
170  *        capabilities of latest rev (2.20), as well as older Symbol cards.
171  *      o Disable Power Management in newer Symbol firmware, the API 
172  *        has changed (documentation needed).
173  *
174  * v0.07a -> v0.08 - 3/10/2001 - David Gibson
175  *      o Fixed a possible buffer overrun found by the Stanford checker (in
176  *        dldwd_ioctl_setiwencode()).  Can only be called by root anyway, so not
177  *        a big problem.
178  *      o Turned has_big_wep on for Intersil cards.  That's not true for all of
179  *        them but we should at least let the capable ones try.
180  *      o Wait for BUSY to clear at the beginning of hermes_bap_seek().  I
181  *        realized that my assumption that the driver's serialization
182  *        would prevent the BAP being busy on entry was possibly false, because
183  *        things other than seeks may make the BAP busy.
184  *      o Use "alternate" (oui 00:00:00) encapsulation by default.
185  *        Setting use_old_encaps will mimic the old behaviour, but I think we
186  *        will be able to eliminate this.
187  *      o Don't try to make __initdata const (the version string).  This can't
188  *        work because of the way the __initdata sectioning works.
189  *      o Added MODULE_LICENSE tags.
190  *      o Support for PLX (transparent PCMCIA->PCI bridge) cards.
191  *      o Changed to using the new type-fascist min/max.
192  *
193  * v0.08 -> v0.08a - 9/10/2001 - David Gibson
194  *      o Inserted some missing acknowledgements/info into the Changelog.
195  *      o Fixed some bugs in the normalization of signal level reporting.
196  *      o Fixed bad bug in WEP key handling on Intersil and Symbol firmware,
197  *        which led to an instant crash on big-endian machines.
198  *
199  * v0.08a -> v0.08b - 20/11/2001 - David Gibson
200  *      o Lots of cleanup and bugfixes in orinoco_plx.c
201  *      o Cleanup to handling of Tx rate setting.
202  *      o Removed support for old encapsulation method.
203  *      o Removed old "dldwd" names.
204  *      o Split RID constants into a new file hermes_rid.h
205  *      o Renamed RID constants to match linux-wlan-ng and prism2.o
206  *      o Bugfixes in hermes.c
207  *      o Poke the PLX's INTCSR register, so it actually starts
208  *        generating interrupts.  These cards might actually work now.
209  *      o Update to wireless extensions v12 (Jean II)
210  *      o Support for tallies and inquire command (Jean II)
211  *      o Airport updates for newer PPC kernels (BenH)
212  *
213  * v0.08b -> v0.09 - 21/12/2001 - David Gibson
214  *      o Some new PCI IDs for PLX cards.
215  *      o Removed broken attempt to do ALLMULTI reception.  Just use
216  *        promiscuous mode instead
217  *      o Preliminary work for list-AP (Jean II)
218  *      o Airport updates from (BenH)
219  *      o Eliminated racy hw_ready stuff
220  *      o Fixed generation of fake events in irq handler.  This should
221  *        finally kill the EIO problems (Jean II & dgibson)
222  *      o Fixed breakage of bitrate set/get on Agere firmware (Jean II)
223  *
224  * v0.09 -> v0.09a - 2/1/2002 - David Gibson
225  *      o Fixed stupid mistake in multicast list handling, triggering
226  *        a BUG()
227  *
228  * v0.09a -> v0.09b - 16/1/2002 - David Gibson
229  *      o Fixed even stupider mistake in new interrupt handling, which
230  *        seriously broke things on big-endian machines.
231  *      o Removed a bunch of redundant includes and exports.
232  *      o Removed a redundant MOD_{INC,DEC}_USE_COUNT pair in airport.c
233  *      o Don't attempt to do hardware level multicast reception on
234  *        Intersil firmware, just go promisc instead.
235  *      o Typo fixed in hermes_issue_cmd()
236  *      o Eliminated WIRELESS_SPY #ifdefs
237  *      o Status code reported on Tx exceptions
238  *      o Moved netif_wake_queue() from ALLOC interrupts to TX and TXEXC
239  *        interrupts, which should fix the timeouts we're seeing.
240  *
241  * v0.09b -> v0.10 - 25 Feb 2002 - David Gibson
242  *      o Removed nested structures used for header parsing, so the
243  *        driver should now work without hackery on ARM
244  *      o Fix for WEP handling on Intersil (Hawk Newton)
245  *      o Eliminated the /proc/hermes/ethXX/regs debugging file.  It
246  *        was never very useful.
247  *      o Make Rx errors less noisy.
248  *
249  * v0.10 -> v0.11 - 5 Apr 2002 - David Gibson
250  *      o Laid the groundwork in hermes.[ch] for devices which map
251  *        into PCI memory space rather than IO space.
252  *      o Fixed bug in multicast handling (cleared multicast list when
253  *        leaving promiscuous mode).
254  *      o Relegated Tx error messages to debug.
255  *      o Cleaned up / corrected handling of allocation lengths.
256  *      o Set OWNSSID in IBSS mode for WinXP interoperability (jimc).
257  *      o Change to using alloc_etherdev() for structure allocations. 
258  *      o Check for and drop undersized packets.
259  *      o Fixed a race in stopping/waking the queue.  This should fix
260  *        the timeout problems (Pavel Roskin)
261  *      o Reverted to netif_wake_queue() on the ALLOC event.
262  *      o Fixes for recent Symbol firmwares which lack AP density
263  *        (Pavel Roskin).
264  *
265  * v0.11 -> v0.11a - 29 Apr 2002 - David Gibson
266  *      o Handle different register spacing, necessary for Prism 2.5
267  *        PCI adaptors (Steve Hill).
268  *      o Cleaned up initialization of card structures in orinoco_cs
269  *        and airport.  Removed card->priv field.
270  *      o Make response structure optional for hermes_docmd_wait()
271  *        Pavel Roskin)
272  *      o Added PCI id for Nortel emobility to orinoco_plx.c.
273  *      o Cleanup to handling of Symbol's allocation bug. (Pavel Roskin)
274  *      o Cleanups to firmware capability detection.
275  *      o Arrange for orinoco_pci.c to override firmware detection.
276  *        We should be able to support the PCI Intersil cards now.
277  *      o Cleanup handling of reset_cor and hard_reset (Pavel Roskin).
278  *      o Remove erroneous use of USER_BAP in the TxExc handler (Jouni
279  *        Malinen).
280  *      o Makefile changes for better integration into David Hinds
281  *        pcmcia-cs package.
282  *
283  * v0.11a -> v0.11b - 1 May 2002 - David Gibson
284  *      o Better error reporting in orinoco_plx_init_one()
285  *      o Fixed multiple bad kfree() bugs introduced by the
286  *        alloc_orinocodev() changes.
287  *
288  * v0.11b -> v0.12 - 19 Jun 2002 - David Gibson
289  *      o Support changing the MAC address.
290  *      o Correct display of Intersil firmware revision numbers.
291  *      o Entirely revised locking scheme.  Should be both simpler and
292  *         better.
293  *      o Merged some common code in orinoco_plx, orinoco_pci and
294  *        airport by creating orinoco_default_{open,stop,reset}()
295  *        which are used as the dev->open, dev->stop, priv->reset
296  *        callbacks if none are specified when alloc_orinocodev() is
297  *        called.
298  *      o Removed orinoco_plx_interrupt() and orinoco_pci_interrupt().
299  *        They didn't do anything.
300  *
301  * v0.12 -> v0.12a - 4 Jul 2002 - David Gibson
302  *      o Some rearrangement of code.
303  *      o Numerous fixups to locking and rest handling, particularly
304  *        for PCMCIA.
305  *      o This allows open and stop net_device methods to be in
306  *        orinoco.c now, rather than in the init modules.
307  *      o In orinoco_cs.c link->priv now points to the struct
308  *        net_device not to the struct orinoco_private.
309  *      o Added a check for undersized SNAP frames, which could cause
310  *        crashes.
311  *
312  * v0.12a -> v0.12b - 11 Jul 2002 - David Gibson
313  *      o Fix hw->num_init testing code, so num_init is actually
314  *        incremented.
315  *      o Fix very stupid bug in orinoco_cs which broke compile with
316  *        CONFIG_SMP.
317  *      o Squashed a warning.
318  *
319  * v0.12b -> v0.12c - 26 Jul 2002 - David Gibson
320  *      o Change to C9X style designated initializers.
321  *      o Add support for 3Com AirConnect PCI.
322  *      o No longer ignore the hard_reset argument to
323  *        alloc_orinocodev().  Oops.
324  *
325  * v0.12c -> v0.13beta1 - 13 Sep 2002 - David Gibson
326  *      o Revert the broken 0.12* locking scheme and go to a new yet
327  *        simpler scheme.
328  *      o Do firmware resets only in orinoco_init() and when waking
329  *        the card from hard sleep.
330  *
331  * v0.13beta1 -> v0.13 - 27 Sep 2002 - David Gibson
332  *      o Re-introduced full resets (via schedule_task()) on Tx
333  *        timeout.
334  *
335  * v0.13 -> v0.13a - 30 Sep 2002 - David Gibson
336  *      o Minor cleanups to info frame handling.  Add basic support
337  *        for linkstatus info frames.
338  *      o Include required kernel headers in orinoco.h, to avoid
339  *        compile problems.
340  *
341  * v0.13a -> v0.13b - 10 Feb 2003 - David Gibson
342  *      o Implemented hard reset for Airport cards
343  *      o Experimental suspend/resume implementation for orinoco_pci
344  *      o Abolished /proc debugging support, replaced with a debugging
345  *        iwpriv.  Now it's ugly and simple instead of ugly and complex.
346  *      o Bugfix in hermes.c if the firmware returned a record length
347  *        of 0, we could go clobbering memory.
348  *      o Bugfix in orinoco_stop() - it used to fail if hw_unavailable
349  *        was set, which was usually true on PCMCIA hot removes.
350  *      o Track LINKSTATUS messages, silently drop Tx packets before
351  *        we are connected (avoids confusing the firmware), and only
352  *        give LINKSTATUS printk()s if the status has changed.
353  *
354  * v0.13b -> v0.13c - 11 Mar 2003 - David Gibson
355  *      o Cleanup: use dev instead of priv in various places.
356  *      o Bug fix: Don't ReleaseConfiguration on RESET_PHYSICAL event
357  *        if we're in the middle of a (driver initiated) hard reset.
358  *      o Bug fix: ETH_ZLEN is supposed to include the header
359  *        (Dionysus Blazakis & Manish Karir)
360  *      o Convert to using workqueues instead of taskqueues (and
361  *        backwards compatibility macros for pre 2.5.41 kernels).
362  *      o Drop redundant (I think...) MOD_{INC,DEC}_USE_COUNT in
363  *        airport.c
364  *      o New orinoco_tmd.c init module from Joerg Dorchain for
365  *        TMD7160 based PCI to PCMCIA bridges (similar to
366  *        orinoco_plx.c).
367  *
368  * v0.13c -> v0.13d - 22 Apr 2003 - David Gibson
369  *      o Make hw_unavailable a counter, rather than just a flag, this
370  *        is necessary to avoid some races (such as a card being
371  *        removed in the middle of orinoco_reset().
372  *      o Restore Release/RequestConfiguration in the PCMCIA event handler
373  *        when dealing with a driver initiated hard reset.  This is
374  *        necessary to prevent hangs due to a spurious interrupt while
375  *        the reset is in progress.
376  *      o Clear the 802.11 header when transmitting, even though we
377  *        don't use it.  This fixes a long standing bug on some
378  *        firmwares, which seem to get confused if that isn't done.
379  *      o Be less eager to de-encapsulate SNAP frames, only do so if
380  *        the OUI is 00:00:00 or 00:00:f8, leave others alone.  The old
381  *        behaviour broke CDP (Cisco Discovery Protocol).
382  *      o Use dev instead of priv for free_irq() as well as
383  *        request_irq() (oops).
384  *      o Attempt to reset rather than giving up if we get too many
385  *        IRQs.
386  *      o Changed semantics of __orinoco_down() so it can be called
387  *        safely with hw_unavailable set.  It also now clears the
388  *        linkstatus (since we're going to have to reassociate).
389  *
390  * v0.13d -> v0.13e - 12 May 2003 - David Gibson
391  *      o Support for post-2.5.68 return values from irq handler.
392  *      o Fixed bug where underlength packets would be double counted
393  *        in the rx_dropped statistics.
394  *      o Provided a module parameter to suppress linkstatus messages.
395  *
396  * v0.13e -> v0.14alpha1 - 30 Sep 2003 - David Gibson
397  *      o Replaced priv->connected logic with netif_carrier_on/off()
398  *        calls.
399  *      o Remove has_ibss_any and never set the CREATEIBSS RID when
400  *        the ESSID is empty.  Too many firmwares break if we do.
401  *      o 2.6 merges: Replace pdev->slot_name with pci_name(), remove
402  *        __devinitdata from PCI ID tables, use free_netdev().
403  *      o Enabled shared-key authentication for Agere firmware (from
404  *        Robert J. Moore <Robert.J.Moore AT allanbank.com>
405  *      o Move netif_wake_queue() (back) to the Tx completion from the
406  *        ALLOC event.  This seems to prevent/mitigate the rolling
407  *        error -110 problems at least on some Intersil firmwares.
408  *        Theoretically reduces performance, but I can't measure it.
409  *        Patch from Andrew Tridgell <tridge AT samba.org>
410  *
411  * v0.14alpha1 -> v0.14alpha2 - 20 Oct 2003 - David Gibson
412  *      o Correctly turn off shared-key authentication when requested
413  *        (bugfix from Robert J. Moore).
414  *      o Correct airport sleep interfaces for current 2.6 kernels.
415  *      o Add code for key change without disabling/enabling the MAC
416  *        port.  This is supposed to allow 802.1x to work sanely, but
417  *        doesn't seem to yet.
418  *
419  * TODO
420  *      o New wireless extensions API (patch from Moustafa
421  *        Youssef, updated by Jim Carter and Pavel Roskin).
422  *      o Handle de-encapsulation within network layer, provide 802.11
423  *        headers (patch from Thomas 'Dent' Mirlacher)
424  *      o RF monitor mode support
425  *      o Fix possible races in SPY handling.
426  *      o Disconnect wireless extensions from fundamental configuration.
427  *      o (maybe) Software WEP support (patch from Stano Meduna).
428  *      o (maybe) Use multiple Tx buffers - driver handling queue
429  *        rather than firmware.
430  */
431
432 /* Locking and synchronization:
433  *
434  * The basic principle is that everything is serialized through a
435  * single spinlock, priv->lock.  The lock is used in user, bh and irq
436  * context, so when taken outside hardirq context it should always be
437  * taken with interrupts disabled.  The lock protects both the
438  * hardware and the struct orinoco_private.
439  *
440  * Another flag, priv->hw_unavailable indicates that the hardware is
441  * unavailable for an extended period of time (e.g. suspended, or in
442  * the middle of a hard reset).  This flag is protected by the
443  * spinlock.  All code which touches the hardware should check the
444  * flag after taking the lock, and if it is set, give up on whatever
445  * they are doing and drop the lock again.  The orinoco_lock()
446  * function handles this (it unlocks and returns -EBUSY if
447  * hw_unavailable is non-zero).
448  */
449
450 #define DRIVER_NAME "orinoco"
451
452 #include <linux/config.h>
453
454 #include <linux/module.h>
455 #include <linux/kernel.h>
456 #include <linux/init.h>
457 #include <linux/ptrace.h>
458 #include <linux/slab.h>
459 #include <linux/string.h>
460 #include <linux/timer.h>
461 #include <linux/ioport.h>
462 #include <linux/netdevice.h>
463 #include <linux/if_arp.h>
464 #include <linux/etherdevice.h>
465 #include <linux/ethtool.h>
466 #include <linux/wireless.h>
467 #include <net/iw_handler.h>
468 #include <net/ieee80211.h>
469
470 #include <asm/uaccess.h>
471 #include <asm/io.h>
472 #include <asm/system.h>
473
474 #include "hermes.h"
475 #include "hermes_rid.h"
476 #include "orinoco.h"
477 #include "ieee802_11.h"
478
479 /********************************************************************/
480 /* Module information                                               */
481 /********************************************************************/
482
483 MODULE_AUTHOR("Pavel Roskin <proski@gnu.org> & David Gibson <hermes@gibson.dropbear.id.au>");
484 MODULE_DESCRIPTION("Driver for Lucent Orinoco, Prism II based and similar wireless cards");
485 MODULE_LICENSE("Dual MPL/GPL");
486
487 /* Level of debugging. Used in the macros in orinoco.h */
488 #ifdef ORINOCO_DEBUG
489 int orinoco_debug = ORINOCO_DEBUG;
490 module_param(orinoco_debug, int, 0644);
491 MODULE_PARM_DESC(orinoco_debug, "Debug level");
492 EXPORT_SYMBOL(orinoco_debug);
493 #endif
494
495 static int suppress_linkstatus; /* = 0 */
496 module_param(suppress_linkstatus, bool, 0644);
497 MODULE_PARM_DESC(suppress_linkstatus, "Don't log link status changes");
498 static int ignore_disconnect; /* = 0 */
499 module_param(ignore_disconnect, int, 0644);
500 MODULE_PARM_DESC(ignore_disconnect, "Don't report lost link to the network layer");
501
502 /********************************************************************/
503 /* Compile time configuration and compatibility stuff               */
504 /********************************************************************/
505
506 /* We do this this way to avoid ifdefs in the actual code */
507 #ifdef WIRELESS_SPY
508 #define SPY_NUMBER(priv)        (priv->spy_number)
509 #else
510 #define SPY_NUMBER(priv)        0
511 #endif /* WIRELESS_SPY */
512
513 /********************************************************************/
514 /* Internal constants                                               */
515 /********************************************************************/
516
517 /* 802.2 LLC/SNAP header used for Ethernet encapsulation over 802.11 */
518 static const u8 encaps_hdr[] = {0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00};
519 #define ENCAPS_OVERHEAD         (sizeof(encaps_hdr) + 2)
520
521 #define ORINOCO_MIN_MTU         256
522 #define ORINOCO_MAX_MTU         (IEEE802_11_DATA_LEN - ENCAPS_OVERHEAD)
523
524 #define SYMBOL_MAX_VER_LEN      (14)
525 #define USER_BAP                0
526 #define IRQ_BAP                 1
527 #define MAX_IRQLOOPS_PER_IRQ    10
528 #define MAX_IRQLOOPS_PER_JIFFY  (20000/HZ) /* Based on a guestimate of
529                                             * how many events the
530                                             * device could
531                                             * legitimately generate */
532 #define SMALL_KEY_SIZE          5
533 #define LARGE_KEY_SIZE          13
534 #define TX_NICBUF_SIZE_BUG      1585            /* Bug in Symbol firmware */
535
536 #define DUMMY_FID               0xFFFF
537
538 /*#define MAX_MULTICAST(priv)   (priv->firmware_type == FIRMWARE_TYPE_AGERE ? \
539   HERMES_MAX_MULTICAST : 0)*/
540 #define MAX_MULTICAST(priv)     (HERMES_MAX_MULTICAST)
541
542 #define ORINOCO_INTEN           (HERMES_EV_RX | HERMES_EV_ALLOC \
543                                  | HERMES_EV_TX | HERMES_EV_TXEXC \
544                                  | HERMES_EV_WTERR | HERMES_EV_INFO \
545                                  | HERMES_EV_INFDROP )
546
547 #define MAX_RID_LEN 1024
548
549 static const struct iw_handler_def orinoco_handler_def;
550 static struct ethtool_ops orinoco_ethtool_ops;
551
552 /********************************************************************/
553 /* Data tables                                                      */
554 /********************************************************************/
555
556 /* The frequency of each channel in MHz */
557 static const long channel_frequency[] = {
558         2412, 2417, 2422, 2427, 2432, 2437, 2442,
559         2447, 2452, 2457, 2462, 2467, 2472, 2484
560 };
561 #define NUM_CHANNELS ARRAY_SIZE(channel_frequency)
562
563 /* This tables gives the actual meanings of the bitrate IDs returned
564  * by the firmware. */
565 static struct {
566         int bitrate; /* in 100s of kilobits */
567         int automatic;
568         u16 agere_txratectrl;
569         u16 intersil_txratectrl;
570 } bitrate_table[] = {
571         {110, 1,  3, 15}, /* Entry 0 is the default */
572         {10,  0,  1,  1},
573         {10,  1,  1,  1},
574         {20,  0,  2,  2},
575         {20,  1,  6,  3},
576         {55,  0,  4,  4},
577         {55,  1,  7,  7},
578         {110, 0,  5,  8},
579 };
580 #define BITRATE_TABLE_SIZE ARRAY_SIZE(bitrate_table)
581
582 /********************************************************************/
583 /* Data types                                                       */
584 /********************************************************************/
585
586 /* Used in Event handling.
587  * We avoid nested structres as they break on ARM -- Moustafa */
588 struct hermes_tx_descriptor_802_11 {
589         /* hermes_tx_descriptor */
590         u16 status;
591         u16 reserved1;
592         u16 reserved2;
593         u32 sw_support;
594         u8 retry_count;
595         u8 tx_rate;
596         u16 tx_control;
597
598         /* ieee802_11_hdr */
599         u16 frame_ctl;
600         u16 duration_id;
601         u8 addr1[ETH_ALEN];
602         u8 addr2[ETH_ALEN];
603         u8 addr3[ETH_ALEN];
604         u16 seq_ctl;
605         u8 addr4[ETH_ALEN];
606         u16 data_len;
607
608         /* ethhdr */
609         unsigned char   h_dest[ETH_ALEN];       /* destination eth addr */
610         unsigned char   h_source[ETH_ALEN];     /* source ether addr    */
611         unsigned short  h_proto;                /* packet type ID field */
612
613         /* p8022_hdr */
614         u8 dsap;
615         u8 ssap;
616         u8 ctrl;
617         u8 oui[3];
618
619         u16 ethertype;
620 } __attribute__ ((packed));
621
622 struct hermes_rx_descriptor {
623         u16 status;
624         u32 time;
625         u8 silence;
626         u8 signal;
627         u8 rate;
628         u8 rxflow;
629         u32 reserved;
630 } __attribute__ ((packed));
631
632 /********************************************************************/
633 /* Function prototypes                                              */
634 /********************************************************************/
635
636 static int __orinoco_program_rids(struct net_device *dev);
637 static void __orinoco_set_multicast_list(struct net_device *dev);
638
639 /********************************************************************/
640 /* Internal helper functions                                        */
641 /********************************************************************/
642
643 static inline void set_port_type(struct orinoco_private *priv)
644 {
645         switch (priv->iw_mode) {
646         case IW_MODE_INFRA:
647                 priv->port_type = 1;
648                 priv->createibss = 0;
649                 break;
650         case IW_MODE_ADHOC:
651                 if (priv->prefer_port3) {
652                         priv->port_type = 3;
653                         priv->createibss = 0;
654                 } else {
655                         priv->port_type = priv->ibss_port;
656                         priv->createibss = 1;
657                 }
658                 break;
659         default:
660                 printk(KERN_ERR "%s: Invalid priv->iw_mode in set_port_type()\n",
661                        priv->ndev->name);
662         }
663 }
664
665 /********************************************************************/
666 /* Device methods                                                   */
667 /********************************************************************/
668
669 static int orinoco_open(struct net_device *dev)
670 {
671         struct orinoco_private *priv = netdev_priv(dev);
672         unsigned long flags;
673         int err;
674
675         if (orinoco_lock(priv, &flags) != 0)
676                 return -EBUSY;
677
678         err = __orinoco_up(dev);
679
680         if (! err)
681                 priv->open = 1;
682
683         orinoco_unlock(priv, &flags);
684
685         return err;
686 }
687
688 static int orinoco_stop(struct net_device *dev)
689 {
690         struct orinoco_private *priv = netdev_priv(dev);
691         int err = 0;
692
693         /* We mustn't use orinoco_lock() here, because we need to be
694            able to close the interface even if hw_unavailable is set
695            (e.g. as we're released after a PC Card removal) */
696         spin_lock_irq(&priv->lock);
697
698         priv->open = 0;
699
700         err = __orinoco_down(dev);
701
702         spin_unlock_irq(&priv->lock);
703
704         return err;
705 }
706
707 static struct net_device_stats *orinoco_get_stats(struct net_device *dev)
708 {
709         struct orinoco_private *priv = netdev_priv(dev);
710         
711         return &priv->stats;
712 }
713
714 static struct iw_statistics *orinoco_get_wireless_stats(struct net_device *dev)
715 {
716         struct orinoco_private *priv = netdev_priv(dev);
717         hermes_t *hw = &priv->hw;
718         struct iw_statistics *wstats = &priv->wstats;
719         int err;
720         unsigned long flags;
721
722         if (! netif_device_present(dev)) {
723                 printk(KERN_WARNING "%s: get_wireless_stats() called while device not present\n",
724                        dev->name);
725                 return NULL; /* FIXME: Can we do better than this? */
726         }
727
728         /* If busy, return the old stats.  Returning NULL may cause
729          * the interface to disappear from /proc/net/wireless */
730         if (orinoco_lock(priv, &flags) != 0)
731                 return wstats;
732
733         /* We can't really wait for the tallies inquiry command to
734          * complete, so we just use the previous results and trigger
735          * a new tallies inquiry command for next time - Jean II */
736         /* FIXME: Really we should wait for the inquiry to come back -
737          * as it is the stats we give don't make a whole lot of sense.
738          * Unfortunately, it's not clear how to do that within the
739          * wireless extensions framework: I think we're in user
740          * context, but a lock seems to be held by the time we get in
741          * here so we're not safe to sleep here. */
742         hermes_inquire(hw, HERMES_INQ_TALLIES);
743
744         if (priv->iw_mode == IW_MODE_ADHOC) {
745                 memset(&wstats->qual, 0, sizeof(wstats->qual));
746                 /* If a spy address is defined, we report stats of the
747                  * first spy address - Jean II */
748                 if (SPY_NUMBER(priv)) {
749                         wstats->qual.qual = priv->spy_stat[0].qual;
750                         wstats->qual.level = priv->spy_stat[0].level;
751                         wstats->qual.noise = priv->spy_stat[0].noise;
752                         wstats->qual.updated = priv->spy_stat[0].updated;
753                 }
754         } else {
755                 struct {
756                         u16 qual, signal, noise;
757                 } __attribute__ ((packed)) cq;
758
759                 err = HERMES_READ_RECORD(hw, USER_BAP,
760                                          HERMES_RID_COMMSQUALITY, &cq);
761
762                 if (!err) {
763                         wstats->qual.qual = (int)le16_to_cpu(cq.qual);
764                         wstats->qual.level = (int)le16_to_cpu(cq.signal) - 0x95;
765                         wstats->qual.noise = (int)le16_to_cpu(cq.noise) - 0x95;
766                         wstats->qual.updated = 7;
767                 }
768         }
769
770         orinoco_unlock(priv, &flags);
771         return wstats;
772 }
773
774 static void orinoco_set_multicast_list(struct net_device *dev)
775 {
776         struct orinoco_private *priv = netdev_priv(dev);
777         unsigned long flags;
778
779         if (orinoco_lock(priv, &flags) != 0) {
780                 printk(KERN_DEBUG "%s: orinoco_set_multicast_list() "
781                        "called when hw_unavailable\n", dev->name);
782                 return;
783         }
784
785         __orinoco_set_multicast_list(dev);
786         orinoco_unlock(priv, &flags);
787 }
788
789 static int orinoco_change_mtu(struct net_device *dev, int new_mtu)
790 {
791         struct orinoco_private *priv = netdev_priv(dev);
792
793         if ( (new_mtu < ORINOCO_MIN_MTU) || (new_mtu > ORINOCO_MAX_MTU) )
794                 return -EINVAL;
795
796         if ( (new_mtu + ENCAPS_OVERHEAD + IEEE802_11_HLEN) >
797              (priv->nicbuf_size - ETH_HLEN) )
798                 return -EINVAL;
799
800         dev->mtu = new_mtu;
801
802         return 0;
803 }
804
805 /********************************************************************/
806 /* Tx path                                                          */
807 /********************************************************************/
808
809 static int orinoco_xmit(struct sk_buff *skb, struct net_device *dev)
810 {
811         struct orinoco_private *priv = netdev_priv(dev);
812         struct net_device_stats *stats = &priv->stats;
813         hermes_t *hw = &priv->hw;
814         int err = 0;
815         u16 txfid = priv->txfid;
816         char *p;
817         struct ethhdr *eh;
818         int len, data_len, data_off;
819         struct hermes_tx_descriptor desc;
820         unsigned long flags;
821
822         TRACE_ENTER(dev->name);
823
824         if (! netif_running(dev)) {
825                 printk(KERN_ERR "%s: Tx on stopped device!\n",
826                        dev->name);
827                 TRACE_EXIT(dev->name);
828                 return 1;
829         }
830         
831         if (netif_queue_stopped(dev)) {
832                 printk(KERN_DEBUG "%s: Tx while transmitter busy!\n", 
833                        dev->name);
834                 TRACE_EXIT(dev->name);
835                 return 1;
836         }
837         
838         if (orinoco_lock(priv, &flags) != 0) {
839                 printk(KERN_ERR "%s: orinoco_xmit() called while hw_unavailable\n",
840                        dev->name);
841                 TRACE_EXIT(dev->name);
842                 return 1;
843         }
844
845         if (! netif_carrier_ok(dev)) {
846                 /* Oops, the firmware hasn't established a connection,
847                    silently drop the packet (this seems to be the
848                    safest approach). */
849                 stats->tx_errors++;
850                 orinoco_unlock(priv, &flags);
851                 dev_kfree_skb(skb);
852                 TRACE_EXIT(dev->name);
853                 return 0;
854         }
855
856         /* Length of the packet body */
857         /* FIXME: what if the skb is smaller than this? */
858         len = max_t(int,skb->len - ETH_HLEN, ETH_ZLEN - ETH_HLEN);
859
860         eh = (struct ethhdr *)skb->data;
861
862         memset(&desc, 0, sizeof(desc));
863         desc.tx_control = cpu_to_le16(HERMES_TXCTRL_TX_OK | HERMES_TXCTRL_TX_EX);
864         err = hermes_bap_pwrite(hw, USER_BAP, &desc, sizeof(desc), txfid, 0);
865         if (err) {
866                 if (net_ratelimit())
867                         printk(KERN_ERR "%s: Error %d writing Tx descriptor "
868                                "to BAP\n", dev->name, err);
869                 stats->tx_errors++;
870                 goto fail;
871         }
872
873         /* Clear the 802.11 header and data length fields - some
874          * firmwares (e.g. Lucent/Agere 8.xx) appear to get confused
875          * if this isn't done. */
876         hermes_clear_words(hw, HERMES_DATA0,
877                            HERMES_802_3_OFFSET - HERMES_802_11_OFFSET);
878
879         /* Encapsulate Ethernet-II frames */
880         if (ntohs(eh->h_proto) > ETH_DATA_LEN) { /* Ethernet-II frame */
881                 struct header_struct hdr;
882                 data_len = len;
883                 data_off = HERMES_802_3_OFFSET + sizeof(hdr);
884                 p = skb->data + ETH_HLEN;
885
886                 /* 802.3 header */
887                 memcpy(hdr.dest, eh->h_dest, ETH_ALEN);
888                 memcpy(hdr.src, eh->h_source, ETH_ALEN);
889                 hdr.len = htons(data_len + ENCAPS_OVERHEAD);
890                 
891                 /* 802.2 header */
892                 memcpy(&hdr.dsap, &encaps_hdr, sizeof(encaps_hdr));
893                         
894                 hdr.ethertype = eh->h_proto;
895                 err  = hermes_bap_pwrite(hw, USER_BAP, &hdr, sizeof(hdr),
896                                          txfid, HERMES_802_3_OFFSET);
897                 if (err) {
898                         if (net_ratelimit())
899                                 printk(KERN_ERR "%s: Error %d writing packet "
900                                        "header to BAP\n", dev->name, err);
901                         stats->tx_errors++;
902                         goto fail;
903                 }
904         } else { /* IEEE 802.3 frame */
905                 data_len = len + ETH_HLEN;
906                 data_off = HERMES_802_3_OFFSET;
907                 p = skb->data;
908         }
909
910         /* Round up for odd length packets */
911         err = hermes_bap_pwrite(hw, USER_BAP, p, ALIGN(data_len, 2),
912                                 txfid, data_off);
913         if (err) {
914                 printk(KERN_ERR "%s: Error %d writing packet to BAP\n",
915                        dev->name, err);
916                 stats->tx_errors++;
917                 goto fail;
918         }
919
920         /* Finally, we actually initiate the send */
921         netif_stop_queue(dev);
922
923         err = hermes_docmd_wait(hw, HERMES_CMD_TX | HERMES_CMD_RECL,
924                                 txfid, NULL);
925         if (err) {
926                 netif_start_queue(dev);
927                 printk(KERN_ERR "%s: Error %d transmitting packet\n",
928                        dev->name, err);
929                 stats->tx_errors++;
930                 goto fail;
931         }
932
933         dev->trans_start = jiffies;
934         stats->tx_bytes += data_off + data_len;
935
936         orinoco_unlock(priv, &flags);
937
938         dev_kfree_skb(skb);
939
940         TRACE_EXIT(dev->name);
941
942         return 0;
943  fail:
944         TRACE_EXIT(dev->name);
945
946         orinoco_unlock(priv, &flags);
947         return err;
948 }
949
950 static void __orinoco_ev_alloc(struct net_device *dev, hermes_t *hw)
951 {
952         struct orinoco_private *priv = netdev_priv(dev);
953         u16 fid = hermes_read_regn(hw, ALLOCFID);
954
955         if (fid != priv->txfid) {
956                 if (fid != DUMMY_FID)
957                         printk(KERN_WARNING "%s: Allocate event on unexpected fid (%04X)\n",
958                                dev->name, fid);
959                 return;
960         }
961
962         hermes_write_regn(hw, ALLOCFID, DUMMY_FID);
963 }
964
965 static void __orinoco_ev_tx(struct net_device *dev, hermes_t *hw)
966 {
967         struct orinoco_private *priv = netdev_priv(dev);
968         struct net_device_stats *stats = &priv->stats;
969
970         stats->tx_packets++;
971
972         netif_wake_queue(dev);
973
974         hermes_write_regn(hw, TXCOMPLFID, DUMMY_FID);
975 }
976
977 static void __orinoco_ev_txexc(struct net_device *dev, hermes_t *hw)
978 {
979         struct orinoco_private *priv = netdev_priv(dev);
980         struct net_device_stats *stats = &priv->stats;
981         u16 fid = hermes_read_regn(hw, TXCOMPLFID);
982         struct hermes_tx_descriptor_802_11 hdr;
983         int err = 0;
984
985         if (fid == DUMMY_FID)
986                 return; /* Nothing's really happened */
987
988         /* Read the frame header */
989         err = hermes_bap_pread(hw, IRQ_BAP, &hdr,
990                                sizeof(struct hermes_tx_descriptor) +
991                                sizeof(struct ieee80211_hdr),
992                                fid, 0);
993
994         hermes_write_regn(hw, TXCOMPLFID, DUMMY_FID);
995         stats->tx_errors++;
996
997         if (err) {
998                 printk(KERN_WARNING "%s: Unable to read descriptor on Tx error "
999                        "(FID=%04X error %d)\n",
1000                        dev->name, fid, err);
1001                 return;
1002         }
1003         
1004         DEBUG(1, "%s: Tx error, err %d (FID=%04X)\n", dev->name,
1005               err, fid);
1006     
1007         /* We produce a TXDROP event only for retry or lifetime
1008          * exceeded, because that's the only status that really mean
1009          * that this particular node went away.
1010          * Other errors means that *we* screwed up. - Jean II */
1011         hdr.status = le16_to_cpu(hdr.status);
1012         if (hdr.status & (HERMES_TXSTAT_RETRYERR | HERMES_TXSTAT_AGEDERR)) {
1013                 union iwreq_data        wrqu;
1014
1015                 /* Copy 802.11 dest address.
1016                  * We use the 802.11 header because the frame may
1017                  * not be 802.3 or may be mangled...
1018                  * In Ad-Hoc mode, it will be the node address.
1019                  * In managed mode, it will be most likely the AP addr
1020                  * User space will figure out how to convert it to
1021                  * whatever it needs (IP address or else).
1022                  * - Jean II */
1023                 memcpy(wrqu.addr.sa_data, hdr.addr1, ETH_ALEN);
1024                 wrqu.addr.sa_family = ARPHRD_ETHER;
1025
1026                 /* Send event to user space */
1027                 wireless_send_event(dev, IWEVTXDROP, &wrqu, NULL);
1028         }
1029
1030         netif_wake_queue(dev);
1031 }
1032
1033 static void orinoco_tx_timeout(struct net_device *dev)
1034 {
1035         struct orinoco_private *priv = netdev_priv(dev);
1036         struct net_device_stats *stats = &priv->stats;
1037         struct hermes *hw = &priv->hw;
1038
1039         printk(KERN_WARNING "%s: Tx timeout! "
1040                "ALLOCFID=%04x, TXCOMPLFID=%04x, EVSTAT=%04x\n",
1041                dev->name, hermes_read_regn(hw, ALLOCFID),
1042                hermes_read_regn(hw, TXCOMPLFID), hermes_read_regn(hw, EVSTAT));
1043
1044         stats->tx_errors++;
1045
1046         schedule_work(&priv->reset_work);
1047 }
1048
1049 /********************************************************************/
1050 /* Rx path (data frames)                                            */
1051 /********************************************************************/
1052
1053 /* Does the frame have a SNAP header indicating it should be
1054  * de-encapsulated to Ethernet-II? */
1055 static inline int is_ethersnap(void *_hdr)
1056 {
1057         u8 *hdr = _hdr;
1058
1059         /* We de-encapsulate all packets which, a) have SNAP headers
1060          * (i.e. SSAP=DSAP=0xaa and CTRL=0x3 in the 802.2 LLC header
1061          * and where b) the OUI of the SNAP header is 00:00:00 or
1062          * 00:00:f8 - we need both because different APs appear to use
1063          * different OUIs for some reason */
1064         return (memcmp(hdr, &encaps_hdr, 5) == 0)
1065                 && ( (hdr[5] == 0x00) || (hdr[5] == 0xf8) );
1066 }
1067
1068 static inline void orinoco_spy_gather(struct net_device *dev, u_char *mac,
1069                                       int level, int noise)
1070 {
1071         struct orinoco_private *priv = netdev_priv(dev);
1072         int i;
1073
1074         /* Gather wireless spy statistics: for each packet, compare the
1075          * source address with out list, and if match, get the stats... */
1076         for (i = 0; i < priv->spy_number; i++)
1077                 if (!memcmp(mac, priv->spy_address[i], ETH_ALEN)) {
1078                         priv->spy_stat[i].level = level - 0x95;
1079                         priv->spy_stat[i].noise = noise - 0x95;
1080                         priv->spy_stat[i].qual = (level > noise) ? (level - noise) : 0;
1081                         priv->spy_stat[i].updated = 7;
1082                 }
1083 }
1084
1085 static void orinoco_stat_gather(struct net_device *dev,
1086                                 struct sk_buff *skb,
1087                                 struct hermes_rx_descriptor *desc)
1088 {
1089         struct orinoco_private *priv = netdev_priv(dev);
1090
1091         /* Using spy support with lots of Rx packets, like in an
1092          * infrastructure (AP), will really slow down everything, because
1093          * the MAC address must be compared to each entry of the spy list.
1094          * If the user really asks for it (set some address in the
1095          * spy list), we do it, but he will pay the price.
1096          * Note that to get here, you need both WIRELESS_SPY
1097          * compiled in AND some addresses in the list !!!
1098          */
1099         /* Note : gcc will optimise the whole section away if
1100          * WIRELESS_SPY is not defined... - Jean II */
1101         if (SPY_NUMBER(priv)) {
1102                 orinoco_spy_gather(dev, skb->mac.raw + ETH_ALEN,
1103                                    desc->signal, desc->silence);
1104         }
1105 }
1106
1107 static void __orinoco_ev_rx(struct net_device *dev, hermes_t *hw)
1108 {
1109         struct orinoco_private *priv = netdev_priv(dev);
1110         struct net_device_stats *stats = &priv->stats;
1111         struct iw_statistics *wstats = &priv->wstats;
1112         struct sk_buff *skb = NULL;
1113         u16 rxfid, status;
1114         int length, data_len, data_off;
1115         char *p;
1116         struct hermes_rx_descriptor desc;
1117         struct header_struct hdr;
1118         struct ethhdr *eh;
1119         int err;
1120
1121         rxfid = hermes_read_regn(hw, RXFID);
1122
1123         err = hermes_bap_pread(hw, IRQ_BAP, &desc, sizeof(desc),
1124                                rxfid, 0);
1125         if (err) {
1126                 printk(KERN_ERR "%s: error %d reading Rx descriptor. "
1127                        "Frame dropped.\n", dev->name, err);
1128                 stats->rx_errors++;
1129                 goto drop;
1130         }
1131
1132         status = le16_to_cpu(desc.status);
1133
1134         if (status & HERMES_RXSTAT_ERR) {
1135                 if (status & HERMES_RXSTAT_UNDECRYPTABLE) {
1136                         wstats->discard.code++;
1137                         DEBUG(1, "%s: Undecryptable frame on Rx. Frame dropped.\n",
1138                                dev->name);
1139                 } else {
1140                         stats->rx_crc_errors++;
1141                         DEBUG(1, "%s: Bad CRC on Rx. Frame dropped.\n", dev->name);
1142                 }
1143                 stats->rx_errors++;
1144                 goto drop;
1145         }
1146
1147         /* For now we ignore the 802.11 header completely, assuming
1148            that the card's firmware has handled anything vital */
1149
1150         err = hermes_bap_pread(hw, IRQ_BAP, &hdr, sizeof(hdr),
1151                                rxfid, HERMES_802_3_OFFSET);
1152         if (err) {
1153                 printk(KERN_ERR "%s: error %d reading frame header. "
1154                        "Frame dropped.\n", dev->name, err);
1155                 stats->rx_errors++;
1156                 goto drop;
1157         }
1158
1159         length = ntohs(hdr.len);
1160         
1161         /* Sanity checks */
1162         if (length < 3) { /* No for even an 802.2 LLC header */
1163                 /* At least on Symbol firmware with PCF we get quite a
1164                    lot of these legitimately - Poll frames with no
1165                    data. */
1166                 stats->rx_dropped++;
1167                 goto drop;
1168         }
1169         if (length > IEEE802_11_DATA_LEN) {
1170                 printk(KERN_WARNING "%s: Oversized frame received (%d bytes)\n",
1171                        dev->name, length);
1172                 stats->rx_length_errors++;
1173                 stats->rx_errors++;
1174                 goto drop;
1175         }
1176
1177         /* We need space for the packet data itself, plus an ethernet
1178            header, plus 2 bytes so we can align the IP header on a
1179            32bit boundary, plus 1 byte so we can read in odd length
1180            packets from the card, which has an IO granularity of 16
1181            bits */  
1182         skb = dev_alloc_skb(length+ETH_HLEN+2+1);
1183         if (!skb) {
1184                 printk(KERN_WARNING "%s: Can't allocate skb for Rx\n",
1185                        dev->name);
1186                 goto drop;
1187         }
1188
1189         skb_reserve(skb, 2); /* This way the IP header is aligned */
1190
1191         /* Handle decapsulation
1192          * In most cases, the firmware tell us about SNAP frames.
1193          * For some reason, the SNAP frames sent by LinkSys APs
1194          * are not properly recognised by most firmwares.
1195          * So, check ourselves */
1196         if (((status & HERMES_RXSTAT_MSGTYPE) == HERMES_RXSTAT_1042) ||
1197             ((status & HERMES_RXSTAT_MSGTYPE) == HERMES_RXSTAT_TUNNEL) ||
1198             is_ethersnap(&hdr)) {
1199                 /* These indicate a SNAP within 802.2 LLC within
1200                    802.11 frame which we'll need to de-encapsulate to
1201                    the original EthernetII frame. */
1202
1203                 if (length < ENCAPS_OVERHEAD) { /* No room for full LLC+SNAP */
1204                         stats->rx_length_errors++;
1205                         goto drop;
1206                 }
1207
1208                 /* Remove SNAP header, reconstruct EthernetII frame */
1209                 data_len = length - ENCAPS_OVERHEAD;
1210                 data_off = HERMES_802_3_OFFSET + sizeof(hdr);
1211
1212                 eh = (struct ethhdr *)skb_put(skb, ETH_HLEN);
1213
1214                 memcpy(eh, &hdr, 2 * ETH_ALEN);
1215                 eh->h_proto = hdr.ethertype;
1216         } else {
1217                 /* All other cases indicate a genuine 802.3 frame.  No
1218                    decapsulation needed.  We just throw the whole
1219                    thing in, and hope the protocol layer can deal with
1220                    it as 802.3 */
1221                 data_len = length;
1222                 data_off = HERMES_802_3_OFFSET;
1223                 /* FIXME: we re-read from the card data we already read here */
1224         }
1225
1226         p = skb_put(skb, data_len);
1227         err = hermes_bap_pread(hw, IRQ_BAP, p, ALIGN(data_len, 2),
1228                                rxfid, data_off);
1229         if (err) {
1230                 printk(KERN_ERR "%s: error %d reading frame. "
1231                        "Frame dropped.\n", dev->name, err);
1232                 stats->rx_errors++;
1233                 goto drop;
1234         }
1235
1236         dev->last_rx = jiffies;
1237         skb->dev = dev;
1238         skb->protocol = eth_type_trans(skb, dev);
1239         skb->ip_summed = CHECKSUM_NONE;
1240         
1241         /* Process the wireless stats if needed */
1242         orinoco_stat_gather(dev, skb, &desc);
1243
1244         /* Pass the packet to the networking stack */
1245         netif_rx(skb);
1246         stats->rx_packets++;
1247         stats->rx_bytes += length;
1248
1249         return;
1250
1251  drop:  
1252         stats->rx_dropped++;
1253
1254         if (skb)
1255                 dev_kfree_skb_irq(skb);
1256         return;
1257 }
1258
1259 /********************************************************************/
1260 /* Rx path (info frames)                                            */
1261 /********************************************************************/
1262
1263 static void print_linkstatus(struct net_device *dev, u16 status)
1264 {
1265         char * s;
1266
1267         if (suppress_linkstatus)
1268                 return;
1269
1270         switch (status) {
1271         case HERMES_LINKSTATUS_NOT_CONNECTED:
1272                 s = "Not Connected";
1273                 break;
1274         case HERMES_LINKSTATUS_CONNECTED:
1275                 s = "Connected";
1276                 break;
1277         case HERMES_LINKSTATUS_DISCONNECTED:
1278                 s = "Disconnected";
1279                 break;
1280         case HERMES_LINKSTATUS_AP_CHANGE:
1281                 s = "AP Changed";
1282                 break;
1283         case HERMES_LINKSTATUS_AP_OUT_OF_RANGE:
1284                 s = "AP Out of Range";
1285                 break;
1286         case HERMES_LINKSTATUS_AP_IN_RANGE:
1287                 s = "AP In Range";
1288                 break;
1289         case HERMES_LINKSTATUS_ASSOC_FAILED:
1290                 s = "Association Failed";
1291                 break;
1292         default:
1293                 s = "UNKNOWN";
1294         }
1295         
1296         printk(KERN_INFO "%s: New link status: %s (%04x)\n",
1297                dev->name, s, status);
1298 }
1299
1300 /* Search scan results for requested BSSID, join it if found */
1301 static void orinoco_join_ap(struct net_device *dev)
1302 {
1303         struct orinoco_private *priv = netdev_priv(dev);
1304         struct hermes *hw = &priv->hw;
1305         int err;
1306         unsigned long flags;
1307         struct join_req {
1308                 u8 bssid[ETH_ALEN];
1309                 u16 channel;
1310         } __attribute__ ((packed)) req;
1311         const int atom_len = offsetof(struct prism2_scan_apinfo, atim);
1312         struct prism2_scan_apinfo *atom;
1313         int offset = 4;
1314         u8 *buf;
1315         u16 len;
1316
1317         /* Allocate buffer for scan results */
1318         buf = kmalloc(MAX_SCAN_LEN, GFP_KERNEL);
1319         if (! buf)
1320                 return;
1321
1322         if (orinoco_lock(priv, &flags) != 0)
1323                 goto out;
1324
1325         /* Sanity checks in case user changed something in the meantime */
1326         if (! priv->bssid_fixed)
1327                 goto out;
1328
1329         if (strlen(priv->desired_essid) == 0)
1330                 goto out;
1331
1332         /* Read scan results from the firmware */
1333         err = hermes_read_ltv(hw, USER_BAP,
1334                               HERMES_RID_SCANRESULTSTABLE,
1335                               MAX_SCAN_LEN, &len, buf);
1336         if (err) {
1337                 printk(KERN_ERR "%s: Cannot read scan results\n",
1338                        dev->name);
1339                 goto out;
1340         }
1341
1342         len = HERMES_RECLEN_TO_BYTES(len);
1343
1344         /* Go through the scan results looking for the channel of the AP
1345          * we were requested to join */
1346         for (; offset + atom_len <= len; offset += atom_len) {
1347                 atom = (struct prism2_scan_apinfo *) (buf + offset);
1348                 if (memcmp(&atom->bssid, priv->desired_bssid, ETH_ALEN) == 0)
1349                         goto found;
1350         }
1351
1352         DEBUG(1, "%s: Requested AP not found in scan results\n",
1353               dev->name);
1354         goto out;
1355
1356  found:
1357         memcpy(req.bssid, priv->desired_bssid, ETH_ALEN);
1358         req.channel = atom->channel;    /* both are little-endian */
1359         err = HERMES_WRITE_RECORD(hw, USER_BAP, HERMES_RID_CNFJOINREQUEST,
1360                                   &req);
1361         if (err)
1362                 printk(KERN_ERR "%s: Error issuing join request\n", dev->name);
1363
1364  out:
1365         kfree(buf);
1366         orinoco_unlock(priv, &flags);
1367 }
1368
1369 /* Send new BSSID to userspace */
1370 static void orinoco_send_wevents(struct net_device *dev)
1371 {
1372         struct orinoco_private *priv = netdev_priv(dev);
1373         struct hermes *hw = &priv->hw;
1374         union iwreq_data wrqu;
1375         int err;
1376         unsigned long flags;
1377
1378         if (orinoco_lock(priv, &flags) != 0)
1379                 return;
1380
1381         err = hermes_read_ltv(hw, IRQ_BAP, HERMES_RID_CURRENTBSSID,
1382                               ETH_ALEN, NULL, wrqu.ap_addr.sa_data);
1383         if (err != 0)
1384                 return;
1385
1386         wrqu.ap_addr.sa_family = ARPHRD_ETHER;
1387
1388         /* Send event to user space */
1389         wireless_send_event(dev, SIOCGIWAP, &wrqu, NULL);
1390         orinoco_unlock(priv, &flags);
1391 }
1392
1393 static void __orinoco_ev_info(struct net_device *dev, hermes_t *hw)
1394 {
1395         struct orinoco_private *priv = netdev_priv(dev);
1396         u16 infofid;
1397         struct {
1398                 u16 len;
1399                 u16 type;
1400         } __attribute__ ((packed)) info;
1401         int len, type;
1402         int err;
1403
1404         /* This is an answer to an INQUIRE command that we did earlier,
1405          * or an information "event" generated by the card
1406          * The controller return to us a pseudo frame containing
1407          * the information in question - Jean II */
1408         infofid = hermes_read_regn(hw, INFOFID);
1409
1410         /* Read the info frame header - don't try too hard */
1411         err = hermes_bap_pread(hw, IRQ_BAP, &info, sizeof(info),
1412                                infofid, 0);
1413         if (err) {
1414                 printk(KERN_ERR "%s: error %d reading info frame. "
1415                        "Frame dropped.\n", dev->name, err);
1416                 return;
1417         }
1418         
1419         len = HERMES_RECLEN_TO_BYTES(le16_to_cpu(info.len));
1420         type = le16_to_cpu(info.type);
1421
1422         switch (type) {
1423         case HERMES_INQ_TALLIES: {
1424                 struct hermes_tallies_frame tallies;
1425                 struct iw_statistics *wstats = &priv->wstats;
1426                 
1427                 if (len > sizeof(tallies)) {
1428                         printk(KERN_WARNING "%s: Tallies frame too long (%d bytes)\n",
1429                                dev->name, len);
1430                         len = sizeof(tallies);
1431                 }
1432                 
1433                 err = hermes_bap_pread(hw, IRQ_BAP, &tallies, len,
1434                                        infofid, sizeof(info));
1435                 if (err)
1436                         break;
1437                 
1438                 /* Increment our various counters */
1439                 /* wstats->discard.nwid - no wrong BSSID stuff */
1440                 wstats->discard.code +=
1441                         le16_to_cpu(tallies.RxWEPUndecryptable);
1442                 if (len == sizeof(tallies))  
1443                         wstats->discard.code +=
1444                                 le16_to_cpu(tallies.RxDiscards_WEPICVError) +
1445                                 le16_to_cpu(tallies.RxDiscards_WEPExcluded);
1446                 wstats->discard.misc +=
1447                         le16_to_cpu(tallies.TxDiscardsWrongSA);
1448                 wstats->discard.fragment +=
1449                         le16_to_cpu(tallies.RxMsgInBadMsgFragments);
1450                 wstats->discard.retries +=
1451                         le16_to_cpu(tallies.TxRetryLimitExceeded);
1452                 /* wstats->miss.beacon - no match */
1453         }
1454         break;
1455         case HERMES_INQ_LINKSTATUS: {
1456                 struct hermes_linkstatus linkstatus;
1457                 u16 newstatus;
1458                 int connected;
1459
1460                 if (len != sizeof(linkstatus)) {
1461                         printk(KERN_WARNING "%s: Unexpected size for linkstatus frame (%d bytes)\n",
1462                                dev->name, len);
1463                         break;
1464                 }
1465
1466                 err = hermes_bap_pread(hw, IRQ_BAP, &linkstatus, len,
1467                                        infofid, sizeof(info));
1468                 if (err)
1469                         break;
1470                 newstatus = le16_to_cpu(linkstatus.linkstatus);
1471
1472                 /* Symbol firmware uses "out of range" to signal that
1473                  * the hostscan frame can be requested.  */
1474                 if (newstatus == HERMES_LINKSTATUS_AP_OUT_OF_RANGE &&
1475                     priv->firmware_type == FIRMWARE_TYPE_SYMBOL &&
1476                     priv->has_hostscan && priv->scan_inprogress) {
1477                         hermes_inquire(hw, HERMES_INQ_HOSTSCAN_SYMBOL);
1478                         break;
1479                 }
1480
1481                 connected = (newstatus == HERMES_LINKSTATUS_CONNECTED)
1482                         || (newstatus == HERMES_LINKSTATUS_AP_CHANGE)
1483                         || (newstatus == HERMES_LINKSTATUS_AP_IN_RANGE);
1484
1485                 if (connected)
1486                         netif_carrier_on(dev);
1487                 else if (!ignore_disconnect)
1488                         netif_carrier_off(dev);
1489
1490                 if (newstatus != priv->last_linkstatus) {
1491                         priv->last_linkstatus = newstatus;
1492                         print_linkstatus(dev, newstatus);
1493                         /* The info frame contains only one word which is the
1494                          * status (see hermes.h). The status is pretty boring
1495                          * in itself, that's why we export the new BSSID...
1496                          * Jean II */
1497                         schedule_work(&priv->wevent_work);
1498                 }
1499         }
1500         break;
1501         case HERMES_INQ_SCAN:
1502                 if (!priv->scan_inprogress && priv->bssid_fixed &&
1503                     priv->firmware_type == FIRMWARE_TYPE_INTERSIL) {
1504                         schedule_work(&priv->join_work);
1505                         break;
1506                 }
1507                 /* fall through */
1508         case HERMES_INQ_HOSTSCAN:
1509         case HERMES_INQ_HOSTSCAN_SYMBOL: {
1510                 /* Result of a scanning. Contains information about
1511                  * cells in the vicinity - Jean II */
1512                 union iwreq_data        wrqu;
1513                 unsigned char *buf;
1514
1515                 /* Sanity check */
1516                 if (len > 4096) {
1517                         printk(KERN_WARNING "%s: Scan results too large (%d bytes)\n",
1518                                dev->name, len);
1519                         break;
1520                 }
1521
1522                 /* We are a strict producer. If the previous scan results
1523                  * have not been consumed, we just have to drop this
1524                  * frame. We can't remove the previous results ourselves,
1525                  * that would be *very* racy... Jean II */
1526                 if (priv->scan_result != NULL) {
1527                         printk(KERN_WARNING "%s: Previous scan results not consumed, dropping info frame.\n", dev->name);
1528                         break;
1529                 }
1530
1531                 /* Allocate buffer for results */
1532                 buf = kmalloc(len, GFP_ATOMIC);
1533                 if (buf == NULL)
1534                         /* No memory, so can't printk()... */
1535                         break;
1536
1537                 /* Read scan data */
1538                 err = hermes_bap_pread(hw, IRQ_BAP, (void *) buf, len,
1539                                        infofid, sizeof(info));
1540                 if (err)
1541                         break;
1542
1543 #ifdef ORINOCO_DEBUG
1544                 {
1545                         int     i;
1546                         printk(KERN_DEBUG "Scan result [%02X", buf[0]);
1547                         for(i = 1; i < (len * 2); i++)
1548                                 printk(":%02X", buf[i]);
1549                         printk("]\n");
1550                 }
1551 #endif  /* ORINOCO_DEBUG */
1552
1553                 /* Allow the clients to access the results */
1554                 priv->scan_len = len;
1555                 priv->scan_result = buf;
1556
1557                 /* Send an empty event to user space.
1558                  * We don't send the received data on the event because
1559                  * it would require us to do complex transcoding, and
1560                  * we want to minimise the work done in the irq handler
1561                  * Use a request to extract the data - Jean II */
1562                 wrqu.data.length = 0;
1563                 wrqu.data.flags = 0;
1564                 wireless_send_event(dev, SIOCGIWSCAN, &wrqu, NULL);
1565         }
1566         break;
1567         case HERMES_INQ_SEC_STAT_AGERE:
1568                 /* Security status (Agere specific) */
1569                 /* Ignore this frame for now */
1570                 if (priv->firmware_type == FIRMWARE_TYPE_AGERE)
1571                         break;
1572                 /* fall through */
1573         default:
1574                 printk(KERN_DEBUG "%s: Unknown information frame received: "
1575                        "type 0x%04x, length %d\n", dev->name, type, len);
1576                 /* We don't actually do anything about it */
1577                 break;
1578         }
1579 }
1580
1581 static void __orinoco_ev_infdrop(struct net_device *dev, hermes_t *hw)
1582 {
1583         if (net_ratelimit())
1584                 printk(KERN_DEBUG "%s: Information frame lost.\n", dev->name);
1585 }
1586
1587 /********************************************************************/
1588 /* Internal hardware control routines                               */
1589 /********************************************************************/
1590
1591 int __orinoco_up(struct net_device *dev)
1592 {
1593         struct orinoco_private *priv = netdev_priv(dev);
1594         struct hermes *hw = &priv->hw;
1595         int err;
1596
1597         netif_carrier_off(dev); /* just to make sure */
1598
1599         err = __orinoco_program_rids(dev);
1600         if (err) {
1601                 printk(KERN_ERR "%s: Error %d configuring card\n",
1602                        dev->name, err);
1603                 return err;
1604         }
1605
1606         /* Fire things up again */
1607         hermes_set_irqmask(hw, ORINOCO_INTEN);
1608         err = hermes_enable_port(hw, 0);
1609         if (err) {
1610                 printk(KERN_ERR "%s: Error %d enabling MAC port\n",
1611                        dev->name, err);
1612                 return err;
1613         }
1614
1615         netif_start_queue(dev);
1616
1617         return 0;
1618 }
1619
1620 int __orinoco_down(struct net_device *dev)
1621 {
1622         struct orinoco_private *priv = netdev_priv(dev);
1623         struct hermes *hw = &priv->hw;
1624         int err;
1625
1626         netif_stop_queue(dev);
1627
1628         if (! priv->hw_unavailable) {
1629                 if (! priv->broken_disableport) {
1630                         err = hermes_disable_port(hw, 0);
1631                         if (err) {
1632                                 /* Some firmwares (e.g. Intersil 1.3.x) seem
1633                                  * to have problems disabling the port, oh
1634                                  * well, too bad. */
1635                                 printk(KERN_WARNING "%s: Error %d disabling MAC port\n",
1636                                        dev->name, err);
1637                                 priv->broken_disableport = 1;
1638                         }
1639                 }
1640                 hermes_set_irqmask(hw, 0);
1641                 hermes_write_regn(hw, EVACK, 0xffff);
1642         }
1643         
1644         /* firmware will have to reassociate */
1645         netif_carrier_off(dev);
1646         priv->last_linkstatus = 0xffff;
1647
1648         return 0;
1649 }
1650
1651 int orinoco_reinit_firmware(struct net_device *dev)
1652 {
1653         struct orinoco_private *priv = netdev_priv(dev);
1654         struct hermes *hw = &priv->hw;
1655         int err;
1656
1657         err = hermes_init(hw);
1658         if (err)
1659                 return err;
1660
1661         err = hermes_allocate(hw, priv->nicbuf_size, &priv->txfid);
1662         if (err == -EIO && priv->nicbuf_size > TX_NICBUF_SIZE_BUG) {
1663                 /* Try workaround for old Symbol firmware bug */
1664                 printk(KERN_WARNING "%s: firmware ALLOC bug detected "
1665                        "(old Symbol firmware?). Trying to work around... ",
1666                        dev->name);
1667                 
1668                 priv->nicbuf_size = TX_NICBUF_SIZE_BUG;
1669                 err = hermes_allocate(hw, priv->nicbuf_size, &priv->txfid);
1670                 if (err)
1671                         printk("failed!\n");
1672                 else
1673                         printk("ok.\n");
1674         }
1675
1676         return err;
1677 }
1678
1679 static int __orinoco_hw_set_bitrate(struct orinoco_private *priv)
1680 {
1681         hermes_t *hw = &priv->hw;
1682         int err = 0;
1683
1684         if (priv->bitratemode >= BITRATE_TABLE_SIZE) {
1685                 printk(KERN_ERR "%s: BUG: Invalid bitrate mode %d\n",
1686                        priv->ndev->name, priv->bitratemode);
1687                 return -EINVAL;
1688         }
1689
1690         switch (priv->firmware_type) {
1691         case FIRMWARE_TYPE_AGERE:
1692                 err = hermes_write_wordrec(hw, USER_BAP,
1693                                            HERMES_RID_CNFTXRATECONTROL,
1694                                            bitrate_table[priv->bitratemode].agere_txratectrl);
1695                 break;
1696         case FIRMWARE_TYPE_INTERSIL:
1697         case FIRMWARE_TYPE_SYMBOL:
1698                 err = hermes_write_wordrec(hw, USER_BAP,
1699                                            HERMES_RID_CNFTXRATECONTROL,
1700                                            bitrate_table[priv->bitratemode].intersil_txratectrl);
1701                 break;
1702         default:
1703                 BUG();
1704         }
1705
1706         return err;
1707 }
1708
1709 /* Set fixed AP address */
1710 static int __orinoco_hw_set_wap(struct orinoco_private *priv)
1711 {
1712         int roaming_flag;
1713         int err = 0;
1714         hermes_t *hw = &priv->hw;
1715
1716         switch (priv->firmware_type) {
1717         case FIRMWARE_TYPE_AGERE:
1718                 /* not supported */
1719                 break;
1720         case FIRMWARE_TYPE_INTERSIL:
1721                 if (priv->bssid_fixed)
1722                         roaming_flag = 2;
1723                 else
1724                         roaming_flag = 1;
1725
1726                 err = hermes_write_wordrec(hw, USER_BAP,
1727                                            HERMES_RID_CNFROAMINGMODE,
1728                                            roaming_flag);
1729                 break;
1730         case FIRMWARE_TYPE_SYMBOL:
1731                 err = HERMES_WRITE_RECORD(hw, USER_BAP,
1732                                           HERMES_RID_CNFMANDATORYBSSID_SYMBOL,
1733                                           &priv->desired_bssid);
1734                 break;
1735         }
1736         return err;
1737 }
1738
1739 /* Change the WEP keys and/or the current keys.  Can be called
1740  * either from __orinoco_hw_setup_wep() or directly from
1741  * orinoco_ioctl_setiwencode().  In the later case the association
1742  * with the AP is not broken (if the firmware can handle it),
1743  * which is needed for 802.1x implementations. */
1744 static int __orinoco_hw_setup_wepkeys(struct orinoco_private *priv)
1745 {
1746         hermes_t *hw = &priv->hw;
1747         int err = 0;
1748
1749         switch (priv->firmware_type) {
1750         case FIRMWARE_TYPE_AGERE:
1751                 err = HERMES_WRITE_RECORD(hw, USER_BAP,
1752                                           HERMES_RID_CNFWEPKEYS_AGERE,
1753                                           &priv->keys);
1754                 if (err)
1755                         return err;
1756                 err = hermes_write_wordrec(hw, USER_BAP,
1757                                            HERMES_RID_CNFTXKEY_AGERE,
1758                                            priv->tx_key);
1759                 if (err)
1760                         return err;
1761                 break;
1762         case FIRMWARE_TYPE_INTERSIL:
1763         case FIRMWARE_TYPE_SYMBOL:
1764                 {
1765                         int keylen;
1766                         int i;
1767
1768                         /* Force uniform key length to work around firmware bugs */
1769                         keylen = le16_to_cpu(priv->keys[priv->tx_key].len);
1770                         
1771                         if (keylen > LARGE_KEY_SIZE) {
1772                                 printk(KERN_ERR "%s: BUG: Key %d has oversize length %d.\n",
1773                                        priv->ndev->name, priv->tx_key, keylen);
1774                                 return -E2BIG;
1775                         }
1776
1777                         /* Write all 4 keys */
1778                         for(i = 0; i < ORINOCO_MAX_KEYS; i++) {
1779                                 err = hermes_write_ltv(hw, USER_BAP,
1780                                                        HERMES_RID_CNFDEFAULTKEY0 + i,
1781                                                        HERMES_BYTES_TO_RECLEN(keylen),
1782                                                        priv->keys[i].data);
1783                                 if (err)
1784                                         return err;
1785                         }
1786
1787                         /* Write the index of the key used in transmission */
1788                         err = hermes_write_wordrec(hw, USER_BAP,
1789                                                    HERMES_RID_CNFWEPDEFAULTKEYID,
1790                                                    priv->tx_key);
1791                         if (err)
1792                                 return err;
1793                 }
1794                 break;
1795         }
1796
1797         return 0;
1798 }
1799
1800 static int __orinoco_hw_setup_wep(struct orinoco_private *priv)
1801 {
1802         hermes_t *hw = &priv->hw;
1803         int err = 0;
1804         int master_wep_flag;
1805         int auth_flag;
1806
1807         if (priv->wep_on)
1808                 __orinoco_hw_setup_wepkeys(priv);
1809
1810         if (priv->wep_restrict)
1811                 auth_flag = HERMES_AUTH_SHARED_KEY;
1812         else
1813                 auth_flag = HERMES_AUTH_OPEN;
1814
1815         switch (priv->firmware_type) {
1816         case FIRMWARE_TYPE_AGERE: /* Agere style WEP */
1817                 if (priv->wep_on) {
1818                         /* Enable the shared-key authentication. */
1819                         err = hermes_write_wordrec(hw, USER_BAP,
1820                                                    HERMES_RID_CNFAUTHENTICATION_AGERE,
1821                                                    auth_flag);
1822                 }
1823                 err = hermes_write_wordrec(hw, USER_BAP,
1824                                            HERMES_RID_CNFWEPENABLED_AGERE,
1825                                            priv->wep_on);
1826                 if (err)
1827                         return err;
1828                 break;
1829
1830         case FIRMWARE_TYPE_INTERSIL: /* Intersil style WEP */
1831         case FIRMWARE_TYPE_SYMBOL: /* Symbol style WEP */
1832                 if (priv->wep_on) {
1833                         if (priv->wep_restrict ||
1834                             (priv->firmware_type == FIRMWARE_TYPE_SYMBOL))
1835                                 master_wep_flag = HERMES_WEP_PRIVACY_INVOKED |
1836                                                   HERMES_WEP_EXCL_UNENCRYPTED;
1837                         else
1838                                 master_wep_flag = HERMES_WEP_PRIVACY_INVOKED;
1839
1840                         err = hermes_write_wordrec(hw, USER_BAP,
1841                                                    HERMES_RID_CNFAUTHENTICATION,
1842                                                    auth_flag);
1843                         if (err)
1844                                 return err;
1845                 } else
1846                         master_wep_flag = 0;
1847
1848                 if (priv->iw_mode == IW_MODE_MONITOR)
1849                         master_wep_flag |= HERMES_WEP_HOST_DECRYPT;
1850
1851                 /* Master WEP setting : on/off */
1852                 err = hermes_write_wordrec(hw, USER_BAP,
1853                                            HERMES_RID_CNFWEPFLAGS_INTERSIL,
1854                                            master_wep_flag);
1855                 if (err)
1856                         return err;     
1857
1858                 break;
1859         }
1860
1861         return 0;
1862 }
1863
1864 static int __orinoco_program_rids(struct net_device *dev)
1865 {
1866         struct orinoco_private *priv = netdev_priv(dev);
1867         hermes_t *hw = &priv->hw;
1868         int err;
1869         struct hermes_idstring idbuf;
1870
1871         /* Set the MAC address */
1872         err = hermes_write_ltv(hw, USER_BAP, HERMES_RID_CNFOWNMACADDR,
1873                                HERMES_BYTES_TO_RECLEN(ETH_ALEN), dev->dev_addr);
1874         if (err) {
1875                 printk(KERN_ERR "%s: Error %d setting MAC address\n",
1876                        dev->name, err);
1877                 return err;
1878         }
1879
1880         /* Set up the link mode */
1881         err = hermes_write_wordrec(hw, USER_BAP, HERMES_RID_CNFPORTTYPE,
1882                                    priv->port_type);
1883         if (err) {
1884                 printk(KERN_ERR "%s: Error %d setting port type\n",
1885                        dev->name, err);
1886                 return err;
1887         }
1888         /* Set the channel/frequency */
1889         if (priv->channel != 0 && priv->iw_mode != IW_MODE_INFRA) {
1890                 err = hermes_write_wordrec(hw, USER_BAP,
1891                                            HERMES_RID_CNFOWNCHANNEL,
1892                                            priv->channel);
1893                 if (err) {
1894                         printk(KERN_ERR "%s: Error %d setting channel %d\n",
1895                                dev->name, err, priv->channel);
1896                         return err;
1897                 }
1898         }
1899
1900         if (priv->has_ibss) {
1901                 u16 createibss;
1902
1903                 if ((strlen(priv->desired_essid) == 0) && (priv->createibss)) {
1904                         printk(KERN_WARNING "%s: This firmware requires an "
1905                                "ESSID in IBSS-Ad-Hoc mode.\n", dev->name);
1906                         /* With wvlan_cs, in this case, we would crash.
1907                          * hopefully, this driver will behave better...
1908                          * Jean II */
1909                         createibss = 0;
1910                 } else {
1911                         createibss = priv->createibss;
1912                 }
1913                 
1914                 err = hermes_write_wordrec(hw, USER_BAP,
1915                                            HERMES_RID_CNFCREATEIBSS,
1916                                            createibss);
1917                 if (err) {
1918                         printk(KERN_ERR "%s: Error %d setting CREATEIBSS\n",
1919                                dev->name, err);
1920                         return err;
1921                 }
1922         }
1923
1924         /* Set the desired BSSID */
1925         err = __orinoco_hw_set_wap(priv);
1926         if (err) {
1927                 printk(KERN_ERR "%s: Error %d setting AP address\n",
1928                        dev->name, err);
1929                 return err;
1930         }
1931         /* Set the desired ESSID */
1932         idbuf.len = cpu_to_le16(strlen(priv->desired_essid));
1933         memcpy(&idbuf.val, priv->desired_essid, sizeof(idbuf.val));
1934         /* WinXP wants partner to configure OWNSSID even in IBSS mode. (jimc) */
1935         err = hermes_write_ltv(hw, USER_BAP, HERMES_RID_CNFOWNSSID,
1936                                HERMES_BYTES_TO_RECLEN(strlen(priv->desired_essid)+2),
1937                                &idbuf);
1938         if (err) {
1939                 printk(KERN_ERR "%s: Error %d setting OWNSSID\n",
1940                        dev->name, err);
1941                 return err;
1942         }
1943         err = hermes_write_ltv(hw, USER_BAP, HERMES_RID_CNFDESIREDSSID,
1944                                HERMES_BYTES_TO_RECLEN(strlen(priv->desired_essid)+2),
1945                                &idbuf);
1946         if (err) {
1947                 printk(KERN_ERR "%s: Error %d setting DESIREDSSID\n",
1948                        dev->name, err);
1949                 return err;
1950         }
1951
1952         /* Set the station name */
1953         idbuf.len = cpu_to_le16(strlen(priv->nick));
1954         memcpy(&idbuf.val, priv->nick, sizeof(idbuf.val));
1955         err = hermes_write_ltv(hw, USER_BAP, HERMES_RID_CNFOWNNAME,
1956                                HERMES_BYTES_TO_RECLEN(strlen(priv->nick)+2),
1957                                &idbuf);
1958         if (err) {
1959                 printk(KERN_ERR "%s: Error %d setting nickname\n",
1960                        dev->name, err);
1961                 return err;
1962         }
1963
1964         /* Set AP density */
1965         if (priv->has_sensitivity) {
1966                 err = hermes_write_wordrec(hw, USER_BAP,
1967                                            HERMES_RID_CNFSYSTEMSCALE,
1968                                            priv->ap_density);
1969                 if (err) {
1970                         printk(KERN_WARNING "%s: Error %d setting SYSTEMSCALE.  "
1971                                "Disabling sensitivity control\n",
1972                                dev->name, err);
1973
1974                         priv->has_sensitivity = 0;
1975                 }
1976         }
1977
1978         /* Set RTS threshold */
1979         err = hermes_write_wordrec(hw, USER_BAP, HERMES_RID_CNFRTSTHRESHOLD,
1980                                    priv->rts_thresh);
1981         if (err) {
1982                 printk(KERN_ERR "%s: Error %d setting RTS threshold\n",
1983                        dev->name, err);
1984                 return err;
1985         }
1986
1987         /* Set fragmentation threshold or MWO robustness */
1988         if (priv->has_mwo)
1989                 err = hermes_write_wordrec(hw, USER_BAP,
1990                                            HERMES_RID_CNFMWOROBUST_AGERE,
1991                                            priv->mwo_robust);
1992         else
1993                 err = hermes_write_wordrec(hw, USER_BAP,
1994                                            HERMES_RID_CNFFRAGMENTATIONTHRESHOLD,
1995                                            priv->frag_thresh);
1996         if (err) {
1997                 printk(KERN_ERR "%s: Error %d setting fragmentation\n",
1998                        dev->name, err);
1999                 return err;
2000         }
2001
2002         /* Set bitrate */
2003         err = __orinoco_hw_set_bitrate(priv);
2004         if (err) {
2005                 printk(KERN_ERR "%s: Error %d setting bitrate\n",
2006                        dev->name, err);
2007                 return err;
2008         }
2009
2010         /* Set power management */
2011         if (priv->has_pm) {
2012                 err = hermes_write_wordrec(hw, USER_BAP,
2013                                            HERMES_RID_CNFPMENABLED,
2014                                            priv->pm_on);
2015                 if (err) {
2016                         printk(KERN_ERR "%s: Error %d setting up PM\n",
2017                                dev->name, err);
2018                         return err;
2019                 }
2020
2021                 err = hermes_write_wordrec(hw, USER_BAP,
2022                                            HERMES_RID_CNFMULTICASTRECEIVE,
2023                                            priv->pm_mcast);
2024                 if (err) {
2025                         printk(KERN_ERR "%s: Error %d setting up PM\n",
2026                                dev->name, err);
2027                         return err;
2028                 }
2029                 err = hermes_write_wordrec(hw, USER_BAP,
2030                                            HERMES_RID_CNFMAXSLEEPDURATION,
2031                                            priv->pm_period);
2032                 if (err) {
2033                         printk(KERN_ERR "%s: Error %d setting up PM\n",
2034                                dev->name, err);
2035                         return err;
2036                 }
2037                 err = hermes_write_wordrec(hw, USER_BAP,
2038                                            HERMES_RID_CNFPMHOLDOVERDURATION,
2039                                            priv->pm_timeout);
2040                 if (err) {
2041                         printk(KERN_ERR "%s: Error %d setting up PM\n",
2042                                dev->name, err);
2043                         return err;
2044                 }
2045         }
2046
2047         /* Set preamble - only for Symbol so far... */
2048         if (priv->has_preamble) {
2049                 err = hermes_write_wordrec(hw, USER_BAP,
2050                                            HERMES_RID_CNFPREAMBLE_SYMBOL,
2051                                            priv->preamble);
2052                 if (err) {
2053                         printk(KERN_ERR "%s: Error %d setting preamble\n",
2054                                dev->name, err);
2055                         return err;
2056                 }
2057         }
2058
2059         /* Set up encryption */
2060         if (priv->has_wep) {
2061                 err = __orinoco_hw_setup_wep(priv);
2062                 if (err) {
2063                         printk(KERN_ERR "%s: Error %d activating WEP\n",
2064                                dev->name, err);
2065                         return err;
2066                 }
2067         }
2068
2069         /* Set promiscuity / multicast*/
2070         priv->promiscuous = 0;
2071         priv->mc_count = 0;
2072         __orinoco_set_multicast_list(dev); /* FIXME: what about the xmit_lock */
2073
2074         return 0;
2075 }
2076
2077 /* FIXME: return int? */
2078 static void
2079 __orinoco_set_multicast_list(struct net_device *dev)
2080 {
2081         struct orinoco_private *priv = netdev_priv(dev);
2082         hermes_t *hw = &priv->hw;
2083         int err = 0;
2084         int promisc, mc_count;
2085
2086         /* The Hermes doesn't seem to have an allmulti mode, so we go
2087          * into promiscuous mode and let the upper levels deal. */
2088         if ( (dev->flags & IFF_PROMISC) || (dev->flags & IFF_ALLMULTI) ||
2089              (dev->mc_count > MAX_MULTICAST(priv)) ) {
2090                 promisc = 1;
2091                 mc_count = 0;
2092         } else {
2093                 promisc = 0;
2094                 mc_count = dev->mc_count;
2095         }
2096
2097         if (promisc != priv->promiscuous) {
2098                 err = hermes_write_wordrec(hw, USER_BAP,
2099                                            HERMES_RID_CNFPROMISCUOUSMODE,
2100                                            promisc);
2101                 if (err) {
2102                         printk(KERN_ERR "%s: Error %d setting PROMISCUOUSMODE to 1.\n",
2103                                dev->name, err);
2104                 } else 
2105                         priv->promiscuous = promisc;
2106         }
2107
2108         if (! promisc && (mc_count || priv->mc_count) ) {
2109                 struct dev_mc_list *p = dev->mc_list;
2110                 struct hermes_multicast mclist;
2111                 int i;
2112
2113                 for (i = 0; i < mc_count; i++) {
2114                         /* paranoia: is list shorter than mc_count? */
2115                         BUG_ON(! p);
2116                         /* paranoia: bad address size in list? */
2117                         BUG_ON(p->dmi_addrlen != ETH_ALEN);
2118                         
2119                         memcpy(mclist.addr[i], p->dmi_addr, ETH_ALEN);
2120                         p = p->next;
2121                 }
2122                 
2123                 if (p)
2124                         printk(KERN_WARNING "%s: Multicast list is "
2125                                "longer than mc_count\n", dev->name);
2126
2127                 err = hermes_write_ltv(hw, USER_BAP, HERMES_RID_CNFGROUPADDRESSES,
2128                                        HERMES_BYTES_TO_RECLEN(priv->mc_count * ETH_ALEN),
2129                                        &mclist);
2130                 if (err)
2131                         printk(KERN_ERR "%s: Error %d setting multicast list.\n",
2132                                dev->name, err);
2133                 else
2134                         priv->mc_count = mc_count;
2135         }
2136
2137         /* Since we can set the promiscuous flag when it wasn't asked
2138            for, make sure the net_device knows about it. */
2139         if (priv->promiscuous)
2140                 dev->flags |= IFF_PROMISC;
2141         else
2142                 dev->flags &= ~IFF_PROMISC;
2143 }
2144
2145 /* This must be called from user context, without locks held - use
2146  * schedule_work() */
2147 static void orinoco_reset(struct net_device *dev)
2148 {
2149         struct orinoco_private *priv = netdev_priv(dev);
2150         struct hermes *hw = &priv->hw;
2151         int err;
2152         unsigned long flags;
2153
2154         if (orinoco_lock(priv, &flags) != 0)
2155                 /* When the hardware becomes available again, whatever
2156                  * detects that is responsible for re-initializing
2157                  * it. So no need for anything further */
2158                 return;
2159
2160         netif_stop_queue(dev);
2161
2162         /* Shut off interrupts.  Depending on what state the hardware
2163          * is in, this might not work, but we'll try anyway */
2164         hermes_set_irqmask(hw, 0);
2165         hermes_write_regn(hw, EVACK, 0xffff);
2166
2167         priv->hw_unavailable++;
2168         priv->last_linkstatus = 0xffff; /* firmware will have to reassociate */
2169         netif_carrier_off(dev);
2170
2171         orinoco_unlock(priv, &flags);
2172
2173         /* Scanning support: Cleanup of driver struct */
2174         kfree(priv->scan_result);
2175         priv->scan_result = NULL;
2176         priv->scan_inprogress = 0;
2177
2178         if (priv->hard_reset) {
2179                 err = (*priv->hard_reset)(priv);
2180                 if (err) {
2181                         printk(KERN_ERR "%s: orinoco_reset: Error %d "
2182                                "performing hard reset\n", dev->name, err);
2183                         goto disable;
2184                 }
2185         }
2186
2187         err = orinoco_reinit_firmware(dev);
2188         if (err) {
2189                 printk(KERN_ERR "%s: orinoco_reset: Error %d re-initializing firmware\n",
2190                        dev->name, err);
2191                 goto disable;
2192         }
2193
2194         spin_lock_irq(&priv->lock); /* This has to be called from user context */
2195
2196         priv->hw_unavailable--;
2197
2198         /* priv->open or priv->hw_unavailable might have changed while
2199          * we dropped the lock */
2200         if (priv->open && (! priv->hw_unavailable)) {
2201                 err = __orinoco_up(dev);
2202                 if (err) {
2203                         printk(KERN_ERR "%s: orinoco_reset: Error %d reenabling card\n",
2204                                dev->name, err);
2205                 } else
2206                         dev->trans_start = jiffies;
2207         }
2208
2209         spin_unlock_irq(&priv->lock);
2210
2211         return;
2212  disable:
2213         hermes_set_irqmask(hw, 0);
2214         netif_device_detach(dev);
2215         printk(KERN_ERR "%s: Device has been disabled!\n", dev->name);
2216 }
2217
2218 /********************************************************************/
2219 /* Interrupt handler                                                */
2220 /********************************************************************/
2221
2222 static void __orinoco_ev_tick(struct net_device *dev, hermes_t *hw)
2223 {
2224         printk(KERN_DEBUG "%s: TICK\n", dev->name);
2225 }
2226
2227 static void __orinoco_ev_wterr(struct net_device *dev, hermes_t *hw)
2228 {
2229         /* This seems to happen a fair bit under load, but ignoring it
2230            seems to work fine...*/
2231         printk(KERN_DEBUG "%s: MAC controller error (WTERR). Ignoring.\n",
2232                dev->name);
2233 }
2234
2235 irqreturn_t orinoco_interrupt(int irq, void *dev_id, struct pt_regs *regs)
2236 {
2237         struct net_device *dev = (struct net_device *)dev_id;
2238         struct orinoco_private *priv = netdev_priv(dev);
2239         hermes_t *hw = &priv->hw;
2240         int count = MAX_IRQLOOPS_PER_IRQ;
2241         u16 evstat, events;
2242         /* These are used to detect a runaway interrupt situation */
2243         /* If we get more than MAX_IRQLOOPS_PER_JIFFY iterations in a jiffy,
2244          * we panic and shut down the hardware */
2245         static int last_irq_jiffy = 0; /* jiffies value the last time
2246                                         * we were called */
2247         static int loops_this_jiffy = 0;
2248         unsigned long flags;
2249
2250         if (orinoco_lock(priv, &flags) != 0) {
2251                 /* If hw is unavailable - we don't know if the irq was
2252                  * for us or not */
2253                 return IRQ_HANDLED;
2254         }
2255
2256         evstat = hermes_read_regn(hw, EVSTAT);
2257         events = evstat & hw->inten;
2258         if (! events) {
2259                 orinoco_unlock(priv, &flags);
2260                 return IRQ_NONE;
2261         }
2262         
2263         if (jiffies != last_irq_jiffy)
2264                 loops_this_jiffy = 0;
2265         last_irq_jiffy = jiffies;
2266
2267         while (events && count--) {
2268                 if (++loops_this_jiffy > MAX_IRQLOOPS_PER_JIFFY) {
2269                         printk(KERN_WARNING "%s: IRQ handler is looping too "
2270                                "much! Resetting.\n", dev->name);
2271                         /* Disable interrupts for now */
2272                         hermes_set_irqmask(hw, 0);
2273                         schedule_work(&priv->reset_work);
2274                         break;
2275                 }
2276
2277                 /* Check the card hasn't been removed */
2278                 if (! hermes_present(hw)) {
2279                         DEBUG(0, "orinoco_interrupt(): card removed\n");
2280                         break;
2281                 }
2282
2283                 if (events & HERMES_EV_TICK)
2284                         __orinoco_ev_tick(dev, hw);
2285                 if (events & HERMES_EV_WTERR)
2286                         __orinoco_ev_wterr(dev, hw);
2287                 if (events & HERMES_EV_INFDROP)
2288                         __orinoco_ev_infdrop(dev, hw);
2289                 if (events & HERMES_EV_INFO)
2290                         __orinoco_ev_info(dev, hw);
2291                 if (events & HERMES_EV_RX)
2292                         __orinoco_ev_rx(dev, hw);
2293                 if (events & HERMES_EV_TXEXC)
2294                         __orinoco_ev_txexc(dev, hw);
2295                 if (events & HERMES_EV_TX)
2296                         __orinoco_ev_tx(dev, hw);
2297                 if (events & HERMES_EV_ALLOC)
2298                         __orinoco_ev_alloc(dev, hw);
2299                 
2300                 hermes_write_regn(hw, EVACK, evstat);
2301
2302                 evstat = hermes_read_regn(hw, EVSTAT);
2303                 events = evstat & hw->inten;
2304         };
2305
2306         orinoco_unlock(priv, &flags);
2307         return IRQ_HANDLED;
2308 }
2309
2310 /********************************************************************/
2311 /* Initialization                                                   */
2312 /********************************************************************/
2313
2314 struct comp_id {
2315         u16 id, variant, major, minor;
2316 } __attribute__ ((packed));
2317
2318 static inline fwtype_t determine_firmware_type(struct comp_id *nic_id)
2319 {
2320         if (nic_id->id < 0x8000)
2321                 return FIRMWARE_TYPE_AGERE;
2322         else if (nic_id->id == 0x8000 && nic_id->major == 0)
2323                 return FIRMWARE_TYPE_SYMBOL;
2324         else
2325                 return FIRMWARE_TYPE_INTERSIL;
2326 }
2327
2328 /* Set priv->firmware type, determine firmware properties */
2329 static int determine_firmware(struct net_device *dev)
2330 {
2331         struct orinoco_private *priv = netdev_priv(dev);
2332         hermes_t *hw = &priv->hw;
2333         int err;
2334         struct comp_id nic_id, sta_id;
2335         unsigned int firmver;
2336         char tmp[SYMBOL_MAX_VER_LEN+1];
2337
2338         /* Get the hardware version */
2339         err = HERMES_READ_RECORD(hw, USER_BAP, HERMES_RID_NICID, &nic_id);
2340         if (err) {
2341                 printk(KERN_ERR "%s: Cannot read hardware identity: error %d\n",
2342                        dev->name, err);
2343                 return err;
2344         }
2345
2346         le16_to_cpus(&nic_id.id);
2347         le16_to_cpus(&nic_id.variant);
2348         le16_to_cpus(&nic_id.major);
2349         le16_to_cpus(&nic_id.minor);
2350         printk(KERN_DEBUG "%s: Hardware identity %04x:%04x:%04x:%04x\n",
2351                dev->name, nic_id.id, nic_id.variant,
2352                nic_id.major, nic_id.minor);
2353
2354         priv->firmware_type = determine_firmware_type(&nic_id);
2355
2356         /* Get the firmware version */
2357         err = HERMES_READ_RECORD(hw, USER_BAP, HERMES_RID_STAID, &sta_id);
2358         if (err) {
2359                 printk(KERN_ERR "%s: Cannot read station identity: error %d\n",
2360                        dev->name, err);
2361                 return err;
2362         }
2363
2364         le16_to_cpus(&sta_id.id);
2365         le16_to_cpus(&sta_id.variant);
2366         le16_to_cpus(&sta_id.major);
2367         le16_to_cpus(&sta_id.minor);
2368         printk(KERN_DEBUG "%s: Station identity  %04x:%04x:%04x:%04x\n",
2369                dev->name, sta_id.id, sta_id.variant,
2370                sta_id.major, sta_id.minor);
2371
2372         switch (sta_id.id) {
2373         case 0x15:
2374                 printk(KERN_ERR "%s: Primary firmware is active\n",
2375                        dev->name);
2376                 return -ENODEV;
2377         case 0x14b:
2378                 printk(KERN_ERR "%s: Tertiary firmware is active\n",
2379                        dev->name);
2380                 return -ENODEV;
2381         case 0x1f:      /* Intersil, Agere, Symbol Spectrum24 */
2382         case 0x21:      /* Symbol Spectrum24 Trilogy */
2383                 break;
2384         default:
2385                 printk(KERN_NOTICE "%s: Unknown station ID, please report\n",
2386                        dev->name);
2387                 break;
2388         }
2389
2390         /* Default capabilities */
2391         priv->has_sensitivity = 1;
2392         priv->has_mwo = 0;
2393         priv->has_preamble = 0;
2394         priv->has_port3 = 1;
2395         priv->has_ibss = 1;
2396         priv->has_wep = 0;
2397         priv->has_big_wep = 0;
2398
2399         /* Determine capabilities from the firmware version */
2400         switch (priv->firmware_type) {
2401         case FIRMWARE_TYPE_AGERE:
2402                 /* Lucent Wavelan IEEE, Lucent Orinoco, Cabletron RoamAbout,
2403                    ELSA, Melco, HP, IBM, Dell 1150, Compaq 110/210 */
2404                 snprintf(priv->fw_name, sizeof(priv->fw_name) - 1,
2405                          "Lucent/Agere %d.%02d", sta_id.major, sta_id.minor);
2406
2407                 firmver = ((unsigned long)sta_id.major << 16) | sta_id.minor;
2408
2409                 priv->has_ibss = (firmver >= 0x60006);
2410                 priv->has_wep = (firmver >= 0x40020);
2411                 priv->has_big_wep = 1; /* FIXME: this is wrong - how do we tell
2412                                           Gold cards from the others? */
2413                 priv->has_mwo = (firmver >= 0x60000);
2414                 priv->has_pm = (firmver >= 0x40020); /* Don't work in 7.52 ? */
2415                 priv->ibss_port = 1;
2416                 priv->has_hostscan = (firmver >= 0x8000a);
2417
2418                 /* Tested with Agere firmware :
2419                  *      1.16 ; 4.08 ; 4.52 ; 6.04 ; 6.16 ; 7.28 => Jean II
2420                  * Tested CableTron firmware : 4.32 => Anton */
2421                 break;
2422         case FIRMWARE_TYPE_SYMBOL:
2423                 /* Symbol , 3Com AirConnect, Intel, Ericsson WLAN */
2424                 /* Intel MAC : 00:02:B3:* */
2425                 /* 3Com MAC : 00:50:DA:* */
2426                 memset(tmp, 0, sizeof(tmp));
2427                 /* Get the Symbol firmware version */
2428                 err = hermes_read_ltv(hw, USER_BAP,
2429                                       HERMES_RID_SECONDARYVERSION_SYMBOL,
2430                                       SYMBOL_MAX_VER_LEN, NULL, &tmp);
2431                 if (err) {
2432                         printk(KERN_WARNING
2433                                "%s: Error %d reading Symbol firmware info. Wildly guessing capabilities...\n",
2434                                dev->name, err);
2435                         firmver = 0;
2436                         tmp[0] = '\0';
2437                 } else {
2438                         /* The firmware revision is a string, the format is
2439                          * something like : "V2.20-01".
2440                          * Quick and dirty parsing... - Jean II
2441                          */
2442                         firmver = ((tmp[1] - '0') << 16) | ((tmp[3] - '0') << 12)
2443                                 | ((tmp[4] - '0') << 8) | ((tmp[6] - '0') << 4)
2444                                 | (tmp[7] - '0');
2445
2446                         tmp[SYMBOL_MAX_VER_LEN] = '\0';
2447                 }
2448
2449                 snprintf(priv->fw_name, sizeof(priv->fw_name) - 1,
2450                          "Symbol %s", tmp);
2451
2452                 priv->has_ibss = (firmver >= 0x20000);
2453                 priv->has_wep = (firmver >= 0x15012);
2454                 priv->has_big_wep = (firmver >= 0x20000);
2455                 priv->has_pm = (firmver >= 0x20000 && firmver < 0x22000) || 
2456                                (firmver >= 0x29000 && firmver < 0x30000) ||
2457                                firmver >= 0x31000;
2458                 priv->has_preamble = (firmver >= 0x20000);
2459                 priv->ibss_port = 4;
2460                 priv->broken_disableport = (firmver == 0x25013) ||
2461                                            (firmver >= 0x30000 && firmver <= 0x31000);
2462                 priv->has_hostscan = (firmver >= 0x31001) ||
2463                                      (firmver >= 0x29057 && firmver < 0x30000);
2464                 /* Tested with Intel firmware : 0x20015 => Jean II */
2465                 /* Tested with 3Com firmware : 0x15012 & 0x22001 => Jean II */
2466                 break;
2467         case FIRMWARE_TYPE_INTERSIL:
2468                 /* D-Link, Linksys, Adtron, ZoomAir, and many others...
2469                  * Samsung, Compaq 100/200 and Proxim are slightly
2470                  * different and less well tested */
2471                 /* D-Link MAC : 00:40:05:* */
2472                 /* Addtron MAC : 00:90:D1:* */
2473                 snprintf(priv->fw_name, sizeof(priv->fw_name) - 1,
2474                          "Intersil %d.%d.%d", sta_id.major, sta_id.minor,
2475                          sta_id.variant);
2476
2477                 firmver = ((unsigned long)sta_id.major << 16) |
2478                         ((unsigned long)sta_id.minor << 8) | sta_id.variant;
2479
2480                 priv->has_ibss = (firmver >= 0x000700); /* FIXME */
2481                 priv->has_big_wep = priv->has_wep = (firmver >= 0x000800);
2482                 priv->has_pm = (firmver >= 0x000700);
2483                 priv->has_hostscan = (firmver >= 0x010301);
2484
2485                 if (firmver >= 0x000800)
2486                         priv->ibss_port = 0;
2487                 else {
2488                         printk(KERN_NOTICE "%s: Intersil firmware earlier "
2489                                "than v0.8.x - several features not supported\n",
2490                                dev->name);
2491                         priv->ibss_port = 1;
2492                 }
2493                 break;
2494         }
2495         printk(KERN_DEBUG "%s: Firmware determined as %s\n", dev->name,
2496                priv->fw_name);
2497
2498         return 0;
2499 }
2500
2501 static int orinoco_init(struct net_device *dev)
2502 {
2503         struct orinoco_private *priv = netdev_priv(dev);
2504         hermes_t *hw = &priv->hw;
2505         int err = 0;
2506         struct hermes_idstring nickbuf;
2507         u16 reclen;
2508         int len;
2509
2510         TRACE_ENTER(dev->name);
2511
2512         /* No need to lock, the hw_unavailable flag is already set in
2513          * alloc_orinocodev() */
2514         priv->nicbuf_size = IEEE802_11_FRAME_LEN + ETH_HLEN;
2515
2516         /* Initialize the firmware */
2517         err = orinoco_reinit_firmware(dev);
2518         if (err != 0) {
2519                 printk(KERN_ERR "%s: failed to initialize firmware (err = %d)\n",
2520                        dev->name, err);
2521                 goto out;
2522         }
2523
2524         err = determine_firmware(dev);
2525         if (err != 0) {
2526                 printk(KERN_ERR "%s: Incompatible firmware, aborting\n",
2527                        dev->name);
2528                 goto out;
2529         }
2530
2531         if (priv->has_port3)
2532                 printk(KERN_DEBUG "%s: Ad-hoc demo mode supported\n", dev->name);
2533         if (priv->has_ibss)
2534                 printk(KERN_DEBUG "%s: IEEE standard IBSS ad-hoc mode supported\n",
2535                        dev->name);
2536         if (priv->has_wep) {
2537                 printk(KERN_DEBUG "%s: WEP supported, ", dev->name);
2538                 if (priv->has_big_wep)
2539                         printk("104-bit key\n");
2540                 else
2541                         printk("40-bit key\n");
2542         }
2543
2544         /* Get the MAC address */
2545         err = hermes_read_ltv(hw, USER_BAP, HERMES_RID_CNFOWNMACADDR,
2546                               ETH_ALEN, NULL, dev->dev_addr);
2547         if (err) {
2548                 printk(KERN_WARNING "%s: failed to read MAC address!\n",
2549                        dev->name);
2550                 goto out;
2551         }
2552
2553         printk(KERN_DEBUG "%s: MAC address %02X:%02X:%02X:%02X:%02X:%02X\n",
2554                dev->name, dev->dev_addr[0], dev->dev_addr[1],
2555                dev->dev_addr[2], dev->dev_addr[3], dev->dev_addr[4],
2556                dev->dev_addr[5]);
2557
2558         /* Get the station name */
2559         err = hermes_read_ltv(hw, USER_BAP, HERMES_RID_CNFOWNNAME,
2560                               sizeof(nickbuf), &reclen, &nickbuf);
2561         if (err) {
2562                 printk(KERN_ERR "%s: failed to read station name\n",
2563                        dev->name);
2564                 goto out;
2565         }
2566         if (nickbuf.len)
2567                 len = min(IW_ESSID_MAX_SIZE, (int)le16_to_cpu(nickbuf.len));
2568         else
2569                 len = min(IW_ESSID_MAX_SIZE, 2 * reclen);
2570         memcpy(priv->nick, &nickbuf.val, len);
2571         priv->nick[len] = '\0';
2572
2573         printk(KERN_DEBUG "%s: Station name \"%s\"\n", dev->name, priv->nick);
2574
2575         /* Get allowed channels */
2576         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CHANNELLIST,
2577                                   &priv->channel_mask);
2578         if (err) {
2579                 printk(KERN_ERR "%s: failed to read channel list!\n",
2580                        dev->name);
2581                 goto out;
2582         }
2583
2584         /* Get initial AP density */
2585         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CNFSYSTEMSCALE,
2586                                   &priv->ap_density);
2587         if (err || priv->ap_density < 1 || priv->ap_density > 3) {
2588                 priv->has_sensitivity = 0;
2589         }
2590
2591         /* Get initial RTS threshold */
2592         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CNFRTSTHRESHOLD,
2593                                   &priv->rts_thresh);
2594         if (err) {
2595                 printk(KERN_ERR "%s: failed to read RTS threshold!\n",
2596                        dev->name);
2597                 goto out;
2598         }
2599
2600         /* Get initial fragmentation settings */
2601         if (priv->has_mwo)
2602                 err = hermes_read_wordrec(hw, USER_BAP,
2603                                           HERMES_RID_CNFMWOROBUST_AGERE,
2604                                           &priv->mwo_robust);
2605         else
2606                 err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CNFFRAGMENTATIONTHRESHOLD,
2607                                           &priv->frag_thresh);
2608         if (err) {
2609                 printk(KERN_ERR "%s: failed to read fragmentation settings!\n",
2610                        dev->name);
2611                 goto out;
2612         }
2613
2614         /* Power management setup */
2615         if (priv->has_pm) {
2616                 priv->pm_on = 0;
2617                 priv->pm_mcast = 1;
2618                 err = hermes_read_wordrec(hw, USER_BAP,
2619                                           HERMES_RID_CNFMAXSLEEPDURATION,
2620                                           &priv->pm_period);
2621                 if (err) {
2622                         printk(KERN_ERR "%s: failed to read power management period!\n",
2623                                dev->name);
2624                         goto out;
2625                 }
2626                 err = hermes_read_wordrec(hw, USER_BAP,
2627                                           HERMES_RID_CNFPMHOLDOVERDURATION,
2628                                           &priv->pm_timeout);
2629                 if (err) {
2630                         printk(KERN_ERR "%s: failed to read power management timeout!\n",
2631                                dev->name);
2632                         goto out;
2633                 }
2634         }
2635
2636         /* Preamble setup */
2637         if (priv->has_preamble) {
2638                 err = hermes_read_wordrec(hw, USER_BAP,
2639                                           HERMES_RID_CNFPREAMBLE_SYMBOL,
2640                                           &priv->preamble);
2641                 if (err)
2642                         goto out;
2643         }
2644                 
2645         /* Set up the default configuration */
2646         priv->iw_mode = IW_MODE_INFRA;
2647         /* By default use IEEE/IBSS ad-hoc mode if we have it */
2648         priv->prefer_port3 = priv->has_port3 && (! priv->has_ibss);
2649         set_port_type(priv);
2650         priv->channel = 0; /* use firmware default */
2651
2652         priv->promiscuous = 0;
2653         priv->wep_on = 0;
2654         priv->tx_key = 0;
2655
2656         /* Make the hardware available, as long as it hasn't been
2657          * removed elsewhere (e.g. by PCMCIA hot unplug) */
2658         spin_lock_irq(&priv->lock);
2659         priv->hw_unavailable--;
2660         spin_unlock_irq(&priv->lock);
2661
2662         printk(KERN_DEBUG "%s: ready\n", dev->name);
2663
2664  out:
2665         TRACE_EXIT(dev->name);
2666         return err;
2667 }
2668
2669 struct net_device *alloc_orinocodev(int sizeof_card,
2670                                     int (*hard_reset)(struct orinoco_private *))
2671 {
2672         struct net_device *dev;
2673         struct orinoco_private *priv;
2674
2675         dev = alloc_etherdev(sizeof(struct orinoco_private) + sizeof_card);
2676         if (! dev)
2677                 return NULL;
2678         priv = netdev_priv(dev);
2679         priv->ndev = dev;
2680         if (sizeof_card)
2681                 priv->card = (void *)((unsigned long)priv
2682                                       + sizeof(struct orinoco_private));
2683         else
2684                 priv->card = NULL;
2685
2686         /* Setup / override net_device fields */
2687         dev->init = orinoco_init;
2688         dev->hard_start_xmit = orinoco_xmit;
2689         dev->tx_timeout = orinoco_tx_timeout;
2690         dev->watchdog_timeo = HZ; /* 1 second timeout */
2691         dev->get_stats = orinoco_get_stats;
2692         dev->ethtool_ops = &orinoco_ethtool_ops;
2693         dev->get_wireless_stats = orinoco_get_wireless_stats;
2694         dev->wireless_handlers = (struct iw_handler_def *)&orinoco_handler_def;
2695         dev->change_mtu = orinoco_change_mtu;
2696         dev->set_multicast_list = orinoco_set_multicast_list;
2697         /* we use the default eth_mac_addr for setting the MAC addr */
2698
2699         /* Set up default callbacks */
2700         dev->open = orinoco_open;
2701         dev->stop = orinoco_stop;
2702         priv->hard_reset = hard_reset;
2703
2704         spin_lock_init(&priv->lock);
2705         priv->open = 0;
2706         priv->hw_unavailable = 1; /* orinoco_init() must clear this
2707                                    * before anything else touches the
2708                                    * hardware */
2709         INIT_WORK(&priv->reset_work, (void (*)(void *))orinoco_reset, dev);
2710         INIT_WORK(&priv->join_work, (void (*)(void *))orinoco_join_ap, dev);
2711         INIT_WORK(&priv->wevent_work, (void (*)(void *))orinoco_send_wevents, dev);
2712
2713         netif_carrier_off(dev);
2714         priv->last_linkstatus = 0xffff;
2715
2716         return dev;
2717
2718 }
2719
2720 void free_orinocodev(struct net_device *dev)
2721 {
2722         struct orinoco_private *priv = netdev_priv(dev);
2723
2724         kfree(priv->scan_result);
2725         free_netdev(dev);
2726 }
2727
2728 /********************************************************************/
2729 /* Wireless extensions                                              */
2730 /********************************************************************/
2731
2732 static int orinoco_hw_get_essid(struct orinoco_private *priv, int *active,
2733                                 char buf[IW_ESSID_MAX_SIZE+1])
2734 {
2735         hermes_t *hw = &priv->hw;
2736         int err = 0;
2737         struct hermes_idstring essidbuf;
2738         char *p = (char *)(&essidbuf.val);
2739         int len;
2740         unsigned long flags;
2741
2742         if (orinoco_lock(priv, &flags) != 0)
2743                 return -EBUSY;
2744
2745         if (strlen(priv->desired_essid) > 0) {
2746                 /* We read the desired SSID from the hardware rather
2747                    than from priv->desired_essid, just in case the
2748                    firmware is allowed to change it on us. I'm not
2749                    sure about this */
2750                 /* My guess is that the OWNSSID should always be whatever
2751                  * we set to the card, whereas CURRENT_SSID is the one that
2752                  * may change... - Jean II */
2753                 u16 rid;
2754
2755                 *active = 1;
2756
2757                 rid = (priv->port_type == 3) ? HERMES_RID_CNFOWNSSID :
2758                         HERMES_RID_CNFDESIREDSSID;
2759                 
2760                 err = hermes_read_ltv(hw, USER_BAP, rid, sizeof(essidbuf),
2761                                       NULL, &essidbuf);
2762                 if (err)
2763                         goto fail_unlock;
2764         } else {
2765                 *active = 0;
2766
2767                 err = hermes_read_ltv(hw, USER_BAP, HERMES_RID_CURRENTSSID,
2768                                       sizeof(essidbuf), NULL, &essidbuf);
2769                 if (err)
2770                         goto fail_unlock;
2771         }
2772
2773         len = le16_to_cpu(essidbuf.len);
2774         BUG_ON(len > IW_ESSID_MAX_SIZE);
2775
2776         memset(buf, 0, IW_ESSID_MAX_SIZE+1);
2777         memcpy(buf, p, len);
2778         buf[len] = '\0';
2779
2780  fail_unlock:
2781         orinoco_unlock(priv, &flags);
2782
2783         return err;       
2784 }
2785
2786 static long orinoco_hw_get_freq(struct orinoco_private *priv)
2787 {
2788         
2789         hermes_t *hw = &priv->hw;
2790         int err = 0;
2791         u16 channel;
2792         long freq = 0;
2793         unsigned long flags;
2794
2795         if (orinoco_lock(priv, &flags) != 0)
2796                 return -EBUSY;
2797         
2798         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CURRENTCHANNEL, &channel);
2799         if (err)
2800                 goto out;
2801
2802         /* Intersil firmware 1.3.5 returns 0 when the interface is down */
2803         if (channel == 0) {
2804                 err = -EBUSY;
2805                 goto out;
2806         }
2807
2808         if ( (channel < 1) || (channel > NUM_CHANNELS) ) {
2809                 printk(KERN_WARNING "%s: Channel out of range (%d)!\n",
2810                        priv->ndev->name, channel);
2811                 err = -EBUSY;
2812                 goto out;
2813
2814         }
2815         freq = channel_frequency[channel-1] * 100000;
2816
2817  out:
2818         orinoco_unlock(priv, &flags);
2819
2820         if (err > 0)
2821                 err = -EBUSY;
2822         return err ? err : freq;
2823 }
2824
2825 static int orinoco_hw_get_bitratelist(struct orinoco_private *priv,
2826                                       int *numrates, s32 *rates, int max)
2827 {
2828         hermes_t *hw = &priv->hw;
2829         struct hermes_idstring list;
2830         unsigned char *p = (unsigned char *)&list.val;
2831         int err = 0;
2832         int num;
2833         int i;
2834         unsigned long flags;
2835
2836         if (orinoco_lock(priv, &flags) != 0)
2837                 return -EBUSY;
2838
2839         err = hermes_read_ltv(hw, USER_BAP, HERMES_RID_SUPPORTEDDATARATES,
2840                               sizeof(list), NULL, &list);
2841         orinoco_unlock(priv, &flags);
2842
2843         if (err)
2844                 return err;
2845         
2846         num = le16_to_cpu(list.len);
2847         *numrates = num;
2848         num = min(num, max);
2849
2850         for (i = 0; i < num; i++) {
2851                 rates[i] = (p[i] & 0x7f) * 500000; /* convert to bps */
2852         }
2853
2854         return 0;
2855 }
2856
2857 static int orinoco_ioctl_getname(struct net_device *dev,
2858                                  struct iw_request_info *info,
2859                                  char *name,
2860                                  char *extra)
2861 {
2862         struct orinoco_private *priv = netdev_priv(dev);
2863         int numrates;
2864         int err;
2865
2866         err = orinoco_hw_get_bitratelist(priv, &numrates, NULL, 0);
2867
2868         if (!err && (numrates > 2))
2869                 strcpy(name, "IEEE 802.11b");
2870         else
2871                 strcpy(name, "IEEE 802.11-DS");
2872
2873         return 0;
2874 }
2875
2876 static int orinoco_ioctl_setwap(struct net_device *dev,
2877                                 struct iw_request_info *info,
2878                                 struct sockaddr *ap_addr,
2879                                 char *extra)
2880 {
2881         struct orinoco_private *priv = netdev_priv(dev);
2882         int err = -EINPROGRESS;         /* Call commit handler */
2883         unsigned long flags;
2884         static const u8 off_addr[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
2885         static const u8 any_addr[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
2886
2887         if (orinoco_lock(priv, &flags) != 0)
2888                 return -EBUSY;
2889
2890         /* Enable automatic roaming - no sanity checks are needed */
2891         if (memcmp(&ap_addr->sa_data, off_addr, ETH_ALEN) == 0 ||
2892             memcmp(&ap_addr->sa_data, any_addr, ETH_ALEN) == 0) {
2893                 priv->bssid_fixed = 0;
2894                 memset(priv->desired_bssid, 0, ETH_ALEN);
2895
2896                 /* "off" means keep existing connection */
2897                 if (ap_addr->sa_data[0] == 0) {
2898                         __orinoco_hw_set_wap(priv);
2899                         err = 0;
2900                 }
2901                 goto out;
2902         }
2903
2904         if (priv->firmware_type == FIRMWARE_TYPE_AGERE) {
2905                 printk(KERN_WARNING "%s: Lucent/Agere firmware doesn't "
2906                        "support manual roaming\n",
2907                        dev->name);
2908                 err = -EOPNOTSUPP;
2909                 goto out;
2910         }
2911
2912         if (priv->iw_mode != IW_MODE_INFRA) {
2913                 printk(KERN_WARNING "%s: Manual roaming supported only in "
2914                        "managed mode\n", dev->name);
2915                 err = -EOPNOTSUPP;
2916                 goto out;
2917         }
2918
2919         /* Intersil firmware hangs without Desired ESSID */
2920         if (priv->firmware_type == FIRMWARE_TYPE_INTERSIL &&
2921             strlen(priv->desired_essid) == 0) {
2922                 printk(KERN_WARNING "%s: Desired ESSID must be set for "
2923                        "manual roaming\n", dev->name);
2924                 err = -EOPNOTSUPP;
2925                 goto out;
2926         }
2927
2928         /* Finally, enable manual roaming */
2929         priv->bssid_fixed = 1;
2930         memcpy(priv->desired_bssid, &ap_addr->sa_data, ETH_ALEN);
2931
2932  out:
2933         orinoco_unlock(priv, &flags);
2934         return err;
2935 }
2936
2937 static int orinoco_ioctl_getwap(struct net_device *dev,
2938                                 struct iw_request_info *info,
2939                                 struct sockaddr *ap_addr,
2940                                 char *extra)
2941 {
2942         struct orinoco_private *priv = netdev_priv(dev);
2943
2944         hermes_t *hw = &priv->hw;
2945         int err = 0;
2946         unsigned long flags;
2947
2948         if (orinoco_lock(priv, &flags) != 0)
2949                 return -EBUSY;
2950
2951         ap_addr->sa_family = ARPHRD_ETHER;
2952         err = hermes_read_ltv(hw, USER_BAP, HERMES_RID_CURRENTBSSID,
2953                               ETH_ALEN, NULL, ap_addr->sa_data);
2954
2955         orinoco_unlock(priv, &flags);
2956
2957         return err;
2958 }
2959
2960 static int orinoco_ioctl_setmode(struct net_device *dev,
2961                                  struct iw_request_info *info,
2962                                  u32 *mode,
2963                                  char *extra)
2964 {
2965         struct orinoco_private *priv = netdev_priv(dev);
2966         int err = -EINPROGRESS;         /* Call commit handler */
2967         unsigned long flags;
2968
2969         if (priv->iw_mode == *mode)
2970                 return 0;
2971
2972         if (orinoco_lock(priv, &flags) != 0)
2973                 return -EBUSY;
2974
2975         switch (*mode) {
2976         case IW_MODE_ADHOC:
2977                 if (!priv->has_ibss && !priv->has_port3)
2978                         err = -EOPNOTSUPP;
2979                 break;
2980
2981         case IW_MODE_INFRA:
2982                 break;
2983
2984         default:
2985                 err = -EOPNOTSUPP;
2986                 break;
2987         }
2988
2989         if (err == -EINPROGRESS) {
2990                 priv->iw_mode = *mode;
2991                 set_port_type(priv);
2992         }
2993
2994         orinoco_unlock(priv, &flags);
2995
2996         return err;
2997 }
2998
2999 static int orinoco_ioctl_getmode(struct net_device *dev,
3000                                  struct iw_request_info *info,
3001                                  u32 *mode,
3002                                  char *extra)
3003 {
3004         struct orinoco_private *priv = netdev_priv(dev);
3005
3006         *mode = priv->iw_mode;
3007         return 0;
3008 }
3009
3010 static int orinoco_ioctl_getiwrange(struct net_device *dev,
3011                                     struct iw_request_info *info,
3012                                     struct iw_point *rrq,
3013                                     char *extra)
3014 {
3015         struct orinoco_private *priv = netdev_priv(dev);
3016         int err = 0;
3017         struct iw_range *range = (struct iw_range *) extra;
3018         int numrates;
3019         int i, k;
3020
3021         TRACE_ENTER(dev->name);
3022
3023         rrq->length = sizeof(struct iw_range);
3024         memset(range, 0, sizeof(struct iw_range));
3025
3026         range->we_version_compiled = WIRELESS_EXT;
3027         range->we_version_source = 14;
3028
3029         /* Set available channels/frequencies */
3030         range->num_channels = NUM_CHANNELS;
3031         k = 0;
3032         for (i = 0; i < NUM_CHANNELS; i++) {
3033                 if (priv->channel_mask & (1 << i)) {
3034                         range->freq[k].i = i + 1;
3035                         range->freq[k].m = channel_frequency[i] * 100000;
3036                         range->freq[k].e = 1;
3037                         k++;
3038                 }
3039                 
3040                 if (k >= IW_MAX_FREQUENCIES)
3041                         break;
3042         }
3043         range->num_frequency = k;
3044         range->sensitivity = 3;
3045
3046         if (priv->has_wep) {
3047                 range->max_encoding_tokens = ORINOCO_MAX_KEYS;
3048                 range->encoding_size[0] = SMALL_KEY_SIZE;
3049                 range->num_encoding_sizes = 1;
3050
3051                 if (priv->has_big_wep) {
3052                         range->encoding_size[1] = LARGE_KEY_SIZE;
3053                         range->num_encoding_sizes = 2;
3054                 }
3055         }
3056
3057         if ((priv->iw_mode == IW_MODE_ADHOC) && (priv->spy_number == 0)){
3058                 /* Quality stats meaningless in ad-hoc mode */
3059         } else {
3060                 range->max_qual.qual = 0x8b - 0x2f;
3061                 range->max_qual.level = 0x2f - 0x95 - 1;
3062                 range->max_qual.noise = 0x2f - 0x95 - 1;
3063                 /* Need to get better values */
3064                 range->avg_qual.qual = 0x24;
3065                 range->avg_qual.level = 0xC2;
3066                 range->avg_qual.noise = 0x9E;
3067         }
3068
3069         err = orinoco_hw_get_bitratelist(priv, &numrates,
3070                                          range->bitrate, IW_MAX_BITRATES);
3071         if (err)
3072                 return err;
3073         range->num_bitrates = numrates;
3074
3075         /* Set an indication of the max TCP throughput in bit/s that we can
3076          * expect using this interface. May be use for QoS stuff...
3077          * Jean II */
3078         if (numrates > 2)
3079                 range->throughput = 5 * 1000 * 1000;    /* ~5 Mb/s */
3080         else
3081                 range->throughput = 1.5 * 1000 * 1000;  /* ~1.5 Mb/s */
3082
3083         range->min_rts = 0;
3084         range->max_rts = 2347;
3085         range->min_frag = 256;
3086         range->max_frag = 2346;
3087
3088         range->min_pmp = 0;
3089         range->max_pmp = 65535000;
3090         range->min_pmt = 0;
3091         range->max_pmt = 65535 * 1000;  /* ??? */
3092         range->pmp_flags = IW_POWER_PERIOD;
3093         range->pmt_flags = IW_POWER_TIMEOUT;
3094         range->pm_capa = IW_POWER_PERIOD | IW_POWER_TIMEOUT | IW_POWER_UNICAST_R;
3095
3096         range->retry_capa = IW_RETRY_LIMIT | IW_RETRY_LIFETIME;
3097         range->retry_flags = IW_RETRY_LIMIT;
3098         range->r_time_flags = IW_RETRY_LIFETIME;
3099         range->min_retry = 0;
3100         range->max_retry = 65535;       /* ??? */
3101         range->min_r_time = 0;
3102         range->max_r_time = 65535 * 1000;       /* ??? */
3103
3104         TRACE_EXIT(dev->name);
3105
3106         return 0;
3107 }
3108
3109 static int orinoco_ioctl_setiwencode(struct net_device *dev,
3110                                      struct iw_request_info *info,
3111                                      struct iw_point *erq,
3112                                      char *keybuf)
3113 {
3114         struct orinoco_private *priv = netdev_priv(dev);
3115         int index = (erq->flags & IW_ENCODE_INDEX) - 1;
3116         int setindex = priv->tx_key;
3117         int enable = priv->wep_on;
3118         int restricted = priv->wep_restrict;
3119         u16 xlen = 0;
3120         int err = -EINPROGRESS;         /* Call commit handler */
3121         unsigned long flags;
3122
3123         if (! priv->has_wep)
3124                 return -EOPNOTSUPP;
3125
3126         if (erq->pointer) {
3127                 /* We actually have a key to set - check its length */
3128                 if (erq->length > LARGE_KEY_SIZE)
3129                         return -E2BIG;
3130
3131                 if ( (erq->length > SMALL_KEY_SIZE) && !priv->has_big_wep )
3132                         return -E2BIG;
3133         }
3134
3135         if (orinoco_lock(priv, &flags) != 0)
3136                 return -EBUSY;
3137
3138         if (erq->pointer) {
3139                 if ((index < 0) || (index >= ORINOCO_MAX_KEYS))
3140                         index = priv->tx_key;
3141
3142                 /* Adjust key length to a supported value */
3143                 if (erq->length > SMALL_KEY_SIZE) {
3144                         xlen = LARGE_KEY_SIZE;
3145                 } else if (erq->length > 0) {
3146                         xlen = SMALL_KEY_SIZE;
3147                 } else
3148                         xlen = 0;
3149
3150                 /* Switch on WEP if off */
3151                 if ((!enable) && (xlen > 0)) {
3152                         setindex = index;
3153                         enable = 1;
3154                 }
3155         } else {
3156                 /* Important note : if the user do "iwconfig eth0 enc off",
3157                  * we will arrive there with an index of -1. This is valid
3158                  * but need to be taken care off... Jean II */
3159                 if ((index < 0) || (index >= ORINOCO_MAX_KEYS)) {
3160                         if((index != -1) || (erq->flags == 0)) {
3161                                 err = -EINVAL;
3162                                 goto out;
3163                         }
3164                 } else {
3165                         /* Set the index : Check that the key is valid */
3166                         if(priv->keys[index].len == 0) {
3167                                 err = -EINVAL;
3168                                 goto out;
3169                         }
3170                         setindex = index;
3171                 }
3172         }
3173
3174         if (erq->flags & IW_ENCODE_DISABLED)
3175                 enable = 0;
3176         if (erq->flags & IW_ENCODE_OPEN)
3177                 restricted = 0;
3178         if (erq->flags & IW_ENCODE_RESTRICTED)
3179                 restricted = 1;
3180
3181         if (erq->pointer) {
3182                 priv->keys[index].len = cpu_to_le16(xlen);
3183                 memset(priv->keys[index].data, 0,
3184                        sizeof(priv->keys[index].data));
3185                 memcpy(priv->keys[index].data, keybuf, erq->length);
3186         }
3187         priv->tx_key = setindex;
3188
3189         /* Try fast key change if connected and only keys are changed */
3190         if (priv->wep_on && enable && (priv->wep_restrict == restricted) &&
3191             netif_carrier_ok(dev)) {
3192                 err = __orinoco_hw_setup_wepkeys(priv);
3193                 /* No need to commit if successful */
3194                 goto out;
3195         }
3196
3197         priv->wep_on = enable;
3198         priv->wep_restrict = restricted;
3199
3200  out:
3201         orinoco_unlock(priv, &flags);
3202
3203         return err;
3204 }
3205
3206 static int orinoco_ioctl_getiwencode(struct net_device *dev,
3207                                      struct iw_request_info *info,
3208                                      struct iw_point *erq,
3209                                      char *keybuf)
3210 {
3211         struct orinoco_private *priv = netdev_priv(dev);
3212         int index = (erq->flags & IW_ENCODE_INDEX) - 1;
3213         u16 xlen = 0;
3214         unsigned long flags;
3215
3216         if (! priv->has_wep)
3217                 return -EOPNOTSUPP;
3218
3219         if (orinoco_lock(priv, &flags) != 0)
3220                 return -EBUSY;
3221
3222         if ((index < 0) || (index >= ORINOCO_MAX_KEYS))
3223                 index = priv->tx_key;
3224
3225         erq->flags = 0;
3226         if (! priv->wep_on)
3227                 erq->flags |= IW_ENCODE_DISABLED;
3228         erq->flags |= index + 1;
3229
3230         if (priv->wep_restrict)
3231                 erq->flags |= IW_ENCODE_RESTRICTED;
3232         else
3233                 erq->flags |= IW_ENCODE_OPEN;
3234
3235         xlen = le16_to_cpu(priv->keys[index].len);
3236
3237         erq->length = xlen;
3238
3239         memcpy(keybuf, priv->keys[index].data, ORINOCO_MAX_KEY_SIZE);
3240
3241         orinoco_unlock(priv, &flags);
3242         return 0;
3243 }
3244
3245 static int orinoco_ioctl_setessid(struct net_device *dev,
3246                                   struct iw_request_info *info,
3247                                   struct iw_point *erq,
3248                                   char *essidbuf)
3249 {
3250         struct orinoco_private *priv = netdev_priv(dev);
3251         unsigned long flags;
3252
3253         /* Note : ESSID is ignored in Ad-Hoc demo mode, but we can set it
3254          * anyway... - Jean II */
3255
3256         /* Hum... Should not use Wireless Extension constant (may change),
3257          * should use our own... - Jean II */
3258         if (erq->length > IW_ESSID_MAX_SIZE)
3259                 return -E2BIG;
3260
3261         if (orinoco_lock(priv, &flags) != 0)
3262                 return -EBUSY;
3263
3264         /* NULL the string (for NULL termination & ESSID = ANY) - Jean II */
3265         memset(priv->desired_essid, 0, sizeof(priv->desired_essid));
3266
3267         /* If not ANY, get the new ESSID */
3268         if (erq->flags) {
3269                 memcpy(priv->desired_essid, essidbuf, erq->length);
3270         }
3271
3272         orinoco_unlock(priv, &flags);
3273
3274         return -EINPROGRESS;            /* Call commit handler */
3275 }
3276
3277 static int orinoco_ioctl_getessid(struct net_device *dev,
3278                                   struct iw_request_info *info,
3279                                   struct iw_point *erq,
3280                                   char *essidbuf)
3281 {
3282         struct orinoco_private *priv = netdev_priv(dev);
3283         int active;
3284         int err = 0;
3285         unsigned long flags;
3286
3287         TRACE_ENTER(dev->name);
3288
3289         if (netif_running(dev)) {
3290                 err = orinoco_hw_get_essid(priv, &active, essidbuf);
3291                 if (err)
3292                         return err;
3293         } else {
3294                 if (orinoco_lock(priv, &flags) != 0)
3295                         return -EBUSY;
3296                 memcpy(essidbuf, priv->desired_essid, IW_ESSID_MAX_SIZE + 1);
3297                 orinoco_unlock(priv, &flags);
3298         }
3299
3300         erq->flags = 1;
3301         erq->length = strlen(essidbuf) + 1;
3302
3303         TRACE_EXIT(dev->name);
3304         
3305         return 0;
3306 }
3307
3308 static int orinoco_ioctl_setnick(struct net_device *dev,
3309                                  struct iw_request_info *info,
3310                                  struct iw_point *nrq,
3311                                  char *nickbuf)
3312 {
3313         struct orinoco_private *priv = netdev_priv(dev);
3314         unsigned long flags;
3315
3316         if (nrq->length > IW_ESSID_MAX_SIZE)
3317                 return -E2BIG;
3318
3319         if (orinoco_lock(priv, &flags) != 0)
3320                 return -EBUSY;
3321
3322         memset(priv->nick, 0, sizeof(priv->nick));
3323         memcpy(priv->nick, nickbuf, nrq->length);
3324
3325         orinoco_unlock(priv, &flags);
3326
3327         return -EINPROGRESS;            /* Call commit handler */
3328 }
3329
3330 static int orinoco_ioctl_getnick(struct net_device *dev,
3331                                  struct iw_request_info *info,
3332                                  struct iw_point *nrq,
3333                                  char *nickbuf)
3334 {
3335         struct orinoco_private *priv = netdev_priv(dev);
3336         unsigned long flags;
3337
3338         if (orinoco_lock(priv, &flags) != 0)
3339                 return -EBUSY;
3340
3341         memcpy(nickbuf, priv->nick, IW_ESSID_MAX_SIZE+1);
3342         orinoco_unlock(priv, &flags);
3343
3344         nrq->length = strlen(nickbuf)+1;
3345
3346         return 0;
3347 }
3348
3349 static int orinoco_ioctl_setfreq(struct net_device *dev,
3350                                  struct iw_request_info *info,
3351                                  struct iw_freq *frq,
3352                                  char *extra)
3353 {
3354         struct orinoco_private *priv = netdev_priv(dev);
3355         int chan = -1;
3356         unsigned long flags;
3357         int err = -EINPROGRESS;         /* Call commit handler */
3358
3359         /* We can only use this in Ad-Hoc demo mode to set the operating
3360          * frequency, or in IBSS mode to set the frequency where the IBSS
3361          * will be created - Jean II */
3362         if (priv->iw_mode != IW_MODE_ADHOC)
3363                 return -EOPNOTSUPP;
3364
3365         if ( (frq->e == 0) && (frq->m <= 1000) ) {
3366                 /* Setting by channel number */
3367                 chan = frq->m;
3368         } else {
3369                 /* Setting by frequency - search the table */
3370                 int mult = 1;
3371                 int i;
3372
3373                 for (i = 0; i < (6 - frq->e); i++)
3374                         mult *= 10;
3375
3376                 for (i = 0; i < NUM_CHANNELS; i++)
3377                         if (frq->m == (channel_frequency[i] * mult))
3378                                 chan = i+1;
3379         }
3380
3381         if ( (chan < 1) || (chan > NUM_CHANNELS) ||
3382              ! (priv->channel_mask & (1 << (chan-1)) ) )
3383                 return -EINVAL;
3384
3385         if (orinoco_lock(priv, &flags) != 0)
3386                 return -EBUSY;
3387         priv->channel = chan;
3388         orinoco_unlock(priv, &flags);
3389
3390         return err;
3391 }
3392
3393 static int orinoco_ioctl_getfreq(struct net_device *dev,
3394                                  struct iw_request_info *info,
3395                                  struct iw_freq *frq,
3396                                  char *extra)
3397 {
3398         struct orinoco_private *priv = netdev_priv(dev);
3399         int tmp;
3400
3401         /* Locking done in there */
3402         tmp = orinoco_hw_get_freq(priv);
3403         if (tmp < 0) {
3404                 return tmp;
3405         }
3406
3407         frq->m = tmp;
3408         frq->e = 1;
3409
3410         return 0;
3411 }
3412
3413 static int orinoco_ioctl_getsens(struct net_device *dev,
3414                                  struct iw_request_info *info,
3415                                  struct iw_param *srq,
3416                                  char *extra)
3417 {
3418         struct orinoco_private *priv = netdev_priv(dev);
3419         hermes_t *hw = &priv->hw;
3420         u16 val;
3421         int err;
3422         unsigned long flags;
3423
3424         if (!priv->has_sensitivity)
3425                 return -EOPNOTSUPP;
3426
3427         if (orinoco_lock(priv, &flags) != 0)
3428                 return -EBUSY;
3429         err = hermes_read_wordrec(hw, USER_BAP,
3430                                   HERMES_RID_CNFSYSTEMSCALE, &val);
3431         orinoco_unlock(priv, &flags);
3432
3433         if (err)
3434                 return err;
3435
3436         srq->value = val;
3437         srq->fixed = 0; /* auto */
3438
3439         return 0;
3440 }
3441
3442 static int orinoco_ioctl_setsens(struct net_device *dev,
3443                                  struct iw_request_info *info,
3444                                  struct iw_param *srq,
3445                                  char *extra)
3446 {
3447         struct orinoco_private *priv = netdev_priv(dev);
3448         int val = srq->value;
3449         unsigned long flags;
3450
3451         if (!priv->has_sensitivity)
3452                 return -EOPNOTSUPP;
3453
3454         if ((val < 1) || (val > 3))
3455                 return -EINVAL;
3456         
3457         if (orinoco_lock(priv, &flags) != 0)
3458                 return -EBUSY;
3459         priv->ap_density = val;
3460         orinoco_unlock(priv, &flags);
3461
3462         return -EINPROGRESS;            /* Call commit handler */
3463 }
3464
3465 static int orinoco_ioctl_setrts(struct net_device *dev,
3466                                 struct iw_request_info *info,
3467                                 struct iw_param *rrq,
3468                                 char *extra)
3469 {
3470         struct orinoco_private *priv = netdev_priv(dev);
3471         int val = rrq->value;
3472         unsigned long flags;
3473
3474         if (rrq->disabled)
3475                 val = 2347;
3476
3477         if ( (val < 0) || (val > 2347) )
3478                 return -EINVAL;
3479
3480         if (orinoco_lock(priv, &flags) != 0)
3481                 return -EBUSY;
3482
3483         priv->rts_thresh = val;
3484         orinoco_unlock(priv, &flags);
3485
3486         return -EINPROGRESS;            /* Call commit handler */
3487 }
3488
3489 static int orinoco_ioctl_getrts(struct net_device *dev,
3490                                 struct iw_request_info *info,
3491                                 struct iw_param *rrq,
3492                                 char *extra)
3493 {
3494         struct orinoco_private *priv = netdev_priv(dev);
3495
3496         rrq->value = priv->rts_thresh;
3497         rrq->disabled = (rrq->value == 2347);
3498         rrq->fixed = 1;
3499
3500         return 0;
3501 }
3502
3503 static int orinoco_ioctl_setfrag(struct net_device *dev,
3504                                  struct iw_request_info *info,
3505                                  struct iw_param *frq,
3506                                  char *extra)
3507 {
3508         struct orinoco_private *priv = netdev_priv(dev);
3509         int err = -EINPROGRESS;         /* Call commit handler */
3510         unsigned long flags;
3511
3512         if (orinoco_lock(priv, &flags) != 0)
3513                 return -EBUSY;
3514
3515         if (priv->has_mwo) {
3516                 if (frq->disabled)
3517                         priv->mwo_robust = 0;
3518                 else {
3519                         if (frq->fixed)
3520                                 printk(KERN_WARNING "%s: Fixed fragmentation is "
3521                                        "not supported on this firmware. "
3522                                        "Using MWO robust instead.\n", dev->name);
3523                         priv->mwo_robust = 1;
3524                 }
3525         } else {
3526                 if (frq->disabled)
3527                         priv->frag_thresh = 2346;
3528                 else {
3529                         if ( (frq->value < 256) || (frq->value > 2346) )
3530                                 err = -EINVAL;
3531                         else
3532                                 priv->frag_thresh = frq->value & ~0x1; /* must be even */
3533                 }
3534         }
3535
3536         orinoco_unlock(priv, &flags);
3537
3538         return err;
3539 }
3540
3541 static int orinoco_ioctl_getfrag(struct net_device *dev,
3542                                  struct iw_request_info *info,
3543                                  struct iw_param *frq,
3544                                  char *extra)
3545 {
3546         struct orinoco_private *priv = netdev_priv(dev);
3547         hermes_t *hw = &priv->hw;
3548         int err;
3549         u16 val;
3550         unsigned long flags;
3551
3552         if (orinoco_lock(priv, &flags) != 0)
3553                 return -EBUSY;
3554         
3555         if (priv->has_mwo) {
3556                 err = hermes_read_wordrec(hw, USER_BAP,
3557                                           HERMES_RID_CNFMWOROBUST_AGERE,
3558                                           &val);
3559                 if (err)
3560                         val = 0;
3561
3562                 frq->value = val ? 2347 : 0;
3563                 frq->disabled = ! val;
3564                 frq->fixed = 0;
3565         } else {
3566                 err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CNFFRAGMENTATIONTHRESHOLD,
3567                                           &val);
3568                 if (err)
3569                         val = 0;
3570
3571                 frq->value = val;
3572                 frq->disabled = (val >= 2346);
3573                 frq->fixed = 1;
3574         }
3575
3576         orinoco_unlock(priv, &flags);
3577         
3578         return err;
3579 }
3580
3581 static int orinoco_ioctl_setrate(struct net_device *dev,
3582                                  struct iw_request_info *info,
3583                                  struct iw_param *rrq,
3584                                  char *extra)
3585 {
3586         struct orinoco_private *priv = netdev_priv(dev);
3587         int ratemode = -1;
3588         int bitrate; /* 100s of kilobits */
3589         int i;
3590         unsigned long flags;
3591         
3592         /* As the user space doesn't know our highest rate, it uses -1
3593          * to ask us to set the highest rate.  Test it using "iwconfig
3594          * ethX rate auto" - Jean II */
3595         if (rrq->value == -1)
3596                 bitrate = 110;
3597         else {
3598                 if (rrq->value % 100000)
3599                         return -EINVAL;
3600                 bitrate = rrq->value / 100000;
3601         }
3602
3603         if ( (bitrate != 10) && (bitrate != 20) &&
3604              (bitrate != 55) && (bitrate != 110) )
3605                 return -EINVAL;
3606
3607         for (i = 0; i < BITRATE_TABLE_SIZE; i++)
3608                 if ( (bitrate_table[i].bitrate == bitrate) &&
3609                      (bitrate_table[i].automatic == ! rrq->fixed) ) {
3610                         ratemode = i;
3611                         break;
3612                 }
3613         
3614         if (ratemode == -1)
3615                 return -EINVAL;
3616
3617         if (orinoco_lock(priv, &flags) != 0)
3618                 return -EBUSY;
3619         priv->bitratemode = ratemode;
3620         orinoco_unlock(priv, &flags);
3621
3622         return -EINPROGRESS;
3623 }
3624
3625 static int orinoco_ioctl_getrate(struct net_device *dev,
3626                                  struct iw_request_info *info,
3627                                  struct iw_param *rrq,
3628                                  char *extra)
3629 {
3630         struct orinoco_private *priv = netdev_priv(dev);
3631         hermes_t *hw = &priv->hw;
3632         int err = 0;
3633         int ratemode;
3634         int i;
3635         u16 val;
3636         unsigned long flags;
3637
3638         if (orinoco_lock(priv, &flags) != 0)
3639                 return -EBUSY;
3640
3641         ratemode = priv->bitratemode;
3642
3643         BUG_ON((ratemode < 0) || (ratemode >= BITRATE_TABLE_SIZE));
3644
3645         rrq->value = bitrate_table[ratemode].bitrate * 100000;
3646         rrq->fixed = ! bitrate_table[ratemode].automatic;
3647         rrq->disabled = 0;
3648
3649         /* If the interface is running we try to find more about the
3650            current mode */
3651         if (netif_running(dev)) {
3652                 err = hermes_read_wordrec(hw, USER_BAP,
3653                                           HERMES_RID_CURRENTTXRATE, &val);
3654                 if (err)
3655                         goto out;
3656                 
3657                 switch (priv->firmware_type) {
3658                 case FIRMWARE_TYPE_AGERE: /* Lucent style rate */
3659                         /* Note : in Lucent firmware, the return value of
3660                          * HERMES_RID_CURRENTTXRATE is the bitrate in Mb/s,
3661                          * and therefore is totally different from the
3662                          * encoding of HERMES_RID_CNFTXRATECONTROL.
3663                          * Don't forget that 6Mb/s is really 5.5Mb/s */
3664                         if (val == 6)
3665                                 rrq->value = 5500000;
3666                         else
3667                                 rrq->value = val * 1000000;
3668                         break;
3669                 case FIRMWARE_TYPE_INTERSIL: /* Intersil style rate */
3670                 case FIRMWARE_TYPE_SYMBOL: /* Symbol style rate */
3671                         for (i = 0; i < BITRATE_TABLE_SIZE; i++)
3672                                 if (bitrate_table[i].intersil_txratectrl == val) {
3673                                         ratemode = i;
3674                                         break;
3675                                 }
3676                         if (i >= BITRATE_TABLE_SIZE)
3677                                 printk(KERN_INFO "%s: Unable to determine current bitrate (0x%04hx)\n",
3678                                        dev->name, val);
3679
3680                         rrq->value = bitrate_table[ratemode].bitrate * 100000;
3681                         break;
3682                 default:
3683                         BUG();
3684                 }
3685         }
3686
3687  out:
3688         orinoco_unlock(priv, &flags);
3689
3690         return err;
3691 }
3692
3693 static int orinoco_ioctl_setpower(struct net_device *dev,
3694                                   struct iw_request_info *info,
3695                                   struct iw_param *prq,
3696                                   char *extra)
3697 {
3698         struct orinoco_private *priv = netdev_priv(dev);
3699         int err = -EINPROGRESS;         /* Call commit handler */
3700         unsigned long flags;
3701
3702         if (orinoco_lock(priv, &flags) != 0)
3703                 return -EBUSY;
3704
3705         if (prq->disabled) {
3706                 priv->pm_on = 0;
3707         } else {
3708                 switch (prq->flags & IW_POWER_MODE) {
3709                 case IW_POWER_UNICAST_R:
3710                         priv->pm_mcast = 0;
3711                         priv->pm_on = 1;
3712                         break;
3713                 case IW_POWER_ALL_R:
3714                         priv->pm_mcast = 1;
3715                         priv->pm_on = 1;
3716                         break;
3717                 case IW_POWER_ON:
3718                         /* No flags : but we may have a value - Jean II */
3719                         break;
3720                 default:
3721                         err = -EINVAL;
3722                 }
3723                 if (err)
3724                         goto out;
3725                 
3726                 if (prq->flags & IW_POWER_TIMEOUT) {
3727                         priv->pm_on = 1;
3728                         priv->pm_timeout = prq->value / 1000;
3729                 }
3730                 if (prq->flags & IW_POWER_PERIOD) {
3731                         priv->pm_on = 1;
3732                         priv->pm_period = prq->value / 1000;
3733                 }
3734                 /* It's valid to not have a value if we are just toggling
3735                  * the flags... Jean II */
3736                 if(!priv->pm_on) {
3737                         err = -EINVAL;
3738                         goto out;
3739                 }                       
3740         }
3741
3742  out:
3743         orinoco_unlock(priv, &flags);
3744
3745         return err;
3746 }
3747
3748 static int orinoco_ioctl_getpower(struct net_device *dev,
3749                                   struct iw_request_info *info,
3750                                   struct iw_param *prq,
3751                                   char *extra)
3752 {
3753         struct orinoco_private *priv = netdev_priv(dev);
3754         hermes_t *hw = &priv->hw;
3755         int err = 0;
3756         u16 enable, period, timeout, mcast;
3757         unsigned long flags;
3758
3759         if (orinoco_lock(priv, &flags) != 0)
3760                 return -EBUSY;
3761         
3762         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CNFPMENABLED, &enable);
3763         if (err)
3764                 goto out;
3765
3766         err = hermes_read_wordrec(hw, USER_BAP,
3767                                   HERMES_RID_CNFMAXSLEEPDURATION, &period);
3768         if (err)
3769                 goto out;
3770
3771         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CNFPMHOLDOVERDURATION, &timeout);
3772         if (err)
3773                 goto out;
3774
3775         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CNFMULTICASTRECEIVE, &mcast);
3776         if (err)
3777                 goto out;
3778
3779         prq->disabled = !enable;
3780         /* Note : by default, display the period */
3781         if ((prq->flags & IW_POWER_TYPE) == IW_POWER_TIMEOUT) {
3782                 prq->flags = IW_POWER_TIMEOUT;
3783                 prq->value = timeout * 1000;
3784         } else {
3785                 prq->flags = IW_POWER_PERIOD;
3786                 prq->value = period * 1000;
3787         }
3788         if (mcast)
3789                 prq->flags |= IW_POWER_ALL_R;
3790         else
3791                 prq->flags |= IW_POWER_UNICAST_R;
3792
3793  out:
3794         orinoco_unlock(priv, &flags);
3795
3796         return err;
3797 }
3798
3799 static int orinoco_ioctl_getretry(struct net_device *dev,
3800                                   struct iw_request_info *info,
3801                                   struct iw_param *rrq,
3802                                   char *extra)
3803 {
3804         struct orinoco_private *priv = netdev_priv(dev);
3805         hermes_t *hw = &priv->hw;
3806         int err = 0;
3807         u16 short_limit, long_limit, lifetime;
3808         unsigned long flags;
3809
3810         if (orinoco_lock(priv, &flags) != 0)
3811                 return -EBUSY;
3812         
3813         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_SHORTRETRYLIMIT,
3814                                   &short_limit);
3815         if (err)
3816                 goto out;
3817
3818         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_LONGRETRYLIMIT,
3819                                   &long_limit);
3820         if (err)
3821                 goto out;
3822
3823         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_MAXTRANSMITLIFETIME,
3824                                   &lifetime);
3825         if (err)
3826                 goto out;
3827
3828         rrq->disabled = 0;              /* Can't be disabled */
3829
3830         /* Note : by default, display the retry number */
3831         if ((rrq->flags & IW_RETRY_TYPE) == IW_RETRY_LIFETIME) {
3832                 rrq->flags = IW_RETRY_LIFETIME;
3833                 rrq->value = lifetime * 1000;   /* ??? */
3834         } else {
3835                 /* By default, display the min number */
3836                 if ((rrq->flags & IW_RETRY_MAX)) {
3837                         rrq->flags = IW_RETRY_LIMIT | IW_RETRY_MAX;
3838                         rrq->value = long_limit;
3839                 } else {
3840                         rrq->flags = IW_RETRY_LIMIT;
3841                         rrq->value = short_limit;
3842                         if(short_limit != long_limit)
3843                                 rrq->flags |= IW_RETRY_MIN;
3844                 }
3845         }
3846
3847  out:
3848         orinoco_unlock(priv, &flags);
3849
3850         return err;
3851 }
3852
3853 static int orinoco_ioctl_reset(struct net_device *dev,
3854                                struct iw_request_info *info,
3855                                void *wrqu,
3856                                char *extra)
3857 {
3858         struct orinoco_private *priv = netdev_priv(dev);
3859
3860         if (! capable(CAP_NET_ADMIN))
3861                 return -EPERM;
3862
3863         if (info->cmd == (SIOCIWFIRSTPRIV + 0x1)) {
3864                 printk(KERN_DEBUG "%s: Forcing reset!\n", dev->name);
3865
3866                 /* Firmware reset */
3867                 orinoco_reset(dev);
3868         } else {
3869                 printk(KERN_DEBUG "%s: Force scheduling reset!\n", dev->name);
3870
3871                 schedule_work(&priv->reset_work);
3872         }
3873
3874         return 0;
3875 }
3876
3877 static int orinoco_ioctl_setibssport(struct net_device *dev,
3878                                      struct iw_request_info *info,
3879                                      void *wrqu,
3880                                      char *extra)
3881
3882 {
3883         struct orinoco_private *priv = netdev_priv(dev);
3884         int val = *( (int *) extra );
3885         unsigned long flags;
3886
3887         if (orinoco_lock(priv, &flags) != 0)
3888                 return -EBUSY;
3889
3890         priv->ibss_port = val ;
3891
3892         /* Actually update the mode we are using */
3893         set_port_type(priv);
3894
3895         orinoco_unlock(priv, &flags);
3896         return -EINPROGRESS;            /* Call commit handler */
3897 }
3898
3899 static int orinoco_ioctl_getibssport(struct net_device *dev,
3900                                      struct iw_request_info *info,
3901                                      void *wrqu,
3902                                      char *extra)
3903 {
3904         struct orinoco_private *priv = netdev_priv(dev);
3905         int *val = (int *) extra;
3906
3907         *val = priv->ibss_port;
3908         return 0;
3909 }
3910
3911 static int orinoco_ioctl_setport3(struct net_device *dev,
3912                                   struct iw_request_info *info,
3913                                   void *wrqu,
3914                                   char *extra)
3915 {
3916         struct orinoco_private *priv = netdev_priv(dev);
3917         int val = *( (int *) extra );
3918         int err = 0;
3919         unsigned long flags;
3920
3921         if (orinoco_lock(priv, &flags) != 0)
3922                 return -EBUSY;
3923
3924         switch (val) {
3925         case 0: /* Try to do IEEE ad-hoc mode */
3926                 if (! priv->has_ibss) {
3927                         err = -EINVAL;
3928                         break;
3929                 }
3930                 priv->prefer_port3 = 0;
3931                         
3932                 break;
3933
3934         case 1: /* Try to do Lucent proprietary ad-hoc mode */
3935                 if (! priv->has_port3) {
3936                         err = -EINVAL;
3937                         break;
3938                 }
3939                 priv->prefer_port3 = 1;
3940                 break;
3941
3942         default:
3943                 err = -EINVAL;
3944         }
3945
3946         if (! err) {
3947                 /* Actually update the mode we are using */
3948                 set_port_type(priv);
3949                 err = -EINPROGRESS;
3950         }
3951
3952         orinoco_unlock(priv, &flags);
3953
3954         return err;
3955 }
3956
3957 static int orinoco_ioctl_getport3(struct net_device *dev,
3958                                   struct iw_request_info *info,
3959                                   void *wrqu,
3960                                   char *extra)
3961 {
3962         struct orinoco_private *priv = netdev_priv(dev);
3963         int *val = (int *) extra;
3964
3965         *val = priv->prefer_port3;
3966         return 0;
3967 }
3968
3969 static int orinoco_ioctl_setpreamble(struct net_device *dev,
3970                                      struct iw_request_info *info,
3971                                      void *wrqu,
3972                                      char *extra)
3973 {
3974         struct orinoco_private *priv = netdev_priv(dev);
3975         unsigned long flags;
3976         int val;
3977
3978         if (! priv->has_preamble)
3979                 return -EOPNOTSUPP;
3980
3981         /* 802.11b has recently defined some short preamble.
3982          * Basically, the Phy header has been reduced in size.
3983          * This increase performance, especially at high rates
3984          * (the preamble is transmitted at 1Mb/s), unfortunately
3985          * this give compatibility troubles... - Jean II */
3986         val = *( (int *) extra );
3987
3988         if (orinoco_lock(priv, &flags) != 0)
3989                 return -EBUSY;
3990
3991         if (val)
3992                 priv->preamble = 1;
3993         else
3994                 priv->preamble = 0;
3995
3996         orinoco_unlock(priv, &flags);
3997
3998         return -EINPROGRESS;            /* Call commit handler */
3999 }
4000
4001 static int orinoco_ioctl_getpreamble(struct net_device *dev,
4002                                      struct iw_request_info *info,
4003                                      void *wrqu,
4004                                      char *extra)
4005 {
4006         struct orinoco_private *priv = netdev_priv(dev);
4007         int *val = (int *) extra;
4008
4009         if (! priv->has_preamble)
4010                 return -EOPNOTSUPP;
4011
4012         *val = priv->preamble;
4013         return 0;
4014 }
4015
4016 /* ioctl interface to hermes_read_ltv()
4017  * To use with iwpriv, pass the RID as the token argument, e.g.
4018  * iwpriv get_rid [0xfc00]
4019  * At least Wireless Tools 25 is required to use iwpriv.
4020  * For Wireless Tools 25 and 26 append "dummy" are the end. */
4021 static int orinoco_ioctl_getrid(struct net_device *dev,
4022                                 struct iw_request_info *info,
4023                                 struct iw_point *data,
4024                                 char *extra)
4025 {
4026         struct orinoco_private *priv = netdev_priv(dev);
4027         hermes_t *hw = &priv->hw;
4028         int rid = data->flags;
4029         u16 length;
4030         int err;
4031         unsigned long flags;
4032
4033         /* It's a "get" function, but we don't want users to access the
4034          * WEP key and other raw firmware data */
4035         if (! capable(CAP_NET_ADMIN))
4036                 return -EPERM;
4037
4038         if (rid < 0xfc00 || rid > 0xffff)
4039                 return -EINVAL;
4040
4041         if (orinoco_lock(priv, &flags) != 0)
4042                 return -EBUSY;
4043
4044         err = hermes_read_ltv(hw, USER_BAP, rid, MAX_RID_LEN, &length,
4045                               extra);
4046         if (err)
4047                 goto out;
4048
4049         data->length = min_t(u16, HERMES_RECLEN_TO_BYTES(length),
4050                              MAX_RID_LEN);
4051
4052  out:
4053         orinoco_unlock(priv, &flags);
4054         return err;
4055 }
4056
4057 /* Spy is used for link quality/strength measurements in Ad-Hoc mode
4058  * Jean II */
4059 static int orinoco_ioctl_setspy(struct net_device *dev,
4060                                 struct iw_request_info *info,
4061                                 struct iw_point *srq,
4062                                 char *extra)
4063
4064 {
4065         struct orinoco_private *priv = netdev_priv(dev);
4066         struct sockaddr *address = (struct sockaddr *) extra;
4067         int number = srq->length;
4068         int i;
4069         unsigned long flags;
4070
4071         /* Make sure nobody mess with the structure while we do */
4072         if (orinoco_lock(priv, &flags) != 0)
4073                 return -EBUSY;
4074
4075         /* orinoco_lock() doesn't disable interrupts, so make sure the
4076          * interrupt rx path don't get confused while we copy */
4077         priv->spy_number = 0;
4078
4079         if (number > 0) {
4080                 /* Extract the addresses */
4081                 for (i = 0; i < number; i++)
4082                         memcpy(priv->spy_address[i], address[i].sa_data,
4083                                ETH_ALEN);
4084                 /* Reset stats */
4085                 memset(priv->spy_stat, 0,
4086                        sizeof(struct iw_quality) * IW_MAX_SPY);
4087                 /* Set number of addresses */
4088                 priv->spy_number = number;
4089         }
4090
4091         /* Now, let the others play */
4092         orinoco_unlock(priv, &flags);
4093
4094         /* Do NOT call commit handler */
4095         return 0;
4096 }
4097
4098 static int orinoco_ioctl_getspy(struct net_device *dev,
4099                                 struct iw_request_info *info,
4100                                 struct iw_point *srq,
4101                                 char *extra)
4102 {
4103         struct orinoco_private *priv = netdev_priv(dev);
4104         struct sockaddr *address = (struct sockaddr *) extra;
4105         int number;
4106         int i;
4107         unsigned long flags;
4108
4109         if (orinoco_lock(priv, &flags) != 0)
4110                 return -EBUSY;
4111
4112         number = priv->spy_number;
4113         /* Create address struct */
4114         for (i = 0; i < number; i++) {
4115                 memcpy(address[i].sa_data, priv->spy_address[i], ETH_ALEN);
4116                 address[i].sa_family = AF_UNIX;
4117         }
4118         if (number > 0) {
4119                 /* Create address struct */
4120                 for (i = 0; i < number; i++) {
4121                         memcpy(address[i].sa_data, priv->spy_address[i],
4122                                ETH_ALEN);
4123                         address[i].sa_family = AF_UNIX;
4124                 }
4125                 /* Copy stats */
4126                 /* In theory, we should disable irqs while copying the stats
4127                  * because the rx path might update it in the middle...
4128                  * Bah, who care ? - Jean II */
4129                 memcpy(extra  + (sizeof(struct sockaddr) * number),
4130                        priv->spy_stat, sizeof(struct iw_quality) * number);
4131         }
4132         /* Reset updated flags. */
4133         for (i = 0; i < number; i++)
4134                 priv->spy_stat[i].updated = 0;
4135
4136         orinoco_unlock(priv, &flags);
4137
4138         srq->length = number;
4139
4140         return 0;
4141 }
4142
4143 /* Trigger a scan (look for other cells in the vicinity */
4144 static int orinoco_ioctl_setscan(struct net_device *dev,
4145                                  struct iw_request_info *info,
4146                                  struct iw_param *srq,
4147                                  char *extra)
4148 {
4149         struct orinoco_private *priv = netdev_priv(dev);
4150         hermes_t *hw = &priv->hw;
4151         int err = 0;
4152         unsigned long flags;
4153
4154         /* Note : you may have realised that, as this is a SET operation,
4155          * this is priviledged and therefore a normal user can't
4156          * perform scanning.
4157          * This is not an error, while the device perform scanning,
4158          * traffic doesn't flow, so it's a perfect DoS...
4159          * Jean II */
4160
4161         if (orinoco_lock(priv, &flags) != 0)
4162                 return -EBUSY;
4163
4164         /* Scanning with port 0 disabled would fail */
4165         if (!netif_running(dev)) {
4166                 err = -ENETDOWN;
4167                 goto out;
4168         }
4169
4170         /* In monitor mode, the scan results are always empty.
4171          * Probe responses are passed to the driver as received
4172          * frames and could be processed in software. */
4173         if (priv->iw_mode == IW_MODE_MONITOR) {
4174                 err = -EOPNOTSUPP;
4175                 goto out;
4176         }
4177
4178         /* Note : because we don't lock out the irq handler, the way
4179          * we access scan variables in priv is critical.
4180          *      o scan_inprogress : not touched by irq handler
4181          *      o scan_mode : not touched by irq handler
4182          *      o scan_result : irq is strict producer, non-irq is strict
4183          *              consumer.
4184          *      o scan_len : synchronised with scan_result
4185          * Before modifying anything on those variables, please think hard !
4186          * Jean II */
4187
4188         /* If there is still some left-over scan results, get rid of it */
4189         if (priv->scan_result != NULL) {
4190                 /* What's likely is that a client did crash or was killed
4191                  * between triggering the scan request and reading the
4192                  * results, so we need to reset everything.
4193                  * Some clients that are too slow may suffer from that...
4194                  * Jean II */
4195                 kfree(priv->scan_result);
4196                 priv->scan_result = NULL;
4197         }
4198
4199         /* Save flags */
4200         priv->scan_mode = srq->flags;
4201
4202         /* Always trigger scanning, even if it's in progress.
4203          * This way, if the info frame get lost, we will recover somewhat
4204          * gracefully  - Jean II */
4205
4206         if (priv->has_hostscan) {
4207                 switch (priv->firmware_type) {
4208                 case FIRMWARE_TYPE_SYMBOL:
4209                         err = hermes_write_wordrec(hw, USER_BAP,
4210                                                    HERMES_RID_CNFHOSTSCAN_SYMBOL,
4211                                                    HERMES_HOSTSCAN_SYMBOL_ONCE |
4212                                                    HERMES_HOSTSCAN_SYMBOL_BCAST);
4213                         break;
4214                 case FIRMWARE_TYPE_INTERSIL: {
4215                         u16 req[3];
4216
4217                         req[0] = cpu_to_le16(0x3fff);   /* All channels */
4218                         req[1] = cpu_to_le16(0x0001);   /* rate 1 Mbps */
4219                         req[2] = 0;                     /* Any ESSID */
4220                         err = HERMES_WRITE_RECORD(hw, USER_BAP,
4221                                                   HERMES_RID_CNFHOSTSCAN, &req);
4222                 }
4223                 break;
4224                 case FIRMWARE_TYPE_AGERE:
4225                         err = hermes_write_wordrec(hw, USER_BAP,
4226                                                    HERMES_RID_CNFSCANSSID_AGERE,
4227                                                    0);  /* Any ESSID */
4228                         if (err)
4229                                 break;
4230
4231                         err = hermes_inquire(hw, HERMES_INQ_SCAN);
4232                         break;
4233                 }
4234         } else
4235                 err = hermes_inquire(hw, HERMES_INQ_SCAN);
4236
4237         /* One more client */
4238         if (! err)
4239                 priv->scan_inprogress = 1;
4240
4241  out:
4242         orinoco_unlock(priv, &flags);
4243         return err;
4244 }
4245
4246 /* Translate scan data returned from the card to a card independant
4247  * format that the Wireless Tools will understand - Jean II */
4248 static inline int orinoco_translate_scan(struct net_device *dev,
4249                                          char *buffer,
4250                                          char *scan,
4251                                          int scan_len)
4252 {
4253         struct orinoco_private *priv = netdev_priv(dev);
4254         int                     offset;         /* In the scan data */
4255         union hermes_scan_info *atom;
4256         int                     atom_len;
4257         u16                     capabilities;
4258         u16                     channel;
4259         struct iw_event         iwe;            /* Temporary buffer */
4260         char *                  current_ev = buffer;
4261         char *                  end_buf = buffer + IW_SCAN_MAX_DATA;
4262
4263         switch (priv->firmware_type) {
4264         case FIRMWARE_TYPE_AGERE:
4265                 atom_len = sizeof(struct agere_scan_apinfo);
4266                 offset = 0;
4267                 break;
4268         case FIRMWARE_TYPE_SYMBOL:
4269                 /* Lack of documentation necessitates this hack.
4270                  * Different firmwares have 68 or 76 byte long atoms.
4271                  * We try modulo first.  If the length divides by both,
4272                  * we check what would be the channel in the second
4273                  * frame for a 68-byte atom.  76-byte atoms have 0 there.
4274                  * Valid channel cannot be 0.  */
4275                 if (scan_len % 76)
4276                         atom_len = 68;
4277                 else if (scan_len % 68)
4278                         atom_len = 76;
4279                 else if (scan_len >= 1292 && scan[68] == 0)
4280                         atom_len = 76;
4281                 else
4282                         atom_len = 68;
4283                 offset = 0;
4284                 break;
4285         case FIRMWARE_TYPE_INTERSIL:
4286                 offset = 4;
4287                 if (priv->has_hostscan)
4288                         atom_len = scan[0] + (scan[1] << 8);
4289                 else
4290                         atom_len = offsetof(struct prism2_scan_apinfo, atim);
4291                 break;
4292         default:
4293                 return 0;
4294         }
4295
4296         /* Check that we got an whole number of atoms */
4297         if ((scan_len - offset) % atom_len) {
4298                 printk(KERN_ERR "%s: Unexpected scan data length %d, "
4299                        "atom_len %d, offset %d\n", dev->name, scan_len,
4300                        atom_len, offset);
4301                 return 0;
4302         }
4303
4304         /* Read the entries one by one */
4305         for (; offset + atom_len <= scan_len; offset += atom_len) {
4306                 /* Get next atom */
4307                 atom = (union hermes_scan_info *) (scan + offset);
4308
4309                 /* First entry *MUST* be the AP MAC address */
4310                 iwe.cmd = SIOCGIWAP;
4311                 iwe.u.ap_addr.sa_family = ARPHRD_ETHER;
4312                 memcpy(iwe.u.ap_addr.sa_data, atom->a.bssid, ETH_ALEN);
4313                 current_ev = iwe_stream_add_event(current_ev, end_buf, &iwe, IW_EV_ADDR_LEN);
4314
4315                 /* Other entries will be displayed in the order we give them */
4316
4317                 /* Add the ESSID */
4318                 iwe.u.data.length = le16_to_cpu(atom->a.essid_len);
4319                 if (iwe.u.data.length > 32)
4320                         iwe.u.data.length = 32;
4321                 iwe.cmd = SIOCGIWESSID;
4322                 iwe.u.data.flags = 1;
4323                 current_ev = iwe_stream_add_point(current_ev, end_buf, &iwe, atom->a.essid);
4324
4325                 /* Add mode */
4326                 iwe.cmd = SIOCGIWMODE;
4327                 capabilities = le16_to_cpu(atom->a.capabilities);
4328                 if (capabilities & 0x3) {
4329                         if (capabilities & 0x1)
4330                                 iwe.u.mode = IW_MODE_MASTER;
4331                         else
4332                                 iwe.u.mode = IW_MODE_ADHOC;
4333                         current_ev = iwe_stream_add_event(current_ev, end_buf, &iwe, IW_EV_UINT_LEN);
4334                 }
4335
4336                 channel = atom->s.channel;
4337                 if ( (channel >= 1) && (channel <= NUM_CHANNELS) ) {
4338                         /* Add frequency */
4339                         iwe.cmd = SIOCGIWFREQ;
4340                         iwe.u.freq.m = channel_frequency[channel-1] * 100000;
4341                         iwe.u.freq.e = 1;
4342                         current_ev = iwe_stream_add_event(current_ev, end_buf,
4343                                                           &iwe, IW_EV_FREQ_LEN);
4344                 }
4345
4346                 /* Add quality statistics */
4347                 iwe.cmd = IWEVQUAL;
4348                 iwe.u.qual.updated = 0x10;      /* no link quality */
4349                 iwe.u.qual.level = (__u8) le16_to_cpu(atom->a.level) - 0x95;
4350                 iwe.u.qual.noise = (__u8) le16_to_cpu(atom->a.noise) - 0x95;
4351                 /* Wireless tools prior to 27.pre22 will show link quality
4352                  * anyway, so we provide a reasonable value. */
4353                 if (iwe.u.qual.level > iwe.u.qual.noise)
4354                         iwe.u.qual.qual = iwe.u.qual.level - iwe.u.qual.noise;
4355                 else
4356                         iwe.u.qual.qual = 0;
4357                 current_ev = iwe_stream_add_event(current_ev, end_buf, &iwe, IW_EV_QUAL_LEN);
4358
4359                 /* Add encryption capability */
4360                 iwe.cmd = SIOCGIWENCODE;
4361                 if (capabilities & 0x10)
4362                         iwe.u.data.flags = IW_ENCODE_ENABLED | IW_ENCODE_NOKEY;
4363                 else
4364                         iwe.u.data.flags = IW_ENCODE_DISABLED;
4365                 iwe.u.data.length = 0;
4366                 current_ev = iwe_stream_add_point(current_ev, end_buf, &iwe, atom->a.essid);
4367
4368                 /* Bit rate is not available in Lucent/Agere firmwares */
4369                 if (priv->firmware_type != FIRMWARE_TYPE_AGERE) {
4370                         char *  current_val = current_ev + IW_EV_LCP_LEN;
4371                         int     i;
4372                         int     step;
4373
4374                         if (priv->firmware_type == FIRMWARE_TYPE_SYMBOL)
4375                                 step = 2;
4376                         else
4377                                 step = 1;
4378
4379                         iwe.cmd = SIOCGIWRATE;
4380                         /* Those two flags are ignored... */
4381                         iwe.u.bitrate.fixed = iwe.u.bitrate.disabled = 0;
4382                         /* Max 10 values */
4383                         for (i = 0; i < 10; i += step) {
4384                                 /* NULL terminated */
4385                                 if (atom->p.rates[i] == 0x0)
4386                                         break;
4387                                 /* Bit rate given in 500 kb/s units (+ 0x80) */
4388                                 iwe.u.bitrate.value = ((atom->p.rates[i] & 0x7f) * 500000);
4389                                 current_val = iwe_stream_add_value(current_ev, current_val,
4390                                                                    end_buf, &iwe,
4391                                                                    IW_EV_PARAM_LEN);
4392                         }
4393                         /* Check if we added any event */
4394                         if ((current_val - current_ev) > IW_EV_LCP_LEN)
4395                                 current_ev = current_val;
4396                 }
4397
4398                 /* The other data in the scan result are not really
4399                  * interesting, so for now drop it - Jean II */
4400         }
4401         return current_ev - buffer;
4402 }
4403
4404 /* Return results of a scan */
4405 static int orinoco_ioctl_getscan(struct net_device *dev,
4406                                  struct iw_request_info *info,
4407                                  struct iw_point *srq,
4408                                  char *extra)
4409 {
4410         struct orinoco_private *priv = netdev_priv(dev);
4411         int err = 0;
4412         unsigned long flags;
4413
4414         if (orinoco_lock(priv, &flags) != 0)
4415                 return -EBUSY;
4416
4417         /* If no results yet, ask to try again later */
4418         if (priv->scan_result == NULL) {
4419                 if (priv->scan_inprogress)
4420                         /* Important note : we don't want to block the caller
4421                          * until results are ready for various reasons.
4422                          * First, managing wait queues is complex and racy.
4423                          * Second, we grab some rtnetlink lock before comming
4424                          * here (in dev_ioctl()).
4425                          * Third, we generate an Wireless Event, so the
4426                          * caller can wait itself on that - Jean II */
4427                         err = -EAGAIN;
4428                 else
4429                         /* Client error, no scan results...
4430                          * The caller need to restart the scan. */
4431                         err = -ENODATA;
4432         } else {
4433                 /* We have some results to push back to user space */
4434
4435                 /* Translate to WE format */
4436                 srq->length = orinoco_translate_scan(dev, extra,
4437                                                      priv->scan_result,
4438                                                      priv->scan_len);
4439
4440                 /* Return flags */
4441                 srq->flags = (__u16) priv->scan_mode;
4442
4443                 /* Results are here, so scan no longer in progress */
4444                 priv->scan_inprogress = 0;
4445
4446                 /* In any case, Scan results will be cleaned up in the
4447                  * reset function and when exiting the driver.
4448                  * The person triggering the scanning may never come to
4449                  * pick the results, so we need to do it in those places.
4450                  * Jean II */
4451
4452 #ifdef SCAN_SINGLE_READ
4453                 /* If you enable this option, only one client (the first
4454                  * one) will be able to read the result (and only one
4455                  * time). If there is multiple concurent clients that
4456                  * want to read scan results, this behavior is not
4457                  * advisable - Jean II */
4458                 kfree(priv->scan_result);
4459                 priv->scan_result = NULL;
4460 #endif /* SCAN_SINGLE_READ */
4461                 /* Here, if too much time has elapsed since last scan,
4462                  * we may want to clean up scan results... - Jean II */
4463         }
4464           
4465         orinoco_unlock(priv, &flags);
4466         return err;
4467 }
4468
4469 /* Commit handler, called after set operations */
4470 static int orinoco_ioctl_commit(struct net_device *dev,
4471                                 struct iw_request_info *info,
4472                                 void *wrqu,
4473                                 char *extra)
4474 {
4475         struct orinoco_private *priv = netdev_priv(dev);
4476         struct hermes *hw = &priv->hw;
4477         unsigned long flags;
4478         int err = 0;
4479
4480         if (!priv->open)
4481                 return 0;
4482
4483         if (priv->broken_disableport) {
4484                 orinoco_reset(dev);
4485                 return 0;
4486         }
4487
4488         if (orinoco_lock(priv, &flags) != 0)
4489                 return err;
4490
4491         err = hermes_disable_port(hw, 0);
4492         if (err) {
4493                 printk(KERN_WARNING "%s: Unable to disable port "
4494                        "while reconfiguring card\n", dev->name);
4495                 priv->broken_disableport = 1;
4496                 goto out;
4497         }
4498
4499         err = __orinoco_program_rids(dev);
4500         if (err) {
4501                 printk(KERN_WARNING "%s: Unable to reconfigure card\n",
4502                        dev->name);
4503                 goto out;
4504         }
4505
4506         err = hermes_enable_port(hw, 0);
4507         if (err) {
4508                 printk(KERN_WARNING "%s: Unable to enable port while reconfiguring card\n",
4509                        dev->name);
4510                 goto out;
4511         }
4512
4513  out:
4514         if (err) {
4515                 printk(KERN_WARNING "%s: Resetting instead...\n", dev->name);
4516                 schedule_work(&priv->reset_work);
4517                 err = 0;
4518         }
4519
4520         orinoco_unlock(priv, &flags);
4521         return err;
4522 }
4523
4524 static const struct iw_priv_args orinoco_privtab[] = {
4525         { SIOCIWFIRSTPRIV + 0x0, 0, 0, "force_reset" },
4526         { SIOCIWFIRSTPRIV + 0x1, 0, 0, "card_reset" },
4527         { SIOCIWFIRSTPRIV + 0x2, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,
4528           0, "set_port3" },
4529         { SIOCIWFIRSTPRIV + 0x3, 0, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,
4530           "get_port3" },
4531         { SIOCIWFIRSTPRIV + 0x4, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,
4532           0, "set_preamble" },
4533         { SIOCIWFIRSTPRIV + 0x5, 0, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,
4534           "get_preamble" },
4535         { SIOCIWFIRSTPRIV + 0x6, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,
4536           0, "set_ibssport" },
4537         { SIOCIWFIRSTPRIV + 0x7, 0, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,
4538           "get_ibssport" },
4539         { SIOCIWFIRSTPRIV + 0x9, 0, IW_PRIV_TYPE_BYTE | MAX_RID_LEN,
4540           "get_rid" },
4541 };
4542
4543
4544 /*
4545  * Structures to export the Wireless Handlers
4546  */
4547
4548 static const iw_handler orinoco_handler[] = {
4549         [SIOCSIWCOMMIT-SIOCIWFIRST] (iw_handler) orinoco_ioctl_commit,
4550         [SIOCGIWNAME  -SIOCIWFIRST] (iw_handler) orinoco_ioctl_getname,
4551         [SIOCSIWFREQ  -SIOCIWFIRST] (iw_handler) orinoco_ioctl_setfreq,
4552         [SIOCGIWFREQ  -SIOCIWFIRST] (iw_handler) orinoco_ioctl_getfreq,
4553         [SIOCSIWMODE  -SIOCIWFIRST] (iw_handler) orinoco_ioctl_setmode,
4554         [SIOCGIWMODE  -SIOCIWFIRST] (iw_handler) orinoco_ioctl_getmode,
4555         [SIOCSIWSENS  -SIOCIWFIRST] (iw_handler) orinoco_ioctl_setsens,
4556         [SIOCGIWSENS  -SIOCIWFIRST] (iw_handler) orinoco_ioctl_getsens,
4557         [SIOCGIWRANGE -SIOCIWFIRST] (iw_handler) orinoco_ioctl_getiwrange,
4558         [SIOCSIWSPY   -SIOCIWFIRST] (iw_handler) orinoco_ioctl_setspy,
4559         [SIOCGIWSPY   -SIOCIWFIRST] (iw_handler) orinoco_ioctl_getspy,
4560         [SIOCSIWAP    -SIOCIWFIRST] (iw_handler) orinoco_ioctl_setwap,
4561         [SIOCGIWAP    -SIOCIWFIRST] (iw_handler) orinoco_ioctl_getwap,
4562         [SIOCSIWSCAN  -SIOCIWFIRST] (iw_handler) orinoco_ioctl_setscan,
4563         [SIOCGIWSCAN  -SIOCIWFIRST] (iw_handler) orinoco_ioctl_getscan,
4564         [SIOCSIWESSID -SIOCIWFIRST] (iw_handler) orinoco_ioctl_setessid,
4565         [SIOCGIWESSID -SIOCIWFIRST] (iw_handler) orinoco_ioctl_getessid,
4566         [SIOCSIWNICKN -SIOCIWFIRST] (iw_handler) orinoco_ioctl_setnick,
4567         [SIOCGIWNICKN -SIOCIWFIRST] (iw_handler) orinoco_ioctl_getnick,
4568         [SIOCSIWRATE  -SIOCIWFIRST] (iw_handler) orinoco_ioctl_setrate,
4569         [SIOCGIWRATE  -SIOCIWFIRST] (iw_handler) orinoco_ioctl_getrate,
4570         [SIOCSIWRTS   -SIOCIWFIRST] (iw_handler) orinoco_ioctl_setrts,
4571         [SIOCGIWRTS   -SIOCIWFIRST] (iw_handler) orinoco_ioctl_getrts,
4572         [SIOCSIWFRAG  -SIOCIWFIRST] (iw_handler) orinoco_ioctl_setfrag,
4573         [SIOCGIWFRAG  -SIOCIWFIRST] (iw_handler) orinoco_ioctl_getfrag,
4574         [SIOCGIWRETRY -SIOCIWFIRST] (iw_handler) orinoco_ioctl_getretry,
4575         [SIOCSIWENCODE-SIOCIWFIRST] (iw_handler) orinoco_ioctl_setiwencode,
4576         [SIOCGIWENCODE-SIOCIWFIRST] (iw_handler) orinoco_ioctl_getiwencode,
4577         [SIOCSIWPOWER -SIOCIWFIRST] (iw_handler) orinoco_ioctl_setpower,
4578         [SIOCGIWPOWER -SIOCIWFIRST] (iw_handler) orinoco_ioctl_getpower,
4579 };
4580
4581
4582 /*
4583   Added typecasting since we no longer use iwreq_data -- Moustafa
4584  */
4585 static const iw_handler orinoco_private_handler[] = {
4586         [0] (iw_handler) orinoco_ioctl_reset,
4587         [1] (iw_handler) orinoco_ioctl_reset,
4588         [2] (iw_handler) orinoco_ioctl_setport3,
4589         [3] (iw_handler) orinoco_ioctl_getport3,
4590         [4] (iw_handler) orinoco_ioctl_setpreamble,
4591         [5] (iw_handler) orinoco_ioctl_getpreamble,
4592         [6] (iw_handler) orinoco_ioctl_setibssport,
4593         [7] (iw_handler) orinoco_ioctl_getibssport,
4594         [9] (iw_handler) orinoco_ioctl_getrid,
4595 };
4596
4597 static const struct iw_handler_def orinoco_handler_def = {
4598         .num_standard = ARRAY_SIZE(orinoco_handler),
4599         .num_private = ARRAY_SIZE(orinoco_private_handler),
4600         .num_private_args = ARRAY_SIZE(orinoco_privtab),
4601         .standard = orinoco_handler,
4602         .private = orinoco_private_handler,
4603         .private_args = orinoco_privtab,
4604 };
4605
4606 static void orinoco_get_drvinfo(struct net_device *dev,
4607                                 struct ethtool_drvinfo *info)
4608 {
4609         struct orinoco_private *priv = netdev_priv(dev);
4610
4611         strncpy(info->driver, DRIVER_NAME, sizeof(info->driver) - 1);
4612         strncpy(info->version, DRIVER_VERSION, sizeof(info->version) - 1);
4613         strncpy(info->fw_version, priv->fw_name, sizeof(info->fw_version) - 1);
4614         if (dev->class_dev.dev)
4615                 strncpy(info->bus_info, dev->class_dev.dev->bus_id,
4616                         sizeof(info->bus_info) - 1);
4617         else
4618                 snprintf(info->bus_info, sizeof(info->bus_info) - 1,
4619                          "PCMCIA %p", priv->hw.iobase);
4620 }
4621
4622 static struct ethtool_ops orinoco_ethtool_ops = {
4623         .get_drvinfo = orinoco_get_drvinfo,
4624         .get_link = ethtool_op_get_link,
4625 };
4626
4627 /********************************************************************/
4628 /* Debugging                                                        */
4629 /********************************************************************/
4630
4631 #if 0
4632 static void show_rx_frame(struct orinoco_rxframe_hdr *frame)
4633 {
4634         printk(KERN_DEBUG "RX descriptor:\n");
4635         printk(KERN_DEBUG "  status      = 0x%04x\n", frame->desc.status);
4636         printk(KERN_DEBUG "  time        = 0x%08x\n", frame->desc.time);
4637         printk(KERN_DEBUG "  silence     = 0x%02x\n", frame->desc.silence);
4638         printk(KERN_DEBUG "  signal      = 0x%02x\n", frame->desc.signal);
4639         printk(KERN_DEBUG "  rate        = 0x%02x\n", frame->desc.rate);
4640         printk(KERN_DEBUG "  rxflow      = 0x%02x\n", frame->desc.rxflow);
4641         printk(KERN_DEBUG "  reserved    = 0x%08x\n", frame->desc.reserved);
4642
4643         printk(KERN_DEBUG "IEEE 802.11 header:\n");
4644         printk(KERN_DEBUG "  frame_ctl   = 0x%04x\n",
4645                frame->p80211.frame_ctl);
4646         printk(KERN_DEBUG "  duration_id = 0x%04x\n",
4647                frame->p80211.duration_id);
4648         printk(KERN_DEBUG "  addr1       = %02x:%02x:%02x:%02x:%02x:%02x\n",
4649                frame->p80211.addr1[0], frame->p80211.addr1[1],
4650                frame->p80211.addr1[2], frame->p80211.addr1[3],
4651                frame->p80211.addr1[4], frame->p80211.addr1[5]);
4652         printk(KERN_DEBUG "  addr2       = %02x:%02x:%02x:%02x:%02x:%02x\n",
4653                frame->p80211.addr2[0], frame->p80211.addr2[1],
4654                frame->p80211.addr2[2], frame->p80211.addr2[3],
4655                frame->p80211.addr2[4], frame->p80211.addr2[5]);
4656         printk(KERN_DEBUG "  addr3       = %02x:%02x:%02x:%02x:%02x:%02x\n",
4657                frame->p80211.addr3[0], frame->p80211.addr3[1],
4658                frame->p80211.addr3[2], frame->p80211.addr3[3],
4659                frame->p80211.addr3[4], frame->p80211.addr3[5]);
4660         printk(KERN_DEBUG "  seq_ctl     = 0x%04x\n",
4661                frame->p80211.seq_ctl);
4662         printk(KERN_DEBUG "  addr4       = %02x:%02x:%02x:%02x:%02x:%02x\n",
4663                frame->p80211.addr4[0], frame->p80211.addr4[1],
4664                frame->p80211.addr4[2], frame->p80211.addr4[3],
4665                frame->p80211.addr4[4], frame->p80211.addr4[5]);
4666         printk(KERN_DEBUG "  data_len    = 0x%04x\n",
4667                frame->p80211.data_len);
4668
4669         printk(KERN_DEBUG "IEEE 802.3 header:\n");
4670         printk(KERN_DEBUG "  dest        = %02x:%02x:%02x:%02x:%02x:%02x\n",
4671                frame->p8023.h_dest[0], frame->p8023.h_dest[1],
4672                frame->p8023.h_dest[2], frame->p8023.h_dest[3],
4673                frame->p8023.h_dest[4], frame->p8023.h_dest[5]);
4674         printk(KERN_DEBUG "  src         = %02x:%02x:%02x:%02x:%02x:%02x\n",
4675                frame->p8023.h_source[0], frame->p8023.h_source[1],
4676                frame->p8023.h_source[2], frame->p8023.h_source[3],
4677                frame->p8023.h_source[4], frame->p8023.h_source[5]);
4678         printk(KERN_DEBUG "  len         = 0x%04x\n", frame->p8023.h_proto);
4679
4680         printk(KERN_DEBUG "IEEE 802.2 LLC/SNAP header:\n");
4681         printk(KERN_DEBUG "  DSAP        = 0x%02x\n", frame->p8022.dsap);
4682         printk(KERN_DEBUG "  SSAP        = 0x%02x\n", frame->p8022.ssap);
4683         printk(KERN_DEBUG "  ctrl        = 0x%02x\n", frame->p8022.ctrl);
4684         printk(KERN_DEBUG "  OUI         = %02x:%02x:%02x\n",
4685                frame->p8022.oui[0], frame->p8022.oui[1], frame->p8022.oui[2]);
4686         printk(KERN_DEBUG "  ethertype  = 0x%04x\n", frame->ethertype);
4687 }
4688 #endif /* 0 */
4689
4690 /********************************************************************/
4691 /* Module initialization                                            */
4692 /********************************************************************/
4693
4694 EXPORT_SYMBOL(alloc_orinocodev);
4695 EXPORT_SYMBOL(free_orinocodev);
4696
4697 EXPORT_SYMBOL(__orinoco_up);
4698 EXPORT_SYMBOL(__orinoco_down);
4699 EXPORT_SYMBOL(orinoco_reinit_firmware);
4700
4701 EXPORT_SYMBOL(orinoco_interrupt);
4702
4703 /* Can't be declared "const" or the whole __initdata section will
4704  * become const */
4705 static char version[] __initdata = DRIVER_NAME " " DRIVER_VERSION
4706         " (David Gibson <hermes@gibson.dropbear.id.au>, "
4707         "Pavel Roskin <proski@gnu.org>, et al)";
4708
4709 static int __init init_orinoco(void)
4710 {
4711         printk(KERN_DEBUG "%s\n", version);
4712         return 0;
4713 }
4714
4715 static void __exit exit_orinoco(void)
4716 {
4717 }
4718
4719 module_init(init_orinoco);
4720 module_exit(exit_orinoco);