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