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