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