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