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