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