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