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