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