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