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