Pull platform-drivers into test branch
[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.raw + 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->mac.raw = skb->data;
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->dev = dev;
919         skb->protocol = eth_type_trans(skb, dev);
920         skb->ip_summed = CHECKSUM_NONE;
921         if (fc & IEEE80211_FCTL_TODS)
922                 skb->pkt_type = PACKET_OTHERHOST;
923         
924         /* Process the wireless stats if needed */
925         orinoco_stat_gather(dev, skb, &desc);
926
927         /* Pass the packet to the networking stack */
928         netif_rx(skb);
929         stats->rx_packets++;
930         stats->rx_bytes += length;
931
932         return;
933
934  drop:  
935         dev_kfree_skb_irq(skb);
936  update_stats:
937         stats->rx_errors++;
938         stats->rx_dropped++;
939 }
940
941 /********************************************************************/
942 /* Rx path (info frames)                                            */
943 /********************************************************************/
944
945 static void print_linkstatus(struct net_device *dev, u16 status)
946 {
947         char * s;
948
949         if (suppress_linkstatus)
950                 return;
951
952         switch (status) {
953         case HERMES_LINKSTATUS_NOT_CONNECTED:
954                 s = "Not Connected";
955                 break;
956         case HERMES_LINKSTATUS_CONNECTED:
957                 s = "Connected";
958                 break;
959         case HERMES_LINKSTATUS_DISCONNECTED:
960                 s = "Disconnected";
961                 break;
962         case HERMES_LINKSTATUS_AP_CHANGE:
963                 s = "AP Changed";
964                 break;
965         case HERMES_LINKSTATUS_AP_OUT_OF_RANGE:
966                 s = "AP Out of Range";
967                 break;
968         case HERMES_LINKSTATUS_AP_IN_RANGE:
969                 s = "AP In Range";
970                 break;
971         case HERMES_LINKSTATUS_ASSOC_FAILED:
972                 s = "Association Failed";
973                 break;
974         default:
975                 s = "UNKNOWN";
976         }
977         
978         printk(KERN_INFO "%s: New link status: %s (%04x)\n",
979                dev->name, s, status);
980 }
981
982 /* Search scan results for requested BSSID, join it if found */
983 static void orinoco_join_ap(struct work_struct *work)
984 {
985         struct orinoco_private *priv =
986                 container_of(work, struct orinoco_private, join_work);
987         struct net_device *dev = priv->ndev;
988         struct hermes *hw = &priv->hw;
989         int err;
990         unsigned long flags;
991         struct join_req {
992                 u8 bssid[ETH_ALEN];
993                 __le16 channel;
994         } __attribute__ ((packed)) req;
995         const int atom_len = offsetof(struct prism2_scan_apinfo, atim);
996         struct prism2_scan_apinfo *atom = NULL;
997         int offset = 4;
998         int found = 0;
999         u8 *buf;
1000         u16 len;
1001
1002         /* Allocate buffer for scan results */
1003         buf = kmalloc(MAX_SCAN_LEN, GFP_KERNEL);
1004         if (! buf)
1005                 return;
1006
1007         if (orinoco_lock(priv, &flags) != 0)
1008                 goto fail_lock;
1009
1010         /* Sanity checks in case user changed something in the meantime */
1011         if (! priv->bssid_fixed)
1012                 goto out;
1013
1014         if (strlen(priv->desired_essid) == 0)
1015                 goto out;
1016
1017         /* Read scan results from the firmware */
1018         err = hermes_read_ltv(hw, USER_BAP,
1019                               HERMES_RID_SCANRESULTSTABLE,
1020                               MAX_SCAN_LEN, &len, buf);
1021         if (err) {
1022                 printk(KERN_ERR "%s: Cannot read scan results\n",
1023                        dev->name);
1024                 goto out;
1025         }
1026
1027         len = HERMES_RECLEN_TO_BYTES(len);
1028
1029         /* Go through the scan results looking for the channel of the AP
1030          * we were requested to join */
1031         for (; offset + atom_len <= len; offset += atom_len) {
1032                 atom = (struct prism2_scan_apinfo *) (buf + offset);
1033                 if (memcmp(&atom->bssid, priv->desired_bssid, ETH_ALEN) == 0) {
1034                         found = 1;
1035                         break;
1036                 }
1037         }
1038
1039         if (! found) {
1040                 DEBUG(1, "%s: Requested AP not found in scan results\n",
1041                       dev->name);
1042                 goto out;
1043         }
1044
1045         memcpy(req.bssid, priv->desired_bssid, ETH_ALEN);
1046         req.channel = atom->channel;    /* both are little-endian */
1047         err = HERMES_WRITE_RECORD(hw, USER_BAP, HERMES_RID_CNFJOINREQUEST,
1048                                   &req);
1049         if (err)
1050                 printk(KERN_ERR "%s: Error issuing join request\n", dev->name);
1051
1052  out:
1053         orinoco_unlock(priv, &flags);
1054
1055  fail_lock:
1056         kfree(buf);
1057 }
1058
1059 /* Send new BSSID to userspace */
1060 static void orinoco_send_wevents(struct work_struct *work)
1061 {
1062         struct orinoco_private *priv =
1063                 container_of(work, struct orinoco_private, wevent_work);
1064         struct net_device *dev = priv->ndev;
1065         struct hermes *hw = &priv->hw;
1066         union iwreq_data wrqu;
1067         int err;
1068         unsigned long flags;
1069
1070         if (orinoco_lock(priv, &flags) != 0)
1071                 return;
1072
1073         err = hermes_read_ltv(hw, IRQ_BAP, HERMES_RID_CURRENTBSSID,
1074                               ETH_ALEN, NULL, wrqu.ap_addr.sa_data);
1075         if (err != 0)
1076                 goto out;
1077
1078         wrqu.ap_addr.sa_family = ARPHRD_ETHER;
1079
1080         /* Send event to user space */
1081         wireless_send_event(dev, SIOCGIWAP, &wrqu, NULL);
1082
1083  out:
1084         orinoco_unlock(priv, &flags);
1085 }
1086
1087 static void __orinoco_ev_info(struct net_device *dev, hermes_t *hw)
1088 {
1089         struct orinoco_private *priv = netdev_priv(dev);
1090         u16 infofid;
1091         struct {
1092                 __le16 len;
1093                 __le16 type;
1094         } __attribute__ ((packed)) info;
1095         int len, type;
1096         int err;
1097
1098         /* This is an answer to an INQUIRE command that we did earlier,
1099          * or an information "event" generated by the card
1100          * The controller return to us a pseudo frame containing
1101          * the information in question - Jean II */
1102         infofid = hermes_read_regn(hw, INFOFID);
1103
1104         /* Read the info frame header - don't try too hard */
1105         err = hermes_bap_pread(hw, IRQ_BAP, &info, sizeof(info),
1106                                infofid, 0);
1107         if (err) {
1108                 printk(KERN_ERR "%s: error %d reading info frame. "
1109                        "Frame dropped.\n", dev->name, err);
1110                 return;
1111         }
1112         
1113         len = HERMES_RECLEN_TO_BYTES(le16_to_cpu(info.len));
1114         type = le16_to_cpu(info.type);
1115
1116         switch (type) {
1117         case HERMES_INQ_TALLIES: {
1118                 struct hermes_tallies_frame tallies;
1119                 struct iw_statistics *wstats = &priv->wstats;
1120                 
1121                 if (len > sizeof(tallies)) {
1122                         printk(KERN_WARNING "%s: Tallies frame too long (%d bytes)\n",
1123                                dev->name, len);
1124                         len = sizeof(tallies);
1125                 }
1126                 
1127                 err = hermes_bap_pread(hw, IRQ_BAP, &tallies, len,
1128                                        infofid, sizeof(info));
1129                 if (err)
1130                         break;
1131                 
1132                 /* Increment our various counters */
1133                 /* wstats->discard.nwid - no wrong BSSID stuff */
1134                 wstats->discard.code +=
1135                         le16_to_cpu(tallies.RxWEPUndecryptable);
1136                 if (len == sizeof(tallies))  
1137                         wstats->discard.code +=
1138                                 le16_to_cpu(tallies.RxDiscards_WEPICVError) +
1139                                 le16_to_cpu(tallies.RxDiscards_WEPExcluded);
1140                 wstats->discard.misc +=
1141                         le16_to_cpu(tallies.TxDiscardsWrongSA);
1142                 wstats->discard.fragment +=
1143                         le16_to_cpu(tallies.RxMsgInBadMsgFragments);
1144                 wstats->discard.retries +=
1145                         le16_to_cpu(tallies.TxRetryLimitExceeded);
1146                 /* wstats->miss.beacon - no match */
1147         }
1148         break;
1149         case HERMES_INQ_LINKSTATUS: {
1150                 struct hermes_linkstatus linkstatus;
1151                 u16 newstatus;
1152                 int connected;
1153
1154                 if (priv->iw_mode == IW_MODE_MONITOR)
1155                         break;
1156
1157                 if (len != sizeof(linkstatus)) {
1158                         printk(KERN_WARNING "%s: Unexpected size for linkstatus frame (%d bytes)\n",
1159                                dev->name, len);
1160                         break;
1161                 }
1162
1163                 err = hermes_bap_pread(hw, IRQ_BAP, &linkstatus, len,
1164                                        infofid, sizeof(info));
1165                 if (err)
1166                         break;
1167                 newstatus = le16_to_cpu(linkstatus.linkstatus);
1168
1169                 /* Symbol firmware uses "out of range" to signal that
1170                  * the hostscan frame can be requested.  */
1171                 if (newstatus == HERMES_LINKSTATUS_AP_OUT_OF_RANGE &&
1172                     priv->firmware_type == FIRMWARE_TYPE_SYMBOL &&
1173                     priv->has_hostscan && priv->scan_inprogress) {
1174                         hermes_inquire(hw, HERMES_INQ_HOSTSCAN_SYMBOL);
1175                         break;
1176                 }
1177
1178                 connected = (newstatus == HERMES_LINKSTATUS_CONNECTED)
1179                         || (newstatus == HERMES_LINKSTATUS_AP_CHANGE)
1180                         || (newstatus == HERMES_LINKSTATUS_AP_IN_RANGE);
1181
1182                 if (connected)
1183                         netif_carrier_on(dev);
1184                 else if (!ignore_disconnect)
1185                         netif_carrier_off(dev);
1186
1187                 if (newstatus != priv->last_linkstatus) {
1188                         priv->last_linkstatus = newstatus;
1189                         print_linkstatus(dev, newstatus);
1190                         /* The info frame contains only one word which is the
1191                          * status (see hermes.h). The status is pretty boring
1192                          * in itself, that's why we export the new BSSID...
1193                          * Jean II */
1194                         schedule_work(&priv->wevent_work);
1195                 }
1196         }
1197         break;
1198         case HERMES_INQ_SCAN:
1199                 if (!priv->scan_inprogress && priv->bssid_fixed &&
1200                     priv->firmware_type == FIRMWARE_TYPE_INTERSIL) {
1201                         schedule_work(&priv->join_work);
1202                         break;
1203                 }
1204                 /* fall through */
1205         case HERMES_INQ_HOSTSCAN:
1206         case HERMES_INQ_HOSTSCAN_SYMBOL: {
1207                 /* Result of a scanning. Contains information about
1208                  * cells in the vicinity - Jean II */
1209                 union iwreq_data        wrqu;
1210                 unsigned char *buf;
1211
1212                 /* Sanity check */
1213                 if (len > 4096) {
1214                         printk(KERN_WARNING "%s: Scan results too large (%d bytes)\n",
1215                                dev->name, len);
1216                         break;
1217                 }
1218
1219                 /* We are a strict producer. If the previous scan results
1220                  * have not been consumed, we just have to drop this
1221                  * frame. We can't remove the previous results ourselves,
1222                  * that would be *very* racy... Jean II */
1223                 if (priv->scan_result != NULL) {
1224                         printk(KERN_WARNING "%s: Previous scan results not consumed, dropping info frame.\n", dev->name);
1225                         break;
1226                 }
1227
1228                 /* Allocate buffer for results */
1229                 buf = kmalloc(len, GFP_ATOMIC);
1230                 if (buf == NULL)
1231                         /* No memory, so can't printk()... */
1232                         break;
1233
1234                 /* Read scan data */
1235                 err = hermes_bap_pread(hw, IRQ_BAP, (void *) buf, len,
1236                                        infofid, sizeof(info));
1237                 if (err) {
1238                         kfree(buf);
1239                         break;
1240                 }
1241
1242 #ifdef ORINOCO_DEBUG
1243                 {
1244                         int     i;
1245                         printk(KERN_DEBUG "Scan result [%02X", buf[0]);
1246                         for(i = 1; i < (len * 2); i++)
1247                                 printk(":%02X", buf[i]);
1248                         printk("]\n");
1249                 }
1250 #endif  /* ORINOCO_DEBUG */
1251
1252                 /* Allow the clients to access the results */
1253                 priv->scan_len = len;
1254                 priv->scan_result = buf;
1255
1256                 /* Send an empty event to user space.
1257                  * We don't send the received data on the event because
1258                  * it would require us to do complex transcoding, and
1259                  * we want to minimise the work done in the irq handler
1260                  * Use a request to extract the data - Jean II */
1261                 wrqu.data.length = 0;
1262                 wrqu.data.flags = 0;
1263                 wireless_send_event(dev, SIOCGIWSCAN, &wrqu, NULL);
1264         }
1265         break;
1266         case HERMES_INQ_SEC_STAT_AGERE:
1267                 /* Security status (Agere specific) */
1268                 /* Ignore this frame for now */
1269                 if (priv->firmware_type == FIRMWARE_TYPE_AGERE)
1270                         break;
1271                 /* fall through */
1272         default:
1273                 printk(KERN_DEBUG "%s: Unknown information frame received: "
1274                        "type 0x%04x, length %d\n", dev->name, type, len);
1275                 /* We don't actually do anything about it */
1276                 break;
1277         }
1278 }
1279
1280 static void __orinoco_ev_infdrop(struct net_device *dev, hermes_t *hw)
1281 {
1282         if (net_ratelimit())
1283                 printk(KERN_DEBUG "%s: Information frame lost.\n", dev->name);
1284 }
1285
1286 /********************************************************************/
1287 /* Internal hardware control routines                               */
1288 /********************************************************************/
1289
1290 int __orinoco_up(struct net_device *dev)
1291 {
1292         struct orinoco_private *priv = netdev_priv(dev);
1293         struct hermes *hw = &priv->hw;
1294         int err;
1295
1296         netif_carrier_off(dev); /* just to make sure */
1297
1298         err = __orinoco_program_rids(dev);
1299         if (err) {
1300                 printk(KERN_ERR "%s: Error %d configuring card\n",
1301                        dev->name, err);
1302                 return err;
1303         }
1304
1305         /* Fire things up again */
1306         hermes_set_irqmask(hw, ORINOCO_INTEN);
1307         err = hermes_enable_port(hw, 0);
1308         if (err) {
1309                 printk(KERN_ERR "%s: Error %d enabling MAC port\n",
1310                        dev->name, err);
1311                 return err;
1312         }
1313
1314         netif_start_queue(dev);
1315
1316         return 0;
1317 }
1318
1319 int __orinoco_down(struct net_device *dev)
1320 {
1321         struct orinoco_private *priv = netdev_priv(dev);
1322         struct hermes *hw = &priv->hw;
1323         int err;
1324
1325         netif_stop_queue(dev);
1326
1327         if (! priv->hw_unavailable) {
1328                 if (! priv->broken_disableport) {
1329                         err = hermes_disable_port(hw, 0);
1330                         if (err) {
1331                                 /* Some firmwares (e.g. Intersil 1.3.x) seem
1332                                  * to have problems disabling the port, oh
1333                                  * well, too bad. */
1334                                 printk(KERN_WARNING "%s: Error %d disabling MAC port\n",
1335                                        dev->name, err);
1336                                 priv->broken_disableport = 1;
1337                         }
1338                 }
1339                 hermes_set_irqmask(hw, 0);
1340                 hermes_write_regn(hw, EVACK, 0xffff);
1341         }
1342         
1343         /* firmware will have to reassociate */
1344         netif_carrier_off(dev);
1345         priv->last_linkstatus = 0xffff;
1346
1347         return 0;
1348 }
1349
1350 static int orinoco_allocate_fid(struct net_device *dev)
1351 {
1352         struct orinoco_private *priv = netdev_priv(dev);
1353         struct hermes *hw = &priv->hw;
1354         int err;
1355
1356         err = hermes_allocate(hw, priv->nicbuf_size, &priv->txfid);
1357         if (err == -EIO && priv->nicbuf_size > TX_NICBUF_SIZE_BUG) {
1358                 /* Try workaround for old Symbol firmware bug */
1359                 printk(KERN_WARNING "%s: firmware ALLOC bug detected "
1360                        "(old Symbol firmware?). Trying to work around... ",
1361                        dev->name);
1362                 
1363                 priv->nicbuf_size = TX_NICBUF_SIZE_BUG;
1364                 err = hermes_allocate(hw, priv->nicbuf_size, &priv->txfid);
1365                 if (err)
1366                         printk("failed!\n");
1367                 else
1368                         printk("ok.\n");
1369         }
1370
1371         return err;
1372 }
1373
1374 int orinoco_reinit_firmware(struct net_device *dev)
1375 {
1376         struct orinoco_private *priv = netdev_priv(dev);
1377         struct hermes *hw = &priv->hw;
1378         int err;
1379
1380         err = hermes_init(hw);
1381         if (!err)
1382                 err = orinoco_allocate_fid(dev);
1383
1384         return err;
1385 }
1386
1387 static int __orinoco_hw_set_bitrate(struct orinoco_private *priv)
1388 {
1389         hermes_t *hw = &priv->hw;
1390         int err = 0;
1391
1392         if (priv->bitratemode >= BITRATE_TABLE_SIZE) {
1393                 printk(KERN_ERR "%s: BUG: Invalid bitrate mode %d\n",
1394                        priv->ndev->name, priv->bitratemode);
1395                 return -EINVAL;
1396         }
1397
1398         switch (priv->firmware_type) {
1399         case FIRMWARE_TYPE_AGERE:
1400                 err = hermes_write_wordrec(hw, USER_BAP,
1401                                            HERMES_RID_CNFTXRATECONTROL,
1402                                            bitrate_table[priv->bitratemode].agere_txratectrl);
1403                 break;
1404         case FIRMWARE_TYPE_INTERSIL:
1405         case FIRMWARE_TYPE_SYMBOL:
1406                 err = hermes_write_wordrec(hw, USER_BAP,
1407                                            HERMES_RID_CNFTXRATECONTROL,
1408                                            bitrate_table[priv->bitratemode].intersil_txratectrl);
1409                 break;
1410         default:
1411                 BUG();
1412         }
1413
1414         return err;
1415 }
1416
1417 /* Set fixed AP address */
1418 static int __orinoco_hw_set_wap(struct orinoco_private *priv)
1419 {
1420         int roaming_flag;
1421         int err = 0;
1422         hermes_t *hw = &priv->hw;
1423
1424         switch (priv->firmware_type) {
1425         case FIRMWARE_TYPE_AGERE:
1426                 /* not supported */
1427                 break;
1428         case FIRMWARE_TYPE_INTERSIL:
1429                 if (priv->bssid_fixed)
1430                         roaming_flag = 2;
1431                 else
1432                         roaming_flag = 1;
1433
1434                 err = hermes_write_wordrec(hw, USER_BAP,
1435                                            HERMES_RID_CNFROAMINGMODE,
1436                                            roaming_flag);
1437                 break;
1438         case FIRMWARE_TYPE_SYMBOL:
1439                 err = HERMES_WRITE_RECORD(hw, USER_BAP,
1440                                           HERMES_RID_CNFMANDATORYBSSID_SYMBOL,
1441                                           &priv->desired_bssid);
1442                 break;
1443         }
1444         return err;
1445 }
1446
1447 /* Change the WEP keys and/or the current keys.  Can be called
1448  * either from __orinoco_hw_setup_wep() or directly from
1449  * orinoco_ioctl_setiwencode().  In the later case the association
1450  * with the AP is not broken (if the firmware can handle it),
1451  * which is needed for 802.1x implementations. */
1452 static int __orinoco_hw_setup_wepkeys(struct orinoco_private *priv)
1453 {
1454         hermes_t *hw = &priv->hw;
1455         int err = 0;
1456
1457         switch (priv->firmware_type) {
1458         case FIRMWARE_TYPE_AGERE:
1459                 err = HERMES_WRITE_RECORD(hw, USER_BAP,
1460                                           HERMES_RID_CNFWEPKEYS_AGERE,
1461                                           &priv->keys);
1462                 if (err)
1463                         return err;
1464                 err = hermes_write_wordrec(hw, USER_BAP,
1465                                            HERMES_RID_CNFTXKEY_AGERE,
1466                                            priv->tx_key);
1467                 if (err)
1468                         return err;
1469                 break;
1470         case FIRMWARE_TYPE_INTERSIL:
1471         case FIRMWARE_TYPE_SYMBOL:
1472                 {
1473                         int keylen;
1474                         int i;
1475
1476                         /* Force uniform key length to work around firmware bugs */
1477                         keylen = le16_to_cpu(priv->keys[priv->tx_key].len);
1478                         
1479                         if (keylen > LARGE_KEY_SIZE) {
1480                                 printk(KERN_ERR "%s: BUG: Key %d has oversize length %d.\n",
1481                                        priv->ndev->name, priv->tx_key, keylen);
1482                                 return -E2BIG;
1483                         }
1484
1485                         /* Write all 4 keys */
1486                         for(i = 0; i < ORINOCO_MAX_KEYS; i++) {
1487                                 err = hermes_write_ltv(hw, USER_BAP,
1488                                                        HERMES_RID_CNFDEFAULTKEY0 + i,
1489                                                        HERMES_BYTES_TO_RECLEN(keylen),
1490                                                        priv->keys[i].data);
1491                                 if (err)
1492                                         return err;
1493                         }
1494
1495                         /* Write the index of the key used in transmission */
1496                         err = hermes_write_wordrec(hw, USER_BAP,
1497                                                    HERMES_RID_CNFWEPDEFAULTKEYID,
1498                                                    priv->tx_key);
1499                         if (err)
1500                                 return err;
1501                 }
1502                 break;
1503         }
1504
1505         return 0;
1506 }
1507
1508 static int __orinoco_hw_setup_wep(struct orinoco_private *priv)
1509 {
1510         hermes_t *hw = &priv->hw;
1511         int err = 0;
1512         int master_wep_flag;
1513         int auth_flag;
1514
1515         if (priv->wep_on)
1516                 __orinoco_hw_setup_wepkeys(priv);
1517
1518         if (priv->wep_restrict)
1519                 auth_flag = HERMES_AUTH_SHARED_KEY;
1520         else
1521                 auth_flag = HERMES_AUTH_OPEN;
1522
1523         switch (priv->firmware_type) {
1524         case FIRMWARE_TYPE_AGERE: /* Agere style WEP */
1525                 if (priv->wep_on) {
1526                         /* Enable the shared-key authentication. */
1527                         err = hermes_write_wordrec(hw, USER_BAP,
1528                                                    HERMES_RID_CNFAUTHENTICATION_AGERE,
1529                                                    auth_flag);
1530                 }
1531                 err = hermes_write_wordrec(hw, USER_BAP,
1532                                            HERMES_RID_CNFWEPENABLED_AGERE,
1533                                            priv->wep_on);
1534                 if (err)
1535                         return err;
1536                 break;
1537
1538         case FIRMWARE_TYPE_INTERSIL: /* Intersil style WEP */
1539         case FIRMWARE_TYPE_SYMBOL: /* Symbol style WEP */
1540                 if (priv->wep_on) {
1541                         if (priv->wep_restrict ||
1542                             (priv->firmware_type == FIRMWARE_TYPE_SYMBOL))
1543                                 master_wep_flag = HERMES_WEP_PRIVACY_INVOKED |
1544                                                   HERMES_WEP_EXCL_UNENCRYPTED;
1545                         else
1546                                 master_wep_flag = HERMES_WEP_PRIVACY_INVOKED;
1547
1548                         err = hermes_write_wordrec(hw, USER_BAP,
1549                                                    HERMES_RID_CNFAUTHENTICATION,
1550                                                    auth_flag);
1551                         if (err)
1552                                 return err;
1553                 } else
1554                         master_wep_flag = 0;
1555
1556                 if (priv->iw_mode == IW_MODE_MONITOR)
1557                         master_wep_flag |= HERMES_WEP_HOST_DECRYPT;
1558
1559                 /* Master WEP setting : on/off */
1560                 err = hermes_write_wordrec(hw, USER_BAP,
1561                                            HERMES_RID_CNFWEPFLAGS_INTERSIL,
1562                                            master_wep_flag);
1563                 if (err)
1564                         return err;     
1565
1566                 break;
1567         }
1568
1569         return 0;
1570 }
1571
1572 static int __orinoco_program_rids(struct net_device *dev)
1573 {
1574         struct orinoco_private *priv = netdev_priv(dev);
1575         hermes_t *hw = &priv->hw;
1576         int err;
1577         struct hermes_idstring idbuf;
1578
1579         /* Set the MAC address */
1580         err = hermes_write_ltv(hw, USER_BAP, HERMES_RID_CNFOWNMACADDR,
1581                                HERMES_BYTES_TO_RECLEN(ETH_ALEN), dev->dev_addr);
1582         if (err) {
1583                 printk(KERN_ERR "%s: Error %d setting MAC address\n",
1584                        dev->name, err);
1585                 return err;
1586         }
1587
1588         /* Set up the link mode */
1589         err = hermes_write_wordrec(hw, USER_BAP, HERMES_RID_CNFPORTTYPE,
1590                                    priv->port_type);
1591         if (err) {
1592                 printk(KERN_ERR "%s: Error %d setting port type\n",
1593                        dev->name, err);
1594                 return err;
1595         }
1596         /* Set the channel/frequency */
1597         if (priv->channel != 0 && priv->iw_mode != IW_MODE_INFRA) {
1598                 err = hermes_write_wordrec(hw, USER_BAP,
1599                                            HERMES_RID_CNFOWNCHANNEL,
1600                                            priv->channel);
1601                 if (err) {
1602                         printk(KERN_ERR "%s: Error %d setting channel %d\n",
1603                                dev->name, err, priv->channel);
1604                         return err;
1605                 }
1606         }
1607
1608         if (priv->has_ibss) {
1609                 u16 createibss;
1610
1611                 if ((strlen(priv->desired_essid) == 0) && (priv->createibss)) {
1612                         printk(KERN_WARNING "%s: This firmware requires an "
1613                                "ESSID in IBSS-Ad-Hoc mode.\n", dev->name);
1614                         /* With wvlan_cs, in this case, we would crash.
1615                          * hopefully, this driver will behave better...
1616                          * Jean II */
1617                         createibss = 0;
1618                 } else {
1619                         createibss = priv->createibss;
1620                 }
1621                 
1622                 err = hermes_write_wordrec(hw, USER_BAP,
1623                                            HERMES_RID_CNFCREATEIBSS,
1624                                            createibss);
1625                 if (err) {
1626                         printk(KERN_ERR "%s: Error %d setting CREATEIBSS\n",
1627                                dev->name, err);
1628                         return err;
1629                 }
1630         }
1631
1632         /* Set the desired BSSID */
1633         err = __orinoco_hw_set_wap(priv);
1634         if (err) {
1635                 printk(KERN_ERR "%s: Error %d setting AP address\n",
1636                        dev->name, err);
1637                 return err;
1638         }
1639         /* Set the desired ESSID */
1640         idbuf.len = cpu_to_le16(strlen(priv->desired_essid));
1641         memcpy(&idbuf.val, priv->desired_essid, sizeof(idbuf.val));
1642         /* WinXP wants partner to configure OWNSSID even in IBSS mode. (jimc) */
1643         err = hermes_write_ltv(hw, USER_BAP, HERMES_RID_CNFOWNSSID,
1644                                HERMES_BYTES_TO_RECLEN(strlen(priv->desired_essid)+2),
1645                                &idbuf);
1646         if (err) {
1647                 printk(KERN_ERR "%s: Error %d setting OWNSSID\n",
1648                        dev->name, err);
1649                 return err;
1650         }
1651         err = hermes_write_ltv(hw, USER_BAP, HERMES_RID_CNFDESIREDSSID,
1652                                HERMES_BYTES_TO_RECLEN(strlen(priv->desired_essid)+2),
1653                                &idbuf);
1654         if (err) {
1655                 printk(KERN_ERR "%s: Error %d setting DESIREDSSID\n",
1656                        dev->name, err);
1657                 return err;
1658         }
1659
1660         /* Set the station name */
1661         idbuf.len = cpu_to_le16(strlen(priv->nick));
1662         memcpy(&idbuf.val, priv->nick, sizeof(idbuf.val));
1663         err = hermes_write_ltv(hw, USER_BAP, HERMES_RID_CNFOWNNAME,
1664                                HERMES_BYTES_TO_RECLEN(strlen(priv->nick)+2),
1665                                &idbuf);
1666         if (err) {
1667                 printk(KERN_ERR "%s: Error %d setting nickname\n",
1668                        dev->name, err);
1669                 return err;
1670         }
1671
1672         /* Set AP density */
1673         if (priv->has_sensitivity) {
1674                 err = hermes_write_wordrec(hw, USER_BAP,
1675                                            HERMES_RID_CNFSYSTEMSCALE,
1676                                            priv->ap_density);
1677                 if (err) {
1678                         printk(KERN_WARNING "%s: Error %d setting SYSTEMSCALE.  "
1679                                "Disabling sensitivity control\n",
1680                                dev->name, err);
1681
1682                         priv->has_sensitivity = 0;
1683                 }
1684         }
1685
1686         /* Set RTS threshold */
1687         err = hermes_write_wordrec(hw, USER_BAP, HERMES_RID_CNFRTSTHRESHOLD,
1688                                    priv->rts_thresh);
1689         if (err) {
1690                 printk(KERN_ERR "%s: Error %d setting RTS threshold\n",
1691                        dev->name, err);
1692                 return err;
1693         }
1694
1695         /* Set fragmentation threshold or MWO robustness */
1696         if (priv->has_mwo)
1697                 err = hermes_write_wordrec(hw, USER_BAP,
1698                                            HERMES_RID_CNFMWOROBUST_AGERE,
1699                                            priv->mwo_robust);
1700         else
1701                 err = hermes_write_wordrec(hw, USER_BAP,
1702                                            HERMES_RID_CNFFRAGMENTATIONTHRESHOLD,
1703                                            priv->frag_thresh);
1704         if (err) {
1705                 printk(KERN_ERR "%s: Error %d setting fragmentation\n",
1706                        dev->name, err);
1707                 return err;
1708         }
1709
1710         /* Set bitrate */
1711         err = __orinoco_hw_set_bitrate(priv);
1712         if (err) {
1713                 printk(KERN_ERR "%s: Error %d setting bitrate\n",
1714                        dev->name, err);
1715                 return err;
1716         }
1717
1718         /* Set power management */
1719         if (priv->has_pm) {
1720                 err = hermes_write_wordrec(hw, USER_BAP,
1721                                            HERMES_RID_CNFPMENABLED,
1722                                            priv->pm_on);
1723                 if (err) {
1724                         printk(KERN_ERR "%s: Error %d setting up PM\n",
1725                                dev->name, err);
1726                         return err;
1727                 }
1728
1729                 err = hermes_write_wordrec(hw, USER_BAP,
1730                                            HERMES_RID_CNFMULTICASTRECEIVE,
1731                                            priv->pm_mcast);
1732                 if (err) {
1733                         printk(KERN_ERR "%s: Error %d setting up PM\n",
1734                                dev->name, err);
1735                         return err;
1736                 }
1737                 err = hermes_write_wordrec(hw, USER_BAP,
1738                                            HERMES_RID_CNFMAXSLEEPDURATION,
1739                                            priv->pm_period);
1740                 if (err) {
1741                         printk(KERN_ERR "%s: Error %d setting up PM\n",
1742                                dev->name, err);
1743                         return err;
1744                 }
1745                 err = hermes_write_wordrec(hw, USER_BAP,
1746                                            HERMES_RID_CNFPMHOLDOVERDURATION,
1747                                            priv->pm_timeout);
1748                 if (err) {
1749                         printk(KERN_ERR "%s: Error %d setting up PM\n",
1750                                dev->name, err);
1751                         return err;
1752                 }
1753         }
1754
1755         /* Set preamble - only for Symbol so far... */
1756         if (priv->has_preamble) {
1757                 err = hermes_write_wordrec(hw, USER_BAP,
1758                                            HERMES_RID_CNFPREAMBLE_SYMBOL,
1759                                            priv->preamble);
1760                 if (err) {
1761                         printk(KERN_ERR "%s: Error %d setting preamble\n",
1762                                dev->name, err);
1763                         return err;
1764                 }
1765         }
1766
1767         /* Set up encryption */
1768         if (priv->has_wep) {
1769                 err = __orinoco_hw_setup_wep(priv);
1770                 if (err) {
1771                         printk(KERN_ERR "%s: Error %d activating WEP\n",
1772                                dev->name, err);
1773                         return err;
1774                 }
1775         }
1776
1777         if (priv->iw_mode == IW_MODE_MONITOR) {
1778                 /* Enable monitor mode */
1779                 dev->type = ARPHRD_IEEE80211;
1780                 err = hermes_docmd_wait(hw, HERMES_CMD_TEST | 
1781                                             HERMES_TEST_MONITOR, 0, NULL);
1782         } else {
1783                 /* Disable monitor mode */
1784                 dev->type = ARPHRD_ETHER;
1785                 err = hermes_docmd_wait(hw, HERMES_CMD_TEST |
1786                                             HERMES_TEST_STOP, 0, NULL);
1787         }
1788         if (err)
1789                 return err;
1790
1791         /* Set promiscuity / multicast*/
1792         priv->promiscuous = 0;
1793         priv->mc_count = 0;
1794
1795         /* FIXME: what about netif_tx_lock */
1796         __orinoco_set_multicast_list(dev);
1797
1798         return 0;
1799 }
1800
1801 /* FIXME: return int? */
1802 static void
1803 __orinoco_set_multicast_list(struct net_device *dev)
1804 {
1805         struct orinoco_private *priv = netdev_priv(dev);
1806         hermes_t *hw = &priv->hw;
1807         int err = 0;
1808         int promisc, mc_count;
1809
1810         /* The Hermes doesn't seem to have an allmulti mode, so we go
1811          * into promiscuous mode and let the upper levels deal. */
1812         if ( (dev->flags & IFF_PROMISC) || (dev->flags & IFF_ALLMULTI) ||
1813              (dev->mc_count > MAX_MULTICAST(priv)) ) {
1814                 promisc = 1;
1815                 mc_count = 0;
1816         } else {
1817                 promisc = 0;
1818                 mc_count = dev->mc_count;
1819         }
1820
1821         if (promisc != priv->promiscuous) {
1822                 err = hermes_write_wordrec(hw, USER_BAP,
1823                                            HERMES_RID_CNFPROMISCUOUSMODE,
1824                                            promisc);
1825                 if (err) {
1826                         printk(KERN_ERR "%s: Error %d setting PROMISCUOUSMODE to 1.\n",
1827                                dev->name, err);
1828                 } else 
1829                         priv->promiscuous = promisc;
1830         }
1831
1832         if (! promisc && (mc_count || priv->mc_count) ) {
1833                 struct dev_mc_list *p = dev->mc_list;
1834                 struct hermes_multicast mclist;
1835                 int i;
1836
1837                 for (i = 0; i < mc_count; i++) {
1838                         /* paranoia: is list shorter than mc_count? */
1839                         BUG_ON(! p);
1840                         /* paranoia: bad address size in list? */
1841                         BUG_ON(p->dmi_addrlen != ETH_ALEN);
1842                         
1843                         memcpy(mclist.addr[i], p->dmi_addr, ETH_ALEN);
1844                         p = p->next;
1845                 }
1846                 
1847                 if (p)
1848                         printk(KERN_WARNING "%s: Multicast list is "
1849                                "longer than mc_count\n", dev->name);
1850
1851                 err = hermes_write_ltv(hw, USER_BAP, HERMES_RID_CNFGROUPADDRESSES,
1852                                        HERMES_BYTES_TO_RECLEN(priv->mc_count * ETH_ALEN),
1853                                        &mclist);
1854                 if (err)
1855                         printk(KERN_ERR "%s: Error %d setting multicast list.\n",
1856                                dev->name, err);
1857                 else
1858                         priv->mc_count = mc_count;
1859         }
1860
1861         /* Since we can set the promiscuous flag when it wasn't asked
1862            for, make sure the net_device knows about it. */
1863         if (priv->promiscuous)
1864                 dev->flags |= IFF_PROMISC;
1865         else
1866                 dev->flags &= ~IFF_PROMISC;
1867 }
1868
1869 /* This must be called from user context, without locks held - use
1870  * schedule_work() */
1871 static void orinoco_reset(struct work_struct *work)
1872 {
1873         struct orinoco_private *priv =
1874                 container_of(work, struct orinoco_private, reset_work);
1875         struct net_device *dev = priv->ndev;
1876         struct hermes *hw = &priv->hw;
1877         int err;
1878         unsigned long flags;
1879
1880         if (orinoco_lock(priv, &flags) != 0)
1881                 /* When the hardware becomes available again, whatever
1882                  * detects that is responsible for re-initializing
1883                  * it. So no need for anything further */
1884                 return;
1885
1886         netif_stop_queue(dev);
1887
1888         /* Shut off interrupts.  Depending on what state the hardware
1889          * is in, this might not work, but we'll try anyway */
1890         hermes_set_irqmask(hw, 0);
1891         hermes_write_regn(hw, EVACK, 0xffff);
1892
1893         priv->hw_unavailable++;
1894         priv->last_linkstatus = 0xffff; /* firmware will have to reassociate */
1895         netif_carrier_off(dev);
1896
1897         orinoco_unlock(priv, &flags);
1898
1899         /* Scanning support: Cleanup of driver struct */
1900         kfree(priv->scan_result);
1901         priv->scan_result = NULL;
1902         priv->scan_inprogress = 0;
1903
1904         if (priv->hard_reset) {
1905                 err = (*priv->hard_reset)(priv);
1906                 if (err) {
1907                         printk(KERN_ERR "%s: orinoco_reset: Error %d "
1908                                "performing hard reset\n", dev->name, err);
1909                         goto disable;
1910                 }
1911         }
1912
1913         err = orinoco_reinit_firmware(dev);
1914         if (err) {
1915                 printk(KERN_ERR "%s: orinoco_reset: Error %d re-initializing firmware\n",
1916                        dev->name, err);
1917                 goto disable;
1918         }
1919
1920         spin_lock_irq(&priv->lock); /* This has to be called from user context */
1921
1922         priv->hw_unavailable--;
1923
1924         /* priv->open or priv->hw_unavailable might have changed while
1925          * we dropped the lock */
1926         if (priv->open && (! priv->hw_unavailable)) {
1927                 err = __orinoco_up(dev);
1928                 if (err) {
1929                         printk(KERN_ERR "%s: orinoco_reset: Error %d reenabling card\n",
1930                                dev->name, err);
1931                 } else
1932                         dev->trans_start = jiffies;
1933         }
1934
1935         spin_unlock_irq(&priv->lock);
1936
1937         return;
1938  disable:
1939         hermes_set_irqmask(hw, 0);
1940         netif_device_detach(dev);
1941         printk(KERN_ERR "%s: Device has been disabled!\n", dev->name);
1942 }
1943
1944 /********************************************************************/
1945 /* Interrupt handler                                                */
1946 /********************************************************************/
1947
1948 static void __orinoco_ev_tick(struct net_device *dev, hermes_t *hw)
1949 {
1950         printk(KERN_DEBUG "%s: TICK\n", dev->name);
1951 }
1952
1953 static void __orinoco_ev_wterr(struct net_device *dev, hermes_t *hw)
1954 {
1955         /* This seems to happen a fair bit under load, but ignoring it
1956            seems to work fine...*/
1957         printk(KERN_DEBUG "%s: MAC controller error (WTERR). Ignoring.\n",
1958                dev->name);
1959 }
1960
1961 irqreturn_t orinoco_interrupt(int irq, void *dev_id)
1962 {
1963         struct net_device *dev = dev_id;
1964         struct orinoco_private *priv = netdev_priv(dev);
1965         hermes_t *hw = &priv->hw;
1966         int count = MAX_IRQLOOPS_PER_IRQ;
1967         u16 evstat, events;
1968         /* These are used to detect a runaway interrupt situation */
1969         /* If we get more than MAX_IRQLOOPS_PER_JIFFY iterations in a jiffy,
1970          * we panic and shut down the hardware */
1971         static int last_irq_jiffy = 0; /* jiffies value the last time
1972                                         * we were called */
1973         static int loops_this_jiffy = 0;
1974         unsigned long flags;
1975
1976         if (orinoco_lock(priv, &flags) != 0) {
1977                 /* If hw is unavailable - we don't know if the irq was
1978                  * for us or not */
1979                 return IRQ_HANDLED;
1980         }
1981
1982         evstat = hermes_read_regn(hw, EVSTAT);
1983         events = evstat & hw->inten;
1984         if (! events) {
1985                 orinoco_unlock(priv, &flags);
1986                 return IRQ_NONE;
1987         }
1988         
1989         if (jiffies != last_irq_jiffy)
1990                 loops_this_jiffy = 0;
1991         last_irq_jiffy = jiffies;
1992
1993         while (events && count--) {
1994                 if (++loops_this_jiffy > MAX_IRQLOOPS_PER_JIFFY) {
1995                         printk(KERN_WARNING "%s: IRQ handler is looping too "
1996                                "much! Resetting.\n", dev->name);
1997                         /* Disable interrupts for now */
1998                         hermes_set_irqmask(hw, 0);
1999                         schedule_work(&priv->reset_work);
2000                         break;
2001                 }
2002
2003                 /* Check the card hasn't been removed */
2004                 if (! hermes_present(hw)) {
2005                         DEBUG(0, "orinoco_interrupt(): card removed\n");
2006                         break;
2007                 }
2008
2009                 if (events & HERMES_EV_TICK)
2010                         __orinoco_ev_tick(dev, hw);
2011                 if (events & HERMES_EV_WTERR)
2012                         __orinoco_ev_wterr(dev, hw);
2013                 if (events & HERMES_EV_INFDROP)
2014                         __orinoco_ev_infdrop(dev, hw);
2015                 if (events & HERMES_EV_INFO)
2016                         __orinoco_ev_info(dev, hw);
2017                 if (events & HERMES_EV_RX)
2018                         __orinoco_ev_rx(dev, hw);
2019                 if (events & HERMES_EV_TXEXC)
2020                         __orinoco_ev_txexc(dev, hw);
2021                 if (events & HERMES_EV_TX)
2022                         __orinoco_ev_tx(dev, hw);
2023                 if (events & HERMES_EV_ALLOC)
2024                         __orinoco_ev_alloc(dev, hw);
2025                 
2026                 hermes_write_regn(hw, EVACK, evstat);
2027
2028                 evstat = hermes_read_regn(hw, EVSTAT);
2029                 events = evstat & hw->inten;
2030         };
2031
2032         orinoco_unlock(priv, &flags);
2033         return IRQ_HANDLED;
2034 }
2035
2036 /********************************************************************/
2037 /* Initialization                                                   */
2038 /********************************************************************/
2039
2040 struct comp_id {
2041         u16 id, variant, major, minor;
2042 } __attribute__ ((packed));
2043
2044 static inline fwtype_t determine_firmware_type(struct comp_id *nic_id)
2045 {
2046         if (nic_id->id < 0x8000)
2047                 return FIRMWARE_TYPE_AGERE;
2048         else if (nic_id->id == 0x8000 && nic_id->major == 0)
2049                 return FIRMWARE_TYPE_SYMBOL;
2050         else
2051                 return FIRMWARE_TYPE_INTERSIL;
2052 }
2053
2054 /* Set priv->firmware type, determine firmware properties */
2055 static int determine_firmware(struct net_device *dev)
2056 {
2057         struct orinoco_private *priv = netdev_priv(dev);
2058         hermes_t *hw = &priv->hw;
2059         int err;
2060         struct comp_id nic_id, sta_id;
2061         unsigned int firmver;
2062         char tmp[SYMBOL_MAX_VER_LEN+1];
2063
2064         /* Get the hardware version */
2065         err = HERMES_READ_RECORD(hw, USER_BAP, HERMES_RID_NICID, &nic_id);
2066         if (err) {
2067                 printk(KERN_ERR "%s: Cannot read hardware identity: error %d\n",
2068                        dev->name, err);
2069                 return err;
2070         }
2071
2072         le16_to_cpus(&nic_id.id);
2073         le16_to_cpus(&nic_id.variant);
2074         le16_to_cpus(&nic_id.major);
2075         le16_to_cpus(&nic_id.minor);
2076         printk(KERN_DEBUG "%s: Hardware identity %04x:%04x:%04x:%04x\n",
2077                dev->name, nic_id.id, nic_id.variant,
2078                nic_id.major, nic_id.minor);
2079
2080         priv->firmware_type = determine_firmware_type(&nic_id);
2081
2082         /* Get the firmware version */
2083         err = HERMES_READ_RECORD(hw, USER_BAP, HERMES_RID_STAID, &sta_id);
2084         if (err) {
2085                 printk(KERN_ERR "%s: Cannot read station identity: error %d\n",
2086                        dev->name, err);
2087                 return err;
2088         }
2089
2090         le16_to_cpus(&sta_id.id);
2091         le16_to_cpus(&sta_id.variant);
2092         le16_to_cpus(&sta_id.major);
2093         le16_to_cpus(&sta_id.minor);
2094         printk(KERN_DEBUG "%s: Station identity  %04x:%04x:%04x:%04x\n",
2095                dev->name, sta_id.id, sta_id.variant,
2096                sta_id.major, sta_id.minor);
2097
2098         switch (sta_id.id) {
2099         case 0x15:
2100                 printk(KERN_ERR "%s: Primary firmware is active\n",
2101                        dev->name);
2102                 return -ENODEV;
2103         case 0x14b:
2104                 printk(KERN_ERR "%s: Tertiary firmware is active\n",
2105                        dev->name);
2106                 return -ENODEV;
2107         case 0x1f:      /* Intersil, Agere, Symbol Spectrum24 */
2108         case 0x21:      /* Symbol Spectrum24 Trilogy */
2109                 break;
2110         default:
2111                 printk(KERN_NOTICE "%s: Unknown station ID, please report\n",
2112                        dev->name);
2113                 break;
2114         }
2115
2116         /* Default capabilities */
2117         priv->has_sensitivity = 1;
2118         priv->has_mwo = 0;
2119         priv->has_preamble = 0;
2120         priv->has_port3 = 1;
2121         priv->has_ibss = 1;
2122         priv->has_wep = 0;
2123         priv->has_big_wep = 0;
2124
2125         /* Determine capabilities from the firmware version */
2126         switch (priv->firmware_type) {
2127         case FIRMWARE_TYPE_AGERE:
2128                 /* Lucent Wavelan IEEE, Lucent Orinoco, Cabletron RoamAbout,
2129                    ELSA, Melco, HP, IBM, Dell 1150, Compaq 110/210 */
2130                 snprintf(priv->fw_name, sizeof(priv->fw_name) - 1,
2131                          "Lucent/Agere %d.%02d", sta_id.major, sta_id.minor);
2132
2133                 firmver = ((unsigned long)sta_id.major << 16) | sta_id.minor;
2134
2135                 priv->has_ibss = (firmver >= 0x60006);
2136                 priv->has_wep = (firmver >= 0x40020);
2137                 priv->has_big_wep = 1; /* FIXME: this is wrong - how do we tell
2138                                           Gold cards from the others? */
2139                 priv->has_mwo = (firmver >= 0x60000);
2140                 priv->has_pm = (firmver >= 0x40020); /* Don't work in 7.52 ? */
2141                 priv->ibss_port = 1;
2142                 priv->has_hostscan = (firmver >= 0x8000a);
2143                 priv->broken_monitor = (firmver >= 0x80000);
2144
2145                 /* Tested with Agere firmware :
2146                  *      1.16 ; 4.08 ; 4.52 ; 6.04 ; 6.16 ; 7.28 => Jean II
2147                  * Tested CableTron firmware : 4.32 => Anton */
2148                 break;
2149         case FIRMWARE_TYPE_SYMBOL:
2150                 /* Symbol , 3Com AirConnect, Intel, Ericsson WLAN */
2151                 /* Intel MAC : 00:02:B3:* */
2152                 /* 3Com MAC : 00:50:DA:* */
2153                 memset(tmp, 0, sizeof(tmp));
2154                 /* Get the Symbol firmware version */
2155                 err = hermes_read_ltv(hw, USER_BAP,
2156                                       HERMES_RID_SECONDARYVERSION_SYMBOL,
2157                                       SYMBOL_MAX_VER_LEN, NULL, &tmp);
2158                 if (err) {
2159                         printk(KERN_WARNING
2160                                "%s: Error %d reading Symbol firmware info. Wildly guessing capabilities...\n",
2161                                dev->name, err);
2162                         firmver = 0;
2163                         tmp[0] = '\0';
2164                 } else {
2165                         /* The firmware revision is a string, the format is
2166                          * something like : "V2.20-01".
2167                          * Quick and dirty parsing... - Jean II
2168                          */
2169                         firmver = ((tmp[1] - '0') << 16) | ((tmp[3] - '0') << 12)
2170                                 | ((tmp[4] - '0') << 8) | ((tmp[6] - '0') << 4)
2171                                 | (tmp[7] - '0');
2172
2173                         tmp[SYMBOL_MAX_VER_LEN] = '\0';
2174                 }
2175
2176                 snprintf(priv->fw_name, sizeof(priv->fw_name) - 1,
2177                          "Symbol %s", tmp);
2178
2179                 priv->has_ibss = (firmver >= 0x20000);
2180                 priv->has_wep = (firmver >= 0x15012);
2181                 priv->has_big_wep = (firmver >= 0x20000);
2182                 priv->has_pm = (firmver >= 0x20000 && firmver < 0x22000) || 
2183                                (firmver >= 0x29000 && firmver < 0x30000) ||
2184                                firmver >= 0x31000;
2185                 priv->has_preamble = (firmver >= 0x20000);
2186                 priv->ibss_port = 4;
2187                 priv->broken_disableport = (firmver == 0x25013) ||
2188                                            (firmver >= 0x30000 && firmver <= 0x31000);
2189                 priv->has_hostscan = (firmver >= 0x31001) ||
2190                                      (firmver >= 0x29057 && firmver < 0x30000);
2191                 /* Tested with Intel firmware : 0x20015 => Jean II */
2192                 /* Tested with 3Com firmware : 0x15012 & 0x22001 => Jean II */
2193                 break;
2194         case FIRMWARE_TYPE_INTERSIL:
2195                 /* D-Link, Linksys, Adtron, ZoomAir, and many others...
2196                  * Samsung, Compaq 100/200 and Proxim are slightly
2197                  * different and less well tested */
2198                 /* D-Link MAC : 00:40:05:* */
2199                 /* Addtron MAC : 00:90:D1:* */
2200                 snprintf(priv->fw_name, sizeof(priv->fw_name) - 1,
2201                          "Intersil %d.%d.%d", sta_id.major, sta_id.minor,
2202                          sta_id.variant);
2203
2204                 firmver = ((unsigned long)sta_id.major << 16) |
2205                         ((unsigned long)sta_id.minor << 8) | sta_id.variant;
2206
2207                 priv->has_ibss = (firmver >= 0x000700); /* FIXME */
2208                 priv->has_big_wep = priv->has_wep = (firmver >= 0x000800);
2209                 priv->has_pm = (firmver >= 0x000700);
2210                 priv->has_hostscan = (firmver >= 0x010301);
2211
2212                 if (firmver >= 0x000800)
2213                         priv->ibss_port = 0;
2214                 else {
2215                         printk(KERN_NOTICE "%s: Intersil firmware earlier "
2216                                "than v0.8.x - several features not supported\n",
2217                                dev->name);
2218                         priv->ibss_port = 1;
2219                 }
2220                 break;
2221         }
2222         printk(KERN_DEBUG "%s: Firmware determined as %s\n", dev->name,
2223                priv->fw_name);
2224
2225         return 0;
2226 }
2227
2228 static int orinoco_init(struct net_device *dev)
2229 {
2230         struct orinoco_private *priv = netdev_priv(dev);
2231         hermes_t *hw = &priv->hw;
2232         int err = 0;
2233         struct hermes_idstring nickbuf;
2234         u16 reclen;
2235         int len;
2236
2237         /* No need to lock, the hw_unavailable flag is already set in
2238          * alloc_orinocodev() */
2239         priv->nicbuf_size = IEEE80211_FRAME_LEN + ETH_HLEN;
2240
2241         /* Initialize the firmware */
2242         err = hermes_init(hw);
2243         if (err != 0) {
2244                 printk(KERN_ERR "%s: failed to initialize firmware (err = %d)\n",
2245                        dev->name, err);
2246                 goto out;
2247         }
2248
2249         err = determine_firmware(dev);
2250         if (err != 0) {
2251                 printk(KERN_ERR "%s: Incompatible firmware, aborting\n",
2252                        dev->name);
2253                 goto out;
2254         }
2255
2256         if (priv->has_port3)
2257                 printk(KERN_DEBUG "%s: Ad-hoc demo mode supported\n", dev->name);
2258         if (priv->has_ibss)
2259                 printk(KERN_DEBUG "%s: IEEE standard IBSS ad-hoc mode supported\n",
2260                        dev->name);
2261         if (priv->has_wep) {
2262                 printk(KERN_DEBUG "%s: WEP supported, ", dev->name);
2263                 if (priv->has_big_wep)
2264                         printk("104-bit key\n");
2265                 else
2266                         printk("40-bit key\n");
2267         }
2268
2269         /* Get the MAC address */
2270         err = hermes_read_ltv(hw, USER_BAP, HERMES_RID_CNFOWNMACADDR,
2271                               ETH_ALEN, NULL, dev->dev_addr);
2272         if (err) {
2273                 printk(KERN_WARNING "%s: failed to read MAC address!\n",
2274                        dev->name);
2275                 goto out;
2276         }
2277
2278         printk(KERN_DEBUG "%s: MAC address %02X:%02X:%02X:%02X:%02X:%02X\n",
2279                dev->name, dev->dev_addr[0], dev->dev_addr[1],
2280                dev->dev_addr[2], dev->dev_addr[3], dev->dev_addr[4],
2281                dev->dev_addr[5]);
2282
2283         /* Get the station name */
2284         err = hermes_read_ltv(hw, USER_BAP, HERMES_RID_CNFOWNNAME,
2285                               sizeof(nickbuf), &reclen, &nickbuf);
2286         if (err) {
2287                 printk(KERN_ERR "%s: failed to read station name\n",
2288                        dev->name);
2289                 goto out;
2290         }
2291         if (nickbuf.len)
2292                 len = min(IW_ESSID_MAX_SIZE, (int)le16_to_cpu(nickbuf.len));
2293         else
2294                 len = min(IW_ESSID_MAX_SIZE, 2 * reclen);
2295         memcpy(priv->nick, &nickbuf.val, len);
2296         priv->nick[len] = '\0';
2297
2298         printk(KERN_DEBUG "%s: Station name \"%s\"\n", dev->name, priv->nick);
2299
2300         err = orinoco_allocate_fid(dev);
2301         if (err) {
2302                 printk(KERN_ERR "%s: failed to allocate NIC buffer!\n",
2303                        dev->name);
2304                 goto out;
2305         }
2306
2307         /* Get allowed channels */
2308         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CHANNELLIST,
2309                                   &priv->channel_mask);
2310         if (err) {
2311                 printk(KERN_ERR "%s: failed to read channel list!\n",
2312                        dev->name);
2313                 goto out;
2314         }
2315
2316         /* Get initial AP density */
2317         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CNFSYSTEMSCALE,
2318                                   &priv->ap_density);
2319         if (err || priv->ap_density < 1 || priv->ap_density > 3) {
2320                 priv->has_sensitivity = 0;
2321         }
2322
2323         /* Get initial RTS threshold */
2324         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CNFRTSTHRESHOLD,
2325                                   &priv->rts_thresh);
2326         if (err) {
2327                 printk(KERN_ERR "%s: failed to read RTS threshold!\n",
2328                        dev->name);
2329                 goto out;
2330         }
2331
2332         /* Get initial fragmentation settings */
2333         if (priv->has_mwo)
2334                 err = hermes_read_wordrec(hw, USER_BAP,
2335                                           HERMES_RID_CNFMWOROBUST_AGERE,
2336                                           &priv->mwo_robust);
2337         else
2338                 err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CNFFRAGMENTATIONTHRESHOLD,
2339                                           &priv->frag_thresh);
2340         if (err) {
2341                 printk(KERN_ERR "%s: failed to read fragmentation settings!\n",
2342                        dev->name);
2343                 goto out;
2344         }
2345
2346         /* Power management setup */
2347         if (priv->has_pm) {
2348                 priv->pm_on = 0;
2349                 priv->pm_mcast = 1;
2350                 err = hermes_read_wordrec(hw, USER_BAP,
2351                                           HERMES_RID_CNFMAXSLEEPDURATION,
2352                                           &priv->pm_period);
2353                 if (err) {
2354                         printk(KERN_ERR "%s: failed to read power management period!\n",
2355                                dev->name);
2356                         goto out;
2357                 }
2358                 err = hermes_read_wordrec(hw, USER_BAP,
2359                                           HERMES_RID_CNFPMHOLDOVERDURATION,
2360                                           &priv->pm_timeout);
2361                 if (err) {
2362                         printk(KERN_ERR "%s: failed to read power management timeout!\n",
2363                                dev->name);
2364                         goto out;
2365                 }
2366         }
2367
2368         /* Preamble setup */
2369         if (priv->has_preamble) {
2370                 err = hermes_read_wordrec(hw, USER_BAP,
2371                                           HERMES_RID_CNFPREAMBLE_SYMBOL,
2372                                           &priv->preamble);
2373                 if (err)
2374                         goto out;
2375         }
2376                 
2377         /* Set up the default configuration */
2378         priv->iw_mode = IW_MODE_INFRA;
2379         /* By default use IEEE/IBSS ad-hoc mode if we have it */
2380         priv->prefer_port3 = priv->has_port3 && (! priv->has_ibss);
2381         set_port_type(priv);
2382         priv->channel = 0; /* use firmware default */
2383
2384         priv->promiscuous = 0;
2385         priv->wep_on = 0;
2386         priv->tx_key = 0;
2387
2388         /* Make the hardware available, as long as it hasn't been
2389          * removed elsewhere (e.g. by PCMCIA hot unplug) */
2390         spin_lock_irq(&priv->lock);
2391         priv->hw_unavailable--;
2392         spin_unlock_irq(&priv->lock);
2393
2394         printk(KERN_DEBUG "%s: ready\n", dev->name);
2395
2396  out:
2397         return err;
2398 }
2399
2400 struct net_device *alloc_orinocodev(int sizeof_card,
2401                                     int (*hard_reset)(struct orinoco_private *))
2402 {
2403         struct net_device *dev;
2404         struct orinoco_private *priv;
2405
2406         dev = alloc_etherdev(sizeof(struct orinoco_private) + sizeof_card);
2407         if (! dev)
2408                 return NULL;
2409         priv = netdev_priv(dev);
2410         priv->ndev = dev;
2411         if (sizeof_card)
2412                 priv->card = (void *)((unsigned long)priv
2413                                       + sizeof(struct orinoco_private));
2414         else
2415                 priv->card = NULL;
2416
2417         /* Setup / override net_device fields */
2418         dev->init = orinoco_init;
2419         dev->hard_start_xmit = orinoco_xmit;
2420         dev->tx_timeout = orinoco_tx_timeout;
2421         dev->watchdog_timeo = HZ; /* 1 second timeout */
2422         dev->get_stats = orinoco_get_stats;
2423         dev->ethtool_ops = &orinoco_ethtool_ops;
2424         dev->wireless_handlers = (struct iw_handler_def *)&orinoco_handler_def;
2425 #ifdef WIRELESS_SPY
2426         priv->wireless_data.spy_data = &priv->spy_data;
2427         dev->wireless_data = &priv->wireless_data;
2428 #endif
2429         dev->change_mtu = orinoco_change_mtu;
2430         dev->set_multicast_list = orinoco_set_multicast_list;
2431         /* we use the default eth_mac_addr for setting the MAC addr */
2432
2433         /* Set up default callbacks */
2434         dev->open = orinoco_open;
2435         dev->stop = orinoco_stop;
2436         priv->hard_reset = hard_reset;
2437
2438         spin_lock_init(&priv->lock);
2439         priv->open = 0;
2440         priv->hw_unavailable = 1; /* orinoco_init() must clear this
2441                                    * before anything else touches the
2442                                    * hardware */
2443         INIT_WORK(&priv->reset_work, orinoco_reset);
2444         INIT_WORK(&priv->join_work, orinoco_join_ap);
2445         INIT_WORK(&priv->wevent_work, orinoco_send_wevents);
2446
2447         netif_carrier_off(dev);
2448         priv->last_linkstatus = 0xffff;
2449
2450         return dev;
2451
2452 }
2453
2454 void free_orinocodev(struct net_device *dev)
2455 {
2456         struct orinoco_private *priv = netdev_priv(dev);
2457
2458         kfree(priv->scan_result);
2459         free_netdev(dev);
2460 }
2461
2462 /********************************************************************/
2463 /* Wireless extensions                                              */
2464 /********************************************************************/
2465
2466 /* Return : < 0 -> error code ; >= 0 -> length */
2467 static int orinoco_hw_get_essid(struct orinoco_private *priv, int *active,
2468                                 char buf[IW_ESSID_MAX_SIZE+1])
2469 {
2470         hermes_t *hw = &priv->hw;
2471         int err = 0;
2472         struct hermes_idstring essidbuf;
2473         char *p = (char *)(&essidbuf.val);
2474         int len;
2475         unsigned long flags;
2476
2477         if (orinoco_lock(priv, &flags) != 0)
2478                 return -EBUSY;
2479
2480         if (strlen(priv->desired_essid) > 0) {
2481                 /* We read the desired SSID from the hardware rather
2482                    than from priv->desired_essid, just in case the
2483                    firmware is allowed to change it on us. I'm not
2484                    sure about this */
2485                 /* My guess is that the OWNSSID should always be whatever
2486                  * we set to the card, whereas CURRENT_SSID is the one that
2487                  * may change... - Jean II */
2488                 u16 rid;
2489
2490                 *active = 1;
2491
2492                 rid = (priv->port_type == 3) ? HERMES_RID_CNFOWNSSID :
2493                         HERMES_RID_CNFDESIREDSSID;
2494                 
2495                 err = hermes_read_ltv(hw, USER_BAP, rid, sizeof(essidbuf),
2496                                       NULL, &essidbuf);
2497                 if (err)
2498                         goto fail_unlock;
2499         } else {
2500                 *active = 0;
2501
2502                 err = hermes_read_ltv(hw, USER_BAP, HERMES_RID_CURRENTSSID,
2503                                       sizeof(essidbuf), NULL, &essidbuf);
2504                 if (err)
2505                         goto fail_unlock;
2506         }
2507
2508         len = le16_to_cpu(essidbuf.len);
2509         BUG_ON(len > IW_ESSID_MAX_SIZE);
2510
2511         memset(buf, 0, IW_ESSID_MAX_SIZE);
2512         memcpy(buf, p, len);
2513         err = len;
2514
2515  fail_unlock:
2516         orinoco_unlock(priv, &flags);
2517
2518         return err;       
2519 }
2520
2521 static long orinoco_hw_get_freq(struct orinoco_private *priv)
2522 {
2523         
2524         hermes_t *hw = &priv->hw;
2525         int err = 0;
2526         u16 channel;
2527         long freq = 0;
2528         unsigned long flags;
2529
2530         if (orinoco_lock(priv, &flags) != 0)
2531                 return -EBUSY;
2532         
2533         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CURRENTCHANNEL, &channel);
2534         if (err)
2535                 goto out;
2536
2537         /* Intersil firmware 1.3.5 returns 0 when the interface is down */
2538         if (channel == 0) {
2539                 err = -EBUSY;
2540                 goto out;
2541         }
2542
2543         if ( (channel < 1) || (channel > NUM_CHANNELS) ) {
2544                 printk(KERN_WARNING "%s: Channel out of range (%d)!\n",
2545                        priv->ndev->name, channel);
2546                 err = -EBUSY;
2547                 goto out;
2548
2549         }
2550         freq = channel_frequency[channel-1] * 100000;
2551
2552  out:
2553         orinoco_unlock(priv, &flags);
2554
2555         if (err > 0)
2556                 err = -EBUSY;
2557         return err ? err : freq;
2558 }
2559
2560 static int orinoco_hw_get_bitratelist(struct orinoco_private *priv,
2561                                       int *numrates, s32 *rates, int max)
2562 {
2563         hermes_t *hw = &priv->hw;
2564         struct hermes_idstring list;
2565         unsigned char *p = (unsigned char *)&list.val;
2566         int err = 0;
2567         int num;
2568         int i;
2569         unsigned long flags;
2570
2571         if (orinoco_lock(priv, &flags) != 0)
2572                 return -EBUSY;
2573
2574         err = hermes_read_ltv(hw, USER_BAP, HERMES_RID_SUPPORTEDDATARATES,
2575                               sizeof(list), NULL, &list);
2576         orinoco_unlock(priv, &flags);
2577
2578         if (err)
2579                 return err;
2580         
2581         num = le16_to_cpu(list.len);
2582         *numrates = num;
2583         num = min(num, max);
2584
2585         for (i = 0; i < num; i++) {
2586                 rates[i] = (p[i] & 0x7f) * 500000; /* convert to bps */
2587         }
2588
2589         return 0;
2590 }
2591
2592 static int orinoco_ioctl_getname(struct net_device *dev,
2593                                  struct iw_request_info *info,
2594                                  char *name,
2595                                  char *extra)
2596 {
2597         struct orinoco_private *priv = netdev_priv(dev);
2598         int numrates;
2599         int err;
2600
2601         err = orinoco_hw_get_bitratelist(priv, &numrates, NULL, 0);
2602
2603         if (!err && (numrates > 2))
2604                 strcpy(name, "IEEE 802.11b");
2605         else
2606                 strcpy(name, "IEEE 802.11-DS");
2607
2608         return 0;
2609 }
2610
2611 static int orinoco_ioctl_setwap(struct net_device *dev,
2612                                 struct iw_request_info *info,
2613                                 struct sockaddr *ap_addr,
2614                                 char *extra)
2615 {
2616         struct orinoco_private *priv = netdev_priv(dev);
2617         int err = -EINPROGRESS;         /* Call commit handler */
2618         unsigned long flags;
2619         static const u8 off_addr[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
2620         static const u8 any_addr[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
2621
2622         if (orinoco_lock(priv, &flags) != 0)
2623                 return -EBUSY;
2624
2625         /* Enable automatic roaming - no sanity checks are needed */
2626         if (memcmp(&ap_addr->sa_data, off_addr, ETH_ALEN) == 0 ||
2627             memcmp(&ap_addr->sa_data, any_addr, ETH_ALEN) == 0) {
2628                 priv->bssid_fixed = 0;
2629                 memset(priv->desired_bssid, 0, ETH_ALEN);
2630
2631                 /* "off" means keep existing connection */
2632                 if (ap_addr->sa_data[0] == 0) {
2633                         __orinoco_hw_set_wap(priv);
2634                         err = 0;
2635                 }
2636                 goto out;
2637         }
2638
2639         if (priv->firmware_type == FIRMWARE_TYPE_AGERE) {
2640                 printk(KERN_WARNING "%s: Lucent/Agere firmware doesn't "
2641                        "support manual roaming\n",
2642                        dev->name);
2643                 err = -EOPNOTSUPP;
2644                 goto out;
2645         }
2646
2647         if (priv->iw_mode != IW_MODE_INFRA) {
2648                 printk(KERN_WARNING "%s: Manual roaming supported only in "
2649                        "managed mode\n", dev->name);
2650                 err = -EOPNOTSUPP;
2651                 goto out;
2652         }
2653
2654         /* Intersil firmware hangs without Desired ESSID */
2655         if (priv->firmware_type == FIRMWARE_TYPE_INTERSIL &&
2656             strlen(priv->desired_essid) == 0) {
2657                 printk(KERN_WARNING "%s: Desired ESSID must be set for "
2658                        "manual roaming\n", dev->name);
2659                 err = -EOPNOTSUPP;
2660                 goto out;
2661         }
2662
2663         /* Finally, enable manual roaming */
2664         priv->bssid_fixed = 1;
2665         memcpy(priv->desired_bssid, &ap_addr->sa_data, ETH_ALEN);
2666
2667  out:
2668         orinoco_unlock(priv, &flags);
2669         return err;
2670 }
2671
2672 static int orinoco_ioctl_getwap(struct net_device *dev,
2673                                 struct iw_request_info *info,
2674                                 struct sockaddr *ap_addr,
2675                                 char *extra)
2676 {
2677         struct orinoco_private *priv = netdev_priv(dev);
2678
2679         hermes_t *hw = &priv->hw;
2680         int err = 0;
2681         unsigned long flags;
2682
2683         if (orinoco_lock(priv, &flags) != 0)
2684                 return -EBUSY;
2685
2686         ap_addr->sa_family = ARPHRD_ETHER;
2687         err = hermes_read_ltv(hw, USER_BAP, HERMES_RID_CURRENTBSSID,
2688                               ETH_ALEN, NULL, ap_addr->sa_data);
2689
2690         orinoco_unlock(priv, &flags);
2691
2692         return err;
2693 }
2694
2695 static int orinoco_ioctl_setmode(struct net_device *dev,
2696                                  struct iw_request_info *info,
2697                                  u32 *mode,
2698                                  char *extra)
2699 {
2700         struct orinoco_private *priv = netdev_priv(dev);
2701         int err = -EINPROGRESS;         /* Call commit handler */
2702         unsigned long flags;
2703
2704         if (priv->iw_mode == *mode)
2705                 return 0;
2706
2707         if (orinoco_lock(priv, &flags) != 0)
2708                 return -EBUSY;
2709
2710         switch (*mode) {
2711         case IW_MODE_ADHOC:
2712                 if (!priv->has_ibss && !priv->has_port3)
2713                         err = -EOPNOTSUPP;
2714                 break;
2715
2716         case IW_MODE_INFRA:
2717                 break;
2718
2719         case IW_MODE_MONITOR:
2720                 if (priv->broken_monitor && !force_monitor) {
2721                         printk(KERN_WARNING "%s: Monitor mode support is "
2722                                "buggy in this firmware, not enabling\n",
2723                                dev->name);
2724                         err = -EOPNOTSUPP;
2725                 }
2726                 break;
2727
2728         default:
2729                 err = -EOPNOTSUPP;
2730                 break;
2731         }
2732
2733         if (err == -EINPROGRESS) {
2734                 priv->iw_mode = *mode;
2735                 set_port_type(priv);
2736         }
2737
2738         orinoco_unlock(priv, &flags);
2739
2740         return err;
2741 }
2742
2743 static int orinoco_ioctl_getmode(struct net_device *dev,
2744                                  struct iw_request_info *info,
2745                                  u32 *mode,
2746                                  char *extra)
2747 {
2748         struct orinoco_private *priv = netdev_priv(dev);
2749
2750         *mode = priv->iw_mode;
2751         return 0;
2752 }
2753
2754 static int orinoco_ioctl_getiwrange(struct net_device *dev,
2755                                     struct iw_request_info *info,
2756                                     struct iw_point *rrq,
2757                                     char *extra)
2758 {
2759         struct orinoco_private *priv = netdev_priv(dev);
2760         int err = 0;
2761         struct iw_range *range = (struct iw_range *) extra;
2762         int numrates;
2763         int i, k;
2764
2765         rrq->length = sizeof(struct iw_range);
2766         memset(range, 0, sizeof(struct iw_range));
2767
2768         range->we_version_compiled = WIRELESS_EXT;
2769         range->we_version_source = 14;
2770
2771         /* Set available channels/frequencies */
2772         range->num_channels = NUM_CHANNELS;
2773         k = 0;
2774         for (i = 0; i < NUM_CHANNELS; i++) {
2775                 if (priv->channel_mask & (1 << i)) {
2776                         range->freq[k].i = i + 1;
2777                         range->freq[k].m = channel_frequency[i] * 100000;
2778                         range->freq[k].e = 1;
2779                         k++;
2780                 }
2781                 
2782                 if (k >= IW_MAX_FREQUENCIES)
2783                         break;
2784         }
2785         range->num_frequency = k;
2786         range->sensitivity = 3;
2787
2788         if (priv->has_wep) {
2789                 range->max_encoding_tokens = ORINOCO_MAX_KEYS;
2790                 range->encoding_size[0] = SMALL_KEY_SIZE;
2791                 range->num_encoding_sizes = 1;
2792
2793                 if (priv->has_big_wep) {
2794                         range->encoding_size[1] = LARGE_KEY_SIZE;
2795                         range->num_encoding_sizes = 2;
2796                 }
2797         }
2798
2799         if ((priv->iw_mode == IW_MODE_ADHOC) && (!SPY_NUMBER(priv))){
2800                 /* Quality stats meaningless in ad-hoc mode */
2801         } else {
2802                 range->max_qual.qual = 0x8b - 0x2f;
2803                 range->max_qual.level = 0x2f - 0x95 - 1;
2804                 range->max_qual.noise = 0x2f - 0x95 - 1;
2805                 /* Need to get better values */
2806                 range->avg_qual.qual = 0x24;
2807                 range->avg_qual.level = 0xC2;
2808                 range->avg_qual.noise = 0x9E;
2809         }
2810
2811         err = orinoco_hw_get_bitratelist(priv, &numrates,
2812                                          range->bitrate, IW_MAX_BITRATES);
2813         if (err)
2814                 return err;
2815         range->num_bitrates = numrates;
2816
2817         /* Set an indication of the max TCP throughput in bit/s that we can
2818          * expect using this interface. May be use for QoS stuff...
2819          * Jean II */
2820         if (numrates > 2)
2821                 range->throughput = 5 * 1000 * 1000;    /* ~5 Mb/s */
2822         else
2823                 range->throughput = 1.5 * 1000 * 1000;  /* ~1.5 Mb/s */
2824
2825         range->min_rts = 0;
2826         range->max_rts = 2347;
2827         range->min_frag = 256;
2828         range->max_frag = 2346;
2829
2830         range->min_pmp = 0;
2831         range->max_pmp = 65535000;
2832         range->min_pmt = 0;
2833         range->max_pmt = 65535 * 1000;  /* ??? */
2834         range->pmp_flags = IW_POWER_PERIOD;
2835         range->pmt_flags = IW_POWER_TIMEOUT;
2836         range->pm_capa = IW_POWER_PERIOD | IW_POWER_TIMEOUT | IW_POWER_UNICAST_R;
2837
2838         range->retry_capa = IW_RETRY_LIMIT | IW_RETRY_LIFETIME;
2839         range->retry_flags = IW_RETRY_LIMIT;
2840         range->r_time_flags = IW_RETRY_LIFETIME;
2841         range->min_retry = 0;
2842         range->max_retry = 65535;       /* ??? */
2843         range->min_r_time = 0;
2844         range->max_r_time = 65535 * 1000;       /* ??? */
2845
2846         /* Event capability (kernel) */
2847         IW_EVENT_CAPA_SET_KERNEL(range->event_capa);
2848         /* Event capability (driver) */
2849         IW_EVENT_CAPA_SET(range->event_capa, SIOCGIWTHRSPY);
2850         IW_EVENT_CAPA_SET(range->event_capa, SIOCGIWAP);
2851         IW_EVENT_CAPA_SET(range->event_capa, SIOCGIWSCAN);
2852         IW_EVENT_CAPA_SET(range->event_capa, IWEVTXDROP);
2853
2854         return 0;
2855 }
2856
2857 static int orinoco_ioctl_setiwencode(struct net_device *dev,
2858                                      struct iw_request_info *info,
2859                                      struct iw_point *erq,
2860                                      char *keybuf)
2861 {
2862         struct orinoco_private *priv = netdev_priv(dev);
2863         int index = (erq->flags & IW_ENCODE_INDEX) - 1;
2864         int setindex = priv->tx_key;
2865         int enable = priv->wep_on;
2866         int restricted = priv->wep_restrict;
2867         u16 xlen = 0;
2868         int err = -EINPROGRESS;         /* Call commit handler */
2869         unsigned long flags;
2870
2871         if (! priv->has_wep)
2872                 return -EOPNOTSUPP;
2873
2874         if (erq->pointer) {
2875                 /* We actually have a key to set - check its length */
2876                 if (erq->length > LARGE_KEY_SIZE)
2877                         return -E2BIG;
2878
2879                 if ( (erq->length > SMALL_KEY_SIZE) && !priv->has_big_wep )
2880                         return -E2BIG;
2881         }
2882
2883         if (orinoco_lock(priv, &flags) != 0)
2884                 return -EBUSY;
2885
2886         if (erq->length > 0) {
2887                 if ((index < 0) || (index >= ORINOCO_MAX_KEYS))
2888                         index = priv->tx_key;
2889
2890                 /* Adjust key length to a supported value */
2891                 if (erq->length > SMALL_KEY_SIZE) {
2892                         xlen = LARGE_KEY_SIZE;
2893                 } else if (erq->length > 0) {
2894                         xlen = SMALL_KEY_SIZE;
2895                 } else
2896                         xlen = 0;
2897
2898                 /* Switch on WEP if off */
2899                 if ((!enable) && (xlen > 0)) {
2900                         setindex = index;
2901                         enable = 1;
2902                 }
2903         } else {
2904                 /* Important note : if the user do "iwconfig eth0 enc off",
2905                  * we will arrive there with an index of -1. This is valid
2906                  * but need to be taken care off... Jean II */
2907                 if ((index < 0) || (index >= ORINOCO_MAX_KEYS)) {
2908                         if((index != -1) || (erq->flags == 0)) {
2909                                 err = -EINVAL;
2910                                 goto out;
2911                         }
2912                 } else {
2913                         /* Set the index : Check that the key is valid */
2914                         if(priv->keys[index].len == 0) {
2915                                 err = -EINVAL;
2916                                 goto out;
2917                         }
2918                         setindex = index;
2919                 }
2920         }
2921
2922         if (erq->flags & IW_ENCODE_DISABLED)
2923                 enable = 0;
2924         if (erq->flags & IW_ENCODE_OPEN)
2925                 restricted = 0;
2926         if (erq->flags & IW_ENCODE_RESTRICTED)
2927                 restricted = 1;
2928
2929         if (erq->pointer && erq->length > 0) {
2930                 priv->keys[index].len = cpu_to_le16(xlen);
2931                 memset(priv->keys[index].data, 0,
2932                        sizeof(priv->keys[index].data));
2933                 memcpy(priv->keys[index].data, keybuf, erq->length);
2934         }
2935         priv->tx_key = setindex;
2936
2937         /* Try fast key change if connected and only keys are changed */
2938         if (priv->wep_on && enable && (priv->wep_restrict == restricted) &&
2939             netif_carrier_ok(dev)) {
2940                 err = __orinoco_hw_setup_wepkeys(priv);
2941                 /* No need to commit if successful */
2942                 goto out;
2943         }
2944
2945         priv->wep_on = enable;
2946         priv->wep_restrict = restricted;
2947
2948  out:
2949         orinoco_unlock(priv, &flags);
2950
2951         return err;
2952 }
2953
2954 static int orinoco_ioctl_getiwencode(struct net_device *dev,
2955                                      struct iw_request_info *info,
2956                                      struct iw_point *erq,
2957                                      char *keybuf)
2958 {
2959         struct orinoco_private *priv = netdev_priv(dev);
2960         int index = (erq->flags & IW_ENCODE_INDEX) - 1;
2961         u16 xlen = 0;
2962         unsigned long flags;
2963
2964         if (! priv->has_wep)
2965                 return -EOPNOTSUPP;
2966
2967         if (orinoco_lock(priv, &flags) != 0)
2968                 return -EBUSY;
2969
2970         if ((index < 0) || (index >= ORINOCO_MAX_KEYS))
2971                 index = priv->tx_key;
2972
2973         erq->flags = 0;
2974         if (! priv->wep_on)
2975                 erq->flags |= IW_ENCODE_DISABLED;
2976         erq->flags |= index + 1;
2977
2978         if (priv->wep_restrict)
2979                 erq->flags |= IW_ENCODE_RESTRICTED;
2980         else
2981                 erq->flags |= IW_ENCODE_OPEN;
2982
2983         xlen = le16_to_cpu(priv->keys[index].len);
2984
2985         erq->length = xlen;
2986
2987         memcpy(keybuf, priv->keys[index].data, ORINOCO_MAX_KEY_SIZE);
2988
2989         orinoco_unlock(priv, &flags);
2990         return 0;
2991 }
2992
2993 static int orinoco_ioctl_setessid(struct net_device *dev,
2994                                   struct iw_request_info *info,
2995                                   struct iw_point *erq,
2996                                   char *essidbuf)
2997 {
2998         struct orinoco_private *priv = netdev_priv(dev);
2999         unsigned long flags;
3000
3001         /* Note : ESSID is ignored in Ad-Hoc demo mode, but we can set it
3002          * anyway... - Jean II */
3003
3004         /* Hum... Should not use Wireless Extension constant (may change),
3005          * should use our own... - Jean II */
3006         if (erq->length > IW_ESSID_MAX_SIZE)
3007                 return -E2BIG;
3008
3009         if (orinoco_lock(priv, &flags) != 0)
3010                 return -EBUSY;
3011
3012         /* NULL the string (for NULL termination & ESSID = ANY) - Jean II */
3013         memset(priv->desired_essid, 0, sizeof(priv->desired_essid));
3014
3015         /* If not ANY, get the new ESSID */
3016         if (erq->flags) {
3017                 memcpy(priv->desired_essid, essidbuf, erq->length);
3018         }
3019
3020         orinoco_unlock(priv, &flags);
3021
3022         return -EINPROGRESS;            /* Call commit handler */
3023 }
3024
3025 static int orinoco_ioctl_getessid(struct net_device *dev,
3026                                   struct iw_request_info *info,
3027                                   struct iw_point *erq,
3028                                   char *essidbuf)
3029 {
3030         struct orinoco_private *priv = netdev_priv(dev);
3031         int active;
3032         int err = 0;
3033         unsigned long flags;
3034
3035         if (netif_running(dev)) {
3036                 err = orinoco_hw_get_essid(priv, &active, essidbuf);
3037                 if (err < 0)
3038                         return err;
3039                 erq->length = err;
3040         } else {
3041                 if (orinoco_lock(priv, &flags) != 0)
3042                         return -EBUSY;
3043                 memcpy(essidbuf, priv->desired_essid, IW_ESSID_MAX_SIZE);
3044                 erq->length = strlen(priv->desired_essid);
3045                 orinoco_unlock(priv, &flags);
3046         }
3047
3048         erq->flags = 1;
3049
3050         return 0;
3051 }
3052
3053 static int orinoco_ioctl_setnick(struct net_device *dev,
3054                                  struct iw_request_info *info,
3055                                  struct iw_point *nrq,
3056                                  char *nickbuf)
3057 {
3058         struct orinoco_private *priv = netdev_priv(dev);
3059         unsigned long flags;
3060
3061         if (nrq->length > IW_ESSID_MAX_SIZE)
3062                 return -E2BIG;
3063
3064         if (orinoco_lock(priv, &flags) != 0)
3065                 return -EBUSY;
3066
3067         memset(priv->nick, 0, sizeof(priv->nick));
3068         memcpy(priv->nick, nickbuf, nrq->length);
3069
3070         orinoco_unlock(priv, &flags);
3071
3072         return -EINPROGRESS;            /* Call commit handler */
3073 }
3074
3075 static int orinoco_ioctl_getnick(struct net_device *dev,
3076                                  struct iw_request_info *info,
3077                                  struct iw_point *nrq,
3078                                  char *nickbuf)
3079 {
3080         struct orinoco_private *priv = netdev_priv(dev);
3081         unsigned long flags;
3082
3083         if (orinoco_lock(priv, &flags) != 0)
3084                 return -EBUSY;
3085
3086         memcpy(nickbuf, priv->nick, IW_ESSID_MAX_SIZE);
3087         orinoco_unlock(priv, &flags);
3088
3089         nrq->length = strlen(priv->nick);
3090
3091         return 0;
3092 }
3093
3094 static int orinoco_ioctl_setfreq(struct net_device *dev,
3095                                  struct iw_request_info *info,
3096                                  struct iw_freq *frq,
3097                                  char *extra)
3098 {
3099         struct orinoco_private *priv = netdev_priv(dev);
3100         int chan = -1;
3101         unsigned long flags;
3102         int err = -EINPROGRESS;         /* Call commit handler */
3103
3104         /* In infrastructure mode the AP sets the channel */
3105         if (priv->iw_mode == IW_MODE_INFRA)
3106                 return -EBUSY;
3107
3108         if ( (frq->e == 0) && (frq->m <= 1000) ) {
3109                 /* Setting by channel number */
3110                 chan = frq->m;
3111         } else {
3112                 /* Setting by frequency - search the table */
3113                 int mult = 1;
3114                 int i;
3115
3116                 for (i = 0; i < (6 - frq->e); i++)
3117                         mult *= 10;
3118
3119                 for (i = 0; i < NUM_CHANNELS; i++)
3120                         if (frq->m == (channel_frequency[i] * mult))
3121                                 chan = i+1;
3122         }
3123
3124         if ( (chan < 1) || (chan > NUM_CHANNELS) ||
3125              ! (priv->channel_mask & (1 << (chan-1)) ) )
3126                 return -EINVAL;
3127
3128         if (orinoco_lock(priv, &flags) != 0)
3129                 return -EBUSY;
3130
3131         priv->channel = chan;
3132         if (priv->iw_mode == IW_MODE_MONITOR) {
3133                 /* Fast channel change - no commit if successful */
3134                 hermes_t *hw = &priv->hw;
3135                 err = hermes_docmd_wait(hw, HERMES_CMD_TEST |
3136                                             HERMES_TEST_SET_CHANNEL,
3137                                         chan, NULL);
3138         }
3139         orinoco_unlock(priv, &flags);
3140
3141         return err;
3142 }
3143
3144 static int orinoco_ioctl_getfreq(struct net_device *dev,
3145                                  struct iw_request_info *info,
3146                                  struct iw_freq *frq,
3147                                  char *extra)
3148 {
3149         struct orinoco_private *priv = netdev_priv(dev);
3150         int tmp;
3151
3152         /* Locking done in there */
3153         tmp = orinoco_hw_get_freq(priv);
3154         if (tmp < 0) {
3155                 return tmp;
3156         }
3157
3158         frq->m = tmp;
3159         frq->e = 1;
3160
3161         return 0;
3162 }
3163
3164 static int orinoco_ioctl_getsens(struct net_device *dev,
3165                                  struct iw_request_info *info,
3166                                  struct iw_param *srq,
3167                                  char *extra)
3168 {
3169         struct orinoco_private *priv = netdev_priv(dev);
3170         hermes_t *hw = &priv->hw;
3171         u16 val;
3172         int err;
3173         unsigned long flags;
3174
3175         if (!priv->has_sensitivity)
3176                 return -EOPNOTSUPP;
3177
3178         if (orinoco_lock(priv, &flags) != 0)
3179                 return -EBUSY;
3180         err = hermes_read_wordrec(hw, USER_BAP,
3181                                   HERMES_RID_CNFSYSTEMSCALE, &val);
3182         orinoco_unlock(priv, &flags);
3183
3184         if (err)
3185                 return err;
3186
3187         srq->value = val;
3188         srq->fixed = 0; /* auto */
3189
3190         return 0;
3191 }
3192
3193 static int orinoco_ioctl_setsens(struct net_device *dev,
3194                                  struct iw_request_info *info,
3195                                  struct iw_param *srq,
3196                                  char *extra)
3197 {
3198         struct orinoco_private *priv = netdev_priv(dev);
3199         int val = srq->value;
3200         unsigned long flags;
3201
3202         if (!priv->has_sensitivity)
3203                 return -EOPNOTSUPP;
3204
3205         if ((val < 1) || (val > 3))
3206                 return -EINVAL;
3207         
3208         if (orinoco_lock(priv, &flags) != 0)
3209                 return -EBUSY;
3210         priv->ap_density = val;
3211         orinoco_unlock(priv, &flags);
3212
3213         return -EINPROGRESS;            /* Call commit handler */
3214 }
3215
3216 static int orinoco_ioctl_setrts(struct net_device *dev,
3217                                 struct iw_request_info *info,
3218                                 struct iw_param *rrq,
3219                                 char *extra)
3220 {
3221         struct orinoco_private *priv = netdev_priv(dev);
3222         int val = rrq->value;
3223         unsigned long flags;
3224
3225         if (rrq->disabled)
3226                 val = 2347;
3227
3228         if ( (val < 0) || (val > 2347) )
3229                 return -EINVAL;
3230
3231         if (orinoco_lock(priv, &flags) != 0)
3232                 return -EBUSY;
3233
3234         priv->rts_thresh = val;
3235         orinoco_unlock(priv, &flags);
3236
3237         return -EINPROGRESS;            /* Call commit handler */
3238 }
3239
3240 static int orinoco_ioctl_getrts(struct net_device *dev,
3241                                 struct iw_request_info *info,
3242                                 struct iw_param *rrq,
3243                                 char *extra)
3244 {
3245         struct orinoco_private *priv = netdev_priv(dev);
3246
3247         rrq->value = priv->rts_thresh;
3248         rrq->disabled = (rrq->value == 2347);
3249         rrq->fixed = 1;
3250
3251         return 0;
3252 }
3253
3254 static int orinoco_ioctl_setfrag(struct net_device *dev,
3255                                  struct iw_request_info *info,
3256                                  struct iw_param *frq,
3257                                  char *extra)
3258 {
3259         struct orinoco_private *priv = netdev_priv(dev);
3260         int err = -EINPROGRESS;         /* Call commit handler */
3261         unsigned long flags;
3262
3263         if (orinoco_lock(priv, &flags) != 0)
3264                 return -EBUSY;
3265
3266         if (priv->has_mwo) {
3267                 if (frq->disabled)
3268                         priv->mwo_robust = 0;
3269                 else {
3270                         if (frq->fixed)
3271                                 printk(KERN_WARNING "%s: Fixed fragmentation is "
3272                                        "not supported on this firmware. "
3273                                        "Using MWO robust instead.\n", dev->name);
3274                         priv->mwo_robust = 1;
3275                 }
3276         } else {
3277                 if (frq->disabled)
3278                         priv->frag_thresh = 2346;
3279                 else {
3280                         if ( (frq->value < 256) || (frq->value > 2346) )
3281                                 err = -EINVAL;
3282                         else
3283                                 priv->frag_thresh = frq->value & ~0x1; /* must be even */
3284                 }
3285         }
3286
3287         orinoco_unlock(priv, &flags);
3288
3289         return err;
3290 }
3291
3292 static int orinoco_ioctl_getfrag(struct net_device *dev,
3293                                  struct iw_request_info *info,
3294                                  struct iw_param *frq,
3295                                  char *extra)
3296 {
3297         struct orinoco_private *priv = netdev_priv(dev);
3298         hermes_t *hw = &priv->hw;
3299         int err;
3300         u16 val;
3301         unsigned long flags;
3302
3303         if (orinoco_lock(priv, &flags) != 0)
3304                 return -EBUSY;
3305         
3306         if (priv->has_mwo) {
3307                 err = hermes_read_wordrec(hw, USER_BAP,
3308                                           HERMES_RID_CNFMWOROBUST_AGERE,
3309                                           &val);
3310                 if (err)
3311                         val = 0;
3312
3313                 frq->value = val ? 2347 : 0;
3314                 frq->disabled = ! val;
3315                 frq->fixed = 0;
3316         } else {
3317                 err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CNFFRAGMENTATIONTHRESHOLD,
3318                                           &val);
3319                 if (err)
3320                         val = 0;
3321
3322                 frq->value = val;
3323                 frq->disabled = (val >= 2346);
3324                 frq->fixed = 1;
3325         }
3326
3327         orinoco_unlock(priv, &flags);
3328         
3329         return err;
3330 }
3331
3332 static int orinoco_ioctl_setrate(struct net_device *dev,
3333                                  struct iw_request_info *info,
3334                                  struct iw_param *rrq,
3335                                  char *extra)
3336 {
3337         struct orinoco_private *priv = netdev_priv(dev);
3338         int ratemode = -1;
3339         int bitrate; /* 100s of kilobits */
3340         int i;
3341         unsigned long flags;
3342         
3343         /* As the user space doesn't know our highest rate, it uses -1
3344          * to ask us to set the highest rate.  Test it using "iwconfig
3345          * ethX rate auto" - Jean II */
3346         if (rrq->value == -1)
3347                 bitrate = 110;
3348         else {
3349                 if (rrq->value % 100000)
3350                         return -EINVAL;
3351                 bitrate = rrq->value / 100000;
3352         }
3353
3354         if ( (bitrate != 10) && (bitrate != 20) &&
3355              (bitrate != 55) && (bitrate != 110) )
3356                 return -EINVAL;
3357
3358         for (i = 0; i < BITRATE_TABLE_SIZE; i++)
3359                 if ( (bitrate_table[i].bitrate == bitrate) &&
3360                      (bitrate_table[i].automatic == ! rrq->fixed) ) {
3361                         ratemode = i;
3362                         break;
3363                 }
3364         
3365         if (ratemode == -1)
3366                 return -EINVAL;
3367
3368         if (orinoco_lock(priv, &flags) != 0)
3369                 return -EBUSY;
3370         priv->bitratemode = ratemode;
3371         orinoco_unlock(priv, &flags);
3372
3373         return -EINPROGRESS;
3374 }
3375
3376 static int orinoco_ioctl_getrate(struct net_device *dev,
3377                                  struct iw_request_info *info,
3378                                  struct iw_param *rrq,
3379                                  char *extra)
3380 {
3381         struct orinoco_private *priv = netdev_priv(dev);
3382         hermes_t *hw = &priv->hw;
3383         int err = 0;
3384         int ratemode;
3385         int i;
3386         u16 val;
3387         unsigned long flags;
3388
3389         if (orinoco_lock(priv, &flags) != 0)
3390                 return -EBUSY;
3391
3392         ratemode = priv->bitratemode;
3393
3394         BUG_ON((ratemode < 0) || (ratemode >= BITRATE_TABLE_SIZE));
3395
3396         rrq->value = bitrate_table[ratemode].bitrate * 100000;
3397         rrq->fixed = ! bitrate_table[ratemode].automatic;
3398         rrq->disabled = 0;
3399
3400         /* If the interface is running we try to find more about the
3401            current mode */
3402         if (netif_running(dev)) {
3403                 err = hermes_read_wordrec(hw, USER_BAP,
3404                                           HERMES_RID_CURRENTTXRATE, &val);
3405                 if (err)
3406                         goto out;
3407                 
3408                 switch (priv->firmware_type) {
3409                 case FIRMWARE_TYPE_AGERE: /* Lucent style rate */
3410                         /* Note : in Lucent firmware, the return value of
3411                          * HERMES_RID_CURRENTTXRATE is the bitrate in Mb/s,
3412                          * and therefore is totally different from the
3413                          * encoding of HERMES_RID_CNFTXRATECONTROL.
3414                          * Don't forget that 6Mb/s is really 5.5Mb/s */
3415                         if (val == 6)
3416                                 rrq->value = 5500000;
3417                         else
3418                                 rrq->value = val * 1000000;
3419                         break;
3420                 case FIRMWARE_TYPE_INTERSIL: /* Intersil style rate */
3421                 case FIRMWARE_TYPE_SYMBOL: /* Symbol style rate */
3422                         for (i = 0; i < BITRATE_TABLE_SIZE; i++)
3423                                 if (bitrate_table[i].intersil_txratectrl == val) {
3424                                         ratemode = i;
3425                                         break;
3426                                 }
3427                         if (i >= BITRATE_TABLE_SIZE)
3428                                 printk(KERN_INFO "%s: Unable to determine current bitrate (0x%04hx)\n",
3429                                        dev->name, val);
3430
3431                         rrq->value = bitrate_table[ratemode].bitrate * 100000;
3432                         break;
3433                 default:
3434                         BUG();
3435                 }
3436         }
3437
3438  out:
3439         orinoco_unlock(priv, &flags);
3440
3441         return err;
3442 }
3443
3444 static int orinoco_ioctl_setpower(struct net_device *dev,
3445                                   struct iw_request_info *info,
3446                                   struct iw_param *prq,
3447                                   char *extra)
3448 {
3449         struct orinoco_private *priv = netdev_priv(dev);
3450         int err = -EINPROGRESS;         /* Call commit handler */
3451         unsigned long flags;
3452
3453         if (orinoco_lock(priv, &flags) != 0)
3454                 return -EBUSY;
3455
3456         if (prq->disabled) {
3457                 priv->pm_on = 0;
3458         } else {
3459                 switch (prq->flags & IW_POWER_MODE) {
3460                 case IW_POWER_UNICAST_R:
3461                         priv->pm_mcast = 0;
3462                         priv->pm_on = 1;
3463                         break;
3464                 case IW_POWER_ALL_R:
3465                         priv->pm_mcast = 1;
3466                         priv->pm_on = 1;
3467                         break;
3468                 case IW_POWER_ON:
3469                         /* No flags : but we may have a value - Jean II */
3470                         break;
3471                 default:
3472                         err = -EINVAL;
3473                         goto out;
3474                 }
3475                 
3476                 if (prq->flags & IW_POWER_TIMEOUT) {
3477                         priv->pm_on = 1;
3478                         priv->pm_timeout = prq->value / 1000;
3479                 }
3480                 if (prq->flags & IW_POWER_PERIOD) {
3481                         priv->pm_on = 1;
3482                         priv->pm_period = prq->value / 1000;
3483                 }
3484                 /* It's valid to not have a value if we are just toggling
3485                  * the flags... Jean II */
3486                 if(!priv->pm_on) {
3487                         err = -EINVAL;
3488                         goto out;
3489                 }                       
3490         }
3491
3492  out:
3493         orinoco_unlock(priv, &flags);
3494
3495         return err;
3496 }
3497
3498 static int orinoco_ioctl_getpower(struct net_device *dev,
3499                                   struct iw_request_info *info,
3500                                   struct iw_param *prq,
3501                                   char *extra)
3502 {
3503         struct orinoco_private *priv = netdev_priv(dev);
3504         hermes_t *hw = &priv->hw;
3505         int err = 0;
3506         u16 enable, period, timeout, mcast;
3507         unsigned long flags;
3508
3509         if (orinoco_lock(priv, &flags) != 0)
3510                 return -EBUSY;
3511         
3512         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CNFPMENABLED, &enable);
3513         if (err)
3514                 goto out;
3515
3516         err = hermes_read_wordrec(hw, USER_BAP,
3517                                   HERMES_RID_CNFMAXSLEEPDURATION, &period);
3518         if (err)
3519                 goto out;
3520
3521         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CNFPMHOLDOVERDURATION, &timeout);
3522         if (err)
3523                 goto out;
3524
3525         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_CNFMULTICASTRECEIVE, &mcast);
3526         if (err)
3527                 goto out;
3528
3529         prq->disabled = !enable;
3530         /* Note : by default, display the period */
3531         if ((prq->flags & IW_POWER_TYPE) == IW_POWER_TIMEOUT) {
3532                 prq->flags = IW_POWER_TIMEOUT;
3533                 prq->value = timeout * 1000;
3534         } else {
3535                 prq->flags = IW_POWER_PERIOD;
3536                 prq->value = period * 1000;
3537         }
3538         if (mcast)
3539                 prq->flags |= IW_POWER_ALL_R;
3540         else
3541                 prq->flags |= IW_POWER_UNICAST_R;
3542
3543  out:
3544         orinoco_unlock(priv, &flags);
3545
3546         return err;
3547 }
3548
3549 static int orinoco_ioctl_getretry(struct net_device *dev,
3550                                   struct iw_request_info *info,
3551                                   struct iw_param *rrq,
3552                                   char *extra)
3553 {
3554         struct orinoco_private *priv = netdev_priv(dev);
3555         hermes_t *hw = &priv->hw;
3556         int err = 0;
3557         u16 short_limit, long_limit, lifetime;
3558         unsigned long flags;
3559
3560         if (orinoco_lock(priv, &flags) != 0)
3561                 return -EBUSY;
3562         
3563         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_SHORTRETRYLIMIT,
3564                                   &short_limit);
3565         if (err)
3566                 goto out;
3567
3568         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_LONGRETRYLIMIT,
3569                                   &long_limit);
3570         if (err)
3571                 goto out;
3572
3573         err = hermes_read_wordrec(hw, USER_BAP, HERMES_RID_MAXTRANSMITLIFETIME,
3574                                   &lifetime);
3575         if (err)
3576                 goto out;
3577
3578         rrq->disabled = 0;              /* Can't be disabled */
3579
3580         /* Note : by default, display the retry number */
3581         if ((rrq->flags & IW_RETRY_TYPE) == IW_RETRY_LIFETIME) {
3582                 rrq->flags = IW_RETRY_LIFETIME;
3583                 rrq->value = lifetime * 1000;   /* ??? */
3584         } else {
3585                 /* By default, display the min number */
3586                 if ((rrq->flags & IW_RETRY_LONG)) {
3587                         rrq->flags = IW_RETRY_LIMIT | IW_RETRY_LONG;
3588                         rrq->value = long_limit;
3589                 } else {
3590                         rrq->flags = IW_RETRY_LIMIT;
3591                         rrq->value = short_limit;
3592                         if(short_limit != long_limit)
3593                                 rrq->flags |= IW_RETRY_SHORT;
3594                 }
3595         }
3596
3597  out:
3598         orinoco_unlock(priv, &flags);
3599
3600         return err;
3601 }
3602
3603 static int orinoco_ioctl_reset(struct net_device *dev,
3604                                struct iw_request_info *info,
3605                                void *wrqu,
3606                                char *extra)
3607 {
3608         struct orinoco_private *priv = netdev_priv(dev);
3609
3610         if (! capable(CAP_NET_ADMIN))
3611                 return -EPERM;
3612
3613         if (info->cmd == (SIOCIWFIRSTPRIV + 0x1)) {
3614                 printk(KERN_DEBUG "%s: Forcing reset!\n", dev->name);
3615
3616                 /* Firmware reset */
3617                 orinoco_reset(&priv->reset_work);
3618         } else {
3619                 printk(KERN_DEBUG "%s: Force scheduling reset!\n", dev->name);
3620
3621                 schedule_work(&priv->reset_work);
3622         }
3623
3624         return 0;
3625 }
3626
3627 static int orinoco_ioctl_setibssport(struct net_device *dev,
3628                                      struct iw_request_info *info,
3629                                      void *wrqu,
3630                                      char *extra)
3631
3632 {
3633         struct orinoco_private *priv = netdev_priv(dev);
3634         int val = *( (int *) extra );
3635         unsigned long flags;
3636
3637         if (orinoco_lock(priv, &flags) != 0)
3638                 return -EBUSY;
3639
3640         priv->ibss_port = val ;
3641
3642         /* Actually update the mode we are using */
3643         set_port_type(priv);
3644
3645         orinoco_unlock(priv, &flags);
3646         return -EINPROGRESS;            /* Call commit handler */
3647 }
3648
3649 static int orinoco_ioctl_getibssport(struct net_device *dev,
3650                                      struct iw_request_info *info,
3651                                      void *wrqu,
3652                                      char *extra)
3653 {
3654         struct orinoco_private *priv = netdev_priv(dev);
3655         int *val = (int *) extra;
3656
3657         *val = priv->ibss_port;
3658         return 0;
3659 }
3660
3661 static int orinoco_ioctl_setport3(struct net_device *dev,
3662                                   struct iw_request_info *info,
3663                                   void *wrqu,
3664                                   char *extra)
3665 {
3666         struct orinoco_private *priv = netdev_priv(dev);
3667         int val = *( (int *) extra );
3668         int err = 0;
3669         unsigned long flags;
3670
3671         if (orinoco_lock(priv, &flags) != 0)
3672                 return -EBUSY;
3673
3674         switch (val) {
3675         case 0: /* Try to do IEEE ad-hoc mode */
3676                 if (! priv->has_ibss) {
3677                         err = -EINVAL;
3678                         break;
3679                 }
3680                 priv->prefer_port3 = 0;
3681                         
3682                 break;
3683
3684         case 1: /* Try to do Lucent proprietary ad-hoc mode */
3685                 if (! priv->has_port3) {
3686                         err = -EINVAL;
3687                         break;
3688                 }
3689                 priv->prefer_port3 = 1;
3690                 break;
3691
3692         default:
3693                 err = -EINVAL;
3694         }
3695
3696         if (! err) {
3697                 /* Actually update the mode we are using */
3698                 set_port_type(priv);
3699                 err = -EINPROGRESS;
3700         }
3701
3702         orinoco_unlock(priv, &flags);
3703
3704         return err;
3705 }
3706
3707 static int orinoco_ioctl_getport3(struct net_device *dev,
3708                                   struct iw_request_info *info,
3709                                   void *wrqu,
3710                                   char *extra)
3711 {
3712         struct orinoco_private *priv = netdev_priv(dev);
3713         int *val = (int *) extra;
3714
3715         *val = priv->prefer_port3;
3716         return 0;
3717 }
3718
3719 static int orinoco_ioctl_setpreamble(struct net_device *dev,
3720                                      struct iw_request_info *info,
3721                                      void *wrqu,
3722                                      char *extra)
3723 {
3724         struct orinoco_private *priv = netdev_priv(dev);
3725         unsigned long flags;
3726         int val;
3727
3728         if (! priv->has_preamble)
3729                 return -EOPNOTSUPP;
3730
3731         /* 802.11b has recently defined some short preamble.
3732          * Basically, the Phy header has been reduced in size.
3733          * This increase performance, especially at high rates
3734          * (the preamble is transmitted at 1Mb/s), unfortunately
3735          * this give compatibility troubles... - Jean II */
3736         val = *( (int *) extra );
3737
3738         if (orinoco_lock(priv, &flags) != 0)
3739                 return -EBUSY;
3740
3741         if (val)
3742                 priv->preamble = 1;
3743         else
3744                 priv->preamble = 0;
3745
3746         orinoco_unlock(priv, &flags);
3747
3748         return -EINPROGRESS;            /* Call commit handler */
3749 }
3750
3751 static int orinoco_ioctl_getpreamble(struct net_device *dev,
3752                                      struct iw_request_info *info,
3753                                      void *wrqu,
3754                                      char *extra)
3755 {
3756         struct orinoco_private *priv = netdev_priv(dev);
3757         int *val = (int *) extra;
3758
3759         if (! priv->has_preamble)
3760                 return -EOPNOTSUPP;
3761
3762         *val = priv->preamble;
3763         return 0;
3764 }
3765
3766 /* ioctl interface to hermes_read_ltv()
3767  * To use with iwpriv, pass the RID as the token argument, e.g.
3768  * iwpriv get_rid [0xfc00]
3769  * At least Wireless Tools 25 is required to use iwpriv.
3770  * For Wireless Tools 25 and 26 append "dummy" are the end. */
3771 static int orinoco_ioctl_getrid(struct net_device *dev,
3772                                 struct iw_request_info *info,
3773                                 struct iw_point *data,
3774                                 char *extra)
3775 {
3776         struct orinoco_private *priv = netdev_priv(dev);
3777         hermes_t *hw = &priv->hw;
3778         int rid = data->flags;
3779         u16 length;
3780         int err;
3781         unsigned long flags;
3782
3783         /* It's a "get" function, but we don't want users to access the
3784          * WEP key and other raw firmware data */
3785         if (! capable(CAP_NET_ADMIN))
3786                 return -EPERM;
3787
3788         if (rid < 0xfc00 || rid > 0xffff)
3789                 return -EINVAL;
3790
3791         if (orinoco_lock(priv, &flags) != 0)
3792                 return -EBUSY;
3793
3794         err = hermes_read_ltv(hw, USER_BAP, rid, MAX_RID_LEN, &length,
3795                               extra);
3796         if (err)
3797                 goto out;
3798
3799         data->length = min_t(u16, HERMES_RECLEN_TO_BYTES(length),
3800                              MAX_RID_LEN);
3801
3802  out:
3803         orinoco_unlock(priv, &flags);
3804         return err;
3805 }
3806
3807 /* Trigger a scan (look for other cells in the vicinity */
3808 static int orinoco_ioctl_setscan(struct net_device *dev,
3809                                  struct iw_request_info *info,
3810                                  struct iw_param *srq,
3811                                  char *extra)
3812 {
3813         struct orinoco_private *priv = netdev_priv(dev);
3814         hermes_t *hw = &priv->hw;
3815         int err = 0;
3816         unsigned long flags;
3817
3818         /* Note : you may have realised that, as this is a SET operation,
3819          * this is privileged and therefore a normal user can't
3820          * perform scanning.
3821          * This is not an error, while the device perform scanning,
3822          * traffic doesn't flow, so it's a perfect DoS...
3823          * Jean II */
3824
3825         if (orinoco_lock(priv, &flags) != 0)
3826                 return -EBUSY;
3827
3828         /* Scanning with port 0 disabled would fail */
3829         if (!netif_running(dev)) {
3830                 err = -ENETDOWN;
3831                 goto out;
3832         }
3833
3834         /* In monitor mode, the scan results are always empty.
3835          * Probe responses are passed to the driver as received
3836          * frames and could be processed in software. */
3837         if (priv->iw_mode == IW_MODE_MONITOR) {
3838                 err = -EOPNOTSUPP;
3839                 goto out;
3840         }
3841
3842         /* Note : because we don't lock out the irq handler, the way
3843          * we access scan variables in priv is critical.
3844          *      o scan_inprogress : not touched by irq handler
3845          *      o scan_mode : not touched by irq handler
3846          *      o scan_result : irq is strict producer, non-irq is strict
3847          *              consumer.
3848          *      o scan_len : synchronised with scan_result
3849          * Before modifying anything on those variables, please think hard !
3850          * Jean II */
3851
3852         /* If there is still some left-over scan results, get rid of it */
3853         if (priv->scan_result != NULL) {
3854                 /* What's likely is that a client did crash or was killed
3855                  * between triggering the scan request and reading the
3856                  * results, so we need to reset everything.
3857                  * Some clients that are too slow may suffer from that...
3858                  * Jean II */
3859                 kfree(priv->scan_result);
3860                 priv->scan_result = NULL;
3861         }
3862
3863         /* Save flags */
3864         priv->scan_mode = srq->flags;
3865
3866         /* Always trigger scanning, even if it's in progress.
3867          * This way, if the info frame get lost, we will recover somewhat
3868          * gracefully  - Jean II */
3869
3870         if (priv->has_hostscan) {
3871                 switch (priv->firmware_type) {
3872                 case FIRMWARE_TYPE_SYMBOL:
3873                         err = hermes_write_wordrec(hw, USER_BAP,
3874                                                    HERMES_RID_CNFHOSTSCAN_SYMBOL,
3875                                                    HERMES_HOSTSCAN_SYMBOL_ONCE |
3876                                                    HERMES_HOSTSCAN_SYMBOL_BCAST);
3877                         break;
3878                 case FIRMWARE_TYPE_INTERSIL: {
3879                         __le16 req[3];
3880
3881                         req[0] = cpu_to_le16(0x3fff);   /* All channels */
3882                         req[1] = cpu_to_le16(0x0001);   /* rate 1 Mbps */
3883                         req[2] = 0;                     /* Any ESSID */
3884                         err = HERMES_WRITE_RECORD(hw, USER_BAP,
3885                                                   HERMES_RID_CNFHOSTSCAN, &req);
3886                 }
3887                 break;
3888                 case FIRMWARE_TYPE_AGERE:
3889                         err = hermes_write_wordrec(hw, USER_BAP,
3890                                                    HERMES_RID_CNFSCANSSID_AGERE,
3891                                                    0);  /* Any ESSID */
3892                         if (err)
3893                                 break;
3894
3895                         err = hermes_inquire(hw, HERMES_INQ_SCAN);
3896                         break;
3897                 }
3898         } else
3899                 err = hermes_inquire(hw, HERMES_INQ_SCAN);
3900
3901         /* One more client */
3902         if (! err)
3903                 priv->scan_inprogress = 1;
3904
3905  out:
3906         orinoco_unlock(priv, &flags);
3907         return err;
3908 }
3909
3910 /* Translate scan data returned from the card to a card independant
3911  * format that the Wireless Tools will understand - Jean II
3912  * Return message length or -errno for fatal errors */
3913 static inline int orinoco_translate_scan(struct net_device *dev,
3914                                          char *buffer,
3915                                          char *scan,
3916                                          int scan_len)
3917 {
3918         struct orinoco_private *priv = netdev_priv(dev);
3919         int                     offset;         /* In the scan data */
3920         union hermes_scan_info *atom;
3921         int                     atom_len;
3922         u16                     capabilities;
3923         u16                     channel;
3924         struct iw_event         iwe;            /* Temporary buffer */
3925         char *                  current_ev = buffer;
3926         char *                  end_buf = buffer + IW_SCAN_MAX_DATA;
3927
3928         switch (priv->firmware_type) {
3929         case FIRMWARE_TYPE_AGERE:
3930                 atom_len = sizeof(struct agere_scan_apinfo);
3931                 offset = 0;
3932                 break;
3933         case FIRMWARE_TYPE_SYMBOL:
3934                 /* Lack of documentation necessitates this hack.
3935                  * Different firmwares have 68 or 76 byte long atoms.
3936                  * We try modulo first.  If the length divides by both,
3937                  * we check what would be the channel in the second
3938                  * frame for a 68-byte atom.  76-byte atoms have 0 there.
3939                  * Valid channel cannot be 0.  */
3940                 if (scan_len % 76)
3941                         atom_len = 68;
3942                 else if (scan_len % 68)
3943                         atom_len = 76;
3944                 else if (scan_len >= 1292 && scan[68] == 0)
3945                         atom_len = 76;
3946                 else
3947                         atom_len = 68;
3948                 offset = 0;
3949                 break;
3950         case FIRMWARE_TYPE_INTERSIL:
3951                 offset = 4;
3952                 if (priv->has_hostscan) {
3953                         atom_len = le16_to_cpup((__le16 *)scan);
3954                         /* Sanity check for atom_len */
3955                         if (atom_len < sizeof(struct prism2_scan_apinfo)) {
3956                                 printk(KERN_ERR "%s: Invalid atom_len in scan data: %d\n",
3957                                 dev->name, atom_len);
3958                                 return -EIO;
3959                         }
3960                 } else
3961                         atom_len = offsetof(struct prism2_scan_apinfo, atim);
3962                 break;
3963         default:
3964                 return -EOPNOTSUPP;
3965         }
3966
3967         /* Check that we got an whole number of atoms */
3968         if ((scan_len - offset) % atom_len) {
3969                 printk(KERN_ERR "%s: Unexpected scan data length %d, "
3970                        "atom_len %d, offset %d\n", dev->name, scan_len,
3971                        atom_len, offset);
3972                 return -EIO;
3973         }
3974
3975         /* Read the entries one by one */
3976         for (; offset + atom_len <= scan_len; offset += atom_len) {
3977                 /* Get next atom */
3978                 atom = (union hermes_scan_info *) (scan + offset);
3979
3980                 /* First entry *MUST* be the AP MAC address */
3981                 iwe.cmd = SIOCGIWAP;
3982                 iwe.u.ap_addr.sa_family = ARPHRD_ETHER;
3983                 memcpy(iwe.u.ap_addr.sa_data, atom->a.bssid, ETH_ALEN);
3984                 current_ev = iwe_stream_add_event(current_ev, end_buf, &iwe, IW_EV_ADDR_LEN);
3985
3986                 /* Other entries will be displayed in the order we give them */
3987
3988                 /* Add the ESSID */
3989                 iwe.u.data.length = le16_to_cpu(atom->a.essid_len);
3990                 if (iwe.u.data.length > 32)
3991                         iwe.u.data.length = 32;
3992                 iwe.cmd = SIOCGIWESSID;
3993                 iwe.u.data.flags = 1;
3994                 current_ev = iwe_stream_add_point(current_ev, end_buf, &iwe, atom->a.essid);
3995
3996                 /* Add mode */
3997                 iwe.cmd = SIOCGIWMODE;
3998                 capabilities = le16_to_cpu(atom->a.capabilities);
3999                 if (capabilities & 0x3) {
4000                         if (capabilities & 0x1)
4001                                 iwe.u.mode = IW_MODE_MASTER;
4002                         else
4003                                 iwe.u.mode = IW_MODE_ADHOC;
4004                         current_ev = iwe_stream_add_event(current_ev, end_buf, &iwe, IW_EV_UINT_LEN);
4005                 }
4006
4007                 channel = atom->s.channel;
4008                 if ( (channel >= 1) && (channel <= NUM_CHANNELS) ) {
4009                         /* Add frequency */
4010                         iwe.cmd = SIOCGIWFREQ;
4011                         iwe.u.freq.m = channel_frequency[channel-1] * 100000;
4012                         iwe.u.freq.e = 1;
4013                         current_ev = iwe_stream_add_event(current_ev, end_buf,
4014                                                           &iwe, IW_EV_FREQ_LEN);
4015                 }
4016
4017                 /* Add quality statistics */
4018                 iwe.cmd = IWEVQUAL;
4019                 iwe.u.qual.updated = 0x10;      /* no link quality */
4020                 iwe.u.qual.level = (__u8) le16_to_cpu(atom->a.level) - 0x95;
4021                 iwe.u.qual.noise = (__u8) le16_to_cpu(atom->a.noise) - 0x95;
4022                 /* Wireless tools prior to 27.pre22 will show link quality
4023                  * anyway, so we provide a reasonable value. */
4024                 if (iwe.u.qual.level > iwe.u.qual.noise)
4025                         iwe.u.qual.qual = iwe.u.qual.level - iwe.u.qual.noise;
4026                 else
4027                         iwe.u.qual.qual = 0;
4028                 current_ev = iwe_stream_add_event(current_ev, end_buf, &iwe, IW_EV_QUAL_LEN);
4029
4030                 /* Add encryption capability */
4031                 iwe.cmd = SIOCGIWENCODE;
4032                 if (capabilities & 0x10)
4033                         iwe.u.data.flags = IW_ENCODE_ENABLED | IW_ENCODE_NOKEY;
4034                 else
4035                         iwe.u.data.flags = IW_ENCODE_DISABLED;
4036                 iwe.u.data.length = 0;
4037                 current_ev = iwe_stream_add_point(current_ev, end_buf, &iwe, atom->a.essid);
4038
4039                 /* Bit rate is not available in Lucent/Agere firmwares */
4040                 if (priv->firmware_type != FIRMWARE_TYPE_AGERE) {
4041                         char *  current_val = current_ev + IW_EV_LCP_LEN;
4042                         int     i;
4043                         int     step;
4044
4045                         if (priv->firmware_type == FIRMWARE_TYPE_SYMBOL)
4046                                 step = 2;
4047                         else
4048                                 step = 1;
4049
4050                         iwe.cmd = SIOCGIWRATE;
4051                         /* Those two flags are ignored... */
4052                         iwe.u.bitrate.fixed = iwe.u.bitrate.disabled = 0;
4053                         /* Max 10 values */
4054                         for (i = 0; i < 10; i += step) {
4055                                 /* NULL terminated */
4056                                 if (atom->p.rates[i] == 0x0)
4057                                         break;
4058                                 /* Bit rate given in 500 kb/s units (+ 0x80) */
4059                                 iwe.u.bitrate.value = ((atom->p.rates[i] & 0x7f) * 500000);
4060                                 current_val = iwe_stream_add_value(current_ev, current_val,
4061                                                                    end_buf, &iwe,
4062                                                                    IW_EV_PARAM_LEN);
4063                         }
4064                         /* Check if we added any event */
4065                         if ((current_val - current_ev) > IW_EV_LCP_LEN)
4066                                 current_ev = current_val;
4067                 }
4068
4069                 /* The other data in the scan result are not really
4070                  * interesting, so for now drop it - Jean II */
4071         }
4072         return current_ev - buffer;
4073 }
4074
4075 /* Return results of a scan */
4076 static int orinoco_ioctl_getscan(struct net_device *dev,
4077                                  struct iw_request_info *info,
4078                                  struct iw_point *srq,
4079                                  char *extra)
4080 {
4081         struct orinoco_private *priv = netdev_priv(dev);
4082         int err = 0;
4083         unsigned long flags;
4084
4085         if (orinoco_lock(priv, &flags) != 0)
4086                 return -EBUSY;
4087
4088         /* If no results yet, ask to try again later */
4089         if (priv->scan_result == NULL) {
4090                 if (priv->scan_inprogress)
4091                         /* Important note : we don't want to block the caller
4092                          * until results are ready for various reasons.
4093                          * First, managing wait queues is complex and racy.
4094                          * Second, we grab some rtnetlink lock before comming
4095                          * here (in dev_ioctl()).
4096                          * Third, we generate an Wireless Event, so the
4097                          * caller can wait itself on that - Jean II */
4098                         err = -EAGAIN;
4099                 else
4100                         /* Client error, no scan results...
4101                          * The caller need to restart the scan. */
4102                         err = -ENODATA;
4103         } else {
4104                 /* We have some results to push back to user space */
4105
4106                 /* Translate to WE format */
4107                 int ret = orinoco_translate_scan(dev, extra,
4108                                                  priv->scan_result,
4109                                                  priv->scan_len);
4110
4111                 if (ret < 0) {
4112                         err = ret;
4113                         kfree(priv->scan_result);
4114                         priv->scan_result = NULL;
4115                 } else {
4116                         srq->length = ret;
4117
4118                         /* Return flags */
4119                         srq->flags = (__u16) priv->scan_mode;
4120
4121                         /* In any case, Scan results will be cleaned up in the
4122                          * reset function and when exiting the driver.
4123                          * The person triggering the scanning may never come to
4124                          * pick the results, so we need to do it in those places.
4125                          * Jean II */
4126
4127 #ifdef SCAN_SINGLE_READ
4128                         /* If you enable this option, only one client (the first
4129                          * one) will be able to read the result (and only one
4130                          * time). If there is multiple concurent clients that
4131                          * want to read scan results, this behavior is not
4132                          * advisable - Jean II */
4133                         kfree(priv->scan_result);
4134                         priv->scan_result = NULL;
4135 #endif /* SCAN_SINGLE_READ */
4136                         /* Here, if too much time has elapsed since last scan,
4137                          * we may want to clean up scan results... - Jean II */
4138                 }
4139
4140                 /* Scan is no longer in progress */
4141                 priv->scan_inprogress = 0;
4142         }
4143           
4144         orinoco_unlock(priv, &flags);
4145         return err;
4146 }
4147
4148 /* Commit handler, called after set operations */
4149 static int orinoco_ioctl_commit(struct net_device *dev,
4150                                 struct iw_request_info *info,
4151                                 void *wrqu,
4152                                 char *extra)
4153 {
4154         struct orinoco_private *priv = netdev_priv(dev);
4155         struct hermes *hw = &priv->hw;
4156         unsigned long flags;
4157         int err = 0;
4158
4159         if (!priv->open)
4160                 return 0;
4161
4162         if (priv->broken_disableport) {
4163                 orinoco_reset(&priv->reset_work);
4164                 return 0;
4165         }
4166
4167         if (orinoco_lock(priv, &flags) != 0)
4168                 return err;
4169
4170         err = hermes_disable_port(hw, 0);
4171         if (err) {
4172                 printk(KERN_WARNING "%s: Unable to disable port "
4173                        "while reconfiguring card\n", dev->name);
4174                 priv->broken_disableport = 1;
4175                 goto out;
4176         }
4177
4178         err = __orinoco_program_rids(dev);
4179         if (err) {
4180                 printk(KERN_WARNING "%s: Unable to reconfigure card\n",
4181                        dev->name);
4182                 goto out;
4183         }
4184
4185         err = hermes_enable_port(hw, 0);
4186         if (err) {
4187                 printk(KERN_WARNING "%s: Unable to enable port while reconfiguring card\n",
4188                        dev->name);
4189                 goto out;
4190         }
4191
4192  out:
4193         if (err) {
4194                 printk(KERN_WARNING "%s: Resetting instead...\n", dev->name);
4195                 schedule_work(&priv->reset_work);
4196                 err = 0;
4197         }
4198
4199         orinoco_unlock(priv, &flags);
4200         return err;
4201 }
4202
4203 static const struct iw_priv_args orinoco_privtab[] = {
4204         { SIOCIWFIRSTPRIV + 0x0, 0, 0, "force_reset" },
4205         { SIOCIWFIRSTPRIV + 0x1, 0, 0, "card_reset" },
4206         { SIOCIWFIRSTPRIV + 0x2, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,
4207           0, "set_port3" },
4208         { SIOCIWFIRSTPRIV + 0x3, 0, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,
4209           "get_port3" },
4210         { SIOCIWFIRSTPRIV + 0x4, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,
4211           0, "set_preamble" },
4212         { SIOCIWFIRSTPRIV + 0x5, 0, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,
4213           "get_preamble" },
4214         { SIOCIWFIRSTPRIV + 0x6, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,
4215           0, "set_ibssport" },
4216         { SIOCIWFIRSTPRIV + 0x7, 0, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,
4217           "get_ibssport" },
4218         { SIOCIWFIRSTPRIV + 0x9, 0, IW_PRIV_TYPE_BYTE | MAX_RID_LEN,
4219           "get_rid" },
4220 };
4221
4222
4223 /*
4224  * Structures to export the Wireless Handlers
4225  */
4226
4227 static const iw_handler orinoco_handler[] = {
4228         [SIOCSIWCOMMIT-SIOCIWFIRST] = (iw_handler) orinoco_ioctl_commit,
4229         [SIOCGIWNAME  -SIOCIWFIRST] = (iw_handler) orinoco_ioctl_getname,
4230         [SIOCSIWFREQ  -SIOCIWFIRST] = (iw_handler) orinoco_ioctl_setfreq,
4231         [SIOCGIWFREQ  -SIOCIWFIRST] = (iw_handler) orinoco_ioctl_getfreq,
4232         [SIOCSIWMODE  -SIOCIWFIRST] = (iw_handler) orinoco_ioctl_setmode,
4233         [SIOCGIWMODE  -SIOCIWFIRST] = (iw_handler) orinoco_ioctl_getmode,
4234         [SIOCSIWSENS  -SIOCIWFIRST] = (iw_handler) orinoco_ioctl_setsens,
4235         [SIOCGIWSENS  -SIOCIWFIRST] = (iw_handler) orinoco_ioctl_getsens,
4236         [SIOCGIWRANGE -SIOCIWFIRST] = (iw_handler) orinoco_ioctl_getiwrange,
4237         [SIOCSIWSPY   -SIOCIWFIRST] = (iw_handler) iw_handler_set_spy,
4238         [SIOCGIWSPY   -SIOCIWFIRST] = (iw_handler) iw_handler_get_spy,
4239         [SIOCSIWTHRSPY-SIOCIWFIRST] = (iw_handler) iw_handler_set_thrspy,
4240         [SIOCGIWTHRSPY-SIOCIWFIRST] = (iw_handler) iw_handler_get_thrspy,
4241         [SIOCSIWAP    -SIOCIWFIRST] = (iw_handler) orinoco_ioctl_setwap,
4242         [SIOCGIWAP    -SIOCIWFIRST] = (iw_handler) orinoco_ioctl_getwap,
4243         [SIOCSIWSCAN  -SIOCIWFIRST] = (iw_handler) orinoco_ioctl_setscan,
4244         [SIOCGIWSCAN  -SIOCIWFIRST] = (iw_handler) orinoco_ioctl_getscan,
4245         [SIOCSIWESSID -SIOCIWFIRST] = (iw_handler) orinoco_ioctl_setessid,
4246         [SIOCGIWESSID -SIOCIWFIRST] = (iw_handler) orinoco_ioctl_getessid,
4247         [SIOCSIWNICKN -SIOCIWFIRST] = (iw_handler) orinoco_ioctl_setnick,
4248         [SIOCGIWNICKN -SIOCIWFIRST] = (iw_handler) orinoco_ioctl_getnick,
4249         [SIOCSIWRATE  -SIOCIWFIRST] = (iw_handler) orinoco_ioctl_setrate,
4250         [SIOCGIWRATE  -SIOCIWFIRST] = (iw_handler) orinoco_ioctl_getrate,
4251         [SIOCSIWRTS   -SIOCIWFIRST] = (iw_handler) orinoco_ioctl_setrts,
4252         [SIOCGIWRTS   -SIOCIWFIRST] = (iw_handler) orinoco_ioctl_getrts,
4253         [SIOCSIWFRAG  -SIOCIWFIRST] = (iw_handler) orinoco_ioctl_setfrag,
4254         [SIOCGIWFRAG  -SIOCIWFIRST] = (iw_handler) orinoco_ioctl_getfrag,
4255         [SIOCGIWRETRY -SIOCIWFIRST] = (iw_handler) orinoco_ioctl_getretry,
4256         [SIOCSIWENCODE-SIOCIWFIRST] = (iw_handler) orinoco_ioctl_setiwencode,
4257         [SIOCGIWENCODE-SIOCIWFIRST] = (iw_handler) orinoco_ioctl_getiwencode,
4258         [SIOCSIWPOWER -SIOCIWFIRST] = (iw_handler) orinoco_ioctl_setpower,
4259         [SIOCGIWPOWER -SIOCIWFIRST] = (iw_handler) orinoco_ioctl_getpower,
4260 };
4261
4262
4263 /*
4264   Added typecasting since we no longer use iwreq_data -- Moustafa
4265  */
4266 static const iw_handler orinoco_private_handler[] = {
4267         [0] = (iw_handler) orinoco_ioctl_reset,
4268         [1] = (iw_handler) orinoco_ioctl_reset,
4269         [2] = (iw_handler) orinoco_ioctl_setport3,
4270         [3] = (iw_handler) orinoco_ioctl_getport3,
4271         [4] = (iw_handler) orinoco_ioctl_setpreamble,
4272         [5] = (iw_handler) orinoco_ioctl_getpreamble,
4273         [6] = (iw_handler) orinoco_ioctl_setibssport,
4274         [7] = (iw_handler) orinoco_ioctl_getibssport,
4275         [9] = (iw_handler) orinoco_ioctl_getrid,
4276 };
4277
4278 static const struct iw_handler_def orinoco_handler_def = {
4279         .num_standard = ARRAY_SIZE(orinoco_handler),
4280         .num_private = ARRAY_SIZE(orinoco_private_handler),
4281         .num_private_args = ARRAY_SIZE(orinoco_privtab),
4282         .standard = orinoco_handler,
4283         .private = orinoco_private_handler,
4284         .private_args = orinoco_privtab,
4285         .get_wireless_stats = orinoco_get_wireless_stats,
4286 };
4287
4288 static void orinoco_get_drvinfo(struct net_device *dev,
4289                                 struct ethtool_drvinfo *info)
4290 {
4291         struct orinoco_private *priv = netdev_priv(dev);
4292
4293         strncpy(info->driver, DRIVER_NAME, sizeof(info->driver) - 1);
4294         strncpy(info->version, DRIVER_VERSION, sizeof(info->version) - 1);
4295         strncpy(info->fw_version, priv->fw_name, sizeof(info->fw_version) - 1);
4296         if (dev->class_dev.dev)
4297                 strncpy(info->bus_info, dev->class_dev.dev->bus_id,
4298                         sizeof(info->bus_info) - 1);
4299         else
4300                 snprintf(info->bus_info, sizeof(info->bus_info) - 1,
4301                          "PCMCIA %p", priv->hw.iobase);
4302 }
4303
4304 static const struct ethtool_ops orinoco_ethtool_ops = {
4305         .get_drvinfo = orinoco_get_drvinfo,
4306         .get_link = ethtool_op_get_link,
4307 };
4308
4309 /********************************************************************/
4310 /* Module initialization                                            */
4311 /********************************************************************/
4312
4313 EXPORT_SYMBOL(alloc_orinocodev);
4314 EXPORT_SYMBOL(free_orinocodev);
4315
4316 EXPORT_SYMBOL(__orinoco_up);
4317 EXPORT_SYMBOL(__orinoco_down);
4318 EXPORT_SYMBOL(orinoco_reinit_firmware);
4319
4320 EXPORT_SYMBOL(orinoco_interrupt);
4321
4322 /* Can't be declared "const" or the whole __initdata section will
4323  * become const */
4324 static char version[] __initdata = DRIVER_NAME " " DRIVER_VERSION
4325         " (David Gibson <hermes@gibson.dropbear.id.au>, "
4326         "Pavel Roskin <proski@gnu.org>, et al)";
4327
4328 static int __init init_orinoco(void)
4329 {
4330         printk(KERN_DEBUG "%s\n", version);
4331         return 0;
4332 }
4333
4334 static void __exit exit_orinoco(void)
4335 {
4336 }
4337
4338 module_init(init_orinoco);
4339 module_exit(exit_orinoco);