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