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