iwl3945: kill iwl3945_rx_queue_space
[linux-2.6.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-fh.h"
52 #include "iwl-3945-fh.h"
53 #include "iwl-commands.h"
54 #include "iwl-3945.h"
55 #include "iwl-helpers.h"
56 #include "iwl-core.h"
57 #include "iwl-dev.h"
58
59 static int iwl3945_tx_queue_update_write_ptr(struct iwl_priv *priv,
60                                   struct iwl_tx_queue *txq);
61
62 /*
63  * module name, copyright, version, etc.
64  */
65
66 #define DRV_DESCRIPTION \
67 "Intel(R) PRO/Wireless 3945ABG/BG Network Connection driver for Linux"
68
69 #ifdef CONFIG_IWL3945_DEBUG
70 #define VD "d"
71 #else
72 #define VD
73 #endif
74
75 #ifdef CONFIG_IWL3945_SPECTRUM_MEASUREMENT
76 #define VS "s"
77 #else
78 #define VS
79 #endif
80
81 #define IWL39_VERSION "1.2.26k" VD VS
82 #define DRV_COPYRIGHT   "Copyright(c) 2003-2008 Intel Corporation"
83 #define DRV_AUTHOR     "<ilw@linux.intel.com>"
84 #define DRV_VERSION     IWL39_VERSION
85
86
87 MODULE_DESCRIPTION(DRV_DESCRIPTION);
88 MODULE_VERSION(DRV_VERSION);
89 MODULE_AUTHOR(DRV_COPYRIGHT " " DRV_AUTHOR);
90 MODULE_LICENSE("GPL");
91
92  /* module parameters */
93 struct iwl_mod_params iwl3945_mod_params = {
94         .num_of_queues = IWL39_MAX_NUM_QUEUES,
95         /* the rest are 0 by default */
96 };
97
98 /*************** DMA-QUEUE-GENERAL-FUNCTIONS  *****
99  * DMA services
100  *
101  * Theory of operation
102  *
103  * A Tx or Rx queue resides in host DRAM, and is comprised of a circular buffer
104  * of buffer descriptors, each of which points to one or more data buffers for
105  * the device to read from or fill.  Driver and device exchange status of each
106  * queue via "read" and "write" pointers.  Driver keeps minimum of 2 empty
107  * entries in each circular buffer, to protect against confusing empty and full
108  * queue states.
109  *
110  * The device reads or writes the data in the queues via the device's several
111  * DMA/FIFO channels.  Each queue is mapped to a single DMA channel.
112  *
113  * For Tx queue, there are low mark and high mark limits. If, after queuing
114  * the packet for Tx, free space become < low mark, Tx queue stopped. When
115  * reclaiming packets (on 'tx done IRQ), if free space become > high mark,
116  * Tx queue resumed.
117  *
118  * The 3945 operates with six queues:  One receive queue, one transmit queue
119  * (#4) for sending commands to the device firmware, and four transmit queues
120  * (#0-3) for data tx via EDCA.  An additional 2 HCCA queues are unused.
121  ***************************************************/
122
123 int iwl3945_x2_queue_used(const struct iwl_queue *q, int i)
124 {
125         return q->write_ptr > q->read_ptr ?
126                 (i >= q->read_ptr && i < q->write_ptr) :
127                 !(i < q->read_ptr && i >= q->write_ptr);
128 }
129
130 /**
131  * iwl3945_queue_init - Initialize queue's high/low-water and read/write indexes
132  */
133 static int iwl3945_queue_init(struct iwl_priv *priv, struct iwl_queue *q,
134                           int count, int slots_num, u32 id)
135 {
136         q->n_bd = count;
137         q->n_window = slots_num;
138         q->id = id;
139
140         /* count must be power-of-two size, otherwise iwl_queue_inc_wrap
141          * and iwl_queue_dec_wrap are broken. */
142         BUG_ON(!is_power_of_2(count));
143
144         /* slots_num must be power-of-two size, otherwise
145          * get_cmd_index is broken. */
146         BUG_ON(!is_power_of_2(slots_num));
147
148         q->low_mark = q->n_window / 4;
149         if (q->low_mark < 4)
150                 q->low_mark = 4;
151
152         q->high_mark = q->n_window / 8;
153         if (q->high_mark < 2)
154                 q->high_mark = 2;
155
156         q->write_ptr = q->read_ptr = 0;
157
158         return 0;
159 }
160
161 /**
162  * iwl3945_tx_queue_alloc - Alloc driver data and TFD CB for one Tx/cmd queue
163  */
164 static int iwl3945_tx_queue_alloc(struct iwl_priv *priv,
165                               struct iwl_tx_queue *txq, u32 id)
166 {
167         struct pci_dev *dev = priv->pci_dev;
168
169         /* Driver private data, only for Tx (not command) queues,
170          * not shared with device. */
171         if (id != IWL_CMD_QUEUE_NUM) {
172                 txq->txb = kmalloc(sizeof(txq->txb[0]) *
173                                    TFD_QUEUE_SIZE_MAX, GFP_KERNEL);
174                 if (!txq->txb) {
175                         IWL_ERR(priv, "kmalloc for auxiliary BD "
176                                   "structures failed\n");
177                         goto error;
178                 }
179         } else
180                 txq->txb = NULL;
181
182         /* Circular buffer of transmit frame descriptors (TFDs),
183          * shared with device */
184         txq->tfds39 = pci_alloc_consistent(dev,
185                         sizeof(txq->tfds39[0]) * TFD_QUEUE_SIZE_MAX,
186                         &txq->q.dma_addr);
187
188         if (!txq->tfds39) {
189                 IWL_ERR(priv, "pci_alloc_consistent(%zd) failed\n",
190                           sizeof(txq->tfds39[0]) * TFD_QUEUE_SIZE_MAX);
191                 goto error;
192         }
193         txq->q.id = id;
194
195         return 0;
196
197  error:
198         kfree(txq->txb);
199         txq->txb = NULL;
200
201         return -ENOMEM;
202 }
203
204 /**
205  * iwl3945_tx_queue_init - Allocate and initialize one tx/cmd queue
206  */
207 int iwl3945_tx_queue_init(struct iwl_priv *priv,
208                       struct iwl_tx_queue *txq, int slots_num, u32 txq_id)
209 {
210         int len, i;
211         int rc = 0;
212
213         /*
214          * Alloc buffer array for commands (Tx or other types of commands).
215          * For the command queue (#4), allocate command space + one big
216          * command for scan, since scan command is very huge; the system will
217          * not have two scans at the same time, so only one is needed.
218          * For data Tx queues (all other queues), no super-size command
219          * space is needed.
220          */
221         len = sizeof(struct iwl_cmd);
222         for (i = 0; i <= slots_num; i++) {
223                 if (i == slots_num) {
224                         if (txq_id == IWL_CMD_QUEUE_NUM)
225                                 len += IWL_MAX_SCAN_SIZE;
226                         else
227                                 continue;
228                 }
229
230                 txq->cmd[i] = kmalloc(len, GFP_KERNEL);
231                 if (!txq->cmd[i])
232                         goto err;
233         }
234
235         /* Alloc driver data array and TFD circular buffer */
236         rc = iwl3945_tx_queue_alloc(priv, txq, txq_id);
237         if (rc)
238                 goto err;
239
240         txq->need_update = 0;
241
242         /* TFD_QUEUE_SIZE_MAX must be power-of-two size, otherwise
243          * iwl_queue_inc_wrap and iwl_queue_dec_wrap are broken. */
244         BUILD_BUG_ON(TFD_QUEUE_SIZE_MAX & (TFD_QUEUE_SIZE_MAX - 1));
245
246         /* Initialize queue high/low-water, head/tail indexes */
247         iwl3945_queue_init(priv, &txq->q, TFD_QUEUE_SIZE_MAX, slots_num, txq_id);
248
249         /* Tell device where to find queue, enable DMA channel. */
250         iwl3945_hw_tx_queue_init(priv, txq);
251
252         return 0;
253 err:
254         for (i = 0; i < slots_num; i++) {
255                 kfree(txq->cmd[i]);
256                 txq->cmd[i] = NULL;
257         }
258
259         if (txq_id == IWL_CMD_QUEUE_NUM) {
260                 kfree(txq->cmd[slots_num]);
261                 txq->cmd[slots_num] = NULL;
262         }
263         return -ENOMEM;
264 }
265
266 /**
267  * iwl3945_tx_queue_free - Deallocate DMA queue.
268  * @txq: Transmit queue to deallocate.
269  *
270  * Empty queue by removing and destroying all BD's.
271  * Free all buffers.
272  * 0-fill, but do not free "txq" descriptor structure.
273  */
274 void iwl3945_tx_queue_free(struct iwl_priv *priv, struct iwl_tx_queue *txq)
275 {
276         struct iwl_queue *q = &txq->q;
277         struct pci_dev *dev = priv->pci_dev;
278         int len, i;
279
280         if (q->n_bd == 0)
281                 return;
282
283         /* first, empty all BD's */
284         for (; q->write_ptr != q->read_ptr;
285              q->read_ptr = iwl_queue_inc_wrap(q->read_ptr, q->n_bd))
286                 iwl3945_hw_txq_free_tfd(priv, txq);
287
288         len = sizeof(struct iwl_cmd) * q->n_window;
289         if (q->id == IWL_CMD_QUEUE_NUM)
290                 len += IWL_MAX_SCAN_SIZE;
291
292         /* De-alloc array of command/tx buffers */
293         for (i = 0; i < TFD_TX_CMD_SLOTS; i++)
294                 kfree(txq->cmd[i]);
295
296         /* De-alloc circular buffer of TFDs */
297         if (txq->q.n_bd)
298                 pci_free_consistent(dev, sizeof(struct iwl3945_tfd) *
299                                     txq->q.n_bd, txq->tfds39, txq->q.dma_addr);
300
301         /* De-alloc array of per-TFD driver data */
302         kfree(txq->txb);
303         txq->txb = NULL;
304
305         /* 0-fill queue descriptor structure */
306         memset(txq, 0, sizeof(*txq));
307 }
308
309 /*************** STATION TABLE MANAGEMENT ****
310  * mac80211 should be examined to determine if sta_info is duplicating
311  * the functionality provided here
312  */
313
314 /**************************************************************/
315 #if 0 /* temporary disable till we add real remove station */
316 /**
317  * iwl3945_remove_station - Remove driver's knowledge of station.
318  *
319  * NOTE:  This does not remove station from device's station table.
320  */
321 static u8 iwl3945_remove_station(struct iwl_priv *priv, const u8 *addr, int is_ap)
322 {
323         int index = IWL_INVALID_STATION;
324         int i;
325         unsigned long flags;
326
327         spin_lock_irqsave(&priv->sta_lock, flags);
328
329         if (is_ap)
330                 index = IWL_AP_ID;
331         else if (is_broadcast_ether_addr(addr))
332                 index = priv->hw_params.bcast_sta_id;
333         else
334                 for (i = IWL_STA_ID; i < priv->hw_params.max_stations; i++)
335                         if (priv->stations_39[i].used &&
336                             !compare_ether_addr(priv->stations_39[i].sta.sta.addr,
337                                                 addr)) {
338                                 index = i;
339                                 break;
340                         }
341
342         if (unlikely(index == IWL_INVALID_STATION))
343                 goto out;
344
345         if (priv->stations_39[index].used) {
346                 priv->stations_39[index].used = 0;
347                 priv->num_stations--;
348         }
349
350         BUG_ON(priv->num_stations < 0);
351
352 out:
353         spin_unlock_irqrestore(&priv->sta_lock, flags);
354         return 0;
355 }
356 #endif
357
358 /**
359  * iwl3945_clear_stations_table - Clear the driver's station table
360  *
361  * NOTE:  This does not clear or otherwise alter the device's station table.
362  */
363 static void iwl3945_clear_stations_table(struct iwl_priv *priv)
364 {
365         unsigned long flags;
366
367         spin_lock_irqsave(&priv->sta_lock, flags);
368
369         priv->num_stations = 0;
370         memset(priv->stations_39, 0, sizeof(priv->stations_39));
371
372         spin_unlock_irqrestore(&priv->sta_lock, flags);
373 }
374
375 /**
376  * iwl3945_add_station - Add station to station tables in driver and device
377  */
378 u8 iwl3945_add_station(struct iwl_priv *priv, const u8 *addr, int is_ap, u8 flags)
379 {
380         int i;
381         int index = IWL_INVALID_STATION;
382         struct iwl3945_station_entry *station;
383         unsigned long flags_spin;
384         u8 rate;
385
386         spin_lock_irqsave(&priv->sta_lock, flags_spin);
387         if (is_ap)
388                 index = IWL_AP_ID;
389         else if (is_broadcast_ether_addr(addr))
390                 index = priv->hw_params.bcast_sta_id;
391         else
392                 for (i = IWL_STA_ID; i < priv->hw_params.max_stations; i++) {
393                         if (!compare_ether_addr(priv->stations_39[i].sta.sta.addr,
394                                                 addr)) {
395                                 index = i;
396                                 break;
397                         }
398
399                         if (!priv->stations_39[i].used &&
400                             index == IWL_INVALID_STATION)
401                                 index = i;
402                 }
403
404         /* These two conditions has the same outcome but keep them separate
405           since they have different meaning */
406         if (unlikely(index == IWL_INVALID_STATION)) {
407                 spin_unlock_irqrestore(&priv->sta_lock, flags_spin);
408                 return index;
409         }
410
411         if (priv->stations_39[index].used &&
412            !compare_ether_addr(priv->stations_39[index].sta.sta.addr, addr)) {
413                 spin_unlock_irqrestore(&priv->sta_lock, flags_spin);
414                 return index;
415         }
416
417         IWL_DEBUG_ASSOC("Add STA ID %d: %pM\n", index, addr);
418         station = &priv->stations_39[index];
419         station->used = 1;
420         priv->num_stations++;
421
422         /* Set up the REPLY_ADD_STA command to send to device */
423         memset(&station->sta, 0, sizeof(struct iwl3945_addsta_cmd));
424         memcpy(station->sta.sta.addr, addr, ETH_ALEN);
425         station->sta.mode = 0;
426         station->sta.sta.sta_id = index;
427         station->sta.station_flags = 0;
428
429         if (priv->band == IEEE80211_BAND_5GHZ)
430                 rate = IWL_RATE_6M_PLCP;
431         else
432                 rate =  IWL_RATE_1M_PLCP;
433
434         /* Turn on both antennas for the station... */
435         station->sta.rate_n_flags =
436                         iwl3945_hw_set_rate_n_flags(rate, RATE_MCS_ANT_AB_MSK);
437
438         spin_unlock_irqrestore(&priv->sta_lock, flags_spin);
439
440         /* Add station to device's station table */
441         iwl3945_send_add_station(priv, &station->sta, flags);
442         return index;
443
444 }
445
446
447 /*************** HOST COMMAND QUEUE FUNCTIONS   *****/
448
449 #define IWL_CMD(x) case x: return #x
450 #define HOST_COMPLETE_TIMEOUT (HZ / 2)
451
452 /**
453  * iwl3945_enqueue_hcmd - enqueue a uCode command
454  * @priv: device private data point
455  * @cmd: a point to the ucode command structure
456  *
457  * The function returns < 0 values to indicate the operation is
458  * failed. On success, it turns the index (> 0) of command in the
459  * command queue.
460  */
461 static int iwl3945_enqueue_hcmd(struct iwl_priv *priv, struct iwl_host_cmd *cmd)
462 {
463         struct iwl_tx_queue *txq = &priv->txq[IWL_CMD_QUEUE_NUM];
464         struct iwl_queue *q = &txq->q;
465         struct iwl3945_tfd *tfd;
466         struct iwl_cmd *out_cmd;
467         u32 idx;
468         u16 fix_size = (u16)(cmd->len + sizeof(out_cmd->hdr));
469         dma_addr_t phys_addr;
470         int pad;
471         int ret, len;
472         unsigned long flags;
473
474         /* If any of the command structures end up being larger than
475          * the TFD_MAX_PAYLOAD_SIZE, and it sent as a 'small' command then
476          * we will need to increase the size of the TFD entries */
477         BUG_ON((fix_size > TFD_MAX_PAYLOAD_SIZE) &&
478                !(cmd->meta.flags & CMD_SIZE_HUGE));
479
480
481         if (iwl_is_rfkill(priv)) {
482                 IWL_DEBUG_INFO("Not sending command - RF KILL");
483                 return -EIO;
484         }
485
486         if (iwl_queue_space(q) < ((cmd->meta.flags & CMD_ASYNC) ? 2 : 1)) {
487                 IWL_ERR(priv, "No space for Tx\n");
488                 return -ENOSPC;
489         }
490
491         spin_lock_irqsave(&priv->hcmd_lock, flags);
492
493         tfd = &txq->tfds39[q->write_ptr];
494         memset(tfd, 0, sizeof(*tfd));
495
496         idx = get_cmd_index(q, q->write_ptr, cmd->meta.flags & CMD_SIZE_HUGE);
497         out_cmd = txq->cmd[idx];
498
499         out_cmd->hdr.cmd = cmd->id;
500         memcpy(&out_cmd->meta, &cmd->meta, sizeof(cmd->meta));
501         memcpy(&out_cmd->cmd.payload, cmd->data, cmd->len);
502
503         /* At this point, the out_cmd now has all of the incoming cmd
504          * information */
505
506         out_cmd->hdr.flags = 0;
507         out_cmd->hdr.sequence = cpu_to_le16(QUEUE_TO_SEQ(IWL_CMD_QUEUE_NUM) |
508                         INDEX_TO_SEQ(q->write_ptr));
509         if (out_cmd->meta.flags & CMD_SIZE_HUGE)
510                 out_cmd->hdr.sequence |= SEQ_HUGE_FRAME;
511
512         len = (idx == TFD_CMD_SLOTS) ?
513                         IWL_MAX_SCAN_SIZE : sizeof(struct iwl_cmd);
514
515         phys_addr = pci_map_single(priv->pci_dev, out_cmd,
516                                         len, PCI_DMA_TODEVICE);
517         pci_unmap_addr_set(&out_cmd->meta, mapping, phys_addr);
518         pci_unmap_len_set(&out_cmd->meta, len, len);
519         phys_addr += offsetof(struct iwl_cmd, hdr);
520
521         iwl3945_hw_txq_attach_buf_to_tfd(priv, tfd, phys_addr, fix_size);
522
523         pad = U32_PAD(cmd->len);
524         tfd->control_flags |= cpu_to_le32(TFD_CTL_PAD_SET(pad));
525
526         IWL_DEBUG_HC("Sending command %s (#%x), seq: 0x%04X, "
527                      "%d bytes at %d[%d]:%d\n",
528                      get_cmd_string(out_cmd->hdr.cmd),
529                      out_cmd->hdr.cmd, le16_to_cpu(out_cmd->hdr.sequence),
530                      fix_size, q->write_ptr, idx, IWL_CMD_QUEUE_NUM);
531
532         txq->need_update = 1;
533
534         /* Increment and update queue's write index */
535         q->write_ptr = iwl_queue_inc_wrap(q->write_ptr, q->n_bd);
536         ret = iwl3945_tx_queue_update_write_ptr(priv, txq);
537
538         spin_unlock_irqrestore(&priv->hcmd_lock, flags);
539         return ret ? ret : idx;
540 }
541
542 static int iwl3945_send_cmd_async(struct iwl_priv *priv,
543                                   struct iwl_host_cmd *cmd)
544 {
545         int ret;
546
547         BUG_ON(!(cmd->meta.flags & CMD_ASYNC));
548
549         /* An asynchronous command can not expect an SKB to be set. */
550         BUG_ON(cmd->meta.flags & CMD_WANT_SKB);
551
552         /* An asynchronous command MUST have a callback. */
553         BUG_ON(!cmd->meta.u.callback);
554
555         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
556                 return -EBUSY;
557
558         ret = iwl3945_enqueue_hcmd(priv, cmd);
559         if (ret < 0) {
560                 IWL_ERR(priv,
561                         "Error sending %s: iwl3945_enqueue_hcmd failed: %d\n",
562                         get_cmd_string(cmd->id), ret);
563                 return ret;
564         }
565         return 0;
566 }
567
568 static int iwl3945_send_cmd_sync(struct iwl_priv *priv,
569                                  struct iwl_host_cmd *cmd)
570 {
571         int cmd_idx;
572         int ret;
573
574         BUG_ON(cmd->meta.flags & CMD_ASYNC);
575
576          /* A synchronous command can not have a callback set. */
577         BUG_ON(cmd->meta.u.callback != NULL);
578
579         if (test_and_set_bit(STATUS_HCMD_SYNC_ACTIVE, &priv->status)) {
580                 IWL_ERR(priv,
581                         "Error sending %s: Already sending a host command\n",
582                         get_cmd_string(cmd->id));
583                 ret = -EBUSY;
584                 goto out;
585         }
586
587         set_bit(STATUS_HCMD_ACTIVE, &priv->status);
588
589         if (cmd->meta.flags & CMD_WANT_SKB)
590                 cmd->meta.source = &cmd->meta;
591
592         cmd_idx = iwl3945_enqueue_hcmd(priv, cmd);
593         if (cmd_idx < 0) {
594                 ret = cmd_idx;
595                 IWL_ERR(priv,
596                         "Error sending %s: iwl3945_enqueue_hcmd failed: %d\n",
597                         get_cmd_string(cmd->id), ret);
598                 goto out;
599         }
600
601         ret = wait_event_interruptible_timeout(priv->wait_command_queue,
602                         !test_bit(STATUS_HCMD_ACTIVE, &priv->status),
603                         HOST_COMPLETE_TIMEOUT);
604         if (!ret) {
605                 if (test_bit(STATUS_HCMD_ACTIVE, &priv->status)) {
606                         IWL_ERR(priv, "Error sending %s: time out after %dms\n",
607                                   get_cmd_string(cmd->id),
608                                   jiffies_to_msecs(HOST_COMPLETE_TIMEOUT));
609
610                         clear_bit(STATUS_HCMD_ACTIVE, &priv->status);
611                         ret = -ETIMEDOUT;
612                         goto cancel;
613                 }
614         }
615
616         if (test_bit(STATUS_RF_KILL_HW, &priv->status)) {
617                 IWL_DEBUG_INFO("Command %s aborted: RF KILL Switch\n",
618                                get_cmd_string(cmd->id));
619                 ret = -ECANCELED;
620                 goto fail;
621         }
622         if (test_bit(STATUS_FW_ERROR, &priv->status)) {
623                 IWL_DEBUG_INFO("Command %s failed: FW Error\n",
624                                get_cmd_string(cmd->id));
625                 ret = -EIO;
626                 goto fail;
627         }
628         if ((cmd->meta.flags & CMD_WANT_SKB) && !cmd->meta.u.skb) {
629                 IWL_ERR(priv, "Error: Response NULL in '%s'\n",
630                           get_cmd_string(cmd->id));
631                 ret = -EIO;
632                 goto cancel;
633         }
634
635         ret = 0;
636         goto out;
637
638 cancel:
639         if (cmd->meta.flags & CMD_WANT_SKB) {
640                 struct iwl_cmd *qcmd;
641
642                 /* Cancel the CMD_WANT_SKB flag for the cmd in the
643                  * TX cmd queue. Otherwise in case the cmd comes
644                  * in later, it will possibly set an invalid
645                  * address (cmd->meta.source). */
646                 qcmd = priv->txq[IWL_CMD_QUEUE_NUM].cmd[cmd_idx];
647                 qcmd->meta.flags &= ~CMD_WANT_SKB;
648         }
649 fail:
650         if (cmd->meta.u.skb) {
651                 dev_kfree_skb_any(cmd->meta.u.skb);
652                 cmd->meta.u.skb = NULL;
653         }
654 out:
655         clear_bit(STATUS_HCMD_SYNC_ACTIVE, &priv->status);
656         return ret;
657 }
658
659 int iwl3945_send_cmd(struct iwl_priv *priv, struct iwl_host_cmd *cmd)
660 {
661         if (cmd->meta.flags & CMD_ASYNC)
662                 return iwl3945_send_cmd_async(priv, cmd);
663
664         return iwl3945_send_cmd_sync(priv, cmd);
665 }
666
667 int iwl3945_send_cmd_pdu(struct iwl_priv *priv, u8 id, u16 len, const void *data)
668 {
669         struct iwl_host_cmd cmd = {
670                 .id = id,
671                 .len = len,
672                 .data = data,
673         };
674
675         return iwl3945_send_cmd_sync(priv, &cmd);
676 }
677
678 static int __must_check iwl3945_send_cmd_u32(struct iwl_priv *priv, u8 id, u32 val)
679 {
680         struct iwl_host_cmd cmd = {
681                 .id = id,
682                 .len = sizeof(val),
683                 .data = &val,
684         };
685
686         return iwl3945_send_cmd_sync(priv, &cmd);
687 }
688
689 int iwl3945_send_statistics_request(struct iwl_priv *priv)
690 {
691         return iwl3945_send_cmd_u32(priv, REPLY_STATISTICS_CMD, 0);
692 }
693
694 /**
695  * iwl3945_set_rxon_channel - Set the phymode and channel values in staging RXON
696  * @band: 2.4 or 5 GHz band
697  * @channel: Any channel valid for the requested band
698
699  * In addition to setting the staging RXON, priv->band is also set.
700  *
701  * NOTE:  Does not commit to the hardware; it sets appropriate bit fields
702  * in the staging RXON flag structure based on the band
703  */
704 static int iwl3945_set_rxon_channel(struct iwl_priv *priv,
705                                     enum ieee80211_band band,
706                                     u16 channel)
707 {
708         if (!iwl3945_get_channel_info(priv, band, channel)) {
709                 IWL_DEBUG_INFO("Could not set channel to %d [%d]\n",
710                                channel, band);
711                 return -EINVAL;
712         }
713
714         if ((le16_to_cpu(priv->staging39_rxon.channel) == channel) &&
715             (priv->band == band))
716                 return 0;
717
718         priv->staging39_rxon.channel = cpu_to_le16(channel);
719         if (band == IEEE80211_BAND_5GHZ)
720                 priv->staging39_rxon.flags &= ~RXON_FLG_BAND_24G_MSK;
721         else
722                 priv->staging39_rxon.flags |= RXON_FLG_BAND_24G_MSK;
723
724         priv->band = band;
725
726         IWL_DEBUG_INFO("Staging channel set to %d [%d]\n", channel, band);
727
728         return 0;
729 }
730
731 /**
732  * iwl3945_check_rxon_cmd - validate RXON structure is valid
733  *
734  * NOTE:  This is really only useful during development and can eventually
735  * be #ifdef'd out once the driver is stable and folks aren't actively
736  * making changes
737  */
738 static int iwl3945_check_rxon_cmd(struct iwl_priv *priv)
739 {
740         int error = 0;
741         int counter = 1;
742         struct iwl3945_rxon_cmd *rxon = &priv->staging39_rxon;
743
744         if (rxon->flags & RXON_FLG_BAND_24G_MSK) {
745                 error |= le32_to_cpu(rxon->flags &
746                                 (RXON_FLG_TGJ_NARROW_BAND_MSK |
747                                  RXON_FLG_RADAR_DETECT_MSK));
748                 if (error)
749                         IWL_WARN(priv, "check 24G fields %d | %d\n",
750                                     counter++, error);
751         } else {
752                 error |= (rxon->flags & RXON_FLG_SHORT_SLOT_MSK) ?
753                                 0 : le32_to_cpu(RXON_FLG_SHORT_SLOT_MSK);
754                 if (error)
755                         IWL_WARN(priv, "check 52 fields %d | %d\n",
756                                     counter++, error);
757                 error |= le32_to_cpu(rxon->flags & RXON_FLG_CCK_MSK);
758                 if (error)
759                         IWL_WARN(priv, "check 52 CCK %d | %d\n",
760                                     counter++, error);
761         }
762         error |= (rxon->node_addr[0] | rxon->bssid_addr[0]) & 0x1;
763         if (error)
764                 IWL_WARN(priv, "check mac addr %d | %d\n", counter++, error);
765
766         /* make sure basic rates 6Mbps and 1Mbps are supported */
767         error |= (((rxon->ofdm_basic_rates & IWL_RATE_6M_MASK) == 0) &&
768                   ((rxon->cck_basic_rates & IWL_RATE_1M_MASK) == 0));
769         if (error)
770                 IWL_WARN(priv, "check basic rate %d | %d\n", counter++, error);
771
772         error |= (le16_to_cpu(rxon->assoc_id) > 2007);
773         if (error)
774                 IWL_WARN(priv, "check assoc id %d | %d\n", counter++, error);
775
776         error |= ((rxon->flags & (RXON_FLG_CCK_MSK | RXON_FLG_SHORT_SLOT_MSK))
777                         == (RXON_FLG_CCK_MSK | RXON_FLG_SHORT_SLOT_MSK));
778         if (error)
779                 IWL_WARN(priv, "check CCK and short slot %d | %d\n",
780                             counter++, error);
781
782         error |= ((rxon->flags & (RXON_FLG_CCK_MSK | RXON_FLG_AUTO_DETECT_MSK))
783                         == (RXON_FLG_CCK_MSK | RXON_FLG_AUTO_DETECT_MSK));
784         if (error)
785                 IWL_WARN(priv, "check CCK & auto detect %d | %d\n",
786                             counter++, error);
787
788         error |= ((rxon->flags & (RXON_FLG_AUTO_DETECT_MSK |
789                         RXON_FLG_TGG_PROTECT_MSK)) == RXON_FLG_TGG_PROTECT_MSK);
790         if (error)
791                 IWL_WARN(priv, "check TGG and auto detect %d | %d\n",
792                             counter++, error);
793
794         if ((rxon->flags & RXON_FLG_DIS_DIV_MSK))
795                 error |= ((rxon->flags & (RXON_FLG_ANT_B_MSK |
796                                 RXON_FLG_ANT_A_MSK)) == 0);
797         if (error)
798                 IWL_WARN(priv, "check antenna %d %d\n", counter++, error);
799
800         if (error)
801                 IWL_WARN(priv, "Tuning to channel %d\n",
802                             le16_to_cpu(rxon->channel));
803
804         if (error) {
805                 IWL_ERR(priv, "Not a valid rxon_assoc_cmd field values\n");
806                 return -1;
807         }
808         return 0;
809 }
810
811 /**
812  * iwl3945_full_rxon_required - check if full RXON (vs RXON_ASSOC) cmd is needed
813  * @priv: staging_rxon is compared to active_rxon
814  *
815  * If the RXON structure is changing enough to require a new tune,
816  * or is clearing the RXON_FILTER_ASSOC_MSK, then return 1 to indicate that
817  * a new tune (full RXON command, rather than RXON_ASSOC cmd) is required.
818  */
819 static int iwl3945_full_rxon_required(struct iwl_priv *priv)
820 {
821
822         /* These items are only settable from the full RXON command */
823         if (!(iwl3945_is_associated(priv)) ||
824             compare_ether_addr(priv->staging39_rxon.bssid_addr,
825                                priv->active39_rxon.bssid_addr) ||
826             compare_ether_addr(priv->staging39_rxon.node_addr,
827                                priv->active39_rxon.node_addr) ||
828             compare_ether_addr(priv->staging39_rxon.wlap_bssid_addr,
829                                priv->active39_rxon.wlap_bssid_addr) ||
830             (priv->staging39_rxon.dev_type != priv->active39_rxon.dev_type) ||
831             (priv->staging39_rxon.channel != priv->active39_rxon.channel) ||
832             (priv->staging39_rxon.air_propagation !=
833              priv->active39_rxon.air_propagation) ||
834             (priv->staging39_rxon.assoc_id != priv->active39_rxon.assoc_id))
835                 return 1;
836
837         /* flags, filter_flags, ofdm_basic_rates, and cck_basic_rates can
838          * be updated with the RXON_ASSOC command -- however only some
839          * flag transitions are allowed using RXON_ASSOC */
840
841         /* Check if we are not switching bands */
842         if ((priv->staging39_rxon.flags & RXON_FLG_BAND_24G_MSK) !=
843             (priv->active39_rxon.flags & RXON_FLG_BAND_24G_MSK))
844                 return 1;
845
846         /* Check if we are switching association toggle */
847         if ((priv->staging39_rxon.filter_flags & RXON_FILTER_ASSOC_MSK) !=
848                 (priv->active39_rxon.filter_flags & RXON_FILTER_ASSOC_MSK))
849                 return 1;
850
851         return 0;
852 }
853
854 static int iwl3945_send_rxon_assoc(struct iwl_priv *priv)
855 {
856         int rc = 0;
857         struct iwl_rx_packet *res = NULL;
858         struct iwl3945_rxon_assoc_cmd rxon_assoc;
859         struct iwl_host_cmd cmd = {
860                 .id = REPLY_RXON_ASSOC,
861                 .len = sizeof(rxon_assoc),
862                 .meta.flags = CMD_WANT_SKB,
863                 .data = &rxon_assoc,
864         };
865         const struct iwl3945_rxon_cmd *rxon1 = &priv->staging39_rxon;
866         const struct iwl3945_rxon_cmd *rxon2 = &priv->active39_rxon;
867
868         if ((rxon1->flags == rxon2->flags) &&
869             (rxon1->filter_flags == rxon2->filter_flags) &&
870             (rxon1->cck_basic_rates == rxon2->cck_basic_rates) &&
871             (rxon1->ofdm_basic_rates == rxon2->ofdm_basic_rates)) {
872                 IWL_DEBUG_INFO("Using current RXON_ASSOC.  Not resending.\n");
873                 return 0;
874         }
875
876         rxon_assoc.flags = priv->staging39_rxon.flags;
877         rxon_assoc.filter_flags = priv->staging39_rxon.filter_flags;
878         rxon_assoc.ofdm_basic_rates = priv->staging39_rxon.ofdm_basic_rates;
879         rxon_assoc.cck_basic_rates = priv->staging39_rxon.cck_basic_rates;
880         rxon_assoc.reserved = 0;
881
882         rc = iwl3945_send_cmd_sync(priv, &cmd);
883         if (rc)
884                 return rc;
885
886         res = (struct iwl_rx_packet *)cmd.meta.u.skb->data;
887         if (res->hdr.flags & IWL_CMD_FAILED_MSK) {
888                 IWL_ERR(priv, "Bad return from REPLY_RXON_ASSOC command\n");
889                 rc = -EIO;
890         }
891
892         priv->alloc_rxb_skb--;
893         dev_kfree_skb_any(cmd.meta.u.skb);
894
895         return rc;
896 }
897
898 /**
899  * iwl3945_commit_rxon - commit staging_rxon to hardware
900  *
901  * The RXON command in staging_rxon is committed to the hardware and
902  * the active_rxon structure is updated with the new data.  This
903  * function correctly transitions out of the RXON_ASSOC_MSK state if
904  * a HW tune is required based on the RXON structure changes.
905  */
906 static int iwl3945_commit_rxon(struct iwl_priv *priv)
907 {
908         /* cast away the const for active_rxon in this function */
909         struct iwl3945_rxon_cmd *active_rxon = (void *)&priv->active39_rxon;
910         int rc = 0;
911
912         if (!iwl_is_alive(priv))
913                 return -1;
914
915         /* always get timestamp with Rx frame */
916         priv->staging39_rxon.flags |= RXON_FLG_TSF2HOST_MSK;
917
918         /* select antenna */
919         priv->staging39_rxon.flags &=
920             ~(RXON_FLG_DIS_DIV_MSK | RXON_FLG_ANT_SEL_MSK);
921         priv->staging39_rxon.flags |= iwl3945_get_antenna_flags(priv);
922
923         rc = iwl3945_check_rxon_cmd(priv);
924         if (rc) {
925                 IWL_ERR(priv, "Invalid RXON configuration.  Not committing.\n");
926                 return -EINVAL;
927         }
928
929         /* If we don't need to send a full RXON, we can use
930          * iwl3945_rxon_assoc_cmd which is used to reconfigure filter
931          * and other flags for the current radio configuration. */
932         if (!iwl3945_full_rxon_required(priv)) {
933                 rc = iwl3945_send_rxon_assoc(priv);
934                 if (rc) {
935                         IWL_ERR(priv, "Error setting RXON_ASSOC "
936                                   "configuration (%d).\n", rc);
937                         return rc;
938                 }
939
940                 memcpy(active_rxon, &priv->staging39_rxon, sizeof(*active_rxon));
941
942                 return 0;
943         }
944
945         /* If we are currently associated and the new config requires
946          * an RXON_ASSOC and the new config wants the associated mask enabled,
947          * we must clear the associated from the active configuration
948          * before we apply the new config */
949         if (iwl3945_is_associated(priv) &&
950             (priv->staging39_rxon.filter_flags & RXON_FILTER_ASSOC_MSK)) {
951                 IWL_DEBUG_INFO("Toggling associated bit on current RXON\n");
952                 active_rxon->filter_flags &= ~RXON_FILTER_ASSOC_MSK;
953
954                 rc = iwl3945_send_cmd_pdu(priv, REPLY_RXON,
955                                       sizeof(struct iwl3945_rxon_cmd),
956                                       &priv->active39_rxon);
957
958                 /* If the mask clearing failed then we set
959                  * active_rxon back to what it was previously */
960                 if (rc) {
961                         active_rxon->filter_flags |= RXON_FILTER_ASSOC_MSK;
962                         IWL_ERR(priv, "Error clearing ASSOC_MSK on current "
963                                   "configuration (%d).\n", rc);
964                         return rc;
965                 }
966         }
967
968         IWL_DEBUG_INFO("Sending RXON\n"
969                        "* with%s RXON_FILTER_ASSOC_MSK\n"
970                        "* channel = %d\n"
971                        "* bssid = %pM\n",
972                        ((priv->staging39_rxon.filter_flags &
973                          RXON_FILTER_ASSOC_MSK) ? "" : "out"),
974                        le16_to_cpu(priv->staging39_rxon.channel),
975                        priv->staging_rxon.bssid_addr);
976
977         /* Apply the new configuration */
978         rc = iwl3945_send_cmd_pdu(priv, REPLY_RXON,
979                               sizeof(struct iwl3945_rxon_cmd), &priv->staging39_rxon);
980         if (rc) {
981                 IWL_ERR(priv, "Error setting new configuration (%d).\n", rc);
982                 return rc;
983         }
984
985         memcpy(active_rxon, &priv->staging39_rxon, sizeof(*active_rxon));
986
987         iwl3945_clear_stations_table(priv);
988
989         /* If we issue a new RXON command which required a tune then we must
990          * send a new TXPOWER command or we won't be able to Tx any frames */
991         rc = iwl3945_hw_reg_send_txpower(priv);
992         if (rc) {
993                 IWL_ERR(priv, "Error setting Tx power (%d).\n", rc);
994                 return rc;
995         }
996
997         /* Add the broadcast address so we can send broadcast frames */
998         if (iwl3945_add_station(priv, iwl_bcast_addr, 0, 0) ==
999             IWL_INVALID_STATION) {
1000                 IWL_ERR(priv, "Error adding BROADCAST address for transmit.\n");
1001                 return -EIO;
1002         }
1003
1004         /* If we have set the ASSOC_MSK and we are in BSS mode then
1005          * add the IWL_AP_ID to the station rate table */
1006         if (iwl3945_is_associated(priv) &&
1007             (priv->iw_mode == NL80211_IFTYPE_STATION))
1008                 if (iwl3945_add_station(priv, priv->active39_rxon.bssid_addr, 1, 0)
1009                     == IWL_INVALID_STATION) {
1010                         IWL_ERR(priv, "Error adding AP address for transmit\n");
1011                         return -EIO;
1012                 }
1013
1014         /* Init the hardware's rate fallback order based on the band */
1015         rc = iwl3945_init_hw_rate_table(priv);
1016         if (rc) {
1017                 IWL_ERR(priv, "Error setting HW rate table: %02X\n", rc);
1018                 return -EIO;
1019         }
1020
1021         return 0;
1022 }
1023
1024 static int iwl3945_send_bt_config(struct iwl_priv *priv)
1025 {
1026         struct iwl_bt_cmd bt_cmd = {
1027                 .flags = 3,
1028                 .lead_time = 0xAA,
1029                 .max_kill = 1,
1030                 .kill_ack_mask = 0,
1031                 .kill_cts_mask = 0,
1032         };
1033
1034         return iwl3945_send_cmd_pdu(priv, REPLY_BT_CONFIG,
1035                                         sizeof(bt_cmd), &bt_cmd);
1036 }
1037
1038 static int iwl3945_send_scan_abort(struct iwl_priv *priv)
1039 {
1040         int rc = 0;
1041         struct iwl_rx_packet *res;
1042         struct iwl_host_cmd cmd = {
1043                 .id = REPLY_SCAN_ABORT_CMD,
1044                 .meta.flags = CMD_WANT_SKB,
1045         };
1046
1047         /* If there isn't a scan actively going on in the hardware
1048          * then we are in between scan bands and not actually
1049          * actively scanning, so don't send the abort command */
1050         if (!test_bit(STATUS_SCAN_HW, &priv->status)) {
1051                 clear_bit(STATUS_SCAN_ABORTING, &priv->status);
1052                 return 0;
1053         }
1054
1055         rc = iwl3945_send_cmd_sync(priv, &cmd);
1056         if (rc) {
1057                 clear_bit(STATUS_SCAN_ABORTING, &priv->status);
1058                 return rc;
1059         }
1060
1061         res = (struct iwl_rx_packet *)cmd.meta.u.skb->data;
1062         if (res->u.status != CAN_ABORT_STATUS) {
1063                 /* The scan abort will return 1 for success or
1064                  * 2 for "failure".  A failure condition can be
1065                  * due to simply not being in an active scan which
1066                  * can occur if we send the scan abort before we
1067                  * the microcode has notified us that a scan is
1068                  * completed. */
1069                 IWL_DEBUG_INFO("SCAN_ABORT returned %d.\n", res->u.status);
1070                 clear_bit(STATUS_SCAN_ABORTING, &priv->status);
1071                 clear_bit(STATUS_SCAN_HW, &priv->status);
1072         }
1073
1074         dev_kfree_skb_any(cmd.meta.u.skb);
1075
1076         return rc;
1077 }
1078
1079 static int iwl3945_add_sta_sync_callback(struct iwl_priv *priv,
1080                                      struct iwl_cmd *cmd, struct sk_buff *skb)
1081 {
1082         struct iwl_rx_packet *res = NULL;
1083
1084         if (!skb) {
1085                 IWL_ERR(priv, "Error: Response NULL in REPLY_ADD_STA.\n");
1086                 return 1;
1087         }
1088
1089         res = (struct iwl_rx_packet *)skb->data;
1090         if (res->hdr.flags & IWL_CMD_FAILED_MSK) {
1091                 IWL_ERR(priv, "Bad return from REPLY_ADD_STA (0x%08X)\n",
1092                           res->hdr.flags);
1093                 return 1;
1094         }
1095
1096         switch (res->u.add_sta.status) {
1097         case ADD_STA_SUCCESS_MSK:
1098                 break;
1099         default:
1100                 break;
1101         }
1102
1103         /* We didn't cache the SKB; let the caller free it */
1104         return 1;
1105 }
1106
1107 int iwl3945_send_add_station(struct iwl_priv *priv,
1108                          struct iwl3945_addsta_cmd *sta, u8 flags)
1109 {
1110         struct iwl_rx_packet *res = NULL;
1111         int rc = 0;
1112         struct iwl_host_cmd cmd = {
1113                 .id = REPLY_ADD_STA,
1114                 .len = sizeof(struct iwl3945_addsta_cmd),
1115                 .meta.flags = flags,
1116                 .data = sta,
1117         };
1118
1119         if (flags & CMD_ASYNC)
1120                 cmd.meta.u.callback = iwl3945_add_sta_sync_callback;
1121         else
1122                 cmd.meta.flags |= CMD_WANT_SKB;
1123
1124         rc = iwl3945_send_cmd(priv, &cmd);
1125
1126         if (rc || (flags & CMD_ASYNC))
1127                 return rc;
1128
1129         res = (struct iwl_rx_packet *)cmd.meta.u.skb->data;
1130         if (res->hdr.flags & IWL_CMD_FAILED_MSK) {
1131                 IWL_ERR(priv, "Bad return from REPLY_ADD_STA (0x%08X)\n",
1132                           res->hdr.flags);
1133                 rc = -EIO;
1134         }
1135
1136         if (rc == 0) {
1137                 switch (res->u.add_sta.status) {
1138                 case ADD_STA_SUCCESS_MSK:
1139                         IWL_DEBUG_INFO("REPLY_ADD_STA PASSED\n");
1140                         break;
1141                 default:
1142                         rc = -EIO;
1143                         IWL_WARN(priv, "REPLY_ADD_STA failed\n");
1144                         break;
1145                 }
1146         }
1147
1148         priv->alloc_rxb_skb--;
1149         dev_kfree_skb_any(cmd.meta.u.skb);
1150
1151         return rc;
1152 }
1153
1154 static int iwl3945_update_sta_key_info(struct iwl_priv *priv,
1155                                    struct ieee80211_key_conf *keyconf,
1156                                    u8 sta_id)
1157 {
1158         unsigned long flags;
1159         __le16 key_flags = 0;
1160
1161         switch (keyconf->alg) {
1162         case ALG_CCMP:
1163                 key_flags |= STA_KEY_FLG_CCMP;
1164                 key_flags |= cpu_to_le16(
1165                                 keyconf->keyidx << STA_KEY_FLG_KEYID_POS);
1166                 key_flags &= ~STA_KEY_FLG_INVALID;
1167                 break;
1168         case ALG_TKIP:
1169         case ALG_WEP:
1170         default:
1171                 return -EINVAL;
1172         }
1173         spin_lock_irqsave(&priv->sta_lock, flags);
1174         priv->stations_39[sta_id].keyinfo.alg = keyconf->alg;
1175         priv->stations_39[sta_id].keyinfo.keylen = keyconf->keylen;
1176         memcpy(priv->stations_39[sta_id].keyinfo.key, keyconf->key,
1177                keyconf->keylen);
1178
1179         memcpy(priv->stations_39[sta_id].sta.key.key, keyconf->key,
1180                keyconf->keylen);
1181         priv->stations_39[sta_id].sta.key.key_flags = key_flags;
1182         priv->stations_39[sta_id].sta.sta.modify_mask = STA_MODIFY_KEY_MASK;
1183         priv->stations_39[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
1184
1185         spin_unlock_irqrestore(&priv->sta_lock, flags);
1186
1187         IWL_DEBUG_INFO("hwcrypto: modify ucode station key info\n");
1188         iwl3945_send_add_station(priv, &priv->stations_39[sta_id].sta, 0);
1189         return 0;
1190 }
1191
1192 static int iwl3945_clear_sta_key_info(struct iwl_priv *priv, u8 sta_id)
1193 {
1194         unsigned long flags;
1195
1196         spin_lock_irqsave(&priv->sta_lock, flags);
1197         memset(&priv->stations_39[sta_id].keyinfo, 0, sizeof(struct iwl3945_hw_key));
1198         memset(&priv->stations_39[sta_id].sta.key, 0,
1199                 sizeof(struct iwl4965_keyinfo));
1200         priv->stations_39[sta_id].sta.key.key_flags = STA_KEY_FLG_NO_ENC;
1201         priv->stations_39[sta_id].sta.sta.modify_mask = STA_MODIFY_KEY_MASK;
1202         priv->stations_39[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
1203         spin_unlock_irqrestore(&priv->sta_lock, flags);
1204
1205         IWL_DEBUG_INFO("hwcrypto: clear ucode station key info\n");
1206         iwl3945_send_add_station(priv, &priv->stations_39[sta_id].sta, 0);
1207         return 0;
1208 }
1209
1210 static void iwl3945_clear_free_frames(struct iwl_priv *priv)
1211 {
1212         struct list_head *element;
1213
1214         IWL_DEBUG_INFO("%d frames on pre-allocated heap on clear.\n",
1215                        priv->frames_count);
1216
1217         while (!list_empty(&priv->free_frames)) {
1218                 element = priv->free_frames.next;
1219                 list_del(element);
1220                 kfree(list_entry(element, struct iwl3945_frame, list));
1221                 priv->frames_count--;
1222         }
1223
1224         if (priv->frames_count) {
1225                 IWL_WARN(priv, "%d frames still in use.  Did we lose one?\n",
1226                             priv->frames_count);
1227                 priv->frames_count = 0;
1228         }
1229 }
1230
1231 static struct iwl3945_frame *iwl3945_get_free_frame(struct iwl_priv *priv)
1232 {
1233         struct iwl3945_frame *frame;
1234         struct list_head *element;
1235         if (list_empty(&priv->free_frames)) {
1236                 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1237                 if (!frame) {
1238                         IWL_ERR(priv, "Could not allocate frame!\n");
1239                         return NULL;
1240                 }
1241
1242                 priv->frames_count++;
1243                 return frame;
1244         }
1245
1246         element = priv->free_frames.next;
1247         list_del(element);
1248         return list_entry(element, struct iwl3945_frame, list);
1249 }
1250
1251 static void iwl3945_free_frame(struct iwl_priv *priv, struct iwl3945_frame *frame)
1252 {
1253         memset(frame, 0, sizeof(*frame));
1254         list_add(&frame->list, &priv->free_frames);
1255 }
1256
1257 unsigned int iwl3945_fill_beacon_frame(struct iwl_priv *priv,
1258                                 struct ieee80211_hdr *hdr,
1259                                 int left)
1260 {
1261
1262         if (!iwl3945_is_associated(priv) || !priv->ibss_beacon ||
1263             ((priv->iw_mode != NL80211_IFTYPE_ADHOC) &&
1264              (priv->iw_mode != NL80211_IFTYPE_AP)))
1265                 return 0;
1266
1267         if (priv->ibss_beacon->len > left)
1268                 return 0;
1269
1270         memcpy(hdr, priv->ibss_beacon->data, priv->ibss_beacon->len);
1271
1272         return priv->ibss_beacon->len;
1273 }
1274
1275 static u8 iwl3945_rate_get_lowest_plcp(struct iwl_priv *priv)
1276 {
1277         u8 i;
1278         int rate_mask;
1279
1280         /* Set rate mask*/
1281         if (priv->staging39_rxon.flags & RXON_FLG_BAND_24G_MSK)
1282                 rate_mask = priv->active_rate_basic & IWL_CCK_RATES_MASK;
1283         else
1284                 rate_mask = priv->active_rate_basic & IWL_OFDM_RATES_MASK;
1285
1286         for (i = IWL_RATE_1M_INDEX; i != IWL_RATE_INVALID;
1287              i = iwl3945_rates[i].next_ieee) {
1288                 if (rate_mask & (1 << i))
1289                         return iwl3945_rates[i].plcp;
1290         }
1291
1292         /* No valid rate was found. Assign the lowest one */
1293         if (priv->staging39_rxon.flags & RXON_FLG_BAND_24G_MSK)
1294                 return IWL_RATE_1M_PLCP;
1295         else
1296                 return IWL_RATE_6M_PLCP;
1297 }
1298
1299 static int iwl3945_send_beacon_cmd(struct iwl_priv *priv)
1300 {
1301         struct iwl3945_frame *frame;
1302         unsigned int frame_size;
1303         int rc;
1304         u8 rate;
1305
1306         frame = iwl3945_get_free_frame(priv);
1307
1308         if (!frame) {
1309                 IWL_ERR(priv, "Could not obtain free frame buffer for beacon "
1310                           "command.\n");
1311                 return -ENOMEM;
1312         }
1313
1314         rate = iwl3945_rate_get_lowest_plcp(priv);
1315
1316         frame_size = iwl3945_hw_get_beacon_cmd(priv, frame, rate);
1317
1318         rc = iwl3945_send_cmd_pdu(priv, REPLY_TX_BEACON, frame_size,
1319                               &frame->u.cmd[0]);
1320
1321         iwl3945_free_frame(priv, frame);
1322
1323         return rc;
1324 }
1325
1326 /******************************************************************************
1327  *
1328  * EEPROM related functions
1329  *
1330  ******************************************************************************/
1331
1332 static void get_eeprom_mac(struct iwl_priv *priv, u8 *mac)
1333 {
1334         memcpy(mac, priv->eeprom39.mac_address, 6);
1335 }
1336
1337 /*
1338  * Clear the OWNER_MSK, to establish driver (instead of uCode running on
1339  * embedded controller) as EEPROM reader; each read is a series of pulses
1340  * to/from the EEPROM chip, not a single event, so even reads could conflict
1341  * if they weren't arbitrated by some ownership mechanism.  Here, the driver
1342  * simply claims ownership, which should be safe when this function is called
1343  * (i.e. before loading uCode!).
1344  */
1345 static inline int iwl3945_eeprom_acquire_semaphore(struct iwl_priv *priv)
1346 {
1347         _iwl_clear_bit(priv, CSR_EEPROM_GP, CSR_EEPROM_GP_IF_OWNER_MSK);
1348         return 0;
1349 }
1350
1351 /**
1352  * iwl3945_eeprom_init - read EEPROM contents
1353  *
1354  * Load the EEPROM contents from adapter into priv->eeprom39
1355  *
1356  * NOTE:  This routine uses the non-debug IO access functions.
1357  */
1358 int iwl3945_eeprom_init(struct iwl_priv *priv)
1359 {
1360         u16 *e = (u16 *)&priv->eeprom39;
1361         u32 gp = iwl_read32(priv, CSR_EEPROM_GP);
1362         int sz = sizeof(priv->eeprom39);
1363         int ret;
1364         u16 addr;
1365
1366         /* The EEPROM structure has several padding buffers within it
1367          * and when adding new EEPROM maps is subject to programmer errors
1368          * which may be very difficult to identify without explicitly
1369          * checking the resulting size of the eeprom map. */
1370         BUILD_BUG_ON(sizeof(priv->eeprom39) != IWL_EEPROM_IMAGE_SIZE);
1371
1372         if ((gp & CSR_EEPROM_GP_VALID_MSK) == CSR_EEPROM_GP_BAD_SIGNATURE) {
1373                 IWL_ERR(priv, "EEPROM not found, EEPROM_GP=0x%08x\n", gp);
1374                 return -ENOENT;
1375         }
1376
1377         /* Make sure driver (instead of uCode) is allowed to read EEPROM */
1378         ret = iwl3945_eeprom_acquire_semaphore(priv);
1379         if (ret < 0) {
1380                 IWL_ERR(priv, "Failed to acquire EEPROM semaphore.\n");
1381                 return -ENOENT;
1382         }
1383
1384         /* eeprom is an array of 16bit values */
1385         for (addr = 0; addr < sz; addr += sizeof(u16)) {
1386                 u32 r;
1387
1388                 _iwl_write32(priv, CSR_EEPROM_REG,
1389                                  CSR_EEPROM_REG_MSK_ADDR & (addr << 1));
1390                 _iwl_clear_bit(priv, CSR_EEPROM_REG, CSR_EEPROM_REG_BIT_CMD);
1391                 ret = iwl_poll_direct_bit(priv, CSR_EEPROM_REG,
1392                                               CSR_EEPROM_REG_READ_VALID_MSK,
1393                                               IWL_EEPROM_ACCESS_TIMEOUT);
1394                 if (ret < 0) {
1395                         IWL_ERR(priv, "Time out reading EEPROM[%d]\n", addr);
1396                         return ret;
1397                 }
1398
1399                 r = _iwl_read_direct32(priv, CSR_EEPROM_REG);
1400                 e[addr / 2] = le16_to_cpu((__force __le16)(r >> 16));
1401         }
1402
1403         return 0;
1404 }
1405
1406 static void iwl3945_unset_hw_params(struct iwl_priv *priv)
1407 {
1408         if (priv->shared_virt)
1409                 pci_free_consistent(priv->pci_dev,
1410                                     sizeof(struct iwl3945_shared),
1411                                     priv->shared_virt,
1412                                     priv->shared_phys);
1413 }
1414
1415 /**
1416  * iwl3945_supported_rate_to_ie - fill in the supported rate in IE field
1417  *
1418  * return : set the bit for each supported rate insert in ie
1419  */
1420 static u16 iwl3945_supported_rate_to_ie(u8 *ie, u16 supported_rate,
1421                                     u16 basic_rate, int *left)
1422 {
1423         u16 ret_rates = 0, bit;
1424         int i;
1425         u8 *cnt = ie;
1426         u8 *rates = ie + 1;
1427
1428         for (bit = 1, i = 0; i < IWL_RATE_COUNT; i++, bit <<= 1) {
1429                 if (bit & supported_rate) {
1430                         ret_rates |= bit;
1431                         rates[*cnt] = iwl3945_rates[i].ieee |
1432                                 ((bit & basic_rate) ? 0x80 : 0x00);
1433                         (*cnt)++;
1434                         (*left)--;
1435                         if ((*left <= 0) ||
1436                             (*cnt >= IWL_SUPPORTED_RATES_IE_LEN))
1437                                 break;
1438                 }
1439         }
1440
1441         return ret_rates;
1442 }
1443
1444 /**
1445  * iwl3945_fill_probe_req - fill in all required fields and IE for probe request
1446  */
1447 static u16 iwl3945_fill_probe_req(struct iwl_priv *priv,
1448                               struct ieee80211_mgmt *frame,
1449                               int left)
1450 {
1451         int len = 0;
1452         u8 *pos = NULL;
1453         u16 active_rates, ret_rates, cck_rates;
1454
1455         /* Make sure there is enough space for the probe request,
1456          * two mandatory IEs and the data */
1457         left -= 24;
1458         if (left < 0)
1459                 return 0;
1460         len += 24;
1461
1462         frame->frame_control = cpu_to_le16(IEEE80211_STYPE_PROBE_REQ);
1463         memcpy(frame->da, iwl_bcast_addr, ETH_ALEN);
1464         memcpy(frame->sa, priv->mac_addr, ETH_ALEN);
1465         memcpy(frame->bssid, iwl_bcast_addr, ETH_ALEN);
1466         frame->seq_ctrl = 0;
1467
1468         /* fill in our indirect SSID IE */
1469         /* ...next IE... */
1470
1471         left -= 2;
1472         if (left < 0)
1473                 return 0;
1474         len += 2;
1475         pos = &(frame->u.probe_req.variable[0]);
1476         *pos++ = WLAN_EID_SSID;
1477         *pos++ = 0;
1478
1479         /* fill in supported rate */
1480         /* ...next IE... */
1481         left -= 2;
1482         if (left < 0)
1483                 return 0;
1484
1485         /* ... fill it in... */
1486         *pos++ = WLAN_EID_SUPP_RATES;
1487         *pos = 0;
1488
1489         priv->active_rate = priv->rates_mask;
1490         active_rates = priv->active_rate;
1491         priv->active_rate_basic = priv->rates_mask & IWL_BASIC_RATES_MASK;
1492
1493         cck_rates = IWL_CCK_RATES_MASK & active_rates;
1494         ret_rates = iwl3945_supported_rate_to_ie(pos, cck_rates,
1495                         priv->active_rate_basic, &left);
1496         active_rates &= ~ret_rates;
1497
1498         ret_rates = iwl3945_supported_rate_to_ie(pos, active_rates,
1499                                  priv->active_rate_basic, &left);
1500         active_rates &= ~ret_rates;
1501
1502         len += 2 + *pos;
1503         pos += (*pos) + 1;
1504         if (active_rates == 0)
1505                 goto fill_end;
1506
1507         /* fill in supported extended rate */
1508         /* ...next IE... */
1509         left -= 2;
1510         if (left < 0)
1511                 return 0;
1512         /* ... fill it in... */
1513         *pos++ = WLAN_EID_EXT_SUPP_RATES;
1514         *pos = 0;
1515         iwl3945_supported_rate_to_ie(pos, active_rates,
1516                                  priv->active_rate_basic, &left);
1517         if (*pos > 0)
1518                 len += 2 + *pos;
1519
1520  fill_end:
1521         return (u16)len;
1522 }
1523
1524 /*
1525  * QoS  support
1526 */
1527 static int iwl3945_send_qos_params_command(struct iwl_priv *priv,
1528                                        struct iwl_qosparam_cmd *qos)
1529 {
1530
1531         return iwl3945_send_cmd_pdu(priv, REPLY_QOS_PARAM,
1532                                 sizeof(struct iwl_qosparam_cmd), qos);
1533 }
1534
1535 static void iwl3945_activate_qos(struct iwl_priv *priv, u8 force)
1536 {
1537         unsigned long flags;
1538
1539         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
1540                 return;
1541
1542         spin_lock_irqsave(&priv->lock, flags);
1543         priv->qos_data.def_qos_parm.qos_flags = 0;
1544
1545         if (priv->qos_data.qos_cap.q_AP.queue_request &&
1546             !priv->qos_data.qos_cap.q_AP.txop_request)
1547                 priv->qos_data.def_qos_parm.qos_flags |=
1548                         QOS_PARAM_FLG_TXOP_TYPE_MSK;
1549
1550         if (priv->qos_data.qos_active)
1551                 priv->qos_data.def_qos_parm.qos_flags |=
1552                         QOS_PARAM_FLG_UPDATE_EDCA_MSK;
1553
1554         spin_unlock_irqrestore(&priv->lock, flags);
1555
1556         if (force || iwl3945_is_associated(priv)) {
1557                 IWL_DEBUG_QOS("send QoS cmd with QoS active %d \n",
1558                               priv->qos_data.qos_active);
1559
1560                 iwl3945_send_qos_params_command(priv,
1561                                 &(priv->qos_data.def_qos_parm));
1562         }
1563 }
1564
1565 /*
1566  * Power management (not Tx power!) functions
1567  */
1568 #define MSEC_TO_USEC 1024
1569
1570
1571 #define NOSLP __constant_cpu_to_le16(0), 0, 0
1572 #define SLP IWL_POWER_DRIVER_ALLOW_SLEEP_MSK, 0, 0
1573 #define SLP_TIMEOUT(T) __constant_cpu_to_le32((T) * MSEC_TO_USEC)
1574 #define SLP_VEC(X0, X1, X2, X3, X4) {__constant_cpu_to_le32(X0), \
1575                                      __constant_cpu_to_le32(X1), \
1576                                      __constant_cpu_to_le32(X2), \
1577                                      __constant_cpu_to_le32(X3), \
1578                                      __constant_cpu_to_le32(X4)}
1579
1580 /* default power management (not Tx power) table values */
1581 /* for TIM  0-10 */
1582 static struct iwl_power_vec_entry range_0[IWL39_POWER_AC] = {
1583         {{NOSLP, SLP_TIMEOUT(0), SLP_TIMEOUT(0), SLP_VEC(0, 0, 0, 0, 0)}, 0},
1584         {{SLP, SLP_TIMEOUT(200), SLP_TIMEOUT(500), SLP_VEC(1, 2, 3, 4, 4)}, 0},
1585         {{SLP, SLP_TIMEOUT(200), SLP_TIMEOUT(300), SLP_VEC(2, 4, 6, 7, 7)}, 0},
1586         {{SLP, SLP_TIMEOUT(50), SLP_TIMEOUT(100), SLP_VEC(2, 6, 9, 9, 10)}, 0},
1587         {{SLP, SLP_TIMEOUT(50), SLP_TIMEOUT(25), SLP_VEC(2, 7, 9, 9, 10)}, 1},
1588         {{SLP, SLP_TIMEOUT(25), SLP_TIMEOUT(25), SLP_VEC(4, 7, 10, 10, 10)}, 1}
1589 };
1590
1591 /* for TIM > 10 */
1592 static struct iwl_power_vec_entry range_1[IWL39_POWER_AC] = {
1593         {{NOSLP, SLP_TIMEOUT(0), SLP_TIMEOUT(0), SLP_VEC(0, 0, 0, 0, 0)}, 0},
1594         {{SLP, SLP_TIMEOUT(200), SLP_TIMEOUT(500),
1595                  SLP_VEC(1, 2, 3, 4, 0xFF)}, 0},
1596         {{SLP, SLP_TIMEOUT(200), SLP_TIMEOUT(300),
1597                  SLP_VEC(2, 4, 6, 7, 0xFF)}, 0},
1598         {{SLP, SLP_TIMEOUT(50), SLP_TIMEOUT(100),
1599                  SLP_VEC(2, 6, 9, 9, 0xFF)}, 0},
1600         {{SLP, SLP_TIMEOUT(50), SLP_TIMEOUT(25), SLP_VEC(2, 7, 9, 9, 0xFF)}, 0},
1601         {{SLP, SLP_TIMEOUT(25), SLP_TIMEOUT(25),
1602                  SLP_VEC(4, 7, 10, 10, 0xFF)}, 0}
1603 };
1604
1605 int iwl3945_power_init_handle(struct iwl_priv *priv)
1606 {
1607         int rc = 0, i;
1608         struct iwl3945_power_mgr *pow_data;
1609         int size = sizeof(struct iwl_power_vec_entry) * IWL39_POWER_AC;
1610         u16 pci_pm;
1611
1612         IWL_DEBUG_POWER("Initialize power \n");
1613
1614         pow_data = &(priv->power_data_39);
1615
1616         memset(pow_data, 0, sizeof(*pow_data));
1617
1618         pow_data->active_index = IWL_POWER_RANGE_0;
1619         pow_data->dtim_val = 0xffff;
1620
1621         memcpy(&pow_data->pwr_range_0[0], &range_0[0], size);
1622         memcpy(&pow_data->pwr_range_1[0], &range_1[0], size);
1623
1624         rc = pci_read_config_word(priv->pci_dev, PCI_LINK_CTRL, &pci_pm);
1625         if (rc != 0)
1626                 return 0;
1627         else {
1628                 struct iwl_powertable_cmd *cmd;
1629
1630                 IWL_DEBUG_POWER("adjust power command flags\n");
1631
1632                 for (i = 0; i < IWL39_POWER_AC; i++) {
1633                         cmd = &pow_data->pwr_range_0[i].cmd;
1634
1635                         if (pci_pm & 0x1)
1636                                 cmd->flags &= ~IWL_POWER_PCI_PM_MSK;
1637                         else
1638                                 cmd->flags |= IWL_POWER_PCI_PM_MSK;
1639                 }
1640         }
1641         return rc;
1642 }
1643
1644 static int iwl3945_update_power_cmd(struct iwl_priv *priv,
1645                                 struct iwl_powertable_cmd *cmd, u32 mode)
1646 {
1647         int rc = 0, i;
1648         u8 skip;
1649         u32 max_sleep = 0;
1650         struct iwl_power_vec_entry *range;
1651         u8 period = 0;
1652         struct iwl3945_power_mgr *pow_data;
1653
1654         if (mode > IWL_POWER_INDEX_5) {
1655                 IWL_DEBUG_POWER("Error invalid power mode \n");
1656                 return -1;
1657         }
1658         pow_data = &(priv->power_data_39);
1659
1660         if (pow_data->active_index == IWL_POWER_RANGE_0)
1661                 range = &pow_data->pwr_range_0[0];
1662         else
1663                 range = &pow_data->pwr_range_1[1];
1664
1665         memcpy(cmd, &range[mode].cmd, sizeof(struct iwl3945_powertable_cmd));
1666
1667 #ifdef IWL_MAC80211_DISABLE
1668         if (priv->assoc_network != NULL) {
1669                 unsigned long flags;
1670
1671                 period = priv->assoc_network->tim.tim_period;
1672         }
1673 #endif  /*IWL_MAC80211_DISABLE */
1674         skip = range[mode].no_dtim;
1675
1676         if (period == 0) {
1677                 period = 1;
1678                 skip = 0;
1679         }
1680
1681         if (skip == 0) {
1682                 max_sleep = period;
1683                 cmd->flags &= ~IWL_POWER_SLEEP_OVER_DTIM_MSK;
1684         } else {
1685                 __le32 slp_itrvl = cmd->sleep_interval[IWL_POWER_VEC_SIZE - 1];
1686                 max_sleep = (le32_to_cpu(slp_itrvl) / period) * period;
1687                 cmd->flags |= IWL_POWER_SLEEP_OVER_DTIM_MSK;
1688         }
1689
1690         for (i = 0; i < IWL_POWER_VEC_SIZE; i++) {
1691                 if (le32_to_cpu(cmd->sleep_interval[i]) > max_sleep)
1692                         cmd->sleep_interval[i] = cpu_to_le32(max_sleep);
1693         }
1694
1695         IWL_DEBUG_POWER("Flags value = 0x%08X\n", cmd->flags);
1696         IWL_DEBUG_POWER("Tx timeout = %u\n", le32_to_cpu(cmd->tx_data_timeout));
1697         IWL_DEBUG_POWER("Rx timeout = %u\n", le32_to_cpu(cmd->rx_data_timeout));
1698         IWL_DEBUG_POWER("Sleep interval vector = { %d , %d , %d , %d , %d }\n",
1699                         le32_to_cpu(cmd->sleep_interval[0]),
1700                         le32_to_cpu(cmd->sleep_interval[1]),
1701                         le32_to_cpu(cmd->sleep_interval[2]),
1702                         le32_to_cpu(cmd->sleep_interval[3]),
1703                         le32_to_cpu(cmd->sleep_interval[4]));
1704
1705         return rc;
1706 }
1707
1708 static int iwl3945_send_power_mode(struct iwl_priv *priv, u32 mode)
1709 {
1710         u32 uninitialized_var(final_mode);
1711         int rc;
1712         struct iwl_powertable_cmd cmd;
1713
1714         /* If on battery, set to 3,
1715          * if plugged into AC power, set to CAM ("continuously aware mode"),
1716          * else user level */
1717         switch (mode) {
1718         case IWL39_POWER_BATTERY:
1719                 final_mode = IWL_POWER_INDEX_3;
1720                 break;
1721         case IWL39_POWER_AC:
1722                 final_mode = IWL_POWER_MODE_CAM;
1723                 break;
1724         default:
1725                 final_mode = mode;
1726                 break;
1727         }
1728
1729         iwl3945_update_power_cmd(priv, &cmd, final_mode);
1730
1731         /* FIXME use get_hcmd_size 3945 command is 4 bytes shorter */
1732         rc = iwl3945_send_cmd_pdu(priv, POWER_TABLE_CMD,
1733                                 sizeof(struct iwl3945_powertable_cmd), &cmd);
1734
1735         if (final_mode == IWL_POWER_MODE_CAM)
1736                 clear_bit(STATUS_POWER_PMI, &priv->status);
1737         else
1738                 set_bit(STATUS_POWER_PMI, &priv->status);
1739
1740         return rc;
1741 }
1742
1743 /**
1744  * iwl3945_scan_cancel - Cancel any currently executing HW scan
1745  *
1746  * NOTE: priv->mutex is not required before calling this function
1747  */
1748 static int iwl3945_scan_cancel(struct iwl_priv *priv)
1749 {
1750         if (!test_bit(STATUS_SCAN_HW, &priv->status)) {
1751                 clear_bit(STATUS_SCANNING, &priv->status);
1752                 return 0;
1753         }
1754
1755         if (test_bit(STATUS_SCANNING, &priv->status)) {
1756                 if (!test_bit(STATUS_SCAN_ABORTING, &priv->status)) {
1757                         IWL_DEBUG_SCAN("Queuing scan abort.\n");
1758                         set_bit(STATUS_SCAN_ABORTING, &priv->status);
1759                         queue_work(priv->workqueue, &priv->abort_scan);
1760
1761                 } else
1762                         IWL_DEBUG_SCAN("Scan abort already in progress.\n");
1763
1764                 return test_bit(STATUS_SCANNING, &priv->status);
1765         }
1766
1767         return 0;
1768 }
1769
1770 /**
1771  * iwl3945_scan_cancel_timeout - Cancel any currently executing HW scan
1772  * @ms: amount of time to wait (in milliseconds) for scan to abort
1773  *
1774  * NOTE: priv->mutex must be held before calling this function
1775  */
1776 static int iwl3945_scan_cancel_timeout(struct iwl_priv *priv, unsigned long ms)
1777 {
1778         unsigned long now = jiffies;
1779         int ret;
1780
1781         ret = iwl3945_scan_cancel(priv);
1782         if (ret && ms) {
1783                 mutex_unlock(&priv->mutex);
1784                 while (!time_after(jiffies, now + msecs_to_jiffies(ms)) &&
1785                                 test_bit(STATUS_SCANNING, &priv->status))
1786                         msleep(1);
1787                 mutex_lock(&priv->mutex);
1788
1789                 return test_bit(STATUS_SCANNING, &priv->status);
1790         }
1791
1792         return ret;
1793 }
1794
1795 #define MAX_UCODE_BEACON_INTERVAL       1024
1796 #define INTEL_CONN_LISTEN_INTERVAL      __constant_cpu_to_le16(0xA)
1797
1798 static __le16 iwl3945_adjust_beacon_interval(u16 beacon_val)
1799 {
1800         u16 new_val = 0;
1801         u16 beacon_factor = 0;
1802
1803         beacon_factor =
1804             (beacon_val + MAX_UCODE_BEACON_INTERVAL)
1805                 / MAX_UCODE_BEACON_INTERVAL;
1806         new_val = beacon_val / beacon_factor;
1807
1808         return cpu_to_le16(new_val);
1809 }
1810
1811 static void iwl3945_setup_rxon_timing(struct iwl_priv *priv)
1812 {
1813         u64 interval_tm_unit;
1814         u64 tsf, result;
1815         unsigned long flags;
1816         struct ieee80211_conf *conf = NULL;
1817         u16 beacon_int = 0;
1818
1819         conf = ieee80211_get_hw_conf(priv->hw);
1820
1821         spin_lock_irqsave(&priv->lock, flags);
1822         priv->rxon_timing.timestamp = cpu_to_le64(priv->timestamp);
1823         priv->rxon_timing.listen_interval = INTEL_CONN_LISTEN_INTERVAL;
1824
1825         tsf = priv->timestamp;
1826
1827         beacon_int = priv->beacon_int;
1828         spin_unlock_irqrestore(&priv->lock, flags);
1829
1830         if (priv->iw_mode == NL80211_IFTYPE_STATION) {
1831                 if (beacon_int == 0) {
1832                         priv->rxon_timing.beacon_interval = cpu_to_le16(100);
1833                         priv->rxon_timing.beacon_init_val = cpu_to_le32(102400);
1834                 } else {
1835                         priv->rxon_timing.beacon_interval =
1836                                 cpu_to_le16(beacon_int);
1837                         priv->rxon_timing.beacon_interval =
1838                             iwl3945_adjust_beacon_interval(
1839                                 le16_to_cpu(priv->rxon_timing.beacon_interval));
1840                 }
1841
1842                 priv->rxon_timing.atim_window = 0;
1843         } else {
1844                 priv->rxon_timing.beacon_interval =
1845                         iwl3945_adjust_beacon_interval(conf->beacon_int);
1846                 /* TODO: we need to get atim_window from upper stack
1847                  * for now we set to 0 */
1848                 priv->rxon_timing.atim_window = 0;
1849         }
1850
1851         interval_tm_unit =
1852                 (le16_to_cpu(priv->rxon_timing.beacon_interval) * 1024);
1853         result = do_div(tsf, interval_tm_unit);
1854         priv->rxon_timing.beacon_init_val =
1855             cpu_to_le32((u32) ((u64) interval_tm_unit - result));
1856
1857         IWL_DEBUG_ASSOC
1858             ("beacon interval %d beacon timer %d beacon tim %d\n",
1859                 le16_to_cpu(priv->rxon_timing.beacon_interval),
1860                 le32_to_cpu(priv->rxon_timing.beacon_init_val),
1861                 le16_to_cpu(priv->rxon_timing.atim_window));
1862 }
1863
1864 static int iwl3945_scan_initiate(struct iwl_priv *priv)
1865 {
1866         if (!iwl_is_ready_rf(priv)) {
1867                 IWL_DEBUG_SCAN("Aborting scan due to not ready.\n");
1868                 return -EIO;
1869         }
1870
1871         if (test_bit(STATUS_SCANNING, &priv->status)) {
1872                 IWL_DEBUG_SCAN("Scan already in progress.\n");
1873                 return -EAGAIN;
1874         }
1875
1876         if (test_bit(STATUS_SCAN_ABORTING, &priv->status)) {
1877                 IWL_DEBUG_SCAN("Scan request while abort pending.  "
1878                                "Queuing.\n");
1879                 return -EAGAIN;
1880         }
1881
1882         IWL_DEBUG_INFO("Starting scan...\n");
1883         if (priv->cfg->sku & IWL_SKU_G)
1884                 priv->scan_bands |= BIT(IEEE80211_BAND_2GHZ);
1885         if (priv->cfg->sku & IWL_SKU_A)
1886                 priv->scan_bands |= BIT(IEEE80211_BAND_5GHZ);
1887         set_bit(STATUS_SCANNING, &priv->status);
1888         priv->scan_start = jiffies;
1889         priv->scan_pass_start = priv->scan_start;
1890
1891         queue_work(priv->workqueue, &priv->request_scan);
1892
1893         return 0;
1894 }
1895
1896 static int iwl3945_set_rxon_hwcrypto(struct iwl_priv *priv, int hw_decrypt)
1897 {
1898         struct iwl3945_rxon_cmd *rxon = &priv->staging39_rxon;
1899
1900         if (hw_decrypt)
1901                 rxon->filter_flags &= ~RXON_FILTER_DIS_DECRYPT_MSK;
1902         else
1903                 rxon->filter_flags |= RXON_FILTER_DIS_DECRYPT_MSK;
1904
1905         return 0;
1906 }
1907
1908 static void iwl3945_set_flags_for_phymode(struct iwl_priv *priv,
1909                                           enum ieee80211_band band)
1910 {
1911         if (band == IEEE80211_BAND_5GHZ) {
1912                 priv->staging39_rxon.flags &=
1913                     ~(RXON_FLG_BAND_24G_MSK | RXON_FLG_AUTO_DETECT_MSK
1914                       | RXON_FLG_CCK_MSK);
1915                 priv->staging39_rxon.flags |= RXON_FLG_SHORT_SLOT_MSK;
1916         } else {
1917                 /* Copied from iwl3945_bg_post_associate() */
1918                 if (priv->assoc_capability & WLAN_CAPABILITY_SHORT_SLOT_TIME)
1919                         priv->staging39_rxon.flags |= RXON_FLG_SHORT_SLOT_MSK;
1920                 else
1921                         priv->staging39_rxon.flags &= ~RXON_FLG_SHORT_SLOT_MSK;
1922
1923                 if (priv->iw_mode == NL80211_IFTYPE_ADHOC)
1924                         priv->staging39_rxon.flags &= ~RXON_FLG_SHORT_SLOT_MSK;
1925
1926                 priv->staging39_rxon.flags |= RXON_FLG_BAND_24G_MSK;
1927                 priv->staging39_rxon.flags |= RXON_FLG_AUTO_DETECT_MSK;
1928                 priv->staging39_rxon.flags &= ~RXON_FLG_CCK_MSK;
1929         }
1930 }
1931
1932 /*
1933  * initialize rxon structure with default values from eeprom
1934  */
1935 static void iwl3945_connection_init_rx_config(struct iwl_priv *priv,
1936                                               int mode)
1937 {
1938         const struct iwl_channel_info *ch_info;
1939
1940         memset(&priv->staging39_rxon, 0, sizeof(priv->staging39_rxon));
1941
1942         switch (mode) {
1943         case NL80211_IFTYPE_AP:
1944                 priv->staging39_rxon.dev_type = RXON_DEV_TYPE_AP;
1945                 break;
1946
1947         case NL80211_IFTYPE_STATION:
1948                 priv->staging39_rxon.dev_type = RXON_DEV_TYPE_ESS;
1949                 priv->staging39_rxon.filter_flags = RXON_FILTER_ACCEPT_GRP_MSK;
1950                 break;
1951
1952         case NL80211_IFTYPE_ADHOC:
1953                 priv->staging39_rxon.dev_type = RXON_DEV_TYPE_IBSS;
1954                 priv->staging39_rxon.flags = RXON_FLG_SHORT_PREAMBLE_MSK;
1955                 priv->staging39_rxon.filter_flags = RXON_FILTER_BCON_AWARE_MSK |
1956                                                   RXON_FILTER_ACCEPT_GRP_MSK;
1957                 break;
1958
1959         case NL80211_IFTYPE_MONITOR:
1960                 priv->staging39_rxon.dev_type = RXON_DEV_TYPE_SNIFFER;
1961                 priv->staging39_rxon.filter_flags = RXON_FILTER_PROMISC_MSK |
1962                     RXON_FILTER_CTL2HOST_MSK | RXON_FILTER_ACCEPT_GRP_MSK;
1963                 break;
1964         default:
1965                 IWL_ERR(priv, "Unsupported interface type %d\n", mode);
1966                 break;
1967         }
1968
1969 #if 0
1970         /* TODO:  Figure out when short_preamble would be set and cache from
1971          * that */
1972         if (!hw_to_local(priv->hw)->short_preamble)
1973                 priv->staging39_rxon.flags &= ~RXON_FLG_SHORT_PREAMBLE_MSK;
1974         else
1975                 priv->staging39_rxon.flags |= RXON_FLG_SHORT_PREAMBLE_MSK;
1976 #endif
1977
1978         ch_info = iwl3945_get_channel_info(priv, priv->band,
1979                                        le16_to_cpu(priv->active39_rxon.channel));
1980
1981         if (!ch_info)
1982                 ch_info = &priv->channel_info[0];
1983
1984         /*
1985          * in some case A channels are all non IBSS
1986          * in this case force B/G channel
1987          */
1988         if ((mode == NL80211_IFTYPE_ADHOC) && !(is_channel_ibss(ch_info)))
1989                 ch_info = &priv->channel_info[0];
1990
1991         priv->staging39_rxon.channel = cpu_to_le16(ch_info->channel);
1992         if (is_channel_a_band(ch_info))
1993                 priv->band = IEEE80211_BAND_5GHZ;
1994         else
1995                 priv->band = IEEE80211_BAND_2GHZ;
1996
1997         iwl3945_set_flags_for_phymode(priv, priv->band);
1998
1999         priv->staging39_rxon.ofdm_basic_rates =
2000             (IWL_OFDM_RATES_MASK >> IWL_FIRST_OFDM_RATE) & 0xFF;
2001         priv->staging39_rxon.cck_basic_rates =
2002             (IWL_CCK_RATES_MASK >> IWL_FIRST_CCK_RATE) & 0xF;
2003 }
2004
2005 static int iwl3945_set_mode(struct iwl_priv *priv, int mode)
2006 {
2007         if (mode == NL80211_IFTYPE_ADHOC) {
2008                 const struct iwl_channel_info *ch_info;
2009
2010                 ch_info = iwl3945_get_channel_info(priv,
2011                         priv->band,
2012                         le16_to_cpu(priv->staging39_rxon.channel));
2013
2014                 if (!ch_info || !is_channel_ibss(ch_info)) {
2015                         IWL_ERR(priv, "channel %d not IBSS channel\n",
2016                                   le16_to_cpu(priv->staging39_rxon.channel));
2017                         return -EINVAL;
2018                 }
2019         }
2020
2021         iwl3945_connection_init_rx_config(priv, mode);
2022         memcpy(priv->staging39_rxon.node_addr, priv->mac_addr, ETH_ALEN);
2023
2024         iwl3945_clear_stations_table(priv);
2025
2026         /* don't commit rxon if rf-kill is on*/
2027         if (!iwl_is_ready_rf(priv))
2028                 return -EAGAIN;
2029
2030         cancel_delayed_work(&priv->scan_check);
2031         if (iwl3945_scan_cancel_timeout(priv, 100)) {
2032                 IWL_WARN(priv, "Aborted scan still in progress after 100ms\n");
2033                 IWL_DEBUG_MAC80211("leaving - scan abort failed.\n");
2034                 return -EAGAIN;
2035         }
2036
2037         iwl3945_commit_rxon(priv);
2038
2039         return 0;
2040 }
2041
2042 static void iwl3945_build_tx_cmd_hwcrypto(struct iwl_priv *priv,
2043                                       struct ieee80211_tx_info *info,
2044                                       struct iwl_cmd *cmd,
2045                                       struct sk_buff *skb_frag,
2046                                       int last_frag)
2047 {
2048         struct iwl3945_tx_cmd *tx = (struct iwl3945_tx_cmd *)cmd->cmd.payload;
2049         struct iwl3945_hw_key *keyinfo =
2050             &priv->stations_39[info->control.hw_key->hw_key_idx].keyinfo;
2051
2052         switch (keyinfo->alg) {
2053         case ALG_CCMP:
2054                 tx->sec_ctl = TX_CMD_SEC_CCM;
2055                 memcpy(tx->key, keyinfo->key, keyinfo->keylen);
2056                 IWL_DEBUG_TX("tx_cmd with AES hwcrypto\n");
2057                 break;
2058
2059         case ALG_TKIP:
2060 #if 0
2061                 tx->sec_ctl = TX_CMD_SEC_TKIP;
2062
2063                 if (last_frag)
2064                         memcpy(tx->tkip_mic.byte, skb_frag->tail - 8,
2065                                8);
2066                 else
2067                         memset(tx->tkip_mic.byte, 0, 8);
2068 #endif
2069                 break;
2070
2071         case ALG_WEP:
2072                 tx->sec_ctl = TX_CMD_SEC_WEP |
2073                     (info->control.hw_key->hw_key_idx & TX_CMD_SEC_MSK) << TX_CMD_SEC_SHIFT;
2074
2075                 if (keyinfo->keylen == 13)
2076                         tx->sec_ctl |= TX_CMD_SEC_KEY128;
2077
2078                 memcpy(&tx->key[3], keyinfo->key, keyinfo->keylen);
2079
2080                 IWL_DEBUG_TX("Configuring packet for WEP encryption "
2081                              "with key %d\n", info->control.hw_key->hw_key_idx);
2082                 break;
2083
2084         default:
2085                 IWL_ERR(priv, "Unknown encode alg %d\n", keyinfo->alg);
2086                 break;
2087         }
2088 }
2089
2090 /*
2091  * handle build REPLY_TX command notification.
2092  */
2093 static void iwl3945_build_tx_cmd_basic(struct iwl_priv *priv,
2094                                   struct iwl_cmd *cmd,
2095                                   struct ieee80211_tx_info *info,
2096                                   struct ieee80211_hdr *hdr, u8 std_id)
2097 {
2098         struct iwl3945_tx_cmd *tx = (struct iwl3945_tx_cmd *)cmd->cmd.payload;
2099         __le32 tx_flags = tx->tx_flags;
2100         __le16 fc = hdr->frame_control;
2101         u8 rc_flags = info->control.rates[0].flags;
2102
2103         tx->stop_time.life_time = TX_CMD_LIFE_TIME_INFINITE;
2104         if (!(info->flags & IEEE80211_TX_CTL_NO_ACK)) {
2105                 tx_flags |= TX_CMD_FLG_ACK_MSK;
2106                 if (ieee80211_is_mgmt(fc))
2107                         tx_flags |= TX_CMD_FLG_SEQ_CTL_MSK;
2108                 if (ieee80211_is_probe_resp(fc) &&
2109                     !(le16_to_cpu(hdr->seq_ctrl) & 0xf))
2110                         tx_flags |= TX_CMD_FLG_TSF_MSK;
2111         } else {
2112                 tx_flags &= (~TX_CMD_FLG_ACK_MSK);
2113                 tx_flags |= TX_CMD_FLG_SEQ_CTL_MSK;
2114         }
2115
2116         tx->sta_id = std_id;
2117         if (ieee80211_has_morefrags(fc))
2118                 tx_flags |= TX_CMD_FLG_MORE_FRAG_MSK;
2119
2120         if (ieee80211_is_data_qos(fc)) {
2121                 u8 *qc = ieee80211_get_qos_ctl(hdr);
2122                 tx->tid_tspec = qc[0] & 0xf;
2123                 tx_flags &= ~TX_CMD_FLG_SEQ_CTL_MSK;
2124         } else {
2125                 tx_flags |= TX_CMD_FLG_SEQ_CTL_MSK;
2126         }
2127
2128         if (rc_flags & IEEE80211_TX_RC_USE_RTS_CTS) {
2129                 tx_flags |= TX_CMD_FLG_RTS_MSK;
2130                 tx_flags &= ~TX_CMD_FLG_CTS_MSK;
2131         } else if (rc_flags & IEEE80211_TX_RC_USE_CTS_PROTECT) {
2132                 tx_flags &= ~TX_CMD_FLG_RTS_MSK;
2133                 tx_flags |= TX_CMD_FLG_CTS_MSK;
2134         }
2135
2136         if ((tx_flags & TX_CMD_FLG_RTS_MSK) || (tx_flags & TX_CMD_FLG_CTS_MSK))
2137                 tx_flags |= TX_CMD_FLG_FULL_TXOP_PROT_MSK;
2138
2139         tx_flags &= ~(TX_CMD_FLG_ANT_SEL_MSK);
2140         if (ieee80211_is_mgmt(fc)) {
2141                 if (ieee80211_is_assoc_req(fc) || ieee80211_is_reassoc_req(fc))
2142                         tx->timeout.pm_frame_timeout = cpu_to_le16(3);
2143                 else
2144                         tx->timeout.pm_frame_timeout = cpu_to_le16(2);
2145         } else {
2146                 tx->timeout.pm_frame_timeout = 0;
2147 #ifdef CONFIG_IWL3945_LEDS
2148                 priv->rxtxpackets += le16_to_cpu(cmd->cmd.tx.len);
2149 #endif
2150         }
2151
2152         tx->driver_txop = 0;
2153         tx->tx_flags = tx_flags;
2154         tx->next_frame_len = 0;
2155 }
2156
2157 /**
2158  * iwl3945_get_sta_id - Find station's index within station table
2159  */
2160 static int iwl3945_get_sta_id(struct iwl_priv *priv, struct ieee80211_hdr *hdr)
2161 {
2162         int sta_id;
2163         u16 fc = le16_to_cpu(hdr->frame_control);
2164
2165         /* If this frame is broadcast or management, use broadcast station id */
2166         if (((fc & IEEE80211_FCTL_FTYPE) != IEEE80211_FTYPE_DATA) ||
2167             is_multicast_ether_addr(hdr->addr1))
2168                 return priv->hw_params.bcast_sta_id;
2169
2170         switch (priv->iw_mode) {
2171
2172         /* If we are a client station in a BSS network, use the special
2173          * AP station entry (that's the only station we communicate with) */
2174         case NL80211_IFTYPE_STATION:
2175                 return IWL_AP_ID;
2176
2177         /* If we are an AP, then find the station, or use BCAST */
2178         case NL80211_IFTYPE_AP:
2179                 sta_id = iwl3945_hw_find_station(priv, hdr->addr1);
2180                 if (sta_id != IWL_INVALID_STATION)
2181                         return sta_id;
2182                 return priv->hw_params.bcast_sta_id;
2183
2184         /* If this frame is going out to an IBSS network, find the station,
2185          * or create a new station table entry */
2186         case NL80211_IFTYPE_ADHOC: {
2187                 /* Create new station table entry */
2188                 sta_id = iwl3945_hw_find_station(priv, hdr->addr1);
2189                 if (sta_id != IWL_INVALID_STATION)
2190                         return sta_id;
2191
2192                 sta_id = iwl3945_add_station(priv, hdr->addr1, 0, CMD_ASYNC);
2193
2194                 if (sta_id != IWL_INVALID_STATION)
2195                         return sta_id;
2196
2197                 IWL_DEBUG_DROP("Station %pM not in station map. "
2198                                "Defaulting to broadcast...\n",
2199                                hdr->addr1);
2200                 iwl_print_hex_dump(priv, IWL_DL_DROP, (u8 *) hdr, sizeof(*hdr));
2201                 return priv->hw_params.bcast_sta_id;
2202         }
2203         /* If we are in monitor mode, use BCAST. This is required for
2204          * packet injection. */
2205         case NL80211_IFTYPE_MONITOR:
2206                 return priv->hw_params.bcast_sta_id;
2207
2208         default:
2209                 IWL_WARN(priv, "Unknown mode of operation: %d\n",
2210                         priv->iw_mode);
2211                 return priv->hw_params.bcast_sta_id;
2212         }
2213 }
2214
2215 /*
2216  * start REPLY_TX command process
2217  */
2218 static int iwl3945_tx_skb(struct iwl_priv *priv, struct sk_buff *skb)
2219 {
2220         struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
2221         struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
2222         struct iwl3945_tfd *tfd;
2223         struct iwl3945_tx_cmd *tx;
2224         struct iwl_tx_queue *txq = NULL;
2225         struct iwl_queue *q = NULL;
2226         struct iwl_cmd *out_cmd = NULL;
2227         dma_addr_t phys_addr;
2228         dma_addr_t txcmd_phys;
2229         int txq_id = skb_get_queue_mapping(skb);
2230         u16 len, idx, len_org, hdr_len;
2231         u8 id;
2232         u8 unicast;
2233         u8 sta_id;
2234         u8 tid = 0;
2235         u16 seq_number = 0;
2236         __le16 fc;
2237         u8 wait_write_ptr = 0;
2238         u8 *qc = NULL;
2239         unsigned long flags;
2240         int rc;
2241
2242         spin_lock_irqsave(&priv->lock, flags);
2243         if (iwl_is_rfkill(priv)) {
2244                 IWL_DEBUG_DROP("Dropping - RF KILL\n");
2245                 goto drop_unlock;
2246         }
2247
2248         if ((ieee80211_get_tx_rate(priv->hw, info)->hw_value & 0xFF) == IWL_INVALID_RATE) {
2249                 IWL_ERR(priv, "ERROR: No TX rate available.\n");
2250                 goto drop_unlock;
2251         }
2252
2253         unicast = !is_multicast_ether_addr(hdr->addr1);
2254         id = 0;
2255
2256         fc = hdr->frame_control;
2257
2258 #ifdef CONFIG_IWL3945_DEBUG
2259         if (ieee80211_is_auth(fc))
2260                 IWL_DEBUG_TX("Sending AUTH frame\n");
2261         else if (ieee80211_is_assoc_req(fc))
2262                 IWL_DEBUG_TX("Sending ASSOC frame\n");
2263         else if (ieee80211_is_reassoc_req(fc))
2264                 IWL_DEBUG_TX("Sending REASSOC frame\n");
2265 #endif
2266
2267         /* drop all data frame if we are not associated */
2268         if (ieee80211_is_data(fc) &&
2269             (priv->iw_mode != NL80211_IFTYPE_MONITOR) && /* packet injection */
2270             (!iwl3945_is_associated(priv) ||
2271              ((priv->iw_mode == NL80211_IFTYPE_STATION) && !priv->assoc_id))) {
2272                 IWL_DEBUG_DROP("Dropping - !iwl3945_is_associated\n");
2273                 goto drop_unlock;
2274         }
2275
2276         spin_unlock_irqrestore(&priv->lock, flags);
2277
2278         hdr_len = ieee80211_hdrlen(fc);
2279
2280         /* Find (or create) index into station table for destination station */
2281         sta_id = iwl3945_get_sta_id(priv, hdr);
2282         if (sta_id == IWL_INVALID_STATION) {
2283                 IWL_DEBUG_DROP("Dropping - INVALID STATION: %pM\n",
2284                                hdr->addr1);
2285                 goto drop;
2286         }
2287
2288         IWL_DEBUG_RATE("station Id %d\n", sta_id);
2289
2290         if (ieee80211_is_data_qos(fc)) {
2291                 qc = ieee80211_get_qos_ctl(hdr);
2292                 tid = qc[0] & IEEE80211_QOS_CTL_TID_MASK;
2293                 seq_number = priv->stations_39[sta_id].tid[tid].seq_number &
2294                                 IEEE80211_SCTL_SEQ;
2295                 hdr->seq_ctrl = cpu_to_le16(seq_number) |
2296                         (hdr->seq_ctrl &
2297                                 __constant_cpu_to_le16(IEEE80211_SCTL_FRAG));
2298                 seq_number += 0x10;
2299         }
2300
2301         /* Descriptor for chosen Tx queue */
2302         txq = &priv->txq[txq_id];
2303         q = &txq->q;
2304
2305         spin_lock_irqsave(&priv->lock, flags);
2306
2307         /* Set up first empty TFD within this queue's circular TFD buffer */
2308         tfd = &txq->tfds39[q->write_ptr];
2309         memset(tfd, 0, sizeof(*tfd));
2310         idx = get_cmd_index(q, q->write_ptr, 0);
2311
2312         /* Set up driver data for this TFD */
2313         memset(&(txq->txb[q->write_ptr]), 0, sizeof(struct iwl_tx_info));
2314         txq->txb[q->write_ptr].skb[0] = skb;
2315
2316         /* Init first empty entry in queue's array of Tx/cmd buffers */
2317         out_cmd = txq->cmd[idx];
2318         tx = (struct iwl3945_tx_cmd *)out_cmd->cmd.payload;
2319         memset(&out_cmd->hdr, 0, sizeof(out_cmd->hdr));
2320         memset(tx, 0, sizeof(*tx));
2321
2322         /*
2323          * Set up the Tx-command (not MAC!) header.
2324          * Store the chosen Tx queue and TFD index within the sequence field;
2325          * after Tx, uCode's Tx response will return this value so driver can
2326          * locate the frame within the tx queue and do post-tx processing.
2327          */
2328         out_cmd->hdr.cmd = REPLY_TX;
2329         out_cmd->hdr.sequence = cpu_to_le16((u16)(QUEUE_TO_SEQ(txq_id) |
2330                                 INDEX_TO_SEQ(q->write_ptr)));
2331
2332         /* Copy MAC header from skb into command buffer */
2333         memcpy(tx->hdr, hdr, hdr_len);
2334
2335         /*
2336          * Use the first empty entry in this queue's command buffer array
2337          * to contain the Tx command and MAC header concatenated together
2338          * (payload data will be in another buffer).
2339          * Size of this varies, due to varying MAC header length.
2340          * If end is not dword aligned, we'll have 2 extra bytes at the end
2341          * of the MAC header (device reads on dword boundaries).
2342          * We'll tell device about this padding later.
2343          */
2344         len = sizeof(struct iwl3945_tx_cmd) +
2345                         sizeof(struct iwl_cmd_header) + hdr_len;
2346
2347         len_org = len;
2348         len = (len + 3) & ~3;
2349
2350         if (len_org != len)
2351                 len_org = 1;
2352         else
2353                 len_org = 0;
2354
2355         /* Physical address of this Tx command's header (not MAC header!),
2356          * within command buffer array. */
2357         txcmd_phys = pci_map_single(priv->pci_dev,
2358                                     out_cmd, sizeof(struct iwl_cmd),
2359                                     PCI_DMA_TODEVICE);
2360         pci_unmap_addr_set(&out_cmd->meta, mapping, txcmd_phys);
2361         pci_unmap_len_set(&out_cmd->meta, len, sizeof(struct iwl_cmd));
2362         /* Add buffer containing Tx command and MAC(!) header to TFD's
2363          * first entry */
2364         txcmd_phys += offsetof(struct iwl_cmd, hdr);
2365
2366         /* Add buffer containing Tx command and MAC(!) header to TFD's
2367          * first entry */
2368         iwl3945_hw_txq_attach_buf_to_tfd(priv, tfd, txcmd_phys, len);
2369
2370         if (info->control.hw_key)
2371                 iwl3945_build_tx_cmd_hwcrypto(priv, info, out_cmd, skb, 0);
2372
2373         /* Set up TFD's 2nd entry to point directly to remainder of skb,
2374          * if any (802.11 null frames have no payload). */
2375         len = skb->len - hdr_len;
2376         if (len) {
2377                 phys_addr = pci_map_single(priv->pci_dev, skb->data + hdr_len,
2378                                            len, PCI_DMA_TODEVICE);
2379                 iwl3945_hw_txq_attach_buf_to_tfd(priv, tfd, phys_addr, len);
2380         }
2381
2382         if (!len)
2383                 /* If there is no payload, then we use only one Tx buffer */
2384                 tfd->control_flags = cpu_to_le32(TFD_CTL_COUNT_SET(1));
2385         else
2386                 /* Else use 2 buffers.
2387                  * Tell 3945 about any padding after MAC header */
2388                 tfd->control_flags = cpu_to_le32(TFD_CTL_COUNT_SET(2) |
2389                         TFD_CTL_PAD_SET(U32_PAD(len)));
2390
2391         /* Total # bytes to be transmitted */
2392         len = (u16)skb->len;
2393         tx->len = cpu_to_le16(len);
2394
2395         /* TODO need this for burst mode later on */
2396         iwl3945_build_tx_cmd_basic(priv, out_cmd, info, hdr, sta_id);
2397
2398         /* set is_hcca to 0; it probably will never be implemented */
2399         iwl3945_hw_build_tx_cmd_rate(priv, out_cmd, info, hdr, sta_id, 0);
2400
2401         tx->tx_flags &= ~TX_CMD_FLG_ANT_A_MSK;
2402         tx->tx_flags &= ~TX_CMD_FLG_ANT_B_MSK;
2403
2404         if (!ieee80211_has_morefrags(hdr->frame_control)) {
2405                 txq->need_update = 1;
2406                 if (qc)
2407                         priv->stations_39[sta_id].tid[tid].seq_number = seq_number;
2408         } else {
2409                 wait_write_ptr = 1;
2410                 txq->need_update = 0;
2411         }
2412
2413         iwl_print_hex_dump(priv, IWL_DL_TX, tx, sizeof(*tx));
2414
2415         iwl_print_hex_dump(priv, IWL_DL_TX, (u8 *)tx->hdr,
2416                            ieee80211_hdrlen(fc));
2417
2418         /* Tell device the write index *just past* this latest filled TFD */
2419         q->write_ptr = iwl_queue_inc_wrap(q->write_ptr, q->n_bd);
2420         rc = iwl3945_tx_queue_update_write_ptr(priv, txq);
2421         spin_unlock_irqrestore(&priv->lock, flags);
2422
2423         if (rc)
2424                 return rc;
2425
2426         if ((iwl_queue_space(q) < q->high_mark)
2427             && priv->mac80211_registered) {
2428                 if (wait_write_ptr) {
2429                         spin_lock_irqsave(&priv->lock, flags);
2430                         txq->need_update = 1;
2431                         iwl3945_tx_queue_update_write_ptr(priv, txq);
2432                         spin_unlock_irqrestore(&priv->lock, flags);
2433                 }
2434
2435                 ieee80211_stop_queue(priv->hw, skb_get_queue_mapping(skb));
2436         }
2437
2438         return 0;
2439
2440 drop_unlock:
2441         spin_unlock_irqrestore(&priv->lock, flags);
2442 drop:
2443         return -1;
2444 }
2445
2446 static void iwl3945_set_rate(struct iwl_priv *priv)
2447 {
2448         const struct ieee80211_supported_band *sband = NULL;
2449         struct ieee80211_rate *rate;
2450         int i;
2451
2452         sband = iwl_get_hw_mode(priv, priv->band);
2453         if (!sband) {
2454                 IWL_ERR(priv, "Failed to set rate: unable to get hw mode\n");
2455                 return;
2456         }
2457
2458         priv->active_rate = 0;
2459         priv->active_rate_basic = 0;
2460
2461         IWL_DEBUG_RATE("Setting rates for %s GHz\n",
2462                        sband->band == IEEE80211_BAND_2GHZ ? "2.4" : "5");
2463
2464         for (i = 0; i < sband->n_bitrates; i++) {
2465                 rate = &sband->bitrates[i];
2466                 if ((rate->hw_value < IWL_RATE_COUNT) &&
2467                     !(rate->flags & IEEE80211_CHAN_DISABLED)) {
2468                         IWL_DEBUG_RATE("Adding rate index %d (plcp %d)\n",
2469                                        rate->hw_value, iwl3945_rates[rate->hw_value].plcp);
2470                         priv->active_rate |= (1 << rate->hw_value);
2471                 }
2472         }
2473
2474         IWL_DEBUG_RATE("Set active_rate = %0x, active_rate_basic = %0x\n",
2475                        priv->active_rate, priv->active_rate_basic);
2476
2477         /*
2478          * If a basic rate is configured, then use it (adding IWL_RATE_1M_MASK)
2479          * otherwise set it to the default of all CCK rates and 6, 12, 24 for
2480          * OFDM
2481          */
2482         if (priv->active_rate_basic & IWL_CCK_BASIC_RATES_MASK)
2483                 priv->staging39_rxon.cck_basic_rates =
2484                     ((priv->active_rate_basic &
2485                       IWL_CCK_RATES_MASK) >> IWL_FIRST_CCK_RATE) & 0xF;
2486         else
2487                 priv->staging39_rxon.cck_basic_rates =
2488                     (IWL_CCK_BASIC_RATES_MASK >> IWL_FIRST_CCK_RATE) & 0xF;
2489
2490         if (priv->active_rate_basic & IWL_OFDM_BASIC_RATES_MASK)
2491                 priv->staging39_rxon.ofdm_basic_rates =
2492                     ((priv->active_rate_basic &
2493                       (IWL_OFDM_BASIC_RATES_MASK | IWL_RATE_6M_MASK)) >>
2494                       IWL_FIRST_OFDM_RATE) & 0xFF;
2495         else
2496                 priv->staging39_rxon.ofdm_basic_rates =
2497                    (IWL_OFDM_BASIC_RATES_MASK >> IWL_FIRST_OFDM_RATE) & 0xFF;
2498 }
2499
2500 static void iwl3945_radio_kill_sw(struct iwl_priv *priv, int disable_radio)
2501 {
2502         unsigned long flags;
2503
2504         if (!!disable_radio == test_bit(STATUS_RF_KILL_SW, &priv->status))
2505                 return;
2506
2507         IWL_DEBUG_RF_KILL("Manual SW RF KILL set to: RADIO %s\n",
2508                           disable_radio ? "OFF" : "ON");
2509
2510         if (disable_radio) {
2511                 iwl3945_scan_cancel(priv);
2512                 /* FIXME: This is a workaround for AP */
2513                 if (priv->iw_mode != NL80211_IFTYPE_AP) {
2514                         spin_lock_irqsave(&priv->lock, flags);
2515                         iwl_write32(priv, CSR_UCODE_DRV_GP1_SET,
2516                                     CSR_UCODE_SW_BIT_RFKILL);
2517                         spin_unlock_irqrestore(&priv->lock, flags);
2518                         iwl_send_card_state(priv, CARD_STATE_CMD_DISABLE, 0);
2519                         set_bit(STATUS_RF_KILL_SW, &priv->status);
2520                 }
2521                 return;
2522         }
2523
2524         spin_lock_irqsave(&priv->lock, flags);
2525         iwl_write32(priv, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
2526
2527         clear_bit(STATUS_RF_KILL_SW, &priv->status);
2528         spin_unlock_irqrestore(&priv->lock, flags);
2529
2530         /* wake up ucode */
2531         msleep(10);
2532
2533         spin_lock_irqsave(&priv->lock, flags);
2534         iwl_read32(priv, CSR_UCODE_DRV_GP1);
2535         if (!iwl_grab_nic_access(priv))
2536                 iwl_release_nic_access(priv);
2537         spin_unlock_irqrestore(&priv->lock, flags);
2538
2539         if (test_bit(STATUS_RF_KILL_HW, &priv->status)) {
2540                 IWL_DEBUG_RF_KILL("Can not turn radio back on - "
2541                                   "disabled by HW switch\n");
2542                 return;
2543         }
2544
2545         if (priv->is_open)
2546                 queue_work(priv->workqueue, &priv->restart);
2547         return;
2548 }
2549
2550 void iwl3945_set_decrypted_flag(struct iwl_priv *priv, struct sk_buff *skb,
2551                             u32 decrypt_res, struct ieee80211_rx_status *stats)
2552 {
2553         u16 fc =
2554             le16_to_cpu(((struct ieee80211_hdr *)skb->data)->frame_control);
2555
2556         if (priv->active39_rxon.filter_flags & RXON_FILTER_DIS_DECRYPT_MSK)
2557                 return;
2558
2559         if (!(fc & IEEE80211_FCTL_PROTECTED))
2560                 return;
2561
2562         IWL_DEBUG_RX("decrypt_res:0x%x\n", decrypt_res);
2563         switch (decrypt_res & RX_RES_STATUS_SEC_TYPE_MSK) {
2564         case RX_RES_STATUS_SEC_TYPE_TKIP:
2565                 if ((decrypt_res & RX_RES_STATUS_DECRYPT_TYPE_MSK) ==
2566                     RX_RES_STATUS_BAD_ICV_MIC)
2567                         stats->flag |= RX_FLAG_MMIC_ERROR;
2568         case RX_RES_STATUS_SEC_TYPE_WEP:
2569         case RX_RES_STATUS_SEC_TYPE_CCMP:
2570                 if ((decrypt_res & RX_RES_STATUS_DECRYPT_TYPE_MSK) ==
2571                     RX_RES_STATUS_DECRYPT_OK) {
2572                         IWL_DEBUG_RX("hw decrypt successfully!!!\n");
2573                         stats->flag |= RX_FLAG_DECRYPTED;
2574                 }
2575                 break;
2576
2577         default:
2578                 break;
2579         }
2580 }
2581
2582 #ifdef CONFIG_IWL3945_SPECTRUM_MEASUREMENT
2583
2584 #include "iwl-spectrum.h"
2585
2586 #define BEACON_TIME_MASK_LOW    0x00FFFFFF
2587 #define BEACON_TIME_MASK_HIGH   0xFF000000
2588 #define TIME_UNIT               1024
2589
2590 /*
2591  * extended beacon time format
2592  * time in usec will be changed into a 32-bit value in 8:24 format
2593  * the high 1 byte is the beacon counts
2594  * the lower 3 bytes is the time in usec within one beacon interval
2595  */
2596
2597 static u32 iwl3945_usecs_to_beacons(u32 usec, u32 beacon_interval)
2598 {
2599         u32 quot;
2600         u32 rem;
2601         u32 interval = beacon_interval * 1024;
2602
2603         if (!interval || !usec)
2604                 return 0;
2605
2606         quot = (usec / interval) & (BEACON_TIME_MASK_HIGH >> 24);
2607         rem = (usec % interval) & BEACON_TIME_MASK_LOW;
2608
2609         return (quot << 24) + rem;
2610 }
2611
2612 /* base is usually what we get from ucode with each received frame,
2613  * the same as HW timer counter counting down
2614  */
2615
2616 static __le32 iwl3945_add_beacon_time(u32 base, u32 addon, u32 beacon_interval)
2617 {
2618         u32 base_low = base & BEACON_TIME_MASK_LOW;
2619         u32 addon_low = addon & BEACON_TIME_MASK_LOW;
2620         u32 interval = beacon_interval * TIME_UNIT;
2621         u32 res = (base & BEACON_TIME_MASK_HIGH) +
2622             (addon & BEACON_TIME_MASK_HIGH);
2623
2624         if (base_low > addon_low)
2625                 res += base_low - addon_low;
2626         else if (base_low < addon_low) {
2627                 res += interval + base_low - addon_low;
2628                 res += (1 << 24);
2629         } else
2630                 res += (1 << 24);
2631
2632         return cpu_to_le32(res);
2633 }
2634
2635 static int iwl3945_get_measurement(struct iwl_priv *priv,
2636                                struct ieee80211_measurement_params *params,
2637                                u8 type)
2638 {
2639         struct iwl_spectrum_cmd spectrum;
2640         struct iwl_rx_packet *res;
2641         struct iwl_host_cmd cmd = {
2642                 .id = REPLY_SPECTRUM_MEASUREMENT_CMD,
2643                 .data = (void *)&spectrum,
2644                 .meta.flags = CMD_WANT_SKB,
2645         };
2646         u32 add_time = le64_to_cpu(params->start_time);
2647         int rc;
2648         int spectrum_resp_status;
2649         int duration = le16_to_cpu(params->duration);
2650
2651         if (iwl3945_is_associated(priv))
2652                 add_time =
2653                     iwl3945_usecs_to_beacons(
2654                         le64_to_cpu(params->start_time) - priv->last_tsf,
2655                         le16_to_cpu(priv->rxon_timing.beacon_interval));
2656
2657         memset(&spectrum, 0, sizeof(spectrum));
2658
2659         spectrum.channel_count = cpu_to_le16(1);
2660         spectrum.flags =
2661             RXON_FLG_TSF2HOST_MSK | RXON_FLG_ANT_A_MSK | RXON_FLG_DIS_DIV_MSK;
2662         spectrum.filter_flags = MEASUREMENT_FILTER_FLAG;
2663         cmd.len = sizeof(spectrum);
2664         spectrum.len = cpu_to_le16(cmd.len - sizeof(spectrum.len));
2665
2666         if (iwl3945_is_associated(priv))
2667                 spectrum.start_time =
2668                     iwl3945_add_beacon_time(priv->last_beacon_time,
2669                                 add_time,
2670                                 le16_to_cpu(priv->rxon_timing.beacon_interval));
2671         else
2672                 spectrum.start_time = 0;
2673
2674         spectrum.channels[0].duration = cpu_to_le32(duration * TIME_UNIT);
2675         spectrum.channels[0].channel = params->channel;
2676         spectrum.channels[0].type = type;
2677         if (priv->active39_rxon.flags & RXON_FLG_BAND_24G_MSK)
2678                 spectrum.flags |= RXON_FLG_BAND_24G_MSK |
2679                     RXON_FLG_AUTO_DETECT_MSK | RXON_FLG_TGG_PROTECT_MSK;
2680
2681         rc = iwl3945_send_cmd_sync(priv, &cmd);
2682         if (rc)
2683                 return rc;
2684
2685         res = (struct iwl_rx_packet *)cmd.meta.u.skb->data;
2686         if (res->hdr.flags & IWL_CMD_FAILED_MSK) {
2687                 IWL_ERR(priv, "Bad return from REPLY_RX_ON_ASSOC command\n");
2688                 rc = -EIO;
2689         }
2690
2691         spectrum_resp_status = le16_to_cpu(res->u.spectrum.status);
2692         switch (spectrum_resp_status) {
2693         case 0:         /* Command will be handled */
2694                 if (res->u.spectrum.id != 0xff) {
2695                         IWL_DEBUG_INFO("Replaced existing measurement: %d\n",
2696                                                 res->u.spectrum.id);
2697                         priv->measurement_status &= ~MEASUREMENT_READY;
2698                 }
2699                 priv->measurement_status |= MEASUREMENT_ACTIVE;
2700                 rc = 0;
2701                 break;
2702
2703         case 1:         /* Command will not be handled */
2704                 rc = -EAGAIN;
2705                 break;
2706         }
2707
2708         dev_kfree_skb_any(cmd.meta.u.skb);
2709
2710         return rc;
2711 }
2712 #endif
2713
2714 static void iwl3945_rx_reply_alive(struct iwl_priv *priv,
2715                                struct iwl_rx_mem_buffer *rxb)
2716 {
2717         struct iwl_rx_packet *pkt = (void *)rxb->skb->data;
2718         struct iwl_alive_resp *palive;
2719         struct delayed_work *pwork;
2720
2721         palive = &pkt->u.alive_frame;
2722
2723         IWL_DEBUG_INFO("Alive ucode status 0x%08X revision "
2724                        "0x%01X 0x%01X\n",
2725                        palive->is_valid, palive->ver_type,
2726                        palive->ver_subtype);
2727
2728         if (palive->ver_subtype == INITIALIZE_SUBTYPE) {
2729                 IWL_DEBUG_INFO("Initialization Alive received.\n");
2730                 memcpy(&priv->card_alive_init, &pkt->u.alive_frame,
2731                        sizeof(struct iwl_alive_resp));
2732                 pwork = &priv->init_alive_start;
2733         } else {
2734                 IWL_DEBUG_INFO("Runtime Alive received.\n");
2735                 memcpy(&priv->card_alive, &pkt->u.alive_frame,
2736                        sizeof(struct iwl_alive_resp));
2737                 pwork = &priv->alive_start;
2738                 iwl3945_disable_events(priv);
2739         }
2740
2741         /* We delay the ALIVE response by 5ms to
2742          * give the HW RF Kill time to activate... */
2743         if (palive->is_valid == UCODE_VALID_OK)
2744                 queue_delayed_work(priv->workqueue, pwork,
2745                                    msecs_to_jiffies(5));
2746         else
2747                 IWL_WARN(priv, "uCode did not respond OK.\n");
2748 }
2749
2750 static void iwl3945_rx_reply_add_sta(struct iwl_priv *priv,
2751                                  struct iwl_rx_mem_buffer *rxb)
2752 {
2753         struct iwl_rx_packet *pkt = (void *)rxb->skb->data;
2754
2755         IWL_DEBUG_RX("Received REPLY_ADD_STA: 0x%02X\n", pkt->u.status);
2756         return;
2757 }
2758
2759 static void iwl3945_rx_reply_error(struct iwl_priv *priv,
2760                                struct iwl_rx_mem_buffer *rxb)
2761 {
2762         struct iwl_rx_packet *pkt = (void *)rxb->skb->data;
2763
2764         IWL_ERR(priv, "Error Reply type 0x%08X cmd %s (0x%02X) "
2765                 "seq 0x%04X ser 0x%08X\n",
2766                 le32_to_cpu(pkt->u.err_resp.error_type),
2767                 get_cmd_string(pkt->u.err_resp.cmd_id),
2768                 pkt->u.err_resp.cmd_id,
2769                 le16_to_cpu(pkt->u.err_resp.bad_cmd_seq_num),
2770                 le32_to_cpu(pkt->u.err_resp.error_info));
2771 }
2772
2773 #define TX_STATUS_ENTRY(x) case TX_STATUS_FAIL_ ## x: return #x
2774
2775 static void iwl3945_rx_csa(struct iwl_priv *priv, struct iwl_rx_mem_buffer *rxb)
2776 {
2777         struct iwl_rx_packet *pkt = (void *)rxb->skb->data;
2778         struct iwl3945_rxon_cmd *rxon = (void *)&priv->active39_rxon;
2779         struct iwl_csa_notification *csa = &(pkt->u.csa_notif);
2780         IWL_DEBUG_11H("CSA notif: channel %d, status %d\n",
2781                       le16_to_cpu(csa->channel), le32_to_cpu(csa->status));
2782         rxon->channel = csa->channel;
2783         priv->staging39_rxon.channel = csa->channel;
2784 }
2785
2786 static void iwl3945_rx_spectrum_measure_notif(struct iwl_priv *priv,
2787                                           struct iwl_rx_mem_buffer *rxb)
2788 {
2789 #ifdef CONFIG_IWL3945_SPECTRUM_MEASUREMENT
2790         struct iwl_rx_packet *pkt = (void *)rxb->skb->data;
2791         struct iwl_spectrum_notification *report = &(pkt->u.spectrum_notif);
2792
2793         if (!report->state) {
2794                 IWL_DEBUG(IWL_DL_11H | IWL_DL_INFO,
2795                           "Spectrum Measure Notification: Start\n");
2796                 return;
2797         }
2798
2799         memcpy(&priv->measure_report, report, sizeof(*report));
2800         priv->measurement_status |= MEASUREMENT_READY;
2801 #endif
2802 }
2803
2804 static void iwl3945_rx_pm_sleep_notif(struct iwl_priv *priv,
2805                                   struct iwl_rx_mem_buffer *rxb)
2806 {
2807 #ifdef CONFIG_IWL3945_DEBUG
2808         struct iwl_rx_packet *pkt = (void *)rxb->skb->data;
2809         struct iwl_sleep_notification *sleep = &(pkt->u.sleep_notif);
2810         IWL_DEBUG_RX("sleep mode: %d, src: %d\n",
2811                      sleep->pm_sleep_mode, sleep->pm_wakeup_src);
2812 #endif
2813 }
2814
2815 static void iwl3945_rx_pm_debug_statistics_notif(struct iwl_priv *priv,
2816                                              struct iwl_rx_mem_buffer *rxb)
2817 {
2818         struct iwl_rx_packet *pkt = (void *)rxb->skb->data;
2819         IWL_DEBUG_RADIO("Dumping %d bytes of unhandled "
2820                         "notification for %s:\n",
2821                         le32_to_cpu(pkt->len), get_cmd_string(pkt->hdr.cmd));
2822         iwl_print_hex_dump(priv, IWL_DL_RADIO, pkt->u.raw,
2823                            le32_to_cpu(pkt->len));
2824 }
2825
2826 static void iwl3945_bg_beacon_update(struct work_struct *work)
2827 {
2828         struct iwl_priv *priv =
2829                 container_of(work, struct iwl_priv, beacon_update);
2830         struct sk_buff *beacon;
2831
2832         /* Pull updated AP beacon from mac80211. will fail if not in AP mode */
2833         beacon = ieee80211_beacon_get(priv->hw, priv->vif);
2834
2835         if (!beacon) {
2836                 IWL_ERR(priv, "update beacon failed\n");
2837                 return;
2838         }
2839
2840         mutex_lock(&priv->mutex);
2841         /* new beacon skb is allocated every time; dispose previous.*/
2842         if (priv->ibss_beacon)
2843                 dev_kfree_skb(priv->ibss_beacon);
2844
2845         priv->ibss_beacon = beacon;
2846         mutex_unlock(&priv->mutex);
2847
2848         iwl3945_send_beacon_cmd(priv);
2849 }
2850
2851 static void iwl3945_rx_beacon_notif(struct iwl_priv *priv,
2852                                 struct iwl_rx_mem_buffer *rxb)
2853 {
2854 #ifdef CONFIG_IWL3945_DEBUG
2855         struct iwl_rx_packet *pkt = (void *)rxb->skb->data;
2856         struct iwl3945_beacon_notif *beacon = &(pkt->u.beacon_status);
2857         u8 rate = beacon->beacon_notify_hdr.rate;
2858
2859         IWL_DEBUG_RX("beacon status %x retries %d iss %d "
2860                 "tsf %d %d rate %d\n",
2861                 le32_to_cpu(beacon->beacon_notify_hdr.status) & TX_STATUS_MSK,
2862                 beacon->beacon_notify_hdr.failure_frame,
2863                 le32_to_cpu(beacon->ibss_mgr_status),
2864                 le32_to_cpu(beacon->high_tsf),
2865                 le32_to_cpu(beacon->low_tsf), rate);
2866 #endif
2867
2868         if ((priv->iw_mode == NL80211_IFTYPE_AP) &&
2869             (!test_bit(STATUS_EXIT_PENDING, &priv->status)))
2870                 queue_work(priv->workqueue, &priv->beacon_update);
2871 }
2872
2873 /* Service response to REPLY_SCAN_CMD (0x80) */
2874 static void iwl3945_rx_reply_scan(struct iwl_priv *priv,
2875                               struct iwl_rx_mem_buffer *rxb)
2876 {
2877 #ifdef CONFIG_IWL3945_DEBUG
2878         struct iwl_rx_packet *pkt = (void *)rxb->skb->data;
2879         struct iwl_scanreq_notification *notif =
2880             (struct iwl_scanreq_notification *)pkt->u.raw;
2881
2882         IWL_DEBUG_RX("Scan request status = 0x%x\n", notif->status);
2883 #endif
2884 }
2885
2886 /* Service SCAN_START_NOTIFICATION (0x82) */
2887 static void iwl3945_rx_scan_start_notif(struct iwl_priv *priv,
2888                                     struct iwl_rx_mem_buffer *rxb)
2889 {
2890         struct iwl_rx_packet *pkt = (void *)rxb->skb->data;
2891         struct iwl_scanstart_notification *notif =
2892             (struct iwl_scanstart_notification *)pkt->u.raw;
2893         priv->scan_start_tsf = le32_to_cpu(notif->tsf_low);
2894         IWL_DEBUG_SCAN("Scan start: "
2895                        "%d [802.11%s] "
2896                        "(TSF: 0x%08X:%08X) - %d (beacon timer %u)\n",
2897                        notif->channel,
2898                        notif->band ? "bg" : "a",
2899                        notif->tsf_high,
2900                        notif->tsf_low, notif->status, notif->beacon_timer);
2901 }
2902
2903 /* Service SCAN_RESULTS_NOTIFICATION (0x83) */
2904 static void iwl3945_rx_scan_results_notif(struct iwl_priv *priv,
2905                                       struct iwl_rx_mem_buffer *rxb)
2906 {
2907         struct iwl_rx_packet *pkt = (void *)rxb->skb->data;
2908         struct iwl_scanresults_notification *notif =
2909             (struct iwl_scanresults_notification *)pkt->u.raw;
2910
2911         IWL_DEBUG_SCAN("Scan ch.res: "
2912                        "%d [802.11%s] "
2913                        "(TSF: 0x%08X:%08X) - %d "
2914                        "elapsed=%lu usec (%dms since last)\n",
2915                        notif->channel,
2916                        notif->band ? "bg" : "a",
2917                        le32_to_cpu(notif->tsf_high),
2918                        le32_to_cpu(notif->tsf_low),
2919                        le32_to_cpu(notif->statistics[0]),
2920                        le32_to_cpu(notif->tsf_low) - priv->scan_start_tsf,
2921                        jiffies_to_msecs(elapsed_jiffies
2922                                         (priv->last_scan_jiffies, jiffies)));
2923
2924         priv->last_scan_jiffies = jiffies;
2925         priv->next_scan_jiffies = 0;
2926 }
2927
2928 /* Service SCAN_COMPLETE_NOTIFICATION (0x84) */
2929 static void iwl3945_rx_scan_complete_notif(struct iwl_priv *priv,
2930                                        struct iwl_rx_mem_buffer *rxb)
2931 {
2932         struct iwl_rx_packet *pkt = (void *)rxb->skb->data;
2933         struct iwl_scancomplete_notification *scan_notif = (void *)pkt->u.raw;
2934
2935         IWL_DEBUG_SCAN("Scan complete: %d channels (TSF 0x%08X:%08X) - %d\n",
2936                        scan_notif->scanned_channels,
2937                        scan_notif->tsf_low,
2938                        scan_notif->tsf_high, scan_notif->status);
2939
2940         /* The HW is no longer scanning */
2941         clear_bit(STATUS_SCAN_HW, &priv->status);
2942
2943         /* The scan completion notification came in, so kill that timer... */
2944         cancel_delayed_work(&priv->scan_check);
2945
2946         IWL_DEBUG_INFO("Scan pass on %sGHz took %dms\n",
2947                        (priv->scan_bands & BIT(IEEE80211_BAND_2GHZ)) ?
2948                                                         "2.4" : "5.2",
2949                        jiffies_to_msecs(elapsed_jiffies
2950                                         (priv->scan_pass_start, jiffies)));
2951
2952         /* Remove this scanned band from the list of pending
2953          * bands to scan, band G precedes A in order of scanning
2954          * as seen in iwl3945_bg_request_scan */
2955         if (priv->scan_bands & BIT(IEEE80211_BAND_2GHZ))
2956                 priv->scan_bands &= ~BIT(IEEE80211_BAND_2GHZ);
2957         else if (priv->scan_bands &  BIT(IEEE80211_BAND_5GHZ))
2958                 priv->scan_bands &= ~BIT(IEEE80211_BAND_5GHZ);
2959
2960         /* If a request to abort was given, or the scan did not succeed
2961          * then we reset the scan state machine and terminate,
2962          * re-queuing another scan if one has been requested */
2963         if (test_bit(STATUS_SCAN_ABORTING, &priv->status)) {
2964                 IWL_DEBUG_INFO("Aborted scan completed.\n");
2965                 clear_bit(STATUS_SCAN_ABORTING, &priv->status);
2966         } else {
2967                 /* If there are more bands on this scan pass reschedule */
2968                 if (priv->scan_bands > 0)
2969                         goto reschedule;
2970         }
2971
2972         priv->last_scan_jiffies = jiffies;
2973         priv->next_scan_jiffies = 0;
2974         IWL_DEBUG_INFO("Setting scan to off\n");
2975
2976         clear_bit(STATUS_SCANNING, &priv->status);
2977
2978         IWL_DEBUG_INFO("Scan took %dms\n",
2979                 jiffies_to_msecs(elapsed_jiffies(priv->scan_start, jiffies)));
2980
2981         queue_work(priv->workqueue, &priv->scan_completed);
2982
2983         return;
2984
2985 reschedule:
2986         priv->scan_pass_start = jiffies;
2987         queue_work(priv->workqueue, &priv->request_scan);
2988 }
2989
2990 /* Handle notification from uCode that card's power state is changing
2991  * due to software, hardware, or critical temperature RFKILL */
2992 static void iwl3945_rx_card_state_notif(struct iwl_priv *priv,
2993                                     struct iwl_rx_mem_buffer *rxb)
2994 {
2995         struct iwl_rx_packet *pkt = (void *)rxb->skb->data;
2996         u32 flags = le32_to_cpu(pkt->u.card_state_notif.flags);
2997         unsigned long status = priv->status;
2998
2999         IWL_DEBUG_RF_KILL("Card state received: HW:%s SW:%s\n",
3000                           (flags & HW_CARD_DISABLED) ? "Kill" : "On",
3001                           (flags & SW_CARD_DISABLED) ? "Kill" : "On");
3002
3003         iwl_write32(priv, CSR_UCODE_DRV_GP1_SET,
3004                     CSR_UCODE_DRV_GP1_BIT_CMD_BLOCKED);
3005
3006         if (flags & HW_CARD_DISABLED)
3007                 set_bit(STATUS_RF_KILL_HW, &priv->status);
3008         else
3009                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
3010
3011
3012         if (flags & SW_CARD_DISABLED)
3013                 set_bit(STATUS_RF_KILL_SW, &priv->status);
3014         else
3015                 clear_bit(STATUS_RF_KILL_SW, &priv->status);
3016
3017         iwl3945_scan_cancel(priv);
3018
3019         if ((test_bit(STATUS_RF_KILL_HW, &status) !=
3020              test_bit(STATUS_RF_KILL_HW, &priv->status)) ||
3021             (test_bit(STATUS_RF_KILL_SW, &status) !=
3022              test_bit(STATUS_RF_KILL_SW, &priv->status)))
3023                 queue_work(priv->workqueue, &priv->rf_kill);
3024         else
3025                 wake_up_interruptible(&priv->wait_command_queue);
3026 }
3027
3028 /**
3029  * iwl3945_setup_rx_handlers - Initialize Rx handler callbacks
3030  *
3031  * Setup the RX handlers for each of the reply types sent from the uCode
3032  * to the host.
3033  *
3034  * This function chains into the hardware specific files for them to setup
3035  * any hardware specific handlers as well.
3036  */
3037 static void iwl3945_setup_rx_handlers(struct iwl_priv *priv)
3038 {
3039         priv->rx_handlers[REPLY_ALIVE] = iwl3945_rx_reply_alive;
3040         priv->rx_handlers[REPLY_ADD_STA] = iwl3945_rx_reply_add_sta;
3041         priv->rx_handlers[REPLY_ERROR] = iwl3945_rx_reply_error;
3042         priv->rx_handlers[CHANNEL_SWITCH_NOTIFICATION] = iwl3945_rx_csa;
3043         priv->rx_handlers[SPECTRUM_MEASURE_NOTIFICATION] =
3044             iwl3945_rx_spectrum_measure_notif;
3045         priv->rx_handlers[PM_SLEEP_NOTIFICATION] = iwl3945_rx_pm_sleep_notif;
3046         priv->rx_handlers[PM_DEBUG_STATISTIC_NOTIFIC] =
3047             iwl3945_rx_pm_debug_statistics_notif;
3048         priv->rx_handlers[BEACON_NOTIFICATION] = iwl3945_rx_beacon_notif;
3049
3050         /*
3051          * The same handler is used for both the REPLY to a discrete
3052          * statistics request from the host as well as for the periodic
3053          * statistics notifications (after received beacons) from the uCode.
3054          */
3055         priv->rx_handlers[REPLY_STATISTICS_CMD] = iwl3945_hw_rx_statistics;
3056         priv->rx_handlers[STATISTICS_NOTIFICATION] = iwl3945_hw_rx_statistics;
3057
3058         priv->rx_handlers[REPLY_SCAN_CMD] = iwl3945_rx_reply_scan;
3059         priv->rx_handlers[SCAN_START_NOTIFICATION] = iwl3945_rx_scan_start_notif;
3060         priv->rx_handlers[SCAN_RESULTS_NOTIFICATION] =
3061             iwl3945_rx_scan_results_notif;
3062         priv->rx_handlers[SCAN_COMPLETE_NOTIFICATION] =
3063             iwl3945_rx_scan_complete_notif;
3064         priv->rx_handlers[CARD_STATE_NOTIFICATION] = iwl3945_rx_card_state_notif;
3065
3066         /* Set up hardware specific Rx handlers */
3067         iwl3945_hw_rx_handler_setup(priv);
3068 }
3069
3070 /**
3071  * iwl3945_cmd_queue_reclaim - Reclaim CMD queue entries
3072  * When FW advances 'R' index, all entries between old and new 'R' index
3073  * need to be reclaimed.
3074  */
3075 static void iwl3945_cmd_queue_reclaim(struct iwl_priv *priv,
3076                                       int txq_id, int index)
3077 {
3078         struct iwl_tx_queue *txq = &priv->txq[txq_id];
3079         struct iwl_queue *q = &txq->q;
3080         int nfreed = 0;
3081
3082         if ((index >= q->n_bd) || (iwl3945_x2_queue_used(q, index) == 0)) {
3083                 IWL_ERR(priv, "Read index for DMA queue txq id (%d), index %d, "
3084                           "is out of range [0-%d] %d %d.\n", txq_id,
3085                           index, q->n_bd, q->write_ptr, q->read_ptr);
3086                 return;
3087         }
3088
3089         for (index = iwl_queue_inc_wrap(index, q->n_bd); q->read_ptr != index;
3090                 q->read_ptr = iwl_queue_inc_wrap(q->read_ptr, q->n_bd)) {
3091                 if (nfreed > 1) {
3092                         IWL_ERR(priv, "HCMD skipped: index (%d) %d %d\n", index,
3093                                         q->write_ptr, q->read_ptr);
3094                         queue_work(priv->workqueue, &priv->restart);
3095                         break;
3096                 }
3097                 nfreed++;
3098         }
3099 }
3100
3101
3102 /**
3103  * iwl3945_tx_cmd_complete - Pull unused buffers off the queue and reclaim them
3104  * @rxb: Rx buffer to reclaim
3105  *
3106  * If an Rx buffer has an async callback associated with it the callback
3107  * will be executed.  The attached skb (if present) will only be freed
3108  * if the callback returns 1
3109  */
3110 static void iwl3945_tx_cmd_complete(struct iwl_priv *priv,
3111                                 struct iwl_rx_mem_buffer *rxb)
3112 {
3113         struct iwl_rx_packet *pkt = (struct iwl_rx_packet *)rxb->skb->data;
3114         u16 sequence = le16_to_cpu(pkt->hdr.sequence);
3115         int txq_id = SEQ_TO_QUEUE(sequence);
3116         int index = SEQ_TO_INDEX(sequence);
3117         int huge =  !!(pkt->hdr.sequence & SEQ_HUGE_FRAME);
3118         int cmd_index;
3119         struct iwl_cmd *cmd;
3120
3121         BUG_ON(txq_id != IWL_CMD_QUEUE_NUM);
3122
3123         cmd_index = get_cmd_index(&priv->txq[IWL_CMD_QUEUE_NUM].q, index, huge);
3124         cmd = priv->txq[IWL_CMD_QUEUE_NUM].cmd[cmd_index];
3125
3126         /* Input error checking is done when commands are added to queue. */
3127         if (cmd->meta.flags & CMD_WANT_SKB) {
3128                 cmd->meta.source->u.skb = rxb->skb;
3129                 rxb->skb = NULL;
3130         } else if (cmd->meta.u.callback &&
3131                    !cmd->meta.u.callback(priv, cmd, rxb->skb))
3132                 rxb->skb = NULL;
3133
3134         iwl3945_cmd_queue_reclaim(priv, txq_id, index);
3135
3136         if (!(cmd->meta.flags & CMD_ASYNC)) {
3137                 clear_bit(STATUS_HCMD_ACTIVE, &priv->status);
3138                 wake_up_interruptible(&priv->wait_command_queue);
3139         }
3140 }
3141
3142 /************************** RX-FUNCTIONS ****************************/
3143 /*
3144  * Rx theory of operation
3145  *
3146  * The host allocates 32 DMA target addresses and passes the host address
3147  * to the firmware at register IWL_RFDS_TABLE_LOWER + N * RFD_SIZE where N is
3148  * 0 to 31
3149  *
3150  * Rx Queue Indexes
3151  * The host/firmware share two index registers for managing the Rx buffers.
3152  *
3153  * The READ index maps to the first position that the firmware may be writing
3154  * to -- the driver can read up to (but not including) this position and get
3155  * good data.
3156  * The READ index is managed by the firmware once the card is enabled.
3157  *
3158  * The WRITE index maps to the last position the driver has read from -- the
3159  * position preceding WRITE is the last slot the firmware can place a packet.
3160  *
3161  * The queue is empty (no good data) if WRITE = READ - 1, and is full if
3162  * WRITE = READ.
3163  *
3164  * During initialization, the host sets up the READ queue position to the first
3165  * INDEX position, and WRITE to the last (READ - 1 wrapped)
3166  *
3167  * When the firmware places a packet in a buffer, it will advance the READ index
3168  * and fire the RX interrupt.  The driver can then query the READ index and
3169  * process as many packets as possible, moving the WRITE index forward as it
3170  * resets the Rx queue buffers with new memory.
3171  *
3172  * The management in the driver is as follows:
3173  * + A list of pre-allocated SKBs is stored in iwl->rxq->rx_free.  When
3174  *   iwl->rxq->free_count drops to or below RX_LOW_WATERMARK, work is scheduled
3175  *   to replenish the iwl->rxq->rx_free.
3176  * + In iwl3945_rx_replenish (scheduled) if 'processed' != 'read' then the
3177  *   iwl->rxq is replenished and the READ INDEX is updated (updating the
3178  *   'processed' and 'read' driver indexes as well)
3179  * + A received packet is processed and handed to the kernel network stack,
3180  *   detached from the iwl->rxq.  The driver 'processed' index is updated.
3181  * + The Host/Firmware iwl->rxq is replenished at tasklet time from the rx_free
3182  *   list. If there are no allocated buffers in iwl->rxq->rx_free, the READ
3183  *   INDEX is not incremented and iwl->status(RX_STALLED) is set.  If there
3184  *   were enough free buffers and RX_STALLED is set it is cleared.
3185  *
3186  *
3187  * Driver sequence:
3188  *
3189  * iwl3945_rx_replenish()     Replenishes rx_free list from rx_used, and calls
3190  *                            iwl3945_rx_queue_restock
3191  * iwl3945_rx_queue_restock() Moves available buffers from rx_free into Rx
3192  *                            queue, updates firmware pointers, and updates
3193  *                            the WRITE index.  If insufficient rx_free buffers
3194  *                            are available, schedules iwl3945_rx_replenish
3195  *
3196  * -- enable interrupts --
3197  * ISR - iwl3945_rx()         Detach iwl_rx_mem_buffers from pool up to the
3198  *                            READ INDEX, detaching the SKB from the pool.
3199  *                            Moves the packet buffer from queue to rx_used.
3200  *                            Calls iwl3945_rx_queue_restock to refill any empty
3201  *                            slots.
3202  * ...
3203  *
3204  */
3205
3206 /**
3207  * iwl3945_dma_addr2rbd_ptr - convert a DMA address to a uCode read buffer ptr
3208  */
3209 static inline __le32 iwl3945_dma_addr2rbd_ptr(struct iwl_priv *priv,
3210                                           dma_addr_t dma_addr)
3211 {
3212         return cpu_to_le32((u32)dma_addr);
3213 }
3214
3215 /**
3216  * iwl3945_rx_queue_restock - refill RX queue from pre-allocated pool
3217  *
3218  * If there are slots in the RX queue that need to be restocked,
3219  * and we have free pre-allocated buffers, fill the ranks as much
3220  * as we can, pulling from rx_free.
3221  *
3222  * This moves the 'write' index forward to catch up with 'processed', and
3223  * also updates the memory address in the firmware to reference the new
3224  * target buffer.
3225  */
3226 static int iwl3945_rx_queue_restock(struct iwl_priv *priv)
3227 {
3228         struct iwl_rx_queue *rxq = &priv->rxq;
3229         struct list_head *element;
3230         struct iwl_rx_mem_buffer *rxb;
3231         unsigned long flags;
3232         int write, rc;
3233
3234         spin_lock_irqsave(&rxq->lock, flags);
3235         write = rxq->write & ~0x7;
3236         while ((iwl_rx_queue_space(rxq) > 0) && (rxq->free_count)) {
3237                 /* Get next free Rx buffer, remove from free list */
3238                 element = rxq->rx_free.next;
3239                 rxb = list_entry(element, struct iwl_rx_mem_buffer, list);
3240                 list_del(element);
3241
3242                 /* Point to Rx buffer via next RBD in circular buffer */
3243                 rxq->bd[rxq->write] = iwl3945_dma_addr2rbd_ptr(priv, rxb->real_dma_addr);
3244                 rxq->queue[rxq->write] = rxb;
3245                 rxq->write = (rxq->write + 1) & RX_QUEUE_MASK;
3246                 rxq->free_count--;
3247         }
3248         spin_unlock_irqrestore(&rxq->lock, flags);
3249         /* If the pre-allocated buffer pool is dropping low, schedule to
3250          * refill it */
3251         if (rxq->free_count <= RX_LOW_WATERMARK)
3252                 queue_work(priv->workqueue, &priv->rx_replenish);
3253
3254
3255         /* If we've added more space for the firmware to place data, tell it.
3256          * Increment device's write pointer in multiples of 8. */
3257         if ((write != (rxq->write & ~0x7))
3258             || (abs(rxq->write - rxq->read) > 7)) {
3259                 spin_lock_irqsave(&rxq->lock, flags);
3260                 rxq->need_update = 1;
3261                 spin_unlock_irqrestore(&rxq->lock, flags);
3262                 rc = iwl_rx_queue_update_write_ptr(priv, rxq);
3263                 if (rc)
3264                         return rc;
3265         }
3266
3267         return 0;
3268 }
3269
3270 /**
3271  * iwl3945_rx_replenish - Move all used packet from rx_used to rx_free
3272  *
3273  * When moving to rx_free an SKB is allocated for the slot.
3274  *
3275  * Also restock the Rx queue via iwl3945_rx_queue_restock.
3276  * This is called as a scheduled work item (except for during initialization)
3277  */
3278 static void iwl3945_rx_allocate(struct iwl_priv *priv)
3279 {
3280         struct iwl_rx_queue *rxq = &priv->rxq;
3281         struct list_head *element;
3282         struct iwl_rx_mem_buffer *rxb;
3283         unsigned long flags;
3284         spin_lock_irqsave(&rxq->lock, flags);
3285         while (!list_empty(&rxq->rx_used)) {
3286                 element = rxq->rx_used.next;
3287                 rxb = list_entry(element, struct iwl_rx_mem_buffer, list);
3288
3289                 /* Alloc a new receive buffer */
3290                 rxb->skb =
3291                     alloc_skb(IWL_RX_BUF_SIZE, __GFP_NOWARN | GFP_ATOMIC);
3292                 if (!rxb->skb) {
3293                         if (net_ratelimit())
3294                                 IWL_CRIT(priv, ": Can not allocate SKB buffers\n");
3295                         /* We don't reschedule replenish work here -- we will
3296                          * call the restock method and if it still needs
3297                          * more buffers it will schedule replenish */
3298                         break;
3299                 }
3300
3301                 /* If radiotap head is required, reserve some headroom here.
3302                  * The physical head count is a variable rx_stats->phy_count.
3303                  * We reserve 4 bytes here. Plus these extra bytes, the
3304                  * headroom of the physical head should be enough for the
3305                  * radiotap head that iwl3945 supported. See iwl3945_rt.
3306                  */
3307                 skb_reserve(rxb->skb, 4);
3308
3309                 priv->alloc_rxb_skb++;
3310                 list_del(element);
3311
3312                 /* Get physical address of RB/SKB */
3313                 rxb->real_dma_addr =
3314                     pci_map_single(priv->pci_dev, rxb->skb->data,
3315                                    IWL_RX_BUF_SIZE, PCI_DMA_FROMDEVICE);
3316                 list_add_tail(&rxb->list, &rxq->rx_free);
3317                 rxq->free_count++;
3318         }
3319         spin_unlock_irqrestore(&rxq->lock, flags);
3320 }
3321
3322 /*
3323  * this should be called while priv->lock is locked
3324  */
3325 static void __iwl3945_rx_replenish(void *data)
3326 {
3327         struct iwl_priv *priv = data;
3328
3329         iwl3945_rx_allocate(priv);
3330         iwl3945_rx_queue_restock(priv);
3331 }
3332
3333
3334 void iwl3945_rx_replenish(void *data)
3335 {
3336         struct iwl_priv *priv = data;
3337         unsigned long flags;
3338
3339         iwl3945_rx_allocate(priv);
3340
3341         spin_lock_irqsave(&priv->lock, flags);
3342         iwl3945_rx_queue_restock(priv);
3343         spin_unlock_irqrestore(&priv->lock, flags);
3344 }
3345
3346 /* Convert linear signal-to-noise ratio into dB */
3347 static u8 ratio2dB[100] = {
3348 /*       0   1   2   3   4   5   6   7   8   9 */
3349          0,  0,  6, 10, 12, 14, 16, 17, 18, 19, /* 00 - 09 */
3350         20, 21, 22, 22, 23, 23, 24, 25, 26, 26, /* 10 - 19 */
3351         26, 26, 26, 27, 27, 28, 28, 28, 29, 29, /* 20 - 29 */
3352         29, 30, 30, 30, 31, 31, 31, 31, 32, 32, /* 30 - 39 */
3353         32, 32, 32, 33, 33, 33, 33, 33, 34, 34, /* 40 - 49 */
3354         34, 34, 34, 34, 35, 35, 35, 35, 35, 35, /* 50 - 59 */
3355         36, 36, 36, 36, 36, 36, 36, 37, 37, 37, /* 60 - 69 */
3356         37, 37, 37, 37, 37, 38, 38, 38, 38, 38, /* 70 - 79 */
3357         38, 38, 38, 38, 38, 39, 39, 39, 39, 39, /* 80 - 89 */
3358         39, 39, 39, 39, 39, 40, 40, 40, 40, 40  /* 90 - 99 */
3359 };
3360
3361 /* Calculates a relative dB value from a ratio of linear
3362  *   (i.e. not dB) signal levels.
3363  * Conversion assumes that levels are voltages (20*log), not powers (10*log). */
3364 int iwl3945_calc_db_from_ratio(int sig_ratio)
3365 {
3366         /* 1000:1 or higher just report as 60 dB */
3367         if (sig_ratio >= 1000)
3368                 return 60;
3369
3370         /* 100:1 or higher, divide by 10 and use table,
3371          *   add 20 dB to make up for divide by 10 */
3372         if (sig_ratio >= 100)
3373                 return 20 + (int)ratio2dB[sig_ratio/10];
3374
3375         /* We shouldn't see this */
3376         if (sig_ratio < 1)
3377                 return 0;
3378
3379         /* Use table for ratios 1:1 - 99:1 */
3380         return (int)ratio2dB[sig_ratio];
3381 }
3382
3383 #define PERFECT_RSSI (-20) /* dBm */
3384 #define WORST_RSSI (-95)   /* dBm */
3385 #define RSSI_RANGE (PERFECT_RSSI - WORST_RSSI)
3386
3387 /* Calculate an indication of rx signal quality (a percentage, not dBm!).
3388  * See http://www.ces.clemson.edu/linux/signal_quality.shtml for info
3389  *   about formulas used below. */
3390 int iwl3945_calc_sig_qual(int rssi_dbm, int noise_dbm)
3391 {
3392         int sig_qual;
3393         int degradation = PERFECT_RSSI - rssi_dbm;
3394
3395         /* If we get a noise measurement, use signal-to-noise ratio (SNR)
3396          * as indicator; formula is (signal dbm - noise dbm).
3397          * SNR at or above 40 is a great signal (100%).
3398          * Below that, scale to fit SNR of 0 - 40 dB within 0 - 100% indicator.
3399          * Weakest usable signal is usually 10 - 15 dB SNR. */
3400         if (noise_dbm) {
3401                 if (rssi_dbm - noise_dbm >= 40)
3402                         return 100;
3403                 else if (rssi_dbm < noise_dbm)
3404                         return 0;
3405                 sig_qual = ((rssi_dbm - noise_dbm) * 5) / 2;
3406
3407         /* Else use just the signal level.
3408          * This formula is a least squares fit of data points collected and
3409          *   compared with a reference system that had a percentage (%) display
3410          *   for signal quality. */
3411         } else
3412                 sig_qual = (100 * (RSSI_RANGE * RSSI_RANGE) - degradation *
3413                             (15 * RSSI_RANGE + 62 * degradation)) /
3414                            (RSSI_RANGE * RSSI_RANGE);
3415
3416         if (sig_qual > 100)
3417                 sig_qual = 100;
3418         else if (sig_qual < 1)
3419                 sig_qual = 0;
3420
3421         return sig_qual;
3422 }
3423
3424 /**
3425  * iwl3945_rx_handle - Main entry function for receiving responses from uCode
3426  *
3427  * Uses the priv->rx_handlers callback function array to invoke
3428  * the appropriate handlers, including command responses,
3429  * frame-received notifications, and other notifications.
3430  */
3431 static void iwl3945_rx_handle(struct iwl_priv *priv)
3432 {
3433         struct iwl_rx_mem_buffer *rxb;
3434         struct iwl_rx_packet *pkt;
3435         struct iwl_rx_queue *rxq = &priv->rxq;
3436         u32 r, i;
3437         int reclaim;
3438         unsigned long flags;
3439         u8 fill_rx = 0;
3440         u32 count = 8;
3441
3442         /* uCode's read index (stored in shared DRAM) indicates the last Rx
3443          * buffer that the driver may process (last buffer filled by ucode). */
3444         r = le16_to_cpu(rxq->rb_stts->closed_rb_num) &  0x0FFF;
3445         i = rxq->read;
3446
3447         if (iwl_rx_queue_space(rxq) > (RX_QUEUE_SIZE / 2))
3448                 fill_rx = 1;
3449         /* Rx interrupt, but nothing sent from uCode */
3450         if (i == r)
3451                 IWL_DEBUG(IWL_DL_RX | IWL_DL_ISR, "r = %d, i = %d\n", r, i);
3452
3453         while (i != r) {
3454                 rxb = rxq->queue[i];
3455
3456                 /* If an RXB doesn't have a Rx queue slot associated with it,
3457                  * then a bug has been introduced in the queue refilling
3458                  * routines -- catch it here */
3459                 BUG_ON(rxb == NULL);
3460
3461                 rxq->queue[i] = NULL;
3462
3463                 pci_dma_sync_single_for_cpu(priv->pci_dev, rxb->real_dma_addr,
3464                                             IWL_RX_BUF_SIZE,
3465                                             PCI_DMA_FROMDEVICE);
3466                 pkt = (struct iwl_rx_packet *)rxb->skb->data;
3467
3468                 /* Reclaim a command buffer only if this packet is a response
3469                  *   to a (driver-originated) command.
3470                  * If the packet (e.g. Rx frame) originated from uCode,
3471                  *   there is no command buffer to reclaim.
3472                  * Ucode should set SEQ_RX_FRAME bit if ucode-originated,
3473                  *   but apparently a few don't get set; catch them here. */
3474                 reclaim = !(pkt->hdr.sequence & SEQ_RX_FRAME) &&
3475                         (pkt->hdr.cmd != STATISTICS_NOTIFICATION) &&
3476                         (pkt->hdr.cmd != REPLY_TX);
3477
3478                 /* Based on type of command response or notification,
3479                  *   handle those that need handling via function in
3480                  *   rx_handlers table.  See iwl3945_setup_rx_handlers() */
3481                 if (priv->rx_handlers[pkt->hdr.cmd]) {
3482                         IWL_DEBUG(IWL_DL_HCMD | IWL_DL_RX | IWL_DL_ISR,
3483                                 "r = %d, i = %d, %s, 0x%02x\n", r, i,
3484                                 get_cmd_string(pkt->hdr.cmd), pkt->hdr.cmd);
3485                         priv->rx_handlers[pkt->hdr.cmd] (priv, rxb);
3486                 } else {
3487                         /* No handling needed */
3488                         IWL_DEBUG(IWL_DL_HCMD | IWL_DL_RX | IWL_DL_ISR,
3489                                 "r %d i %d No handler needed for %s, 0x%02x\n",
3490                                 r, i, get_cmd_string(pkt->hdr.cmd),
3491                                 pkt->hdr.cmd);
3492                 }
3493
3494                 if (reclaim) {
3495                         /* Invoke any callbacks, transfer the skb to caller, and
3496                          * fire off the (possibly) blocking iwl3945_send_cmd()
3497                          * as we reclaim the driver command queue */
3498                         if (rxb && rxb->skb)
3499                                 iwl3945_tx_cmd_complete(priv, rxb);
3500                         else
3501                                 IWL_WARN(priv, "Claim null rxb?\n");
3502                 }
3503
3504                 /* For now we just don't re-use anything.  We can tweak this
3505                  * later to try and re-use notification packets and SKBs that
3506                  * fail to Rx correctly */
3507                 if (rxb->skb != NULL) {
3508                         priv->alloc_rxb_skb--;
3509                         dev_kfree_skb_any(rxb->skb);
3510                         rxb->skb = NULL;
3511                 }
3512
3513                 pci_unmap_single(priv->pci_dev, rxb->real_dma_addr,
3514                                  IWL_RX_BUF_SIZE, PCI_DMA_FROMDEVICE);
3515                 spin_lock_irqsave(&rxq->lock, flags);
3516                 list_add_tail(&rxb->list, &priv->rxq.rx_used);
3517                 spin_unlock_irqrestore(&rxq->lock, flags);
3518                 i = (i + 1) & RX_QUEUE_MASK;
3519                 /* If there are a lot of unused frames,
3520                  * restock the Rx queue so ucode won't assert. */
3521                 if (fill_rx) {
3522                         count++;
3523                         if (count >= 8) {
3524                                 priv->rxq.read = i;
3525                                 __iwl3945_rx_replenish(priv);
3526                                 count = 0;
3527                         }
3528                 }
3529         }
3530
3531         /* Backtrack one entry */
3532         priv->rxq.read = i;
3533         iwl3945_rx_queue_restock(priv);
3534 }
3535
3536 /**
3537  * iwl3945_tx_queue_update_write_ptr - Send new write index to hardware
3538  */
3539 static int iwl3945_tx_queue_update_write_ptr(struct iwl_priv *priv,
3540                                   struct iwl_tx_queue *txq)
3541 {
3542         u32 reg = 0;
3543         int rc = 0;
3544         int txq_id = txq->q.id;
3545
3546         if (txq->need_update == 0)
3547                 return rc;
3548
3549         /* if we're trying to save power */
3550         if (test_bit(STATUS_POWER_PMI, &priv->status)) {
3551                 /* wake up nic if it's powered down ...
3552                  * uCode will wake up, and interrupt us again, so next
3553                  * time we'll skip this part. */
3554                 reg = iwl_read32(priv, CSR_UCODE_DRV_GP1);
3555
3556                 if (reg & CSR_UCODE_DRV_GP1_BIT_MAC_SLEEP) {
3557                         IWL_DEBUG_INFO("Requesting wakeup, GP1 = 0x%x\n", reg);
3558                         iwl_set_bit(priv, CSR_GP_CNTRL,
3559                                     CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
3560                         return rc;
3561                 }
3562
3563                 /* restore this queue's parameters in nic hardware. */
3564                 rc = iwl_grab_nic_access(priv);
3565                 if (rc)
3566                         return rc;
3567                 iwl_write_direct32(priv, HBUS_TARG_WRPTR,
3568                                      txq->q.write_ptr | (txq_id << 8));
3569                 iwl_release_nic_access(priv);
3570
3571         /* else not in power-save mode, uCode will never sleep when we're
3572          * trying to tx (during RFKILL, we're not trying to tx). */
3573         } else
3574                 iwl_write32(priv, HBUS_TARG_WRPTR,
3575                             txq->q.write_ptr | (txq_id << 8));
3576
3577         txq->need_update = 0;
3578
3579         return rc;
3580 }
3581
3582 #ifdef CONFIG_IWL3945_DEBUG
3583 static void iwl3945_print_rx_config_cmd(struct iwl_priv *priv,
3584                                         struct iwl3945_rxon_cmd *rxon)
3585 {
3586         IWL_DEBUG_RADIO("RX CONFIG:\n");
3587         iwl_print_hex_dump(priv, IWL_DL_RADIO, (u8 *) rxon, sizeof(*rxon));
3588         IWL_DEBUG_RADIO("u16 channel: 0x%x\n", le16_to_cpu(rxon->channel));
3589         IWL_DEBUG_RADIO("u32 flags: 0x%08X\n", le32_to_cpu(rxon->flags));
3590         IWL_DEBUG_RADIO("u32 filter_flags: 0x%08x\n",
3591                         le32_to_cpu(rxon->filter_flags));
3592         IWL_DEBUG_RADIO("u8 dev_type: 0x%x\n", rxon->dev_type);
3593         IWL_DEBUG_RADIO("u8 ofdm_basic_rates: 0x%02x\n",
3594                         rxon->ofdm_basic_rates);
3595         IWL_DEBUG_RADIO("u8 cck_basic_rates: 0x%02x\n", rxon->cck_basic_rates);
3596         IWL_DEBUG_RADIO("u8[6] node_addr: %pM\n", rxon->node_addr);
3597         IWL_DEBUG_RADIO("u8[6] bssid_addr: %pM\n", rxon->bssid_addr);
3598         IWL_DEBUG_RADIO("u16 assoc_id: 0x%x\n", le16_to_cpu(rxon->assoc_id));
3599 }
3600 #endif
3601
3602 static void iwl3945_enable_interrupts(struct iwl_priv *priv)
3603 {
3604         IWL_DEBUG_ISR("Enabling interrupts\n");
3605         set_bit(STATUS_INT_ENABLED, &priv->status);
3606         iwl_write32(priv, CSR_INT_MASK, CSR_INI_SET_MASK);
3607 }
3608
3609
3610 /* call this function to flush any scheduled tasklet */
3611 static inline void iwl_synchronize_irq(struct iwl_priv *priv)
3612 {
3613         /* wait to make sure we flush pending tasklet*/
3614         synchronize_irq(priv->pci_dev->irq);
3615         tasklet_kill(&priv->irq_tasklet);
3616 }
3617
3618
3619 static inline void iwl3945_disable_interrupts(struct iwl_priv *priv)
3620 {
3621         clear_bit(STATUS_INT_ENABLED, &priv->status);
3622
3623         /* disable interrupts from uCode/NIC to host */
3624         iwl_write32(priv, CSR_INT_MASK, 0x00000000);
3625
3626         /* acknowledge/clear/reset any interrupts still pending
3627          * from uCode or flow handler (Rx/Tx DMA) */
3628         iwl_write32(priv, CSR_INT, 0xffffffff);
3629         iwl_write32(priv, CSR_FH_INT_STATUS, 0xffffffff);
3630         IWL_DEBUG_ISR("Disabled interrupts\n");
3631 }
3632
3633 static const char *desc_lookup(int i)
3634 {
3635         switch (i) {
3636         case 1:
3637                 return "FAIL";
3638         case 2:
3639                 return "BAD_PARAM";
3640         case 3:
3641                 return "BAD_CHECKSUM";
3642         case 4:
3643                 return "NMI_INTERRUPT";
3644         case 5:
3645                 return "SYSASSERT";
3646         case 6:
3647                 return "FATAL_ERROR";
3648         }
3649
3650         return "UNKNOWN";
3651 }
3652
3653 #define ERROR_START_OFFSET  (1 * sizeof(u32))
3654 #define ERROR_ELEM_SIZE     (7 * sizeof(u32))
3655
3656 static void iwl3945_dump_nic_error_log(struct iwl_priv *priv)
3657 {
3658         u32 i;
3659         u32 desc, time, count, base, data1;
3660         u32 blink1, blink2, ilink1, ilink2;
3661         int rc;
3662
3663         base = le32_to_cpu(priv->card_alive.error_event_table_ptr);
3664
3665         if (!iwl3945_hw_valid_rtc_data_addr(base)) {
3666                 IWL_ERR(priv, "Not valid error log pointer 0x%08X\n", base);
3667                 return;
3668         }
3669
3670         rc = iwl_grab_nic_access(priv);
3671         if (rc) {
3672                 IWL_WARN(priv, "Can not read from adapter at this time.\n");
3673                 return;
3674         }
3675
3676         count = iwl_read_targ_mem(priv, base);
3677
3678         if (ERROR_START_OFFSET <= count * ERROR_ELEM_SIZE) {
3679                 IWL_ERR(priv, "Start IWL Error Log Dump:\n");
3680                 IWL_ERR(priv, "Status: 0x%08lX, count: %d\n",
3681                         priv->status, count);
3682         }
3683
3684         IWL_ERR(priv, "Desc       Time       asrtPC  blink2 "
3685                   "ilink1  nmiPC   Line\n");
3686         for (i = ERROR_START_OFFSET;
3687              i < (count * ERROR_ELEM_SIZE) + ERROR_START_OFFSET;
3688              i += ERROR_ELEM_SIZE) {
3689                 desc = iwl_read_targ_mem(priv, base + i);
3690                 time =
3691                     iwl_read_targ_mem(priv, base + i + 1 * sizeof(u32));
3692                 blink1 =
3693                     iwl_read_targ_mem(priv, base + i + 2 * sizeof(u32));
3694                 blink2 =
3695                     iwl_read_targ_mem(priv, base + i + 3 * sizeof(u32));
3696                 ilink1 =
3697                     iwl_read_targ_mem(priv, base + i + 4 * sizeof(u32));
3698                 ilink2 =
3699                     iwl_read_targ_mem(priv, base + i + 5 * sizeof(u32));
3700                 data1 =
3701                     iwl_read_targ_mem(priv, base + i + 6 * sizeof(u32));
3702
3703                 IWL_ERR(priv,
3704                         "%-13s (#%d) %010u 0x%05X 0x%05X 0x%05X 0x%05X %u\n\n",
3705                         desc_lookup(desc), desc, time, blink1, blink2,
3706                         ilink1, ilink2, data1);
3707         }
3708
3709         iwl_release_nic_access(priv);
3710
3711 }
3712
3713 #define EVENT_START_OFFSET  (6 * sizeof(u32))
3714
3715 /**
3716  * iwl3945_print_event_log - Dump error event log to syslog
3717  *
3718  * NOTE: Must be called with iwl_grab_nic_access() already obtained!
3719  */
3720 static void iwl3945_print_event_log(struct iwl_priv *priv, u32 start_idx,
3721                                 u32 num_events, u32 mode)
3722 {
3723         u32 i;
3724         u32 base;       /* SRAM byte address of event log header */
3725         u32 event_size; /* 2 u32s, or 3 u32s if timestamp recorded */
3726         u32 ptr;        /* SRAM byte address of log data */
3727         u32 ev, time, data; /* event log data */
3728
3729         if (num_events == 0)
3730                 return;
3731
3732         base = le32_to_cpu(priv->card_alive.log_event_table_ptr);
3733
3734         if (mode == 0)
3735                 event_size = 2 * sizeof(u32);
3736         else
3737                 event_size = 3 * sizeof(u32);
3738
3739         ptr = base + EVENT_START_OFFSET + (start_idx * event_size);
3740
3741         /* "time" is actually "data" for mode 0 (no timestamp).
3742          * place event id # at far right for easier visual parsing. */
3743         for (i = 0; i < num_events; i++) {
3744                 ev = iwl_read_targ_mem(priv, ptr);
3745                 ptr += sizeof(u32);
3746                 time = iwl_read_targ_mem(priv, ptr);
3747                 ptr += sizeof(u32);
3748                 if (mode == 0) {
3749                         /* data, ev */
3750                         IWL_ERR(priv, "0x%08x\t%04u\n", time, ev);
3751                 } else {
3752                         data = iwl_read_targ_mem(priv, ptr);
3753                         ptr += sizeof(u32);
3754                         IWL_ERR(priv, "%010u\t0x%08x\t%04u\n", time, data, ev);
3755                 }
3756         }
3757 }
3758
3759 static void iwl3945_dump_nic_event_log(struct iwl_priv *priv)
3760 {
3761         int rc;
3762         u32 base;       /* SRAM byte address of event log header */
3763         u32 capacity;   /* event log capacity in # entries */
3764         u32 mode;       /* 0 - no timestamp, 1 - timestamp recorded */
3765         u32 num_wraps;  /* # times uCode wrapped to top of log */
3766         u32 next_entry; /* index of next entry to be written by uCode */
3767         u32 size;       /* # entries that we'll print */
3768
3769         base = le32_to_cpu(priv->card_alive.log_event_table_ptr);
3770         if (!iwl3945_hw_valid_rtc_data_addr(base)) {
3771                 IWL_ERR(priv, "Invalid event log pointer 0x%08X\n", base);
3772                 return;
3773         }
3774
3775         rc = iwl_grab_nic_access(priv);
3776         if (rc) {
3777                 IWL_WARN(priv, "Can not read from adapter at this time.\n");
3778                 return;
3779         }
3780
3781         /* event log header */
3782         capacity = iwl_read_targ_mem(priv, base);
3783         mode = iwl_read_targ_mem(priv, base + (1 * sizeof(u32)));
3784         num_wraps = iwl_read_targ_mem(priv, base + (2 * sizeof(u32)));
3785         next_entry = iwl_read_targ_mem(priv, base + (3 * sizeof(u32)));
3786
3787         size = num_wraps ? capacity : next_entry;
3788
3789         /* bail out if nothing in log */
3790         if (size == 0) {
3791                 IWL_ERR(priv, "Start IWL Event Log Dump: nothing in log\n");
3792                 iwl_release_nic_access(priv);
3793                 return;
3794         }
3795
3796         IWL_ERR(priv, "Start IWL Event Log Dump: display count %d, wraps %d\n",
3797                   size, num_wraps);
3798
3799         /* if uCode has wrapped back to top of log, start at the oldest entry,
3800          * i.e the next one that uCode would fill. */
3801         if (num_wraps)
3802                 iwl3945_print_event_log(priv, next_entry,
3803                                     capacity - next_entry, mode);
3804
3805         /* (then/else) start at top of log */
3806         iwl3945_print_event_log(priv, 0, next_entry, mode);
3807
3808         iwl_release_nic_access(priv);
3809 }
3810
3811 /**
3812  * iwl3945_irq_handle_error - called for HW or SW error interrupt from card
3813  */
3814 static void iwl3945_irq_handle_error(struct iwl_priv *priv)
3815 {
3816         /* Set the FW error flag -- cleared on iwl3945_down */
3817         set_bit(STATUS_FW_ERROR, &priv->status);
3818
3819         /* Cancel currently queued command. */
3820         clear_bit(STATUS_HCMD_ACTIVE, &priv->status);
3821
3822 #ifdef CONFIG_IWL3945_DEBUG
3823         if (priv->debug_level & IWL_DL_FW_ERRORS) {
3824                 iwl3945_dump_nic_error_log(priv);
3825                 iwl3945_dump_nic_event_log(priv);
3826                 iwl3945_print_rx_config_cmd(priv, &priv->staging39_rxon);
3827         }
3828 #endif
3829
3830         wake_up_interruptible(&priv->wait_command_queue);
3831
3832         /* Keep the restart process from trying to send host
3833          * commands by clearing the INIT status bit */
3834         clear_bit(STATUS_READY, &priv->status);
3835
3836         if (!test_bit(STATUS_EXIT_PENDING, &priv->status)) {
3837                 IWL_DEBUG(IWL_DL_INFO | IWL_DL_FW_ERRORS,
3838                           "Restarting adapter due to uCode error.\n");
3839
3840                 if (iwl3945_is_associated(priv)) {
3841                         memcpy(&priv->recovery39_rxon, &priv->active39_rxon,
3842                                sizeof(priv->recovery39_rxon));
3843                         priv->error_recovering = 1;
3844                 }
3845                 queue_work(priv->workqueue, &priv->restart);
3846         }
3847 }
3848
3849 static void iwl3945_error_recovery(struct iwl_priv *priv)
3850 {
3851         unsigned long flags;
3852
3853         memcpy(&priv->staging39_rxon, &priv->recovery39_rxon,
3854                sizeof(priv->staging39_rxon));
3855         priv->staging39_rxon.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
3856         iwl3945_commit_rxon(priv);
3857
3858         iwl3945_add_station(priv, priv->bssid, 1, 0);
3859
3860         spin_lock_irqsave(&priv->lock, flags);
3861         priv->assoc_id = le16_to_cpu(priv->staging39_rxon.assoc_id);
3862         priv->error_recovering = 0;
3863         spin_unlock_irqrestore(&priv->lock, flags);
3864 }
3865
3866 static void iwl3945_irq_tasklet(struct iwl_priv *priv)
3867 {
3868         u32 inta, handled = 0;
3869         u32 inta_fh;
3870         unsigned long flags;
3871 #ifdef CONFIG_IWL3945_DEBUG
3872         u32 inta_mask;
3873 #endif
3874
3875         spin_lock_irqsave(&priv->lock, flags);
3876
3877         /* Ack/clear/reset pending uCode interrupts.
3878          * Note:  Some bits in CSR_INT are "OR" of bits in CSR_FH_INT_STATUS,
3879          *  and will clear only when CSR_FH_INT_STATUS gets cleared. */
3880         inta = iwl_read32(priv, CSR_INT);
3881         iwl_write32(priv, CSR_INT, inta);
3882
3883         /* Ack/clear/reset pending flow-handler (DMA) interrupts.
3884          * Any new interrupts that happen after this, either while we're
3885          * in this tasklet, or later, will show up in next ISR/tasklet. */
3886         inta_fh = iwl_read32(priv, CSR_FH_INT_STATUS);
3887         iwl_write32(priv, CSR_FH_INT_STATUS, inta_fh);
3888
3889 #ifdef CONFIG_IWL3945_DEBUG
3890         if (priv->debug_level & IWL_DL_ISR) {
3891                 /* just for debug */
3892                 inta_mask = iwl_read32(priv, CSR_INT_MASK);
3893                 IWL_DEBUG_ISR("inta 0x%08x, enabled 0x%08x, fh 0x%08x\n",
3894                               inta, inta_mask, inta_fh);
3895         }
3896 #endif
3897
3898         /* Since CSR_INT and CSR_FH_INT_STATUS reads and clears are not
3899          * atomic, make sure that inta covers all the interrupts that
3900          * we've discovered, even if FH interrupt came in just after
3901          * reading CSR_INT. */
3902         if (inta_fh & CSR39_FH_INT_RX_MASK)
3903                 inta |= CSR_INT_BIT_FH_RX;
3904         if (inta_fh & CSR39_FH_INT_TX_MASK)
3905                 inta |= CSR_INT_BIT_FH_TX;
3906
3907         /* Now service all interrupt bits discovered above. */
3908         if (inta & CSR_INT_BIT_HW_ERR) {
3909                 IWL_ERR(priv, "Microcode HW error detected.  Restarting.\n");
3910
3911                 /* Tell the device to stop sending interrupts */
3912                 iwl3945_disable_interrupts(priv);
3913
3914                 iwl3945_irq_handle_error(priv);
3915
3916                 handled |= CSR_INT_BIT_HW_ERR;
3917
3918                 spin_unlock_irqrestore(&priv->lock, flags);
3919
3920                 return;
3921         }
3922
3923 #ifdef CONFIG_IWL3945_DEBUG
3924         if (priv->debug_level & (IWL_DL_ISR)) {
3925                 /* NIC fires this, but we don't use it, redundant with WAKEUP */
3926                 if (inta & CSR_INT_BIT_SCD)
3927                         IWL_DEBUG_ISR("Scheduler finished to transmit "
3928                                       "the frame/frames.\n");
3929
3930                 /* Alive notification via Rx interrupt will do the real work */
3931                 if (inta & CSR_INT_BIT_ALIVE)
3932                         IWL_DEBUG_ISR("Alive interrupt\n");
3933         }
3934 #endif
3935         /* Safely ignore these bits for debug checks below */
3936         inta &= ~(CSR_INT_BIT_SCD | CSR_INT_BIT_ALIVE);
3937
3938         /* Error detected by uCode */
3939         if (inta & CSR_INT_BIT_SW_ERR) {
3940                 IWL_ERR(priv, "Microcode SW error detected. "
3941                         "Restarting 0x%X.\n", inta);
3942                 iwl3945_irq_handle_error(priv);
3943                 handled |= CSR_INT_BIT_SW_ERR;
3944         }
3945
3946         /* uCode wakes up after power-down sleep */
3947         if (inta & CSR_INT_BIT_WAKEUP) {
3948                 IWL_DEBUG_ISR("Wakeup interrupt\n");
3949                 iwl_rx_queue_update_write_ptr(priv, &priv->rxq);
3950                 iwl3945_tx_queue_update_write_ptr(priv, &priv->txq[0]);
3951                 iwl3945_tx_queue_update_write_ptr(priv, &priv->txq[1]);
3952                 iwl3945_tx_queue_update_write_ptr(priv, &priv->txq[2]);
3953                 iwl3945_tx_queue_update_write_ptr(priv, &priv->txq[3]);
3954                 iwl3945_tx_queue_update_write_ptr(priv, &priv->txq[4]);
3955                 iwl3945_tx_queue_update_write_ptr(priv, &priv->txq[5]);
3956
3957                 handled |= CSR_INT_BIT_WAKEUP;
3958         }
3959
3960         /* All uCode command responses, including Tx command responses,
3961          * Rx "responses" (frame-received notification), and other
3962          * notifications from uCode come through here*/
3963         if (inta & (CSR_INT_BIT_FH_RX | CSR_INT_BIT_SW_RX)) {
3964                 iwl3945_rx_handle(priv);
3965                 handled |= (CSR_INT_BIT_FH_RX | CSR_INT_BIT_SW_RX);
3966         }
3967
3968         if (inta & CSR_INT_BIT_FH_TX) {
3969                 IWL_DEBUG_ISR("Tx interrupt\n");
3970
3971                 iwl_write32(priv, CSR_FH_INT_STATUS, (1 << 6));
3972                 if (!iwl_grab_nic_access(priv)) {
3973                         iwl_write_direct32(priv, FH39_TCSR_CREDIT
3974                                              (FH39_SRVC_CHNL), 0x0);
3975                         iwl_release_nic_access(priv);
3976                 }
3977                 handled |= CSR_INT_BIT_FH_TX;
3978         }
3979
3980         if (inta & ~handled)
3981                 IWL_ERR(priv, "Unhandled INTA bits 0x%08x\n", inta & ~handled);
3982
3983         if (inta & ~CSR_INI_SET_MASK) {
3984                 IWL_WARN(priv, "Disabled INTA bits 0x%08x were pending\n",
3985                          inta & ~CSR_INI_SET_MASK);
3986                 IWL_WARN(priv, "   with FH_INT = 0x%08x\n", inta_fh);
3987         }
3988
3989         /* Re-enable all interrupts */
3990         /* only Re-enable if disabled by irq */
3991         if (test_bit(STATUS_INT_ENABLED, &priv->status))
3992                 iwl3945_enable_interrupts(priv);
3993
3994 #ifdef CONFIG_IWL3945_DEBUG
3995         if (priv->debug_level & (IWL_DL_ISR)) {
3996                 inta = iwl_read32(priv, CSR_INT);
3997                 inta_mask = iwl_read32(priv, CSR_INT_MASK);
3998                 inta_fh = iwl_read32(priv, CSR_FH_INT_STATUS);
3999                 IWL_DEBUG_ISR("End inta 0x%08x, enabled 0x%08x, fh 0x%08x, "
4000                         "flags 0x%08lx\n", inta, inta_mask, inta_fh, flags);
4001         }
4002 #endif
4003         spin_unlock_irqrestore(&priv->lock, flags);
4004 }
4005
4006 static irqreturn_t iwl3945_isr(int irq, void *data)
4007 {
4008         struct iwl_priv *priv = data;
4009         u32 inta, inta_mask;
4010         u32 inta_fh;
4011         if (!priv)
4012                 return IRQ_NONE;
4013
4014         spin_lock(&priv->lock);
4015
4016         /* Disable (but don't clear!) interrupts here to avoid
4017          *    back-to-back ISRs and sporadic interrupts from our NIC.
4018          * If we have something to service, the tasklet will re-enable ints.
4019          * If we *don't* have something, we'll re-enable before leaving here. */
4020         inta_mask = iwl_read32(priv, CSR_INT_MASK);  /* just for debug */
4021         iwl_write32(priv, CSR_INT_MASK, 0x00000000);
4022
4023         /* Discover which interrupts are active/pending */
4024         inta = iwl_read32(priv, CSR_INT);
4025         inta_fh = iwl_read32(priv, CSR_FH_INT_STATUS);
4026
4027         /* Ignore interrupt if there's nothing in NIC to service.
4028          * This may be due to IRQ shared with another device,
4029          * or due to sporadic interrupts thrown from our NIC. */
4030         if (!inta && !inta_fh) {
4031                 IWL_DEBUG_ISR("Ignore interrupt, inta == 0, inta_fh == 0\n");
4032                 goto none;
4033         }
4034
4035         if ((inta == 0xFFFFFFFF) || ((inta & 0xFFFFFFF0) == 0xa5a5a5a0)) {
4036                 /* Hardware disappeared */
4037                 IWL_WARN(priv, "HARDWARE GONE?? INTA == 0x%08x\n", inta);
4038                 goto unplugged;
4039         }
4040
4041         IWL_DEBUG_ISR("ISR inta 0x%08x, enabled 0x%08x, fh 0x%08x\n",
4042                       inta, inta_mask, inta_fh);
4043
4044         inta &= ~CSR_INT_BIT_SCD;
4045
4046         /* iwl3945_irq_tasklet() will service interrupts and re-enable them */
4047         if (likely(inta || inta_fh))
4048                 tasklet_schedule(&priv->irq_tasklet);
4049 unplugged:
4050         spin_unlock(&priv->lock);
4051
4052         return IRQ_HANDLED;
4053
4054  none:
4055         /* re-enable interrupts here since we don't have anything to service. */
4056         /* only Re-enable if disabled by irq */
4057         if (test_bit(STATUS_INT_ENABLED, &priv->status))
4058                 iwl3945_enable_interrupts(priv);
4059         spin_unlock(&priv->lock);
4060         return IRQ_NONE;
4061 }
4062
4063 /************************** EEPROM BANDS ****************************
4064  *
4065  * The iwl3945_eeprom_band definitions below provide the mapping from the
4066  * EEPROM contents to the specific channel number supported for each
4067  * band.
4068  *
4069  * For example, iwl3945_priv->eeprom39.band_3_channels[4] from the band_3
4070  * definition below maps to physical channel 42 in the 5.2GHz spectrum.
4071  * The specific geography and calibration information for that channel
4072  * is contained in the eeprom map itself.
4073  *
4074  * During init, we copy the eeprom information and channel map
4075  * information into priv->channel_info_24/52 and priv->channel_map_24/52
4076  *
4077  * channel_map_24/52 provides the index in the channel_info array for a
4078  * given channel.  We have to have two separate maps as there is channel
4079  * overlap with the 2.4GHz and 5.2GHz spectrum as seen in band_1 and
4080  * band_2
4081  *
4082  * A value of 0xff stored in the channel_map indicates that the channel
4083  * is not supported by the hardware at all.
4084  *
4085  * A value of 0xfe in the channel_map indicates that the channel is not
4086  * valid for Tx with the current hardware.  This means that
4087  * while the system can tune and receive on a given channel, it may not
4088  * be able to associate or transmit any frames on that
4089  * channel.  There is no corresponding channel information for that
4090  * entry.
4091  *
4092  *********************************************************************/
4093
4094 /* 2.4 GHz */
4095 static const u8 iwl3945_eeprom_band_1[14] = {
4096         1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14
4097 };
4098
4099 /* 5.2 GHz bands */
4100 static const u8 iwl3945_eeprom_band_2[] = {     /* 4915-5080MHz */
4101         183, 184, 185, 187, 188, 189, 192, 196, 7, 8, 11, 12, 16
4102 };
4103
4104 static const u8 iwl3945_eeprom_band_3[] = {     /* 5170-5320MHz */
4105         34, 36, 38, 40, 42, 44, 46, 48, 52, 56, 60, 64
4106 };
4107
4108 static const u8 iwl3945_eeprom_band_4[] = {     /* 5500-5700MHz */
4109         100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140
4110 };
4111
4112 static const u8 iwl3945_eeprom_band_5[] = {     /* 5725-5825MHz */
4113         145, 149, 153, 157, 161, 165
4114 };
4115
4116 static void iwl3945_init_band_reference(const struct iwl_priv *priv, int band,
4117                                     int *eeprom_ch_count,
4118                                     const struct iwl_eeprom_channel
4119                                     **eeprom_ch_info,
4120                                     const u8 **eeprom_ch_index)
4121 {
4122         switch (band) {
4123         case 1:         /* 2.4GHz band */
4124                 *eeprom_ch_count = ARRAY_SIZE(iwl3945_eeprom_band_1);
4125                 *eeprom_ch_info = priv->eeprom39.band_1_channels;
4126                 *eeprom_ch_index = iwl3945_eeprom_band_1;
4127                 break;
4128         case 2:         /* 4.9GHz band */
4129                 *eeprom_ch_count = ARRAY_SIZE(iwl3945_eeprom_band_2);
4130                 *eeprom_ch_info = priv->eeprom39.band_2_channels;
4131                 *eeprom_ch_index = iwl3945_eeprom_band_2;
4132                 break;
4133         case 3:         /* 5.2GHz band */
4134                 *eeprom_ch_count = ARRAY_SIZE(iwl3945_eeprom_band_3);
4135                 *eeprom_ch_info = priv->eeprom39.band_3_channels;
4136                 *eeprom_ch_index = iwl3945_eeprom_band_3;
4137                 break;
4138         case 4:         /* 5.5GHz band */
4139                 *eeprom_ch_count = ARRAY_SIZE(iwl3945_eeprom_band_4);
4140                 *eeprom_ch_info = priv->eeprom39.band_4_channels;
4141                 *eeprom_ch_index = iwl3945_eeprom_band_4;
4142                 break;
4143         case 5:         /* 5.7GHz band */
4144                 *eeprom_ch_count = ARRAY_SIZE(iwl3945_eeprom_band_5);
4145                 *eeprom_ch_info = priv->eeprom39.band_5_channels;
4146                 *eeprom_ch_index = iwl3945_eeprom_band_5;
4147                 break;
4148         default:
4149                 BUG();
4150                 return;
4151         }
4152 }
4153
4154 /**
4155  * iwl3945_get_channel_info - Find driver's private channel info
4156  *
4157  * Based on band and channel number.
4158  */
4159 const struct iwl_channel_info *
4160 iwl3945_get_channel_info(const struct iwl_priv *priv,
4161                          enum ieee80211_band band, u16 channel)
4162 {
4163         int i;
4164
4165         switch (band) {
4166         case IEEE80211_BAND_5GHZ:
4167                 for (i = 14; i < priv->channel_count; i++) {
4168                         if (priv->channel_info[i].channel == channel)
4169                                 return &priv->channel_info[i];
4170                 }
4171                 break;
4172
4173         case IEEE80211_BAND_2GHZ:
4174                 if (channel >= 1 && channel <= 14)
4175                         return &priv->channel_info[channel - 1];
4176                 break;
4177         case IEEE80211_NUM_BANDS:
4178                 WARN_ON(1);
4179         }
4180
4181         return NULL;
4182 }
4183
4184 #define CHECK_AND_PRINT(x) ((eeprom_ch_info[ch].flags & EEPROM_CHANNEL_##x) \
4185                             ? # x " " : "")
4186
4187 /**
4188  * iwl3945_init_channel_map - Set up driver's info for all possible channels
4189  */
4190 static int iwl3945_init_channel_map(struct iwl_priv *priv)
4191 {
4192         int eeprom_ch_count = 0;
4193         const u8 *eeprom_ch_index = NULL;
4194         const struct iwl_eeprom_channel *eeprom_ch_info = NULL;
4195         int band, ch;
4196         struct iwl_channel_info *ch_info;
4197
4198         if (priv->channel_count) {
4199                 IWL_DEBUG_INFO("Channel map already initialized.\n");
4200                 return 0;
4201         }
4202
4203         if (priv->eeprom39.version < 0x2f) {
4204                 IWL_WARN(priv, "Unsupported EEPROM version: 0x%04X\n",
4205                             priv->eeprom39.version);
4206                 return -EINVAL;
4207         }
4208
4209         IWL_DEBUG_INFO("Initializing regulatory info from EEPROM\n");
4210
4211         priv->channel_count =
4212             ARRAY_SIZE(iwl3945_eeprom_band_1) +
4213             ARRAY_SIZE(iwl3945_eeprom_band_2) +
4214             ARRAY_SIZE(iwl3945_eeprom_band_3) +
4215             ARRAY_SIZE(iwl3945_eeprom_band_4) +
4216             ARRAY_SIZE(iwl3945_eeprom_band_5);
4217
4218         IWL_DEBUG_INFO("Parsing data for %d channels.\n", priv->channel_count);
4219
4220         priv->channel_info = kzalloc(sizeof(struct iwl_channel_info) *
4221                                      priv->channel_count, GFP_KERNEL);
4222         if (!priv->channel_info) {
4223                 IWL_ERR(priv, "Could not allocate channel_info\n");
4224                 priv->channel_count = 0;
4225                 return -ENOMEM;
4226         }
4227
4228         ch_info = priv->channel_info;
4229
4230         /* Loop through the 5 EEPROM bands adding them in order to the
4231          * channel map we maintain (that contains additional information than
4232          * what just in the EEPROM) */
4233         for (band = 1; band <= 5; band++) {
4234
4235                 iwl3945_init_band_reference(priv, band, &eeprom_ch_count,
4236                                         &eeprom_ch_info, &eeprom_ch_index);
4237
4238                 /* Loop through each band adding each of the channels */
4239                 for (ch = 0; ch < eeprom_ch_count; ch++) {
4240                         ch_info->channel = eeprom_ch_index[ch];
4241                         ch_info->band = (band == 1) ? IEEE80211_BAND_2GHZ :
4242                             IEEE80211_BAND_5GHZ;
4243
4244                         /* permanently store EEPROM's channel regulatory flags
4245                          *   and max power in channel info database. */
4246                         ch_info->eeprom = eeprom_ch_info[ch];
4247
4248                         /* Copy the run-time flags so they are there even on
4249                          * invalid channels */
4250                         ch_info->flags = eeprom_ch_info[ch].flags;
4251
4252                         if (!(is_channel_valid(ch_info))) {
4253                                 IWL_DEBUG_INFO("Ch. %d Flags %x [%sGHz] - "
4254                                                "No traffic\n",
4255                                                ch_info->channel,
4256                                                ch_info->flags,
4257                                                is_channel_a_band(ch_info) ?
4258                                                "5.2" : "2.4");
4259                                 ch_info++;
4260                                 continue;
4261                         }
4262
4263                         /* Initialize regulatory-based run-time data */
4264                         ch_info->max_power_avg = ch_info->curr_txpow =
4265                             eeprom_ch_info[ch].max_power_avg;
4266                         ch_info->scan_power = eeprom_ch_info[ch].max_power_avg;
4267                         ch_info->min_power = 0;
4268
4269                         IWL_DEBUG_INFO("Ch. %d [%sGHz] %s%s%s%s%s%s(0x%02x"
4270                                        " %ddBm): Ad-Hoc %ssupported\n",
4271                                        ch_info->channel,
4272                                        is_channel_a_band(ch_info) ?
4273                                        "5.2" : "2.4",
4274                                        CHECK_AND_PRINT(VALID),
4275                                        CHECK_AND_PRINT(IBSS),
4276                                        CHECK_AND_PRINT(ACTIVE),
4277                                        CHECK_AND_PRINT(RADAR),
4278                                        CHECK_AND_PRINT(WIDE),
4279                                        CHECK_AND_PRINT(DFS),
4280                                        eeprom_ch_info[ch].flags,
4281                                        eeprom_ch_info[ch].max_power_avg,
4282                                        ((eeprom_ch_info[ch].
4283                                          flags & EEPROM_CHANNEL_IBSS)
4284                                         && !(eeprom_ch_info[ch].
4285                                              flags & EEPROM_CHANNEL_RADAR))
4286                                        ? "" : "not ");
4287
4288                         /* Set the user_txpower_limit to the highest power
4289                          * supported by any channel */
4290                         if (eeprom_ch_info[ch].max_power_avg >
4291                             priv->user_txpower_limit)
4292                                 priv->user_txpower_limit =
4293                                     eeprom_ch_info[ch].max_power_avg;
4294
4295                         ch_info++;
4296                 }
4297         }
4298
4299         /* Set up txpower settings in driver for all channels */
4300         if (iwl3945_txpower_set_from_eeprom(priv))
4301                 return -EIO;
4302
4303         return 0;
4304 }
4305
4306 /*
4307  * iwl3945_free_channel_map - undo allocations in iwl3945_init_channel_map
4308  */
4309 static void iwl3945_free_channel_map(struct iwl_priv *priv)
4310 {
4311         kfree(priv->channel_info);
4312         priv->channel_count = 0;
4313 }
4314
4315 /* For active scan, listen ACTIVE_DWELL_TIME (msec) on each channel after
4316  * sending probe req.  This should be set long enough to hear probe responses
4317  * from more than one AP.  */
4318 #define IWL_ACTIVE_DWELL_TIME_24    (30)        /* all times in msec */
4319 #define IWL_ACTIVE_DWELL_TIME_52    (20)
4320
4321 #define IWL_ACTIVE_DWELL_FACTOR_24GHZ (3)
4322 #define IWL_ACTIVE_DWELL_FACTOR_52GHZ (2)
4323
4324 /* For faster active scanning, scan will move to the next channel if fewer than
4325  * PLCP_QUIET_THRESH packets are heard on this channel within
4326  * ACTIVE_QUIET_TIME after sending probe request.  This shortens the dwell
4327  * time if it's a quiet channel (nothing responded to our probe, and there's
4328  * no other traffic).
4329  * Disable "quiet" feature by setting PLCP_QUIET_THRESH to 0. */
4330 #define IWL_PLCP_QUIET_THRESH       __constant_cpu_to_le16(1)   /* packets */
4331 #define IWL_ACTIVE_QUIET_TIME       __constant_cpu_to_le16(10)  /* msec */
4332
4333 /* For passive scan, listen PASSIVE_DWELL_TIME (msec) on each channel.
4334  * Must be set longer than active dwell time.
4335  * For the most reliable scan, set > AP beacon interval (typically 100msec). */
4336 #define IWL_PASSIVE_DWELL_TIME_24   (20)        /* all times in msec */
4337 #define IWL_PASSIVE_DWELL_TIME_52   (10)
4338 #define IWL_PASSIVE_DWELL_BASE      (100)
4339 #define IWL_CHANNEL_TUNE_TIME       5
4340
4341 #define IWL_SCAN_PROBE_MASK(n)   (BIT(n) | (BIT(n) - BIT(1)))
4342
4343 static inline u16 iwl3945_get_active_dwell_time(struct iwl_priv *priv,
4344                                                 enum ieee80211_band band,
4345                                                 u8 n_probes)
4346 {
4347         if (band == IEEE80211_BAND_5GHZ)
4348                 return IWL_ACTIVE_DWELL_TIME_52 +
4349                         IWL_ACTIVE_DWELL_FACTOR_52GHZ * (n_probes + 1);
4350         else
4351                 return IWL_ACTIVE_DWELL_TIME_24 +
4352                         IWL_ACTIVE_DWELL_FACTOR_24GHZ * (n_probes + 1);
4353 }
4354
4355 static u16 iwl3945_get_passive_dwell_time(struct iwl_priv *priv,
4356                                           enum ieee80211_band band)
4357 {
4358         u16 passive = (band == IEEE80211_BAND_2GHZ) ?
4359             IWL_PASSIVE_DWELL_BASE + IWL_PASSIVE_DWELL_TIME_24 :
4360             IWL_PASSIVE_DWELL_BASE + IWL_PASSIVE_DWELL_TIME_52;
4361
4362         if (iwl3945_is_associated(priv)) {
4363                 /* If we're associated, we clamp the maximum passive
4364                  * dwell time to be 98% of the beacon interval (minus
4365                  * 2 * channel tune time) */
4366                 passive = priv->beacon_int;
4367                 if ((passive > IWL_PASSIVE_DWELL_BASE) || !passive)
4368                         passive = IWL_PASSIVE_DWELL_BASE;
4369                 passive = (passive * 98) / 100 - IWL_CHANNEL_TUNE_TIME * 2;
4370         }
4371
4372         return passive;
4373 }
4374
4375 static int iwl3945_get_channels_for_scan(struct iwl_priv *priv,
4376                                          enum ieee80211_band band,
4377                                      u8 is_active, u8 n_probes,
4378                                      struct iwl3945_scan_channel *scan_ch)
4379 {
4380         const struct ieee80211_channel *channels = NULL;
4381         const struct ieee80211_supported_band *sband;
4382         const struct iwl_channel_info *ch_info;
4383         u16 passive_dwell = 0;
4384         u16 active_dwell = 0;
4385         int added, i;
4386
4387         sband = iwl_get_hw_mode(priv, band);
4388         if (!sband)
4389                 return 0;
4390
4391         channels = sband->channels;
4392
4393         active_dwell = iwl3945_get_active_dwell_time(priv, band, n_probes);
4394         passive_dwell = iwl3945_get_passive_dwell_time(priv, band);
4395
4396         if (passive_dwell <= active_dwell)
4397                 passive_dwell = active_dwell + 1;
4398
4399         for (i = 0, added = 0; i < sband->n_channels; i++) {
4400                 if (channels[i].flags & IEEE80211_CHAN_DISABLED)
4401                         continue;
4402
4403                 scan_ch->channel = channels[i].hw_value;
4404
4405                 ch_info = iwl3945_get_channel_info(priv, band, scan_ch->channel);
4406                 if (!is_channel_valid(ch_info)) {
4407                         IWL_DEBUG_SCAN("Channel %d is INVALID for this band.\n",
4408                                        scan_ch->channel);
4409                         continue;
4410                 }
4411
4412                 scan_ch->active_dwell = cpu_to_le16(active_dwell);
4413                 scan_ch->passive_dwell = cpu_to_le16(passive_dwell);
4414                 /* If passive , set up for auto-switch
4415                  *  and use long active_dwell time.
4416                  */
4417                 if (!is_active || is_channel_passive(ch_info) ||
4418                     (channels[i].flags & IEEE80211_CHAN_PASSIVE_SCAN)) {
4419                         scan_ch->type = 0;      /* passive */
4420                         if (IWL_UCODE_API(priv->ucode_ver) == 1)
4421                                 scan_ch->active_dwell = cpu_to_le16(passive_dwell - 1);
4422                 } else {
4423                         scan_ch->type = 1;      /* active */
4424                 }
4425
4426                 /* Set direct probe bits. These may be used both for active
4427                  * scan channels (probes gets sent right away),
4428                  * or for passive channels (probes get se sent only after
4429                  * hearing clear Rx packet).*/
4430                 if (IWL_UCODE_API(priv->ucode_ver) >= 2) {
4431                         if (n_probes)
4432                                 scan_ch->type |= IWL_SCAN_PROBE_MASK(n_probes);
4433                 } else {
4434                         /* uCode v1 does not allow setting direct probe bits on
4435                          * passive channel. */
4436                         if ((scan_ch->type & 1) && n_probes)
4437                                 scan_ch->type |= IWL_SCAN_PROBE_MASK(n_probes);
4438                 }
4439
4440                 /* Set txpower levels to defaults */
4441                 scan_ch->tpc.dsp_atten = 110;
4442                 /* scan_pwr_info->tpc.dsp_atten; */
4443
4444                 /*scan_pwr_info->tpc.tx_gain; */
4445                 if (band == IEEE80211_BAND_5GHZ)
4446                         scan_ch->tpc.tx_gain = ((1 << 5) | (3 << 3)) | 3;
4447                 else {
4448                         scan_ch->tpc.tx_gain = ((1 << 5) | (5 << 3));
4449                         /* NOTE: if we were doing 6Mb OFDM for scans we'd use
4450                          * power level:
4451                          * scan_ch->tpc.tx_gain = ((1 << 5) | (2 << 3)) | 3;
4452                          */
4453                 }
4454
4455                 IWL_DEBUG_SCAN("Scanning %d [%s %d]\n",
4456                                scan_ch->channel,
4457                                (scan_ch->type & 1) ? "ACTIVE" : "PASSIVE",
4458                                (scan_ch->type & 1) ?
4459                                active_dwell : passive_dwell);
4460
4461                 scan_ch++;
4462                 added++;
4463         }
4464
4465         IWL_DEBUG_SCAN("total channels to scan %d \n", added);
4466         return added;
4467 }
4468
4469 static void iwl3945_init_hw_rates(struct iwl_priv *priv,
4470                               struct ieee80211_rate *rates)
4471 {
4472         int i;
4473
4474         for (i = 0; i < IWL_RATE_COUNT; i++) {
4475                 rates[i].bitrate = iwl3945_rates[i].ieee * 5;
4476                 rates[i].hw_value = i; /* Rate scaling will work on indexes */
4477                 rates[i].hw_value_short = i;
4478                 rates[i].flags = 0;
4479                 if ((i > IWL39_LAST_OFDM_RATE) || (i < IWL_FIRST_OFDM_RATE)) {
4480                         /*
4481                          * If CCK != 1M then set short preamble rate flag.
4482                          */
4483                         rates[i].flags |= (iwl3945_rates[i].plcp == 10) ?
4484                                 0 : IEEE80211_RATE_SHORT_PREAMBLE;
4485                 }
4486         }
4487 }
4488
4489 /**
4490  * iwl3945_init_geos - Initialize mac80211's geo/channel info based from eeprom
4491  */
4492 static int iwl3945_init_geos(struct iwl_priv *priv)
4493 {
4494         struct iwl_channel_info *ch;
4495         struct ieee80211_supported_band *sband;
4496         struct ieee80211_channel *channels;
4497         struct ieee80211_channel *geo_ch;
4498         struct ieee80211_rate *rates;
4499         int i = 0;
4500
4501         if (priv->bands[IEEE80211_BAND_2GHZ].n_bitrates ||
4502             priv->bands[IEEE80211_BAND_5GHZ].n_bitrates) {
4503                 IWL_DEBUG_INFO("Geography modes already initialized.\n");
4504                 set_bit(STATUS_GEO_CONFIGURED, &priv->status);
4505                 return 0;
4506         }
4507
4508         channels = kzalloc(sizeof(struct ieee80211_channel) *
4509                            priv->channel_count, GFP_KERNEL);
4510         if (!channels)
4511                 return -ENOMEM;
4512
4513         rates = kzalloc((sizeof(struct ieee80211_rate) * (IWL_RATE_COUNT + 1)),
4514                         GFP_KERNEL);
4515         if (!rates) {
4516                 kfree(channels);
4517                 return -ENOMEM;
4518         }
4519
4520         /* 5.2GHz channels start after the 2.4GHz channels */
4521         sband = &priv->bands[IEEE80211_BAND_5GHZ];
4522         sband->channels = &channels[ARRAY_SIZE(iwl3945_eeprom_band_1)];
4523         /* just OFDM */
4524         sband->bitrates = &rates[IWL_FIRST_OFDM_RATE];
4525         sband->n_bitrates = IWL_RATE_COUNT - IWL_FIRST_OFDM_RATE;
4526
4527         sband = &priv->bands[IEEE80211_BAND_2GHZ];
4528         sband->channels = channels;
4529         /* OFDM & CCK */
4530         sband->bitrates = rates;
4531         sband->n_bitrates = IWL_RATE_COUNT;
4532
4533         priv->ieee_channels = channels;
4534         priv->ieee_rates = rates;
4535
4536         iwl3945_init_hw_rates(priv, rates);
4537
4538         for (i = 0;  i < priv->channel_count; i++) {
4539                 ch = &priv->channel_info[i];
4540
4541                 /* FIXME: might be removed if scan is OK*/
4542                 if (!is_channel_valid(ch))
4543                         continue;
4544
4545                 if (is_channel_a_band(ch))
4546                         sband =  &priv->bands[IEEE80211_BAND_5GHZ];
4547                 else
4548                         sband =  &priv->bands[IEEE80211_BAND_2GHZ];
4549
4550                 geo_ch = &sband->channels[sband->n_channels++];
4551
4552                 geo_ch->center_freq = ieee80211_channel_to_frequency(ch->channel);
4553                 geo_ch->max_power = ch->max_power_avg;
4554                 geo_ch->max_antenna_gain = 0xff;
4555                 geo_ch->hw_value = ch->channel;
4556
4557                 if (is_channel_valid(ch)) {
4558                         if (!(ch->flags & EEPROM_CHANNEL_IBSS))
4559                                 geo_ch->flags |= IEEE80211_CHAN_NO_IBSS;
4560
4561                         if (!(ch->flags & EEPROM_CHANNEL_ACTIVE))
4562                                 geo_ch->flags |= IEEE80211_CHAN_PASSIVE_SCAN;
4563
4564                         if (ch->flags & EEPROM_CHANNEL_RADAR)
4565                                 geo_ch->flags |= IEEE80211_CHAN_RADAR;
4566
4567                         if (ch->max_power_avg > priv->max_channel_txpower_limit)
4568                                 priv->max_channel_txpower_limit =
4569                                     ch->max_power_avg;
4570                 } else {
4571                         geo_ch->flags |= IEEE80211_CHAN_DISABLED;
4572                 }
4573
4574                 /* Save flags for reg domain usage */
4575                 geo_ch->orig_flags = geo_ch->flags;
4576
4577                 IWL_DEBUG_INFO("Channel %d Freq=%d[%sGHz] %s flag=0%X\n",
4578                                 ch->channel, geo_ch->center_freq,
4579                                 is_channel_a_band(ch) ?  "5.2" : "2.4",
4580                                 geo_ch->flags & IEEE80211_CHAN_DISABLED ?
4581                                 "restricted" : "valid",
4582                                  geo_ch->flags);
4583         }
4584
4585         if ((priv->bands[IEEE80211_BAND_5GHZ].n_channels == 0) &&
4586              priv->cfg->sku & IWL_SKU_A) {
4587                 IWL_INFO(priv, "Incorrectly detected BG card as ABG. "
4588                         "Please send your PCI ID 0x%04X:0x%04X to maintainer.\n",
4589                         priv->pci_dev->device, priv->pci_dev->subsystem_device);
4590                  priv->cfg->sku &= ~IWL_SKU_A;
4591         }
4592
4593         IWL_INFO(priv, "Tunable channels: %d 802.11bg, %d 802.11a channels\n",
4594                priv->bands[IEEE80211_BAND_2GHZ].n_channels,
4595                priv->bands[IEEE80211_BAND_5GHZ].n_channels);
4596
4597         if (priv->bands[IEEE80211_BAND_2GHZ].n_channels)
4598                 priv->hw->wiphy->bands[IEEE80211_BAND_2GHZ] =
4599                         &priv->bands[IEEE80211_BAND_2GHZ];
4600         if (priv->bands[IEEE80211_BAND_5GHZ].n_channels)
4601                 priv->hw->wiphy->bands[IEEE80211_BAND_5GHZ] =
4602                         &priv->bands[IEEE80211_BAND_5GHZ];
4603
4604         set_bit(STATUS_GEO_CONFIGURED, &priv->status);
4605
4606         return 0;
4607 }
4608
4609 /*
4610  * iwl3945_free_geos - undo allocations in iwl3945_init_geos
4611  */
4612 static void iwl3945_free_geos(struct iwl_priv *priv)
4613 {
4614         kfree(priv->ieee_channels);
4615         kfree(priv->ieee_rates);
4616         clear_bit(STATUS_GEO_CONFIGURED, &priv->status);
4617 }
4618
4619 /******************************************************************************
4620  *
4621  * uCode download functions
4622  *
4623  ******************************************************************************/
4624
4625 static void iwl3945_dealloc_ucode_pci(struct iwl_priv *priv)
4626 {
4627         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_code);
4628         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_data);
4629         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_data_backup);
4630         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_init);
4631         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_init_data);
4632         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_boot);
4633 }
4634
4635 /**
4636  * iwl3945_verify_inst_full - verify runtime uCode image in card vs. host,
4637  *     looking at all data.
4638  */
4639 static int iwl3945_verify_inst_full(struct iwl_priv *priv, __le32 *image, u32 len)
4640 {
4641         u32 val;
4642         u32 save_len = len;
4643         int rc = 0;
4644         u32 errcnt;
4645
4646         IWL_DEBUG_INFO("ucode inst image size is %u\n", len);
4647
4648         rc = iwl_grab_nic_access(priv);
4649         if (rc)
4650                 return rc;
4651
4652         iwl_write_direct32(priv, HBUS_TARG_MEM_RADDR,
4653                                IWL39_RTC_INST_LOWER_BOUND);
4654
4655         errcnt = 0;
4656         for (; len > 0; len -= sizeof(u32), image++) {
4657                 /* read data comes through single port, auto-incr addr */
4658                 /* NOTE: Use the debugless read so we don't flood kernel log
4659                  * if IWL_DL_IO is set */
4660                 val = _iwl_read_direct32(priv, HBUS_TARG_MEM_RDAT);
4661                 if (val != le32_to_cpu(*image)) {
4662                         IWL_ERR(priv, "uCode INST section is invalid at "
4663                                   "offset 0x%x, is 0x%x, s/b 0x%x\n",
4664                                   save_len - len, val, le32_to_cpu(*image));
4665                         rc = -EIO;
4666                         errcnt++;
4667                         if (errcnt >= 20)
4668                                 break;
4669                 }
4670         }
4671
4672         iwl_release_nic_access(priv);
4673
4674         if (!errcnt)
4675                 IWL_DEBUG_INFO("ucode image in INSTRUCTION memory is good\n");
4676
4677         return rc;
4678 }
4679
4680
4681 /**
4682  * iwl3945_verify_inst_sparse - verify runtime uCode image in card vs. host,
4683  *   using sample data 100 bytes apart.  If these sample points are good,
4684  *   it's a pretty good bet that everything between them is good, too.
4685  */
4686 static int iwl3945_verify_inst_sparse(struct iwl_priv *priv, __le32 *image, u32 len)
4687 {
4688         u32 val;
4689         int rc = 0;
4690         u32 errcnt = 0;
4691         u32 i;
4692
4693         IWL_DEBUG_INFO("ucode inst image size is %u\n", len);
4694
4695         rc = iwl_grab_nic_access(priv);
4696         if (rc)
4697                 return rc;
4698
4699         for (i = 0; i < len; i += 100, image += 100/sizeof(u32)) {
4700                 /* read data comes through single port, auto-incr addr */
4701                 /* NOTE: Use the debugless read so we don't flood kernel log
4702                  * if IWL_DL_IO is set */
4703                 iwl_write_direct32(priv, HBUS_TARG_MEM_RADDR,
4704                         i + IWL39_RTC_INST_LOWER_BOUND);
4705                 val = _iwl_read_direct32(priv, HBUS_TARG_MEM_RDAT);
4706                 if (val != le32_to_cpu(*image)) {
4707 #if 0 /* Enable this if you want to see details */
4708                         IWL_ERR(priv, "uCode INST section is invalid at "
4709                                   "offset 0x%x, is 0x%x, s/b 0x%x\n",
4710                                   i, val, *image);
4711 #endif
4712                         rc = -EIO;
4713                         errcnt++;
4714                         if (errcnt >= 3)
4715                                 break;
4716                 }
4717         }
4718
4719         iwl_release_nic_access(priv);
4720
4721         return rc;
4722 }
4723
4724
4725 /**
4726  * iwl3945_verify_ucode - determine which instruction image is in SRAM,
4727  *    and verify its contents
4728  */
4729 static int iwl3945_verify_ucode(struct iwl_priv *priv)
4730 {
4731         __le32 *image;
4732         u32 len;
4733         int rc = 0;
4734
4735         /* Try bootstrap */
4736         image = (__le32 *)priv->ucode_boot.v_addr;
4737         len = priv->ucode_boot.len;
4738         rc = iwl3945_verify_inst_sparse(priv, image, len);
4739         if (rc == 0) {
4740                 IWL_DEBUG_INFO("Bootstrap uCode is good in inst SRAM\n");
4741                 return 0;
4742         }
4743
4744         /* Try initialize */
4745         image = (__le32 *)priv->ucode_init.v_addr;
4746         len = priv->ucode_init.len;
4747         rc = iwl3945_verify_inst_sparse(priv, image, len);
4748         if (rc == 0) {
4749                 IWL_DEBUG_INFO("Initialize uCode is good in inst SRAM\n");
4750                 return 0;
4751         }
4752
4753         /* Try runtime/protocol */
4754         image = (__le32 *)priv->ucode_code.v_addr;
4755         len = priv->ucode_code.len;
4756         rc = iwl3945_verify_inst_sparse(priv, image, len);
4757         if (rc == 0) {
4758                 IWL_DEBUG_INFO("Runtime uCode is good in inst SRAM\n");
4759                 return 0;
4760         }
4761
4762         IWL_ERR(priv, "NO VALID UCODE IMAGE IN INSTRUCTION SRAM!!\n");
4763
4764         /* Since nothing seems to match, show first several data entries in
4765          * instruction SRAM, so maybe visual inspection will give a clue.
4766          * Selection of bootstrap image (vs. other images) is arbitrary. */
4767         image = (__le32 *)priv->ucode_boot.v_addr;
4768         len = priv->ucode_boot.len;
4769         rc = iwl3945_verify_inst_full(priv, image, len);
4770
4771         return rc;
4772 }
4773
4774 static void iwl3945_nic_start(struct iwl_priv *priv)
4775 {
4776         /* Remove all resets to allow NIC to operate */
4777         iwl_write32(priv, CSR_RESET, 0);
4778 }
4779
4780 /**
4781  * iwl3945_read_ucode - Read uCode images from disk file.
4782  *
4783  * Copy into buffers for card to fetch via bus-mastering
4784  */
4785 static int iwl3945_read_ucode(struct iwl_priv *priv)
4786 {
4787         struct iwl_ucode *ucode;
4788         int ret = -EINVAL, index;
4789         const struct firmware *ucode_raw;
4790         /* firmware file name contains uCode/driver compatibility version */
4791         const char *name_pre = priv->cfg->fw_name_pre;
4792         const unsigned int api_max = priv->cfg->ucode_api_max;
4793         const unsigned int api_min = priv->cfg->ucode_api_min;
4794         char buf[25];
4795         u8 *src;
4796         size_t len;
4797         u32 api_ver, inst_size, data_size, init_size, init_data_size, boot_size;
4798
4799         /* Ask kernel firmware_class module to get the boot firmware off disk.
4800          * request_firmware() is synchronous, file is in memory on return. */
4801         for (index = api_max; index >= api_min; index--) {
4802                 sprintf(buf, "%s%u%s", name_pre, index, ".ucode");
4803                 ret = request_firmware(&ucode_raw, buf, &priv->pci_dev->dev);
4804                 if (ret < 0) {
4805                         IWL_ERR(priv, "%s firmware file req failed: %d\n",
4806                                   buf, ret);
4807                         if (ret == -ENOENT)
4808                                 continue;
4809                         else
4810                                 goto error;
4811                 } else {
4812                         if (index < api_max)
4813                                 IWL_ERR(priv, "Loaded firmware %s, "
4814                                         "which is deprecated. "
4815                                         " Please use API v%u instead.\n",
4816                                           buf, api_max);
4817                         IWL_DEBUG_INFO("Got firmware '%s' file (%zd bytes) from disk\n",
4818                                        buf, ucode_raw->size);
4819                         break;
4820                 }
4821         }
4822
4823         if (ret < 0)
4824                 goto error;
4825
4826         /* Make sure that we got at least our header! */
4827         if (ucode_raw->size < sizeof(*ucode)) {
4828                 IWL_ERR(priv, "File size way too small!\n");
4829                 ret = -EINVAL;
4830                 goto err_release;
4831         }
4832
4833         /* Data from ucode file:  header followed by uCode images */
4834         ucode = (void *)ucode_raw->data;
4835
4836         priv->ucode_ver = le32_to_cpu(ucode->ver);
4837         api_ver = IWL_UCODE_API(priv->ucode_ver);
4838         inst_size = le32_to_cpu(ucode->inst_size);
4839         data_size = le32_to_cpu(ucode->data_size);
4840         init_size = le32_to_cpu(ucode->init_size);
4841         init_data_size = le32_to_cpu(ucode->init_data_size);
4842         boot_size = le32_to_cpu(ucode->boot_size);
4843
4844         /* api_ver should match the api version forming part of the
4845          * firmware filename ... but we don't check for that and only rely
4846          * on the API version read from firware header from here on forward */
4847
4848         if (api_ver < api_min || api_ver > api_max) {
4849                 IWL_ERR(priv, "Driver unable to support your firmware API. "
4850                           "Driver supports v%u, firmware is v%u.\n",
4851                           api_max, api_ver);
4852                 priv->ucode_ver = 0;
4853                 ret = -EINVAL;
4854                 goto err_release;
4855         }
4856         if (api_ver != api_max)
4857                 IWL_ERR(priv, "Firmware has old API version. Expected %u, "
4858                           "got %u. New firmware can be obtained "
4859                           "from http://www.intellinuxwireless.org.\n",
4860                           api_max, api_ver);
4861
4862         IWL_INFO(priv, "loaded firmware version %u.%u.%u.%u\n",
4863                 IWL_UCODE_MAJOR(priv->ucode_ver),
4864                 IWL_UCODE_MINOR(priv->ucode_ver),
4865                 IWL_UCODE_API(priv->ucode_ver),
4866                 IWL_UCODE_SERIAL(priv->ucode_ver));
4867
4868         IWL_DEBUG_INFO("f/w package hdr ucode version raw = 0x%x\n",
4869                        priv->ucode_ver);
4870         IWL_DEBUG_INFO("f/w package hdr runtime inst size = %u\n", inst_size);
4871         IWL_DEBUG_INFO("f/w package hdr runtime data size = %u\n", data_size);
4872         IWL_DEBUG_INFO("f/w package hdr init inst size = %u\n", init_size);
4873         IWL_DEBUG_INFO("f/w package hdr init data size = %u\n", init_data_size);
4874         IWL_DEBUG_INFO("f/w package hdr boot inst size = %u\n", boot_size);
4875
4876
4877         /* Verify size of file vs. image size info in file's header */
4878         if (ucode_raw->size < sizeof(*ucode) +
4879                 inst_size + data_size + init_size +
4880                 init_data_size + boot_size) {
4881
4882                 IWL_DEBUG_INFO("uCode file size %d too small\n",
4883                                (int)ucode_raw->size);
4884                 ret = -EINVAL;
4885                 goto err_release;
4886         }
4887
4888         /* Verify that uCode images will fit in card's SRAM */
4889         if (inst_size > IWL39_MAX_INST_SIZE) {
4890                 IWL_DEBUG_INFO("uCode instr len %d too large to fit in\n",
4891                                inst_size);
4892                 ret = -EINVAL;
4893                 goto err_release;
4894         }
4895
4896         if (data_size > IWL39_MAX_DATA_SIZE) {
4897                 IWL_DEBUG_INFO("uCode data len %d too large to fit in\n",
4898                                data_size);
4899                 ret = -EINVAL;
4900                 goto err_release;
4901         }
4902         if (init_size > IWL39_MAX_INST_SIZE) {
4903                 IWL_DEBUG_INFO("uCode init instr len %d too large to fit in\n",
4904                                 init_size);
4905                 ret = -EINVAL;
4906                 goto err_release;
4907         }
4908         if (init_data_size > IWL39_MAX_DATA_SIZE) {
4909                 IWL_DEBUG_INFO("uCode init data len %d too large to fit in\n",
4910                                 init_data_size);
4911                 ret = -EINVAL;
4912                 goto err_release;
4913         }
4914         if (boot_size > IWL39_MAX_BSM_SIZE) {
4915                 IWL_DEBUG_INFO("uCode boot instr len %d too large to fit in\n",
4916                                 boot_size);
4917                 ret = -EINVAL;
4918                 goto err_release;
4919         }
4920
4921         /* Allocate ucode buffers for card's bus-master loading ... */
4922
4923         /* Runtime instructions and 2 copies of data:
4924          * 1) unmodified from disk
4925          * 2) backup cache for save/restore during power-downs */
4926         priv->ucode_code.len = inst_size;
4927         iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_code);
4928
4929         priv->ucode_data.len = data_size;
4930         iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_data);
4931
4932         priv->ucode_data_backup.len = data_size;
4933         iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_data_backup);
4934
4935         if (!priv->ucode_code.v_addr || !priv->ucode_data.v_addr ||
4936             !priv->ucode_data_backup.v_addr)
4937                 goto err_pci_alloc;
4938
4939         /* Initialization instructions and data */
4940         if (init_size && init_data_size) {
4941                 priv->ucode_init.len = init_size;
4942                 iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_init);
4943
4944                 priv->ucode_init_data.len = init_data_size;
4945                 iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_init_data);
4946
4947                 if (!priv->ucode_init.v_addr || !priv->ucode_init_data.v_addr)
4948                         goto err_pci_alloc;
4949         }
4950
4951         /* Bootstrap (instructions only, no data) */
4952         if (boot_size) {
4953                 priv->ucode_boot.len = boot_size;
4954                 iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_boot);
4955
4956                 if (!priv->ucode_boot.v_addr)
4957                         goto err_pci_alloc;
4958         }
4959
4960         /* Copy images into buffers for card's bus-master reads ... */
4961
4962         /* Runtime instructions (first block of data in file) */
4963         src = &ucode->data[0];
4964         len = priv->ucode_code.len;
4965         IWL_DEBUG_INFO("Copying (but not loading) uCode instr len %Zd\n", len);
4966         memcpy(priv->ucode_code.v_addr, src, len);
4967         IWL_DEBUG_INFO("uCode instr buf vaddr = 0x%p, paddr = 0x%08x\n",
4968                 priv->ucode_code.v_addr, (u32)priv->ucode_code.p_addr);
4969
4970         /* Runtime data (2nd block)
4971          * NOTE:  Copy into backup buffer will be done in iwl3945_up()  */
4972         src = &ucode->data[inst_size];
4973         len = priv->ucode_data.len;
4974         IWL_DEBUG_INFO("Copying (but not loading) uCode data len %Zd\n", len);
4975         memcpy(priv->ucode_data.v_addr, src, len);
4976         memcpy(priv->ucode_data_backup.v_addr, src, len);
4977
4978         /* Initialization instructions (3rd block) */
4979         if (init_size) {
4980                 src = &ucode->data[inst_size + data_size];
4981                 len = priv->ucode_init.len;
4982                 IWL_DEBUG_INFO("Copying (but not loading) init instr len %Zd\n",
4983                                len);
4984                 memcpy(priv->ucode_init.v_addr, src, len);
4985         }
4986
4987         /* Initialization data (4th block) */
4988         if (init_data_size) {
4989                 src = &ucode->data[inst_size + data_size + init_size];
4990                 len = priv->ucode_init_data.len;
4991                 IWL_DEBUG_INFO("Copying (but not loading) init data len %d\n",
4992                                (int)len);
4993                 memcpy(priv->ucode_init_data.v_addr, src, len);
4994         }
4995
4996         /* Bootstrap instructions (5th block) */
4997         src = &ucode->data[inst_size + data_size + init_size + init_data_size];
4998         len = priv->ucode_boot.len;
4999         IWL_DEBUG_INFO("Copying (but not loading) boot instr len %d\n",
5000                        (int)len);
5001         memcpy(priv->ucode_boot.v_addr, src, len);
5002
5003         /* We have our copies now, allow OS release its copies */
5004         release_firmware(ucode_raw);
5005         return 0;
5006
5007  err_pci_alloc:
5008         IWL_ERR(priv, "failed to allocate pci memory\n");
5009         ret = -ENOMEM;
5010         iwl3945_dealloc_ucode_pci(priv);
5011
5012  err_release:
5013         release_firmware(ucode_raw);
5014
5015  error:
5016         return ret;
5017 }
5018
5019
5020 /**
5021  * iwl3945_set_ucode_ptrs - Set uCode address location
5022  *
5023  * Tell initialization uCode where to find runtime uCode.
5024  *
5025  * BSM registers initially contain pointers to initialization uCode.
5026  * We need to replace them to load runtime uCode inst and data,
5027  * and to save runtime data when powering down.
5028  */
5029 static int iwl3945_set_ucode_ptrs(struct iwl_priv *priv)
5030 {
5031         dma_addr_t pinst;
5032         dma_addr_t pdata;
5033         int rc = 0;
5034         unsigned long flags;
5035
5036         /* bits 31:0 for 3945 */
5037         pinst = priv->ucode_code.p_addr;
5038         pdata = priv->ucode_data_backup.p_addr;
5039
5040         spin_lock_irqsave(&priv->lock, flags);
5041         rc = iwl_grab_nic_access(priv);
5042         if (rc) {
5043                 spin_unlock_irqrestore(&priv->lock, flags);
5044                 return rc;
5045         }
5046
5047         /* Tell bootstrap uCode where to find image to load */
5048         iwl_write_prph(priv, BSM_DRAM_INST_PTR_REG, pinst);
5049         iwl_write_prph(priv, BSM_DRAM_DATA_PTR_REG, pdata);
5050         iwl_write_prph(priv, BSM_DRAM_DATA_BYTECOUNT_REG,
5051                                  priv->ucode_data.len);
5052
5053         /* Inst byte count must be last to set up, bit 31 signals uCode
5054          *   that all new ptr/size info is in place */
5055         iwl_write_prph(priv, BSM_DRAM_INST_BYTECOUNT_REG,
5056                                  priv->ucode_code.len | BSM_DRAM_INST_LOAD);
5057
5058         iwl_release_nic_access(priv);
5059
5060         spin_unlock_irqrestore(&priv->lock, flags);
5061
5062         IWL_DEBUG_INFO("Runtime uCode pointers are set.\n");
5063
5064         return rc;
5065 }
5066
5067 /**
5068  * iwl3945_init_alive_start - Called after REPLY_ALIVE notification received
5069  *
5070  * Called after REPLY_ALIVE notification received from "initialize" uCode.
5071  *
5072  * Tell "initialize" uCode to go ahead and load the runtime uCode.
5073  */
5074 static void iwl3945_init_alive_start(struct iwl_priv *priv)
5075 {
5076         /* Check alive response for "valid" sign from uCode */
5077         if (priv->card_alive_init.is_valid != UCODE_VALID_OK) {
5078                 /* We had an error bringing up the hardware, so take it
5079                  * all the way back down so we can try again */
5080                 IWL_DEBUG_INFO("Initialize Alive failed.\n");
5081                 goto restart;
5082         }
5083
5084         /* Bootstrap uCode has loaded initialize uCode ... verify inst image.
5085          * This is a paranoid check, because we would not have gotten the
5086          * "initialize" alive if code weren't properly loaded.  */
5087         if (iwl3945_verify_ucode(priv)) {
5088                 /* Runtime instruction load was bad;
5089                  * take it all the way back down so we can try again */
5090                 IWL_DEBUG_INFO("Bad \"initialize\" uCode load.\n");
5091                 goto restart;
5092         }
5093
5094         /* Send pointers to protocol/runtime uCode image ... init code will
5095          * load and launch runtime uCode, which will send us another "Alive"
5096          * notification. */
5097         IWL_DEBUG_INFO("Initialization Alive received.\n");
5098         if (iwl3945_set_ucode_ptrs(priv)) {
5099                 /* Runtime instruction load won't happen;
5100                  * take it all the way back down so we can try again */
5101                 IWL_DEBUG_INFO("Couldn't set up uCode pointers.\n");
5102                 goto restart;
5103         }
5104         return;
5105
5106  restart:
5107         queue_work(priv->workqueue, &priv->restart);
5108 }
5109
5110
5111 /* temporary */
5112 static int iwl3945_mac_beacon_update(struct ieee80211_hw *hw,
5113                                      struct sk_buff *skb);
5114
5115 /**
5116  * iwl3945_alive_start - called after REPLY_ALIVE notification received
5117  *                   from protocol/runtime uCode (initialization uCode's
5118  *                   Alive gets handled by iwl3945_init_alive_start()).
5119  */
5120 static void iwl3945_alive_start(struct iwl_priv *priv)
5121 {
5122         int rc = 0;
5123         int thermal_spin = 0;
5124         u32 rfkill;
5125
5126         IWL_DEBUG_INFO("Runtime Alive received.\n");
5127
5128         if (priv->card_alive.is_valid != UCODE_VALID_OK) {
5129                 /* We had an error bringing up the hardware, so take it
5130                  * all the way back down so we can try again */
5131                 IWL_DEBUG_INFO("Alive failed.\n");
5132                 goto restart;
5133         }
5134
5135         /* Initialize uCode has loaded Runtime uCode ... verify inst image.
5136          * This is a paranoid check, because we would not have gotten the
5137          * "runtime" alive if code weren't properly loaded.  */
5138         if (iwl3945_verify_ucode(priv)) {
5139                 /* Runtime instruction load was bad;
5140                  * take it all the way back down so we can try again */
5141                 IWL_DEBUG_INFO("Bad runtime uCode load.\n");
5142                 goto restart;
5143         }
5144
5145         iwl3945_clear_stations_table(priv);
5146
5147         rc = iwl_grab_nic_access(priv);
5148         if (rc) {
5149                 IWL_WARN(priv, "Can not read RFKILL status from adapter\n");
5150                 return;
5151         }
5152
5153         rfkill = iwl_read_prph(priv, APMG_RFKILL_REG);
5154         IWL_DEBUG_INFO("RFKILL status: 0x%x\n", rfkill);
5155         iwl_release_nic_access(priv);
5156
5157         if (rfkill & 0x1) {
5158                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
5159                 /* if RFKILL is not on, then wait for thermal
5160                  * sensor in adapter to kick in */
5161                 while (iwl3945_hw_get_temperature(priv) == 0) {
5162                         thermal_spin++;
5163                         udelay(10);
5164                 }
5165
5166                 if (thermal_spin)
5167                         IWL_DEBUG_INFO("Thermal calibration took %dus\n",
5168                                        thermal_spin * 10);
5169         } else
5170                 set_bit(STATUS_RF_KILL_HW, &priv->status);
5171
5172         /* After the ALIVE response, we can send commands to 3945 uCode */
5173         set_bit(STATUS_ALIVE, &priv->status);
5174
5175         /* Clear out the uCode error bit if it is set */
5176         clear_bit(STATUS_FW_ERROR, &priv->status);
5177
5178         if (iwl_is_rfkill(priv))
5179                 return;
5180
5181         ieee80211_wake_queues(priv->hw);
5182
5183         priv->active_rate = priv->rates_mask;
5184         priv->active_rate_basic = priv->rates_mask & IWL_BASIC_RATES_MASK;
5185
5186         iwl3945_send_power_mode(priv, IWL_POWER_LEVEL(priv->power_mode));
5187
5188         if (iwl3945_is_associated(priv)) {
5189                 struct iwl3945_rxon_cmd *active_rxon =
5190                                 (struct iwl3945_rxon_cmd *)(&priv->active39_rxon);
5191
5192                 memcpy(&priv->staging39_rxon, &priv->active39_rxon,
5193                        sizeof(priv->staging39_rxon));
5194                 active_rxon->filter_flags &= ~RXON_FILTER_ASSOC_MSK;
5195         } else {
5196                 /* Initialize our rx_config data */
5197                 iwl3945_connection_init_rx_config(priv, priv->iw_mode);
5198                 memcpy(priv->staging39_rxon.node_addr, priv->mac_addr, ETH_ALEN);
5199         }
5200
5201         /* Configure Bluetooth device coexistence support */
5202         iwl3945_send_bt_config(priv);
5203
5204         /* Configure the adapter for unassociated operation */
5205         iwl3945_commit_rxon(priv);
5206
5207         iwl3945_reg_txpower_periodic(priv);
5208
5209         iwl3945_led_register(priv);
5210
5211         IWL_DEBUG_INFO("ALIVE processing complete.\n");
5212         set_bit(STATUS_READY, &priv->status);
5213         wake_up_interruptible(&priv->wait_command_queue);
5214
5215         if (priv->error_recovering)
5216                 iwl3945_error_recovery(priv);
5217
5218         /* reassociate for ADHOC mode */
5219         if (priv->vif && (priv->iw_mode == NL80211_IFTYPE_ADHOC)) {
5220                 struct sk_buff *beacon = ieee80211_beacon_get(priv->hw,
5221                                                                 priv->vif);
5222                 if (beacon)
5223                         iwl3945_mac_beacon_update(priv->hw, beacon);
5224         }
5225
5226         return;
5227
5228  restart:
5229         queue_work(priv->workqueue, &priv->restart);
5230 }
5231
5232 static void iwl3945_cancel_deferred_work(struct iwl_priv *priv);
5233
5234 static void __iwl3945_down(struct iwl_priv *priv)
5235 {
5236         unsigned long flags;
5237         int exit_pending = test_bit(STATUS_EXIT_PENDING, &priv->status);
5238         struct ieee80211_conf *conf = NULL;
5239
5240         IWL_DEBUG_INFO(DRV_NAME " is going down\n");
5241
5242         conf = ieee80211_get_hw_conf(priv->hw);
5243
5244         if (!exit_pending)
5245                 set_bit(STATUS_EXIT_PENDING, &priv->status);
5246
5247         iwl3945_led_unregister(priv);
5248         iwl3945_clear_stations_table(priv);
5249
5250         /* Unblock any waiting calls */
5251         wake_up_interruptible_all(&priv->wait_command_queue);
5252
5253         /* Wipe out the EXIT_PENDING status bit if we are not actually
5254          * exiting the module */
5255         if (!exit_pending)
5256                 clear_bit(STATUS_EXIT_PENDING, &priv->status);
5257
5258         /* stop and reset the on-board processor */
5259         iwl_write32(priv, CSR_RESET, CSR_RESET_REG_FLAG_NEVO_RESET);
5260
5261         /* tell the device to stop sending interrupts */
5262         spin_lock_irqsave(&priv->lock, flags);
5263         iwl3945_disable_interrupts(priv);
5264         spin_unlock_irqrestore(&priv->lock, flags);
5265         iwl_synchronize_irq(priv);
5266
5267         if (priv->mac80211_registered)
5268                 ieee80211_stop_queues(priv->hw);
5269
5270         /* If we have not previously called iwl3945_init() then
5271          * clear all bits but the RF Kill and SUSPEND bits and return */
5272         if (!iwl_is_init(priv)) {
5273                 priv->status = test_bit(STATUS_RF_KILL_HW, &priv->status) <<
5274                                         STATUS_RF_KILL_HW |
5275                                test_bit(STATUS_RF_KILL_SW, &priv->status) <<
5276                                         STATUS_RF_KILL_SW |
5277                                test_bit(STATUS_GEO_CONFIGURED, &priv->status) <<
5278                                         STATUS_GEO_CONFIGURED |
5279                                test_bit(STATUS_IN_SUSPEND, &priv->status) <<
5280                                         STATUS_IN_SUSPEND |
5281                                 test_bit(STATUS_EXIT_PENDING, &priv->status) <<
5282                                         STATUS_EXIT_PENDING;
5283                 goto exit;
5284         }
5285
5286         /* ...otherwise clear out all the status bits but the RF Kill and
5287          * SUSPEND bits and continue taking the NIC down. */
5288         priv->status &= test_bit(STATUS_RF_KILL_HW, &priv->status) <<
5289                                 STATUS_RF_KILL_HW |
5290                         test_bit(STATUS_RF_KILL_SW, &priv->status) <<
5291                                 STATUS_RF_KILL_SW |
5292                         test_bit(STATUS_GEO_CONFIGURED, &priv->status) <<
5293                                 STATUS_GEO_CONFIGURED |
5294                         test_bit(STATUS_IN_SUSPEND, &priv->status) <<
5295                                 STATUS_IN_SUSPEND |
5296                         test_bit(STATUS_FW_ERROR, &priv->status) <<
5297                                 STATUS_FW_ERROR |
5298                         test_bit(STATUS_EXIT_PENDING, &priv->status) <<
5299                                 STATUS_EXIT_PENDING;
5300
5301         spin_lock_irqsave(&priv->lock, flags);
5302         iwl_clear_bit(priv, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
5303         spin_unlock_irqrestore(&priv->lock, flags);
5304
5305         iwl3945_hw_txq_ctx_stop(priv);
5306         iwl3945_hw_rxq_stop(priv);
5307
5308         spin_lock_irqsave(&priv->lock, flags);
5309         if (!iwl_grab_nic_access(priv)) {
5310                 iwl_write_prph(priv, APMG_CLK_DIS_REG,
5311                                          APMG_CLK_VAL_DMA_CLK_RQT);
5312                 iwl_release_nic_access(priv);
5313         }
5314         spin_unlock_irqrestore(&priv->lock, flags);
5315
5316         udelay(5);
5317
5318         priv->cfg->ops->lib->apm_ops.reset(priv);
5319  exit:
5320         memset(&priv->card_alive, 0, sizeof(struct iwl_alive_resp));
5321
5322         if (priv->ibss_beacon)
5323                 dev_kfree_skb(priv->ibss_beacon);
5324         priv->ibss_beacon = NULL;
5325
5326         /* clear out any free frames */
5327         iwl3945_clear_free_frames(priv);
5328 }
5329
5330 static void iwl3945_down(struct iwl_priv *priv)
5331 {
5332         mutex_lock(&priv->mutex);
5333         __iwl3945_down(priv);
5334         mutex_unlock(&priv->mutex);
5335
5336         iwl3945_cancel_deferred_work(priv);
5337 }
5338
5339 #define MAX_HW_RESTARTS 5
5340
5341 static int __iwl3945_up(struct iwl_priv *priv)
5342 {
5343         int rc, i;
5344
5345         if (test_bit(STATUS_EXIT_PENDING, &priv->status)) {
5346                 IWL_WARN(priv, "Exit pending; will not bring the NIC up\n");
5347                 return -EIO;
5348         }
5349
5350         if (test_bit(STATUS_RF_KILL_SW, &priv->status)) {
5351                 IWL_WARN(priv, "Radio disabled by SW RF kill (module "
5352                             "parameter)\n");
5353                 return -ENODEV;
5354         }
5355
5356         if (!priv->ucode_data_backup.v_addr || !priv->ucode_data.v_addr) {
5357                 IWL_ERR(priv, "ucode not available for device bring up\n");
5358                 return -EIO;
5359         }
5360
5361         /* If platform's RF_KILL switch is NOT set to KILL */
5362         if (iwl_read32(priv, CSR_GP_CNTRL) &
5363                                 CSR_GP_CNTRL_REG_FLAG_HW_RF_KILL_SW)
5364                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
5365         else {
5366                 set_bit(STATUS_RF_KILL_HW, &priv->status);
5367                 if (!test_bit(STATUS_IN_SUSPEND, &priv->status)) {
5368                         IWL_WARN(priv, "Radio disabled by HW RF Kill switch\n");
5369                         return -ENODEV;
5370                 }
5371         }
5372
5373         iwl_write32(priv, CSR_INT, 0xFFFFFFFF);
5374
5375         rc = iwl3945_hw_nic_init(priv);
5376         if (rc) {
5377                 IWL_ERR(priv, "Unable to int nic\n");
5378                 return rc;
5379         }
5380
5381         /* make sure rfkill handshake bits are cleared */
5382         iwl_write32(priv, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
5383         iwl_write32(priv, CSR_UCODE_DRV_GP1_CLR,
5384                     CSR_UCODE_DRV_GP1_BIT_CMD_BLOCKED);
5385
5386         /* clear (again), then enable host interrupts */
5387         iwl_write32(priv, CSR_INT, 0xFFFFFFFF);
5388         iwl3945_enable_interrupts(priv);
5389
5390         /* really make sure rfkill handshake bits are cleared */
5391         iwl_write32(priv, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
5392         iwl_write32(priv, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
5393
5394         /* Copy original ucode data image from disk into backup cache.
5395          * This will be used to initialize the on-board processor's
5396          * data SRAM for a clean start when the runtime program first loads. */
5397         memcpy(priv->ucode_data_backup.v_addr, priv->ucode_data.v_addr,
5398                priv->ucode_data.len);
5399
5400         /* We return success when we resume from suspend and rf_kill is on. */
5401         if (test_bit(STATUS_RF_KILL_HW, &priv->status))
5402                 return 0;
5403
5404         for (i = 0; i < MAX_HW_RESTARTS; i++) {
5405
5406                 iwl3945_clear_stations_table(priv);
5407
5408                 /* load bootstrap state machine,
5409                  * load bootstrap program into processor's memory,
5410                  * prepare to load the "initialize" uCode */
5411                 priv->cfg->ops->lib->load_ucode(priv);
5412
5413                 if (rc) {
5414                         IWL_ERR(priv,
5415                                 "Unable to set up bootstrap uCode: %d\n", rc);
5416                         continue;
5417                 }
5418
5419                 /* start card; "initialize" will load runtime ucode */
5420                 iwl3945_nic_start(priv);
5421
5422                 IWL_DEBUG_INFO(DRV_NAME " is coming up\n");
5423
5424                 return 0;
5425         }
5426
5427         set_bit(STATUS_EXIT_PENDING, &priv->status);
5428         __iwl3945_down(priv);
5429         clear_bit(STATUS_EXIT_PENDING, &priv->status);
5430
5431         /* tried to restart and config the device for as long as our
5432          * patience could withstand */
5433         IWL_ERR(priv, "Unable to initialize device after %d attempts.\n", i);
5434         return -EIO;
5435 }
5436
5437
5438 /*****************************************************************************
5439  *
5440  * Workqueue callbacks
5441  *
5442  *****************************************************************************/
5443
5444 static void iwl3945_bg_init_alive_start(struct work_struct *data)
5445 {
5446         struct iwl_priv *priv =
5447             container_of(data, struct iwl_priv, init_alive_start.work);
5448
5449         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
5450                 return;
5451
5452         mutex_lock(&priv->mutex);
5453         iwl3945_init_alive_start(priv);
5454         mutex_unlock(&priv->mutex);
5455 }
5456
5457 static void iwl3945_bg_alive_start(struct work_struct *data)
5458 {
5459         struct iwl_priv *priv =
5460             container_of(data, struct iwl_priv, alive_start.work);
5461
5462         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
5463                 return;
5464
5465         mutex_lock(&priv->mutex);
5466         iwl3945_alive_start(priv);
5467         mutex_unlock(&priv->mutex);
5468 }
5469
5470 static void iwl3945_bg_rf_kill(struct work_struct *work)
5471 {
5472         struct iwl_priv *priv = container_of(work, struct iwl_priv, rf_kill);
5473
5474         wake_up_interruptible(&priv->wait_command_queue);
5475
5476         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
5477                 return;
5478
5479         mutex_lock(&priv->mutex);
5480
5481         if (!iwl_is_rfkill(priv)) {
5482                 IWL_DEBUG(IWL_DL_INFO | IWL_DL_RF_KILL,
5483                           "HW and/or SW RF Kill no longer active, restarting "
5484                           "device\n");
5485                 if (!test_bit(STATUS_EXIT_PENDING, &priv->status))
5486                         queue_work(priv->workqueue, &priv->restart);
5487         } else {
5488
5489                 if (!test_bit(STATUS_RF_KILL_HW, &priv->status))
5490                         IWL_DEBUG_RF_KILL("Can not turn radio back on - "
5491                                           "disabled by SW switch\n");
5492                 else
5493                         IWL_WARN(priv, "Radio Frequency Kill Switch is On:\n"
5494                                     "Kill switch must be turned off for "
5495                                     "wireless networking to work.\n");
5496         }
5497
5498         mutex_unlock(&priv->mutex);
5499         iwl3945_rfkill_set_hw_state(priv);
5500 }
5501
5502 #define IWL_SCAN_CHECK_WATCHDOG (7 * HZ)
5503
5504 static void iwl3945_bg_scan_check(struct work_struct *data)
5505 {
5506         struct iwl_priv *priv =
5507             container_of(data, struct iwl_priv, scan_check.work);
5508
5509         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
5510                 return;
5511
5512         mutex_lock(&priv->mutex);
5513         if (test_bit(STATUS_SCANNING, &priv->status) ||
5514             test_bit(STATUS_SCAN_ABORTING, &priv->status)) {
5515                 IWL_DEBUG(IWL_DL_INFO | IWL_DL_SCAN,
5516                           "Scan completion watchdog resetting adapter (%dms)\n",
5517                           jiffies_to_msecs(IWL_SCAN_CHECK_WATCHDOG));
5518
5519                 if (!test_bit(STATUS_EXIT_PENDING, &priv->status))
5520                         iwl3945_send_scan_abort(priv);
5521         }
5522         mutex_unlock(&priv->mutex);
5523 }
5524
5525 static void iwl3945_bg_request_scan(struct work_struct *data)
5526 {
5527         struct iwl_priv *priv =
5528             container_of(data, struct iwl_priv, request_scan);
5529         struct iwl_host_cmd cmd = {
5530                 .id = REPLY_SCAN_CMD,
5531                 .len = sizeof(struct iwl3945_scan_cmd),
5532                 .meta.flags = CMD_SIZE_HUGE,
5533         };
5534         int rc = 0;
5535         struct iwl3945_scan_cmd *scan;
5536         struct ieee80211_conf *conf = NULL;
5537         u8 n_probes = 2;
5538         enum ieee80211_band band;
5539         DECLARE_SSID_BUF(ssid);
5540
5541         conf = ieee80211_get_hw_conf(priv->hw);
5542
5543         mutex_lock(&priv->mutex);
5544
5545         if (!iwl_is_ready(priv)) {
5546                 IWL_WARN(priv, "request scan called when driver not ready.\n");
5547                 goto done;
5548         }
5549
5550         /* Make sure the scan wasn't canceled before this queued work
5551          * was given the chance to run... */
5552         if (!test_bit(STATUS_SCANNING, &priv->status))
5553                 goto done;
5554
5555         /* This should never be called or scheduled if there is currently
5556          * a scan active in the hardware. */
5557         if (test_bit(STATUS_SCAN_HW, &priv->status)) {
5558                 IWL_DEBUG_INFO("Multiple concurrent scan requests in parallel. "
5559                                "Ignoring second request.\n");
5560                 rc = -EIO;
5561                 goto done;
5562         }
5563
5564         if (test_bit(STATUS_EXIT_PENDING, &priv->status)) {
5565                 IWL_DEBUG_SCAN("Aborting scan due to device shutdown\n");
5566                 goto done;
5567         }
5568
5569         if (test_bit(STATUS_SCAN_ABORTING, &priv->status)) {
5570                 IWL_DEBUG_HC("Scan request while abort pending.  Queuing.\n");
5571                 goto done;
5572         }
5573
5574         if (iwl_is_rfkill(priv)) {
5575                 IWL_DEBUG_HC("Aborting scan due to RF Kill activation\n");
5576                 goto done;
5577         }
5578
5579         if (!test_bit(STATUS_READY, &priv->status)) {
5580                 IWL_DEBUG_HC("Scan request while uninitialized.  Queuing.\n");
5581                 goto done;
5582         }
5583
5584         if (!priv->scan_bands) {
5585                 IWL_DEBUG_HC("Aborting scan due to no requested bands\n");
5586                 goto done;
5587         }
5588
5589         if (!priv->scan39) {
5590                 priv->scan39 = kmalloc(sizeof(struct iwl3945_scan_cmd) +
5591                                      IWL_MAX_SCAN_SIZE, GFP_KERNEL);
5592                 if (!priv->scan39) {
5593                         rc = -ENOMEM;
5594                         goto done;
5595                 }
5596         }
5597         scan = priv->scan39;
5598         memset(scan, 0, sizeof(struct iwl3945_scan_cmd) + IWL_MAX_SCAN_SIZE);
5599
5600         scan->quiet_plcp_th = IWL_PLCP_QUIET_THRESH;
5601         scan->quiet_time = IWL_ACTIVE_QUIET_TIME;
5602
5603         if (iwl3945_is_associated(priv)) {
5604                 u16 interval = 0;
5605                 u32 extra;
5606                 u32 suspend_time = 100;
5607                 u32 scan_suspend_time = 100;
5608                 unsigned long flags;
5609
5610                 IWL_DEBUG_INFO("Scanning while associated...\n");
5611
5612                 spin_lock_irqsave(&priv->lock, flags);
5613                 interval = priv->beacon_int;
5614                 spin_unlock_irqrestore(&priv->lock, flags);
5615
5616                 scan->suspend_time = 0;
5617                 scan->max_out_time = cpu_to_le32(200 * 1024);
5618                 if (!interval)
5619                         interval = suspend_time;
5620                 /*
5621                  * suspend time format:
5622                  *  0-19: beacon interval in usec (time before exec.)
5623                  * 20-23: 0
5624                  * 24-31: number of beacons (suspend between channels)
5625                  */
5626
5627                 extra = (suspend_time / interval) << 24;
5628                 scan_suspend_time = 0xFF0FFFFF &
5629                     (extra | ((suspend_time % interval) * 1024));
5630
5631                 scan->suspend_time = cpu_to_le32(scan_suspend_time);
5632                 IWL_DEBUG_SCAN("suspend_time 0x%X beacon interval %d\n",
5633                                scan_suspend_time, interval);
5634         }
5635
5636         /* We should add the ability for user to lock to PASSIVE ONLY */
5637         if (priv->one_direct_scan) {
5638                 IWL_DEBUG_SCAN
5639                     ("Kicking off one direct scan for '%s'\n",
5640                      print_ssid(ssid, priv->direct_ssid,
5641                                 priv->direct_ssid_len));
5642                 scan->direct_scan[0].id = WLAN_EID_SSID;
5643                 scan->direct_scan[0].len = priv->direct_ssid_len;
5644                 memcpy(scan->direct_scan[0].ssid,
5645                        priv->direct_ssid, priv->direct_ssid_len);
5646                 n_probes++;
5647         } else
5648                 IWL_DEBUG_SCAN("Kicking off one indirect scan.\n");
5649
5650         /* We don't build a direct scan probe request; the uCode will do
5651          * that based on the direct_mask added to each channel entry */
5652         scan->tx_cmd.len = cpu_to_le16(
5653                 iwl3945_fill_probe_req(priv, (struct ieee80211_mgmt *)scan->data,
5654                         IWL_MAX_SCAN_SIZE - sizeof(*scan)));
5655         scan->tx_cmd.tx_flags = TX_CMD_FLG_SEQ_CTL_MSK;
5656         scan->tx_cmd.sta_id = priv->hw_params.bcast_sta_id;
5657         scan->tx_cmd.stop_time.life_time = TX_CMD_LIFE_TIME_INFINITE;
5658
5659         /* flags + rate selection */
5660
5661         if (priv->scan_bands & BIT(IEEE80211_BAND_2GHZ)) {
5662                 scan->flags = RXON_FLG_BAND_24G_MSK | RXON_FLG_AUTO_DETECT_MSK;
5663                 scan->tx_cmd.rate = IWL_RATE_1M_PLCP;
5664                 scan->good_CRC_th = 0;
5665                 band = IEEE80211_BAND_2GHZ;
5666         } else if (priv->scan_bands & BIT(IEEE80211_BAND_5GHZ)) {
5667                 scan->tx_cmd.rate = IWL_RATE_6M_PLCP;
5668                 scan->good_CRC_th = IWL_GOOD_CRC_TH;
5669                 band = IEEE80211_BAND_5GHZ;
5670         } else {
5671                 IWL_WARN(priv, "Invalid scan band count\n");
5672                 goto done;
5673         }
5674
5675         /* select Rx antennas */
5676         scan->flags |= iwl3945_get_antenna_flags(priv);
5677
5678         if (priv->iw_mode == NL80211_IFTYPE_MONITOR)
5679                 scan->filter_flags = RXON_FILTER_PROMISC_MSK;
5680
5681         scan->channel_count =
5682                 iwl3945_get_channels_for_scan(priv, band, 1, /* active */
5683                                               n_probes,
5684                         (void *)&scan->data[le16_to_cpu(scan->tx_cmd.len)]);
5685
5686         if (scan->channel_count == 0) {
5687                 IWL_DEBUG_SCAN("channel count %d\n", scan->channel_count);
5688                 goto done;
5689         }
5690
5691         cmd.len += le16_to_cpu(scan->tx_cmd.len) +
5692             scan->channel_count * sizeof(struct iwl3945_scan_channel);
5693         cmd.data = scan;
5694         scan->len = cpu_to_le16(cmd.len);
5695
5696         set_bit(STATUS_SCAN_HW, &priv->status);
5697         rc = iwl3945_send_cmd_sync(priv, &cmd);
5698         if (rc)
5699                 goto done;
5700
5701         queue_delayed_work(priv->workqueue, &priv->scan_check,
5702                            IWL_SCAN_CHECK_WATCHDOG);
5703
5704         mutex_unlock(&priv->mutex);
5705         return;
5706
5707  done:
5708         /* can not perform scan make sure we clear scanning
5709          * bits from status so next scan request can be performed.
5710          * if we dont clear scanning status bit here all next scan
5711          * will fail
5712         */
5713         clear_bit(STATUS_SCAN_HW, &priv->status);
5714         clear_bit(STATUS_SCANNING, &priv->status);
5715
5716         /* inform mac80211 scan aborted */
5717         queue_work(priv->workqueue, &priv->scan_completed);
5718         mutex_unlock(&priv->mutex);
5719 }
5720
5721 static void iwl3945_bg_up(struct work_struct *data)
5722 {
5723         struct iwl_priv *priv = container_of(data, struct iwl_priv, up);
5724
5725         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
5726                 return;
5727
5728         mutex_lock(&priv->mutex);
5729         __iwl3945_up(priv);
5730         mutex_unlock(&priv->mutex);
5731         iwl3945_rfkill_set_hw_state(priv);
5732 }
5733
5734 static void iwl3945_bg_restart(struct work_struct *data)
5735 {
5736         struct iwl_priv *priv = container_of(data, struct iwl_priv, restart);
5737
5738         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
5739                 return;
5740
5741         iwl3945_down(priv);
5742         queue_work(priv->workqueue, &priv->up);
5743 }
5744
5745 static void iwl3945_bg_rx_replenish(struct work_struct *data)
5746 {
5747         struct iwl_priv *priv =
5748             container_of(data, struct iwl_priv, rx_replenish);
5749
5750         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
5751                 return;
5752
5753         mutex_lock(&priv->mutex);
5754         iwl3945_rx_replenish(priv);
5755         mutex_unlock(&priv->mutex);
5756 }
5757
5758 #define IWL_DELAY_NEXT_SCAN (HZ*2)
5759
5760 static void iwl3945_post_associate(struct iwl_priv *priv)
5761 {
5762         int rc = 0;
5763         struct ieee80211_conf *conf = NULL;
5764
5765         if (priv->iw_mode == NL80211_IFTYPE_AP) {
5766                 IWL_ERR(priv, "%s Should not be called in AP mode\n", __func__);
5767                 return;
5768         }
5769
5770
5771         IWL_DEBUG_ASSOC("Associated as %d to: %pM\n",
5772                         priv->assoc_id, priv->active39_rxon.bssid_addr);
5773
5774         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
5775                 return;
5776
5777         if (!priv->vif || !priv->is_open)
5778                 return;
5779
5780         iwl3945_scan_cancel_timeout(priv, 200);
5781
5782         conf = ieee80211_get_hw_conf(priv->hw);
5783
5784         priv->staging39_rxon.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
5785         iwl3945_commit_rxon(priv);
5786
5787         memset(&priv->rxon_timing, 0, sizeof(struct iwl_rxon_time_cmd));
5788         iwl3945_setup_rxon_timing(priv);
5789         rc = iwl3945_send_cmd_pdu(priv, REPLY_RXON_TIMING,
5790                               sizeof(priv->rxon_timing), &priv->rxon_timing);
5791         if (rc)
5792                 IWL_WARN(priv, "REPLY_RXON_TIMING failed - "
5793                             "Attempting to continue.\n");
5794
5795         priv->staging39_rxon.filter_flags |= RXON_FILTER_ASSOC_MSK;
5796
5797         priv->staging39_rxon.assoc_id = cpu_to_le16(priv->assoc_id);
5798
5799         IWL_DEBUG_ASSOC("assoc id %d beacon interval %d\n",
5800                         priv->assoc_id, priv->beacon_int);
5801
5802         if (priv->assoc_capability & WLAN_CAPABILITY_SHORT_PREAMBLE)
5803                 priv->staging39_rxon.flags |= RXON_FLG_SHORT_PREAMBLE_MSK;
5804         else
5805                 priv->staging39_rxon.flags &= ~RXON_FLG_SHORT_PREAMBLE_MSK;
5806
5807         if (priv->staging39_rxon.flags & RXON_FLG_BAND_24G_MSK) {
5808                 if (priv->assoc_capability & WLAN_CAPABILITY_SHORT_SLOT_TIME)
5809                         priv->staging39_rxon.flags |= RXON_FLG_SHORT_SLOT_MSK;
5810                 else
5811                         priv->staging39_rxon.flags &= ~RXON_FLG_SHORT_SLOT_MSK;
5812
5813                 if (priv->iw_mode == NL80211_IFTYPE_ADHOC)
5814                         priv->staging39_rxon.flags &= ~RXON_FLG_SHORT_SLOT_MSK;
5815
5816         }
5817
5818         iwl3945_commit_rxon(priv);
5819
5820         switch (priv->iw_mode) {
5821         case NL80211_IFTYPE_STATION:
5822                 iwl3945_rate_scale_init(priv->hw, IWL_AP_ID);
5823                 break;
5824
5825         case NL80211_IFTYPE_ADHOC:
5826
5827                 priv->assoc_id = 1;
5828                 iwl3945_add_station(priv, priv->bssid, 0, 0);
5829                 iwl3945_sync_sta(priv, IWL_STA_ID,
5830                                  (priv->band == IEEE80211_BAND_5GHZ) ?
5831                                  IWL_RATE_6M_PLCP : IWL_RATE_1M_PLCP,
5832                                  CMD_ASYNC);
5833                 iwl3945_rate_scale_init(priv->hw, IWL_STA_ID);
5834                 iwl3945_send_beacon_cmd(priv);
5835
5836                 break;
5837
5838         default:
5839                  IWL_ERR(priv, "%s Should not be called in %d mode\n",
5840                            __func__, priv->iw_mode);
5841                 break;
5842         }
5843
5844         iwl3945_activate_qos(priv, 0);
5845
5846         /* we have just associated, don't start scan too early */
5847         priv->next_scan_jiffies = jiffies + IWL_DELAY_NEXT_SCAN;
5848 }
5849
5850 static void iwl3945_bg_abort_scan(struct work_struct *work)
5851 {
5852         struct iwl_priv *priv = container_of(work, struct iwl_priv, abort_scan);
5853
5854         if (!iwl_is_ready(priv))
5855                 return;
5856
5857         mutex_lock(&priv->mutex);
5858
5859         set_bit(STATUS_SCAN_ABORTING, &priv->status);
5860         iwl3945_send_scan_abort(priv);
5861
5862         mutex_unlock(&priv->mutex);
5863 }
5864
5865 static int iwl3945_mac_config(struct ieee80211_hw *hw, u32 changed);
5866
5867 static void iwl3945_bg_scan_completed(struct work_struct *work)
5868 {
5869         struct iwl_priv *priv =
5870             container_of(work, struct iwl_priv, scan_completed);
5871
5872         IWL_DEBUG(IWL_DL_INFO | IWL_DL_SCAN, "SCAN complete scan\n");
5873
5874         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
5875                 return;
5876
5877         if (test_bit(STATUS_CONF_PENDING, &priv->status))
5878                 iwl3945_mac_config(priv->hw, 0);
5879
5880         ieee80211_scan_completed(priv->hw);
5881
5882         /* Since setting the TXPOWER may have been deferred while
5883          * performing the scan, fire one off */
5884         mutex_lock(&priv->mutex);
5885         iwl3945_hw_reg_send_txpower(priv);
5886         mutex_unlock(&priv->mutex);
5887 }
5888
5889 /*****************************************************************************
5890  *
5891  * mac80211 entry point functions
5892  *
5893  *****************************************************************************/
5894
5895 #define UCODE_READY_TIMEOUT     (2 * HZ)
5896
5897 static int iwl3945_mac_start(struct ieee80211_hw *hw)
5898 {
5899         struct iwl_priv *priv = hw->priv;
5900         int ret;
5901
5902         IWL_DEBUG_MAC80211("enter\n");
5903
5904         if (pci_enable_device(priv->pci_dev)) {
5905                 IWL_ERR(priv, "Fail to pci_enable_device\n");
5906                 return -ENODEV;
5907         }
5908         pci_restore_state(priv->pci_dev);
5909         pci_enable_msi(priv->pci_dev);
5910
5911         ret = request_irq(priv->pci_dev->irq, iwl3945_isr, IRQF_SHARED,
5912                           DRV_NAME, priv);
5913         if (ret) {
5914                 IWL_ERR(priv, "Error allocating IRQ %d\n", priv->pci_dev->irq);
5915                 goto out_disable_msi;
5916         }
5917
5918         /* we should be verifying the device is ready to be opened */
5919         mutex_lock(&priv->mutex);
5920
5921         memset(&priv->staging39_rxon, 0, sizeof(struct iwl3945_rxon_cmd));
5922         /* fetch ucode file from disk, alloc and copy to bus-master buffers ...
5923          * ucode filename and max sizes are card-specific. */
5924
5925         if (!priv->ucode_code.len) {
5926                 ret = iwl3945_read_ucode(priv);
5927                 if (ret) {
5928                         IWL_ERR(priv, "Could not read microcode: %d\n", ret);
5929                         mutex_unlock(&priv->mutex);
5930                         goto out_release_irq;
5931                 }
5932         }
5933
5934         ret = __iwl3945_up(priv);
5935
5936         mutex_unlock(&priv->mutex);
5937
5938         iwl3945_rfkill_set_hw_state(priv);
5939
5940         if (ret)
5941                 goto out_release_irq;
5942
5943         IWL_DEBUG_INFO("Start UP work.\n");
5944
5945         if (test_bit(STATUS_IN_SUSPEND, &priv->status))
5946                 return 0;
5947
5948         /* Wait for START_ALIVE from ucode. Otherwise callbacks from
5949          * mac80211 will not be run successfully. */
5950         ret = wait_event_interruptible_timeout(priv->wait_command_queue,
5951                         test_bit(STATUS_READY, &priv->status),
5952                         UCODE_READY_TIMEOUT);
5953         if (!ret) {
5954                 if (!test_bit(STATUS_READY, &priv->status)) {
5955                         IWL_ERR(priv,
5956                                 "Wait for START_ALIVE timeout after %dms.\n",
5957                                 jiffies_to_msecs(UCODE_READY_TIMEOUT));
5958                         ret = -ETIMEDOUT;
5959                         goto out_release_irq;
5960                 }
5961         }
5962
5963         priv->is_open = 1;
5964         IWL_DEBUG_MAC80211("leave\n");
5965         return 0;
5966
5967 out_release_irq:
5968         free_irq(priv->pci_dev->irq, priv);
5969 out_disable_msi:
5970         pci_disable_msi(priv->pci_dev);
5971         pci_disable_device(priv->pci_dev);
5972         priv->is_open = 0;
5973         IWL_DEBUG_MAC80211("leave - failed\n");
5974         return ret;
5975 }
5976
5977 static void iwl3945_mac_stop(struct ieee80211_hw *hw)
5978 {
5979         struct iwl_priv *priv = hw->priv;
5980
5981         IWL_DEBUG_MAC80211("enter\n");
5982
5983         if (!priv->is_open) {
5984                 IWL_DEBUG_MAC80211("leave - skip\n");
5985                 return;
5986         }
5987
5988         priv->is_open = 0;
5989
5990         if (iwl_is_ready_rf(priv)) {
5991                 /* stop mac, cancel any scan request and clear
5992                  * RXON_FILTER_ASSOC_MSK BIT
5993                  */
5994                 mutex_lock(&priv->mutex);
5995                 iwl3945_scan_cancel_timeout(priv, 100);
5996                 mutex_unlock(&priv->mutex);
5997         }
5998
5999         iwl3945_down(priv);
6000
6001         flush_workqueue(priv->workqueue);
6002         free_irq(priv->pci_dev->irq, priv);
6003         pci_disable_msi(priv->pci_dev);
6004         pci_save_state(priv->pci_dev);
6005         pci_disable_device(priv->pci_dev);
6006
6007         IWL_DEBUG_MAC80211("leave\n");
6008 }
6009
6010 static int iwl3945_mac_tx(struct ieee80211_hw *hw, struct sk_buff *skb)
6011 {
6012         struct iwl_priv *priv = hw->priv;
6013
6014         IWL_DEBUG_MAC80211("enter\n");
6015
6016         IWL_DEBUG_TX("dev->xmit(%d bytes) at rate 0x%02x\n", skb->len,
6017                      ieee80211_get_tx_rate(hw, IEEE80211_SKB_CB(skb))->bitrate);
6018
6019         if (iwl3945_tx_skb(priv, skb))
6020                 dev_kfree_skb_any(skb);
6021
6022         IWL_DEBUG_MAC80211("leave\n");
6023         return NETDEV_TX_OK;
6024 }
6025
6026 static int iwl3945_mac_add_interface(struct ieee80211_hw *hw,
6027                                  struct ieee80211_if_init_conf *conf)
6028 {
6029         struct iwl_priv *priv = hw->priv;
6030         unsigned long flags;
6031
6032         IWL_DEBUG_MAC80211("enter: type %d\n", conf->type);
6033
6034         if (priv->vif) {
6035                 IWL_DEBUG_MAC80211("leave - vif != NULL\n");
6036                 return -EOPNOTSUPP;
6037         }
6038
6039         spin_lock_irqsave(&priv->lock, flags);
6040         priv->vif = conf->vif;
6041         priv->iw_mode = conf->type;
6042
6043         spin_unlock_irqrestore(&priv->lock, flags);
6044
6045         mutex_lock(&priv->mutex);
6046
6047         if (conf->mac_addr) {
6048                 IWL_DEBUG_MAC80211("Set: %pM\n", conf->mac_addr);
6049                 memcpy(priv->mac_addr, conf->mac_addr, ETH_ALEN);
6050         }
6051
6052         if (iwl_is_ready(priv))
6053                 iwl3945_set_mode(priv, conf->type);
6054
6055         mutex_unlock(&priv->mutex);
6056
6057         IWL_DEBUG_MAC80211("leave\n");
6058         return 0;
6059 }
6060
6061 /**
6062  * iwl3945_mac_config - mac80211 config callback
6063  *
6064  * We ignore conf->flags & IEEE80211_CONF_SHORT_SLOT_TIME since it seems to
6065  * be set inappropriately and the driver currently sets the hardware up to
6066  * use it whenever needed.
6067  */
6068 static int iwl3945_mac_config(struct ieee80211_hw *hw, u32 changed)
6069 {
6070         struct iwl_priv *priv = hw->priv;
6071         const struct iwl_channel_info *ch_info;
6072         struct ieee80211_conf *conf = &hw->conf;
6073         unsigned long flags;