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