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