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