orinoco: Add WE-18 ioctls for WPA
[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  * TODO
50  *      o Handle de-encapsulation within network layer, provide 802.11
51  *        headers (patch from Thomas 'Dent' Mirlacher)
52  *      o Fix possible races in SPY handling.
53  *      o Disconnect wireless extensions from fundamental configuration.
54  *      o (maybe) Software WEP support (patch from Stano Meduna).
55  *      o (maybe) Use multiple Tx buffers - driver handling queue
56  *        rather than firmware.
57  */
58
59 /* Locking and synchronization:
60  *
61  * The basic principle is that everything is serialized through a
62  * single spinlock, priv->lock.  The lock is used in user, bh and irq
63  * context, so when taken outside hardirq context it should always be
64  * taken with interrupts disabled.  The lock protects both the
65  * hardware and the struct orinoco_private.
66  *
67  * Another flag, priv->hw_unavailable indicates that the hardware is
68  * unavailable for an extended period of time (e.g. suspended, or in
69  * the middle of a hard reset).  This flag is protected by the
70  * spinlock.  All code which touches the hardware should check the
71  * flag after taking the lock, and if it is set, give up on whatever
72  * they are doing and drop the lock again.  The orinoco_lock()
73  * function handles this (it unlocks and returns -EBUSY if
74  * hw_unavailable is non-zero).
75  */
76
77 #define DRIVER_NAME "orinoco"
78
79 #include <linux/module.h>
80 #include <linux/kernel.h>
81 #include <linux/init.h>
82 #include <linux/delay.h>
83 #include <linux/netdevice.h>
84 #include <linux/etherdevice.h>
85 #include <linux/ethtool.h>
86 #include <linux/firmware.h>
87 #include <linux/if_arp.h>
88 #include <linux/wireless.h>
89 #include <net/iw_handler.h>
90 #include <net/ieee80211.h>
91
92 #include "hermes_rid.h"
93 #include "hermes_dld.h"
94 #include "orinoco.h"
95
96 /********************************************************************/
97 /* Module information                                               */
98 /********************************************************************/
99
100 MODULE_AUTHOR("Pavel Roskin <proski@gnu.org> & David Gibson <hermes@gibson.dropbear.id.au>");
101 MODULE_DESCRIPTION("Driver for Lucent Orinoco, Prism II based and similar wireless cards");
102 MODULE_LICENSE("Dual MPL/GPL");
103
104 /* Level of debugging. Used in the macros in orinoco.h */
105 #ifdef ORINOCO_DEBUG
106 int orinoco_debug = ORINOCO_DEBUG;
107 module_param(orinoco_debug, int, 0644);
108 MODULE_PARM_DESC(orinoco_debug, "Debug level");
109 EXPORT_SYMBOL(orinoco_debug);
110 #endif
111
112 static int suppress_linkstatus; /* = 0 */
113 module_param(suppress_linkstatus, bool, 0644);
114 MODULE_PARM_DESC(suppress_linkstatus, "Don't log link status changes");
115 static int ignore_disconnect; /* = 0 */
116 module_param(ignore_disconnect, int, 0644);
117 MODULE_PARM_DESC(ignore_disconnect, "Don't report lost link to the network layer");
118
119 static int force_monitor; /* = 0 */
120 module_param(force_monitor, int, 0644);
121 MODULE_PARM_DESC(force_monitor, "Allow monitor mode for all firmware versions");
122
123 /********************************************************************/
124 /* Compile time configuration and compatibility stuff               */
125 /********************************************************************/
126
127 /* We do this this way to avoid ifdefs in the actual code */
128 #ifdef WIRELESS_SPY
129 #define SPY_NUMBER(priv)        (priv->spy_data.spy_number)
130 #else
131 #define SPY_NUMBER(priv)        0
132 #endif /* WIRELESS_SPY */
133
134 /********************************************************************/
135 /* Internal constants                                               */
136 /********************************************************************/
137
138 /* 802.2 LLC/SNAP header used for Ethernet encapsulation over 802.11 */
139 static const u8 encaps_hdr[] = {0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00};
140 #define ENCAPS_OVERHEAD         (sizeof(encaps_hdr) + 2)
141
142 #define ORINOCO_MIN_MTU         256
143 #define ORINOCO_MAX_MTU         (IEEE80211_DATA_LEN - ENCAPS_OVERHEAD)
144
145 #define SYMBOL_MAX_VER_LEN      (14)
146 #define USER_BAP                0
147 #define IRQ_BAP                 1
148 #define MAX_IRQLOOPS_PER_IRQ    10
149 #define MAX_IRQLOOPS_PER_JIFFY  (20000/HZ) /* Based on a guestimate of
150                                             * how many events the
151                                             * device could
152                                             * legitimately generate */
153 #define SMALL_KEY_SIZE          5
154 #define LARGE_KEY_SIZE          13
155 #define TX_NICBUF_SIZE_BUG      1585            /* Bug in Symbol firmware */
156
157 #define DUMMY_FID               0xFFFF
158
159 /*#define MAX_MULTICAST(priv)   (priv->firmware_type == FIRMWARE_TYPE_AGERE ? \
160   HERMES_MAX_MULTICAST : 0)*/
161 #define MAX_MULTICAST(priv)     (HERMES_MAX_MULTICAST)
162
163 #define ORINOCO_INTEN           (HERMES_EV_RX | HERMES_EV_ALLOC \
164                                  | HERMES_EV_TX | HERMES_EV_TXEXC \
165                                  | HERMES_EV_WTERR | HERMES_EV_INFO \
166                                  | HERMES_EV_INFDROP )
167
168 #define MAX_RID_LEN 1024
169
170 static const struct iw_handler_def orinoco_handler_def;
171 static const struct ethtool_ops orinoco_ethtool_ops;
172
173 /********************************************************************/
174 /* Data tables                                                      */
175 /********************************************************************/
176
177 /* The frequency of each channel in MHz */
178 static const long channel_frequency[] = {
179         2412, 2417, 2422, 2427, 2432, 2437, 2442,
180         2447, 2452, 2457, 2462, 2467, 2472, 2484
181 };
182 #define NUM_CHANNELS ARRAY_SIZE(channel_frequency)
183
184 /* This tables gives the actual meanings of the bitrate IDs returned
185  * by the firmware. */
186 static struct {
187         int bitrate; /* in 100s of kilobits */
188         int automatic;
189         u16 agere_txratectrl;
190         u16 intersil_txratectrl;
191 } bitrate_table[] = {
192         {110, 1,  3, 15}, /* Entry 0 is the default */
193         {10,  0,  1,  1},
194         {10,  1,  1,  1},
195         {20,  0,  2,  2},
196         {20,  1,  6,  3},
197         {55,  0,  4,  4},
198         {55,  1,  7,  7},
199         {110, 0,  5,  8},
200 };
201 #define BITRATE_TABLE_SIZE ARRAY_SIZE(bitrate_table)
202
203 /********************************************************************/
204 /* Data types                                                       */
205 /********************************************************************/
206
207 /* Beginning of the Tx descriptor, used in TxExc handling */
208 struct hermes_txexc_data {
209         struct hermes_tx_descriptor desc;
210         __le16 frame_ctl;
211         __le16 duration_id;
212         u8 addr1[ETH_ALEN];
213 } __attribute__ ((packed));
214
215 /* Rx frame header except compatibility 802.3 header */
216 struct hermes_rx_descriptor {
217         /* Control */
218         __le16 status;
219         __le32 time;
220         u8 silence;
221         u8 signal;
222         u8 rate;
223         u8 rxflow;
224         __le32 reserved;
225
226         /* 802.11 header */
227         __le16 frame_ctl;
228         __le16 duration_id;
229         u8 addr1[ETH_ALEN];
230         u8 addr2[ETH_ALEN];
231         u8 addr3[ETH_ALEN];
232         __le16 seq_ctl;
233         u8 addr4[ETH_ALEN];
234
235         /* Data length */
236         __le16 data_len;
237 } __attribute__ ((packed));
238
239 /********************************************************************/
240 /* Function prototypes                                              */
241 /********************************************************************/
242
243 static int __orinoco_program_rids(struct net_device *dev);
244 static void __orinoco_set_multicast_list(struct net_device *dev);
245
246 /********************************************************************/
247 /* Internal helper functions                                        */
248 /********************************************************************/
249
250 static inline void set_port_type(struct orinoco_private *priv)
251 {
252         switch (priv->iw_mode) {
253         case IW_MODE_INFRA:
254                 priv->port_type = 1;
255                 priv->createibss = 0;
256                 break;
257         case IW_MODE_ADHOC:
258                 if (priv->prefer_port3) {
259                         priv->port_type = 3;
260                         priv->createibss = 0;
261                 } else {
262                         priv->port_type = priv->ibss_port;
263                         priv->createibss = 1;
264                 }
265                 break;
266         case IW_MODE_MONITOR:
267                 priv->port_type = 3;
268                 priv->createibss = 0;
269                 break;
270         default:
271                 printk(KERN_ERR "%s: Invalid priv->iw_mode in set_port_type()\n",
272                        priv->ndev->name);
273         }
274 }
275
276 #define ORINOCO_MAX_BSS_COUNT   64
277 static int orinoco_bss_data_allocate(struct orinoco_private *priv)
278 {
279         if (priv->bss_xbss_data)
280                 return 0;
281
282         if (priv->has_ext_scan)
283                 priv->bss_xbss_data = kzalloc(ORINOCO_MAX_BSS_COUNT *
284                                               sizeof(struct xbss_element),
285                                               GFP_KERNEL);
286         else
287                 priv->bss_xbss_data = kzalloc(ORINOCO_MAX_BSS_COUNT *
288                                               sizeof(struct bss_element),
289                                               GFP_KERNEL);
290
291         if (!priv->bss_xbss_data) {
292                 printk(KERN_WARNING "Out of memory allocating beacons");
293                 return -ENOMEM;
294         }
295         return 0;
296 }
297
298 static void orinoco_bss_data_free(struct orinoco_private *priv)
299 {
300         kfree(priv->bss_xbss_data);
301         priv->bss_xbss_data = NULL;
302 }
303
304 #define PRIV_BSS        ((struct bss_element *)priv->bss_xbss_data)
305 #define PRIV_XBSS       ((struct xbss_element *)priv->bss_xbss_data)
306 static void orinoco_bss_data_init(struct orinoco_private *priv)
307 {
308         int i;
309
310         INIT_LIST_HEAD(&priv->bss_free_list);
311         INIT_LIST_HEAD(&priv->bss_list);
312         if (priv->has_ext_scan)
313                 for (i = 0; i < ORINOCO_MAX_BSS_COUNT; i++)
314                         list_add_tail(&(PRIV_XBSS[i].list),
315                                       &priv->bss_free_list);
316         else
317                 for (i = 0; i < ORINOCO_MAX_BSS_COUNT; i++)
318                         list_add_tail(&(PRIV_BSS[i].list),
319                                       &priv->bss_free_list);
320
321 }
322
323 static inline u8 *orinoco_get_ie(u8 *data, size_t len,
324                                  enum ieee80211_mfie eid)
325 {
326         u8 *p = data;
327         while ((p + 2) < (data + len)) {
328                 if (p[0] == eid)
329                         return p;
330                 p += p[1] + 2;
331         }
332         return NULL;
333 }
334
335 #define WPA_OUI_TYPE    "\x00\x50\xF2\x01"
336 #define WPA_SELECTOR_LEN 4
337 static inline u8 *orinoco_get_wpa_ie(u8 *data, size_t len)
338 {
339         u8 *p = data;
340         while ((p + 2 + WPA_SELECTOR_LEN) < (data + len)) {
341                 if ((p[0] == MFIE_TYPE_GENERIC) &&
342                     (memcmp(&p[2], WPA_OUI_TYPE, WPA_SELECTOR_LEN) == 0))
343                         return p;
344                 p += p[1] + 2;
345         }
346         return NULL;
347 }
348
349
350 /********************************************************************/
351 /* Download functionality                                           */
352 /********************************************************************/
353
354 struct fw_info {
355         char *pri_fw;
356         char *sta_fw;
357         char *ap_fw;
358         u32 pda_addr;
359         u16 pda_size;
360 };
361
362 const static struct fw_info orinoco_fw[] = {
363         { "", "agere_sta_fw.bin", "agere_ap_fw.bin", 0x00390000, 1000 },
364         { "", "prism_sta_fw.bin", "prism_ap_fw.bin", 0, 1024 },
365         { "symbol_sp24t_prim_fw", "symbol_sp24t_sec_fw", "", 0x00003100, 0x100 }
366 };
367
368 /* Structure used to access fields in FW
369  * Make sure LE decoding macros are used
370  */
371 struct orinoco_fw_header {
372         char hdr_vers[6];       /* ASCII string for header version */
373         __le16 headersize;      /* Total length of header */
374         __le32 entry_point;     /* NIC entry point */
375         __le32 blocks;          /* Number of blocks to program */
376         __le32 block_offset;    /* Offset of block data from eof header */
377         __le32 pdr_offset;      /* Offset to PDR data from eof header */
378         __le32 pri_offset;      /* Offset to primary plug data */
379         __le32 compat_offset;   /* Offset to compatibility data*/
380         char signature[0];      /* FW signature length headersize-20 */
381 } __attribute__ ((packed));
382
383 /* Download either STA or AP firmware into the card. */
384 static int
385 orinoco_dl_firmware(struct orinoco_private *priv,
386                     const struct fw_info *fw,
387                     int ap)
388 {
389         /* Plug Data Area (PDA) */
390         __le16 pda[512] = { 0 };
391
392         hermes_t *hw = &priv->hw;
393         const struct firmware *fw_entry;
394         const struct orinoco_fw_header *hdr;
395         const unsigned char *first_block;
396         const unsigned char *end;
397         const char *firmware;
398         struct net_device *dev = priv->ndev;
399         int err;
400
401         if (ap)
402                 firmware = fw->ap_fw;
403         else
404                 firmware = fw->sta_fw;
405
406         printk(KERN_DEBUG "%s: Attempting to download firmware %s\n",
407                dev->name, firmware);
408
409         /* Read current plug data */
410         err = hermes_read_pda(hw, pda, fw->pda_addr,
411                               min_t(u16, fw->pda_size, sizeof(pda)), 0);
412         printk(KERN_DEBUG "%s: Read PDA returned %d\n", dev->name, err);
413         if (err)
414                 return err;
415
416         err = request_firmware(&fw_entry, firmware, priv->dev);
417         if (err) {
418                 printk(KERN_ERR "%s: Cannot find firmware %s\n",
419                        dev->name, firmware);
420                 return -ENOENT;
421         }
422
423         hdr = (const struct orinoco_fw_header *) fw_entry->data;
424
425         /* Enable aux port to allow programming */
426         err = hermesi_program_init(hw, le32_to_cpu(hdr->entry_point));
427         printk(KERN_DEBUG "%s: Program init returned %d\n", dev->name, err);
428         if (err != 0)
429                 goto abort;
430
431         /* Program data */
432         first_block = (fw_entry->data +
433                        le16_to_cpu(hdr->headersize) +
434                        le32_to_cpu(hdr->block_offset));
435         end = fw_entry->data + fw_entry->size;
436
437         err = hermes_program(hw, first_block, end);
438         printk(KERN_DEBUG "%s: Program returned %d\n", dev->name, err);
439         if (err != 0)
440                 goto abort;
441
442         /* Update production data */
443         first_block = (fw_entry->data +
444                        le16_to_cpu(hdr->headersize) +
445                        le32_to_cpu(hdr->pdr_offset));
446
447         err = hermes_apply_pda_with_defaults(hw, first_block, pda);
448         printk(KERN_DEBUG "%s: Apply PDA returned %d\n", dev->name, err);
449         if (err)
450                 goto abort;
451
452         /* Tell card we've finished */
453         err = hermesi_program_end(hw);
454         printk(KERN_DEBUG "%s: Program end returned %d\n", dev->name, err);
455         if (err != 0)
456                 goto abort;
457
458         /* Check if we're running */
459         printk(KERN_DEBUG "%s: hermes_present returned %d\n",
460                dev->name, hermes_present(hw));
461
462 abort:
463         release_firmware(fw_entry);
464         return err;
465 }
466
467 /* End markers */
468 #define TEXT_END        0x1A            /* End of text header */
469
470 /*
471  * Process a firmware image - stop the card, load the firmware, reset
472  * the card and make sure it responds.  For the secondary firmware take
473  * care of the PDA - read it and then write it on top of the firmware.
474  */
475 static int
476 symbol_dl_image(struct orinoco_private *priv, const struct fw_info *fw,
477                 const unsigned char *image, const unsigned char *end,
478                 int secondary)
479 {
480         hermes_t *hw = &priv->hw;
481         int ret;
482         const unsigned char *ptr;
483         const unsigned char *first_block;
484
485         /* Plug Data Area (PDA) */
486         __le16 pda[256];
487
488         /* Binary block begins after the 0x1A marker */
489         ptr = image;
490         while (*ptr++ != TEXT_END);
491         first_block = ptr;
492
493         /* Read the PDA from EEPROM */
494         if (secondary) {
495                 ret = hermes_read_pda(hw, pda, fw->pda_addr, sizeof(pda), 1);
496                 if (ret)
497                         return ret;
498         }
499
500         /* Stop the firmware, so that it can be safely rewritten */
501         if (priv->stop_fw) {
502                 ret = priv->stop_fw(priv, 1);
503                 if (ret)
504                         return ret;
505         }
506
507         /* Program the adapter with new firmware */
508         ret = hermes_program(hw, first_block, end);
509         if (ret)
510                 return ret;
511
512         /* Write the PDA to the adapter */
513         if (secondary) {
514                 size_t len = hermes_blocks_length(first_block);
515                 ptr = first_block + len;
516                 ret = hermes_apply_pda(hw, ptr, pda);
517                 if (ret)
518                         return ret;
519         }
520
521         /* Run the firmware */
522         if (priv->stop_fw) {
523                 ret = priv->stop_fw(priv, 0);
524                 if (ret)
525                         return ret;
526         }
527
528         /* Reset hermes chip and make sure it responds */
529         ret = hermes_init(hw);
530
531         /* hermes_reset() should return 0 with the secondary firmware */
532         if (secondary && ret != 0)
533                 return -ENODEV;
534
535         /* And this should work with any firmware */
536         if (!hermes_present(hw))
537                 return -ENODEV;
538
539         return 0;
540 }
541
542
543 /*
544  * Download the firmware into the card, this also does a PCMCIA soft
545  * reset on the card, to make sure it's in a sane state.
546  */
547 static int
548 symbol_dl_firmware(struct orinoco_private *priv,
549                    const struct fw_info *fw)
550 {
551         struct net_device *dev = priv->ndev;
552         int ret;
553         const struct firmware *fw_entry;
554
555         if (request_firmware(&fw_entry, fw->pri_fw,
556                              priv->dev) != 0) {
557                 printk(KERN_ERR "%s: Cannot find firmware: %s\n",
558                        dev->name, fw->pri_fw);
559                 return -ENOENT;
560         }
561
562         /* Load primary firmware */
563         ret = symbol_dl_image(priv, fw, fw_entry->data,
564                               fw_entry->data + fw_entry->size, 0);
565         release_firmware(fw_entry);
566         if (ret) {
567                 printk(KERN_ERR "%s: Primary firmware download failed\n",
568                        dev->name);
569                 return ret;
570         }
571
572         if (request_firmware(&fw_entry, fw->sta_fw,
573                              priv->dev) != 0) {
574                 printk(KERN_ERR "%s: Cannot find firmware: %s\n",
575                        dev->name, fw->sta_fw);
576                 return -ENOENT;
577         }
578
579         /* Load secondary firmware */
580         ret = symbol_dl_image(priv, fw, fw_entry->data,
581                               fw_entry->data + fw_entry->size, 1);
582         release_firmware(fw_entry);
583         if (ret) {
584                 printk(KERN_ERR "%s: Secondary firmware download failed\n",
585                        dev->name);
586         }
587
588         return ret;
589 }
590
591 static int orinoco_download(struct orinoco_private *priv)
592 {
593         int err = 0;
594         /* Reload firmware */
595         switch (priv->firmware_type) {
596         case FIRMWARE_TYPE_AGERE:
597                 /* case FIRMWARE_TYPE_INTERSIL: */
598                 err = orinoco_dl_firmware(priv,
599                                           &orinoco_fw[priv->firmware_type], 0);
600                 break;
601
602         case FIRMWARE_TYPE_SYMBOL:
603                 err = symbol_dl_firmware(priv,
604                                          &orinoco_fw[priv->firmware_type]);
605                 break;
606         case FIRMWARE_TYPE_INTERSIL:
607                 break;
608         }
609         /* TODO: if we fail we probably need to reinitialise
610          * the driver */
611
612         return err;
613 }
614
615 /********************************************************************/
616 /* Device methods                                                   */
617 /********************************************************************/
618
619 static int orinoco_open(struct net_device *dev)
620 {
621         struct orinoco_private *priv = netdev_priv(dev);
622         unsigned long flags;
623         int err;
624
625         if (orinoco_lock(priv, &flags) != 0)
626                 return -EBUSY;
627
628         err = __orinoco_up(dev);
629
630         if (! err)
631                 priv->open = 1;
632
633         orinoco_unlock(priv, &flags);
634
635         return err;
636 }
637
638 static int orinoco_stop(struct net_device *dev)
639 {
640         struct orinoco_private *priv = netdev_priv(dev);
641         int err = 0;
642
643         /* We mustn't use orinoco_lock() here, because we need to be
644            able to close the interface even if hw_unavailable is set
645            (e.g. as we're released after a PC Card removal) */
646         spin_lock_irq(&priv->lock);
647
648         priv->open = 0;
649
650         err = __orinoco_down(dev);
651
652         spin_unlock_irq(&priv->lock);
653
654         return err;
655 }
656
657 static struct net_device_stats *orinoco_get_stats(struct net_device *dev)
658 {
659         struct orinoco_private *priv = netdev_priv(dev);
660         
661         return &priv->stats;
662 }
663
664 static struct iw_statistics *orinoco_get_wireless_stats(struct net_device *dev)
665 {
666         struct orinoco_private *priv = netdev_priv(dev);
667         hermes_t *hw = &priv->hw;
668         struct iw_statistics *wstats = &priv->wstats;
669         int err;
670         unsigned long flags;
671
672         if (! netif_device_present(dev)) {
673                 printk(KERN_WARNING "%s: get_wireless_stats() called while device not present\n",
674                        dev->name);
675                 return NULL; /* FIXME: Can we do better than this? */
676         }
677
678         /* If busy, return the old stats.  Returning NULL may cause
679          * the interface to disappear from /proc/net/wireless */
680         if (orinoco_lock(priv, &flags) != 0)
681                 return wstats;
682
683         /* We can't really wait for the tallies inquiry command to
684          * complete, so we just use the previous results and trigger
685          * a new tallies inquiry command for next time - Jean II */
686         /* FIXME: Really we should wait for the inquiry to come back -
687          * as it is the stats we give don't make a whole lot of sense.
688          * Unfortunately, it's not clear how to do that within the
689          * wireless extensions framework: I think we're in user
690          * context, but a lock seems to be held by the time we get in
691          * here so we're not safe to sleep here. */
692         hermes_inquire(hw, HERMES_INQ_TALLIES);
693
694         if (priv->iw_mode == IW_MODE_ADHOC) {
695                 memset(&wstats->qual, 0, sizeof(wstats->qual));
696                 /* If a spy address is defined, we report stats of the
697                  * first spy address - Jean II */
698                 if (SPY_NUMBER(priv)) {
699                         wstats->qual.qual = priv->spy_data.spy_stat[0].qual;
700                         wstats->qual.level = priv->spy_data.spy_stat[0].level;
701                         wstats->qual.noise = priv->spy_data.spy_stat[0].noise;
702                         wstats->qual.updated = priv->spy_data.spy_stat[0].updated;
703                 }
704         } else {
705                 struct {
706                         __le16 qual, signal, noise, unused;
707                 } __attribute__ ((packed)) cq;
708
709                 err = HERMES_READ_RECORD(hw, USER_BAP,
710                                          HERMES_RID_COMMSQUALITY, &cq);
711
712                 if (!err) {
713                         wstats->qual.qual = (int)le16_to_cpu(cq.qual);
714                         wstats->qual.level = (int)le16_to_cpu(cq.signal) - 0x95;
715                         wstats->qual.noise = (int)le16_to_cpu(cq.noise) - 0x95;
716                         wstats->qual.updated = 7;
717                 }
718         }
719
720         orinoco_unlock(priv, &flags);
721         return wstats;
722 }
723
724 static void orinoco_set_multicast_list(struct net_device *dev)
725 {
726         struct orinoco_private *priv = netdev_priv(dev);
727         unsigned long flags;
728
729         if (orinoco_lock(priv, &flags) != 0) {
730                 printk(KERN_DEBUG "%s: orinoco_set_multicast_list() "
731                        "called when hw_unavailable\n", dev->name);
732                 return;
733         }
734
735         __orinoco_set_multicast_list(dev);
736         orinoco_unlock(priv, &flags);
737 }
738
739 static int orinoco_change_mtu(struct net_device *dev, int new_mtu)
740 {
741         struct orinoco_private *priv = netdev_priv(dev);
742
743         if ( (new_mtu < ORINOCO_MIN_MTU) || (new_mtu > ORINOCO_MAX_MTU) )
744                 return -EINVAL;
745
746         if ( (new_mtu + ENCAPS_OVERHEAD + IEEE80211_HLEN) >
747              (priv->nicbuf_size - ETH_HLEN) )
748                 return -EINVAL;
749
750         dev->mtu = new_mtu;
751
752         return 0;
753 }
754
755 /********************************************************************/
756 /* Tx path                                                          */
757 /********************************************************************/
758
759 static int orinoco_xmit(struct sk_buff *skb, struct net_device *dev)
760 {
761         struct orinoco_private *priv = netdev_priv(dev);
762         struct net_device_stats *stats = &priv->stats;
763         hermes_t *hw = &priv->hw;
764         int err = 0;
765         u16 txfid = priv->txfid;
766         struct ethhdr *eh;
767         int data_off;
768         int tx_control;
769         unsigned long flags;
770
771         if (! netif_running(dev)) {
772                 printk(KERN_ERR "%s: Tx on stopped device!\n",
773                        dev->name);
774                 return NETDEV_TX_BUSY;
775         }
776         
777         if (netif_queue_stopped(dev)) {
778                 printk(KERN_DEBUG "%s: Tx while transmitter busy!\n", 
779                        dev->name);
780                 return NETDEV_TX_BUSY;
781         }
782         
783         if (orinoco_lock(priv, &flags) != 0) {
784                 printk(KERN_ERR "%s: orinoco_xmit() called while hw_unavailable\n",
785                        dev->name);
786                 return NETDEV_TX_BUSY;
787         }
788
789         if (! netif_carrier_ok(dev) || (priv->iw_mode == IW_MODE_MONITOR)) {
790                 /* Oops, the firmware hasn't established a connection,
791                    silently drop the packet (this seems to be the
792                    safest approach). */
793                 goto drop;
794         }
795
796         /* Check packet length */
797         if (skb->len < ETH_HLEN)
798                 goto drop;
799
800         eh = (struct ethhdr *)skb->data;
801
802         tx_control = HERMES_TXCTRL_TX_OK | HERMES_TXCTRL_TX_EX;
803
804         if (priv->has_alt_txcntl) {
805                 /* WPA enabled firmwares have tx_cntl at the end of
806                  * the 802.11 header.  So write zeroed descriptor and
807                  * 802.11 header at the same time
808                  */
809                 char desc[HERMES_802_3_OFFSET];
810                 __le16 *txcntl = (__le16 *) &desc[HERMES_TXCNTL2_OFFSET];
811
812                 memset(&desc, 0, sizeof(desc));
813
814                 *txcntl = cpu_to_le16(tx_control);
815                 err = hermes_bap_pwrite(hw, USER_BAP, &desc, sizeof(desc),
816                                         txfid, 0);
817                 if (err) {
818                         if (net_ratelimit())
819                                 printk(KERN_ERR "%s: Error %d writing Tx "
820                                        "descriptor to BAP\n", dev->name, err);
821                         goto busy;
822                 }
823         } else {
824                 struct hermes_tx_descriptor desc;
825
826                 memset(&desc, 0, sizeof(desc));
827
828                 desc.tx_control = cpu_to_le16(tx_control);
829                 err = hermes_bap_pwrite(hw, USER_BAP, &desc, sizeof(desc),
830                                         txfid, 0);
831                 if (err) {
832                         if (net_ratelimit())
833                                 printk(KERN_ERR "%s: Error %d writing Tx "
834                                        "descriptor to BAP\n", dev->name, err);
835                         goto busy;
836                 }
837
838                 /* Clear the 802.11 header and data length fields - some
839                  * firmwares (e.g. Lucent/Agere 8.xx) appear to get confused
840                  * if this isn't done. */
841                 hermes_clear_words(hw, HERMES_DATA0,
842                                    HERMES_802_3_OFFSET - HERMES_802_11_OFFSET);
843         }
844
845         /* Encapsulate Ethernet-II frames */
846         if (ntohs(eh->h_proto) > ETH_DATA_LEN) { /* Ethernet-II frame */
847                 struct header_struct {
848                         struct ethhdr eth;      /* 802.3 header */
849                         u8 encap[6];            /* 802.2 header */
850                 } __attribute__ ((packed)) hdr;
851
852                 /* Strip destination and source from the data */
853                 skb_pull(skb, 2 * ETH_ALEN);
854                 data_off = HERMES_802_2_OFFSET + sizeof(encaps_hdr);
855
856                 /* And move them to a separate header */
857                 memcpy(&hdr.eth, eh, 2 * ETH_ALEN);
858                 hdr.eth.h_proto = htons(sizeof(encaps_hdr) + skb->len);
859                 memcpy(hdr.encap, encaps_hdr, sizeof(encaps_hdr));
860
861                 err = hermes_bap_pwrite(hw, USER_BAP, &hdr, sizeof(hdr),
862                                         txfid, HERMES_802_3_OFFSET);
863                 if (err) {
864                         if (net_ratelimit())
865                                 printk(KERN_ERR "%s: Error %d writing packet "
866                                        "header to BAP\n", dev->name, err);
867                         goto busy;
868                 }
869         } else { /* IEEE 802.3 frame */
870                 data_off = HERMES_802_3_OFFSET;
871         }
872
873         err = hermes_bap_pwrite(hw, USER_BAP, skb->data, skb->len,
874                                 txfid, data_off);
875         if (err) {
876                 printk(KERN_ERR "%s: Error %d writing packet to BAP\n",
877                        dev->name, err);
878                 goto busy;
879         }
880
881         /* Finally, we actually initiate the send */
882         netif_stop_queue(dev);
883
884         err = hermes_docmd_wait(hw, HERMES_CMD_TX | HERMES_CMD_RECL,
885                                 txfid, NULL);
886         if (err) {
887                 netif_start_queue(dev);
888                 if (net_ratelimit())
889                         printk(KERN_ERR "%s: Error %d transmitting packet\n",
890                                 dev->name, err);
891                 goto busy;
892         }
893
894         dev->trans_start = jiffies;
895         stats->tx_bytes += data_off + skb->len;
896         goto ok;
897
898  drop:
899         stats->tx_errors++;
900         stats->tx_dropped++;
901
902  ok:
903         orinoco_unlock(priv, &flags);
904         dev_kfree_skb(skb);
905         return NETDEV_TX_OK;
906
907  busy:
908         if (err == -EIO)
909                 schedule_work(&priv->reset_work);
910         orinoco_unlock(priv, &flags);
911         return NETDEV_TX_BUSY;
912 }
913
914 static void __orinoco_ev_alloc(struct net_device *dev, hermes_t *hw)
915 {
916         struct orinoco_private *priv = netdev_priv(dev);
917         u16 fid = hermes_read_regn(hw, ALLOCFID);
918
919         if (fid != priv->txfid) {
920                 if (fid != DUMMY_FID)
921                         printk(KERN_WARNING "%s: Allocate event on unexpected fid (%04X)\n",
922                                dev->name, fid);
923                 return;
924         }
925
926         hermes_write_regn(hw, ALLOCFID, DUMMY_FID);
927 }
928
929 static void __orinoco_ev_tx(struct net_device *dev, hermes_t *hw)
930 {
931         struct orinoco_private *priv = netdev_priv(dev);
932         struct net_device_stats *stats = &priv->stats;
933
934         stats->tx_packets++;
935
936         netif_wake_queue(dev);
937
938         hermes_write_regn(hw, TXCOMPLFID, DUMMY_FID);
939 }
940
941 static void __orinoco_ev_txexc(struct net_device *dev, hermes_t *hw)
942 {
943         struct orinoco_private *priv = netdev_priv(dev);
944         struct net_device_stats *stats = &priv->stats;
945         u16 fid = hermes_read_regn(hw, TXCOMPLFID);
946         u16 status;
947         struct hermes_txexc_data hdr;
948         int err = 0;
949
950         if (fid == DUMMY_FID)
951                 return; /* Nothing's really happened */
952
953         /* Read part of the frame header - we need status and addr1 */
954         err = hermes_bap_pread(hw, IRQ_BAP, &hdr,
955                                sizeof(struct hermes_txexc_data),
956                                fid, 0);
957
958         hermes_write_regn(hw, TXCOMPLFID, DUMMY_FID);
959         stats->tx_errors++;
960
961         if (err) {
962                 printk(KERN_WARNING "%s: Unable to read descriptor on Tx error "
963                        "(FID=%04X error %d)\n",
964                        dev->name, fid, err);
965                 return;
966         }
967         
968         DEBUG(1, "%s: Tx error, err %d (FID=%04X)\n", dev->name,
969               err, fid);
970     
971         /* We produce a TXDROP event only for retry or lifetime
972          * exceeded, because that's the only status that really mean
973          * that this particular node went away.
974          * Other errors means that *we* screwed up. - Jean II */
975         status = le16_to_cpu(hdr.desc.status);
976         if (status & (HERMES_TXSTAT_RETRYERR | HERMES_TXSTAT_AGEDERR)) {
977                 union iwreq_data        wrqu;
978
979                 /* Copy 802.11 dest address.
980                  * We use the 802.11 header because the frame may
981                  * not be 802.3 or may be mangled...
982                  * In Ad-Hoc mode, it will be the node address.
983                  * In managed mode, it will be most likely the AP addr
984                  * User space will figure out how to convert it to
985                  * whatever it needs (IP address or else).
986                  * - Jean II */
987                 memcpy(wrqu.addr.sa_data, hdr.addr1, ETH_ALEN);
988                 wrqu.addr.sa_family = ARPHRD_ETHER;
989
990                 /* Send event to user space */
991                 wireless_send_event(dev, IWEVTXDROP, &wrqu, NULL);
992         }
993
994         netif_wake_queue(dev);
995 }
996
997 static void orinoco_tx_timeout(struct net_device *dev)
998 {
999         struct orinoco_private *priv = netdev_priv(dev);
1000         struct net_device_stats *stats = &priv->stats;
1001         struct hermes *hw = &priv->hw;
1002
1003         printk(KERN_WARNING "%s: Tx timeout! "
1004                "ALLOCFID=%04x, TXCOMPLFID=%04x, EVSTAT=%04x\n",
1005                dev->name, hermes_read_regn(hw, ALLOCFID),
1006                hermes_read_regn(hw, TXCOMPLFID), hermes_read_regn(hw, EVSTAT));
1007
1008         stats->tx_errors++;
1009
1010         schedule_work(&priv->reset_work);
1011 }
1012
1013 /********************************************************************/
1014 /* Rx path (data frames)                                            */
1015 /********************************************************************/
1016
1017 /* Does the frame have a SNAP header indicating it should be
1018  * de-encapsulated to Ethernet-II? */
1019 static inline int is_ethersnap(void *_hdr)
1020 {
1021         u8 *hdr = _hdr;
1022
1023         /* We de-encapsulate all packets which, a) have SNAP headers
1024          * (i.e. SSAP=DSAP=0xaa and CTRL=0x3 in the 802.2 LLC header
1025          * and where b) the OUI of the SNAP header is 00:00:00 or
1026          * 00:00:f8 - we need both because different APs appear to use
1027          * different OUIs for some reason */
1028         return (memcmp(hdr, &encaps_hdr, 5) == 0)
1029                 && ( (hdr[5] == 0x00) || (hdr[5] == 0xf8) );
1030 }
1031
1032 static inline void orinoco_spy_gather(struct net_device *dev, u_char *mac,
1033                                       int level, int noise)
1034 {
1035         struct iw_quality wstats;
1036         wstats.level = level - 0x95;
1037         wstats.noise = noise - 0x95;
1038         wstats.qual = (level > noise) ? (level - noise) : 0;
1039         wstats.updated = 7;
1040         /* Update spy records */
1041         wireless_spy_update(dev, mac, &wstats);
1042 }
1043
1044 static void orinoco_stat_gather(struct net_device *dev,
1045                                 struct sk_buff *skb,
1046                                 struct hermes_rx_descriptor *desc)
1047 {
1048         struct orinoco_private *priv = netdev_priv(dev);
1049
1050         /* Using spy support with lots of Rx packets, like in an
1051          * infrastructure (AP), will really slow down everything, because
1052          * the MAC address must be compared to each entry of the spy list.
1053          * If the user really asks for it (set some address in the
1054          * spy list), we do it, but he will pay the price.
1055          * Note that to get here, you need both WIRELESS_SPY
1056          * compiled in AND some addresses in the list !!!
1057          */
1058         /* Note : gcc will optimise the whole section away if
1059          * WIRELESS_SPY is not defined... - Jean II */
1060         if (SPY_NUMBER(priv)) {
1061                 orinoco_spy_gather(dev, skb_mac_header(skb) + ETH_ALEN,
1062                                    desc->signal, desc->silence);
1063         }
1064 }
1065
1066 /*
1067  * orinoco_rx_monitor - handle received monitor frames.
1068  *
1069  * Arguments:
1070  *      dev             network device
1071  *      rxfid           received FID
1072  *      desc            rx descriptor of the frame
1073  *
1074  * Call context: interrupt
1075  */
1076 static void orinoco_rx_monitor(struct net_device *dev, u16 rxfid,
1077                                struct hermes_rx_descriptor *desc)
1078 {
1079         u32 hdrlen = 30;        /* return full header by default */
1080         u32 datalen = 0;
1081         u16 fc;
1082         int err;
1083         int len;
1084         struct sk_buff *skb;
1085         struct orinoco_private *priv = netdev_priv(dev);
1086         struct net_device_stats *stats = &priv->stats;
1087         hermes_t *hw = &priv->hw;
1088
1089         len = le16_to_cpu(desc->data_len);
1090
1091         /* Determine the size of the header and the data */
1092         fc = le16_to_cpu(desc->frame_ctl);
1093         switch (fc & IEEE80211_FCTL_FTYPE) {
1094         case IEEE80211_FTYPE_DATA:
1095                 if ((fc & IEEE80211_FCTL_TODS)
1096                     && (fc & IEEE80211_FCTL_FROMDS))
1097                         hdrlen = 30;
1098                 else
1099                         hdrlen = 24;
1100                 datalen = len;
1101                 break;
1102         case IEEE80211_FTYPE_MGMT:
1103                 hdrlen = 24;
1104                 datalen = len;
1105                 break;
1106         case IEEE80211_FTYPE_CTL:
1107                 switch (fc & IEEE80211_FCTL_STYPE) {
1108                 case IEEE80211_STYPE_PSPOLL:
1109                 case IEEE80211_STYPE_RTS:
1110                 case IEEE80211_STYPE_CFEND:
1111                 case IEEE80211_STYPE_CFENDACK:
1112                         hdrlen = 16;
1113                         break;
1114                 case IEEE80211_STYPE_CTS:
1115                 case IEEE80211_STYPE_ACK:
1116                         hdrlen = 10;
1117                         break;
1118                 }
1119                 break;
1120         default:
1121                 /* Unknown frame type */
1122                 break;
1123         }
1124
1125         /* sanity check the length */
1126         if (datalen > IEEE80211_DATA_LEN + 12) {
1127                 printk(KERN_DEBUG "%s: oversized monitor frame, "
1128                        "data length = %d\n", dev->name, datalen);
1129                 stats->rx_length_errors++;
1130                 goto update_stats;
1131         }
1132
1133         skb = dev_alloc_skb(hdrlen + datalen);
1134         if (!skb) {
1135                 printk(KERN_WARNING "%s: Cannot allocate skb for monitor frame\n",
1136                        dev->name);
1137                 goto update_stats;
1138         }
1139
1140         /* Copy the 802.11 header to the skb */
1141         memcpy(skb_put(skb, hdrlen), &(desc->frame_ctl), hdrlen);
1142         skb_reset_mac_header(skb);
1143
1144         /* If any, copy the data from the card to the skb */
1145         if (datalen > 0) {
1146                 err = hermes_bap_pread(hw, IRQ_BAP, skb_put(skb, datalen),
1147                                        ALIGN(datalen, 2), rxfid,
1148                                        HERMES_802_2_OFFSET);
1149                 if (err) {
1150                         printk(KERN_ERR "%s: error %d reading monitor frame\n",
1151                                dev->name, err);
1152                         goto drop;
1153                 }
1154         }
1155
1156         skb->dev = dev;
1157         skb->ip_summed = CHECKSUM_NONE;
1158         skb->pkt_type = PACKET_OTHERHOST;
1159         skb->protocol = __constant_htons(ETH_P_802_2);
1160         
1161         dev->last_rx = jiffies;
1162         stats->rx_packets++;
1163         stats->rx_bytes += skb->len;
1164
1165         netif_rx(skb);
1166         return;
1167
1168  drop:
1169         dev_kfree_skb_irq(skb);
1170  update_stats:
1171         stats->rx_errors++;
1172         stats->rx_dropped++;
1173 }
1174
1175 static void __orinoco_ev_rx(struct net_device *dev, hermes_t *hw)
1176 {
1177         struct orinoco_private *priv = netdev_priv(dev);
1178         struct net_device_stats *stats = &priv->stats;
1179         struct iw_statistics *wstats = &priv->wstats;
1180         struct sk_buff *skb = NULL;
1181         u16 rxfid, status, fc;
1182         int length;
1183         struct hermes_rx_descriptor desc;
1184         struct ethhdr *hdr;
1185         int err;
1186
1187         rxfid = hermes_read_regn(hw, RXFID);
1188
1189         err = hermes_bap_pread(hw, IRQ_BAP, &desc, sizeof(desc),
1190                                rxfid, 0);
1191         if (err) {
1192                 printk(KERN_ERR "%s: error %d reading Rx descriptor. "
1193                        "Frame dropped.\n", dev->name, err);
1194                 goto update_stats;
1195         }
1196
1197         status = le16_to_cpu(desc.status);
1198
1199         if (status & HERMES_RXSTAT_BADCRC) {
1200                 DEBUG(1, "%s: Bad CRC on Rx. Frame dropped.\n",
1201                       dev->name);
1202                 stats->rx_crc_errors++;
1203                 goto update_stats;
1204         }
1205
1206         /* Handle frames in monitor mode */
1207         if (priv->iw_mode == IW_MODE_MONITOR) {
1208                 orinoco_rx_monitor(dev, rxfid, &desc);
1209                 return;
1210         }
1211
1212         if (status & HERMES_RXSTAT_UNDECRYPTABLE) {
1213                 DEBUG(1, "%s: Undecryptable frame on Rx. Frame dropped.\n",
1214                       dev->name);
1215                 wstats->discard.code++;
1216                 goto update_stats;
1217         }
1218
1219         length = le16_to_cpu(desc.data_len);
1220         fc = le16_to_cpu(desc.frame_ctl);
1221
1222         /* Sanity checks */
1223         if (length < 3) { /* No for even an 802.2 LLC header */
1224                 /* At least on Symbol firmware with PCF we get quite a
1225                    lot of these legitimately - Poll frames with no
1226                    data. */
1227                 return;
1228         }
1229         if (length > IEEE80211_DATA_LEN) {
1230                 printk(KERN_WARNING "%s: Oversized frame received (%d bytes)\n",
1231                        dev->name, length);
1232                 stats->rx_length_errors++;
1233                 goto update_stats;
1234         }
1235
1236         /* We need space for the packet data itself, plus an ethernet
1237            header, plus 2 bytes so we can align the IP header on a
1238            32bit boundary, plus 1 byte so we can read in odd length
1239            packets from the card, which has an IO granularity of 16
1240            bits */  
1241         skb = dev_alloc_skb(length+ETH_HLEN+2+1);
1242         if (!skb) {
1243                 printk(KERN_WARNING "%s: Can't allocate skb for Rx\n",
1244                        dev->name);
1245                 goto update_stats;
1246         }
1247
1248         /* We'll prepend the header, so reserve space for it.  The worst
1249            case is no decapsulation, when 802.3 header is prepended and
1250            nothing is removed.  2 is for aligning the IP header.  */
1251         skb_reserve(skb, ETH_HLEN + 2);
1252
1253         err = hermes_bap_pread(hw, IRQ_BAP, skb_put(skb, length),
1254                                ALIGN(length, 2), rxfid,
1255                                HERMES_802_2_OFFSET);
1256         if (err) {
1257                 printk(KERN_ERR "%s: error %d reading frame. "
1258                        "Frame dropped.\n", dev->name, err);
1259                 goto drop;
1260         }
1261
1262         /* Handle decapsulation
1263          * In most cases, the firmware tell us about SNAP frames.
1264          * For some reason, the SNAP frames sent by LinkSys APs
1265          * are not properly recognised by most firmwares.
1266          * So, check ourselves */
1267         if (length >= ENCAPS_OVERHEAD &&
1268             (((status & HERMES_RXSTAT_MSGTYPE) == HERMES_RXSTAT_1042) ||
1269              ((status & HERMES_RXSTAT_MSGTYPE) == HERMES_RXSTAT_TUNNEL) ||
1270              is_ethersnap(skb->data))) {
1271                 /* These indicate a SNAP within 802.2 LLC within
1272                    802.11 frame which we'll need to de-encapsulate to
1273                    the original EthernetII frame. */
1274                 hdr = (struct ethhdr *)skb_push(skb, ETH_HLEN - ENCAPS_OVERHEAD);
1275         } else {
1276                 /* 802.3 frame - prepend 802.3 header as is */
1277                 hdr = (struct ethhdr *)skb_push(skb, ETH_HLEN);
1278                 hdr->h_proto = htons(length);
1279         }
1280         memcpy(hdr->h_dest, desc.addr1, ETH_ALEN);
1281         if (fc & IEEE80211_FCTL_FROMDS)
1282                 memcpy(hdr->h_source, desc.addr3, ETH_ALEN);
1283         else
1284                 memcpy(hdr->h_source, desc.addr2, ETH_ALEN);
1285
1286         dev->last_rx = jiffies;
1287         skb->protocol = eth_type_trans(skb, dev);
1288         skb->ip_summed = CHECKSUM_NONE;
1289         if (fc & IEEE80211_FCTL_TODS)
1290                 skb->pkt_type = PACKET_OTHERHOST;
1291         
1292         /* Process the wireless stats if needed */
1293         orinoco_stat_gather(dev, skb, &desc);
1294
1295         /* Pass the packet to the networking stack */
1296         netif_rx(skb);
1297         stats->rx_packets++;
1298         stats->rx_bytes += length;
1299
1300         return;
1301
1302  drop:  
1303         dev_kfree_skb_irq(skb);
1304  update_stats:
1305         stats->rx_errors++;
1306         stats->rx_dropped++;
1307 }
1308
1309 /********************************************************************/
1310 /* Rx path (info frames)                                            */
1311 /********************************************************************/
1312
1313 static void print_linkstatus(struct net_device *dev, u16 status)
1314 {
1315         char * s;
1316
1317         if (suppress_linkstatus)
1318                 return;
1319
1320         switch (status) {
1321         case HERMES_LINKSTATUS_NOT_CONNECTED:
1322                 s = "Not Connected";
1323                 break;
1324         case HERMES_LINKSTATUS_CONNECTED:
1325                 s = "Connected";
1326                 break;
1327         case HERMES_LINKSTATUS_DISCONNECTED:
1328                 s = "Disconnected";
1329                 break;
1330         case HERMES_LINKSTATUS_AP_CHANGE:
1331                 s = "AP Changed";
1332                 break;
1333         case HERMES_LINKSTATUS_AP_OUT_OF_RANGE:
1334                 s = "AP Out of Range";
1335                 break;
1336         case HERMES_LINKSTATUS_AP_IN_RANGE:
1337                 s = "AP In Range";
1338                 break;
1339         case HERMES_LINKSTATUS_ASSOC_FAILED:
1340                 s = "Association Failed";
1341                 break;
1342         default:
1343                 s = "UNKNOWN";
1344         }
1345         
1346         printk(KERN_INFO "%s: New link status: %s (%04x)\n",
1347                dev->name, s, status);
1348 }
1349
1350 /* Search scan results for requested BSSID, join it if found */
1351 static void orinoco_join_ap(struct work_struct *work)
1352 {
1353         struct orinoco_private *priv =
1354                 container_of(work, struct orinoco_private, join_work);
1355         struct net_device *dev = priv->ndev;
1356         struct hermes *hw = &priv->hw;
1357         int err;
1358         unsigned long flags;
1359         struct join_req {
1360                 u8 bssid[ETH_ALEN];
1361                 __le16 channel;
1362         } __attribute__ ((packed)) req;
1363         const int atom_len = offsetof(struct prism2_scan_apinfo, atim);
1364         struct prism2_scan_apinfo *atom = NULL;
1365         int offset = 4;
1366         int found = 0;
1367         u8 *buf;
1368         u16 len;
1369
1370         /* Allocate buffer for scan results */
1371         buf = kmalloc(MAX_SCAN_LEN, GFP_KERNEL);
1372         if (! buf)
1373                 return;
1374
1375         if (orinoco_lock(priv, &flags) != 0)
1376                 goto fail_lock;
1377
1378         /* Sanity checks in case user changed something in the meantime */
1379         if (! priv->bssid_fixed)
1380                 goto out;
1381
1382         if (strlen(priv->desired_essid) == 0)
1383                 goto out;
1384
1385         /* Read scan results from the firmware */
1386         err = hermes_read_ltv(hw, USER_BAP,
1387                               HERMES_RID_SCANRESULTSTABLE,
1388                               MAX_SCAN_LEN, &len, buf);
1389         if (err) {
1390                 printk(KERN_ERR "%s: Cannot read scan results\n",
1391                        dev->name);
1392                 goto out;
1393         }
1394
1395         len = HERMES_RECLEN_TO_BYTES(len);
1396
1397         /* Go through the scan results looking for the channel of the AP
1398          * we were requested to join */
1399         for (; offset + atom_len <= len; offset += atom_len) {
1400                 atom = (struct prism2_scan_apinfo *) (buf + offset);
1401                 if (memcmp(&atom->bssid, priv->desired_bssid, ETH_ALEN) == 0) {
1402                         found = 1;
1403                         break;
1404                 }
1405         }
1406
1407         if (! found) {
1408                 DEBUG(1, "%s: Requested AP not found in scan results\n",
1409                       dev->name);
1410                 goto out;
1411         }
1412
1413         memcpy(req.bssid, priv->desired_bssid, ETH_ALEN);
1414         req.channel = atom->channel;    /* both are little-endian */
1415         err = HERMES_WRITE_RECORD(hw, USER_BAP, HERMES_RID_CNFJOINREQUEST,
1416                                   &req);
1417         if (err)
1418                 printk(KERN_ERR "%s: Error issuing join request\n", dev->name);
1419
1420  out:
1421         orinoco_unlock(priv, &flags);
1422
1423  fail_lock:
1424         kfree(buf);
1425 }
1426
1427 /* Send new BSSID to userspace */
1428 static void orinoco_send_bssid_wevent(struct orinoco_private *priv)
1429 {
1430         struct net_device *dev = priv->ndev;
1431         struct hermes *hw = &priv->hw;
1432         union iwreq_data wrqu;
1433         int err;
1434
1435         err = hermes_read_ltv(hw, IRQ_BAP, HERMES_RID_CURRENTBSSID,
1436                               ETH_ALEN, NULL, wrqu.ap_addr.sa_data);
1437         if (err != 0)
1438                 return;
1439
1440         wrqu.ap_addr.sa_family = ARPHRD_ETHER;
1441
1442         /* Send event to user space */
1443         wireless_send_event(dev, SIOCGIWAP, &wrqu, NULL);
1444 }
1445
1446 static void orinoco_send_wevents(struct work_struct *work)
1447 {
1448         struct orinoco_private *priv =
1449                 container_of(work, struct orinoco_private, wevent_work);
1450         unsigned long flags;
1451
1452         if (orinoco_lock(priv, &flags) != 0)
1453                 return;
1454
1455         orinoco_send_bssid_wevent(priv);
1456
1457         orinoco_unlock(priv, &flags);
1458 }
1459
1460 static inline void orinoco_clear_scan_results(struct orinoco_private *priv,
1461                                               unsigned long scan_age)
1462 {
1463         if (priv->has_ext_scan) {
1464                 struct xbss_element *bss;
1465                 struct xbss_element *tmp_bss;
1466
1467                 /* Blow away current list of scan results */
1468                 list_for_each_entry_safe(bss, tmp_bss, &priv->bss_list, list) {
1469                         if (!scan_age ||
1470                             time_after(jiffies, bss->last_scanned + scan_age)) {
1471                                 list_move_tail(&bss->list,
1472                                                &priv->bss_free_list);
1473                                 /* Don't blow away ->list, just BSS data */
1474                                 memset(&bss->bss, 0, sizeof(bss->bss));
1475                                 bss->last_scanned = 0;
1476                         }
1477                 }
1478         } else {
1479                 struct bss_element *bss;
1480                 struct bss_element *tmp_bss;
1481
1482                 /* Blow away current list of scan results */
1483                 list_for_each_entry_safe(bss, tmp_bss, &priv->bss_list, list) {
1484                         if (!scan_age ||
1485                             time_after(jiffies, bss->last_scanned + scan_age)) {
1486                                 list_move_tail(&bss->list,
1487                                                &priv->bss_free_list);
1488                                 /* Don't blow away ->list, just BSS data */
1489                                 memset(&bss->bss, 0, sizeof(bss->bss));
1490                                 bss->last_scanned = 0;
1491                         }
1492                 }
1493         }
1494 }
1495
1496 static void orinoco_add_ext_scan_result(struct orinoco_private *priv,
1497                                         struct agere_ext_scan_info *atom)
1498 {
1499         struct xbss_element *bss = NULL;
1500         int found = 0;
1501
1502         /* Try to update an existing bss first */
1503         list_for_each_entry(bss, &priv->bss_list, list) {
1504                 if (compare_ether_addr(bss->bss.bssid, atom->bssid))
1505                         continue;
1506                 /* ESSID lengths */
1507                 if (bss->bss.data[1] != atom->data[1])
1508                         continue;
1509                 if (memcmp(&bss->bss.data[2], &atom->data[2],
1510                            atom->data[1]))
1511                         continue;
1512                 found = 1;
1513                 break;
1514         }
1515
1516         /* Grab a bss off the free list */
1517         if (!found && !list_empty(&priv->bss_free_list)) {
1518                 bss = list_entry(priv->bss_free_list.next,
1519                                  struct xbss_element, list);
1520                 list_del(priv->bss_free_list.next);
1521
1522                 list_add_tail(&bss->list, &priv->bss_list);
1523         }
1524
1525         if (bss) {
1526                 /* Always update the BSS to get latest beacon info */
1527                 memcpy(&bss->bss, atom, sizeof(bss->bss));
1528                 bss->last_scanned = jiffies;
1529         }
1530 }
1531
1532 static int orinoco_process_scan_results(struct net_device *dev,
1533                                         unsigned char *buf,
1534                                         int len)
1535 {
1536         struct orinoco_private *priv = netdev_priv(dev);
1537         int                     offset;         /* In the scan data */
1538         union hermes_scan_info *atom;
1539         int                     atom_len;
1540
1541         switch (priv->firmware_type) {
1542         case FIRMWARE_TYPE_AGERE:
1543                 atom_len = sizeof(struct agere_scan_apinfo);
1544                 offset = 0;
1545                 break;
1546         case FIRMWARE_TYPE_SYMBOL:
1547                 /* Lack of documentation necessitates this hack.
1548                  * Different firmwares have 68 or 76 byte long atoms.
1549                  * We try modulo first.  If the length divides by both,
1550                  * we check what would be the channel in the second
1551                  * frame for a 68-byte atom.  76-byte atoms have 0 there.
1552                  * Valid channel cannot be 0.  */
1553                 if (len % 76)
1554                         atom_len = 68;
1555                 else if (len % 68)
1556                         atom_len = 76;
1557                 else if (len >= 1292 && buf[68] == 0)
1558                         atom_len = 76;
1559                 else
1560                         atom_len = 68;
1561                 offset = 0;
1562                 break;
1563         case FIRMWARE_TYPE_INTERSIL:
1564                 offset = 4;
1565                 if (priv->has_hostscan) {
1566                         atom_len = le16_to_cpup((__le16 *)buf);
1567                         /* Sanity check for atom_len */
1568                         if (atom_len < sizeof(struct prism2_scan_apinfo)) {
1569                                 printk(KERN_ERR "%s: Invalid atom_len in scan "
1570                                        "data: %d\n", dev->name, atom_len);
1571                                 return -EIO;
1572                         }
1573                 } else
1574                         atom_len = offsetof(struct prism2_scan_apinfo, atim);
1575                 break;
1576         default:
1577                 return -EOPNOTSUPP;
1578         }
1579
1580         /* Check that we got an whole number of atoms */
1581         if ((len - offset) % atom_len) {
1582                 printk(KERN_ERR "%s: Unexpected scan data length %d, "
1583                        "atom_len %d, offset %d\n", dev->name, len,
1584                        atom_len, offset);
1585                 return -EIO;
1586         }
1587
1588         orinoco_clear_scan_results(priv, msecs_to_jiffies(15000));
1589
1590         /* Read the entries one by one */
1591         for (; offset + atom_len <= len; offset += atom_len) {
1592                 int found = 0;
1593                 struct bss_element *bss = NULL;
1594
1595                 /* Get next atom */
1596                 atom = (union hermes_scan_info *) (buf + offset);
1597
1598                 /* Try to update an existing bss first */
1599                 list_for_each_entry(bss, &priv->bss_list, list) {
1600                         if (compare_ether_addr(bss->bss.a.bssid, atom->a.bssid))
1601                                 continue;
1602                         if (le16_to_cpu(bss->bss.a.essid_len) !=
1603                               le16_to_cpu(atom->a.essid_len))
1604                                 continue;
1605                         if (memcmp(bss->bss.a.essid, atom->a.essid,
1606                               le16_to_cpu(atom->a.essid_len)))
1607                                 continue;
1608                         found = 1;
1609                         break;
1610                 }
1611
1612                 /* Grab a bss off the free list */
1613                 if (!found && !list_empty(&priv->bss_free_list)) {
1614                         bss = list_entry(priv->bss_free_list.next,
1615                                          struct bss_element, list);
1616                         list_del(priv->bss_free_list.next);
1617
1618                         list_add_tail(&bss->list, &priv->bss_list);
1619                 }
1620
1621                 if (bss) {
1622                         /* Always update the BSS to get latest beacon info */
1623                         memcpy(&bss->bss, atom, sizeof(bss->bss));
1624                         bss->last_scanned = jiffies;
1625                 }
1626         }
1627
1628         return 0;
1629 }
1630
1631 static void __orinoco_ev_info(struct net_device *dev, hermes_t *hw)
1632 {
1633         struct orinoco_private *priv = netdev_priv(dev);
1634         u16 infofid;
1635         struct {
1636                 __le16 len;
1637                 __le16 type;
1638         } __attribute__ ((packed)) info;
1639         int len, type;
1640         int err;
1641
1642         /* This is an answer to an INQUIRE command that we did earlier,
1643          * or an information "event" generated by the card
1644          * The controller return to us a pseudo frame containing
1645          * the information in question - Jean II */
1646         infofid = hermes_read_regn(hw, INFOFID);
1647
1648         /* Read the info frame header - don't try too hard */
1649         err = hermes_bap_pread(hw, IRQ_BAP, &info, sizeof(info),
1650                                infofid, 0);
1651         if (err) {
1652                 printk(KERN_ERR "%s: error %d reading info frame. "
1653                        "Frame dropped.\n", dev->name, err);
1654                 return;
1655         }
1656         
1657         len = HERMES_RECLEN_TO_BYTES(le16_to_cpu(info.len));
1658         type = le16_to_cpu(info.type);
1659
1660         switch (type) {
1661         case HERMES_INQ_TALLIES: {
1662                 struct hermes_tallies_frame tallies;
1663                 struct iw_statistics *wstats = &priv->wstats;
1664                 
1665                 if (len > sizeof(tallies)) {
1666                         printk(KERN_WARNING "%s: Tallies frame too long (%d bytes)\n",
1667                                dev->name, len);
1668                         len = sizeof(tallies);
1669                 }
1670                 
1671                 err = hermes_bap_pread(hw, IRQ_BAP, &tallies, len,
1672                                        infofid, sizeof(info));
1673                 if (err)
1674                         break;
1675                 
1676                 /* Increment our various counters */
1677                 /* wstats->discard.nwid - no wrong BSSID stuff */
1678                 wstats->discard.code +=
1679                         le16_to_cpu(tallies.RxWEPUndecryptable);
1680                 if (len == sizeof(tallies))  
1681                         wstats->discard.code +=
1682                                 le16_to_cpu(tallies.RxDiscards_WEPICVError) +
1683                                 le16_to_cpu(tallies.RxDiscards_WEPExcluded);
1684                 wstats->discard.misc +=
1685                         le16_to_cpu(tallies.TxDiscardsWrongSA);
1686                 wstats->discard.fragment +=
1687                         le16_to_cpu(tallies.RxMsgInBadMsgFragments);
1688                 wstats->discard.retries +=
1689                         le16_to_cpu(tallies.TxRetryLimitExceeded);
1690                 /* wstats->miss.beacon - no match */
1691         }
1692         break;
1693         case HERMES_INQ_LINKSTATUS: {
1694                 struct hermes_linkstatus linkstatus;
1695                 u16 newstatus;
1696                 int connected;
1697
1698                 if (priv->iw_mode == IW_MODE_MONITOR)
1699                         break;
1700
1701                 if (len != sizeof(linkstatus)) {
1702                         printk(KERN_WARNING "%s: Unexpected size for linkstatus frame (%d bytes)\n",
1703                                dev->name, len);
1704                         break;
1705                 }
1706
1707                 err = hermes_bap_pread(hw, IRQ_BAP, &linkstatus, len,
1708                                        infofid, sizeof(info));
1709                 if (err)
1710                         break;
1711                 newstatus = le16_to_cpu(linkstatus.linkstatus);
1712
1713                 /* Symbol firmware uses "out of range" to signal that
1714                  * the hostscan frame can be requested.  */
1715                 if (newstatus == HERMES_LINKSTATUS_AP_OUT_OF_RANGE &&
1716                     priv->firmware_type == FIRMWARE_TYPE_SYMBOL &&
1717                     priv->has_hostscan && priv->scan_inprogress) {
1718                         hermes_inquire(hw, HERMES_INQ_HOSTSCAN_SYMBOL);
1719                         break;
1720                 }
1721
1722                 connected = (newstatus == HERMES_LINKSTATUS_CONNECTED)
1723                         || (newstatus == HERMES_LINKSTATUS_AP_CHANGE)
1724                         || (newstatus == HERMES_LINKSTATUS_AP_IN_RANGE);
1725
1726                 if (connected)
1727                         netif_carrier_on(dev);
1728                 else if (!ignore_disconnect)
1729                         netif_carrier_off(dev);
1730
1731                 if (newstatus != priv->last_linkstatus) {
1732                         priv->last_linkstatus = newstatus;
1733                         print_linkstatus(dev, newstatus);
1734                         /* The info frame contains only one word which is the
1735                          * status (see hermes.h). The status is pretty boring
1736                          * in itself, that's why we export the new BSSID...
1737                          * Jean II */
1738                         schedule_work(&priv->wevent_work);
1739                 }
1740         }
1741         break;
1742         case HERMES_INQ_SCAN:
1743                 if (!priv->scan_inprogress && priv->bssid_fixed &&
1744                     priv->firmware_type == FIRMWARE_TYPE_INTERSIL) {
1745                         schedule_work(&priv->join_work);
1746                         break;
1747                 }
1748                 /* fall through */
1749         case HERMES_INQ_HOSTSCAN:
1750         case HERMES_INQ_HOSTSCAN_SYMBOL: {
1751                 /* Result of a scanning. Contains information about
1752                  * cells in the vicinity - Jean II */
1753                 union iwreq_data        wrqu;
1754                 unsigned char *buf;
1755
1756                 /* Scan is no longer in progress */
1757                 priv->scan_inprogress = 0;
1758
1759                 /* Sanity check */
1760                 if (len > 4096) {
1761                         printk(KERN_WARNING "%s: Scan results too large (%d bytes)\n",
1762                                dev->name, len);
1763                         break;
1764                 }
1765
1766                 /* Allocate buffer for results */
1767                 buf = kmalloc(len, GFP_ATOMIC);
1768                 if (buf == NULL)
1769                         /* No memory, so can't printk()... */
1770                         break;
1771
1772                 /* Read scan data */
1773                 err = hermes_bap_pread(hw, IRQ_BAP, (void *) buf, len,
1774                                        infofid, sizeof(info));
1775                 if (err) {
1776                         kfree(buf);
1777                         break;
1778                 }
1779
1780 #ifdef ORINOCO_DEBUG
1781                 {
1782                         int     i;
1783                         printk(KERN_DEBUG "Scan result [%02X", buf[0]);
1784                         for(i = 1; i < (len * 2); i++)
1785                                 printk(":%02X", buf[i]);
1786                         printk("]\n");
1787                 }
1788 #endif  /* ORINOCO_DEBUG */
1789
1790                 if (orinoco_process_scan_results(dev, buf, len) == 0) {
1791                         /* Send an empty event to user space.
1792                          * We don't send the received data on the event because
1793                          * it would require us to do complex transcoding, and
1794                          * we want to minimise the work done in the irq handler
1795                          * Use a request to extract the data - Jean II */
1796                         wrqu.data.length = 0;
1797                         wrqu.data.flags = 0;
1798                         wireless_send_event(dev, SIOCGIWSCAN, &wrqu, NULL);
1799                 }
1800                 kfree(buf);
1801         }
1802         break;
1803         case HERMES_INQ_CHANNELINFO:
1804         {
1805                 struct agere_ext_scan_info *bss;
1806
1807                 if (!priv->scan_inprogress) {
1808                         printk(KERN_DEBUG "%s: Got chaninfo without scan, "
1809                                "len=%d\n", dev->name, len);
1810                         break;
1811                 }
1812
1813                 /* An empty result indicates that the scan is complete */
1814                 if (len == 0) {
1815                         union iwreq_data        wrqu;
1816
1817                         /* Scan is no longer in progress */
1818                         priv->scan_inprogress = 0;
1819
1820                         wrqu.data.length = 0;
1821                         wrqu.data.flags = 0;
1822                         wireless_send_event(dev, SIOCGIWSCAN, &wrqu, NULL);
1823                         break;
1824                 }
1825
1826                 /* Sanity check */
1827                 else if (len > sizeof(*bss)) {
1828                         printk(KERN_WARNING
1829                                "%s: Ext scan results too large (%d bytes). "
1830                                "Truncating results to %zd bytes.\n",
1831                                dev->name, len, sizeof(*bss));
1832                         len = sizeof(*bss);
1833                 } else if (len < (offsetof(struct agere_ext_scan_info,
1834                                            data) + 2)) {
1835                         /* Drop this result now so we don't have to
1836                          * keep checking later */
1837                         printk(KERN_WARNING
1838                                "%s: Ext scan results too short (%d bytes)\n",
1839                                dev->name, len);
1840                         break;
1841                 }
1842
1843                 bss = kmalloc(sizeof(*bss), GFP_ATOMIC);
1844                 if (bss == NULL)
1845                         break;
1846
1847                 /* Read scan data */
1848                 err = hermes_bap_pread(hw, IRQ_BAP, (void *) bss, len,
1849                                        infofid, sizeof(info));
1850                 if (err) {
1851                         kfree(bss);
1852                         break;
1853                 }
1854
1855                 orinoco_add_ext_scan_result(priv, bss);
1856
1857                 kfree(bss);
1858                 break;
1859         }
1860         case HERMES_INQ_SEC_STAT_AGERE:
1861                 /* Security status (Agere specific) */
1862                 /* Ignore this frame for now */
1863                 if (priv->firmware_type == FIRMWARE_TYPE_AGERE)
1864                         break;
1865                 /* fall through */
1866         default:
1867                 printk(KERN_DEBUG "%s: Unknown information frame received: "
1868                        "type 0x%04x, length %d\n", dev->name, type, len);
1869                 /* We don't actually do anything about it */
1870                 break;
1871         }
1872 }
1873
1874 static void __orinoco_ev_infdrop(struct net_device *dev, hermes_t *hw)
1875 {
1876         if (net_ratelimit())
1877                 printk(KERN_DEBUG "%s: Information frame lost.\n", dev->name);
1878 }
1879
1880 /********************************************************************/
1881 /* Internal hardware control routines                               */
1882 /********************************************************************/
1883
1884 int __orinoco_up(struct net_device *dev)
1885 {
1886         struct orinoco_private *priv = netdev_priv(dev);
1887         struct hermes *hw = &priv->hw;
1888         int err;
1889
1890         netif_carrier_off(dev); /* just to make sure */
1891
1892         err = __orinoco_program_rids(dev);
1893         if (err) {
1894                 printk(KERN_ERR "%s: Error %d configuring card\n",
1895                        dev->name, err);
1896                 return err;
1897         }
1898
1899         /* Fire things up again */
1900         hermes_set_irqmask(hw, ORINOCO_INTEN);
1901         err = hermes_enable_port(hw, 0);
1902         if (err) {
1903                 printk(KERN_ERR "%s: Error %d enabling MAC port\n",
1904                        dev->name, err);
1905                 return err;
1906         }
1907
1908         netif_start_queue(dev);
1909
1910         return 0;
1911 }
1912
1913 int __orinoco_down(struct net_device *dev)
1914 {
1915         struct orinoco_private *priv = netdev_priv(dev);
1916         struct hermes *hw = &priv->hw;
1917         int err;
1918
1919         netif_stop_queue(dev);
1920
1921         if (! priv->hw_unavailable) {
1922                 if (! priv->broken_disableport) {
1923                         err = hermes_disable_port(hw, 0);
1924                         if (err) {
1925                                 /* Some firmwares (e.g. Intersil 1.3.x) seem
1926                                  * to have problems disabling the port, oh
1927                                  * well, too bad. */
1928                                 printk(KERN_WARNING "%s: Error %d disabling MAC port\n",
1929                                        dev->name, err);
1930                                 priv->broken_disableport = 1;
1931                         }
1932                 }
1933                 hermes_set_irqmask(hw, 0);
1934                 hermes_write_regn(hw, EVACK, 0xffff);
1935         }
1936         
1937         /* firmware will have to reassociate */
1938         netif_carrier_off(dev);
1939         priv->last_linkstatus = 0xffff;
1940
1941         return 0;
1942 }
1943
1944 static int orinoco_allocate_fid(struct net_device *dev)
1945 {
1946         struct orinoco_private *priv = netdev_priv(dev);
1947         struct hermes *hw = &priv->hw;
1948         int err;
1949
1950         err = hermes_allocate(hw, priv->nicbuf_size, &priv->txfid);
1951         if (err == -EIO && priv->nicbuf_size > TX_NICBUF_SIZE_BUG) {
1952                 /* Try workaround for old Symbol firmware bug */
1953                 printk(KERN_WARNING "%s: firmware ALLOC bug detected "
1954                        "(old Symbol firmware?). Trying to work around... ",
1955                        dev->name);
1956                 
1957                 priv->nicbuf_size = TX_NICBUF_SIZE_BUG;
1958                 err = hermes_allocate(hw, priv->nicbuf_size, &priv->txfid);
1959                 if (err)
1960                         printk("failed!\n");
1961                 else
1962                         printk("ok.\n");
1963         }
1964
1965         return err;
1966 }
1967
1968 int orinoco_reinit_firmware(struct net_device *dev)
1969 {
1970         struct orinoco_private *priv = netdev_priv(dev);
1971         struct hermes *hw = &priv->hw;
1972         int err;
1973
1974         err = hermes_init(hw);
1975         if (!err)
1976                 err = orinoco_allocate_fid(dev);
1977
1978         return err;
1979 }
1980
1981 static int __orinoco_hw_set_bitrate(struct orinoco_private *priv)
1982 {
1983         hermes_t *hw = &priv->hw;
1984         int err = 0;
1985
1986         if (priv->bitratemode >= BITRATE_TABLE_SIZE) {
1987                 printk(KERN_ERR "%s: BUG: Invalid bitrate mode %d\n",
1988                        priv->ndev->name, priv->bitratemode);
1989                 return -EINVAL;
1990         }
1991
1992         switch (priv->firmware_type) {
1993         case FIRMWARE_TYPE_AGERE:
1994                 err = hermes_write_wordrec(hw, USER_BAP,
1995                                            HERMES_RID_CNFTXRATECONTROL,
1996                                            bitrate_table[priv->bitratemode].agere_txratectrl);
1997                 break;
1998         case FIRMWARE_TYPE_INTERSIL:
1999         case FIRMWARE_TYPE_SYMBOL:
2000                 err = hermes_write_wordrec(hw, USER_BAP,
2001                                            HERMES_RID_CNFTXRATECONTROL,
2002                                            bitrate_table[priv->bitratemode].intersil_txratectrl);
2003                 break;
2004         default:
2005                 BUG();
2006         }
2007
2008         return err;
2009 }
2010
2011 /* Set fixed AP address */
2012 static int __orinoco_hw_set_wap(struct orinoco_private *priv)
2013 {
2014         int roaming_flag;
2015         int err = 0;
2016         hermes_t *hw = &priv->hw;
2017
2018         switch (priv->firmware_type) {
2019         case FIRMWARE_TYPE_AGERE:
2020                 /* not supported */
2021                 break;
2022         case FIRMWARE_TYPE_INTERSIL:
2023                 if (priv->bssid_fixed)
2024                         roaming_flag = 2;
2025                 else
2026                         roaming_flag = 1;
2027
2028                 err = hermes_write_wordrec(hw, USER_BAP,
2029                                            HERMES_RID_CNFROAMINGMODE,
2030                                            roaming_flag);
2031                 break;
2032         case FIRMWARE_TYPE_SYMBOL:
2033                 err = HERMES_WRITE_RECORD(hw, USER_BAP,
2034                                           HERMES_RID_CNFMANDATORYBSSID_SYMBOL,
2035                                           &priv->desired_bssid);
2036                 break;
2037         }
2038         return err;
2039 }
2040
2041 /* Change the WEP keys and/or the current keys.  Can be called
2042  * either from __orinoco_hw_setup_enc() or directly from
2043  * orinoco_ioctl_setiwencode().  In the later case the association
2044  * with the AP is not broken (if the firmware can handle it),
2045  * which is needed for 802.1x implementations. */
2046 static int __orinoco_hw_setup_wepkeys(struct orinoco_private *priv)
2047 {
2048         hermes_t *hw = &priv->hw;
2049         int err = 0;
2050
2051         switch (priv->firmware_type) {
2052         case FIRMWARE_TYPE_AGERE:
2053                 err = HERMES_WRITE_RECORD(hw, USER_BAP,
2054                                           HERMES_RID_CNFWEPKEYS_AGERE,
2055                                           &priv->keys);
2056                 if (err)
2057                         return err;
2058                 err = hermes_write_wordrec(hw, USER_BAP,
2059                                            HERMES_RID_CNFTXKEY_AGERE,
2060                                            priv->tx_key);
2061                 if (err)
2062                         return err;
2063                 break;
2064         case FIRMWARE_TYPE_INTERSIL:
2065         case FIRMWARE_TYPE_SYMBOL:
2066                 {
2067                         int keylen;
2068                         int i;
2069
2070                         /* Force uniform key length to work around firmware bugs */
2071                         keylen = le16_to_cpu(priv->keys[priv->tx_key].len);
2072                         
2073                         if (keylen > LARGE_KEY_SIZE) {
2074                                 printk(KERN_ERR "%s: BUG: Key %d has oversize length %d.\n",
2075                                        priv->ndev->name, priv->tx_key, keylen);
2076                                 return -E2BIG;
2077                         }
2078
2079                         /* Write all 4 keys */
2080                         for(i = 0; i < ORINOCO_MAX_KEYS; i++) {
2081                                 err = hermes_write_ltv(hw, USER_BAP,
2082                                                        HERMES_RID_CNFDEFAULTKEY0 + i,
2083                                                        HERMES_BYTES_TO_RECLEN(keylen),
2084                                                        priv->keys[i].data);
2085                                 if (err)
2086                                         return err;
2087                         }
2088
2089                         /* Write the index of the key used in transmission */
2090                         err = hermes_write_wordrec(hw, USER_BAP,
2091                                                    HERMES_RID_CNFWEPDEFAULTKEYID,
2092                                                    priv->tx_key);
2093                         if (err)
2094                                 return err;
2095                 }
2096                 break;
2097         }
2098
2099         return 0;
2100 }
2101
2102 static int __orinoco_hw_setup_enc(struct orinoco_private *priv)
2103 {
2104         hermes_t *hw = &priv->hw;
2105         int err = 0;
2106         int master_wep_flag;
2107         int auth_flag;
2108         int enc_flag;
2109
2110         /* Setup WEP keys for WEP and WPA */
2111         if (priv->encode_alg)
2112                 __orinoco_hw_setup_wepkeys(priv);
2113
2114         if (priv->wep_restrict)
2115                 auth_flag = HERMES_AUTH_SHARED_KEY;
2116         else
2117                 auth_flag = HERMES_AUTH_OPEN;
2118
2119         if (priv->wpa_enabled)
2120                 enc_flag = 2;
2121         else if (priv->encode_alg == IW_ENCODE_ALG_WEP)
2122                 enc_flag = 1;
2123         else
2124                 enc_flag = 0;
2125
2126         switch (priv->firmware_type) {
2127         case FIRMWARE_TYPE_AGERE: /* Agere style WEP */
2128                 if (priv->encode_alg == IW_ENCODE_ALG_WEP) {
2129                         /* Enable the shared-key authentication. */
2130                         err = hermes_write_wordrec(hw, USER_BAP,
2131                                                    HERMES_RID_CNFAUTHENTICATION_AGERE,
2132                                                    auth_flag);
2133                 }
2134                 err = hermes_write_wordrec(hw, USER_BAP,
2135                                            HERMES_RID_CNFWEPENABLED_AGERE,
2136                                            enc_flag);
2137                 if (err)
2138                         return err;
2139
2140                 if (priv->has_wpa) {
2141                         /* Set WPA key management */
2142                         err = hermes_write_wordrec(hw, USER_BAP,
2143                                   HERMES_RID_CNFSETWPAAUTHMGMTSUITE_AGERE,
2144                                   priv->key_mgmt);
2145                         if (err)
2146                                 return err;
2147                 }
2148
2149                 break;
2150
2151         case FIRMWARE_TYPE_INTERSIL: /* Intersil style WEP */
2152         case FIRMWARE_TYPE_SYMBOL: /* Symbol style WEP */
2153                 if (priv->encode_alg == IW_ENCODE_ALG_WEP) {
2154                         if (priv->wep_restrict ||
2155                             (priv->firmware_type == FIRMWARE_TYPE_SYMBOL))
2156                                 master_wep_flag = HERMES_WEP_PRIVACY_INVOKED |
2157                                                   HERMES_WEP_EXCL_UNENCRYPTED;
2158                         else
2159                                 master_wep_flag = HERMES_WEP_PRIVACY_INVOKED;
2160
2161                         err = hermes_write_wordrec(hw, USER_BAP,
2162                                                    HERMES_RID_CNFAUTHENTICATION,
2163                                                    auth_flag);
2164                         if (err)
2165                                 return err;
2166                 } else
2167                         master_wep_flag = 0;
2168
2169                 if (priv->iw_mode == IW_MODE_MONITOR)
2170                         master_wep_flag |= HERMES_WEP_HOST_DECRYPT;
2171
2172                 /* Master WEP setting : on/off */
2173                 err = hermes_write_wordrec(hw, USER_BAP,
2174                                            HERMES_RID_CNFWEPFLAGS_INTERSIL,
2175                                            master_wep_flag);
2176                 if (err)
2177                         return err;     
2178
2179                 break;
2180         }
2181
2182         return 0;
2183 }
2184
2185 /* key must be 32 bytes, including the tx and rx MIC keys.
2186  * rsc must be 8 bytes
2187  * tsc must be 8 bytes or NULL
2188  */
2189 static int __orinoco_hw_set_tkip_key(hermes_t *hw, int key_idx, int set_tx,
2190                                      u8 *key, u8 *rsc, u8 *tsc)
2191 {
2192         struct {
2193                 __le16 idx;
2194                 u8 rsc[IW_ENCODE_SEQ_MAX_SIZE];
2195                 u8 key[TKIP_KEYLEN];
2196                 u8 tx_mic[MIC_KEYLEN];
2197                 u8 rx_mic[MIC_KEYLEN];
2198                 u8 tsc[IW_ENCODE_SEQ_MAX_SIZE];
2199         } __attribute__ ((packed)) buf;
2200         int ret;
2201         int err;
2202         int k;
2203         u16 xmitting;
2204
2205         key_idx &= 0x3;
2206
2207         if (set_tx)
2208                 key_idx |= 0x8000;
2209
2210         buf.idx = cpu_to_le16(key_idx);
2211         memcpy(buf.key, key,
2212                sizeof(buf.key) + sizeof(buf.tx_mic) + sizeof(buf.rx_mic));
2213
2214         if (rsc == NULL)
2215                 memset(buf.rsc, 0, sizeof(buf.rsc));
2216         else
2217                 memcpy(buf.rsc, rsc, sizeof(buf.rsc));
2218
2219         if (tsc == NULL) {
2220                 memset(buf.tsc, 0, sizeof(buf.tsc));
2221                 buf.tsc[4] = 0x10;
2222         } else {
2223                 memcpy(buf.tsc, tsc, sizeof(buf.tsc));
2224         }
2225
2226         /* Wait upto 100ms for tx queue to empty */
2227         k = 100;
2228         do {
2229                 k--;
2230                 udelay(1000);
2231                 ret = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_TXQUEUEEMPTY,
2232                                           &xmitting);
2233                 if (ret)
2234                         break;
2235         } while ((k > 0) && xmitting);
2236
2237         if (k == 0)
2238                 ret = -ETIMEDOUT;
2239
2240         err = HERMES_WRITE_RECORD(hw, USER_BAP,
2241                                   HERMES_RID_CNFADDDEFAULTTKIPKEY_AGERE,
2242                                   &buf);
2243
2244         return ret ? ret : err;
2245 }
2246
2247 static int orinoco_clear_tkip_key(struct orinoco_private *priv,
2248                                   int key_idx)
2249 {
2250         hermes_t *hw = &priv->hw;
2251         int err;
2252
2253         memset(&priv->tkip_key[key_idx], 0, sizeof(priv->tkip_key[key_idx]));
2254         err = hermes_write_wordrec(hw, USER_BAP,
2255                                    HERMES_RID_CNFREMDEFAULTTKIPKEY_AGERE,
2256                                    key_idx);
2257         if (err)
2258                 printk(KERN_WARNING "%s: Error %d clearing TKIP key %d\n",
2259                        priv->ndev->name, err, key_idx);
2260         return err;
2261 }
2262
2263 static int __orinoco_program_rids(struct net_device *dev)
2264 {
2265         struct orinoco_private *priv = netdev_priv(dev);
2266         hermes_t *hw = &priv->hw;
2267         int err;
2268         struct hermes_idstring idbuf;
2269
2270         /* Set the MAC address */
2271         err = hermes_write_ltv(hw, USER_BAP, HERMES_RID_CNFOWNMACADDR,
2272                                HERMES_BYTES_TO_RECLEN(ETH_ALEN), dev->dev_addr);
2273         if (err) {
2274                 printk(KERN_ERR "%s: Error %d setting MAC address\n",
2275                        dev->name, err);
2276                 return err;
2277         }
2278
2279         /* Set up the link mode */
2280         err = hermes_write_wordrec(hw, USER_BAP, HERMES_RID_CNFPORTTYPE,
2281                                    priv->port_type);
2282         if (err) {
2283                 printk(KERN_ERR "%s: Error %d setting port type\n",
2284                        dev->name, err);
2285                 return err;
2286         }
2287         /* Set the channel/frequency */
2288         if (priv->channel != 0 && priv->iw_mode != IW_MODE_INFRA) {
2289                 err = hermes_write_wordrec(hw, USER_BAP,
2290                                            HERMES_RID_CNFOWNCHANNEL,
2291                                            priv->channel);
2292                 if (err) {
2293                         printk(KERN_ERR "%s: Error %d setting channel %d\n",
2294                                dev->name, err, priv->channel);
2295                         return err;
2296                 }
2297         }
2298
2299         if (priv->has_ibss) {
2300                 u16 createibss;
2301
2302                 if ((strlen(priv->desired_essid) == 0) && (priv->createibss)) {
2303                         printk(KERN_WARNING "%s: This firmware requires an "
2304                                "ESSID in IBSS-Ad-Hoc mode.\n", dev->name);
2305                         /* With wvlan_cs, in this case, we would crash.
2306                          * hopefully, this driver will behave better...
2307                          * Jean II */
2308                         createibss = 0;
2309                 } else {
2310                         createibss = priv->createibss;
2311                 }
2312                 
2313                 err = hermes_write_wordrec(hw, USER_BAP,
2314                                            HERMES_RID_CNFCREATEIBSS,
2315                                            createibss);
2316                 if (err) {
2317                         printk(KERN_ERR "%s: Error %d setting CREATEIBSS\n",
2318                                dev->name, err);
2319                         return err;
2320                 }
2321         }
2322
2323         /* Set the desired BSSID */
2324         err = __orinoco_hw_set_wap(priv);
2325         if (err) {
2326                 printk(KERN_ERR "%s: Error %d setting AP address\n",
2327                        dev->name, err);
2328                 return err;
2329         }
2330         /* Set the desired ESSID */
2331         idbuf.len = cpu_to_le16(strlen(priv->desired_essid));
2332         memcpy(&idbuf.val, priv->desired_essid, sizeof(idbuf.val));
2333         /* WinXP wants partner to configure OWNSSID even in IBSS mode. (jimc) */
2334         err = hermes_write_ltv(hw, USER_BAP, HERMES_RID_CNFOWNSSID,
2335                                HERMES_BYTES_TO_RECLEN(strlen(priv->desired_essid)+2),
2336                                &idbuf);
2337         if (err) {
2338                 printk(KERN_ERR "%s: Error %d setting OWNSSID\n",
2339                        dev->name, err);
2340                 return err;
2341         }
2342         err = hermes_write_ltv(hw, USER_BAP, HERMES_RID_CNFDESIREDSSID,
2343                                HERMES_BYTES_TO_RECLEN(strlen(priv->desired_essid)+2),
2344                                &idbuf);
2345         if (err) {
2346                 printk(KERN_ERR "%s: Error %d setting DESIREDSSID\n",
2347                        dev->name, err);
2348                 return err;
2349         }
2350
2351         /* Set the station name */
2352         idbuf.len = cpu_to_le16(strlen(priv->nick));
2353         memcpy(&idbuf.val, priv->nick, sizeof(idbuf.val));
2354         err = hermes_write_ltv(hw, USER_BAP, HERMES_RID_CNFOWNNAME,
2355                                HERMES_BYTES_TO_RECLEN(strlen(priv->nick)+2),
2356                                &idbuf);
2357         if (err) {
2358                 printk(KERN_ERR "%s: Error %d setting nickname\n",
2359                        dev->name, err);
2360                 return err;
2361         }
2362
2363         /* Set AP density */
2364         if (priv->has_sensitivity) {
2365                 err = hermes_write_wordrec(hw, USER_BAP,
2366                                            HERMES_RID_CNFSYSTEMSCALE,
2367                                            priv->ap_density);
2368                 if (err) {
2369                         printk(KERN_WARNING "%s: Error %d setting SYSTEMSCALE.  "
2370                                "Disabling sensitivity control\n",
2371                                dev->name, err);
2372
2373                         priv->has_sensitivity = 0;
2374                 }
2375         }
2376
2377         /* Set RTS threshold */
2378         err = hermes_write_wordrec(hw, USER_BAP, HERMES_RID_CNFRTSTHRESHOLD,
2379                                    priv->rts_thresh);
2380         if (err) {
2381                 printk(KERN_ERR "%s: Error %d setting RTS threshold\n",
2382                        dev->name, err);
2383                 return err;
2384         }
2385
2386         /* Set fragmentation threshold or MWO robustness */
2387         if (priv->has_mwo)
2388                 err = hermes_write_wordrec(hw, USER_BAP,
2389                                            HERMES_RID_CNFMWOROBUST_AGERE,
2390                                            priv->mwo_robust);
2391         else
2392                 err = hermes_write_wordrec(hw, USER_BAP,
2393                                            HERMES_RID_CNFFRAGMENTATIONTHRESHOLD,
2394                                            priv->frag_thresh);
2395         if (err) {
2396                 printk(KERN_ERR "%s: Error %d setting fragmentation\n",
2397                        dev->name, err);
2398                 return err;
2399         }
2400
2401         /* Set bitrate */
2402         err = __orinoco_hw_set_bitrate(priv);
2403         if (err) {
2404                 printk(KERN_ERR "%s: Error %d setting bitrate\n",
2405                        dev->name, err);
2406                 return err;
2407         }
2408
2409         /* Set power management */
2410         if (priv->has_pm) {
2411                 err = hermes_write_wordrec(hw, USER_BAP,
2412                                            HERMES_RID_CNFPMENABLED,
2413                                            priv->pm_on);
2414                 if (err) {
2415                         printk(KERN_ERR "%s: Error %d setting up PM\n",
2416                                dev->name, err);
2417                         return err;
2418                 }
2419
2420                 err = hermes_write_wordrec(hw, USER_BAP,
2421                                            HERMES_RID_CNFMULTICASTRECEIVE,
2422                                            priv->pm_mcast);
2423                 if (err) {
2424                         printk(KERN_ERR "%s: Error %d setting up PM\n",
2425                                dev->name, err);
2426                         return err;
2427                 }
2428                 err = hermes_write_wordrec(hw, USER_BAP,
2429                                            HERMES_RID_CNFMAXSLEEPDURATION,
2430                                            priv->pm_period);
2431                 if (err) {
2432                         printk(KERN_ERR "%s: Error %d setting up PM\n",
2433                                dev->name, err);
2434                         return err;
2435                 }
2436                 err = hermes_write_wordrec(hw, USER_BAP,
2437                                            HERMES_RID_CNFPMHOLDOVERDURATION,
2438                                            priv->pm_timeout);
2439                 if (err) {
2440                         printk(KERN_ERR "%s: Error %d setting up PM\n",
2441                                dev->name, err);
2442                         return err;
2443                 }
2444         }
2445
2446         /* Set preamble - only for Symbol so far... */
2447         if (priv->has_preamble) {
2448                 err = hermes_write_wordrec(hw, USER_BAP,
2449                                            HERMES_RID_CNFPREAMBLE_SYMBOL,
2450                                            priv->preamble);
2451                 if (err) {
2452                         printk(KERN_ERR "%s: Error %d setting preamble\n",
2453                                dev->name, err);
2454                         return err;
2455                 }
2456         }
2457
2458         /* Set up encryption */
2459         if (priv->has_wep || priv->has_wpa) {
2460                 err = __orinoco_hw_setup_enc(priv);
2461                 if (err) {
2462                         printk(KERN_ERR "%s: Error %d activating encryption\n",
2463                                dev->name, err);
2464                         return err;
2465                 }
2466         }
2467
2468         if (priv->iw_mode == IW_MODE_MONITOR) {
2469                 /* Enable monitor mode */
2470                 dev->type = ARPHRD_IEEE80211;
2471                 err = hermes_docmd_wait(hw, HERMES_CMD_TEST | 
2472                                             HERMES_TEST_MONITOR, 0, NULL);
2473         } else {
2474                 /* Disable monitor mode */
2475                 dev->type = ARPHRD_ETHER;
2476                 err = hermes_docmd_wait(hw, HERMES_CMD_TEST |
2477                                             HERMES_TEST_STOP, 0, NULL);
2478         }
2479         if (err)
2480                 return err;
2481
2482         /* Set promiscuity / multicast*/
2483         priv->promiscuous = 0;
2484         priv->mc_count = 0;
2485
2486         /* FIXME: what about netif_tx_lock */
2487         __orinoco_set_multicast_list(dev);
2488
2489         return 0;
2490 }
2491
2492 /* FIXME: return int? */
2493 static void
2494 __orinoco_set_multicast_list(struct net_device *dev)
2495 {
2496         struct orinoco_private *priv = netdev_priv(dev);
2497         hermes_t *hw = &priv->hw;
2498         int err = 0;
2499         int promisc, mc_count;
2500
2501         /* The Hermes doesn't seem to have an allmulti mode, so we go
2502          * into promiscuous mode and let the upper levels deal. */
2503         if ( (dev->flags & IFF_PROMISC) || (dev->flags & IFF_ALLMULTI) ||
2504              (dev->mc_count > MAX_MULTICAST(priv)) ) {
2505                 promisc = 1;
2506                 mc_count = 0;
2507         } else {
2508                 promisc = 0;
2509                 mc_count = dev->mc_count;
2510         }
2511
2512         if (promisc != priv->promiscuous) {
2513                 err = hermes_write_wordrec(hw, USER_BAP,
2514                                            HERMES_RID_CNFPROMISCUOUSMODE,
2515                                            promisc);
2516                 if (err) {
2517                         printk(KERN_ERR "%s: Error %d setting PROMISCUOUSMODE to 1.\n",
2518                                dev->name, err);
2519                 } else 
2520                         priv->promiscuous = promisc;
2521         }
2522
2523         if (! promisc && (mc_count || priv->mc_count) ) {
2524                 struct dev_mc_list *p = dev->mc_list;
2525                 struct hermes_multicast mclist;
2526                 int i;
2527
2528                 for (i = 0; i < mc_count; i++) {
2529                         /* paranoia: is list shorter than mc_count? */
2530                         BUG_ON(! p);
2531                         /* paranoia: bad address size in list? */
2532                         BUG_ON(p->dmi_addrlen != ETH_ALEN);
2533                         
2534                         memcpy(mclist.addr[i], p->dmi_addr, ETH_ALEN);
2535                         p = p->next;
2536                 }
2537                 
2538                 if (p)
2539                         printk(KERN_WARNING "%s: Multicast list is "
2540                                "longer than mc_count\n", dev->name);
2541
2542                 err = hermes_write_ltv(hw, USER_BAP, HERMES_RID_CNFGROUPADDRESSES,
2543                                        HERMES_BYTES_TO_RECLEN(priv->mc_count * ETH_ALEN),
2544                                        &mclist);
2545                 if (err)
2546                         printk(KERN_ERR "%s: Error %d setting multicast list.\n",
2547                                dev->name, err);
2548                 else
2549                         priv->mc_count = mc_count;
2550         }
2551 }
2552
2553 /* This must be called from user context, without locks held - use
2554  * schedule_work() */
2555 static void orinoco_reset(struct work_struct *work)
2556 {
2557         struct orinoco_private *priv =
2558                 container_of(work, struct orinoco_private, reset_work);
2559         struct net_device *dev = priv->ndev;
2560         struct hermes *hw = &priv->hw;
2561         int err;
2562         unsigned long flags;
2563
2564         if (orinoco_lock(priv, &flags) != 0)
2565                 /* When the hardware becomes available again, whatever
2566                  * detects that is responsible for re-initializing
2567                  * it. So no need for anything further */
2568                 return;
2569
2570         netif_stop_queue(dev);
2571
2572         /* Shut off interrupts.  Depending on what state the hardware
2573          * is in, this might not work, but we'll try anyway */
2574         hermes_set_irqmask(hw, 0);
2575         hermes_write_regn(hw, EVACK, 0xffff);
2576
2577         priv->hw_unavailable++;
2578         priv->last_linkstatus = 0xffff; /* firmware will have to reassociate */
2579         netif_carrier_off(dev);
2580
2581         orinoco_unlock(priv, &flags);
2582
2583         /* Scanning support: Cleanup of driver struct */
2584         orinoco_clear_scan_results(priv, 0);
2585         priv->scan_inprogress = 0;
2586
2587         if (priv->hard_reset) {
2588                 err = (*priv->hard_reset)(priv);
2589                 if (err) {
2590                         printk(KERN_ERR "%s: orinoco_reset: Error %d "
2591                                "performing hard reset\n", dev->name, err);
2592                         goto disable;
2593                 }
2594         }
2595
2596         if (priv->do_fw_download) {
2597                 err = orinoco_download(priv);
2598                 if (err)
2599                         priv->do_fw_download = 0;
2600         }
2601
2602         err = orinoco_reinit_firmware(dev);
2603         if (err) {
2604                 printk(KERN_ERR "%s: orinoco_reset: Error %d re-initializing firmware\n",
2605                        dev->name, err);
2606                 goto disable;
2607         }
2608
2609         spin_lock_irq(&priv->lock); /* This has to be called from user context */
2610
2611         priv->hw_unavailable--;
2612
2613         /* priv->open or priv->hw_unavailable might have changed while
2614          * we dropped the lock */
2615         if (priv->open && (! priv->hw_unavailable)) {
2616                 err = __orinoco_up(dev);
2617                 if (err) {
2618                         printk(KERN_ERR "%s: orinoco_reset: Error %d reenabling card\n",
2619                                dev->name, err);
2620                 } else
2621                         dev->trans_start = jiffies;
2622         }
2623
2624         spin_unlock_irq(&priv->lock);
2625
2626         return;
2627  disable:
2628         hermes_set_irqmask(hw, 0);
2629         netif_device_detach(dev);
2630         printk(KERN_ERR "%s: Device has been disabled!\n", dev->name);
2631 }
2632
2633 /********************************************************************/
2634 /* Interrupt handler                                                */
2635 /********************************************************************/
2636
2637 static void __orinoco_ev_tick(struct net_device *dev, hermes_t *hw)
2638 {
2639         printk(KERN_DEBUG "%s: TICK\n", dev->name);
2640 }
2641
2642 static void __orinoco_ev_wterr(struct net_device *dev, hermes_t *hw)
2643 {
2644         /* This seems to happen a fair bit under load, but ignoring it
2645            seems to work fine...*/
2646         printk(KERN_DEBUG "%s: MAC controller error (WTERR). Ignoring.\n",
2647                dev->name);
2648 }
2649
2650 irqreturn_t orinoco_interrupt(int irq, void *dev_id)
2651 {
2652         struct net_device *dev = dev_id;
2653         struct orinoco_private *priv = netdev_priv(dev);
2654         hermes_t *hw = &priv->hw;
2655         int count = MAX_IRQLOOPS_PER_IRQ;
2656         u16 evstat, events;
2657         /* These are used to detect a runaway interrupt situation */
2658         /* If we get more than MAX_IRQLOOPS_PER_JIFFY iterations in a jiffy,
2659          * we panic and shut down the hardware */
2660         static int last_irq_jiffy = 0; /* jiffies value the last time
2661                                         * we were called */
2662         static int loops_this_jiffy = 0;
2663         unsigned long flags;
2664
2665         if (orinoco_lock(priv, &flags) != 0) {
2666                 /* If hw is unavailable - we don't know if the irq was
2667                  * for us or not */
2668                 return IRQ_HANDLED;
2669         }
2670
2671         evstat = hermes_read_regn(hw, EVSTAT);
2672         events = evstat & hw->inten;
2673         if (! events) {
2674                 orinoco_unlock(priv, &flags);
2675                 return IRQ_NONE;
2676         }
2677         
2678         if (jiffies != last_irq_jiffy)
2679                 loops_this_jiffy = 0;
2680         last_irq_jiffy = jiffies;
2681
2682         while (events && count--) {
2683                 if (++loops_this_jiffy > MAX_IRQLOOPS_PER_JIFFY) {
2684                         printk(KERN_WARNING "%s: IRQ handler is looping too "
2685                                "much! Resetting.\n", dev->name);
2686                         /* Disable interrupts for now */
2687                         hermes_set_irqmask(hw, 0);
2688                         schedule_work(&priv->reset_work);
2689                         break;
2690                 }
2691
2692                 /* Check the card hasn't been removed */
2693                 if (! hermes_present(hw)) {
2694                         DEBUG(0, "orinoco_interrupt(): card removed\n");
2695                         break;
2696                 }
2697
2698                 if (events & HERMES_EV_TICK)
2699                         __orinoco_ev_tick(dev, hw);
2700                 if (events & HERMES_EV_WTERR)
2701                         __orinoco_ev_wterr(dev, hw);
2702                 if (events & HERMES_EV_INFDROP)
2703                         __orinoco_ev_infdrop(dev, hw);
2704                 if (events & HERMES_EV_INFO)
2705                         __orinoco_ev_info(dev, hw);
2706                 if (events & HERMES_EV_RX)
2707                         __orinoco_ev_rx(dev, hw);
2708                 if (events & HERMES_EV_TXEXC)
2709                         __orinoco_ev_txexc(dev, hw);
2710                 if (events & HERMES_EV_TX)
2711                         __orinoco_ev_tx(dev, hw);
2712                 if (events & HERMES_EV_ALLOC)
2713                         __orinoco_ev_alloc(dev, hw);
2714                 
2715                 hermes_write_regn(hw, EVACK, evstat);
2716
2717                 evstat = hermes_read_regn(hw, EVSTAT);
2718                 events = evstat & hw->inten;
2719         };
2720
2721         orinoco_unlock(priv, &flags);
2722         return IRQ_HANDLED;
2723 }
2724
2725 /********************************************************************/
2726 /* Initialization                                                   */
2727 /********************************************************************/
2728
2729 struct comp_id {
2730         u16 id, variant, major, minor;
2731 } __attribute__ ((packed));
2732
2733 static inline fwtype_t determine_firmware_type(struct comp_id *nic_id)
2734 {
2735         if (nic_id->id < 0x8000)
2736                 return FIRMWARE_TYPE_AGERE;
2737         else if (nic_id->id == 0x8000 && nic_id->major == 0)
2738                 return FIRMWARE_TYPE_SYMBOL;
2739         else
2740                 return FIRMWARE_TYPE_INTERSIL;
2741 }
2742
2743 /* Set priv->firmware type, determine firmware properties */
2744 static int determine_firmware(struct net_device *dev)
2745 {
2746         struct orinoco_private *priv = netdev_priv(dev);
2747         hermes_t *hw = &priv->hw;
2748         int err;
2749         struct comp_id nic_id, sta_id;
2750         unsigned int firmver;
2751         char tmp[SYMBOL_MAX_VER_LEN+1] __attribute__((aligned(2)));
2752
2753         /* Get the hardware version */
2754         err = HERMES_READ_RECORD(hw, USER_BAP, HERMES_RID_NICID, &nic_id);
2755         if (err) {
2756                 printk(KERN_ERR "%s: Cannot read hardware identity: error %d\n",
2757                        dev->name, err);
2758                 return err;
2759         }
2760
2761         le16_to_cpus(&nic_id.id);
2762         le16_to_cpus(&nic_id.variant);
2763         le16_to_cpus(&nic_id.major);
2764         le16_to_cpus(&nic_id.minor);
2765         printk(KERN_DEBUG "%s: Hardware identity %04x:%04x:%04x:%04x\n",
2766                dev->name, nic_id.id, nic_id.variant,
2767                nic_id.major, nic_id.minor);
2768
2769         priv->firmware_type = determine_firmware_type(&nic_id);
2770
2771         /* Get the firmware version */
2772         err = HERMES_READ_RECORD(hw, USER_BAP, HERMES_RID_STAID, &sta_id);
2773         if (err) {
2774                 printk(KERN_ERR "%s: Cannot read station identity: error %d\n",
2775                        dev->name, err);
2776                 return err;
2777         }
2778
2779         le16_to_cpus(&sta_id.id);
2780         le16_to_cpus(&sta_id.variant);
2781         le16_to_cpus(&sta_id.major);
2782         le16_to_cpus(&sta_id.minor);
2783         printk(KERN_DEBUG "%s: Station identity  %04x:%04x:%04x:%04x\n",
2784                dev->name, sta_id.id, sta_id.variant,
2785                sta_id.major, sta_id.minor);
2786
2787         switch (sta_id.id) {
2788         case 0x15:
2789                 printk(KERN_ERR "%s: Primary firmware is active\n",
2790                        dev->name);
2791                 return -ENODEV;
2792         case 0x14b:
2793                 printk(KERN_ERR "%s: Tertiary firmware is active\n",
2794                        dev->name);
2795                 return -ENODEV;
2796         case 0x1f:      /* Intersil, Agere, Symbol Spectrum24 */
2797         case 0x21:      /* Symbol Spectrum24 Trilogy */
2798                 break;
2799         default:
2800                 printk(KERN_NOTICE "%s: Unknown station ID, please report\n",
2801                        dev->name);
2802                 break;
2803         }
2804
2805         /* Default capabilities */
2806         priv->has_sensitivity = 1;
2807         priv->has_mwo = 0;
2808         priv->has_preamble = 0;
2809         priv->has_port3 = 1;
2810         priv->has_ibss = 1;
2811         priv->has_wep = 0;
2812         priv->has_big_wep = 0;
2813         priv->has_alt_txcntl = 0;
2814         priv->has_ext_scan = 0;
2815         priv->has_wpa = 0;
2816         priv->do_fw_download = 0;
2817
2818         /* Determine capabilities from the firmware version */
2819         switch (priv->firmware_type) {
2820         case FIRMWARE_TYPE_AGERE:
2821                 /* Lucent Wavelan IEEE, Lucent Orinoco, Cabletron RoamAbout,
2822                    ELSA, Melco, HP, IBM, Dell 1150, Compaq 110/210 */
2823                 snprintf(priv->fw_name, sizeof(priv->fw_name) - 1,
2824                          "Lucent/Agere %d.%02d", sta_id.major, sta_id.minor);
2825
2826                 firmver = ((unsigned long)sta_id.major << 16) | sta_id.minor;
2827
2828                 priv->has_ibss = (firmver >= 0x60006);
2829                 priv->has_wep = (firmver >= 0x40020);
2830                 priv->has_big_wep = 1; /* FIXME: this is wrong - how do we tell
2831                                           Gold cards from the others? */
2832                 priv->has_mwo = (firmver >= 0x60000);
2833                 priv->has_pm = (firmver >= 0x40020); /* Don't work in 7.52 ? */
2834                 priv->ibss_port = 1;
2835                 priv->has_hostscan = (firmver >= 0x8000a);
2836                 priv->do_fw_download = 1;
2837                 priv->broken_monitor = (firmver >= 0x80000);
2838                 priv->has_alt_txcntl = (firmver >= 0x90000); /* All 9.x ? */
2839                 priv->has_ext_scan = (firmver >= 0x90000); /* All 9.x ? */
2840                 priv->has_wpa = (firmver >= 0x9002a);
2841                 /* Tested with Agere firmware :
2842                  *      1.16 ; 4.08 ; 4.52 ; 6.04 ; 6.16 ; 7.28 => Jean II
2843                  * Tested CableTron firmware : 4.32 => Anton */
2844                 break;
2845         case FIRMWARE_TYPE_SYMBOL:
2846                 /* Symbol , 3Com AirConnect, Intel, Ericsson WLAN */
2847                 /* Intel MAC : 00:02:B3:* */
2848                 /* 3Com MAC : 00:50:DA:* */
2849                 memset(tmp, 0, sizeof(tmp));
2850                 /* Get the Symbol firmware version */
2851                 err = hermes_read_ltv(hw, USER_BAP,
2852                                       HERMES_RID_SECONDARYVERSION_SYMBOL,
2853                                       SYMBOL_MAX_VER_LEN, NULL, &tmp);
2854                 if (err) {
2855                         printk(KERN_WARNING
2856                                "%s: Error %d reading Symbol firmware info. Wildly guessing capabilities...\n",
2857                                dev->name, err);
2858                         firmver = 0;
2859                         tmp[0] = '\0';
2860                 } else {
2861                         /* The firmware revision is a string, the format is
2862                          * something like : "V2.20-01".
2863                          * Quick and dirty parsing... - Jean II
2864                          */
2865                         firmver = ((tmp[1] - '0') << 16) | ((tmp[3] - '0') << 12)
2866                                 | ((tmp[4] - '0') << 8) | ((tmp[6] - '0') << 4)
2867                                 | (tmp[7] - '0');
2868
2869                         tmp[SYMBOL_MAX_VER_LEN] = '\0';
2870                 }
2871
2872                 snprintf(priv->fw_name, sizeof(priv->fw_name) - 1,
2873                          "Symbol %s", tmp);
2874
2875                 priv->has_ibss = (firmver >= 0x20000);
2876                 priv->has_wep = (firmver >= 0x15012);
2877                 priv->has_big_wep = (firmver >= 0x20000);
2878                 priv->has_pm = (firmver >= 0x20000 && firmver < 0x22000) || 
2879                                (firmver >= 0x29000 && firmver < 0x30000) ||
2880                                firmver >= 0x31000;
2881                 priv->has_preamble = (firmver >= 0x20000);
2882                 priv->ibss_port = 4;
2883
2884                 /* Symbol firmware is found on various cards, but
2885                  * there has been no attempt to check firmware
2886                  * download on non-spectrum_cs based cards.
2887                  *
2888                  * Given that the Agere firmware download works
2889                  * differently, we should avoid doing a firmware
2890                  * download with the Symbol algorithm on non-spectrum
2891                  * cards.
2892                  *
2893                  * For now we can identify a spectrum_cs based card
2894                  * because it has a firmware reset function.
2895                  */
2896                 priv->do_fw_download = (priv->stop_fw != NULL);
2897
2898                 priv->broken_disableport = (firmver == 0x25013) ||
2899                                            (firmver >= 0x30000 && firmver <= 0x31000);
2900                 priv->has_hostscan = (firmver >= 0x31001) ||
2901                                      (firmver >= 0x29057 && firmver < 0x30000);
2902                 /* Tested with Intel firmware : 0x20015 => Jean II */
2903                 /* Tested with 3Com firmware : 0x15012 & 0x22001 => Jean II */
2904                 break;
2905         case FIRMWARE_TYPE_INTERSIL:
2906                 /* D-Link, Linksys, Adtron, ZoomAir, and many others...
2907                  * Samsung, Compaq 100/200 and Proxim are slightly
2908                  * different and less well tested */
2909                 /* D-Link MAC : 00:40:05:* */
2910                 /* Addtron MAC : 00:90:D1:* */
2911                 snprintf(priv->fw_name, sizeof(priv->fw_name) - 1,
2912                          "Intersil %d.%d.%d", sta_id.major, sta_id.minor,
2913                          sta_id.variant);
2914
2915                 firmver = ((unsigned long)sta_id.major << 16) |
2916                         ((unsigned long)sta_id.minor << 8) | sta_id.variant;
2917
2918                 priv->has_ibss = (firmver >= 0x000700); /* FIXME */
2919                 priv->has_big_wep = priv->has_wep = (firmver >= 0x000800);
2920                 priv->has_pm = (firmver >= 0x000700);
2921                 priv->has_hostscan = (firmver >= 0x010301);
2922
2923                 if (firmver >= 0x000800)
2924                         priv->ibss_port = 0;
2925                 else {
2926                         printk(KERN_NOTICE "%s: Intersil firmware earlier "
2927                                "than v0.8.x - several features not supported\n",
2928                                dev->name);
2929                         priv->ibss_port = 1;
2930                 }
2931                 break;
2932         }
2933         printk(KERN_DEBUG "%s: Firmware determined as %s\n", dev->name,
2934                priv->fw_name);
2935
2936         return 0;
2937 }
2938
2939 static int orinoco_init(struct net_device *dev)
2940 {
2941         struct orinoco_private *priv = netdev_priv(dev);
2942         hermes_t *hw = &priv->hw;
2943         int err = 0;
2944         struct hermes_idstring nickbuf;
2945         u16 reclen;
2946         int len;
2947         DECLARE_MAC_BUF(mac);
2948
2949         /* No need to lock, the hw_unavailable flag is already set in
2950          * alloc_orinocodev() */
2951         priv->nicbuf_size = IEEE80211_FRAME_LEN + ETH_HLEN;
2952
2953         /* Initialize the firmware */
2954         err = hermes_init(hw);
2955         if (err != 0) {
2956                 printk(KERN_ERR "%s: failed to initialize firmware (err = %d)\n",
2957                        dev->name, err);
2958                 goto out;
2959         }
2960
2961         err = determine_firmware(dev);
2962         if (err != 0) {
2963                 printk(KERN_ERR "%s: Incompatible firmware, aborting\n",
2964                        dev->name);
2965                 goto out;
2966         }
2967
2968         if (priv->do_fw_download) {
2969                 err = orinoco_download(priv);
2970                 if (err)
2971                         priv->do_fw_download = 0;
2972
2973                 /* Check firmware version again */
2974                 err = determine_firmware(dev);
2975                 if (err != 0) {
2976                         printk(KERN_ERR "%s: Incompatible firmware, aborting\n",
2977                                dev->name);
2978                         goto out;
2979                 }
2980         }
2981
2982         if (priv->has_port3)
2983                 printk(KERN_DEBUG "%s: Ad-hoc demo mode supported\n", dev->name);
2984         if (priv->has_ibss)
2985                 printk(KERN_DEBUG "%s: IEEE standard IBSS ad-hoc mode supported\n",
2986                        dev->name);
2987         if (priv->has_wep) {
2988                 printk(KERN_DEBUG "%s: WEP supported, ", dev->name);
2989                 if (priv->has_big_wep)
2990                         printk("104-bit key\n");
2991                 else
2992                         printk("40-bit key\n");
2993         }
2994         if (priv->has_wpa)
2995                 printk(KERN_DEBUG "%s: WPA-PSK supported\n", dev->name);
2996
2997         /* Now we have the firmware capabilities, allocate appropiate
2998          * sized scan buffers */
2999         if (orinoco_bss_data_allocate(priv))
3000                 goto out;
3001         orinoco_bss_data_init(priv);
3002
3003         /* Get the MAC address */
3004         err = hermes_read_ltv(hw, USER_BAP, HERMES_RID_CNFOWNMACADDR,
3005                               ETH_ALEN, NULL, dev->dev_addr);
3006         if (err) {
3007                 printk(KERN_WARNING "%s: failed to read MAC address!\n",
3008                        dev->name);
3009                 goto out;
3010         }
3011
3012         printk(KERN_DEBUG "%s: MAC address %s\n",
3013                dev->name, print_mac(mac, dev->dev_addr));
3014
3015         /* Get the station name */
3016         err = hermes_read_ltv(hw, USER_BAP, HERMES_RID_CNFOWNNAME,
3017                               sizeof(nickbuf), &reclen, &nickbuf);
3018         if (err) {
3019                 printk(KERN_ERR "%s: failed to read station name\n",
3020                        dev->name);
3021                 goto out;
3022         }
3023         if (nickbuf.len)
3024                 len = min(IW_ESSID_MAX_SIZE, (int)le16_to_cpu(nickbuf.len));
3025         else
3026                 len = min(IW_ESSID_MAX_SIZE, 2 * reclen);
3027         memcpy(priv->nick, &nickbuf.val, len);
3028         priv->nick[len] = '\0';
3029
3030         printk(KERN_DEBUG "%s: Station name \"%s\"\n", dev->name, priv->nick);
3031
3032         err = orinoco_allocate_fid(dev);
3033         if (err) {
3034                 printk(KERN_ERR "%s: failed to allocate NIC buffer!\n",
3035                        dev->name);
3036                 goto out;
3037         }
3038
3039         /* Get allowed channels */
3040         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CHANNELLIST,
3041                                   &priv->channel_mask);
3042         if (err) {
3043                 printk(KERN_ERR "%s: failed to read channel list!\n",
3044                        dev->name);
3045                 goto out;
3046         }
3047
3048         /* Get initial AP density */
3049         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CNFSYSTEMSCALE,
3050                                   &priv->ap_density);
3051         if (err || priv->ap_density < 1 || priv->ap_density > 3) {
3052                 priv->has_sensitivity = 0;
3053         }
3054
3055         /* Get initial RTS threshold */
3056         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CNFRTSTHRESHOLD,
3057                                   &priv->rts_thresh);
3058         if (err) {
3059                 printk(KERN_ERR "%s: failed to read RTS threshold!\n",
3060                        dev->name);
3061                 goto out;
3062         }
3063
3064         /* Get initial fragmentation settings */
3065         if (priv->has_mwo)
3066                 err = hermes_read_wordrec(hw, USER_BAP,
3067                                           HERMES_RID_CNFMWOROBUST_AGERE,
3068                                           &priv->mwo_robust);
3069         else
3070                 err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CNFFRAGMENTATIONTHRESHOLD,
3071                                           &priv->frag_thresh);
3072         if (err) {
3073                 printk(KERN_ERR "%s: failed to read fragmentation settings!\n",
3074                        dev->name);
3075                 goto out;
3076         }
3077
3078         /* Power management setup */
3079         if (priv->has_pm) {
3080                 priv->pm_on = 0;
3081                 priv->pm_mcast = 1;
3082                 err = hermes_read_wordrec(hw, USER_BAP,
3083                                           HERMES_RID_CNFMAXSLEEPDURATION,
3084                                           &priv->pm_period);
3085                 if (err) {
3086                         printk(KERN_ERR "%s: failed to read power management period!\n",
3087                                dev->name);
3088                         goto out;
3089                 }
3090                 err = hermes_read_wordrec(hw, USER_BAP,
3091                                           HERMES_RID_CNFPMHOLDOVERDURATION,
3092                                           &priv->pm_timeout);
3093                 if (err) {
3094                         printk(KERN_ERR "%s: failed to read power management timeout!\n",
3095                                dev->name);
3096                         goto out;
3097                 }
3098         }
3099
3100         /* Preamble setup */
3101         if (priv->has_preamble) {
3102                 err = hermes_read_wordrec(hw, USER_BAP,
3103                                           HERMES_RID_CNFPREAMBLE_SYMBOL,
3104                                           &priv->preamble);
3105                 if (err)
3106                         goto out;
3107         }
3108                 
3109         /* Set up the default configuration */
3110         priv->iw_mode = IW_MODE_INFRA;
3111         /* By default use IEEE/IBSS ad-hoc mode if we have it */
3112         priv->prefer_port3 = priv->has_port3 && (! priv->has_ibss);
3113         set_port_type(priv);
3114         priv->channel = 0; /* use firmware default */
3115
3116         priv->promiscuous = 0;
3117         priv->encode_alg = IW_ENCODE_ALG_NONE;
3118         priv->tx_key = 0;
3119         priv->wpa_enabled = 0;
3120         priv->tkip_cm_active = 0;
3121         priv->key_mgmt = 0;
3122         priv->wpa_ie_len = 0;
3123         priv->wpa_ie = NULL;
3124
3125         /* Make the hardware available, as long as it hasn't been
3126          * removed elsewhere (e.g. by PCMCIA hot unplug) */
3127         spin_lock_irq(&priv->lock);
3128         priv->hw_unavailable--;
3129         spin_unlock_irq(&priv->lock);
3130
3131         printk(KERN_DEBUG "%s: ready\n", dev->name);
3132
3133  out:
3134         return err;
3135 }
3136
3137 struct net_device
3138 *alloc_orinocodev(int sizeof_card,
3139                   struct device *device,
3140                   int (*hard_reset)(struct orinoco_private *),
3141                   int (*stop_fw)(struct orinoco_private *, int))
3142 {
3143         struct net_device *dev;
3144         struct orinoco_private *priv;
3145
3146         dev = alloc_etherdev(sizeof(struct orinoco_private) + sizeof_card);
3147         if (! dev)
3148                 return NULL;
3149         priv = netdev_priv(dev);
3150         priv->ndev = dev;
3151         if (sizeof_card)
3152                 priv->card = (void *)((unsigned long)priv
3153                                       + sizeof(struct orinoco_private));
3154         else
3155                 priv->card = NULL;
3156         priv->dev = device;
3157
3158         /* Setup / override net_device fields */
3159         dev->init = orinoco_init;
3160         dev->hard_start_xmit = orinoco_xmit;
3161         dev->tx_timeout = orinoco_tx_timeout;
3162         dev->watchdog_timeo = HZ; /* 1 second timeout */
3163         dev->get_stats = orinoco_get_stats;
3164         dev->ethtool_ops = &orinoco_ethtool_ops;
3165         dev->wireless_handlers = (struct iw_handler_def *)&orinoco_handler_def;
3166 #ifdef WIRELESS_SPY
3167         priv->wireless_data.spy_data = &priv->spy_data;
3168         dev->wireless_data = &priv->wireless_data;
3169 #endif
3170         dev->change_mtu = orinoco_change_mtu;
3171         dev->set_multicast_list = orinoco_set_multicast_list;
3172         /* we use the default eth_mac_addr for setting the MAC addr */
3173
3174         /* Set up default callbacks */
3175         dev->open = orinoco_open;
3176         dev->stop = orinoco_stop;
3177         priv->hard_reset = hard_reset;
3178         priv->stop_fw = stop_fw;
3179
3180         spin_lock_init(&priv->lock);
3181         priv->open = 0;
3182         priv->hw_unavailable = 1; /* orinoco_init() must clear this
3183                                    * before anything else touches the
3184                                    * hardware */
3185         INIT_WORK(&priv->reset_work, orinoco_reset);
3186         INIT_WORK(&priv->join_work, orinoco_join_ap);
3187         INIT_WORK(&priv->wevent_work, orinoco_send_wevents);
3188
3189         netif_carrier_off(dev);
3190         priv->last_linkstatus = 0xffff;
3191
3192         return dev;
3193 }
3194
3195 void free_orinocodev(struct net_device *dev)
3196 {
3197         struct orinoco_private *priv = netdev_priv(dev);
3198
3199         priv->wpa_ie_len = 0;
3200         kfree(priv->wpa_ie);
3201         orinoco_bss_data_free(priv);
3202         free_netdev(dev);
3203 }
3204
3205 /********************************************************************/
3206 /* Wireless extensions                                              */
3207 /********************************************************************/
3208
3209 /* Return : < 0 -> error code ; >= 0 -> length */
3210 static int orinoco_hw_get_essid(struct orinoco_private *priv, int *active,
3211                                 char buf[IW_ESSID_MAX_SIZE+1])
3212 {
3213         hermes_t *hw = &priv->hw;
3214         int err = 0;
3215         struct hermes_idstring essidbuf;
3216         char *p = (char *)(&essidbuf.val);
3217         int len;
3218         unsigned long flags;
3219
3220         if (orinoco_lock(priv, &flags) != 0)
3221                 return -EBUSY;
3222
3223         if (strlen(priv->desired_essid) > 0) {
3224                 /* We read the desired SSID from the hardware rather
3225                    than from priv->desired_essid, just in case the
3226                    firmware is allowed to change it on us. I'm not
3227                    sure about this */
3228                 /* My guess is that the OWNSSID should always be whatever
3229                  * we set to the card, whereas CURRENT_SSID is the one that
3230                  * may change... - Jean II */
3231                 u16 rid;
3232
3233                 *active = 1;
3234
3235                 rid = (priv->port_type == 3) ? HERMES_RID_CNFOWNSSID :
3236                         HERMES_RID_CNFDESIREDSSID;
3237                 
3238                 err = hermes_read_ltv(hw, USER_BAP, rid, sizeof(essidbuf),
3239                                       NULL, &essidbuf);
3240                 if (err)
3241                         goto fail_unlock;
3242         } else {
3243                 *active = 0;
3244
3245                 err = hermes_read_ltv(hw, USER_BAP, HERMES_RID_CURRENTSSID,
3246                                       sizeof(essidbuf), NULL, &essidbuf);
3247                 if (err)
3248                         goto fail_unlock;
3249         }
3250
3251         len = le16_to_cpu(essidbuf.len);
3252         BUG_ON(len > IW_ESSID_MAX_SIZE);
3253
3254         memset(buf, 0, IW_ESSID_MAX_SIZE);
3255         memcpy(buf, p, len);
3256         err = len;
3257
3258  fail_unlock:
3259         orinoco_unlock(priv, &flags);
3260
3261         return err;       
3262 }
3263
3264 static long orinoco_hw_get_freq(struct orinoco_private *priv)
3265 {
3266         
3267         hermes_t *hw = &priv->hw;
3268         int err = 0;
3269         u16 channel;
3270         long freq = 0;
3271         unsigned long flags;
3272
3273         if (orinoco_lock(priv, &flags) != 0)
3274                 return -EBUSY;
3275         
3276         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CURRENTCHANNEL, &channel);
3277         if (err)
3278                 goto out;
3279
3280         /* Intersil firmware 1.3.5 returns 0 when the interface is down */
3281         if (channel == 0) {
3282                 err = -EBUSY;
3283                 goto out;
3284         }
3285
3286         if ( (channel < 1) || (channel > NUM_CHANNELS) ) {
3287                 printk(KERN_WARNING "%s: Channel out of range (%d)!\n",
3288                        priv->ndev->name, channel);
3289                 err = -EBUSY;
3290                 goto out;
3291
3292         }
3293         freq = channel_frequency[channel-1] * 100000;
3294
3295  out:
3296         orinoco_unlock(priv, &flags);
3297
3298         if (err > 0)
3299                 err = -EBUSY;
3300         return err ? err : freq;
3301 }
3302
3303 static int orinoco_hw_get_bitratelist(struct orinoco_private *priv,
3304                                       int *numrates, s32 *rates, int max)
3305 {
3306         hermes_t *hw = &priv->hw;
3307         struct hermes_idstring list;
3308         unsigned char *p = (unsigned char *)&list.val;
3309         int err = 0;
3310         int num;
3311         int i;
3312         unsigned long flags;
3313
3314         if (orinoco_lock(priv, &flags) != 0)
3315                 return -EBUSY;
3316
3317         err = hermes_read_ltv(hw, USER_BAP, HERMES_RID_SUPPORTEDDATARATES,
3318                               sizeof(list), NULL, &list);
3319         orinoco_unlock(priv, &flags);
3320
3321         if (err)
3322                 return err;
3323         
3324         num = le16_to_cpu(list.len);
3325         *numrates = num;
3326         num = min(num, max);
3327
3328         for (i = 0; i < num; i++) {
3329                 rates[i] = (p[i] & 0x7f) * 500000; /* convert to bps */
3330         }
3331
3332         return 0;
3333 }
3334
3335 static int orinoco_ioctl_getname(struct net_device *dev,
3336                                  struct iw_request_info *info,
3337                                  char *name,
3338                                  char *extra)
3339 {
3340         struct orinoco_private *priv = netdev_priv(dev);
3341         int numrates;
3342         int err;
3343
3344         err = orinoco_hw_get_bitratelist(priv, &numrates, NULL, 0);
3345
3346         if (!err && (numrates > 2))
3347                 strcpy(name, "IEEE 802.11b");
3348         else
3349                 strcpy(name, "IEEE 802.11-DS");
3350
3351         return 0;
3352 }
3353
3354 static int orinoco_ioctl_setwap(struct net_device *dev,
3355                                 struct iw_request_info *info,
3356                                 struct sockaddr *ap_addr,
3357                                 char *extra)
3358 {
3359         struct orinoco_private *priv = netdev_priv(dev);
3360         int err = -EINPROGRESS;         /* Call commit handler */
3361         unsigned long flags;
3362         static const u8 off_addr[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
3363         static const u8 any_addr[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
3364
3365         if (orinoco_lock(priv, &flags) != 0)
3366                 return -EBUSY;
3367
3368         /* Enable automatic roaming - no sanity checks are needed */
3369         if (memcmp(&ap_addr->sa_data, off_addr, ETH_ALEN) == 0 ||
3370             memcmp(&ap_addr->sa_data, any_addr, ETH_ALEN) == 0) {
3371                 priv->bssid_fixed = 0;
3372                 memset(priv->desired_bssid, 0, ETH_ALEN);
3373
3374                 /* "off" means keep existing connection */
3375                 if (ap_addr->sa_data[0] == 0) {
3376                         __orinoco_hw_set_wap(priv);
3377                         err = 0;
3378                 }
3379                 goto out;
3380         }
3381
3382         if (priv->firmware_type == FIRMWARE_TYPE_AGERE) {
3383                 printk(KERN_WARNING "%s: Lucent/Agere firmware doesn't "
3384                        "support manual roaming\n",
3385                        dev->name);
3386                 err = -EOPNOTSUPP;
3387                 goto out;
3388         }
3389
3390         if (priv->iw_mode != IW_MODE_INFRA) {
3391                 printk(KERN_WARNING "%s: Manual roaming supported only in "
3392                        "managed mode\n", dev->name);
3393                 err = -EOPNOTSUPP;
3394                 goto out;
3395         }
3396
3397         /* Intersil firmware hangs without Desired ESSID */
3398         if (priv->firmware_type == FIRMWARE_TYPE_INTERSIL &&
3399             strlen(priv->desired_essid) == 0) {
3400                 printk(KERN_WARNING "%s: Desired ESSID must be set for "
3401                        "manual roaming\n", dev->name);
3402                 err = -EOPNOTSUPP;
3403                 goto out;
3404         }
3405
3406         /* Finally, enable manual roaming */
3407         priv->bssid_fixed = 1;
3408         memcpy(priv->desired_bssid, &ap_addr->sa_data, ETH_ALEN);
3409
3410  out:
3411         orinoco_unlock(priv, &flags);
3412         return err;
3413 }
3414
3415 static int orinoco_ioctl_getwap(struct net_device *dev,
3416                                 struct iw_request_info *info,
3417                                 struct sockaddr *ap_addr,
3418                                 char *extra)
3419 {
3420         struct orinoco_private *priv = netdev_priv(dev);
3421
3422         hermes_t *hw = &priv->hw;
3423         int err = 0;
3424         unsigned long flags;
3425
3426         if (orinoco_lock(priv, &flags) != 0)
3427                 return -EBUSY;
3428
3429         ap_addr->sa_family = ARPHRD_ETHER;
3430         err = hermes_read_ltv(hw, USER_BAP, HERMES_RID_CURRENTBSSID,
3431                               ETH_ALEN, NULL, ap_addr->sa_data);
3432
3433         orinoco_unlock(priv, &flags);
3434
3435         return err;
3436 }
3437
3438 static int orinoco_ioctl_setmode(struct net_device *dev,
3439                                  struct iw_request_info *info,
3440                                  u32 *mode,
3441                                  char *extra)
3442 {
3443         struct orinoco_private *priv = netdev_priv(dev);
3444         int err = -EINPROGRESS;         /* Call commit handler */
3445         unsigned long flags;
3446
3447         if (priv->iw_mode == *mode)
3448                 return 0;
3449
3450         if (orinoco_lock(priv, &flags) != 0)
3451                 return -EBUSY;
3452
3453         switch (*mode) {
3454         case IW_MODE_ADHOC:
3455                 if (!priv->has_ibss && !priv->has_port3)
3456                         err = -EOPNOTSUPP;
3457                 break;
3458
3459         case IW_MODE_INFRA:
3460                 break;
3461
3462         case IW_MODE_MONITOR:
3463                 if (priv->broken_monitor && !force_monitor) {
3464                         printk(KERN_WARNING "%s: Monitor mode support is "
3465                                "buggy in this firmware, not enabling\n",
3466                                dev->name);
3467                         err = -EOPNOTSUPP;
3468                 }
3469                 break;
3470
3471         default:
3472                 err = -EOPNOTSUPP;
3473                 break;
3474         }
3475
3476         if (err == -EINPROGRESS) {
3477                 priv->iw_mode = *mode;
3478                 set_port_type(priv);
3479         }
3480
3481         orinoco_unlock(priv, &flags);
3482
3483         return err;
3484 }
3485
3486 static int orinoco_ioctl_getmode(struct net_device *dev,
3487                                  struct iw_request_info *info,
3488                                  u32 *mode,
3489                                  char *extra)
3490 {
3491         struct orinoco_private *priv = netdev_priv(dev);
3492
3493         *mode = priv->iw_mode;
3494         return 0;
3495 }
3496
3497 static int orinoco_ioctl_getiwrange(struct net_device *dev,
3498                                     struct iw_request_info *info,
3499                                     struct iw_point *rrq,
3500                                     char *extra)
3501 {
3502         struct orinoco_private *priv = netdev_priv(dev);
3503         int err = 0;
3504         struct iw_range *range = (struct iw_range *) extra;
3505         int numrates;
3506         int i, k;
3507
3508         rrq->length = sizeof(struct iw_range);
3509         memset(range, 0, sizeof(struct iw_range));
3510
3511         range->we_version_compiled = WIRELESS_EXT;
3512         range->we_version_source = 22;
3513
3514         /* Set available channels/frequencies */
3515         range->num_channels = NUM_CHANNELS;
3516         k = 0;
3517         for (i = 0; i < NUM_CHANNELS; i++) {
3518                 if (priv->channel_mask & (1 << i)) {
3519                         range->freq[k].i = i + 1;
3520                         range->freq[k].m = channel_frequency[i] * 100000;
3521                         range->freq[k].e = 1;
3522                         k++;
3523                 }
3524                 
3525                 if (k >= IW_MAX_FREQUENCIES)
3526                         break;
3527         }
3528         range->num_frequency = k;
3529         range->sensitivity = 3;
3530
3531         if (priv->has_wep) {
3532                 range->max_encoding_tokens = ORINOCO_MAX_KEYS;
3533                 range->encoding_size[0] = SMALL_KEY_SIZE;
3534                 range->num_encoding_sizes = 1;
3535
3536                 if (priv->has_big_wep) {
3537                         range->encoding_size[1] = LARGE_KEY_SIZE;
3538                         range->num_encoding_sizes = 2;
3539                 }
3540         }
3541
3542         if (priv->has_wpa)
3543                 range->enc_capa = IW_ENC_CAPA_WPA | IW_ENC_CAPA_CIPHER_TKIP;
3544
3545         if ((priv->iw_mode == IW_MODE_ADHOC) && (!SPY_NUMBER(priv))){
3546                 /* Quality stats meaningless in ad-hoc mode */
3547         } else {
3548                 range->max_qual.qual = 0x8b - 0x2f;
3549                 range->max_qual.level = 0x2f - 0x95 - 1;
3550                 range->max_qual.noise = 0x2f - 0x95 - 1;
3551                 /* Need to get better values */
3552                 range->avg_qual.qual = 0x24;
3553                 range->avg_qual.level = 0xC2;
3554                 range->avg_qual.noise = 0x9E;
3555         }
3556
3557         err = orinoco_hw_get_bitratelist(priv, &numrates,
3558                                          range->bitrate, IW_MAX_BITRATES);
3559         if (err)
3560                 return err;
3561         range->num_bitrates = numrates;
3562
3563         /* Set an indication of the max TCP throughput in bit/s that we can
3564          * expect using this interface. May be use for QoS stuff...
3565          * Jean II */
3566         if (numrates > 2)
3567                 range->throughput = 5 * 1000 * 1000;    /* ~5 Mb/s */
3568         else
3569                 range->throughput = 1.5 * 1000 * 1000;  /* ~1.5 Mb/s */
3570
3571         range->min_rts = 0;
3572         range->max_rts = 2347;
3573         range->min_frag = 256;
3574         range->max_frag = 2346;
3575
3576         range->min_pmp = 0;
3577         range->max_pmp = 65535000;
3578         range->min_pmt = 0;
3579         range->max_pmt = 65535 * 1000;  /* ??? */
3580         range->pmp_flags = IW_POWER_PERIOD;
3581         range->pmt_flags = IW_POWER_TIMEOUT;
3582         range->pm_capa = IW_POWER_PERIOD | IW_POWER_TIMEOUT | IW_POWER_UNICAST_R;
3583
3584         range->retry_capa = IW_RETRY_LIMIT | IW_RETRY_LIFETIME;
3585         range->retry_flags = IW_RETRY_LIMIT;
3586         range->r_time_flags = IW_RETRY_LIFETIME;
3587         range->min_retry = 0;
3588         range->max_retry = 65535;       /* ??? */
3589         range->min_r_time = 0;
3590         range->max_r_time = 65535 * 1000;       /* ??? */
3591
3592         if (priv->firmware_type == FIRMWARE_TYPE_AGERE)
3593                 range->scan_capa = IW_SCAN_CAPA_ESSID;
3594         else
3595                 range->scan_capa = IW_SCAN_CAPA_NONE;
3596
3597         /* Event capability (kernel) */
3598         IW_EVENT_CAPA_SET_KERNEL(range->event_capa);
3599         /* Event capability (driver) */
3600         IW_EVENT_CAPA_SET(range->event_capa, SIOCGIWTHRSPY);
3601         IW_EVENT_CAPA_SET(range->event_capa, SIOCGIWAP);
3602         IW_EVENT_CAPA_SET(range->event_capa, SIOCGIWSCAN);
3603         IW_EVENT_CAPA_SET(range->event_capa, IWEVTXDROP);
3604
3605         return 0;
3606 }
3607
3608 static int orinoco_ioctl_setiwencode(struct net_device *dev,
3609                                      struct iw_request_info *info,
3610                                      struct iw_point *erq,
3611                                      char *keybuf)
3612 {
3613         struct orinoco_private *priv = netdev_priv(dev);
3614         int index = (erq->flags & IW_ENCODE_INDEX) - 1;
3615         int setindex = priv->tx_key;
3616         int encode_alg = priv->encode_alg;
3617         int restricted = priv->wep_restrict;
3618         u16 xlen = 0;
3619         int err = -EINPROGRESS;         /* Call commit handler */
3620         unsigned long flags;
3621
3622         if (! priv->has_wep)
3623                 return -EOPNOTSUPP;
3624
3625         if (erq->pointer) {
3626                 /* We actually have a key to set - check its length */
3627                 if (erq->length > LARGE_KEY_SIZE)
3628                         return -E2BIG;
3629
3630                 if ( (erq->length > SMALL_KEY_SIZE) && !priv->has_big_wep )
3631                         return -E2BIG;
3632         }
3633
3634         if (orinoco_lock(priv, &flags) != 0)
3635                 return -EBUSY;
3636
3637         /* Clear any TKIP key we have */
3638         if ((priv->has_wpa) && (priv->encode_alg == IW_ENCODE_ALG_TKIP))
3639                 (void) orinoco_clear_tkip_key(priv, setindex);
3640
3641         if (erq->length > 0) {
3642                 if ((index < 0) || (index >= ORINOCO_MAX_KEYS))
3643                         index = priv->tx_key;
3644
3645                 /* Adjust key length to a supported value */
3646                 if (erq->length > SMALL_KEY_SIZE) {
3647                         xlen = LARGE_KEY_SIZE;
3648                 } else if (erq->length > 0) {
3649                         xlen = SMALL_KEY_SIZE;
3650                 } else
3651                         xlen = 0;
3652
3653                 /* Switch on WEP if off */
3654                 if ((encode_alg != IW_ENCODE_ALG_WEP) && (xlen > 0)) {
3655                         setindex = index;
3656                         encode_alg = IW_ENCODE_ALG_WEP;
3657                 }
3658         } else {
3659                 /* Important note : if the user do "iwconfig eth0 enc off",
3660                  * we will arrive there with an index of -1. This is valid
3661                  * but need to be taken care off... Jean II */
3662                 if ((index < 0) || (index >= ORINOCO_MAX_KEYS)) {
3663                         if((index != -1) || (erq->flags == 0)) {
3664                                 err = -EINVAL;
3665                                 goto out;
3666                         }
3667                 } else {
3668                         /* Set the index : Check that the key is valid */
3669                         if(priv->keys[index].len == 0) {
3670                                 err = -EINVAL;
3671                                 goto out;
3672                         }
3673                         setindex = index;
3674                 }
3675         }
3676
3677         if (erq->flags & IW_ENCODE_DISABLED)
3678                 encode_alg = IW_ENCODE_ALG_NONE;
3679         if (erq->flags & IW_ENCODE_OPEN)
3680                 restricted = 0;
3681         if (erq->flags & IW_ENCODE_RESTRICTED)
3682                 restricted = 1;
3683
3684         if (erq->pointer && erq->length > 0) {
3685                 priv->keys[index].len = cpu_to_le16(xlen);
3686                 memset(priv->keys[index].data, 0,
3687                        sizeof(priv->keys[index].data));
3688                 memcpy(priv->keys[index].data, keybuf, erq->length);
3689         }
3690         priv->tx_key = setindex;
3691
3692         /* Try fast key change if connected and only keys are changed */
3693         if ((priv->encode_alg == encode_alg) &&
3694             (priv->wep_restrict == restricted) &&
3695             netif_carrier_ok(dev)) {
3696                 err = __orinoco_hw_setup_wepkeys(priv);
3697                 /* No need to commit if successful */
3698                 goto out;
3699         }
3700
3701         priv->encode_alg = encode_alg;
3702         priv->wep_restrict = restricted;
3703
3704  out:
3705         orinoco_unlock(priv, &flags);
3706
3707         return err;
3708 }
3709
3710 static int orinoco_ioctl_getiwencode(struct net_device *dev,
3711                                      struct iw_request_info *info,
3712                                      struct iw_point *erq,
3713                                      char *keybuf)
3714 {
3715         struct orinoco_private *priv = netdev_priv(dev);
3716         int index = (erq->flags & IW_ENCODE_INDEX) - 1;
3717         u16 xlen = 0;
3718         unsigned long flags;
3719
3720         if (! priv->has_wep)
3721                 return -EOPNOTSUPP;
3722
3723         if (orinoco_lock(priv, &flags) != 0)
3724                 return -EBUSY;
3725
3726         if ((index < 0) || (index >= ORINOCO_MAX_KEYS))
3727                 index = priv->tx_key;
3728
3729         erq->flags = 0;
3730         if (!priv->encode_alg)
3731                 erq->flags |= IW_ENCODE_DISABLED;
3732         erq->flags |= index + 1;
3733
3734         if (priv->wep_restrict)
3735                 erq->flags |= IW_ENCODE_RESTRICTED;
3736         else
3737                 erq->flags |= IW_ENCODE_OPEN;
3738
3739         xlen = le16_to_cpu(priv->keys[index].len);
3740
3741         erq->length = xlen;
3742
3743         memcpy(keybuf, priv->keys[index].data, ORINOCO_MAX_KEY_SIZE);
3744
3745         orinoco_unlock(priv, &flags);
3746         return 0;
3747 }
3748
3749 static int orinoco_ioctl_setessid(struct net_device *dev,
3750                                   struct iw_request_info *info,
3751                                   struct iw_point *erq,
3752                                   char *essidbuf)
3753 {
3754         struct orinoco_private *priv = netdev_priv(dev);
3755         unsigned long flags;
3756
3757         /* Note : ESSID is ignored in Ad-Hoc demo mode, but we can set it
3758          * anyway... - Jean II */
3759
3760         /* Hum... Should not use Wireless Extension constant (may change),
3761          * should use our own... - Jean II */
3762         if (erq->length > IW_ESSID_MAX_SIZE)
3763                 return -E2BIG;
3764
3765         if (orinoco_lock(priv, &flags) != 0)
3766                 return -EBUSY;
3767
3768         /* NULL the string (for NULL termination & ESSID = ANY) - Jean II */
3769         memset(priv->desired_essid, 0, sizeof(priv->desired_essid));
3770
3771         /* If not ANY, get the new ESSID */
3772         if (erq->flags) {
3773                 memcpy(priv->desired_essid, essidbuf, erq->length);
3774         }
3775
3776         orinoco_unlock(priv, &flags);
3777
3778         return -EINPROGRESS;            /* Call commit handler */
3779 }
3780
3781 static int orinoco_ioctl_getessid(struct net_device *dev,
3782                                   struct iw_request_info *info,
3783                                   struct iw_point *erq,
3784                                   char *essidbuf)
3785 {
3786         struct orinoco_private *priv = netdev_priv(dev);
3787         int active;
3788         int err = 0;
3789         unsigned long flags;
3790
3791         if (netif_running(dev)) {
3792                 err = orinoco_hw_get_essid(priv, &active, essidbuf);
3793                 if (err < 0)
3794                         return err;
3795                 erq->length = err;
3796         } else {
3797                 if (orinoco_lock(priv, &flags) != 0)
3798                         return -EBUSY;
3799                 memcpy(essidbuf, priv->desired_essid, IW_ESSID_MAX_SIZE);
3800                 erq->length = strlen(priv->desired_essid);
3801                 orinoco_unlock(priv, &flags);
3802         }
3803
3804         erq->flags = 1;
3805
3806         return 0;
3807 }
3808
3809 static int orinoco_ioctl_setnick(struct net_device *dev,
3810                                  struct iw_request_info *info,
3811                                  struct iw_point *nrq,
3812                                  char *nickbuf)
3813 {
3814         struct orinoco_private *priv = netdev_priv(dev);
3815         unsigned long flags;
3816
3817         if (nrq->length > IW_ESSID_MAX_SIZE)
3818                 return -E2BIG;
3819
3820         if (orinoco_lock(priv, &flags) != 0)
3821                 return -EBUSY;
3822
3823         memset(priv->nick, 0, sizeof(priv->nick));
3824         memcpy(priv->nick, nickbuf, nrq->length);
3825
3826         orinoco_unlock(priv, &flags);
3827
3828         return -EINPROGRESS;            /* Call commit handler */
3829 }
3830
3831 static int orinoco_ioctl_getnick(struct net_device *dev,
3832                                  struct iw_request_info *info,
3833                                  struct iw_point *nrq,
3834                                  char *nickbuf)
3835 {
3836         struct orinoco_private *priv = netdev_priv(dev);
3837         unsigned long flags;
3838
3839         if (orinoco_lock(priv, &flags) != 0)
3840                 return -EBUSY;
3841
3842         memcpy(nickbuf, priv->nick, IW_ESSID_MAX_SIZE);
3843         orinoco_unlock(priv, &flags);
3844
3845         nrq->length = strlen(priv->nick);
3846
3847         return 0;
3848 }
3849
3850 static int orinoco_ioctl_setfreq(struct net_device *dev,
3851                                  struct iw_request_info *info,
3852                                  struct iw_freq *frq,
3853                                  char *extra)
3854 {
3855         struct orinoco_private *priv = netdev_priv(dev);
3856         int chan = -1;
3857         unsigned long flags;
3858         int err = -EINPROGRESS;         /* Call commit handler */
3859
3860         /* In infrastructure mode the AP sets the channel */
3861         if (priv->iw_mode == IW_MODE_INFRA)
3862                 return -EBUSY;
3863
3864         if ( (frq->e == 0) && (frq->m <= 1000) ) {
3865                 /* Setting by channel number */
3866                 chan = frq->m;
3867         } else {
3868                 /* Setting by frequency - search the table */
3869                 int mult = 1;
3870                 int i;
3871
3872                 for (i = 0; i < (6 - frq->e); i++)
3873                         mult *= 10;
3874
3875                 for (i = 0; i < NUM_CHANNELS; i++)
3876                         if (frq->m == (channel_frequency[i] * mult))
3877                                 chan = i+1;
3878         }
3879
3880         if ( (chan < 1) || (chan > NUM_CHANNELS) ||
3881              ! (priv->channel_mask & (1 << (chan-1)) ) )
3882                 return -EINVAL;
3883
3884         if (orinoco_lock(priv, &flags) != 0)
3885                 return -EBUSY;
3886
3887         priv->channel = chan;
3888         if (priv->iw_mode == IW_MODE_MONITOR) {
3889                 /* Fast channel change - no commit if successful */
3890                 hermes_t *hw = &priv->hw;
3891                 err = hermes_docmd_wait(hw, HERMES_CMD_TEST |
3892                                             HERMES_TEST_SET_CHANNEL,
3893                                         chan, NULL);
3894         }
3895         orinoco_unlock(priv, &flags);
3896
3897         return err;
3898 }
3899
3900 static int orinoco_ioctl_getfreq(struct net_device *dev,
3901                                  struct iw_request_info *info,
3902                                  struct iw_freq *frq,
3903                                  char *extra)
3904 {
3905         struct orinoco_private *priv = netdev_priv(dev);
3906         int tmp;
3907
3908         /* Locking done in there */
3909         tmp = orinoco_hw_get_freq(priv);
3910         if (tmp < 0) {
3911                 return tmp;
3912         }
3913
3914         frq->m = tmp;
3915         frq->e = 1;
3916
3917         return 0;
3918 }
3919
3920 static int orinoco_ioctl_getsens(struct net_device *dev,
3921                                  struct iw_request_info *info,
3922                                  struct iw_param *srq,
3923                                  char *extra)
3924 {
3925         struct orinoco_private *priv = netdev_priv(dev);
3926         hermes_t *hw = &priv->hw;
3927         u16 val;
3928         int err;
3929         unsigned long flags;
3930
3931         if (!priv->has_sensitivity)
3932                 return -EOPNOTSUPP;
3933
3934         if (orinoco_lock(priv, &flags) != 0)
3935                 return -EBUSY;
3936         err = hermes_read_wordrec(hw, USER_BAP,
3937                                   HERMES_RID_CNFSYSTEMSCALE, &val);
3938         orinoco_unlock(priv, &flags);
3939
3940         if (err)
3941                 return err;
3942
3943         srq->value = val;
3944         srq->fixed = 0; /* auto */
3945
3946         return 0;
3947 }
3948
3949 static int orinoco_ioctl_setsens(struct net_device *dev,
3950                                  struct iw_request_info *info,
3951                                  struct iw_param *srq,
3952                                  char *extra)
3953 {
3954         struct orinoco_private *priv = netdev_priv(dev);
3955         int val = srq->value;
3956         unsigned long flags;
3957
3958         if (!priv->has_sensitivity)
3959                 return -EOPNOTSUPP;
3960
3961         if ((val < 1) || (val > 3))
3962                 return -EINVAL;
3963         
3964         if (orinoco_lock(priv, &flags) != 0)
3965                 return -EBUSY;
3966         priv->ap_density = val;
3967         orinoco_unlock(priv, &flags);
3968
3969         return -EINPROGRESS;            /* Call commit handler */
3970 }
3971
3972 static int orinoco_ioctl_setrts(struct net_device *dev,
3973                                 struct iw_request_info *info,
3974                                 struct iw_param *rrq,
3975                                 char *extra)
3976 {
3977         struct orinoco_private *priv = netdev_priv(dev);
3978         int val = rrq->value;
3979         unsigned long flags;
3980
3981         if (rrq->disabled)
3982                 val = 2347;
3983
3984         if ( (val < 0) || (val > 2347) )
3985                 return -EINVAL;
3986
3987         if (orinoco_lock(priv, &flags) != 0)
3988                 return -EBUSY;
3989
3990         priv->rts_thresh = val;
3991         orinoco_unlock(priv, &flags);
3992
3993         return -EINPROGRESS;            /* Call commit handler */
3994 }
3995
3996 static int orinoco_ioctl_getrts(struct net_device *dev,
3997                                 struct iw_request_info *info,
3998                                 struct iw_param *rrq,
3999                                 char *extra)
4000 {
4001         struct orinoco_private *priv = netdev_priv(dev);
4002
4003         rrq->value = priv->rts_thresh;
4004         rrq->disabled = (rrq->value == 2347);
4005         rrq->fixed = 1;
4006
4007         return 0;
4008 }
4009
4010 static int orinoco_ioctl_setfrag(struct net_device *dev,
4011                                  struct iw_request_info *info,
4012                                  struct iw_param *frq,
4013                                  char *extra)
4014 {
4015         struct orinoco_private *priv = netdev_priv(dev);
4016         int err = -EINPROGRESS;         /* Call commit handler */
4017         unsigned long flags;
4018
4019         if (orinoco_lock(priv, &flags) != 0)
4020                 return -EBUSY;
4021
4022         if (priv->has_mwo) {
4023                 if (frq->disabled)
4024                         priv->mwo_robust = 0;
4025                 else {
4026                         if (frq->fixed)
4027                                 printk(KERN_WARNING "%s: Fixed fragmentation is "
4028                                        "not supported on this firmware. "
4029                                        "Using MWO robust instead.\n", dev->name);
4030                         priv->mwo_robust = 1;
4031                 }
4032         } else {
4033                 if (frq->disabled)
4034                         priv->frag_thresh = 2346;
4035                 else {
4036                         if ( (frq->value < 256) || (frq->value > 2346) )
4037                                 err = -EINVAL;
4038                         else
4039                                 priv->frag_thresh = frq->value & ~0x1; /* must be even */
4040                 }
4041         }
4042
4043         orinoco_unlock(priv, &flags);
4044
4045         return err;
4046 }
4047
4048 static int orinoco_ioctl_getfrag(struct net_device *dev,
4049                                  struct iw_request_info *info,
4050                                  struct iw_param *frq,
4051                                  char *extra)
4052 {
4053         struct orinoco_private *priv = netdev_priv(dev);
4054         hermes_t *hw = &priv->hw;
4055         int err;
4056         u16 val;
4057         unsigned long flags;
4058
4059         if (orinoco_lock(priv, &flags) != 0)
4060                 return -EBUSY;
4061         
4062         if (priv->has_mwo) {
4063                 err = hermes_read_wordrec(hw, USER_BAP,
4064                                           HERMES_RID_CNFMWOROBUST_AGERE,
4065                                           &val);
4066                 if (err)
4067                         val = 0;
4068
4069                 frq->value = val ? 2347 : 0;
4070                 frq->disabled = ! val;
4071                 frq->fixed = 0;
4072         } else {
4073                 err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CNFFRAGMENTATIONTHRESHOLD,
4074                                           &val);
4075                 if (err)
4076                         val = 0;
4077
4078                 frq->value = val;
4079                 frq->disabled = (val >= 2346);
4080                 frq->fixed = 1;
4081         }
4082
4083         orinoco_unlock(priv, &flags);
4084         
4085         return err;
4086 }
4087
4088 static int orinoco_ioctl_setrate(struct net_device *dev,
4089                                  struct iw_request_info *info,
4090                                  struct iw_param *rrq,
4091                                  char *extra)
4092 {
4093         struct orinoco_private *priv = netdev_priv(dev);
4094         int ratemode = -1;
4095         int bitrate; /* 100s of kilobits */
4096         int i;
4097         unsigned long flags;
4098         
4099         /* As the user space doesn't know our highest rate, it uses -1
4100          * to ask us to set the highest rate.  Test it using "iwconfig
4101          * ethX rate auto" - Jean II */
4102         if (rrq->value == -1)
4103                 bitrate = 110;
4104         else {
4105                 if (rrq->value % 100000)
4106                         return -EINVAL;
4107                 bitrate = rrq->value / 100000;
4108         }
4109
4110         if ( (bitrate != 10) && (bitrate != 20) &&
4111              (bitrate != 55) && (bitrate != 110) )
4112                 return -EINVAL;
4113
4114         for (i = 0; i < BITRATE_TABLE_SIZE; i++)
4115                 if ( (bitrate_table[i].bitrate == bitrate) &&
4116                      (bitrate_table[i].automatic == ! rrq->fixed) ) {
4117                         ratemode = i;
4118                         break;
4119                 }
4120         
4121         if (ratemode == -1)
4122                 return -EINVAL;
4123
4124         if (orinoco_lock(priv, &flags) != 0)
4125                 return -EBUSY;
4126         priv->bitratemode = ratemode;
4127         orinoco_unlock(priv, &flags);
4128
4129         return -EINPROGRESS;
4130 }
4131
4132 static int orinoco_ioctl_getrate(struct net_device *dev,
4133                                  struct iw_request_info *info,
4134                                  struct iw_param *rrq,
4135                                  char *extra)
4136 {
4137         struct orinoco_private *priv = netdev_priv(dev);
4138         hermes_t *hw = &priv->hw;
4139         int err = 0;
4140         int ratemode;
4141         int i;
4142         u16 val;
4143         unsigned long flags;
4144
4145         if (orinoco_lock(priv, &flags) != 0)
4146                 return -EBUSY;
4147
4148         ratemode = priv->bitratemode;
4149
4150         BUG_ON((ratemode < 0) || (ratemode >= BITRATE_TABLE_SIZE));
4151
4152         rrq->value = bitrate_table[ratemode].bitrate * 100000;
4153         rrq->fixed = ! bitrate_table[ratemode].automatic;
4154         rrq->disabled = 0;
4155
4156         /* If the interface is running we try to find more about the
4157            current mode */
4158         if (netif_running(dev)) {
4159                 err = hermes_read_wordrec(hw, USER_BAP,
4160                                           HERMES_RID_CURRENTTXRATE, &val);
4161                 if (err)
4162                         goto out;
4163                 
4164                 switch (priv->firmware_type) {
4165                 case FIRMWARE_TYPE_AGERE: /* Lucent style rate */
4166                         /* Note : in Lucent firmware, the return value of
4167                          * HERMES_RID_CURRENTTXRATE is the bitrate in Mb/s,
4168                          * and therefore is totally different from the
4169                          * encoding of HERMES_RID_CNFTXRATECONTROL.
4170                          * Don't forget that 6Mb/s is really 5.5Mb/s */
4171                         if (val == 6)
4172                                 rrq->value = 5500000;
4173                         else
4174                                 rrq->value = val * 1000000;
4175                         break;
4176                 case FIRMWARE_TYPE_INTERSIL: /* Intersil style rate */
4177                 case FIRMWARE_TYPE_SYMBOL: /* Symbol style rate */
4178                         for (i = 0; i < BITRATE_TABLE_SIZE; i++)
4179                                 if (bitrate_table[i].intersil_txratectrl == val) {
4180                                         ratemode = i;
4181                                         break;
4182                                 }
4183                         if (i >= BITRATE_TABLE_SIZE)
4184                                 printk(KERN_INFO "%s: Unable to determine current bitrate (0x%04hx)\n",
4185                                        dev->name, val);
4186
4187                         rrq->value = bitrate_table[ratemode].bitrate * 100000;
4188                         break;
4189                 default:
4190                         BUG();
4191                 }
4192         }
4193
4194  out:
4195         orinoco_unlock(priv, &flags);
4196
4197         return err;
4198 }
4199
4200 static int orinoco_ioctl_setpower(struct net_device *dev,
4201                                   struct iw_request_info *info,
4202                                   struct iw_param *prq,
4203                                   char *extra)
4204 {
4205         struct orinoco_private *priv = netdev_priv(dev);
4206         int err = -EINPROGRESS;         /* Call commit handler */
4207         unsigned long flags;
4208
4209         if (orinoco_lock(priv, &flags) != 0)
4210                 return -EBUSY;
4211
4212         if (prq->disabled) {
4213                 priv->pm_on = 0;
4214         } else {
4215                 switch (prq->flags & IW_POWER_MODE) {
4216                 case IW_POWER_UNICAST_R:
4217                         priv->pm_mcast = 0;
4218                         priv->pm_on = 1;
4219                         break;
4220                 case IW_POWER_ALL_R:
4221                         priv->pm_mcast = 1;
4222                         priv->pm_on = 1;
4223                         break;
4224                 case IW_POWER_ON:
4225                         /* No flags : but we may have a value - Jean II */
4226                         break;
4227                 default:
4228                         err = -EINVAL;
4229                         goto out;
4230                 }
4231                 
4232                 if (prq->flags & IW_POWER_TIMEOUT) {
4233                         priv->pm_on = 1;
4234                         priv->pm_timeout = prq->value / 1000;
4235                 }
4236                 if (prq->flags & IW_POWER_PERIOD) {
4237                         priv->pm_on = 1;
4238                         priv->pm_period = prq->value / 1000;
4239                 }
4240                 /* It's valid to not have a value if we are just toggling
4241                  * the flags... Jean II */
4242                 if(!priv->pm_on) {
4243                         err = -EINVAL;
4244                         goto out;
4245                 }                       
4246         }
4247
4248  out:
4249         orinoco_unlock(priv, &flags);
4250
4251         return err;
4252 }
4253
4254 static int orinoco_ioctl_getpower(struct net_device *dev,
4255                                   struct iw_request_info *info,
4256                                   struct iw_param *prq,
4257                                   char *extra)
4258 {
4259         struct orinoco_private *priv = netdev_priv(dev);
4260         hermes_t *hw = &priv->hw;
4261         int err = 0;
4262         u16 enable, period, timeout, mcast;
4263         unsigned long flags;
4264
4265         if (orinoco_lock(priv, &flags) != 0)
4266                 return -EBUSY;
4267         
4268         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CNFPMENABLED, &enable);
4269         if (err)
4270                 goto out;
4271
4272         err = hermes_read_wordrec(hw, USER_BAP,
4273                                   HERMES_RID_CNFMAXSLEEPDURATION, &period);
4274         if (err)
4275                 goto out;
4276
4277         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CNFPMHOLDOVERDURATION, &timeout);
4278         if (err)
4279                 goto out;
4280
4281         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CNFMULTICASTRECEIVE, &mcast);
4282         if (err)
4283                 goto out;
4284
4285         prq->disabled = !enable;
4286         /* Note : by default, display the period */
4287         if ((prq->flags & IW_POWER_TYPE) == IW_POWER_TIMEOUT) {
4288                 prq->flags = IW_POWER_TIMEOUT;
4289                 prq->value = timeout * 1000;
4290         } else {
4291                 prq->flags = IW_POWER_PERIOD;
4292                 prq->value = period * 1000;
4293         }
4294         if (mcast)
4295                 prq->flags |= IW_POWER_ALL_R;
4296         else
4297                 prq->flags |= IW_POWER_UNICAST_R;
4298
4299  out:
4300         orinoco_unlock(priv, &flags);
4301
4302         return err;
4303 }
4304
4305 static int orinoco_ioctl_set_encodeext(struct net_device *dev,
4306                                        struct iw_request_info *info,
4307                                        union iwreq_data *wrqu,
4308                                        char *extra)
4309 {
4310         struct orinoco_private *priv = netdev_priv(dev);
4311         struct iw_point *encoding = &wrqu->encoding;
4312         struct iw_encode_ext *ext = (struct iw_encode_ext *)extra;
4313         int idx, alg = ext->alg, set_key = 1;
4314         unsigned long flags;
4315         int err = -EINVAL;
4316         u16 key_len;
4317
4318         if (orinoco_lock(priv, &flags) != 0)
4319                 return -EBUSY;
4320
4321         /* Determine and validate the key index */
4322         idx = encoding->flags & IW_ENCODE_INDEX;
4323         if (idx) {
4324                 if ((idx < 1) || (idx > WEP_KEYS))
4325                         goto out;
4326                 idx--;
4327         } else
4328                 idx = priv->tx_key;
4329
4330         if (encoding->flags & IW_ENCODE_DISABLED)
4331             alg = IW_ENCODE_ALG_NONE;
4332
4333         if (priv->has_wpa && (alg != IW_ENCODE_ALG_TKIP)) {
4334                 /* Clear any TKIP TX key we had */
4335                 (void) orinoco_clear_tkip_key(priv, priv->tx_key);
4336         }
4337
4338         if (ext->ext_flags & IW_ENCODE_EXT_SET_TX_KEY) {
4339                 priv->tx_key = idx;
4340                 set_key = ((alg == IW_ENCODE_ALG_TKIP) ||
4341                            (ext->key_len > 0)) ? 1 : 0;
4342         }
4343
4344         if (set_key) {
4345                 /* Set the requested key first */
4346                 switch (alg) {
4347                 case IW_ENCODE_ALG_NONE:
4348                         priv->encode_alg = alg;
4349                         priv->keys[idx].len = 0;
4350                         break;
4351
4352                 case IW_ENCODE_ALG_WEP:
4353                         if (ext->key_len > SMALL_KEY_SIZE)
4354                                 key_len = LARGE_KEY_SIZE;
4355                         else if (ext->key_len > 0)
4356                                 key_len = SMALL_KEY_SIZE;
4357                         else
4358                                 goto out;
4359
4360                         priv->encode_alg = alg;
4361                         priv->keys[idx].len = cpu_to_le16(key_len);
4362
4363                         key_len = min(ext->key_len, key_len);
4364
4365                         memset(priv->keys[idx].data, 0, ORINOCO_MAX_KEY_SIZE);
4366                         memcpy(priv->keys[idx].data, ext->key, key_len);
4367                         break;
4368
4369                 case IW_ENCODE_ALG_TKIP:
4370                 {
4371                         hermes_t *hw = &priv->hw;
4372                         u8 *tkip_iv = NULL;
4373
4374                         if (!priv->has_wpa ||
4375                             (ext->key_len > sizeof(priv->tkip_key[0])))
4376                                 goto out;
4377
4378                         priv->encode_alg = alg;
4379                         memset(&priv->tkip_key[idx], 0,
4380                                sizeof(priv->tkip_key[idx]));
4381                         memcpy(&priv->tkip_key[idx], ext->key, ext->key_len);
4382
4383                         if (ext->ext_flags & IW_ENCODE_EXT_RX_SEQ_VALID)
4384                                 tkip_iv = &ext->rx_seq[0];
4385
4386                         err = __orinoco_hw_set_tkip_key(hw, idx,
4387                                  ext->ext_flags & IW_ENCODE_EXT_SET_TX_KEY,
4388                                  (u8 *) &priv->tkip_key[idx],
4389                                  tkip_iv, NULL);
4390                         if (err)
4391                                 printk(KERN_ERR "%s: Error %d setting TKIP key"
4392                                        "\n", dev->name, err);
4393
4394                         goto out;
4395                 }
4396                 default:
4397                         goto out;
4398                 }
4399         }
4400         err = -EINPROGRESS;
4401  out:
4402         orinoco_unlock(priv, &flags);
4403
4404         return err;
4405 }
4406
4407 static int orinoco_ioctl_get_encodeext(struct net_device *dev,
4408                                        struct iw_request_info *info,
4409                                        union iwreq_data *wrqu,
4410                                        char *extra)
4411 {
4412         struct orinoco_private *priv = netdev_priv(dev);
4413         struct iw_point *encoding = &wrqu->encoding;
4414         struct iw_encode_ext *ext = (struct iw_encode_ext *)extra;
4415         int idx, max_key_len;
4416         unsigned long flags;
4417         int err;
4418
4419         if (orinoco_lock(priv, &flags) != 0)
4420                 return -EBUSY;
4421
4422         err = -EINVAL;
4423         max_key_len = encoding->length - sizeof(*ext);
4424         if (max_key_len < 0)
4425                 goto out;
4426
4427         idx = encoding->flags & IW_ENCODE_INDEX;
4428         if (idx) {
4429                 if ((idx < 1) || (idx > WEP_KEYS))
4430                         goto out;
4431                 idx--;
4432         } else
4433                 idx = priv->tx_key;
4434
4435         encoding->flags = idx + 1;
4436         memset(ext, 0, sizeof(*ext));
4437
4438         ext->alg = priv->encode_alg;
4439         switch (priv->encode_alg) {
4440         case IW_ENCODE_ALG_NONE:
4441                 ext->key_len = 0;
4442                 encoding->flags |= IW_ENCODE_DISABLED;
4443                 break;
4444         case IW_ENCODE_ALG_WEP:
4445                 ext->key_len = min(le16_to_cpu(priv->keys[idx].len),
4446                                    (u16) max_key_len);
4447                 memcpy(ext->key, priv->keys[idx].data, ext->key_len);
4448                 encoding->flags |= IW_ENCODE_ENABLED;
4449                 break;
4450         case IW_ENCODE_ALG_TKIP:
4451                 ext->key_len = min((u16) sizeof(struct orinoco_tkip_key),
4452                                    (u16) max_key_len);
4453                 memcpy(ext->key, &priv->tkip_key[idx], ext->key_len);
4454                 encoding->flags |= IW_ENCODE_ENABLED;
4455                 break;
4456         }
4457
4458         err = 0;
4459  out:
4460         orinoco_unlock(priv, &flags);
4461
4462         return err;
4463 }
4464
4465 static int orinoco_ioctl_set_auth(struct net_device *dev,
4466                                   struct iw_request_info *info,
4467                                   union iwreq_data *wrqu, char *extra)
4468 {
4469         struct orinoco_private *priv = netdev_priv(dev);
4470         hermes_t *hw = &priv->hw;
4471         struct iw_param *param = &wrqu->param;
4472         unsigned long flags;
4473         int ret = -EINPROGRESS;
4474
4475         if (orinoco_lock(priv, &flags) != 0)
4476                 return -EBUSY;
4477
4478         switch (param->flags & IW_AUTH_INDEX) {
4479         case IW_AUTH_WPA_VERSION:
4480         case IW_AUTH_CIPHER_PAIRWISE:
4481         case IW_AUTH_CIPHER_GROUP:
4482         case IW_AUTH_RX_UNENCRYPTED_EAPOL:
4483         case IW_AUTH_PRIVACY_INVOKED:
4484         case IW_AUTH_DROP_UNENCRYPTED:
4485                 /*
4486                  * orinoco does not use these parameters
4487                  */
4488                 break;
4489
4490         case IW_AUTH_KEY_MGMT:
4491                 /* wl_lkm implies value 2 == PSK for Hermes I
4492                  * which ties in with WEXT
4493                  * no other hints tho :(
4494                  */
4495                 priv->key_mgmt = param->value;
4496                 break;
4497
4498         case IW_AUTH_TKIP_COUNTERMEASURES:
4499                 /* When countermeasures are enabled, shut down the
4500                  * card; when disabled, re-enable the card. This must
4501                  * take effect immediately.
4502                  *
4503                  * TODO: Make sure that the EAPOL message is getting
4504                  *       out before card disabled
4505                  */
4506                 if (param->value) {
4507                         priv->tkip_cm_active = 1;
4508                         ret = hermes_enable_port(hw, 0);
4509                 } else {
4510                         priv->tkip_cm_active = 0;
4511                         ret = hermes_disable_port(hw, 0);
4512                 }
4513                 break;
4514
4515         case IW_AUTH_80211_AUTH_ALG:
4516                 if (param->value & IW_AUTH_ALG_SHARED_KEY)
4517                         priv->wep_restrict = 1;
4518                 else if (param->value & IW_AUTH_ALG_OPEN_SYSTEM)
4519                         priv->wep_restrict = 0;
4520                 else
4521                         ret = -EINVAL;
4522                 break;
4523
4524         case IW_AUTH_WPA_ENABLED:
4525                 if (priv->has_wpa) {
4526                         priv->wpa_enabled = param->value ? 1 : 0;
4527                 } else {
4528                         if (param->value)
4529                                 ret = -EOPNOTSUPP;
4530                         /* else silently accept disable of WPA */
4531                         priv->wpa_enabled = 0;
4532                 }
4533                 break;
4534
4535         default:
4536                 ret = -EOPNOTSUPP;
4537         }
4538
4539         orinoco_unlock(priv, &flags);
4540         return ret;
4541 }
4542
4543 static int orinoco_ioctl_get_auth(struct net_device *dev,
4544                                   struct iw_request_info *info,
4545                                   union iwreq_data *wrqu, char *extra)
4546 {
4547         struct orinoco_private *priv = netdev_priv(dev);
4548         struct iw_param *param = &wrqu->param;
4549         unsigned long flags;
4550         int ret = 0;
4551
4552         if (orinoco_lock(priv, &flags) != 0)
4553                 return -EBUSY;
4554
4555         switch (param->flags & IW_AUTH_INDEX) {
4556         case IW_AUTH_KEY_MGMT:
4557                 param->value = priv->key_mgmt;
4558                 break;
4559
4560         case IW_AUTH_TKIP_COUNTERMEASURES:
4561                 param->value = priv->tkip_cm_active;
4562                 break;
4563
4564         case IW_AUTH_80211_AUTH_ALG:
4565                 if (priv->wep_restrict)
4566                         param->value = IW_AUTH_ALG_SHARED_KEY;
4567                 else
4568                         param->value = IW_AUTH_ALG_OPEN_SYSTEM;
4569                 break;
4570
4571         case IW_AUTH_WPA_ENABLED:
4572                 param->value = priv->wpa_enabled;
4573                 break;
4574
4575         default:
4576                 ret = -EOPNOTSUPP;
4577         }
4578
4579         orinoco_unlock(priv, &flags);
4580         return ret;
4581 }
4582
4583 static int orinoco_ioctl_set_genie(struct net_device *dev,
4584                                    struct iw_request_info *info,
4585                                    union iwreq_data *wrqu, char *extra)
4586 {
4587         struct orinoco_private *priv = netdev_priv(dev);
4588         u8 *buf;
4589         unsigned long flags;
4590         int err = 0;
4591
4592         if ((wrqu->data.length > MAX_WPA_IE_LEN) ||
4593             (wrqu->data.length && (extra == NULL)))
4594                 return -EINVAL;
4595
4596         if (orinoco_lock(priv, &flags) != 0)
4597                 return -EBUSY;
4598
4599         if (wrqu->data.length) {
4600                 buf = kmalloc(wrqu->data.length, GFP_KERNEL);
4601                 if (buf == NULL) {
4602                         err = -ENOMEM;
4603                         goto out;
4604                 }
4605
4606                 memcpy(buf, extra, wrqu->data.length);
4607                 kfree(priv->wpa_ie);
4608                 priv->wpa_ie = buf;
4609                 priv->wpa_ie_len = wrqu->data.length;
4610         } else {
4611                 kfree(priv->wpa_ie);
4612                 priv->wpa_ie = NULL;
4613                 priv->wpa_ie_len = 0;
4614         }
4615
4616         if (priv->wpa_ie) {
4617                 /* Looks like wl_lkm wants to check the auth alg, and
4618                  * somehow pass it to the firmware.
4619                  * Instead it just calls the key mgmt rid
4620                  *   - we do this in set auth.
4621                  */
4622         }
4623
4624 out:
4625         orinoco_unlock(priv, &flags);
4626         return err;
4627 }
4628
4629 static int orinoco_ioctl_get_genie(struct net_device *dev,
4630                                    struct iw_request_info *info,
4631                                    union iwreq_data *wrqu, char *extra)
4632 {
4633         struct orinoco_private *priv = netdev_priv(dev);
4634         unsigned long flags;
4635         int err = 0;
4636
4637         if (orinoco_lock(priv, &flags) != 0)
4638                 return -EBUSY;
4639
4640         if ((priv->wpa_ie_len == 0) || (priv->wpa_ie == NULL)) {
4641                 wrqu->data.length = 0;
4642                 goto out;
4643         }
4644
4645         if (wrqu->data.length < priv->wpa_ie_len) {
4646                 err = -E2BIG;
4647                 goto out;
4648         }
4649
4650         wrqu->data.length = priv->wpa_ie_len;
4651         memcpy(extra, priv->wpa_ie, priv->wpa_ie_len);
4652
4653 out:
4654         orinoco_unlock(priv, &flags);
4655         return err;
4656 }
4657
4658 static int orinoco_ioctl_set_mlme(struct net_device *dev,
4659                                   struct iw_request_info *info,
4660                                   union iwreq_data *wrqu, char *extra)
4661 {
4662         struct orinoco_private *priv = netdev_priv(dev);
4663         hermes_t *hw = &priv->hw;
4664         struct iw_mlme *mlme = (struct iw_mlme *)extra;
4665         unsigned long flags;
4666         int ret = 0;
4667
4668         if (orinoco_lock(priv, &flags) != 0)
4669                 return -EBUSY;
4670
4671         switch (mlme->cmd) {
4672         case IW_MLME_DEAUTH:
4673                 /* silently ignore */
4674                 break;
4675
4676         case IW_MLME_DISASSOC:
4677         {
4678                 struct {
4679                         u8 addr[ETH_ALEN];
4680                         __le16 reason_code;
4681                 } __attribute__ ((packed)) buf;
4682
4683                 memcpy(buf.addr, mlme->addr.sa_data, ETH_ALEN);
4684                 buf.reason_code = cpu_to_le16(mlme->reason_code);
4685                 ret = HERMES_WRITE_RECORD(hw, USER_BAP,
4686                                           HERMES_RID_CNFDISASSOCIATE,
4687                                           &buf);
4688                 break;
4689         }
4690         default:
4691                 ret = -EOPNOTSUPP;
4692         }
4693
4694         orinoco_unlock(priv, &flags);
4695         return ret;
4696 }
4697
4698 static int orinoco_ioctl_getretry(struct net_device *dev,
4699                                   struct iw_request_info *info,
4700                                   struct iw_param *rrq,
4701                                   char *extra)
4702 {
4703         struct orinoco_private *priv = netdev_priv(dev);
4704         hermes_t *hw = &priv->hw;
4705         int err = 0;
4706         u16 short_limit, long_limit, lifetime;
4707         unsigned long flags;
4708
4709         if (orinoco_lock(priv, &flags) != 0)
4710                 return -EBUSY;
4711         
4712         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_SHORTRETRYLIMIT,
4713                                   &short_limit);
4714         if (err)
4715                 goto out;
4716
4717         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_LONGRETRYLIMIT,
4718                                   &long_limit);
4719         if (err)
4720                 goto out;
4721
4722         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_MAXTRANSMITLIFETIME,
4723                                   &lifetime);
4724         if (err)
4725                 goto out;
4726
4727         rrq->disabled = 0;              /* Can't be disabled */
4728
4729         /* Note : by default, display the retry number */
4730         if ((rrq->flags & IW_RETRY_TYPE) == IW_RETRY_LIFETIME) {
4731                 rrq->flags = IW_RETRY_LIFETIME;
4732                 rrq->value = lifetime * 1000;   /* ??? */
4733         } else {
4734                 /* By default, display the min number */
4735                 if ((rrq->flags & IW_RETRY_LONG)) {
4736                         rrq->flags = IW_RETRY_LIMIT | IW_RETRY_LONG;
4737                         rrq->value = long_limit;
4738                 } else {
4739                         rrq->flags = IW_RETRY_LIMIT;
4740                         rrq->value = short_limit;
4741                         if(short_limit != long_limit)
4742                                 rrq->flags |= IW_RETRY_SHORT;
4743                 }
4744         }
4745
4746  out:
4747         orinoco_unlock(priv, &flags);
4748
4749         return err;
4750 }
4751
4752 static int orinoco_ioctl_reset(struct net_device *dev,
4753                                struct iw_request_info *info,
4754                                void *wrqu,
4755                                char *extra)
4756 {
4757         struct orinoco_private *priv = netdev_priv(dev);
4758
4759         if (! capable(CAP_NET_ADMIN))
4760                 return -EPERM;
4761
4762         if (info->cmd == (SIOCIWFIRSTPRIV + 0x1)) {
4763                 printk(KERN_DEBUG "%s: Forcing reset!\n", dev->name);
4764
4765                 /* Firmware reset */
4766                 orinoco_reset(&priv->reset_work);
4767         } else {
4768                 printk(KERN_DEBUG "%s: Force scheduling reset!\n", dev->name);
4769
4770                 schedule_work(&priv->reset_work);
4771         }
4772
4773         return 0;
4774 }
4775
4776 static int orinoco_ioctl_setibssport(struct net_device *dev,
4777                                      struct iw_request_info *info,
4778                                      void *wrqu,
4779                                      char *extra)
4780
4781 {
4782         struct orinoco_private *priv = netdev_priv(dev);
4783         int val = *( (int *) extra );
4784         unsigned long flags;
4785
4786         if (orinoco_lock(priv, &flags) != 0)
4787                 return -EBUSY;
4788
4789         priv->ibss_port = val ;
4790
4791         /* Actually update the mode we are using */
4792         set_port_type(priv);
4793
4794         orinoco_unlock(priv, &flags);
4795         return -EINPROGRESS;            /* Call commit handler */
4796 }
4797
4798 static int orinoco_ioctl_getibssport(struct net_device *dev,
4799                                      struct iw_request_info *info,
4800                                      void *wrqu,
4801                                      char *extra)
4802 {
4803         struct orinoco_private *priv = netdev_priv(dev);
4804         int *val = (int *) extra;
4805
4806         *val = priv->ibss_port;
4807         return 0;
4808 }
4809
4810 static int orinoco_ioctl_setport3(struct net_device *dev,
4811                                   struct iw_request_info *info,
4812                                   void *wrqu,
4813                                   char *extra)
4814 {
4815         struct orinoco_private *priv = netdev_priv(dev);
4816         int val = *( (int *) extra );
4817         int err = 0;
4818         unsigned long flags;
4819
4820         if (orinoco_lock(priv, &flags) != 0)
4821                 return -EBUSY;
4822
4823         switch (val) {
4824         case 0: /* Try to do IEEE ad-hoc mode */
4825                 if (! priv->has_ibss) {
4826                         err = -EINVAL;
4827                         break;
4828                 }
4829                 priv->prefer_port3 = 0;
4830                         
4831                 break;
4832
4833         case 1: /* Try to do Lucent proprietary ad-hoc mode */
4834                 if (! priv->has_port3) {
4835                         err = -EINVAL;
4836                         break;
4837                 }
4838                 priv->prefer_port3 = 1;
4839                 break;
4840
4841         default:
4842                 err = -EINVAL;
4843         }
4844
4845         if (! err) {
4846                 /* Actually update the mode we are using */
4847                 set_port_type(priv);
4848                 err = -EINPROGRESS;
4849         }
4850
4851         orinoco_unlock(priv, &flags);
4852
4853         return err;
4854 }
4855
4856 static int orinoco_ioctl_getport3(struct net_device *dev,
4857                                   struct iw_request_info *info,
4858                                   void *wrqu,
4859                                   char *extra)
4860 {
4861         struct orinoco_private *priv = netdev_priv(dev);
4862         int *val = (int *) extra;
4863
4864         *val = priv->prefer_port3;
4865         return 0;
4866 }
4867
4868 static int orinoco_ioctl_setpreamble(struct net_device *dev,
4869                                      struct iw_request_info *info,
4870                                      void *wrqu,
4871                                      char *extra)
4872 {
4873         struct orinoco_private *priv = netdev_priv(dev);
4874         unsigned long flags;
4875         int val;
4876
4877         if (! priv->has_preamble)
4878                 return -EOPNOTSUPP;
4879
4880         /* 802.11b has recently defined some short preamble.
4881          * Basically, the Phy header has been reduced in size.
4882          * This increase performance, especially at high rates
4883          * (the preamble is transmitted at 1Mb/s), unfortunately
4884          * this give compatibility troubles... - Jean II */
4885         val = *( (int *) extra );
4886
4887         if (orinoco_lock(priv, &flags) != 0)
4888                 return -EBUSY;
4889
4890         if (val)
4891                 priv->preamble = 1;
4892         else
4893                 priv->preamble = 0;
4894
4895         orinoco_unlock(priv, &flags);
4896
4897         return -EINPROGRESS;            /* Call commit handler */
4898 }
4899
4900 static int orinoco_ioctl_getpreamble(struct net_device *dev,
4901                                      struct iw_request_info *info,
4902                                      void *wrqu,
4903                                      char *extra)
4904 {
4905         struct orinoco_private *priv = netdev_priv(dev);
4906         int *val = (int *) extra;
4907
4908         if (! priv->has_preamble)
4909                 return -EOPNOTSUPP;
4910
4911         *val = priv->preamble;
4912         return 0;
4913 }
4914
4915 /* ioctl interface to hermes_read_ltv()
4916  * To use with iwpriv, pass the RID as the token argument, e.g.
4917  * iwpriv get_rid [0xfc00]
4918  * At least Wireless Tools 25 is required to use iwpriv.
4919  * For Wireless Tools 25 and 26 append "dummy" are the end. */
4920 static int orinoco_ioctl_getrid(struct net_device *dev,
4921                                 struct iw_request_info *info,
4922                                 struct iw_point *data,
4923                                 char *extra)
4924 {
4925         struct orinoco_private *priv = netdev_priv(dev);
4926         hermes_t *hw = &priv->hw;
4927         int rid = data->flags;
4928         u16 length;
4929         int err;
4930         unsigned long flags;
4931
4932         /* It's a "get" function, but we don't want users to access the
4933          * WEP key and other raw firmware data */
4934         if (! capable(CAP_NET_ADMIN))
4935                 return -EPERM;
4936
4937         if (rid < 0xfc00 || rid > 0xffff)
4938                 return -EINVAL;
4939
4940         if (orinoco_lock(priv, &flags) != 0)
4941                 return -EBUSY;
4942
4943         err = hermes_read_ltv(hw, USER_BAP, rid, MAX_RID_LEN, &length,
4944                               extra);
4945         if (err)
4946                 goto out;
4947
4948         data->length = min_t(u16, HERMES_RECLEN_TO_BYTES(length),
4949                              MAX_RID_LEN);
4950
4951  out:
4952         orinoco_unlock(priv, &flags);
4953         return err;
4954 }
4955
4956 /* Trigger a scan (look for other cells in the vicinity) */
4957 static int orinoco_ioctl_setscan(struct net_device *dev,
4958                                  struct iw_request_info *info,
4959                                  struct iw_param *srq,
4960                                  char *extra)
4961 {
4962         struct orinoco_private *priv = netdev_priv(dev);
4963         hermes_t *hw = &priv->hw;
4964         struct iw_scan_req *si = (struct iw_scan_req *) extra;
4965         int err = 0;
4966         unsigned long flags;
4967
4968         /* Note : you may have realised that, as this is a SET operation,
4969          * this is privileged and therefore a normal user can't
4970          * perform scanning.
4971          * This is not an error, while the device perform scanning,
4972          * traffic doesn't flow, so it's a perfect DoS...
4973          * Jean II */
4974
4975         if (orinoco_lock(priv, &flags) != 0)
4976                 return -EBUSY;
4977
4978         /* Scanning with port 0 disabled would fail */
4979         if (!netif_running(dev)) {
4980                 err = -ENETDOWN;
4981                 goto out;
4982         }
4983
4984         /* In monitor mode, the scan results are always empty.
4985          * Probe responses are passed to the driver as received
4986          * frames and could be processed in software. */
4987         if (priv->iw_mode == IW_MODE_MONITOR) {
4988                 err = -EOPNOTSUPP;
4989                 goto out;
4990         }
4991
4992         /* Note : because we don't lock out the irq handler, the way
4993          * we access scan variables in priv is critical.
4994          *      o scan_inprogress : not touched by irq handler
4995          *      o scan_mode : not touched by irq handler
4996          * Before modifying anything on those variables, please think hard !
4997          * Jean II */
4998
4999         /* Save flags */
5000         priv->scan_mode = srq->flags;
5001
5002         /* Always trigger scanning, even if it's in progress.
5003          * This way, if the info frame get lost, we will recover somewhat
5004          * gracefully  - Jean II */
5005
5006         if (priv->has_hostscan) {
5007                 switch (priv->firmware_type) {
5008                 case FIRMWARE_TYPE_SYMBOL:
5009                         err = hermes_write_wordrec(hw, USER_BAP,
5010                                                    HERMES_RID_CNFHOSTSCAN_SYMBOL,
5011                                                    HERMES_HOSTSCAN_SYMBOL_ONCE |
5012                                                    HERMES_HOSTSCAN_SYMBOL_BCAST);
5013                         break;
5014                 case FIRMWARE_TYPE_INTERSIL: {
5015                         __le16 req[3];
5016
5017                         req[0] = cpu_to_le16(0x3fff);   /* All channels */
5018                         req[1] = cpu_to_le16(0x0001);   /* rate 1 Mbps */
5019                         req[2] = 0;                     /* Any ESSID */
5020                         err = HERMES_WRITE_RECORD(hw, USER_BAP,
5021                                                   HERMES_RID_CNFHOSTSCAN, &req);
5022                 }
5023                 break;
5024                 case FIRMWARE_TYPE_AGERE:
5025                         if (priv->scan_mode & IW_SCAN_THIS_ESSID) {
5026                                 struct hermes_idstring idbuf;
5027                                 size_t len = min(sizeof(idbuf.val),
5028                                                  (size_t) si->essid_len);
5029                                 idbuf.len = cpu_to_le16(len);
5030                                 memcpy(idbuf.val, si->essid, len);
5031
5032                                 err = hermes_write_ltv(hw, USER_BAP,
5033                                                HERMES_RID_CNFSCANSSID_AGERE,
5034                                                HERMES_BYTES_TO_RECLEN(len + 2),
5035                                                &idbuf);
5036                         } else
5037                                 err = hermes_write_wordrec(hw, USER_BAP,
5038                                                    HERMES_RID_CNFSCANSSID_AGERE,
5039                                                    0);  /* Any ESSID */
5040                         if (err)
5041                                 break;
5042
5043                         if (priv->has_ext_scan) {
5044                                 /* Clear scan results at the start of
5045                                  * an extended scan */
5046                                 orinoco_clear_scan_results(priv,
5047                                                 msecs_to_jiffies(15000));
5048
5049                                 /* TODO: Is this available on older firmware?
5050                                  *   Can we use it to scan specific channels
5051                                  *   for IW_SCAN_THIS_FREQ? */
5052                                 err = hermes_write_wordrec(hw, USER_BAP,
5053                                                 HERMES_RID_CNFSCANCHANNELS2GHZ,
5054                                                 0x7FFF);
5055                                 if (err)
5056                                         goto out;
5057
5058                                 err = hermes_inquire(hw,
5059                                                      HERMES_INQ_CHANNELINFO);
5060                         } else
5061                                 err = hermes_inquire(hw, HERMES_INQ_SCAN);
5062                         break;
5063                 }
5064         } else
5065                 err = hermes_inquire(hw, HERMES_INQ_SCAN);
5066
5067         /* One more client */
5068         if (! err)
5069                 priv->scan_inprogress = 1;
5070
5071  out:
5072         orinoco_unlock(priv, &flags);
5073         return err;
5074 }
5075
5076 #define MAX_CUSTOM_LEN 64
5077
5078 /* Translate scan data returned from the card to a card independant
5079  * format that the Wireless Tools will understand - Jean II */
5080 static inline char *orinoco_translate_scan(struct net_device *dev,
5081                                            struct iw_request_info *info,
5082                                            char *current_ev,
5083                                            char *end_buf,
5084                                            union hermes_scan_info *bss,
5085                                            unsigned int last_scanned)
5086 {
5087         struct orinoco_private *priv = netdev_priv(dev);
5088         u16                     capabilities;
5089         u16                     channel;
5090         struct iw_event         iwe;            /* Temporary buffer */
5091         char custom[MAX_CUSTOM_LEN];
5092
5093         memset(&iwe, 0, sizeof(iwe));
5094
5095         /* First entry *MUST* be the AP MAC address */
5096         iwe.cmd = SIOCGIWAP;
5097         iwe.u.ap_addr.sa_family = ARPHRD_ETHER;
5098         memcpy(iwe.u.ap_addr.sa_data, bss->a.bssid, ETH_ALEN);
5099         current_ev = iwe_stream_add_event(info, current_ev, end_buf,
5100                                           &iwe, IW_EV_ADDR_LEN);
5101
5102         /* Other entries will be displayed in the order we give them */
5103
5104         /* Add the ESSID */
5105         iwe.u.data.length = le16_to_cpu(bss->a.essid_len);
5106         if (iwe.u.data.length > 32)
5107                 iwe.u.data.length = 32;
5108         iwe.cmd = SIOCGIWESSID;
5109         iwe.u.data.flags = 1;
5110         current_ev = iwe_stream_add_point(info, current_ev, end_buf,
5111                                           &iwe, bss->a.essid);
5112
5113         /* Add mode */
5114         iwe.cmd = SIOCGIWMODE;
5115         capabilities = le16_to_cpu(bss->a.capabilities);
5116         if (capabilities & (WLAN_CAPABILITY_ESS | WLAN_CAPABILITY_IBSS)) {
5117                 if (capabilities & WLAN_CAPABILITY_ESS)
5118                         iwe.u.mode = IW_MODE_MASTER;
5119                 else
5120                         iwe.u.mode = IW_MODE_ADHOC;
5121                 current_ev = iwe_stream_add_event(info, current_ev, end_buf,
5122                                                   &iwe, IW_EV_UINT_LEN);
5123         }
5124
5125         channel = bss->s.channel;
5126         if ((channel >= 1) && (channel <= NUM_CHANNELS)) {
5127                 /* Add channel and frequency */
5128                 iwe.cmd = SIOCGIWFREQ;
5129                 iwe.u.freq.m = channel;
5130                 iwe.u.freq.e = 0;
5131                 current_ev = iwe_stream_add_event(info, current_ev, end_buf,
5132                                                   &iwe, IW_EV_FREQ_LEN);
5133
5134                 iwe.u.freq.m = channel_frequency[channel-1] * 100000;
5135                 iwe.u.freq.e = 1;
5136                 current_ev = iwe_stream_add_event(info, current_ev, end_buf,
5137                                                   &iwe, IW_EV_FREQ_LEN);
5138         }
5139
5140         /* Add quality statistics. level and noise in dB. No link quality */
5141         iwe.cmd = IWEVQUAL;
5142         iwe.u.qual.updated = IW_QUAL_DBM | IW_QUAL_QUAL_INVALID;
5143         iwe.u.qual.level = (__u8) le16_to_cpu(bss->a.level) - 0x95;
5144         iwe.u.qual.noise = (__u8) le16_to_cpu(bss->a.noise) - 0x95;
5145         /* Wireless tools prior to 27.pre22 will show link quality
5146          * anyway, so we provide a reasonable value. */
5147         if (iwe.u.qual.level > iwe.u.qual.noise)
5148                 iwe.u.qual.qual = iwe.u.qual.level - iwe.u.qual.noise;
5149         else
5150                 iwe.u.qual.qual = 0;
5151         current_ev = iwe_stream_add_event(info, current_ev, end_buf,
5152                                           &iwe, IW_EV_QUAL_LEN);
5153
5154         /* Add encryption capability */
5155         iwe.cmd = SIOCGIWENCODE;
5156         if (capabilities & WLAN_CAPABILITY_PRIVACY)
5157                 iwe.u.data.flags = IW_ENCODE_ENABLED | IW_ENCODE_NOKEY;
5158         else
5159                 iwe.u.data.flags = IW_ENCODE_DISABLED;
5160         iwe.u.data.length = 0;
5161         current_ev = iwe_stream_add_point(info, current_ev, end_buf,
5162                                           &iwe, NULL);
5163
5164         /* Bit rate is not available in Lucent/Agere firmwares */
5165         if (priv->firmware_type != FIRMWARE_TYPE_AGERE) {
5166                 char *current_val = current_ev + iwe_stream_lcp_len(info);
5167                 int i;
5168                 int step;
5169
5170                 if (priv->firmware_type == FIRMWARE_TYPE_SYMBOL)
5171                         step = 2;
5172                 else
5173                         step = 1;
5174
5175                 iwe.cmd = SIOCGIWRATE;
5176                 /* Those two flags are ignored... */
5177                 iwe.u.bitrate.fixed = iwe.u.bitrate.disabled = 0;
5178                 /* Max 10 values */
5179                 for (i = 0; i < 10; i += step) {
5180                         /* NULL terminated */
5181                         if (bss->p.rates[i] == 0x0)
5182                                 break;
5183                         /* Bit rate given in 500 kb/s units (+ 0x80) */
5184                         iwe.u.bitrate.value =
5185                                 ((bss->p.rates[i] & 0x7f) * 500000);
5186                         current_val = iwe_stream_add_value(info, current_ev,
5187                                                            current_val,
5188                                                            end_buf, &iwe,
5189                                                            IW_EV_PARAM_LEN);
5190                 }
5191                 /* Check if we added any event */
5192                 if ((current_val - current_ev) > iwe_stream_lcp_len(info))
5193                         current_ev = current_val;
5194         }
5195
5196         /* Beacon interval */
5197         iwe.cmd = IWEVCUSTOM;
5198         iwe.u.data.length = snprintf(custom, MAX_CUSTOM_LEN,
5199                                      "bcn_int=%d",
5200                                      le16_to_cpu(bss->a.beacon_interv));
5201         if (iwe.u.data.length)
5202                 current_ev = iwe_stream_add_point(info, current_ev, end_buf,
5203                                                   &iwe, custom);
5204
5205         /* Capabilites */
5206         iwe.cmd = IWEVCUSTOM;
5207         iwe.u.data.length = snprintf(custom, MAX_CUSTOM_LEN,
5208                                      "capab=0x%04x",
5209                                      capabilities);
5210         if (iwe.u.data.length)
5211                 current_ev = iwe_stream_add_point(info, current_ev, end_buf,
5212                                                   &iwe, custom);
5213
5214         /* Add EXTRA: Age to display seconds since last beacon/probe response
5215          * for given network. */
5216         iwe.cmd = IWEVCUSTOM;
5217         iwe.u.data.length = snprintf(custom, MAX_CUSTOM_LEN,
5218                                      " Last beacon: %dms ago",
5219                                      jiffies_to_msecs(jiffies - last_scanned));
5220         if (iwe.u.data.length)
5221                 current_ev = iwe_stream_add_point(info, current_ev, end_buf,
5222                                                   &iwe, custom);
5223
5224         return current_ev;
5225 }
5226
5227 static inline char *orinoco_translate_ext_scan(struct net_device *dev,
5228                                                struct iw_request_info *info,
5229                                                char *current_ev,
5230                                                char *end_buf,
5231                                                struct agere_ext_scan_info *bss,
5232                                                unsigned int last_scanned)
5233 {
5234         u16                     capabilities;
5235         u16                     channel;
5236         struct iw_event         iwe;            /* Temporary buffer */
5237         char custom[MAX_CUSTOM_LEN];
5238         u8 *ie;
5239
5240         memset(&iwe, 0, sizeof(iwe));
5241
5242         /* First entry *MUST* be the AP MAC address */
5243         iwe.cmd = SIOCGIWAP;
5244         iwe.u.ap_addr.sa_family = ARPHRD_ETHER;
5245         memcpy(iwe.u.ap_addr.sa_data, bss->bssid, ETH_ALEN);
5246         current_ev = iwe_stream_add_event(info, current_ev, end_buf,
5247                                           &iwe, IW_EV_ADDR_LEN);
5248
5249         /* Other entries will be displayed in the order we give them */
5250
5251         /* Add the ESSID */
5252         ie = bss->data;
5253         iwe.u.data.length = ie[1];
5254         if (iwe.u.data.length) {
5255                 if (iwe.u.data.length > 32)
5256                         iwe.u.data.length = 32;
5257                 iwe.cmd = SIOCGIWESSID;
5258                 iwe.u.data.flags = 1;
5259                 current_ev = iwe_stream_add_point(info, current_ev, end_buf,
5260                                                   &iwe, &ie[2]);
5261         }
5262
5263         /* Add mode */
5264         capabilities = le16_to_cpu(bss->capabilities);
5265         if (capabilities & (WLAN_CAPABILITY_ESS | WLAN_CAPABILITY_IBSS)) {
5266                 iwe.cmd = SIOCGIWMODE;
5267                 if (capabilities & WLAN_CAPABILITY_ESS)
5268                         iwe.u.mode = IW_MODE_MASTER;
5269                 else
5270                         iwe.u.mode = IW_MODE_ADHOC;
5271                 current_ev = iwe_stream_add_event(info, current_ev, end_buf,
5272                                                   &iwe, IW_EV_UINT_LEN);
5273         }
5274
5275         ie = orinoco_get_ie(bss->data, sizeof(bss->data), MFIE_TYPE_DS_SET);
5276         channel = ie ? ie[2] : 0;
5277         if ((channel >= 1) && (channel <= NUM_CHANNELS)) {
5278                 /* Add channel and frequency */
5279                 iwe.cmd = SIOCGIWFREQ;
5280                 iwe.u.freq.m = channel;
5281                 iwe.u.freq.e = 0;
5282                 current_ev = iwe_stream_add_event(info, current_ev, end_buf,
5283                                                   &iwe, IW_EV_FREQ_LEN);
5284
5285                 iwe.u.freq.m = channel_frequency[channel-1] * 100000;
5286                 iwe.u.freq.e = 1;
5287                 current_ev = iwe_stream_add_event(info, current_ev, end_buf,
5288                                                   &iwe, IW_EV_FREQ_LEN);
5289         }
5290
5291         /* Add quality statistics. level and noise in dB. No link quality */
5292         iwe.cmd = IWEVQUAL;
5293         iwe.u.qual.updated = IW_QUAL_DBM | IW_QUAL_QUAL_INVALID;
5294         iwe.u.qual.level = bss->level - 0x95;
5295         iwe.u.qual.noise = bss->noise - 0x95;
5296         /* Wireless tools prior to 27.pre22 will show link quality
5297          * anyway, so we provide a reasonable value. */
5298         if (iwe.u.qual.level > iwe.u.qual.noise)
5299                 iwe.u.qual.qual = iwe.u.qual.level - iwe.u.qual.noise;
5300         else
5301                 iwe.u.qual.qual = 0;
5302         current_ev = iwe_stream_add_event(info, current_ev, end_buf,
5303                                           &iwe, IW_EV_QUAL_LEN);
5304
5305         /* Add encryption capability */
5306         iwe.cmd = SIOCGIWENCODE;
5307         if (capabilities & WLAN_CAPABILITY_PRIVACY)
5308                 iwe.u.data.flags = IW_ENCODE_ENABLED | IW_ENCODE_NOKEY;
5309         else
5310                 iwe.u.data.flags = IW_ENCODE_DISABLED;
5311         iwe.u.data.length = 0;
5312         current_ev = iwe_stream_add_point(info, current_ev, end_buf,
5313                                           &iwe, NULL);
5314
5315         /* WPA IE */
5316         ie = orinoco_get_wpa_ie(bss->data, sizeof(bss->data));
5317         if (ie) {
5318                 iwe.cmd = IWEVGENIE;
5319                 iwe.u.data.length = ie[1] + 2;
5320                 current_ev = iwe_stream_add_point(info, current_ev, end_buf,
5321                                                   &iwe, ie);
5322         }
5323
5324         /* RSN IE */
5325         ie = orinoco_get_ie(bss->data, sizeof(bss->data), MFIE_TYPE_RSN);
5326         if (ie) {
5327                 iwe.cmd = IWEVGENIE;
5328                 iwe.u.data.length = ie[1] + 2;
5329                 current_ev = iwe_stream_add_point(info, current_ev, end_buf,
5330                                                   &iwe, ie);
5331         }
5332
5333         ie = orinoco_get_ie(bss->data, sizeof(bss->data), MFIE_TYPE_RATES);
5334         if (ie) {
5335                 char *p = current_ev + iwe_stream_lcp_len(info);
5336                 int i;
5337
5338                 iwe.cmd = SIOCGIWRATE;
5339                 /* Those two flags are ignored... */
5340                 iwe.u.bitrate.fixed = iwe.u.bitrate.disabled = 0;
5341
5342                 for (i = 2; i < (ie[1] + 2); i++) {
5343                         iwe.u.bitrate.value = ((ie[i] & 0x7F) * 500000);
5344                         p = iwe_stream_add_value(info, current_ev, p, end_buf,
5345                                                  &iwe, IW_EV_PARAM_LEN);
5346                 }
5347                 /* Check if we added any event */
5348                 if (p > (current_ev + iwe_stream_lcp_len(info)))
5349                         current_ev = p;
5350         }
5351
5352         /* Timestamp */
5353         iwe.cmd = IWEVCUSTOM;
5354         iwe.u.data.length = snprintf(custom, MAX_CUSTOM_LEN,
5355                                      "tsf=%016llx",
5356                                      le64_to_cpu(bss->timestamp));
5357         if (iwe.u.data.length)
5358                 current_ev = iwe_stream_add_point(info, current_ev, end_buf,
5359                                                   &iwe, custom);
5360
5361         /* Beacon interval */
5362         iwe.cmd = IWEVCUSTOM;
5363         iwe.u.data.length = snprintf(custom, MAX_CUSTOM_LEN,
5364                                      "bcn_int=%d",
5365                                      le16_to_cpu(bss->beacon_interval));
5366         if (iwe.u.data.length)
5367                 current_ev = iwe_stream_add_point(info, current_ev, end_buf,
5368                                                   &iwe, custom);
5369
5370         /* Capabilites */
5371         iwe.cmd = IWEVCUSTOM;
5372         iwe.u.data.length = snprintf(custom, MAX_CUSTOM_LEN,
5373                                      "capab=0x%04x",
5374                                      capabilities);
5375         if (iwe.u.data.length)
5376                 current_ev = iwe_stream_add_point(info, current_ev, end_buf,
5377                                                   &iwe, custom);
5378
5379         /* Add EXTRA: Age to display seconds since last beacon/probe response
5380          * for given network. */
5381         iwe.cmd = IWEVCUSTOM;
5382         iwe.u.data.length = snprintf(custom, MAX_CUSTOM_LEN,
5383                                      " Last beacon: %dms ago",
5384                                      jiffies_to_msecs(jiffies - last_scanned));
5385         if (iwe.u.data.length)
5386                 current_ev = iwe_stream_add_point(info, current_ev, end_buf,
5387                                                   &iwe, custom);
5388
5389         return current_ev;
5390 }
5391
5392 /* Return results of a scan */
5393 static int orinoco_ioctl_getscan(struct net_device *dev,
5394                                  struct iw_request_info *info,
5395                                  struct iw_point *srq,
5396                                  char *extra)
5397 {
5398         struct orinoco_private *priv = netdev_priv(dev);
5399         int err = 0;
5400         unsigned long flags;
5401         char *current_ev = extra;
5402
5403         if (orinoco_lock(priv, &flags) != 0)
5404                 return -EBUSY;
5405
5406         if (priv->scan_inprogress) {
5407                 /* Important note : we don't want to block the caller
5408                  * until results are ready for various reasons.
5409                  * First, managing wait queues is complex and racy.
5410                  * Second, we grab some rtnetlink lock before comming
5411                  * here (in dev_ioctl()).
5412                  * Third, we generate an Wireless Event, so the
5413                  * caller can wait itself on that - Jean II */
5414                 err = -EAGAIN;
5415                 goto out;
5416         }
5417
5418         if (priv->has_ext_scan) {
5419                 struct xbss_element *bss;
5420
5421                 list_for_each_entry(bss, &priv->bss_list, list) {
5422                         /* Translate this entry to WE format */
5423                         current_ev =
5424                                 orinoco_translate_ext_scan(dev, info,
5425                                                            current_ev,
5426                                                            extra + srq->length,
5427                                                            &bss->bss,
5428                                                            bss->last_scanned);
5429
5430                         /* Check if there is space for one more entry */
5431                         if ((extra + srq->length - current_ev)
5432                             <= IW_EV_ADDR_LEN) {
5433                                 /* Ask user space to try again with a
5434                                  * bigger buffer */
5435                                 err = -E2BIG;
5436                                 goto out;
5437                         }
5438                 }
5439
5440         } else {
5441                 struct bss_element *bss;
5442
5443                 list_for_each_entry(bss, &priv->bss_list, list) {
5444                         /* Translate this entry to WE format */
5445                         current_ev = orinoco_translate_scan(dev, info,
5446                                                             current_ev,
5447                                                             extra + srq->length,
5448                                                             &bss->bss,
5449                                                             bss->last_scanned);
5450
5451                         /* Check if there is space for one more entry */
5452                         if ((extra + srq->length - current_ev)
5453                             <= IW_EV_ADDR_LEN) {
5454                                 /* Ask user space to try again with a
5455                                  * bigger buffer */
5456                                 err = -E2BIG;
5457                                 goto out;
5458                         }
5459                 }
5460         }
5461
5462         srq->length = (current_ev - extra);
5463         srq->flags = (__u16) priv->scan_mode;
5464
5465 out:
5466         orinoco_unlock(priv, &flags);
5467         return err;
5468 }
5469
5470 /* Commit handler, called after set operations */
5471 static int orinoco_ioctl_commit(struct net_device *dev,
5472                                 struct iw_request_info *info,
5473                                 void *wrqu,
5474                                 char *extra)
5475 {
5476         struct orinoco_private *priv = netdev_priv(dev);
5477         struct hermes *hw = &priv->hw;
5478         unsigned long flags;
5479         int err = 0;
5480
5481         if (!priv->open)
5482                 return 0;
5483
5484         if (priv->broken_disableport) {
5485                 orinoco_reset(&priv->reset_work);
5486                 return 0;
5487         }
5488
5489         if (orinoco_lock(priv, &flags) != 0)
5490                 return err;
5491
5492         err = hermes_disable_port(hw, 0);
5493         if (err) {
5494                 printk(KERN_WARNING "%s: Unable to disable port "
5495                        "while reconfiguring card\n", dev->name);
5496                 priv->broken_disableport = 1;
5497                 goto out;
5498         }
5499
5500         err = __orinoco_program_rids(dev);
5501         if (err) {
5502                 printk(KERN_WARNING "%s: Unable to reconfigure card\n",
5503                        dev->name);
5504                 goto out;
5505         }
5506
5507         err = hermes_enable_port(hw, 0);
5508         if (err) {
5509                 printk(KERN_WARNING "%s: Unable to enable port while reconfiguring card\n",
5510                        dev->name);
5511                 goto out;
5512         }
5513
5514  out:
5515         if (err) {
5516                 printk(KERN_WARNING "%s: Resetting instead...\n", dev->name);
5517                 schedule_work(&priv->reset_work);
5518                 err = 0;
5519         }
5520
5521         orinoco_unlock(priv, &flags);
5522         return err;
5523 }
5524
5525 static const struct iw_priv_args orinoco_privtab[] = {
5526         { SIOCIWFIRSTPRIV + 0x0, 0, 0, "force_reset" },
5527         { SIOCIWFIRSTPRIV + 0x1, 0, 0, "card_reset" },
5528         { SIOCIWFIRSTPRIV + 0x2, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,
5529           0, "set_port3" },
5530         { SIOCIWFIRSTPRIV + 0x3, 0, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,
5531           "get_port3" },
5532         { SIOCIWFIRSTPRIV + 0x4, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,
5533           0, "set_preamble" },
5534         { SIOCIWFIRSTPRIV + 0x5, 0, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,
5535           "get_preamble" },
5536         { SIOCIWFIRSTPRIV + 0x6, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,
5537           0, "set_ibssport" },
5538         { SIOCIWFIRSTPRIV + 0x7, 0, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,
5539           "get_ibssport" },
5540         { SIOCIWFIRSTPRIV + 0x9, 0, IW_PRIV_TYPE_BYTE | MAX_RID_LEN,
5541           "get_rid" },
5542 };
5543
5544
5545 /*
5546  * Structures to export the Wireless Handlers
5547  */
5548
5549 #define STD_IW_HANDLER(id, func) \
5550         [IW_IOCTL_IDX(id)] = (iw_handler) func
5551 static const iw_handler orinoco_handler[] = {
5552         STD_IW_HANDLER(SIOCSIWCOMMIT,   orinoco_ioctl_commit),
5553         STD_IW_HANDLER(SIOCGIWNAME,     orinoco_ioctl_getname),
5554         STD_IW_HANDLER(SIOCSIWFREQ,     orinoco_ioctl_setfreq),
5555         STD_IW_HANDLER(SIOCGIWFREQ,     orinoco_ioctl_getfreq),
5556         STD_IW_HANDLER(SIOCSIWMODE,     orinoco_ioctl_setmode),
5557         STD_IW_HANDLER(SIOCGIWMODE,     orinoco_ioctl_getmode),
5558         STD_IW_HANDLER(SIOCSIWSENS,     orinoco_ioctl_setsens),
5559         STD_IW_HANDLER(SIOCGIWSENS,     orinoco_ioctl_getsens),
5560         STD_IW_HANDLER(SIOCGIWRANGE,    orinoco_ioctl_getiwrange),
5561         STD_IW_HANDLER(SIOCSIWSPY,      iw_handler_set_spy),
5562         STD_IW_HANDLER(SIOCGIWSPY,      iw_handler_get_spy),
5563         STD_IW_HANDLER(SIOCSIWTHRSPY,   iw_handler_set_thrspy),
5564         STD_IW_HANDLER(SIOCGIWTHRSPY,   iw_handler_get_thrspy),
5565         STD_IW_HANDLER(SIOCSIWAP,       orinoco_ioctl_setwap),
5566         STD_IW_HANDLER(SIOCGIWAP,       orinoco_ioctl_getwap),
5567         STD_IW_HANDLER(SIOCSIWSCAN,     orinoco_ioctl_setscan),
5568         STD_IW_HANDLER(SIOCGIWSCAN,     orinoco_ioctl_getscan),
5569         STD_IW_HANDLER(SIOCSIWESSID,    orinoco_ioctl_setessid),
5570         STD_IW_HANDLER(SIOCGIWESSID,    orinoco_ioctl_getessid),
5571         STD_IW_HANDLER(SIOCSIWNICKN,    orinoco_ioctl_setnick),
5572         STD_IW_HANDLER(SIOCGIWNICKN,    orinoco_ioctl_getnick),
5573         STD_IW_HANDLER(SIOCSIWRATE,     orinoco_ioctl_setrate),
5574         STD_IW_HANDLER(SIOCGIWRATE,     orinoco_ioctl_getrate),
5575         STD_IW_HANDLER(SIOCSIWRTS,      orinoco_ioctl_setrts),
5576         STD_IW_HANDLER(SIOCGIWRTS,      orinoco_ioctl_getrts),
5577         STD_IW_HANDLER(SIOCSIWFRAG,     orinoco_ioctl_setfrag),
5578         STD_IW_HANDLER(SIOCGIWFRAG,     orinoco_ioctl_getfrag),
5579         STD_IW_HANDLER(SIOCGIWRETRY,    orinoco_ioctl_getretry),
5580         STD_IW_HANDLER(SIOCSIWENCODE,   orinoco_ioctl_setiwencode),
5581         STD_IW_HANDLER(SIOCGIWENCODE,   orinoco_ioctl_getiwencode),
5582         STD_IW_HANDLER(SIOCSIWPOWER,    orinoco_ioctl_setpower),
5583         STD_IW_HANDLER(SIOCGIWPOWER,    orinoco_ioctl_getpower),
5584         STD_IW_HANDLER(SIOCSIWGENIE,    orinoco_ioctl_set_genie),
5585         STD_IW_HANDLER(SIOCGIWGENIE,    orinoco_ioctl_get_genie),
5586         STD_IW_HANDLER(SIOCSIWMLME,     orinoco_ioctl_set_mlme),
5587         STD_IW_HANDLER(SIOCSIWAUTH,     orinoco_ioctl_set_auth),
5588         STD_IW_HANDLER(SIOCGIWAUTH,     orinoco_ioctl_get_auth),
5589         STD_IW_HANDLER(SIOCSIWENCODEEXT, orinoco_ioctl_set_encodeext),
5590         STD_IW_HANDLER(SIOCGIWENCODEEXT, orinoco_ioctl_get_encodeext),
5591 };
5592
5593
5594 /*
5595   Added typecasting since we no longer use iwreq_data -- Moustafa
5596  */
5597 static const iw_handler orinoco_private_handler[] = {
5598         [0] = (iw_handler) orinoco_ioctl_reset,
5599         [1] = (iw_handler) orinoco_ioctl_reset,
5600         [2] = (iw_handler) orinoco_ioctl_setport3,
5601         [3] = (iw_handler) orinoco_ioctl_getport3,
5602         [4] = (iw_handler) orinoco_ioctl_setpreamble,
5603         [5] = (iw_handler) orinoco_ioctl_getpreamble,
5604         [6] = (iw_handler) orinoco_ioctl_setibssport,
5605         [7] = (iw_handler) orinoco_ioctl_getibssport,
5606         [9] = (iw_handler) orinoco_ioctl_getrid,
5607 };
5608
5609 static const struct iw_handler_def orinoco_handler_def = {
5610         .num_standard = ARRAY_SIZE(orinoco_handler),
5611         .num_private = ARRAY_SIZE(orinoco_private_handler),
5612         .num_private_args = ARRAY_SIZE(orinoco_privtab),
5613         .standard = orinoco_handler,
5614         .private = orinoco_private_handler,
5615         .private_args = orinoco_privtab,
5616         .get_wireless_stats = orinoco_get_wireless_stats,
5617 };
5618
5619 static void orinoco_get_drvinfo(struct net_device *dev,
5620                                 struct ethtool_drvinfo *info)
5621 {
5622         struct orinoco_private *priv = netdev_priv(dev);
5623
5624         strncpy(info->driver, DRIVER_NAME, sizeof(info->driver) - 1);
5625         strncpy(info->version, DRIVER_VERSION, sizeof(info->version) - 1);
5626         strncpy(info->fw_version, priv->fw_name, sizeof(info->fw_version) - 1);
5627         if (dev->dev.parent)
5628                 strncpy(info->bus_info, dev->dev.parent->bus_id,
5629                         sizeof(info->bus_info) - 1);
5630         else
5631                 snprintf(info->bus_info, sizeof(info->bus_info) - 1,
5632                          "PCMCIA %p", priv->hw.iobase);
5633 }
5634
5635 static const struct ethtool_ops orinoco_ethtool_ops = {
5636         .get_drvinfo = orinoco_get_drvinfo,
5637         .get_link = ethtool_op_get_link,
5638 };
5639
5640 /********************************************************************/
5641 /* Module initialization                                            */
5642 /********************************************************************/
5643
5644 EXPORT_SYMBOL(alloc_orinocodev);
5645 EXPORT_SYMBOL(free_orinocodev);
5646
5647 EXPORT_SYMBOL(__orinoco_up);
5648 EXPORT_SYMBOL(__orinoco_down);
5649 EXPORT_SYMBOL(orinoco_reinit_firmware);
5650
5651 EXPORT_SYMBOL(orinoco_interrupt);
5652
5653 /* Can't be declared "const" or the whole __initdata section will
5654  * become const */
5655 static char version[] __initdata = DRIVER_NAME " " DRIVER_VERSION
5656         " (David Gibson <hermes@gibson.dropbear.id.au>, "
5657         "Pavel Roskin <proski@gnu.org>, et al)";
5658
5659 static int __init init_orinoco(void)
5660 {
5661         printk(KERN_DEBUG "%s\n", version);
5662         return 0;
5663 }
5664
5665 static void __exit exit_orinoco(void)
5666 {
5667 }
5668
5669 module_init(init_orinoco);
5670 module_exit(exit_orinoco);