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