d7947358e49db7bd55a59058fd0ca88ac65091ce
[linux-2.6.git] / drivers / net / wireless / orinoco.c
1 /* orinoco.c - (formerly known as dldwd_cs.c and orinoco_cs.c)
2  *
3  * A driver for Hermes or Prism 2 chipset based PCMCIA wireless
4  * adaptors, with Lucent/Agere, Intersil or Symbol firmware.
5  *
6  * Current maintainers (as of 29 September 2003) are:
7  *      Pavel Roskin <proski AT gnu.org>
8  * and  David Gibson <hermes AT gibson.dropbear.id.au>
9  *
10  * (C) Copyright David Gibson, IBM Corporation 2001-2003.
11  * Copyright (C) 2000 David Gibson, Linuxcare Australia.
12  *      With some help from :
13  * Copyright (C) 2001 Jean Tourrilhes, HP Labs
14  * Copyright (C) 2001 Benjamin Herrenschmidt
15  *
16  * Based on dummy_cs.c 1.27 2000/06/12 21:27:25
17  *
18  * Portions based on wvlan_cs.c 1.0.6, Copyright Andreas Neuhaus <andy
19  * AT fasta.fh-dortmund.de>
20  *      http://www.stud.fh-dortmund.de/~andy/wvlan/
21  *
22  * The contents of this file are subject to the Mozilla Public License
23  * Version 1.1 (the "License"); you may not use this file except in
24  * compliance with the License. You may obtain a copy of the License
25  * at http://www.mozilla.org/MPL/
26  *
27  * Software distributed under the License is distributed on an "AS IS"
28  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
29  * the License for the specific language governing rights and
30  * limitations under the License.
31  *
32  * The initial developer of the original code is David A. Hinds
33  * <dahinds AT users.sourceforge.net>.  Portions created by David
34  * A. Hinds are Copyright (C) 1999 David A. Hinds.  All Rights
35  * Reserved.
36  *
37  * Alternatively, the contents of this file may be used under the
38  * terms of the GNU General Public License version 2 (the "GPL"), in
39  * which case the provisions of the GPL are applicable instead of the
40  * above.  If you wish to allow the use of your version of this file
41  * only under the terms of the GPL and not to allow others to use your
42  * version of this file under the MPL, indicate your decision by
43  * deleting the provisions above and replace them with the notice and
44  * other provisions required by the GPL.  If you do not delete the
45  * provisions above, a recipient may use your version of this file
46  * under either the MPL or the GPL.  */
47
48 /*
49  * TODO
50  *      o Handle de-encapsulation within network layer, provide 802.11
51  *        headers (patch from Thomas 'Dent' Mirlacher)
52  *      o Fix possible races in SPY handling.
53  *      o Disconnect wireless extensions from fundamental configuration.
54  *      o (maybe) Software WEP support (patch from Stano Meduna).
55  *      o (maybe) Use multiple Tx buffers - driver handling queue
56  *        rather than firmware.
57  */
58
59 /* Locking and synchronization:
60  *
61  * The basic principle is that everything is serialized through a
62  * single spinlock, priv->lock.  The lock is used in user, bh and irq
63  * context, so when taken outside hardirq context it should always be
64  * taken with interrupts disabled.  The lock protects both the
65  * hardware and the struct orinoco_private.
66  *
67  * Another flag, priv->hw_unavailable indicates that the hardware is
68  * unavailable for an extended period of time (e.g. suspended, or in
69  * the middle of a hard reset).  This flag is protected by the
70  * spinlock.  All code which touches the hardware should check the
71  * flag after taking the lock, and if it is set, give up on whatever
72  * they are doing and drop the lock again.  The orinoco_lock()
73  * function handles this (it unlocks and returns -EBUSY if
74  * hw_unavailable is non-zero).
75  */
76
77 #define DRIVER_NAME "orinoco"
78
79 #include <linux/config.h>
80
81 #include <linux/module.h>
82 #include <linux/kernel.h>
83 #include <linux/init.h>
84 #include <linux/ptrace.h>
85 #include <linux/slab.h>
86 #include <linux/string.h>
87 #include <linux/timer.h>
88 #include <linux/ioport.h>
89 #include <linux/netdevice.h>
90 #include <linux/if_arp.h>
91 #include <linux/etherdevice.h>
92 #include <linux/ethtool.h>
93 #include <linux/wireless.h>
94 #include <net/iw_handler.h>
95 #include <net/ieee80211.h>
96
97 #include <net/ieee80211.h>
98
99 #include <asm/uaccess.h>
100 #include <asm/io.h>
101 #include <asm/system.h>
102
103 #include "hermes.h"
104 #include "hermes_rid.h"
105 #include "orinoco.h"
106
107 /********************************************************************/
108 /* Module information                                               */
109 /********************************************************************/
110
111 MODULE_AUTHOR("Pavel Roskin <proski@gnu.org> & David Gibson <hermes@gibson.dropbear.id.au>");
112 MODULE_DESCRIPTION("Driver for Lucent Orinoco, Prism II based and similar wireless cards");
113 MODULE_LICENSE("Dual MPL/GPL");
114
115 /* Level of debugging. Used in the macros in orinoco.h */
116 #ifdef ORINOCO_DEBUG
117 int orinoco_debug = ORINOCO_DEBUG;
118 module_param(orinoco_debug, int, 0644);
119 MODULE_PARM_DESC(orinoco_debug, "Debug level");
120 EXPORT_SYMBOL(orinoco_debug);
121 #endif
122
123 static int suppress_linkstatus; /* = 0 */
124 module_param(suppress_linkstatus, bool, 0644);
125 MODULE_PARM_DESC(suppress_linkstatus, "Don't log link status changes");
126 static int ignore_disconnect; /* = 0 */
127 module_param(ignore_disconnect, int, 0644);
128 MODULE_PARM_DESC(ignore_disconnect, "Don't report lost link to the network layer");
129
130 static int force_monitor; /* = 0 */
131 module_param(force_monitor, int, 0644);
132 MODULE_PARM_DESC(force_monitor, "Allow monitor mode for all firmware versions");
133
134 /********************************************************************/
135 /* Compile time configuration and compatibility stuff               */
136 /********************************************************************/
137
138 /* We do this this way to avoid ifdefs in the actual code */
139 #ifdef WIRELESS_SPY
140 #define SPY_NUMBER(priv)        (priv->spy_number)
141 #else
142 #define SPY_NUMBER(priv)        0
143 #endif /* WIRELESS_SPY */
144
145 /********************************************************************/
146 /* Internal constants                                               */
147 /********************************************************************/
148
149 /* 802.2 LLC/SNAP header used for Ethernet encapsulation over 802.11 */
150 static const u8 encaps_hdr[] = {0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00};
151 #define ENCAPS_OVERHEAD         (sizeof(encaps_hdr) + 2)
152
153 #define ORINOCO_MIN_MTU         256
154 #define ORINOCO_MAX_MTU         (IEEE80211_DATA_LEN - ENCAPS_OVERHEAD)
155
156 #define SYMBOL_MAX_VER_LEN      (14)
157 #define USER_BAP                0
158 #define IRQ_BAP                 1
159 #define MAX_IRQLOOPS_PER_IRQ    10
160 #define MAX_IRQLOOPS_PER_JIFFY  (20000/HZ) /* Based on a guestimate of
161                                             * how many events the
162                                             * device could
163                                             * legitimately generate */
164 #define SMALL_KEY_SIZE          5
165 #define LARGE_KEY_SIZE          13
166 #define TX_NICBUF_SIZE_BUG      1585            /* Bug in Symbol firmware */
167
168 #define DUMMY_FID               0xFFFF
169
170 /*#define MAX_MULTICAST(priv)   (priv->firmware_type == FIRMWARE_TYPE_AGERE ? \
171   HERMES_MAX_MULTICAST : 0)*/
172 #define MAX_MULTICAST(priv)     (HERMES_MAX_MULTICAST)
173
174 #define ORINOCO_INTEN           (HERMES_EV_RX | HERMES_EV_ALLOC \
175                                  | HERMES_EV_TX | HERMES_EV_TXEXC \
176                                  | HERMES_EV_WTERR | HERMES_EV_INFO \
177                                  | HERMES_EV_INFDROP )
178
179 #define MAX_RID_LEN 1024
180
181 static const struct iw_handler_def orinoco_handler_def;
182 static struct ethtool_ops orinoco_ethtool_ops;
183
184 /********************************************************************/
185 /* Data tables                                                      */
186 /********************************************************************/
187
188 /* The frequency of each channel in MHz */
189 static const long channel_frequency[] = {
190         2412, 2417, 2422, 2427, 2432, 2437, 2442,
191         2447, 2452, 2457, 2462, 2467, 2472, 2484
192 };
193 #define NUM_CHANNELS ARRAY_SIZE(channel_frequency)
194
195 /* This tables gives the actual meanings of the bitrate IDs returned
196  * by the firmware. */
197 static struct {
198         int bitrate; /* in 100s of kilobits */
199         int automatic;
200         u16 agere_txratectrl;
201         u16 intersil_txratectrl;
202 } bitrate_table[] = {
203         {110, 1,  3, 15}, /* Entry 0 is the default */
204         {10,  0,  1,  1},
205         {10,  1,  1,  1},
206         {20,  0,  2,  2},
207         {20,  1,  6,  3},
208         {55,  0,  4,  4},
209         {55,  1,  7,  7},
210         {110, 0,  5,  8},
211 };
212 #define BITRATE_TABLE_SIZE ARRAY_SIZE(bitrate_table)
213
214 /********************************************************************/
215 /* Data types                                                       */
216 /********************************************************************/
217
218 /* Used in Event handling.
219  * We avoid nested structres as they break on ARM -- Moustafa */
220 struct hermes_tx_descriptor_802_11 {
221         /* hermes_tx_descriptor */
222         u16 status;
223         u16 reserved1;
224         u16 reserved2;
225         u32 sw_support;
226         u8 retry_count;
227         u8 tx_rate;
228         u16 tx_control;
229
230         /* ieee802_11_hdr */
231         u16 frame_ctl;
232         u16 duration_id;
233         u8 addr1[ETH_ALEN];
234         u8 addr2[ETH_ALEN];
235         u8 addr3[ETH_ALEN];
236         u16 seq_ctl;
237         u8 addr4[ETH_ALEN];
238         u16 data_len;
239
240         /* ethhdr */
241         unsigned char   h_dest[ETH_ALEN];       /* destination eth addr */
242         unsigned char   h_source[ETH_ALEN];     /* source ether addr    */
243         unsigned short  h_proto;                /* packet type ID field */
244
245         /* p8022_hdr */
246         u8 dsap;
247         u8 ssap;
248         u8 ctrl;
249         u8 oui[3];
250
251         u16 ethertype;
252 } __attribute__ ((packed));
253
254 /* Rx frame header except compatibility 802.3 header */
255 struct hermes_rx_descriptor {
256         /* Control */
257         u16 status;
258         u32 time;
259         u8 silence;
260         u8 signal;
261         u8 rate;
262         u8 rxflow;
263         u32 reserved;
264
265         /* 802.11 header */
266         u16 frame_ctl;
267         u16 duration_id;
268         u8 addr1[ETH_ALEN];
269         u8 addr2[ETH_ALEN];
270         u8 addr3[ETH_ALEN];
271         u16 seq_ctl;
272         u8 addr4[ETH_ALEN];
273
274         /* Data length */
275         u16 data_len;
276 } __attribute__ ((packed));
277
278 /********************************************************************/
279 /* Function prototypes                                              */
280 /********************************************************************/
281
282 static int __orinoco_program_rids(struct net_device *dev);
283 static void __orinoco_set_multicast_list(struct net_device *dev);
284
285 /********************************************************************/
286 /* Internal helper functions                                        */
287 /********************************************************************/
288
289 static inline void set_port_type(struct orinoco_private *priv)
290 {
291         switch (priv->iw_mode) {
292         case IW_MODE_INFRA:
293                 priv->port_type = 1;
294                 priv->createibss = 0;
295                 break;
296         case IW_MODE_ADHOC:
297                 if (priv->prefer_port3) {
298                         priv->port_type = 3;
299                         priv->createibss = 0;
300                 } else {
301                         priv->port_type = priv->ibss_port;
302                         priv->createibss = 1;
303                 }
304                 break;
305         case IW_MODE_MONITOR:
306                 priv->port_type = 3;
307                 priv->createibss = 0;
308                 break;
309         default:
310                 printk(KERN_ERR "%s: Invalid priv->iw_mode in set_port_type()\n",
311                        priv->ndev->name);
312         }
313 }
314
315 /********************************************************************/
316 /* Device methods                                                   */
317 /********************************************************************/
318
319 static int orinoco_open(struct net_device *dev)
320 {
321         struct orinoco_private *priv = netdev_priv(dev);
322         unsigned long flags;
323         int err;
324
325         if (orinoco_lock(priv, &flags) != 0)
326                 return -EBUSY;
327
328         err = __orinoco_up(dev);
329
330         if (! err)
331                 priv->open = 1;
332
333         orinoco_unlock(priv, &flags);
334
335         return err;
336 }
337
338 static int orinoco_stop(struct net_device *dev)
339 {
340         struct orinoco_private *priv = netdev_priv(dev);
341         int err = 0;
342
343         /* We mustn't use orinoco_lock() here, because we need to be
344            able to close the interface even if hw_unavailable is set
345            (e.g. as we're released after a PC Card removal) */
346         spin_lock_irq(&priv->lock);
347
348         priv->open = 0;
349
350         err = __orinoco_down(dev);
351
352         spin_unlock_irq(&priv->lock);
353
354         return err;
355 }
356
357 static struct net_device_stats *orinoco_get_stats(struct net_device *dev)
358 {
359         struct orinoco_private *priv = netdev_priv(dev);
360         
361         return &priv->stats;
362 }
363
364 static struct iw_statistics *orinoco_get_wireless_stats(struct net_device *dev)
365 {
366         struct orinoco_private *priv = netdev_priv(dev);
367         hermes_t *hw = &priv->hw;
368         struct iw_statistics *wstats = &priv->wstats;
369         int err;
370         unsigned long flags;
371
372         if (! netif_device_present(dev)) {
373                 printk(KERN_WARNING "%s: get_wireless_stats() called while device not present\n",
374                        dev->name);
375                 return NULL; /* FIXME: Can we do better than this? */
376         }
377
378         /* If busy, return the old stats.  Returning NULL may cause
379          * the interface to disappear from /proc/net/wireless */
380         if (orinoco_lock(priv, &flags) != 0)
381                 return wstats;
382
383         /* We can't really wait for the tallies inquiry command to
384          * complete, so we just use the previous results and trigger
385          * a new tallies inquiry command for next time - Jean II */
386         /* FIXME: Really we should wait for the inquiry to come back -
387          * as it is the stats we give don't make a whole lot of sense.
388          * Unfortunately, it's not clear how to do that within the
389          * wireless extensions framework: I think we're in user
390          * context, but a lock seems to be held by the time we get in
391          * here so we're not safe to sleep here. */
392         hermes_inquire(hw, HERMES_INQ_TALLIES);
393
394         if (priv->iw_mode == IW_MODE_ADHOC) {
395                 memset(&wstats->qual, 0, sizeof(wstats->qual));
396                 /* If a spy address is defined, we report stats of the
397                  * first spy address - Jean II */
398                 if (SPY_NUMBER(priv)) {
399                         wstats->qual.qual = priv->spy_stat[0].qual;
400                         wstats->qual.level = priv->spy_stat[0].level;
401                         wstats->qual.noise = priv->spy_stat[0].noise;
402                         wstats->qual.updated = priv->spy_stat[0].updated;
403                 }
404         } else {
405                 struct {
406                         u16 qual, signal, noise;
407                 } __attribute__ ((packed)) cq;
408
409                 err = HERMES_READ_RECORD(hw, USER_BAP,
410                                          HERMES_RID_COMMSQUALITY, &cq);
411
412                 if (!err) {
413                         wstats->qual.qual = (int)le16_to_cpu(cq.qual);
414                         wstats->qual.level = (int)le16_to_cpu(cq.signal) - 0x95;
415                         wstats->qual.noise = (int)le16_to_cpu(cq.noise) - 0x95;
416                         wstats->qual.updated = 7;
417                 }
418         }
419
420         orinoco_unlock(priv, &flags);
421         return wstats;
422 }
423
424 static void orinoco_set_multicast_list(struct net_device *dev)
425 {
426         struct orinoco_private *priv = netdev_priv(dev);
427         unsigned long flags;
428
429         if (orinoco_lock(priv, &flags) != 0) {
430                 printk(KERN_DEBUG "%s: orinoco_set_multicast_list() "
431                        "called when hw_unavailable\n", dev->name);
432                 return;
433         }
434
435         __orinoco_set_multicast_list(dev);
436         orinoco_unlock(priv, &flags);
437 }
438
439 static int orinoco_change_mtu(struct net_device *dev, int new_mtu)
440 {
441         struct orinoco_private *priv = netdev_priv(dev);
442
443         if ( (new_mtu < ORINOCO_MIN_MTU) || (new_mtu > ORINOCO_MAX_MTU) )
444                 return -EINVAL;
445
446         if ( (new_mtu + ENCAPS_OVERHEAD + IEEE80211_HLEN) >
447              (priv->nicbuf_size - ETH_HLEN) )
448                 return -EINVAL;
449
450         dev->mtu = new_mtu;
451
452         return 0;
453 }
454
455 /********************************************************************/
456 /* Tx path                                                          */
457 /********************************************************************/
458
459 static int orinoco_xmit(struct sk_buff *skb, struct net_device *dev)
460 {
461         struct orinoco_private *priv = netdev_priv(dev);
462         struct net_device_stats *stats = &priv->stats;
463         hermes_t *hw = &priv->hw;
464         int err = 0;
465         u16 txfid = priv->txfid;
466         char *p;
467         struct ethhdr *eh;
468         int len, data_len, data_off;
469         struct hermes_tx_descriptor desc;
470         unsigned long flags;
471
472         TRACE_ENTER(dev->name);
473
474         if (! netif_running(dev)) {
475                 printk(KERN_ERR "%s: Tx on stopped device!\n",
476                        dev->name);
477                 TRACE_EXIT(dev->name);
478                 return 1;
479         }
480         
481         if (netif_queue_stopped(dev)) {
482                 printk(KERN_DEBUG "%s: Tx while transmitter busy!\n", 
483                        dev->name);
484                 TRACE_EXIT(dev->name);
485                 return 1;
486         }
487         
488         if (orinoco_lock(priv, &flags) != 0) {
489                 printk(KERN_ERR "%s: orinoco_xmit() called while hw_unavailable\n",
490                        dev->name);
491                 TRACE_EXIT(dev->name);
492                 return 1;
493         }
494
495         if (! netif_carrier_ok(dev) || (priv->iw_mode == IW_MODE_MONITOR)) {
496                 /* Oops, the firmware hasn't established a connection,
497                    silently drop the packet (this seems to be the
498                    safest approach). */
499                 stats->tx_errors++;
500                 orinoco_unlock(priv, &flags);
501                 dev_kfree_skb(skb);
502                 TRACE_EXIT(dev->name);
503                 return 0;
504         }
505
506         /* Length of the packet body */
507         /* FIXME: what if the skb is smaller than this? */
508         len = max_t(int,skb->len - ETH_HLEN, ETH_ZLEN - ETH_HLEN);
509
510         eh = (struct ethhdr *)skb->data;
511
512         memset(&desc, 0, sizeof(desc));
513         desc.tx_control = cpu_to_le16(HERMES_TXCTRL_TX_OK | HERMES_TXCTRL_TX_EX);
514         err = hermes_bap_pwrite(hw, USER_BAP, &desc, sizeof(desc), txfid, 0);
515         if (err) {
516                 if (net_ratelimit())
517                         printk(KERN_ERR "%s: Error %d writing Tx descriptor "
518                                "to BAP\n", dev->name, err);
519                 stats->tx_errors++;
520                 goto fail;
521         }
522
523         /* Clear the 802.11 header and data length fields - some
524          * firmwares (e.g. Lucent/Agere 8.xx) appear to get confused
525          * if this isn't done. */
526         hermes_clear_words(hw, HERMES_DATA0,
527                            HERMES_802_3_OFFSET - HERMES_802_11_OFFSET);
528
529         /* Encapsulate Ethernet-II frames */
530         if (ntohs(eh->h_proto) > ETH_DATA_LEN) { /* Ethernet-II frame */
531                 struct header_struct hdr;
532                 data_len = len;
533                 data_off = HERMES_802_3_OFFSET + sizeof(hdr);
534                 p = skb->data + ETH_HLEN;
535
536                 /* 802.3 header */
537                 memcpy(hdr.dest, eh->h_dest, ETH_ALEN);
538                 memcpy(hdr.src, eh->h_source, ETH_ALEN);
539                 hdr.len = htons(data_len + ENCAPS_OVERHEAD);
540                 
541                 /* 802.2 header */
542                 memcpy(&hdr.dsap, &encaps_hdr, sizeof(encaps_hdr));
543                         
544                 hdr.ethertype = eh->h_proto;
545                 err  = hermes_bap_pwrite(hw, USER_BAP, &hdr, sizeof(hdr),
546                                          txfid, HERMES_802_3_OFFSET);
547                 if (err) {
548                         if (net_ratelimit())
549                                 printk(KERN_ERR "%s: Error %d writing packet "
550                                        "header to BAP\n", dev->name, err);
551                         stats->tx_errors++;
552                         goto fail;
553                 }
554         } else { /* IEEE 802.3 frame */
555                 data_len = len + ETH_HLEN;
556                 data_off = HERMES_802_3_OFFSET;
557                 p = skb->data;
558         }
559
560         /* Round up for odd length packets */
561         err = hermes_bap_pwrite(hw, USER_BAP, p, ALIGN(data_len, 2),
562                                 txfid, data_off);
563         if (err) {
564                 printk(KERN_ERR "%s: Error %d writing packet to BAP\n",
565                        dev->name, err);
566                 stats->tx_errors++;
567                 goto fail;
568         }
569
570         /* Finally, we actually initiate the send */
571         netif_stop_queue(dev);
572
573         err = hermes_docmd_wait(hw, HERMES_CMD_TX | HERMES_CMD_RECL,
574                                 txfid, NULL);
575         if (err) {
576                 netif_start_queue(dev);
577                 printk(KERN_ERR "%s: Error %d transmitting packet\n",
578                        dev->name, err);
579                 stats->tx_errors++;
580                 goto fail;
581         }
582
583         dev->trans_start = jiffies;
584         stats->tx_bytes += data_off + data_len;
585
586         orinoco_unlock(priv, &flags);
587
588         dev_kfree_skb(skb);
589
590         TRACE_EXIT(dev->name);
591
592         return 0;
593  fail:
594         TRACE_EXIT(dev->name);
595
596         orinoco_unlock(priv, &flags);
597         return err;
598 }
599
600 static void __orinoco_ev_alloc(struct net_device *dev, hermes_t *hw)
601 {
602         struct orinoco_private *priv = netdev_priv(dev);
603         u16 fid = hermes_read_regn(hw, ALLOCFID);
604
605         if (fid != priv->txfid) {
606                 if (fid != DUMMY_FID)
607                         printk(KERN_WARNING "%s: Allocate event on unexpected fid (%04X)\n",
608                                dev->name, fid);
609                 return;
610         }
611
612         hermes_write_regn(hw, ALLOCFID, DUMMY_FID);
613 }
614
615 static void __orinoco_ev_tx(struct net_device *dev, hermes_t *hw)
616 {
617         struct orinoco_private *priv = netdev_priv(dev);
618         struct net_device_stats *stats = &priv->stats;
619
620         stats->tx_packets++;
621
622         netif_wake_queue(dev);
623
624         hermes_write_regn(hw, TXCOMPLFID, DUMMY_FID);
625 }
626
627 static void __orinoco_ev_txexc(struct net_device *dev, hermes_t *hw)
628 {
629         struct orinoco_private *priv = netdev_priv(dev);
630         struct net_device_stats *stats = &priv->stats;
631         u16 fid = hermes_read_regn(hw, TXCOMPLFID);
632         struct hermes_tx_descriptor_802_11 hdr;
633         int err = 0;
634
635         if (fid == DUMMY_FID)
636                 return; /* Nothing's really happened */
637
638         /* Read the frame header */
639         err = hermes_bap_pread(hw, IRQ_BAP, &hdr,
640                                sizeof(struct hermes_tx_descriptor) +
641                                sizeof(struct ieee80211_hdr),
642                                fid, 0);
643
644         hermes_write_regn(hw, TXCOMPLFID, DUMMY_FID);
645         stats->tx_errors++;
646
647         if (err) {
648                 printk(KERN_WARNING "%s: Unable to read descriptor on Tx error "
649                        "(FID=%04X error %d)\n",
650                        dev->name, fid, err);
651                 return;
652         }
653         
654         DEBUG(1, "%s: Tx error, err %d (FID=%04X)\n", dev->name,
655               err, fid);
656     
657         /* We produce a TXDROP event only for retry or lifetime
658          * exceeded, because that's the only status that really mean
659          * that this particular node went away.
660          * Other errors means that *we* screwed up. - Jean II */
661         hdr.status = le16_to_cpu(hdr.status);
662         if (hdr.status & (HERMES_TXSTAT_RETRYERR | HERMES_TXSTAT_AGEDERR)) {
663                 union iwreq_data        wrqu;
664
665                 /* Copy 802.11 dest address.
666                  * We use the 802.11 header because the frame may
667                  * not be 802.3 or may be mangled...
668                  * In Ad-Hoc mode, it will be the node address.
669                  * In managed mode, it will be most likely the AP addr
670                  * User space will figure out how to convert it to
671                  * whatever it needs (IP address or else).
672                  * - Jean II */
673                 memcpy(wrqu.addr.sa_data, hdr.addr1, ETH_ALEN);
674                 wrqu.addr.sa_family = ARPHRD_ETHER;
675
676                 /* Send event to user space */
677                 wireless_send_event(dev, IWEVTXDROP, &wrqu, NULL);
678         }
679
680         netif_wake_queue(dev);
681 }
682
683 static void orinoco_tx_timeout(struct net_device *dev)
684 {
685         struct orinoco_private *priv = netdev_priv(dev);
686         struct net_device_stats *stats = &priv->stats;
687         struct hermes *hw = &priv->hw;
688
689         printk(KERN_WARNING "%s: Tx timeout! "
690                "ALLOCFID=%04x, TXCOMPLFID=%04x, EVSTAT=%04x\n",
691                dev->name, hermes_read_regn(hw, ALLOCFID),
692                hermes_read_regn(hw, TXCOMPLFID), hermes_read_regn(hw, EVSTAT));
693
694         stats->tx_errors++;
695
696         schedule_work(&priv->reset_work);
697 }
698
699 /********************************************************************/
700 /* Rx path (data frames)                                            */
701 /********************************************************************/
702
703 /* Does the frame have a SNAP header indicating it should be
704  * de-encapsulated to Ethernet-II? */
705 static inline int is_ethersnap(void *_hdr)
706 {
707         u8 *hdr = _hdr;
708
709         /* We de-encapsulate all packets which, a) have SNAP headers
710          * (i.e. SSAP=DSAP=0xaa and CTRL=0x3 in the 802.2 LLC header
711          * and where b) the OUI of the SNAP header is 00:00:00 or
712          * 00:00:f8 - we need both because different APs appear to use
713          * different OUIs for some reason */
714         return (memcmp(hdr, &encaps_hdr, 5) == 0)
715                 && ( (hdr[5] == 0x00) || (hdr[5] == 0xf8) );
716 }
717
718 static inline void orinoco_spy_gather(struct net_device *dev, u_char *mac,
719                                       int level, int noise)
720 {
721         struct orinoco_private *priv = netdev_priv(dev);
722         int i;
723
724         /* Gather wireless spy statistics: for each packet, compare the
725          * source address with out list, and if match, get the stats... */
726         for (i = 0; i < priv->spy_number; i++)
727                 if (!memcmp(mac, priv->spy_address[i], ETH_ALEN)) {
728                         priv->spy_stat[i].level = level - 0x95;
729                         priv->spy_stat[i].noise = noise - 0x95;
730                         priv->spy_stat[i].qual = (level > noise) ? (level - noise) : 0;
731                         priv->spy_stat[i].updated = 7;
732                 }
733 }
734
735 static void orinoco_stat_gather(struct net_device *dev,
736                                 struct sk_buff *skb,
737                                 struct hermes_rx_descriptor *desc)
738 {
739         struct orinoco_private *priv = netdev_priv(dev);
740
741         /* Using spy support with lots of Rx packets, like in an
742          * infrastructure (AP), will really slow down everything, because
743          * the MAC address must be compared to each entry of the spy list.
744          * If the user really asks for it (set some address in the
745          * spy list), we do it, but he will pay the price.
746          * Note that to get here, you need both WIRELESS_SPY
747          * compiled in AND some addresses in the list !!!
748          */
749         /* Note : gcc will optimise the whole section away if
750          * WIRELESS_SPY is not defined... - Jean II */
751         if (SPY_NUMBER(priv)) {
752                 orinoco_spy_gather(dev, skb->mac.raw + ETH_ALEN,
753                                    desc->signal, desc->silence);
754         }
755 }
756
757 /*
758  * orinoco_rx_monitor - handle received monitor frames.
759  *
760  * Arguments:
761  *      dev             network device
762  *      rxfid           received FID
763  *      desc            rx descriptor of the frame
764  *
765  * Call context: interrupt
766  */
767 static void orinoco_rx_monitor(struct net_device *dev, u16 rxfid,
768                                struct hermes_rx_descriptor *desc)
769 {
770         u32 hdrlen = 30;        /* return full header by default */
771         u32 datalen = 0;
772         u16 fc;
773         int err;
774         int len;
775         struct sk_buff *skb;
776         struct orinoco_private *priv = netdev_priv(dev);
777         struct net_device_stats *stats = &priv->stats;
778         hermes_t *hw = &priv->hw;
779
780         len = le16_to_cpu(desc->data_len);
781
782         /* Determine the size of the header and the data */
783         fc = le16_to_cpu(desc->frame_ctl);
784         switch (fc & IEEE80211_FCTL_FTYPE) {
785         case IEEE80211_FTYPE_DATA:
786                 if ((fc & IEEE80211_FCTL_TODS)
787                     && (fc & IEEE80211_FCTL_FROMDS))
788                         hdrlen = 30;
789                 else
790                         hdrlen = 24;
791                 datalen = len;
792                 break;
793         case IEEE80211_FTYPE_MGMT:
794                 hdrlen = 24;
795                 datalen = len;
796                 break;
797         case IEEE80211_FTYPE_CTL:
798                 switch (fc & IEEE80211_FCTL_STYPE) {
799                 case IEEE80211_STYPE_PSPOLL:
800                 case IEEE80211_STYPE_RTS:
801                 case IEEE80211_STYPE_CFEND:
802                 case IEEE80211_STYPE_CFENDACK:
803                         hdrlen = 16;
804                         break;
805                 case IEEE80211_STYPE_CTS:
806                 case IEEE80211_STYPE_ACK:
807                         hdrlen = 10;
808                         break;
809                 }
810                 break;
811         default:
812                 /* Unknown frame type */
813                 break;
814         }
815
816         /* sanity check the length */
817         if (datalen > IEEE80211_DATA_LEN + 12) {
818                 printk(KERN_DEBUG "%s: oversized monitor frame, "
819                        "data length = %d\n", dev->name, datalen);
820                 err = -EIO;
821                 stats->rx_length_errors++;
822                 goto update_stats;
823         }
824
825         skb = dev_alloc_skb(hdrlen + datalen);
826         if (!skb) {
827                 printk(KERN_WARNING "%s: Cannot allocate skb for monitor frame\n",
828                        dev->name);
829                 err = -ENOMEM;
830                 goto drop;
831         }
832
833         /* Copy the 802.11 header to the skb */
834         memcpy(skb_put(skb, hdrlen), &(desc->frame_ctl), hdrlen);
835         skb->mac.raw = skb->data;
836
837         /* If any, copy the data from the card to the skb */
838         if (datalen > 0) {
839                 err = hermes_bap_pread(hw, IRQ_BAP, skb_put(skb, datalen),
840                                        ALIGN(datalen, 2), rxfid,
841                                        HERMES_802_2_OFFSET);
842                 if (err) {
843                         printk(KERN_ERR "%s: error %d reading monitor frame\n",
844                                dev->name, err);
845                         goto drop;
846                 }
847         }
848
849         skb->dev = dev;
850         skb->ip_summed = CHECKSUM_NONE;
851         skb->pkt_type = PACKET_OTHERHOST;
852         skb->protocol = __constant_htons(ETH_P_802_2);
853         
854         dev->last_rx = jiffies;
855         stats->rx_packets++;
856         stats->rx_bytes += skb->len;
857
858         netif_rx(skb);
859         return;
860
861  drop:
862         dev_kfree_skb_irq(skb);
863  update_stats:
864         stats->rx_errors++;
865         stats->rx_dropped++;
866 }
867
868 static void __orinoco_ev_rx(struct net_device *dev, hermes_t *hw)
869 {
870         struct orinoco_private *priv = netdev_priv(dev);
871         struct net_device_stats *stats = &priv->stats;
872         struct iw_statistics *wstats = &priv->wstats;
873         struct sk_buff *skb = NULL;
874         u16 rxfid, status, fc;
875         int length;
876         struct hermes_rx_descriptor desc;
877         struct ethhdr *hdr;
878         int err;
879
880         rxfid = hermes_read_regn(hw, RXFID);
881
882         err = hermes_bap_pread(hw, IRQ_BAP, &desc, sizeof(desc),
883                                rxfid, 0);
884         if (err) {
885                 printk(KERN_ERR "%s: error %d reading Rx descriptor. "
886                        "Frame dropped.\n", dev->name, err);
887                 goto update_stats;
888         }
889
890         status = le16_to_cpu(desc.status);
891
892         if (status & HERMES_RXSTAT_BADCRC) {
893                 DEBUG(1, "%s: Bad CRC on Rx. Frame dropped.\n",
894                       dev->name);
895                 stats->rx_crc_errors++;
896                 goto update_stats;
897         }
898
899         /* Handle frames in monitor mode */
900         if (priv->iw_mode == IW_MODE_MONITOR) {
901                 orinoco_rx_monitor(dev, rxfid, &desc);
902                 return;
903         }
904
905         if (status & HERMES_RXSTAT_UNDECRYPTABLE) {
906                 DEBUG(1, "%s: Undecryptable frame on Rx. Frame dropped.\n",
907                       dev->name);
908                 wstats->discard.code++;
909                 goto update_stats;
910         }
911
912         length = le16_to_cpu(desc.data_len);
913         fc = le16_to_cpu(desc.frame_ctl);
914
915         /* Sanity checks */
916         if (length < 3) { /* No for even an 802.2 LLC header */
917                 /* At least on Symbol firmware with PCF we get quite a
918                    lot of these legitimately - Poll frames with no
919                    data. */
920                 return;
921         }
922         if (length > IEEE80211_DATA_LEN) {
923                 printk(KERN_WARNING "%s: Oversized frame received (%d bytes)\n",
924                        dev->name, length);
925                 stats->rx_length_errors++;
926                 goto update_stats;
927         }
928
929         /* We need space for the packet data itself, plus an ethernet
930            header, plus 2 bytes so we can align the IP header on a
931            32bit boundary, plus 1 byte so we can read in odd length
932            packets from the card, which has an IO granularity of 16
933            bits */  
934         skb = dev_alloc_skb(length+ETH_HLEN+2+1);
935         if (!skb) {
936                 printk(KERN_WARNING "%s: Can't allocate skb for Rx\n",
937                        dev->name);
938                 goto update_stats;
939         }
940
941         /* We'll prepend the header, so reserve space for it.  The worst
942            case is no decapsulation, when 802.3 header is prepended and
943            nothing is removed.  2 is for aligning the IP header.  */
944         skb_reserve(skb, ETH_HLEN + 2);
945
946         err = hermes_bap_pread(hw, IRQ_BAP, skb_put(skb, length),
947                                ALIGN(length, 2), rxfid,
948                                HERMES_802_2_OFFSET);
949         if (err) {
950                 printk(KERN_ERR "%s: error %d reading frame. "
951                        "Frame dropped.\n", dev->name, err);
952                 goto drop;
953         }
954
955         /* Handle decapsulation
956          * In most cases, the firmware tell us about SNAP frames.
957          * For some reason, the SNAP frames sent by LinkSys APs
958          * are not properly recognised by most firmwares.
959          * So, check ourselves */
960         if (length >= ENCAPS_OVERHEAD &&
961             (((status & HERMES_RXSTAT_MSGTYPE) == HERMES_RXSTAT_1042) ||
962              ((status & HERMES_RXSTAT_MSGTYPE) == HERMES_RXSTAT_TUNNEL) ||
963              is_ethersnap(skb->data))) {
964                 /* These indicate a SNAP within 802.2 LLC within
965                    802.11 frame which we'll need to de-encapsulate to
966                    the original EthernetII frame. */
967                 hdr = (struct ethhdr *)skb_push(skb, ETH_HLEN - ENCAPS_OVERHEAD);
968         } else {
969                 /* 802.3 frame - prepend 802.3 header as is */
970                 hdr = (struct ethhdr *)skb_push(skb, ETH_HLEN);
971                 hdr->h_proto = htons(length);
972         }
973         memcpy(hdr->h_dest, desc.addr1, ETH_ALEN);
974         if (fc & IEEE80211_FCTL_FROMDS)
975                 memcpy(hdr->h_source, desc.addr3, ETH_ALEN);
976         else
977                 memcpy(hdr->h_source, desc.addr2, ETH_ALEN);
978
979         dev->last_rx = jiffies;
980         skb->dev = dev;
981         skb->protocol = eth_type_trans(skb, dev);
982         skb->ip_summed = CHECKSUM_NONE;
983         if (fc & IEEE80211_FCTL_TODS)
984                 skb->pkt_type = PACKET_OTHERHOST;
985         
986         /* Process the wireless stats if needed */
987         orinoco_stat_gather(dev, skb, &desc);
988
989         /* Pass the packet to the networking stack */
990         netif_rx(skb);
991         stats->rx_packets++;
992         stats->rx_bytes += length;
993
994         return;
995
996  drop:  
997         dev_kfree_skb_irq(skb);
998  update_stats:
999         stats->rx_errors++;
1000         stats->rx_dropped++;
1001 }
1002
1003 /********************************************************************/
1004 /* Rx path (info frames)                                            */
1005 /********************************************************************/
1006
1007 static void print_linkstatus(struct net_device *dev, u16 status)
1008 {
1009         char * s;
1010
1011         if (suppress_linkstatus)
1012                 return;
1013
1014         switch (status) {
1015         case HERMES_LINKSTATUS_NOT_CONNECTED:
1016                 s = "Not Connected";
1017                 break;
1018         case HERMES_LINKSTATUS_CONNECTED:
1019                 s = "Connected";
1020                 break;
1021         case HERMES_LINKSTATUS_DISCONNECTED:
1022                 s = "Disconnected";
1023                 break;
1024         case HERMES_LINKSTATUS_AP_CHANGE:
1025                 s = "AP Changed";
1026                 break;
1027         case HERMES_LINKSTATUS_AP_OUT_OF_RANGE:
1028                 s = "AP Out of Range";
1029                 break;
1030         case HERMES_LINKSTATUS_AP_IN_RANGE:
1031                 s = "AP In Range";
1032                 break;
1033         case HERMES_LINKSTATUS_ASSOC_FAILED:
1034                 s = "Association Failed";
1035                 break;
1036         default:
1037                 s = "UNKNOWN";
1038         }
1039         
1040         printk(KERN_INFO "%s: New link status: %s (%04x)\n",
1041                dev->name, s, status);
1042 }
1043
1044 /* Search scan results for requested BSSID, join it if found */
1045 static void orinoco_join_ap(struct net_device *dev)
1046 {
1047         struct orinoco_private *priv = netdev_priv(dev);
1048         struct hermes *hw = &priv->hw;
1049         int err;
1050         unsigned long flags;
1051         struct join_req {
1052                 u8 bssid[ETH_ALEN];
1053                 u16 channel;
1054         } __attribute__ ((packed)) req;
1055         const int atom_len = offsetof(struct prism2_scan_apinfo, atim);
1056         struct prism2_scan_apinfo *atom;
1057         int offset = 4;
1058         u8 *buf;
1059         u16 len;
1060
1061         /* Allocate buffer for scan results */
1062         buf = kmalloc(MAX_SCAN_LEN, GFP_KERNEL);
1063         if (! buf)
1064                 return;
1065
1066         if (orinoco_lock(priv, &flags) != 0)
1067                 goto out;
1068
1069         /* Sanity checks in case user changed something in the meantime */
1070         if (! priv->bssid_fixed)
1071                 goto out;
1072
1073         if (strlen(priv->desired_essid) == 0)
1074                 goto out;
1075
1076         /* Read scan results from the firmware */
1077         err = hermes_read_ltv(hw, USER_BAP,
1078                               HERMES_RID_SCANRESULTSTABLE,
1079                               MAX_SCAN_LEN, &len, buf);
1080         if (err) {
1081                 printk(KERN_ERR "%s: Cannot read scan results\n",
1082                        dev->name);
1083                 goto out;
1084         }
1085
1086         len = HERMES_RECLEN_TO_BYTES(len);
1087
1088         /* Go through the scan results looking for the channel of the AP
1089          * we were requested to join */
1090         for (; offset + atom_len <= len; offset += atom_len) {
1091                 atom = (struct prism2_scan_apinfo *) (buf + offset);
1092                 if (memcmp(&atom->bssid, priv->desired_bssid, ETH_ALEN) == 0)
1093                         goto found;
1094         }
1095
1096         DEBUG(1, "%s: Requested AP not found in scan results\n",
1097               dev->name);
1098         goto out;
1099
1100  found:
1101         memcpy(req.bssid, priv->desired_bssid, ETH_ALEN);
1102         req.channel = atom->channel;    /* both are little-endian */
1103         err = HERMES_WRITE_RECORD(hw, USER_BAP, HERMES_RID_CNFJOINREQUEST,
1104                                   &req);
1105         if (err)
1106                 printk(KERN_ERR "%s: Error issuing join request\n", dev->name);
1107
1108  out:
1109         kfree(buf);
1110         orinoco_unlock(priv, &flags);
1111 }
1112
1113 /* Send new BSSID to userspace */
1114 static void orinoco_send_wevents(struct net_device *dev)
1115 {
1116         struct orinoco_private *priv = netdev_priv(dev);
1117         struct hermes *hw = &priv->hw;
1118         union iwreq_data wrqu;
1119         int err;
1120         unsigned long flags;
1121
1122         if (orinoco_lock(priv, &flags) != 0)
1123                 return;
1124
1125         err = hermes_read_ltv(hw, IRQ_BAP, HERMES_RID_CURRENTBSSID,
1126                               ETH_ALEN, NULL, wrqu.ap_addr.sa_data);
1127         if (err != 0)
1128                 return;
1129
1130         wrqu.ap_addr.sa_family = ARPHRD_ETHER;
1131
1132         /* Send event to user space */
1133         wireless_send_event(dev, SIOCGIWAP, &wrqu, NULL);
1134         orinoco_unlock(priv, &flags);
1135 }
1136
1137 static void __orinoco_ev_info(struct net_device *dev, hermes_t *hw)
1138 {
1139         struct orinoco_private *priv = netdev_priv(dev);
1140         u16 infofid;
1141         struct {
1142                 u16 len;
1143                 u16 type;
1144         } __attribute__ ((packed)) info;
1145         int len, type;
1146         int err;
1147
1148         /* This is an answer to an INQUIRE command that we did earlier,
1149          * or an information "event" generated by the card
1150          * The controller return to us a pseudo frame containing
1151          * the information in question - Jean II */
1152         infofid = hermes_read_regn(hw, INFOFID);
1153
1154         /* Read the info frame header - don't try too hard */
1155         err = hermes_bap_pread(hw, IRQ_BAP, &info, sizeof(info),
1156                                infofid, 0);
1157         if (err) {
1158                 printk(KERN_ERR "%s: error %d reading info frame. "
1159                        "Frame dropped.\n", dev->name, err);
1160                 return;
1161         }
1162         
1163         len = HERMES_RECLEN_TO_BYTES(le16_to_cpu(info.len));
1164         type = le16_to_cpu(info.type);
1165
1166         switch (type) {
1167         case HERMES_INQ_TALLIES: {
1168                 struct hermes_tallies_frame tallies;
1169                 struct iw_statistics *wstats = &priv->wstats;
1170                 
1171                 if (len > sizeof(tallies)) {
1172                         printk(KERN_WARNING "%s: Tallies frame too long (%d bytes)\n",
1173                                dev->name, len);
1174                         len = sizeof(tallies);
1175                 }
1176                 
1177                 err = hermes_bap_pread(hw, IRQ_BAP, &tallies, len,
1178                                        infofid, sizeof(info));
1179                 if (err)
1180                         break;
1181                 
1182                 /* Increment our various counters */
1183                 /* wstats->discard.nwid - no wrong BSSID stuff */
1184                 wstats->discard.code +=
1185                         le16_to_cpu(tallies.RxWEPUndecryptable);
1186                 if (len == sizeof(tallies))  
1187                         wstats->discard.code +=
1188                                 le16_to_cpu(tallies.RxDiscards_WEPICVError) +
1189                                 le16_to_cpu(tallies.RxDiscards_WEPExcluded);
1190                 wstats->discard.misc +=
1191                         le16_to_cpu(tallies.TxDiscardsWrongSA);
1192                 wstats->discard.fragment +=
1193                         le16_to_cpu(tallies.RxMsgInBadMsgFragments);
1194                 wstats->discard.retries +=
1195                         le16_to_cpu(tallies.TxRetryLimitExceeded);
1196                 /* wstats->miss.beacon - no match */
1197         }
1198         break;
1199         case HERMES_INQ_LINKSTATUS: {
1200                 struct hermes_linkstatus linkstatus;
1201                 u16 newstatus;
1202                 int connected;
1203
1204                 if (priv->iw_mode == IW_MODE_MONITOR)
1205                         break;
1206
1207                 if (len != sizeof(linkstatus)) {
1208                         printk(KERN_WARNING "%s: Unexpected size for linkstatus frame (%d bytes)\n",
1209                                dev->name, len);
1210                         break;
1211                 }
1212
1213                 err = hermes_bap_pread(hw, IRQ_BAP, &linkstatus, len,
1214                                        infofid, sizeof(info));
1215                 if (err)
1216                         break;
1217                 newstatus = le16_to_cpu(linkstatus.linkstatus);
1218
1219                 /* Symbol firmware uses "out of range" to signal that
1220                  * the hostscan frame can be requested.  */
1221                 if (newstatus == HERMES_LINKSTATUS_AP_OUT_OF_RANGE &&
1222                     priv->firmware_type == FIRMWARE_TYPE_SYMBOL &&
1223                     priv->has_hostscan && priv->scan_inprogress) {
1224                         hermes_inquire(hw, HERMES_INQ_HOSTSCAN_SYMBOL);
1225                         break;
1226                 }
1227
1228                 connected = (newstatus == HERMES_LINKSTATUS_CONNECTED)
1229                         || (newstatus == HERMES_LINKSTATUS_AP_CHANGE)
1230                         || (newstatus == HERMES_LINKSTATUS_AP_IN_RANGE);
1231
1232                 if (connected)
1233                         netif_carrier_on(dev);
1234                 else if (!ignore_disconnect)
1235                         netif_carrier_off(dev);
1236
1237                 if (newstatus != priv->last_linkstatus) {
1238                         priv->last_linkstatus = newstatus;
1239                         print_linkstatus(dev, newstatus);
1240                         /* The info frame contains only one word which is the
1241                          * status (see hermes.h). The status is pretty boring
1242                          * in itself, that's why we export the new BSSID...
1243                          * Jean II */
1244                         schedule_work(&priv->wevent_work);
1245                 }
1246         }
1247         break;
1248         case HERMES_INQ_SCAN:
1249                 if (!priv->scan_inprogress && priv->bssid_fixed &&
1250                     priv->firmware_type == FIRMWARE_TYPE_INTERSIL) {
1251                         schedule_work(&priv->join_work);
1252                         break;
1253                 }
1254                 /* fall through */
1255         case HERMES_INQ_HOSTSCAN:
1256         case HERMES_INQ_HOSTSCAN_SYMBOL: {
1257                 /* Result of a scanning. Contains information about
1258                  * cells in the vicinity - Jean II */
1259                 union iwreq_data        wrqu;
1260                 unsigned char *buf;
1261
1262                 /* Sanity check */
1263                 if (len > 4096) {
1264                         printk(KERN_WARNING "%s: Scan results too large (%d bytes)\n",
1265                                dev->name, len);
1266                         break;
1267                 }
1268
1269                 /* We are a strict producer. If the previous scan results
1270                  * have not been consumed, we just have to drop this
1271                  * frame. We can't remove the previous results ourselves,
1272                  * that would be *very* racy... Jean II */
1273                 if (priv->scan_result != NULL) {
1274                         printk(KERN_WARNING "%s: Previous scan results not consumed, dropping info frame.\n", dev->name);
1275                         break;
1276                 }
1277
1278                 /* Allocate buffer for results */
1279                 buf = kmalloc(len, GFP_ATOMIC);
1280                 if (buf == NULL)
1281                         /* No memory, so can't printk()... */
1282                         break;
1283
1284                 /* Read scan data */
1285                 err = hermes_bap_pread(hw, IRQ_BAP, (void *) buf, len,
1286                                        infofid, sizeof(info));
1287                 if (err)
1288                         break;
1289
1290 #ifdef ORINOCO_DEBUG
1291                 {
1292                         int     i;
1293                         printk(KERN_DEBUG "Scan result [%02X", buf[0]);
1294                         for(i = 1; i < (len * 2); i++)
1295                                 printk(":%02X", buf[i]);
1296                         printk("]\n");
1297                 }
1298 #endif  /* ORINOCO_DEBUG */
1299
1300                 /* Allow the clients to access the results */
1301                 priv->scan_len = len;
1302                 priv->scan_result = buf;
1303
1304                 /* Send an empty event to user space.
1305                  * We don't send the received data on the event because
1306                  * it would require us to do complex transcoding, and
1307                  * we want to minimise the work done in the irq handler
1308                  * Use a request to extract the data - Jean II */
1309                 wrqu.data.length = 0;
1310                 wrqu.data.flags = 0;
1311                 wireless_send_event(dev, SIOCGIWSCAN, &wrqu, NULL);
1312         }
1313         break;
1314         case HERMES_INQ_SEC_STAT_AGERE:
1315                 /* Security status (Agere specific) */
1316                 /* Ignore this frame for now */
1317                 if (priv->firmware_type == FIRMWARE_TYPE_AGERE)
1318                         break;
1319                 /* fall through */
1320         default:
1321                 printk(KERN_DEBUG "%s: Unknown information frame received: "
1322                        "type 0x%04x, length %d\n", dev->name, type, len);
1323                 /* We don't actually do anything about it */
1324                 break;
1325         }
1326 }
1327
1328 static void __orinoco_ev_infdrop(struct net_device *dev, hermes_t *hw)
1329 {
1330         if (net_ratelimit())
1331                 printk(KERN_DEBUG "%s: Information frame lost.\n", dev->name);
1332 }
1333
1334 /********************************************************************/
1335 /* Internal hardware control routines                               */
1336 /********************************************************************/
1337
1338 int __orinoco_up(struct net_device *dev)
1339 {
1340         struct orinoco_private *priv = netdev_priv(dev);
1341         struct hermes *hw = &priv->hw;
1342         int err;
1343
1344         netif_carrier_off(dev); /* just to make sure */
1345
1346         err = __orinoco_program_rids(dev);
1347         if (err) {
1348                 printk(KERN_ERR "%s: Error %d configuring card\n",
1349                        dev->name, err);
1350                 return err;
1351         }
1352
1353         /* Fire things up again */
1354         hermes_set_irqmask(hw, ORINOCO_INTEN);
1355         err = hermes_enable_port(hw, 0);
1356         if (err) {
1357                 printk(KERN_ERR "%s: Error %d enabling MAC port\n",
1358                        dev->name, err);
1359                 return err;
1360         }
1361
1362         netif_start_queue(dev);
1363
1364         return 0;
1365 }
1366
1367 int __orinoco_down(struct net_device *dev)
1368 {
1369         struct orinoco_private *priv = netdev_priv(dev);
1370         struct hermes *hw = &priv->hw;
1371         int err;
1372
1373         netif_stop_queue(dev);
1374
1375         if (! priv->hw_unavailable) {
1376                 if (! priv->broken_disableport) {
1377                         err = hermes_disable_port(hw, 0);
1378                         if (err) {
1379                                 /* Some firmwares (e.g. Intersil 1.3.x) seem
1380                                  * to have problems disabling the port, oh
1381                                  * well, too bad. */
1382                                 printk(KERN_WARNING "%s: Error %d disabling MAC port\n",
1383                                        dev->name, err);
1384                                 priv->broken_disableport = 1;
1385                         }
1386                 }
1387                 hermes_set_irqmask(hw, 0);
1388                 hermes_write_regn(hw, EVACK, 0xffff);
1389         }
1390         
1391         /* firmware will have to reassociate */
1392         netif_carrier_off(dev);
1393         priv->last_linkstatus = 0xffff;
1394
1395         return 0;
1396 }
1397
1398 int orinoco_reinit_firmware(struct net_device *dev)
1399 {
1400         struct orinoco_private *priv = netdev_priv(dev);
1401         struct hermes *hw = &priv->hw;
1402         int err;
1403
1404         err = hermes_init(hw);
1405         if (err)
1406                 return err;
1407
1408         err = hermes_allocate(hw, priv->nicbuf_size, &priv->txfid);
1409         if (err == -EIO && priv->nicbuf_size > TX_NICBUF_SIZE_BUG) {
1410                 /* Try workaround for old Symbol firmware bug */
1411                 printk(KERN_WARNING "%s: firmware ALLOC bug detected "
1412                        "(old Symbol firmware?). Trying to work around... ",
1413                        dev->name);
1414                 
1415                 priv->nicbuf_size = TX_NICBUF_SIZE_BUG;
1416                 err = hermes_allocate(hw, priv->nicbuf_size, &priv->txfid);
1417                 if (err)
1418                         printk("failed!\n");
1419                 else
1420                         printk("ok.\n");
1421         }
1422
1423         return err;
1424 }
1425
1426 static int __orinoco_hw_set_bitrate(struct orinoco_private *priv)
1427 {
1428         hermes_t *hw = &priv->hw;
1429         int err = 0;
1430
1431         if (priv->bitratemode >= BITRATE_TABLE_SIZE) {
1432                 printk(KERN_ERR "%s: BUG: Invalid bitrate mode %d\n",
1433                        priv->ndev->name, priv->bitratemode);
1434                 return -EINVAL;
1435         }
1436
1437         switch (priv->firmware_type) {
1438         case FIRMWARE_TYPE_AGERE:
1439                 err = hermes_write_wordrec(hw, USER_BAP,
1440                                            HERMES_RID_CNFTXRATECONTROL,
1441                                            bitrate_table[priv->bitratemode].agere_txratectrl);
1442                 break;
1443         case FIRMWARE_TYPE_INTERSIL:
1444         case FIRMWARE_TYPE_SYMBOL:
1445                 err = hermes_write_wordrec(hw, USER_BAP,
1446                                            HERMES_RID_CNFTXRATECONTROL,
1447                                            bitrate_table[priv->bitratemode].intersil_txratectrl);
1448                 break;
1449         default:
1450                 BUG();
1451         }
1452
1453         return err;
1454 }
1455
1456 /* Set fixed AP address */
1457 static int __orinoco_hw_set_wap(struct orinoco_private *priv)
1458 {
1459         int roaming_flag;
1460         int err = 0;
1461         hermes_t *hw = &priv->hw;
1462
1463         switch (priv->firmware_type) {
1464         case FIRMWARE_TYPE_AGERE:
1465                 /* not supported */
1466                 break;
1467         case FIRMWARE_TYPE_INTERSIL:
1468                 if (priv->bssid_fixed)
1469                         roaming_flag = 2;
1470                 else
1471                         roaming_flag = 1;
1472
1473                 err = hermes_write_wordrec(hw, USER_BAP,
1474                                            HERMES_RID_CNFROAMINGMODE,
1475                                            roaming_flag);
1476                 break;
1477         case FIRMWARE_TYPE_SYMBOL:
1478                 err = HERMES_WRITE_RECORD(hw, USER_BAP,
1479                                           HERMES_RID_CNFMANDATORYBSSID_SYMBOL,
1480                                           &priv->desired_bssid);
1481                 break;
1482         }
1483         return err;
1484 }
1485
1486 /* Change the WEP keys and/or the current keys.  Can be called
1487  * either from __orinoco_hw_setup_wep() or directly from
1488  * orinoco_ioctl_setiwencode().  In the later case the association
1489  * with the AP is not broken (if the firmware can handle it),
1490  * which is needed for 802.1x implementations. */
1491 static int __orinoco_hw_setup_wepkeys(struct orinoco_private *priv)
1492 {
1493         hermes_t *hw = &priv->hw;
1494         int err = 0;
1495
1496         switch (priv->firmware_type) {
1497         case FIRMWARE_TYPE_AGERE:
1498                 err = HERMES_WRITE_RECORD(hw, USER_BAP,
1499                                           HERMES_RID_CNFWEPKEYS_AGERE,
1500                                           &priv->keys);
1501                 if (err)
1502                         return err;
1503                 err = hermes_write_wordrec(hw, USER_BAP,
1504                                            HERMES_RID_CNFTXKEY_AGERE,
1505                                            priv->tx_key);
1506                 if (err)
1507                         return err;
1508                 break;
1509         case FIRMWARE_TYPE_INTERSIL:
1510         case FIRMWARE_TYPE_SYMBOL:
1511                 {
1512                         int keylen;
1513                         int i;
1514
1515                         /* Force uniform key length to work around firmware bugs */
1516                         keylen = le16_to_cpu(priv->keys[priv->tx_key].len);
1517                         
1518                         if (keylen > LARGE_KEY_SIZE) {
1519                                 printk(KERN_ERR "%s: BUG: Key %d has oversize length %d.\n",
1520                                        priv->ndev->name, priv->tx_key, keylen);
1521                                 return -E2BIG;
1522                         }
1523
1524                         /* Write all 4 keys */
1525                         for(i = 0; i < ORINOCO_MAX_KEYS; i++) {
1526                                 err = hermes_write_ltv(hw, USER_BAP,
1527                                                        HERMES_RID_CNFDEFAULTKEY0 + i,
1528                                                        HERMES_BYTES_TO_RECLEN(keylen),
1529                                                        priv->keys[i].data);
1530                                 if (err)
1531                                         return err;
1532                         }
1533
1534                         /* Write the index of the key used in transmission */
1535                         err = hermes_write_wordrec(hw, USER_BAP,
1536                                                    HERMES_RID_CNFWEPDEFAULTKEYID,
1537                                                    priv->tx_key);
1538                         if (err)
1539                                 return err;
1540                 }
1541                 break;
1542         }
1543
1544         return 0;
1545 }
1546
1547 static int __orinoco_hw_setup_wep(struct orinoco_private *priv)
1548 {
1549         hermes_t *hw = &priv->hw;
1550         int err = 0;
1551         int master_wep_flag;
1552         int auth_flag;
1553
1554         if (priv->wep_on)
1555                 __orinoco_hw_setup_wepkeys(priv);
1556
1557         if (priv->wep_restrict)
1558                 auth_flag = HERMES_AUTH_SHARED_KEY;
1559         else
1560                 auth_flag = HERMES_AUTH_OPEN;
1561
1562         switch (priv->firmware_type) {
1563         case FIRMWARE_TYPE_AGERE: /* Agere style WEP */
1564                 if (priv->wep_on) {
1565                         /* Enable the shared-key authentication. */
1566                         err = hermes_write_wordrec(hw, USER_BAP,
1567                                                    HERMES_RID_CNFAUTHENTICATION_AGERE,
1568                                                    auth_flag);
1569                 }
1570                 err = hermes_write_wordrec(hw, USER_BAP,
1571                                            HERMES_RID_CNFWEPENABLED_AGERE,
1572                                            priv->wep_on);
1573                 if (err)
1574                         return err;
1575                 break;
1576
1577         case FIRMWARE_TYPE_INTERSIL: /* Intersil style WEP */
1578         case FIRMWARE_TYPE_SYMBOL: /* Symbol style WEP */
1579                 if (priv->wep_on) {
1580                         if (priv->wep_restrict ||
1581                             (priv->firmware_type == FIRMWARE_TYPE_SYMBOL))
1582                                 master_wep_flag = HERMES_WEP_PRIVACY_INVOKED |
1583                                                   HERMES_WEP_EXCL_UNENCRYPTED;
1584                         else
1585                                 master_wep_flag = HERMES_WEP_PRIVACY_INVOKED;
1586
1587                         err = hermes_write_wordrec(hw, USER_BAP,
1588                                                    HERMES_RID_CNFAUTHENTICATION,
1589                                                    auth_flag);
1590                         if (err)
1591                                 return err;
1592                 } else
1593                         master_wep_flag = 0;
1594
1595                 if (priv->iw_mode == IW_MODE_MONITOR)
1596                         master_wep_flag |= HERMES_WEP_HOST_DECRYPT;
1597
1598                 /* Master WEP setting : on/off */
1599                 err = hermes_write_wordrec(hw, USER_BAP,
1600                                            HERMES_RID_CNFWEPFLAGS_INTERSIL,
1601                                            master_wep_flag);
1602                 if (err)
1603                         return err;     
1604
1605                 break;
1606         }
1607
1608         return 0;
1609 }
1610
1611 static int __orinoco_program_rids(struct net_device *dev)
1612 {
1613         struct orinoco_private *priv = netdev_priv(dev);
1614         hermes_t *hw = &priv->hw;
1615         int err;
1616         struct hermes_idstring idbuf;
1617
1618         /* Set the MAC address */
1619         err = hermes_write_ltv(hw, USER_BAP, HERMES_RID_CNFOWNMACADDR,
1620                                HERMES_BYTES_TO_RECLEN(ETH_ALEN), dev->dev_addr);
1621         if (err) {
1622                 printk(KERN_ERR "%s: Error %d setting MAC address\n",
1623                        dev->name, err);
1624                 return err;
1625         }
1626
1627         /* Set up the link mode */
1628         err = hermes_write_wordrec(hw, USER_BAP, HERMES_RID_CNFPORTTYPE,
1629                                    priv->port_type);
1630         if (err) {
1631                 printk(KERN_ERR "%s: Error %d setting port type\n",
1632                        dev->name, err);
1633                 return err;
1634         }
1635         /* Set the channel/frequency */
1636         if (priv->channel != 0 && priv->iw_mode != IW_MODE_INFRA) {
1637                 err = hermes_write_wordrec(hw, USER_BAP,
1638                                            HERMES_RID_CNFOWNCHANNEL,
1639                                            priv->channel);
1640                 if (err) {
1641                         printk(KERN_ERR "%s: Error %d setting channel %d\n",
1642                                dev->name, err, priv->channel);
1643                         return err;
1644                 }
1645         }
1646
1647         if (priv->has_ibss) {
1648                 u16 createibss;
1649
1650                 if ((strlen(priv->desired_essid) == 0) && (priv->createibss)) {
1651                         printk(KERN_WARNING "%s: This firmware requires an "
1652                                "ESSID in IBSS-Ad-Hoc mode.\n", dev->name);
1653                         /* With wvlan_cs, in this case, we would crash.
1654                          * hopefully, this driver will behave better...
1655                          * Jean II */
1656                         createibss = 0;
1657                 } else {
1658                         createibss = priv->createibss;
1659                 }
1660                 
1661                 err = hermes_write_wordrec(hw, USER_BAP,
1662                                            HERMES_RID_CNFCREATEIBSS,
1663                                            createibss);
1664                 if (err) {
1665                         printk(KERN_ERR "%s: Error %d setting CREATEIBSS\n",
1666                                dev->name, err);
1667                         return err;
1668                 }
1669         }
1670
1671         /* Set the desired BSSID */
1672         err = __orinoco_hw_set_wap(priv);
1673         if (err) {
1674                 printk(KERN_ERR "%s: Error %d setting AP address\n",
1675                        dev->name, err);
1676                 return err;
1677         }
1678         /* Set the desired ESSID */
1679         idbuf.len = cpu_to_le16(strlen(priv->desired_essid));
1680         memcpy(&idbuf.val, priv->desired_essid, sizeof(idbuf.val));
1681         /* WinXP wants partner to configure OWNSSID even in IBSS mode. (jimc) */
1682         err = hermes_write_ltv(hw, USER_BAP, HERMES_RID_CNFOWNSSID,
1683                                HERMES_BYTES_TO_RECLEN(strlen(priv->desired_essid)+2),
1684                                &idbuf);
1685         if (err) {
1686                 printk(KERN_ERR "%s: Error %d setting OWNSSID\n",
1687                        dev->name, err);
1688                 return err;
1689         }
1690         err = hermes_write_ltv(hw, USER_BAP, HERMES_RID_CNFDESIREDSSID,
1691                                HERMES_BYTES_TO_RECLEN(strlen(priv->desired_essid)+2),
1692                                &idbuf);
1693         if (err) {
1694                 printk(KERN_ERR "%s: Error %d setting DESIREDSSID\n",
1695                        dev->name, err);
1696                 return err;
1697         }
1698
1699         /* Set the station name */
1700         idbuf.len = cpu_to_le16(strlen(priv->nick));
1701         memcpy(&idbuf.val, priv->nick, sizeof(idbuf.val));
1702         err = hermes_write_ltv(hw, USER_BAP, HERMES_RID_CNFOWNNAME,
1703                                HERMES_BYTES_TO_RECLEN(strlen(priv->nick)+2),
1704                                &idbuf);
1705         if (err) {
1706                 printk(KERN_ERR "%s: Error %d setting nickname\n",
1707                        dev->name, err);
1708                 return err;
1709         }
1710
1711         /* Set AP density */
1712         if (priv->has_sensitivity) {
1713                 err = hermes_write_wordrec(hw, USER_BAP,
1714                                            HERMES_RID_CNFSYSTEMSCALE,
1715                                            priv->ap_density);
1716                 if (err) {
1717                         printk(KERN_WARNING "%s: Error %d setting SYSTEMSCALE.  "
1718                                "Disabling sensitivity control\n",
1719                                dev->name, err);
1720
1721                         priv->has_sensitivity = 0;
1722                 }
1723         }
1724
1725         /* Set RTS threshold */
1726         err = hermes_write_wordrec(hw, USER_BAP, HERMES_RID_CNFRTSTHRESHOLD,
1727                                    priv->rts_thresh);
1728         if (err) {
1729                 printk(KERN_ERR "%s: Error %d setting RTS threshold\n",
1730                        dev->name, err);
1731                 return err;
1732         }
1733
1734         /* Set fragmentation threshold or MWO robustness */
1735         if (priv->has_mwo)
1736                 err = hermes_write_wordrec(hw, USER_BAP,
1737                                            HERMES_RID_CNFMWOROBUST_AGERE,
1738                                            priv->mwo_robust);
1739         else
1740                 err = hermes_write_wordrec(hw, USER_BAP,
1741                                            HERMES_RID_CNFFRAGMENTATIONTHRESHOLD,
1742                                            priv->frag_thresh);
1743         if (err) {
1744                 printk(KERN_ERR "%s: Error %d setting fragmentation\n",
1745                        dev->name, err);
1746                 return err;
1747         }
1748
1749         /* Set bitrate */
1750         err = __orinoco_hw_set_bitrate(priv);
1751         if (err) {
1752                 printk(KERN_ERR "%s: Error %d setting bitrate\n",
1753                        dev->name, err);
1754                 return err;
1755         }
1756
1757         /* Set power management */
1758         if (priv->has_pm) {
1759                 err = hermes_write_wordrec(hw, USER_BAP,
1760                                            HERMES_RID_CNFPMENABLED,
1761                                            priv->pm_on);
1762                 if (err) {
1763                         printk(KERN_ERR "%s: Error %d setting up PM\n",
1764                                dev->name, err);
1765                         return err;
1766                 }
1767
1768                 err = hermes_write_wordrec(hw, USER_BAP,
1769                                            HERMES_RID_CNFMULTICASTRECEIVE,
1770                                            priv->pm_mcast);
1771                 if (err) {
1772                         printk(KERN_ERR "%s: Error %d setting up PM\n",
1773                                dev->name, err);
1774                         return err;
1775                 }
1776                 err = hermes_write_wordrec(hw, USER_BAP,
1777                                            HERMES_RID_CNFMAXSLEEPDURATION,
1778                                            priv->pm_period);
1779                 if (err) {
1780                         printk(KERN_ERR "%s: Error %d setting up PM\n",
1781                                dev->name, err);
1782                         return err;
1783                 }
1784                 err = hermes_write_wordrec(hw, USER_BAP,
1785                                            HERMES_RID_CNFPMHOLDOVERDURATION,
1786                                            priv->pm_timeout);
1787                 if (err) {
1788                         printk(KERN_ERR "%s: Error %d setting up PM\n",
1789                                dev->name, err);
1790                         return err;
1791                 }
1792         }
1793
1794         /* Set preamble - only for Symbol so far... */
1795         if (priv->has_preamble) {
1796                 err = hermes_write_wordrec(hw, USER_BAP,
1797                                            HERMES_RID_CNFPREAMBLE_SYMBOL,
1798                                            priv->preamble);
1799                 if (err) {
1800                         printk(KERN_ERR "%s: Error %d setting preamble\n",
1801                                dev->name, err);
1802                         return err;
1803                 }
1804         }
1805
1806         /* Set up encryption */
1807         if (priv->has_wep) {
1808                 err = __orinoco_hw_setup_wep(priv);
1809                 if (err) {
1810                         printk(KERN_ERR "%s: Error %d activating WEP\n",
1811                                dev->name, err);
1812                         return err;
1813                 }
1814         }
1815
1816         if (priv->iw_mode == IW_MODE_MONITOR) {
1817                 /* Enable monitor mode */
1818                 dev->type = ARPHRD_IEEE80211;
1819                 err = hermes_docmd_wait(hw, HERMES_CMD_TEST | 
1820                                             HERMES_TEST_MONITOR, 0, NULL);
1821         } else {
1822                 /* Disable monitor mode */
1823                 dev->type = ARPHRD_ETHER;
1824                 err = hermes_docmd_wait(hw, HERMES_CMD_TEST |
1825                                             HERMES_TEST_STOP, 0, NULL);
1826         }
1827         if (err)
1828                 return err;
1829
1830         /* Set promiscuity / multicast*/
1831         priv->promiscuous = 0;
1832         priv->mc_count = 0;
1833         __orinoco_set_multicast_list(dev); /* FIXME: what about the xmit_lock */
1834
1835         return 0;
1836 }
1837
1838 /* FIXME: return int? */
1839 static void
1840 __orinoco_set_multicast_list(struct net_device *dev)
1841 {
1842         struct orinoco_private *priv = netdev_priv(dev);
1843         hermes_t *hw = &priv->hw;
1844         int err = 0;
1845         int promisc, mc_count;
1846
1847         /* The Hermes doesn't seem to have an allmulti mode, so we go
1848          * into promiscuous mode and let the upper levels deal. */
1849         if ( (dev->flags & IFF_PROMISC) || (dev->flags & IFF_ALLMULTI) ||
1850              (dev->mc_count > MAX_MULTICAST(priv)) ) {
1851                 promisc = 1;
1852                 mc_count = 0;
1853         } else {
1854                 promisc = 0;
1855                 mc_count = dev->mc_count;
1856         }
1857
1858         if (promisc != priv->promiscuous) {
1859                 err = hermes_write_wordrec(hw, USER_BAP,
1860                                            HERMES_RID_CNFPROMISCUOUSMODE,
1861                                            promisc);
1862                 if (err) {
1863                         printk(KERN_ERR "%s: Error %d setting PROMISCUOUSMODE to 1.\n",
1864                                dev->name, err);
1865                 } else 
1866                         priv->promiscuous = promisc;
1867         }
1868
1869         if (! promisc && (mc_count || priv->mc_count) ) {
1870                 struct dev_mc_list *p = dev->mc_list;
1871                 struct hermes_multicast mclist;
1872                 int i;
1873
1874                 for (i = 0; i < mc_count; i++) {
1875                         /* paranoia: is list shorter than mc_count? */
1876                         BUG_ON(! p);
1877                         /* paranoia: bad address size in list? */
1878                         BUG_ON(p->dmi_addrlen != ETH_ALEN);
1879                         
1880                         memcpy(mclist.addr[i], p->dmi_addr, ETH_ALEN);
1881                         p = p->next;
1882                 }
1883                 
1884                 if (p)
1885                         printk(KERN_WARNING "%s: Multicast list is "
1886                                "longer than mc_count\n", dev->name);
1887
1888                 err = hermes_write_ltv(hw, USER_BAP, HERMES_RID_CNFGROUPADDRESSES,
1889                                        HERMES_BYTES_TO_RECLEN(priv->mc_count * ETH_ALEN),
1890                                        &mclist);
1891                 if (err)
1892                         printk(KERN_ERR "%s: Error %d setting multicast list.\n",
1893                                dev->name, err);
1894                 else
1895                         priv->mc_count = mc_count;
1896         }
1897
1898         /* Since we can set the promiscuous flag when it wasn't asked
1899            for, make sure the net_device knows about it. */
1900         if (priv->promiscuous)
1901                 dev->flags |= IFF_PROMISC;
1902         else
1903                 dev->flags &= ~IFF_PROMISC;
1904 }
1905
1906 /* This must be called from user context, without locks held - use
1907  * schedule_work() */
1908 static void orinoco_reset(struct net_device *dev)
1909 {
1910         struct orinoco_private *priv = netdev_priv(dev);
1911         struct hermes *hw = &priv->hw;
1912         int err;
1913         unsigned long flags;
1914
1915         if (orinoco_lock(priv, &flags) != 0)
1916                 /* When the hardware becomes available again, whatever
1917                  * detects that is responsible for re-initializing
1918                  * it. So no need for anything further */
1919                 return;
1920
1921         netif_stop_queue(dev);
1922
1923         /* Shut off interrupts.  Depending on what state the hardware
1924          * is in, this might not work, but we'll try anyway */
1925         hermes_set_irqmask(hw, 0);
1926         hermes_write_regn(hw, EVACK, 0xffff);
1927
1928         priv->hw_unavailable++;
1929         priv->last_linkstatus = 0xffff; /* firmware will have to reassociate */
1930         netif_carrier_off(dev);
1931
1932         orinoco_unlock(priv, &flags);
1933
1934         /* Scanning support: Cleanup of driver struct */
1935         kfree(priv->scan_result);
1936         priv->scan_result = NULL;
1937         priv->scan_inprogress = 0;
1938
1939         if (priv->hard_reset) {
1940                 err = (*priv->hard_reset)(priv);
1941                 if (err) {
1942                         printk(KERN_ERR "%s: orinoco_reset: Error %d "
1943                                "performing hard reset\n", dev->name, err);
1944                         goto disable;
1945                 }
1946         }
1947
1948         err = orinoco_reinit_firmware(dev);
1949         if (err) {
1950                 printk(KERN_ERR "%s: orinoco_reset: Error %d re-initializing firmware\n",
1951                        dev->name, err);
1952                 goto disable;
1953         }
1954
1955         spin_lock_irq(&priv->lock); /* This has to be called from user context */
1956
1957         priv->hw_unavailable--;
1958
1959         /* priv->open or priv->hw_unavailable might have changed while
1960          * we dropped the lock */
1961         if (priv->open && (! priv->hw_unavailable)) {
1962                 err = __orinoco_up(dev);
1963                 if (err) {
1964                         printk(KERN_ERR "%s: orinoco_reset: Error %d reenabling card\n",
1965                                dev->name, err);
1966                 } else
1967                         dev->trans_start = jiffies;
1968         }
1969
1970         spin_unlock_irq(&priv->lock);
1971
1972         return;
1973  disable:
1974         hermes_set_irqmask(hw, 0);
1975         netif_device_detach(dev);
1976         printk(KERN_ERR "%s: Device has been disabled!\n", dev->name);
1977 }
1978
1979 /********************************************************************/
1980 /* Interrupt handler                                                */
1981 /********************************************************************/
1982
1983 static void __orinoco_ev_tick(struct net_device *dev, hermes_t *hw)
1984 {
1985         printk(KERN_DEBUG "%s: TICK\n", dev->name);
1986 }
1987
1988 static void __orinoco_ev_wterr(struct net_device *dev, hermes_t *hw)
1989 {
1990         /* This seems to happen a fair bit under load, but ignoring it
1991            seems to work fine...*/
1992         printk(KERN_DEBUG "%s: MAC controller error (WTERR). Ignoring.\n",
1993                dev->name);
1994 }
1995
1996 irqreturn_t orinoco_interrupt(int irq, void *dev_id, struct pt_regs *regs)
1997 {
1998         struct net_device *dev = (struct net_device *)dev_id;
1999         struct orinoco_private *priv = netdev_priv(dev);
2000         hermes_t *hw = &priv->hw;
2001         int count = MAX_IRQLOOPS_PER_IRQ;
2002         u16 evstat, events;
2003         /* These are used to detect a runaway interrupt situation */
2004         /* If we get more than MAX_IRQLOOPS_PER_JIFFY iterations in a jiffy,
2005          * we panic and shut down the hardware */
2006         static int last_irq_jiffy = 0; /* jiffies value the last time
2007                                         * we were called */
2008         static int loops_this_jiffy = 0;
2009         unsigned long flags;
2010
2011         if (orinoco_lock(priv, &flags) != 0) {
2012                 /* If hw is unavailable - we don't know if the irq was
2013                  * for us or not */
2014                 return IRQ_HANDLED;
2015         }
2016
2017         evstat = hermes_read_regn(hw, EVSTAT);
2018         events = evstat & hw->inten;
2019         if (! events) {
2020                 orinoco_unlock(priv, &flags);
2021                 return IRQ_NONE;
2022         }
2023         
2024         if (jiffies != last_irq_jiffy)
2025                 loops_this_jiffy = 0;
2026         last_irq_jiffy = jiffies;
2027
2028         while (events && count--) {
2029                 if (++loops_this_jiffy > MAX_IRQLOOPS_PER_JIFFY) {
2030                         printk(KERN_WARNING "%s: IRQ handler is looping too "
2031                                "much! Resetting.\n", dev->name);
2032                         /* Disable interrupts for now */
2033                         hermes_set_irqmask(hw, 0);
2034                         schedule_work(&priv->reset_work);
2035                         break;
2036                 }
2037
2038                 /* Check the card hasn't been removed */
2039                 if (! hermes_present(hw)) {
2040                         DEBUG(0, "orinoco_interrupt(): card removed\n");
2041                         break;
2042                 }
2043
2044                 if (events & HERMES_EV_TICK)
2045                         __orinoco_ev_tick(dev, hw);
2046                 if (events & HERMES_EV_WTERR)
2047                         __orinoco_ev_wterr(dev, hw);
2048                 if (events & HERMES_EV_INFDROP)
2049                         __orinoco_ev_infdrop(dev, hw);
2050                 if (events & HERMES_EV_INFO)
2051                         __orinoco_ev_info(dev, hw);
2052                 if (events & HERMES_EV_RX)
2053                         __orinoco_ev_rx(dev, hw);
2054                 if (events & HERMES_EV_TXEXC)
2055                         __orinoco_ev_txexc(dev, hw);
2056                 if (events & HERMES_EV_TX)
2057                         __orinoco_ev_tx(dev, hw);
2058                 if (events & HERMES_EV_ALLOC)
2059                         __orinoco_ev_alloc(dev, hw);
2060                 
2061                 hermes_write_regn(hw, EVACK, evstat);
2062
2063                 evstat = hermes_read_regn(hw, EVSTAT);
2064                 events = evstat & hw->inten;
2065         };
2066
2067         orinoco_unlock(priv, &flags);
2068         return IRQ_HANDLED;
2069 }
2070
2071 /********************************************************************/
2072 /* Initialization                                                   */
2073 /********************************************************************/
2074
2075 struct comp_id {
2076         u16 id, variant, major, minor;
2077 } __attribute__ ((packed));
2078
2079 static inline fwtype_t determine_firmware_type(struct comp_id *nic_id)
2080 {
2081         if (nic_id->id < 0x8000)
2082                 return FIRMWARE_TYPE_AGERE;
2083         else if (nic_id->id == 0x8000 && nic_id->major == 0)
2084                 return FIRMWARE_TYPE_SYMBOL;
2085         else
2086                 return FIRMWARE_TYPE_INTERSIL;
2087 }
2088
2089 /* Set priv->firmware type, determine firmware properties */
2090 static int determine_firmware(struct net_device *dev)
2091 {
2092         struct orinoco_private *priv = netdev_priv(dev);
2093         hermes_t *hw = &priv->hw;
2094         int err;
2095         struct comp_id nic_id, sta_id;
2096         unsigned int firmver;
2097         char tmp[SYMBOL_MAX_VER_LEN+1];
2098
2099         /* Get the hardware version */
2100         err = HERMES_READ_RECORD(hw, USER_BAP, HERMES_RID_NICID, &nic_id);
2101         if (err) {
2102                 printk(KERN_ERR "%s: Cannot read hardware identity: error %d\n",
2103                        dev->name, err);
2104                 return err;
2105         }
2106
2107         le16_to_cpus(&nic_id.id);
2108         le16_to_cpus(&nic_id.variant);
2109         le16_to_cpus(&nic_id.major);
2110         le16_to_cpus(&nic_id.minor);
2111         printk(KERN_DEBUG "%s: Hardware identity %04x:%04x:%04x:%04x\n",
2112                dev->name, nic_id.id, nic_id.variant,
2113                nic_id.major, nic_id.minor);
2114
2115         priv->firmware_type = determine_firmware_type(&nic_id);
2116
2117         /* Get the firmware version */
2118         err = HERMES_READ_RECORD(hw, USER_BAP, HERMES_RID_STAID, &sta_id);
2119         if (err) {
2120                 printk(KERN_ERR "%s: Cannot read station identity: error %d\n",
2121                        dev->name, err);
2122                 return err;
2123         }
2124
2125         le16_to_cpus(&sta_id.id);
2126         le16_to_cpus(&sta_id.variant);
2127         le16_to_cpus(&sta_id.major);
2128         le16_to_cpus(&sta_id.minor);
2129         printk(KERN_DEBUG "%s: Station identity  %04x:%04x:%04x:%04x\n",
2130                dev->name, sta_id.id, sta_id.variant,
2131                sta_id.major, sta_id.minor);
2132
2133         switch (sta_id.id) {
2134         case 0x15:
2135                 printk(KERN_ERR "%s: Primary firmware is active\n",
2136                        dev->name);
2137                 return -ENODEV;
2138         case 0x14b:
2139                 printk(KERN_ERR "%s: Tertiary firmware is active\n",
2140                        dev->name);
2141                 return -ENODEV;
2142         case 0x1f:      /* Intersil, Agere, Symbol Spectrum24 */
2143         case 0x21:      /* Symbol Spectrum24 Trilogy */
2144                 break;
2145         default:
2146                 printk(KERN_NOTICE "%s: Unknown station ID, please report\n",
2147                        dev->name);
2148                 break;
2149         }
2150
2151         /* Default capabilities */
2152         priv->has_sensitivity = 1;
2153         priv->has_mwo = 0;
2154         priv->has_preamble = 0;
2155         priv->has_port3 = 1;
2156         priv->has_ibss = 1;
2157         priv->has_wep = 0;
2158         priv->has_big_wep = 0;
2159
2160         /* Determine capabilities from the firmware version */
2161         switch (priv->firmware_type) {
2162         case FIRMWARE_TYPE_AGERE:
2163                 /* Lucent Wavelan IEEE, Lucent Orinoco, Cabletron RoamAbout,
2164                    ELSA, Melco, HP, IBM, Dell 1150, Compaq 110/210 */
2165                 snprintf(priv->fw_name, sizeof(priv->fw_name) - 1,
2166                          "Lucent/Agere %d.%02d", sta_id.major, sta_id.minor);
2167
2168                 firmver = ((unsigned long)sta_id.major << 16) | sta_id.minor;
2169
2170                 priv->has_ibss = (firmver >= 0x60006);
2171                 priv->has_wep = (firmver >= 0x40020);
2172                 priv->has_big_wep = 1; /* FIXME: this is wrong - how do we tell
2173                                           Gold cards from the others? */
2174                 priv->has_mwo = (firmver >= 0x60000);
2175                 priv->has_pm = (firmver >= 0x40020); /* Don't work in 7.52 ? */
2176                 priv->ibss_port = 1;
2177                 priv->has_hostscan = (firmver >= 0x8000a);
2178                 priv->broken_monitor = (firmver >= 0x80000);
2179
2180                 /* Tested with Agere firmware :
2181                  *      1.16 ; 4.08 ; 4.52 ; 6.04 ; 6.16 ; 7.28 => Jean II
2182                  * Tested CableTron firmware : 4.32 => Anton */
2183                 break;
2184         case FIRMWARE_TYPE_SYMBOL:
2185                 /* Symbol , 3Com AirConnect, Intel, Ericsson WLAN */
2186                 /* Intel MAC : 00:02:B3:* */
2187                 /* 3Com MAC : 00:50:DA:* */
2188                 memset(tmp, 0, sizeof(tmp));
2189                 /* Get the Symbol firmware version */
2190                 err = hermes_read_ltv(hw, USER_BAP,
2191                                       HERMES_RID_SECONDARYVERSION_SYMBOL,
2192                                       SYMBOL_MAX_VER_LEN, NULL, &tmp);
2193                 if (err) {
2194                         printk(KERN_WARNING
2195                                "%s: Error %d reading Symbol firmware info. Wildly guessing capabilities...\n",
2196                                dev->name, err);
2197                         firmver = 0;
2198                         tmp[0] = '\0';
2199                 } else {
2200                         /* The firmware revision is a string, the format is
2201                          * something like : "V2.20-01".
2202                          * Quick and dirty parsing... - Jean II
2203                          */
2204                         firmver = ((tmp[1] - '0') << 16) | ((tmp[3] - '0') << 12)
2205                                 | ((tmp[4] - '0') << 8) | ((tmp[6] - '0') << 4)
2206                                 | (tmp[7] - '0');
2207
2208                         tmp[SYMBOL_MAX_VER_LEN] = '\0';
2209                 }
2210
2211                 snprintf(priv->fw_name, sizeof(priv->fw_name) - 1,
2212                          "Symbol %s", tmp);
2213
2214                 priv->has_ibss = (firmver >= 0x20000);
2215                 priv->has_wep = (firmver >= 0x15012);
2216                 priv->has_big_wep = (firmver >= 0x20000);
2217                 priv->has_pm = (firmver >= 0x20000 && firmver < 0x22000) || 
2218                                (firmver >= 0x29000 && firmver < 0x30000) ||
2219                                firmver >= 0x31000;
2220                 priv->has_preamble = (firmver >= 0x20000);
2221                 priv->ibss_port = 4;
2222                 priv->broken_disableport = (firmver == 0x25013) ||
2223                                            (firmver >= 0x30000 && firmver <= 0x31000);
2224                 priv->has_hostscan = (firmver >= 0x31001) ||
2225                                      (firmver >= 0x29057 && firmver < 0x30000);
2226                 /* Tested with Intel firmware : 0x20015 => Jean II */
2227                 /* Tested with 3Com firmware : 0x15012 & 0x22001 => Jean II */
2228                 break;
2229         case FIRMWARE_TYPE_INTERSIL:
2230                 /* D-Link, Linksys, Adtron, ZoomAir, and many others...
2231                  * Samsung, Compaq 100/200 and Proxim are slightly
2232                  * different and less well tested */
2233                 /* D-Link MAC : 00:40:05:* */
2234                 /* Addtron MAC : 00:90:D1:* */
2235                 snprintf(priv->fw_name, sizeof(priv->fw_name) - 1,
2236                          "Intersil %d.%d.%d", sta_id.major, sta_id.minor,
2237                          sta_id.variant);
2238
2239                 firmver = ((unsigned long)sta_id.major << 16) |
2240                         ((unsigned long)sta_id.minor << 8) | sta_id.variant;
2241
2242                 priv->has_ibss = (firmver >= 0x000700); /* FIXME */
2243                 priv->has_big_wep = priv->has_wep = (firmver >= 0x000800);
2244                 priv->has_pm = (firmver >= 0x000700);
2245                 priv->has_hostscan = (firmver >= 0x010301);
2246
2247                 if (firmver >= 0x000800)
2248                         priv->ibss_port = 0;
2249                 else {
2250                         printk(KERN_NOTICE "%s: Intersil firmware earlier "
2251                                "than v0.8.x - several features not supported\n",
2252                                dev->name);
2253                         priv->ibss_port = 1;
2254                 }
2255                 break;
2256         }
2257         printk(KERN_DEBUG "%s: Firmware determined as %s\n", dev->name,
2258                priv->fw_name);
2259
2260         return 0;
2261 }
2262
2263 static int orinoco_init(struct net_device *dev)
2264 {
2265         struct orinoco_private *priv = netdev_priv(dev);
2266         hermes_t *hw = &priv->hw;
2267         int err = 0;
2268         struct hermes_idstring nickbuf;
2269         u16 reclen;
2270         int len;
2271
2272         TRACE_ENTER(dev->name);
2273
2274         /* No need to lock, the hw_unavailable flag is already set in
2275          * alloc_orinocodev() */
2276         priv->nicbuf_size = IEEE80211_FRAME_LEN + ETH_HLEN;
2277
2278         /* Initialize the firmware */
2279         err = orinoco_reinit_firmware(dev);
2280         if (err != 0) {
2281                 printk(KERN_ERR "%s: failed to initialize firmware (err = %d)\n",
2282                        dev->name, err);
2283                 goto out;
2284         }
2285
2286         err = determine_firmware(dev);
2287         if (err != 0) {
2288                 printk(KERN_ERR "%s: Incompatible firmware, aborting\n",
2289                        dev->name);
2290                 goto out;
2291         }
2292
2293         if (priv->has_port3)
2294                 printk(KERN_DEBUG "%s: Ad-hoc demo mode supported\n", dev->name);
2295         if (priv->has_ibss)
2296                 printk(KERN_DEBUG "%s: IEEE standard IBSS ad-hoc mode supported\n",
2297                        dev->name);
2298         if (priv->has_wep) {
2299                 printk(KERN_DEBUG "%s: WEP supported, ", dev->name);
2300                 if (priv->has_big_wep)
2301                         printk("104-bit key\n");
2302                 else
2303                         printk("40-bit key\n");
2304         }
2305
2306         /* Get the MAC address */
2307         err = hermes_read_ltv(hw, USER_BAP, HERMES_RID_CNFOWNMACADDR,
2308                               ETH_ALEN, NULL, dev->dev_addr);
2309         if (err) {
2310                 printk(KERN_WARNING "%s: failed to read MAC address!\n",
2311                        dev->name);
2312                 goto out;
2313         }
2314
2315         printk(KERN_DEBUG "%s: MAC address %02X:%02X:%02X:%02X:%02X:%02X\n",
2316                dev->name, dev->dev_addr[0], dev->dev_addr[1],
2317                dev->dev_addr[2], dev->dev_addr[3], dev->dev_addr[4],
2318                dev->dev_addr[5]);
2319
2320         /* Get the station name */
2321         err = hermes_read_ltv(hw, USER_BAP, HERMES_RID_CNFOWNNAME,
2322                               sizeof(nickbuf), &reclen, &nickbuf);
2323         if (err) {
2324                 printk(KERN_ERR "%s: failed to read station name\n",
2325                        dev->name);
2326                 goto out;
2327         }
2328         if (nickbuf.len)
2329                 len = min(IW_ESSID_MAX_SIZE, (int)le16_to_cpu(nickbuf.len));
2330         else
2331                 len = min(IW_ESSID_MAX_SIZE, 2 * reclen);
2332         memcpy(priv->nick, &nickbuf.val, len);
2333         priv->nick[len] = '\0';
2334
2335         printk(KERN_DEBUG "%s: Station name \"%s\"\n", dev->name, priv->nick);
2336
2337         /* Get allowed channels */
2338         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CHANNELLIST,
2339                                   &priv->channel_mask);
2340         if (err) {
2341                 printk(KERN_ERR "%s: failed to read channel list!\n",
2342                        dev->name);
2343                 goto out;
2344         }
2345
2346         /* Get initial AP density */
2347         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CNFSYSTEMSCALE,
2348                                   &priv->ap_density);
2349         if (err || priv->ap_density < 1 || priv->ap_density > 3) {
2350                 priv->has_sensitivity = 0;
2351         }
2352
2353         /* Get initial RTS threshold */
2354         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CNFRTSTHRESHOLD,
2355                                   &priv->rts_thresh);
2356         if (err) {
2357                 printk(KERN_ERR "%s: failed to read RTS threshold!\n",
2358                        dev->name);
2359                 goto out;
2360         }
2361
2362         /* Get initial fragmentation settings */
2363         if (priv->has_mwo)
2364                 err = hermes_read_wordrec(hw, USER_BAP,
2365                                           HERMES_RID_CNFMWOROBUST_AGERE,
2366                                           &priv->mwo_robust);
2367         else
2368                 err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CNFFRAGMENTATIONTHRESHOLD,
2369                                           &priv->frag_thresh);
2370         if (err) {
2371                 printk(KERN_ERR "%s: failed to read fragmentation settings!\n",
2372                        dev->name);
2373                 goto out;
2374         }
2375
2376         /* Power management setup */
2377         if (priv->has_pm) {
2378                 priv->pm_on = 0;
2379                 priv->pm_mcast = 1;
2380                 err = hermes_read_wordrec(hw, USER_BAP,
2381                                           HERMES_RID_CNFMAXSLEEPDURATION,
2382                                           &priv->pm_period);
2383                 if (err) {
2384                         printk(KERN_ERR "%s: failed to read power management period!\n",
2385                                dev->name);
2386                         goto out;
2387                 }
2388                 err = hermes_read_wordrec(hw, USER_BAP,
2389                                           HERMES_RID_CNFPMHOLDOVERDURATION,
2390                                           &priv->pm_timeout);
2391                 if (err) {
2392                         printk(KERN_ERR "%s: failed to read power management timeout!\n",
2393                                dev->name);
2394                         goto out;
2395                 }
2396         }
2397
2398         /* Preamble setup */
2399         if (priv->has_preamble) {
2400                 err = hermes_read_wordrec(hw, USER_BAP,
2401                                           HERMES_RID_CNFPREAMBLE_SYMBOL,
2402                                           &priv->preamble);
2403                 if (err)
2404                         goto out;
2405         }
2406                 
2407         /* Set up the default configuration */
2408         priv->iw_mode = IW_MODE_INFRA;
2409         /* By default use IEEE/IBSS ad-hoc mode if we have it */
2410         priv->prefer_port3 = priv->has_port3 && (! priv->has_ibss);
2411         set_port_type(priv);
2412         priv->channel = 0; /* use firmware default */
2413
2414         priv->promiscuous = 0;
2415         priv->wep_on = 0;
2416         priv->tx_key = 0;
2417
2418         /* Make the hardware available, as long as it hasn't been
2419          * removed elsewhere (e.g. by PCMCIA hot unplug) */
2420         spin_lock_irq(&priv->lock);
2421         priv->hw_unavailable--;
2422         spin_unlock_irq(&priv->lock);
2423
2424         printk(KERN_DEBUG "%s: ready\n", dev->name);
2425
2426  out:
2427         TRACE_EXIT(dev->name);
2428         return err;
2429 }
2430
2431 struct net_device *alloc_orinocodev(int sizeof_card,
2432                                     int (*hard_reset)(struct orinoco_private *))
2433 {
2434         struct net_device *dev;
2435         struct orinoco_private *priv;
2436
2437         dev = alloc_etherdev(sizeof(struct orinoco_private) + sizeof_card);
2438         if (! dev)
2439                 return NULL;
2440         priv = netdev_priv(dev);
2441         priv->ndev = dev;
2442         if (sizeof_card)
2443                 priv->card = (void *)((unsigned long)priv
2444                                       + sizeof(struct orinoco_private));
2445         else
2446                 priv->card = NULL;
2447
2448         /* Setup / override net_device fields */
2449         dev->init = orinoco_init;
2450         dev->hard_start_xmit = orinoco_xmit;
2451         dev->tx_timeout = orinoco_tx_timeout;
2452         dev->watchdog_timeo = HZ; /* 1 second timeout */
2453         dev->get_stats = orinoco_get_stats;
2454         dev->ethtool_ops = &orinoco_ethtool_ops;
2455         dev->get_wireless_stats = orinoco_get_wireless_stats;
2456         dev->wireless_handlers = (struct iw_handler_def *)&orinoco_handler_def;
2457         dev->change_mtu = orinoco_change_mtu;
2458         dev->set_multicast_list = orinoco_set_multicast_list;
2459         /* we use the default eth_mac_addr for setting the MAC addr */
2460
2461         /* Set up default callbacks */
2462         dev->open = orinoco_open;
2463         dev->stop = orinoco_stop;
2464         priv->hard_reset = hard_reset;
2465
2466         spin_lock_init(&priv->lock);
2467         priv->open = 0;
2468         priv->hw_unavailable = 1; /* orinoco_init() must clear this
2469                                    * before anything else touches the
2470                                    * hardware */
2471         INIT_WORK(&priv->reset_work, (void (*)(void *))orinoco_reset, dev);
2472         INIT_WORK(&priv->join_work, (void (*)(void *))orinoco_join_ap, dev);
2473         INIT_WORK(&priv->wevent_work, (void (*)(void *))orinoco_send_wevents, dev);
2474
2475         netif_carrier_off(dev);
2476         priv->last_linkstatus = 0xffff;
2477
2478         return dev;
2479
2480 }
2481
2482 void free_orinocodev(struct net_device *dev)
2483 {
2484         struct orinoco_private *priv = netdev_priv(dev);
2485
2486         kfree(priv->scan_result);
2487         free_netdev(dev);
2488 }
2489
2490 /********************************************************************/
2491 /* Wireless extensions                                              */
2492 /********************************************************************/
2493
2494 static int orinoco_hw_get_essid(struct orinoco_private *priv, int *active,
2495                                 char buf[IW_ESSID_MAX_SIZE+1])
2496 {
2497         hermes_t *hw = &priv->hw;
2498         int err = 0;
2499         struct hermes_idstring essidbuf;
2500         char *p = (char *)(&essidbuf.val);
2501         int len;
2502         unsigned long flags;
2503
2504         if (orinoco_lock(priv, &flags) != 0)
2505                 return -EBUSY;
2506
2507         if (strlen(priv->desired_essid) > 0) {
2508                 /* We read the desired SSID from the hardware rather
2509                    than from priv->desired_essid, just in case the
2510                    firmware is allowed to change it on us. I'm not
2511                    sure about this */
2512                 /* My guess is that the OWNSSID should always be whatever
2513                  * we set to the card, whereas CURRENT_SSID is the one that
2514                  * may change... - Jean II */
2515                 u16 rid;
2516
2517                 *active = 1;
2518
2519                 rid = (priv->port_type == 3) ? HERMES_RID_CNFOWNSSID :
2520                         HERMES_RID_CNFDESIREDSSID;
2521                 
2522                 err = hermes_read_ltv(hw, USER_BAP, rid, sizeof(essidbuf),
2523                                       NULL, &essidbuf);
2524                 if (err)
2525                         goto fail_unlock;
2526         } else {
2527                 *active = 0;
2528
2529                 err = hermes_read_ltv(hw, USER_BAP, HERMES_RID_CURRENTSSID,
2530                                       sizeof(essidbuf), NULL, &essidbuf);
2531                 if (err)
2532                         goto fail_unlock;
2533         }
2534
2535         len = le16_to_cpu(essidbuf.len);
2536         BUG_ON(len > IW_ESSID_MAX_SIZE);
2537
2538         memset(buf, 0, IW_ESSID_MAX_SIZE+1);
2539         memcpy(buf, p, len);
2540         buf[len] = '\0';
2541
2542  fail_unlock:
2543         orinoco_unlock(priv, &flags);
2544
2545         return err;       
2546 }
2547
2548 static long orinoco_hw_get_freq(struct orinoco_private *priv)
2549 {
2550         
2551         hermes_t *hw = &priv->hw;
2552         int err = 0;
2553         u16 channel;
2554         long freq = 0;
2555         unsigned long flags;
2556
2557         if (orinoco_lock(priv, &flags) != 0)
2558                 return -EBUSY;
2559         
2560         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CURRENTCHANNEL, &channel);
2561         if (err)
2562                 goto out;
2563
2564         /* Intersil firmware 1.3.5 returns 0 when the interface is down */
2565         if (channel == 0) {
2566                 err = -EBUSY;
2567                 goto out;
2568         }
2569
2570         if ( (channel < 1) || (channel > NUM_CHANNELS) ) {
2571                 printk(KERN_WARNING "%s: Channel out of range (%d)!\n",
2572                        priv->ndev->name, channel);
2573                 err = -EBUSY;
2574                 goto out;
2575
2576         }
2577         freq = channel_frequency[channel-1] * 100000;
2578
2579  out:
2580         orinoco_unlock(priv, &flags);
2581
2582         if (err > 0)
2583                 err = -EBUSY;
2584         return err ? err : freq;
2585 }
2586
2587 static int orinoco_hw_get_bitratelist(struct orinoco_private *priv,
2588                                       int *numrates, s32 *rates, int max)
2589 {
2590         hermes_t *hw = &priv->hw;
2591         struct hermes_idstring list;
2592         unsigned char *p = (unsigned char *)&list.val;
2593         int err = 0;
2594         int num;
2595         int i;
2596         unsigned long flags;
2597
2598         if (orinoco_lock(priv, &flags) != 0)
2599                 return -EBUSY;
2600
2601         err = hermes_read_ltv(hw, USER_BAP, HERMES_RID_SUPPORTEDDATARATES,
2602                               sizeof(list), NULL, &list);
2603         orinoco_unlock(priv, &flags);
2604
2605         if (err)
2606                 return err;
2607         
2608         num = le16_to_cpu(list.len);
2609         *numrates = num;
2610         num = min(num, max);
2611
2612         for (i = 0; i < num; i++) {
2613                 rates[i] = (p[i] & 0x7f) * 500000; /* convert to bps */
2614         }
2615
2616         return 0;
2617 }
2618
2619 static int orinoco_ioctl_getname(struct net_device *dev,
2620                                  struct iw_request_info *info,
2621                                  char *name,
2622                                  char *extra)
2623 {
2624         struct orinoco_private *priv = netdev_priv(dev);
2625         int numrates;
2626         int err;
2627
2628         err = orinoco_hw_get_bitratelist(priv, &numrates, NULL, 0);
2629
2630         if (!err && (numrates > 2))
2631                 strcpy(name, "IEEE 802.11b");
2632         else
2633                 strcpy(name, "IEEE 802.11-DS");
2634
2635         return 0;
2636 }
2637
2638 static int orinoco_ioctl_setwap(struct net_device *dev,
2639                                 struct iw_request_info *info,
2640                                 struct sockaddr *ap_addr,
2641                                 char *extra)
2642 {
2643         struct orinoco_private *priv = netdev_priv(dev);
2644         int err = -EINPROGRESS;         /* Call commit handler */
2645         unsigned long flags;
2646         static const u8 off_addr[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
2647         static const u8 any_addr[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
2648
2649         if (orinoco_lock(priv, &flags) != 0)
2650                 return -EBUSY;
2651
2652         /* Enable automatic roaming - no sanity checks are needed */
2653         if (memcmp(&ap_addr->sa_data, off_addr, ETH_ALEN) == 0 ||
2654             memcmp(&ap_addr->sa_data, any_addr, ETH_ALEN) == 0) {
2655                 priv->bssid_fixed = 0;
2656                 memset(priv->desired_bssid, 0, ETH_ALEN);
2657
2658                 /* "off" means keep existing connection */
2659                 if (ap_addr->sa_data[0] == 0) {
2660                         __orinoco_hw_set_wap(priv);
2661                         err = 0;
2662                 }
2663                 goto out;
2664         }
2665
2666         if (priv->firmware_type == FIRMWARE_TYPE_AGERE) {
2667                 printk(KERN_WARNING "%s: Lucent/Agere firmware doesn't "
2668                        "support manual roaming\n",
2669                        dev->name);
2670                 err = -EOPNOTSUPP;
2671                 goto out;
2672         }
2673
2674         if (priv->iw_mode != IW_MODE_INFRA) {
2675                 printk(KERN_WARNING "%s: Manual roaming supported only in "
2676                        "managed mode\n", dev->name);
2677                 err = -EOPNOTSUPP;
2678                 goto out;
2679         }
2680
2681         /* Intersil firmware hangs without Desired ESSID */
2682         if (priv->firmware_type == FIRMWARE_TYPE_INTERSIL &&
2683             strlen(priv->desired_essid) == 0) {
2684                 printk(KERN_WARNING "%s: Desired ESSID must be set for "
2685                        "manual roaming\n", dev->name);
2686                 err = -EOPNOTSUPP;
2687                 goto out;
2688         }
2689
2690         /* Finally, enable manual roaming */
2691         priv->bssid_fixed = 1;
2692         memcpy(priv->desired_bssid, &ap_addr->sa_data, ETH_ALEN);
2693
2694  out:
2695         orinoco_unlock(priv, &flags);
2696         return err;
2697 }
2698
2699 static int orinoco_ioctl_getwap(struct net_device *dev,
2700                                 struct iw_request_info *info,
2701                                 struct sockaddr *ap_addr,
2702                                 char *extra)
2703 {
2704         struct orinoco_private *priv = netdev_priv(dev);
2705
2706         hermes_t *hw = &priv->hw;
2707         int err = 0;
2708         unsigned long flags;
2709
2710         if (orinoco_lock(priv, &flags) != 0)
2711                 return -EBUSY;
2712
2713         ap_addr->sa_family = ARPHRD_ETHER;
2714         err = hermes_read_ltv(hw, USER_BAP, HERMES_RID_CURRENTBSSID,
2715                               ETH_ALEN, NULL, ap_addr->sa_data);
2716
2717         orinoco_unlock(priv, &flags);
2718
2719         return err;
2720 }
2721
2722 static int orinoco_ioctl_setmode(struct net_device *dev,
2723                                  struct iw_request_info *info,
2724                                  u32 *mode,
2725                                  char *extra)
2726 {
2727         struct orinoco_private *priv = netdev_priv(dev);
2728         int err = -EINPROGRESS;         /* Call commit handler */
2729         unsigned long flags;
2730
2731         if (priv->iw_mode == *mode)
2732                 return 0;
2733
2734         if (orinoco_lock(priv, &flags) != 0)
2735                 return -EBUSY;
2736
2737         switch (*mode) {
2738         case IW_MODE_ADHOC:
2739                 if (!priv->has_ibss && !priv->has_port3)
2740                         err = -EOPNOTSUPP;
2741                 break;
2742
2743         case IW_MODE_INFRA:
2744                 break;
2745
2746         case IW_MODE_MONITOR:
2747                 if (priv->broken_monitor && !force_monitor) {
2748                         printk(KERN_WARNING "%s: Monitor mode support is "
2749                                "buggy in this firmware, not enabling\n",
2750                                dev->name);
2751                         err = -EOPNOTSUPP;
2752                 }
2753                 break;
2754
2755         default:
2756                 err = -EOPNOTSUPP;
2757                 break;
2758         }
2759
2760         if (err == -EINPROGRESS) {
2761                 priv->iw_mode = *mode;
2762                 set_port_type(priv);
2763         }
2764
2765         orinoco_unlock(priv, &flags);
2766
2767         return err;
2768 }
2769
2770 static int orinoco_ioctl_getmode(struct net_device *dev,
2771                                  struct iw_request_info *info,
2772                                  u32 *mode,
2773                                  char *extra)
2774 {
2775         struct orinoco_private *priv = netdev_priv(dev);
2776
2777         *mode = priv->iw_mode;
2778         return 0;
2779 }
2780
2781 static int orinoco_ioctl_getiwrange(struct net_device *dev,
2782                                     struct iw_request_info *info,
2783                                     struct iw_point *rrq,
2784                                     char *extra)
2785 {
2786         struct orinoco_private *priv = netdev_priv(dev);
2787         int err = 0;
2788         struct iw_range *range = (struct iw_range *) extra;
2789         int numrates;
2790         int i, k;
2791
2792         TRACE_ENTER(dev->name);
2793
2794         rrq->length = sizeof(struct iw_range);
2795         memset(range, 0, sizeof(struct iw_range));
2796
2797         range->we_version_compiled = WIRELESS_EXT;
2798         range->we_version_source = 14;
2799
2800         /* Set available channels/frequencies */
2801         range->num_channels = NUM_CHANNELS;
2802         k = 0;
2803         for (i = 0; i < NUM_CHANNELS; i++) {
2804                 if (priv->channel_mask & (1 << i)) {
2805                         range->freq[k].i = i + 1;
2806                         range->freq[k].m = channel_frequency[i] * 100000;
2807                         range->freq[k].e = 1;
2808                         k++;
2809                 }
2810                 
2811                 if (k >= IW_MAX_FREQUENCIES)
2812                         break;
2813         }
2814         range->num_frequency = k;
2815         range->sensitivity = 3;
2816
2817         if (priv->has_wep) {
2818                 range->max_encoding_tokens = ORINOCO_MAX_KEYS;
2819                 range->encoding_size[0] = SMALL_KEY_SIZE;
2820                 range->num_encoding_sizes = 1;
2821
2822                 if (priv->has_big_wep) {
2823                         range->encoding_size[1] = LARGE_KEY_SIZE;
2824                         range->num_encoding_sizes = 2;
2825                 }
2826         }
2827
2828         if ((priv->iw_mode == IW_MODE_ADHOC) && (priv->spy_number == 0)){
2829                 /* Quality stats meaningless in ad-hoc mode */
2830         } else {
2831                 range->max_qual.qual = 0x8b - 0x2f;
2832                 range->max_qual.level = 0x2f - 0x95 - 1;
2833                 range->max_qual.noise = 0x2f - 0x95 - 1;
2834                 /* Need to get better values */
2835                 range->avg_qual.qual = 0x24;
2836                 range->avg_qual.level = 0xC2;
2837                 range->avg_qual.noise = 0x9E;
2838         }
2839
2840         err = orinoco_hw_get_bitratelist(priv, &numrates,
2841                                          range->bitrate, IW_MAX_BITRATES);
2842         if (err)
2843                 return err;
2844         range->num_bitrates = numrates;
2845
2846         /* Set an indication of the max TCP throughput in bit/s that we can
2847          * expect using this interface. May be use for QoS stuff...
2848          * Jean II */
2849         if (numrates > 2)
2850                 range->throughput = 5 * 1000 * 1000;    /* ~5 Mb/s */
2851         else
2852                 range->throughput = 1.5 * 1000 * 1000;  /* ~1.5 Mb/s */
2853
2854         range->min_rts = 0;
2855         range->max_rts = 2347;
2856         range->min_frag = 256;
2857         range->max_frag = 2346;
2858
2859         range->min_pmp = 0;
2860         range->max_pmp = 65535000;
2861         range->min_pmt = 0;
2862         range->max_pmt = 65535 * 1000;  /* ??? */
2863         range->pmp_flags = IW_POWER_PERIOD;
2864         range->pmt_flags = IW_POWER_TIMEOUT;
2865         range->pm_capa = IW_POWER_PERIOD | IW_POWER_TIMEOUT | IW_POWER_UNICAST_R;
2866
2867         range->retry_capa = IW_RETRY_LIMIT | IW_RETRY_LIFETIME;
2868         range->retry_flags = IW_RETRY_LIMIT;
2869         range->r_time_flags = IW_RETRY_LIFETIME;
2870         range->min_retry = 0;
2871         range->max_retry = 65535;       /* ??? */
2872         range->min_r_time = 0;
2873         range->max_r_time = 65535 * 1000;       /* ??? */
2874
2875         TRACE_EXIT(dev->name);
2876
2877         return 0;
2878 }
2879
2880 static int orinoco_ioctl_setiwencode(struct net_device *dev,
2881                                      struct iw_request_info *info,
2882                                      struct iw_point *erq,
2883                                      char *keybuf)
2884 {
2885         struct orinoco_private *priv = netdev_priv(dev);
2886         int index = (erq->flags & IW_ENCODE_INDEX) - 1;
2887         int setindex = priv->tx_key;
2888         int enable = priv->wep_on;
2889         int restricted = priv->wep_restrict;
2890         u16 xlen = 0;
2891         int err = -EINPROGRESS;         /* Call commit handler */
2892         unsigned long flags;
2893
2894         if (! priv->has_wep)
2895                 return -EOPNOTSUPP;
2896
2897         if (erq->pointer) {
2898                 /* We actually have a key to set - check its length */
2899                 if (erq->length > LARGE_KEY_SIZE)
2900                         return -E2BIG;
2901
2902                 if ( (erq->length > SMALL_KEY_SIZE) && !priv->has_big_wep )
2903                         return -E2BIG;
2904         }
2905
2906         if (orinoco_lock(priv, &flags) != 0)
2907                 return -EBUSY;
2908
2909         if (erq->pointer) {
2910                 if ((index < 0) || (index >= ORINOCO_MAX_KEYS))
2911                         index = priv->tx_key;
2912
2913                 /* Adjust key length to a supported value */
2914                 if (erq->length > SMALL_KEY_SIZE) {
2915                         xlen = LARGE_KEY_SIZE;
2916                 } else if (erq->length > 0) {
2917                         xlen = SMALL_KEY_SIZE;
2918                 } else
2919                         xlen = 0;
2920
2921                 /* Switch on WEP if off */
2922                 if ((!enable) && (xlen > 0)) {
2923                         setindex = index;
2924                         enable = 1;
2925                 }
2926         } else {
2927                 /* Important note : if the user do "iwconfig eth0 enc off",
2928                  * we will arrive there with an index of -1. This is valid
2929                  * but need to be taken care off... Jean II */
2930                 if ((index < 0) || (index >= ORINOCO_MAX_KEYS)) {
2931                         if((index != -1) || (erq->flags == 0)) {
2932                                 err = -EINVAL;
2933                                 goto out;
2934                         }
2935                 } else {
2936                         /* Set the index : Check that the key is valid */
2937                         if(priv->keys[index].len == 0) {
2938                                 err = -EINVAL;
2939                                 goto out;
2940                         }
2941                         setindex = index;
2942                 }
2943         }
2944
2945         if (erq->flags & IW_ENCODE_DISABLED)
2946                 enable = 0;
2947         if (erq->flags & IW_ENCODE_OPEN)
2948                 restricted = 0;
2949         if (erq->flags & IW_ENCODE_RESTRICTED)
2950                 restricted = 1;
2951
2952         if (erq->pointer) {
2953                 priv->keys[index].len = cpu_to_le16(xlen);
2954                 memset(priv->keys[index].data, 0,
2955                        sizeof(priv->keys[index].data));
2956                 memcpy(priv->keys[index].data, keybuf, erq->length);
2957         }
2958         priv->tx_key = setindex;
2959
2960         /* Try fast key change if connected and only keys are changed */
2961         if (priv->wep_on && enable && (priv->wep_restrict == restricted) &&
2962             netif_carrier_ok(dev)) {
2963                 err = __orinoco_hw_setup_wepkeys(priv);
2964                 /* No need to commit if successful */
2965                 goto out;
2966         }
2967
2968         priv->wep_on = enable;
2969         priv->wep_restrict = restricted;
2970
2971  out:
2972         orinoco_unlock(priv, &flags);
2973
2974         return err;
2975 }
2976
2977 static int orinoco_ioctl_getiwencode(struct net_device *dev,
2978                                      struct iw_request_info *info,
2979                                      struct iw_point *erq,
2980                                      char *keybuf)
2981 {
2982         struct orinoco_private *priv = netdev_priv(dev);
2983         int index = (erq->flags & IW_ENCODE_INDEX) - 1;
2984         u16 xlen = 0;
2985         unsigned long flags;
2986
2987         if (! priv->has_wep)
2988                 return -EOPNOTSUPP;
2989
2990         if (orinoco_lock(priv, &flags) != 0)
2991                 return -EBUSY;
2992
2993         if ((index < 0) || (index >= ORINOCO_MAX_KEYS))
2994                 index = priv->tx_key;
2995
2996         erq->flags = 0;
2997         if (! priv->wep_on)
2998                 erq->flags |= IW_ENCODE_DISABLED;
2999         erq->flags |= index + 1;
3000
3001         if (priv->wep_restrict)
3002                 erq->flags |= IW_ENCODE_RESTRICTED;
3003         else
3004                 erq->flags |= IW_ENCODE_OPEN;
3005
3006         xlen = le16_to_cpu(priv->keys[index].len);
3007
3008         erq->length = xlen;
3009
3010         memcpy(keybuf, priv->keys[index].data, ORINOCO_MAX_KEY_SIZE);
3011
3012         orinoco_unlock(priv, &flags);
3013         return 0;
3014 }
3015
3016 static int orinoco_ioctl_setessid(struct net_device *dev,
3017                                   struct iw_request_info *info,
3018                                   struct iw_point *erq,
3019                                   char *essidbuf)
3020 {
3021         struct orinoco_private *priv = netdev_priv(dev);
3022         unsigned long flags;
3023
3024         /* Note : ESSID is ignored in Ad-Hoc demo mode, but we can set it
3025          * anyway... - Jean II */
3026
3027         /* Hum... Should not use Wireless Extension constant (may change),
3028          * should use our own... - Jean II */
3029         if (erq->length > IW_ESSID_MAX_SIZE)
3030                 return -E2BIG;
3031
3032         if (orinoco_lock(priv, &flags) != 0)
3033                 return -EBUSY;
3034
3035         /* NULL the string (for NULL termination & ESSID = ANY) - Jean II */
3036         memset(priv->desired_essid, 0, sizeof(priv->desired_essid));
3037
3038         /* If not ANY, get the new ESSID */
3039         if (erq->flags) {
3040                 memcpy(priv->desired_essid, essidbuf, erq->length);
3041         }
3042
3043         orinoco_unlock(priv, &flags);
3044
3045         return -EINPROGRESS;            /* Call commit handler */
3046 }
3047
3048 static int orinoco_ioctl_getessid(struct net_device *dev,
3049                                   struct iw_request_info *info,
3050                                   struct iw_point *erq,
3051                                   char *essidbuf)
3052 {
3053         struct orinoco_private *priv = netdev_priv(dev);
3054         int active;
3055         int err = 0;
3056         unsigned long flags;
3057
3058         TRACE_ENTER(dev->name);
3059
3060         if (netif_running(dev)) {
3061                 err = orinoco_hw_get_essid(priv, &active, essidbuf);
3062                 if (err)
3063                         return err;
3064         } else {
3065                 if (orinoco_lock(priv, &flags) != 0)
3066                         return -EBUSY;
3067                 memcpy(essidbuf, priv->desired_essid, IW_ESSID_MAX_SIZE + 1);
3068                 orinoco_unlock(priv, &flags);
3069         }
3070
3071         erq->flags = 1;
3072         erq->length = strlen(essidbuf) + 1;
3073
3074         TRACE_EXIT(dev->name);
3075         
3076         return 0;
3077 }
3078
3079 static int orinoco_ioctl_setnick(struct net_device *dev,
3080                                  struct iw_request_info *info,
3081                                  struct iw_point *nrq,
3082                                  char *nickbuf)
3083 {
3084         struct orinoco_private *priv = netdev_priv(dev);
3085         unsigned long flags;
3086
3087         if (nrq->length > IW_ESSID_MAX_SIZE)
3088                 return -E2BIG;
3089
3090         if (orinoco_lock(priv, &flags) != 0)
3091                 return -EBUSY;
3092
3093         memset(priv->nick, 0, sizeof(priv->nick));
3094         memcpy(priv->nick, nickbuf, nrq->length);
3095
3096         orinoco_unlock(priv, &flags);
3097
3098         return -EINPROGRESS;            /* Call commit handler */
3099 }
3100
3101 static int orinoco_ioctl_getnick(struct net_device *dev,
3102                                  struct iw_request_info *info,
3103                                  struct iw_point *nrq,
3104                                  char *nickbuf)
3105 {
3106         struct orinoco_private *priv = netdev_priv(dev);
3107         unsigned long flags;
3108
3109         if (orinoco_lock(priv, &flags) != 0)
3110                 return -EBUSY;
3111
3112         memcpy(nickbuf, priv->nick, IW_ESSID_MAX_SIZE+1);
3113         orinoco_unlock(priv, &flags);
3114
3115         nrq->length = strlen(nickbuf)+1;
3116
3117         return 0;
3118 }
3119
3120 static int orinoco_ioctl_setfreq(struct net_device *dev,
3121                                  struct iw_request_info *info,
3122                                  struct iw_freq *frq,
3123                                  char *extra)
3124 {
3125         struct orinoco_private *priv = netdev_priv(dev);
3126         int chan = -1;
3127         unsigned long flags;
3128         int err = -EINPROGRESS;         /* Call commit handler */
3129
3130         /* In infrastructure mode the AP sets the channel */
3131         if (priv->iw_mode == IW_MODE_INFRA)
3132                 return -EBUSY;
3133
3134         if ( (frq->e == 0) && (frq->m <= 1000) ) {
3135                 /* Setting by channel number */
3136                 chan = frq->m;