b1464c71ea0a9f5b7cc5025cb1c0d50d52dd19e1
[linux-2.6.git] / 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/init.h>
33 #include <linux/pci.h>
34 #include <linux/dma-mapping.h>
35 #include <linux/delay.h>
36 #include <linux/skbuff.h>
37 #include <linux/netdevice.h>
38 #include <linux/wireless.h>
39 #include <linux/firmware.h>
40 #include <linux/etherdevice.h>
41 #include <linux/if_arp.h>
42
43 #include <net/ieee80211_radiotap.h>
44 #include <net/mac80211.h>
45
46 #include <asm/div64.h>
47
48 #include "iwl-3945-core.h"
49 #include "iwl-3945.h"
50 #include "iwl-helpers.h"
51
52 #ifdef CONFIG_IWL3945_DEBUG
53 u32 iwl3945_debug_level;
54 #endif
55
56 static int iwl3945_tx_queue_update_write_ptr(struct iwl3945_priv *priv,
57                                   struct iwl3945_tx_queue *txq);
58
59 /******************************************************************************
60  *
61  * module boiler plate
62  *
63  ******************************************************************************/
64
65 /* module parameters */
66 static int iwl3945_param_disable_hw_scan; /* def: 0 = use 3945's h/w scan */
67 static int iwl3945_param_debug;    /* def: 0 = minimal debug log messages */
68 static int iwl3945_param_disable;  /* def: 0 = enable radio */
69 static int iwl3945_param_antenna;  /* def: 0 = both antennas (use diversity) */
70 int iwl3945_param_hwcrypto;        /* def: 0 = use software encryption */
71 static int iwl3945_param_qos_enable = 1; /* def: 1 = use quality of service */
72 int iwl3945_param_queues_num = IWL39_MAX_NUM_QUEUES; /* def: 8 Tx queues */
73
74 /*
75  * module name, copyright, version, etc.
76  * NOTE: DRV_NAME is defined in iwlwifi.h for use by iwl-debug.h and printk
77  */
78
79 #define DRV_DESCRIPTION \
80 "Intel(R) PRO/Wireless 3945ABG/BG Network Connection driver for Linux"
81
82 #ifdef CONFIG_IWL3945_DEBUG
83 #define VD "d"
84 #else
85 #define VD
86 #endif
87
88 #ifdef CONFIG_IWL3945_SPECTRUM_MEASUREMENT
89 #define VS "s"
90 #else
91 #define VS
92 #endif
93
94 #define IWLWIFI_VERSION "1.2.26k" VD VS
95 #define DRV_COPYRIGHT   "Copyright(c) 2003-2008 Intel Corporation"
96 #define DRV_VERSION     IWLWIFI_VERSION
97
98
99 MODULE_DESCRIPTION(DRV_DESCRIPTION);
100 MODULE_VERSION(DRV_VERSION);
101 MODULE_AUTHOR(DRV_COPYRIGHT);
102 MODULE_LICENSE("GPL");
103
104 static const struct ieee80211_supported_band *iwl3945_get_band(
105                 struct iwl3945_priv *priv, enum ieee80211_band band)
106 {
107         return priv->hw->wiphy->bands[band];
108 }
109
110 static int iwl3945_is_empty_essid(const char *essid, int essid_len)
111 {
112         /* Single white space is for Linksys APs */
113         if (essid_len == 1 && essid[0] == ' ')
114                 return 1;
115
116         /* Otherwise, if the entire essid is 0, we assume it is hidden */
117         while (essid_len) {
118                 essid_len--;
119                 if (essid[essid_len] != '\0')
120                         return 0;
121         }
122
123         return 1;
124 }
125
126 static const char *iwl3945_escape_essid(const char *essid, u8 essid_len)
127 {
128         static char escaped[IW_ESSID_MAX_SIZE * 2 + 1];
129         const char *s = essid;
130         char *d = escaped;
131
132         if (iwl3945_is_empty_essid(essid, essid_len)) {
133                 memcpy(escaped, "<hidden>", sizeof("<hidden>"));
134                 return escaped;
135         }
136
137         essid_len = min(essid_len, (u8) IW_ESSID_MAX_SIZE);
138         while (essid_len--) {
139                 if (*s == '\0') {
140                         *d++ = '\\';
141                         *d++ = '0';
142                         s++;
143                 } else
144                         *d++ = *s++;
145         }
146         *d = '\0';
147         return escaped;
148 }
149
150 /*************** DMA-QUEUE-GENERAL-FUNCTIONS  *****
151  * DMA services
152  *
153  * Theory of operation
154  *
155  * A Tx or Rx queue resides in host DRAM, and is comprised of a circular buffer
156  * of buffer descriptors, each of which points to one or more data buffers for
157  * the device to read from or fill.  Driver and device exchange status of each
158  * queue via "read" and "write" pointers.  Driver keeps minimum of 2 empty
159  * entries in each circular buffer, to protect against confusing empty and full
160  * queue states.
161  *
162  * The device reads or writes the data in the queues via the device's several
163  * DMA/FIFO channels.  Each queue is mapped to a single DMA channel.
164  *
165  * For Tx queue, there are low mark and high mark limits. If, after queuing
166  * the packet for Tx, free space become < low mark, Tx queue stopped. When
167  * reclaiming packets (on 'tx done IRQ), if free space become > high mark,
168  * Tx queue resumed.
169  *
170  * The 3945 operates with six queues:  One receive queue, one transmit queue
171  * (#4) for sending commands to the device firmware, and four transmit queues
172  * (#0-3) for data tx via EDCA.  An additional 2 HCCA queues are unused.
173  ***************************************************/
174
175 int iwl3945_queue_space(const struct iwl3945_queue *q)
176 {
177         int s = q->read_ptr - q->write_ptr;
178
179         if (q->read_ptr > q->write_ptr)
180                 s -= q->n_bd;
181
182         if (s <= 0)
183                 s += q->n_window;
184         /* keep some reserve to not confuse empty and full situations */
185         s -= 2;
186         if (s < 0)
187                 s = 0;
188         return s;
189 }
190
191 int iwl3945_x2_queue_used(const struct iwl3945_queue *q, int i)
192 {
193         return q->write_ptr > q->read_ptr ?
194                 (i >= q->read_ptr && i < q->write_ptr) :
195                 !(i < q->read_ptr && i >= q->write_ptr);
196 }
197
198
199 static inline u8 get_cmd_index(struct iwl3945_queue *q, u32 index, int is_huge)
200 {
201         /* This is for scan command, the big buffer at end of command array */
202         if (is_huge)
203                 return q->n_window;     /* must be power of 2 */
204
205         /* Otherwise, use normal size buffers */
206         return index & (q->n_window - 1);
207 }
208
209 /**
210  * iwl3945_queue_init - Initialize queue's high/low-water and read/write indexes
211  */
212 static int iwl3945_queue_init(struct iwl3945_priv *priv, struct iwl3945_queue *q,
213                           int count, int slots_num, u32 id)
214 {
215         q->n_bd = count;
216         q->n_window = slots_num;
217         q->id = id;
218
219         /* count must be power-of-two size, otherwise iwl_queue_inc_wrap
220          * and iwl_queue_dec_wrap are broken. */
221         BUG_ON(!is_power_of_2(count));
222
223         /* slots_num must be power-of-two size, otherwise
224          * get_cmd_index is broken. */
225         BUG_ON(!is_power_of_2(slots_num));
226
227         q->low_mark = q->n_window / 4;
228         if (q->low_mark < 4)
229                 q->low_mark = 4;
230
231         q->high_mark = q->n_window / 8;
232         if (q->high_mark < 2)
233                 q->high_mark = 2;
234
235         q->write_ptr = q->read_ptr = 0;
236
237         return 0;
238 }
239
240 /**
241  * iwl3945_tx_queue_alloc - Alloc driver data and TFD CB for one Tx/cmd queue
242  */
243 static int iwl3945_tx_queue_alloc(struct iwl3945_priv *priv,
244                               struct iwl3945_tx_queue *txq, u32 id)
245 {
246         struct pci_dev *dev = priv->pci_dev;
247
248         /* Driver private data, only for Tx (not command) queues,
249          * not shared with device. */
250         if (id != IWL_CMD_QUEUE_NUM) {
251                 txq->txb = kmalloc(sizeof(txq->txb[0]) *
252                                    TFD_QUEUE_SIZE_MAX, GFP_KERNEL);
253                 if (!txq->txb) {
254                         IWL_ERROR("kmalloc for auxiliary BD "
255                                   "structures failed\n");
256                         goto error;
257                 }
258         } else
259                 txq->txb = NULL;
260
261         /* Circular buffer of transmit frame descriptors (TFDs),
262          * shared with device */
263         txq->bd = pci_alloc_consistent(dev,
264                         sizeof(txq->bd[0]) * TFD_QUEUE_SIZE_MAX,
265                         &txq->q.dma_addr);
266
267         if (!txq->bd) {
268                 IWL_ERROR("pci_alloc_consistent(%zd) failed\n",
269                           sizeof(txq->bd[0]) * TFD_QUEUE_SIZE_MAX);
270                 goto error;
271         }
272         txq->q.id = id;
273
274         return 0;
275
276  error:
277         kfree(txq->txb);
278         txq->txb = NULL;
279
280         return -ENOMEM;
281 }
282
283 /**
284  * iwl3945_tx_queue_init - Allocate and initialize one tx/cmd queue
285  */
286 int iwl3945_tx_queue_init(struct iwl3945_priv *priv,
287                       struct iwl3945_tx_queue *txq, int slots_num, u32 txq_id)
288 {
289         struct pci_dev *dev = priv->pci_dev;
290         int len;
291         int rc = 0;
292
293         /*
294          * Alloc buffer array for commands (Tx or other types of commands).
295          * For the command queue (#4), allocate command space + one big
296          * command for scan, since scan command is very huge; the system will
297          * not have two scans at the same time, so only one is needed.
298          * For data Tx queues (all other queues), no super-size command
299          * space is needed.
300          */
301         len = sizeof(struct iwl3945_cmd) * slots_num;
302         if (txq_id == IWL_CMD_QUEUE_NUM)
303                 len +=  IWL_MAX_SCAN_SIZE;
304         txq->cmd = pci_alloc_consistent(dev, len, &txq->dma_addr_cmd);
305         if (!txq->cmd)
306                 return -ENOMEM;
307
308         /* Alloc driver data array and TFD circular buffer */
309         rc = iwl3945_tx_queue_alloc(priv, txq, txq_id);
310         if (rc) {
311                 pci_free_consistent(dev, len, txq->cmd, txq->dma_addr_cmd);
312
313                 return -ENOMEM;
314         }
315         txq->need_update = 0;
316
317         /* TFD_QUEUE_SIZE_MAX must be power-of-two size, otherwise
318          * iwl_queue_inc_wrap and iwl_queue_dec_wrap are broken. */
319         BUILD_BUG_ON(TFD_QUEUE_SIZE_MAX & (TFD_QUEUE_SIZE_MAX - 1));
320
321         /* Initialize queue high/low-water, head/tail indexes */
322         iwl3945_queue_init(priv, &txq->q, TFD_QUEUE_SIZE_MAX, slots_num, txq_id);
323
324         /* Tell device where to find queue, enable DMA channel. */
325         iwl3945_hw_tx_queue_init(priv, txq);
326
327         return 0;
328 }
329
330 /**
331  * iwl3945_tx_queue_free - Deallocate DMA queue.
332  * @txq: Transmit queue to deallocate.
333  *
334  * Empty queue by removing and destroying all BD's.
335  * Free all buffers.
336  * 0-fill, but do not free "txq" descriptor structure.
337  */
338 void iwl3945_tx_queue_free(struct iwl3945_priv *priv, struct iwl3945_tx_queue *txq)
339 {
340         struct iwl3945_queue *q = &txq->q;
341         struct pci_dev *dev = priv->pci_dev;
342         int len;
343
344         if (q->n_bd == 0)
345                 return;
346
347         /* first, empty all BD's */
348         for (; q->write_ptr != q->read_ptr;
349              q->read_ptr = iwl_queue_inc_wrap(q->read_ptr, q->n_bd))
350                 iwl3945_hw_txq_free_tfd(priv, txq);
351
352         len = sizeof(struct iwl3945_cmd) * q->n_window;
353         if (q->id == IWL_CMD_QUEUE_NUM)
354                 len += IWL_MAX_SCAN_SIZE;
355
356         /* De-alloc array of command/tx buffers */
357         pci_free_consistent(dev, len, txq->cmd, txq->dma_addr_cmd);
358
359         /* De-alloc circular buffer of TFDs */
360         if (txq->q.n_bd)
361                 pci_free_consistent(dev, sizeof(struct iwl3945_tfd_frame) *
362                                     txq->q.n_bd, txq->bd, txq->q.dma_addr);
363
364         /* De-alloc array of per-TFD driver data */
365         kfree(txq->txb);
366         txq->txb = NULL;
367
368         /* 0-fill queue descriptor structure */
369         memset(txq, 0, sizeof(*txq));
370 }
371
372 const u8 iwl3945_broadcast_addr[ETH_ALEN] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
373
374 /*************** STATION TABLE MANAGEMENT ****
375  * mac80211 should be examined to determine if sta_info is duplicating
376  * the functionality provided here
377  */
378
379 /**************************************************************/
380 #if 0 /* temporary disable till we add real remove station */
381 /**
382  * iwl3945_remove_station - Remove driver's knowledge of station.
383  *
384  * NOTE:  This does not remove station from device's station table.
385  */
386 static u8 iwl3945_remove_station(struct iwl3945_priv *priv, const u8 *addr, int is_ap)
387 {
388         int index = IWL_INVALID_STATION;
389         int i;
390         unsigned long flags;
391
392         spin_lock_irqsave(&priv->sta_lock, flags);
393
394         if (is_ap)
395                 index = IWL_AP_ID;
396         else if (is_broadcast_ether_addr(addr))
397                 index = priv->hw_setting.bcast_sta_id;
398         else
399                 for (i = IWL_STA_ID; i < priv->hw_setting.max_stations; i++)
400                         if (priv->stations[i].used &&
401                             !compare_ether_addr(priv->stations[i].sta.sta.addr,
402                                                 addr)) {
403                                 index = i;
404                                 break;
405                         }
406
407         if (unlikely(index == IWL_INVALID_STATION))
408                 goto out;
409
410         if (priv->stations[index].used) {
411                 priv->stations[index].used = 0;
412                 priv->num_stations--;
413         }
414
415         BUG_ON(priv->num_stations < 0);
416
417 out:
418         spin_unlock_irqrestore(&priv->sta_lock, flags);
419         return 0;
420 }
421 #endif
422
423 /**
424  * iwl3945_clear_stations_table - Clear the driver's station table
425  *
426  * NOTE:  This does not clear or otherwise alter the device's station table.
427  */
428 static void iwl3945_clear_stations_table(struct iwl3945_priv *priv)
429 {
430         unsigned long flags;
431
432         spin_lock_irqsave(&priv->sta_lock, flags);
433
434         priv->num_stations = 0;
435         memset(priv->stations, 0, sizeof(priv->stations));
436
437         spin_unlock_irqrestore(&priv->sta_lock, flags);
438 }
439
440 /**
441  * iwl3945_add_station - Add station to station tables in driver and device
442  */
443 u8 iwl3945_add_station(struct iwl3945_priv *priv, const u8 *addr, int is_ap, u8 flags)
444 {
445         int i;
446         int index = IWL_INVALID_STATION;
447         struct iwl3945_station_entry *station;
448         unsigned long flags_spin;
449         u8 rate;
450
451         spin_lock_irqsave(&priv->sta_lock, flags_spin);
452         if (is_ap)
453                 index = IWL_AP_ID;
454         else if (is_broadcast_ether_addr(addr))
455                 index = priv->hw_setting.bcast_sta_id;
456         else
457                 for (i = IWL_STA_ID; i < priv->hw_setting.max_stations; i++) {
458                         if (!compare_ether_addr(priv->stations[i].sta.sta.addr,
459                                                 addr)) {
460                                 index = i;
461                                 break;
462                         }
463
464                         if (!priv->stations[i].used &&
465                             index == IWL_INVALID_STATION)
466                                 index = i;
467                 }
468
469         /* These two conditions has the same outcome but keep them separate
470           since they have different meaning */
471         if (unlikely(index == IWL_INVALID_STATION)) {
472                 spin_unlock_irqrestore(&priv->sta_lock, flags_spin);
473                 return index;
474         }
475
476         if (priv->stations[index].used &&
477            !compare_ether_addr(priv->stations[index].sta.sta.addr, addr)) {
478                 spin_unlock_irqrestore(&priv->sta_lock, flags_spin);
479                 return index;
480         }
481
482         IWL_DEBUG_ASSOC("Add STA ID %d: %pM\n", index, addr);
483         station = &priv->stations[index];
484         station->used = 1;
485         priv->num_stations++;
486
487         /* Set up the REPLY_ADD_STA command to send to device */
488         memset(&station->sta, 0, sizeof(struct iwl3945_addsta_cmd));
489         memcpy(station->sta.sta.addr, addr, ETH_ALEN);
490         station->sta.mode = 0;
491         station->sta.sta.sta_id = index;
492         station->sta.station_flags = 0;
493
494         if (priv->band == IEEE80211_BAND_5GHZ)
495                 rate = IWL_RATE_6M_PLCP;
496         else
497                 rate =  IWL_RATE_1M_PLCP;
498
499         /* Turn on both antennas for the station... */
500         station->sta.rate_n_flags =
501                         iwl3945_hw_set_rate_n_flags(rate, RATE_MCS_ANT_AB_MSK);
502         station->current_rate.rate_n_flags =
503                         le16_to_cpu(station->sta.rate_n_flags);
504
505         spin_unlock_irqrestore(&priv->sta_lock, flags_spin);
506
507         /* Add station to device's station table */
508         iwl3945_send_add_station(priv, &station->sta, flags);
509         return index;
510
511 }
512
513 /*************** DRIVER STATUS FUNCTIONS   *****/
514
515 static inline int iwl3945_is_ready(struct iwl3945_priv *priv)
516 {
517         /* The adapter is 'ready' if READY and GEO_CONFIGURED bits are
518          * set but EXIT_PENDING is not */
519         return test_bit(STATUS_READY, &priv->status) &&
520                test_bit(STATUS_GEO_CONFIGURED, &priv->status) &&
521                !test_bit(STATUS_EXIT_PENDING, &priv->status);
522 }
523
524 static inline int iwl3945_is_alive(struct iwl3945_priv *priv)
525 {
526         return test_bit(STATUS_ALIVE, &priv->status);
527 }
528
529 static inline int iwl3945_is_init(struct iwl3945_priv *priv)
530 {
531         return test_bit(STATUS_INIT, &priv->status);
532 }
533
534 static inline int iwl3945_is_rfkill_sw(struct iwl3945_priv *priv)
535 {
536         return test_bit(STATUS_RF_KILL_SW, &priv->status);
537 }
538
539 static inline int iwl3945_is_rfkill_hw(struct iwl3945_priv *priv)
540 {
541         return test_bit(STATUS_RF_KILL_HW, &priv->status);
542 }
543
544 static inline int iwl3945_is_rfkill(struct iwl3945_priv *priv)
545 {
546         return iwl3945_is_rfkill_hw(priv) ||
547                 iwl3945_is_rfkill_sw(priv);
548 }
549
550 static inline int iwl3945_is_ready_rf(struct iwl3945_priv *priv)
551 {
552
553         if (iwl3945_is_rfkill(priv))
554                 return 0;
555
556         return iwl3945_is_ready(priv);
557 }
558
559 /*************** HOST COMMAND QUEUE FUNCTIONS   *****/
560
561 #define IWL_CMD(x) case x : return #x
562
563 static const char *get_cmd_string(u8 cmd)
564 {
565         switch (cmd) {
566                 IWL_CMD(REPLY_ALIVE);
567                 IWL_CMD(REPLY_ERROR);
568                 IWL_CMD(REPLY_RXON);
569                 IWL_CMD(REPLY_RXON_ASSOC);
570                 IWL_CMD(REPLY_QOS_PARAM);
571                 IWL_CMD(REPLY_RXON_TIMING);
572                 IWL_CMD(REPLY_ADD_STA);
573                 IWL_CMD(REPLY_REMOVE_STA);
574                 IWL_CMD(REPLY_REMOVE_ALL_STA);
575                 IWL_CMD(REPLY_3945_RX);
576                 IWL_CMD(REPLY_TX);
577                 IWL_CMD(REPLY_RATE_SCALE);
578                 IWL_CMD(REPLY_LEDS_CMD);
579                 IWL_CMD(REPLY_TX_LINK_QUALITY_CMD);
580                 IWL_CMD(RADAR_NOTIFICATION);
581                 IWL_CMD(REPLY_QUIET_CMD);
582                 IWL_CMD(REPLY_CHANNEL_SWITCH);
583                 IWL_CMD(CHANNEL_SWITCH_NOTIFICATION);
584                 IWL_CMD(REPLY_SPECTRUM_MEASUREMENT_CMD);
585                 IWL_CMD(SPECTRUM_MEASURE_NOTIFICATION);
586                 IWL_CMD(POWER_TABLE_CMD);
587                 IWL_CMD(PM_SLEEP_NOTIFICATION);
588                 IWL_CMD(PM_DEBUG_STATISTIC_NOTIFIC);
589                 IWL_CMD(REPLY_SCAN_CMD);
590                 IWL_CMD(REPLY_SCAN_ABORT_CMD);
591                 IWL_CMD(SCAN_START_NOTIFICATION);
592                 IWL_CMD(SCAN_RESULTS_NOTIFICATION);
593                 IWL_CMD(SCAN_COMPLETE_NOTIFICATION);
594                 IWL_CMD(BEACON_NOTIFICATION);
595                 IWL_CMD(REPLY_TX_BEACON);
596                 IWL_CMD(WHO_IS_AWAKE_NOTIFICATION);
597                 IWL_CMD(QUIET_NOTIFICATION);
598                 IWL_CMD(REPLY_TX_PWR_TABLE_CMD);
599                 IWL_CMD(MEASURE_ABORT_NOTIFICATION);
600                 IWL_CMD(REPLY_BT_CONFIG);
601                 IWL_CMD(REPLY_STATISTICS_CMD);
602                 IWL_CMD(STATISTICS_NOTIFICATION);
603                 IWL_CMD(REPLY_CARD_STATE_CMD);
604                 IWL_CMD(CARD_STATE_NOTIFICATION);
605                 IWL_CMD(MISSED_BEACONS_NOTIFICATION);
606         default:
607                 return "UNKNOWN";
608
609         }
610 }
611
612 #define HOST_COMPLETE_TIMEOUT (HZ / 2)
613
614 /**
615  * iwl3945_enqueue_hcmd - enqueue a uCode command
616  * @priv: device private data point
617  * @cmd: a point to the ucode command structure
618  *
619  * The function returns < 0 values to indicate the operation is
620  * failed. On success, it turns the index (> 0) of command in the
621  * command queue.
622  */
623 static int iwl3945_enqueue_hcmd(struct iwl3945_priv *priv, struct iwl3945_host_cmd *cmd)
624 {
625         struct iwl3945_tx_queue *txq = &priv->txq[IWL_CMD_QUEUE_NUM];
626         struct iwl3945_queue *q = &txq->q;
627         struct iwl3945_tfd_frame *tfd;
628         u32 *control_flags;
629         struct iwl3945_cmd *out_cmd;
630         u32 idx;
631         u16 fix_size = (u16)(cmd->len + sizeof(out_cmd->hdr));
632         dma_addr_t phys_addr;
633         int pad;
634         u16 count;
635         int ret;
636         unsigned long flags;
637
638         /* If any of the command structures end up being larger than
639          * the TFD_MAX_PAYLOAD_SIZE, and it sent as a 'small' command then
640          * we will need to increase the size of the TFD entries */
641         BUG_ON((fix_size > TFD_MAX_PAYLOAD_SIZE) &&
642                !(cmd->meta.flags & CMD_SIZE_HUGE));
643
644
645         if (iwl3945_is_rfkill(priv)) {
646                 IWL_DEBUG_INFO("Not sending command - RF KILL");
647                 return -EIO;
648         }
649
650         if (iwl3945_queue_space(q) < ((cmd->meta.flags & CMD_ASYNC) ? 2 : 1)) {
651                 IWL_ERROR("No space for Tx\n");
652                 return -ENOSPC;
653         }
654
655         spin_lock_irqsave(&priv->hcmd_lock, flags);
656
657         tfd = &txq->bd[q->write_ptr];
658         memset(tfd, 0, sizeof(*tfd));
659
660         control_flags = (u32 *) tfd;
661
662         idx = get_cmd_index(q, q->write_ptr, cmd->meta.flags & CMD_SIZE_HUGE);
663         out_cmd = &txq->cmd[idx];
664
665         out_cmd->hdr.cmd = cmd->id;
666         memcpy(&out_cmd->meta, &cmd->meta, sizeof(cmd->meta));
667         memcpy(&out_cmd->cmd.payload, cmd->data, cmd->len);
668
669         /* At this point, the out_cmd now has all of the incoming cmd
670          * information */
671
672         out_cmd->hdr.flags = 0;
673         out_cmd->hdr.sequence = cpu_to_le16(QUEUE_TO_SEQ(IWL_CMD_QUEUE_NUM) |
674                         INDEX_TO_SEQ(q->write_ptr));
675         if (out_cmd->meta.flags & CMD_SIZE_HUGE)
676                 out_cmd->hdr.sequence |= cpu_to_le16(SEQ_HUGE_FRAME);
677
678         phys_addr = txq->dma_addr_cmd + sizeof(txq->cmd[0]) * idx +
679                         offsetof(struct iwl3945_cmd, hdr);
680         iwl3945_hw_txq_attach_buf_to_tfd(priv, tfd, phys_addr, fix_size);
681
682         pad = U32_PAD(cmd->len);
683         count = TFD_CTL_COUNT_GET(*control_flags);
684         *control_flags = TFD_CTL_COUNT_SET(count) | TFD_CTL_PAD_SET(pad);
685
686         IWL_DEBUG_HC("Sending command %s (#%x), seq: 0x%04X, "
687                      "%d bytes at %d[%d]:%d\n",
688                      get_cmd_string(out_cmd->hdr.cmd),
689                      out_cmd->hdr.cmd, le16_to_cpu(out_cmd->hdr.sequence),
690                      fix_size, q->write_ptr, idx, IWL_CMD_QUEUE_NUM);
691
692         txq->need_update = 1;
693
694         /* Increment and update queue's write index */
695         q->write_ptr = iwl_queue_inc_wrap(q->write_ptr, q->n_bd);
696         ret = iwl3945_tx_queue_update_write_ptr(priv, txq);
697
698         spin_unlock_irqrestore(&priv->hcmd_lock, flags);
699         return ret ? ret : idx;
700 }
701
702 static int iwl3945_send_cmd_async(struct iwl3945_priv *priv, struct iwl3945_host_cmd *cmd)
703 {
704         int ret;
705
706         BUG_ON(!(cmd->meta.flags & CMD_ASYNC));
707
708         /* An asynchronous command can not expect an SKB to be set. */
709         BUG_ON(cmd->meta.flags & CMD_WANT_SKB);
710
711         /* An asynchronous command MUST have a callback. */
712         BUG_ON(!cmd->meta.u.callback);
713
714         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
715                 return -EBUSY;
716
717         ret = iwl3945_enqueue_hcmd(priv, cmd);
718         if (ret < 0) {
719                 IWL_ERROR("Error sending %s: iwl3945_enqueue_hcmd failed: %d\n",
720                           get_cmd_string(cmd->id), ret);
721                 return ret;
722         }
723         return 0;
724 }
725
726 static int iwl3945_send_cmd_sync(struct iwl3945_priv *priv, struct iwl3945_host_cmd *cmd)
727 {
728         int cmd_idx;
729         int ret;
730
731         BUG_ON(cmd->meta.flags & CMD_ASYNC);
732
733          /* A synchronous command can not have a callback set. */
734         BUG_ON(cmd->meta.u.callback != NULL);
735
736         if (test_and_set_bit(STATUS_HCMD_SYNC_ACTIVE, &priv->status)) {
737                 IWL_ERROR("Error sending %s: Already sending a host command\n",
738                           get_cmd_string(cmd->id));
739                 ret = -EBUSY;
740                 goto out;
741         }
742
743         set_bit(STATUS_HCMD_ACTIVE, &priv->status);
744
745         if (cmd->meta.flags & CMD_WANT_SKB)
746                 cmd->meta.source = &cmd->meta;
747
748         cmd_idx = iwl3945_enqueue_hcmd(priv, cmd);
749         if (cmd_idx < 0) {
750                 ret = cmd_idx;
751                 IWL_ERROR("Error sending %s: iwl3945_enqueue_hcmd failed: %d\n",
752                           get_cmd_string(cmd->id), ret);
753                 goto out;
754         }
755
756         ret = wait_event_interruptible_timeout(priv->wait_command_queue,
757                         !test_bit(STATUS_HCMD_ACTIVE, &priv->status),
758                         HOST_COMPLETE_TIMEOUT);
759         if (!ret) {
760                 if (test_bit(STATUS_HCMD_ACTIVE, &priv->status)) {
761                         IWL_ERROR("Error sending %s: time out after %dms.\n",
762                                   get_cmd_string(cmd->id),
763                                   jiffies_to_msecs(HOST_COMPLETE_TIMEOUT));
764
765                         clear_bit(STATUS_HCMD_ACTIVE, &priv->status);
766                         ret = -ETIMEDOUT;
767                         goto cancel;
768                 }
769         }
770
771         if (test_bit(STATUS_RF_KILL_HW, &priv->status)) {
772                 IWL_DEBUG_INFO("Command %s aborted: RF KILL Switch\n",
773                                get_cmd_string(cmd->id));
774                 ret = -ECANCELED;
775                 goto fail;
776         }
777         if (test_bit(STATUS_FW_ERROR, &priv->status)) {
778                 IWL_DEBUG_INFO("Command %s failed: FW Error\n",
779                                get_cmd_string(cmd->id));
780                 ret = -EIO;
781                 goto fail;
782         }
783         if ((cmd->meta.flags & CMD_WANT_SKB) && !cmd->meta.u.skb) {
784                 IWL_ERROR("Error: Response NULL in '%s'\n",
785                           get_cmd_string(cmd->id));
786                 ret = -EIO;
787                 goto out;
788         }
789
790         ret = 0;
791         goto out;
792
793 cancel:
794         if (cmd->meta.flags & CMD_WANT_SKB) {
795                 struct iwl3945_cmd *qcmd;
796
797                 /* Cancel the CMD_WANT_SKB flag for the cmd in the
798                  * TX cmd queue. Otherwise in case the cmd comes
799                  * in later, it will possibly set an invalid
800                  * address (cmd->meta.source). */
801                 qcmd = &priv->txq[IWL_CMD_QUEUE_NUM].cmd[cmd_idx];
802                 qcmd->meta.flags &= ~CMD_WANT_SKB;
803         }
804 fail:
805         if (cmd->meta.u.skb) {
806                 dev_kfree_skb_any(cmd->meta.u.skb);
807                 cmd->meta.u.skb = NULL;
808         }
809 out:
810         clear_bit(STATUS_HCMD_SYNC_ACTIVE, &priv->status);
811         return ret;
812 }
813
814 int iwl3945_send_cmd(struct iwl3945_priv *priv, struct iwl3945_host_cmd *cmd)
815 {
816         if (cmd->meta.flags & CMD_ASYNC)
817                 return iwl3945_send_cmd_async(priv, cmd);
818
819         return iwl3945_send_cmd_sync(priv, cmd);
820 }
821
822 int iwl3945_send_cmd_pdu(struct iwl3945_priv *priv, u8 id, u16 len, const void *data)
823 {
824         struct iwl3945_host_cmd cmd = {
825                 .id = id,
826                 .len = len,
827                 .data = data,
828         };
829
830         return iwl3945_send_cmd_sync(priv, &cmd);
831 }
832
833 static int __must_check iwl3945_send_cmd_u32(struct iwl3945_priv *priv, u8 id, u32 val)
834 {
835         struct iwl3945_host_cmd cmd = {
836                 .id = id,
837                 .len = sizeof(val),
838                 .data = &val,
839         };
840
841         return iwl3945_send_cmd_sync(priv, &cmd);
842 }
843
844 int iwl3945_send_statistics_request(struct iwl3945_priv *priv)
845 {
846         return iwl3945_send_cmd_u32(priv, REPLY_STATISTICS_CMD, 0);
847 }
848
849 /**
850  * iwl3945_set_rxon_channel - Set the phymode and channel values in staging RXON
851  * @band: 2.4 or 5 GHz band
852  * @channel: Any channel valid for the requested band
853
854  * In addition to setting the staging RXON, priv->band is also set.
855  *
856  * NOTE:  Does not commit to the hardware; it sets appropriate bit fields
857  * in the staging RXON flag structure based on the band
858  */
859 static int iwl3945_set_rxon_channel(struct iwl3945_priv *priv,
860                                     enum ieee80211_band band,
861                                     u16 channel)
862 {
863         if (!iwl3945_get_channel_info(priv, band, channel)) {
864                 IWL_DEBUG_INFO("Could not set channel to %d [%d]\n",
865                                channel, band);
866                 return -EINVAL;
867         }
868
869         if ((le16_to_cpu(priv->staging_rxon.channel) == channel) &&
870             (priv->band == band))
871                 return 0;
872
873         priv->staging_rxon.channel = cpu_to_le16(channel);
874         if (band == IEEE80211_BAND_5GHZ)
875                 priv->staging_rxon.flags &= ~RXON_FLG_BAND_24G_MSK;
876         else
877                 priv->staging_rxon.flags |= RXON_FLG_BAND_24G_MSK;
878
879         priv->band = band;
880
881         IWL_DEBUG_INFO("Staging channel set to %d [%d]\n", channel, band);
882
883         return 0;
884 }
885
886 /**
887  * iwl3945_check_rxon_cmd - validate RXON structure is valid
888  *
889  * NOTE:  This is really only useful during development and can eventually
890  * be #ifdef'd out once the driver is stable and folks aren't actively
891  * making changes
892  */
893 static int iwl3945_check_rxon_cmd(struct iwl3945_rxon_cmd *rxon)
894 {
895         int error = 0;
896         int counter = 1;
897
898         if (rxon->flags & RXON_FLG_BAND_24G_MSK) {
899                 error |= le32_to_cpu(rxon->flags &
900                                 (RXON_FLG_TGJ_NARROW_BAND_MSK |
901                                  RXON_FLG_RADAR_DETECT_MSK));
902                 if (error)
903                         IWL_WARNING("check 24G fields %d | %d\n",
904                                     counter++, error);
905         } else {
906                 error |= (rxon->flags & RXON_FLG_SHORT_SLOT_MSK) ?
907                                 0 : le32_to_cpu(RXON_FLG_SHORT_SLOT_MSK);
908                 if (error)
909                         IWL_WARNING("check 52 fields %d | %d\n",
910                                     counter++, error);
911                 error |= le32_to_cpu(rxon->flags & RXON_FLG_CCK_MSK);
912                 if (error)
913                         IWL_WARNING("check 52 CCK %d | %d\n",
914                                     counter++, error);
915         }
916         error |= (rxon->node_addr[0] | rxon->bssid_addr[0]) & 0x1;
917         if (error)
918                 IWL_WARNING("check mac addr %d | %d\n", counter++, error);
919
920         /* make sure basic rates 6Mbps and 1Mbps are supported */
921         error |= (((rxon->ofdm_basic_rates & IWL_RATE_6M_MASK) == 0) &&
922                   ((rxon->cck_basic_rates & IWL_RATE_1M_MASK) == 0));
923         if (error)
924                 IWL_WARNING("check basic rate %d | %d\n", counter++, error);
925
926         error |= (le16_to_cpu(rxon->assoc_id) > 2007);
927         if (error)
928                 IWL_WARNING("check assoc id %d | %d\n", counter++, error);
929
930         error |= ((rxon->flags & (RXON_FLG_CCK_MSK | RXON_FLG_SHORT_SLOT_MSK))
931                         == (RXON_FLG_CCK_MSK | RXON_FLG_SHORT_SLOT_MSK));
932         if (error)
933                 IWL_WARNING("check CCK and short slot %d | %d\n",
934                             counter++, error);
935
936         error |= ((rxon->flags & (RXON_FLG_CCK_MSK | RXON_FLG_AUTO_DETECT_MSK))
937                         == (RXON_FLG_CCK_MSK | RXON_FLG_AUTO_DETECT_MSK));
938         if (error)
939                 IWL_WARNING("check CCK & auto detect %d | %d\n",
940                             counter++, error);
941
942         error |= ((rxon->flags & (RXON_FLG_AUTO_DETECT_MSK |
943                         RXON_FLG_TGG_PROTECT_MSK)) == RXON_FLG_TGG_PROTECT_MSK);
944         if (error)
945                 IWL_WARNING("check TGG and auto detect %d | %d\n",
946                             counter++, error);
947
948         if ((rxon->flags & RXON_FLG_DIS_DIV_MSK))
949                 error |= ((rxon->flags & (RXON_FLG_ANT_B_MSK |
950                                 RXON_FLG_ANT_A_MSK)) == 0);
951         if (error)
952                 IWL_WARNING("check antenna %d %d\n", counter++, error);
953
954         if (error)
955                 IWL_WARNING("Tuning to channel %d\n",
956                             le16_to_cpu(rxon->channel));
957
958         if (error) {
959                 IWL_ERROR("Not a valid iwl3945_rxon_assoc_cmd field values\n");
960                 return -1;
961         }
962         return 0;
963 }
964
965 /**
966  * iwl3945_full_rxon_required - check if full RXON (vs RXON_ASSOC) cmd is needed
967  * @priv: staging_rxon is compared to active_rxon
968  *
969  * If the RXON structure is changing enough to require a new tune,
970  * or is clearing the RXON_FILTER_ASSOC_MSK, then return 1 to indicate that
971  * a new tune (full RXON command, rather than RXON_ASSOC cmd) is required.
972  */
973 static int iwl3945_full_rxon_required(struct iwl3945_priv *priv)
974 {
975
976         /* These items are only settable from the full RXON command */
977         if (!(iwl3945_is_associated(priv)) ||
978             compare_ether_addr(priv->staging_rxon.bssid_addr,
979                                priv->active_rxon.bssid_addr) ||
980             compare_ether_addr(priv->staging_rxon.node_addr,
981                                priv->active_rxon.node_addr) ||
982             compare_ether_addr(priv->staging_rxon.wlap_bssid_addr,
983                                priv->active_rxon.wlap_bssid_addr) ||
984             (priv->staging_rxon.dev_type != priv->active_rxon.dev_type) ||
985             (priv->staging_rxon.channel != priv->active_rxon.channel) ||
986             (priv->staging_rxon.air_propagation !=
987              priv->active_rxon.air_propagation) ||
988             (priv->staging_rxon.assoc_id != priv->active_rxon.assoc_id))
989                 return 1;
990
991         /* flags, filter_flags, ofdm_basic_rates, and cck_basic_rates can
992          * be updated with the RXON_ASSOC command -- however only some
993          * flag transitions are allowed using RXON_ASSOC */
994
995         /* Check if we are not switching bands */
996         if ((priv->staging_rxon.flags & RXON_FLG_BAND_24G_MSK) !=
997             (priv->active_rxon.flags & RXON_FLG_BAND_24G_MSK))
998                 return 1;
999
1000         /* Check if we are switching association toggle */
1001         if ((priv->staging_rxon.filter_flags & RXON_FILTER_ASSOC_MSK) !=
1002                 (priv->active_rxon.filter_flags & RXON_FILTER_ASSOC_MSK))
1003                 return 1;
1004
1005         return 0;
1006 }
1007
1008 static int iwl3945_send_rxon_assoc(struct iwl3945_priv *priv)
1009 {
1010         int rc = 0;
1011         struct iwl3945_rx_packet *res = NULL;
1012         struct iwl3945_rxon_assoc_cmd rxon_assoc;
1013         struct iwl3945_host_cmd cmd = {
1014                 .id = REPLY_RXON_ASSOC,
1015                 .len = sizeof(rxon_assoc),
1016                 .meta.flags = CMD_WANT_SKB,
1017                 .data = &rxon_assoc,
1018         };
1019         const struct iwl3945_rxon_cmd *rxon1 = &priv->staging_rxon;
1020         const struct iwl3945_rxon_cmd *rxon2 = &priv->active_rxon;
1021
1022         if ((rxon1->flags == rxon2->flags) &&
1023             (rxon1->filter_flags == rxon2->filter_flags) &&
1024             (rxon1->cck_basic_rates == rxon2->cck_basic_rates) &&
1025             (rxon1->ofdm_basic_rates == rxon2->ofdm_basic_rates)) {
1026                 IWL_DEBUG_INFO("Using current RXON_ASSOC.  Not resending.\n");
1027                 return 0;
1028         }
1029
1030         rxon_assoc.flags = priv->staging_rxon.flags;
1031         rxon_assoc.filter_flags = priv->staging_rxon.filter_flags;
1032         rxon_assoc.ofdm_basic_rates = priv->staging_rxon.ofdm_basic_rates;
1033         rxon_assoc.cck_basic_rates = priv->staging_rxon.cck_basic_rates;
1034         rxon_assoc.reserved = 0;
1035
1036         rc = iwl3945_send_cmd_sync(priv, &cmd);
1037         if (rc)
1038                 return rc;
1039
1040         res = (struct iwl3945_rx_packet *)cmd.meta.u.skb->data;
1041         if (res->hdr.flags & IWL_CMD_FAILED_MSK) {
1042                 IWL_ERROR("Bad return from REPLY_RXON_ASSOC command\n");
1043                 rc = -EIO;
1044         }
1045
1046         priv->alloc_rxb_skb--;
1047         dev_kfree_skb_any(cmd.meta.u.skb);
1048
1049         return rc;
1050 }
1051
1052 /**
1053  * iwl3945_commit_rxon - commit staging_rxon to hardware
1054  *
1055  * The RXON command in staging_rxon is committed to the hardware and
1056  * the active_rxon structure is updated with the new data.  This
1057  * function correctly transitions out of the RXON_ASSOC_MSK state if
1058  * a HW tune is required based on the RXON structure changes.
1059  */
1060 static int iwl3945_commit_rxon(struct iwl3945_priv *priv)
1061 {
1062         /* cast away the const for active_rxon in this function */
1063         struct iwl3945_rxon_cmd *active_rxon = (void *)&priv->active_rxon;
1064         int rc = 0;
1065
1066         if (!iwl3945_is_alive(priv))
1067                 return -1;
1068
1069         /* always get timestamp with Rx frame */
1070         priv->staging_rxon.flags |= RXON_FLG_TSF2HOST_MSK;
1071
1072         /* select antenna */
1073         priv->staging_rxon.flags &=
1074             ~(RXON_FLG_DIS_DIV_MSK | RXON_FLG_ANT_SEL_MSK);
1075         priv->staging_rxon.flags |= iwl3945_get_antenna_flags(priv);
1076
1077         rc = iwl3945_check_rxon_cmd(&priv->staging_rxon);
1078         if (rc) {
1079                 IWL_ERROR("Invalid RXON configuration.  Not committing.\n");
1080                 return -EINVAL;
1081         }
1082
1083         /* If we don't need to send a full RXON, we can use
1084          * iwl3945_rxon_assoc_cmd which is used to reconfigure filter
1085          * and other flags for the current radio configuration. */
1086         if (!iwl3945_full_rxon_required(priv)) {
1087                 rc = iwl3945_send_rxon_assoc(priv);
1088                 if (rc) {
1089                         IWL_ERROR("Error setting RXON_ASSOC "
1090                                   "configuration (%d).\n", rc);
1091                         return rc;
1092                 }
1093
1094                 memcpy(active_rxon, &priv->staging_rxon, sizeof(*active_rxon));
1095
1096                 return 0;
1097         }
1098
1099         /* If we are currently associated and the new config requires
1100          * an RXON_ASSOC and the new config wants the associated mask enabled,
1101          * we must clear the associated from the active configuration
1102          * before we apply the new config */
1103         if (iwl3945_is_associated(priv) &&
1104             (priv->staging_rxon.filter_flags & RXON_FILTER_ASSOC_MSK)) {
1105                 IWL_DEBUG_INFO("Toggling associated bit on current RXON\n");
1106                 active_rxon->filter_flags &= ~RXON_FILTER_ASSOC_MSK;
1107
1108                 rc = iwl3945_send_cmd_pdu(priv, REPLY_RXON,
1109                                       sizeof(struct iwl3945_rxon_cmd),
1110                                       &priv->active_rxon);
1111
1112                 /* If the mask clearing failed then we set
1113                  * active_rxon back to what it was previously */
1114                 if (rc) {
1115                         active_rxon->filter_flags |= RXON_FILTER_ASSOC_MSK;
1116                         IWL_ERROR("Error clearing ASSOC_MSK on current "
1117                                   "configuration (%d).\n", rc);
1118                         return rc;
1119                 }
1120         }
1121
1122         IWL_DEBUG_INFO("Sending RXON\n"
1123                        "* with%s RXON_FILTER_ASSOC_MSK\n"
1124                        "* channel = %d\n"
1125                        "* bssid = %pM\n",
1126                        ((priv->staging_rxon.filter_flags &
1127                          RXON_FILTER_ASSOC_MSK) ? "" : "out"),
1128                        le16_to_cpu(priv->staging_rxon.channel),
1129                        priv->staging_rxon.bssid_addr);
1130
1131         /* Apply the new configuration */
1132         rc = iwl3945_send_cmd_pdu(priv, REPLY_RXON,
1133                               sizeof(struct iwl3945_rxon_cmd), &priv->staging_rxon);
1134         if (rc) {
1135                 IWL_ERROR("Error setting new configuration (%d).\n", rc);
1136                 return rc;
1137         }
1138
1139         memcpy(active_rxon, &priv->staging_rxon, sizeof(*active_rxon));
1140
1141         iwl3945_clear_stations_table(priv);
1142
1143         /* If we issue a new RXON command which required a tune then we must
1144          * send a new TXPOWER command or we won't be able to Tx any frames */
1145         rc = iwl3945_hw_reg_send_txpower(priv);
1146         if (rc) {
1147                 IWL_ERROR("Error setting Tx power (%d).\n", rc);
1148                 return rc;
1149         }
1150
1151         /* Add the broadcast address so we can send broadcast frames */
1152         if (iwl3945_add_station(priv, iwl3945_broadcast_addr, 0, 0) ==
1153             IWL_INVALID_STATION) {
1154                 IWL_ERROR("Error adding BROADCAST address for transmit.\n");
1155                 return -EIO;
1156         }
1157
1158         /* If we have set the ASSOC_MSK and we are in BSS mode then
1159          * add the IWL_AP_ID to the station rate table */
1160         if (iwl3945_is_associated(priv) &&
1161             (priv->iw_mode == NL80211_IFTYPE_STATION))
1162                 if (iwl3945_add_station(priv, priv->active_rxon.bssid_addr, 1, 0)
1163                     == IWL_INVALID_STATION) {
1164                         IWL_ERROR("Error adding AP address for transmit.\n");
1165                         return -EIO;
1166                 }
1167
1168         /* Init the hardware's rate fallback order based on the band */
1169         rc = iwl3945_init_hw_rate_table(priv);
1170         if (rc) {
1171                 IWL_ERROR("Error setting HW rate table: %02X\n", rc);
1172                 return -EIO;
1173         }
1174
1175         return 0;
1176 }
1177
1178 static int iwl3945_send_bt_config(struct iwl3945_priv *priv)
1179 {
1180         struct iwl3945_bt_cmd bt_cmd = {
1181                 .flags = 3,
1182                 .lead_time = 0xAA,
1183                 .max_kill = 1,
1184                 .kill_ack_mask = 0,
1185                 .kill_cts_mask = 0,
1186         };
1187
1188         return iwl3945_send_cmd_pdu(priv, REPLY_BT_CONFIG,
1189                                 sizeof(struct iwl3945_bt_cmd), &bt_cmd);
1190 }
1191
1192 static int iwl3945_send_scan_abort(struct iwl3945_priv *priv)
1193 {
1194         int rc = 0;
1195         struct iwl3945_rx_packet *res;
1196         struct iwl3945_host_cmd cmd = {
1197                 .id = REPLY_SCAN_ABORT_CMD,
1198                 .meta.flags = CMD_WANT_SKB,
1199         };
1200
1201         /* If there isn't a scan actively going on in the hardware
1202          * then we are in between scan bands and not actually
1203          * actively scanning, so don't send the abort command */
1204         if (!test_bit(STATUS_SCAN_HW, &priv->status)) {
1205                 clear_bit(STATUS_SCAN_ABORTING, &priv->status);
1206                 return 0;
1207         }
1208
1209         rc = iwl3945_send_cmd_sync(priv, &cmd);
1210         if (rc) {
1211                 clear_bit(STATUS_SCAN_ABORTING, &priv->status);
1212                 return rc;
1213         }
1214
1215         res = (struct iwl3945_rx_packet *)cmd.meta.u.skb->data;
1216         if (res->u.status != CAN_ABORT_STATUS) {
1217                 /* The scan abort will return 1 for success or
1218                  * 2 for "failure".  A failure condition can be
1219                  * due to simply not being in an active scan which
1220                  * can occur if we send the scan abort before we
1221                  * the microcode has notified us that a scan is
1222                  * completed. */
1223                 IWL_DEBUG_INFO("SCAN_ABORT returned %d.\n", res->u.status);
1224                 clear_bit(STATUS_SCAN_ABORTING, &priv->status);
1225                 clear_bit(STATUS_SCAN_HW, &priv->status);
1226         }
1227
1228         dev_kfree_skb_any(cmd.meta.u.skb);
1229
1230         return rc;
1231 }
1232
1233 static int iwl3945_card_state_sync_callback(struct iwl3945_priv *priv,
1234                                         struct iwl3945_cmd *cmd,
1235                                         struct sk_buff *skb)
1236 {
1237         return 1;
1238 }
1239
1240 /*
1241  * CARD_STATE_CMD
1242  *
1243  * Use: Sets the device's internal card state to enable, disable, or halt
1244  *
1245  * When in the 'enable' state the card operates as normal.
1246  * When in the 'disable' state, the card enters into a low power mode.
1247  * When in the 'halt' state, the card is shut down and must be fully
1248  * restarted to come back on.
1249  */
1250 static int iwl3945_send_card_state(struct iwl3945_priv *priv, u32 flags, u8 meta_flag)
1251 {
1252         struct iwl3945_host_cmd cmd = {
1253                 .id = REPLY_CARD_STATE_CMD,
1254                 .len = sizeof(u32),
1255                 .data = &flags,
1256                 .meta.flags = meta_flag,
1257         };
1258
1259         if (meta_flag & CMD_ASYNC)
1260                 cmd.meta.u.callback = iwl3945_card_state_sync_callback;
1261
1262         return iwl3945_send_cmd(priv, &cmd);
1263 }
1264
1265 static int iwl3945_add_sta_sync_callback(struct iwl3945_priv *priv,
1266                                      struct iwl3945_cmd *cmd, struct sk_buff *skb)
1267 {
1268         struct iwl3945_rx_packet *res = NULL;
1269
1270         if (!skb) {
1271                 IWL_ERROR("Error: Response NULL in REPLY_ADD_STA.\n");
1272                 return 1;
1273         }
1274
1275         res = (struct iwl3945_rx_packet *)skb->data;
1276         if (res->hdr.flags & IWL_CMD_FAILED_MSK) {
1277                 IWL_ERROR("Bad return from REPLY_ADD_STA (0x%08X)\n",
1278                           res->hdr.flags);
1279                 return 1;
1280         }
1281
1282         switch (res->u.add_sta.status) {
1283         case ADD_STA_SUCCESS_MSK:
1284                 break;
1285         default:
1286                 break;
1287         }
1288
1289         /* We didn't cache the SKB; let the caller free it */
1290         return 1;
1291 }
1292
1293 int iwl3945_send_add_station(struct iwl3945_priv *priv,
1294                          struct iwl3945_addsta_cmd *sta, u8 flags)
1295 {
1296         struct iwl3945_rx_packet *res = NULL;
1297         int rc = 0;
1298         struct iwl3945_host_cmd cmd = {
1299                 .id = REPLY_ADD_STA,
1300                 .len = sizeof(struct iwl3945_addsta_cmd),
1301                 .meta.flags = flags,
1302                 .data = sta,
1303         };
1304
1305         if (flags & CMD_ASYNC)
1306                 cmd.meta.u.callback = iwl3945_add_sta_sync_callback;
1307         else
1308                 cmd.meta.flags |= CMD_WANT_SKB;
1309
1310         rc = iwl3945_send_cmd(priv, &cmd);
1311
1312         if (rc || (flags & CMD_ASYNC))
1313                 return rc;
1314
1315         res = (struct iwl3945_rx_packet *)cmd.meta.u.skb->data;
1316         if (res->hdr.flags & IWL_CMD_FAILED_MSK) {
1317                 IWL_ERROR("Bad return from REPLY_ADD_STA (0x%08X)\n",
1318                           res->hdr.flags);
1319                 rc = -EIO;
1320         }
1321
1322         if (rc == 0) {
1323                 switch (res->u.add_sta.status) {
1324                 case ADD_STA_SUCCESS_MSK:
1325                         IWL_DEBUG_INFO("REPLY_ADD_STA PASSED\n");
1326                         break;
1327                 default:
1328                         rc = -EIO;
1329                         IWL_WARNING("REPLY_ADD_STA failed\n");
1330                         break;
1331                 }
1332         }
1333
1334         priv->alloc_rxb_skb--;
1335         dev_kfree_skb_any(cmd.meta.u.skb);
1336
1337         return rc;
1338 }
1339
1340 static int iwl3945_update_sta_key_info(struct iwl3945_priv *priv,
1341                                    struct ieee80211_key_conf *keyconf,
1342                                    u8 sta_id)
1343 {
1344         unsigned long flags;
1345         __le16 key_flags = 0;
1346
1347         switch (keyconf->alg) {
1348         case ALG_CCMP:
1349                 key_flags |= STA_KEY_FLG_CCMP;
1350                 key_flags |= cpu_to_le16(
1351                                 keyconf->keyidx << STA_KEY_FLG_KEYID_POS);
1352                 key_flags &= ~STA_KEY_FLG_INVALID;
1353                 break;
1354         case ALG_TKIP:
1355         case ALG_WEP:
1356         default:
1357                 return -EINVAL;
1358         }
1359         spin_lock_irqsave(&priv->sta_lock, flags);
1360         priv->stations[sta_id].keyinfo.alg = keyconf->alg;
1361         priv->stations[sta_id].keyinfo.keylen = keyconf->keylen;
1362         memcpy(priv->stations[sta_id].keyinfo.key, keyconf->key,
1363                keyconf->keylen);
1364
1365         memcpy(priv->stations[sta_id].sta.key.key, keyconf->key,
1366                keyconf->keylen);
1367         priv->stations[sta_id].sta.key.key_flags = key_flags;
1368         priv->stations[sta_id].sta.sta.modify_mask = STA_MODIFY_KEY_MASK;
1369         priv->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
1370
1371         spin_unlock_irqrestore(&priv->sta_lock, flags);
1372
1373         IWL_DEBUG_INFO("hwcrypto: modify ucode station key info\n");
1374         iwl3945_send_add_station(priv, &priv->stations[sta_id].sta, 0);
1375         return 0;
1376 }
1377
1378 static int iwl3945_clear_sta_key_info(struct iwl3945_priv *priv, u8 sta_id)
1379 {
1380         unsigned long flags;
1381
1382         spin_lock_irqsave(&priv->sta_lock, flags);
1383         memset(&priv->stations[sta_id].keyinfo, 0, sizeof(struct iwl3945_hw_key));
1384         memset(&priv->stations[sta_id].sta.key, 0, sizeof(struct iwl3945_keyinfo));
1385         priv->stations[sta_id].sta.key.key_flags = STA_KEY_FLG_NO_ENC;
1386         priv->stations[sta_id].sta.sta.modify_mask = STA_MODIFY_KEY_MASK;
1387         priv->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
1388         spin_unlock_irqrestore(&priv->sta_lock, flags);
1389
1390         IWL_DEBUG_INFO("hwcrypto: clear ucode station key info\n");
1391         iwl3945_send_add_station(priv, &priv->stations[sta_id].sta, 0);
1392         return 0;
1393 }
1394
1395 static void iwl3945_clear_free_frames(struct iwl3945_priv *priv)
1396 {
1397         struct list_head *element;
1398
1399         IWL_DEBUG_INFO("%d frames on pre-allocated heap on clear.\n",
1400                        priv->frames_count);
1401
1402         while (!list_empty(&priv->free_frames)) {
1403                 element = priv->free_frames.next;
1404                 list_del(element);
1405                 kfree(list_entry(element, struct iwl3945_frame, list));
1406                 priv->frames_count--;
1407         }
1408
1409         if (priv->frames_count) {
1410                 IWL_WARNING("%d frames still in use.  Did we lose one?\n",
1411                             priv->frames_count);
1412                 priv->frames_count = 0;
1413         }
1414 }
1415
1416 static struct iwl3945_frame *iwl3945_get_free_frame(struct iwl3945_priv *priv)
1417 {
1418         struct iwl3945_frame *frame;
1419         struct list_head *element;
1420         if (list_empty(&priv->free_frames)) {
1421                 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1422                 if (!frame) {
1423                         IWL_ERROR("Could not allocate frame!\n");
1424                         return NULL;
1425                 }
1426
1427                 priv->frames_count++;
1428                 return frame;
1429         }
1430
1431         element = priv->free_frames.next;
1432         list_del(element);
1433         return list_entry(element, struct iwl3945_frame, list);
1434 }
1435
1436 static void iwl3945_free_frame(struct iwl3945_priv *priv, struct iwl3945_frame *frame)
1437 {
1438         memset(frame, 0, sizeof(*frame));
1439         list_add(&frame->list, &priv->free_frames);
1440 }
1441
1442 unsigned int iwl3945_fill_beacon_frame(struct iwl3945_priv *priv,
1443                                 struct ieee80211_hdr *hdr,
1444                                 const u8 *dest, int left)
1445 {
1446
1447         if (!iwl3945_is_associated(priv) || !priv->ibss_beacon ||
1448             ((priv->iw_mode != NL80211_IFTYPE_ADHOC) &&
1449              (priv->iw_mode != NL80211_IFTYPE_AP)))
1450                 return 0;
1451
1452         if (priv->ibss_beacon->len > left)
1453                 return 0;
1454
1455         memcpy(hdr, priv->ibss_beacon->data, priv->ibss_beacon->len);
1456
1457         return priv->ibss_beacon->len;
1458 }
1459
1460 static u8 iwl3945_rate_get_lowest_plcp(int rate_mask)
1461 {
1462         u8 i;
1463
1464         for (i = IWL_RATE_1M_INDEX; i != IWL_RATE_INVALID;
1465              i = iwl3945_rates[i].next_ieee) {
1466                 if (rate_mask & (1 << i))
1467                         return iwl3945_rates[i].plcp;
1468         }
1469
1470         return IWL_RATE_INVALID;
1471 }
1472
1473 static int iwl3945_send_beacon_cmd(struct iwl3945_priv *priv)
1474 {
1475         struct iwl3945_frame *frame;
1476         unsigned int frame_size;
1477         int rc;
1478         u8 rate;
1479
1480         frame = iwl3945_get_free_frame(priv);
1481
1482         if (!frame) {
1483                 IWL_ERROR("Could not obtain free frame buffer for beacon "
1484                           "command.\n");
1485                 return -ENOMEM;
1486         }
1487
1488         if (!(priv->staging_rxon.flags & RXON_FLG_BAND_24G_MSK)) {
1489                 rate = iwl3945_rate_get_lowest_plcp(priv->active_rate_basic &
1490                                                 0xFF0);
1491                 if (rate == IWL_INVALID_RATE)
1492                         rate = IWL_RATE_6M_PLCP;
1493         } else {
1494                 rate = iwl3945_rate_get_lowest_plcp(priv->active_rate_basic & 0xF);
1495                 if (rate == IWL_INVALID_RATE)
1496                         rate = IWL_RATE_1M_PLCP;
1497         }
1498
1499         frame_size = iwl3945_hw_get_beacon_cmd(priv, frame, rate);
1500
1501         rc = iwl3945_send_cmd_pdu(priv, REPLY_TX_BEACON, frame_size,
1502                               &frame->u.cmd[0]);
1503
1504         iwl3945_free_frame(priv, frame);
1505
1506         return rc;
1507 }
1508
1509 /******************************************************************************
1510  *
1511  * EEPROM related functions
1512  *
1513  ******************************************************************************/
1514
1515 static void get_eeprom_mac(struct iwl3945_priv *priv, u8 *mac)
1516 {
1517         memcpy(mac, priv->eeprom.mac_address, 6);
1518 }
1519
1520 /*
1521  * Clear the OWNER_MSK, to establish driver (instead of uCode running on
1522  * embedded controller) as EEPROM reader; each read is a series of pulses
1523  * to/from the EEPROM chip, not a single event, so even reads could conflict
1524  * if they weren't arbitrated by some ownership mechanism.  Here, the driver
1525  * simply claims ownership, which should be safe when this function is called
1526  * (i.e. before loading uCode!).
1527  */
1528 static inline int iwl3945_eeprom_acquire_semaphore(struct iwl3945_priv *priv)
1529 {
1530         _iwl3945_clear_bit(priv, CSR_EEPROM_GP, CSR_EEPROM_GP_IF_OWNER_MSK);
1531         return 0;
1532 }
1533
1534 /**
1535  * iwl3945_eeprom_init - read EEPROM contents
1536  *
1537  * Load the EEPROM contents from adapter into priv->eeprom
1538  *
1539  * NOTE:  This routine uses the non-debug IO access functions.
1540  */
1541 int iwl3945_eeprom_init(struct iwl3945_priv *priv)
1542 {
1543         u16 *e = (u16 *)&priv->eeprom;
1544         u32 gp = iwl3945_read32(priv, CSR_EEPROM_GP);
1545         u32 r;
1546         int sz = sizeof(priv->eeprom);
1547         int rc;
1548         int i;
1549         u16 addr;
1550
1551         /* The EEPROM structure has several padding buffers within it
1552          * and when adding new EEPROM maps is subject to programmer errors
1553          * which may be very difficult to identify without explicitly
1554          * checking the resulting size of the eeprom map. */
1555         BUILD_BUG_ON(sizeof(priv->eeprom) != IWL_EEPROM_IMAGE_SIZE);
1556
1557         if ((gp & CSR_EEPROM_GP_VALID_MSK) == CSR_EEPROM_GP_BAD_SIGNATURE) {
1558                 IWL_ERROR("EEPROM not found, EEPROM_GP=0x%08x\n", gp);
1559                 return -ENOENT;
1560         }
1561
1562         /* Make sure driver (instead of uCode) is allowed to read EEPROM */
1563         rc = iwl3945_eeprom_acquire_semaphore(priv);
1564         if (rc < 0) {
1565                 IWL_ERROR("Failed to acquire EEPROM semaphore.\n");
1566                 return -ENOENT;
1567         }
1568
1569         /* eeprom is an array of 16bit values */
1570         for (addr = 0; addr < sz; addr += sizeof(u16)) {
1571                 _iwl3945_write32(priv, CSR_EEPROM_REG, addr << 1);
1572                 _iwl3945_clear_bit(priv, CSR_EEPROM_REG, CSR_EEPROM_REG_BIT_CMD);
1573
1574                 for (i = 0; i < IWL_EEPROM_ACCESS_TIMEOUT;
1575                                         i += IWL_EEPROM_ACCESS_DELAY) {
1576                         r = _iwl3945_read_direct32(priv, CSR_EEPROM_REG);
1577                         if (r & CSR_EEPROM_REG_READ_VALID_MSK)
1578                                 break;
1579                         udelay(IWL_EEPROM_ACCESS_DELAY);
1580                 }
1581
1582                 if (!(r & CSR_EEPROM_REG_READ_VALID_MSK)) {
1583                         IWL_ERROR("Time out reading EEPROM[%d]\n", addr);
1584                         return -ETIMEDOUT;
1585                 }
1586                 e[addr / 2] = le16_to_cpu((__force __le16)(r >> 16));
1587         }
1588
1589         return 0;
1590 }
1591
1592 static void iwl3945_unset_hw_setting(struct iwl3945_priv *priv)
1593 {
1594         if (priv->hw_setting.shared_virt)
1595                 pci_free_consistent(priv->pci_dev,
1596                                     sizeof(struct iwl3945_shared),
1597                                     priv->hw_setting.shared_virt,
1598                                     priv->hw_setting.shared_phys);
1599 }
1600
1601 /**
1602  * iwl3945_supported_rate_to_ie - fill in the supported rate in IE field
1603  *
1604  * return : set the bit for each supported rate insert in ie
1605  */
1606 static u16 iwl3945_supported_rate_to_ie(u8 *ie, u16 supported_rate,
1607                                     u16 basic_rate, int *left)
1608 {
1609         u16 ret_rates = 0, bit;
1610         int i;
1611         u8 *cnt = ie;
1612         u8 *rates = ie + 1;
1613
1614         for (bit = 1, i = 0; i < IWL_RATE_COUNT; i++, bit <<= 1) {
1615                 if (bit & supported_rate) {
1616                         ret_rates |= bit;
1617                         rates[*cnt] = iwl3945_rates[i].ieee |
1618                                 ((bit & basic_rate) ? 0x80 : 0x00);
1619                         (*cnt)++;
1620                         (*left)--;
1621                         if ((*left <= 0) ||
1622                             (*cnt >= IWL_SUPPORTED_RATES_IE_LEN))
1623                                 break;
1624                 }
1625         }
1626
1627         return ret_rates;
1628 }
1629
1630 /**
1631  * iwl3945_fill_probe_req - fill in all required fields and IE for probe request
1632  */
1633 static u16 iwl3945_fill_probe_req(struct iwl3945_priv *priv,
1634                               struct ieee80211_mgmt *frame,
1635                               int left, int is_direct)
1636 {
1637         int len = 0;
1638         u8 *pos = NULL;
1639         u16 active_rates, ret_rates, cck_rates;
1640
1641         /* Make sure there is enough space for the probe request,
1642          * two mandatory IEs and the data */
1643         left -= 24;
1644         if (left < 0)
1645                 return 0;
1646         len += 24;
1647
1648         frame->frame_control = cpu_to_le16(IEEE80211_STYPE_PROBE_REQ);
1649         memcpy(frame->da, iwl3945_broadcast_addr, ETH_ALEN);
1650         memcpy(frame->sa, priv->mac_addr, ETH_ALEN);
1651         memcpy(frame->bssid, iwl3945_broadcast_addr, ETH_ALEN);
1652         frame->seq_ctrl = 0;
1653
1654         /* fill in our indirect SSID IE */
1655         /* ...next IE... */
1656
1657         left -= 2;
1658         if (left < 0)
1659                 return 0;
1660         len += 2;
1661         pos = &(frame->u.probe_req.variable[0]);
1662         *pos++ = WLAN_EID_SSID;
1663         *pos++ = 0;
1664
1665         /* fill in our direct SSID IE... */
1666         if (is_direct) {
1667                 /* ...next IE... */
1668                 left -= 2 + priv->essid_len;
1669                 if (left < 0)
1670                         return 0;
1671                 /* ... fill it in... */
1672                 *pos++ = WLAN_EID_SSID;
1673                 *pos++ = priv->essid_len;
1674                 memcpy(pos, priv->essid, priv->essid_len);
1675                 pos += priv->essid_len;
1676                 len += 2 + priv->essid_len;
1677         }
1678
1679         /* fill in supported rate */
1680         /* ...next IE... */
1681         left -= 2;
1682         if (left < 0)
1683                 return 0;
1684
1685         /* ... fill it in... */
1686         *pos++ = WLAN_EID_SUPP_RATES;
1687         *pos = 0;
1688
1689         priv->active_rate = priv->rates_mask;
1690         active_rates = priv->active_rate;
1691         priv->active_rate_basic = priv->rates_mask & IWL_BASIC_RATES_MASK;
1692
1693         cck_rates = IWL_CCK_RATES_MASK & active_rates;
1694         ret_rates = iwl3945_supported_rate_to_ie(pos, cck_rates,
1695                         priv->active_rate_basic, &left);
1696         active_rates &= ~ret_rates;
1697
1698         ret_rates = iwl3945_supported_rate_to_ie(pos, active_rates,
1699                                  priv->active_rate_basic, &left);
1700         active_rates &= ~ret_rates;
1701
1702         len += 2 + *pos;
1703         pos += (*pos) + 1;
1704         if (active_rates == 0)
1705                 goto fill_end;
1706
1707         /* fill in supported extended rate */
1708         /* ...next IE... */
1709         left -= 2;
1710         if (left < 0)
1711                 return 0;
1712         /* ... fill it in... */
1713         *pos++ = WLAN_EID_EXT_SUPP_RATES;
1714         *pos = 0;
1715         iwl3945_supported_rate_to_ie(pos, active_rates,
1716                                  priv->active_rate_basic, &left);
1717         if (*pos > 0)
1718                 len += 2 + *pos;
1719
1720  fill_end:
1721         return (u16)len;
1722 }
1723
1724 /*
1725  * QoS  support
1726 */
1727 static int iwl3945_send_qos_params_command(struct iwl3945_priv *priv,
1728                                        struct iwl3945_qosparam_cmd *qos)
1729 {
1730
1731         return iwl3945_send_cmd_pdu(priv, REPLY_QOS_PARAM,
1732                                 sizeof(struct iwl3945_qosparam_cmd), qos);
1733 }
1734
1735 static void iwl3945_reset_qos(struct iwl3945_priv *priv)
1736 {
1737         u16 cw_min = 15;
1738         u16 cw_max = 1023;
1739         u8 aifs = 2;
1740         u8 is_legacy = 0;
1741         unsigned long flags;
1742         int i;
1743
1744         spin_lock_irqsave(&priv->lock, flags);
1745         priv->qos_data.qos_active = 0;
1746
1747         if (priv->iw_mode == NL80211_IFTYPE_ADHOC) {
1748                 if (priv->qos_data.qos_enable)
1749                         priv->qos_data.qos_active = 1;
1750                 if (!(priv->active_rate & 0xfff0)) {
1751                         cw_min = 31;
1752                         is_legacy = 1;
1753                 }
1754         } else if (priv->iw_mode == NL80211_IFTYPE_AP) {
1755                 if (priv->qos_data.qos_enable)
1756                         priv->qos_data.qos_active = 1;
1757         } else if (!(priv->staging_rxon.flags & RXON_FLG_SHORT_SLOT_MSK)) {
1758                 cw_min = 31;
1759                 is_legacy = 1;
1760         }
1761
1762         if (priv->qos_data.qos_active)
1763                 aifs = 3;
1764
1765         priv->qos_data.def_qos_parm.ac[0].cw_min = cpu_to_le16(cw_min);
1766         priv->qos_data.def_qos_parm.ac[0].cw_max = cpu_to_le16(cw_max);
1767         priv->qos_data.def_qos_parm.ac[0].aifsn = aifs;
1768         priv->qos_data.def_qos_parm.ac[0].edca_txop = 0;
1769         priv->qos_data.def_qos_parm.ac[0].reserved1 = 0;
1770
1771         if (priv->qos_data.qos_active) {
1772                 i = 1;
1773                 priv->qos_data.def_qos_parm.ac[i].cw_min = cpu_to_le16(cw_min);
1774                 priv->qos_data.def_qos_parm.ac[i].cw_max = cpu_to_le16(cw_max);
1775                 priv->qos_data.def_qos_parm.ac[i].aifsn = 7;
1776                 priv->qos_data.def_qos_parm.ac[i].edca_txop = 0;
1777                 priv->qos_data.def_qos_parm.ac[i].reserved1 = 0;
1778
1779                 i = 2;
1780                 priv->qos_data.def_qos_parm.ac[i].cw_min =
1781                         cpu_to_le16((cw_min + 1) / 2 - 1);
1782                 priv->qos_data.def_qos_parm.ac[i].cw_max =
1783                         cpu_to_le16(cw_max);
1784                 priv->qos_data.def_qos_parm.ac[i].aifsn = 2;
1785                 if (is_legacy)
1786                         priv->qos_data.def_qos_parm.ac[i].edca_txop =
1787                                 cpu_to_le16(6016);
1788                 else
1789                         priv->qos_data.def_qos_parm.ac[i].edca_txop =
1790                                 cpu_to_le16(3008);
1791                 priv->qos_data.def_qos_parm.ac[i].reserved1 = 0;
1792
1793                 i = 3;
1794                 priv->qos_data.def_qos_parm.ac[i].cw_min =
1795                         cpu_to_le16((cw_min + 1) / 4 - 1);
1796                 priv->qos_data.def_qos_parm.ac[i].cw_max =
1797                         cpu_to_le16((cw_max + 1) / 2 - 1);
1798                 priv->qos_data.def_qos_parm.ac[i].aifsn = 2;
1799                 priv->qos_data.def_qos_parm.ac[i].reserved1 = 0;
1800                 if (is_legacy)
1801                         priv->qos_data.def_qos_parm.ac[i].edca_txop =
1802                                 cpu_to_le16(3264);
1803                 else
1804                         priv->qos_data.def_qos_parm.ac[i].edca_txop =
1805                                 cpu_to_le16(1504);
1806         } else {
1807                 for (i = 1; i < 4; i++) {
1808                         priv->qos_data.def_qos_parm.ac[i].cw_min =
1809                                 cpu_to_le16(cw_min);
1810                         priv->qos_data.def_qos_parm.ac[i].cw_max =
1811                                 cpu_to_le16(cw_max);
1812                         priv->qos_data.def_qos_parm.ac[i].aifsn = aifs;
1813                         priv->qos_data.def_qos_parm.ac[i].edca_txop = 0;
1814                         priv->qos_data.def_qos_parm.ac[i].reserved1 = 0;
1815                 }
1816         }
1817         IWL_DEBUG_QOS("set QoS to default \n");
1818
1819         spin_unlock_irqrestore(&priv->lock, flags);
1820 }
1821
1822 static void iwl3945_activate_qos(struct iwl3945_priv *priv, u8 force)
1823 {
1824         unsigned long flags;
1825
1826         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
1827                 return;
1828
1829         if (!priv->qos_data.qos_enable)
1830                 return;
1831
1832         spin_lock_irqsave(&priv->lock, flags);
1833         priv->qos_data.def_qos_parm.qos_flags = 0;
1834
1835         if (priv->qos_data.qos_cap.q_AP.queue_request &&
1836             !priv->qos_data.qos_cap.q_AP.txop_request)
1837                 priv->qos_data.def_qos_parm.qos_flags |=
1838                         QOS_PARAM_FLG_TXOP_TYPE_MSK;
1839
1840         if (priv->qos_data.qos_active)
1841                 priv->qos_data.def_qos_parm.qos_flags |=
1842                         QOS_PARAM_FLG_UPDATE_EDCA_MSK;
1843
1844         spin_unlock_irqrestore(&priv->lock, flags);
1845
1846         if (force || iwl3945_is_associated(priv)) {
1847                 IWL_DEBUG_QOS("send QoS cmd with Qos active %d \n",
1848                               priv->qos_data.qos_active);
1849
1850                 iwl3945_send_qos_params_command(priv,
1851                                 &(priv->qos_data.def_qos_parm));
1852         }
1853 }
1854
1855 /*
1856  * Power management (not Tx power!) functions
1857  */
1858 #define MSEC_TO_USEC 1024
1859
1860 #define NOSLP __constant_cpu_to_le32(0)
1861 #define SLP IWL_POWER_DRIVER_ALLOW_SLEEP_MSK
1862 #define SLP_TIMEOUT(T) __constant_cpu_to_le32((T) * MSEC_TO_USEC)
1863 #define SLP_VEC(X0, X1, X2, X3, X4) {__constant_cpu_to_le32(X0), \
1864                                      __constant_cpu_to_le32(X1), \
1865                                      __constant_cpu_to_le32(X2), \
1866                                      __constant_cpu_to_le32(X3), \
1867                                      __constant_cpu_to_le32(X4)}
1868
1869
1870 /* default power management (not Tx power) table values */
1871 /* for tim  0-10 */
1872 static struct iwl3945_power_vec_entry range_0[IWL_POWER_AC] = {
1873         {{NOSLP, SLP_TIMEOUT(0), SLP_TIMEOUT(0), SLP_VEC(0, 0, 0, 0, 0)}, 0},
1874         {{SLP, SLP_TIMEOUT(200), SLP_TIMEOUT(500), SLP_VEC(1, 2, 3, 4, 4)}, 0},
1875         {{SLP, SLP_TIMEOUT(200), SLP_TIMEOUT(300), SLP_VEC(2, 4, 6, 7, 7)}, 0},
1876         {{SLP, SLP_TIMEOUT(50), SLP_TIMEOUT(100), SLP_VEC(2, 6, 9, 9, 10)}, 0},
1877         {{SLP, SLP_TIMEOUT(50), SLP_TIMEOUT(25), SLP_VEC(2, 7, 9, 9, 10)}, 1},
1878         {{SLP, SLP_TIMEOUT(25), SLP_TIMEOUT(25), SLP_VEC(4, 7, 10, 10, 10)}, 1}
1879 };
1880
1881 /* for tim > 10 */
1882 static struct iwl3945_power_vec_entry range_1[IWL_POWER_AC] = {
1883         {{NOSLP, SLP_TIMEOUT(0), SLP_TIMEOUT(0), SLP_VEC(0, 0, 0, 0, 0)}, 0},
1884         {{SLP, SLP_TIMEOUT(200), SLP_TIMEOUT(500),
1885                  SLP_VEC(1, 2, 3, 4, 0xFF)}, 0},
1886         {{SLP, SLP_TIMEOUT(200), SLP_TIMEOUT(300),
1887                  SLP_VEC(2, 4, 6, 7, 0xFF)}, 0},
1888         {{SLP, SLP_TIMEOUT(50), SLP_TIMEOUT(100),
1889                  SLP_VEC(2, 6, 9, 9, 0xFF)}, 0},
1890         {{SLP, SLP_TIMEOUT(50), SLP_TIMEOUT(25), SLP_VEC(2, 7, 9, 9, 0xFF)}, 0},
1891         {{SLP, SLP_TIMEOUT(25), SLP_TIMEOUT(25),
1892                  SLP_VEC(4, 7, 10, 10, 0xFF)}, 0}
1893 };
1894
1895 int iwl3945_power_init_handle(struct iwl3945_priv *priv)
1896 {
1897         int rc = 0, i;
1898         struct iwl3945_power_mgr *pow_data;
1899         int size = sizeof(struct iwl3945_power_vec_entry) * IWL_POWER_AC;
1900         u16 pci_pm;
1901
1902         IWL_DEBUG_POWER("Initialize power \n");
1903
1904         pow_data = &(priv->power_data);
1905
1906         memset(pow_data, 0, sizeof(*pow_data));
1907
1908         pow_data->active_index = IWL_POWER_RANGE_0;
1909         pow_data->dtim_val = 0xffff;
1910
1911         memcpy(&pow_data->pwr_range_0[0], &range_0[0], size);
1912         memcpy(&pow_data->pwr_range_1[0], &range_1[0], size);
1913
1914         rc = pci_read_config_word(priv->pci_dev, PCI_LINK_CTRL, &pci_pm);
1915         if (rc != 0)
1916                 return 0;
1917         else {
1918                 struct iwl3945_powertable_cmd *cmd;
1919
1920                 IWL_DEBUG_POWER("adjust power command flags\n");
1921
1922                 for (i = 0; i < IWL_POWER_AC; i++) {
1923                         cmd = &pow_data->pwr_range_0[i].cmd;
1924
1925                         if (pci_pm & 0x1)
1926                                 cmd->flags &= ~IWL_POWER_PCI_PM_MSK;
1927                         else
1928                                 cmd->flags |= IWL_POWER_PCI_PM_MSK;
1929                 }
1930         }
1931         return rc;
1932 }
1933
1934 static int iwl3945_update_power_cmd(struct iwl3945_priv *priv,
1935                                 struct iwl3945_powertable_cmd *cmd, u32 mode)
1936 {
1937         int rc = 0, i;
1938         u8 skip;
1939         u32 max_sleep = 0;
1940         struct iwl3945_power_vec_entry *range;
1941         u8 period = 0;
1942         struct iwl3945_power_mgr *pow_data;
1943
1944         if (mode > IWL_POWER_INDEX_5) {
1945                 IWL_DEBUG_POWER("Error invalid power mode \n");
1946                 return -1;
1947         }
1948         pow_data = &(priv->power_data);
1949
1950         if (pow_data->active_index == IWL_POWER_RANGE_0)
1951                 range = &pow_data->pwr_range_0[0];
1952         else
1953                 range = &pow_data->pwr_range_1[1];
1954
1955         memcpy(cmd, &range[mode].cmd, sizeof(struct iwl3945_powertable_cmd));
1956
1957 #ifdef IWL_MAC80211_DISABLE
1958         if (priv->assoc_network != NULL) {
1959                 unsigned long flags;
1960
1961                 period = priv->assoc_network->tim.tim_period;
1962         }
1963 #endif  /*IWL_MAC80211_DISABLE */
1964         skip = range[mode].no_dtim;
1965
1966         if (period == 0) {
1967                 period = 1;
1968                 skip = 0;
1969         }
1970
1971         if (skip == 0) {
1972                 max_sleep = period;
1973                 cmd->flags &= ~IWL_POWER_SLEEP_OVER_DTIM_MSK;
1974         } else {
1975                 __le32 slp_itrvl = cmd->sleep_interval[IWL_POWER_VEC_SIZE - 1];
1976                 max_sleep = (le32_to_cpu(slp_itrvl) / period) * period;
1977                 cmd->flags |= IWL_POWER_SLEEP_OVER_DTIM_MSK;
1978         }
1979
1980         for (i = 0; i < IWL_POWER_VEC_SIZE; i++) {
1981                 if (le32_to_cpu(cmd->sleep_interval[i]) > max_sleep)
1982                         cmd->sleep_interval[i] = cpu_to_le32(max_sleep);
1983         }
1984
1985         IWL_DEBUG_POWER("Flags value = 0x%08X\n", cmd->flags);
1986         IWL_DEBUG_POWER("Tx timeout = %u\n", le32_to_cpu(cmd->tx_data_timeout));
1987         IWL_DEBUG_POWER("Rx timeout = %u\n", le32_to_cpu(cmd->rx_data_timeout));
1988         IWL_DEBUG_POWER("Sleep interval vector = { %d , %d , %d , %d , %d }\n",
1989                         le32_to_cpu(cmd->sleep_interval[0]),
1990                         le32_to_cpu(cmd->sleep_interval[1]),
1991                         le32_to_cpu(cmd->sleep_interval[2]),
1992                         le32_to_cpu(cmd->sleep_interval[3]),
1993                         le32_to_cpu(cmd->sleep_interval[4]));
1994
1995         return rc;
1996 }
1997
1998 static int iwl3945_send_power_mode(struct iwl3945_priv *priv, u32 mode)
1999 {
2000         u32 uninitialized_var(final_mode);
2001         int rc;
2002         struct iwl3945_powertable_cmd cmd;
2003
2004         /* If on battery, set to 3,
2005          * if plugged into AC power, set to CAM ("continuously aware mode"),
2006          * else user level */
2007         switch (mode) {
2008         case IWL_POWER_BATTERY:
2009                 final_mode = IWL_POWER_INDEX_3;
2010                 break;
2011         case IWL_POWER_AC:
2012                 final_mode = IWL_POWER_MODE_CAM;
2013                 break;
2014         default:
2015                 final_mode = mode;
2016                 break;
2017         }
2018
2019         iwl3945_update_power_cmd(priv, &cmd, final_mode);
2020
2021         rc = iwl3945_send_cmd_pdu(priv, POWER_TABLE_CMD, sizeof(cmd), &cmd);
2022
2023         if (final_mode == IWL_POWER_MODE_CAM)
2024                 clear_bit(STATUS_POWER_PMI, &priv->status);
2025         else
2026                 set_bit(STATUS_POWER_PMI, &priv->status);
2027
2028         return rc;
2029 }
2030
2031 /**
2032  * iwl3945_scan_cancel - Cancel any currently executing HW scan
2033  *
2034  * NOTE: priv->mutex is not required before calling this function
2035  */
2036 static int iwl3945_scan_cancel(struct iwl3945_priv *priv)
2037 {
2038         if (!test_bit(STATUS_SCAN_HW, &priv->status)) {
2039                 clear_bit(STATUS_SCANNING, &priv->status);
2040                 return 0;
2041         }
2042
2043         if (test_bit(STATUS_SCANNING, &priv->status)) {
2044                 if (!test_bit(STATUS_SCAN_ABORTING, &priv->status)) {
2045                         IWL_DEBUG_SCAN("Queuing scan abort.\n");
2046                         set_bit(STATUS_SCAN_ABORTING, &priv->status);
2047                         queue_work(priv->workqueue, &priv->abort_scan);
2048
2049                 } else
2050                         IWL_DEBUG_SCAN("Scan abort already in progress.\n");
2051
2052                 return test_bit(STATUS_SCANNING, &priv->status);
2053         }
2054
2055         return 0;
2056 }
2057
2058 /**
2059  * iwl3945_scan_cancel_timeout - Cancel any currently executing HW scan
2060  * @ms: amount of time to wait (in milliseconds) for scan to abort
2061  *
2062  * NOTE: priv->mutex must be held before calling this function
2063  */
2064 static int iwl3945_scan_cancel_timeout(struct iwl3945_priv *priv, unsigned long ms)
2065 {
2066         unsigned long now = jiffies;
2067         int ret;
2068
2069         ret = iwl3945_scan_cancel(priv);
2070         if (ret && ms) {
2071                 mutex_unlock(&priv->mutex);
2072                 while (!time_after(jiffies, now + msecs_to_jiffies(ms)) &&
2073                                 test_bit(STATUS_SCANNING, &priv->status))
2074                         msleep(1);
2075                 mutex_lock(&priv->mutex);
2076
2077                 return test_bit(STATUS_SCANNING, &priv->status);
2078         }
2079
2080         return ret;
2081 }
2082
2083 #define MAX_UCODE_BEACON_INTERVAL       1024
2084 #define INTEL_CONN_LISTEN_INTERVAL      __constant_cpu_to_le16(0xA)
2085
2086 static __le16 iwl3945_adjust_beacon_interval(u16 beacon_val)
2087 {
2088         u16 new_val = 0;
2089         u16 beacon_factor = 0;
2090
2091         beacon_factor =
2092             (beacon_val + MAX_UCODE_BEACON_INTERVAL)
2093                 / MAX_UCODE_BEACON_INTERVAL;
2094         new_val = beacon_val / beacon_factor;
2095
2096         return cpu_to_le16(new_val);
2097 }
2098
2099 static void iwl3945_setup_rxon_timing(struct iwl3945_priv *priv)
2100 {
2101         u64 interval_tm_unit;
2102         u64 tsf, result;
2103         unsigned long flags;
2104         struct ieee80211_conf *conf = NULL;
2105         u16 beacon_int = 0;
2106
2107         conf = ieee80211_get_hw_conf(priv->hw);
2108
2109         spin_lock_irqsave(&priv->lock, flags);
2110         priv->rxon_timing.timestamp.dw[1] = cpu_to_le32(priv->timestamp1);
2111         priv->rxon_timing.timestamp.dw[0] = cpu_to_le32(priv->timestamp0);
2112
2113         priv->rxon_timing.listen_interval = INTEL_CONN_LISTEN_INTERVAL;
2114
2115         tsf = priv->timestamp1;
2116         tsf = ((tsf << 32) | priv->timestamp0);
2117
2118         beacon_int = priv->beacon_int;
2119         spin_unlock_irqrestore(&priv->lock, flags);
2120
2121         if (priv->iw_mode == NL80211_IFTYPE_STATION) {
2122                 if (beacon_int == 0) {
2123                         priv->rxon_timing.beacon_interval = cpu_to_le16(100);
2124                         priv->rxon_timing.beacon_init_val = cpu_to_le32(102400);
2125                 } else {
2126                         priv->rxon_timing.beacon_interval =
2127                                 cpu_to_le16(beacon_int);
2128                         priv->rxon_timing.beacon_interval =
2129                             iwl3945_adjust_beacon_interval(
2130                                 le16_to_cpu(priv->rxon_timing.beacon_interval));
2131                 }
2132
2133                 priv->rxon_timing.atim_window = 0;
2134         } else {
2135                 priv->rxon_timing.beacon_interval =
2136                         iwl3945_adjust_beacon_interval(conf->beacon_int);
2137                 /* TODO: we need to get atim_window from upper stack
2138                  * for now we set to 0 */
2139                 priv->rxon_timing.atim_window = 0;
2140         }
2141
2142         interval_tm_unit =
2143                 (le16_to_cpu(priv->rxon_timing.beacon_interval) * 1024);
2144         result = do_div(tsf, interval_tm_unit);
2145         priv->rxon_timing.beacon_init_val =
2146             cpu_to_le32((u32) ((u64) interval_tm_unit - result));
2147
2148         IWL_DEBUG_ASSOC
2149             ("beacon interval %d beacon timer %d beacon tim %d\n",
2150                 le16_to_cpu(priv->rxon_timing.beacon_interval),
2151                 le32_to_cpu(priv->rxon_timing.beacon_init_val),
2152                 le16_to_cpu(priv->rxon_timing.atim_window));
2153 }
2154
2155 static int iwl3945_scan_initiate(struct iwl3945_priv *priv)
2156 {
2157         if (priv->iw_mode == NL80211_IFTYPE_AP) {
2158                 IWL_ERROR("APs don't scan.\n");
2159                 return 0;
2160         }
2161
2162         if (!iwl3945_is_ready_rf(priv)) {
2163                 IWL_DEBUG_SCAN("Aborting scan due to not ready.\n");
2164                 return -EIO;
2165         }
2166
2167         if (test_bit(STATUS_SCANNING, &priv->status)) {
2168                 IWL_DEBUG_SCAN("Scan already in progress.\n");
2169                 return -EAGAIN;
2170         }
2171
2172         if (test_bit(STATUS_SCAN_ABORTING, &priv->status)) {
2173                 IWL_DEBUG_SCAN("Scan request while abort pending.  "
2174                                "Queuing.\n");
2175                 return -EAGAIN;
2176         }
2177
2178         IWL_DEBUG_INFO("Starting scan...\n");
2179         if (priv->cfg->sku & IWL_SKU_G)
2180                 priv->scan_bands |= BIT(IEEE80211_BAND_2GHZ);
2181         if (priv->cfg->sku & IWL_SKU_A)
2182                 priv->scan_bands |= BIT(IEEE80211_BAND_5GHZ);
2183         set_bit(STATUS_SCANNING, &priv->status);
2184         priv->scan_start = jiffies;
2185         priv->scan_pass_start = priv->scan_start;
2186
2187         queue_work(priv->workqueue, &priv->request_scan);
2188
2189         return 0;
2190 }
2191
2192 static int iwl3945_set_rxon_hwcrypto(struct iwl3945_priv *priv, int hw_decrypt)
2193 {
2194         struct iwl3945_rxon_cmd *rxon = &priv->staging_rxon;
2195
2196         if (hw_decrypt)
2197                 rxon->filter_flags &= ~RXON_FILTER_DIS_DECRYPT_MSK;
2198         else
2199                 rxon->filter_flags |= RXON_FILTER_DIS_DECRYPT_MSK;
2200
2201         return 0;
2202 }
2203
2204 static void iwl3945_set_flags_for_phymode(struct iwl3945_priv *priv,
2205                                           enum ieee80211_band band)
2206 {
2207         if (band == IEEE80211_BAND_5GHZ) {
2208                 priv->staging_rxon.flags &=
2209                     ~(RXON_FLG_BAND_24G_MSK | RXON_FLG_AUTO_DETECT_MSK
2210                       | RXON_FLG_CCK_MSK);
2211                 priv->staging_rxon.flags |= RXON_FLG_SHORT_SLOT_MSK;
2212         } else {
2213                 /* Copied from iwl3945_bg_post_associate() */
2214                 if (priv->assoc_capability & WLAN_CAPABILITY_SHORT_SLOT_TIME)
2215                         priv->staging_rxon.flags |= RXON_FLG_SHORT_SLOT_MSK;
2216                 else
2217                         priv->staging_rxon.flags &= ~RXON_FLG_SHORT_SLOT_MSK;
2218
2219                 if (priv->iw_mode == NL80211_IFTYPE_ADHOC)
2220                         priv->staging_rxon.flags &= ~RXON_FLG_SHORT_SLOT_MSK;
2221
2222                 priv->staging_rxon.flags |= RXON_FLG_BAND_24G_MSK;
2223                 priv->staging_rxon.flags |= RXON_FLG_AUTO_DETECT_MSK;
2224                 priv->staging_rxon.flags &= ~RXON_FLG_CCK_MSK;
2225         }
2226 }
2227
2228 /*
2229  * initialize rxon structure with default values from eeprom
2230  */
2231 static void iwl3945_connection_init_rx_config(struct iwl3945_priv *priv)
2232 {
2233         const struct iwl3945_channel_info *ch_info;
2234
2235         memset(&priv->staging_rxon, 0, sizeof(priv->staging_rxon));
2236
2237         switch (priv->iw_mode) {
2238         case NL80211_IFTYPE_AP:
2239                 priv->staging_rxon.dev_type = RXON_DEV_TYPE_AP;
2240                 break;
2241
2242         case NL80211_IFTYPE_STATION:
2243                 priv->staging_rxon.dev_type = RXON_DEV_TYPE_ESS;
2244                 priv->staging_rxon.filter_flags = RXON_FILTER_ACCEPT_GRP_MSK;
2245                 break;
2246
2247         case NL80211_IFTYPE_ADHOC:
2248                 priv->staging_rxon.dev_type = RXON_DEV_TYPE_IBSS;
2249                 priv->staging_rxon.flags = RXON_FLG_SHORT_PREAMBLE_MSK;
2250                 priv->staging_rxon.filter_flags = RXON_FILTER_BCON_AWARE_MSK |
2251                                                   RXON_FILTER_ACCEPT_GRP_MSK;
2252                 break;
2253
2254         case NL80211_IFTYPE_MONITOR:
2255                 priv->staging_rxon.dev_type = RXON_DEV_TYPE_SNIFFER;
2256                 priv->staging_rxon.filter_flags = RXON_FILTER_PROMISC_MSK |
2257                     RXON_FILTER_CTL2HOST_MSK | RXON_FILTER_ACCEPT_GRP_MSK;
2258                 break;
2259         default:
2260                 IWL_ERROR("Unsupported interface type %d\n", priv->iw_mode);
2261                 break;
2262         }
2263
2264 #if 0
2265         /* TODO:  Figure out when short_preamble would be set and cache from
2266          * that */
2267         if (!hw_to_local(priv->hw)->short_preamble)
2268                 priv->staging_rxon.flags &= ~RXON_FLG_SHORT_PREAMBLE_MSK;
2269         else
2270                 priv->staging_rxon.flags |= RXON_FLG_SHORT_PREAMBLE_MSK;
2271 #endif
2272
2273         ch_info = iwl3945_get_channel_info(priv, priv->band,
2274                                        le16_to_cpu(priv->active_rxon.channel));
2275
2276         if (!ch_info)
2277                 ch_info = &priv->channel_info[0];
2278
2279         /*
2280          * in some case A channels are all non IBSS
2281          * in this case force B/G channel
2282          */
2283         if ((priv->iw_mode == NL80211_IFTYPE_ADHOC) &&
2284             !(is_channel_ibss(ch_info)))
2285                 ch_info = &priv->channel_info[0];
2286
2287         priv->staging_rxon.channel = cpu_to_le16(ch_info->channel);
2288         if (is_channel_a_band(ch_info))
2289                 priv->band = IEEE80211_BAND_5GHZ;
2290         else
2291                 priv->band = IEEE80211_BAND_2GHZ;
2292
2293         iwl3945_set_flags_for_phymode(priv, priv->band);
2294
2295         priv->staging_rxon.ofdm_basic_rates =
2296             (IWL_OFDM_RATES_MASK >> IWL_FIRST_OFDM_RATE) & 0xFF;
2297         priv->staging_rxon.cck_basic_rates =
2298             (IWL_CCK_RATES_MASK >> IWL_FIRST_CCK_RATE) & 0xF;
2299 }
2300
2301 static int iwl3945_set_mode(struct iwl3945_priv *priv, int mode)
2302 {
2303         if (mode == NL80211_IFTYPE_ADHOC) {
2304                 const struct iwl3945_channel_info *ch_info;
2305
2306                 ch_info = iwl3945_get_channel_info(priv,
2307                         priv->band,
2308                         le16_to_cpu(priv->staging_rxon.channel));
2309
2310                 if (!ch_info || !is_channel_ibss(ch_info)) {
2311                         IWL_ERROR("channel %d not IBSS channel\n",
2312                                   le16_to_cpu(priv->staging_rxon.channel));
2313                         return -EINVAL;
2314                 }
2315         }
2316
2317         priv->iw_mode = mode;
2318
2319         iwl3945_connection_init_rx_config(priv);
2320         memcpy(priv->staging_rxon.node_addr, priv->mac_addr, ETH_ALEN);
2321
2322         iwl3945_clear_stations_table(priv);
2323
2324         /* dont commit rxon if rf-kill is on*/
2325         if (!iwl3945_is_ready_rf(priv))
2326                 return -EAGAIN;
2327
2328         cancel_delayed_work(&priv->scan_check);
2329         if (iwl3945_scan_cancel_timeout(priv, 100)) {
2330                 IWL_WARNING("Aborted scan still in progress after 100ms\n");
2331                 IWL_DEBUG_MAC80211("leaving - scan abort failed.\n");
2332                 return -EAGAIN;
2333         }
2334
2335         iwl3945_commit_rxon(priv);
2336
2337         return 0;
2338 }
2339
2340 static void iwl3945_build_tx_cmd_hwcrypto(struct iwl3945_priv *priv,
2341                                       struct ieee80211_tx_info *info,
2342                                       struct iwl3945_cmd *cmd,
2343                                       struct sk_buff *skb_frag,
2344                                       int last_frag)
2345 {
2346         struct iwl3945_hw_key *keyinfo =
2347             &priv->stations[info->control.hw_key->hw_key_idx].keyinfo;
2348
2349         switch (keyinfo->alg) {
2350         case ALG_CCMP:
2351                 cmd->cmd.tx.sec_ctl = TX_CMD_SEC_CCM;
2352                 memcpy(cmd->cmd.tx.key, keyinfo->key, keyinfo->keylen);
2353                 IWL_DEBUG_TX("tx_cmd with aes hwcrypto\n");
2354                 break;
2355
2356         case ALG_TKIP:
2357 #if 0
2358                 cmd->cmd.tx.sec_ctl = TX_CMD_SEC_TKIP;
2359
2360                 if (last_frag)
2361                         memcpy(cmd->cmd.tx.tkip_mic.byte, skb_frag->tail - 8,
2362                                8);
2363                 else
2364                         memset(cmd->cmd.tx.tkip_mic.byte, 0, 8);
2365 #endif
2366                 break;
2367
2368         case ALG_WEP:
2369                 cmd->cmd.tx.sec_ctl = TX_CMD_SEC_WEP |
2370                     (info->control.hw_key->hw_key_idx & TX_CMD_SEC_MSK) << TX_CMD_SEC_SHIFT;
2371
2372                 if (keyinfo->keylen == 13)
2373                         cmd->cmd.tx.sec_ctl |= TX_CMD_SEC_KEY128;
2374
2375                 memcpy(&cmd->cmd.tx.key[3], keyinfo->key, keyinfo->keylen);
2376
2377                 IWL_DEBUG_TX("Configuring packet for WEP encryption "
2378                              "with key %d\n", info->control.hw_key->hw_key_idx);
2379                 break;
2380
2381         default:
2382                 printk(KERN_ERR "Unknown encode alg %d\n", keyinfo->alg);
2383                 break;
2384         }
2385 }
2386
2387 /*
2388  * handle build REPLY_TX command notification.
2389  */
2390 static void iwl3945_build_tx_cmd_basic(struct iwl3945_priv *priv,
2391                                   struct iwl3945_cmd *cmd,
2392                                   struct ieee80211_tx_info *info,
2393                                   struct ieee80211_hdr *hdr,
2394                                   int is_unicast, u8 std_id)
2395 {
2396         __le16 fc = hdr->frame_control;
2397         __le32 tx_flags = cmd->cmd.tx.tx_flags;
2398
2399         cmd->cmd.tx.stop_time.life_time = TX_CMD_LIFE_TIME_INFINITE;
2400         if (!(info->flags & IEEE80211_TX_CTL_NO_ACK)) {
2401                 tx_flags |= TX_CMD_FLG_ACK_MSK;
2402                 if (ieee80211_is_mgmt(fc))
2403                         tx_flags |= TX_CMD_FLG_SEQ_CTL_MSK;
2404                 if (ieee80211_is_probe_resp(fc) &&
2405                     !(le16_to_cpu(hdr->seq_ctrl) & 0xf))
2406                         tx_flags |= TX_CMD_FLG_TSF_MSK;
2407         } else {
2408                 tx_flags &= (~TX_CMD_FLG_ACK_MSK);
2409                 tx_flags |= TX_CMD_FLG_SEQ_CTL_MSK;
2410         }
2411
2412         cmd->cmd.tx.sta_id = std_id;
2413         if (ieee80211_has_morefrags(fc))
2414                 tx_flags |= TX_CMD_FLG_MORE_FRAG_MSK;
2415
2416         if (ieee80211_is_data_qos(fc)) {
2417                 u8 *qc = ieee80211_get_qos_ctl(hdr);
2418                 cmd->cmd.tx.tid_tspec = qc[0] & 0xf;
2419                 tx_flags &= ~TX_CMD_FLG_SEQ_CTL_MSK;
2420         } else {
2421                 tx_flags |= TX_CMD_FLG_SEQ_CTL_MSK;
2422         }
2423
2424         if (info->flags & IEEE80211_TX_CTL_USE_RTS_CTS) {
2425                 tx_flags |= TX_CMD_FLG_RTS_MSK;
2426                 tx_flags &= ~TX_CMD_FLG_CTS_MSK;
2427         } else if (info->flags & IEEE80211_TX_CTL_USE_CTS_PROTECT) {
2428                 tx_flags &= ~TX_CMD_FLG_RTS_MSK;
2429                 tx_flags |= TX_CMD_FLG_CTS_MSK;
2430         }
2431
2432         if ((tx_flags & TX_CMD_FLG_RTS_MSK) || (tx_flags & TX_CMD_FLG_CTS_MSK))
2433                 tx_flags |= TX_CMD_FLG_FULL_TXOP_PROT_MSK;
2434
2435         tx_flags &= ~(TX_CMD_FLG_ANT_SEL_MSK);
2436         if (ieee80211_is_mgmt(fc)) {
2437                 if (ieee80211_is_assoc_req(fc) || ieee80211_is_reassoc_req(fc))
2438                         cmd->cmd.tx.timeout.pm_frame_timeout = cpu_to_le16(3);
2439                 else
2440                         cmd->cmd.tx.timeout.pm_frame_timeout = cpu_to_le16(2);
2441         } else {
2442                 cmd->cmd.tx.timeout.pm_frame_timeout = 0;
2443 #ifdef CONFIG_IWL3945_LEDS
2444                 priv->rxtxpackets += le16_to_cpu(cmd->cmd.tx.len);
2445 #endif
2446         }
2447
2448         cmd->cmd.tx.driver_txop = 0;
2449         cmd->cmd.tx.tx_flags = tx_flags;
2450         cmd->cmd.tx.next_frame_len = 0;
2451 }
2452
2453 /**
2454  * iwl3945_get_sta_id - Find station's index within station table
2455  */
2456 static int iwl3945_get_sta_id(struct iwl3945_priv *priv, struct ieee80211_hdr *hdr)
2457 {
2458         int sta_id;
2459         u16 fc = le16_to_cpu(hdr->frame_control);
2460
2461         /* If this frame is broadcast or management, use broadcast station id */
2462         if (((fc & IEEE80211_FCTL_FTYPE) != IEEE80211_FTYPE_DATA) ||
2463             is_multicast_ether_addr(hdr->addr1))
2464                 return priv->hw_setting.bcast_sta_id;
2465
2466         switch (priv->iw_mode) {
2467
2468         /* If we are a client station in a BSS network, use the special
2469          * AP station entry (that's the only station we communicate with) */
2470         case NL80211_IFTYPE_STATION:
2471                 return IWL_AP_ID;
2472
2473         /* If we are an AP, then find the station, or use BCAST */
2474         case NL80211_IFTYPE_AP:
2475                 sta_id = iwl3945_hw_find_station(priv, hdr->addr1);
2476                 if (sta_id != IWL_INVALID_STATION)
2477                         return sta_id;
2478                 return priv->hw_setting.bcast_sta_id;
2479
2480         /* If this frame is going out to an IBSS network, find the station,
2481          * or create a new station table entry */
2482         case NL80211_IFTYPE_ADHOC: {
2483                 /* Create new station table entry */
2484                 sta_id = iwl3945_hw_find_station(priv, hdr->addr1);
2485                 if (sta_id != IWL_INVALID_STATION)
2486                         return sta_id;
2487
2488                 sta_id = iwl3945_add_station(priv, hdr->addr1, 0, CMD_ASYNC);
2489
2490                 if (sta_id != IWL_INVALID_STATION)
2491                         return sta_id;
2492
2493                 IWL_DEBUG_DROP("Station %pM not in station map. "
2494                                "Defaulting to broadcast...\n",
2495                                hdr->addr1);
2496                 iwl3945_print_hex_dump(IWL_DL_DROP, (u8 *) hdr, sizeof(*hdr));
2497                 return priv->hw_setting.bcast_sta_id;
2498         }
2499         /* If we are in monitor mode, use BCAST. This is required for
2500          * packet injection. */
2501         case NL80211_IFTYPE_MONITOR:
2502                 return priv->hw_setting.bcast_sta_id;
2503
2504         default:
2505                 IWL_WARNING("Unknown mode of operation: %d\n", priv->iw_mode);
2506                 return priv->hw_setting.bcast_sta_id;
2507         }
2508 }
2509
2510 /*
2511  * start REPLY_TX command process
2512  */
2513 static int iwl3945_tx_skb(struct iwl3945_priv *priv, struct sk_buff *skb)
2514 {
2515         struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
2516         struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
2517         struct iwl3945_tfd_frame *tfd;
2518         u32 *control_flags;
2519         int txq_id = skb_get_queue_mapping(skb);
2520         struct iwl3945_tx_queue *txq = NULL;
2521         struct iwl3945_queue *q = NULL;
2522         dma_addr_t phys_addr;
2523         dma_addr_t txcmd_phys;
2524         struct iwl3945_cmd *out_cmd = NULL;
2525         u16 len, idx, len_org, hdr_len;
2526         u8 id;
2527         u8 unicast;
2528         u8 sta_id;
2529         u8 tid = 0;
2530         u16 seq_number = 0;
2531         __le16 fc;
2532         u8 wait_write_ptr = 0;
2533         u8 *qc = NULL;
2534         unsigned long flags;
2535         int rc;
2536
2537         spin_lock_irqsave(&priv->lock, flags);
2538         if (iwl3945_is_rfkill(priv)) {
2539                 IWL_DEBUG_DROP("Dropping - RF KILL\n");
2540                 goto drop_unlock;
2541         }
2542
2543         if ((ieee80211_get_tx_rate(priv->hw, info)->hw_value & 0xFF) == IWL_INVALID_RATE) {
2544                 IWL_ERROR("ERROR: No TX rate available.\n");
2545                 goto drop_unlock;
2546         }
2547
2548         unicast = !is_multicast_ether_addr(hdr->addr1);
2549         id = 0;
2550
2551         fc = hdr->frame_control;
2552
2553 #ifdef CONFIG_IWL3945_DEBUG
2554         if (ieee80211_is_auth(fc))
2555                 IWL_DEBUG_TX("Sending AUTH frame\n");
2556         else if (ieee80211_is_assoc_req(fc))
2557                 IWL_DEBUG_TX("Sending ASSOC frame\n");
2558         else if (ieee80211_is_reassoc_req(fc))
2559                 IWL_DEBUG_TX("Sending REASSOC frame\n");
2560 #endif
2561
2562         /* drop all data frame if we are not associated */
2563         if (ieee80211_is_data(fc) &&
2564             (priv->iw_mode != NL80211_IFTYPE_MONITOR) && /* packet injection */
2565             (!iwl3945_is_associated(priv) ||
2566              ((priv->iw_mode == NL80211_IFTYPE_STATION) && !priv->assoc_id))) {
2567                 IWL_DEBUG_DROP("Dropping - !iwl3945_is_associated\n");
2568                 goto drop_unlock;
2569         }
2570
2571         spin_unlock_irqrestore(&priv->lock, flags);
2572
2573         hdr_len = ieee80211_hdrlen(fc);
2574
2575         /* Find (or create) index into station table for destination station */
2576         sta_id = iwl3945_get_sta_id(priv, hdr);
2577         if (sta_id == IWL_INVALID_STATION) {
2578                 IWL_DEBUG_DROP("Dropping - INVALID STATION: %pM\n",
2579                                hdr->addr1);
2580                 goto drop;
2581         }
2582
2583         IWL_DEBUG_RATE("station Id %d\n", sta_id);
2584
2585         if (ieee80211_is_data_qos(fc)) {
2586                 qc = ieee80211_get_qos_ctl(hdr);
2587                 tid = qc[0] & IEEE80211_QOS_CTL_TID_MASK;
2588                 seq_number = priv->stations[sta_id].tid[tid].seq_number &
2589                                 IEEE80211_SCTL_SEQ;
2590                 hdr->seq_ctrl = cpu_to_le16(seq_number) |
2591                         (hdr->seq_ctrl &
2592                                 __constant_cpu_to_le16(IEEE80211_SCTL_FRAG));
2593                 seq_number += 0x10;
2594         }
2595
2596         /* Descriptor for chosen Tx queue */
2597         txq = &priv->txq[txq_id];
2598         q = &txq->q;
2599
2600         spin_lock_irqsave(&priv->lock, flags);
2601
2602         /* Set up first empty TFD within this queue's circular TFD buffer */
2603         tfd = &txq->bd[q->write_ptr];
2604         memset(tfd, 0, sizeof(*tfd));
2605         control_flags = (u32 *) tfd;
2606         idx = get_cmd_index(q, q->write_ptr, 0);
2607
2608         /* Set up driver data for this TFD */
2609         memset(&(txq->txb[q->write_ptr]), 0, sizeof(struct iwl3945_tx_info));
2610         txq->txb[q->write_ptr].skb[0] = skb;
2611
2612         /* Init first empty entry in queue's array of Tx/cmd buffers */
2613         out_cmd = &txq->cmd[idx];
2614         memset(&out_cmd->hdr, 0, sizeof(out_cmd->hdr));
2615         memset(&out_cmd->cmd.tx, 0, sizeof(out_cmd->cmd.tx));
2616
2617         /*
2618          * Set up the Tx-command (not MAC!) header.
2619          * Store the chosen Tx queue and TFD index within the sequence field;
2620          * after Tx, uCode's Tx response will return this value so driver can
2621          * locate the frame within the tx queue and do post-tx processing.
2622          */
2623         out_cmd->hdr.cmd = REPLY_TX;
2624         out_cmd->hdr.sequence = cpu_to_le16((u16)(QUEUE_TO_SEQ(txq_id) |
2625                                 INDEX_TO_SEQ(q->write_ptr)));
2626
2627         /* Copy MAC header from skb into command buffer */
2628         memcpy(out_cmd->cmd.tx.hdr, hdr, hdr_len);
2629
2630         /*
2631          * Use the first empty entry in this queue's command buffer array
2632          * to contain the Tx command and MAC header concatenated together
2633          * (payload data will be in another buffer).
2634          * Size of this varies, due to varying MAC header length.
2635          * If end is not dword aligned, we'll have 2 extra bytes at the end
2636          * of the MAC header (device reads on dword boundaries).
2637          * We'll tell device about this padding later.
2638          */
2639         len = priv->hw_setting.tx_cmd_len +
2640                 sizeof(struct iwl3945_cmd_header) + hdr_len;
2641
2642         len_org = len;
2643         len = (len + 3) & ~3;
2644
2645         if (len_org != len)
2646                 len_org = 1;
2647         else
2648                 len_org = 0;
2649
2650         /* Physical address of this Tx command's header (not MAC header!),
2651          * within command buffer array. */
2652         txcmd_phys = txq->dma_addr_cmd + sizeof(struct iwl3945_cmd) * idx +
2653                      offsetof(struct iwl3945_cmd, hdr);
2654
2655         /* Add buffer containing Tx command and MAC(!) header to TFD's
2656          * first entry */
2657         iwl3945_hw_txq_attach_buf_to_tfd(priv, tfd, txcmd_phys, len);
2658
2659         if (info->control.hw_key)
2660                 iwl3945_build_tx_cmd_hwcrypto(priv, info, out_cmd, skb, 0);
2661
2662         /* Set up TFD's 2nd entry to point directly to remainder of skb,
2663          * if any (802.11 null frames have no payload). */
2664         len = skb->len - hdr_len;
2665         if (len) {
2666                 phys_addr = pci_map_single(priv->pci_dev, skb->data + hdr_len,
2667                                            len, PCI_DMA_TODEVICE);
2668                 iwl3945_hw_txq_attach_buf_to_tfd(priv, tfd, phys_addr, len);
2669         }
2670
2671         if (!len)
2672                 /* If there is no payload, then we use only one Tx buffer */
2673                 *control_flags = TFD_CTL_COUNT_SET(1);
2674         else
2675                 /* Else use 2 buffers.
2676                  * Tell 3945 about any padding after MAC header */
2677                 *control_flags = TFD_CTL_COUNT_SET(2) |
2678                         TFD_CTL_PAD_SET(U32_PAD(len));
2679
2680         /* Total # bytes to be transmitted */
2681         len = (u16)skb->len;
2682         out_cmd->cmd.tx.len = cpu_to_le16(len);
2683
2684         /* TODO need this for burst mode later on */
2685         iwl3945_build_tx_cmd_basic(priv, out_cmd, info, hdr, unicast, sta_id);
2686
2687         /* set is_hcca to 0; it probably will never be implemented */
2688         iwl3945_hw_build_tx_cmd_rate(priv, out_cmd, info, hdr, sta_id, 0);
2689
2690         out_cmd->cmd.tx.tx_flags &= ~TX_CMD_FLG_ANT_A_MSK;
2691         out_cmd->cmd.tx.tx_flags &= ~TX_CMD_FLG_ANT_B_MSK;
2692
2693         if (!ieee80211_has_morefrags(hdr->frame_control)) {
2694                 txq->need_update = 1;
2695                 if (qc)
2696                         priv->stations[sta_id].tid[tid].seq_number = seq_number;
2697         } else {
2698                 wait_write_ptr = 1;
2699                 txq->need_update = 0;
2700         }
2701
2702         iwl3945_print_hex_dump(IWL_DL_TX, out_cmd->cmd.payload,
2703                            sizeof(out_cmd->cmd.tx));
2704
2705         iwl3945_print_hex_dump(IWL_DL_TX, (u8 *)out_cmd->cmd.tx.hdr,
2706                            ieee80211_hdrlen(fc));
2707
2708         /* Tell device the write index *just past* this latest filled TFD */
2709         q->write_ptr = iwl_queue_inc_wrap(q->write_ptr, q->n_bd);
2710         rc = iwl3945_tx_queue_update_write_ptr(priv, txq);
2711         spin_unlock_irqrestore(&priv->lock, flags);
2712
2713         if (rc)
2714                 return rc;
2715
2716         if ((iwl3945_queue_space(q) < q->high_mark)
2717             && priv->mac80211_registered) {
2718                 if (wait_write_ptr) {
2719                         spin_lock_irqsave(&priv->lock, flags);
2720                         txq->need_update = 1;
2721                         iwl3945_tx_queue_update_write_ptr(priv, txq);
2722                         spin_unlock_irqrestore(&priv->lock, flags);
2723                 }
2724
2725                 ieee80211_stop_queue(priv->hw, skb_get_queue_mapping(skb));
2726         }
2727
2728         return 0;
2729
2730 drop_unlock:
2731         spin_unlock_irqrestore(&priv->lock, flags);
2732 drop:
2733         return -1;
2734 }
2735
2736 static void iwl3945_set_rate(struct iwl3945_priv *priv)
2737 {
2738         const struct ieee80211_supported_band *sband = NULL;
2739         struct ieee80211_rate *rate;
2740         int i;
2741
2742         sband = iwl3945_get_band(priv, priv->band);
2743         if (!sband) {
2744                 IWL_ERROR("Failed to set rate: unable to get hw mode\n");
2745                 return;
2746         }
2747
2748         priv->active_rate = 0;
2749         priv->active_rate_basic = 0;
2750
2751         IWL_DEBUG_RATE("Setting rates for %s GHz\n",
2752                        sband->band == IEEE80211_BAND_2GHZ ? "2.4" : "5");
2753
2754         for (i = 0; i < sband->n_bitrates; i++) {
2755                 rate = &sband->bitrates[i];
2756                 if ((rate->hw_value < IWL_RATE_COUNT) &&
2757                     !(rate->flags & IEEE80211_CHAN_DISABLED)) {
2758                         IWL_DEBUG_RATE("Adding rate index %d (plcp %d)\n",
2759                                        rate->hw_value, iwl3945_rates[rate->hw_value].plcp);
2760                         priv->active_rate |= (1 << rate->hw_value);
2761                 }
2762         }
2763
2764         IWL_DEBUG_RATE("Set active_rate = %0x, active_rate_basic = %0x\n",
2765                        priv->active_rate, priv->active_rate_basic);
2766
2767         /*
2768          * If a basic rate is configured, then use it (adding IWL_RATE_1M_MASK)
2769          * otherwise set it to the default of all CCK rates and 6, 12, 24 for
2770          * OFDM
2771          */
2772         if (priv->active_rate_basic & IWL_CCK_BASIC_RATES_MASK)
2773                 priv->staging_rxon.cck_basic_rates =
2774                     ((priv->active_rate_basic &
2775                       IWL_CCK_RATES_MASK) >> IWL_FIRST_CCK_RATE) & 0xF;
2776         else
2777                 priv->staging_rxon.cck_basic_rates =
2778                     (IWL_CCK_BASIC_RATES_MASK >> IWL_FIRST_CCK_RATE) & 0xF;
2779
2780         if (priv->active_rate_basic & IWL_OFDM_BASIC_RATES_MASK)
2781                 priv->staging_rxon.ofdm_basic_rates =
2782                     ((priv->active_rate_basic &
2783                       (IWL_OFDM_BASIC_RATES_MASK | IWL_RATE_6M_MASK)) >>
2784                       IWL_FIRST_OFDM_RATE) & 0xFF;
2785         else
2786                 priv->staging_rxon.ofdm_basic_rates =
2787                    (IWL_OFDM_BASIC_RATES_MASK >> IWL_FIRST_OFDM_RATE) & 0xFF;
2788 }
2789
2790 static void iwl3945_radio_kill_sw(struct iwl3945_priv *priv, int disable_radio)
2791 {
2792         unsigned long flags;
2793
2794         if (!!disable_radio == test_bit(STATUS_RF_KILL_SW, &priv->status))
2795                 return;
2796
2797         IWL_DEBUG_RF_KILL("Manual SW RF KILL set to: RADIO %s\n",
2798                           disable_radio ? "OFF" : "ON");
2799
2800         if (disable_radio) {
2801                 iwl3945_scan_cancel(priv);
2802                 /* FIXME: This is a workaround for AP */
2803                 if (priv->iw_mode != NL80211_IFTYPE_AP) {
2804                         spin_lock_irqsave(&priv->lock, flags);
2805                         iwl3945_write32(priv, CSR_UCODE_DRV_GP1_SET,
2806                                     CSR_UCODE_SW_BIT_RFKILL);
2807                         spin_unlock_irqrestore(&priv->lock, flags);
2808                         iwl3945_send_card_state(priv, CARD_STATE_CMD_DISABLE, 0);
2809                         set_bit(STATUS_RF_KILL_SW, &priv->status);
2810                 }
2811                 return;
2812         }
2813
2814         spin_lock_irqsave(&priv->lock, flags);
2815         iwl3945_write32(priv, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
2816
2817         clear_bit(STATUS_RF_KILL_SW, &priv->status);
2818         spin_unlock_irqrestore(&priv->lock, flags);
2819
2820         /* wake up ucode */
2821         msleep(10);
2822
2823         spin_lock_irqsave(&priv->lock, flags);
2824         iwl3945_read32(priv, CSR_UCODE_DRV_GP1);
2825         if (!iwl3945_grab_nic_access(priv))
2826                 iwl3945_release_nic_access(priv);
2827         spin_unlock_irqrestore(&priv->lock, flags);
2828
2829         if (test_bit(STATUS_RF_KILL_HW, &priv->status)) {
2830                 IWL_DEBUG_RF_KILL("Can not turn radio back on - "
2831                                   "disabled by HW switch\n");
2832                 return;
2833         }
2834
2835         if (priv->is_open)
2836                 queue_work(priv->workqueue, &priv->restart);
2837         return;
2838 }
2839
2840 void iwl3945_set_decrypted_flag(struct iwl3945_priv *priv, struct sk_buff *skb,
2841                             u32 decrypt_res, struct ieee80211_rx_status *stats)
2842 {
2843         u16 fc =
2844             le16_to_cpu(((struct ieee80211_hdr *)skb->data)->frame_control);
2845
2846         if (priv->active_rxon.filter_flags & RXON_FILTER_DIS_DECRYPT_MSK)
2847                 return;
2848
2849         if (!(fc & IEEE80211_FCTL_PROTECTED))
2850                 return;
2851
2852         IWL_DEBUG_RX("decrypt_res:0x%x\n", decrypt_res);
2853         switch (decrypt_res & RX_RES_STATUS_SEC_TYPE_MSK) {
2854         case RX_RES_STATUS_SEC_TYPE_TKIP:
2855                 if ((decrypt_res & RX_RES_STATUS_DECRYPT_TYPE_MSK) ==
2856                     RX_RES_STATUS_BAD_ICV_MIC)
2857                         stats->flag |= RX_FLAG_MMIC_ERROR;
2858         case RX_RES_STATUS_SEC_TYPE_WEP:
2859         case RX_RES_STATUS_SEC_TYPE_CCMP:
2860                 if ((decrypt_res & RX_RES_STATUS_DECRYPT_TYPE_MSK) ==
2861                     RX_RES_STATUS_DECRYPT_OK) {
2862                         IWL_DEBUG_RX("hw decrypt successfully!!!\n");
2863                         stats->flag |= RX_FLAG_DECRYPTED;
2864                 }
2865                 break;
2866
2867         default:
2868                 break;
2869         }
2870 }
2871
2872 #ifdef CONFIG_IWL3945_SPECTRUM_MEASUREMENT
2873
2874 #include "iwl-spectrum.h"
2875
2876 #define BEACON_TIME_MASK_LOW    0x00FFFFFF
2877 #define BEACON_TIME_MASK_HIGH   0xFF000000
2878 #define TIME_UNIT               1024
2879
2880 /*
2881  * extended beacon time format
2882  * time in usec will be changed into a 32-bit value in 8:24 format
2883  * the high 1 byte is the beacon counts
2884  * the lower 3 bytes is the time in usec within one beacon interval
2885  */
2886
2887 static u32 iwl3945_usecs_to_beacons(u32 usec, u32 beacon_interval)
2888 {
2889         u32 quot;
2890         u32 rem;
2891         u32 interval = beacon_interval * 1024;
2892
2893         if (!interval || !usec)
2894                 return 0;
2895
2896         quot = (usec / interval) & (BEACON_TIME_MASK_HIGH >> 24);
2897         rem = (usec % interval) & BEACON_TIME_MASK_LOW;
2898
2899         return (quot << 24) + rem;
2900 }
2901
2902 /* base is usually what we get from ucode with each received frame,
2903  * the same as HW timer counter counting down
2904  */
2905
2906 static __le32 iwl3945_add_beacon_time(u32 base, u32 addon, u32 beacon_interval)
2907 {
2908         u32 base_low = base & BEACON_TIME_MASK_LOW;
2909         u32 addon_low = addon & BEACON_TIME_MASK_LOW;
2910         u32 interval = beacon_interval * TIME_UNIT;
2911         u32 res = (base & BEACON_TIME_MASK_HIGH) +
2912             (addon & BEACON_TIME_MASK_HIGH);
2913
2914         if (base_low > addon_low)
2915                 res += base_low - addon_low;
2916         else if (base_low < addon_low) {
2917                 res += interval + base_low - addon_low;
2918                 res += (1 << 24);
2919         } else
2920                 res += (1 << 24);
2921
2922         return cpu_to_le32(res);
2923 }
2924
2925 static int iwl3945_get_measurement(struct iwl3945_priv *priv,
2926                                struct ieee80211_measurement_params *params,
2927                                u8 type)
2928 {
2929         struct iwl3945_spectrum_cmd spectrum;
2930         struct iwl3945_rx_packet *res;
2931         struct iwl3945_host_cmd cmd = {
2932                 .id = REPLY_SPECTRUM_MEASUREMENT_CMD,
2933                 .data = (void *)&spectrum,
2934                 .meta.flags = CMD_WANT_SKB,
2935         };
2936         u32 add_time = le64_to_cpu(params->start_time);
2937         int rc;
2938         int spectrum_resp_status;
2939         int duration = le16_to_cpu(params->duration);
2940
2941         if (iwl3945_is_associated(priv))
2942                 add_time =
2943                     iwl3945_usecs_to_beacons(
2944                         le64_to_cpu(params->start_time) - priv->last_tsf,
2945                         le16_to_cpu(priv->rxon_timing.beacon_interval));
2946
2947         memset(&spectrum, 0, sizeof(spectrum));
2948
2949         spectrum.channel_count = cpu_to_le16(1);
2950         spectrum.flags =
2951             RXON_FLG_TSF2HOST_MSK | RXON_FLG_ANT_A_MSK | RXON_FLG_DIS_DIV_MSK;
2952         spectrum.filter_flags = MEASUREMENT_FILTER_FLAG;
2953         cmd.len = sizeof(spectrum);
2954         spectrum.len = cpu_to_le16(cmd.len - sizeof(spectrum.len));
2955
2956         if (iwl3945_is_associated(priv))
2957                 spectrum.start_time =
2958                     iwl3945_add_beacon_time(priv->last_beacon_time,
2959                                 add_time,
2960                                 le16_to_cpu(priv->rxon_timing.beacon_interval));
2961         else
2962                 spectrum.start_time = 0;
2963
2964         spectrum.channels[0].duration = cpu_to_le32(duration * TIME_UNIT);
2965         spectrum.channels[0].channel = params->channel;
2966         spectrum.channels[0].type = type;
2967         if (priv->active_rxon.flags & RXON_FLG_BAND_24G_MSK)
2968                 spectrum.flags |= RXON_FLG_BAND_24G_MSK |
2969                     RXON_FLG_AUTO_DETECT_MSK | RXON_FLG_TGG_PROTECT_MSK;
2970
2971         rc = iwl3945_send_cmd_sync(priv, &cmd);
2972         if (rc)
2973                 return rc;
2974
2975         res = (struct iwl3945_rx_packet *)cmd.meta.u.skb->data;
2976         if (res->hdr.flags & IWL_CMD_FAILED_MSK) {
2977                 IWL_ERROR("Bad return from REPLY_RX_ON_ASSOC command\n");
2978                 rc = -EIO;
2979         }
2980
2981         spectrum_resp_status = le16_to_cpu(res->u.spectrum.status);
2982         switch (spectrum_resp_status) {
2983         case 0:         /* Command will be handled */
2984                 if (res->u.spectrum.id != 0xff) {
2985                         IWL_DEBUG_INFO("Replaced existing measurement: %d\n",
2986                                                 res->u.spectrum.id);
2987                         priv->measurement_status &= ~MEASUREMENT_READY;
2988                 }
2989                 priv->measurement_status |= MEASUREMENT_ACTIVE;
2990                 rc = 0;
2991                 break;
2992
2993         case 1:         /* Command will not be handled */
2994                 rc = -EAGAIN;
2995                 break;
2996         }
2997
2998         dev_kfree_skb_any(cmd.meta.u.skb);
2999
3000         return rc;
3001 }
3002 #endif
3003
3004 static void iwl3945_rx_reply_alive(struct iwl3945_priv *priv,
3005                                struct iwl3945_rx_mem_buffer *rxb)
3006 {
3007         struct iwl3945_rx_packet *pkt = (void *)rxb->skb->data;
3008         struct iwl3945_alive_resp *palive;
3009         struct delayed_work *pwork;
3010
3011         palive = &pkt->u.alive_frame;
3012
3013         IWL_DEBUG_INFO("Alive ucode status 0x%08X revision "
3014                        "0x%01X 0x%01X\n",
3015                        palive->is_valid, palive->ver_type,
3016                        palive->ver_subtype);
3017
3018         if (palive->ver_subtype == INITIALIZE_SUBTYPE) {
3019                 IWL_DEBUG_INFO("Initialization Alive received.\n");
3020                 memcpy(&priv->card_alive_init,
3021                        &pkt->u.alive_frame,
3022                        sizeof(struct iwl3945_init_alive_resp));
3023                 pwork = &priv->init_alive_start;
3024         } else {
3025                 IWL_DEBUG_INFO("Runtime Alive received.\n");
3026                 memcpy(&priv->card_alive, &pkt->u.alive_frame,
3027                        sizeof(struct iwl3945_alive_resp));
3028                 pwork = &priv->alive_start;
3029                 iwl3945_disable_events(priv);
3030         }
3031
3032         /* We delay the ALIVE response by 5ms to
3033          * give the HW RF Kill time to activate... */
3034         if (palive->is_valid == UCODE_VALID_OK)
3035                 queue_delayed_work(priv->workqueue, pwork,
3036                                    msecs_to_jiffies(5));
3037         else
3038                 IWL_WARNING("uCode did not respond OK.\n");
3039 }
3040
3041 static void iwl3945_rx_reply_add_sta(struct iwl3945_priv *priv,
3042                                  struct iwl3945_rx_mem_buffer *rxb)
3043 {
3044         struct iwl3945_rx_packet *pkt = (void *)rxb->skb->data;
3045
3046         IWL_DEBUG_RX("Received REPLY_ADD_STA: 0x%02X\n", pkt->u.status);
3047         return;
3048 }
3049
3050 static void iwl3945_rx_reply_error(struct iwl3945_priv *priv,
3051                                struct iwl3945_rx_mem_buffer *rxb)
3052 {
3053         struct iwl3945_rx_packet *pkt = (void *)rxb->skb->data;
3054
3055         IWL_ERROR("Error Reply type 0x%08X cmd %s (0x%02X) "
3056                 "seq 0x%04X ser 0x%08X\n",
3057                 le32_to_cpu(pkt->u.err_resp.error_type),
3058                 get_cmd_string(pkt->u.err_resp.cmd_id),
3059                 pkt->u.err_resp.cmd_id,
3060                 le16_to_cpu(pkt->u.err_resp.bad_cmd_seq_num),
3061                 le32_to_cpu(pkt->u.err_resp.error_info));
3062 }
3063
3064 #define TX_STATUS_ENTRY(x) case TX_STATUS_FAIL_ ## x: return #x
3065
3066 static void iwl3945_rx_csa(struct iwl3945_priv *priv, struct iwl3945_rx_mem_buffer *rxb)
3067 {
3068         struct iwl3945_rx_packet *pkt = (void *)rxb->skb->data;
3069         struct iwl3945_rxon_cmd *rxon = (void *)&priv->active_rxon;
3070         struct iwl3945_csa_notification *csa = &(pkt->u.csa_notif);
3071         IWL_DEBUG_11H("CSA notif: channel %d, status %d\n",
3072                       le16_to_cpu(csa->channel), le32_to_cpu(csa->status));
3073         rxon->channel = csa->channel;
3074         priv->staging_rxon.channel = csa->channel;
3075 }
3076
3077 static void iwl3945_rx_spectrum_measure_notif(struct iwl3945_priv *priv,
3078                                           struct iwl3945_rx_mem_buffer *rxb)
3079 {
3080 #ifdef CONFIG_IWL3945_SPECTRUM_MEASUREMENT
3081         struct iwl3945_rx_packet *pkt = (void *)rxb->skb->data;
3082         struct iwl3945_spectrum_notification *report = &(pkt->u.spectrum_notif);
3083
3084         if (!report->state) {
3085                 IWL_DEBUG(IWL_DL_11H | IWL_DL_INFO,
3086                           "Spectrum Measure Notification: Start\n");
3087                 return;
3088         }
3089
3090         memcpy(&priv->measure_report, report, sizeof(*report));
3091         priv->measurement_status |= MEASUREMENT_READY;
3092 #endif
3093 }
3094
3095 static void iwl3945_rx_pm_sleep_notif(struct iwl3945_priv *priv,
3096                                   struct iwl3945_rx_mem_buffer *rxb)
3097 {
3098 #ifdef CONFIG_IWL3945_DEBUG
3099         struct iwl3945_rx_packet *pkt = (void *)rxb->skb->data;
3100         struct iwl3945_sleep_notification *sleep = &(pkt->u.sleep_notif);
3101         IWL_DEBUG_RX("sleep mode: %d, src: %d\n",
3102                      sleep->pm_sleep_mode, sleep->pm_wakeup_src);
3103 #endif
3104 }
3105
3106 static void iwl3945_rx_pm_debug_statistics_notif(struct iwl3945_priv *priv,
3107                                              struct iwl3945_rx_mem_buffer *rxb)
3108 {
3109         struct iwl3945_rx_packet *pkt = (void *)rxb->skb->data;
3110         IWL_DEBUG_RADIO("Dumping %d bytes of unhandled "
3111                         "notification for %s:\n",
3112                         le32_to_cpu(pkt->len), get_cmd_string(pkt->hdr.cmd));
3113         iwl3945_print_hex_dump(IWL_DL_RADIO, pkt->u.raw, le32_to_cpu(pkt->len));
3114 }
3115
3116 static void iwl3945_bg_beacon_update(struct work_struct *work)
3117 {
3118         struct iwl3945_priv *priv =
3119                 container_of(work, struct iwl3945_priv, beacon_update);
3120         struct sk_buff *beacon;
3121
3122         /* Pull updated AP beacon from mac80211. will fail if not in AP mode */
3123         beacon = ieee80211_beacon_get(priv->hw, priv->vif);
3124
3125         if (!beacon) {
3126                 IWL_ERROR("update beacon failed\n");
3127                 return;
3128         }
3129
3130         mutex_lock(&priv->mutex);
3131         /* new beacon skb is allocated every time; dispose previous.*/
3132         if (priv->ibss_beacon)
3133                 dev_kfree_skb(priv->ibss_beacon);
3134
3135         priv->ibss_beacon = beacon;
3136         mutex_unlock(&priv->mutex);
3137
3138         iwl3945_send_beacon_cmd(priv);
3139 }
3140
3141 static void iwl3945_rx_beacon_notif(struct iwl3945_priv *priv,
3142                                 struct iwl3945_rx_mem_buffer *rxb)
3143 {
3144 #ifdef CONFIG_IWL3945_DEBUG
3145         struct iwl3945_rx_packet *pkt = (void *)rxb->skb->data;
3146         struct iwl3945_beacon_notif *beacon = &(pkt->u.beacon_status);
3147         u8 rate = beacon->beacon_notify_hdr.rate;
3148
3149         IWL_DEBUG_RX("beacon status %x retries %d iss %d "
3150                 "tsf %d %d rate %d\n",
3151                 le32_to_cpu(beacon->beacon_notify_hdr.status) & TX_STATUS_MSK,
3152                 beacon->beacon_notify_hdr.failure_frame,
3153                 le32_to_cpu(beacon->ibss_mgr_status),
3154                 le32_to_cpu(beacon->high_tsf),
3155                 le32_to_cpu(beacon->low_tsf), rate);
3156 #endif
3157
3158         if ((priv->iw_mode == NL80211_IFTYPE_AP) &&
3159             (!test_bit(STATUS_EXIT_PENDING, &priv->status)))
3160                 queue_work(priv->workqueue, &priv->beacon_update);
3161 }
3162
3163 /* Service response to REPLY_SCAN_CMD (0x80) */
3164 static void iwl3945_rx_reply_scan(struct iwl3945_priv *priv,
3165                               struct iwl3945_rx_mem_buffer *rxb)
3166 {
3167 #ifdef CONFIG_IWL3945_DEBUG
3168         struct iwl3945_rx_packet *pkt = (void *)rxb->skb->data;
3169         struct iwl3945_scanreq_notification *notif =
3170             (struct iwl3945_scanreq_notification *)pkt->u.raw;
3171
3172         IWL_DEBUG_RX("Scan request status = 0x%x\n", notif->status);
3173 #endif
3174 }
3175
3176 /* Service SCAN_START_NOTIFICATION (0x82) */
3177 static void iwl3945_rx_scan_start_notif(struct iwl3945_priv *priv,
3178                                     struct iwl3945_rx_mem_buffer *rxb)
3179 {
3180         struct iwl3945_rx_packet *pkt = (void *)rxb->skb->data;
3181         struct iwl3945_scanstart_notification *notif =
3182             (struct iwl3945_scanstart_notification *)pkt->u.raw;
3183         priv->scan_start_tsf = le32_to_cpu(notif->tsf_low);
3184         IWL_DEBUG_SCAN("Scan start: "
3185                        "%d [802.11%s] "
3186                        "(TSF: 0x%08X:%08X) - %d (beacon timer %u)\n",
3187                        notif->channel,
3188                        notif->band ? "bg" : "a",
3189                        notif->tsf_high,
3190                        notif->tsf_low, notif->status, notif->beacon_timer);
3191 }
3192
3193 /* Service SCAN_RESULTS_NOTIFICATION (0x83) */
3194 static void iwl3945_rx_scan_results_notif(struct iwl3945_priv *priv,
3195                                       struct iwl3945_rx_mem_buffer *rxb)
3196 {
3197         struct iwl3945_rx_packet *pkt = (void *)rxb->skb->data;
3198         struct iwl3945_scanresults_notification *notif =
3199             (struct iwl3945_scanresults_notification *)pkt->u.raw;
3200
3201         IWL_DEBUG_SCAN("Scan ch.res: "
3202                        "%d [802.11%s] "
3203                        "(TSF: 0x%08X:%08X) - %d "
3204                        "elapsed=%lu usec (%dms since last)\n",
3205                        notif->channel,
3206                        notif->band ? "bg" : "a",
3207                        le32_to_cpu(notif->tsf_high),
3208                        le32_to_cpu(notif->tsf_low),
3209                        le32_to_cpu(notif->statistics[0]),
3210                        le32_to_cpu(notif->tsf_low) - priv->scan_start_tsf,
3211                        jiffies_to_msecs(elapsed_jiffies
3212                                         (priv->last_scan_jiffies, jiffies)));
3213
3214         priv->last_scan_jiffies = jiffies;
3215         priv->next_scan_jiffies = 0;
3216 }
3217
3218 /* Service SCAN_COMPLETE_NOTIFICATION (0x84) */
3219 static void iwl3945_rx_scan_complete_notif(struct iwl3945_priv *priv,
3220                                        struct iwl3945_rx_mem_buffer *rxb)
3221 {
3222         struct iwl3945_rx_packet *pkt = (void *)rxb->skb->data;
3223         struct iwl3945_scancomplete_notification *scan_notif = (void *)pkt->u.raw;
3224
3225         IWL_DEBUG_SCAN("Scan complete: %d channels (TSF 0x%08X:%08X) - %d\n",
3226                        scan_notif->scanned_channels,
3227                        scan_notif->tsf_low,
3228                        scan_notif->tsf_high, scan_notif->status);
3229
3230         /* The HW is no longer scanning */
3231         clear_bit(STATUS_SCAN_HW, &priv->status);
3232
3233         /* The scan completion notification came in, so kill that timer... */
3234         cancel_delayed_work(&priv->scan_check);
3235
3236         IWL_DEBUG_INFO("Scan pass on %sGHz took %dms\n",
3237                        (priv->scan_bands & BIT(IEEE80211_BAND_2GHZ)) ?
3238                                                         "2.4" : "5.2",
3239                        jiffies_to_msecs(elapsed_jiffies
3240                                         (priv->scan_pass_start, jiffies)));
3241
3242         /* Remove this scanned band from the list of pending
3243          * bands to scan, band G precedes A in order of scanning
3244          * as seen in iwl3945_bg_request_scan */
3245         if (priv->scan_bands & BIT(IEEE80211_BAND_2GHZ))
3246                 priv->scan_bands &= ~BIT(IEEE80211_BAND_2GHZ);
3247         else if (priv->scan_bands &  BIT(IEEE80211_BAND_5GHZ))
3248                 priv->scan_bands &= ~BIT(IEEE80211_BAND_5GHZ);
3249
3250         /* If a request to abort was given, or the scan did not succeed
3251          * then we reset the scan state machine and terminate,
3252          * re-queuing another scan if one has been requested */
3253         if (test_bit(STATUS_SCAN_ABORTING, &priv->status)) {
3254                 IWL_DEBUG_INFO("Aborted scan completed.\n");
3255                 clear_bit(STATUS_SCAN_ABORTING, &priv->status);
3256         } else {
3257                 /* If there are more bands on this scan pass reschedule */
3258                 if (priv->scan_bands > 0)
3259                         goto reschedule;
3260         }
3261
3262         priv->last_scan_jiffies = jiffies;
3263         priv->next_scan_jiffies = 0;
3264         IWL_DEBUG_INFO("Setting scan to off\n");
3265
3266         clear_bit(STATUS_SCANNING, &priv->status);
3267
3268         IWL_DEBUG_INFO("Scan took %dms\n",
3269                 jiffies_to_msecs(elapsed_jiffies(priv->scan_start, jiffies)));
3270
3271         queue_work(priv->workqueue, &priv->scan_completed);
3272
3273         return;
3274
3275 reschedule:
3276         priv->scan_pass_start = jiffies;
3277         queue_work(priv->workqueue, &priv->request_scan);
3278 }
3279
3280 /* Handle notification from uCode that card's power state is changing
3281  * due to software, hardware, or critical temperature RFKILL */
3282 static void iwl3945_rx_card_state_notif(struct iwl3945_priv *priv,
3283                                     struct iwl3945_rx_mem_buffer *rxb)
3284 {
3285         struct iwl3945_rx_packet *pkt = (void *)rxb->skb->data;
3286         u32 flags = le32_to_cpu(pkt->u.card_state_notif.flags);
3287         unsigned long status = priv->status;
3288
3289         IWL_DEBUG_RF_KILL("Card state received: HW:%s SW:%s\n",
3290                           (flags & HW_CARD_DISABLED) ? "Kill" : "On",
3291                           (flags & SW_CARD_DISABLED) ? "Kill" : "On");
3292
3293         iwl3945_write32(priv, CSR_UCODE_DRV_GP1_SET,
3294                     CSR_UCODE_DRV_GP1_BIT_CMD_BLOCKED);
3295
3296         if (flags & HW_CARD_DISABLED)
3297                 set_bit(STATUS_RF_KILL_HW, &priv->status);
3298         else
3299                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
3300
3301
3302         if (flags & SW_CARD_DISABLED)
3303                 set_bit(STATUS_RF_KILL_SW, &priv->status);
3304         else
3305                 clear_bit(STATUS_RF_KILL_SW, &priv->status);
3306
3307         iwl3945_scan_cancel(priv);
3308
3309         if ((test_bit(STATUS_RF_KILL_HW, &status) !=
3310              test_bit(STATUS_RF_KILL_HW, &priv->status)) ||
3311             (test_bit(STATUS_RF_KILL_SW, &status) !=
3312              test_bit(STATUS_RF_KILL_SW, &priv->status)))
3313                 queue_work(priv->workqueue, &priv->rf_kill);
3314         else
3315                 wake_up_interruptible(&priv->wait_command_queue);
3316 }
3317
3318 /**
3319  * iwl3945_setup_rx_handlers - Initialize Rx handler callbacks
3320  *
3321  * Setup the RX handlers for each of the reply types sent from the uCode
3322  * to the host.
3323  *
3324  * This function chains into the hardware specific files for them to setup
3325  * any hardware specific handlers as well.
3326  */
3327 static void iwl3945_setup_rx_handlers(struct iwl3945_priv *priv)
3328 {
3329         priv->rx_handlers[REPLY_ALIVE] = iwl3945_rx_reply_alive;
3330         priv->rx_handlers[REPLY_ADD_STA] = iwl3945_rx_reply_add_sta;
3331         priv->rx_handlers[REPLY_ERROR] = iwl3945_rx_reply_error;
3332         priv->rx_handlers[CHANNEL_SWITCH_NOTIFICATION] = iwl3945_rx_csa;
3333         priv->rx_handlers[SPECTRUM_MEASURE_NOTIFICATION] =
3334             iwl3945_rx_spectrum_measure_notif;
3335         priv->rx_handlers[PM_SLEEP_NOTIFICATION] = iwl3945_rx_pm_sleep_notif;
3336         priv->rx_handlers[PM_DEBUG_STATISTIC_NOTIFIC] =
3337             iwl3945_rx_pm_debug_statistics_notif;
3338         priv->rx_handlers[BEACON_NOTIFICATION] = iwl3945_rx_beacon_notif;
3339
3340         /*
3341          * The same handler is used for both the REPLY to a discrete
3342          * statistics request from the host as well as for the periodic
3343          * statistics notifications (after received beacons) from the uCode.
3344          */
3345         priv->rx_handlers[REPLY_STATISTICS_CMD] = iwl3945_hw_rx_statistics;
3346         priv->rx_handlers[STATISTICS_NOTIFICATION] = iwl3945_hw_rx_statistics;
3347
3348         priv->rx_handlers[REPLY_SCAN_CMD] = iwl3945_rx_reply_scan;
3349         priv->rx_handlers[SCAN_START_NOTIFICATION] = iwl3945_rx_scan_start_notif;
3350         priv->rx_handlers[SCAN_RESULTS_NOTIFICATION] =
3351             iwl3945_rx_scan_results_notif;
3352         priv->rx_handlers[SCAN_COMPLETE_NOTIFICATION] =
3353             iwl3945_rx_scan_complete_notif;
3354         priv->rx_handlers[CARD_STATE_NOTIFICATION] = iwl3945_rx_card_state_notif;
3355
3356         /* Set up hardware specific Rx handlers */
3357         iwl3945_hw_rx_handler_setup(priv);
3358 }
3359
3360 /**
3361  * iwl3945_cmd_queue_reclaim - Reclaim CMD queue entries
3362  * When FW advances 'R' index, all entries between old and new 'R' index
3363  * need to be reclaimed.
3364  */
3365 static void iwl3945_cmd_queue_reclaim(struct iwl3945_priv *priv,
3366                                       int txq_id, int index)
3367 {
3368         struct iwl3945_tx_queue *txq = &priv->txq[txq_id];
3369         struct iwl3945_queue *q = &txq->q;
3370         int nfreed = 0;
3371
3372         if ((index >= q->n_bd) || (iwl3945_x2_queue_used(q, index) == 0)) {
3373                 IWL_ERROR("Read index for DMA queue txq id (%d), index %d, "
3374                           "is out of range [0-%d] %d %d.\n", txq_id,
3375                           index, q->n_bd, q->write_ptr, q->read_ptr);
3376                 return;
3377         }
3378
3379         for (index = iwl_queue_inc_wrap(index, q->n_bd); q->read_ptr != index;
3380                 q->read_ptr = iwl_queue_inc_wrap(q->read_ptr, q->n_bd)) {
3381                 if (nfreed > 1) {
3382                         IWL_ERROR("HCMD skipped: index (%d) %d %d\n", index,
3383                                         q->write_ptr, q->read_ptr);
3384                         queue_work(priv->workqueue, &priv->restart);
3385                         break;
3386                 }
3387                 nfreed++;
3388         }
3389 }
3390
3391
3392 /**
3393  * iwl3945_tx_cmd_complete - Pull unused buffers off the queue and reclaim them
3394  * @rxb: Rx buffer to reclaim
3395  *
3396  * If an Rx buffer has an async callback associated with it the callback
3397  * will be executed.  The attached skb (if present) will only be freed
3398  * if the callback returns 1
3399  */
3400 static void iwl3945_tx_cmd_complete(struct iwl3945_priv *priv,
3401                                 struct iwl3945_rx_mem_buffer *rxb)
3402 {
3403         struct iwl3945_rx_packet *pkt = (struct iwl3945_rx_packet *)rxb->skb->data;
3404         u16 sequence = le16_to_cpu(pkt->hdr.sequence);
3405         int txq_id = SEQ_TO_QUEUE(sequence);
3406         int index = SEQ_TO_INDEX(sequence);
3407         int huge = sequence & SEQ_HUGE_FRAME;
3408         int cmd_index;
3409         struct iwl3945_cmd *cmd;
3410
3411         BUG_ON(txq_id != IWL_CMD_QUEUE_NUM);
3412
3413         cmd_index = get_cmd_index(&priv->txq[IWL_CMD_QUEUE_NUM].q, index, huge);
3414         cmd = &priv->txq[IWL_CMD_QUEUE_NUM].cmd[cmd_index];
3415
3416         /* Input error checking is done when commands are added to queue. */
3417         if (cmd->meta.flags & CMD_WANT_SKB) {
3418                 cmd->meta.source->u.skb = rxb->skb;
3419                 rxb->skb = NULL;
3420         } else if (cmd->meta.u.callback &&
3421                    !cmd->meta.u.callback(priv, cmd, rxb->skb))
3422                 rxb->skb = NULL;
3423
3424         iwl3945_cmd_queue_reclaim(priv, txq_id, index);
3425
3426         if (!(cmd->meta.flags & CMD_ASYNC)) {
3427                 clear_bit(STATUS_HCMD_ACTIVE, &priv->status);
3428                 wake_up_interruptible(&priv->wait_command_queue);
3429         }
3430 }
3431
3432 /************************** RX-FUNCTIONS ****************************/
3433 /*
3434  * Rx theory of operation
3435  *
3436  * The host allocates 32 DMA target addresses and passes the host address
3437  * to the firmware at register IWL_RFDS_TABLE_LOWER + N * RFD_SIZE where N is
3438  * 0 to 31
3439  *
3440  * Rx Queue Indexes
3441  * The host/firmware share two index registers for managing the Rx buffers.
3442  *
3443  * The READ index maps to the first position that the firmware may be writing
3444  * to -- the driver can read up to (but not including) this position and get
3445  * good data.
3446  * The READ index is managed by the firmware once the card is enabled.
3447  *
3448  * The WRITE index maps to the last position the driver has read from -- the
3449  * position preceding WRITE is the last slot the firmware can place a packet.
3450  *
3451  * The queue is empty (no good data) if WRITE = READ - 1, and is full if
3452  * WRITE = READ.
3453  *
3454  * During initialization, the host sets up the READ queue position to the first
3455  * INDEX position, and WRITE to the last (READ - 1 wrapped)
3456  *
3457  * When the firmware places a packet in a buffer, it will advance the READ index
3458  * and fire the RX interrupt.  The driver can then query the READ index and
3459  * process as many packets as possible, moving the WRITE index forward as it
3460  * resets the Rx queue buffers with new memory.
3461  *
3462  * The management in the driver is as follows:
3463  * + A list of pre-allocated SKBs is stored in iwl->rxq->rx_free.  When
3464  *   iwl->rxq->free_count drops to or below RX_LOW_WATERMARK, work is scheduled
3465  *   to replenish the iwl->rxq->rx_free.
3466  * + In iwl3945_rx_replenish (scheduled) if 'processed' != 'read' then the
3467  *   iwl->rxq is replenished and the READ INDEX is updated (updating the
3468  *   'processed' and 'read' driver indexes as well)
3469  * + A received packet is processed and handed to the kernel network stack,
3470  *   detached from the iwl->rxq.  The driver 'processed' index is updated.
3471  * + The Host/Firmware iwl->rxq is replenished at tasklet time from the rx_free
3472  *   list. If there are no allocated buffers in iwl->rxq->rx_free, the READ
3473  *   INDEX is not incremented and iwl->status(RX_STALLED) is set.  If there
3474  *   were enough free buffers and RX_STALLED is set it is cleared.
3475  *
3476  *
3477  * Driver sequence:
3478  *
3479  * iwl3945_rx_queue_alloc()   Allocates rx_free
3480  * iwl3945_rx_replenish()     Replenishes rx_free list from rx_used, and calls
3481  *                            iwl3945_rx_queue_restock
3482  * iwl3945_rx_queue_restock() Moves available buffers from rx_free into Rx
3483  *                            queue, updates firmware pointers, and updates
3484  *                            the WRITE index.  If insufficient rx_free buffers
3485  *                            are available, schedules iwl3945_rx_replenish
3486  *
3487  * -- enable interrupts --
3488  * ISR - iwl3945_rx()         Detach iwl3945_rx_mem_buffers from pool up to the
3489  *                            READ INDEX, detaching the SKB from the pool.
3490  *                            Moves the packet buffer from queue to rx_used.
3491  *                            Calls iwl3945_rx_queue_restock to refill any empty
3492  *                            slots.
3493  * ...
3494  *
3495  */
3496
3497 /**
3498  * iwl3945_rx_queue_space - Return number of free slots available in queue.
3499  */
3500 static int iwl3945_rx_queue_space(const struct iwl3945_rx_queue *q)
3501 {
3502         int s = q->read - q->write;
3503         if (s <= 0)
3504                 s += RX_QUEUE_SIZE;
3505         /* keep some buffer to not confuse full and empty queue */
3506         s -= 2;
3507         if (s < 0)
3508                 s = 0;
3509         return s;
3510 }
3511
3512 /**
3513  * iwl3945_rx_queue_update_write_ptr - Update the write pointer for the RX queue
3514  */
3515 int iwl3945_rx_queue_update_write_ptr(struct iwl3945_priv *priv, struct iwl3945_rx_queue *q)
3516 {
3517         u32 reg = 0;
3518         int rc = 0;
3519         unsigned long flags;
3520
3521         spin_lock_irqsave(&q->lock, flags);
3522
3523         if (q->need_update == 0)
3524                 goto exit_unlock;
3525
3526         /* If power-saving is in use, make sure device is awake */
3527         if (test_bit(STATUS_POWER_PMI, &priv->status)) {
3528                 reg = iwl3945_read32(priv, CSR_UCODE_DRV_GP1);
3529
3530                 if (reg & CSR_UCODE_DRV_GP1_BIT_MAC_SLEEP) {
3531                         iwl3945_set_bit(priv, CSR_GP_CNTRL,
3532                                     CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
3533                         goto exit_unlock;
3534                 }
3535
3536                 rc = iwl3945_grab_nic_access(priv);
3537                 if (rc)
3538                         goto exit_unlock;
3539
3540                 /* Device expects a multiple of 8 */
3541                 iwl3945_write_direct32(priv, FH_RSCSR_CHNL0_WPTR,
3542                                      q->write & ~0x7);
3543                 iwl3945_release_nic_access(priv);
3544
3545         /* Else device is assumed to be awake */
3546         } else
3547                 /* Device expects a multiple of 8 */
3548                 iwl3945_write32(priv, FH_RSCSR_CHNL0_WPTR, q->write & ~0x7);
3549
3550
3551         q->need_update = 0;
3552
3553  exit_unlock:
3554         spin_unlock_irqrestore(&q->lock, flags);
3555         return rc;
3556 }
3557
3558 /**
3559  * iwl3945_dma_addr2rbd_ptr - convert a DMA address to a uCode read buffer ptr
3560  */
3561 static inline __le32 iwl3945_dma_addr2rbd_ptr(struct iwl3945_priv *priv,
3562                                           dma_addr_t dma_addr)
3563 {
3564         return cpu_to_le32((u32)dma_addr);
3565 }
3566
3567 /**
3568  * iwl3945_rx_queue_restock - refill RX queue from pre-allocated pool
3569  *
3570  * If there are slots in the RX queue that need to be restocked,
3571  * and we have free pre-allocated buffers, fill the ranks as much
3572  * as we can, pulling from rx_free.
3573  *
3574  * This moves the 'write' index forward to catch up with 'processed', and
3575  * also updates the memory address in the firmware to reference the new
3576  * target buffer.
3577  */
3578 static int iwl3945_rx_queue_restock(struct iwl3945_priv *priv)
3579 {
3580         struct iwl3945_rx_queue *rxq = &priv->rxq;
3581         struct list_head *element;
3582         struct iwl3945_rx_mem_buffer *rxb;
3583         unsigned long flags;
3584         int write, rc;
3585
3586         spin_lock_irqsave(&rxq->lock, flags);
3587         write = rxq->write & ~0x7;
3588         while ((iwl3945_rx_queue_space(rxq) > 0) && (rxq->free_count)) {
3589                 /* Get next free Rx buffer, remove from free list */
3590                 element = rxq->rx_free.next;
3591                 rxb = list_entry(element, struct iwl3945_rx_mem_buffer, list);
3592                 list_del(element);
3593
3594                 /* Point to Rx buffer via next RBD in circular buffer */
3595                 rxq->bd[rxq->write] = iwl3945_dma_addr2rbd_ptr(priv, rxb->dma_addr);
3596                 rxq->queue[rxq->write] = rxb;
3597                 rxq->write = (rxq->write + 1) & RX_QUEUE_MASK;
3598                 rxq->free_count--;
3599         }
3600         spin_unlock_irqrestore(&rxq->lock, flags);
3601         /* If the pre-allocated buffer pool is dropping low, schedule to
3602          * refill it */
3603         if (rxq->free_count <= RX_LOW_WATERMARK)
3604                 queue_work(priv->workqueue, &priv->rx_replenish);
3605
3606
3607         /* If we've added more space for the firmware to place data, tell it.
3608          * Increment device's write pointer in multiples of 8. */
3609         if ((write != (rxq->write & ~0x7))
3610             || (abs(rxq->write - rxq->read) > 7)) {
3611                 spin_lock_irqsave(&rxq->lock, flags);
3612                 rxq->need_update = 1;
3613                 spin_unlock_irqrestore(&rxq->lock, flags);
3614                 rc = iwl3945_rx_queue_update_write_ptr(priv, rxq);
3615                 if (rc)
3616                         return rc;
3617         }
3618
3619         return 0;
3620 }
3621
3622 /**
3623  * iwl3945_rx_replenish - Move all used packet from rx_used to rx_free
3624  *
3625  * When moving to rx_free an SKB is allocated for the slot.
3626  *
3627  * Also restock the Rx queue via iwl3945_rx_queue_restock.
3628  * This is called as a scheduled work item (except for during initialization)
3629  */
3630 static void iwl3945_rx_allocate(struct iwl3945_priv *priv)
3631 {
3632         struct iwl3945_rx_queue *rxq = &priv->rxq;
3633         struct list_head *element;
3634         struct iwl3945_rx_mem_buffer *rxb;
3635         unsigned long flags;
3636         spin_lock_irqsave(&rxq->lock, flags);
3637         while (!list_empty(&rxq->rx_used)) {
3638                 element = rxq->rx_used.next;
3639                 rxb = list_entry(element, struct iwl3945_rx_mem_buffer, list);
3640
3641                 /* Alloc a new receive buffer */
3642                 rxb->skb =
3643                     alloc_skb(IWL_RX_BUF_SIZE, __GFP_NOWARN | GFP_ATOMIC);
3644                 if (!rxb->skb) {
3645                         if (net_ratelimit())
3646                                 printk(KERN_CRIT DRV_NAME
3647                                        ": Can not allocate SKB buffers\n");
3648                         /* We don't reschedule replenish work here -- we will
3649                          * call the restock method and if it still needs
3650                          * more buffers it will schedule replenish */
3651                         break;
3652                 }
3653
3654                 /* If radiotap head is required, reserve some headroom here.
3655                  * The physical head count is a variable rx_stats->phy_count.
3656                  * We reserve 4 bytes here. Plus these extra bytes, the
3657                  * headroom of the physical head should be enough for the
3658                  * radiotap head that iwl3945 supported. See iwl3945_rt.
3659                  */
3660                 skb_reserve(rxb->skb, 4);
3661
3662                 priv->alloc_rxb_skb++;
3663                 list_del(element);
3664
3665                 /* Get physical address of RB/SKB */
3666                 rxb->dma_addr =
3667                     pci_map_single(priv->pci_dev, rxb->skb->data,
3668                                    IWL_RX_BUF_SIZE, PCI_DMA_FROMDEVICE);
3669                 list_add_tail(&rxb->list, &rxq->rx_free);
3670                 rxq->free_count++;
3671         }
3672         spin_unlock_irqrestore(&rxq->lock, flags);
3673 }
3674
3675 /*
3676  * this should be called while priv->lock is locked
3677  */
3678 static void __iwl3945_rx_replenish(void *data)
3679 {
3680         struct iwl3945_priv *priv = data;
3681
3682         iwl3945_rx_allocate(priv);
3683         iwl3945_rx_queue_restock(priv);
3684 }
3685
3686
3687 void iwl3945_rx_replenish(void *data)
3688 {
3689         struct iwl3945_priv *priv = data;
3690         unsigned long flags;
3691
3692         iwl3945_rx_allocate(priv);
3693
3694         spin_lock_irqsave(&priv->lock, flags);
3695         iwl3945_rx_queue_restock(priv);
3696         spin_unlock_irqrestore(&priv->lock, flags);
3697 }
3698
3699 /* Assumes that the skb field of the buffers in 'pool' is kept accurate.
3700  * If an SKB has been detached, the POOL needs to have its SKB set to NULL
3701  * This free routine walks the list of POOL entries and if SKB is set to
3702  * non NULL it is unmapped and freed
3703  */
3704 static void iwl3945_rx_queue_free(struct iwl3945_priv *priv, struct iwl3945_rx_queue *rxq)
3705 {
3706         int i;
3707         for (i = 0; i < RX_QUEUE_SIZE + RX_FREE_BUFFERS; i++) {
3708                 if (rxq->pool[i].skb != NULL) {
3709                         pci_unmap_single(priv->pci_dev,
3710                                          rxq->pool[i].dma_addr,
3711                                          IWL_RX_BUF_SIZE, PCI_DMA_FROMDEVICE);
3712                         dev_kfree_skb(rxq->pool[i].skb);
3713                 }
3714         }
3715
3716         pci_free_consistent(priv->pci_dev, 4 * RX_QUEUE_SIZE, rxq->bd,
3717                             rxq->dma_addr);
3718         rxq->bd = NULL;
3719 }
3720
3721 int iwl3945_rx_queue_alloc(struct iwl3945_priv *priv)
3722 {
3723         struct iwl3945_rx_queue *rxq = &priv->rxq;
3724         struct pci_dev *dev = priv->pci_dev;
3725         int i;
3726
3727         spin_lock_init(&rxq->lock);
3728         INIT_LIST_HEAD(&rxq->rx_free);
3729         INIT_LIST_HEAD(&rxq->rx_used);
3730
3731         /* Alloc the circular buffer of Read Buffer Descriptors (RBDs) */
3732         rxq->bd = pci_alloc_consistent(dev, 4 * RX_QUEUE_SIZE, &rxq->dma_addr);
3733         if (!rxq->bd)
3734                 return -ENOMEM;
3735
3736         /* Fill the rx_used queue with _all_ of the Rx buffers */
3737         for (i = 0; i < RX_FREE_BUFFERS + RX_QUEUE_SIZE; i++)
3738                 list_add_tail(&rxq->pool[i].list, &rxq->rx_used);
3739
3740         /* Set us so that we have processed and used all buffers, but have
3741          * not restocked the Rx queue with fresh buffers */
3742         rxq->read = rxq->write = 0;
3743         rxq->free_count = 0;
3744         rxq->need_update = 0;
3745         return 0;
3746 }
3747
3748 void iwl3945_rx_queue_reset(struct iwl3945_priv *priv, struct iwl3945_rx_queue *rxq)
3749 {
3750         unsigned long flags;
3751         int i;
3752         spin_lock_irqsave(&rxq->lock, flags);
3753         INIT_LIST_HEAD(&rxq->rx_free);
3754         INIT_LIST_HEAD(&rxq->rx_used);
3755         /* Fill the rx_used queue with _all_ of the Rx buffers */
3756         for (i = 0; i < RX_FREE_BUFFERS + RX_QUEUE_SIZE; i++) {
3757                 /* In the reset function, these buffers may have been allocated
3758                  * to an SKB, so we need to unmap and free potential storage */
3759                 if (rxq->pool[i].skb != NULL) {
3760                         pci_unmap_single(priv->pci_dev,
3761                                          rxq->pool[i].dma_addr,
3762                                          IWL_RX_BUF_SIZE, PCI_DMA_FROMDEVICE);
3763                         priv->alloc_rxb_skb--;
3764                         dev_kfree_skb(rxq->pool[i].skb);
3765                         rxq->pool[i].skb = NULL;
3766                 }
3767                 list_add_tail(&rxq->pool[i].list, &rxq->rx_used);
3768         }
3769
3770         /* Set us so that we have processed and used all buffers, but have
3771          * not restocked the Rx queue with fresh buffers */
3772         rxq->read = rxq->write = 0;
3773         rxq->free_count = 0;
3774         spin_unlock_irqrestore(&rxq->lock, flags);
3775 }
3776
3777 /* Convert linear signal-to-noise ratio into dB */
3778 static u8 ratio2dB[100] = {
3779 /*       0   1   2   3   4   5   6   7   8   9 */
3780          0,  0,  6, 10, 12, 14, 16, 17, 18, 19, /* 00 - 09 */
3781         20, 21, 22, 22, 23, 23, 24, 25, 26, 26, /* 10 - 19 */
3782         26, 26, 26, 27, 27, 28, 28, 28, 29, 29, /* 20 - 29 */
3783         29, 30, 30, 30, 31, 31, 31, 31, 32, 32, /* 30 - 39 */
3784         32, 32, 32, 33, 33, 33, 33, 33, 34, 34, /* 40 - 49 */
3785         34, 34, 34, 34, 35, 35, 35, 35, 35, 35, /* 50 - 59 */
3786         36, 36, 36, 36, 36, 36, 36, 37, 37, 37, /* 60 - 69 */
3787         37, 37, 37, 37, 37, 38, 38, 38, 38, 38, /* 70 - 79 */
3788         38, 38, 38, 38, 38, 39, 39, 39, 39, 39, /* 80 - 89 */
3789         39, 39, 39, 39, 39, 40, 40, 40, 40, 40  /* 90 - 99 */
3790 };
3791
3792 /* Calculates a relative dB value from a ratio of linear
3793  *   (i.e. not dB) signal levels.
3794  * Conversion assumes that levels are voltages (20*log), not powers (10*log). */
3795 int iwl3945_calc_db_from_ratio(int sig_ratio)
3796 {
3797         /* 1000:1 or higher just report as 60 dB */
3798         if (sig_ratio >= 1000)
3799                 return 60;
3800
3801         /* 100:1 or higher, divide by 10 and use table,
3802          *   add 20 dB to make up for divide by 10 */
3803         if (sig_ratio >= 100)
3804                 return 20 + (int)ratio2dB[sig_ratio/10];
3805
3806         /* We shouldn't see this */
3807         if (sig_ratio < 1)
3808                 return 0;
3809
3810         /* Use table for ratios 1:1 - 99:1 */
3811         return (int)ratio2dB[sig_ratio];
3812 }
3813
3814 #define PERFECT_RSSI (-20) /* dBm */
3815 #define WORST_RSSI (-95)   /* dBm */
3816 #define RSSI_RANGE (PERFECT_RSSI - WORST_RSSI)
3817
3818 /* Calculate an indication of rx signal quality (a percentage, not dBm!).
3819  * See http://www.ces.clemson.edu/linux/signal_quality.shtml for info
3820  *   about formulas used below. */
3821 int iwl3945_calc_sig_qual(int rssi_dbm, int noise_dbm)
3822 {
3823         int sig_qual;
3824         int degradation = PERFECT_RSSI - rssi_dbm;
3825
3826         /* If we get a noise measurement, use signal-to-noise ratio (SNR)
3827          * as indicator; formula is (signal dbm - noise dbm).
3828          * SNR at or above 40 is a great signal (100%).
3829          * Below that, scale to fit SNR of 0 - 40 dB within 0 - 100% indicator.
3830          * Weakest usable signal is usually 10 - 15 dB SNR. */
3831         if (noise_dbm) {
3832                 if (rssi_dbm - noise_dbm >= 40)
3833                         return 100;
3834                 else if (rssi_dbm < noise_dbm)
3835                         return 0;
3836                 sig_qual = ((rssi_dbm - noise_dbm) * 5) / 2;
3837
3838         /* Else use just the signal level.
3839          * This formula is a least squares fit of data points collected and
3840          *   compared with a reference system that had a percentage (%) display
3841          *   for signal quality. */
3842         } else
3843                 sig_qual = (100 * (RSSI_RANGE * RSSI_RANGE) - degradation *
3844                             (15 * RSSI_RANGE + 62 * degradation)) /
3845                            (RSSI_RANGE * RSSI_RANGE);
3846
3847         if (sig_qual > 100)
3848                 sig_qual = 100;
3849         else if (sig_qual < 1)
3850                 sig_qual = 0;
3851
3852         return sig_qual;
3853 }
3854
3855 /**
3856  * iwl3945_rx_handle - Main entry function for receiving responses from uCode
3857  *
3858  * Uses the priv->rx_handlers callback function array to invoke
3859  * the appropriate handlers, including command responses,
3860  * frame-received notifications, and other notifications.
3861  */
3862 static void iwl3945_rx_handle(struct iwl3945_priv *priv)
3863 {
3864         struct iwl3945_rx_mem_buffer *rxb;
3865         struct iwl3945_rx_packet *pkt;
3866         struct iwl3945_rx_queue *rxq = &priv->rxq;
3867         u32 r, i;
3868         int reclaim;
3869         unsigned long flags;
3870         u8 fill_rx = 0;
3871         u32 count = 8;
3872
3873         /* uCode's read index (stored in shared DRAM) indicates the last Rx
3874          * buffer that the driver may process (last buffer filled by ucode). */
3875         r = iwl3945_hw_get_rx_read(priv);
3876         i = rxq->read;
3877
3878         if (iwl3945_rx_queue_space(rxq) > (RX_QUEUE_SIZE / 2))
3879                 fill_rx = 1;
3880         /* Rx interrupt, but nothing sent from uCode */
3881         if (i == r)
3882                 IWL_DEBUG(IWL_DL_RX | IWL_DL_ISR, "r = %d, i = %d\n", r, i);
3883
3884         while (i != r) {
3885                 rxb = rxq->queue[i];
3886
3887                 /* If an RXB doesn't have a Rx queue slot associated with it,
3888                  * then a bug has been introduced in the queue refilling
3889                  * routines -- catch it here */
3890                 BUG_ON(rxb == NULL);
3891
3892                 rxq->queue[i] = NULL;
3893
3894                 pci_dma_sync_single_for_cpu(priv->pci_dev, rxb->dma_addr,
3895                                             IWL_RX_BUF_SIZE,
3896                                             PCI_DMA_FROMDEVICE);
3897                 pkt = (struct iwl3945_rx_packet *)rxb->skb->data;
3898
3899                 /* Reclaim a command buffer only if this packet is a response
3900                  *   to a (driver-originated) command.
3901                  * If the packet (e.g. Rx frame) originated from uCode,
3902                  *   there is no command buffer to reclaim.
3903                  * Ucode should set SEQ_RX_FRAME bit if ucode-originated,
3904                  *   but apparently a few don't get set; catch them here. */
3905                 reclaim = !(pkt->hdr.sequence & SEQ_RX_FRAME) &&
3906                         (pkt->hdr.cmd != STATISTICS_NOTIFICATION) &&
3907                         (pkt->hdr.cmd != REPLY_TX);
3908
3909                 /* Based on type of command response or notification,
3910                  *   handle those that need handling via function in
3911                  *   rx_handlers table.  See iwl3945_setup_rx_handlers() */
3912                 if (priv->rx_handlers[pkt->hdr.cmd]) {
3913                         IWL_DEBUG(IWL_DL_HOST_COMMAND | IWL_DL_RX | IWL_DL_ISR,
3914                                 "r = %d, i = %d, %s, 0x%02x\n", r, i,
3915                                 get_cmd_string(pkt->hdr.cmd), pkt->hdr.cmd);
3916                         priv->rx_handlers[pkt->hdr.cmd] (priv, rxb);
3917                 } else {
3918                         /* No handling needed */
3919                         IWL_DEBUG(IWL_DL_HOST_COMMAND | IWL_DL_RX | IWL_DL_ISR,
3920                                 "r %d i %d No handler needed for %s, 0x%02x\n",
3921                                 r, i, get_cmd_string(pkt->hdr.cmd),
3922                                 pkt->hdr.cmd);
3923                 }
3924
3925                 if (reclaim) {
3926                         /* Invoke any callbacks, transfer the skb to caller, and
3927                          * fire off the (possibly) blocking iwl3945_send_cmd()
3928                          * as we reclaim the driver command queue */
3929                         if (rxb && rxb->skb)
3930                                 iwl3945_tx_cmd_complete(priv, rxb);
3931                         else
3932                                 IWL_WARNING("Claim null rxb?\n");
3933                 }
3934
3935                 /* For now we just don't re-use anything.  We can tweak this
3936                  * later to try and re-use notification packets and SKBs that
3937                  * fail to Rx correctly */
3938                 if (rxb->skb != NULL) {
3939                         priv->alloc_rxb_skb--;
3940                         dev_kfree_skb_any(rxb->skb);
3941                         rxb->skb = NULL;
3942                 }
3943
3944                 pci_unmap_single(priv->pci_dev, rxb->dma_addr,
3945                                  IWL_RX_BUF_SIZE, PCI_DMA_FROMDEVICE);
3946                 spin_lock_irqsave(&rxq->lock, flags);
3947                 list_add_tail(&rxb->list, &priv->rxq.rx_used);
3948                 spin_unlock_irqrestore(&rxq->lock, flags);
3949                 i = (i + 1) & RX_QUEUE_MASK;
3950                 /* If there are a lot of unused frames,
3951                  * restock the Rx queue so ucode won't assert. */
3952                 if (fill_rx) {
3953                         count++;
3954                         if (count >= 8) {
3955                                 priv->rxq.read = i;
3956                                 __iwl3945_rx_replenish(priv);
3957                                 count = 0;
3958                         }
3959                 }
3960         }
3961
3962         /* Backtrack one entry */
3963         priv->rxq.read = i;
3964         iwl3945_rx_queue_restock(priv);
3965 }
3966
3967 /**
3968  * iwl3945_tx_queue_update_write_ptr - Send new write index to hardware
3969  */
3970 static int iwl3945_tx_queue_update_write_ptr(struct iwl3945_priv *priv,
3971                                   struct iwl3945_tx_queue *txq)
3972 {
3973         u32 reg = 0;
3974         int rc = 0;
3975         int txq_id = txq->q.id;
3976
3977         if (txq->need_update == 0)
3978                 return rc;
3979
3980         /* if we're trying to save power */
3981         if (test_bit(STATUS_POWER_PMI, &priv->status)) {
3982                 /* wake up nic if it's powered down ...
3983                  * uCode will wake up, and interrupt us again, so next
3984                  * time we'll skip this part. */
3985                 reg = iwl3945_read32(priv, CSR_UCODE_DRV_GP1);
3986
3987                 if (reg & CSR_UCODE_DRV_GP1_BIT_MAC_SLEEP) {
3988                         IWL_DEBUG_INFO("Requesting wakeup, GP1 = 0x%x\n", reg);
3989                         iwl3945_set_bit(priv, CSR_GP_CNTRL,
3990                                     CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
3991                         return rc;
3992                 }
3993
3994                 /* restore this queue's parameters in nic hardware. */
3995                 rc = iwl3945_grab_nic_access(priv);
3996                 if (rc)
3997                         return rc;
3998                 iwl3945_write_direct32(priv, HBUS_TARG_WRPTR,
3999                                      txq->q.write_ptr | (txq_id << 8));
4000                 iwl3945_release_nic_access(priv);
4001
4002         /* else not in power-save mode, uCode will never sleep when we're
4003          * trying to tx (during RFKILL, we're not trying to tx). */
4004         } else
4005                 iwl3945_write32(priv, HBUS_TARG_WRPTR,
4006                             txq->q.write_ptr | (txq_id << 8));
4007
4008         txq->need_update = 0;
4009
4010         return rc;
4011 }
4012
4013 #ifdef CONFIG_IWL3945_DEBUG
4014 static void iwl3945_print_rx_config_cmd(struct iwl3945_rxon_cmd *rxon)
4015 {
4016         IWL_DEBUG_RADIO("RX CONFIG:\n");
4017         iwl3945_print_hex_dump(IWL_DL_RADIO, (u8 *) rxon, sizeof(*rxon));
4018         IWL_DEBUG_RADIO("u16 channel: 0x%x\n", le16_to_cpu(rxon->channel));
4019         IWL_DEBUG_RADIO("u32 flags: 0x%08X\n", le32_to_cpu(rxon->flags));
4020         IWL_DEBUG_RADIO("u32 filter_flags: 0x%08x\n",
4021                         le32_to_cpu(rxon->filter_flags));
4022         IWL_DEBUG_RADIO("u8 dev_type: 0x%x\n", rxon->dev_type);
4023         IWL_DEBUG_RADIO("u8 ofdm_basic_rates: 0x%02x\n",
4024                         rxon->ofdm_basic_rates);
4025         IWL_DEBUG_RADIO("u8 cck_basic_rates: 0x%02x\n", rxon->cck_basic_rates);
4026         IWL_DEBUG_RADIO("u8[6] node_addr: %pM\n", rxon->node_addr);
4027         IWL_DEBUG_RADIO("u8[6] bssid_addr: %pM\n", rxon->bssid_addr);
4028         IWL_DEBUG_RADIO("u16 assoc_id: 0x%x\n", le16_to_cpu(rxon->assoc_id));
4029 }
4030 #endif
4031
4032 static void iwl3945_enable_interrupts(struct iwl3945_priv *priv)
4033 {
4034         IWL_DEBUG_ISR("Enabling interrupts\n");
4035         set_bit(STATUS_INT_ENABLED, &priv->status);
4036         iwl3945_write32(priv, CSR_INT_MASK, CSR_INI_SET_MASK);
4037 }
4038
4039
4040 /* call this function to flush any scheduled tasklet */
4041 static inline void iwl_synchronize_irq(struct iwl3945_priv *priv)
4042 {
4043         /* wait to make sure we flush pedding tasklet*/
4044         synchronize_irq(priv->pci_dev->irq);
4045         tasklet_kill(&priv->irq_tasklet);
4046 }
4047
4048
4049 static inline void iwl3945_disable_interrupts(struct iwl3945_priv *priv)
4050 {
4051         clear_bit(STATUS_INT_ENABLED, &priv->status);
4052
4053         /* disable interrupts from uCode/NIC to host */
4054         iwl3945_write32(priv, CSR_INT_MASK, 0x00000000);
4055
4056         /* acknowledge/clear/reset any interrupts still pending
4057          * from uCode or flow handler (Rx/Tx DMA) */
4058         iwl3945_write32(priv, CSR_INT, 0xffffffff);
4059         iwl3945_write32(priv, CSR_FH_INT_STATUS, 0xffffffff);
4060         IWL_DEBUG_ISR("Disabled interrupts\n");
4061 }
4062
4063 static const char *desc_lookup(int i)
4064 {
4065         switch (i) {
4066         case 1:
4067                 return "FAIL";
4068         case 2:
4069                 return "BAD_PARAM";
4070         case 3:
4071                 return "BAD_CHECKSUM";
4072         case 4:
4073                 return "NMI_INTERRUPT";
4074         case 5:
4075                 return "SYSASSERT";
4076         case 6:
4077                 return "FATAL_ERROR";
4078         }
4079
4080         return "UNKNOWN";
4081 }
4082
4083 #define ERROR_START_OFFSET  (1 * sizeof(u32))
4084 #define ERROR_ELEM_SIZE     (7 * sizeof(u32))
4085
4086 static void iwl3945_dump_nic_error_log(struct iwl3945_priv *priv)
4087 {
4088         u32 i;
4089         u32 desc, time, count, base, data1;
4090         u32 blink1, blink2, ilink1, ilink2;
4091         int rc;
4092
4093         base = le32_to_cpu(priv->card_alive.error_event_table_ptr);
4094
4095         if (!iwl3945_hw_valid_rtc_data_addr(base)) {
4096                 IWL_ERROR("Not valid error log pointer 0x%08X\n", base);
4097                 return;
4098         }
4099
4100         rc = iwl3945_grab_nic_access(priv);
4101         if (rc) {
4102                 IWL_WARNING("Can not read from adapter at this time.\n");
4103                 return;
4104         }
4105
4106         count = iwl3945_read_targ_mem(priv, base);
4107
4108         if (ERROR_START_OFFSET <= count * ERROR_ELEM_SIZE) {
4109                 IWL_ERROR("Start IWL Error Log Dump:\n");
4110                 IWL_ERROR("Status: 0x%08lX, count: %d\n", priv->status, count);
4111         }
4112
4113         IWL_ERROR("Desc       Time       asrtPC  blink2 "
4114                   "ilink1  nmiPC   Line\n");
4115         for (i = ERROR_START_OFFSET;
4116              i < (count * ERROR_ELEM_SIZE) + ERROR_START_OFFSET;
4117              i += ERROR_ELEM_SIZE) {
4118                 desc = iwl3945_read_targ_mem(priv, base + i);
4119                 time =
4120                     iwl3945_read_targ_mem(priv, base + i + 1 * sizeof(u32));
4121                 blink1 =
4122                     iwl3945_read_targ_mem(priv, base + i + 2 * sizeof(u32));
4123                 blink2 =
4124                     iwl3945_read_targ_mem(priv, base + i + 3 * sizeof(u32));
4125                 ilink1 =
4126                     iwl3945_read_targ_mem(priv, base + i + 4 * sizeof(u32));
4127                 ilink2 =
4128                     iwl3945_read_targ_mem(priv, base + i + 5 * sizeof(u32));
4129                 data1 =
4130                     iwl3945_read_targ_mem(priv, base + i + 6 * sizeof(u32));
4131
4132                 IWL_ERROR
4133                     ("%-13s (#%d) %010u 0x%05X 0x%05X 0x%05X 0x%05X %u\n\n",
4134                      desc_lookup(desc), desc, time, blink1, blink2,
4135                      ilink1, ilink2, data1);
4136         }
4137
4138         iwl3945_release_nic_access(priv);
4139
4140 }
4141
4142 #define EVENT_START_OFFSET  (6 * sizeof(u32))
4143
4144 /**
4145  * iwl3945_print_event_log - Dump error event log to syslog
4146  *
4147  * NOTE: Must be called with iwl3945_grab_nic_access() already obtained!
4148  */
4149 static void iwl3945_print_event_log(struct iwl3945_priv *priv, u32 start_idx,
4150                                 u32 num_events, u32 mode)
4151 {
4152         u32 i;
4153         u32 base;       /* SRAM byte address of event log header */
4154         u32 event_size; /* 2 u32s, or 3 u32s if timestamp recorded */
4155         u32 ptr;        /* SRAM byte address of log data */
4156         u32 ev, time, data; /* event log data */
4157
4158         if (num_events == 0)
4159                 return;
4160
4161         base = le32_to_cpu(priv->card_alive.log_event_table_ptr);
4162
4163         if (mode == 0)
4164                 event_size = 2 * sizeof(u32);
4165         else
4166                 event_size = 3 * sizeof(u32);
4167
4168         ptr = base + EVENT_START_OFFSET + (start_idx * event_size);
4169
4170         /* "time" is actually "data" for mode 0 (no timestamp).
4171          * place event id # at far right for easier visual parsing. */
4172         for (i = 0; i < num_events; i++) {
4173                 ev = iwl3945_read_targ_mem(priv, ptr);
4174                 ptr += sizeof(u32);
4175                 time = iwl3945_read_targ_mem(priv, ptr);
4176                 ptr += sizeof(u32);
4177                 if (mode == 0)
4178                         IWL_ERROR("0x%08x\t%04u\n", time, ev); /* data, ev */
4179                 else {
4180                         data = iwl3945_read_targ_mem(priv, ptr);
4181                         ptr += sizeof(u32);
4182                         IWL_ERROR("%010u\t0x%08x\t%04u\n", time, data, ev);
4183                 }
4184         }
4185 }
4186
4187 static void iwl3945_dump_nic_event_log(struct iwl3945_priv *priv)
4188 {
4189         int rc;
4190         u32 base;       /* SRAM byte address of event log header */
4191         u32 capacity;   /* event log capacity in # entries */
4192         u32 mode;       /* 0 - no timestamp, 1 - timestamp recorded */
4193         u32 num_wraps;  /* # times uCode wrapped to top of log */
4194         u32 next_entry; /* index of next entry to be written by uCode */
4195         u32 size;       /* # entries that we'll print */
4196
4197         base = le32_to_cpu(priv->card_alive.log_event_table_ptr);
4198         if (!iwl3945_hw_valid_rtc_data_addr(base)) {
4199                 IWL_ERROR("Invalid event log pointer 0x%08X\n", base);
4200                 return;
4201         }
4202
4203         rc = iwl3945_grab_nic_access(priv);
4204         if (rc) {
4205                 IWL_WARNING("Can not read from adapter at this time.\n");
4206                 return;
4207         }
4208
4209         /* event log header */
4210         capacity = iwl3945_read_targ_mem(priv, base);
4211         mode = iwl3945_read_targ_mem(priv, base + (1 * sizeof(u32)));
4212         num_wraps = iwl3945_read_targ_mem(priv, base + (2 * sizeof(u32)));
4213         next_entry = iwl3945_read_targ_mem(priv, base + (3 * sizeof(u32)));
4214
4215         size = num_wraps ? capacity : next_entry;
4216
4217         /* bail out if nothing in log */
4218         if (size == 0) {
4219                 IWL_ERROR("Start IWL Event Log Dump: nothing in log\n");
4220                 iwl3945_release_nic_access(priv);
4221                 return;
4222         }
4223
4224         IWL_ERROR("Start IWL Event Log Dump: display count %d, wraps %d\n",
4225                   size, num_wraps);
4226
4227         /* if uCode has wrapped back to top of log, start at the oldest entry,
4228          * i.e the next one that uCode would fill. */
4229         if (num_wraps)
4230                 iwl3945_print_event_log(priv, next_entry,
4231                                     capacity - next_entry, mode);
4232
4233         /* (then/else) start at top of log */
4234         iwl3945_print_event_log(priv, 0, next_entry, mode);
4235
4236         iwl3945_release_nic_access(priv);
4237 }
4238
4239 /**
4240  * iwl3945_irq_handle_error - called for HW or SW error interrupt from card
4241  */
4242 static void iwl3945_irq_handle_error(struct iwl3945_priv *priv)
4243 {
4244         /* Set the FW error flag -- cleared on iwl3945_down */
4245         set_bit(STATUS_FW_ERROR, &priv->status);
4246
4247         /* Cancel currently queued command. */
4248         clear_bit(STATUS_HCMD_ACTIVE, &priv->status);
4249
4250 #ifdef CONFIG_IWL3945_DEBUG
4251         if (iwl3945_debug_level & IWL_DL_FW_ERRORS) {
4252                 iwl3945_dump_nic_error_log(priv);
4253                 iwl3945_dump_nic_event_log(priv);
4254                 iwl3945_print_rx_config_cmd(&priv->staging_rxon);
4255         }
4256 #endif
4257
4258         wake_up_interruptible(&priv->wait_command_queue);
4259
4260         /* Keep the restart process from trying to send host
4261          * commands by clearing the INIT status bit */
4262         clear_bit(STATUS_READY, &priv->status);
4263
4264         if (!test_bit(STATUS_EXIT_PENDING, &priv->status)) {
4265                 IWL_DEBUG(IWL_DL_INFO | IWL_DL_FW_ERRORS,
4266                           "Restarting adapter due to uCode error.\n");
4267
4268                 if (iwl3945_is_associated(priv)) {
4269                         memcpy(&priv->recovery_rxon, &priv->active_rxon,
4270                                sizeof(priv->recovery_rxon));
4271                         priv->error_recovering = 1;
4272                 }
4273                 queue_work(priv->workqueue, &priv->restart);
4274         }
4275 }
4276
4277 static void iwl3945_error_recovery(struct iwl3945_priv *priv)
4278 {
4279         unsigned long flags;
4280
4281         memcpy(&priv->staging_rxon, &priv->recovery_rxon,
4282                sizeof(priv->staging_rxon));
4283         priv->staging_rxon.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
4284         iwl3945_commit_rxon(priv);
4285
4286         iwl3945_add_station(priv, priv->bssid, 1, 0);
4287
4288         spin_lock_irqsave(&priv->lock, flags);
4289         priv->assoc_id = le16_to_cpu(priv->staging_rxon.assoc_id);
4290         priv->error_recovering = 0;
4291         spin_unlock_irqrestore(&priv->lock, flags);
4292 }
4293
4294 static void iwl3945_irq_tasklet(struct iwl3945_priv *priv)
4295 {
4296         u32 inta, handled = 0;
4297         u32 inta_fh;
4298         unsigned long flags;
4299 #ifdef CONFIG_IWL3945_DEBUG
4300         u32 inta_mask;
4301 #endif
4302
4303         spin_lock_irqsave(&priv->lock, flags);
4304
4305         /* Ack/clear/reset pending uCode interrupts.
4306          * Note:  Some bits in CSR_INT are "OR" of bits in CSR_FH_INT_STATUS,
4307          *  and will clear only when CSR_FH_INT_STATUS gets cleared. */
4308         inta = iwl3945_read32(priv, CSR_INT);
4309         iwl3945_write32(priv, CSR_INT, inta);
4310
4311         /* Ack/clear/reset pending flow-handler (DMA) interrupts.
4312          * Any new interrupts that happen after this, either while we're
4313          * in this tasklet, or later, will show up in next ISR/tasklet. */
4314         inta_fh = iwl3945_read32(priv, CSR_FH_INT_STATUS);
4315         iwl3945_write32(priv, CSR_FH_INT_STATUS, inta_fh);
4316
4317 #ifdef CONFIG_IWL3945_DEBUG
4318         if (iwl3945_debug_level & IWL_DL_ISR) {
4319                 /* just for debug */
4320                 inta_mask = iwl3945_read32(priv, CSR_INT_MASK);
4321                 IWL_DEBUG_ISR("inta 0x%08x, enabled 0x%08x, fh 0x%08x\n",
4322                               inta, inta_mask, inta_fh);
4323         }
4324 #endif
4325
4326         /* Since CSR_INT and CSR_FH_INT_STATUS reads and clears are not
4327          * atomic, make sure that inta covers all the interrupts that
4328          * we've discovered, even if FH interrupt came in just after
4329          * reading CSR_INT. */
4330         if (inta_fh & CSR39_FH_INT_RX_MASK)
4331                 inta |= CSR_INT_BIT_FH_RX;
4332         if (inta_fh & CSR39_FH_INT_TX_MASK)
4333                 inta |= CSR_INT_BIT_FH_TX;
4334
4335         /* Now service all interrupt bits discovered above. */
4336         if (inta & CSR_INT_BIT_HW_ERR) {
4337                 IWL_ERROR("Microcode HW error detected.  Restarting.\n");
4338
4339                 /* Tell the device to stop sending interrupts */
4340                 iwl3945_disable_interrupts(priv);
4341
4342                 iwl3945_irq_handle_error(priv);
4343
4344                 handled |= CSR_INT_BIT_HW_ERR;
4345
4346                 spin_unlock_irqrestore(&priv->lock, flags);
4347
4348                 return;
4349         }
4350
4351 #ifdef CONFIG_IWL3945_DEBUG
4352         if (iwl3945_debug_level & (IWL_DL_ISR)) {
4353                 /* NIC fires this, but we don't use it, redundant with WAKEUP */
4354                 if (inta & CSR_INT_BIT_SCD)
4355                         IWL_DEBUG_ISR("Scheduler finished to transmit "
4356                                       "the frame/frames.\n");
4357
4358                 /* Alive notification via Rx interrupt will do the real work */
4359                 if (inta & CSR_INT_BIT_ALIVE)
4360                         IWL_DEBUG_ISR("Alive interrupt\n");
4361         }
4362 #endif
4363         /* Safely ignore these bits for debug checks below */
4364         inta &= ~(CSR_INT_BIT_SCD | CSR_INT_BIT_ALIVE);
4365
4366         /* HW RF KILL switch toggled (4965 only) */
4367         if (inta & CSR_INT_BIT_RF_KILL) {
4368                 int hw_rf_kill = 0;
4369                 if (!(iwl3945_read32(priv, CSR_GP_CNTRL) &
4370                                 CSR_GP_CNTRL_REG_FLAG_HW_RF_KILL_SW))
4371                         hw_rf_kill = 1;
4372
4373                 IWL_DEBUG(IWL_DL_INFO | IWL_DL_RF_KILL | IWL_DL_ISR,
4374                                 "RF_KILL bit toggled to %s.\n",
4375                                 hw_rf_kill ? "disable radio":"enable radio");
4376
4377                 /* Queue restart only if RF_KILL switch was set to "kill"
4378                  *   when we loaded driver, and is now set to "enable".
4379                  * After we're Alive, RF_KILL gets handled by
4380                  *   iwl3945_rx_card_state_notif() */
4381                 if (!hw_rf_kill && !test_bit(STATUS_ALIVE, &priv->status)) {
4382                         clear_bit(STATUS_RF_KILL_HW, &priv->status);
4383                         queue_work(priv->workqueue, &priv->restart);
4384                 }
4385
4386                 handled |= CSR_INT_BIT_RF_KILL;
4387         }
4388
4389         /* Chip got too hot and stopped itself (4965 only) */
4390         if (inta & CSR_INT_BIT_CT_KILL) {
4391                 IWL_ERROR("Microcode CT kill error detected.\n");
4392                 handled |= CSR_INT_BIT_CT_KILL;
4393         }
4394
4395         /* Error detected by uCode */
4396         if (inta & CSR_INT_BIT_SW_ERR) {
4397                 IWL_ERROR("Microcode SW error detected.  Restarting 0x%X.\n",
4398                           inta);
4399                 iwl3945_irq_handle_error(priv);
4400                 handled |= CSR_INT_BIT_SW_ERR;
4401         }
4402
4403         /* uCode wakes up after power-down sleep */
4404         if (inta & CSR_INT_BIT_WAKEUP) {
4405                 IWL_DEBUG_ISR("Wakeup interrupt\n");
4406                 iwl3945_rx_queue_update_write_ptr(priv, &priv->rxq);
4407                 iwl3945_tx_queue_update_write_ptr(priv, &priv->txq[0]);
4408                 iwl3945_tx_queue_update_write_ptr(priv, &priv->txq[1]);
4409                 iwl3945_tx_queue_update_write_ptr(priv, &priv->txq[2]);
4410                 iwl3945_tx_queue_update_write_ptr(priv, &priv->txq[3]);
4411                 iwl3945_tx_queue_update_write_ptr(priv, &priv->txq[4]);
4412                 iwl3945_tx_queue_update_write_ptr(priv, &priv->txq[5]);
4413
4414                 handled |= CSR_INT_BIT_WAKEUP;
4415         }
4416
4417         /* All uCode command responses, including Tx command responses,
4418          * Rx "responses" (frame-received notification), and other
4419          * notifications from uCode come through here*/
4420         if (inta & (CSR_INT_BIT_FH_RX | CSR_INT_BIT_SW_RX)) {
4421                 iwl3945_rx_handle(priv);
4422                 handled |= (CSR_INT_BIT_FH_RX | CSR_INT_BIT_SW_RX);
4423         }
4424
4425         if (inta & CSR_INT_BIT_FH_TX) {
4426                 IWL_DEBUG_ISR("Tx interrupt\n");
4427
4428                 iwl3945_write32(priv, CSR_FH_INT_STATUS, (1 << 6));
4429                 if (!iwl3945_grab_nic_access(priv)) {
4430                         iwl3945_write_direct32(priv,
4431                                              FH_TCSR_CREDIT
4432                                              (ALM_FH_SRVC_CHNL), 0x0);
4433                         iwl3945_release_nic_access(priv);
4434                 }
4435                 handled |= CSR_INT_BIT_FH_TX;
4436         }
4437
4438         if (inta & ~handled)
4439                 IWL_ERROR("Unhandled INTA bits 0x%08x\n", inta & ~handled);
4440
4441         if (inta & ~CSR_INI_SET_MASK) {
4442                 IWL_WARNING("Disabled INTA bits 0x%08x were pending\n",
4443                          inta & ~CSR_INI_SET_MASK);
4444                 IWL_WARNING("   with FH_INT = 0x%08x\n", inta_fh);
4445         }
4446
4447         /* Re-enable all interrupts */
4448         /* only Re-enable if disabled by irq */
4449         if (test_bit(STATUS_INT_ENABLED, &priv->status))
4450                 iwl3945_enable_interrupts(priv);
4451
4452 #ifdef CONFIG_IWL3945_DEBUG
4453         if (iwl3945_debug_level & (IWL_DL_ISR)) {
4454                 inta = iwl3945_read32(priv, CSR_INT);
4455                 inta_mask = iwl3945_read32(priv, CSR_INT_MASK);
4456                 inta_fh = iwl3945_read32(priv, CSR_FH_INT_STATUS);
4457                 IWL_DEBUG_ISR("End inta 0x%08x, enabled 0x%08x, fh 0x%08x, "
4458                         "flags 0x%08lx\n", inta, inta_mask, inta_fh, flags);
4459         }
4460 #endif
4461         spin_unlock_irqrestore(&priv->lock, flags);
4462 }
4463
4464 static irqreturn_t iwl3945_isr(int irq, void *data)
4465 {
4466         struct iwl3945_priv *priv = data;
4467         u32 inta, inta_mask;
4468         u32 inta_fh;
4469         if (!priv)
4470                 return IRQ_NONE;
4471
4472         spin_lock(&priv->lock);
4473
4474         /* Disable (but don't clear!) interrupts here to avoid
4475          *    back-to-back ISRs and sporadic interrupts from our NIC.
4476          * If we have something to service, the tasklet will re-enable ints.
4477          * If we *don't* have something, we'll re-enable before leaving here. */
4478         inta_mask = iwl3945_read32(priv, CSR_INT_MASK);  /* just for debug */
4479         iwl3945_write32(priv, CSR_INT_MASK, 0x00000000);
4480
4481         /* Discover which interrupts are active/pending */
4482         inta = iwl3945_read32(priv, CSR_INT);
4483         inta_fh = iwl3945_read32(priv, CSR_FH_INT_STATUS);
4484
4485         /* Ignore interrupt if there's nothing in NIC to service.
4486          * This may be due to IRQ shared with another device,
4487          * or due to sporadic interrupts thrown from our NIC. */
4488         if (!inta && !inta_fh) {
4489                 IWL_DEBUG_ISR("Ignore interrupt, inta == 0, inta_fh == 0\n");
4490                 goto none;
4491         }
4492
4493         if ((inta == 0xFFFFFFFF) || ((inta & 0xFFFFFFF0) == 0xa5a5a5a0)) {
4494                 /* Hardware disappeared */
4495                 IWL_WARNING("HARDWARE GONE?? INTA == 0x%080x\n", inta);
4496                 goto unplugged;
4497         }
4498
4499         IWL_DEBUG_ISR("ISR inta 0x%08x, enabled 0x%08x, fh 0x%08x\n",
4500                       inta, inta_mask, inta_fh);
4501
4502         inta &= ~CSR_INT_BIT_SCD;
4503
4504         /* iwl3945_irq_tasklet() will service interrupts and re-enable them */
4505         if (likely(inta || inta_fh))
4506                 tasklet_schedule(&priv->irq_tasklet);
4507 unplugged:
4508         spin_unlock(&priv->lock);
4509
4510         return IRQ_HANDLED;
4511
4512  none:
4513         /* re-enable interrupts here since we don't have anything to service. */
4514         /* only Re-enable if disabled by irq */
4515         if (test_bit(STATUS_INT_ENABLED, &priv->status))
4516                 iwl3945_enable_interrupts(priv);
4517         spin_unlock(&priv->lock);
4518         return IRQ_NONE;
4519 }
4520
4521 /************************** EEPROM BANDS ****************************
4522  *
4523  * The iwl3945_eeprom_band definitions below provide the mapping from the
4524  * EEPROM contents to the specific channel number supported for each
4525  * band.
4526  *
4527  * For example, iwl3945_priv->eeprom.band_3_channels[4] from the band_3
4528  * definition below maps to physical channel 42 in the 5.2GHz spectrum.
4529  * The specific geography and calibration information for that channel
4530  * is contained in the eeprom map itself.
4531  *
4532  * During init, we copy the eeprom information and channel map
4533  * information into priv->channel_info_24/52 and priv->channel_map_24/52
4534  *
4535  * channel_map_24/52 provides the index in the channel_info array for a
4536  * given channel.  We have to have two separate maps as there is channel
4537  * overlap with the 2.4GHz and 5.2GHz spectrum as seen in band_1 and
4538  * band_2
4539  *
4540  * A value of 0xff stored in the channel_map indicates that the channel
4541  * is not supported by the hardware at all.
4542  *
4543  * A value of 0xfe in the channel_map indicates that the channel is not
4544  * valid for Tx with the current hardware.  This means that
4545  * while the system can tune and receive on a given channel, it may not
4546  * be able to associate or transmit any frames on that
4547  * channel.  There is no corresponding channel information for that
4548  * entry.
4549  *
4550  *********************************************************************/
4551
4552 /* 2.4 GHz */
4553 static const u8 iwl3945_eeprom_band_1[14] = {
4554         1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14
4555 };
4556
4557 /* 5.2 GHz bands */
4558 static const u8 iwl3945_eeprom_band_2[] = {     /* 4915-5080MHz */
4559         183, 184, 185, 187, 188, 189, 192, 196, 7, 8, 11, 12, 16
4560 };
4561
4562 static const u8 iwl3945_eeprom_band_3[] = {     /* 5170-5320MHz */
4563         34, 36, 38, 40, 42, 44, 46, 48, 52, 56, 60, 64
4564 };
4565
4566 static const u8 iwl3945_eeprom_band_4[] = {     /* 5500-5700MHz */
4567         100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140
4568 };
4569
4570 static const u8 iwl3945_eeprom_band_5[] = {     /* 5725-5825MHz */
4571         145, 149, 153, 157, 161, 165
4572 };
4573
4574 static void iwl3945_init_band_reference(const struct iwl3945_priv *priv, int band,
4575                                     int *eeprom_ch_count,
4576                                     const struct iwl3945_eeprom_channel
4577                                     **eeprom_ch_info,
4578                                     const u8 **eeprom_ch_index)
4579 {
4580         switch (band) {
4581         case 1:         /* 2.4GHz band */
4582                 *eeprom_ch_count = ARRAY_SIZE(iwl3945_eeprom_band_1);
4583                 *eeprom_ch_info = priv->eeprom.band_1_channels;
4584                 *eeprom_ch_index = iwl3945_eeprom_band_1;
4585                 break;
4586         case 2:         /* 4.9GHz band */
4587                 *eeprom_ch_count = ARRAY_SIZE(iwl3945_eeprom_band_2);
4588                 *eeprom_ch_info = priv->eeprom.band_2_channels;
4589                 *eeprom_ch_index = iwl3945_eeprom_band_2;
4590                 break;
4591         case 3:         /* 5.2GHz band */
4592                 *eeprom_ch_count = ARRAY_SIZE(iwl3945_eeprom_band_3);
4593                 *eeprom_ch_info = priv->eeprom.band_3_channels;
4594                 *eeprom_ch_index = iwl3945_eeprom_band_3;
4595                 break;
4596         case 4:         /* 5.5GHz band */
4597                 *eeprom_ch_count = ARRAY_SIZE(iwl3945_eeprom_band_4);
4598                 *eeprom_ch_info = priv->eeprom.band_4_channels;
4599                 *eeprom_ch_index = iwl3945_eeprom_band_4;
4600                 break;
4601         case 5:         /* 5.7GHz band */
4602                 *eeprom_ch_count = ARRAY_SIZE(iwl3945_eeprom_band_5);
4603                 *eeprom_ch_info = priv->eeprom.band_5_channels;
4604                 *eeprom_ch_index = iwl3945_eeprom_band_5;
4605                 break;
4606         default:
4607                 BUG();
4608                 return;
4609         }
4610 }
4611
4612 /**
4613  * iwl3945_get_channel_info - Find driver's private channel info
4614  *
4615  * Based on band and channel number.
4616  */
4617 const struct iwl3945_channel_info *iwl3945_get_channel_info(const struct iwl3945_priv *priv,
4618                                                     enum ieee80211_band band, u16 channel)
4619 {
4620         int i;
4621
4622         switch (band) {
4623         case IEEE80211_BAND_5GHZ:
4624                 for (i = 14; i < priv->channel_count; i++) {
4625                         if (priv->channel_info[i].channel == channel)
4626                                 return &priv->channel_info[i];
4627                 }
4628                 break;
4629
4630         case IEEE80211_BAND_2GHZ:
4631                 if (channel >= 1 && channel <= 14)
4632                         return &priv->channel_info[channel - 1];
4633                 break;
4634         case IEEE80211_NUM_BANDS:
4635                 WARN_ON(1);
4636         }
4637
4638         return NULL;
4639 }
4640
4641 #define CHECK_AND_PRINT(x) ((eeprom_ch_info[ch].flags & EEPROM_CHANNEL_##x) \
4642                             ? # x " " : "")
4643
4644 /**
4645  * iwl3945_init_channel_map - Set up driver's info for all possible channels
4646  */
4647 static int iwl3945_init_channel_map(struct iwl3945_priv *priv)
4648 {
4649         int eeprom_ch_count = 0;
4650         const u8 *eeprom_ch_index = NULL;
4651         const struct iwl3945_eeprom_channel *eeprom_ch_info = NULL;
4652         int band, ch;
4653         struct iwl3945_channel_info *ch_info;
4654
4655         if (priv->channel_count) {
4656                 IWL_DEBUG_INFO("Channel map already initialized.\n");
4657                 return 0;
4658         }
4659
4660         if (priv->eeprom.version < 0x2f) {
4661                 IWL_WARNING("Unsupported EEPROM version: 0x%04X\n",
4662                             priv->eeprom.version);
4663                 return -EINVAL;
4664         }
4665
4666         IWL_DEBUG_INFO("Initializing regulatory info from EEPROM\n");
4667
4668         priv->channel_count =
4669             ARRAY_SIZE(iwl3945_eeprom_band_1) +
4670             ARRAY_SIZE(iwl3945_eeprom_band_2) +
4671             ARRAY_SIZE(iwl3945_eeprom_band_3) +
4672             ARRAY_SIZE(iwl3945_eeprom_band_4) +
4673             ARRAY_SIZE(iwl3945_eeprom_band_5);
4674
4675         IWL_DEBUG_INFO("Parsing data for %d channels.\n", priv->channel_count);
4676
4677         priv->channel_info = kzalloc(sizeof(struct iwl3945_channel_info) *
4678                                      priv->channel_count, GFP_KERNEL);
4679         if (!priv->channel_info) {
4680                 IWL_ERROR("Could not allocate channel_info\n");
4681                 priv->channel_count = 0;
4682                 return -ENOMEM;
4683         }
4684
4685         ch_info = priv->channel_info;
4686
4687         /* Loop through the 5 EEPROM bands adding them in order to the
4688          * channel map we maintain (that contains additional information than
4689          * what just in the EEPROM) */
4690         for (band = 1; band <= 5; band++) {
4691
4692                 iwl3945_init_band_reference(priv, band, &eeprom_ch_count,
4693                                         &eeprom_ch_info, &eeprom_ch_index);
4694
4695                 /* Loop through each band adding each of the channels */
4696                 for (ch = 0; ch < eeprom_ch_count; ch++) {
4697                         ch_info->channel = eeprom_ch_index[ch];
4698                         ch_info->band = (band == 1) ? IEEE80211_BAND_2GHZ :
4699                             IEEE80211_BAND_5GHZ;
4700
4701                         /* permanently store EEPROM's channel regulatory flags
4702                          *   and max power in channel info database. */
4703                         ch_info->eeprom = eeprom_ch_info[ch];
4704
4705                         /* Copy the run-time flags so they are there even on
4706                          * invalid channels */
4707                         ch_info->flags = eeprom_ch_info[ch].flags;
4708
4709                         if (!(is_channel_valid(ch_info))) {
4710                                 IWL_DEBUG_INFO("Ch. %d Flags %x [%sGHz] - "
4711                                                "No traffic\n",
4712                                                ch_info->channel,
4713                                                ch_info->flags,
4714                                                is_channel_a_band(ch_info) ?
4715                                                "5.2" : "2.4");
4716                                 ch_info++;
4717                                 continue;
4718                         }
4719
4720                         /* Initialize regulatory-based run-time data */
4721                         ch_info->max_power_avg = ch_info->curr_txpow =
4722                             eeprom_ch_info[ch].max_power_avg;
4723                         ch_info->scan_power = eeprom_ch_info[ch].max_power_avg;
4724                         ch_info->min_power = 0;
4725
4726                         IWL_DEBUG_INFO("Ch. %d [%sGHz] %s%s%s%s%s%s(0x%02x"
4727                                        " %ddBm): Ad-Hoc %ssupported\n",
4728                                        ch_info->channel,
4729                                        is_channel_a_band(ch_info) ?
4730                                        "5.2" : "2.4",
4731                                        CHECK_AND_PRINT(VALID),
4732                                        CHECK_AND_PRINT(IBSS),
4733                                        CHECK_AND_PRINT(ACTIVE),
4734                                        CHECK_AND_PRINT(RADAR),
4735                                        CHECK_AND_PRINT(WIDE),
4736                                        CHECK_AND_PRINT(DFS),
4737                                        eeprom_ch_info[ch].flags,
4738                                        eeprom_ch_info[ch].max_power_avg,
4739                                        ((eeprom_ch_info[ch].
4740                                          flags & EEPROM_CHANNEL_IBSS)
4741                                         && !(eeprom_ch_info[ch].
4742                                              flags & EEPROM_CHANNEL_RADAR))
4743                                        ? "" : "not ");
4744
4745                         /* Set the user_txpower_limit to the highest power
4746                          * supported by any channel */
4747                         if (eeprom_ch_info[ch].max_power_avg >
4748                             priv->user_txpower_limit)
4749                                 priv->user_txpower_limit =
4750                                     eeprom_ch_info[ch].max_power_avg;
4751
4752                         ch_info++;
4753                 }
4754         }
4755
4756         /* Set up txpower settings in driver for all channels */
4757         if (iwl3945_txpower_set_from_eeprom(priv))
4758                 return -EIO;
4759
4760         return 0;
4761 }
4762
4763 /*
4764  * iwl3945_free_channel_map - undo allocations in iwl3945_init_channel_map
4765  */
4766 static void iwl3945_free_channel_map(struct iwl3945_priv *priv)
4767 {
4768         kfree(priv->channel_info);
4769         priv->channel_count = 0;
4770 }
4771
4772 /* For active scan, listen ACTIVE_DWELL_TIME (msec) on each channel after
4773  * sending probe req.  This should be set long enough to hear probe responses
4774  * from more than one AP.  */
4775 #define IWL_ACTIVE_DWELL_TIME_24    (30)        /* all times in msec */
4776 #define IWL_ACTIVE_DWELL_TIME_52    (20)
4777
4778 #define IWL_ACTIVE_DWELL_FACTOR_24GHZ (3)
4779 #define IWL_ACTIVE_DWELL_FACTOR_52GHZ (2)
4780
4781 /* For faster active scanning, scan will move to the next channel if fewer than
4782  * PLCP_QUIET_THRESH packets are heard on this channel within
4783  * ACTIVE_QUIET_TIME after sending probe request.  This shortens the dwell
4784  * time if it's a quiet channel (nothing responded to our probe, and there's
4785  * no other traffic).
4786  * Disable "quiet" feature by setting PLCP_QUIET_THRESH to 0. */
4787 #define IWL_PLCP_QUIET_THRESH       __constant_cpu_to_le16(1)   /* packets */
4788 #define IWL_ACTIVE_QUIET_TIME       __constant_cpu_to_le16(10)  /* msec */
4789
4790 /* For passive scan, listen PASSIVE_DWELL_TIME (msec) on each channel.
4791  * Must be set longer than active dwell time.
4792  * For the most reliable scan, set > AP beacon interval (typically 100msec). */
4793 #define IWL_PASSIVE_DWELL_TIME_24   (20)        /* all times in msec */
4794 #define IWL_PASSIVE_DWELL_TIME_52   (10)
4795 #define IWL_PASSIVE_DWELL_BASE      (100)
4796 #define IWL_CHANNEL_TUNE_TIME       5
4797
4798 #define IWL_SCAN_PROBE_MASK(n)   cpu_to_le32((BIT(n) | (BIT(n) - BIT(1))))
4799
4800 static inline u16 iwl3945_get_active_dwell_time(struct iwl3945_priv *priv,
4801                                                 enum ieee80211_band band,
4802                                                 u8 n_probes)
4803 {
4804         if (band == IEEE80211_BAND_5GHZ)
4805                 return IWL_ACTIVE_DWELL_TIME_52 +
4806                         IWL_ACTIVE_DWELL_FACTOR_52GHZ * (n_probes + 1);
4807         else
4808                 return IWL_ACTIVE_DWELL_TIME_24 +
4809                         IWL_ACTIVE_DWELL_FACTOR_24GHZ * (n_probes + 1);
4810 }
4811
4812 static u16 iwl3945_get_passive_dwell_time(struct iwl3945_priv *priv,
4813                                           enum ieee80211_band band)
4814 {
4815         u16 passive = (band == IEEE80211_BAND_2GHZ) ?
4816             IWL_PASSIVE_DWELL_BASE + IWL_PASSIVE_DWELL_TIME_24 :
4817             IWL_PASSIVE_DWELL_BASE + IWL_PASSIVE_DWELL_TIME_52;
4818
4819         if (iwl3945_is_associated(priv)) {
4820                 /* If we're associated, we clamp the maximum passive
4821                  * dwell time to be 98% of the beacon interval (minus
4822                  * 2 * channel tune time) */
4823                 passive = priv->beacon_int;
4824                 if ((passive > IWL_PASSIVE_DWELL_BASE) || !passive)
4825                         passive = IWL_PASSIVE_DWELL_BASE;
4826                 passive = (passive * 98) / 100 - IWL_CHANNEL_TUNE_TIME * 2;
4827         }
4828
4829         return passive;
4830 }
4831
4832 static int iwl3945_get_channels_for_scan(struct iwl3945_priv *priv,
4833                                          enum ieee80211_band band,
4834                                      u8 is_active, u8 n_probes,
4835                                      struct iwl3945_scan_channel *scan_ch)
4836 {
4837         const struct ieee80211_channel *channels = NULL;
4838         const struct ieee80211_supported_band *sband;
4839         const struct iwl3945_channel_info *ch_info;
4840         u16 passive_dwell = 0;
4841         u16 active_dwell = 0;
4842         int added, i;
4843
4844         sband = iwl3945_get_band(priv, band);
4845         if (!sband)
4846                 return 0;
4847
4848         channels = sband->channels;
4849
4850         active_dwell = iwl3945_get_active_dwell_time(priv, band, n_probes);
4851         passive_dwell = iwl3945_get_passive_dwell_time(priv, band);
4852
4853         if (passive_dwell <= active_dwell)
4854                 passive_dwell = active_dwell + 1;
4855
4856         for (i = 0, added = 0; i < sband->n_channels; i++) {
4857                 if (channels[i].flags & IEEE80211_CHAN_DISABLED)
4858                         continue;
4859
4860                 scan_ch->channel = channels[i].hw_value;
4861
4862                 ch_info = iwl3945_get_channel_info(priv, band, scan_ch->channel);
4863                 if (!is_channel_valid(ch_info)) {
4864                         IWL_DEBUG_SCAN("Channel %d is INVALID for this band.\n",
4865                                        scan_ch->channel);
4866                         continue;
4867                 }
4868
4869                 if (!is_active || is_channel_passive(ch_info) ||
4870                     (channels[i].flags & IEEE80211_CHAN_PASSIVE_SCAN))
4871                         scan_ch->type = 0;      /* passive */
4872                 else
4873                         scan_ch->type = 1;      /* active */
4874
4875                 if ((scan_ch->type & 1) && n_probes)
4876                         scan_ch->type |= IWL_SCAN_PROBE_MASK(n_probes);
4877
4878                 scan_ch->active_dwell = cpu_to_le16(active_dwell);
4879                 scan_ch->passive_dwell = cpu_to_le16(passive_dwell);
4880
4881                 /* Set txpower levels to defaults */
4882                 scan_ch->tpc.dsp_atten = 110;
4883                 /* scan_pwr_info->tpc.dsp_atten; */
4884
4885                 /*scan_pwr_info->tpc.tx_gain; */
4886                 if (band == IEEE80211_BAND_5GHZ)
4887                         scan_ch->tpc.tx_gain = ((1 << 5) | (3 << 3)) | 3;
4888                 else {
4889                         scan_ch->tpc.tx_gain = ((1 << 5) | (5 << 3));
4890                         /* NOTE: if we were doing 6Mb OFDM for scans we'd use
4891                          * power level:
4892                          * scan_ch->tpc.tx_gain = ((1 << 5) | (2 << 3)) | 3;
4893                          */
4894                 }
4895
4896                 IWL_DEBUG_SCAN("Scanning %d [%s %d]\n",
4897                                scan_ch->channel,
4898                                (scan_ch->type & 1) ? "ACTIVE" : "PASSIVE",
4899                                (scan_ch->type & 1) ?
4900                                active_dwell : passive_dwell);
4901
4902                 scan_ch++;
4903                 added++;
4904         }
4905
4906         IWL_DEBUG_SCAN("total channels to scan %d \n", added);
4907         return added;
4908 }
4909
4910 static void iwl3945_init_hw_rates(struct iwl3945_priv *priv,
4911                               struct ieee80211_rate *rates)
4912 {
4913         int i;
4914
4915         for (i = 0; i < IWL_RATE_COUNT; i++) {
4916                 rates[i].bitrate = iwl3945_rates[i].ieee * 5;
4917                 rates[i].hw_value = i; /* Rate scaling will work on indexes */
4918                 rates[i].hw_value_short = i;
4919                 rates[i].flags = 0;
4920                 if ((i > IWL_LAST_OFDM_RATE) || (i < IWL_FIRST_OFDM_RATE)) {
4921                         /*
4922                          * If CCK != 1M then set short preamble rate flag.
4923                          */
4924                         rates[i].flags |= (iwl3945_rates[i].plcp == 10) ?
4925                                 0 : IEEE80211_RATE_SHORT_PREAMBLE;
4926                 }
4927         }
4928 }
4929
4930 /**
4931  * iwl3945_init_geos - Initialize mac80211's geo/channel info based from eeprom
4932  */
4933 static int iwl3945_init_geos(struct iwl3945_priv *priv)
4934 {
4935         struct iwl3945_channel_info *ch;
4936         struct ieee80211_supported_band *sband;
4937         struct ieee80211_channel *channels;
4938         struct ieee80211_channel *geo_ch;
4939         struct ieee80211_rate *rates;
4940         int i = 0;
4941
4942         if (priv->bands[IEEE80211_BAND_2GHZ].n_bitrates ||
4943             priv->bands[IEEE80211_BAND_5GHZ].n_bitrates) {
4944                 IWL_DEBUG_INFO("Geography modes already initialized.\n");
4945                 set_bit(STATUS_GEO_CONFIGURED, &priv->status);
4946                 return 0;
4947         }
4948
4949         channels = kzalloc(sizeof(struct ieee80211_channel) *
4950                            priv->channel_count, GFP_KERNEL);
4951         if (!channels)
4952                 return -ENOMEM;
4953
4954         rates = kzalloc((sizeof(struct ieee80211_rate) * (IWL_RATE_COUNT + 1)),
4955                         GFP_KERNEL);
4956         if (!rates) {
4957                 kfree(channels);
4958                 return -ENOMEM;
4959         }
4960
4961         /* 5.2GHz channels start after the 2.4GHz channels */
4962         sband = &priv->bands[IEEE80211_BAND_5GHZ];
4963         sband->channels = &channels[ARRAY_SIZE(iwl3945_eeprom_band_1)];
4964         /* just OFDM */
4965         sband->bitrates = &rates[IWL_FIRST_OFDM_RATE];
4966         sband->n_bitrates = IWL_RATE_COUNT - IWL_FIRST_OFDM_RATE;
4967
4968         sband = &priv->bands[IEEE80211_BAND_2GHZ];
4969         sband->channels = channels;
4970         /* OFDM & CCK */
4971         sband->bitrates = rates;
4972         sband->n_bitrates = IWL_RATE_COUNT;
4973
4974         priv->ieee_channels = channels;
4975         priv->ieee_rates = rates;
4976
4977         iwl3945_init_hw_rates(priv, rates);
4978
4979         for (i = 0;  i < priv->channel_count; i++) {
4980                 ch = &priv->channel_info[i];
4981
4982                 /* FIXME: might be removed if scan is OK*/
4983                 if (!is_channel_valid(ch))
4984                         continue;
4985
4986                 if (is_channel_a_band(ch))
4987                         sband =  &priv->bands[IEEE80211_BAND_5GHZ];
4988                 else
4989                         sband =  &priv->bands[IEEE80211_BAND_2GHZ];
4990
4991                 geo_ch = &sband->channels[sband->n_channels++];
4992
4993                 geo_ch->center_freq = ieee80211_channel_to_frequency(ch->channel);
4994                 geo_ch->max_power = ch->max_power_avg;
4995                 geo_ch->max_antenna_gain = 0xff;
4996                 geo_ch->hw_value = ch->channel;
4997
4998                 if (is_channel_valid(ch)) {
4999                         if (!(ch->flags & EEPROM_CHANNEL_IBSS))
5000                                 geo_ch->flags |= IEEE80211_CHAN_NO_IBSS;
5001
5002                         if (!(ch->flags & EEPROM_CHANNEL_ACTIVE))
5003                                 geo_ch->flags |= IEEE80211_CHAN_PASSIVE_SCAN;
5004
5005                         if (ch->flags & EEPROM_CHANNEL_RADAR)
5006                                 geo_ch->flags |= IEEE80211_CHAN_RADAR;
5007
5008                         if (ch->max_power_avg > priv->max_channel_txpower_limit)
5009                                 priv->max_channel_txpower_limit =
5010                                     ch->max_power_avg;
5011                 } else {
5012                         geo_ch->flags |= IEEE80211_CHAN_DISABLED;
5013                 }
5014
5015                 /* Save flags for reg domain usage */
5016                 geo_ch->orig_flags = geo_ch->flags;
5017
5018                 IWL_DEBUG_INFO("Channel %d Freq=%d[%sGHz] %s flag=0%X\n",
5019                                 ch->channel, geo_ch->center_freq,
5020                                 is_channel_a_band(ch) ?  "5.2" : "2.4",
5021                                 geo_ch->flags & IEEE80211_CHAN_DISABLED ?
5022                                 "restricted" : "valid",
5023                                  geo_ch->flags);
5024         }
5025
5026         if ((priv->bands[IEEE80211_BAND_5GHZ].n_channels == 0) &&
5027              priv->cfg->sku & IWL_SKU_A) {
5028                 printk(KERN_INFO DRV_NAME
5029                        ": Incorrectly detected BG card as ABG.  Please send "
5030                        "your PCI ID 0x%04X:0x%04X to maintainer.\n",
5031                        priv->pci_dev->device, priv->pci_dev->subsystem_device);
5032                  priv->cfg->sku &= ~IWL_SKU_A;
5033         }
5034
5035         printk(KERN_INFO DRV_NAME
5036                ": Tunable channels: %d 802.11bg, %d 802.11a channels\n",
5037                priv->bands[IEEE80211_BAND_2GHZ].n_channels,
5038                priv->bands[IEEE80211_BAND_5GHZ].n_channels);
5039
5040         if (priv->bands[IEEE80211_BAND_2GHZ].n_channels)
5041                 priv->hw->wiphy->bands[IEEE80211_BAND_2GHZ] =
5042                         &priv->bands[IEEE80211_BAND_2GHZ];
5043         if (priv->bands[IEEE80211_BAND_5GHZ].n_channels)
5044                 priv->hw->wiphy->bands[IEEE80211_BAND_5GHZ] =
5045                         &priv->bands[IEEE80211_BAND_5GHZ];
5046
5047         set_bit(STATUS_GEO_CONFIGURED, &priv->status);
5048
5049         return 0;
5050 }
5051
5052 /*
5053  * iwl3945_free_geos - undo allocations in iwl3945_init_geos
5054  */
5055 static void iwl3945_free_geos(struct iwl3945_priv *priv)
5056 {
5057         kfree(priv->ieee_channels);
5058         kfree(priv->ieee_rates);
5059         clear_bit(STATUS_GEO_CONFIGURED, &priv->status);
5060 }
5061
5062 /******************************************************************************
5063  *
5064  * uCode download functions
5065  *
5066  ******************************************************************************/
5067
5068 static void iwl3945_dealloc_ucode_pci(struct iwl3945_priv *priv)
5069 {
5070         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_code);
5071         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_data);
5072         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_data_backup);
5073         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_init);
5074         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_init_data);
5075         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_boot);
5076 }
5077
5078 /**
5079  * iwl3945_verify_inst_full - verify runtime uCode image in card vs. host,
5080  *     looking at all data.
5081  */
5082 static int iwl3945_verify_inst_full(struct iwl3945_priv *priv, __le32 *image, u32 len)
5083 {
5084         u32 val;
5085         u32 save_len = len;
5086         int rc = 0;
5087         u32 errcnt;
5088
5089         IWL_DEBUG_INFO("ucode inst image size is %u\n", len);
5090
5091         rc = iwl3945_grab_nic_access(priv);
5092         if (rc)
5093                 return rc;
5094
5095         iwl3945_write_direct32(priv, HBUS_TARG_MEM_RADDR, RTC_INST_LOWER_BOUND);
5096
5097         errcnt = 0;
5098         for (; len > 0; len -= sizeof(u32), image++) {
5099                 /* read data comes through single port, auto-incr addr */
5100                 /* NOTE: Use the debugless read so we don't flood kernel log
5101                  * if IWL_DL_IO is set */
5102                 val = _iwl3945_read_direct32(priv, HBUS_TARG_MEM_RDAT);
5103                 if (val != le32_to_cpu(*image)) {
5104                         IWL_ERROR("uCode INST section is invalid at "
5105                                   "offset 0x%x, is 0x%x, s/b 0x%x\n",
5106                                   save_len - len, val, le32_to_cpu(*image));
5107                         rc = -EIO;
5108                         errcnt++;
5109                         if (errcnt >= 20)
5110                                 break;
5111                 }
5112         }
5113
5114         iwl3945_release_nic_access(priv);
5115
5116         if (!errcnt)
5117                 IWL_DEBUG_INFO("ucode image in INSTRUCTION memory is good\n");
5118
5119         return rc;
5120 }
5121
5122
5123 /**
5124  * iwl3945_verify_inst_sparse - verify runtime uCode image in card vs. host,
5125  *   using sample data 100 bytes apart.  If these sample points are good,
5126  *   it's a pretty good bet that everything between them is good, too.
5127  */
5128 static int iwl3945_verify_inst_sparse(struct iwl3945_priv *priv, __le32 *image, u32 len)
5129 {
5130         u32 val;
5131         int rc = 0;
5132         u32 errcnt = 0;
5133         u32 i;
5134
5135         IWL_DEBUG_INFO("ucode inst image size is %u\n", len);
5136
5137         rc = iwl3945_grab_nic_access(priv);
5138         if (rc)
5139                 return rc;
5140
5141         for (i = 0; i < len; i += 100, image += 100/sizeof(u32)) {
5142                 /* read data comes through single port, auto-incr addr */
5143                 /* NOTE: Use the debugless read so we don't flood kernel log
5144                  * if IWL_DL_IO is set */
5145                 iwl3945_write_direct32(priv, HBUS_TARG_MEM_RADDR,
5146                         i + RTC_INST_LOWER_BOUND);
5147                 val = _iwl3945_read_direct32(priv, HBUS_TARG_MEM_RDAT);
5148                 if (val != le32_to_cpu(*image)) {
5149 #if 0 /* Enable this if you want to see details */
5150                         IWL_ERROR("uCode INST section is invalid at "
5151                                   "offset 0x%x, is 0x%x, s/b 0x%x\n",
5152                                   i, val, *image);
5153 #endif
5154                         rc = -EIO;
5155                         errcnt++;
5156                         if (errcnt >= 3)
5157                                 break;
5158                 }
5159         }
5160
5161         iwl3945_release_nic_access(priv);
5162
5163         return rc;
5164 }
5165
5166
5167 /**
5168  * iwl3945_verify_ucode - determine which instruction image is in SRAM,
5169  *    and verify its contents
5170  */
5171 static int iwl3945_verify_ucode(struct iwl3945_priv *priv)
5172 {
5173         __le32 *image;
5174         u32 len;
5175         int rc = 0;
5176
5177         /* Try bootstrap */
5178         image = (__le32 *)priv->ucode_boot.v_addr;
5179         len = priv->ucode_boot.len;
5180         rc = iwl3945_verify_inst_sparse(priv, image, len);
5181         if (rc == 0) {
5182                 IWL_DEBUG_INFO("Bootstrap uCode is good in inst SRAM\n");
5183                 return 0;
5184         }
5185
5186         /* Try initialize */
5187         image = (__le32 *)priv->ucode_init.v_addr;
5188         len = priv->ucode_init.len;
5189         rc = iwl3945_verify_inst_sparse(priv, image, len);
5190         if (rc == 0) {
5191                 IWL_DEBUG_INFO("Initialize uCode is good in inst SRAM\n");
5192                 return 0;
5193         }
5194
5195         /* Try runtime/protocol */
5196         image = (__le32 *)priv->ucode_code.v_addr;
5197         len = priv->ucode_code.len;
5198         rc = iwl3945_verify_inst_sparse(priv, image, len);
5199         if (rc == 0) {
5200                 IWL_DEBUG_INFO("Runtime uCode is good in inst SRAM\n");
5201                 return 0;
5202         }
5203
5204         IWL_ERROR("NO VALID UCODE IMAGE IN INSTRUCTION SRAM!!\n");
5205
5206         /* Since nothing seems to match, show first several data entries in
5207          * instruction SRAM, so maybe visual inspection will give a clue.
5208          * Selection of bootstrap image (vs. other images) is arbitrary. */
5209         image = (__le32 *)priv->ucode_boot.v_addr;
5210         len = priv->ucode_boot.len;
5211         rc = iwl3945_verify_inst_full(priv, image, len);
5212
5213         return rc;
5214 }
5215
5216
5217 /* check contents of special bootstrap uCode SRAM */
5218 static int iwl3945_verify_bsm(struct iwl3945_priv *priv)
5219 {
5220         __le32 *image = priv->ucode_boot.v_addr;
5221         u32 len = priv->ucode_boot.len;
5222         u32 reg;
5223         u32 val;
5224
5225         IWL_DEBUG_INFO("Begin verify bsm\n");
5226
5227         /* verify BSM SRAM contents */
5228         val = iwl3945_read_prph(priv, BSM_WR_DWCOUNT_REG);
5229         for (reg = BSM_SRAM_LOWER_BOUND;
5230              reg < BSM_SRAM_LOWER_BOUND + len;
5231              reg += sizeof(u32), image++) {
5232                 val = iwl3945_read_prph(priv, reg);
5233                 if (val != le32_to_cpu(*image)) {
5234                         IWL_ERROR("BSM uCode verification failed at "
5235                                   "addr 0x%08X+%u (of %u), is 0x%x, s/b 0x%x\n",
5236                                   BSM_SRAM_LOWER_BOUND,
5237                                   reg - BSM_SRAM_LOWER_BOUND, len,
5238                                   val, le32_to_cpu(*image));
5239                         return -EIO;
5240                 }
5241         }
5242
5243         IWL_DEBUG_INFO("BSM bootstrap uCode image OK\n");
5244
5245         return 0;
5246 }
5247
5248 /**
5249  * iwl3945_load_bsm - Load bootstrap instructions
5250  *
5251  * BSM operation:
5252  *
5253  * The Bootstrap State Machine (BSM) stores a short bootstrap uCode program
5254  * in special SRAM that does not power down during RFKILL.  When powering back
5255  * up after power-saving sleeps (or during initial uCode load), the BSM loads
5256  * the bootstrap program into the on-board processor, and starts it.
5257  *
5258  * The bootstrap program loads (via DMA) instructions and data for a new
5259  * program from host DRAM locations indicated by the host driver in the
5260  * BSM_DRAM_* registers.  Once the new program is loaded, it starts
5261  * automatically.
5262  *
5263  * When initializing the NIC, the host driver points the BSM to the
5264  * "initialize" uCode image.  This uCode sets up some internal data, then
5265  * notifies host via "initialize alive" that it is complete.
5266  *
5267  * The host then replaces the BSM_DRAM_* pointer values to point to the
5268  * normal runtime uCode instructions and a backup uCode data cache buffer
5269  * (filled initially with starting data values for the on-board processor),
5270  * then triggers the "initialize" uCode to load and launch the runtime uCode,
5271  * which begins normal operation.
5272  *
5273  * When doing a power-save shutdown, runtime uCode saves data SRAM into
5274  * the backup data cache in DRAM before SRAM is powered down.
5275  *
5276  * When powering back up, the BSM loads the bootstrap program.  This reloads
5277  * the runtime uCode instructions and the backup data cache into SRAM,
5278  * and re-launches the runtime uCode from where it left off.
5279  */
5280 static int iwl3945_load_bsm(struct iwl3945_priv *priv)
5281 {
5282         __le32 *image = priv->ucode_boot.v_addr;
5283         u32 len = priv->ucode_boot.len;
5284         dma_addr_t pinst;
5285         dma_addr_t pdata;
5286         u32 inst_len;
5287         u32 data_len;
5288         int rc;
5289         int i;
5290         u32 done;
5291         u32 reg_offset;
5292
5293         IWL_DEBUG_INFO("Begin load bsm\n");
5294
5295         /* make sure bootstrap program is no larger than BSM's SRAM size */
5296         if (len > IWL_MAX_BSM_SIZE)
5297                 return -EINVAL;
5298
5299         /* Tell bootstrap uCode where to find the "Initialize" uCode
5300          *   in host DRAM ... host DRAM physical address bits 31:0 for 3945.
5301          * NOTE:  iwl3945_initialize_alive_start() will replace these values,
5302          *        after the "initialize" uCode has run, to point to
5303          *        runtime/protocol instructions and backup data cache. */
5304         pinst = priv->ucode_init.p_addr;
5305         pdata = priv->ucode_init_data.p_addr;
5306         inst_len = priv->ucode_init.len;
5307         data_len = priv->ucode_init_data.len;
5308
5309         rc = iwl3945_grab_nic_access(priv);
5310         if (rc)
5311                 return rc;
5312
5313         iwl3945_write_prph(priv, BSM_DRAM_INST_PTR_REG, pinst);
5314         iwl3945_write_prph(priv, BSM_DRAM_DATA_PTR_REG, pdata);
5315         iwl3945_write_prph(priv, BSM_DRAM_INST_BYTECOUNT_REG, inst_len);
5316         iwl3945_write_prph(priv, BSM_DRAM_DATA_BYTECOUNT_REG, data_len);
5317
5318         /* Fill BSM memory with bootstrap instructions */
5319         for (reg_offset = BSM_SRAM_LOWER_BOUND;
5320              reg_offset < BSM_SRAM_LOWER_BOUND + len;
5321              reg_offset += sizeof(u32), image++)
5322                 _iwl3945_write_prph(priv, reg_offset,
5323                                           le32_to_cpu(*image));
5324
5325         rc = iwl3945_verify_bsm(priv);
5326         if (rc) {
5327                 iwl3945_release_nic_access(priv);
5328                 return rc;
5329         }
5330
5331         /* Tell BSM to copy from BSM SRAM into instruction SRAM, when asked */
5332         iwl3945_write_prph(priv, BSM_WR_MEM_SRC_REG, 0x0);
5333         iwl3945_write_prph(priv, BSM_WR_MEM_DST_REG,
5334                                  RTC_INST_LOWER_BOUND);
5335         iwl3945_write_prph(priv, BSM_WR_DWCOUNT_REG, len / sizeof(u32));
5336
5337         /* Load bootstrap code into instruction SRAM now,
5338          *   to prepare to load "initialize" uCode */
5339         iwl3945_write_prph(priv, BSM_WR_CTRL_REG,
5340                 BSM_WR_CTRL_REG_BIT_START);
5341
5342         /* Wait for load of bootstrap uCode to finish */
5343         for (i = 0; i < 100; i++) {
5344                 done = iwl3945_read_prph(priv, BSM_WR_CTRL_REG);
5345                 if (!(done & BSM_WR_CTRL_REG_BIT_START))
5346                         break;
5347                 udelay(10);
5348         }
5349         if (i < 100)
5350                 IWL_DEBUG_INFO("BSM write complete, poll %d iterations\n", i);
5351         else {
5352                 IWL_ERROR("BSM write did not complete!\n");
5353                 return -EIO;
5354         }
5355
5356         /* Enable future boot loads whenever power management unit triggers it
5357          *   (e.g. when powering back up after power-save shutdown) */
5358         iwl3945_write_prph(priv, BSM_WR_CTRL_REG,
5359                 BSM_WR_CTRL_REG_BIT_START_EN);
5360
5361         iwl3945_release_nic_access(priv);
5362
5363         return 0;
5364 }
5365
5366 static void iwl3945_nic_start(struct iwl3945_priv *priv)
5367 {
5368         /* Remove all resets to allow NIC to operate */
5369         iwl3945_write32(priv, CSR_RESET, 0);
5370 }
5371
5372 /**
5373  * iwl3945_read_ucode - Read uCode images from disk file.
5374  *
5375  * Copy into buffers for card to fetch via bus-mastering
5376  */
5377 static int iwl3945_read_ucode(struct iwl3945_priv *priv)
5378 {
5379         struct iwl3945_ucode *ucode;
5380         int ret = 0;
5381         const struct firmware *ucode_raw;
5382         /* firmware file name contains uCode/driver compatibility version */
5383         const char *name = priv->cfg->fw_name;
5384         u8 *src;
5385         size_t len;
5386         u32 ver, inst_size, data_size, init_size, init_data_size, boot_size;
5387
5388         /* Ask kernel firmware_class module to get the boot firmware off disk.
5389          * request_firmware() is synchronous, file is in memory on return. */
5390         ret = request_firmware(&ucode_raw, name, &priv->pci_dev->dev);
5391         if (ret < 0) {
5392                 IWL_ERROR("%s firmware file req failed: Reason %d\n",
5393                                 name, ret);
5394                 goto error;
5395         }
5396
5397         IWL_DEBUG_INFO("Got firmware '%s' file (%zd bytes) from disk\n",
5398                        name, ucode_raw->size);
5399
5400         /* Make sure that we got at least our header! */
5401         if (ucode_raw->size < sizeof(*ucode)) {
5402                 IWL_ERROR("File size way too small!\n");
5403                 ret = -EINVAL;
5404                 goto err_release;
5405         }
5406
5407         /* Data from ucode file:  header followed by uCode images */
5408         ucode = (void *)ucode_raw->data;
5409
5410         ver = le32_to_cpu(ucode->ver);
5411         inst_size = le32_to_cpu(ucode->inst_size);
5412         data_size = le32_to_cpu(ucode->data_size);
5413         init_size = le32_to_cpu(ucode->init_size);
5414         init_data_size = le32_to_cpu(ucode->init_data_size);
5415         boot_size = le32_to_cpu(ucode->boot_size);
5416
5417         IWL_DEBUG_INFO("f/w package hdr ucode version = 0x%x\n", ver);
5418         IWL_DEBUG_INFO("f/w package hdr runtime inst size = %u\n", inst_size);
5419         IWL_DEBUG_INFO("f/w package hdr runtime data size = %u\n", data_size);
5420         IWL_DEBUG_INFO("f/w package hdr init inst size = %u\n", init_size);
5421         IWL_DEBUG_INFO("f/w package hdr init data size = %u\n", init_data_size);
5422         IWL_DEBUG_INFO("f/w package hdr boot inst size = %u\n", boot_size);
5423
5424         /* Verify size of file vs. image size info in file's header */
5425         if (ucode_raw->size < sizeof(*ucode) +
5426                 inst_size + data_size + init_size +
5427                 init_data_size + boot_size) {
5428
5429                 IWL_DEBUG_INFO("uCode file size %d too small\n",
5430                                (int)ucode_raw->size);
5431                 ret = -EINVAL;
5432                 goto err_release;
5433         }
5434
5435         /* Verify that uCode images will fit in card's SRAM */
5436         if (inst_size > IWL_MAX_INST_SIZE) {
5437                 IWL_DEBUG_INFO("uCode instr len %d too large to fit in\n",
5438                                inst_size);
5439                 ret = -EINVAL;
5440                 goto err_release;
5441         }
5442
5443         if (data_size > IWL_MAX_DATA_SIZE) {
5444                 IWL_DEBUG_INFO("uCode data len %d too large to fit in\n",
5445                                data_size);
5446                 ret = -EINVAL;
5447                 goto err_release;
5448         }
5449         if (init_size > IWL_MAX_INST_SIZE) {
5450                 IWL_DEBUG_INFO("uCode init instr len %d too large to fit in\n",
5451                                 init_size);
5452                 ret = -EINVAL;
5453                 goto err_release;
5454         }
5455         if (init_data_size > IWL_MAX_DATA_SIZE) {
5456                 IWL_DEBUG_INFO("uCode init data len %d too large to fit in\n",
5457                                 init_data_size);
5458                 ret = -EINVAL;
5459                 goto err_release;
5460         }
5461         if (boot_size > IWL_MAX_BSM_SIZE) {
5462                 IWL_DEBUG_INFO("uCode boot instr len %d too large to fit in\n",
5463                                 boot_size);
5464                 ret = -EINVAL;
5465                 goto err_release;
5466         }
5467
5468         /* Allocate ucode buffers for card's bus-master loading ... */
5469
5470         /* Runtime instructions and 2 copies of data:
5471          * 1) unmodified from disk
5472          * 2) backup cache for save/restore during power-downs */
5473         priv->ucode_code.len = inst_size;
5474         iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_code);
5475
5476         priv->ucode_data.len = data_size;
5477         iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_data);
5478
5479         priv->ucode_data_backup.len = data_size;
5480         iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_data_backup);
5481
5482         if (!priv->ucode_code.v_addr || !priv->ucode_data.v_addr ||
5483             !priv->ucode_data_backup.v_addr)
5484                 goto err_pci_alloc;
5485
5486         /* Initialization instructions and data */
5487         if (init_size && init_data_size) {
5488                 priv->ucode_init.len = init_size;
5489                 iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_init);
5490
5491                 priv->ucode_init_data.len = init_data_size;
5492                 iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_init_data);
5493
5494                 if (!priv->ucode_init.v_addr || !priv->ucode_init_data.v_addr)
5495                         goto err_pci_alloc;
5496         }
5497
5498         /* Bootstrap (instructions only, no data) */
5499         if (boot_size) {
5500                 priv->ucode_boot.len = boot_size;
5501                 iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_boot);
5502
5503                 if (!priv->ucode_boot.v_addr)
5504                         goto err_pci_alloc;
5505         }
5506
5507         /* Copy images into buffers for card's bus-master reads ... */
5508
5509         /* Runtime instructions (first block of data in file) */
5510         src = &ucode->data[0];
5511         len = priv->ucode_code.len;
5512         IWL_DEBUG_INFO("Copying (but not loading) uCode instr len %Zd\n", len);
5513         memcpy(priv->ucode_code.v_addr, src, len);
5514         IWL_DEBUG_INFO("uCode instr buf vaddr = 0x%p, paddr = 0x%08x\n",
5515                 priv->ucode_code.v_addr, (u32)priv->ucode_code.p_addr);
5516
5517         /* Runtime data (2nd block)
5518          * NOTE:  Copy into backup buffer will be done in iwl3945_up()  */
5519         src = &ucode->data[inst_size];
5520         len = priv->ucode_data.len;
5521         IWL_DEBUG_INFO("Copying (but not loading) uCode data len %Zd\n", len);
5522         memcpy(priv->ucode_data.v_addr, src, len);
5523         memcpy(priv->ucode_data_backup.v_addr, src, len);
5524
5525         /* Initialization instructions (3rd block) */
5526         if (init_size) {
5527                 src = &ucode->data[inst_size + data_size];
5528                 len = priv->ucode_init.len;
5529                 IWL_DEBUG_INFO("Copying (but not loading) init instr len %Zd\n",
5530                                len);
5531                 memcpy(priv->ucode_init.v_addr, src, len);
5532         }
5533
5534         /* Initialization data (4th block) */
5535         if (init_data_size) {
5536                 src = &ucode->data[inst_size + data_size + init_size];
5537                 len = priv->ucode_init_data.len;
5538                 IWL_DEBUG_INFO("Copying (but not loading) init data len %d\n",
5539                                (int)len);
5540                 memcpy(priv->ucode_init_data.v_addr, src, len);
5541         }
5542
5543         /* Bootstrap instructions (5th block) */
5544         src = &ucode->data[inst_size + data_size + init_size + init_data_size];
5545         len = priv->ucode_boot.len;
5546         IWL_DEBUG_INFO("Copying (but not loading) boot instr len %d\n",
5547                        (int)len);
5548         memcpy(priv->ucode_boot.v_addr, src, len);
5549
5550         /* We have our copies now, allow OS release its copies */
5551         release_firmware(ucode_raw);
5552         return 0;
5553
5554  err_pci_alloc:
5555         IWL_ERROR("failed to allocate pci memory\n");
5556         ret = -ENOMEM;
5557         iwl3945_dealloc_ucode_pci(priv);
5558
5559  err_release:
5560         release_firmware(ucode_raw);
5561
5562  error:
5563         return ret;
5564 }
5565
5566
5567 /**
5568  * iwl3945_set_ucode_ptrs - Set uCode address location
5569  *
5570  * Tell initialization uCode where to find runtime uCode.
5571  *
5572  * BSM registers initially contain pointers to initialization uCode.
5573  * We need to replace them to load runtime uCode inst and data,
5574  * and to save runtime data when powering down.
5575  */
5576 static int iwl3945_set_ucode_ptrs(struct iwl3945_priv *priv)
5577 {
5578         dma_addr_t pinst;
5579         dma_addr_t pdata;
5580         int rc = 0;
5581         unsigned long flags;
5582
5583         /* bits 31:0 for 3945 */
5584         pinst = priv->ucode_code.p_addr;
5585         pdata = priv->ucode_data_backup.p_addr;
5586
5587         spin_lock_irqsave(&priv->lock, flags);
5588         rc = iwl3945_grab_nic_access(priv);
5589         if (rc) {
5590                 spin_unlock_irqrestore(&priv->lock, flags);
5591                 return rc;
5592         }
5593
5594         /* Tell bootstrap uCode where to find image to load */
5595         iwl3945_write_prph(priv, BSM_DRAM_INST_PTR_REG, pinst);
5596         iwl3945_write_prph(priv, BSM_DRAM_DATA_PTR_REG, pdata);
5597         iwl3945_write_prph(priv, BSM_DRAM_DATA_BYTECOUNT_REG,
5598                                  priv->ucode_data.len);
5599
5600         /* Inst bytecount must be last to set up, bit 31 signals uCode
5601          *   that all new ptr/size info is in place */
5602         iwl3945_write_prph(priv, BSM_DRAM_INST_BYTECOUNT_REG,
5603                                  priv->ucode_code.len | BSM_DRAM_INST_LOAD);
5604
5605         iwl3945_release_nic_access(priv);
5606
5607         spin_unlock_irqrestore(&priv->lock, flags);
5608
5609         IWL_DEBUG_INFO("Runtime uCode pointers are set.\n");
5610
5611         return rc;
5612 }
5613
5614 /**
5615  * iwl3945_init_alive_start - Called after REPLY_ALIVE notification received
5616  *
5617  * Called after REPLY_ALIVE notification received from "initialize" uCode.
5618  *
5619  * Tell "initialize" uCode to go ahead and load the runtime uCode.
5620  */
5621 static void iwl3945_init_alive_start(struct iwl3945_priv *priv)
5622 {
5623         /* Check alive response for "valid" sign from uCode */
5624         if (priv->card_alive_init.is_valid != UCODE_VALID_OK) {
5625                 /* We had an error bringing up the hardware, so take it
5626                  * all the way back down so we can try again */
5627                 IWL_DEBUG_INFO("Initialize Alive failed.\n");
5628                 goto restart;
5629         }
5630
5631         /* Bootstrap uCode has loaded initialize uCode ... verify inst image.
5632          * This is a paranoid check, because we would not have gotten the
5633          * "initialize" alive if code weren't properly loaded.  */
5634         if (iwl3945_verify_ucode(priv)) {
5635                 /* Runtime instruction load was bad;
5636                  * take it all the way back down so we can try again */
5637                 IWL_DEBUG_INFO("Bad \"initialize\" uCode load.\n");
5638                 goto restart;
5639         }
5640
5641         /* Send pointers to protocol/runtime uCode image ... init code will
5642          * load and launch runtime uCode, which will send us another "Alive"
5643          * notification. */
5644         IWL_DEBUG_INFO("Initialization Alive received.\n");
5645         if (iwl3945_set_ucode_ptrs(priv)) {
5646                 /* Runtime instruction load won't happen;
5647                  * take it all the way back down so we can try again */
5648                 IWL_DEBUG_INFO("Couldn't set up uCode pointers.\n");
5649                 goto restart;
5650         }
5651         return;
5652
5653  restart:
5654         queue_work(priv->workqueue, &priv->restart);
5655 }
5656
5657
5658 /**
5659  * iwl3945_alive_start - called after REPLY_ALIVE notification received
5660  *                   from protocol/runtime uCode (initialization uCode's
5661  *                   Alive gets handled by iwl3945_init_alive_start()).
5662  */
5663 static void iwl3945_alive_start(struct iwl3945_priv *priv)
5664 {
5665         int rc = 0;
5666         int thermal_spin = 0;
5667         u32 rfkill;
5668
5669         IWL_DEBUG_INFO("Runtime Alive received.\n");
5670
5671         if (priv->card_alive.is_valid != UCODE_VALID_OK) {
5672                 /* We had an error bringing up the hardware, so take it
5673                  * all the way back down so we can try again */
5674                 IWL_DEBUG_INFO("Alive failed.\n");
5675                 goto restart;
5676         }
5677
5678         /* Initialize uCode has loaded Runtime uCode ... verify inst image.
5679          * This is a paranoid check, because we would not have gotten the
5680          * "runtime" alive if code weren't properly loaded.  */
5681         if (iwl3945_verify_ucode(priv)) {
5682                 /* Runtime instruction load was bad;
5683                  * take it all the way back down so we can try again */
5684                 IWL_DEBUG_INFO("Bad runtime uCode load.\n");
5685                 goto restart;
5686         }
5687
5688         iwl3945_clear_stations_table(priv);
5689
5690         rc = iwl3945_grab_nic_access(priv);
5691         if (rc) {
5692                 IWL_WARNING("Can not read rfkill status from adapter\n");
5693                 return;
5694         }
5695
5696         rfkill = iwl3945_read_prph(priv, APMG_RFKILL_REG);
5697         IWL_DEBUG_INFO("RFKILL status: 0x%x\n", rfkill);
5698         iwl3945_release_nic_access(priv);
5699
5700         if (rfkill & 0x1) {
5701                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
5702                 /* if rfkill is not on, then wait for thermal
5703                  * sensor in adapter to kick in */
5704                 while (iwl3945_hw_get_temperature(priv) == 0) {
5705                         thermal_spin++;
5706                         udelay(10);
5707                 }
5708
5709                 if (thermal_spin)
5710                         IWL_DEBUG_INFO("Thermal calibration took %dus\n",
5711                                        thermal_spin * 10);
5712         } else
5713                 set_bit(STATUS_RF_KILL_HW, &priv->status);
5714
5715         /* After the ALIVE response, we can send commands to 3945 uCode */
5716         set_bit(STATUS_ALIVE, &priv->status);
5717
5718         /* Clear out the uCode error bit if it is set */
5719         clear_bit(STATUS_FW_ERROR, &priv->status);
5720
5721         if (iwl3945_is_rfkill(priv))
5722                 return;
5723
5724         ieee80211_wake_queues(priv->hw);
5725
5726         priv->active_rate = priv->rates_mask;
5727         priv->active_rate_basic = priv->rates_mask & IWL_BASIC_RATES_MASK;
5728
5729         iwl3945_send_power_mode(priv, IWL_POWER_LEVEL(priv->power_mode));
5730
5731         if (iwl3945_is_associated(priv)) {
5732                 struct iwl3945_rxon_cmd *active_rxon =
5733                                 (struct iwl3945_rxon_cmd *)(&priv->active_rxon);
5734
5735                 memcpy(&priv->staging_rxon, &priv->active_rxon,
5736                        sizeof(priv->staging_rxon));
5737                 active_rxon->filter_flags &= ~RXON_FILTER_ASSOC_MSK;
5738         } else {
5739                 /* Initialize our rx_config data */
5740                 iwl3945_connection_init_rx_config(priv);
5741                 memcpy(priv->staging_rxon.node_addr, priv->mac_addr, ETH_ALEN);
5742         }
5743
5744         /* Configure Bluetooth device coexistence support */
5745         iwl3945_send_bt_config(priv);
5746
5747         /* Configure the adapter for unassociated operation */
5748         iwl3945_commit_rxon(priv);
5749
5750         iwl3945_reg_txpower_periodic(priv);
5751
5752         iwl3945_led_register(priv);
5753
5754         IWL_DEBUG_INFO("ALIVE processing complete.\n");
5755         set_bit(STATUS_READY, &priv->status);
5756         wake_up_interruptible(&priv->wait_command_queue);
5757
5758         if (priv->error_recovering)
5759                 iwl3945_error_recovery(priv);
5760
5761         ieee80211_notify_mac(priv->hw, IEEE80211_NOTIFY_RE_ASSOC);
5762         return;
5763
5764  restart:
5765         queue_work(priv->workqueue, &priv->restart);
5766 }
5767
5768 static void iwl3945_cancel_deferred_work(struct iwl3945_priv *priv);
5769
5770 static void __iwl3945_down(struct iwl3945_priv *priv)
5771 {
5772         unsigned long flags;
5773         int exit_pending = test_bit(STATUS_EXIT_PENDING, &priv->status);
5774         struct ieee80211_conf *conf = NULL;
5775
5776         IWL_DEBUG_INFO(DRV_NAME " is going down\n");
5777
5778         conf = ieee80211_get_hw_conf(priv->hw);
5779
5780         if (!exit_pending)
5781                 set_bit(STATUS_EXIT_PENDING, &priv->status);
5782
5783         iwl3945_led_unregister(priv);
5784         iwl3945_clear_stations_table(priv);
5785
5786         /* Unblock any waiting calls */
5787         wake_up_interruptible_all(&priv->wait_command_queue);
5788
5789         /* Wipe out the EXIT_PENDING status bit if we are not actually
5790          * exiting the module */
5791         if (!exit_pending)
5792                 clear_bit(STATUS_EXIT_PENDING, &priv->status);
5793
5794         /* stop and reset the on-board processor */
5795         iwl3945_write32(priv, CSR_RESET, CSR_RESET_REG_FLAG_NEVO_RESET);
5796
5797         /* tell the device to stop sending interrupts */
5798         spin_lock_irqsave(&priv->lock, flags);
5799         iwl3945_disable_interrupts(priv);
5800         spin_unlock_irqrestore(&priv->lock, flags);
5801         iwl_synchronize_irq(priv);
5802
5803         if (priv->mac80211_registered)
5804                 ieee80211_stop_queues(priv->hw);
5805
5806         /* If we have not previously called iwl3945_init() then
5807          * clear all bits but the RF Kill and SUSPEND bits and return */
5808         if (!iwl3945_is_init(priv)) {
5809                 priv->status = test_bit(STATUS_RF_KILL_HW, &priv->status) <<
5810                                         STATUS_RF_KILL_HW |
5811                                test_bit(STATUS_RF_KILL_SW, &priv->status) <<
5812                                         STATUS_RF_KILL_SW |
5813                                test_bit(STATUS_GEO_CONFIGURED, &priv->status) <<
5814                                         STATUS_GEO_CONFIGURED |
5815                                test_bit(STATUS_IN_SUSPEND, &priv->status) <<
5816                                         STATUS_IN_SUSPEND |
5817                                 test_bit(STATUS_EXIT_PENDING, &priv->status) <<
5818                                         STATUS_EXIT_PENDING;
5819                 goto exit;
5820         }
5821
5822         /* ...otherwise clear out all the status bits but the RF Kill and
5823          * SUSPEND bits and continue taking the NIC down. */
5824         priv->status &= test_bit(STATUS_RF_KILL_HW, &priv->status) <<
5825                                 STATUS_RF_KILL_HW |
5826                         test_bit(STATUS_RF_KILL_SW, &priv->status) <<
5827                                 STATUS_RF_KILL_SW |
5828                         test_bit(STATUS_GEO_CONFIGURED, &priv->status) <<
5829                                 STATUS_GEO_CONFIGURED |
5830                         test_bit(STATUS_IN_SUSPEND, &priv->status) <<
5831                                 STATUS_IN_SUSPEND |
5832                         test_bit(STATUS_FW_ERROR, &priv->status) <<
5833                                 STATUS_FW_ERROR |
5834                         test_bit(STATUS_EXIT_PENDING, &priv->status) <<
5835                                 STATUS_EXIT_PENDING;
5836
5837         spin_lock_irqsave(&priv->lock, flags);
5838         iwl3945_clear_bit(priv, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
5839         spin_unlock_irqrestore(&priv->lock, flags);
5840
5841         iwl3945_hw_txq_ctx_stop(priv);
5842         iwl3945_hw_rxq_stop(priv);
5843
5844         spin_lock_irqsave(&priv->lock, flags);
5845         if (!iwl3945_grab_nic_access(priv)) {
5846                 iwl3945_write_prph(priv, APMG_CLK_DIS_REG,
5847                                          APMG_CLK_VAL_DMA_CLK_RQT);
5848                 iwl3945_release_nic_access(priv);
5849         }
5850         spin_unlock_irqrestore(&priv->lock, flags);
5851
5852         udelay(5);
5853
5854         iwl3945_hw_nic_stop_master(priv);
5855         iwl3945_set_bit(priv, CSR_RESET, CSR_RESET_REG_FLAG_SW_RESET);
5856         iwl3945_hw_nic_reset(priv);
5857
5858  exit:
5859         memset(&priv->card_alive, 0, sizeof(struct iwl3945_alive_resp));
5860
5861         if (priv->ibss_beacon)
5862                 dev_kfree_skb(priv->ibss_beacon);
5863         priv->ibss_beacon = NULL;
5864
5865         /* clear out any free frames */
5866         iwl3945_clear_free_frames(priv);
5867 }
5868
5869 static void iwl3945_down(struct iwl3945_priv *priv)
5870 {
5871         mutex_lock(&priv->mutex);
5872         __iwl3945_down(priv);
5873         mutex_unlock(&priv->mutex);
5874
5875         iwl3945_cancel_deferred_work(priv);
5876 }
5877
5878 #define MAX_HW_RESTARTS 5
5879
5880 static int __iwl3945_up(struct iwl3945_priv *priv)
5881 {
5882         int rc, i;
5883
5884         if (test_bit(STATUS_EXIT_PENDING, &priv->status)) {
5885                 IWL_WARNING("Exit pending; will not bring the NIC up\n");
5886                 return -EIO;
5887         }
5888
5889         if (test_bit(STATUS_RF_KILL_SW, &priv->status)) {
5890                 IWL_WARNING("Radio disabled by SW RF kill (module "
5891                             "parameter)\n");
5892                 return -ENODEV;
5893         }
5894
5895         if (!priv->ucode_data_backup.v_addr || !priv->ucode_data.v_addr) {
5896                 IWL_ERROR("ucode not available for device bringup\n");
5897                 return -EIO;
5898         }
5899
5900         /* If platform's RF_KILL switch is NOT set to KILL */
5901         if (iwl3945_read32(priv, CSR_GP_CNTRL) &
5902                                 CSR_GP_CNTRL_REG_FLAG_HW_RF_KILL_SW)
5903                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
5904         else {
5905                 set_bit(STATUS_RF_KILL_HW, &priv->status);
5906                 if (!test_bit(STATUS_IN_SUSPEND, &priv->status)) {
5907                         IWL_WARNING("Radio disabled by HW RF Kill switch\n");
5908                         return -ENODEV;
5909                 }
5910         }
5911
5912         iwl3945_write32(priv, CSR_INT, 0xFFFFFFFF);
5913
5914         rc = iwl3945_hw_nic_init(priv);
5915         if (rc) {
5916                 IWL_ERROR("Unable to int nic\n");
5917                 return rc;
5918         }
5919
5920         /* make sure rfkill handshake bits are cleared */
5921         iwl3945_write32(priv, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
5922         iwl3945_write32(priv, CSR_UCODE_DRV_GP1_CLR,
5923                     CSR_UCODE_DRV_GP1_BIT_CMD_BLOCKED);
5924
5925         /* clear (again), then enable host interrupts */
5926         iwl3945_write32(priv, CSR_INT, 0xFFFFFFFF);
5927         iwl3945_enable_interrupts(priv);
5928
5929         /* really make sure rfkill handshake bits are cleared */
5930         iwl3945_write32(priv, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
5931         iwl3945_write32(priv, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
5932
5933         /* Copy original ucode data image from disk into backup cache.
5934          * This will be used to initialize the on-board processor's
5935          * data SRAM for a clean start when the runtime program first loads. */
5936         memcpy(priv->ucode_data_backup.v_addr, priv->ucode_data.v_addr,
5937                priv->ucode_data.len);
5938
5939         /* We return success when we resume from suspend and rf_kill is on. */
5940         if (test_bit(STATUS_RF_KILL_HW, &priv->status))
5941                 return 0;
5942
5943         for (i = 0; i < MAX_HW_RESTARTS; i++) {
5944
5945                 iwl3945_clear_stations_table(priv);
5946
5947                 /* load bootstrap state machine,
5948                  * load bootstrap program into processor's memory,
5949                  * prepare to load the "initialize" uCode */
5950                 rc = iwl3945_load_bsm(priv);
5951
5952                 if (rc) {
5953                         IWL_ERROR("Unable to set up bootstrap uCode: %d\n", rc);
5954                         continue;
5955                 }
5956
5957                 /* start card; "initialize" will load runtime ucode */
5958                 iwl3945_nic_start(priv);
5959
5960                 IWL_DEBUG_INFO(DRV_NAME " is coming up\n");
5961
5962                 return 0;
5963         }
5964
5965         set_bit(STATUS_EXIT_PENDING, &priv->status);
5966         __iwl3945_down(priv);
5967         clear_bit(STATUS_EXIT_PENDING, &priv->status);
5968
5969         /* tried to restart and config the device for as long as our
5970          * patience could withstand */
5971         IWL_ERROR("Unable to initialize device after %d attempts.\n", i);
5972         return -EIO;
5973 }
5974
5975
5976 /*****************************************************************************
5977  *
5978  * Workqueue callbacks
5979  *
5980  *****************************************************************************/
5981
5982 static void iwl3945_bg_init_alive_start(struct work_struct *data)
5983 {
5984         struct iwl3945_priv *priv =
5985             container_of(data, struct iwl3945_priv, init_alive_start.work);
5986
5987         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
5988                 return;
5989
5990         mutex_lock(&priv->mutex);
5991         iwl3945_init_alive_start(priv);
5992         mutex_unlock(&priv->mutex);
5993 }
5994
5995 static void iwl3945_bg_alive_start(struct work_struct *data)
5996 {
5997         struct iwl3945_priv *priv =
5998             container_of(data, struct iwl3945_priv, alive_start.work);
5999
6000         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
6001                 return;
6002
6003         mutex_lock(&priv->mutex);
6004         iwl3945_alive_start(priv);
6005         mutex_unlock(&priv->mutex);
6006 }
6007
6008 static void iwl3945_bg_rf_kill(struct work_struct *work)
6009 {
6010         struct iwl3945_priv *priv = container_of(work, struct iwl3945_priv, rf_kill);
6011
6012         wake_up_interruptible(&priv->wait_command_queue);
6013
6014         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
6015                 return;
6016
6017         mutex_lock(&priv->mutex);
6018
6019         if (!iwl3945_is_rfkill(priv)) {
6020                 IWL_DEBUG(IWL_DL_INFO | IWL_DL_RF_KILL,
6021                           "HW and/or SW RF Kill no longer active, restarting "
6022                           "device\n");
6023                 if (!test_bit(STATUS_EXIT_PENDING, &priv->status))
6024                         queue_work(priv->workqueue, &priv->restart);
6025         } else {
6026
6027                 if (!test_bit(STATUS_RF_KILL_HW, &priv->status))
6028                         IWL_DEBUG_RF_KILL("Can not turn radio back on - "
6029                                           "disabled by SW switch\n");
6030                 else
6031                         IWL_WARNING("Radio Frequency Kill Switch is On:\n"
6032                                     "Kill switch must be turned off for "
6033                                     "wireless networking to work.\n");
6034         }
6035
6036         mutex_unlock(&priv->mutex);
6037         iwl3945_rfkill_set_hw_state(priv);
6038 }
6039
6040 static void iwl3945_bg_set_monitor(struct work_struct *work)
6041 {
6042         struct iwl3945_priv *priv = container_of(work,
6043                                 struct iwl3945_priv, set_monitor);
6044
6045         IWL_DEBUG(IWL_DL_STATE, "setting monitor mode\n");
6046
6047         mutex_lock(&priv->mutex);
6048
6049         if (!iwl3945_is_ready(priv))
6050                 IWL_DEBUG(IWL_DL_STATE, "leave - not ready\n");
6051         else
6052                 if (iwl3945_set_mode(priv, NL80211_IFTYPE_MONITOR) != 0)
6053                         IWL_ERROR("iwl3945_set_mode() failed\n");
6054
6055         mutex_unlock(&priv->mutex);
6056 }
6057
6058 #define IWL_SCAN_CHECK_WATCHDOG (7 * HZ)
6059
6060 static void iwl3945_bg_scan_check(struct work_struct *data)
6061 {
6062         struct iwl3945_priv *priv =
6063             container_of(data, struct iwl3945_priv, scan_check.work);
6064
6065         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
6066                 return;
6067
6068         mutex_lock(&priv->mutex);
6069         if (test_bit(STATUS_SCANNING, &priv->status) ||
6070             test_bit(STATUS_SCAN_ABORTING, &priv->status)) {
6071                 IWL_DEBUG(IWL_DL_INFO | IWL_DL_SCAN,
6072                           "Scan completion watchdog resetting adapter (%dms)\n",
6073                           jiffies_to_msecs(IWL_SCAN_CHECK_WATCHDOG));
6074
6075                 if (!test_bit(STATUS_EXIT_PENDING, &priv->status))
6076                         iwl3945_send_scan_abort(priv);
6077         }
6078         mutex_unlock(&priv->mutex);
6079 }
6080
6081 static void iwl3945_bg_