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