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