iwlwifi: add struct iwl_cfg
[safe/jmp/linux-2.6] / drivers / net / wireless / iwlwifi / iwl3945-base.c
1 /******************************************************************************
2  *
3  * Copyright(c) 2003 - 2007 Intel Corporation. All rights reserved.
4  *
5  * Portions of this file are derived from the ipw3945 project, as well
6  * as portions of the ieee80211 subsystem header files.
7  *
8  * This program is free software; you can redistribute it and/or modify it
9  * under the terms of version 2 of the GNU General Public License as
10  * published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
15  * more details.
16  *
17  * You should have received a copy of the GNU General Public License along with
18  * this program; if not, write to the Free Software Foundation, Inc.,
19  * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
20  *
21  * The full GNU General Public License is included in this distribution in the
22  * file called LICENSE.
23  *
24  * Contact Information:
25  * James P. Ketrenos <ipw2100-admin@linux.intel.com>
26  * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
27  *
28  *****************************************************************************/
29
30 #include <linux/kernel.h>
31 #include <linux/module.h>
32 #include <linux/version.h>
33 #include <linux/init.h>
34 #include <linux/pci.h>
35 #include <linux/dma-mapping.h>
36 #include <linux/delay.h>
37 #include <linux/skbuff.h>
38 #include <linux/netdevice.h>
39 #include <linux/wireless.h>
40 #include <linux/firmware.h>
41 #include <linux/etherdevice.h>
42 #include <linux/if_arp.h>
43
44 #include <net/ieee80211_radiotap.h>
45 #include <net/mac80211.h>
46
47 #include <asm/div64.h>
48
49 #include "iwl-3945-core.h"
50 #include "iwl-3945.h"
51 #include "iwl-helpers.h"
52
53 #ifdef CONFIG_IWL3945_DEBUG
54 u32 iwl3945_debug_level;
55 #endif
56
57 static int iwl3945_tx_queue_update_write_ptr(struct iwl3945_priv *priv,
58                                   struct iwl3945_tx_queue *txq);
59
60 /******************************************************************************
61  *
62  * module boiler plate
63  *
64  ******************************************************************************/
65
66 /* module parameters */
67 static int iwl3945_param_disable_hw_scan; /* def: 0 = use 3945's h/w scan */
68 static int iwl3945_param_debug;    /* def: 0 = minimal debug log messages */
69 static int iwl3945_param_disable;  /* def: 0 = enable radio */
70 static int iwl3945_param_antenna;  /* def: 0 = both antennas (use diversity) */
71 int iwl3945_param_hwcrypto;        /* def: 0 = use software encryption */
72 static int iwl3945_param_qos_enable = 1; /* def: 1 = use quality of service */
73 int iwl3945_param_queues_num = IWL_MAX_NUM_QUEUES; /* def: 8 Tx queues */
74
75 /*
76  * module name, copyright, version, etc.
77  * NOTE: DRV_NAME is defined in iwlwifi.h for use by iwl-debug.h and printk
78  */
79
80 #define DRV_DESCRIPTION \
81 "Intel(R) PRO/Wireless 3945ABG/BG Network Connection driver for Linux"
82
83 #ifdef CONFIG_IWL3945_DEBUG
84 #define VD "d"
85 #else
86 #define VD
87 #endif
88
89 #ifdef CONFIG_IWL3945_SPECTRUM_MEASUREMENT
90 #define VS "s"
91 #else
92 #define VS
93 #endif
94
95 #define IWLWIFI_VERSION "1.2.26k" VD VS
96 #define DRV_COPYRIGHT   "Copyright(c) 2003-2007 Intel Corporation"
97 #define DRV_VERSION     IWLWIFI_VERSION
98
99 /* Change firmware file name, using "-" and incrementing number,
100  *   *only* when uCode interface or architecture changes so that it
101  *   is not compatible with earlier drivers.
102  * This number will also appear in << 8 position of 1st dword of uCode file */
103 #define IWL3945_UCODE_API "-1"
104
105 MODULE_DESCRIPTION(DRV_DESCRIPTION);
106 MODULE_VERSION(DRV_VERSION);
107 MODULE_AUTHOR(DRV_COPYRIGHT);
108 MODULE_LICENSE("GPL");
109
110 static __le16 *ieee80211_get_qos_ctrl(struct ieee80211_hdr *hdr)
111 {
112         u16 fc = le16_to_cpu(hdr->frame_control);
113         int hdr_len = ieee80211_get_hdrlen(fc);
114
115         if ((fc & 0x00cc) == (IEEE80211_STYPE_QOS_DATA | IEEE80211_FTYPE_DATA))
116                 return (__le16 *) ((u8 *) hdr + hdr_len - QOS_CONTROL_LEN);
117         return NULL;
118 }
119
120 static const struct ieee80211_supported_band *iwl3945_get_band(
121                 struct iwl3945_priv *priv, enum ieee80211_band band)
122 {
123         return priv->hw->wiphy->bands[band];
124 }
125
126 static int iwl3945_is_empty_essid(const char *essid, int essid_len)
127 {
128         /* Single white space is for Linksys APs */
129         if (essid_len == 1 && essid[0] == ' ')
130                 return 1;
131
132         /* Otherwise, if the entire essid is 0, we assume it is hidden */
133         while (essid_len) {
134                 essid_len--;
135                 if (essid[essid_len] != '\0')
136                         return 0;
137         }
138
139         return 1;
140 }
141
142 static const char *iwl3945_escape_essid(const char *essid, u8 essid_len)
143 {
144         static char escaped[IW_ESSID_MAX_SIZE * 2 + 1];
145         const char *s = essid;
146         char *d = escaped;
147
148         if (iwl3945_is_empty_essid(essid, essid_len)) {
149                 memcpy(escaped, "<hidden>", sizeof("<hidden>"));
150                 return escaped;
151         }
152
153         essid_len = min(essid_len, (u8) IW_ESSID_MAX_SIZE);
154         while (essid_len--) {
155                 if (*s == '\0') {
156                         *d++ = '\\';
157                         *d++ = '0';
158                         s++;
159                 } else
160                         *d++ = *s++;
161         }
162         *d = '\0';
163         return escaped;
164 }
165
166 /*************** DMA-QUEUE-GENERAL-FUNCTIONS  *****
167  * DMA services
168  *
169  * Theory of operation
170  *
171  * A Tx or Rx queue resides in host DRAM, and is comprised of a circular buffer
172  * of buffer descriptors, each of which points to one or more data buffers for
173  * the device to read from or fill.  Driver and device exchange status of each
174  * queue via "read" and "write" pointers.  Driver keeps minimum of 2 empty
175  * entries in each circular buffer, to protect against confusing empty and full
176  * queue states.
177  *
178  * The device reads or writes the data in the queues via the device's several
179  * DMA/FIFO channels.  Each queue is mapped to a single DMA channel.
180  *
181  * For Tx queue, there are low mark and high mark limits. If, after queuing
182  * the packet for Tx, free space become < low mark, Tx queue stopped. When
183  * reclaiming packets (on 'tx done IRQ), if free space become > high mark,
184  * Tx queue resumed.
185  *
186  * The 3945 operates with six queues:  One receive queue, one transmit queue
187  * (#4) for sending commands to the device firmware, and four transmit queues
188  * (#0-3) for data tx via EDCA.  An additional 2 HCCA queues are unused.
189  ***************************************************/
190
191 static int iwl3945_queue_space(const struct iwl3945_queue *q)
192 {
193         int s = q->read_ptr - q->write_ptr;
194
195         if (q->read_ptr > q->write_ptr)
196                 s -= q->n_bd;
197
198         if (s <= 0)
199                 s += q->n_window;
200         /* keep some reserve to not confuse empty and full situations */
201         s -= 2;
202         if (s < 0)
203                 s = 0;
204         return s;
205 }
206
207 /**
208  * iwl3945_queue_inc_wrap - increment queue index, wrap back to beginning
209  * @index -- current index
210  * @n_bd -- total number of entries in queue (must be power of 2)
211  */
212 static inline int iwl3945_queue_inc_wrap(int index, int n_bd)
213 {
214         return ++index & (n_bd - 1);
215 }
216
217 /**
218  * iwl3945_queue_dec_wrap - increment queue index, wrap back to end
219  * @index -- current index
220  * @n_bd -- total number of entries in queue (must be power of 2)
221  */
222 static inline int iwl3945_queue_dec_wrap(int index, int n_bd)
223 {
224         return --index & (n_bd - 1);
225 }
226
227 static inline int x2_queue_used(const struct iwl3945_queue *q, int i)
228 {
229         return q->write_ptr > q->read_ptr ?
230                 (i >= q->read_ptr && i < q->write_ptr) :
231                 !(i < q->read_ptr && i >= q->write_ptr);
232 }
233
234 static inline u8 get_cmd_index(struct iwl3945_queue *q, u32 index, int is_huge)
235 {
236         /* This is for scan command, the big buffer at end of command array */
237         if (is_huge)
238                 return q->n_window;     /* must be power of 2 */
239
240         /* Otherwise, use normal size buffers */
241         return index & (q->n_window - 1);
242 }
243
244 /**
245  * iwl3945_queue_init - Initialize queue's high/low-water and read/write indexes
246  */
247 static int iwl3945_queue_init(struct iwl3945_priv *priv, struct iwl3945_queue *q,
248                           int count, int slots_num, u32 id)
249 {
250         q->n_bd = count;
251         q->n_window = slots_num;
252         q->id = id;
253
254         /* count must be power-of-two size, otherwise iwl3945_queue_inc_wrap
255          * and iwl3945_queue_dec_wrap are broken. */
256         BUG_ON(!is_power_of_2(count));
257
258         /* slots_num must be power-of-two size, otherwise
259          * get_cmd_index is broken. */
260         BUG_ON(!is_power_of_2(slots_num));
261
262         q->low_mark = q->n_window / 4;
263         if (q->low_mark < 4)
264                 q->low_mark = 4;
265
266         q->high_mark = q->n_window / 8;
267         if (q->high_mark < 2)
268                 q->high_mark = 2;
269
270         q->write_ptr = q->read_ptr = 0;
271
272         return 0;
273 }
274
275 /**
276  * iwl3945_tx_queue_alloc - Alloc driver data and TFD CB for one Tx/cmd queue
277  */
278 static int iwl3945_tx_queue_alloc(struct iwl3945_priv *priv,
279                               struct iwl3945_tx_queue *txq, u32 id)
280 {
281         struct pci_dev *dev = priv->pci_dev;
282
283         /* Driver private data, only for Tx (not command) queues,
284          * not shared with device. */
285         if (id != IWL_CMD_QUEUE_NUM) {
286                 txq->txb = kmalloc(sizeof(txq->txb[0]) *
287                                    TFD_QUEUE_SIZE_MAX, GFP_KERNEL);
288                 if (!txq->txb) {
289                         IWL_ERROR("kmalloc for auxiliary BD "
290                                   "structures failed\n");
291                         goto error;
292                 }
293         } else
294                 txq->txb = NULL;
295
296         /* Circular buffer of transmit frame descriptors (TFDs),
297          * shared with device */
298         txq->bd = pci_alloc_consistent(dev,
299                         sizeof(txq->bd[0]) * TFD_QUEUE_SIZE_MAX,
300                         &txq->q.dma_addr);
301
302         if (!txq->bd) {
303                 IWL_ERROR("pci_alloc_consistent(%zd) failed\n",
304                           sizeof(txq->bd[0]) * TFD_QUEUE_SIZE_MAX);
305                 goto error;
306         }
307         txq->q.id = id;
308
309         return 0;
310
311  error:
312         if (txq->txb) {
313                 kfree(txq->txb);
314                 txq->txb = NULL;
315         }
316
317         return -ENOMEM;
318 }
319
320 /**
321  * iwl3945_tx_queue_init - Allocate and initialize one tx/cmd queue
322  */
323 int iwl3945_tx_queue_init(struct iwl3945_priv *priv,
324                       struct iwl3945_tx_queue *txq, int slots_num, u32 txq_id)
325 {
326         struct pci_dev *dev = priv->pci_dev;
327         int len;
328         int rc = 0;
329
330         /*
331          * Alloc buffer array for commands (Tx or other types of commands).
332          * For the command queue (#4), allocate command space + one big
333          * command for scan, since scan command is very huge; the system will
334          * not have two scans at the same time, so only one is needed.
335          * For data Tx queues (all other queues), no super-size command
336          * space is needed.
337          */
338         len = sizeof(struct iwl3945_cmd) * slots_num;
339         if (txq_id == IWL_CMD_QUEUE_NUM)
340                 len +=  IWL_MAX_SCAN_SIZE;
341         txq->cmd = pci_alloc_consistent(dev, len, &txq->dma_addr_cmd);
342         if (!txq->cmd)
343                 return -ENOMEM;
344
345         /* Alloc driver data array and TFD circular buffer */
346         rc = iwl3945_tx_queue_alloc(priv, txq, txq_id);
347         if (rc) {
348                 pci_free_consistent(dev, len, txq->cmd, txq->dma_addr_cmd);
349
350                 return -ENOMEM;
351         }
352         txq->need_update = 0;
353
354         /* TFD_QUEUE_SIZE_MAX must be power-of-two size, otherwise
355          * iwl3945_queue_inc_wrap and iwl3945_queue_dec_wrap are broken. */
356         BUILD_BUG_ON(TFD_QUEUE_SIZE_MAX & (TFD_QUEUE_SIZE_MAX - 1));
357
358         /* Initialize queue high/low-water, head/tail indexes */
359         iwl3945_queue_init(priv, &txq->q, TFD_QUEUE_SIZE_MAX, slots_num, txq_id);
360
361         /* Tell device where to find queue, enable DMA channel. */
362         iwl3945_hw_tx_queue_init(priv, txq);
363
364         return 0;
365 }
366
367 /**
368  * iwl3945_tx_queue_free - Deallocate DMA queue.
369  * @txq: Transmit queue to deallocate.
370  *
371  * Empty queue by removing and destroying all BD's.
372  * Free all buffers.
373  * 0-fill, but do not free "txq" descriptor structure.
374  */
375 void iwl3945_tx_queue_free(struct iwl3945_priv *priv, struct iwl3945_tx_queue *txq)
376 {
377         struct iwl3945_queue *q = &txq->q;
378         struct pci_dev *dev = priv->pci_dev;
379         int len;
380
381         if (q->n_bd == 0)
382                 return;
383
384         /* first, empty all BD's */
385         for (; q->write_ptr != q->read_ptr;
386              q->read_ptr = iwl3945_queue_inc_wrap(q->read_ptr, q->n_bd))
387                 iwl3945_hw_txq_free_tfd(priv, txq);
388
389         len = sizeof(struct iwl3945_cmd) * q->n_window;
390         if (q->id == IWL_CMD_QUEUE_NUM)
391                 len += IWL_MAX_SCAN_SIZE;
392
393         /* De-alloc array of command/tx buffers */
394         pci_free_consistent(dev, len, txq->cmd, txq->dma_addr_cmd);
395
396         /* De-alloc circular buffer of TFDs */
397         if (txq->q.n_bd)
398                 pci_free_consistent(dev, sizeof(struct iwl3945_tfd_frame) *
399                                     txq->q.n_bd, txq->bd, txq->q.dma_addr);
400
401         /* De-alloc array of per-TFD driver data */
402         if (txq->txb) {
403                 kfree(txq->txb);
404                 txq->txb = NULL;
405         }
406
407         /* 0-fill queue descriptor structure */
408         memset(txq, 0, sizeof(*txq));
409 }
410
411 const u8 iwl3945_broadcast_addr[ETH_ALEN] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
412
413 /*************** STATION TABLE MANAGEMENT ****
414  * mac80211 should be examined to determine if sta_info is duplicating
415  * the functionality provided here
416  */
417
418 /**************************************************************/
419 #if 0 /* temporary disable till we add real remove station */
420 /**
421  * iwl3945_remove_station - Remove driver's knowledge of station.
422  *
423  * NOTE:  This does not remove station from device's station table.
424  */
425 static u8 iwl3945_remove_station(struct iwl3945_priv *priv, const u8 *addr, int is_ap)
426 {
427         int index = IWL_INVALID_STATION;
428         int i;
429         unsigned long flags;
430
431         spin_lock_irqsave(&priv->sta_lock, flags);
432
433         if (is_ap)
434                 index = IWL_AP_ID;
435         else if (is_broadcast_ether_addr(addr))
436                 index = priv->hw_setting.bcast_sta_id;
437         else
438                 for (i = IWL_STA_ID; i < priv->hw_setting.max_stations; i++)
439                         if (priv->stations[i].used &&
440                             !compare_ether_addr(priv->stations[i].sta.sta.addr,
441                                                 addr)) {
442                                 index = i;
443                                 break;
444                         }
445
446         if (unlikely(index == IWL_INVALID_STATION))
447                 goto out;
448
449         if (priv->stations[index].used) {
450                 priv->stations[index].used = 0;
451                 priv->num_stations--;
452         }
453
454         BUG_ON(priv->num_stations < 0);
455
456 out:
457         spin_unlock_irqrestore(&priv->sta_lock, flags);
458         return 0;
459 }
460 #endif
461
462 /**
463  * iwl3945_clear_stations_table - Clear the driver's station table
464  *
465  * NOTE:  This does not clear or otherwise alter the device's station table.
466  */
467 static void iwl3945_clear_stations_table(struct iwl3945_priv *priv)
468 {
469         unsigned long flags;
470
471         spin_lock_irqsave(&priv->sta_lock, flags);
472
473         priv->num_stations = 0;
474         memset(priv->stations, 0, sizeof(priv->stations));
475
476         spin_unlock_irqrestore(&priv->sta_lock, flags);
477 }
478
479 /**
480  * iwl3945_add_station - Add station to station tables in driver and device
481  */
482 u8 iwl3945_add_station(struct iwl3945_priv *priv, const u8 *addr, int is_ap, u8 flags)
483 {
484         int i;
485         int index = IWL_INVALID_STATION;
486         struct iwl3945_station_entry *station;
487         unsigned long flags_spin;
488         DECLARE_MAC_BUF(mac);
489         u8 rate;
490
491         spin_lock_irqsave(&priv->sta_lock, flags_spin);
492         if (is_ap)
493                 index = IWL_AP_ID;
494         else if (is_broadcast_ether_addr(addr))
495                 index = priv->hw_setting.bcast_sta_id;
496         else
497                 for (i = IWL_STA_ID; i < priv->hw_setting.max_stations; i++) {
498                         if (!compare_ether_addr(priv->stations[i].sta.sta.addr,
499                                                 addr)) {
500                                 index = i;
501                                 break;
502                         }
503
504                         if (!priv->stations[i].used &&
505                             index == IWL_INVALID_STATION)
506                                 index = i;
507                 }
508
509         /* These two conditions has the same outcome but keep them separate
510           since they have different meaning */
511         if (unlikely(index == IWL_INVALID_STATION)) {
512                 spin_unlock_irqrestore(&priv->sta_lock, flags_spin);
513                 return index;
514         }
515
516         if (priv->stations[index].used &&
517            !compare_ether_addr(priv->stations[index].sta.sta.addr, addr)) {
518                 spin_unlock_irqrestore(&priv->sta_lock, flags_spin);
519                 return index;
520         }
521
522         IWL_DEBUG_ASSOC("Add STA ID %d: %s\n", index, print_mac(mac, addr));
523         station = &priv->stations[index];
524         station->used = 1;
525         priv->num_stations++;
526
527         /* Set up the REPLY_ADD_STA command to send to device */
528         memset(&station->sta, 0, sizeof(struct iwl3945_addsta_cmd));
529         memcpy(station->sta.sta.addr, addr, ETH_ALEN);
530         station->sta.mode = 0;
531         station->sta.sta.sta_id = index;
532         station->sta.station_flags = 0;
533
534         if (priv->band == IEEE80211_BAND_5GHZ)
535                 rate = IWL_RATE_6M_PLCP;
536         else
537                 rate =  IWL_RATE_1M_PLCP;
538
539         /* Turn on both antennas for the station... */
540         station->sta.rate_n_flags =
541                         iwl3945_hw_set_rate_n_flags(rate, RATE_MCS_ANT_AB_MSK);
542         station->current_rate.rate_n_flags =
543                         le16_to_cpu(station->sta.rate_n_flags);
544
545         spin_unlock_irqrestore(&priv->sta_lock, flags_spin);
546
547         /* Add station to device's station table */
548         iwl3945_send_add_station(priv, &station->sta, flags);
549         return index;
550
551 }
552
553 /*************** DRIVER STATUS FUNCTIONS   *****/
554
555 static inline int iwl3945_is_ready(struct iwl3945_priv *priv)
556 {
557         /* The adapter is 'ready' if READY and GEO_CONFIGURED bits are
558          * set but EXIT_PENDING is not */
559         return test_bit(STATUS_READY, &priv->status) &&
560                test_bit(STATUS_GEO_CONFIGURED, &priv->status) &&
561                !test_bit(STATUS_EXIT_PENDING, &priv->status);
562 }
563
564 static inline int iwl3945_is_alive(struct iwl3945_priv *priv)
565 {
566         return test_bit(STATUS_ALIVE, &priv->status);
567 }
568
569 static inline int iwl3945_is_init(struct iwl3945_priv *priv)
570 {
571         return test_bit(STATUS_INIT, &priv->status);
572 }
573
574 static inline int iwl3945_is_rfkill(struct iwl3945_priv *priv)
575 {
576         return test_bit(STATUS_RF_KILL_HW, &priv->status) ||
577                test_bit(STATUS_RF_KILL_SW, &priv->status);
578 }
579
580 static inline int iwl3945_is_ready_rf(struct iwl3945_priv *priv)
581 {
582
583         if (iwl3945_is_rfkill(priv))
584                 return 0;
585
586         return iwl3945_is_ready(priv);
587 }
588
589 /*************** HOST COMMAND QUEUE FUNCTIONS   *****/
590
591 #define IWL_CMD(x) case x : return #x
592
593 static const char *get_cmd_string(u8 cmd)
594 {
595         switch (cmd) {
596                 IWL_CMD(REPLY_ALIVE);
597                 IWL_CMD(REPLY_ERROR);
598                 IWL_CMD(REPLY_RXON);
599                 IWL_CMD(REPLY_RXON_ASSOC);
600                 IWL_CMD(REPLY_QOS_PARAM);
601                 IWL_CMD(REPLY_RXON_TIMING);
602                 IWL_CMD(REPLY_ADD_STA);
603                 IWL_CMD(REPLY_REMOVE_STA);
604                 IWL_CMD(REPLY_REMOVE_ALL_STA);
605                 IWL_CMD(REPLY_3945_RX);
606                 IWL_CMD(REPLY_TX);
607                 IWL_CMD(REPLY_RATE_SCALE);
608                 IWL_CMD(REPLY_LEDS_CMD);
609                 IWL_CMD(REPLY_TX_LINK_QUALITY_CMD);
610                 IWL_CMD(RADAR_NOTIFICATION);
611                 IWL_CMD(REPLY_QUIET_CMD);
612                 IWL_CMD(REPLY_CHANNEL_SWITCH);
613                 IWL_CMD(CHANNEL_SWITCH_NOTIFICATION);
614                 IWL_CMD(REPLY_SPECTRUM_MEASUREMENT_CMD);
615                 IWL_CMD(SPECTRUM_MEASURE_NOTIFICATION);
616                 IWL_CMD(POWER_TABLE_CMD);
617                 IWL_CMD(PM_SLEEP_NOTIFICATION);
618                 IWL_CMD(PM_DEBUG_STATISTIC_NOTIFIC);
619                 IWL_CMD(REPLY_SCAN_CMD);
620                 IWL_CMD(REPLY_SCAN_ABORT_CMD);
621                 IWL_CMD(SCAN_START_NOTIFICATION);
622                 IWL_CMD(SCAN_RESULTS_NOTIFICATION);
623                 IWL_CMD(SCAN_COMPLETE_NOTIFICATION);
624                 IWL_CMD(BEACON_NOTIFICATION);
625                 IWL_CMD(REPLY_TX_BEACON);
626                 IWL_CMD(WHO_IS_AWAKE_NOTIFICATION);
627                 IWL_CMD(QUIET_NOTIFICATION);
628                 IWL_CMD(REPLY_TX_PWR_TABLE_CMD);
629                 IWL_CMD(MEASURE_ABORT_NOTIFICATION);
630                 IWL_CMD(REPLY_BT_CONFIG);
631                 IWL_CMD(REPLY_STATISTICS_CMD);
632                 IWL_CMD(STATISTICS_NOTIFICATION);
633                 IWL_CMD(REPLY_CARD_STATE_CMD);
634                 IWL_CMD(CARD_STATE_NOTIFICATION);
635                 IWL_CMD(MISSED_BEACONS_NOTIFICATION);
636         default:
637                 return "UNKNOWN";
638
639         }
640 }
641
642 #define HOST_COMPLETE_TIMEOUT (HZ / 2)
643
644 /**
645  * iwl3945_enqueue_hcmd - enqueue a uCode command
646  * @priv: device private data point
647  * @cmd: a point to the ucode command structure
648  *
649  * The function returns < 0 values to indicate the operation is
650  * failed. On success, it turns the index (> 0) of command in the
651  * command queue.
652  */
653 static int iwl3945_enqueue_hcmd(struct iwl3945_priv *priv, struct iwl3945_host_cmd *cmd)
654 {
655         struct iwl3945_tx_queue *txq = &priv->txq[IWL_CMD_QUEUE_NUM];
656         struct iwl3945_queue *q = &txq->q;
657         struct iwl3945_tfd_frame *tfd;
658         u32 *control_flags;
659         struct iwl3945_cmd *out_cmd;
660         u32 idx;
661         u16 fix_size = (u16)(cmd->len + sizeof(out_cmd->hdr));
662         dma_addr_t phys_addr;
663         int pad;
664         u16 count;
665         int ret;
666         unsigned long flags;
667
668         /* If any of the command structures end up being larger than
669          * the TFD_MAX_PAYLOAD_SIZE, and it sent as a 'small' command then
670          * we will need to increase the size of the TFD entries */
671         BUG_ON((fix_size > TFD_MAX_PAYLOAD_SIZE) &&
672                !(cmd->meta.flags & CMD_SIZE_HUGE));
673
674
675         if (iwl3945_is_rfkill(priv)) {
676                 IWL_DEBUG_INFO("Not sending command - RF KILL");
677                 return -EIO;
678         }
679
680         if (iwl3945_queue_space(q) < ((cmd->meta.flags & CMD_ASYNC) ? 2 : 1)) {
681                 IWL_ERROR("No space for Tx\n");
682                 return -ENOSPC;
683         }
684
685         spin_lock_irqsave(&priv->hcmd_lock, flags);
686
687         tfd = &txq->bd[q->write_ptr];
688         memset(tfd, 0, sizeof(*tfd));
689
690         control_flags = (u32 *) tfd;
691
692         idx = get_cmd_index(q, q->write_ptr, cmd->meta.flags & CMD_SIZE_HUGE);
693         out_cmd = &txq->cmd[idx];
694
695         out_cmd->hdr.cmd = cmd->id;
696         memcpy(&out_cmd->meta, &cmd->meta, sizeof(cmd->meta));
697         memcpy(&out_cmd->cmd.payload, cmd->data, cmd->len);
698
699         /* At this point, the out_cmd now has all of the incoming cmd
700          * information */
701
702         out_cmd->hdr.flags = 0;
703         out_cmd->hdr.sequence = cpu_to_le16(QUEUE_TO_SEQ(IWL_CMD_QUEUE_NUM) |
704                         INDEX_TO_SEQ(q->write_ptr));
705         if (out_cmd->meta.flags & CMD_SIZE_HUGE)
706                 out_cmd->hdr.sequence |= cpu_to_le16(SEQ_HUGE_FRAME);
707
708         phys_addr = txq->dma_addr_cmd + sizeof(txq->cmd[0]) * idx +
709                         offsetof(struct iwl3945_cmd, hdr);
710         iwl3945_hw_txq_attach_buf_to_tfd(priv, tfd, phys_addr, fix_size);
711
712         pad = U32_PAD(cmd->len);
713         count = TFD_CTL_COUNT_GET(*control_flags);
714         *control_flags = TFD_CTL_COUNT_SET(count) | TFD_CTL_PAD_SET(pad);
715
716         IWL_DEBUG_HC("Sending command %s (#%x), seq: 0x%04X, "
717                      "%d bytes at %d[%d]:%d\n",
718                      get_cmd_string(out_cmd->hdr.cmd),
719                      out_cmd->hdr.cmd, le16_to_cpu(out_cmd->hdr.sequence),
720                      fix_size, q->write_ptr, idx, IWL_CMD_QUEUE_NUM);
721
722         txq->need_update = 1;
723
724         /* Increment and update queue's write index */
725         q->write_ptr = iwl3945_queue_inc_wrap(q->write_ptr, q->n_bd);
726         ret = iwl3945_tx_queue_update_write_ptr(priv, txq);
727
728         spin_unlock_irqrestore(&priv->hcmd_lock, flags);
729         return ret ? ret : idx;
730 }
731
732 static int iwl3945_send_cmd_async(struct iwl3945_priv *priv, struct iwl3945_host_cmd *cmd)
733 {
734         int ret;
735
736         BUG_ON(!(cmd->meta.flags & CMD_ASYNC));
737
738         /* An asynchronous command can not expect an SKB to be set. */
739         BUG_ON(cmd->meta.flags & CMD_WANT_SKB);
740
741         /* An asynchronous command MUST have a callback. */
742         BUG_ON(!cmd->meta.u.callback);
743
744         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
745                 return -EBUSY;
746
747         ret = iwl3945_enqueue_hcmd(priv, cmd);
748         if (ret < 0) {
749                 IWL_ERROR("Error sending %s: iwl3945_enqueue_hcmd failed: %d\n",
750                           get_cmd_string(cmd->id), ret);
751                 return ret;
752         }
753         return 0;
754 }
755
756 static int iwl3945_send_cmd_sync(struct iwl3945_priv *priv, struct iwl3945_host_cmd *cmd)
757 {
758         int cmd_idx;
759         int ret;
760         static atomic_t entry = ATOMIC_INIT(0); /* reentrance protection */
761
762         BUG_ON(cmd->meta.flags & CMD_ASYNC);
763
764          /* A synchronous command can not have a callback set. */
765         BUG_ON(cmd->meta.u.callback != NULL);
766
767         if (atomic_xchg(&entry, 1)) {
768                 IWL_ERROR("Error sending %s: Already sending a host command\n",
769                           get_cmd_string(cmd->id));
770                 return -EBUSY;
771         }
772
773         set_bit(STATUS_HCMD_ACTIVE, &priv->status);
774
775         if (cmd->meta.flags & CMD_WANT_SKB)
776                 cmd->meta.source = &cmd->meta;
777
778         cmd_idx = iwl3945_enqueue_hcmd(priv, cmd);
779         if (cmd_idx < 0) {
780                 ret = cmd_idx;
781                 IWL_ERROR("Error sending %s: iwl3945_enqueue_hcmd failed: %d\n",
782                           get_cmd_string(cmd->id), ret);
783                 goto out;
784         }
785
786         ret = wait_event_interruptible_timeout(priv->wait_command_queue,
787                         !test_bit(STATUS_HCMD_ACTIVE, &priv->status),
788                         HOST_COMPLETE_TIMEOUT);
789         if (!ret) {
790                 if (test_bit(STATUS_HCMD_ACTIVE, &priv->status)) {
791                         IWL_ERROR("Error sending %s: time out after %dms.\n",
792                                   get_cmd_string(cmd->id),
793                                   jiffies_to_msecs(HOST_COMPLETE_TIMEOUT));
794
795                         clear_bit(STATUS_HCMD_ACTIVE, &priv->status);
796                         ret = -ETIMEDOUT;
797                         goto cancel;
798                 }
799         }
800
801         if (test_bit(STATUS_RF_KILL_HW, &priv->status)) {
802                 IWL_DEBUG_INFO("Command %s aborted: RF KILL Switch\n",
803                                get_cmd_string(cmd->id));
804                 ret = -ECANCELED;
805                 goto fail;
806         }
807         if (test_bit(STATUS_FW_ERROR, &priv->status)) {
808                 IWL_DEBUG_INFO("Command %s failed: FW Error\n",
809                                get_cmd_string(cmd->id));
810                 ret = -EIO;
811                 goto fail;
812         }
813         if ((cmd->meta.flags & CMD_WANT_SKB) && !cmd->meta.u.skb) {
814                 IWL_ERROR("Error: Response NULL in '%s'\n",
815                           get_cmd_string(cmd->id));
816                 ret = -EIO;
817                 goto out;
818         }
819
820         ret = 0;
821         goto out;
822
823 cancel:
824         if (cmd->meta.flags & CMD_WANT_SKB) {
825                 struct iwl3945_cmd *qcmd;
826
827                 /* Cancel the CMD_WANT_SKB flag for the cmd in the
828                  * TX cmd queue. Otherwise in case the cmd comes
829                  * in later, it will possibly set an invalid
830                  * address (cmd->meta.source). */
831                 qcmd = &priv->txq[IWL_CMD_QUEUE_NUM].cmd[cmd_idx];
832                 qcmd->meta.flags &= ~CMD_WANT_SKB;
833         }
834 fail:
835         if (cmd->meta.u.skb) {
836                 dev_kfree_skb_any(cmd->meta.u.skb);
837                 cmd->meta.u.skb = NULL;
838         }
839 out:
840         atomic_set(&entry, 0);
841         return ret;
842 }
843
844 int iwl3945_send_cmd(struct iwl3945_priv *priv, struct iwl3945_host_cmd *cmd)
845 {
846         if (cmd->meta.flags & CMD_ASYNC)
847                 return iwl3945_send_cmd_async(priv, cmd);
848
849         return iwl3945_send_cmd_sync(priv, cmd);
850 }
851
852 int iwl3945_send_cmd_pdu(struct iwl3945_priv *priv, u8 id, u16 len, const void *data)
853 {
854         struct iwl3945_host_cmd cmd = {
855                 .id = id,
856                 .len = len,
857                 .data = data,
858         };
859
860         return iwl3945_send_cmd_sync(priv, &cmd);
861 }
862
863 static int __must_check iwl3945_send_cmd_u32(struct iwl3945_priv *priv, u8 id, u32 val)
864 {
865         struct iwl3945_host_cmd cmd = {
866                 .id = id,
867                 .len = sizeof(val),
868                 .data = &val,
869         };
870
871         return iwl3945_send_cmd_sync(priv, &cmd);
872 }
873
874 int iwl3945_send_statistics_request(struct iwl3945_priv *priv)
875 {
876         return iwl3945_send_cmd_u32(priv, REPLY_STATISTICS_CMD, 0);
877 }
878
879 /**
880  * iwl3945_set_rxon_channel - Set the phymode and channel values in staging RXON
881  * @band: 2.4 or 5 GHz band
882  * @channel: Any channel valid for the requested band
883
884  * In addition to setting the staging RXON, priv->band is also set.
885  *
886  * NOTE:  Does not commit to the hardware; it sets appropriate bit fields
887  * in the staging RXON flag structure based on the band
888  */
889 static int iwl3945_set_rxon_channel(struct iwl3945_priv *priv,
890                                     enum ieee80211_band band,
891                                     u16 channel)
892 {
893         if (!iwl3945_get_channel_info(priv, band, channel)) {
894                 IWL_DEBUG_INFO("Could not set channel to %d [%d]\n",
895                                channel, band);
896                 return -EINVAL;
897         }
898
899         if ((le16_to_cpu(priv->staging_rxon.channel) == channel) &&
900             (priv->band == band))
901                 return 0;
902
903         priv->staging_rxon.channel = cpu_to_le16(channel);
904         if (band == IEEE80211_BAND_5GHZ)
905                 priv->staging_rxon.flags &= ~RXON_FLG_BAND_24G_MSK;
906         else
907                 priv->staging_rxon.flags |= RXON_FLG_BAND_24G_MSK;
908
909         priv->band = band;
910
911         IWL_DEBUG_INFO("Staging channel set to %d [%d]\n", channel, band);
912
913         return 0;
914 }
915
916 /**
917  * iwl3945_check_rxon_cmd - validate RXON structure is valid
918  *
919  * NOTE:  This is really only useful during development and can eventually
920  * be #ifdef'd out once the driver is stable and folks aren't actively
921  * making changes
922  */
923 static int iwl3945_check_rxon_cmd(struct iwl3945_rxon_cmd *rxon)
924 {
925         int error = 0;
926         int counter = 1;
927
928         if (rxon->flags & RXON_FLG_BAND_24G_MSK) {
929                 error |= le32_to_cpu(rxon->flags &
930                                 (RXON_FLG_TGJ_NARROW_BAND_MSK |
931                                  RXON_FLG_RADAR_DETECT_MSK));
932                 if (error)
933                         IWL_WARNING("check 24G fields %d | %d\n",
934                                     counter++, error);
935         } else {
936                 error |= (rxon->flags & RXON_FLG_SHORT_SLOT_MSK) ?
937                                 0 : le32_to_cpu(RXON_FLG_SHORT_SLOT_MSK);
938                 if (error)
939                         IWL_WARNING("check 52 fields %d | %d\n",
940                                     counter++, error);
941                 error |= le32_to_cpu(rxon->flags & RXON_FLG_CCK_MSK);
942                 if (error)
943                         IWL_WARNING("check 52 CCK %d | %d\n",
944                                     counter++, error);
945         }
946         error |= (rxon->node_addr[0] | rxon->bssid_addr[0]) & 0x1;
947         if (error)
948                 IWL_WARNING("check mac addr %d | %d\n", counter++, error);
949
950         /* make sure basic rates 6Mbps and 1Mbps are supported */
951         error |= (((rxon->ofdm_basic_rates & IWL_RATE_6M_MASK) == 0) &&
952                   ((rxon->cck_basic_rates & IWL_RATE_1M_MASK) == 0));
953         if (error)
954                 IWL_WARNING("check basic rate %d | %d\n", counter++, error);
955
956         error |= (le16_to_cpu(rxon->assoc_id) > 2007);
957         if (error)
958                 IWL_WARNING("check assoc id %d | %d\n", counter++, error);
959
960         error |= ((rxon->flags & (RXON_FLG_CCK_MSK | RXON_FLG_SHORT_SLOT_MSK))
961                         == (RXON_FLG_CCK_MSK | RXON_FLG_SHORT_SLOT_MSK));
962         if (error)
963                 IWL_WARNING("check CCK and short slot %d | %d\n",
964                             counter++, error);
965
966         error |= ((rxon->flags & (RXON_FLG_CCK_MSK | RXON_FLG_AUTO_DETECT_MSK))
967                         == (RXON_FLG_CCK_MSK | RXON_FLG_AUTO_DETECT_MSK));
968         if (error)
969                 IWL_WARNING("check CCK & auto detect %d | %d\n",
970                             counter++, error);
971
972         error |= ((rxon->flags & (RXON_FLG_AUTO_DETECT_MSK |
973                         RXON_FLG_TGG_PROTECT_MSK)) == RXON_FLG_TGG_PROTECT_MSK);
974         if (error)
975                 IWL_WARNING("check TGG and auto detect %d | %d\n",
976                             counter++, error);
977
978         if ((rxon->flags & RXON_FLG_DIS_DIV_MSK))
979                 error |= ((rxon->flags & (RXON_FLG_ANT_B_MSK |
980                                 RXON_FLG_ANT_A_MSK)) == 0);
981         if (error)
982                 IWL_WARNING("check antenna %d %d\n", counter++, error);
983
984         if (error)
985                 IWL_WARNING("Tuning to channel %d\n",
986                             le16_to_cpu(rxon->channel));
987
988         if (error) {
989                 IWL_ERROR("Not a valid iwl3945_rxon_assoc_cmd field values\n");
990                 return -1;
991         }
992         return 0;
993 }
994
995 /**
996  * iwl3945_full_rxon_required - check if full RXON (vs RXON_ASSOC) cmd is needed
997  * @priv: staging_rxon is compared to active_rxon
998  *
999  * If the RXON structure is changing enough to require a new tune,
1000  * or is clearing the RXON_FILTER_ASSOC_MSK, then return 1 to indicate that
1001  * a new tune (full RXON command, rather than RXON_ASSOC cmd) is required.
1002  */
1003 static int iwl3945_full_rxon_required(struct iwl3945_priv *priv)
1004 {
1005
1006         /* These items are only settable from the full RXON command */
1007         if (!(priv->active_rxon.filter_flags & RXON_FILTER_ASSOC_MSK) ||
1008             compare_ether_addr(priv->staging_rxon.bssid_addr,
1009                                priv->active_rxon.bssid_addr) ||
1010             compare_ether_addr(priv->staging_rxon.node_addr,
1011                                priv->active_rxon.node_addr) ||
1012             compare_ether_addr(priv->staging_rxon.wlap_bssid_addr,
1013                                priv->active_rxon.wlap_bssid_addr) ||
1014             (priv->staging_rxon.dev_type != priv->active_rxon.dev_type) ||
1015             (priv->staging_rxon.channel != priv->active_rxon.channel) ||
1016             (priv->staging_rxon.air_propagation !=
1017              priv->active_rxon.air_propagation) ||
1018             (priv->staging_rxon.assoc_id != priv->active_rxon.assoc_id))
1019                 return 1;
1020
1021         /* flags, filter_flags, ofdm_basic_rates, and cck_basic_rates can
1022          * be updated with the RXON_ASSOC command -- however only some
1023          * flag transitions are allowed using RXON_ASSOC */
1024
1025         /* Check if we are not switching bands */
1026         if ((priv->staging_rxon.flags & RXON_FLG_BAND_24G_MSK) !=
1027             (priv->active_rxon.flags & RXON_FLG_BAND_24G_MSK))
1028                 return 1;
1029
1030         /* Check if we are switching association toggle */
1031         if ((priv->staging_rxon.filter_flags & RXON_FILTER_ASSOC_MSK) !=
1032                 (priv->active_rxon.filter_flags & RXON_FILTER_ASSOC_MSK))
1033                 return 1;
1034
1035         return 0;
1036 }
1037
1038 static int iwl3945_send_rxon_assoc(struct iwl3945_priv *priv)
1039 {
1040         int rc = 0;
1041         struct iwl3945_rx_packet *res = NULL;
1042         struct iwl3945_rxon_assoc_cmd rxon_assoc;
1043         struct iwl3945_host_cmd cmd = {
1044                 .id = REPLY_RXON_ASSOC,
1045                 .len = sizeof(rxon_assoc),
1046                 .meta.flags = CMD_WANT_SKB,
1047                 .data = &rxon_assoc,
1048         };
1049         const struct iwl3945_rxon_cmd *rxon1 = &priv->staging_rxon;
1050         const struct iwl3945_rxon_cmd *rxon2 = &priv->active_rxon;
1051
1052         if ((rxon1->flags == rxon2->flags) &&
1053             (rxon1->filter_flags == rxon2->filter_flags) &&
1054             (rxon1->cck_basic_rates == rxon2->cck_basic_rates) &&
1055             (rxon1->ofdm_basic_rates == rxon2->ofdm_basic_rates)) {
1056                 IWL_DEBUG_INFO("Using current RXON_ASSOC.  Not resending.\n");
1057                 return 0;
1058         }
1059
1060         rxon_assoc.flags = priv->staging_rxon.flags;
1061         rxon_assoc.filter_flags = priv->staging_rxon.filter_flags;
1062         rxon_assoc.ofdm_basic_rates = priv->staging_rxon.ofdm_basic_rates;
1063         rxon_assoc.cck_basic_rates = priv->staging_rxon.cck_basic_rates;
1064         rxon_assoc.reserved = 0;
1065
1066         rc = iwl3945_send_cmd_sync(priv, &cmd);
1067         if (rc)
1068                 return rc;
1069
1070         res = (struct iwl3945_rx_packet *)cmd.meta.u.skb->data;
1071         if (res->hdr.flags & IWL_CMD_FAILED_MSK) {
1072                 IWL_ERROR("Bad return from REPLY_RXON_ASSOC command\n");
1073                 rc = -EIO;
1074         }
1075
1076         priv->alloc_rxb_skb--;
1077         dev_kfree_skb_any(cmd.meta.u.skb);
1078
1079         return rc;
1080 }
1081
1082 /**
1083  * iwl3945_commit_rxon - commit staging_rxon to hardware
1084  *
1085  * The RXON command in staging_rxon is committed to the hardware and
1086  * the active_rxon structure is updated with the new data.  This
1087  * function correctly transitions out of the RXON_ASSOC_MSK state if
1088  * a HW tune is required based on the RXON structure changes.
1089  */
1090 static int iwl3945_commit_rxon(struct iwl3945_priv *priv)
1091 {
1092         /* cast away the const for active_rxon in this function */
1093         struct iwl3945_rxon_cmd *active_rxon = (void *)&priv->active_rxon;
1094         int rc = 0;
1095         DECLARE_MAC_BUF(mac);
1096
1097         if (!iwl3945_is_alive(priv))
1098                 return -1;
1099
1100         /* always get timestamp with Rx frame */
1101         priv->staging_rxon.flags |= RXON_FLG_TSF2HOST_MSK;
1102
1103         /* select antenna */
1104         priv->staging_rxon.flags &=
1105             ~(RXON_FLG_DIS_DIV_MSK | RXON_FLG_ANT_SEL_MSK);
1106         priv->staging_rxon.flags |= iwl3945_get_antenna_flags(priv);
1107
1108         rc = iwl3945_check_rxon_cmd(&priv->staging_rxon);
1109         if (rc) {
1110                 IWL_ERROR("Invalid RXON configuration.  Not committing.\n");
1111                 return -EINVAL;
1112         }
1113
1114         /* If we don't need to send a full RXON, we can use
1115          * iwl3945_rxon_assoc_cmd which is used to reconfigure filter
1116          * and other flags for the current radio configuration. */
1117         if (!iwl3945_full_rxon_required(priv)) {
1118                 rc = iwl3945_send_rxon_assoc(priv);
1119                 if (rc) {
1120                         IWL_ERROR("Error setting RXON_ASSOC "
1121                                   "configuration (%d).\n", rc);
1122                         return rc;
1123                 }
1124
1125                 memcpy(active_rxon, &priv->staging_rxon, sizeof(*active_rxon));
1126
1127                 return 0;
1128         }
1129
1130         /* If we are currently associated and the new config requires
1131          * an RXON_ASSOC and the new config wants the associated mask enabled,
1132          * we must clear the associated from the active configuration
1133          * before we apply the new config */
1134         if (iwl3945_is_associated(priv) &&
1135             (priv->staging_rxon.filter_flags & RXON_FILTER_ASSOC_MSK)) {
1136                 IWL_DEBUG_INFO("Toggling associated bit on current RXON\n");
1137                 active_rxon->filter_flags &= ~RXON_FILTER_ASSOC_MSK;
1138
1139                 rc = iwl3945_send_cmd_pdu(priv, REPLY_RXON,
1140                                       sizeof(struct iwl3945_rxon_cmd),
1141                                       &priv->active_rxon);
1142
1143                 /* If the mask clearing failed then we set
1144                  * active_rxon back to what it was previously */
1145                 if (rc) {
1146                         active_rxon->filter_flags |= RXON_FILTER_ASSOC_MSK;
1147                         IWL_ERROR("Error clearing ASSOC_MSK on current "
1148                                   "configuration (%d).\n", rc);
1149                         return rc;
1150                 }
1151         }
1152
1153         IWL_DEBUG_INFO("Sending RXON\n"
1154                        "* with%s RXON_FILTER_ASSOC_MSK\n"
1155                        "* channel = %d\n"
1156                        "* bssid = %s\n",
1157                        ((priv->staging_rxon.filter_flags &
1158                          RXON_FILTER_ASSOC_MSK) ? "" : "out"),
1159                        le16_to_cpu(priv->staging_rxon.channel),
1160                        print_mac(mac, priv->staging_rxon.bssid_addr));
1161
1162         /* Apply the new configuration */
1163         rc = iwl3945_send_cmd_pdu(priv, REPLY_RXON,
1164                               sizeof(struct iwl3945_rxon_cmd), &priv->staging_rxon);
1165         if (rc) {
1166                 IWL_ERROR("Error setting new configuration (%d).\n", rc);
1167                 return rc;
1168         }
1169
1170         memcpy(active_rxon, &priv->staging_rxon, sizeof(*active_rxon));
1171
1172         iwl3945_clear_stations_table(priv);
1173
1174         /* If we issue a new RXON command which required a tune then we must
1175          * send a new TXPOWER command or we won't be able to Tx any frames */
1176         rc = iwl3945_hw_reg_send_txpower(priv);
1177         if (rc) {
1178                 IWL_ERROR("Error setting Tx power (%d).\n", rc);
1179                 return rc;
1180         }
1181
1182         /* Add the broadcast address so we can send broadcast frames */
1183         if (iwl3945_add_station(priv, iwl3945_broadcast_addr, 0, 0) ==
1184             IWL_INVALID_STATION) {
1185                 IWL_ERROR("Error adding BROADCAST address for transmit.\n");
1186                 return -EIO;
1187         }
1188
1189         /* If we have set the ASSOC_MSK and we are in BSS mode then
1190          * add the IWL_AP_ID to the station rate table */
1191         if (iwl3945_is_associated(priv) &&
1192             (priv->iw_mode == IEEE80211_IF_TYPE_STA))
1193                 if (iwl3945_add_station(priv, priv->active_rxon.bssid_addr, 1, 0)
1194                     == IWL_INVALID_STATION) {
1195                         IWL_ERROR("Error adding AP address for transmit.\n");
1196                         return -EIO;
1197                 }
1198
1199         /* Init the hardware's rate fallback order based on the band */
1200         rc = iwl3945_init_hw_rate_table(priv);
1201         if (rc) {
1202                 IWL_ERROR("Error setting HW rate table: %02X\n", rc);
1203                 return -EIO;
1204         }
1205
1206         return 0;
1207 }
1208
1209 static int iwl3945_send_bt_config(struct iwl3945_priv *priv)
1210 {
1211         struct iwl3945_bt_cmd bt_cmd = {
1212                 .flags = 3,
1213                 .lead_time = 0xAA,
1214                 .max_kill = 1,
1215                 .kill_ack_mask = 0,
1216                 .kill_cts_mask = 0,
1217         };
1218
1219         return iwl3945_send_cmd_pdu(priv, REPLY_BT_CONFIG,
1220                                 sizeof(struct iwl3945_bt_cmd), &bt_cmd);
1221 }
1222
1223 static int iwl3945_send_scan_abort(struct iwl3945_priv *priv)
1224 {
1225         int rc = 0;
1226         struct iwl3945_rx_packet *res;
1227         struct iwl3945_host_cmd cmd = {
1228                 .id = REPLY_SCAN_ABORT_CMD,
1229                 .meta.flags = CMD_WANT_SKB,
1230         };
1231
1232         /* If there isn't a scan actively going on in the hardware
1233          * then we are in between scan bands and not actually
1234          * actively scanning, so don't send the abort command */
1235         if (!test_bit(STATUS_SCAN_HW, &priv->status)) {
1236                 clear_bit(STATUS_SCAN_ABORTING, &priv->status);
1237                 return 0;
1238         }
1239
1240         rc = iwl3945_send_cmd_sync(priv, &cmd);
1241         if (rc) {
1242                 clear_bit(STATUS_SCAN_ABORTING, &priv->status);
1243                 return rc;
1244         }
1245
1246         res = (struct iwl3945_rx_packet *)cmd.meta.u.skb->data;
1247         if (res->u.status != CAN_ABORT_STATUS) {
1248                 /* The scan abort will return 1 for success or
1249                  * 2 for "failure".  A failure condition can be
1250                  * due to simply not being in an active scan which
1251                  * can occur if we send the scan abort before we
1252                  * the microcode has notified us that a scan is
1253                  * completed. */
1254                 IWL_DEBUG_INFO("SCAN_ABORT returned %d.\n", res->u.status);
1255                 clear_bit(STATUS_SCAN_ABORTING, &priv->status);
1256                 clear_bit(STATUS_SCAN_HW, &priv->status);
1257         }
1258
1259         dev_kfree_skb_any(cmd.meta.u.skb);
1260
1261         return rc;
1262 }
1263
1264 static int iwl3945_card_state_sync_callback(struct iwl3945_priv *priv,
1265                                         struct iwl3945_cmd *cmd,
1266                                         struct sk_buff *skb)
1267 {
1268         return 1;
1269 }
1270
1271 /*
1272  * CARD_STATE_CMD
1273  *
1274  * Use: Sets the device's internal card state to enable, disable, or halt
1275  *
1276  * When in the 'enable' state the card operates as normal.
1277  * When in the 'disable' state, the card enters into a low power mode.
1278  * When in the 'halt' state, the card is shut down and must be fully
1279  * restarted to come back on.
1280  */
1281 static int iwl3945_send_card_state(struct iwl3945_priv *priv, u32 flags, u8 meta_flag)
1282 {
1283         struct iwl3945_host_cmd cmd = {
1284                 .id = REPLY_CARD_STATE_CMD,
1285                 .len = sizeof(u32),
1286                 .data = &flags,
1287                 .meta.flags = meta_flag,
1288         };
1289
1290         if (meta_flag & CMD_ASYNC)
1291                 cmd.meta.u.callback = iwl3945_card_state_sync_callback;
1292
1293         return iwl3945_send_cmd(priv, &cmd);
1294 }
1295
1296 static int iwl3945_add_sta_sync_callback(struct iwl3945_priv *priv,
1297                                      struct iwl3945_cmd *cmd, struct sk_buff *skb)
1298 {
1299         struct iwl3945_rx_packet *res = NULL;
1300
1301         if (!skb) {
1302                 IWL_ERROR("Error: Response NULL in REPLY_ADD_STA.\n");
1303                 return 1;
1304         }
1305
1306         res = (struct iwl3945_rx_packet *)skb->data;
1307         if (res->hdr.flags & IWL_CMD_FAILED_MSK) {
1308                 IWL_ERROR("Bad return from REPLY_ADD_STA (0x%08X)\n",
1309                           res->hdr.flags);
1310                 return 1;
1311         }
1312
1313         switch (res->u.add_sta.status) {
1314         case ADD_STA_SUCCESS_MSK:
1315                 break;
1316         default:
1317                 break;
1318         }
1319
1320         /* We didn't cache the SKB; let the caller free it */
1321         return 1;
1322 }
1323
1324 int iwl3945_send_add_station(struct iwl3945_priv *priv,
1325                          struct iwl3945_addsta_cmd *sta, u8 flags)
1326 {
1327         struct iwl3945_rx_packet *res = NULL;
1328         int rc = 0;
1329         struct iwl3945_host_cmd cmd = {
1330                 .id = REPLY_ADD_STA,
1331                 .len = sizeof(struct iwl3945_addsta_cmd),
1332                 .meta.flags = flags,
1333                 .data = sta,
1334         };
1335
1336         if (flags & CMD_ASYNC)
1337                 cmd.meta.u.callback = iwl3945_add_sta_sync_callback;
1338         else
1339                 cmd.meta.flags |= CMD_WANT_SKB;
1340
1341         rc = iwl3945_send_cmd(priv, &cmd);
1342
1343         if (rc || (flags & CMD_ASYNC))
1344                 return rc;
1345
1346         res = (struct iwl3945_rx_packet *)cmd.meta.u.skb->data;
1347         if (res->hdr.flags & IWL_CMD_FAILED_MSK) {
1348                 IWL_ERROR("Bad return from REPLY_ADD_STA (0x%08X)\n",
1349                           res->hdr.flags);
1350                 rc = -EIO;
1351         }
1352
1353         if (rc == 0) {
1354                 switch (res->u.add_sta.status) {
1355                 case ADD_STA_SUCCESS_MSK:
1356                         IWL_DEBUG_INFO("REPLY_ADD_STA PASSED\n");
1357                         break;
1358                 default:
1359                         rc = -EIO;
1360                         IWL_WARNING("REPLY_ADD_STA failed\n");
1361                         break;
1362                 }
1363         }
1364
1365         priv->alloc_rxb_skb--;
1366         dev_kfree_skb_any(cmd.meta.u.skb);
1367
1368         return rc;
1369 }
1370
1371 static int iwl3945_update_sta_key_info(struct iwl3945_priv *priv,
1372                                    struct ieee80211_key_conf *keyconf,
1373                                    u8 sta_id)
1374 {
1375         unsigned long flags;
1376         __le16 key_flags = 0;
1377
1378         switch (keyconf->alg) {
1379         case ALG_CCMP:
1380                 key_flags |= STA_KEY_FLG_CCMP;
1381                 key_flags |= cpu_to_le16(
1382                                 keyconf->keyidx << STA_KEY_FLG_KEYID_POS);
1383                 key_flags &= ~STA_KEY_FLG_INVALID;
1384                 break;
1385         case ALG_TKIP:
1386         case ALG_WEP:
1387         default:
1388                 return -EINVAL;
1389         }
1390         spin_lock_irqsave(&priv->sta_lock, flags);
1391         priv->stations[sta_id].keyinfo.alg = keyconf->alg;
1392         priv->stations[sta_id].keyinfo.keylen = keyconf->keylen;
1393         memcpy(priv->stations[sta_id].keyinfo.key, keyconf->key,
1394                keyconf->keylen);
1395
1396         memcpy(priv->stations[sta_id].sta.key.key, keyconf->key,
1397                keyconf->keylen);
1398         priv->stations[sta_id].sta.key.key_flags = key_flags;
1399         priv->stations[sta_id].sta.sta.modify_mask = STA_MODIFY_KEY_MASK;
1400         priv->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
1401
1402         spin_unlock_irqrestore(&priv->sta_lock, flags);
1403
1404         IWL_DEBUG_INFO("hwcrypto: modify ucode station key info\n");
1405         iwl3945_send_add_station(priv, &priv->stations[sta_id].sta, 0);
1406         return 0;
1407 }
1408
1409 static int iwl3945_clear_sta_key_info(struct iwl3945_priv *priv, u8 sta_id)
1410 {
1411         unsigned long flags;
1412
1413         spin_lock_irqsave(&priv->sta_lock, flags);
1414         memset(&priv->stations[sta_id].keyinfo, 0, sizeof(struct iwl3945_hw_key));
1415         memset(&priv->stations[sta_id].sta.key, 0, sizeof(struct iwl3945_keyinfo));
1416         priv->stations[sta_id].sta.key.key_flags = STA_KEY_FLG_NO_ENC;
1417         priv->stations[sta_id].sta.sta.modify_mask = STA_MODIFY_KEY_MASK;
1418         priv->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
1419         spin_unlock_irqrestore(&priv->sta_lock, flags);
1420
1421         IWL_DEBUG_INFO("hwcrypto: clear ucode station key info\n");
1422         iwl3945_send_add_station(priv, &priv->stations[sta_id].sta, 0);
1423         return 0;
1424 }
1425
1426 static void iwl3945_clear_free_frames(struct iwl3945_priv *priv)
1427 {
1428         struct list_head *element;
1429
1430         IWL_DEBUG_INFO("%d frames on pre-allocated heap on clear.\n",
1431                        priv->frames_count);
1432
1433         while (!list_empty(&priv->free_frames)) {
1434                 element = priv->free_frames.next;
1435                 list_del(element);
1436                 kfree(list_entry(element, struct iwl3945_frame, list));
1437                 priv->frames_count--;
1438         }
1439
1440         if (priv->frames_count) {
1441                 IWL_WARNING("%d frames still in use.  Did we lose one?\n",
1442                             priv->frames_count);
1443                 priv->frames_count = 0;
1444         }
1445 }
1446
1447 static struct iwl3945_frame *iwl3945_get_free_frame(struct iwl3945_priv *priv)
1448 {
1449         struct iwl3945_frame *frame;
1450         struct list_head *element;
1451         if (list_empty(&priv->free_frames)) {
1452                 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1453                 if (!frame) {
1454                         IWL_ERROR("Could not allocate frame!\n");
1455                         return NULL;
1456                 }
1457
1458                 priv->frames_count++;
1459                 return frame;
1460         }
1461
1462         element = priv->free_frames.next;
1463         list_del(element);
1464         return list_entry(element, struct iwl3945_frame, list);
1465 }
1466
1467 static void iwl3945_free_frame(struct iwl3945_priv *priv, struct iwl3945_frame *frame)
1468 {
1469         memset(frame, 0, sizeof(*frame));
1470         list_add(&frame->list, &priv->free_frames);
1471 }
1472
1473 unsigned int iwl3945_fill_beacon_frame(struct iwl3945_priv *priv,
1474                                 struct ieee80211_hdr *hdr,
1475                                 const u8 *dest, int left)
1476 {
1477
1478         if (!iwl3945_is_associated(priv) || !priv->ibss_beacon ||
1479             ((priv->iw_mode != IEEE80211_IF_TYPE_IBSS) &&
1480              (priv->iw_mode != IEEE80211_IF_TYPE_AP)))
1481                 return 0;
1482
1483         if (priv->ibss_beacon->len > left)
1484                 return 0;
1485
1486         memcpy(hdr, priv->ibss_beacon->data, priv->ibss_beacon->len);
1487
1488         return priv->ibss_beacon->len;
1489 }
1490
1491 static u8 iwl3945_rate_get_lowest_plcp(int rate_mask)
1492 {
1493         u8 i;
1494
1495         for (i = IWL_RATE_1M_INDEX; i != IWL_RATE_INVALID;
1496              i = iwl3945_rates[i].next_ieee) {
1497                 if (rate_mask & (1 << i))
1498                         return iwl3945_rates[i].plcp;
1499         }
1500
1501         return IWL_RATE_INVALID;
1502 }
1503
1504 static int iwl3945_send_beacon_cmd(struct iwl3945_priv *priv)
1505 {
1506         struct iwl3945_frame *frame;
1507         unsigned int frame_size;
1508         int rc;
1509         u8 rate;
1510
1511         frame = iwl3945_get_free_frame(priv);
1512
1513         if (!frame) {
1514                 IWL_ERROR("Could not obtain free frame buffer for beacon "
1515                           "command.\n");
1516                 return -ENOMEM;
1517         }
1518
1519         if (!(priv->staging_rxon.flags & RXON_FLG_BAND_24G_MSK)) {
1520                 rate = iwl3945_rate_get_lowest_plcp(priv->active_rate_basic &
1521                                                 0xFF0);
1522                 if (rate == IWL_INVALID_RATE)
1523                         rate = IWL_RATE_6M_PLCP;
1524         } else {
1525                 rate = iwl3945_rate_get_lowest_plcp(priv->active_rate_basic & 0xF);
1526                 if (rate == IWL_INVALID_RATE)
1527                         rate = IWL_RATE_1M_PLCP;
1528         }
1529
1530         frame_size = iwl3945_hw_get_beacon_cmd(priv, frame, rate);
1531
1532         rc = iwl3945_send_cmd_pdu(priv, REPLY_TX_BEACON, frame_size,
1533                               &frame->u.cmd[0]);
1534
1535         iwl3945_free_frame(priv, frame);
1536
1537         return rc;
1538 }
1539
1540 /******************************************************************************
1541  *
1542  * EEPROM related functions
1543  *
1544  ******************************************************************************/
1545
1546 static void get_eeprom_mac(struct iwl3945_priv *priv, u8 *mac)
1547 {
1548         memcpy(mac, priv->eeprom.mac_address, 6);
1549 }
1550
1551 /*
1552  * Clear the OWNER_MSK, to establish driver (instead of uCode running on
1553  * embedded controller) as EEPROM reader; each read is a series of pulses
1554  * to/from the EEPROM chip, not a single event, so even reads could conflict
1555  * if they weren't arbitrated by some ownership mechanism.  Here, the driver
1556  * simply claims ownership, which should be safe when this function is called
1557  * (i.e. before loading uCode!).
1558  */
1559 static inline int iwl3945_eeprom_acquire_semaphore(struct iwl3945_priv *priv)
1560 {
1561         _iwl3945_clear_bit(priv, CSR_EEPROM_GP, CSR_EEPROM_GP_IF_OWNER_MSK);
1562         return 0;
1563 }
1564
1565 /**
1566  * iwl3945_eeprom_init - read EEPROM contents
1567  *
1568  * Load the EEPROM contents from adapter into priv->eeprom
1569  *
1570  * NOTE:  This routine uses the non-debug IO access functions.
1571  */
1572 int iwl3945_eeprom_init(struct iwl3945_priv *priv)
1573 {
1574         u16 *e = (u16 *)&priv->eeprom;
1575         u32 gp = iwl3945_read32(priv, CSR_EEPROM_GP);
1576         u32 r;
1577         int sz = sizeof(priv->eeprom);
1578         int rc;
1579         int i;
1580         u16 addr;
1581
1582         /* The EEPROM structure has several padding buffers within it
1583          * and when adding new EEPROM maps is subject to programmer errors
1584          * which may be very difficult to identify without explicitly
1585          * checking the resulting size of the eeprom map. */
1586         BUILD_BUG_ON(sizeof(priv->eeprom) != IWL_EEPROM_IMAGE_SIZE);
1587
1588         if ((gp & CSR_EEPROM_GP_VALID_MSK) == CSR_EEPROM_GP_BAD_SIGNATURE) {
1589                 IWL_ERROR("EEPROM not found, EEPROM_GP=0x%08x", gp);
1590                 return -ENOENT;
1591         }
1592
1593         /* Make sure driver (instead of uCode) is allowed to read EEPROM */
1594         rc = iwl3945_eeprom_acquire_semaphore(priv);
1595         if (rc < 0) {
1596                 IWL_ERROR("Failed to acquire EEPROM semaphore.\n");
1597                 return -ENOENT;
1598         }
1599
1600         /* eeprom is an array of 16bit values */
1601         for (addr = 0; addr < sz; addr += sizeof(u16)) {
1602                 _iwl3945_write32(priv, CSR_EEPROM_REG, addr << 1);
1603                 _iwl3945_clear_bit(priv, CSR_EEPROM_REG, CSR_EEPROM_REG_BIT_CMD);
1604
1605                 for (i = 0; i < IWL_EEPROM_ACCESS_TIMEOUT;
1606                                         i += IWL_EEPROM_ACCESS_DELAY) {
1607                         r = _iwl3945_read_direct32(priv, CSR_EEPROM_REG);
1608                         if (r & CSR_EEPROM_REG_READ_VALID_MSK)
1609                                 break;
1610                         udelay(IWL_EEPROM_ACCESS_DELAY);
1611                 }
1612
1613                 if (!(r & CSR_EEPROM_REG_READ_VALID_MSK)) {
1614                         IWL_ERROR("Time out reading EEPROM[%d]", addr);
1615                         return -ETIMEDOUT;
1616                 }
1617                 e[addr / 2] = le16_to_cpu((__force __le16)(r >> 16));
1618         }
1619
1620         return 0;
1621 }
1622
1623 static void iwl3945_unset_hw_setting(struct iwl3945_priv *priv)
1624 {
1625         if (priv->hw_setting.shared_virt)
1626                 pci_free_consistent(priv->pci_dev,
1627                                     sizeof(struct iwl3945_shared),
1628                                     priv->hw_setting.shared_virt,
1629                                     priv->hw_setting.shared_phys);
1630 }
1631
1632 /**
1633  * iwl3945_supported_rate_to_ie - fill in the supported rate in IE field
1634  *
1635  * return : set the bit for each supported rate insert in ie
1636  */
1637 static u16 iwl3945_supported_rate_to_ie(u8 *ie, u16 supported_rate,
1638                                     u16 basic_rate, int *left)
1639 {
1640         u16 ret_rates = 0, bit;
1641         int i;
1642         u8 *cnt = ie;
1643         u8 *rates = ie + 1;
1644
1645         for (bit = 1, i = 0; i < IWL_RATE_COUNT; i++, bit <<= 1) {
1646                 if (bit & supported_rate) {
1647                         ret_rates |= bit;
1648                         rates[*cnt] = iwl3945_rates[i].ieee |
1649                                 ((bit & basic_rate) ? 0x80 : 0x00);
1650                         (*cnt)++;
1651                         (*left)--;
1652                         if ((*left <= 0) ||
1653                             (*cnt >= IWL_SUPPORTED_RATES_IE_LEN))
1654                                 break;
1655                 }
1656         }
1657
1658         return ret_rates;
1659 }
1660
1661 /**
1662  * iwl3945_fill_probe_req - fill in all required fields and IE for probe request
1663  */
1664 static u16 iwl3945_fill_probe_req(struct iwl3945_priv *priv,
1665                               struct ieee80211_mgmt *frame,
1666                               int left, int is_direct)
1667 {
1668         int len = 0;
1669         u8 *pos = NULL;
1670         u16 active_rates, ret_rates, cck_rates;
1671
1672         /* Make sure there is enough space for the probe request,
1673          * two mandatory IEs and the data */
1674         left -= 24;
1675         if (left < 0)
1676                 return 0;
1677         len += 24;
1678
1679         frame->frame_control = cpu_to_le16(IEEE80211_STYPE_PROBE_REQ);
1680         memcpy(frame->da, iwl3945_broadcast_addr, ETH_ALEN);
1681         memcpy(frame->sa, priv->mac_addr, ETH_ALEN);
1682         memcpy(frame->bssid, iwl3945_broadcast_addr, ETH_ALEN);
1683         frame->seq_ctrl = 0;
1684
1685         /* fill in our indirect SSID IE */
1686         /* ...next IE... */
1687
1688         left -= 2;
1689         if (left < 0)
1690                 return 0;
1691         len += 2;
1692         pos = &(frame->u.probe_req.variable[0]);
1693         *pos++ = WLAN_EID_SSID;
1694         *pos++ = 0;
1695
1696         /* fill in our direct SSID IE... */
1697         if (is_direct) {
1698                 /* ...next IE... */
1699                 left -= 2 + priv->essid_len;
1700                 if (left < 0)
1701                         return 0;
1702                 /* ... fill it in... */
1703                 *pos++ = WLAN_EID_SSID;
1704                 *pos++ = priv->essid_len;
1705                 memcpy(pos, priv->essid, priv->essid_len);
1706                 pos += priv->essid_len;
1707                 len += 2 + priv->essid_len;
1708         }
1709
1710         /* fill in supported rate */
1711         /* ...next IE... */
1712         left -= 2;
1713         if (left < 0)
1714                 return 0;
1715
1716         /* ... fill it in... */
1717         *pos++ = WLAN_EID_SUPP_RATES;
1718         *pos = 0;
1719
1720         priv->active_rate = priv->rates_mask;
1721         active_rates = priv->active_rate;
1722         priv->active_rate_basic = priv->rates_mask & IWL_BASIC_RATES_MASK;
1723
1724         cck_rates = IWL_CCK_RATES_MASK & active_rates;
1725         ret_rates = iwl3945_supported_rate_to_ie(pos, cck_rates,
1726                         priv->active_rate_basic, &left);
1727         active_rates &= ~ret_rates;
1728
1729         ret_rates = iwl3945_supported_rate_to_ie(pos, active_rates,
1730                                  priv->active_rate_basic, &left);
1731         active_rates &= ~ret_rates;
1732
1733         len += 2 + *pos;
1734         pos += (*pos) + 1;
1735         if (active_rates == 0)
1736                 goto fill_end;
1737
1738         /* fill in supported extended rate */
1739         /* ...next IE... */
1740         left -= 2;
1741         if (left < 0)
1742                 return 0;
1743         /* ... fill it in... */
1744         *pos++ = WLAN_EID_EXT_SUPP_RATES;
1745         *pos = 0;
1746         iwl3945_supported_rate_to_ie(pos, active_rates,
1747                                  priv->active_rate_basic, &left);
1748         if (*pos > 0)
1749                 len += 2 + *pos;
1750
1751  fill_end:
1752         return (u16)len;
1753 }
1754
1755 /*
1756  * QoS  support
1757 */
1758 static int iwl3945_send_qos_params_command(struct iwl3945_priv *priv,
1759                                        struct iwl3945_qosparam_cmd *qos)
1760 {
1761
1762         return iwl3945_send_cmd_pdu(priv, REPLY_QOS_PARAM,
1763                                 sizeof(struct iwl3945_qosparam_cmd), qos);
1764 }
1765
1766 static void iwl3945_reset_qos(struct iwl3945_priv *priv)
1767 {
1768         u16 cw_min = 15;
1769         u16 cw_max = 1023;
1770         u8 aifs = 2;
1771         u8 is_legacy = 0;
1772         unsigned long flags;
1773         int i;
1774
1775         spin_lock_irqsave(&priv->lock, flags);
1776         priv->qos_data.qos_active = 0;
1777
1778         if (priv->iw_mode == IEEE80211_IF_TYPE_IBSS) {
1779                 if (priv->qos_data.qos_enable)
1780                         priv->qos_data.qos_active = 1;
1781                 if (!(priv->active_rate & 0xfff0)) {
1782                         cw_min = 31;
1783                         is_legacy = 1;
1784                 }
1785         } else if (priv->iw_mode == IEEE80211_IF_TYPE_AP) {
1786                 if (priv->qos_data.qos_enable)
1787                         priv->qos_data.qos_active = 1;
1788         } else if (!(priv->staging_rxon.flags & RXON_FLG_SHORT_SLOT_MSK)) {
1789                 cw_min = 31;
1790                 is_legacy = 1;
1791         }
1792
1793         if (priv->qos_data.qos_active)
1794                 aifs = 3;
1795
1796         priv->qos_data.def_qos_parm.ac[0].cw_min = cpu_to_le16(cw_min);
1797         priv->qos_data.def_qos_parm.ac[0].cw_max = cpu_to_le16(cw_max);
1798         priv->qos_data.def_qos_parm.ac[0].aifsn = aifs;
1799         priv->qos_data.def_qos_parm.ac[0].edca_txop = 0;
1800         priv->qos_data.def_qos_parm.ac[0].reserved1 = 0;
1801
1802         if (priv->qos_data.qos_active) {
1803                 i = 1;
1804                 priv->qos_data.def_qos_parm.ac[i].cw_min = cpu_to_le16(cw_min);
1805                 priv->qos_data.def_qos_parm.ac[i].cw_max = cpu_to_le16(cw_max);
1806                 priv->qos_data.def_qos_parm.ac[i].aifsn = 7;
1807                 priv->qos_data.def_qos_parm.ac[i].edca_txop = 0;
1808                 priv->qos_data.def_qos_parm.ac[i].reserved1 = 0;
1809
1810                 i = 2;
1811                 priv->qos_data.def_qos_parm.ac[i].cw_min =
1812                         cpu_to_le16((cw_min + 1) / 2 - 1);
1813                 priv->qos_data.def_qos_parm.ac[i].cw_max =
1814                         cpu_to_le16(cw_max);
1815                 priv->qos_data.def_qos_parm.ac[i].aifsn = 2;
1816                 if (is_legacy)
1817                         priv->qos_data.def_qos_parm.ac[i].edca_txop =
1818                                 cpu_to_le16(6016);
1819                 else
1820                         priv->qos_data.def_qos_parm.ac[i].edca_txop =
1821                                 cpu_to_le16(3008);
1822                 priv->qos_data.def_qos_parm.ac[i].reserved1 = 0;
1823
1824                 i = 3;
1825                 priv->qos_data.def_qos_parm.ac[i].cw_min =
1826                         cpu_to_le16((cw_min + 1) / 4 - 1);
1827                 priv->qos_data.def_qos_parm.ac[i].cw_max =
1828                         cpu_to_le16((cw_max + 1) / 2 - 1);
1829                 priv->qos_data.def_qos_parm.ac[i].aifsn = 2;
1830                 priv->qos_data.def_qos_parm.ac[i].reserved1 = 0;
1831                 if (is_legacy)
1832                         priv->qos_data.def_qos_parm.ac[i].edca_txop =
1833                                 cpu_to_le16(3264);
1834                 else
1835                         priv->qos_data.def_qos_parm.ac[i].edca_txop =
1836                                 cpu_to_le16(1504);
1837         } else {
1838                 for (i = 1; i < 4; i++) {
1839                         priv->qos_data.def_qos_parm.ac[i].cw_min =
1840                                 cpu_to_le16(cw_min);
1841                         priv->qos_data.def_qos_parm.ac[i].cw_max =
1842                                 cpu_to_le16(cw_max);
1843                         priv->qos_data.def_qos_parm.ac[i].aifsn = aifs;
1844                         priv->qos_data.def_qos_parm.ac[i].edca_txop = 0;
1845                         priv->qos_data.def_qos_parm.ac[i].reserved1 = 0;
1846                 }
1847         }
1848         IWL_DEBUG_QOS("set QoS to default \n");
1849
1850         spin_unlock_irqrestore(&priv->lock, flags);
1851 }
1852
1853 static void iwl3945_activate_qos(struct iwl3945_priv *priv, u8 force)
1854 {
1855         unsigned long flags;
1856
1857         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
1858                 return;
1859
1860         if (!priv->qos_data.qos_enable)
1861                 return;
1862
1863         spin_lock_irqsave(&priv->lock, flags);
1864         priv->qos_data.def_qos_parm.qos_flags = 0;
1865
1866         if (priv->qos_data.qos_cap.q_AP.queue_request &&
1867             !priv->qos_data.qos_cap.q_AP.txop_request)
1868                 priv->qos_data.def_qos_parm.qos_flags |=
1869                         QOS_PARAM_FLG_TXOP_TYPE_MSK;
1870
1871         if (priv->qos_data.qos_active)
1872                 priv->qos_data.def_qos_parm.qos_flags |=
1873                         QOS_PARAM_FLG_UPDATE_EDCA_MSK;
1874
1875         spin_unlock_irqrestore(&priv->lock, flags);
1876
1877         if (force || iwl3945_is_associated(priv)) {
1878                 IWL_DEBUG_QOS("send QoS cmd with Qos active %d \n",
1879                               priv->qos_data.qos_active);
1880
1881                 iwl3945_send_qos_params_command(priv,
1882                                 &(priv->qos_data.def_qos_parm));
1883         }
1884 }
1885
1886 /*
1887  * Power management (not Tx power!) functions
1888  */
1889 #define MSEC_TO_USEC 1024
1890
1891 #define NOSLP __constant_cpu_to_le32(0)
1892 #define SLP IWL_POWER_DRIVER_ALLOW_SLEEP_MSK
1893 #define SLP_TIMEOUT(T) __constant_cpu_to_le32((T) * MSEC_TO_USEC)
1894 #define SLP_VEC(X0, X1, X2, X3, X4) {__constant_cpu_to_le32(X0), \
1895                                      __constant_cpu_to_le32(X1), \
1896                                      __constant_cpu_to_le32(X2), \
1897                                      __constant_cpu_to_le32(X3), \
1898                                      __constant_cpu_to_le32(X4)}
1899
1900
1901 /* default power management (not Tx power) table values */
1902 /* for tim  0-10 */
1903 static struct iwl3945_power_vec_entry range_0[IWL_POWER_AC] = {
1904         {{NOSLP, SLP_TIMEOUT(0), SLP_TIMEOUT(0), SLP_VEC(0, 0, 0, 0, 0)}, 0},
1905         {{SLP, SLP_TIMEOUT(200), SLP_TIMEOUT(500), SLP_VEC(1, 2, 3, 4, 4)}, 0},
1906         {{SLP, SLP_TIMEOUT(200), SLP_TIMEOUT(300), SLP_VEC(2, 4, 6, 7, 7)}, 0},
1907         {{SLP, SLP_TIMEOUT(50), SLP_TIMEOUT(100), SLP_VEC(2, 6, 9, 9, 10)}, 0},
1908         {{SLP, SLP_TIMEOUT(50), SLP_TIMEOUT(25), SLP_VEC(2, 7, 9, 9, 10)}, 1},
1909         {{SLP, SLP_TIMEOUT(25), SLP_TIMEOUT(25), SLP_VEC(4, 7, 10, 10, 10)}, 1}
1910 };
1911
1912 /* for tim > 10 */
1913 static struct iwl3945_power_vec_entry range_1[IWL_POWER_AC] = {
1914         {{NOSLP, SLP_TIMEOUT(0), SLP_TIMEOUT(0), SLP_VEC(0, 0, 0, 0, 0)}, 0},
1915         {{SLP, SLP_TIMEOUT(200), SLP_TIMEOUT(500),
1916                  SLP_VEC(1, 2, 3, 4, 0xFF)}, 0},
1917         {{SLP, SLP_TIMEOUT(200), SLP_TIMEOUT(300),
1918                  SLP_VEC(2, 4, 6, 7, 0xFF)}, 0},
1919         {{SLP, SLP_TIMEOUT(50), SLP_TIMEOUT(100),
1920                  SLP_VEC(2, 6, 9, 9, 0xFF)}, 0},
1921         {{SLP, SLP_TIMEOUT(50), SLP_TIMEOUT(25), SLP_VEC(2, 7, 9, 9, 0xFF)}, 0},
1922         {{SLP, SLP_TIMEOUT(25), SLP_TIMEOUT(25),
1923                  SLP_VEC(4, 7, 10, 10, 0xFF)}, 0}
1924 };
1925
1926 int iwl3945_power_init_handle(struct iwl3945_priv *priv)
1927 {
1928         int rc = 0, i;
1929         struct iwl3945_power_mgr *pow_data;
1930         int size = sizeof(struct iwl3945_power_vec_entry) * IWL_POWER_AC;
1931         u16 pci_pm;
1932
1933         IWL_DEBUG_POWER("Initialize power \n");
1934
1935         pow_data = &(priv->power_data);
1936
1937         memset(pow_data, 0, sizeof(*pow_data));
1938
1939         pow_data->active_index = IWL_POWER_RANGE_0;
1940         pow_data->dtim_val = 0xffff;
1941
1942         memcpy(&pow_data->pwr_range_0[0], &range_0[0], size);
1943         memcpy(&pow_data->pwr_range_1[0], &range_1[0], size);
1944
1945         rc = pci_read_config_word(priv->pci_dev, PCI_LINK_CTRL, &pci_pm);
1946         if (rc != 0)
1947                 return 0;
1948         else {
1949                 struct iwl3945_powertable_cmd *cmd;
1950
1951                 IWL_DEBUG_POWER("adjust power command flags\n");
1952
1953                 for (i = 0; i < IWL_POWER_AC; i++) {
1954                         cmd = &pow_data->pwr_range_0[i].cmd;
1955
1956                         if (pci_pm & 0x1)
1957                                 cmd->flags &= ~IWL_POWER_PCI_PM_MSK;
1958                         else
1959                                 cmd->flags |= IWL_POWER_PCI_PM_MSK;
1960                 }
1961         }
1962         return rc;
1963 }
1964
1965 static int iwl3945_update_power_cmd(struct iwl3945_priv *priv,
1966                                 struct iwl3945_powertable_cmd *cmd, u32 mode)
1967 {
1968         int rc = 0, i;
1969         u8 skip;
1970         u32 max_sleep = 0;
1971         struct iwl3945_power_vec_entry *range;
1972         u8 period = 0;
1973         struct iwl3945_power_mgr *pow_data;
1974
1975         if (mode > IWL_POWER_INDEX_5) {
1976                 IWL_DEBUG_POWER("Error invalid power mode \n");
1977                 return -1;
1978         }
1979         pow_data = &(priv->power_data);
1980
1981         if (pow_data->active_index == IWL_POWER_RANGE_0)
1982                 range = &pow_data->pwr_range_0[0];
1983         else
1984                 range = &pow_data->pwr_range_1[1];
1985
1986         memcpy(cmd, &range[mode].cmd, sizeof(struct iwl3945_powertable_cmd));
1987
1988 #ifdef IWL_MAC80211_DISABLE
1989         if (priv->assoc_network != NULL) {
1990                 unsigned long flags;
1991
1992                 period = priv->assoc_network->tim.tim_period;
1993         }
1994 #endif  /*IWL_MAC80211_DISABLE */
1995         skip = range[mode].no_dtim;
1996
1997         if (period == 0) {
1998                 period = 1;
1999                 skip = 0;
2000         }
2001
2002         if (skip == 0) {
2003                 max_sleep = period;
2004                 cmd->flags &= ~IWL_POWER_SLEEP_OVER_DTIM_MSK;
2005         } else {
2006                 __le32 slp_itrvl = cmd->sleep_interval[IWL_POWER_VEC_SIZE - 1];
2007                 max_sleep = (le32_to_cpu(slp_itrvl) / period) * period;
2008                 cmd->flags |= IWL_POWER_SLEEP_OVER_DTIM_MSK;
2009         }
2010
2011         for (i = 0; i < IWL_POWER_VEC_SIZE; i++) {
2012                 if (le32_to_cpu(cmd->sleep_interval[i]) > max_sleep)
2013                         cmd->sleep_interval[i] = cpu_to_le32(max_sleep);
2014         }
2015
2016         IWL_DEBUG_POWER("Flags value = 0x%08X\n", cmd->flags);
2017         IWL_DEBUG_POWER("Tx timeout = %u\n", le32_to_cpu(cmd->tx_data_timeout));
2018         IWL_DEBUG_POWER("Rx timeout = %u\n", le32_to_cpu(cmd->rx_data_timeout));
2019         IWL_DEBUG_POWER("Sleep interval vector = { %d , %d , %d , %d , %d }\n",
2020                         le32_to_cpu(cmd->sleep_interval[0]),
2021                         le32_to_cpu(cmd->sleep_interval[1]),
2022                         le32_to_cpu(cmd->sleep_interval[2]),
2023                         le32_to_cpu(cmd->sleep_interval[3]),
2024                         le32_to_cpu(cmd->sleep_interval[4]));
2025
2026         return rc;
2027 }
2028
2029 static int iwl3945_send_power_mode(struct iwl3945_priv *priv, u32 mode)
2030 {
2031         u32 uninitialized_var(final_mode);
2032         int rc;
2033         struct iwl3945_powertable_cmd cmd;
2034
2035         /* If on battery, set to 3,
2036          * if plugged into AC power, set to CAM ("continuously aware mode"),
2037          * else user level */
2038         switch (mode) {
2039         case IWL_POWER_BATTERY:
2040                 final_mode = IWL_POWER_INDEX_3;
2041                 break;
2042         case IWL_POWER_AC:
2043                 final_mode = IWL_POWER_MODE_CAM;
2044                 break;
2045         default:
2046                 final_mode = mode;
2047                 break;
2048         }
2049
2050         iwl3945_update_power_cmd(priv, &cmd, final_mode);
2051
2052         rc = iwl3945_send_cmd_pdu(priv, POWER_TABLE_CMD, sizeof(cmd), &cmd);
2053
2054         if (final_mode == IWL_POWER_MODE_CAM)
2055                 clear_bit(STATUS_POWER_PMI, &priv->status);
2056         else
2057                 set_bit(STATUS_POWER_PMI, &priv->status);
2058
2059         return rc;
2060 }
2061
2062 int iwl3945_is_network_packet(struct iwl3945_priv *priv, struct ieee80211_hdr *header)
2063 {
2064         /* Filter incoming packets to determine if they are targeted toward
2065          * this network, discarding packets coming from ourselves */
2066         switch (priv->iw_mode) {
2067         case IEEE80211_IF_TYPE_IBSS: /* Header: Dest. | Source    | BSSID */
2068                 /* packets from our adapter are dropped (echo) */
2069                 if (!compare_ether_addr(header->addr2, priv->mac_addr))
2070                         return 0;
2071                 /* {broad,multi}cast packets to our IBSS go through */
2072                 if (is_multicast_ether_addr(header->addr1))
2073                         return !compare_ether_addr(header->addr3, priv->bssid);
2074                 /* packets to our adapter go through */
2075                 return !compare_ether_addr(header->addr1, priv->mac_addr);
2076         case IEEE80211_IF_TYPE_STA: /* Header: Dest. | AP{BSSID} | Source */
2077                 /* packets from our adapter are dropped (echo) */
2078                 if (!compare_ether_addr(header->addr3, priv->mac_addr))
2079                         return 0;
2080                 /* {broad,multi}cast packets to our BSS go through */
2081                 if (is_multicast_ether_addr(header->addr1))
2082                         return !compare_ether_addr(header->addr2, priv->bssid);
2083                 /* packets to our adapter go through */
2084                 return !compare_ether_addr(header->addr1, priv->mac_addr);
2085         }
2086
2087         return 1;
2088 }
2089
2090 #define TX_STATUS_ENTRY(x) case TX_STATUS_FAIL_ ## x: return #x
2091
2092 static const char *iwl3945_get_tx_fail_reason(u32 status)
2093 {
2094         switch (status & TX_STATUS_MSK) {
2095         case TX_STATUS_SUCCESS:
2096                 return "SUCCESS";
2097                 TX_STATUS_ENTRY(SHORT_LIMIT);
2098                 TX_STATUS_ENTRY(LONG_LIMIT);
2099                 TX_STATUS_ENTRY(FIFO_UNDERRUN);
2100                 TX_STATUS_ENTRY(MGMNT_ABORT);
2101                 TX_STATUS_ENTRY(NEXT_FRAG);
2102                 TX_STATUS_ENTRY(LIFE_EXPIRE);
2103                 TX_STATUS_ENTRY(DEST_PS);
2104                 TX_STATUS_ENTRY(ABORTED);
2105                 TX_STATUS_ENTRY(BT_RETRY);
2106                 TX_STATUS_ENTRY(STA_INVALID);
2107                 TX_STATUS_ENTRY(FRAG_DROPPED);
2108                 TX_STATUS_ENTRY(TID_DISABLE);
2109                 TX_STATUS_ENTRY(FRAME_FLUSHED);
2110                 TX_STATUS_ENTRY(INSUFFICIENT_CF_POLL);
2111                 TX_STATUS_ENTRY(TX_LOCKED);
2112                 TX_STATUS_ENTRY(NO_BEACON_ON_RADAR);
2113         }
2114
2115         return "UNKNOWN";
2116 }
2117
2118 /**
2119  * iwl3945_scan_cancel - Cancel any currently executing HW scan
2120  *
2121  * NOTE: priv->mutex is not required before calling this function
2122  */
2123 static int iwl3945_scan_cancel(struct iwl3945_priv *priv)
2124 {
2125         if (!test_bit(STATUS_SCAN_HW, &priv->status)) {
2126                 clear_bit(STATUS_SCANNING, &priv->status);
2127                 return 0;
2128         }
2129
2130         if (test_bit(STATUS_SCANNING, &priv->status)) {
2131                 if (!test_bit(STATUS_SCAN_ABORTING, &priv->status)) {
2132                         IWL_DEBUG_SCAN("Queuing scan abort.\n");
2133                         set_bit(STATUS_SCAN_ABORTING, &priv->status);
2134                         queue_work(priv->workqueue, &priv->abort_scan);
2135
2136                 } else
2137                         IWL_DEBUG_SCAN("Scan abort already in progress.\n");
2138
2139                 return test_bit(STATUS_SCANNING, &priv->status);
2140         }
2141
2142         return 0;
2143 }
2144
2145 /**
2146  * iwl3945_scan_cancel_timeout - Cancel any currently executing HW scan
2147  * @ms: amount of time to wait (in milliseconds) for scan to abort
2148  *
2149  * NOTE: priv->mutex must be held before calling this function
2150  */
2151 static int iwl3945_scan_cancel_timeout(struct iwl3945_priv *priv, unsigned long ms)
2152 {
2153         unsigned long now = jiffies;
2154         int ret;
2155
2156         ret = iwl3945_scan_cancel(priv);
2157         if (ret && ms) {
2158                 mutex_unlock(&priv->mutex);
2159                 while (!time_after(jiffies, now + msecs_to_jiffies(ms)) &&
2160                                 test_bit(STATUS_SCANNING, &priv->status))
2161                         msleep(1);
2162                 mutex_lock(&priv->mutex);
2163
2164                 return test_bit(STATUS_SCANNING, &priv->status);
2165         }
2166
2167         return ret;
2168 }
2169
2170 static void iwl3945_sequence_reset(struct iwl3945_priv *priv)
2171 {
2172         /* Reset ieee stats */
2173
2174         /* We don't reset the net_device_stats (ieee->stats) on
2175          * re-association */
2176
2177         priv->last_seq_num = -1;
2178         priv->last_frag_num = -1;
2179         priv->last_packet_time = 0;
2180
2181         iwl3945_scan_cancel(priv);
2182 }
2183
2184 #define MAX_UCODE_BEACON_INTERVAL       1024
2185 #define INTEL_CONN_LISTEN_INTERVAL      __constant_cpu_to_le16(0xA)
2186
2187 static __le16 iwl3945_adjust_beacon_interval(u16 beacon_val)
2188 {
2189         u16 new_val = 0;
2190         u16 beacon_factor = 0;
2191
2192         beacon_factor =
2193             (beacon_val + MAX_UCODE_BEACON_INTERVAL)
2194                 / MAX_UCODE_BEACON_INTERVAL;
2195         new_val = beacon_val / beacon_factor;
2196
2197         return cpu_to_le16(new_val);
2198 }
2199
2200 static void iwl3945_setup_rxon_timing(struct iwl3945_priv *priv)
2201 {
2202         u64 interval_tm_unit;
2203         u64 tsf, result;
2204         unsigned long flags;
2205         struct ieee80211_conf *conf = NULL;
2206         u16 beacon_int = 0;
2207
2208         conf = ieee80211_get_hw_conf(priv->hw);
2209
2210         spin_lock_irqsave(&priv->lock, flags);
2211         priv->rxon_timing.timestamp.dw[1] = cpu_to_le32(priv->timestamp1);
2212         priv->rxon_timing.timestamp.dw[0] = cpu_to_le32(priv->timestamp0);
2213
2214         priv->rxon_timing.listen_interval = INTEL_CONN_LISTEN_INTERVAL;
2215
2216         tsf = priv->timestamp1;
2217         tsf = ((tsf << 32) | priv->timestamp0);
2218
2219         beacon_int = priv->beacon_int;
2220         spin_unlock_irqrestore(&priv->lock, flags);
2221
2222         if (priv->iw_mode == IEEE80211_IF_TYPE_STA) {
2223                 if (beacon_int == 0) {
2224                         priv->rxon_timing.beacon_interval = cpu_to_le16(100);
2225                         priv->rxon_timing.beacon_init_val = cpu_to_le32(102400);
2226                 } else {
2227                         priv->rxon_timing.beacon_interval =
2228                                 cpu_to_le16(beacon_int);
2229                         priv->rxon_timing.beacon_interval =
2230                             iwl3945_adjust_beacon_interval(
2231                                 le16_to_cpu(priv->rxon_timing.beacon_interval));
2232                 }
2233
2234                 priv->rxon_timing.atim_window = 0;
2235         } else {
2236                 priv->rxon_timing.beacon_interval =
2237                         iwl3945_adjust_beacon_interval(conf->beacon_int);
2238                 /* TODO: we need to get atim_window from upper stack
2239                  * for now we set to 0 */
2240                 priv->rxon_timing.atim_window = 0;
2241         }
2242
2243         interval_tm_unit =
2244                 (le16_to_cpu(priv->rxon_timing.beacon_interval) * 1024);
2245         result = do_div(tsf, interval_tm_unit);
2246         priv->rxon_timing.beacon_init_val =
2247             cpu_to_le32((u32) ((u64) interval_tm_unit - result));
2248
2249         IWL_DEBUG_ASSOC
2250             ("beacon interval %d beacon timer %d beacon tim %d\n",
2251                 le16_to_cpu(priv->rxon_timing.beacon_interval),
2252                 le32_to_cpu(priv->rxon_timing.beacon_init_val),
2253                 le16_to_cpu(priv->rxon_timing.atim_window));
2254 }
2255
2256 static int iwl3945_scan_initiate(struct iwl3945_priv *priv)
2257 {
2258         if (priv->iw_mode == IEEE80211_IF_TYPE_AP) {
2259                 IWL_ERROR("APs don't scan.\n");
2260                 return 0;
2261         }
2262
2263         if (!iwl3945_is_ready_rf(priv)) {
2264                 IWL_DEBUG_SCAN("Aborting scan due to not ready.\n");
2265                 return -EIO;
2266         }
2267
2268         if (test_bit(STATUS_SCANNING, &priv->status)) {
2269                 IWL_DEBUG_SCAN("Scan already in progress.\n");
2270                 return -EAGAIN;
2271         }
2272
2273         if (test_bit(STATUS_SCAN_ABORTING, &priv->status)) {
2274                 IWL_DEBUG_SCAN("Scan request while abort pending.  "
2275                                "Queuing.\n");
2276                 return -EAGAIN;
2277         }
2278
2279         IWL_DEBUG_INFO("Starting scan...\n");
2280         priv->scan_bands = 2;
2281         set_bit(STATUS_SCANNING, &priv->status);
2282         priv->scan_start = jiffies;
2283         priv->scan_pass_start = priv->scan_start;
2284
2285         queue_work(priv->workqueue, &priv->request_scan);
2286
2287         return 0;
2288 }
2289
2290 static int iwl3945_set_rxon_hwcrypto(struct iwl3945_priv *priv, int hw_decrypt)
2291 {
2292         struct iwl3945_rxon_cmd *rxon = &priv->staging_rxon;
2293
2294         if (hw_decrypt)
2295                 rxon->filter_flags &= ~RXON_FILTER_DIS_DECRYPT_MSK;
2296         else
2297                 rxon->filter_flags |= RXON_FILTER_DIS_DECRYPT_MSK;
2298
2299         return 0;
2300 }
2301
2302 static void iwl3945_set_flags_for_phymode(struct iwl3945_priv *priv,
2303                                           enum ieee80211_band band)
2304 {
2305         if (band == IEEE80211_BAND_5GHZ) {
2306                 priv->staging_rxon.flags &=
2307                     ~(RXON_FLG_BAND_24G_MSK | RXON_FLG_AUTO_DETECT_MSK
2308                       | RXON_FLG_CCK_MSK);
2309                 priv->staging_rxon.flags |= RXON_FLG_SHORT_SLOT_MSK;
2310         } else {
2311                 /* Copied from iwl3945_bg_post_associate() */
2312                 if (priv->assoc_capability & WLAN_CAPABILITY_SHORT_SLOT_TIME)
2313                         priv->staging_rxon.flags |= RXON_FLG_SHORT_SLOT_MSK;
2314                 else
2315                         priv->staging_rxon.flags &= ~RXON_FLG_SHORT_SLOT_MSK;
2316
2317                 if (priv->iw_mode == IEEE80211_IF_TYPE_IBSS)
2318                         priv->staging_rxon.flags &= ~RXON_FLG_SHORT_SLOT_MSK;
2319
2320                 priv->staging_rxon.flags |= RXON_FLG_BAND_24G_MSK;
2321                 priv->staging_rxon.flags |= RXON_FLG_AUTO_DETECT_MSK;
2322                 priv->staging_rxon.flags &= ~RXON_FLG_CCK_MSK;
2323         }
2324 }
2325
2326 /*
2327  * initialize rxon structure with default values from eeprom
2328  */
2329 static void iwl3945_connection_init_rx_config(struct iwl3945_priv *priv)
2330 {
2331         const struct iwl3945_channel_info *ch_info;
2332
2333         memset(&priv->staging_rxon, 0, sizeof(priv->staging_rxon));
2334
2335         switch (priv->iw_mode) {
2336         case IEEE80211_IF_TYPE_AP:
2337                 priv->staging_rxon.dev_type = RXON_DEV_TYPE_AP;
2338                 break;
2339
2340         case IEEE80211_IF_TYPE_STA:
2341                 priv->staging_rxon.dev_type = RXON_DEV_TYPE_ESS;
2342                 priv->staging_rxon.filter_flags = RXON_FILTER_ACCEPT_GRP_MSK;
2343                 break;
2344
2345         case IEEE80211_IF_TYPE_IBSS:
2346                 priv->staging_rxon.dev_type = RXON_DEV_TYPE_IBSS;
2347                 priv->staging_rxon.flags = RXON_FLG_SHORT_PREAMBLE_MSK;
2348                 priv->staging_rxon.filter_flags = RXON_FILTER_BCON_AWARE_MSK |
2349                                                   RXON_FILTER_ACCEPT_GRP_MSK;
2350                 break;
2351
2352         case IEEE80211_IF_TYPE_MNTR:
2353                 priv->staging_rxon.dev_type = RXON_DEV_TYPE_SNIFFER;
2354                 priv->staging_rxon.filter_flags = RXON_FILTER_PROMISC_MSK |
2355                     RXON_FILTER_CTL2HOST_MSK | RXON_FILTER_ACCEPT_GRP_MSK;
2356                 break;
2357         }
2358
2359 #if 0
2360         /* TODO:  Figure out when short_preamble would be set and cache from
2361          * that */
2362         if (!hw_to_local(priv->hw)->short_preamble)
2363                 priv->staging_rxon.flags &= ~RXON_FLG_SHORT_PREAMBLE_MSK;
2364         else
2365                 priv->staging_rxon.flags |= RXON_FLG_SHORT_PREAMBLE_MSK;
2366 #endif
2367
2368         ch_info = iwl3945_get_channel_info(priv, priv->band,
2369                                        le16_to_cpu(priv->staging_rxon.channel));
2370
2371         if (!ch_info)
2372                 ch_info = &priv->channel_info[0];
2373
2374         /*
2375          * in some case A channels are all non IBSS
2376          * in this case force B/G channel
2377          */
2378         if ((priv->iw_mode == IEEE80211_IF_TYPE_IBSS) &&
2379             !(is_channel_ibss(ch_info)))
2380                 ch_info = &priv->channel_info[0];
2381
2382         priv->staging_rxon.channel = cpu_to_le16(ch_info->channel);
2383         if (is_channel_a_band(ch_info))
2384                 priv->band = IEEE80211_BAND_5GHZ;
2385         else
2386                 priv->band = IEEE80211_BAND_2GHZ;
2387
2388         iwl3945_set_flags_for_phymode(priv, priv->band);
2389
2390         priv->staging_rxon.ofdm_basic_rates =
2391             (IWL_OFDM_RATES_MASK >> IWL_FIRST_OFDM_RATE) & 0xFF;
2392         priv->staging_rxon.cck_basic_rates =
2393             (IWL_CCK_RATES_MASK >> IWL_FIRST_CCK_RATE) & 0xF;
2394 }
2395
2396 static int iwl3945_set_mode(struct iwl3945_priv *priv, int mode)
2397 {
2398         if (mode == IEEE80211_IF_TYPE_IBSS) {
2399                 const struct iwl3945_channel_info *ch_info;
2400
2401                 ch_info = iwl3945_get_channel_info(priv,
2402                         priv->band,
2403                         le16_to_cpu(priv->staging_rxon.channel));
2404
2405                 if (!ch_info || !is_channel_ibss(ch_info)) {
2406                         IWL_ERROR("channel %d not IBSS channel\n",
2407                                   le16_to_cpu(priv->staging_rxon.channel));
2408                         return -EINVAL;
2409                 }
2410         }
2411
2412         priv->iw_mode = mode;
2413
2414         iwl3945_connection_init_rx_config(priv);
2415         memcpy(priv->staging_rxon.node_addr, priv->mac_addr, ETH_ALEN);
2416
2417         iwl3945_clear_stations_table(priv);
2418
2419         /* dont commit rxon if rf-kill is on*/
2420         if (!iwl3945_is_ready_rf(priv))
2421                 return -EAGAIN;
2422
2423         cancel_delayed_work(&priv->scan_check);
2424         if (iwl3945_scan_cancel_timeout(priv, 100)) {
2425                 IWL_WARNING("Aborted scan still in progress after 100ms\n");
2426                 IWL_DEBUG_MAC80211("leaving - scan abort failed.\n");
2427                 return -EAGAIN;
2428         }
2429
2430         iwl3945_commit_rxon(priv);
2431
2432         return 0;
2433 }
2434
2435 static void iwl3945_build_tx_cmd_hwcrypto(struct iwl3945_priv *priv,
2436                                       struct ieee80211_tx_control *ctl,
2437                                       struct iwl3945_cmd *cmd,
2438                                       struct sk_buff *skb_frag,
2439                                       int last_frag)
2440 {
2441         struct iwl3945_hw_key *keyinfo = &priv->stations[ctl->key_idx].keyinfo;
2442
2443         switch (keyinfo->alg) {
2444         case ALG_CCMP:
2445                 cmd->cmd.tx.sec_ctl = TX_CMD_SEC_CCM;
2446                 memcpy(cmd->cmd.tx.key, keyinfo->key, keyinfo->keylen);
2447                 IWL_DEBUG_TX("tx_cmd with aes hwcrypto\n");
2448                 break;
2449
2450         case ALG_TKIP:
2451 #if 0
2452                 cmd->cmd.tx.sec_ctl = TX_CMD_SEC_TKIP;
2453
2454                 if (last_frag)
2455                         memcpy(cmd->cmd.tx.tkip_mic.byte, skb_frag->tail - 8,
2456                                8);
2457                 else
2458                         memset(cmd->cmd.tx.tkip_mic.byte, 0, 8);
2459 #endif
2460                 break;
2461
2462         case ALG_WEP:
2463                 cmd->cmd.tx.sec_ctl = TX_CMD_SEC_WEP |
2464                     (ctl->key_idx & TX_CMD_SEC_MSK) << TX_CMD_SEC_SHIFT;
2465
2466                 if (keyinfo->keylen == 13)
2467                         cmd->cmd.tx.sec_ctl |= TX_CMD_SEC_KEY128;
2468
2469                 memcpy(&cmd->cmd.tx.key[3], keyinfo->key, keyinfo->keylen);
2470
2471                 IWL_DEBUG_TX("Configuring packet for WEP encryption "
2472                              "with key %d\n", ctl->key_idx);
2473                 break;
2474
2475         default:
2476                 printk(KERN_ERR "Unknown encode alg %d\n", keyinfo->alg);
2477                 break;
2478         }
2479 }
2480
2481 /*
2482  * handle build REPLY_TX command notification.
2483  */
2484 static void iwl3945_build_tx_cmd_basic(struct iwl3945_priv *priv,
2485                                   struct iwl3945_cmd *cmd,
2486                                   struct ieee80211_tx_control *ctrl,
2487                                   struct ieee80211_hdr *hdr,
2488                                   int is_unicast, u8 std_id)
2489 {
2490         __le16 *qc;
2491         u16 fc = le16_to_cpu(hdr->frame_control);
2492         __le32 tx_flags = cmd->cmd.tx.tx_flags;
2493
2494         cmd->cmd.tx.stop_time.life_time = TX_CMD_LIFE_TIME_INFINITE;
2495         if (!(ctrl->flags & IEEE80211_TXCTL_NO_ACK)) {
2496                 tx_flags |= TX_CMD_FLG_ACK_MSK;
2497                 if ((fc & IEEE80211_FCTL_FTYPE) == IEEE80211_FTYPE_MGMT)
2498                         tx_flags |= TX_CMD_FLG_SEQ_CTL_MSK;
2499                 if (ieee80211_is_probe_response(fc) &&
2500                     !(le16_to_cpu(hdr->seq_ctrl) & 0xf))
2501                         tx_flags |= TX_CMD_FLG_TSF_MSK;
2502         } else {
2503                 tx_flags &= (~TX_CMD_FLG_ACK_MSK);
2504                 tx_flags |= TX_CMD_FLG_SEQ_CTL_MSK;
2505         }
2506
2507         cmd->cmd.tx.sta_id = std_id;
2508         if (ieee80211_get_morefrag(hdr))
2509                 tx_flags |= TX_CMD_FLG_MORE_FRAG_MSK;
2510
2511         qc = ieee80211_get_qos_ctrl(hdr);
2512         if (qc) {
2513                 cmd->cmd.tx.tid_tspec = (u8) (le16_to_cpu(*qc) & 0xf);
2514                 tx_flags &= ~TX_CMD_FLG_SEQ_CTL_MSK;
2515         } else
2516                 tx_flags |= TX_CMD_FLG_SEQ_CTL_MSK;
2517
2518         if (ctrl->flags & IEEE80211_TXCTL_USE_RTS_CTS) {
2519                 tx_flags |= TX_CMD_FLG_RTS_MSK;
2520                 tx_flags &= ~TX_CMD_FLG_CTS_MSK;
2521         } else if (ctrl->flags & IEEE80211_TXCTL_USE_CTS_PROTECT) {
2522                 tx_flags &= ~TX_CMD_FLG_RTS_MSK;
2523                 tx_flags |= TX_CMD_FLG_CTS_MSK;
2524         }
2525
2526         if ((tx_flags & TX_CMD_FLG_RTS_MSK) || (tx_flags & TX_CMD_FLG_CTS_MSK))
2527                 tx_flags |= TX_CMD_FLG_FULL_TXOP_PROT_MSK;
2528
2529         tx_flags &= ~(TX_CMD_FLG_ANT_SEL_MSK);
2530         if ((fc & IEEE80211_FCTL_FTYPE) == IEEE80211_FTYPE_MGMT) {
2531                 if ((fc & IEEE80211_FCTL_STYPE) == IEEE80211_STYPE_ASSOC_REQ ||
2532                     (fc & IEEE80211_FCTL_STYPE) == IEEE80211_STYPE_REASSOC_REQ)
2533                         cmd->cmd.tx.timeout.pm_frame_timeout = cpu_to_le16(3);
2534                 else
2535                         cmd->cmd.tx.timeout.pm_frame_timeout = cpu_to_le16(2);
2536         } else
2537                 cmd->cmd.tx.timeout.pm_frame_timeout = 0;
2538
2539         cmd->cmd.tx.driver_txop = 0;
2540         cmd->cmd.tx.tx_flags = tx_flags;
2541         cmd->cmd.tx.next_frame_len = 0;
2542 }
2543
2544 /**
2545  * iwl3945_get_sta_id - Find station's index within station table
2546  */
2547 static int iwl3945_get_sta_id(struct iwl3945_priv *priv, struct ieee80211_hdr *hdr)
2548 {
2549         int sta_id;
2550         u16 fc = le16_to_cpu(hdr->frame_control);
2551
2552         /* If this frame is broadcast or management, use broadcast station id */
2553         if (((fc & IEEE80211_FCTL_FTYPE) != IEEE80211_FTYPE_DATA) ||
2554             is_multicast_ether_addr(hdr->addr1))
2555                 return priv->hw_setting.bcast_sta_id;
2556
2557         switch (priv->iw_mode) {
2558
2559         /* If we are a client station in a BSS network, use the special
2560          * AP station entry (that's the only station we communicate with) */
2561         case IEEE80211_IF_TYPE_STA:
2562                 return IWL_AP_ID;
2563
2564         /* If we are an AP, then find the station, or use BCAST */
2565         case IEEE80211_IF_TYPE_AP:
2566                 sta_id = iwl3945_hw_find_station(priv, hdr->addr1);
2567                 if (sta_id != IWL_INVALID_STATION)
2568                         return sta_id;
2569                 return priv->hw_setting.bcast_sta_id;
2570
2571         /* If this frame is going out to an IBSS network, find the station,
2572          * or create a new station table entry */
2573         case IEEE80211_IF_TYPE_IBSS: {
2574                 DECLARE_MAC_BUF(mac);
2575
2576                 /* Create new station table entry */
2577                 sta_id = iwl3945_hw_find_station(priv, hdr->addr1);
2578                 if (sta_id != IWL_INVALID_STATION)
2579                         return sta_id;
2580
2581                 sta_id = iwl3945_add_station(priv, hdr->addr1, 0, CMD_ASYNC);
2582
2583                 if (sta_id != IWL_INVALID_STATION)
2584                         return sta_id;
2585
2586                 IWL_DEBUG_DROP("Station %s not in station map. "
2587                                "Defaulting to broadcast...\n",
2588                                print_mac(mac, hdr->addr1));
2589                 iwl3945_print_hex_dump(IWL_DL_DROP, (u8 *) hdr, sizeof(*hdr));
2590                 return priv->hw_setting.bcast_sta_id;
2591         }
2592         default:
2593                 IWL_WARNING("Unknown mode of operation: %d", priv->iw_mode);
2594                 return priv->hw_setting.bcast_sta_id;
2595         }
2596 }
2597
2598 /*
2599  * start REPLY_TX command process
2600  */
2601 static int iwl3945_tx_skb(struct iwl3945_priv *priv,
2602                       struct sk_buff *skb, struct ieee80211_tx_control *ctl)
2603 {
2604         struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
2605         struct iwl3945_tfd_frame *tfd;
2606         u32 *control_flags;
2607         int txq_id = ctl->queue;
2608         struct iwl3945_tx_queue *txq = NULL;
2609         struct iwl3945_queue *q = NULL;
2610         dma_addr_t phys_addr;
2611         dma_addr_t txcmd_phys;
2612         struct iwl3945_cmd *out_cmd = NULL;
2613         u16 len, idx, len_org;
2614         u8 id, hdr_len, unicast;
2615         u8 sta_id;
2616         u16 seq_number = 0;
2617         u16 fc;
2618         __le16 *qc;
2619         u8 wait_write_ptr = 0;
2620         unsigned long flags;
2621         int rc;
2622
2623         spin_lock_irqsave(&priv->lock, flags);
2624         if (iwl3945_is_rfkill(priv)) {
2625                 IWL_DEBUG_DROP("Dropping - RF KILL\n");
2626                 goto drop_unlock;
2627         }
2628
2629         if (!priv->vif) {
2630                 IWL_DEBUG_DROP("Dropping - !priv->vif\n");
2631                 goto drop_unlock;
2632         }
2633
2634         if ((ctl->tx_rate->hw_value & 0xFF) == IWL_INVALID_RATE) {
2635                 IWL_ERROR("ERROR: No TX rate available.\n");
2636                 goto drop_unlock;
2637         }
2638
2639         unicast = !is_multicast_ether_addr(hdr->addr1);
2640         id = 0;
2641
2642         fc = le16_to_cpu(hdr->frame_control);
2643
2644 #ifdef CONFIG_IWL3945_DEBUG
2645         if (ieee80211_is_auth(fc))
2646                 IWL_DEBUG_TX("Sending AUTH frame\n");
2647         else if (ieee80211_is_assoc_request(fc))
2648                 IWL_DEBUG_TX("Sending ASSOC frame\n");
2649         else if (ieee80211_is_reassoc_request(fc))
2650                 IWL_DEBUG_TX("Sending REASSOC frame\n");
2651 #endif
2652
2653         /* drop all data frame if we are not associated */
2654         if ((!iwl3945_is_associated(priv) ||
2655              ((priv->iw_mode == IEEE80211_IF_TYPE_STA) && !priv->assoc_id)) &&
2656             ((fc & IEEE80211_FCTL_FTYPE) == IEEE80211_FTYPE_DATA)) {
2657                 IWL_DEBUG_DROP("Dropping - !iwl3945_is_associated\n");
2658                 goto drop_unlock;
2659         }
2660
2661         spin_unlock_irqrestore(&priv->lock, flags);
2662
2663         hdr_len = ieee80211_get_hdrlen(fc);
2664
2665         /* Find (or create) index into station table for destination station */
2666         sta_id = iwl3945_get_sta_id(priv, hdr);
2667         if (sta_id == IWL_INVALID_STATION) {
2668                 DECLARE_MAC_BUF(mac);
2669
2670                 IWL_DEBUG_DROP("Dropping - INVALID STATION: %s\n",
2671                                print_mac(mac, hdr->addr1));
2672                 goto drop;
2673         }
2674
2675         IWL_DEBUG_RATE("station Id %d\n", sta_id);
2676
2677         qc = ieee80211_get_qos_ctrl(hdr);
2678         if (qc) {
2679                 u8 tid = (u8)(le16_to_cpu(*qc) & 0xf);
2680                 seq_number = priv->stations[sta_id].tid[tid].seq_number &
2681                                 IEEE80211_SCTL_SEQ;
2682                 hdr->seq_ctrl = cpu_to_le16(seq_number) |
2683                         (hdr->seq_ctrl &
2684                                 __constant_cpu_to_le16(IEEE80211_SCTL_FRAG));
2685                 seq_number += 0x10;
2686         }
2687
2688         /* Descriptor for chosen Tx queue */
2689         txq = &priv->txq[txq_id];
2690         q = &txq->q;
2691
2692         spin_lock_irqsave(&priv->lock, flags);
2693
2694         /* Set up first empty TFD within this queue's circular TFD buffer */
2695         tfd = &txq->bd[q->write_ptr];
2696         memset(tfd, 0, sizeof(*tfd));
2697         control_flags = (u32 *) tfd;
2698         idx = get_cmd_index(q, q->write_ptr, 0);
2699
2700         /* Set up driver data for this TFD */
2701         memset(&(txq->txb[q->write_ptr]), 0, sizeof(struct iwl3945_tx_info));
2702         txq->txb[q->write_ptr].skb[0] = skb;
2703         memcpy(&(txq->txb[q->write_ptr].status.control),
2704                ctl, sizeof(struct ieee80211_tx_control));
2705
2706         /* Init first empty entry in queue's array of Tx/cmd buffers */
2707         out_cmd = &txq->cmd[idx];
2708         memset(&out_cmd->hdr, 0, sizeof(out_cmd->hdr));
2709         memset(&out_cmd->cmd.tx, 0, sizeof(out_cmd->cmd.tx));
2710
2711         /*
2712          * Set up the Tx-command (not MAC!) header.
2713          * Store the chosen Tx queue and TFD index within the sequence field;
2714          * after Tx, uCode's Tx response will return this value so driver can
2715          * locate the frame within the tx queue and do post-tx processing.
2716          */
2717         out_cmd->hdr.cmd = REPLY_TX;
2718         out_cmd->hdr.sequence = cpu_to_le16((u16)(QUEUE_TO_SEQ(txq_id) |
2719                                 INDEX_TO_SEQ(q->write_ptr)));
2720
2721         /* Copy MAC header from skb into command buffer */
2722         memcpy(out_cmd->cmd.tx.hdr, hdr, hdr_len);
2723
2724         /*
2725          * Use the first empty entry in this queue's command buffer array
2726          * to contain the Tx command and MAC header concatenated together
2727          * (payload data will be in another buffer).
2728          * Size of this varies, due to varying MAC header length.
2729          * If end is not dword aligned, we'll have 2 extra bytes at the end
2730          * of the MAC header (device reads on dword boundaries).
2731          * We'll tell device about this padding later.
2732          */
2733         len = priv->hw_setting.tx_cmd_len +
2734                 sizeof(struct iwl3945_cmd_header) + hdr_len;
2735
2736         len_org = len;
2737         len = (len + 3) & ~3;
2738
2739         if (len_org != len)
2740                 len_org = 1;
2741         else
2742                 len_org = 0;
2743
2744         /* Physical address of this Tx command's header (not MAC header!),
2745          * within command buffer array. */
2746         txcmd_phys = txq->dma_addr_cmd + sizeof(struct iwl3945_cmd) * idx +
2747                      offsetof(struct iwl3945_cmd, hdr);
2748
2749         /* Add buffer containing Tx command and MAC(!) header to TFD's
2750          * first entry */
2751         iwl3945_hw_txq_attach_buf_to_tfd(priv, tfd, txcmd_phys, len);
2752
2753         if (!(ctl->flags & IEEE80211_TXCTL_DO_NOT_ENCRYPT))
2754                 iwl3945_build_tx_cmd_hwcrypto(priv, ctl, out_cmd, skb, 0);
2755
2756         /* Set up TFD's 2nd entry to point directly to remainder of skb,
2757          * if any (802.11 null frames have no payload). */
2758         len = skb->len - hdr_len;
2759         if (len) {
2760                 phys_addr = pci_map_single(priv->pci_dev, skb->data + hdr_len,
2761                                            len, PCI_DMA_TODEVICE);
2762                 iwl3945_hw_txq_attach_buf_to_tfd(priv, tfd, phys_addr, len);
2763         }
2764
2765         if (!len)
2766                 /* If there is no payload, then we use only one Tx buffer */
2767                 *control_flags = TFD_CTL_COUNT_SET(1);
2768         else
2769                 /* Else use 2 buffers.
2770                  * Tell 3945 about any padding after MAC header */
2771                 *control_flags = TFD_CTL_COUNT_SET(2) |
2772                         TFD_CTL_PAD_SET(U32_PAD(len));
2773
2774         /* Total # bytes to be transmitted */
2775         len = (u16)skb->len;
2776         out_cmd->cmd.tx.len = cpu_to_le16(len);
2777
2778         /* TODO need this for burst mode later on */
2779         iwl3945_build_tx_cmd_basic(priv, out_cmd, ctl, hdr, unicast, sta_id);
2780
2781         /* set is_hcca to 0; it probably will never be implemented */
2782         iwl3945_hw_build_tx_cmd_rate(priv, out_cmd, ctl, hdr, sta_id, 0);
2783
2784         out_cmd->cmd.tx.tx_flags &= ~TX_CMD_FLG_ANT_A_MSK;
2785         out_cmd->cmd.tx.tx_flags &= ~TX_CMD_FLG_ANT_B_MSK;
2786
2787         if (!ieee80211_get_morefrag(hdr)) {
2788                 txq->need_update = 1;
2789                 if (qc) {
2790                         u8 tid = (u8)(le16_to_cpu(*qc) & 0xf);
2791                         priv->stations[sta_id].tid[tid].seq_number = seq_number;
2792                 }
2793         } else {
2794                 wait_write_ptr = 1;
2795                 txq->need_update = 0;
2796         }
2797
2798         iwl3945_print_hex_dump(IWL_DL_TX, out_cmd->cmd.payload,
2799                            sizeof(out_cmd->cmd.tx));
2800
2801         iwl3945_print_hex_dump(IWL_DL_TX, (u8 *)out_cmd->cmd.tx.hdr,
2802                            ieee80211_get_hdrlen(fc));
2803
2804         /* Tell device the write index *just past* this latest filled TFD */
2805         q->write_ptr = iwl3945_queue_inc_wrap(q->write_ptr, q->n_bd);
2806         rc = iwl3945_tx_queue_update_write_ptr(priv, txq);
2807         spin_unlock_irqrestore(&priv->lock, flags);
2808
2809         if (rc)
2810                 return rc;
2811
2812         if ((iwl3945_queue_space(q) < q->high_mark)
2813             && priv->mac80211_registered) {
2814                 if (wait_write_ptr) {
2815                         spin_lock_irqsave(&priv->lock, flags);
2816                         txq->need_update = 1;
2817                         iwl3945_tx_queue_update_write_ptr(priv, txq);
2818                         spin_unlock_irqrestore(&priv->lock, flags);
2819                 }
2820
2821                 ieee80211_stop_queue(priv->hw, ctl->queue);
2822         }
2823
2824         return 0;
2825
2826 drop_unlock:
2827         spin_unlock_irqrestore(&priv->lock, flags);
2828 drop:
2829         return -1;
2830 }
2831
2832 static void iwl3945_set_rate(struct iwl3945_priv *priv)
2833 {
2834         const struct ieee80211_supported_band *sband = NULL;
2835         struct ieee80211_rate *rate;
2836         int i;
2837
2838         sband = iwl3945_get_band(priv, priv->band);
2839         if (!sband) {
2840                 IWL_ERROR("Failed to set rate: unable to get hw mode\n");
2841                 return;
2842         }
2843
2844         priv->active_rate = 0;
2845         priv->active_rate_basic = 0;
2846
2847         IWL_DEBUG_RATE("Setting rates for %s GHz\n",
2848                        sband->band == IEEE80211_BAND_2GHZ ? "2.4" : "5");
2849
2850         for (i = 0; i < sband->n_bitrates; i++) {
2851                 rate = &sband->bitrates[i];
2852                 if ((rate->hw_value < IWL_RATE_COUNT) &&
2853                     !(rate->flags & IEEE80211_CHAN_DISABLED)) {
2854                         IWL_DEBUG_RATE("Adding rate index %d (plcp %d)\n",
2855                                        rate->hw_value, iwl3945_rates[rate->hw_value].plcp);
2856                         priv->active_rate |= (1 << rate->hw_value);
2857                 }
2858         }
2859
2860         IWL_DEBUG_RATE("Set active_rate = %0x, active_rate_basic = %0x\n",
2861                        priv->active_rate, priv->active_rate_basic);
2862
2863         /*
2864          * If a basic rate is configured, then use it (adding IWL_RATE_1M_MASK)
2865          * otherwise set it to the default of all CCK rates and 6, 12, 24 for
2866          * OFDM
2867          */
2868         if (priv->active_rate_basic & IWL_CCK_BASIC_RATES_MASK)
2869                 priv->staging_rxon.cck_basic_rates =
2870                     ((priv->active_rate_basic &
2871                       IWL_CCK_RATES_MASK) >> IWL_FIRST_CCK_RATE) & 0xF;
2872         else
2873                 priv->staging_rxon.cck_basic_rates =
2874                     (IWL_CCK_BASIC_RATES_MASK >> IWL_FIRST_CCK_RATE) & 0xF;
2875
2876         if (priv->active_rate_basic & IWL_OFDM_BASIC_RATES_MASK)
2877                 priv->staging_rxon.ofdm_basic_rates =
2878                     ((priv->active_rate_basic &
2879                       (IWL_OFDM_BASIC_RATES_MASK | IWL_RATE_6M_MASK)) >>
2880                       IWL_FIRST_OFDM_RATE) & 0xFF;
2881         else
2882                 priv->staging_rxon.ofdm_basic_rates =
2883                    (IWL_OFDM_BASIC_RATES_MASK >> IWL_FIRST_OFDM_RATE) & 0xFF;
2884 }
2885
2886 static void iwl3945_radio_kill_sw(struct iwl3945_priv *priv, int disable_radio)
2887 {
2888         unsigned long flags;
2889
2890         if (!!disable_radio == test_bit(STATUS_RF_KILL_SW, &priv->status))
2891                 return;
2892
2893         IWL_DEBUG_RF_KILL("Manual SW RF KILL set to: RADIO %s\n",
2894                           disable_radio ? "OFF" : "ON");
2895
2896         if (disable_radio) {
2897                 iwl3945_scan_cancel(priv);
2898                 /* FIXME: This is a workaround for AP */
2899                 if (priv->iw_mode != IEEE80211_IF_TYPE_AP) {
2900                         spin_lock_irqsave(&priv->lock, flags);
2901                         iwl3945_write32(priv, CSR_UCODE_DRV_GP1_SET,
2902                                     CSR_UCODE_SW_BIT_RFKILL);
2903                         spin_unlock_irqrestore(&priv->lock, flags);
2904                         iwl3945_send_card_state(priv, CARD_STATE_CMD_DISABLE, 0);
2905                         set_bit(STATUS_RF_KILL_SW, &priv->status);
2906                 }
2907                 return;
2908         }
2909
2910         spin_lock_irqsave(&priv->lock, flags);
2911         iwl3945_write32(priv, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
2912
2913         clear_bit(STATUS_RF_KILL_SW, &priv->status);
2914         spin_unlock_irqrestore(&priv->lock, flags);
2915
2916         /* wake up ucode */
2917         msleep(10);
2918
2919         spin_lock_irqsave(&priv->lock, flags);
2920         iwl3945_read32(priv, CSR_UCODE_DRV_GP1);
2921         if (!iwl3945_grab_nic_access(priv))
2922                 iwl3945_release_nic_access(priv);
2923         spin_unlock_irqrestore(&priv->lock, flags);
2924
2925         if (test_bit(STATUS_RF_KILL_HW, &priv->status)) {
2926                 IWL_DEBUG_RF_KILL("Can not turn radio back on - "
2927                                   "disabled by HW switch\n");
2928                 return;
2929         }
2930
2931         queue_work(priv->workqueue, &priv->restart);
2932         return;
2933 }
2934
2935 void iwl3945_set_decrypted_flag(struct iwl3945_priv *priv, struct sk_buff *skb,
2936                             u32 decrypt_res, struct ieee80211_rx_status *stats)
2937 {
2938         u16 fc =
2939             le16_to_cpu(((struct ieee80211_hdr *)skb->data)->frame_control);
2940
2941         if (priv->active_rxon.filter_flags & RXON_FILTER_DIS_DECRYPT_MSK)
2942                 return;
2943
2944         if (!(fc & IEEE80211_FCTL_PROTECTED))
2945                 return;
2946
2947         IWL_DEBUG_RX("decrypt_res:0x%x\n", decrypt_res);
2948         switch (decrypt_res & RX_RES_STATUS_SEC_TYPE_MSK) {
2949         case RX_RES_STATUS_SEC_TYPE_TKIP:
2950                 if ((decrypt_res & RX_RES_STATUS_DECRYPT_TYPE_MSK) ==
2951                     RX_RES_STATUS_BAD_ICV_MIC)
2952                         stats->flag |= RX_FLAG_MMIC_ERROR;
2953         case RX_RES_STATUS_SEC_TYPE_WEP:
2954         case RX_RES_STATUS_SEC_TYPE_CCMP:
2955                 if ((decrypt_res & RX_RES_STATUS_DECRYPT_TYPE_MSK) ==
2956                     RX_RES_STATUS_DECRYPT_OK) {
2957                         IWL_DEBUG_RX("hw decrypt successfully!!!\n");
2958                         stats->flag |= RX_FLAG_DECRYPTED;
2959                 }
2960                 break;
2961
2962         default:
2963                 break;
2964         }
2965 }
2966
2967 #define IWL_PACKET_RETRY_TIME HZ
2968
2969 int iwl3945_is_duplicate_packet(struct iwl3945_priv *priv, struct ieee80211_hdr *header)
2970 {
2971         u16 sc = le16_to_cpu(header->seq_ctrl);
2972         u16 seq = (sc & IEEE80211_SCTL_SEQ) >> 4;
2973         u16 frag = sc & IEEE80211_SCTL_FRAG;
2974         u16 *last_seq, *last_frag;
2975         unsigned long *last_time;
2976
2977         switch (priv->iw_mode) {
2978         case IEEE80211_IF_TYPE_IBSS:{
2979                 struct list_head *p;
2980                 struct iwl3945_ibss_seq *entry = NULL;
2981                 u8 *mac = header->addr2;
2982                 int index = mac[5] & (IWL_IBSS_MAC_HASH_SIZE - 1);
2983
2984                 __list_for_each(p, &priv->ibss_mac_hash[index]) {
2985                         entry = list_entry(p, struct iwl3945_ibss_seq, list);
2986                         if (!compare_ether_addr(entry->mac, mac))
2987                                 break;
2988                 }
2989                 if (p == &priv->ibss_mac_hash[index]) {
2990                         entry = kzalloc(sizeof(*entry), GFP_ATOMIC);
2991                         if (!entry) {
2992                                 IWL_ERROR("Cannot malloc new mac entry\n");
2993                                 return 0;
2994                         }
2995                         memcpy(entry->mac, mac, ETH_ALEN);
2996                         entry->seq_num = seq;
2997                         entry->frag_num = frag;
2998                         entry->packet_time = jiffies;
2999                         list_add(&entry->list, &priv->ibss_mac_hash[index]);
3000                         return 0;
3001                 }
3002                 last_seq = &entry->seq_num;
3003                 last_frag = &entry->frag_num;
3004                 last_time = &entry->packet_time;
3005                 break;
3006         }
3007         case IEEE80211_IF_TYPE_STA:
3008                 last_seq = &priv->last_seq_num;
3009                 last_frag = &priv->last_frag_num;
3010                 last_time = &priv->last_packet_time;
3011                 break;
3012         default:
3013                 return 0;
3014         }
3015         if ((*last_seq == seq) &&
3016             time_after(*last_time + IWL_PACKET_RETRY_TIME, jiffies)) {
3017                 if (*last_frag == frag)
3018                         goto drop;
3019                 if (*last_frag + 1 != frag)
3020                         /* out-of-order fragment */
3021                         goto drop;
3022         } else
3023                 *last_seq = seq;
3024
3025         *last_frag = frag;
3026         *last_time = jiffies;
3027         return 0;
3028
3029  drop:
3030         return 1;
3031 }
3032
3033 #ifdef CONFIG_IWL3945_SPECTRUM_MEASUREMENT
3034
3035 #include "iwl-spectrum.h"
3036
3037 #define BEACON_TIME_MASK_LOW    0x00FFFFFF
3038 #define BEACON_TIME_MASK_HIGH   0xFF000000
3039 #define TIME_UNIT               1024
3040
3041 /*
3042  * extended beacon time format
3043  * time in usec will be changed into a 32-bit value in 8:24 format
3044  * the high 1 byte is the beacon counts
3045  * the lower 3 bytes is the time in usec within one beacon interval
3046  */
3047
3048 static u32 iwl3945_usecs_to_beacons(u32 usec, u32 beacon_interval)
3049 {
3050         u32 quot;
3051         u32 rem;
3052         u32 interval = beacon_interval * 1024;
3053
3054         if (!interval || !usec)
3055                 return 0;
3056
3057         quot = (usec / interval) & (BEACON_TIME_MASK_HIGH >> 24);
3058         rem = (usec % interval) & BEACON_TIME_MASK_LOW;
3059
3060         return (quot << 24) + rem;
3061 }
3062
3063 /* base is usually what we get from ucode with each received frame,
3064  * the same as HW timer counter counting down
3065  */
3066
3067 static __le32 iwl3945_add_beacon_time(u32 base, u32 addon, u32 beacon_interval)
3068 {
3069         u32 base_low = base & BEACON_TIME_MASK_LOW;
3070         u32 addon_low = addon & BEACON_TIME_MASK_LOW;
3071         u32 interval = beacon_interval * TIME_UNIT;
3072         u32 res = (base & BEACON_TIME_MASK_HIGH) +
3073             (addon & BEACON_TIME_MASK_HIGH);
3074
3075         if (base_low > addon_low)
3076                 res += base_low - addon_low;
3077         else if (base_low < addon_low) {
3078                 res += interval + base_low - addon_low;
3079                 res += (1 << 24);
3080         } else
3081                 res += (1 << 24);
3082
3083         return cpu_to_le32(res);
3084 }
3085
3086 static int iwl3945_get_measurement(struct iwl3945_priv *priv,
3087                                struct ieee80211_measurement_params *params,
3088                                u8 type)
3089 {
3090         struct iwl3945_spectrum_cmd spectrum;
3091         struct iwl3945_rx_packet *res;
3092         struct iwl3945_host_cmd cmd = {
3093                 .id = REPLY_SPECTRUM_MEASUREMENT_CMD,
3094                 .data = (void *)&spectrum,
3095                 .meta.flags = CMD_WANT_SKB,
3096         };
3097         u32 add_time = le64_to_cpu(params->start_time);
3098         int rc;
3099         int spectrum_resp_status;
3100         int duration = le16_to_cpu(params->duration);
3101
3102         if (iwl3945_is_associated(priv))
3103                 add_time =
3104                     iwl3945_usecs_to_beacons(
3105                         le64_to_cpu(params->start_time) - priv->last_tsf,
3106                         le16_to_cpu(priv->rxon_timing.beacon_interval));
3107
3108         memset(&spectrum, 0, sizeof(spectrum));
3109
3110         spectrum.channel_count = cpu_to_le16(1);
3111         spectrum.flags =
3112             RXON_FLG_TSF2HOST_MSK | RXON_FLG_ANT_A_MSK | RXON_FLG_DIS_DIV_MSK;
3113         spectrum.filter_flags = MEASUREMENT_FILTER_FLAG;
3114         cmd.len = sizeof(spectrum);
3115         spectrum.len = cpu_to_le16(cmd.len - sizeof(spectrum.len));
3116
3117         if (iwl3945_is_associated(priv))
3118                 spectrum.start_time =
3119                     iwl3945_add_beacon_time(priv->last_beacon_time,
3120                                 add_time,
3121                                 le16_to_cpu(priv->rxon_timing.beacon_interval));
3122         else
3123                 spectrum.start_time = 0;
3124
3125         spectrum.channels[0].duration = cpu_to_le32(duration * TIME_UNIT);
3126         spectrum.channels[0].channel = params->channel;
3127         spectrum.channels[0].type = type;
3128         if (priv->active_rxon.flags & RXON_FLG_BAND_24G_MSK)
3129                 spectrum.flags |= RXON_FLG_BAND_24G_MSK |
3130                     RXON_FLG_AUTO_DETECT_MSK | RXON_FLG_TGG_PROTECT_MSK;
3131
3132         rc = iwl3945_send_cmd_sync(priv, &cmd);
3133         if (rc)
3134                 return rc;
3135
3136         res = (struct iwl3945_rx_packet *)cmd.meta.u.skb->data;
3137         if (res->hdr.flags & IWL_CMD_FAILED_MSK) {
3138                 IWL_ERROR("Bad return from REPLY_RX_ON_ASSOC command\n");
3139                 rc = -EIO;
3140         }
3141
3142         spectrum_resp_status = le16_to_cpu(res->u.spectrum.status);
3143         switch (spectrum_resp_status) {
3144         case 0:         /* Command will be handled */
3145                 if (res->u.spectrum.id != 0xff) {
3146                         IWL_DEBUG_INFO("Replaced existing measurement: %d\n",
3147                                                 res->u.spectrum.id);
3148                         priv->measurement_status &= ~MEASUREMENT_READY;
3149                 }
3150                 priv->measurement_status |= MEASUREMENT_ACTIVE;
3151                 rc = 0;
3152                 break;
3153
3154         case 1:         /* Command will not be handled */
3155                 rc = -EAGAIN;
3156                 break;
3157         }
3158
3159         dev_kfree_skb_any(cmd.meta.u.skb);
3160
3161         return rc;
3162 }
3163 #endif
3164
3165 static void iwl3945_txstatus_to_ieee(struct iwl3945_priv *priv,
3166                                  struct iwl3945_tx_info *tx_sta)
3167 {
3168
3169         tx_sta->status.ack_signal = 0;
3170         tx_sta->status.excessive_retries = 0;
3171         tx_sta->status.queue_length = 0;
3172         tx_sta->status.queue_number = 0;
3173
3174         if (in_interrupt())
3175                 ieee80211_tx_status_irqsafe(priv->hw,
3176                                             tx_sta->skb[0], &(tx_sta->status));
3177         else
3178                 ieee80211_tx_status(priv->hw,
3179                                     tx_sta->skb[0], &(tx_sta->status));
3180
3181         tx_sta->skb[0] = NULL;
3182 }
3183
3184 /**
3185  * iwl3945_tx_queue_reclaim - Reclaim Tx queue entries already Tx'd
3186  *
3187  * When FW advances 'R' index, all entries between old and new 'R' index
3188  * need to be reclaimed. As result, some free space forms. If there is
3189  * enough free space (> low mark), wake the stack that feeds us.
3190  */
3191 static int iwl3945_tx_queue_reclaim(struct iwl3945_priv *priv, int txq_id, int index)
3192 {
3193         struct iwl3945_tx_queue *txq = &priv->txq[txq_id];
3194         struct iwl3945_queue *q = &txq->q;
3195         int nfreed = 0;
3196
3197         if ((index >= q->n_bd) || (x2_queue_used(q, index) == 0)) {
3198                 IWL_ERROR("Read index for DMA queue txq id (%d), index %d, "
3199                           "is out of range [0-%d] %d %d.\n", txq_id,
3200                           index, q->n_bd, q->write_ptr, q->read_ptr);
3201                 return 0;
3202         }
3203
3204         for (index = iwl3945_queue_inc_wrap(index, q->n_bd);
3205                 q->read_ptr != index;
3206                 q->read_ptr = iwl3945_queue_inc_wrap(q->read_ptr, q->n_bd)) {
3207                 if (txq_id != IWL_CMD_QUEUE_NUM) {
3208                         iwl3945_txstatus_to_ieee(priv,
3209                                         &(txq->txb[txq->q.read_ptr]));
3210                         iwl3945_hw_txq_free_tfd(priv, txq);
3211                 } else if (nfreed > 1) {
3212                         IWL_ERROR("HCMD skipped: index (%d) %d %d\n", index,
3213                                         q->write_ptr, q->read_ptr);
3214                         queue_work(priv->workqueue, &priv->restart);
3215                 }
3216                 nfreed++;
3217         }
3218
3219         if (iwl3945_queue_space(q) > q->low_mark && (txq_id >= 0) &&
3220                         (txq_id != IWL_CMD_QUEUE_NUM) &&
3221                         priv->mac80211_registered)
3222                 ieee80211_wake_queue(priv->hw, txq_id);
3223
3224
3225         return nfreed;
3226 }
3227
3228 static int iwl3945_is_tx_success(u32 status)
3229 {
3230         return (status & 0xFF) == 0x1;
3231 }
3232
3233 /******************************************************************************
3234  *
3235  * Generic RX handler implementations
3236  *
3237  ******************************************************************************/
3238 /**
3239  * iwl3945_rx_reply_tx - Handle Tx response
3240  */
3241 static void iwl3945_rx_reply_tx(struct iwl3945_priv *priv,
3242                             struct iwl3945_rx_mem_buffer *rxb)
3243 {
3244         struct iwl3945_rx_packet *pkt = (void *)rxb->skb->data;
3245         u16 sequence = le16_to_cpu(pkt->hdr.sequence);
3246         int txq_id = SEQ_TO_QUEUE(sequence);
3247         int index = SEQ_TO_INDEX(sequence);
3248         struct iwl3945_tx_queue *txq = &priv->txq[txq_id];
3249         struct ieee80211_tx_status *tx_status;
3250         struct iwl3945_tx_resp *tx_resp = (void *)&pkt->u.raw[0];
3251         u32  status = le32_to_cpu(tx_resp->status);
3252
3253         if ((index >= txq->q.n_bd) || (x2_queue_used(&txq->q, index) == 0)) {
3254                 IWL_ERROR("Read index for DMA queue txq_id (%d) index %d "
3255                           "is out of range [0-%d] %d %d\n", txq_id,
3256                           index, txq->q.n_bd, txq->q.write_ptr,
3257                           txq->q.read_ptr);
3258                 return;
3259         }
3260
3261         tx_status = &(txq->txb[txq->q.read_ptr].status);
3262
3263         tx_status->retry_count = tx_resp->failure_frame;
3264         tx_status->queue_number = status;
3265         tx_status->queue_length = tx_resp->bt_kill_count;
3266         tx_status->queue_length |= tx_resp->failure_rts;
3267
3268         tx_status->flags =
3269             iwl3945_is_tx_success(status) ? IEEE80211_TX_STATUS_ACK : 0;
3270
3271         IWL_DEBUG_TX("Tx queue %d Status %s (0x%08x) plcp rate %d retries %d\n",
3272                         txq_id, iwl3945_get_tx_fail_reason(status), status,
3273                         tx_resp->rate, tx_resp->failure_frame);
3274
3275         IWL_DEBUG_TX_REPLY("Tx queue reclaim %d\n", index);
3276         if (index != -1)
3277                 iwl3945_tx_queue_reclaim(priv, txq_id, index);
3278
3279         if (iwl_check_bits(status, TX_ABORT_REQUIRED_MSK))
3280                 IWL_ERROR("TODO:  Implement Tx ABORT REQUIRED!!!\n");
3281 }
3282
3283
3284 static void iwl3945_rx_reply_alive(struct iwl3945_priv *priv,
3285                                struct iwl3945_rx_mem_buffer *rxb)
3286 {
3287         struct iwl3945_rx_packet *pkt = (void *)rxb->skb->data;
3288         struct iwl3945_alive_resp *palive;
3289         struct delayed_work *pwork;
3290
3291         palive = &pkt->u.alive_frame;
3292
3293         IWL_DEBUG_INFO("Alive ucode status 0x%08X revision "
3294                        "0x%01X 0x%01X\n",
3295                        palive->is_valid, palive->ver_type,
3296                        palive->ver_subtype);
3297
3298         if (palive->ver_subtype == INITIALIZE_SUBTYPE) {
3299                 IWL_DEBUG_INFO("Initialization Alive received.\n");
3300                 memcpy(&priv->card_alive_init,
3301                        &pkt->u.alive_frame,
3302                        sizeof(struct iwl3945_init_alive_resp));
3303                 pwork = &priv->init_alive_start;
3304         } else {
3305                 IWL_DEBUG_INFO("Runtime Alive received.\n");
3306                 memcpy(&priv->card_alive, &pkt->u.alive_frame,
3307                        sizeof(struct iwl3945_alive_resp));
3308                 pwork = &priv->alive_start;
3309                 iwl3945_disable_events(priv);
3310         }
3311
3312         /* We delay the ALIVE response by 5ms to
3313          * give the HW RF Kill time to activate... */
3314         if (palive->is_valid == UCODE_VALID_OK)
3315                 queue_delayed_work(priv->workqueue, pwork,
3316                                    msecs_to_jiffies(5));
3317         else
3318                 IWL_WARNING("uCode did not respond OK.\n");
3319 }
3320
3321 static void iwl3945_rx_reply_add_sta(struct iwl3945_priv *priv,
3322                                  struct iwl3945_rx_mem_buffer *rxb)
3323 {
3324         struct iwl3945_rx_packet *pkt = (void *)rxb->skb->data;
3325
3326         IWL_DEBUG_RX("Received REPLY_ADD_STA: 0x%02X\n", pkt->u.status);
3327         return;
3328 }
3329
3330 static void iwl3945_rx_reply_error(struct iwl3945_priv *priv,
3331                                struct iwl3945_rx_mem_buffer *rxb)
3332 {
3333         struct iwl3945_rx_packet *pkt = (void *)rxb->skb->data;
3334
3335         IWL_ERROR("Error Reply type 0x%08X cmd %s (0x%02X) "
3336                 "seq 0x%04X ser 0x%08X\n",
3337                 le32_to_cpu(pkt->u.err_resp.error_type),
3338                 get_cmd_string(pkt->u.err_resp.cmd_id),
3339                 pkt->u.err_resp.cmd_id,
3340                 le16_to_cpu(pkt->u.err_resp.bad_cmd_seq_num),
3341                 le32_to_cpu(pkt->u.err_resp.error_info));
3342 }
3343
3344 #define TX_STATUS_ENTRY(x) case TX_STATUS_FAIL_ ## x: return #x
3345
3346 static void iwl3945_rx_csa(struct iwl3945_priv *priv, struct iwl3945_rx_mem_buffer *rxb)
3347 {
3348         struct iwl3945_rx_packet *pkt = (void *)rxb->skb->data;
3349         struct iwl3945_rxon_cmd *rxon = (void *)&priv->active_rxon;
3350         struct iwl3945_csa_notification *csa = &(pkt->u.csa_notif);
3351         IWL_DEBUG_11H("CSA notif: channel %d, status %d\n",
3352                       le16_to_cpu(csa->channel), le32_to_cpu(csa->status));
3353         rxon->channel = csa->channel;
3354         priv->staging_rxon.channel = csa->channel;
3355 }
3356
3357 static void iwl3945_rx_spectrum_measure_notif(struct iwl3945_priv *priv,
3358                                           struct iwl3945_rx_mem_buffer *rxb)
3359 {
3360 #ifdef CONFIG_IWL3945_SPECTRUM_MEASUREMENT
3361         struct iwl3945_rx_packet *pkt = (void *)rxb->skb->data;
3362         struct iwl3945_spectrum_notification *report = &(pkt->u.spectrum_notif);
3363
3364         if (!report->state) {
3365                 IWL_DEBUG(IWL_DL_11H | IWL_DL_INFO,
3366                           "Spectrum Measure Notification: Start\n");
3367                 return;
3368         }
3369
3370         memcpy(&priv->measure_report, report, sizeof(*report));
3371         priv->measurement_status |= MEASUREMENT_READY;
3372 #endif
3373 }
3374
3375 static void iwl3945_rx_pm_sleep_notif(struct iwl3945_priv *priv,
3376                                   struct iwl3945_rx_mem_buffer *rxb)
3377 {
3378 #ifdef CONFIG_IWL3945_DEBUG
3379         struct iwl3945_rx_packet *pkt = (void *)rxb->skb->data;
3380         struct iwl3945_sleep_notification *sleep = &(pkt->u.sleep_notif);
3381         IWL_DEBUG_RX("sleep mode: %d, src: %d\n",
3382                      sleep->pm_sleep_mode, sleep->pm_wakeup_src);
3383 #endif
3384 }
3385
3386 static void iwl3945_rx_pm_debug_statistics_notif(struct iwl3945_priv *priv,
3387                                              struct iwl3945_rx_mem_buffer *rxb)
3388 {
3389         struct iwl3945_rx_packet *pkt = (void *)rxb->skb->data;
3390         IWL_DEBUG_RADIO("Dumping %d bytes of unhandled "
3391                         "notification for %s:\n",
3392                         le32_to_cpu(pkt->len), get_cmd_string(pkt->hdr.cmd));
3393         iwl3945_print_hex_dump(IWL_DL_RADIO, pkt->u.raw, le32_to_cpu(pkt->len));
3394 }
3395
3396 static void iwl3945_bg_beacon_update(struct work_struct *work)
3397 {
3398         struct iwl3945_priv *priv =
3399                 container_of(work, struct iwl3945_priv, beacon_update);
3400         struct sk_buff *beacon;
3401
3402         /* Pull updated AP beacon from mac80211. will fail if not in AP mode */
3403         beacon = ieee80211_beacon_get(priv->hw, priv->vif, NULL);
3404
3405         if (!beacon) {
3406                 IWL_ERROR("update beacon failed\n");
3407                 return;
3408         }
3409
3410         mutex_lock(&priv->mutex);
3411         /* new beacon skb is allocated every time; dispose previous.*/
3412         if (priv->ibss_beacon)
3413                 dev_kfree_skb(priv->ibss_beacon);
3414
3415         priv->ibss_beacon = beacon;
3416         mutex_unlock(&priv->mutex);
3417
3418         iwl3945_send_beacon_cmd(priv);
3419 }
3420
3421 static void iwl3945_rx_beacon_notif(struct iwl3945_priv *priv,
3422                                 struct iwl3945_rx_mem_buffer *rxb)
3423 {
3424 #ifdef CONFIG_IWL3945_DEBUG
3425         struct iwl3945_rx_packet *pkt = (void *)rxb->skb->data;
3426         struct iwl3945_beacon_notif *beacon = &(pkt->u.beacon_status);
3427         u8 rate = beacon->beacon_notify_hdr.rate;
3428
3429         IWL_DEBUG_RX("beacon status %x retries %d iss %d "
3430                 "tsf %d %d rate %d\n",
3431                 le32_to_cpu(beacon->beacon_notify_hdr.status) & TX_STATUS_MSK,
3432                 beacon->beacon_notify_hdr.failure_frame,
3433                 le32_to_cpu(beacon->ibss_mgr_status),
3434                 le32_to_cpu(beacon->high_tsf),
3435                 le32_to_cpu(beacon->low_tsf), rate);
3436 #endif
3437
3438         if ((priv->iw_mode == IEEE80211_IF_TYPE_AP) &&
3439             (!test_bit(STATUS_EXIT_PENDING, &priv->status)))
3440                 queue_work(priv->workqueue, &priv->beacon_update);
3441 }
3442
3443 /* Service response to REPLY_SCAN_CMD (0x80) */
3444 static void iwl3945_rx_reply_scan(struct iwl3945_priv *priv,
3445                               struct iwl3945_rx_mem_buffer *rxb)
3446 {
3447 #ifdef CONFIG_IWL3945_DEBUG
3448         struct iwl3945_rx_packet *pkt = (void *)rxb->skb->data;
3449         struct iwl3945_scanreq_notification *notif =
3450             (struct iwl3945_scanreq_notification *)pkt->u.raw;
3451
3452         IWL_DEBUG_RX("Scan request status = 0x%x\n", notif->status);
3453 #endif
3454 }
3455
3456 /* Service SCAN_START_NOTIFICATION (0x82) */
3457 static void iwl3945_rx_scan_start_notif(struct iwl3945_priv *priv,
3458                                     struct iwl3945_rx_mem_buffer *rxb)
3459 {
3460         struct iwl3945_rx_packet *pkt = (void *)rxb->skb->data;
3461         struct iwl3945_scanstart_notification *notif =
3462             (struct iwl3945_scanstart_notification *)pkt->u.raw;
3463         priv->scan_start_tsf = le32_to_cpu(notif->tsf_low);
3464         IWL_DEBUG_SCAN("Scan start: "
3465                        "%d [802.11%s] "
3466                        "(TSF: 0x%08X:%08X) - %d (beacon timer %u)\n",
3467                        notif->channel,
3468                        notif->band ? "bg" : "a",
3469                        notif->tsf_high,
3470                        notif->tsf_low, notif->status, notif->beacon_timer);
3471 }
3472
3473 /* Service SCAN_RESULTS_NOTIFICATION (0x83) */
3474 static void iwl3945_rx_scan_results_notif(struct iwl3945_priv *priv,
3475                                       struct iwl3945_rx_mem_buffer *rxb)
3476 {
3477         struct iwl3945_rx_packet *pkt = (void *)rxb->skb->data;
3478         struct iwl3945_scanresults_notification *notif =
3479             (struct iwl3945_scanresults_notification *)pkt->u.raw;
3480
3481         IWL_DEBUG_SCAN("Scan ch.res: "
3482                        "%d [802.11%s] "
3483                        "(TSF: 0x%08X:%08X) - %d "
3484                        "elapsed=%lu usec (%dms since last)\n",
3485                        notif->channel,
3486                        notif->band ? "bg" : "a",
3487                        le32_to_cpu(notif->tsf_high),
3488                        le32_to_cpu(notif->tsf_low),
3489                        le32_to_cpu(notif->statistics[0]),
3490                        le32_to_cpu(notif->tsf_low) - priv->scan_start_tsf,
3491                        jiffies_to_msecs(elapsed_jiffies
3492                                         (priv->last_scan_jiffies, jiffies)));
3493
3494         priv->last_scan_jiffies = jiffies;
3495         priv->next_scan_jiffies = 0;
3496 }
3497
3498 /* Service SCAN_COMPLETE_NOTIFICATION (0x84) */
3499 static void iwl3945_rx_scan_complete_notif(struct iwl3945_priv *priv,
3500                                        struct iwl3945_rx_mem_buffer *rxb)
3501 {
3502         struct iwl3945_rx_packet *pkt = (void *)rxb->skb->data;
3503         struct iwl3945_scancomplete_notification *scan_notif = (void *)pkt->u.raw;
3504
3505         IWL_DEBUG_SCAN("Scan complete: %d channels (TSF 0x%08X:%08X) - %d\n",
3506                        scan_notif->scanned_channels,
3507                        scan_notif->tsf_low,
3508                        scan_notif->tsf_high, scan_notif->status);
3509
3510         /* The HW is no longer scanning */
3511         clear_bit(STATUS_SCAN_HW, &priv->status);
3512
3513         /* The scan completion notification came in, so kill that timer... */
3514         cancel_delayed_work(&priv->scan_check);
3515
3516         IWL_DEBUG_INFO("Scan pass on %sGHz took %dms\n",
3517                        (priv->scan_bands == 2) ? "2.4" : "5.2",
3518                        jiffies_to_msecs(elapsed_jiffies
3519                                         (priv->scan_pass_start, jiffies)));
3520
3521         /* Remove this scanned band from the list
3522          * of pending bands to scan */
3523         priv->scan_bands--;
3524
3525         /* If a request to abort was given, or the scan did not succeed
3526          * then we reset the scan state machine and terminate,
3527          * re-queuing another scan if one has been requested */
3528         if (test_bit(STATUS_SCAN_ABORTING, &priv->status)) {
3529                 IWL_DEBUG_INFO("Aborted scan completed.\n");
3530                 clear_bit(STATUS_SCAN_ABORTING, &priv->status);
3531         } else {
3532                 /* If there are more bands on this scan pass reschedule */
3533                 if (priv->scan_bands > 0)
3534                         goto reschedule;
3535         }
3536
3537         priv->last_scan_jiffies = jiffies;
3538         priv->next_scan_jiffies = 0;
3539         IWL_DEBUG_INFO("Setting scan to off\n");
3540
3541         clear_bit(STATUS_SCANNING, &priv->status);
3542
3543         IWL_DEBUG_INFO("Scan took %dms\n",
3544                 jiffies_to_msecs(elapsed_jiffies(priv->scan_start, jiffies)));
3545
3546         queue_work(priv->workqueue, &priv->scan_completed);
3547
3548         return;
3549
3550 reschedule:
3551         priv->scan_pass_start = jiffies;
3552         queue_work(priv->workqueue, &priv->request_scan);
3553 }
3554
3555 /* Handle notification from uCode that card's power state is changing
3556  * due to software, hardware, or critical temperature RFKILL */
3557 static void iwl3945_rx_card_state_notif(struct iwl3945_priv *priv,
3558                                     struct iwl3945_rx_mem_buffer *rxb)
3559 {
3560         struct iwl3945_rx_packet *pkt = (void *)rxb->skb->data;
3561         u32 flags = le32_to_cpu(pkt->u.card_state_notif.flags);
3562         unsigned long status = priv->status;
3563
3564         IWL_DEBUG_RF_KILL("Card state received: HW:%s SW:%s\n",
3565                           (flags & HW_CARD_DISABLED) ? "Kill" : "On",
3566                           (flags & SW_CARD_DISABLED) ? "Kill" : "On");
3567
3568         iwl3945_write32(priv, CSR_UCODE_DRV_GP1_SET,
3569                     CSR_UCODE_DRV_GP1_BIT_CMD_BLOCKED);
3570
3571         if (flags & HW_CARD_DISABLED)
3572                 set_bit(STATUS_RF_KILL_HW, &priv->status);
3573         else
3574                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
3575
3576
3577         if (flags & SW_CARD_DISABLED)
3578                 set_bit(STATUS_RF_KILL_SW, &priv->status);
3579         else
3580                 clear_bit(STATUS_RF_KILL_SW, &priv->status);
3581
3582         iwl3945_scan_cancel(priv);
3583
3584         if ((test_bit(STATUS_RF_KILL_HW, &status) !=
3585              test_bit(STATUS_RF_KILL_HW, &priv->status)) ||
3586             (test_bit(STATUS_RF_KILL_SW, &status) !=
3587              test_bit(STATUS_RF_KILL_SW, &priv->status)))
3588                 queue_work(priv->workqueue, &priv->rf_kill);
3589         else
3590                 wake_up_interruptible(&priv->wait_command_queue);
3591 }
3592
3593 /**
3594  * iwl3945_setup_rx_handlers - Initialize Rx handler callbacks
3595  *
3596  * Setup the RX handlers for each of the reply types sent from the uCode
3597  * to the host.
3598  *
3599  * This function chains into the hardware specific files for them to setup
3600  * any hardware specific handlers as well.
3601  */
3602 static void iwl3945_setup_rx_handlers(struct iwl3945_priv *priv)
3603 {
3604         priv->rx_handlers[REPLY_ALIVE] = iwl3945_rx_reply_alive;
3605         priv->rx_handlers[REPLY_ADD_STA] = iwl3945_rx_reply_add_sta;
3606         priv->rx_handlers[REPLY_ERROR] = iwl3945_rx_reply_error;
3607         priv->rx_handlers[CHANNEL_SWITCH_NOTIFICATION] = iwl3945_rx_csa;
3608         priv->rx_handlers[SPECTRUM_MEASURE_NOTIFICATION] =
3609             iwl3945_rx_spectrum_measure_notif;
3610         priv->rx_handlers[PM_SLEEP_NOTIFICATION] = iwl3945_rx_pm_sleep_notif;
3611         priv->rx_handlers[PM_DEBUG_STATISTIC_NOTIFIC] =
3612             iwl3945_rx_pm_debug_statistics_notif;
3613         priv->rx_handlers[BEACON_NOTIFICATION] = iwl3945_rx_beacon_notif;
3614
3615         /*
3616          * The same handler is used for both the REPLY to a discrete
3617          * statistics request from the host as well as for the periodic
3618          * statistics notifications (after received beacons) from the uCode.
3619          */
3620         priv->rx_handlers[REPLY_STATISTICS_CMD] = iwl3945_hw_rx_statistics;
3621         priv->rx_handlers[STATISTICS_NOTIFICATION] = iwl3945_hw_rx_statistics;
3622
3623         priv->rx_handlers[REPLY_SCAN_CMD] = iwl3945_rx_reply_scan;
3624         priv->rx_handlers[SCAN_START_NOTIFICATION] = iwl3945_rx_scan_start_notif;
3625         priv->rx_handlers[SCAN_RESULTS_NOTIFICATION] =
3626             iwl3945_rx_scan_results_notif;
3627         priv->rx_handlers[SCAN_COMPLETE_NOTIFICATION] =
3628             iwl3945_rx_scan_complete_notif;
3629         priv->rx_handlers[CARD_STATE_NOTIFICATION] = iwl3945_rx_card_state_notif;
3630         priv->rx_handlers[REPLY_TX] = iwl3945_rx_reply_tx;
3631
3632         /* Set up hardware specific Rx handlers */
3633         iwl3945_hw_rx_handler_setup(priv);
3634 }
3635
3636 /**
3637  * iwl3945_tx_cmd_complete - Pull unused buffers off the queue and reclaim them
3638  * @rxb: Rx buffer to reclaim
3639  *
3640  * If an Rx buffer has an async callback associated with it the callback
3641  * will be executed.  The attached skb (if present) will only be freed
3642  * if the callback returns 1
3643  */
3644 static void iwl3945_tx_cmd_complete(struct iwl3945_priv *priv,
3645                                 struct iwl3945_rx_mem_buffer *rxb)
3646 {
3647         struct iwl3945_rx_packet *pkt = (struct iwl3945_rx_packet *)rxb->skb->data;
3648         u16 sequence = le16_to_cpu(pkt->hdr.sequence);
3649         int txq_id = SEQ_TO_QUEUE(sequence);
3650         int index = SEQ_TO_INDEX(sequence);
3651         int huge = sequence & SEQ_HUGE_FRAME;
3652         int cmd_index;
3653         struct iwl3945_cmd *cmd;
3654
3655         /* If a Tx command is being handled and it isn't in the actual
3656          * command queue then there a command routing bug has been introduced
3657          * in the queue management code. */
3658         if (txq_id != IWL_CMD_QUEUE_NUM)
3659                 IWL_ERROR("Error wrong command queue %d command id 0x%X\n",
3660                           txq_id, pkt->hdr.cmd);
3661         BUG_ON(txq_id != IWL_CMD_QUEUE_NUM);
3662
3663         cmd_index = get_cmd_index(&priv->txq[IWL_CMD_QUEUE_NUM].q, index, huge);
3664         cmd = &priv->txq[IWL_CMD_QUEUE_NUM].cmd[cmd_index];
3665
3666         /* Input error checking is done when commands are added to queue. */
3667         if (cmd->meta.flags & CMD_WANT_SKB) {
3668                 cmd->meta.source->u.skb = rxb->skb;
3669                 rxb->skb = NULL;
3670         } else if (cmd->meta.u.callback &&
3671                    !cmd->meta.u.callback(priv, cmd, rxb->skb))
3672                 rxb->skb = NULL;
3673
3674         iwl3945_tx_queue_reclaim(priv, txq_id, index);
3675
3676         if (!(cmd->meta.flags & CMD_ASYNC)) {
3677                 clear_bit(STATUS_HCMD_ACTIVE, &priv->status);
3678                 wake_up_interruptible(&priv->wait_command_queue);
3679         }
3680 }
3681
3682 /************************** RX-FUNCTIONS ****************************/
3683 /*
3684  * Rx theory of operation
3685  *
3686  * The host allocates 32 DMA target addresses and passes the host address
3687  * to the firmware at register IWL_RFDS_TABLE_LOWER + N * RFD_SIZE where N is
3688  * 0 to 31
3689  *
3690  * Rx Queue Indexes
3691  * The host/firmware share two index registers for managing the Rx buffers.
3692  *
3693  * The READ index maps to the first position that the firmware may be writing
3694  * to -- the driver can read up to (but not including) this position and get
3695  * good data.
3696  * The READ index is managed by the firmware once the card is enabled.
3697  *
3698  * The WRITE index maps to the last position the driver has read from -- the
3699  * position preceding WRITE is the last slot the firmware can place a packet.
3700  *
3701  * The queue is empty (no good data) if WRITE = READ - 1, and is full if
3702  * WRITE = READ.
3703  *
3704  * During initialization, the host sets up the READ queue position to the first
3705  * INDEX position, and WRITE to the last (READ - 1 wrapped)
3706  *
3707  * When the firmware places a packet in a buffer, it will advance the READ index
3708  * and fire the RX interrupt.  The driver can then query the READ index and
3709  * process as many packets as possible, moving the WRITE index forward as it
3710  * resets the Rx queue buffers with new memory.
3711  *
3712  * The management in the driver is as follows:
3713  * + A list of pre-allocated SKBs is stored in iwl->rxq->rx_free.  When
3714  *   iwl->rxq->free_count drops to or below RX_LOW_WATERMARK, work is scheduled
3715  *   to replenish the iwl->rxq->rx_free.
3716  * + In iwl3945_rx_replenish (scheduled) if 'processed' != 'read' then the
3717  *   iwl->rxq is replenished and the READ INDEX is updated (updating the
3718  *   'processed' and 'read' driver indexes as well)
3719  * + A received packet is processed and handed to the kernel network stack,
3720  *   detached from the iwl->rxq.  The driver 'processed' index is updated.
3721  * + The Host/Firmware iwl->rxq is replenished at tasklet time from the rx_free
3722  *   list. If there are no allocated buffers in iwl->rxq->rx_free, the READ
3723  *   INDEX is not incremented and iwl->status(RX_STALLED) is set.  If there
3724  *   were enough free buffers and RX_STALLED is set it is cleared.
3725  *
3726  *
3727  * Driver sequence:
3728  *
3729  * iwl3945_rx_queue_alloc()   Allocates rx_free
3730  * iwl3945_rx_replenish()     Replenishes rx_free list from rx_used, and calls
3731  *                            iwl3945_rx_queue_restock
3732  * iwl3945_rx_queue_restock() Moves available buffers from rx_free into Rx
3733  *                            queue, updates firmware pointers, and updates
3734  *                            the WRITE index.  If insufficient rx_free buffers
3735  *                            are available, schedules iwl3945_rx_replenish
3736  *
3737  * -- enable interrupts --
3738  * ISR - iwl3945_rx()         Detach iwl3945_rx_mem_buffers from pool up to the
3739  *                            READ INDEX, detaching the SKB from the pool.
3740  *                            Moves the packet buffer from queue to rx_used.
3741  *                            Calls iwl3945_rx_queue_restock to refill any empty
3742  *                            slots.
3743  * ...
3744  *
3745  */
3746
3747 /**
3748  * iwl3945_rx_queue_space - Return number of free slots available in queue.
3749  */
3750 static int iwl3945_rx_queue_space(const struct iwl3945_rx_queue *q)
3751 {
3752         int s = q->read - q->write;
3753         if (s <= 0)
3754                 s += RX_QUEUE_SIZE;
3755         /* keep some buffer to not confuse full and empty queue */
3756         s -= 2;
3757         if (s < 0)
3758                 s = 0;
3759         return s;
3760 }
3761
3762 /**
3763  * iwl3945_rx_queue_update_write_ptr - Update the write pointer for the RX queue
3764  */
3765 int iwl3945_rx_queue_update_write_ptr(struct iwl3945_priv *priv, struct iwl3945_rx_queue *q)
3766 {
3767         u32 reg = 0;
3768         int rc = 0;
3769         unsigned long flags;
3770
3771         spin_lock_irqsave(&q->lock, flags);
3772
3773         if (q->need_update == 0)
3774                 goto exit_unlock;
3775
3776         /* If power-saving is in use, make sure device is awake */
3777         if (test_bit(STATUS_POWER_PMI, &priv->status)) {
3778                 reg = iwl3945_read32(priv, CSR_UCODE_DRV_GP1);
3779
3780                 if (reg & CSR_UCODE_DRV_GP1_BIT_MAC_SLEEP) {
3781                         iwl3945_set_bit(priv, CSR_GP_CNTRL,
3782                                     CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
3783                         goto exit_unlock;
3784                 }
3785
3786                 rc = iwl3945_grab_nic_access(priv);
3787                 if (rc)
3788                         goto exit_unlock;
3789
3790                 /* Device expects a multiple of 8 */
3791                 iwl3945_write_direct32(priv, FH_RSCSR_CHNL0_WPTR,
3792                                      q->write & ~0x7);
3793                 iwl3945_release_nic_access(priv);
3794
3795         /* Else device is assumed to be awake */
3796         } else
3797                 /* Device expects a multiple of 8 */
3798                 iwl3945_write32(priv, FH_RSCSR_CHNL0_WPTR, q->write & ~0x7);
3799
3800
3801         q->need_update = 0;
3802
3803  exit_unlock:
3804         spin_unlock_irqrestore(&q->lock, flags);
3805         return rc;
3806 }
3807
3808 /**
3809  * iwl3945_dma_addr2rbd_ptr - convert a DMA address to a uCode read buffer ptr
3810  */
3811 static inline __le32 iwl3945_dma_addr2rbd_ptr(struct iwl3945_priv *priv,
3812                                           dma_addr_t dma_addr)
3813 {
3814         return cpu_to_le32((u32)dma_addr);
3815 }
3816
3817 /**
3818  * iwl3945_rx_queue_restock - refill RX queue from pre-allocated pool
3819  *
3820  * If there are slots in the RX queue that need to be restocked,
3821  * and we have free pre-allocated buffers, fill the ranks as much
3822  * as we can, pulling from rx_free.
3823  *
3824  * This moves the 'write' index forward to catch up with 'processed', and
3825  * also updates the memory address in the firmware to reference the new
3826  * target buffer.
3827  */
3828 static int iwl3945_rx_queue_restock(struct iwl3945_priv *priv)
3829 {
3830         struct iwl3945_rx_queue *rxq = &priv->rxq;
3831         struct list_head *element;
3832         struct iwl3945_rx_mem_buffer *rxb;
3833         unsigned long flags;
3834         int write, rc;
3835
3836         spin_lock_irqsave(&rxq->lock, flags);
3837         write = rxq->write & ~0x7;
3838         while ((iwl3945_rx_queue_space(rxq) > 0) && (rxq->free_count)) {
3839                 /* Get next free Rx buffer, remove from free list */
3840                 element = rxq->rx_free.next;
3841                 rxb = list_entry(element, struct iwl3945_rx_mem_buffer, list);
3842                 list_del(element);
3843
3844                 /* Point to Rx buffer via next RBD in circular buffer */
3845                 rxq->bd[rxq->write] = iwl3945_dma_addr2rbd_ptr(priv, rxb->dma_addr);
3846                 rxq->queue[rxq->write] = rxb;
3847                 rxq->write = (rxq->write + 1) & RX_QUEUE_MASK;
3848                 rxq->free_count--;
3849         }
3850         spin_unlock_irqrestore(&rxq->lock, flags);
3851         /* If the pre-allocated buffer pool is dropping low, schedule to
3852          * refill it */
3853         if (rxq->free_count <= RX_LOW_WATERMARK)
3854                 queue_work(priv->workqueue, &priv->rx_replenish);
3855
3856
3857         /* If we've added more space for the firmware to place data, tell it.
3858          * Increment device's write pointer in multiples of 8. */
3859         if ((write != (rxq->write & ~0x7))
3860             || (abs(rxq->write - rxq->read) > 7)) {
3861                 spin_lock_irqsave(&rxq->lock, flags);
3862                 rxq->need_update = 1;
3863                 spin_unlock_irqrestore(&rxq->lock, flags);
3864                 rc = iwl3945_rx_queue_update_write_ptr(priv, rxq);
3865                 if (rc)
3866                         return rc;
3867         }
3868
3869         return 0;
3870 }
3871
3872 /**
3873  * iwl3945_rx_replenish - Move all used packet from rx_used to rx_free
3874  *
3875  * When moving to rx_free an SKB is allocated for the slot.
3876  *
3877  * Also restock the Rx queue via iwl3945_rx_queue_restock.
3878  * This is called as a scheduled work item (except for during initialization)
3879  */
3880 static void iwl3945_rx_allocate(struct iwl3945_priv *priv)
3881 {
3882         struct iwl3945_rx_queue *rxq = &priv->rxq;
3883         struct list_head *element;
3884         struct iwl3945_rx_mem_buffer *rxb;
3885         unsigned long flags;
3886         spin_lock_irqsave(&rxq->lock, flags);
3887         while (!list_empty(&rxq->rx_used)) {
3888                 element = rxq->rx_used.next;
3889                 rxb = list_entry(element, struct iwl3945_rx_mem_buffer, list);
3890
3891                 /* Alloc a new receive buffer */
3892                 rxb->skb =
3893                     alloc_skb(IWL_RX_BUF_SIZE, __GFP_NOWARN | GFP_ATOMIC);
3894                 if (!rxb->skb) {
3895                         if (net_ratelimit())
3896                                 printk(KERN_CRIT DRV_NAME
3897                                        ": Can not allocate SKB buffers\n");
3898                         /* We don't reschedule replenish work here -- we will
3899                          * call the restock method and if it still needs
3900                          * more buffers it will schedule replenish */
3901                         break;
3902                 }
3903
3904                 /* If radiotap head is required, reserve some headroom here.
3905                  * The physical head count is a variable rx_stats->phy_count.
3906                  * We reserve 4 bytes here. Plus these extra bytes, the
3907                  * headroom of the physical head should be enough for the
3908                  * radiotap head that iwl3945 supported. See iwl3945_rt.
3909                  */
3910                 skb_reserve(rxb->skb, 4);
3911
3912                 priv->alloc_rxb_skb++;
3913                 list_del(element);
3914
3915                 /* Get physical address of RB/SKB */
3916                 rxb->dma_addr =
3917                     pci_map_single(priv->pci_dev, rxb->skb->data,
3918                                    IWL_RX_BUF_SIZE, PCI_DMA_FROMDEVICE);
3919                 list_add_tail(&rxb->list, &rxq->rx_free);
3920                 rxq->free_count++;
3921         }
3922         spin_unlock_irqrestore(&rxq->lock, flags);
3923 }
3924
3925 /*
3926  * this should be called while priv->lock is locked
3927  */
3928 static void __iwl3945_rx_replenish(void *data)
3929 {
3930         struct iwl3945_priv *priv = data;
3931
3932         iwl3945_rx_allocate(priv);
3933         iwl3945_rx_queue_restock(priv);
3934 }
3935
3936
3937 void iwl3945_rx_replenish(void *data)
3938 {
3939         struct iwl3945_priv *priv = data;
3940         unsigned long flags;
3941
3942         iwl3945_rx_allocate(priv);
3943
3944         spin_lock_irqsave(&priv->lock, flags);
3945         iwl3945_rx_queue_restock(priv);
3946         spin_unlock_irqrestore(&priv->lock, flags);
3947 }
3948
3949 /* Assumes that the skb field of the buffers in 'pool' is kept accurate.
3950  * If an SKB has been detached, the POOL needs to have its SKB set to NULL
3951  * This free routine walks the list of POOL entries and if SKB is set to
3952  * non NULL it is unmapped and freed
3953  */
3954 static void iwl3945_rx_queue_free(struct iwl3945_priv *priv, struct iwl3945_rx_queue *rxq)
3955 {
3956         int i;
3957         for (i = 0; i < RX_QUEUE_SIZE + RX_FREE_BUFFERS; i++) {
3958                 if (rxq->pool[i].skb != NULL) {
3959                         pci_unmap_single(priv->pci_dev,
3960                                          rxq->pool[i].dma_addr,
3961                                          IWL_RX_BUF_SIZE, PCI_DMA_FROMDEVICE);
3962                         dev_kfree_skb(rxq->pool[i].skb);
3963                 }
3964         }
3965
3966         pci_free_consistent(priv->pci_dev, 4 * RX_QUEUE_SIZE, rxq->bd,
3967                             rxq->dma_addr);
3968         rxq->bd = NULL;
3969 }
3970
3971 int iwl3945_rx_queue_alloc(struct iwl3945_priv *priv)
3972 {
3973         struct iwl3945_rx_queue *rxq = &priv->rxq;
3974         struct pci_dev *dev = priv->pci_dev;
3975         int i;
3976
3977         spin_lock_init(&rxq->lock);
3978         INIT_LIST_HEAD(&rxq->rx_free);
3979         INIT_LIST_HEAD(&rxq->rx_used);
3980
3981         /* Alloc the circular buffer of Read Buffer Descriptors (RBDs) */
3982         rxq->bd = pci_alloc_consistent(dev, 4 * RX_QUEUE_SIZE, &rxq->dma_addr);
3983         if (!rxq->bd)
3984                 return -ENOMEM;
3985
3986         /* Fill the rx_used queue with _all_ of the Rx buffers */
3987         for (i = 0; i < RX_FREE_BUFFERS + RX_QUEUE_SIZE; i++)
3988                 list_add_tail(&rxq->pool[i].list, &rxq->rx_used);
3989
3990         /* Set us so that we have processed and used all buffers, but have
3991          * not restocked the Rx queue with fresh buffers */
3992         rxq->read = rxq->write = 0;
3993         rxq->free_count = 0;
3994         rxq->need_update = 0;
3995         return 0;
3996 }
3997
3998 void iwl3945_rx_queue_reset(struct iwl3945_priv *priv, struct iwl3945_rx_queue *rxq)
3999 {
4000         unsigned long flags;
4001         int i;
4002         spin_lock_irqsave(&rxq->lock, flags);
4003         INIT_LIST_HEAD(&rxq->rx_free);
4004         INIT_LIST_HEAD(&rxq->rx_used);
4005         /* Fill the rx_used queue with _all_ of the Rx buffers */
4006         for (i = 0; i < RX_FREE_BUFFERS + RX_QUEUE_SIZE; i++) {
4007                 /* In the reset function, these buffers may have been allocated
4008                  * to an SKB, so we need to unmap and free potential storage */
4009                 if (rxq->pool[i].skb != NULL) {
4010                         pci_unmap_single(priv->pci_dev,
4011                                          rxq->pool[i].dma_addr,
4012                                          IWL_RX_BUF_SIZE, PCI_DMA_FROMDEVICE);
4013                         priv->alloc_rxb_skb--;
4014                         dev_kfree_skb(rxq->pool[i].skb);
4015                         rxq->pool[i].skb = NULL;
4016                 }
4017                 list_add_tail(&rxq->pool[i].list, &rxq->rx_used);
4018         }
4019
4020         /* Set us so that we have processed and used all buffers, but have
4021          * not restocked the Rx queue with fresh buffers */
4022         rxq->read = rxq->write = 0;
4023         rxq->free_count = 0;
4024         spin_unlock_irqrestore(&rxq->lock, flags);
4025 }
4026
4027 /* Convert linear signal-to-noise ratio into dB */
4028 static u8 ratio2dB[100] = {
4029 /*       0   1   2   3   4   5   6   7   8   9 */
4030          0,  0,  6, 10, 12, 14, 16, 17, 18, 19, /* 00 - 09 */
4031         20, 21, 22, 22, 23, 23, 24, 25, 26, 26, /* 10 - 19 */
4032         26, 26, 26, 27, 27, 28, 28, 28, 29, 29, /* 20 - 29 */
4033         29, 30, 30, 30, 31, 31, 31, 31, 32, 32, /* 30 - 39 */
4034         32, 32, 32, 33, 33, 33, 33, 33, 34, 34, /* 40 - 49 */
4035         34, 34, 34, 34, 35, 35, 35, 35, 35, 35, /* 50 - 59 */
4036         36, 36, 36, 36, 36, 36, 36, 37, 37, 37, /* 60 - 69 */
4037         37, 37, 37, 37, 37, 38, 38, 38, 38, 38, /* 70 - 79 */
4038         38, 38, 38, 38, 38, 39, 39, 39, 39, 39, /* 80 - 89 */
4039         39, 39, 39, 39, 39, 40, 40, 40, 40, 40  /* 90 - 99 */
4040 };
4041
4042 /* Calculates a relative dB value from a ratio of linear
4043  *   (i.e. not dB) signal levels.
4044  * Conversion assumes that levels are voltages (20*log), not powers (10*log). */
4045 int iwl3945_calc_db_from_ratio(int sig_ratio)
4046 {
4047         /* 1000:1 or higher just report as 60 dB */
4048         if (sig_ratio >= 1000)
4049                 return 60;
4050
4051         /* 100:1 or higher, divide by 10 and use table,
4052          *   add 20 dB to make up for divide by 10 */
4053         if (sig_ratio >= 100)
4054                 return (20 + (int)ratio2dB[sig_ratio/10]);
4055
4056         /* We shouldn't see this */
4057         if (sig_ratio < 1)
4058                 return 0;
4059
4060         /* Use table for ratios 1:1 - 99:1 */
4061         return (int)ratio2dB[sig_ratio];
4062 }
4063
4064 #define PERFECT_RSSI (-20) /* dBm */
4065 #define WORST_RSSI (-95)   /* dBm */
4066 #define RSSI_RANGE (PERFECT_RSSI - WORST_RSSI)
4067
4068 /* Calculate an indication of rx signal quality (a percentage, not dBm!).
4069  * See http://www.ces.clemson.edu/linux/signal_quality.shtml for info
4070  *   about formulas used below. */
4071 int iwl3945_calc_sig_qual(int rssi_dbm, int noise_dbm)
4072 {
4073         int sig_qual;
4074         int degradation = PERFECT_RSSI - rssi_dbm;
4075
4076         /* If we get a noise measurement, use signal-to-noise ratio (SNR)
4077          * as indicator; formula is (signal dbm - noise dbm).
4078          * SNR at or above 40 is a great signal (100%).
4079          * Below that, scale to fit SNR of 0 - 40 dB within 0 - 100% indicator.
4080          * Weakest usable signal is usually 10 - 15 dB SNR. */
4081         if (noise_dbm) {
4082                 if (rssi_dbm - noise_dbm >= 40)
4083                         return 100;
4084                 else if (rssi_dbm < noise_dbm)
4085                         return 0;
4086                 sig_qual = ((rssi_dbm - noise_dbm) * 5) / 2;
4087
4088         /* Else use just the signal level.
4089          * This formula is a least squares fit of data points collected and
4090          *   compared with a reference system that had a percentage (%) display
4091          *   for signal quality. */
4092         } else
4093                 sig_qual = (100 * (RSSI_RANGE * RSSI_RANGE) - degradation *
4094                             (15 * RSSI_RANGE + 62 * degradation)) /
4095                            (RSSI_RANGE * RSSI_RANGE);
4096
4097         if (sig_qual > 100)
4098                 sig_qual = 100;
4099         else if (sig_qual < 1)
4100                 sig_qual = 0;
4101
4102         return sig_qual;
4103 }
4104
4105 /**
4106  * iwl3945_rx_handle - Main entry function for receiving responses from uCode
4107  *
4108  * Uses the priv->rx_handlers callback function array to invoke
4109  * the appropriate handlers, including command responses,
4110  * frame-received notifications, and other notifications.
4111  */
4112 static void iwl3945_rx_handle(struct iwl3945_priv *priv)
4113 {
4114         struct iwl3945_rx_mem_buffer *rxb;
4115         struct iwl3945_rx_packet *pkt;
4116         struct iwl3945_rx_queue *rxq = &priv->rxq;
4117         u32 r, i;
4118         int reclaim;
4119         unsigned long flags;
4120         u8 fill_rx = 0;
4121         u32 count = 8;
4122
4123         /* uCode's read index (stored in shared DRAM) indicates the last Rx
4124          * buffer that the driver may process (last buffer filled by ucode). */
4125         r = iwl3945_hw_get_rx_read(priv);
4126         i = rxq->read;
4127
4128         if (iwl3945_rx_queue_space(rxq) > (RX_QUEUE_SIZE / 2))
4129                 fill_rx = 1;
4130         /* Rx interrupt, but nothing sent from uCode */
4131         if (i == r)
4132                 IWL_DEBUG(IWL_DL_RX | IWL_DL_ISR, "r = %d, i = %d\n", r, i);
4133
4134         while (i != r) {
4135                 rxb = rxq->queue[i];
4136
4137                 /* If an RXB doesn't have a Rx queue slot associated with it,
4138                  * then a bug has been introduced in the queue refilling
4139                  * routines -- catch it here */
4140                 BUG_ON(rxb == NULL);
4141
4142                 rxq->queue[i] = NULL;
4143
4144                 pci_dma_sync_single_for_cpu(priv->pci_dev, rxb->dma_addr,
4145                                             IWL_RX_BUF_SIZE,
4146                                             PCI_DMA_FROMDEVICE);
4147                 pkt = (struct iwl3945_rx_packet *)rxb->skb->data;
4148
4149                 /* Reclaim a command buffer only if this packet is a response
4150                  *   to a (driver-originated) command.
4151                  * If the packet (e.g. Rx frame) originated from uCode,
4152                  *   there is no command buffer to reclaim.
4153                  * Ucode should set SEQ_RX_FRAME bit if ucode-originated,
4154                  *   but apparently a few don't get set; catch them here. */
4155                 reclaim = !(pkt->hdr.sequence & SEQ_RX_FRAME) &&
4156                         (pkt->hdr.cmd != STATISTICS_NOTIFICATION) &&
4157                         (pkt->hdr.cmd != REPLY_TX);
4158
4159                 /* Based on type of command response or notification,
4160                  *   handle those that need handling via function in
4161                  *   rx_handlers table.  See iwl3945_setup_rx_handlers() */
4162                 if (priv->rx_handlers[pkt->hdr.cmd]) {
4163                         IWL_DEBUG(IWL_DL_HOST_COMMAND | IWL_DL_RX | IWL_DL_ISR,
4164                                 "r = %d, i = %d, %s, 0x%02x\n", r, i,
4165                                 get_cmd_string(pkt->hdr.cmd), pkt->hdr.cmd);
4166                         priv->rx_handlers[pkt->hdr.cmd] (priv, rxb);
4167                 } else {
4168                         /* No handling needed */
4169                         IWL_DEBUG(IWL_DL_HOST_COMMAND | IWL_DL_RX | IWL_DL_ISR,
4170                                 "r %d i %d No handler needed for %s, 0x%02x\n",
4171                                 r, i, get_cmd_string(pkt->hdr.cmd),
4172                                 pkt->hdr.cmd);
4173                 }
4174
4175                 if (reclaim) {
4176                         /* Invoke any callbacks, transfer the skb to caller, and
4177                          * fire off the (possibly) blocking iwl3945_send_cmd()
4178                          * as we reclaim the driver command queue */
4179                         if (rxb && rxb->skb)
4180                                 iwl3945_tx_cmd_complete(priv, rxb);
4181                         else
4182                                 IWL_WARNING("Claim null rxb?\n");
4183                 }
4184
4185                 /* For now we just don't re-use anything.  We can tweak this
4186                  * later to try and re-use notification packets and SKBs that
4187                  * fail to Rx correctly */
4188                 if (rxb->skb != NULL) {
4189                         priv->alloc_rxb_skb--;
4190                         dev_kfree_skb_any(rxb->skb);
4191                         rxb->skb = NULL;
4192                 }
4193
4194                 pci_unmap_single(priv->pci_dev, rxb->dma_addr,
4195                                  IWL_RX_BUF_SIZE, PCI_DMA_FROMDEVICE);
4196                 spin_lock_irqsave(&rxq->lock, flags);
4197                 list_add_tail(&rxb->list, &priv->rxq.rx_used);
4198                 spin_unlock_irqrestore(&rxq->lock, flags);
4199                 i = (i + 1) & RX_QUEUE_MASK;
4200                 /* If there are a lot of unused frames,
4201                  * restock the Rx queue so ucode won't assert. */
4202                 if (fill_rx) {
4203                         count++;
4204                         if (count >= 8) {
4205                                 priv->rxq.read = i;
4206                                 __iwl3945_rx_replenish(priv);
4207                                 count = 0;
4208                         }
4209                 }
4210         }
4211
4212         /* Backtrack one entry */
4213         priv->rxq.read = i;
4214         iwl3945_rx_queue_restock(priv);
4215 }
4216
4217 /**
4218  * iwl3945_tx_queue_update_write_ptr - Send new write index to hardware
4219  */
4220 static int iwl3945_tx_queue_update_write_ptr(struct iwl3945_priv *priv,
4221                                   struct iwl3945_tx_queue *txq)
4222 {
4223         u32 reg = 0;
4224         int rc = 0;
4225         int txq_id = txq->q.id;
4226
4227         if (txq->need_update == 0)
4228                 return rc;
4229
4230         /* if we're trying to save power */
4231         if (test_bit(STATUS_POWER_PMI, &priv->status)) {
4232                 /* wake up nic if it's powered down ...
4233                  * uCode will wake up, and interrupt us again, so next
4234                  * time we'll skip this part. */
4235                 reg = iwl3945_read32(priv, CSR_UCODE_DRV_GP1);
4236
4237                 if (reg & CSR_UCODE_DRV_GP1_BIT_MAC_SLEEP) {
4238                         IWL_DEBUG_INFO("Requesting wakeup, GP1 = 0x%x\n", reg);
4239                         iwl3945_set_bit(priv, CSR_GP_CNTRL,
4240                                     CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
4241                         return rc;
4242                 }
4243
4244                 /* restore this queue's parameters in nic hardware. */
4245                 rc = iwl3945_grab_nic_access(priv);
4246                 if (rc)
4247                         return rc;
4248                 iwl3945_write_direct32(priv, HBUS_TARG_WRPTR,
4249                                      txq->q.write_ptr | (txq_id << 8));
4250                 iwl3945_release_nic_access(priv);
4251
4252         /* else not in power-save mode, uCode will never sleep when we're
4253          * trying to tx (during RFKILL, we're not trying to tx). */
4254         } else
4255                 iwl3945_write32(priv, HBUS_TARG_WRPTR,
4256                             txq->q.write_ptr | (txq_id << 8));
4257
4258         txq->need_update = 0;
4259
4260         return rc;
4261 }
4262
4263 #ifdef CONFIG_IWL3945_DEBUG
4264 static void iwl3945_print_rx_config_cmd(struct iwl3945_rxon_cmd *rxon)
4265 {
4266         DECLARE_MAC_BUF(mac);
4267
4268         IWL_DEBUG_RADIO("RX CONFIG:\n");
4269         iwl3945_print_hex_dump(IWL_DL_RADIO, (u8 *) rxon, sizeof(*rxon));
4270         IWL_DEBUG_RADIO("u16 channel: 0x%x\n", le16_to_cpu(rxon->channel));
4271         IWL_DEBUG_RADIO("u32 flags: 0x%08X\n", le32_to_cpu(rxon->flags));
4272         IWL_DEBUG_RADIO("u32 filter_flags: 0x%08x\n",
4273                         le32_to_cpu(rxon->filter_flags));
4274         IWL_DEBUG_RADIO("u8 dev_type: 0x%x\n", rxon->dev_type);
4275         IWL_DEBUG_RADIO("u8 ofdm_basic_rates: 0x%02x\n",
4276                         rxon->ofdm_basic_rates);
4277         IWL_DEBUG_RADIO("u8 cck_basic_rates: 0x%02x\n", rxon->cck_basic_rates);
4278         IWL_DEBUG_RADIO("u8[6] node_addr: %s\n",
4279                         print_mac(mac, rxon->node_addr));
4280         IWL_DEBUG_RADIO("u8[6] bssid_addr: %s\n",
4281                         print_mac(mac, rxon->bssid_addr));
4282         IWL_DEBUG_RADIO("u16 assoc_id: 0x%x\n", le16_to_cpu(rxon->assoc_id));
4283 }
4284 #endif
4285
4286 static void iwl3945_enable_interrupts(struct iwl3945_priv *priv)
4287 {
4288         IWL_DEBUG_ISR("Enabling interrupts\n");
4289         set_bit(STATUS_INT_ENABLED, &priv->status);
4290         iwl3945_write32(priv, CSR_INT_MASK, CSR_INI_SET_MASK);
4291 }
4292
4293 static inline void iwl3945_disable_interrupts(struct iwl3945_priv *priv)
4294 {
4295         clear_bit(STATUS_INT_ENABLED, &priv->status);
4296
4297         /* disable interrupts from uCode/NIC to host */
4298         iwl3945_write32(priv, CSR_INT_MASK, 0x00000000);
4299
4300         /* acknowledge/clear/reset any interrupts still pending
4301          * from uCode or flow handler (Rx/Tx DMA) */
4302         iwl3945_write32(priv, CSR_INT, 0xffffffff);
4303         iwl3945_write32(priv, CSR_FH_INT_STATUS, 0xffffffff);
4304         IWL_DEBUG_ISR("Disabled interrupts\n");
4305 }
4306
4307 static const char *desc_lookup(int i)
4308 {
4309         switch (i) {
4310         case 1:
4311                 return "FAIL";
4312         case 2:
4313                 return "BAD_PARAM";
4314         case 3:
4315                 return "BAD_CHECKSUM";
4316         case 4:
4317                 return "NMI_INTERRUPT";
4318         case 5:
4319                 return "SYSASSERT";
4320         case 6:
4321                 return "FATAL_ERROR";
4322         }
4323
4324         return "UNKNOWN";
4325 }
4326
4327 #define ERROR_START_OFFSET  (1 * sizeof(u32))
4328 #define ERROR_ELEM_SIZE     (7 * sizeof(u32))
4329
4330 static void iwl3945_dump_nic_error_log(struct iwl3945_priv *priv)
4331 {
4332         u32 i;
4333         u32 desc, time, count, base, data1;
4334         u32 blink1, blink2, ilink1, ilink2;
4335         int rc;
4336
4337         base = le32_to_cpu(priv->card_alive.error_event_table_ptr);
4338
4339         if (!iwl3945_hw_valid_rtc_data_addr(base)) {
4340                 IWL_ERROR("Not valid error log pointer 0x%08X\n", base);
4341                 return;
4342         }
4343
4344         rc = iwl3945_grab_nic_access(priv);
4345         if (rc) {
4346                 IWL_WARNING("Can not read from adapter at this time.\n");
4347                 return;
4348         }
4349
4350         count = iwl3945_read_targ_mem(priv, base);
4351
4352         if (ERROR_START_OFFSET <= count * ERROR_ELEM_SIZE) {
4353                 IWL_ERROR("Start IWL Error Log Dump:\n");
4354                 IWL_ERROR("Status: 0x%08lX, count: %d\n", priv->status, count);
4355         }
4356
4357         IWL_ERROR("Desc       Time       asrtPC  blink2 "
4358                   "ilink1  nmiPC   Line\n");
4359         for (i = ERROR_START_OFFSET;
4360              i < (count * ERROR_ELEM_SIZE) + ERROR_START_OFFSET;
4361              i += ERROR_ELEM_SIZE) {
4362                 desc = iwl3945_read_targ_mem(priv, base + i);
4363                 time =
4364                     iwl3945_read_targ_mem(priv, base + i + 1 * sizeof(u32));
4365                 blink1 =
4366                     iwl3945_read_targ_mem(priv, base + i + 2 * sizeof(u32));
4367                 blink2 =
4368                     iwl3945_read_targ_mem(priv, base + i + 3 * sizeof(u32));
4369                 ilink1 =
4370                     iwl3945_read_targ_mem(priv, base + i + 4 * sizeof(u32));
4371                 ilink2 =
4372                     iwl3945_read_targ_mem(priv, base + i + 5 * sizeof(u32));
4373                 data1 =
4374                     iwl3945_read_targ_mem(priv, base + i + 6 * sizeof(u32));
4375
4376                 IWL_ERROR
4377                     ("%-13s (#%d) %010u 0x%05X 0x%05X 0x%05X 0x%05X %u\n\n",
4378                      desc_lookup(desc), desc, time, blink1, blink2,
4379                      ilink1, ilink2, data1);
4380         }
4381
4382         iwl3945_release_nic_access(priv);
4383
4384 }
4385
4386 #define EVENT_START_OFFSET  (6 * sizeof(u32))
4387
4388 /**
4389  * iwl3945_print_event_log - Dump error event log to syslog
4390  *
4391  * NOTE: Must be called with iwl3945_grab_nic_access() already obtained!
4392  */
4393 static void iwl3945_print_event_log(struct iwl3945_priv *priv, u32 start_idx,
4394                                 u32 num_events, u32 mode)
4395 {
4396         u32 i;
4397         u32 base;       /* SRAM byte address of event log header */
4398         u32 event_size; /* 2 u32s, or 3 u32s if timestamp recorded */
4399         u32 ptr;        /* SRAM byte address of log data */
4400         u32 ev, time, data; /* event log data */
4401
4402         if (num_events == 0)
4403                 return;
4404
4405         base = le32_to_cpu(priv->card_alive.log_event_table_ptr);
4406
4407         if (mode == 0)
4408                 event_size = 2 * sizeof(u32);
4409         else
4410                 event_size = 3 * sizeof(u32);
4411
4412         ptr = base + EVENT_START_OFFSET + (start_idx * event_size);
4413
4414         /* "time" is actually "data" for mode 0 (no timestamp).
4415          * place event id # at far right for easier visual parsing. */
4416         for (i = 0; i < num_events; i++) {
4417                 ev = iwl3945_read_targ_mem(priv, ptr);
4418                 ptr += sizeof(u32);
4419                 time = iwl3945_read_targ_mem(priv, ptr);
4420                 ptr += sizeof(u32);
4421                 if (mode == 0)
4422                         IWL_ERROR("0x%08x\t%04u\n", time, ev); /* data, ev */
4423                 else {
4424                         data = iwl3945_read_targ_mem(priv, ptr);
4425                         ptr += sizeof(u32);
4426                         IWL_ERROR("%010u\t0x%08x\t%04u\n", time, data, ev);
4427                 }
4428         }
4429 }
4430
4431 static void iwl3945_dump_nic_event_log(struct iwl3945_priv *priv)
4432 {
4433         int rc;
4434         u32 base;       /* SRAM byte address of event log header */
4435         u32 capacity;   /* event log capacity in # entries */
4436         u32 mode;       /* 0 - no timestamp, 1 - timestamp recorded */
4437         u32 num_wraps;  /* # times uCode wrapped to top of log */
4438         u32 next_entry; /* index of next entry to be written by uCode */
4439         u32 size;       /* # entries that we'll print */
4440
4441         base = le32_to_cpu(priv->card_alive.log_event_table_ptr);
4442         if (!iwl3945_hw_valid_rtc_data_addr(base)) {
4443                 IWL_ERROR("Invalid event log pointer 0x%08X\n", base);
4444                 return;
4445         }
4446
4447         rc = iwl3945_grab_nic_access(priv);
4448         if (rc) {
4449                 IWL_WARNING("Can not read from adapter at this time.\n");
4450                 return;
4451         }
4452
4453         /* event log header */
4454         capacity = iwl3945_read_targ_mem(priv, base);
4455         mode = iwl3945_read_targ_mem(priv, base + (1 * sizeof(u32)));
4456         num_wraps = iwl3945_read_targ_mem(priv, base + (2 * sizeof(u32)));
4457         next_entry = iwl3945_read_targ_mem(priv, base + (3 * sizeof(u32)));
4458
4459         size = num_wraps ? capacity : next_entry;
4460
4461         /* bail out if nothing in log */
4462         if (size == 0) {
4463                 IWL_ERROR("Start IWL Event Log Dump: nothing in log\n");
4464                 iwl3945_release_nic_access(priv);
4465                 return;
4466         }
4467
4468         IWL_ERROR("Start IWL Event Log Dump: display count %d, wraps %d\n",
4469                   size, num_wraps);
4470
4471         /* if uCode has wrapped back to top of log, start at the oldest entry,
4472          * i.e the next one that uCode would fill. */
4473         if (num_wraps)
4474                 iwl3945_print_event_log(priv, next_entry,
4475                                     capacity - next_entry, mode);
4476
4477         /* (then/else) start at top of log */
4478         iwl3945_print_event_log(priv, 0, next_entry, mode);
4479
4480         iwl3945_release_nic_access(priv);
4481 }
4482
4483 /**
4484  * iwl3945_irq_handle_error - called for HW or SW error interrupt from card
4485  */
4486 static void iwl3945_irq_handle_error(struct iwl3945_priv *priv)
4487 {
4488         /* Set the FW error flag -- cleared on iwl3945_down */
4489         set_bit(STATUS_FW_ERROR, &priv->status);
4490
4491         /* Cancel currently queued command. */
4492         clear_bit(STATUS_HCMD_ACTIVE, &priv->status);
4493
4494 #ifdef CONFIG_IWL3945_DEBUG
4495         if (iwl3945_debug_level & IWL_DL_FW_ERRORS) {
4496                 iwl3945_dump_nic_error_log(priv);
4497                 iwl3945_dump_nic_event_log(priv);
4498                 iwl3945_print_rx_config_cmd(&priv->staging_rxon);
4499         }
4500 #endif
4501
4502         wake_up_interruptible(&priv->wait_command_queue);
4503
4504         /* Keep the restart process from trying to send host
4505          * commands by clearing the INIT status bit */
4506         clear_bit(STATUS_READY, &priv->status);
4507
4508         if (!test_bit(STATUS_EXIT_PENDING, &priv->status)) {
4509                 IWL_DEBUG(IWL_DL_INFO | IWL_DL_FW_ERRORS,
4510                           "Restarting adapter due to uCode error.\n");
4511
4512                 if (iwl3945_is_associated(priv)) {
4513                         memcpy(&priv->recovery_rxon, &priv->active_rxon,
4514                                sizeof(priv->recovery_rxon));
4515                         priv->error_recovering = 1;
4516                 }
4517                 queue_work(priv->workqueue, &priv->restart);
4518         }
4519 }
4520
4521 static void iwl3945_error_recovery(struct iwl3945_priv *priv)
4522 {
4523         unsigned long flags;
4524
4525         memcpy(&priv->staging_rxon, &priv->recovery_rxon,
4526                sizeof(priv->staging_rxon));
4527         priv->staging_rxon.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
4528         iwl3945_commit_rxon(priv);
4529
4530         iwl3945_add_station(priv, priv->bssid, 1, 0);
4531
4532         spin_lock_irqsave(&priv->lock, flags);
4533         priv->assoc_id = le16_to_cpu(priv->staging_rxon.assoc_id);
4534         priv->error_recovering = 0;
4535         spin_unlock_irqrestore(&priv->lock, flags);
4536 }
4537
4538 static void iwl3945_irq_tasklet(struct iwl3945_priv *priv)
4539 {
4540         u32 inta, handled = 0;
4541         u32 inta_fh;
4542         unsigned long flags;
4543 #ifdef CONFIG_IWL3945_DEBUG
4544         u32 inta_mask;
4545 #endif
4546
4547         spin_lock_irqsave(&priv->lock, flags);
4548
4549         /* Ack/clear/reset pending uCode interrupts.
4550          * Note:  Some bits in CSR_INT are "OR" of bits in CSR_FH_INT_STATUS,
4551          *  and will clear only when CSR_FH_INT_STATUS gets cleared. */
4552         inta = iwl3945_read32(priv, CSR_INT);
4553         iwl3945_write32(priv, CSR_INT, inta);
4554
4555         /* Ack/clear/reset pending flow-handler (DMA) interrupts.
4556          * Any new interrupts that happen after this, either while we're
4557          * in this tasklet, or later, will show up in next ISR/tasklet. */
4558         inta_fh = iwl3945_read32(priv, CSR_FH_INT_STATUS);
4559         iwl3945_write32(priv, CSR_FH_INT_STATUS, inta_fh);
4560
4561 #ifdef CONFIG_IWL3945_DEBUG
4562         if (iwl3945_debug_level & IWL_DL_ISR) {
4563                 /* just for debug */
4564                 inta_mask = iwl3945_read32(priv, CSR_INT_MASK);
4565                 IWL_DEBUG_ISR("inta 0x%08x, enabled 0x%08x, fh 0x%08x\n",
4566                               inta, inta_mask, inta_fh);
4567         }
4568 #endif
4569
4570         /* Since CSR_INT and CSR_FH_INT_STATUS reads and clears are not
4571          * atomic, make sure that inta covers all the interrupts that
4572          * we've discovered, even if FH interrupt came in just after
4573          * reading CSR_INT. */
4574         if (inta_fh & CSR39_FH_INT_RX_MASK)
4575                 inta |= CSR_INT_BIT_FH_RX;
4576         if (inta_fh & CSR39_FH_INT_TX_MASK)
4577                 inta |= CSR_INT_BIT_FH_TX;
4578
4579         /* Now service all interrupt bits discovered above. */
4580         if (inta & CSR_INT_BIT_HW_ERR) {
4581                 IWL_ERROR("Microcode HW error detected.  Restarting.\n");
4582
4583                 /* Tell the device to stop sending interrupts */
4584                 iwl3945_disable_interrupts(priv);
4585
4586                 iwl3945_irq_handle_error(priv);
4587
4588                 handled |= CSR_INT_BIT_HW_ERR;
4589
4590                 spin_unlock_irqrestore(&priv->lock, flags);
4591
4592                 return;
4593         }
4594
4595 #ifdef CONFIG_IWL3945_DEBUG
4596         if (iwl3945_debug_level & (IWL_DL_ISR)) {
4597                 /* NIC fires this, but we don't use it, redundant with WAKEUP */
4598                 if (inta & CSR_INT_BIT_SCD)
4599                         IWL_DEBUG_ISR("Scheduler finished to transmit "
4600                                       "the frame/frames.\n");
4601
4602                 /* Alive notification via Rx interrupt will do the real work */
4603                 if (inta & CSR_INT_BIT_ALIVE)
4604                         IWL_DEBUG_ISR("Alive interrupt\n");
4605         }
4606 #endif
4607         /* Safely ignore these bits for debug checks below */
4608         inta &= ~(CSR_INT_BIT_SCD | CSR_INT_BIT_ALIVE);
4609
4610         /* HW RF KILL switch toggled (4965 only) */
4611         if (inta & CSR_INT_BIT_RF_KILL) {
4612                 int hw_rf_kill = 0;
4613                 if (!(iwl3945_read32(priv, CSR_GP_CNTRL) &
4614                                 CSR_GP_CNTRL_REG_FLAG_HW_RF_KILL_SW))
4615                         hw_rf_kill = 1;
4616
4617                 IWL_DEBUG(IWL_DL_INFO | IWL_DL_RF_KILL | IWL_DL_ISR,
4618                                 "RF_KILL bit toggled to %s.\n",
4619                                 hw_rf_kill ? "disable radio":"enable radio");
4620
4621                 /* Queue restart only if RF_KILL switch was set to "kill"
4622                  *   when we loaded driver, and is now set to "enable".
4623                  * After we're Alive, RF_KILL gets handled by
4624                  *   iwl3945_rx_card_state_notif() */
4625                 if (!hw_rf_kill && !test_bit(STATUS_ALIVE, &priv->status)) {
4626                         clear_bit(STATUS_RF_KILL_HW, &priv->status);
4627                         queue_work(priv->workqueue, &priv->restart);
4628                 }
4629
4630                 handled |= CSR_INT_BIT_RF_KILL;
4631         }
4632
4633         /* Chip got too hot and stopped itself (4965 only) */
4634         if (inta & CSR_INT_BIT_CT_KILL) {
4635                 IWL_ERROR("Microcode CT kill error detected.\n");
4636                 handled |= CSR_INT_BIT_CT_KILL;
4637         }
4638
4639         /* Error detected by uCode */
4640         if (inta & CSR_INT_BIT_SW_ERR) {
4641                 IWL_ERROR("Microcode SW error detected.  Restarting 0x%X.\n",
4642                           inta);
4643                 iwl3945_irq_handle_error(priv);
4644                 handled |= CSR_INT_BIT_SW_ERR;
4645         }
4646
4647         /* uCode wakes up after power-down sleep */
4648         if (inta & CSR_INT_BIT_WAKEUP) {
4649                 IWL_DEBUG_ISR("Wakeup interrupt\n");
4650                 iwl3945_rx_queue_update_write_ptr(priv, &priv->rxq);
4651                 iwl3945_tx_queue_update_write_ptr(priv, &priv->txq[0]);
4652                 iwl3945_tx_queue_update_write_ptr(priv, &priv->txq[1]);
4653                 iwl3945_tx_queue_update_write_ptr(priv, &priv->txq[2]);
4654                 iwl3945_tx_queue_update_write_ptr(priv, &priv->txq[3]);
4655                 iwl3945_tx_queue_update_write_ptr(priv, &priv->txq[4]);
4656                 iwl3945_tx_queue_update_write_ptr(priv, &priv->txq[5]);
4657
4658                 handled |= CSR_INT_BIT_WAKEUP;
4659         }
4660
4661         /* All uCode command responses, including Tx command responses,
4662          * Rx "responses" (frame-received notification), and other
4663          * notifications from uCode come through here*/
4664         if (inta & (CSR_INT_BIT_FH_RX | CSR_INT_BIT_SW_RX)) {
4665                 iwl3945_rx_handle(priv);
4666                 handled |= (CSR_INT_BIT_FH_RX | CSR_INT_BIT_SW_RX);
4667         }
4668
4669         if (inta & CSR_INT_BIT_FH_TX) {
4670                 IWL_DEBUG_ISR("Tx interrupt\n");
4671
4672                 iwl3945_write32(priv, CSR_FH_INT_STATUS, (1 << 6));
4673                 if (!iwl3945_grab_nic_access(priv)) {
4674                         iwl3945_write_direct32(priv,
4675                                              FH_TCSR_CREDIT
4676                                              (ALM_FH_SRVC_CHNL), 0x0);
4677                         iwl3945_release_nic_access(priv);
4678                 }
4679                 handled |= CSR_INT_BIT_FH_TX;
4680         }
4681
4682         if (inta & ~handled)
4683                 IWL_ERROR("Unhandled INTA bits 0x%08x\n", inta & ~handled);
4684
4685         if (inta & ~CSR_INI_SET_MASK) {
4686                 IWL_WARNING("Disabled INTA bits 0x%08x were pending\n",
4687                          inta & ~CSR_INI_SET_MASK);
4688                 IWL_WARNING("   with FH_INT = 0x%08x\n", inta_fh);
4689         }
4690
4691         /* Re-enable all interrupts */
4692         iwl3945_enable_interrupts(priv);
4693
4694 #ifdef CONFIG_IWL3945_DEBUG
4695         if (iwl3945_debug_level & (IWL_DL_ISR)) {
4696                 inta = iwl3945_read32(priv, CSR_INT);
4697                 inta_mask = iwl3945_read32(priv, CSR_INT_MASK);
4698                 inta_fh = iwl3945_read32(priv, CSR_FH_INT_STATUS);
4699                 IWL_DEBUG_ISR("End inta 0x%08x, enabled 0x%08x, fh 0x%08x, "
4700                         "flags 0x%08lx\n", inta, inta_mask, inta_fh, flags);
4701         }
4702 #endif
4703         spin_unlock_irqrestore(&priv->lock, flags);
4704 }
4705
4706 static irqreturn_t iwl3945_isr(int irq, void *data)
4707 {
4708         struct iwl3945_priv *priv = data;
4709         u32 inta, inta_mask;
4710         u32 inta_fh;
4711         if (!priv)
4712                 return IRQ_NONE;
4713
4714         spin_lock(&priv->lock);
4715
4716         /* Disable (but don't clear!) interrupts here to avoid
4717          *    back-to-back ISRs and sporadic interrupts from our NIC.
4718          * If we have something to service, the tasklet will re-enable ints.
4719          * If we *don't* have something, we'll re-enable before leaving here. */
4720         inta_mask = iwl3945_read32(priv, CSR_INT_MASK);  /* just for debug */
4721         iwl3945_write32(priv, CSR_INT_MASK, 0x00000000);
4722
4723         /* Discover which interrupts are active/pending */
4724         inta = iwl3945_read32(priv, CSR_INT);
4725         inta_fh = iwl3945_read32(priv, CSR_FH_INT_STATUS);
4726
4727         /* Ignore interrupt if there's nothing in NIC to service.
4728          * This may be due to IRQ shared with another device,
4729          * or due to sporadic interrupts thrown from our NIC. */
4730         if (!inta && !inta_fh) {
4731                 IWL_DEBUG_ISR("Ignore interrupt, inta == 0, inta_fh == 0\n");
4732                 goto none;
4733         }
4734
4735         if ((inta == 0xFFFFFFFF) || ((inta & 0xFFFFFFF0) == 0xa5a5a5a0)) {
4736                 /* Hardware disappeared */
4737                 IWL_WARNING("HARDWARE GONE?? INTA == 0x%080x\n", inta);
4738                 goto unplugged;
4739         }
4740
4741         IWL_DEBUG_ISR("ISR inta 0x%08x, enabled 0x%08x, fh 0x%08x\n",
4742                       inta, inta_mask, inta_fh);
4743
4744         inta &= ~CSR_INT_BIT_SCD;
4745
4746         /* iwl3945_irq_tasklet() will service interrupts and re-enable them */
4747         if (likely(inta || inta_fh))
4748                 tasklet_schedule(&priv->irq_tasklet);
4749 unplugged:
4750         spin_unlock(&priv->lock);
4751
4752         return IRQ_HANDLED;
4753
4754  none:
4755         /* re-enable interrupts here since we don't have anything to service. */
4756         iwl3945_enable_interrupts(priv);
4757         spin_unlock(&priv->lock);
4758         return IRQ_NONE;
4759 }
4760
4761 /************************** EEPROM BANDS ****************************
4762  *
4763  * The iwl3945_eeprom_band definitions below provide the mapping from the
4764  * EEPROM contents to the specific channel number supported for each
4765  * band.
4766  *
4767  * For example, iwl3945_priv->eeprom.band_3_channels[4] from the band_3
4768  * definition below maps to physical channel 42 in the 5.2GHz spectrum.
4769  * The specific geography and calibration information for that channel
4770  * is contained in the eeprom map itself.
4771  *
4772  * During init, we copy the eeprom information and channel map
4773  * information into priv->channel_info_24/52 and priv->channel_map_24/52
4774  *
4775  * channel_map_24/52 provides the index in the channel_info array for a
4776  * given channel.  We have to have two separate maps as there is channel
4777  * overlap with the 2.4GHz and 5.2GHz spectrum as seen in band_1 and
4778  * band_2
4779  *
4780  * A value of 0xff stored in the channel_map indicates that the channel
4781  * is not supported by the hardware at all.
4782  *
4783  * A value of 0xfe in the channel_map indicates that the channel is not
4784  * valid for Tx with the current hardware.  This means that
4785  * while the system can tune and receive on a given channel, it may not
4786  * be able to associate or transmit any frames on that
4787  * channel.  There is no corresponding channel information for that
4788  * entry.
4789  *
4790  *********************************************************************/
4791
4792 /* 2.4 GHz */
4793 static const u8 iwl3945_eeprom_band_1[14] = {
4794         1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14
4795 };
4796
4797 /* 5.2 GHz bands */
4798 static const u8 iwl3945_eeprom_band_2[] = {     /* 4915-5080MHz */
4799         183, 184, 185, 187, 188, 189, 192, 196, 7, 8, 11, 12, 16
4800 };
4801
4802 static const u8 iwl3945_eeprom_band_3[] = {     /* 5170-5320MHz */
4803         34, 36, 38, 40, 42, 44, 46, 48, 52, 56, 60, 64
4804 };
4805
4806 static const u8 iwl3945_eeprom_band_4[] = {     /* 5500-5700MHz */
4807         100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140
4808 };
4809
4810 static const u8 iwl3945_eeprom_band_5[] = {     /* 5725-5825MHz */
4811         145, 149, 153, 157, 161, 165
4812 };
4813
4814 static void iwl3945_init_band_reference(const struct iwl3945_priv *priv, int band,
4815                                     int *eeprom_ch_count,
4816                                     const struct iwl3945_eeprom_channel
4817                                     **eeprom_ch_info,
4818                                     const u8 **eeprom_ch_index)
4819 {
4820         switch (band) {
4821         case 1:         /* 2.4GHz band */
4822                 *eeprom_ch_count = ARRAY_SIZE(iwl3945_eeprom_band_1);
4823                 *eeprom_ch_info = priv->eeprom.band_1_channels;
4824                 *eeprom_ch_index = iwl3945_eeprom_band_1;
4825                 break;
4826         case 2:         /* 4.9GHz band */
4827                 *eeprom_ch_count = ARRAY_SIZE(iwl3945_eeprom_band_2);
4828                 *eeprom_ch_info = priv->eeprom.band_2_channels;
4829                 *eeprom_ch_index = iwl3945_eeprom_band_2;
4830                 break;
4831         case 3:         /* 5.2GHz band */
4832                 *eeprom_ch_count = ARRAY_SIZE(iwl3945_eeprom_band_3);
4833                 *eeprom_ch_info = priv->eeprom.band_3_channels;
4834                 *eeprom_ch_index = iwl3945_eeprom_band_3;
4835                 break;
4836         case 4:         /* 5.5GHz band */
4837                 *eeprom_ch_count = ARRAY_SIZE(iwl3945_eeprom_band_4);
4838                 *eeprom_ch_info = priv->eeprom.band_4_channels;
4839                 *eeprom_ch_index = iwl3945_eeprom_band_4;
4840                 break;
4841         case 5:         /* 5.7GHz band */
4842                 *eeprom_ch_count = ARRAY_SIZE(iwl3945_eeprom_band_5);
4843                 *eeprom_ch_info = priv->eeprom.band_5_channels;
4844                 *eeprom_ch_index = iwl3945_eeprom_band_5;
4845                 break;
4846         default:
4847                 BUG();
4848                 return;
4849         }
4850 }
4851
4852 /**
4853  * iwl3945_get_channel_info - Find driver's private channel info
4854  *
4855  * Based on band and channel number.
4856  */
4857 const struct iwl3945_channel_info *iwl3945_get_channel_info(const struct iwl3945_priv *priv,
4858                                                     enum ieee80211_band band, u16 channel)
4859 {
4860         int i;
4861
4862         switch (band) {
4863         case IEEE80211_BAND_5GHZ:
4864                 for (i = 14; i < priv->channel_count; i++) {
4865                         if (priv->channel_info[i].channel == channel)
4866                                 return &priv->channel_info[i];
4867                 }
4868                 break;
4869
4870         case IEEE80211_BAND_2GHZ:
4871                 if (channel >= 1 && channel <= 14)
4872                         return &priv->channel_info[channel - 1];
4873                 break;
4874         case IEEE80211_NUM_BANDS:
4875                 WARN_ON(1);
4876         }
4877
4878         return NULL;
4879 }
4880
4881 #define CHECK_AND_PRINT(x) ((eeprom_ch_info[ch].flags & EEPROM_CHANNEL_##x) \
4882                             ? # x " " : "")
4883
4884 /**
4885  * iwl3945_init_channel_map - Set up driver's info for all possible channels
4886  */
4887 static int iwl3945_init_channel_map(struct iwl3945_priv *priv)
4888 {
4889         int eeprom_ch_count = 0;
4890         const u8 *eeprom_ch_index = NULL;
4891         const struct iwl3945_eeprom_channel *eeprom_ch_info = NULL;
4892         int band, ch;
4893         struct iwl3945_channel_info *ch_info;
4894
4895         if (priv->channel_count) {
4896                 IWL_DEBUG_INFO("Channel map already initialized.\n");
4897                 return 0;
4898         }
4899
4900         if (priv->eeprom.version < 0x2f) {
4901                 IWL_WARNING("Unsupported EEPROM version: 0x%04X\n",
4902                             priv->eeprom.version);
4903                 return -EINVAL;
4904         }
4905
4906         IWL_DEBUG_INFO("Initializing regulatory info from EEPROM\n");
4907
4908         priv->channel_count =
4909             ARRAY_SIZE(iwl3945_eeprom_band_1) +
4910             ARRAY_SIZE(iwl3945_eeprom_band_2) +
4911             ARRAY_SIZE(iwl3945_eeprom_band_3) +
4912             ARRAY_SIZE(iwl3945_eeprom_band_4) +
4913             ARRAY_SIZE(iwl3945_eeprom_band_5);
4914
4915         IWL_DEBUG_INFO("Parsing data for %d channels.\n", priv->channel_count);
4916
4917         priv->channel_info = kzalloc(sizeof(struct iwl3945_channel_info) *
4918                                      priv->channel_count, GFP_KERNEL);
4919         if (!priv->channel_info) {
4920                 IWL_ERROR("Could not allocate channel_info\n");
4921                 priv->channel_count = 0;
4922                 return -ENOMEM;
4923         }
4924
4925         ch_info = priv->channel_info;
4926
4927         /* Loop through the 5 EEPROM bands adding them in order to the
4928          * channel map we maintain (that contains additional information than
4929          * what just in the EEPROM) */
4930         for (band = 1; band <= 5; band++) {
4931
4932                 iwl3945_init_band_reference(priv, band, &eeprom_ch_count,
4933                                         &eeprom_ch_info, &eeprom_ch_index);
4934
4935                 /* Loop through each band adding each of the channels */
4936                 for (ch = 0; ch < eeprom_ch_count; ch++) {
4937                         ch_info->channel = eeprom_ch_index[ch];
4938                         ch_info->band = (band == 1) ? IEEE80211_BAND_2GHZ :
4939                             IEEE80211_BAND_5GHZ;
4940
4941                         /* permanently store EEPROM's channel regulatory flags
4942                          *   and max power in channel info database. */
4943                         ch_info->eeprom = eeprom_ch_info[ch];
4944
4945                         /* Copy the run-time flags so they are there even on
4946                          * invalid channels */
4947                         ch_info->flags = eeprom_ch_info[ch].flags;
4948
4949                         if (!(is_channel_valid(ch_info))) {
4950                                 IWL_DEBUG_INFO("Ch. %d Flags %x [%sGHz] - "
4951                                                "No traffic\n",
4952                                                ch_info->channel,
4953                                                ch_info->flags,
4954                                                is_channel_a_band(ch_info) ?
4955                                                "5.2" : "2.4");
4956                                 ch_info++;
4957                                 continue;
4958                         }
4959
4960                         /* Initialize regulatory-based run-time data */
4961                         ch_info->max_power_avg = ch_info->curr_txpow =
4962                             eeprom_ch_info[ch].max_power_avg;
4963                         ch_info->scan_power = eeprom_ch_info[ch].max_power_avg;
4964                         ch_info->min_power = 0;
4965
4966                         IWL_DEBUG_INFO("Ch. %d [%sGHz] %s%s%s%s%s%s%s(0x%02x"
4967                                        " %ddBm): Ad-Hoc %ssupported\n",
4968                                        ch_info->channel,
4969                                        is_channel_a_band(ch_info) ?
4970                                        "5.2" : "2.4",
4971                                        CHECK_AND_PRINT(VALID),
4972                                        CHECK_AND_PRINT(IBSS),
4973                                        CHECK_AND_PRINT(ACTIVE),
4974                                        CHECK_AND_PRINT(RADAR),
4975                                        CHECK_AND_PRINT(WIDE),
4976                                        CHECK_AND_PRINT(NARROW),
4977                                        CHECK_AND_PRINT(DFS),
4978                                        eeprom_ch_info[ch].flags,
4979                                        eeprom_ch_info[ch].max_power_avg,
4980                                        ((eeprom_ch_info[ch].
4981                                          flags & EEPROM_CHANNEL_IBSS)
4982                                         && !(eeprom_ch_info[ch].
4983                                              flags & EEPROM_CHANNEL_RADAR))
4984                                        ? "" : "not ");
4985
4986                         /* Set the user_txpower_limit to the highest power
4987                          * supported by any channel */
4988                         if (eeprom_ch_info[ch].max_power_avg >
4989                             priv->user_txpower_limit)
4990                                 priv->user_txpower_limit =
4991                                     eeprom_ch_info[ch].max_power_avg;
4992
4993                         ch_info++;
4994                 }
4995         }
4996
4997         /* Set up txpower settings in driver for all channels */
4998         if (iwl3945_txpower_set_from_eeprom(priv))
4999                 return -EIO;
5000
5001         return 0;
5002 }
5003
5004 /*
5005  * iwl3945_free_channel_map - undo allocations in iwl3945_init_channel_map
5006  */
5007 static void iwl3945_free_channel_map(struct iwl3945_priv *priv)
5008 {
5009         kfree(priv->channel_info);
5010         priv->channel_count = 0;
5011 }
5012
5013 /* For active scan, listen ACTIVE_DWELL_TIME (msec) on each channel after
5014  * sending probe req.  This should be set long enough to hear probe responses
5015  * from more than one AP.  */
5016 #define IWL_ACTIVE_DWELL_TIME_24    (20)        /* all times in msec */
5017 #define IWL_ACTIVE_DWELL_TIME_52    (10)
5018
5019 /* For faster active scanning, scan will move to the next channel if fewer than
5020  * PLCP_QUIET_THRESH packets are heard on this channel within
5021  * ACTIVE_QUIET_TIME after sending probe request.  This shortens the dwell
5022  * time if it's a quiet channel (nothing responded to our probe, and there's
5023  * no other traffic).
5024  * Disable "quiet" feature by setting PLCP_QUIET_THRESH to 0. */
5025 #define IWL_PLCP_QUIET_THRESH       __constant_cpu_to_le16(1)   /* packets */
5026 #define IWL_ACTIVE_QUIET_TIME       __constant_cpu_to_le16(5)   /* msec */
5027
5028 /* For passive scan, listen PASSIVE_DWELL_TIME (msec) on each channel.
5029  * Must be set longer than active dwell time.
5030  * For the most reliable scan, set > AP beacon interval (typically 100msec). */
5031 #define IWL_PASSIVE_DWELL_TIME_24   (20)        /* all times in msec */
5032 #define IWL_PASSIVE_DWELL_TIME_52   (10)
5033 #define IWL_PASSIVE_DWELL_BASE      (100)
5034 #define IWL_CHANNEL_TUNE_TIME       5
5035
5036 static inline u16 iwl3945_get_active_dwell_time(struct iwl3945_priv *priv,
5037                                                 enum ieee80211_band band)
5038 {
5039         if (band == IEEE80211_BAND_5GHZ)
5040                 return IWL_ACTIVE_DWELL_TIME_52;
5041         else
5042                 return IWL_ACTIVE_DWELL_TIME_24;
5043 }
5044
5045 static u16 iwl3945_get_passive_dwell_time(struct iwl3945_priv *priv,
5046                                           enum ieee80211_band band)
5047 {
5048         u16 active = iwl3945_get_active_dwell_time(priv, band);
5049         u16 passive = (band == IEEE80211_BAND_2GHZ) ?
5050             IWL_PASSIVE_DWELL_BASE + IWL_PASSIVE_DWELL_TIME_24 :
5051             IWL_PASSIVE_DWELL_BASE + IWL_PASSIVE_DWELL_TIME_52;
5052
5053         if (iwl3945_is_associated(priv)) {
5054                 /* If we're associated, we clamp the maximum passive
5055                  * dwell time to be 98% of the beacon interval (minus
5056                  * 2 * channel tune time) */
5057                 passive = priv->beacon_int;
5058                 if ((passive > IWL_PASSIVE_DWELL_BASE) || !passive)
5059                         passive = IWL_PASSIVE_DWELL_BASE;
5060                 passive = (passive * 98) / 100 - IWL_CHANNEL_TUNE_TIME * 2;
5061         }
5062
5063         if (passive <= active)
5064                 passive = active + 1;
5065
5066         return passive;
5067 }
5068
5069 static int iwl3945_get_channels_for_scan(struct iwl3945_priv *priv,
5070                                          enum ieee80211_band band,
5071                                      u8 is_active, u8 direct_mask,
5072                                      struct iwl3945_scan_channel *scan_ch)
5073 {
5074         const struct ieee80211_channel *channels = NULL;
5075         const struct ieee80211_supported_band *sband;
5076         const struct iwl3945_channel_info *ch_info;
5077         u16 passive_dwell = 0;
5078         u16 active_dwell = 0;
5079         int added, i;
5080
5081         sband = iwl3945_get_band(priv, band);
5082         if (!sband)
5083                 return 0;
5084
5085         channels = sband->channels;
5086
5087         active_dwell = iwl3945_get_active_dwell_time(priv, band);
5088         passive_dwell = iwl3945_get_passive_dwell_time(priv, band);
5089
5090         for (i = 0, added = 0; i < sband->n_channels; i++) {
5091                 if (channels[i].hw_value ==
5092                     le16_to_cpu(priv->active_rxon.channel)) {
5093                         if (iwl3945_is_associated(priv)) {
5094                                 IWL_DEBUG_SCAN
5095                                     ("Skipping current channel %d\n",
5096                                      le16_to_cpu(priv->active_rxon.channel));
5097                                 continue;
5098                         }
5099                 } else if (priv->only_active_channel)
5100                         continue;
5101
5102                 scan_ch->channel = channels[i].hw_value;
5103
5104                 ch_info = iwl3945_get_channel_info(priv, band, scan_ch->channel);
5105                 if (!is_channel_valid(ch_info)) {
5106                         IWL_DEBUG_SCAN("Channel %d is INVALID for this SKU.\n",
5107                                        scan_ch->channel);
5108                         continue;
5109                 }
5110
5111                 if (!is_active || is_channel_passive(ch_info) ||
5112                     (channels[i].flags & IEEE80211_CHAN_PASSIVE_SCAN))
5113                         scan_ch->type = 0;      /* passive */
5114                 else
5115                         scan_ch->type = 1;      /* active */
5116
5117                 if (scan_ch->type & 1)
5118                         scan_ch->type |= (direct_mask << 1);
5119
5120                 if (is_channel_narrow(ch_info))
5121                         scan_ch->type |= (1 << 7);
5122
5123                 scan_ch->active_dwell = cpu_to_le16(active_dwell);
5124                 scan_ch->passive_dwell = cpu_to_le16(passive_dwell);
5125
5126                 /* Set txpower levels to defaults */
5127                 scan_ch->tpc.dsp_atten = 110;
5128                 /* scan_pwr_info->tpc.dsp_atten; */
5129
5130                 /*scan_pwr_info->tpc.tx_gain; */
5131                 if (band == IEEE80211_BAND_5GHZ)
5132                         scan_ch->tpc.tx_gain = ((1 << 5) | (3 << 3)) | 3;
5133                 else {
5134                         scan_ch->tpc.tx_gain = ((1 << 5) | (5 << 3));
5135                         /* NOTE: if we were doing 6Mb OFDM for scans we'd use
5136                          * power level:
5137                          * scan_ch->tpc.tx_gain = ((1 << 5) | (2 << 3)) | 3;
5138                          */
5139                 }
5140
5141                 IWL_DEBUG_SCAN("Scanning %d [%s %d]\n",
5142                                scan_ch->channel,
5143                                (scan_ch->type & 1) ? "ACTIVE" : "PASSIVE",
5144                                (scan_ch->type & 1) ?
5145                                active_dwell : passive_dwell);
5146
5147                 scan_ch++;
5148                 added++;
5149         }
5150
5151         IWL_DEBUG_SCAN("total channels to scan %d \n", added);
5152         return added;
5153 }
5154
5155 static void iwl3945_init_hw_rates(struct iwl3945_priv *priv,
5156                               struct ieee80211_rate *rates)
5157 {
5158         int i;
5159
5160         for (i = 0; i < IWL_RATE_COUNT; i++) {
5161                 rates[i].bitrate = iwl3945_rates[i].ieee * 5;
5162                 rates[i].hw_value = i; /* Rate scaling will work on indexes */
5163                 rates[i].hw_value_short = i;
5164                 rates[i].flags = 0;
5165                 if ((i > IWL_LAST_OFDM_RATE) || (i < IWL_FIRST_OFDM_RATE)) {
5166                         /*
5167                          * If CCK != 1M then set short preamble rate flag.
5168                          */
5169                         rates[i].flags |= (iwl3945_rates[i].plcp == 10) ?
5170                                 0 : IEEE80211_RATE_SHORT_PREAMBLE;
5171                 }
5172         }
5173 }
5174
5175 /**
5176  * iwl3945_init_geos - Initialize mac80211's geo/channel info based from eeprom
5177  */
5178 static int iwl3945_init_geos(struct iwl3945_priv *priv)
5179 {
5180         struct iwl3945_channel_info *ch;
5181         struct ieee80211_supported_band *sband;
5182         struct ieee80211_channel *channels;
5183         struct ieee80211_channel *geo_ch;
5184         struct ieee80211_rate *rates;
5185         int i = 0;
5186
5187         if (priv->bands[IEEE80211_BAND_2GHZ].n_bitrates ||
5188             priv->bands[IEEE80211_BAND_5GHZ].n_bitrates) {
5189                 IWL_DEBUG_INFO("Geography modes already initialized.\n");
5190                 set_bit(STATUS_GEO_CONFIGURED, &priv->status);
5191                 return 0;
5192         }
5193
5194         channels = kzalloc(sizeof(struct ieee80211_channel) *
5195                            priv->channel_count, GFP_KERNEL);
5196         if (!channels)
5197                 return -ENOMEM;
5198
5199         rates = kzalloc((sizeof(struct ieee80211_rate) * (IWL_RATE_COUNT + 1)),
5200                         GFP_KERNEL);
5201         if (!rates) {
5202                 kfree(channels);
5203                 return -ENOMEM;
5204         }
5205
5206         /* 5.2GHz channels start after the 2.4GHz channels */
5207         sband = &priv->bands[IEEE80211_BAND_5GHZ];
5208         sband->channels = &channels[ARRAY_SIZE(iwl3945_eeprom_band_1)];
5209         /* just OFDM */
5210         sband->bitrates = &rates[IWL_FIRST_OFDM_RATE];
5211         sband->n_bitrates = IWL_RATE_COUNT - IWL_FIRST_OFDM_RATE;
5212
5213         sband = &priv->bands[IEEE80211_BAND_2GHZ];
5214         sband->channels = channels;
5215         /* OFDM & CCK */
5216         sband->bitrates = rates;
5217         sband->n_bitrates = IWL_RATE_COUNT;
5218
5219         priv->ieee_channels = channels;
5220         priv->ieee_rates = rates;
5221
5222         iwl3945_init_hw_rates(priv, rates);
5223
5224         for (i = 0;  i < priv->channel_count; i++) {
5225                 ch = &priv->channel_info[i];
5226
5227                 /* FIXME: might be removed if scan is OK*/
5228                 if (!is_channel_valid(ch))
5229                         continue;
5230
5231                 if (is_channel_a_band(ch))
5232                         sband =  &priv->bands[IEEE80211_BAND_5GHZ];
5233                 else
5234                         sband =  &priv->bands[IEEE80211_BAND_2GHZ];
5235
5236                 geo_ch = &sband->channels[sband->n_channels++];
5237
5238                 geo_ch->center_freq = ieee80211_channel_to_frequency(ch->channel);
5239                 geo_ch->max_power = ch->max_power_avg;
5240                 geo_ch->max_antenna_gain = 0xff;
5241                 geo_ch->hw_value = ch->channel;
5242
5243                 if (is_channel_valid(ch)) {
5244                         if (!(ch->flags & EEPROM_CHANNEL_IBSS))
5245                                 geo_ch->flags |= IEEE80211_CHAN_NO_IBSS;
5246
5247                         if (!(ch->flags & EEPROM_CHANNEL_ACTIVE))
5248                                 geo_ch->flags |= IEEE80211_CHAN_PASSIVE_SCAN;
5249
5250                         if (ch->flags & EEPROM_CHANNEL_RADAR)
5251                                 geo_ch->flags |= IEEE80211_CHAN_RADAR;
5252
5253                         if (ch->max_power_avg > priv->max_channel_txpower_limit)
5254                                 priv->max_channel_txpower_limit =
5255                                     ch->max_power_avg;
5256                 } else {
5257                         geo_ch->flags |= IEEE80211_CHAN_DISABLED;
5258                 }
5259
5260                 /* Save flags for reg domain usage */
5261                 geo_ch->orig_flags = geo_ch->flags;
5262
5263                 IWL_DEBUG_INFO("Channel %d Freq=%d[%sGHz] %s flag=0%X\n",
5264                                 ch->channel, geo_ch->center_freq,
5265                                 is_channel_a_band(ch) ?  "5.2" : "2.4",
5266                                 geo_ch->flags & IEEE80211_CHAN_DISABLED ?
5267                                 "restricted" : "valid",
5268                                  geo_ch->flags);
5269         }
5270
5271         if ((priv->bands[IEEE80211_BAND_5GHZ].n_channels == 0) &&
5272              priv->cfg->sku & IWL_SKU_A) {
5273                 printk(KERN_INFO DRV_NAME
5274                        ": Incorrectly detected BG card as ABG.  Please send "
5275                        "your PCI ID 0x%04X:0x%04X to maintainer.\n",
5276                        priv->pci_dev->device, priv->pci_dev->subsystem_device);
5277                  priv->cfg->sku &= ~IWL_SKU_A;
5278         }
5279
5280         printk(KERN_INFO DRV_NAME
5281                ": Tunable channels: %d 802.11bg, %d 802.11a channels\n",
5282                priv->bands[IEEE80211_BAND_2GHZ].n_channels,
5283                priv->bands[IEEE80211_BAND_5GHZ].n_channels);
5284
5285         priv->hw->wiphy->bands[IEEE80211_BAND_2GHZ] = &priv->bands[IEEE80211_BAND_2GHZ];
5286         priv->hw->wiphy->bands[IEEE80211_BAND_5GHZ] = &priv->bands[IEEE80211_BAND_5GHZ];
5287
5288         set_bit(STATUS_GEO_CONFIGURED, &priv->status);
5289
5290         return 0;
5291 }
5292
5293 /*
5294  * iwl3945_free_geos - undo allocations in iwl3945_init_geos
5295  */
5296 static void iwl3945_free_geos(struct iwl3945_priv *priv)
5297 {
5298         kfree(priv->ieee_channels);
5299         kfree(priv->ieee_rates);
5300         clear_bit(STATUS_GEO_CONFIGURED, &priv->status);
5301 }
5302
5303 /******************************************************************************
5304  *
5305  * uCode download functions
5306  *
5307  ******************************************************************************/
5308
5309 static void iwl3945_dealloc_ucode_pci(struct iwl3945_priv *priv)
5310 {
5311         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_code);
5312         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_data);
5313         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_data_backup);
5314         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_init);
5315         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_init_data);
5316         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_boot);
5317 }
5318
5319 /**
5320  * iwl3945_verify_inst_full - verify runtime uCode image in card vs. host,
5321  *     looking at all data.
5322  */
5323 static int iwl3945_verify_inst_full(struct iwl3945_priv *priv, __le32 * image, u32 len)
5324 {
5325         u32 val;
5326         u32 save_len = len;
5327         int rc = 0;
5328         u32 errcnt;
5329
5330         IWL_DEBUG_INFO("ucode inst image size is %u\n", len);
5331
5332         rc = iwl3945_grab_nic_access(priv);
5333         if (rc)
5334                 return rc;
5335
5336         iwl3945_write_direct32(priv, HBUS_TARG_MEM_RADDR, RTC_INST_LOWER_BOUND);
5337
5338         errcnt = 0;
5339         for (; len > 0; len -= sizeof(u32), image++) {
5340                 /* read data comes through single port, auto-incr addr */
5341                 /* NOTE: Use the debugless read so we don't flood kernel log
5342                  * if IWL_DL_IO is set */
5343                 val = _iwl3945_read_direct32(priv, HBUS_TARG_MEM_RDAT);
5344                 if (val != le32_to_cpu(*image)) {
5345                         IWL_ERROR("uCode INST section is invalid at "
5346                                   "offset 0x%x, is 0x%x, s/b 0x%x\n",
5347                                   save_len - len, val, le32_to_cpu(*image));
5348                         rc = -EIO;
5349                         errcnt++;
5350                         if (errcnt >= 20)
5351                                 break;
5352                 }
5353         }
5354
5355         iwl3945_release_nic_access(priv);
5356
5357         if (!errcnt)
5358                 IWL_DEBUG_INFO("ucode image in INSTRUCTION memory is good\n");
5359
5360         return rc;
5361 }
5362
5363
5364 /**
5365  * iwl3945_verify_inst_sparse - verify runtime uCode image in card vs. host,
5366  *   using sample data 100 bytes apart.  If these sample points are good,
5367  *   it's a pretty good bet that everything between them is good, too.
5368  */
5369 static int iwl3945_verify_inst_sparse(struct iwl3945_priv *priv, __le32 *image, u32 len)
5370 {
5371         u32 val;
5372         int rc = 0;
5373         u32 errcnt = 0;
5374         u32 i;
5375
5376         IWL_DEBUG_INFO("ucode inst image size is %u\n", len);
5377
5378         rc = iwl3945_grab_nic_access(priv);
5379         if (rc)
5380                 return rc;
5381
5382         for (i = 0; i < len; i += 100, image += 100/sizeof(u32)) {
5383                 /* read data comes through single port, auto-incr addr */
5384                 /* NOTE: Use the debugless read so we don't flood kernel log
5385                  * if IWL_DL_IO is set */
5386                 iwl3945_write_direct32(priv, HBUS_TARG_MEM_RADDR,
5387                         i + RTC_INST_LOWER_BOUND);
5388                 val = _iwl3945_read_direct32(priv, HBUS_TARG_MEM_RDAT);
5389                 if (val != le32_to_cpu(*image)) {
5390 #if 0 /* Enable this if you want to see details */
5391                         IWL_ERROR("uCode INST section is invalid at "
5392                                   "offset 0x%x, is 0x%x, s/b 0x%x\n",
5393                                   i, val, *image);
5394 #endif
5395                         rc = -EIO;
5396                         errcnt++;
5397                         if (errcnt >= 3)
5398                                 break;
5399                 }
5400         }
5401
5402         iwl3945_release_nic_access(priv);
5403
5404         return rc;
5405 }
5406
5407
5408 /**
5409  * iwl3945_verify_ucode - determine which instruction image is in SRAM,
5410  *    and verify its contents
5411  */
5412 static int iwl3945_verify_ucode(struct iwl3945_priv *priv)
5413 {
5414         __le32 *image;
5415         u32 len;
5416         int rc = 0;
5417
5418         /* Try bootstrap */
5419         image = (__le32 *)priv->ucode_boot.v_addr;
5420         len = priv->ucode_boot.len;
5421         rc = iwl3945_verify_inst_sparse(priv, image, len);
5422         if (rc == 0) {
5423                 IWL_DEBUG_INFO("Bootstrap uCode is good in inst SRAM\n");
5424                 return 0;
5425         }
5426
5427         /* Try initialize */
5428         image = (__le32 *)priv->ucode_init.v_addr;
5429         len = priv->ucode_init.len;
5430         rc = iwl3945_verify_inst_sparse(priv, image, len);
5431         if (rc == 0) {
5432                 IWL_DEBUG_INFO("Initialize uCode is good in inst SRAM\n");
5433                 return 0;
5434         }
5435
5436         /* Try runtime/protocol */
5437         image = (__le32 *)priv->ucode_code.v_addr;
5438         len = priv->ucode_code.len;
5439         rc = iwl3945_verify_inst_sparse(priv, image, len);
5440         if (rc == 0) {
5441                 IWL_DEBUG_INFO("Runtime uCode is good in inst SRAM\n");
5442                 return 0;
5443         }
5444
5445         IWL_ERROR("NO VALID UCODE IMAGE IN INSTRUCTION SRAM!!\n");
5446
5447         /* Since nothing seems to match, show first several data entries in
5448          * instruction SRAM, so maybe visual inspection will give a clue.
5449          * Selection of bootstrap image (vs. other images) is arbitrary. */
5450         image = (__le32 *)priv->ucode_boot.v_addr;
5451         len = priv->ucode_boot.len;
5452         rc = iwl3945_verify_inst_full(priv, image, len);
5453
5454         return rc;
5455 }
5456
5457
5458 /* check contents of special bootstrap uCode SRAM */
5459 static int iwl3945_verify_bsm(struct iwl3945_priv *priv)
5460 {
5461         __le32 *image = priv->ucode_boot.v_addr;
5462         u32 len = priv->ucode_boot.len;
5463         u32 reg;
5464         u32 val;
5465
5466         IWL_DEBUG_INFO("Begin verify bsm\n");
5467
5468         /* verify BSM SRAM contents */
5469         val = iwl3945_read_prph(priv, BSM_WR_DWCOUNT_REG);
5470         for (reg = BSM_SRAM_LOWER_BOUND;
5471              reg < BSM_SRAM_LOWER_BOUND + len;
5472              reg += sizeof(u32), image ++) {
5473                 val = iwl3945_read_prph(priv, reg);
5474                 if (val != le32_to_cpu(*image)) {
5475                         IWL_ERROR("BSM uCode verification failed at "
5476                                   "addr 0x%08X+%u (of %u), is 0x%x, s/b 0x%x\n",
5477                                   BSM_SRAM_LOWER_BOUND,
5478                                   reg - BSM_SRAM_LOWER_BOUND, len,
5479                                   val, le32_to_cpu(*image));
5480                         return -EIO;
5481                 }
5482         }
5483
5484         IWL_DEBUG_INFO("BSM bootstrap uCode image OK\n");
5485
5486         return 0;
5487 }
5488
5489 /**
5490  * iwl3945_load_bsm - Load bootstrap instructions
5491  *
5492  * BSM operation:
5493  *
5494  * The Bootstrap State Machine (BSM) stores a short bootstrap uCode program
5495  * in special SRAM that does not power down during RFKILL.  When powering back
5496  * up after power-saving sleeps (or during initial uCode load), the BSM loads
5497  * the bootstrap program into the on-board processor, and starts it.
5498  *
5499  * The bootstrap program loads (via DMA) instructions and data for a new
5500  * program from host DRAM locations indicated by the host driver in the
5501  * BSM_DRAM_* registers.  Once the new program is loaded, it starts
5502  * automatically.
5503  *
5504  * When initializing the NIC, the host driver points the BSM to the
5505  * "initialize" uCode image.  This uCode sets up some internal data, then
5506  * notifies host via "initialize alive" that it is complete.
5507  *
5508  * The host then replaces the BSM_DRAM_* pointer values to point to the
5509  * normal runtime uCode instructions and a backup uCode data cache buffer
5510  * (filled initially with starting data values for the on-board processor),
5511  * then triggers the "initialize" uCode to load and launch the runtime uCode,
5512  * which begins normal operation.
5513  *
5514  * When doing a power-save shutdown, runtime uCode saves data SRAM into
5515  * the backup data cache in DRAM before SRAM is powered down.
5516  *
5517  * When powering back up, the BSM loads the bootstrap program.  This reloads
5518  * the runtime uCode instructions and the backup data cache into SRAM,
5519  * and re-launches the runtime uCode from where it left off.
5520  */
5521 static int iwl3945_load_bsm(struct iwl3945_priv *priv)
5522 {
5523         __le32 *image = priv->ucode_boot.v_addr;
5524         u32 len = priv->ucode_boot.len;
5525         dma_addr_t pinst;
5526         dma_addr_t pdata;
5527         u32 inst_len;
5528         u32 data_len;
5529         int rc;
5530         int i;
5531         u32 done;
5532         u32 reg_offset;
5533
5534         IWL_DEBUG_INFO("Begin load bsm\n");
5535
5536         /* make sure bootstrap program is no larger than BSM's SRAM size */
5537         if (len > IWL_MAX_BSM_SIZE)
5538                 return -EINVAL;
5539
5540         /* Tell bootstrap uCode where to find the "Initialize" uCode
5541          *   in host DRAM ... host DRAM physical address bits 31:0 for 3945.
5542          * NOTE:  iwl3945_initialize_alive_start() will replace these values,
5543          *        after the "initialize" uCode has run, to point to
5544          *        runtime/protocol instructions and backup data cache. */
5545         pinst = priv->ucode_init.p_addr;
5546         pdata = priv->ucode_init_data.p_addr;
5547         inst_len = priv->ucode_init.len;
5548         data_len = priv->ucode_init_data.len;
5549
5550         rc = iwl3945_grab_nic_access(priv);
5551         if (rc)
5552                 return rc;
5553
5554         iwl3945_write_prph(priv, BSM_DRAM_INST_PTR_REG, pinst);
5555         iwl3945_write_prph(priv, BSM_DRAM_DATA_PTR_REG, pdata);
5556         iwl3945_write_prph(priv, BSM_DRAM_INST_BYTECOUNT_REG, inst_len);
5557         iwl3945_write_prph(priv, BSM_DRAM_DATA_BYTECOUNT_REG, data_len);
5558
5559         /* Fill BSM memory with bootstrap instructions */
5560         for (reg_offset = BSM_SRAM_LOWER_BOUND;
5561              reg_offset < BSM_SRAM_LOWER_BOUND + len;
5562              reg_offset += sizeof(u32), image++)
5563                 _iwl3945_write_prph(priv, reg_offset,
5564                                           le32_to_cpu(*image));
5565
5566         rc = iwl3945_verify_bsm(priv);
5567         if (rc) {
5568                 iwl3945_release_nic_access(priv);
5569                 return rc;
5570         }
5571
5572         /* Tell BSM to copy from BSM SRAM into instruction SRAM, when asked */
5573         iwl3945_write_prph(priv, BSM_WR_MEM_SRC_REG, 0x0);
5574         iwl3945_write_prph(priv, BSM_WR_MEM_DST_REG,
5575                                  RTC_INST_LOWER_BOUND);
5576         iwl3945_write_prph(priv, BSM_WR_DWCOUNT_REG, len / sizeof(u32));
5577
5578         /* Load bootstrap code into instruction SRAM now,
5579          *   to prepare to load "initialize" uCode */
5580         iwl3945_write_prph(priv, BSM_WR_CTRL_REG,
5581                 BSM_WR_CTRL_REG_BIT_START);
5582
5583         /* Wait for load of bootstrap uCode to finish */
5584         for (i = 0; i < 100; i++) {
5585                 done = iwl3945_read_prph(priv, BSM_WR_CTRL_REG);
5586                 if (!(done & BSM_WR_CTRL_REG_BIT_START))
5587                         break;
5588                 udelay(10);
5589         }
5590         if (i < 100)
5591                 IWL_DEBUG_INFO("BSM write complete, poll %d iterations\n", i);
5592         else {
5593                 IWL_ERROR("BSM write did not complete!\n");
5594                 return -EIO;
5595         }
5596
5597         /* Enable future boot loads whenever power management unit triggers it
5598          *   (e.g. when powering back up after power-save shutdown) */
5599         iwl3945_write_prph(priv, BSM_WR_CTRL_REG,
5600                 BSM_WR_CTRL_REG_BIT_START_EN);
5601
5602         iwl3945_release_nic_access(priv);
5603
5604         return 0;
5605 }
5606
5607 static void iwl3945_nic_start(struct iwl3945_priv *priv)
5608 {
5609         /* Remove all resets to allow NIC to operate */
5610         iwl3945_write32(priv, CSR_RESET, 0);
5611 }
5612
5613 /**
5614  * iwl3945_read_ucode - Read uCode images from disk file.
5615  *
5616  * Copy into buffers for card to fetch via bus-mastering
5617  */
5618 static int iwl3945_read_ucode(struct iwl3945_priv *priv)
5619 {
5620         struct iwl3945_ucode *ucode;
5621         int ret = 0;
5622         const struct firmware *ucode_raw;
5623         /* firmware file name contains uCode/driver compatibility version */
5624         const char *name = "iwlwifi-3945" IWL3945_UCODE_API ".ucode";
5625         u8 *src;
5626         size_t len;
5627         u32 ver, inst_size, data_size, init_size, init_data_size, boot_size;
5628
5629         /* Ask kernel firmware_class module to get the boot firmware off disk.
5630          * request_firmware() is synchronous, file is in memory on return. */
5631         ret = request_firmware(&ucode_raw, name, &priv->pci_dev->dev);
5632         if (ret < 0) {
5633                 IWL_ERROR("%s firmware file req failed: Reason %d\n",
5634                                 name, ret);
5635                 goto error;
5636         }
5637
5638         IWL_DEBUG_INFO("Got firmware '%s' file (%zd bytes) from disk\n",
5639                        name, ucode_raw->size);
5640
5641         /* Make sure that we got at least our header! */
5642         if (ucode_raw->size < sizeof(*ucode)) {
5643                 IWL_ERROR("File size way too small!\n");
5644                 ret = -EINVAL;
5645                 goto err_release;
5646         }
5647
5648         /* Data from ucode file:  header followed by uCode images */
5649         ucode = (void *)ucode_raw->data;
5650
5651         ver = le32_to_cpu(ucode->ver);
5652         inst_size = le32_to_cpu(ucode->inst_size);
5653         data_size = le32_to_cpu(ucode->data_size);
5654         init_size = le32_to_cpu(ucode->init_size);
5655         init_data_size = le32_to_cpu(ucode->init_data_size);
5656         boot_size = le32_to_cpu(ucode->boot_size);
5657
5658         IWL_DEBUG_INFO("f/w package hdr ucode version = 0x%x\n", ver);
5659         IWL_DEBUG_INFO("f/w package hdr runtime inst size = %u\n", inst_size);
5660         IWL_DEBUG_INFO("f/w package hdr runtime data size = %u\n", data_size);
5661         IWL_DEBUG_INFO("f/w package hdr init inst size = %u\n", init_size);
5662         IWL_DEBUG_INFO("f/w package hdr init data size = %u\n", init_data_size);
5663         IWL_DEBUG_INFO("f/w package hdr boot inst size = %u\n", boot_size);
5664
5665         /* Verify size of file vs. image size info in file's header */
5666         if (ucode_raw->size < sizeof(*ucode) +
5667                 inst_size + data_size + init_size +
5668                 init_data_size + boot_size) {
5669
5670                 IWL_DEBUG_INFO("uCode file size %d too small\n",
5671                                (int)ucode_raw->size);
5672                 ret = -EINVAL;
5673                 goto err_release;
5674         }
5675
5676         /* Verify that uCode images will fit in card's SRAM */
5677         if (inst_size > IWL_MAX_INST_SIZE) {
5678                 IWL_DEBUG_INFO("uCode instr len %d too large to fit in\n",
5679                                inst_size);
5680                 ret = -EINVAL;
5681                 goto err_release;
5682         }
5683
5684         if (data_size > IWL_MAX_DATA_SIZE) {
5685                 IWL_DEBUG_INFO("uCode data len %d too large to fit in\n",
5686                                data_size);
5687                 ret = -EINVAL;
5688                 goto err_release;
5689         }
5690         if (init_size > IWL_MAX_INST_SIZE) {
5691                 IWL_DEBUG_INFO("uCode init instr len %d too large to fit in\n",
5692                                 init_size);
5693                 ret = -EINVAL;
5694                 goto err_release;
5695         }
5696         if (init_data_size > IWL_MAX_DATA_SIZE) {
5697                 IWL_DEBUG_INFO("uCode init data len %d too large to fit in\n",
5698                                 init_data_size);
5699                 ret = -EINVAL;
5700                 goto err_release;
5701         }
5702         if (boot_size > IWL_MAX_BSM_SIZE) {
5703                 IWL_DEBUG_INFO("uCode boot instr len %d too large to fit in\n",
5704                                 boot_size);
5705                 ret = -EINVAL;
5706                 goto err_release;
5707         }
5708
5709         /* Allocate ucode buffers for card's bus-master loading ... */
5710
5711         /* Runtime instructions and 2 copies of data:
5712          * 1) unmodified from disk
5713          * 2) backup cache for save/restore during power-downs */
5714         priv->ucode_code.len = inst_size;
5715         iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_code);
5716
5717         priv->ucode_data.len = data_size;
5718         iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_data);
5719
5720         priv->ucode_data_backup.len = data_size;
5721         iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_data_backup);
5722
5723         if (!priv->ucode_code.v_addr || !priv->ucode_data.v_addr ||
5724             !priv->ucode_data_backup.v_addr)
5725                 goto err_pci_alloc;
5726
5727         /* Initialization instructions and data */
5728         if (init_size && init_data_size) {
5729                 priv->ucode_init.len = init_size;
5730                 iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_init);
5731
5732                 priv->ucode_init_data.len = init_data_size;
5733                 iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_init_data);
5734
5735                 if (!priv->ucode_init.v_addr || !priv->ucode_init_data.v_addr)
5736                         goto err_pci_alloc;
5737         }
5738
5739         /* Bootstrap (instructions only, no data) */
5740         if (boot_size) {
5741                 priv->ucode_boot.len = boot_size;
5742                 iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_boot);
5743
5744                 if (!priv->ucode_boot.v_addr)
5745                         goto err_pci_alloc;
5746         }
5747
5748         /* Copy images into buffers for card's bus-master reads ... */
5749
5750         /* Runtime instructions (first block of data in file) */
5751         src = &ucode->data[0];
5752         len = priv->ucode_code.len;
5753         IWL_DEBUG_INFO("Copying (but not loading) uCode instr len %Zd\n", len);
5754         memcpy(priv->ucode_code.v_addr, src, len);
5755         IWL_DEBUG_INFO("uCode instr buf vaddr = 0x%p, paddr = 0x%08x\n",
5756                 priv->ucode_code.v_addr, (u32)priv->ucode_code.p_addr);
5757
5758         /* Runtime data (2nd block)
5759          * NOTE:  Copy into backup buffer will be done in iwl3945_up()  */
5760         src = &ucode->data[inst_size];
5761         len = priv->ucode_data.len;
5762         IWL_DEBUG_INFO("Copying (but not loading) uCode data len %Zd\n", len);
5763         memcpy(priv->ucode_data.v_addr, src, len);
5764         memcpy(priv->ucode_data_backup.v_addr, src, len);
5765
5766         /* Initialization instructions (3rd block) */
5767         if (init_size) {
5768                 src = &ucode->data[inst_size + data_size];
5769                 len = priv->ucode_init.len;
5770                 IWL_DEBUG_INFO("Copying (but not loading) init instr len %Zd\n",
5771                                len);
5772                 memcpy(priv->ucode_init.v_addr, src, len);
5773         }
5774
5775         /* Initialization data (4th block) */
5776         if (init_data_size) {
5777                 src = &ucode->data[inst_size + data_size + init_size];
5778                 len = priv->ucode_init_data.len;
5779                 IWL_DEBUG_INFO("Copying (but not loading) init data len %d\n",
5780                                (int)len);
5781                 memcpy(priv->ucode_init_data.v_addr, src, len);
5782         }
5783
5784         /* Bootstrap instructions (5th block) */
5785         src = &ucode->data[inst_size + data_size + init_size + init_data_size];
5786         len = priv->ucode_boot.len;
5787         IWL_DEBUG_INFO("Copying (but not loading) boot instr len %d\n",
5788                        (int)len);
5789         memcpy(priv->ucode_boot.v_addr, src, len);
5790
5791         /* We have our copies now, allow OS release its copies */
5792         release_firmware(ucode_raw);
5793         return 0;
5794
5795  err_pci_alloc:
5796         IWL_ERROR("failed to allocate pci memory\n");
5797         ret = -ENOMEM;
5798         iwl3945_dealloc_ucode_pci(priv);
5799
5800  err_release:
5801         release_firmware(ucode_raw);
5802
5803  error:
5804         return ret;
5805 }
5806
5807
5808 /**
5809  * iwl3945_set_ucode_ptrs - Set uCode address location
5810  *
5811  * Tell initialization uCode where to find runtime uCode.
5812  *
5813  * BSM registers initially contain pointers to initialization uCode.
5814  * We need to replace them to load runtime uCode inst and data,
5815  * and to save runtime data when powering down.
5816  */
5817 static int iwl3945_set_ucode_ptrs(struct iwl3945_priv *priv)
5818 {
5819         dma_addr_t pinst;
5820         dma_addr_t pdata;
5821         int rc = 0;
5822         unsigned long flags;
5823
5824         /* bits 31:0 for 3945 */
5825         pinst = priv->ucode_code.p_addr;
5826         pdata = priv->ucode_data_backup.p_addr;
5827
5828         spin_lock_irqsave(&priv->lock, flags);
5829         rc = iwl3945_grab_nic_access(priv);
5830         if (rc) {
5831                 spin_unlock_irqrestore(&priv->lock, flags);
5832                 return rc;
5833         }
5834
5835         /* Tell bootstrap uCode where to find image to load */
5836         iwl3945_write_prph(priv, BSM_DRAM_INST_PTR_REG, pinst);
5837         iwl3945_write_prph(priv, BSM_DRAM_DATA_PTR_REG, pdata);
5838         iwl3945_write_prph(priv, BSM_DRAM_DATA_BYTECOUNT_REG,
5839                                  priv->ucode_data.len);
5840
5841         /* Inst bytecount must be last to set up, bit 31 signals uCode
5842          *   that all new ptr/size info is in place */
5843         iwl3945_write_prph(priv, BSM_DRAM_INST_BYTECOUNT_REG,
5844                                  priv->ucode_code.len | BSM_DRAM_INST_LOAD);
5845
5846         iwl3945_release_nic_access(priv);
5847
5848         spin_unlock_irqrestore(&priv->lock, flags);
5849
5850         IWL_DEBUG_INFO("Runtime uCode pointers are set.\n");
5851
5852         return rc;
5853 }
5854
5855 /**
5856  * iwl3945_init_alive_start - Called after REPLY_ALIVE notification received
5857  *
5858  * Called after REPLY_ALIVE notification received from "initialize" uCode.
5859  *
5860  * Tell "initialize" uCode to go ahead and load the runtime uCode.
5861  */
5862 static void iwl3945_init_alive_start(struct iwl3945_priv *priv)
5863 {
5864         /* Check alive response for "valid" sign from uCode */
5865         if (priv->card_alive_init.is_valid != UCODE_VALID_OK) {
5866                 /* We had an error bringing up the hardware, so take it
5867                  * all the way back down so we can try again */
5868                 IWL_DEBUG_INFO("Initialize Alive failed.\n");
5869                 goto restart;
5870         }
5871
5872         /* Bootstrap uCode has loaded initialize uCode ... verify inst image.
5873          * This is a paranoid check, because we would not have gotten the
5874          * "initialize" alive if code weren't properly loaded.  */
5875         if (iwl3945_verify_ucode(priv)) {
5876                 /* Runtime instruction load was bad;
5877                  * take it all the way back down so we can try again */
5878                 IWL_DEBUG_INFO("Bad \"initialize\" uCode load.\n");
5879                 goto restart;
5880         }
5881
5882         /* Send pointers to protocol/runtime uCode image ... init code will
5883          * load and launch runtime uCode, which will send us another "Alive"
5884          * notification. */
5885         IWL_DEBUG_INFO("Initialization Alive received.\n");
5886         if (iwl3945_set_ucode_ptrs(priv)) {
5887                 /* Runtime instruction load won't happen;
5888                  * take it all the way back down so we can try again */
5889                 IWL_DEBUG_INFO("Couldn't set up uCode pointers.\n");
5890                 goto restart;
5891         }
5892         return;
5893
5894  restart:
5895         queue_work(priv->workqueue, &priv->restart);
5896 }
5897
5898
5899 /**
5900  * iwl3945_alive_start - called after REPLY_ALIVE notification received
5901  *                   from protocol/runtime uCode (initialization uCode's
5902  *                   Alive gets handled by iwl3945_init_alive_start()).
5903  */
5904 static void iwl3945_alive_start(struct iwl3945_priv *priv)
5905 {
5906         int rc = 0;
5907         int thermal_spin = 0;
5908         u32 rfkill;
5909
5910         IWL_DEBUG_INFO("Runtime Alive received.\n");
5911
5912         if (priv->card_alive.is_valid != UCODE_VALID_OK) {
5913                 /* We had an error bringing up the hardware, so take it
5914                  * all the way back down so we can try again */
5915                 IWL_DEBUG_INFO("Alive failed.\n");
5916                 goto restart;
5917         }
5918
5919         /* Initialize uCode has loaded Runtime uCode ... verify inst image.
5920          * This is a paranoid check, because we would not have gotten the
5921          * "runtime" alive if code weren't properly loaded.  */
5922         if (iwl3945_verify_ucode(priv)) {
5923                 /* Runtime instruction load was bad;
5924                  * take it all the way back down so we can try again */
5925                 IWL_DEBUG_INFO("Bad runtime uCode load.\n");
5926                 goto restart;
5927         }
5928
5929         iwl3945_clear_stations_table(priv);
5930
5931         rc = iwl3945_grab_nic_access(priv);
5932         if (rc) {
5933                 IWL_WARNING("Can not read rfkill status from adapter\n");
5934                 return;
5935         }
5936
5937         rfkill = iwl3945_read_prph(priv, APMG_RFKILL_REG);
5938         IWL_DEBUG_INFO("RFKILL status: 0x%x\n", rfkill);
5939         iwl3945_release_nic_access(priv);
5940
5941         if (rfkill & 0x1) {
5942                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
5943                 /* if rfkill is not on, then wait for thermal
5944                  * sensor in adapter to kick in */
5945                 while (iwl3945_hw_get_temperature(priv) == 0) {
5946                         thermal_spin++;
5947                         udelay(10);
5948                 }
5949
5950                 if (thermal_spin)
5951                         IWL_DEBUG_INFO("Thermal calibration took %dus\n",
5952                                        thermal_spin * 10);
5953         } else
5954                 set_bit(STATUS_RF_KILL_HW, &priv->status);
5955
5956         /* After the ALIVE response, we can send commands to 3945 uCode */
5957         set_bit(STATUS_ALIVE, &priv->status);
5958
5959         /* Clear out the uCode error bit if it is set */
5960         clear_bit(STATUS_FW_ERROR, &priv->status);
5961
5962         if (iwl3945_is_rfkill(priv))
5963                 return;
5964
5965         ieee80211_start_queues(priv->hw);
5966
5967         priv->active_rate = priv->rates_mask;
5968         priv->active_rate_basic = priv->rates_mask & IWL_BASIC_RATES_MASK;
5969
5970         iwl3945_send_power_mode(priv, IWL_POWER_LEVEL(priv->power_mode));
5971
5972         if (iwl3945_is_associated(priv)) {
5973                 struct iwl3945_rxon_cmd *active_rxon =
5974                                 (struct iwl3945_rxon_cmd *)(&priv->active_rxon);
5975
5976                 memcpy(&priv->staging_rxon, &priv->active_rxon,
5977                        sizeof(priv->staging_rxon));
5978                 active_rxon->filter_flags &= ~RXON_FILTER_ASSOC_MSK;
5979         } else {
5980                 /* Initialize our rx_config data */
5981                 iwl3945_connection_init_rx_config(priv);
5982                 memcpy(priv->staging_rxon.node_addr, priv->mac_addr, ETH_ALEN);
5983         }
5984
5985         /* Configure Bluetooth device coexistence support */
5986         iwl3945_send_bt_config(priv);
5987
5988         /* Configure the adapter for unassociated operation */
5989         iwl3945_commit_rxon(priv);
5990
5991         /* At this point, the NIC is initialized and operational */
5992         priv->notif_missed_beacons = 0;
5993         set_bit(STATUS_READY, &priv->status);
5994
5995         iwl3945_reg_txpower_periodic(priv);
5996
5997         IWL_DEBUG_INFO("ALIVE processing complete.\n");
5998         wake_up_interruptible(&priv->wait_command_queue);
5999
6000         if (priv->error_recovering)
6001                 iwl3945_error_recovery(priv);
6002
6003         return;
6004
6005  restart:
6006         queue_work(priv->workqueue, &priv->restart);
6007 }
6008
6009 static void iwl3945_cancel_deferred_work(struct iwl3945_priv *priv);
6010
6011 static void __iwl3945_down(struct iwl3945_priv *priv)
6012 {
6013         unsigned long flags;
6014         int exit_pending = test_bit(STATUS_EXIT_PENDING, &priv->status);
6015         struct ieee80211_conf *conf = NULL;
6016
6017         IWL_DEBUG_INFO(DRV_NAME " is going down\n");
6018
6019         conf = ieee80211_get_hw_conf(priv->hw);
6020
6021         if (!exit_pending)
6022                 set_bit(STATUS_EXIT_PENDING, &priv->status);
6023
6024         iwl3945_clear_stations_table(priv);
6025
6026         /* Unblock any waiting calls */
6027         wake_up_interruptible_all(&priv->wait_command_queue);
6028
6029         /* Wipe out the EXIT_PENDING status bit if we are not actually
6030          * exiting the module */
6031         if (!exit_pending)
6032                 clear_bit(STATUS_EXIT_PENDING, &priv->status);
6033
6034         /* stop and reset the on-board processor */
6035         iwl3945_write32(priv, CSR_RESET, CSR_RESET_REG_FLAG_NEVO_RESET);
6036
6037         /* tell the device to stop sending interrupts */
6038         iwl3945_disable_interrupts(priv);
6039
6040         if (priv->mac80211_registered)
6041                 ieee80211_stop_queues(priv->hw);
6042
6043         /* If we have not previously called iwl3945_init() then
6044          * clear all bits but the RF Kill and SUSPEND bits and return */
6045         if (!iwl3945_is_init(priv)) {
6046                 priv->status = test_bit(STATUS_RF_KILL_HW, &priv->status) <<
6047                                         STATUS_RF_KILL_HW |
6048                                test_bit(STATUS_RF_KILL_SW, &priv->status) <<
6049                                         STATUS_RF_KILL_SW |
6050                                test_bit(STATUS_GEO_CONFIGURED, &priv->status) <<
6051                                         STATUS_GEO_CONFIGURED |
6052                                test_bit(STATUS_IN_SUSPEND, &priv->status) <<
6053                                         STATUS_IN_SUSPEND;
6054                 goto exit;
6055         }
6056
6057         /* ...otherwise clear out all the status bits but the RF Kill and
6058          * SUSPEND bits and continue taking the NIC down. */
6059         priv->status &= test_bit(STATUS_RF_KILL_HW, &priv->status) <<
6060                                 STATUS_RF_KILL_HW |
6061                         test_bit(STATUS_RF_KILL_SW, &priv->status) <<
6062                                 STATUS_RF_KILL_SW |
6063                         test_bit(STATUS_GEO_CONFIGURED, &priv->status) <<
6064                                 STATUS_GEO_CONFIGURED |
6065                         test_bit(STATUS_IN_SUSPEND, &priv->status) <<
6066                                 STATUS_IN_SUSPEND |
6067                         test_bit(STATUS_FW_ERROR, &priv->status) <<
6068                                 STATUS_FW_ERROR;
6069
6070         spin_lock_irqsave(&priv->lock, flags);
6071         iwl3945_clear_bit(priv, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
6072         spin_unlock_irqrestore(&priv->lock, flags);
6073
6074         iwl3945_hw_txq_ctx_stop(priv);
6075         iwl3945_hw_rxq_stop(priv);
6076
6077         spin_lock_irqsave(&priv->lock, flags);
6078         if (!iwl3945_grab_nic_access(priv)) {
6079                 iwl3945_write_prph(priv, APMG_CLK_DIS_REG,
6080                                          APMG_CLK_VAL_DMA_CLK_RQT);
6081                 iwl3945_release_nic_access(priv);
6082         }
6083         spin_unlock_irqrestore(&priv->lock, flags);
6084
6085         udelay(5);
6086
6087         iwl3945_hw_nic_stop_master(priv);
6088         iwl3945_set_bit(priv, CSR_RESET, CSR_RESET_REG_FLAG_SW_RESET);
6089         iwl3945_hw_nic_reset(priv);
6090
6091  exit:
6092         memset(&priv->card_alive, 0, sizeof(struct iwl3945_alive_resp));
6093
6094         if (priv->ibss_beacon)
6095                 dev_kfree_skb(priv->ibss_beacon);
6096         priv->ibss_beacon = NULL;
6097
6098         /* clear out any free frames */
6099         iwl3945_clear_free_frames(priv);
6100 }
6101
6102 static void iwl3945_down(struct iwl3945_priv *priv)
6103 {
6104         mutex_lock(&priv->mutex);
6105         __iwl3945_down(priv);
6106         mutex_unlock(&priv->mutex);
6107
6108         iwl3945_cancel_deferred_work(priv);
6109 }
6110
6111 #define MAX_HW_RESTARTS 5
6112
6113 static int __iwl3945_up(struct iwl3945_priv *priv)
6114 {
6115         int rc, i;
6116
6117         if (test_bit(STATUS_EXIT_PENDING, &priv->status)) {
6118                 IWL_WARNING("Exit pending; will not bring the NIC up\n");
6119                 return -EIO;
6120         }
6121
6122         if (test_bit(STATUS_RF_KILL_SW, &priv->status)) {
6123                 IWL_WARNING("Radio disabled by SW RF kill (module "
6124                             "parameter)\n");
6125                 return -ENODEV;
6126         }
6127
6128         if (!priv->ucode_data_backup.v_addr || !priv->ucode_data.v_addr) {
6129                 IWL_ERROR("ucode not available for device bringup\n");
6130                 return -EIO;
6131         }
6132
6133         /* If platform's RF_KILL switch is NOT set to KILL */
6134         if (iwl3945_read32(priv, CSR_GP_CNTRL) &
6135                                 CSR_GP_CNTRL_REG_FLAG_HW_RF_KILL_SW)
6136                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
6137         else {
6138                 set_bit(STATUS_RF_KILL_HW, &priv->status);
6139                 if (!test_bit(STATUS_IN_SUSPEND, &priv->status)) {
6140                         IWL_WARNING("Radio disabled by HW RF Kill switch\n");
6141                         return -ENODEV;
6142                 }
6143         }
6144
6145         iwl3945_write32(priv, CSR_INT, 0xFFFFFFFF);
6146
6147         rc = iwl3945_hw_nic_init(priv);
6148         if (rc) {
6149                 IWL_ERROR("Unable to int nic\n");
6150                 return rc;
6151         }
6152
6153         /* make sure rfkill handshake bits are cleared */
6154         iwl3945_write32(priv, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
6155         iwl3945_write32(priv, CSR_UCODE_DRV_GP1_CLR,
6156                     CSR_UCODE_DRV_GP1_BIT_CMD_BLOCKED);
6157
6158         /* clear (again), then enable host interrupts */
6159         iwl3945_write32(priv, CSR_INT, 0xFFFFFFFF);
6160         iwl3945_enable_interrupts(priv);
6161
6162         /* really make sure rfkill handshake bits are cleared */
6163         iwl3945_write32(priv, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
6164         iwl3945_write32(priv, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
6165
6166         /* Copy original ucode data image from disk into backup cache.
6167          * This will be used to initialize the on-board processor's
6168          * data SRAM for a clean start when the runtime program first loads. */
6169         memcpy(priv->ucode_data_backup.v_addr, priv->ucode_data.v_addr,
6170                priv->ucode_data.len);
6171
6172         /* We return success when we resume from suspend and rf_kill is on. */
6173         if (test_bit(STATUS_RF_KILL_HW, &priv->status))
6174                 return 0;
6175
6176         for (i = 0; i < MAX_HW_RESTARTS; i++) {
6177
6178                 iwl3945_clear_stations_table(priv);
6179
6180                 /* load bootstrap state machine,
6181                  * load bootstrap program into processor's memory,
6182                  * prepare to load the "initialize" uCode */
6183                 rc = iwl3945_load_bsm(priv);
6184
6185                 if (rc) {
6186                         IWL_ERROR("Unable to set up bootstrap uCode: %d\n", rc);
6187                         continue;
6188                 }
6189
6190                 /* start card; "initialize" will load runtime ucode */
6191                 iwl3945_nic_start(priv);
6192
6193                 IWL_DEBUG_INFO(DRV_NAME " is coming up\n");
6194
6195                 return 0;
6196         }
6197
6198         set_bit(STATUS_EXIT_PENDING, &priv->status);
6199         __iwl3945_down(priv);
6200
6201         /* tried to restart and config the device for as long as our
6202          * patience could withstand */
6203         IWL_ERROR("Unable to initialize device after %d attempts.\n", i);
6204         return -EIO;
6205 }
6206
6207
6208 /*****************************************************************************
6209  *
6210  * Workqueue callbacks
6211  *
6212  *****************************************************************************/
6213
6214 static void iwl3945_bg_init_alive_start(struct work_struct *data)
6215 {
6216         struct iwl3945_priv *priv =
6217             container_of(data, struct iwl3945_priv, init_alive_start.work);
6218
6219         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
6220                 return;
6221
6222         mutex_lock(&priv->mutex);
6223         iwl3945_init_alive_start(priv);
6224         mutex_unlock(&priv->mutex);
6225 }
6226
6227 static void iwl3945_bg_alive_start(struct work_struct *data)
6228 {
6229         struct iwl3945_priv *priv =
6230             container_of(data, struct iwl3945_priv, alive_start.work);
6231
6232         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
6233                 return;
6234
6235         mutex_lock(&priv->mutex);
6236         iwl3945_alive_start(priv);
6237         mutex_unlock(&priv->mutex);
6238 }
6239
6240 static void iwl3945_bg_rf_kill(struct work_struct *work)
6241 {
6242         struct iwl3945_priv *priv = container_of(work, struct iwl3945_priv, rf_kill);
6243
6244         wake_up_interruptible(&priv->wait_command_queue);
6245
6246         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
6247                 return;
6248
6249         mutex_lock(&priv->mutex);
6250
6251         if (!iwl3945_is_rfkill(priv)) {
6252                 IWL_DEBUG(IWL_DL_INFO | IWL_DL_RF_KILL,
6253                           "HW and/or SW RF Kill no longer active, restarting "
6254                           "device\n");
6255                 if (!test_bit(STATUS_EXIT_PENDING, &priv->status))
6256                         queue_work(priv->workqueue, &priv->restart);
6257         } else {
6258
6259                 if (!test_bit(STATUS_RF_KILL_HW, &priv->status))
6260                         IWL_DEBUG_RF_KILL("Can not turn radio back on - "
6261                                           "disabled by SW switch\n");
6262                 else
6263                         IWL_WARNING("Radio Frequency Kill Switch is On:\n"
6264                                     "Kill switch must be turned off for "
6265                                     "wireless networking to work.\n");
6266         }
6267         mutex_unlock(&priv->mutex);
6268 }
6269
6270 #define IWL_SCAN_CHECK_WATCHDOG (7 * HZ)
6271
6272 static void iwl3945_bg_scan_check(struct work_struct *data)
6273 {
6274         struct iwl3945_priv *priv =
6275             container_of(data, struct iwl3945_priv, scan_check.work);
6276
6277         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
6278                 return;
6279
6280         mutex_lock(&priv->mutex);
6281         if (test_bit(STATUS_SCANNING, &priv->status) ||
6282             test_bit(STATUS_SCAN_ABORTING, &priv->status)) {
6283                 IWL_DEBUG(IWL_DL_INFO | IWL_DL_SCAN,
6284                           "Scan completion watchdog resetting adapter (%dms)\n",
6285                           jiffies_to_msecs(IWL_SCAN_CHECK_WATCHDOG));
6286
6287                 if (!test_bit(STATUS_EXIT_PENDING, &priv->status))
6288                         iwl3945_send_scan_abort(priv);
6289         }
6290         mutex_unlock(&priv->mutex);
6291 }
6292
6293 static void iwl3945_bg_request_scan(struct work_struct *data)
6294 {
6295         struct iwl3945_priv *priv =
6296             container_of(data, struct iwl3945_priv, request_scan);
6297         struct iwl3945_host_cmd cmd = {
6298                 .id = REPLY_SCAN_CMD,
6299                 .len = sizeof(struct iwl3945_scan_cmd),
6300                 .meta.flags = CMD_SIZE_HUGE,
6301         };
6302         int rc = 0;
6303         struct iwl3945_scan_cmd *scan;
6304         struct ieee80211_conf *conf = NULL;
6305         u8 direct_mask;
6306         enum ieee80211_band band;
6307
6308         conf = ieee80211_get_hw_conf(priv->hw);
6309
6310         mutex_lock(&priv->mutex);
6311
6312         if (!iwl3945_is_ready(priv)) {
6313                 IWL_WARNING("request scan called when driver not ready.\n");
6314                 goto done;
6315         }
6316
6317         /* Make sure the scan wasn't cancelled before this queued work
6318          * was given the chance to run... */
6319         if (!test_bit(STATUS_SCANNING, &priv->status))
6320                 goto done;
6321
6322         /* This should never be called or scheduled if there is currently
6323          * a scan active in the hardware. */
6324         if (test_bit(STATUS_SCAN_HW, &priv->status)) {
6325                 IWL_DEBUG_INFO("Multiple concurrent scan requests in parallel. "
6326                                "Ignoring second request.\n");
6327                 rc = -EIO;
6328                 goto done;
6329         }
6330
6331         if (test_bit(STATUS_EXIT_PENDING, &priv->status)) {
6332                 IWL_DEBUG_SCAN("Aborting scan due to device shutdown\n");
6333                 goto done;
6334         }
6335
6336         if (test_bit(STATUS_SCAN_ABORTING, &priv->status)) {
6337                 IWL_DEBUG_HC("Scan request while abort pending.  Queuing.\n");
6338                 goto done;
6339         }
6340
6341         if (iwl3945_is_rfkill(priv)) {
6342                 IWL_DEBUG_HC("Aborting scan due to RF Kill activation\n");
6343                 goto done;
6344         }
6345
6346         if (!test_bit(STATUS_READY, &priv->status)) {
6347                 IWL_DEBUG_HC("Scan request while uninitialized.  Queuing.\n");
6348                 goto done;
6349         }
6350
6351         if (!priv->scan_bands) {
6352                 IWL_DEBUG_HC("Aborting scan due to no requested bands\n");
6353                 goto done;
6354         }
6355
6356         if (!priv->scan) {
6357                 priv->scan = kmalloc(sizeof(struct iwl3945_scan_cmd) +
6358                                      IWL_MAX_SCAN_SIZE, GFP_KERNEL);
6359                 if (!priv->scan) {
6360                         rc = -ENOMEM;
6361                         goto done;
6362                 }
6363         }
6364         scan = priv->scan;
6365         memset(scan, 0, sizeof(struct iwl3945_scan_cmd) + IWL_MAX_SCAN_SIZE);
6366
6367         scan->quiet_plcp_th = IWL_PLCP_QUIET_THRESH;
6368         scan->quiet_time = IWL_ACTIVE_QUIET_TIME;
6369
6370         if (iwl3945_is_associated(priv)) {
6371                 u16 interval = 0;
6372                 u32 extra;
6373                 u32 suspend_time = 100;
6374                 u32 scan_suspend_time = 100;
6375                 unsigned long flags;
6376
6377                 IWL_DEBUG_INFO("Scanning while associated...\n");
6378
6379                 spin_lock_irqsave(&priv->lock, flags);
6380                 interval = priv->beacon_int;
6381                 spin_unlock_irqrestore(&priv->lock, flags);
6382
6383                 scan->suspend_time = 0;
6384                 scan->max_out_time = cpu_to_le32(200 * 1024);
6385                 if (!interval)
6386                         interval = suspend_time;
6387                 /*
6388                  * suspend time format:
6389                  *  0-19: beacon interval in usec (time before exec.)
6390                  * 20-23: 0
6391                  * 24-31: number of beacons (suspend between channels)
6392                  */
6393
6394                 extra = (suspend_time / interval) << 24;
6395                 scan_suspend_time = 0xFF0FFFFF &
6396                     (extra | ((suspend_time % interval) * 1024));
6397
6398                 scan->suspend_time = cpu_to_le32(scan_suspend_time);
6399                 IWL_DEBUG_SCAN("suspend_time 0x%X beacon interval %d\n",
6400                                scan_suspend_time, interval);
6401         }
6402
6403         /* We should add the ability for user to lock to PASSIVE ONLY */
6404         if (priv->one_direct_scan) {
6405                 IWL_DEBUG_SCAN
6406                     ("Kicking off one direct scan for '%s'\n",
6407                      iwl3945_escape_essid(priv->direct_ssid,
6408                                       priv->direct_ssid_len));
6409                 scan->direct_scan[0].id = WLAN_EID_SSID;
6410                 scan->direct_scan[0].len = priv->direct_ssid_len;
6411                 memcpy(scan->direct_scan[0].ssid,
6412                        priv->direct_ssid, priv->direct_ssid_len);
6413                 direct_mask = 1;
6414         } else if (!iwl3945_is_associated(priv) && priv->essid_len) {
6415                 scan->direct_scan[0].id = WLAN_EID_SSID;
6416                 scan->direct_scan[0].len = priv->essid_len;
6417                 memcpy(scan->direct_scan[0].ssid, priv->essid, priv->essid_len);
6418                 direct_mask = 1;
6419         } else
6420                 direct_mask = 0;
6421
6422         /* We don't build a direct scan probe request; the uCode will do
6423          * that based on the direct_mask added to each channel entry */
6424         scan->tx_cmd.len = cpu_to_le16(
6425                 iwl3945_fill_probe_req(priv, (struct ieee80211_mgmt *)scan->data,
6426                         IWL_MAX_SCAN_SIZE - sizeof(*scan), 0));
6427         scan->tx_cmd.tx_flags = TX_CMD_FLG_SEQ_CTL_MSK;
6428         scan->tx_cmd.sta_id = priv->hw_setting.bcast_sta_id;
6429         scan->tx_cmd.stop_time.life_time = TX_CMD_LIFE_TIME_INFINITE;
6430
6431         /* flags + rate selection */
6432
6433         switch (priv->scan_bands) {
6434         case 2:
6435                 scan->flags = RXON_FLG_BAND_24G_MSK | RXON_FLG_AUTO_DETECT_MSK;
6436                 scan->tx_cmd.rate = IWL_RATE_1M_PLCP;
6437                 scan->good_CRC_th = 0;
6438                 band = IEEE80211_BAND_2GHZ;
6439                 break;
6440
6441         case 1:
6442                 scan->tx_cmd.rate = IWL_RATE_6M_PLCP;
6443                 scan->good_CRC_th = IWL_GOOD_CRC_TH;
6444                 band = IEEE80211_BAND_5GHZ;
6445                 break;
6446
6447         default:
6448                 IWL_WARNING("Invalid scan band count\n");
6449                 goto done;
6450         }
6451
6452         /* select Rx antennas */
6453         scan->flags |= iwl3945_get_antenna_flags(priv);
6454
6455         if (priv->iw_mode == IEEE80211_IF_TYPE_MNTR)
6456                 scan->filter_flags = RXON_FILTER_PROMISC_MSK;
6457
6458         if (direct_mask)
6459                 IWL_DEBUG_SCAN
6460                     ("Initiating direct scan for %s.\n",
6461                      iwl3945_escape_essid(priv->essid, priv->essid_len));
6462         else
6463                 IWL_DEBUG_SCAN("Initiating indirect scan.\n");
6464
6465         scan->channel_count =
6466                 iwl3945_get_channels_for_scan(
6467                         priv, band, 1, /* active */
6468                         direct_mask,
6469                         (void *)&scan->data[le16_to_cpu(scan->tx_cmd.len)]);
6470
6471         cmd.len += le16_to_cpu(scan->tx_cmd.len) +
6472             scan->channel_count * sizeof(struct iwl3945_scan_channel);
6473         cmd.data = scan;
6474         scan->len = cpu_to_le16(cmd.len);
6475
6476         set_bit(STATUS_SCAN_HW, &priv->status);
6477         rc = iwl3945_send_cmd_sync(priv, &cmd);
6478         if (rc)
6479                 goto done;
6480
6481         queue_delayed_work(priv->workqueue, &priv->scan_check,
6482                            IWL_SCAN_CHECK_WATCHDOG);
6483
6484         mutex_unlock(&priv->mutex);
6485         return;
6486
6487  done:
6488         /* inform mac80211 scan aborted */
6489         queue_work(priv->workqueue, &priv->scan_completed);
6490         mutex_unlock(&priv->mutex);
6491 }
6492
6493 static void iwl3945_bg_up(struct work_struct *data)
6494 {
6495         struct iwl3945_priv *priv = container_of(data, struct iwl3945_priv, up);
6496
6497         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
6498                 return;
6499
6500         mutex_lock(&priv->mutex);
6501         __iwl3945_up(priv);
6502         mutex_unlock(&priv->mutex);
6503 }
6504
6505 static void iwl3945_bg_restart(struct work_struct *data)
6506 {
6507         struct iwl3945_priv *priv = container_of(data, struct iwl3945_priv, restart);
6508
6509         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
6510                 return;
6511
6512         iwl3945_down(priv);
6513         queue_work(priv->workqueue, &priv->up);
6514 }
6515
6516 static void iwl3945_bg_rx_replenish(struct work_struct *data)
6517 {
6518         struct iwl3945_priv *priv =
6519             container_of(data, struct iwl3945_priv, rx_replenish);
6520
6521         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
6522                 return;
6523
6524         mutex_lock(&priv->mutex);
6525         iwl3945_rx_replenish(priv);
6526         mutex_unlock(&priv->mutex);
6527 }
6528
6529 #define IWL_DELAY_NEXT_SCAN (HZ*2)
6530
6531 static void iwl3945_bg_post_associate(struct work_struct *data)
6532 {
6533         struct iwl3945_priv *priv = container_of(data, struct iwl3945_priv,
6534                                              post_associate.work);
6535
6536         int rc = 0;
6537         struct ieee80211_conf *conf = NULL;
6538         DECLARE_MAC_BUF(mac);
6539
6540         if (priv->iw_mode == IEEE80211_IF_TYPE_AP) {
6541                 IWL_ERROR("%s Should not be called in AP mode\n", __FUNCTION__);
6542                 return;
6543         }
6544
6545
6546         IWL_DEBUG_ASSOC("Associated as %d to: %s\n",
6547                         priv->assoc_id,
6548                         print_mac(mac, priv->active_rxon.bssid_addr));
6549
6550         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
6551                 return;
6552
6553         mutex_lock(&priv->mutex);
6554
6555         if (!priv->vif || !priv->is_open) {
6556                 mutex_unlock(&priv->mutex);
6557                 return;
6558         }
6559         iwl3945_scan_cancel_timeout(priv, 200);
6560
6561         conf = ieee80211_get_hw_conf(priv->hw);
6562
6563         priv->staging_rxon.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
6564         iwl3945_commit_rxon(priv);
6565
6566         memset(&priv->rxon_timing, 0, sizeof(struct iwl3945_rxon_time_cmd));
6567         iwl3945_setup_rxon_timing(priv);
6568         rc = iwl3945_send_cmd_pdu(priv, REPLY_RXON_TIMING,
6569                               sizeof(priv->rxon_timing), &priv->rxon_timing);
6570         if (rc)
6571                 IWL_WARNING("REPLY_RXON_TIMING failed - "
6572                             "Attempting to continue.\n");
6573
6574         priv->staging_rxon.filter_flags |= RXON_FILTER_ASSOC_MSK;
6575
6576         priv->staging_rxon.assoc_id = cpu_to_le16(priv->assoc_id);
6577
6578         IWL_DEBUG_ASSOC("assoc id %d beacon interval %d\n",
6579                         priv->assoc_id, priv->beacon_int);
6580
6581         if (priv->assoc_capability & WLAN_CAPABILITY_SHORT_PREAMBLE)
6582                 priv->staging_rxon.flags |= RXON_FLG_SHORT_PREAMBLE_MSK;
6583         else
6584                 priv->staging_rxon.flags &= ~RXON_FLG_SHORT_PREAMBLE_MSK;
6585
6586         if (priv->staging_rxon.flags & RXON_FLG_BAND_24G_MSK) {
6587                 if (priv->assoc_capability & WLAN_CAPABILITY_SHORT_SLOT_TIME)
6588                         priv->staging_rxon.flags |= RXON_FLG_SHORT_SLOT_MSK;
6589                 else
6590                         priv->staging_rxon.flags &= ~RXON_FLG_SHORT_SLOT_MSK;
6591
6592                 if (priv->iw_mode == IEEE80211_IF_TYPE_IBSS)
6593                         priv->staging_rxon.flags &= ~RXON_FLG_SHORT_SLOT_MSK;
6594
6595         }
6596
6597         iwl3945_commit_rxon(priv);
6598
6599         switch (priv->iw_mode) {
6600         case IEEE80211_IF_TYPE_STA:
6601                 iwl3945_rate_scale_init(priv->hw, IWL_AP_ID);
6602                 break;
6603
6604         case IEEE80211_IF_TYPE_IBSS:
6605
6606                 /* clear out the station table */
6607                 iwl3945_clear_stations_table(priv);
6608
6609                 iwl3945_add_station(priv, iwl3945_broadcast_addr, 0, 0);
6610                 iwl3945_add_station(priv, priv->bssid, 0, 0);
6611                 iwl3945_sync_sta(priv, IWL_STA_ID,
6612                                  (priv->band == IEEE80211_BAND_5GHZ) ?
6613                                  IWL_RATE_6M_PLCP : IWL_RATE_1M_PLCP,
6614                                  CMD_ASYNC);
6615                 iwl3945_rate_scale_init(priv->hw, IWL_STA_ID);
6616                 iwl3945_send_beacon_cmd(priv);
6617
6618                 break;
6619
6620         default:
6621                  IWL_ERROR("%s Should not be called in %d mode\n",
6622                            __FUNCTION__, priv->iw_mode);
6623                 break;
6624         }
6625
6626         iwl3945_sequence_reset(priv);
6627
6628         iwl3945_activate_qos(priv, 0);
6629
6630         /* we have just associated, don't start scan too early */
6631         priv->next_scan_jiffies = jiffies + IWL_DELAY_NEXT_SCAN;
6632         mutex_unlock(&priv->mutex);
6633 }
6634
6635 static void iwl3945_bg_abort_scan(struct work_struct *work)
6636 {
6637         struct iwl3945_priv *priv = container_of(work, struct iwl3945_priv, abort_scan);
6638
6639         if (!iwl3945_is_ready(priv))
6640                 return;
6641
6642         mutex_lock(&priv->mutex);
6643
6644         set_bit(STATUS_SCAN_ABORTING, &priv->status);
6645         iwl3945_send_scan_abort(priv);
6646
6647         mutex_unlock(&priv->mutex);
6648 }
6649
6650 static int iwl3945_mac_config(struct ieee80211_hw *hw, struct ieee80211_conf *conf);
6651
6652 static void iwl3945_bg_scan_completed(struct work_struct *work)
6653 {
6654         struct iwl3945_priv *priv =
6655             container_of(work, struct iwl3945_priv, scan_completed);
6656
6657         IWL_DEBUG(IWL_DL_INFO | IWL_DL_SCAN, "SCAN complete scan\n");
6658
6659         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
6660                 return;
6661
6662         if (test_bit(STATUS_CONF_PENDING, &priv->status))
6663                 iwl3945_mac_config(priv->hw, ieee80211_get_hw_conf(priv->hw));
6664
6665         ieee80211_scan_completed(priv->hw);
6666
6667         /* Since setting the TXPOWER may have been deferred while
6668          * performing the scan, fire one off */
6669         mutex_lock(&priv->mutex);
6670         iwl3945_hw_reg_send_txpower(priv);
6671         mutex_unlock(&priv->mutex);
6672 }
6673
6674 /*****************************************************************************
6675  *
6676  * mac80211 entry point functions
6677  *
6678  *****************************************************************************/
6679
6680 #define UCODE_READY_TIMEOUT     (2 * HZ)
6681
6682 static int iwl3945_mac_start(struct ieee80211_hw *hw)
6683 {
6684         struct iwl3945_priv *priv = hw->priv;
6685         int ret;
6686
6687         IWL_DEBUG_MAC80211("enter\n");
6688
6689         if (pci_enable_device(priv->pci_dev)) {
6690                 IWL_ERROR("Fail to pci_enable_device\n");
6691                 return -ENODEV;
6692         }
6693         pci_restore_state(priv->pci_dev);
6694         pci_enable_msi(priv->pci_dev);
6695
6696         ret = request_irq(priv->pci_dev->irq, iwl3945_isr, IRQF_SHARED,
6697                           DRV_NAME, priv);
6698         if (ret) {
6699                 IWL_ERROR("Error allocating IRQ %d\n", priv->pci_dev->irq);
6700                 goto out_disable_msi;
6701         }
6702
6703         /* we should be verifying the device is ready to be opened */
6704         mutex_lock(&priv->mutex);
6705
6706         memset(&priv->staging_rxon, 0, sizeof(struct iwl3945_rxon_cmd));
6707         /* fetch ucode file from disk, alloc and copy to bus-master buffers ...
6708          * ucode filename and max sizes are card-specific. */
6709
6710         if (!priv->ucode_code.len) {
6711                 ret = iwl3945_read_ucode(priv);
6712                 if (ret) {
6713                         IWL_ERROR("Could not read microcode: %d\n", ret);
6714                         mutex_unlock(&priv->mutex);
6715                         goto out_release_irq;
6716                 }
6717         }
6718
6719         ret = __iwl3945_up(priv);
6720
6721         mutex_unlock(&priv->mutex);
6722
6723         if (ret)
6724                 goto out_release_irq;
6725
6726         IWL_DEBUG_INFO("Start UP work.\n");
6727
6728         if (test_bit(STATUS_IN_SUSPEND, &priv->status))
6729                 return 0;
6730
6731         /* Wait for START_ALIVE from ucode. Otherwise callbacks from
6732          * mac80211 will not be run successfully. */
6733         ret = wait_event_interruptible_timeout(priv->wait_command_queue,
6734                         test_bit(STATUS_READY, &priv->status),
6735                         UCODE_READY_TIMEOUT);
6736         if (!ret) {
6737                 if (!test_bit(STATUS_READY, &priv->status)) {
6738                         IWL_ERROR("Wait for START_ALIVE timeout after %dms.\n",
6739                                   jiffies_to_msecs(UCODE_READY_TIMEOUT));
6740                         ret = -ETIMEDOUT;
6741                         goto out_release_irq;
6742                 }
6743         }
6744
6745         priv->is_open = 1;
6746         IWL_DEBUG_MAC80211("leave\n");
6747         return 0;
6748
6749 out_release_irq:
6750         free_irq(priv->pci_dev->irq, priv);
6751 out_disable_msi:
6752         pci_disable_msi(priv->pci_dev);
6753         pci_disable_device(priv->pci_dev);
6754         priv->is_open = 0;
6755         IWL_DEBUG_MAC80211("leave - failed\n");
6756         return ret;
6757 }
6758
6759 static void iwl3945_mac_stop(struct ieee80211_hw *hw)
6760 {
6761         struct iwl3945_priv *priv = hw->priv;
6762
6763         IWL_DEBUG_MAC80211("enter\n");
6764
6765         if (!priv->is_open) {
6766                 IWL_DEBUG_MAC80211("leave - skip\n");
6767                 return;
6768         }
6769
6770         priv->is_open = 0;
6771
6772         if (iwl3945_is_ready_rf(priv)) {
6773                 /* stop mac, cancel any scan request and clear
6774                  * RXON_FILTER_ASSOC_MSK BIT
6775                  */
6776                 mutex_lock(&priv->mutex);
6777                 iwl3945_scan_cancel_timeout(priv, 100);
6778                 cancel_delayed_work(&priv->post_associate);
6779                 mutex_unlock(&priv->mutex);
6780         }
6781
6782         iwl3945_down(priv);
6783
6784         flush_workqueue(priv->workqueue);
6785         free_irq(priv->pci_dev->irq, priv);
6786         pci_disable_msi(priv->pci_dev);
6787         pci_save_state(priv->pci_dev);
6788         pci_disable_device(priv->pci_dev);
6789
6790         IWL_DEBUG_MAC80211("leave\n");
6791 }
6792
6793 static int iwl3945_mac_tx(struct ieee80211_hw *hw, struct sk_buff *skb,
6794                       struct ieee80211_tx_control *ctl)
6795 {
6796         struct iwl3945_priv *priv = hw->priv;
6797
6798         IWL_DEBUG_MAC80211("enter\n");
6799
6800         if (priv->iw_mode == IEEE80211_IF_TYPE_MNTR) {
6801                 IWL_DEBUG_MAC80211("leave - monitor\n");
6802                 return -1;
6803         }
6804
6805         IWL_DEBUG_TX("dev->xmit(%d bytes) at rate 0x%02x\n", skb->len,
6806                      ctl->tx_rate->bitrate);
6807
6808         if (iwl3945_tx_skb(priv, skb, ctl))
6809                 dev_kfree_skb_any(skb);
6810
6811         IWL_DEBUG_MAC80211("leave\n");
6812         return 0;
6813 }
6814
6815 static int iwl3945_mac_add_interface(struct ieee80211_hw *hw,
6816                                  struct ieee80211_if_init_conf *conf)
6817 {
6818         struct iwl3945_priv *priv = hw->priv;
6819         unsigned long flags;
6820         DECLARE_MAC_BUF(mac);
6821
6822         IWL_DEBUG_MAC80211("enter: type %d\n", conf->type);
6823
6824         if (priv->vif) {
6825                 IWL_DEBUG_MAC80211("leave - vif != NULL\n");
6826                 return -EOPNOTSUPP;
6827         }
6828
6829         spin_lock_irqsave(&priv->lock, flags);
6830         priv->vif = conf->vif;
6831
6832         spin_unlock_irqrestore(&priv->lock, flags);
6833
6834         mutex_lock(&priv->mutex);
6835
6836         if (conf->mac_addr) {
6837                 IWL_DEBUG_MAC80211("Set: %s\n", print_mac(mac, conf->mac_addr));
6838                 memcpy(priv->mac_addr, conf->mac_addr, ETH_ALEN);
6839         }
6840
6841         if (iwl3945_is_ready(priv))
6842                 iwl3945_set_mode(priv, conf->type);
6843
6844         mutex_unlock(&priv->mutex);
6845
6846         IWL_DEBUG_MAC80211("leave\n");
6847         return 0;
6848 }
6849
6850 /**
6851  * iwl3945_mac_config - mac80211 config callback
6852  *
6853  * We ignore conf->flags & IEEE80211_CONF_SHORT_SLOT_TIME since it seems to
6854  * be set inappropriately and the driver currently sets the hardware up to
6855  * use it whenever needed.
6856  */
6857 static int iwl3945_mac_config(struct ieee80211_hw *hw, struct ieee80211_conf *conf)
6858 {
6859         struct iwl3945_priv *priv = hw->priv;
6860         const struct iwl3945_channel_info *ch_info;
6861         unsigned long flags;
6862         int ret = 0;
6863
6864         mutex_lock(&priv->mutex);
6865         IWL_DEBUG_MAC80211("enter to channel %d\n", conf->channel->hw_value);
6866
6867         priv->add_radiotap = !!(conf->flags & IEEE80211_CONF_RADIOTAP);
6868
6869         if (!iwl3945_is_ready(priv)) {
6870                 IWL_DEBUG_MAC80211("leave - not ready\n");
6871                 ret = -EIO;
6872                 goto out;
6873         }
6874
6875         if (unlikely(!iwl3945_param_disable_hw_scan &&
6876                      test_bit(STATUS_SCANNING, &priv->status))) {
6877                 IWL_DEBUG_MAC80211("leave - scanning\n");
6878                 set_bit(STATUS_CONF_PENDING, &priv->status);
6879                 mutex_unlock(&priv->mutex);
6880                 return 0;
6881         }
6882
6883         spin_lock_irqsave(&priv->lock, flags);
6884
6885         ch_info = iwl3945_get_channel_info(priv, conf->channel->band,
6886                                            conf->channel->hw_value);
6887         if (!is_channel_valid(ch_info)) {
6888                 IWL_DEBUG_SCAN("Channel %d [%d] is INVALID for this SKU.\n",
6889                                conf->channel->hw_value, conf->channel->band);
6890                 IWL_DEBUG_MAC80211("leave - invalid channel\n");
6891                 spin_unlock_irqrestore(&priv->lock, flags);
6892                 ret = -EINVAL;
6893                 goto out;
6894         }
6895
6896         iwl3945_set_rxon_channel(priv, conf->channel->band, conf->channel->hw_value);
6897
6898         iwl3945_set_flags_for_phymode(priv, conf->channel->band);
6899
6900         /* The list of supported rates and rate mask can be different
6901          * for each phymode; since the phymode may have changed, reset
6902          * the rate mask to what mac80211 lists */
6903         iwl3945_set_rate(priv);
6904
6905         spin_unlock_irqrestore(&priv->lock, flags);
6906
6907 #ifdef IEEE80211_CONF_CHANNEL_SWITCH
6908         if (conf->flags & IEEE80211_CONF_CHANNEL_SWITCH) {
6909                 iwl3945_hw_channel_switch(priv, conf->channel);
6910                 goto out;
6911         }
6912 #endif
6913
6914         iwl3945_radio_kill_sw(priv, !conf->radio_enabled);
6915
6916         if (!conf->radio_enabled) {
6917                 IWL_DEBUG_MAC80211("leave - radio disabled\n");
6918                 goto out;
6919         }
6920
6921         if (iwl3945_is_rfkill(priv)) {
6922                 IWL_DEBUG_MAC80211("leave - RF kill\n");
6923                 ret = -EIO;
6924                 goto out;
6925         }
6926
6927         iwl3945_set_rate(priv);
6928
6929         if (memcmp(&priv->active_rxon,
6930                    &priv->staging_rxon, sizeof(priv->staging_rxon)))
6931                 iwl3945_commit_rxon(priv);
6932         else
6933                 IWL_DEBUG_INFO("No re-sending same RXON configuration.\n");
6934
6935         IWL_DEBUG_MAC80211("leave\n");
6936
6937 out:
6938         clear_bit(STATUS_CONF_PENDING, &priv->status);
6939         mutex_unlock(&priv->mutex);
6940         return ret;
6941 }
6942
6943 static void iwl3945_config_ap(struct iwl3945_priv *priv)
6944 {
6945         int rc = 0;
6946
6947         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
6948                 return;
6949
6950         /* The following should be done only at AP bring up */
6951         if ((priv->active_rxon.filter_flags & RXON_FILTER_ASSOC_MSK) == 0) {
6952
6953                 /* RXON - unassoc (to set timing command) */
6954                 priv->staging_rxon.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
6955                 iwl3945_commit_rxon(priv);
6956
6957                 /* RXON Timing */
6958                 memset(&priv->rxon_timing, 0, sizeof(struct iwl3945_rxon_time_cmd));
6959                 iwl3945_setup_rxon_timing(priv);
6960                 rc = iwl3945_send_cmd_pdu(priv, REPLY_RXON_TIMING,
6961                                 sizeof(priv->rxon_timing), &priv->rxon_timing);
6962                 if (rc)
6963                         IWL_WARNING("REPLY_RXON_TIMING failed - "
6964                                         "Attempting to continue.\n");
6965
6966                 /* FIXME: what should be the assoc_id for AP? */
6967                 priv->staging_rxon.assoc_id = cpu_to_le16(priv->assoc_id);
6968                 if (priv->assoc_capability & WLAN_CAPABILITY_SHORT_PREAMBLE)
6969                         priv->staging_rxon.flags |=
6970                                 RXON_FLG_SHORT_PREAMBLE_MSK;
6971                 else
6972                         priv->staging_rxon.flags &=
6973                                 ~RXON_FLG_SHORT_PREAMBLE_MSK;
6974
6975                 if (priv->staging_rxon.flags & RXON_FLG_BAND_24G_MSK) {
6976                         if (priv->assoc_capability &
6977                                 WLAN_CAPABILITY_SHORT_SLOT_TIME)
6978                                 priv->staging_rxon.flags |=
6979                                         RXON_FLG_SHORT_SLOT_MSK;
6980                         else
6981                                 priv->staging_rxon.flags &=
6982                                         ~RXON_FLG_SHORT_SLOT_MSK;
6983
6984                         if (priv->iw_mode == IEEE80211_IF_TYPE_IBSS)
6985                                 priv->staging_rxon.flags &=
6986                                         ~RXON_FLG_SHORT_SLOT_MSK;
6987                 }
6988                 /* restore RXON assoc */
6989                 priv->staging_rxon.filter_flags |= RXON_FILTER_ASSOC_MSK;
6990                 iwl3945_commit_rxon(priv);
6991                 iwl3945_add_station(priv, iwl3945_broadcast_addr, 0, 0);
6992         }
6993         iwl3945_send_beacon_cmd(priv);
6994
6995         /* FIXME - we need to add code here to detect a totally new
6996          * configuration, reset the AP, unassoc, rxon timing, assoc,
6997          * clear sta table, add BCAST sta... */
6998 }
6999
7000 static int iwl3945_mac_config_interface(struct ieee80211_hw *hw,
7001                                         struct ieee80211_vif *vif,
7002                                     struct ieee80211_if_conf *conf)
7003 {
7004         struct iwl3945_priv *priv = hw->priv;
7005         DECLARE_MAC_BUF(mac);
7006         unsigned long flags;
7007         int rc;
7008
7009         if (conf == NULL)
7010                 return -EIO;
7011
7012         /* XXX: this MUST use conf->mac_addr */
7013
7014         if ((priv->iw_mode == IEEE80211_IF_TYPE_AP) &&
7015             (!conf->beacon || !conf->ssid_len)) {
7016                 IWL_DEBUG_MAC80211
7017                     ("Leaving in AP mode because HostAPD is not ready.\n");
7018                 return 0;
7019         }
7020
7021         if (!iwl3945_is_alive(priv))
7022                 return -EAGAIN;
7023
7024         mutex_lock(&priv->mutex);
7025
7026         if (conf->bssid)
7027                 IWL_DEBUG_MAC80211("bssid: %s\n",
7028                                    print_mac(mac, conf->bssid));
7029
7030 /*
7031  * very dubious code was here; the probe filtering flag is never set:
7032  *
7033         if (unlikely(test_bit(STATUS_SCANNING, &priv->status)) &&
7034             !(priv->hw->flags & IEEE80211_HW_NO_PROBE_FILTERING)) {
7035  */
7036         if (unlikely(test_bit(STATUS_SCANNING, &priv->status))) {
7037                 IWL_DEBUG_MAC80211("leave - scanning\n");
7038                 mutex_unlock(&priv->mutex);
7039                 return 0;
7040         }
7041
7042         if (priv->vif != vif) {
7043                 IWL_DEBUG_MAC80211("leave - priv->vif != vif\n");
7044                 mutex_unlock(&priv->mutex);
7045                 return 0;
7046         }
7047
7048         if (priv->iw_mode == IEEE80211_IF_TYPE_AP) {
7049                 if (!conf->bssid) {
7050                         conf->bssid = priv->mac_addr;
7051                         memcpy(priv->bssid, priv->mac_addr, ETH_ALEN);
7052                         IWL_DEBUG_MAC80211("bssid was set to: %s\n",
7053                                            print_mac(mac, conf->bssid));
7054                 }
7055                 if (priv->ibss_beacon)
7056                         dev_kfree_skb(priv->ibss_beacon);
7057
7058                 priv->ibss_beacon = conf->beacon;
7059         }
7060
7061         if (iwl3945_is_rfkill(priv))
7062                 goto done;
7063
7064         if (conf->bssid && !is_zero_ether_addr(conf->bssid) &&
7065             !is_multicast_ether_addr(conf->bssid)) {
7066                 /* If there is currently a HW scan going on in the background
7067                  * then we need to cancel it else the RXON below will fail. */
7068                 if (iwl3945_scan_cancel_timeout(priv, 100)) {
7069                         IWL_WARNING("Aborted scan still in progress "
7070                                     "after 100ms\n");
7071                         IWL_DEBUG_MAC80211("leaving - scan abort failed.\n");
7072                         mutex_unlock(&priv->mutex);
7073                         return -EAGAIN;
7074                 }
7075                 memcpy(priv->staging_rxon.bssid_addr, conf->bssid, ETH_ALEN);
7076
7077                 /* TODO: Audit driver for usage of these members and see
7078                  * if mac80211 deprecates them (priv->bssid looks like it
7079                  * shouldn't be there, but I haven't scanned the IBSS code
7080                  * to verify) - jpk */
7081                 memcpy(priv->bssid, conf->bssid, ETH_ALEN);
7082
7083                 if (priv->iw_mode == IEEE80211_IF_TYPE_AP)
7084                         iwl3945_config_ap(priv);
7085                 else {
7086                         rc = iwl3945_commit_rxon(priv);
7087                         if ((priv->iw_mode == IEEE80211_IF_TYPE_STA) && rc)
7088                                 iwl3945_add_station(priv,
7089                                         priv->active_rxon.bssid_addr, 1, 0);
7090                 }
7091
7092         } else {
7093                 iwl3945_scan_cancel_timeout(priv, 100);
7094                 priv->staging_rxon.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
7095                 iwl3945_commit_rxon(priv);
7096         }
7097
7098  done:
7099         spin_lock_irqsave(&priv->lock, flags);
7100         if (!conf->ssid_len)
7101                 memset(priv->essid, 0, IW_ESSID_MAX_SIZE);
7102         else
7103                 memcpy(priv->essid, conf->ssid, conf->ssid_len);
7104
7105         priv->essid_len = conf->ssid_len;
7106         spin_unlock_irqrestore(&priv->lock, flags);
7107
7108         IWL_DEBUG_MAC80211("leave\n");
7109         mutex_unlock(&priv->mutex);
7110
7111         return 0;
7112 }
7113
7114 static void iwl3945_configure_filter(struct ieee80211_hw *hw,
7115                                  unsigned int changed_flags,
7116                                  unsigned int *total_flags,
7117                                  int mc_count, struct dev_addr_list *mc_list)
7118 {
7119         /*
7120          * XXX: dummy
7121          * see also iwl3945_connection_init_rx_config
7122          */
7123         *total_flags = 0;
7124 }
7125
7126 static void iwl3945_mac_remove_interface(struct ieee80211_hw *hw,
7127                                      struct ieee80211_if_init_conf *conf)
7128 {
7129         struct iwl3945_priv *priv = hw->priv;
7130
7131         IWL_DEBUG_MAC80211("enter\n");
7132
7133         mutex_lock(&priv->mutex);
7134
7135         if (iwl3945_is_ready_rf(priv)) {
7136                 iwl3945_scan_cancel_timeout(priv, 100);
7137                 cancel_delayed_work(&priv->post_associate);
7138                 priv->staging_rxon.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
7139                 iwl3945_commit_rxon(priv);
7140         }
7141         if (priv->vif == conf->vif) {
7142                 priv->vif = NULL;
7143                 memset(priv->bssid, 0, ETH_ALEN);
7144                 memset(priv->essid, 0, IW_ESSID_MAX_SIZE);
7145                 priv->essid_len = 0;
7146         }
7147         mutex_unlock(&priv->mutex);
7148
7149         IWL_DEBUG_MAC80211("leave\n");
7150 }
7151
7152 static int iwl3945_mac_hw_scan(struct ieee80211_hw *hw, u8 *ssid, size_t len)
7153 {
7154         int rc = 0;
7155         unsigned long flags;
7156         struct iwl3945_priv *priv = hw->priv;
7157
7158         IWL_DEBUG_MAC80211("enter\n");
7159
7160         mutex_lock(&priv->mutex);
7161         spin_lock_irqsave(&priv->lock, flags);
7162
7163         if (!iwl3945_is_ready_rf(priv)) {
7164                 rc = -EIO;
7165                 IWL_DEBUG_MAC80211("leave - not ready or exit pending\n");
7166                 goto out_unlock;
7167         }
7168
7169         if (priv->iw_mode == IEEE80211_IF_TYPE_AP) {    /* APs don't scan */
7170                 rc = -EIO;
7171                 IWL_ERROR("ERROR: APs don't scan\n");
7172                 goto out_unlock;
7173         }
7174
7175         /* we don't schedule scan within next_scan_jiffies period */
7176         if (priv->next_scan_jiffies &&
7177                         time_after(priv->next_scan_jiffies, jiffies)) {
7178                 rc = -EAGAIN;
7179                 goto out_unlock;
7180         }
7181         /* if we just finished scan ask for delay */
7182         if (priv->last_scan_jiffies && time_after(priv->last_scan_jiffies +
7183                                 IWL_DELAY_NEXT_SCAN, jiffies)) {
7184                 rc = -EAGAIN;
7185                 goto out_unlock;
7186         }
7187         if (len) {
7188                 IWL_DEBUG_SCAN("direct scan for %s [%d]\n ",
7189                                iwl3945_escape_essid(ssid, len), (int)len);
7190
7191                 priv->one_direct_scan = 1;
7192                 priv->direct_ssid_len = (u8)
7193                     min((u8) len, (u8) IW_ESSID_MAX_SIZE);
7194                 memcpy(priv->direct_ssid, ssid, priv->direct_ssid_len);
7195         } else
7196                 priv->one_direct_scan = 0;
7197
7198         rc = iwl3945_scan_initiate(priv);
7199
7200         IWL_DEBUG_MAC80211("leave\n");
7201
7202 out_unlock:
7203         spin_unlock_irqrestore(&priv->lock, flags);
7204         mutex_unlock(&priv->mutex);
7205
7206         return rc;
7207 }
7208
7209 static int iwl3945_mac_set_key(struct ieee80211_hw *hw, enum set_key_cmd cmd,
7210                            const u8 *local_addr, const u8 *addr,
7211                            struct ieee80211_key_conf *key)
7212 {
7213         struct iwl3945_priv *priv = hw->priv;
7214         int rc = 0;
7215         u8 sta_id;
7216
7217         IWL_DEBUG_MAC80211("enter\n");
7218
7219         if (!iwl3945_param_hwcrypto) {
7220                 IWL_DEBUG_MAC80211("leave - hwcrypto disabled\n");
7221                 return -EOPNOTSUPP;
7222         }
7223
7224         if (is_zero_ether_addr(addr))
7225                 /* only support pairwise keys */
7226                 return -EOPNOTSUPP;
7227
7228         sta_id = iwl3945_hw_find_station(priv, addr);
7229         if (sta_id == IWL_INVALID_STATION) {
7230                 DECLARE_MAC_BUF(mac);
7231
7232                 IWL_DEBUG_MAC80211("leave - %s not in station map.\n",
7233                                    print_mac(mac, addr));
7234                 return -EINVAL;
7235         }
7236
7237         mutex_lock(&priv->mutex);
7238
7239         iwl3945_scan_cancel_timeout(priv, 100);
7240
7241         switch (cmd) {
7242         case  SET_KEY:
7243                 rc = iwl3945_update_sta_key_info(priv, key, sta_id);
7244                 if (!rc) {
7245                         iwl3945_set_rxon_hwcrypto(priv, 1);
7246                         iwl3945_commit_rxon(priv);
7247                         key->hw_key_idx = sta_id;
7248                         IWL_DEBUG_MAC80211("set_key success, using hwcrypto\n");
7249                         key->flags |= IEEE80211_KEY_FLAG_GENERATE_IV;
7250                 }
7251                 break;
7252         case DISABLE_KEY:
7253                 rc = iwl3945_clear_sta_key_info(priv, sta_id);
7254                 if (!rc) {
7255                         iwl3945_set_rxon_hwcrypto(priv, 0);
7256                         iwl3945_commit_rxon(priv);
7257                         IWL_DEBUG_MAC80211("disable hwcrypto key\n");
7258                 }
7259                 break;
7260         default:
7261                 rc = -EINVAL;
7262         }
7263
7264         IWL_DEBUG_MAC80211("leave\n");
7265         mutex_unlock(&priv->mutex);
7266
7267         return rc;
7268 }
7269
7270 static int iwl3945_mac_conf_tx(struct ieee80211_hw *hw, int queue,
7271                            const struct ieee80211_tx_queue_params *params)
7272 {
7273         struct iwl3945_priv *priv = hw->priv;
7274         unsigned long flags;
7275         int q;
7276
7277         IWL_DEBUG_MAC80211("enter\n");
7278
7279         if (!iwl3945_is_ready_rf(priv)) {
7280                 IWL_DEBUG_MAC80211("leave - RF not ready\n");
7281                 return -EIO;
7282         }
7283
7284         if (queue >= AC_NUM) {
7285                 IWL_DEBUG_MAC80211("leave - queue >= AC_NUM %d\n", queue);
7286                 return 0;
7287         }
7288
7289         if (!priv->qos_data.qos_enable) {
7290                 priv->qos_data.qos_active = 0;
7291                 IWL_DEBUG_MAC80211("leave - qos not enabled\n");
7292                 return 0;
7293         }
7294         q = AC_NUM - 1 - queue;
7295
7296         spin_lock_irqsave(&priv->lock, flags);
7297
7298         priv->qos_data.def_qos_parm.ac[q].cw_min = cpu_to_le16(params->cw_min);
7299         priv->qos_data.def_qos_parm.ac[q].cw_max = cpu_to_le16(params->cw_max);
7300         priv->qos_data.def_qos_parm.ac[q].aifsn = params->aifs;
7301         priv->qos_data.def_qos_parm.ac[q].edca_txop =
7302                         cpu_to_le16((params->txop * 32));
7303
7304         priv->qos_data.def_qos_parm.ac[q].reserved1 = 0;
7305         priv->qos_data.qos_active = 1;
7306
7307         spin_unlock_irqrestore(&priv->lock, flags);
7308
7309         mutex_lock(&priv->mutex);
7310         if (priv->iw_mode == IEEE80211_IF_TYPE_AP)
7311                 iwl3945_activate_qos(priv, 1);
7312         else if (priv->assoc_id && iwl3945_is_associated(priv))
7313                 iwl3945_activate_qos(priv, 0);
7314
7315         mutex_unlock(&priv->mutex);
7316
7317         IWL_DEBUG_MAC80211("leave\n");
7318         return 0;
7319 }
7320
7321 static int iwl3945_mac_get_tx_stats(struct ieee80211_hw *hw,
7322                                 struct ieee80211_tx_queue_stats *stats)
7323 {
7324         struct iwl3945_priv *priv = hw->priv;
7325         int i, avail;
7326         struct iwl3945_tx_queue *txq;
7327         struct iwl3945_queue *q;
7328         unsigned long flags;
7329
7330         IWL_DEBUG_MAC80211("enter\n");
7331
7332         if (!iwl3945_is_ready_rf(priv)) {
7333                 IWL_DEBUG_MAC80211("leave - RF not ready\n");
7334                 return -EIO;
7335         }
7336
7337         spin_lock_irqsave(&priv->lock, flags);
7338
7339         for (i = 0; i < AC_NUM; i++) {
7340                 txq = &priv->txq[i];
7341                 q = &txq->q;
7342                 avail = iwl3945_queue_space(q);
7343
7344                 stats->data[i].len = q->n_window - avail;
7345                 stats->data[i].limit = q->n_window - q->high_mark;
7346                 stats->data[i].count = q->n_window;
7347
7348         }
7349         spin_unlock_irqrestore(&priv->lock, flags);
7350
7351         IWL_DEBUG_MAC80211("leave\n");
7352
7353         return 0;
7354 }
7355
7356 static int iwl3945_mac_get_stats(struct ieee80211_hw *hw,
7357                              struct ieee80211_low_level_stats *stats)
7358 {
7359         IWL_DEBUG_MAC80211("enter\n");
7360         IWL_DEBUG_MAC80211("leave\n");
7361
7362         return 0;
7363 }
7364
7365 static u64 iwl3945_mac_get_tsf(struct ieee80211_hw *hw)
7366 {
7367         IWL_DEBUG_MAC80211("enter\n");
7368         IWL_DEBUG_MAC80211("leave\n");
7369
7370         return 0;
7371 }
7372
7373 static void iwl3945_mac_reset_tsf(struct ieee80211_hw *hw)
7374 {
7375         struct iwl3945_priv *priv = hw->priv;
7376         unsigned long flags;
7377
7378         mutex_lock(&priv->mutex);
7379         IWL_DEBUG_MAC80211("enter\n");
7380
7381         iwl3945_reset_qos(priv);
7382
7383         cancel_delayed_work(&priv->post_associate);
7384
7385         spin_lock_irqsave(&priv->lock, flags);
7386         priv->assoc_id = 0;
7387         priv->assoc_capability = 0;
7388         priv->call_post_assoc_from_beacon = 0;
7389
7390         /* new association get rid of ibss beacon skb */
7391         if (priv->ibss_beacon)
7392                 dev_kfree_skb(priv->ibss_beacon);
7393
7394         priv->ibss_beacon = NULL;
7395
7396         priv->beacon_int = priv->hw->conf.beacon_int;
7397         priv->timestamp1 = 0;
7398         priv->timestamp0 = 0;
7399         if ((priv->iw_mode == IEEE80211_IF_TYPE_STA))
7400                 priv->beacon_int = 0;
7401
7402         spin_unlock_irqrestore(&priv->lock, flags);
7403
7404         if (!iwl3945_is_ready_rf(priv)) {
7405                 IWL_DEBUG_MAC80211("leave - not ready\n");
7406                 mutex_unlock(&priv->mutex);
7407                 return;
7408         }
7409
7410         /* we are restarting association process
7411          * clear RXON_FILTER_ASSOC_MSK bit
7412         */
7413         if (priv->iw_mode != IEEE80211_IF_TYPE_AP) {
7414                 iwl3945_scan_cancel_timeout(priv, 100);
7415                 priv->staging_rxon.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
7416                 iwl3945_commit_rxon(priv);
7417         }
7418
7419         /* Per mac80211.h: This is only used in IBSS mode... */
7420         if (priv->iw_mode != IEEE80211_IF_TYPE_IBSS) {
7421
7422                 IWL_DEBUG_MAC80211("leave - not in IBSS\n");
7423                 mutex_unlock(&priv->mutex);
7424                 return;
7425         }
7426
7427         priv->only_active_channel = 0;
7428
7429         iwl3945_set_rate(priv);
7430
7431         mutex_unlock(&priv->mutex);
7432
7433         IWL_DEBUG_MAC80211("leave\n");
7434
7435 }
7436
7437 static int iwl3945_mac_beacon_update(struct ieee80211_hw *hw, struct sk_buff *skb,
7438                                  struct ieee80211_tx_control *control)
7439 {
7440         struct iwl3945_priv *priv = hw->priv;
7441         unsigned long flags;
7442
7443         mutex_lock(&priv->mutex);
7444         IWL_DEBUG_MAC80211("enter\n");
7445
7446         if (!iwl3945_is_ready_rf(priv)) {
7447                 IWL_DEBUG_MAC80211("leave - RF not ready\n");
7448                 mutex_unlock(&priv->mutex);
7449                 return -EIO;
7450         }
7451
7452         if (priv->iw_mode != IEEE80211_IF_TYPE_IBSS) {
7453                 IWL_DEBUG_MAC80211("leave - not IBSS\n");
7454                 mutex_unlock(&priv->mutex);
7455                 return -EIO;
7456         }
7457
7458         spin_lock_irqsave(&priv->lock, flags);
7459
7460         if (priv->ibss_beacon)
7461                 dev_kfree_skb(priv->ibss_beacon);
7462
7463         priv->ibss_beacon = skb;
7464
7465         priv->assoc_id = 0;
7466
7467         IWL_DEBUG_MAC80211("leave\n");
7468         spin_unlock_irqrestore(&priv->lock, flags);
7469
7470         iwl3945_reset_qos(priv);
7471
7472         queue_work(priv->workqueue, &priv->post_associate.work);
7473
7474         mutex_unlock(&priv->mutex);
7475
7476         return 0;
7477 }
7478
7479 /*****************************************************************************
7480  *
7481  * sysfs attributes
7482  *
7483  *****************************************************************************/
7484
7485 #ifdef CONFIG_IWL3945_DEBUG
7486
7487 /*
7488  * The following adds a new attribute to the sysfs representation
7489  * of this device driver (i.e. a new file in /sys/bus/pci/drivers/iwl/)
7490  * used for controlling the debug level.
7491  *
7492  * See the level definitions in iwl for details.
7493  */
7494
7495 static ssize_t show_debug_level(struct device_driver *d, char *buf)
7496 {
7497         return sprintf(buf, "0x%08X\n", iwl3945_debug_level);
7498 }
7499 static ssize_t store_debug_level(struct device_driver *d,
7500                                  const char *buf, size_t count)
7501 {
7502         char *p = (char *)buf;
7503         u32 val;
7504
7505         val = simple_strtoul(p, &p, 0);
7506         if (p == buf)
7507                 printk(KERN_INFO DRV_NAME
7508                        ": %s is not in hex or decimal form.\n", buf);
7509         else
7510                 iwl3945_debug_level = val;
7511
7512         return strnlen(buf, count);
7513 }
7514
7515 static DRIVER_ATTR(debug_level, S_IWUSR | S_IRUGO,
7516                    show_debug_level, store_debug_level);
7517
7518 #endif /* CONFIG_IWL3945_DEBUG */
7519
7520 static ssize_t show_rf_kill(struct device *d,
7521                             struct device_attribute *attr, char *buf)
7522 {
7523         /*
7524          * 0 - RF kill not enabled
7525          * 1 - SW based RF kill active (sysfs)
7526          * 2 - HW based RF kill active
7527          * 3 - Both HW and SW based RF kill active
7528          */
7529         struct iwl3945_priv *priv = (struct iwl3945_priv *)d->driver_data;
7530         int val = (test_bit(STATUS_RF_KILL_SW, &priv->status) ? 0x1 : 0x0) |
7531                   (test_bit(STATUS_RF_KILL_HW, &priv->status) ? 0x2 : 0x0);
7532
7533         return sprintf(buf, "%i\n", val);
7534 }
7535
7536 static ssize_t store_rf_kill(struct device *d,
7537                              struct device_attribute *attr,
7538                              const char *buf, size_t count)
7539 {
7540         struct iwl3945_priv *priv = (struct iwl3945_priv *)d->driver_data;
7541
7542         mutex_lock(&priv->mutex);
7543         iwl3945_radio_kill_sw(priv, buf[0] == '1');
7544         mutex_unlock(&priv->mutex);
7545
7546         return count;
7547 }
7548
7549 static DEVICE_ATTR(rf_kill, S_IWUSR | S_IRUGO, show_rf_kill, store_rf_kill);
7550
7551 static ssize_t show_temperature(struct device *d,
7552                                 struct device_attribute *attr, char *buf)
7553 {
7554         struct iwl3945_priv *priv = (struct iwl3945_priv *)d->driver_data;
7555
7556         if (!iwl3945_is_alive(priv))
7557                 return -EAGAIN;
7558
7559         return sprintf(buf, "%d\n", iwl3945_hw_get_temperature(priv));
7560 }
7561
7562 static DEVICE_ATTR(temperature, S_IRUGO, show_temperature, NULL);
7563
7564 static ssize_t show_rs_window(struct device *d,
7565                               struct device_attribute *attr,
7566                               char *buf)
7567 {
7568         struct iwl3945_priv *priv = d->driver_data;
7569         return iwl3945_fill_rs_info(priv->hw, buf, IWL_AP_ID);
7570 }
7571 static DEVICE_ATTR(rs_window, S_IRUGO, show_rs_window, NULL);
7572
7573 static ssize_t show_tx_power(struct device *d,
7574                              struct device_attribute *attr, char *buf)
7575 {
7576         struct iwl3945_priv *priv = (struct iwl3945_priv *)d->driver_data;
7577         return sprintf(buf, "%d\n", priv->user_txpower_limit);
7578 }
7579
7580 static ssize_t store_tx_power(struct device *d,
7581                               struct device_attribute *attr,
7582                               const char *buf, size_t count)
7583 {
7584         struct iwl3945_priv *priv = (struct iwl3945_priv *)d->driver_data;
7585         char *p = (char *)buf;
7586         u32 val;
7587
7588         val = simple_strtoul(p, &p, 10);
7589         if (p == buf)
7590                 printk(KERN_INFO DRV_NAME
7591                        ": %s is not in decimal form.\n", buf);
7592         else
7593                 iwl3945_hw_reg_set_txpower(priv, val);
7594
7595         return count;
7596 }
7597
7598 static DEVICE_ATTR(tx_power, S_IWUSR | S_IRUGO, show_tx_power, store_tx_power);
7599
7600 static ssize_t show_flags(struct device *d,
7601                           struct device_attribute *attr, char *buf)
7602 {
7603         struct iwl3945_priv *priv = (struct iwl3945_priv *)d->driver_data;
7604
7605         return sprintf(buf, "0x%04X\n", priv->active_rxon.flags);
7606 }
7607
7608 static ssize_t store_flags(struct device *d,
7609                            struct device_attribute *attr,
7610                            const char *buf, size_t count)
7611 {
7612         struct iwl3945_priv *priv = (struct iwl3945_priv *)d->driver_data;
7613         u32 flags = simple_strtoul(buf, NULL, 0);
7614
7615         mutex_lock(&priv->mutex);
7616         if (le32_to_cpu(priv->staging_rxon.flags) != flags) {
7617                 /* Cancel any currently running scans... */
7618                 if (iwl3945_scan_cancel_timeout(priv, 100))
7619                         IWL_WARNING("Could not cancel scan.\n");
7620                 else {
7621                         IWL_DEBUG_INFO("Committing rxon.flags = 0x%04X\n",
7622                                        flags);
7623                         priv->staging_rxon.flags = cpu_to_le32(flags);
7624                         iwl3945_commit_rxon(priv);
7625                 }
7626         }
7627         mutex_unlock(&priv->mutex);
7628
7629         return count;
7630 }
7631
7632 static DEVICE_ATTR(flags, S_IWUSR | S_IRUGO, show_flags, store_flags);
7633
7634 static ssize_t show_filter_flags(struct device *d,
7635                                  struct device_attribute *attr, char *buf)
7636 {
7637         struct iwl3945_priv *priv = (struct iwl3945_priv *)d->driver_data;
7638
7639         return sprintf(buf, "0x%04X\n",
7640                 le32_to_cpu(priv->active_rxon.filter_flags));
7641 }
7642
7643 static ssize_t store_filter_flags(struct device *d,
7644                                   struct device_attribute *attr,
7645                                   const char *buf, size_t count)
7646 {
7647         struct iwl3945_priv *priv = (struct iwl3945_priv *)d->driver_data;
7648         u32 filter_flags = simple_strtoul(buf, NULL, 0);
7649
7650         mutex_lock(&priv->mutex);
7651         if (le32_to_cpu(priv->staging_rxon.filter_flags) != filter_flags) {
7652                 /* Cancel any currently running scans... */
7653                 if (iwl3945_scan_cancel_timeout(priv, 100))
7654                         IWL_WARNING("Could not cancel scan.\n");
7655                 else {
7656                         IWL_DEBUG_INFO("Committing rxon.filter_flags = "
7657                                        "0x%04X\n", filter_flags);
7658                         priv->staging_rxon.filter_flags =
7659                                 cpu_to_le32(filter_flags);
7660                         iwl3945_commit_rxon(priv);
7661                 }
7662         }
7663         mutex_unlock(&priv->mutex);
7664
7665         return count;
7666 }
7667
7668 static DEVICE_ATTR(filter_flags, S_IWUSR | S_IRUGO, show_filter_flags,
7669                    store_filter_flags);
7670
7671 #ifdef CONFIG_IWL3945_SPECTRUM_MEASUREMENT
7672
7673 static ssize_t show_measurement(struct device *d,
7674                                 struct device_attribute *attr, char *buf)
7675 {
7676         struct iwl3945_priv *priv = dev_get_drvdata(d);
7677         struct iwl3945_spectrum_notification measure_report;
7678         u32 size = sizeof(measure_report), len = 0, ofs = 0;
7679         u8 *data = (u8 *) & measure_report;
7680         unsigned long flags;
7681
7682         spin_lock_irqsave(&priv->lock, flags);
7683         if (!(priv->measurement_status & MEASUREMENT_READY)) {
7684                 spin_unlock_irqrestore(&priv->lock, flags);
7685                 return 0;
7686         }
7687         memcpy(&measure_report, &priv->measure_report, size);
7688         priv->measurement_status = 0;
7689         spin_unlock_irqrestore(&priv->lock, flags);
7690
7691         while (size && (PAGE_SIZE - len)) {
7692                 hex_dump_to_buffer(data + ofs, size, 16, 1, buf + len,
7693                                    PAGE_SIZE - len, 1);
7694                 len = strlen(buf);
7695                 if (PAGE_SIZE - len)
7696                         buf[len++] = '\n';
7697
7698                 ofs += 16;
7699                 size -= min(size, 16U);
7700         }
7701
7702         return len;
7703 }
7704
7705 static ssize_t store_measurement(struct device *d,
7706                                  struct device_attribute *attr,
7707                                  const char *buf, size_t count)
7708 {
7709         struct iwl3945_priv *priv = dev_get_drvdata(d);
7710         struct ieee80211_measurement_params params = {
7711                 .channel = le16_to_cpu(priv->active_rxon.channel),
7712                 .start_time = cpu_to_le64(priv->last_tsf),
7713                 .duration = cpu_to_le16(1),
7714         };
7715         u8 type = IWL_MEASURE_BASIC;
7716         u8 buffer[32];
7717         u8 channel;
7718
7719         if (count) {
7720                 char *p = buffer;
7721                 strncpy(buffer, buf, min(sizeof(buffer), count));
7722                 channel = simple_strtoul(p, NULL, 0);
7723                 if (channel)
7724                         params.channel = channel;
7725
7726                 p = buffer;
7727                 while (*p && *p != ' ')
7728                         p++;
7729                 if (*p)
7730                         type = simple_strtoul(p + 1, NULL, 0);
7731         }
7732
7733         IWL_DEBUG_INFO("Invoking measurement of type %d on "
7734                        "channel %d (for '%s')\n", type, params.channel, buf);
7735         iwl3945_get_measurement(priv, &params, type);
7736
7737         return count;
7738 }
7739
7740 static DEVICE_ATTR(measurement, S_IRUSR | S_IWUSR,
7741                    show_measurement, store_measurement);
7742 #endif /* CONFIG_IWL3945_SPECTRUM_MEASUREMENT */
7743
7744 static ssize_t store_retry_rate(struct device *d,
7745                                 struct device_attribute *attr,
7746                                 const char *buf, size_t count)
7747 {
7748         struct iwl3945_priv *priv = dev_get_drvdata(d);
7749
7750         priv->retry_rate = simple_strtoul(buf, NULL, 0);
7751         if (priv->retry_rate <= 0)
7752                 priv->retry_rate = 1;
7753
7754         return count;
7755 }
7756
7757 static ssize_t show_retry_rate(struct device *d,
7758                                struct device_attribute *attr, char *buf)
7759 {
7760         struct iwl3945_priv *priv = dev_get_drvdata(d);
7761         return sprintf(buf, "%d", priv->retry_rate);
7762 }
7763
7764 static DEVICE_ATTR(retry_rate, S_IWUSR | S_IRUSR, show_retry_rate,
7765                    store_retry_rate);
7766
7767 static ssize_t store_power_level(struct device *d,
7768                                  struct device_attribute *attr,
7769                                  const char *buf, size_t count)
7770 {
7771         struct iwl3945_priv *priv = dev_get_drvdata(d);
7772         int rc;
7773         int mode;
7774
7775         mode = simple_strtoul(buf, NULL, 0);
7776         mutex_lock(&priv->mutex);
7777
7778         if (!iwl3945_is_ready(priv)) {
7779                 rc = -EAGAIN;
7780                 goto out;
7781         }
7782
7783         if ((mode < 1) || (mode > IWL_POWER_LIMIT) || (mode == IWL_POWER_AC))
7784                 mode = IWL_POWER_AC;
7785         else
7786                 mode |= IWL_POWER_ENABLED;
7787
7788         if (mode != priv->power_mode) {
7789                 rc = iwl3945_send_power_mode(priv, IWL_POWER_LEVEL(mode));
7790                 if (rc) {
7791                         IWL_DEBUG_MAC80211("failed setting power mode.\n");
7792                         goto out;
7793                 }
7794                 priv->power_mode = mode;
7795         }
7796
7797         rc = count;
7798
7799  out:
7800         mutex_unlock(&priv->mutex);
7801         return rc;
7802 }
7803
7804 #define MAX_WX_STRING 80
7805
7806 /* Values are in microsecond */
7807 static const s32 timeout_duration[] = {
7808         350000,
7809         250000,
7810         75000,
7811         37000,
7812         25000,
7813 };
7814 static const s32 period_duration[] = {
7815         400000,
7816         700000,
7817         1000000,
7818         1000000,
7819         1000000
7820 };
7821
7822 static ssize_t show_power_level(struct device *d,
7823                                 struct device_attribute *attr, char *buf)
7824 {
7825         struct iwl3945_priv *priv = dev_get_drvdata(d);
7826         int level = IWL_POWER_LEVEL(priv->power_mode);
7827         char *p = buf;
7828
7829         p += sprintf(p, "%d ", level);
7830         switch (level) {
7831         case IWL_POWER_MODE_CAM:
7832         case IWL_POWER_AC:
7833                 p += sprintf(p, "(AC)");
7834                 break;
7835         case IWL_POWER_BATTERY:
7836                 p += sprintf(p, "(BATTERY)");
7837                 break;
7838         default:
7839                 p += sprintf(p,
7840                              "(Timeout %dms, Period %dms)",
7841                              timeout_duration[level - 1] / 1000,
7842                              period_duration[level - 1] / 1000);
7843         }
7844
7845         if (!(priv->power_mode & IWL_POWER_ENABLED))
7846                 p += sprintf(p, " OFF\n");
7847         else
7848                 p += sprintf(p, " \n");
7849
7850         return (p - buf + 1);
7851
7852 }
7853
7854 static DEVICE_ATTR(power_level, S_IWUSR | S_IRUSR, show_power_level,
7855                    store_power_level);
7856
7857 static ssize_t show_channels(struct device *d,
7858                              struct device_attribute *attr, char *buf)
7859 {
7860         /* all this shit doesn't belong into sysfs anyway */
7861         return 0;
7862 }
7863
7864 static DEVICE_ATTR(channels, S_IRUSR, show_channels, NULL);
7865
7866 static ssize_t show_statistics(struct device *d,
7867                                struct device_attribute *attr, char *buf)
7868 {
7869         struct iwl3945_priv *priv = dev_get_drvdata(d);
7870         u32 size = sizeof(struct iwl3945_notif_statistics);
7871         u32 len = 0, ofs = 0;
7872         u8 *data = (u8 *) & priv->statistics;
7873         int rc = 0;
7874
7875         if (!iwl3945_is_alive(priv))
7876                 return -EAGAIN;
7877
7878         mutex_lock(&priv->mutex);
7879         rc = iwl3945_send_statistics_request(priv);
7880         mutex_unlock(&priv->mutex);
7881
7882         if (rc) {
7883                 len = sprintf(buf,
7884                               "Error sending statistics request: 0x%08X\n", rc);
7885                 return len;
7886         }
7887
7888         while (size && (PAGE_SIZE - len)) {
7889                 hex_dump_to_buffer(data + ofs, size, 16, 1, buf + len,
7890                                    PAGE_SIZE - len, 1);
7891                 len = strlen(buf);
7892                 if (PAGE_SIZE - len)
7893                         buf[len++] = '\n';
7894
7895                 ofs += 16;
7896                 size -= min(size, 16U);
7897         }
7898
7899         return len;
7900 }
7901
7902 static DEVICE_ATTR(statistics, S_IRUGO, show_statistics, NULL);
7903
7904 static ssize_t show_antenna(struct device *d,
7905                             struct device_attribute *attr, char *buf)
7906 {
7907         struct iwl3945_priv *priv = dev_get_drvdata(d);
7908
7909         if (!iwl3945_is_alive(priv))
7910                 return -EAGAIN;
7911
7912         return sprintf(buf, "%d\n", priv->antenna);
7913 }
7914
7915 static ssize_t store_antenna(struct device *d,
7916                              struct device_attribute *attr,
7917                              const char *buf, size_t count)
7918 {
7919         int ant;
7920         struct iwl3945_priv *priv = dev_get_drvdata(d);
7921
7922         if (count == 0)
7923                 return 0;
7924
7925         if (sscanf(buf, "%1i", &ant) != 1) {
7926                 IWL_DEBUG_INFO("not in hex or decimal form.\n");
7927                 return count;
7928         }
7929
7930         if ((ant >= 0) && (ant <= 2)) {
7931                 IWL_DEBUG_INFO("Setting antenna select to %d.\n", ant);
7932                 priv->antenna = (enum iwl3945_antenna)ant;
7933         } else
7934                 IWL_DEBUG_INFO("Bad antenna select value %d.\n", ant);
7935
7936
7937         return count;
7938 }
7939
7940 static DEVICE_ATTR(antenna, S_IWUSR | S_IRUGO, show_antenna, store_antenna);
7941
7942 static ssize_t show_status(struct device *d,
7943                            struct device_attribute *attr, char *buf)
7944 {
7945         struct iwl3945_priv *priv = (struct iwl3945_priv *)d->driver_data;
7946         if (!iwl3945_is_alive(priv))
7947                 return -EAGAIN;
7948         return sprintf(buf, "0x%08x\n", (int)priv->status);
7949 }
7950
7951 static DEVICE_ATTR(status, S_IRUGO, show_status, NULL);
7952
7953 static ssize_t dump_error_log(struct device *d,
7954                               struct device_attribute *attr,
7955                               const char *buf, size_t count)
7956 {
7957         char *p = (char *)buf;
7958
7959         if (p[0] == '1')
7960                 iwl3945_dump_nic_error_log((struct iwl3945_priv *)d->driver_data);
7961
7962         return strnlen(buf, count);
7963 }
7964
7965 static DEVICE_ATTR(dump_errors, S_IWUSR, NULL, dump_error_log);
7966
7967 static ssize_t dump_event_log(struct device *d,
7968                               struct device_attribute *attr,
7969                               const char *buf, size_t count)
7970 {
7971         char *p = (char *)buf;
7972
7973         if (p[0] == '1')
7974                 iwl3945_dump_nic_event_log((struct iwl3945_priv *)d->driver_data);
7975
7976         return strnlen(buf, count);
7977 }
7978
7979 static DEVICE_ATTR(dump_events, S_IWUSR, NULL, dump_event_log);
7980
7981 /*****************************************************************************
7982  *
7983  * driver setup and teardown
7984  *
7985  *****************************************************************************/
7986
7987 static void iwl3945_setup_deferred_work(struct iwl3945_priv *priv)
7988 {
7989         priv->workqueue = create_workqueue(DRV_NAME);
7990
7991         init_waitqueue_head(&priv->wait_command_queue);
7992
7993         INIT_WORK(&priv->up, iwl3945_bg_up);
7994         INIT_WORK(&priv->restart, iwl3945_bg_restart);
7995         INIT_WORK(&priv->rx_replenish, iwl3945_bg_rx_replenish);
7996         INIT_WORK(&priv->scan_completed, iwl3945_bg_scan_completed);
7997         INIT_WORK(&priv->request_scan, iwl3945_bg_request_scan);
7998         INIT_WORK(&priv->abort_scan, iwl3945_bg_abort_scan);
7999         INIT_WORK(&priv->rf_kill, iwl3945_bg_rf_kill);
8000         INIT_WORK(&priv->beacon_update, iwl3945_bg_beacon_update);
8001         INIT_DELAYED_WORK(&priv->post_associate, iwl3945_bg_post_associate);
8002         INIT_DELAYED_WORK(&priv->init_alive_start, iwl3945_bg_init_alive_start);
8003         INIT_DELAYED_WORK(&priv->alive_start, iwl3945_bg_alive_start);
8004         INIT_DELAYED_WORK(&priv->scan_check, iwl3945_bg_scan_check);
8005
8006         iwl3945_hw_setup_deferred_work(priv);
8007
8008         tasklet_init(&priv->irq_tasklet, (void (*)(unsigned long))
8009                      iwl3945_irq_tasklet, (unsigned long)priv);
8010 }
8011
8012 static void iwl3945_cancel_deferred_work(struct iwl3945_priv *priv)
8013 {
8014         iwl3945_hw_cancel_deferred_work(priv);
8015
8016         cancel_delayed_work_sync(&priv->init_alive_start);
8017         cancel_delayed_work(&priv->scan_check);
8018         cancel_delayed_work(&priv->alive_start);
8019         cancel_delayed_work(&priv->post_associate);
8020         cancel_work_sync(&priv->beacon_update);
8021 }
8022
8023 static struct attribute *iwl3945_sysfs_entries[] = {
8024         &dev_attr_antenna.attr,
8025         &dev_attr_channels.attr,
8026         &dev_attr_dump_errors.attr,
8027         &dev_attr_dump_events.attr,
8028         &dev_attr_flags.attr,
8029         &dev_attr_filter_flags.attr,
8030 #ifdef CONFIG_IWL3945_SPECTRUM_MEASUREMENT
8031         &dev_attr_measurement.attr,
8032 #endif
8033         &dev_attr_power_level.attr,
8034         &dev_attr_retry_rate.attr,
8035         &dev_attr_rf_kill.attr,
8036         &dev_attr_rs_window.attr,
8037         &dev_attr_statistics.attr,
8038         &dev_attr_status.attr,
8039         &dev_attr_temperature.attr,
8040         &dev_attr_tx_power.attr,
8041
8042         NULL
8043 };
8044
8045 static struct attribute_group iwl3945_attribute_group = {
8046         .name = NULL,           /* put in device directory */
8047         .attrs = iwl3945_sysfs_entries,
8048 };
8049
8050 static struct ieee80211_ops iwl3945_hw_ops = {
8051         .tx = iwl3945_mac_tx,
8052         .start = iwl3945_mac_start,
8053         .stop = iwl3945_mac_stop,
8054         .add_interface = iwl3945_mac_add_interface,
8055         .remove_interface = iwl3945_mac_remove_interface,
8056         .config = iwl3945_mac_config,
8057         .config_interface = iwl3945_mac_config_interface,
8058         .configure_filter = iwl3945_configure_filter,
8059         .set_key = iwl3945_mac_set_key,
8060         .get_stats = iwl3945_mac_get_stats,
8061         .get_tx_stats = iwl3945_mac_get_tx_stats,
8062         .conf_tx = iwl3945_mac_conf_tx,
8063         .get_tsf = iwl3945_mac_get_tsf,
8064         .reset_tsf = iwl3945_mac_reset_tsf,
8065         .beacon_update = iwl3945_mac_beacon_update,
8066         .hw_scan = iwl3945_mac_hw_scan
8067 };
8068
8069 static int iwl3945_pci_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
8070 {
8071         int err = 0;
8072         struct iwl3945_priv *priv;
8073         struct ieee80211_hw *hw;
8074         struct iwl_3945_cfg *cfg = (struct iwl_3945_cfg *)(ent->driver_data);
8075         int i;
8076         DECLARE_MAC_BUF(mac);
8077
8078         /* Disabling hardware scan means that mac80211 will perform scans
8079          * "the hard way", rather than using device's scan. */
8080         if (iwl3945_param_disable_hw_scan) {
8081                 IWL_DEBUG_INFO("Disabling hw_scan\n");
8082                 iwl3945_hw_ops.hw_scan = NULL;
8083         }
8084
8085         if ((iwl3945_param_queues_num > IWL_MAX_NUM_QUEUES) ||
8086             (iwl3945_param_queues_num < IWL_MIN_NUM_QUEUES)) {
8087                 IWL_ERROR("invalid queues_num, should be between %d and %d\n",
8088                           IWL_MIN_NUM_QUEUES, IWL_MAX_NUM_QUEUES);
8089                 err = -EINVAL;
8090                 goto out;
8091         }
8092
8093         /* mac80211 allocates memory for this device instance, including
8094          *   space for this driver's private structure */
8095         hw = ieee80211_alloc_hw(sizeof(struct iwl3945_priv), &iwl3945_hw_ops);
8096         if (hw == NULL) {
8097                 IWL_ERROR("Can not allocate network device\n");
8098                 err = -ENOMEM;
8099                 goto out;
8100         }
8101         SET_IEEE80211_DEV(hw, &pdev->dev);
8102
8103         hw->rate_control_algorithm = "iwl-3945-rs";
8104
8105         IWL_DEBUG_INFO("*** LOAD DRIVER ***\n");
8106         priv = hw->priv;
8107         priv->hw = hw;
8108
8109         priv->pci_dev = pdev;
8110         priv->cfg = cfg;
8111
8112         /* Select antenna (may be helpful if only one antenna is connected) */
8113         priv->antenna = (enum iwl3945_antenna)iwl3945_param_antenna;
8114 #ifdef CONFIG_IWL3945_DEBUG
8115         iwl3945_debug_level = iwl3945_param_debug;
8116         atomic_set(&priv->restrict_refcnt, 0);
8117 #endif
8118         priv->retry_rate = 1;
8119
8120         priv->ibss_beacon = NULL;
8121
8122         /* Tell mac80211 and its clients (e.g. Wireless Extensions)
8123          *   the range of signal quality values that we'll provide.
8124          * Negative values for level/noise indicate that we'll provide dBm.
8125          * For WE, at least, non-0 values here *enable* display of values
8126          *   in app (iwconfig). */
8127         hw->max_rssi = -20;     /* signal level, negative indicates dBm */
8128         hw->max_noise = -20;    /* noise level, negative indicates dBm */
8129         hw->max_signal = 100;   /* link quality indication (%) */
8130
8131         /* Tell mac80211 our Tx characteristics */
8132         hw->flags = IEEE80211_HW_HOST_GEN_BEACON_TEMPLATE;
8133
8134         /* 4 EDCA QOS priorities */
8135         hw->queues = 4;
8136
8137         spin_lock_init(&priv->lock);
8138         spin_lock_init(&priv->power_data.lock);
8139         spin_lock_init(&priv->sta_lock);
8140         spin_lock_init(&priv->hcmd_lock);
8141
8142         for (i = 0; i < IWL_IBSS_MAC_HASH_SIZE; i++)
8143                 INIT_LIST_HEAD(&priv->ibss_mac_hash[i]);
8144
8145         INIT_LIST_HEAD(&priv->free_frames);
8146
8147         mutex_init(&priv->mutex);
8148         if (pci_enable_device(pdev)) {
8149                 err = -ENODEV;
8150                 goto out_ieee80211_free_hw;
8151         }
8152
8153         pci_set_master(pdev);
8154
8155         /* Clear the driver's (not device's) station table */
8156         iwl3945_clear_stations_table(priv);
8157
8158         priv->data_retry_limit = -1;
8159         priv->ieee_channels = NULL;
8160         priv->ieee_rates = NULL;
8161         priv->band = IEEE80211_BAND_2GHZ;
8162
8163         err = pci_set_dma_mask(pdev, DMA_32BIT_MASK);
8164         if (!err)
8165                 err = pci_set_consistent_dma_mask(pdev, DMA_32BIT_MASK);
8166         if (err) {
8167                 printk(KERN_WARNING DRV_NAME ": No suitable DMA available.\n");
8168                 goto out_pci_disable_device;
8169         }
8170
8171         pci_set_drvdata(pdev, priv);
8172         err = pci_request_regions(pdev, DRV_NAME);
8173         if (err)
8174                 goto out_pci_disable_device;
8175
8176         /* We disable the RETRY_TIMEOUT register (0x41) to keep
8177          * PCI Tx retries from interfering with C3 CPU state */
8178         pci_write_config_byte(pdev, 0x41, 0x00);
8179
8180         priv->hw_base = pci_iomap(pdev, 0, 0);
8181         if (!priv->hw_base) {
8182                 err = -ENODEV;
8183                 goto out_pci_release_regions;
8184         }
8185
8186         IWL_DEBUG_INFO("pci_resource_len = 0x%08llx\n",
8187                         (unsigned long long) pci_resource_len(pdev, 0));
8188         IWL_DEBUG_INFO("pci_resource_base = %p\n", priv->hw_base);
8189
8190         /* Initialize module parameter values here */
8191
8192         /* Disable radio (SW RF KILL) via parameter when loading driver */
8193         if (iwl3945_param_disable) {
8194                 set_bit(STATUS_RF_KILL_SW, &priv->status);
8195                 IWL_DEBUG_INFO("Radio disabled.\n");
8196         }
8197
8198         priv->iw_mode = IEEE80211_IF_TYPE_STA;
8199
8200         printk(KERN_INFO DRV_NAME
8201                 ": Detected Intel Wireless WiFi Link %s\n", priv->cfg->name);
8202
8203         /* Device-specific setup */
8204         if (iwl3945_hw_set_hw_setting(priv)) {
8205                 IWL_ERROR("failed to set hw settings\n");
8206                 goto out_iounmap;
8207         }
8208
8209         if (iwl3945_param_qos_enable)
8210                 priv->qos_data.qos_enable = 1;
8211
8212         iwl3945_reset_qos(priv);
8213
8214         priv->qos_data.qos_active = 0;
8215         priv->qos_data.qos_cap.val = 0;
8216
8217         iwl3945_set_rxon_channel(priv, IEEE80211_BAND_2GHZ, 6);
8218         iwl3945_setup_deferred_work(priv);
8219         iwl3945_setup_rx_handlers(priv);
8220
8221         priv->rates_mask = IWL_RATES_MASK;
8222         /* If power management is turned on, default to AC mode */
8223         priv->power_mode = IWL_POWER_AC;
8224         priv->user_txpower_limit = IWL_DEFAULT_TX_POWER;
8225
8226         iwl3945_disable_interrupts(priv);
8227
8228         err = sysfs_create_group(&pdev->dev.kobj, &iwl3945_attribute_group);
8229         if (err) {
8230                 IWL_ERROR("failed to create sysfs device attributes\n");
8231                 goto out_release_irq;
8232         }
8233
8234         /* nic init */
8235         iwl3945_set_bit(priv, CSR_GIO_CHICKEN_BITS,
8236                     CSR_GIO_CHICKEN_BITS_REG_BIT_DIS_L0S_EXIT_TIMER);
8237
8238         iwl3945_set_bit(priv, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_INIT_DONE);
8239         err = iwl3945_poll_bit(priv, CSR_GP_CNTRL,
8240                           CSR_GP_CNTRL_REG_FLAG_MAC_CLOCK_READY,
8241                           CSR_GP_CNTRL_REG_FLAG_MAC_CLOCK_READY, 25000);
8242         if (err < 0) {
8243                 IWL_DEBUG_INFO("Failed to init the card\n");
8244                 goto out_remove_sysfs;
8245         }
8246         /* Read the EEPROM */
8247         err = iwl3945_eeprom_init(priv);
8248         if (err) {
8249                 IWL_ERROR("Unable to init EEPROM\n");
8250                 goto out_remove_sysfs;
8251         }
8252         /* MAC Address location in EEPROM same for 3945/4965 */
8253         get_eeprom_mac(priv, priv->mac_addr);
8254         IWL_DEBUG_INFO("MAC address: %s\n", print_mac(mac, priv->mac_addr));
8255         SET_IEEE80211_PERM_ADDR(priv->hw, priv->mac_addr);
8256
8257         err = iwl3945_init_channel_map(priv);
8258         if (err) {
8259                 IWL_ERROR("initializing regulatory failed: %d\n", err);
8260                 goto out_remove_sysfs;
8261         }
8262
8263         err = iwl3945_init_geos(priv);
8264         if (err) {
8265                 IWL_ERROR("initializing geos failed: %d\n", err);
8266                 goto out_free_channel_map;
8267         }
8268
8269         iwl3945_rate_control_register(priv->hw);
8270         err = ieee80211_register_hw(priv->hw);
8271         if (err) {
8272                 IWL_ERROR("Failed to register network device (error %d)\n", err);
8273                 goto out_free_geos;
8274         }
8275
8276         priv->hw->conf.beacon_int = 100;
8277         priv->mac80211_registered = 1;
8278         pci_save_state(pdev);
8279         pci_disable_device(pdev);
8280
8281         return 0;
8282
8283  out_free_geos:
8284         iwl3945_free_geos(priv);
8285  out_free_channel_map:
8286         iwl3945_free_channel_map(priv);
8287  out_remove_sysfs:
8288         sysfs_remove_group(&pdev->dev.kobj, &iwl3945_attribute_group);
8289
8290  out_release_irq:
8291         destroy_workqueue(priv->workqueue);
8292         priv->workqueue = NULL;
8293         iwl3945_unset_hw_setting(priv);
8294
8295  out_iounmap:
8296         pci_iounmap(pdev, priv->hw_base);
8297  out_pci_release_regions:
8298         pci_release_regions(pdev);
8299  out_pci_disable_device:
8300         pci_disable_device(pdev);
8301         pci_set_drvdata(pdev, NULL);
8302  out_ieee80211_free_hw:
8303         ieee80211_free_hw(priv->hw);
8304  out:
8305         return err;
8306 }
8307
8308 static void iwl3945_pci_remove(struct pci_dev *pdev)
8309 {
8310         struct iwl3945_priv *priv = pci_get_drvdata(pdev);
8311         struct list_head *p, *q;
8312         int i;
8313
8314         if (!priv)
8315                 return;
8316
8317         IWL_DEBUG_INFO("*** UNLOAD DRIVER ***\n");
8318
8319         set_bit(STATUS_EXIT_PENDING, &priv->status);
8320
8321         iwl3945_down(priv);
8322
8323         /* Free MAC hash list for ADHOC */
8324         for (i = 0; i < IWL_IBSS_MAC_HASH_SIZE; i++) {
8325                 list_for_each_safe(p, q, &priv->ibss_mac_hash[i]) {
8326                         list_del(p);
8327                         kfree(list_entry(p, struct iwl3945_ibss_seq, list));
8328                 }
8329         }
8330
8331         sysfs_remove_group(&pdev->dev.kobj, &iwl3945_attribute_group);
8332
8333         iwl3945_dealloc_ucode_pci(priv);
8334
8335         if (priv->rxq.bd)
8336                 iwl3945_rx_queue_free(priv, &priv->rxq);
8337         iwl3945_hw_txq_ctx_free(priv);
8338
8339         iwl3945_unset_hw_setting(priv);
8340         iwl3945_clear_stations_table(priv);
8341
8342         if (priv->mac80211_registered) {
8343                 ieee80211_unregister_hw(priv->hw);
8344                 iwl3945_rate_control_unregister(priv->hw);
8345         }
8346
8347         /*netif_stop_queue(dev); */
8348         flush_workqueue(priv->workqueue);
8349
8350         /* ieee80211_unregister_hw calls iwl3945_mac_stop, which flushes
8351          * priv->workqueue... so we can't take down the workqueue
8352          * until now... */
8353         destroy_workqueue(priv->workqueue);
8354         priv->workqueue = NULL;
8355
8356         pci_iounmap(pdev, priv->hw_base);
8357         pci_release_regions(pdev);
8358         pci_disable_device(pdev);
8359         pci_set_drvdata(pdev, NULL);
8360
8361         iwl3945_free_channel_map(priv);
8362         iwl3945_free_geos(priv);
8363
8364         if (priv->ibss_beacon)
8365                 dev_kfree_skb(priv->ibss_beacon);
8366
8367         ieee80211_free_hw(priv->hw);
8368 }
8369
8370 #ifdef CONFIG_PM
8371
8372 static int iwl3945_pci_suspend(struct pci_dev *pdev, pm_message_t state)
8373 {
8374         struct iwl3945_priv *priv = pci_get_drvdata(pdev);
8375
8376         if (priv->is_open) {
8377                 set_bit(STATUS_IN_SUSPEND, &priv->status);
8378                 iwl3945_mac_stop(priv->hw);
8379                 priv->is_open = 1;
8380         }
8381
8382         pci_set_power_state(pdev, PCI_D3hot);
8383
8384         return 0;
8385 }
8386
8387 static int iwl3945_pci_resume(struct pci_dev *pdev)
8388 {
8389         struct iwl3945_priv *priv = pci_get_drvdata(pdev);
8390
8391         pci_set_power_state(pdev, PCI_D0);
8392
8393         if (priv->is_open)
8394                 iwl3945_mac_start(priv->hw);
8395
8396         clear_bit(STATUS_IN_SUSPEND, &priv->status);
8397         return 0;
8398 }
8399
8400 #endif /* CONFIG_PM */
8401
8402 /*****************************************************************************
8403  *
8404  * driver and module entry point
8405  *
8406  *****************************************************************************/
8407
8408 static struct pci_driver iwl3945_driver = {
8409         .name = DRV_NAME,
8410         .id_table = iwl3945_hw_card_ids,
8411         .probe = iwl3945_pci_probe,
8412         .remove = __devexit_p(iwl3945_pci_remove),
8413 #ifdef CONFIG_PM
8414         .suspend = iwl3945_pci_suspend,
8415         .resume = iwl3945_pci_resume,
8416 #endif
8417 };
8418
8419 static int __init iwl3945_init(void)
8420 {
8421
8422         int ret;
8423         printk(KERN_INFO DRV_NAME ": " DRV_DESCRIPTION ", " DRV_VERSION "\n");
8424         printk(KERN_INFO DRV_NAME ": " DRV_COPYRIGHT "\n");
8425         ret = pci_register_driver(&iwl3945_driver);
8426         if (ret) {
8427                 IWL_ERROR("Unable to initialize PCI module\n");
8428                 return ret;
8429         }
8430 #ifdef CONFIG_IWL3945_DEBUG
8431         ret = driver_create_file(&iwl3945_driver.driver, &driver_attr_debug_level);
8432         if (ret) {
8433                 IWL_ERROR("Unable to create driver sysfs file\n");
8434                 pci_unregister_driver(&iwl3945_driver);
8435                 return ret;
8436         }
8437 #endif
8438
8439         return ret;
8440 }
8441
8442 static void __exit iwl3945_exit(void)
8443 {
8444 #ifdef CONFIG_IWL3945_DEBUG
8445         driver_remove_file(&iwl3945_driver.driver, &driver_attr_debug_level);
8446 #endif
8447         pci_unregister_driver(&iwl3945_driver);
8448 }
8449
8450 module_param_named(antenna, iwl3945_param_antenna, int, 0444);
8451 MODULE_PARM_DESC(antenna, "select antenna (1=Main, 2=Aux, default 0 [both])");
8452 module_param_named(disable, iwl3945_param_disable, int, 0444);
8453 MODULE_PARM_DESC(disable, "manually disable the radio (default 0 [radio on])");
8454 module_param_named(hwcrypto, iwl3945_param_hwcrypto, int, 0444);
8455 MODULE_PARM_DESC(hwcrypto,
8456                  "using hardware crypto engine (default 0 [software])\n");
8457 module_param_named(debug, iwl3945_param_debug, int, 0444);
8458 MODULE_PARM_DESC(debug, "debug output mask");
8459 module_param_named(disable_hw_scan, iwl3945_param_disable_hw_scan, int, 0444);
8460 MODULE_PARM_DESC(disable_hw_scan, "disable hardware scanning (default 0)");
8461
8462 module_param_named(queues_num, iwl3945_param_queues_num, int, 0444);
8463 MODULE_PARM_DESC(queues_num, "number of hw queues.");
8464
8465 /* QoS */
8466 module_param_named(qos_enable, iwl3945_param_qos_enable, int, 0444);
8467 MODULE_PARM_DESC(qos_enable, "enable all QoS functionality");
8468
8469 module_exit(iwl3945_exit);
8470 module_init(iwl3945_init);