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