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