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