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