iwlwifi: prepare for PAN queue/fifo assignment
[platform/adaptation/renesas_rcar/renesas_kernel.git] / drivers / net / wireless / iwlwifi / iwl3945-base.c
1 /******************************************************************************
2  *
3  * Copyright(c) 2003 - 2010 Intel Corporation. All rights reserved.
4  *
5  * Portions of this file are derived from the ipw3945 project, as well
6  * as portions of the ieee80211 subsystem header files.
7  *
8  * This program is free software; you can redistribute it and/or modify it
9  * under the terms of version 2 of the GNU General Public License as
10  * published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
15  * more details.
16  *
17  * You should have received a copy of the GNU General Public License along with
18  * this program; if not, write to the Free Software Foundation, Inc.,
19  * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
20  *
21  * The full GNU General Public License is included in this distribution in the
22  * file called LICENSE.
23  *
24  * Contact Information:
25  *  Intel Linux Wireless <ilw@linux.intel.com>
26  * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
27  *
28  *****************************************************************************/
29
30 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
31
32 #include <linux/kernel.h>
33 #include <linux/module.h>
34 #include <linux/init.h>
35 #include <linux/pci.h>
36 #include <linux/pci-aspm.h>
37 #include <linux/slab.h>
38 #include <linux/dma-mapping.h>
39 #include <linux/delay.h>
40 #include <linux/sched.h>
41 #include <linux/skbuff.h>
42 #include <linux/netdevice.h>
43 #include <linux/wireless.h>
44 #include <linux/firmware.h>
45 #include <linux/etherdevice.h>
46 #include <linux/if_arp.h>
47
48 #include <net/ieee80211_radiotap.h>
49 #include <net/mac80211.h>
50
51 #include <asm/div64.h>
52
53 #define DRV_NAME        "iwl3945"
54
55 #include "iwl-fh.h"
56 #include "iwl-3945-fh.h"
57 #include "iwl-commands.h"
58 #include "iwl-sta.h"
59 #include "iwl-3945.h"
60 #include "iwl-core.h"
61 #include "iwl-helpers.h"
62 #include "iwl-dev.h"
63 #include "iwl-spectrum.h"
64
65 /*
66  * module name, copyright, version, etc.
67  */
68
69 #define DRV_DESCRIPTION \
70 "Intel(R) PRO/Wireless 3945ABG/BG Network Connection driver for Linux"
71
72 #ifdef CONFIG_IWLWIFI_DEBUG
73 #define VD "d"
74 #else
75 #define VD
76 #endif
77
78 /*
79  * add "s" to indicate spectrum measurement included.
80  * we add it here to be consistent with previous releases in which
81  * this was configurable.
82  */
83 #define DRV_VERSION  IWLWIFI_VERSION VD "s"
84 #define DRV_COPYRIGHT   "Copyright(c) 2003-2010 Intel Corporation"
85 #define DRV_AUTHOR     "<ilw@linux.intel.com>"
86
87 MODULE_DESCRIPTION(DRV_DESCRIPTION);
88 MODULE_VERSION(DRV_VERSION);
89 MODULE_AUTHOR(DRV_COPYRIGHT " " DRV_AUTHOR);
90 MODULE_LICENSE("GPL");
91
92  /* module parameters */
93 struct iwl_mod_params iwl3945_mod_params = {
94         .sw_crypto = 1,
95         .restart_fw = 1,
96         /* the rest are 0 by default */
97 };
98
99 /**
100  * iwl3945_get_antenna_flags - Get antenna flags for RXON command
101  * @priv: eeprom and antenna fields are used to determine antenna flags
102  *
103  * priv->eeprom39  is used to determine if antenna AUX/MAIN are reversed
104  * iwl3945_mod_params.antenna specifies the antenna diversity mode:
105  *
106  * IWL_ANTENNA_DIVERSITY - NIC selects best antenna by itself
107  * IWL_ANTENNA_MAIN      - Force MAIN antenna
108  * IWL_ANTENNA_AUX       - Force AUX antenna
109  */
110 __le32 iwl3945_get_antenna_flags(const struct iwl_priv *priv)
111 {
112         struct iwl3945_eeprom *eeprom = (struct iwl3945_eeprom *)priv->eeprom;
113
114         switch (iwl3945_mod_params.antenna) {
115         case IWL_ANTENNA_DIVERSITY:
116                 return 0;
117
118         case IWL_ANTENNA_MAIN:
119                 if (eeprom->antenna_switch_type)
120                         return RXON_FLG_DIS_DIV_MSK | RXON_FLG_ANT_B_MSK;
121                 return RXON_FLG_DIS_DIV_MSK | RXON_FLG_ANT_A_MSK;
122
123         case IWL_ANTENNA_AUX:
124                 if (eeprom->antenna_switch_type)
125                         return RXON_FLG_DIS_DIV_MSK | RXON_FLG_ANT_A_MSK;
126                 return RXON_FLG_DIS_DIV_MSK | RXON_FLG_ANT_B_MSK;
127         }
128
129         /* bad antenna selector value */
130         IWL_ERR(priv, "Bad antenna selector value (0x%x)\n",
131                 iwl3945_mod_params.antenna);
132
133         return 0;               /* "diversity" is default if error */
134 }
135
136 static int iwl3945_set_ccmp_dynamic_key_info(struct iwl_priv *priv,
137                                    struct ieee80211_key_conf *keyconf,
138                                    u8 sta_id)
139 {
140         unsigned long flags;
141         __le16 key_flags = 0;
142         int ret;
143
144         key_flags |= (STA_KEY_FLG_CCMP | STA_KEY_FLG_MAP_KEY_MSK);
145         key_flags |= cpu_to_le16(keyconf->keyidx << STA_KEY_FLG_KEYID_POS);
146
147         if (sta_id == priv->hw_params.bcast_sta_id)
148                 key_flags |= STA_KEY_MULTICAST_MSK;
149
150         keyconf->flags |= IEEE80211_KEY_FLAG_GENERATE_IV;
151         keyconf->hw_key_idx = keyconf->keyidx;
152         key_flags &= ~STA_KEY_FLG_INVALID;
153
154         spin_lock_irqsave(&priv->sta_lock, flags);
155         priv->stations[sta_id].keyinfo.cipher = keyconf->cipher;
156         priv->stations[sta_id].keyinfo.keylen = keyconf->keylen;
157         memcpy(priv->stations[sta_id].keyinfo.key, keyconf->key,
158                keyconf->keylen);
159
160         memcpy(priv->stations[sta_id].sta.key.key, keyconf->key,
161                keyconf->keylen);
162
163         if ((priv->stations[sta_id].sta.key.key_flags & STA_KEY_FLG_ENCRYPT_MSK)
164                         == STA_KEY_FLG_NO_ENC)
165                 priv->stations[sta_id].sta.key.key_offset =
166                                  iwl_get_free_ucode_key_index(priv);
167         /* else, we are overriding an existing key => no need to allocated room
168         * in uCode. */
169
170         WARN(priv->stations[sta_id].sta.key.key_offset == WEP_INVALID_OFFSET,
171                 "no space for a new key");
172
173         priv->stations[sta_id].sta.key.key_flags = key_flags;
174         priv->stations[sta_id].sta.sta.modify_mask = STA_MODIFY_KEY_MASK;
175         priv->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
176
177         IWL_DEBUG_INFO(priv, "hwcrypto: modify ucode station key info\n");
178
179         ret = iwl_send_add_sta(priv, &priv->stations[sta_id].sta, CMD_ASYNC);
180
181         spin_unlock_irqrestore(&priv->sta_lock, flags);
182
183         return ret;
184 }
185
186 static int iwl3945_set_tkip_dynamic_key_info(struct iwl_priv *priv,
187                                   struct ieee80211_key_conf *keyconf,
188                                   u8 sta_id)
189 {
190         return -EOPNOTSUPP;
191 }
192
193 static int iwl3945_set_wep_dynamic_key_info(struct iwl_priv *priv,
194                                   struct ieee80211_key_conf *keyconf,
195                                   u8 sta_id)
196 {
197         return -EOPNOTSUPP;
198 }
199
200 static int iwl3945_clear_sta_key_info(struct iwl_priv *priv, u8 sta_id)
201 {
202         unsigned long flags;
203         struct iwl_addsta_cmd sta_cmd;
204
205         spin_lock_irqsave(&priv->sta_lock, flags);
206         memset(&priv->stations[sta_id].keyinfo, 0, sizeof(struct iwl_hw_key));
207         memset(&priv->stations[sta_id].sta.key, 0,
208                 sizeof(struct iwl4965_keyinfo));
209         priv->stations[sta_id].sta.key.key_flags = STA_KEY_FLG_NO_ENC;
210         priv->stations[sta_id].sta.sta.modify_mask = STA_MODIFY_KEY_MASK;
211         priv->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
212         memcpy(&sta_cmd, &priv->stations[sta_id].sta, sizeof(struct iwl_addsta_cmd));
213         spin_unlock_irqrestore(&priv->sta_lock, flags);
214
215         IWL_DEBUG_INFO(priv, "hwcrypto: clear ucode station key info\n");
216         return iwl_send_add_sta(priv, &sta_cmd, CMD_SYNC);
217 }
218
219 static int iwl3945_set_dynamic_key(struct iwl_priv *priv,
220                         struct ieee80211_key_conf *keyconf, u8 sta_id)
221 {
222         int ret = 0;
223
224         keyconf->hw_key_idx = HW_KEY_DYNAMIC;
225
226         switch (keyconf->cipher) {
227         case WLAN_CIPHER_SUITE_CCMP:
228                 ret = iwl3945_set_ccmp_dynamic_key_info(priv, keyconf, sta_id);
229                 break;
230         case WLAN_CIPHER_SUITE_TKIP:
231                 ret = iwl3945_set_tkip_dynamic_key_info(priv, keyconf, sta_id);
232                 break;
233         case WLAN_CIPHER_SUITE_WEP40:
234         case WLAN_CIPHER_SUITE_WEP104:
235                 ret = iwl3945_set_wep_dynamic_key_info(priv, keyconf, sta_id);
236                 break;
237         default:
238                 IWL_ERR(priv, "Unknown alg: %s alg=%x\n", __func__,
239                         keyconf->cipher);
240                 ret = -EINVAL;
241         }
242
243         IWL_DEBUG_WEP(priv, "Set dynamic key: alg=%x len=%d idx=%d sta=%d ret=%d\n",
244                       keyconf->cipher, keyconf->keylen, keyconf->keyidx,
245                       sta_id, ret);
246
247         return ret;
248 }
249
250 static int iwl3945_remove_static_key(struct iwl_priv *priv)
251 {
252         int ret = -EOPNOTSUPP;
253
254         return ret;
255 }
256
257 static int iwl3945_set_static_key(struct iwl_priv *priv,
258                                 struct ieee80211_key_conf *key)
259 {
260         if (key->cipher == WLAN_CIPHER_SUITE_WEP40 ||
261             key->cipher == WLAN_CIPHER_SUITE_WEP104)
262                 return -EOPNOTSUPP;
263
264         IWL_ERR(priv, "Static key invalid: cipher %x\n", key->cipher);
265         return -EINVAL;
266 }
267
268 static void iwl3945_clear_free_frames(struct iwl_priv *priv)
269 {
270         struct list_head *element;
271
272         IWL_DEBUG_INFO(priv, "%d frames on pre-allocated heap on clear.\n",
273                        priv->frames_count);
274
275         while (!list_empty(&priv->free_frames)) {
276                 element = priv->free_frames.next;
277                 list_del(element);
278                 kfree(list_entry(element, struct iwl3945_frame, list));
279                 priv->frames_count--;
280         }
281
282         if (priv->frames_count) {
283                 IWL_WARN(priv, "%d frames still in use.  Did we lose one?\n",
284                             priv->frames_count);
285                 priv->frames_count = 0;
286         }
287 }
288
289 static struct iwl3945_frame *iwl3945_get_free_frame(struct iwl_priv *priv)
290 {
291         struct iwl3945_frame *frame;
292         struct list_head *element;
293         if (list_empty(&priv->free_frames)) {
294                 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
295                 if (!frame) {
296                         IWL_ERR(priv, "Could not allocate frame!\n");
297                         return NULL;
298                 }
299
300                 priv->frames_count++;
301                 return frame;
302         }
303
304         element = priv->free_frames.next;
305         list_del(element);
306         return list_entry(element, struct iwl3945_frame, list);
307 }
308
309 static void iwl3945_free_frame(struct iwl_priv *priv, struct iwl3945_frame *frame)
310 {
311         memset(frame, 0, sizeof(*frame));
312         list_add(&frame->list, &priv->free_frames);
313 }
314
315 unsigned int iwl3945_fill_beacon_frame(struct iwl_priv *priv,
316                                 struct ieee80211_hdr *hdr,
317                                 int left)
318 {
319
320         if (!iwl_is_associated(priv, IWL_RXON_CTX_BSS) || !priv->ibss_beacon)
321                 return 0;
322
323         if (priv->ibss_beacon->len > left)
324                 return 0;
325
326         memcpy(hdr, priv->ibss_beacon->data, priv->ibss_beacon->len);
327
328         return priv->ibss_beacon->len;
329 }
330
331 static int iwl3945_send_beacon_cmd(struct iwl_priv *priv)
332 {
333         struct iwl3945_frame *frame;
334         unsigned int frame_size;
335         int rc;
336         u8 rate;
337
338         frame = iwl3945_get_free_frame(priv);
339
340         if (!frame) {
341                 IWL_ERR(priv, "Could not obtain free frame buffer for beacon "
342                           "command.\n");
343                 return -ENOMEM;
344         }
345
346         rate = iwl_rate_get_lowest_plcp(priv);
347
348         frame_size = iwl3945_hw_get_beacon_cmd(priv, frame, rate);
349
350         rc = iwl_send_cmd_pdu(priv, REPLY_TX_BEACON, frame_size,
351                               &frame->u.cmd[0]);
352
353         iwl3945_free_frame(priv, frame);
354
355         return rc;
356 }
357
358 static void iwl3945_unset_hw_params(struct iwl_priv *priv)
359 {
360         if (priv->_3945.shared_virt)
361                 dma_free_coherent(&priv->pci_dev->dev,
362                                   sizeof(struct iwl3945_shared),
363                                   priv->_3945.shared_virt,
364                                   priv->_3945.shared_phys);
365 }
366
367 static void iwl3945_build_tx_cmd_hwcrypto(struct iwl_priv *priv,
368                                       struct ieee80211_tx_info *info,
369                                       struct iwl_device_cmd *cmd,
370                                       struct sk_buff *skb_frag,
371                                       int sta_id)
372 {
373         struct iwl3945_tx_cmd *tx_cmd = (struct iwl3945_tx_cmd *)cmd->cmd.payload;
374         struct iwl_hw_key *keyinfo = &priv->stations[sta_id].keyinfo;
375
376         tx_cmd->sec_ctl = 0;
377
378         switch (keyinfo->cipher) {
379         case WLAN_CIPHER_SUITE_CCMP:
380                 tx_cmd->sec_ctl = TX_CMD_SEC_CCM;
381                 memcpy(tx_cmd->key, keyinfo->key, keyinfo->keylen);
382                 IWL_DEBUG_TX(priv, "tx_cmd with AES hwcrypto\n");
383                 break;
384
385         case WLAN_CIPHER_SUITE_TKIP:
386                 break;
387
388         case WLAN_CIPHER_SUITE_WEP104:
389                 tx_cmd->sec_ctl |= TX_CMD_SEC_KEY128;
390                 /* fall through */
391         case WLAN_CIPHER_SUITE_WEP40:
392                 tx_cmd->sec_ctl |= TX_CMD_SEC_WEP |
393                     (info->control.hw_key->hw_key_idx & TX_CMD_SEC_MSK) << TX_CMD_SEC_SHIFT;
394
395                 memcpy(&tx_cmd->key[3], keyinfo->key, keyinfo->keylen);
396
397                 IWL_DEBUG_TX(priv, "Configuring packet for WEP encryption "
398                              "with key %d\n", info->control.hw_key->hw_key_idx);
399                 break;
400
401         default:
402                 IWL_ERR(priv, "Unknown encode cipher %x\n", keyinfo->cipher);
403                 break;
404         }
405 }
406
407 /*
408  * handle build REPLY_TX command notification.
409  */
410 static void iwl3945_build_tx_cmd_basic(struct iwl_priv *priv,
411                                   struct iwl_device_cmd *cmd,
412                                   struct ieee80211_tx_info *info,
413                                   struct ieee80211_hdr *hdr, u8 std_id)
414 {
415         struct iwl3945_tx_cmd *tx_cmd = (struct iwl3945_tx_cmd *)cmd->cmd.payload;
416         __le32 tx_flags = tx_cmd->tx_flags;
417         __le16 fc = hdr->frame_control;
418
419         tx_cmd->stop_time.life_time = TX_CMD_LIFE_TIME_INFINITE;
420         if (!(info->flags & IEEE80211_TX_CTL_NO_ACK)) {
421                 tx_flags |= TX_CMD_FLG_ACK_MSK;
422                 if (ieee80211_is_mgmt(fc))
423                         tx_flags |= TX_CMD_FLG_SEQ_CTL_MSK;
424                 if (ieee80211_is_probe_resp(fc) &&
425                     !(le16_to_cpu(hdr->seq_ctrl) & 0xf))
426                         tx_flags |= TX_CMD_FLG_TSF_MSK;
427         } else {
428                 tx_flags &= (~TX_CMD_FLG_ACK_MSK);
429                 tx_flags |= TX_CMD_FLG_SEQ_CTL_MSK;
430         }
431
432         tx_cmd->sta_id = std_id;
433         if (ieee80211_has_morefrags(fc))
434                 tx_flags |= TX_CMD_FLG_MORE_FRAG_MSK;
435
436         if (ieee80211_is_data_qos(fc)) {
437                 u8 *qc = ieee80211_get_qos_ctl(hdr);
438                 tx_cmd->tid_tspec = qc[0] & 0xf;
439                 tx_flags &= ~TX_CMD_FLG_SEQ_CTL_MSK;
440         } else {
441                 tx_flags |= TX_CMD_FLG_SEQ_CTL_MSK;
442         }
443
444         priv->cfg->ops->utils->tx_cmd_protection(priv, info, fc, &tx_flags);
445
446         tx_flags &= ~(TX_CMD_FLG_ANT_SEL_MSK);
447         if (ieee80211_is_mgmt(fc)) {
448                 if (ieee80211_is_assoc_req(fc) || ieee80211_is_reassoc_req(fc))
449                         tx_cmd->timeout.pm_frame_timeout = cpu_to_le16(3);
450                 else
451                         tx_cmd->timeout.pm_frame_timeout = cpu_to_le16(2);
452         } else {
453                 tx_cmd->timeout.pm_frame_timeout = 0;
454         }
455
456         tx_cmd->driver_txop = 0;
457         tx_cmd->tx_flags = tx_flags;
458         tx_cmd->next_frame_len = 0;
459 }
460
461 /*
462  * start REPLY_TX command process
463  */
464 static int iwl3945_tx_skb(struct iwl_priv *priv, struct sk_buff *skb)
465 {
466         struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
467         struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
468         struct iwl3945_tx_cmd *tx_cmd;
469         struct iwl_tx_queue *txq = NULL;
470         struct iwl_queue *q = NULL;
471         struct iwl_device_cmd *out_cmd;
472         struct iwl_cmd_meta *out_meta;
473         dma_addr_t phys_addr;
474         dma_addr_t txcmd_phys;
475         int txq_id = skb_get_queue_mapping(skb);
476         u16 len, idx, len_org, hdr_len; /* TODO: len_org is not used */
477         u8 id;
478         u8 unicast;
479         u8 sta_id;
480         u8 tid = 0;
481         __le16 fc;
482         u8 wait_write_ptr = 0;
483         unsigned long flags;
484
485         spin_lock_irqsave(&priv->lock, flags);
486         if (iwl_is_rfkill(priv)) {
487                 IWL_DEBUG_DROP(priv, "Dropping - RF KILL\n");
488                 goto drop_unlock;
489         }
490
491         if ((ieee80211_get_tx_rate(priv->hw, info)->hw_value & 0xFF) == IWL_INVALID_RATE) {
492                 IWL_ERR(priv, "ERROR: No TX rate available.\n");
493                 goto drop_unlock;
494         }
495
496         unicast = !is_multicast_ether_addr(hdr->addr1);
497         id = 0;
498
499         fc = hdr->frame_control;
500
501 #ifdef CONFIG_IWLWIFI_DEBUG
502         if (ieee80211_is_auth(fc))
503                 IWL_DEBUG_TX(priv, "Sending AUTH frame\n");
504         else if (ieee80211_is_assoc_req(fc))
505                 IWL_DEBUG_TX(priv, "Sending ASSOC frame\n");
506         else if (ieee80211_is_reassoc_req(fc))
507                 IWL_DEBUG_TX(priv, "Sending REASSOC frame\n");
508 #endif
509
510         spin_unlock_irqrestore(&priv->lock, flags);
511
512         hdr_len = ieee80211_hdrlen(fc);
513
514         /* Find index into station table for destination station */
515         sta_id = iwl_sta_id_or_broadcast(priv, info->control.sta);
516         if (sta_id == IWL_INVALID_STATION) {
517                 IWL_DEBUG_DROP(priv, "Dropping - INVALID STATION: %pM\n",
518                                hdr->addr1);
519                 goto drop;
520         }
521
522         IWL_DEBUG_RATE(priv, "station Id %d\n", sta_id);
523
524         if (ieee80211_is_data_qos(fc)) {
525                 u8 *qc = ieee80211_get_qos_ctl(hdr);
526                 tid = qc[0] & IEEE80211_QOS_CTL_TID_MASK;
527                 if (unlikely(tid >= MAX_TID_COUNT))
528                         goto drop;
529         }
530
531         /* Descriptor for chosen Tx queue */
532         txq = &priv->txq[txq_id];
533         q = &txq->q;
534
535         if ((iwl_queue_space(q) < q->high_mark))
536                 goto drop;
537
538         spin_lock_irqsave(&priv->lock, flags);
539
540         idx = get_cmd_index(q, q->write_ptr, 0);
541
542         /* Set up driver data for this TFD */
543         memset(&(txq->txb[q->write_ptr]), 0, sizeof(struct iwl_tx_info));
544         txq->txb[q->write_ptr].skb = skb;
545
546         /* Init first empty entry in queue's array of Tx/cmd buffers */
547         out_cmd = txq->cmd[idx];
548         out_meta = &txq->meta[idx];
549         tx_cmd = (struct iwl3945_tx_cmd *)out_cmd->cmd.payload;
550         memset(&out_cmd->hdr, 0, sizeof(out_cmd->hdr));
551         memset(tx_cmd, 0, sizeof(*tx_cmd));
552
553         /*
554          * Set up the Tx-command (not MAC!) header.
555          * Store the chosen Tx queue and TFD index within the sequence field;
556          * after Tx, uCode's Tx response will return this value so driver can
557          * locate the frame within the tx queue and do post-tx processing.
558          */
559         out_cmd->hdr.cmd = REPLY_TX;
560         out_cmd->hdr.sequence = cpu_to_le16((u16)(QUEUE_TO_SEQ(txq_id) |
561                                 INDEX_TO_SEQ(q->write_ptr)));
562
563         /* Copy MAC header from skb into command buffer */
564         memcpy(tx_cmd->hdr, hdr, hdr_len);
565
566
567         if (info->control.hw_key)
568                 iwl3945_build_tx_cmd_hwcrypto(priv, info, out_cmd, skb, sta_id);
569
570         /* TODO need this for burst mode later on */
571         iwl3945_build_tx_cmd_basic(priv, out_cmd, info, hdr, sta_id);
572
573         /* set is_hcca to 0; it probably will never be implemented */
574         iwl3945_hw_build_tx_cmd_rate(priv, out_cmd, info, hdr, sta_id, 0);
575
576         /* Total # bytes to be transmitted */
577         len = (u16)skb->len;
578         tx_cmd->len = cpu_to_le16(len);
579
580         iwl_dbg_log_tx_data_frame(priv, len, hdr);
581         iwl_update_stats(priv, true, fc, len);
582         tx_cmd->tx_flags &= ~TX_CMD_FLG_ANT_A_MSK;
583         tx_cmd->tx_flags &= ~TX_CMD_FLG_ANT_B_MSK;
584
585         if (!ieee80211_has_morefrags(hdr->frame_control)) {
586                 txq->need_update = 1;
587         } else {
588                 wait_write_ptr = 1;
589                 txq->need_update = 0;
590         }
591
592         IWL_DEBUG_TX(priv, "sequence nr = 0X%x\n",
593                      le16_to_cpu(out_cmd->hdr.sequence));
594         IWL_DEBUG_TX(priv, "tx_flags = 0X%x\n", le32_to_cpu(tx_cmd->tx_flags));
595         iwl_print_hex_dump(priv, IWL_DL_TX, tx_cmd, sizeof(*tx_cmd));
596         iwl_print_hex_dump(priv, IWL_DL_TX, (u8 *)tx_cmd->hdr,
597                            ieee80211_hdrlen(fc));
598
599         /*
600          * Use the first empty entry in this queue's command buffer array
601          * to contain the Tx command and MAC header concatenated together
602          * (payload data will be in another buffer).
603          * Size of this varies, due to varying MAC header length.
604          * If end is not dword aligned, we'll have 2 extra bytes at the end
605          * of the MAC header (device reads on dword boundaries).
606          * We'll tell device about this padding later.
607          */
608         len = sizeof(struct iwl3945_tx_cmd) +
609                         sizeof(struct iwl_cmd_header) + hdr_len;
610
611         len_org = len;
612         len = (len + 3) & ~3;
613
614         if (len_org != len)
615                 len_org = 1;
616         else
617                 len_org = 0;
618
619         /* Physical address of this Tx command's header (not MAC header!),
620          * within command buffer array. */
621         txcmd_phys = pci_map_single(priv->pci_dev, &out_cmd->hdr,
622                                     len, PCI_DMA_TODEVICE);
623         /* we do not map meta data ... so we can safely access address to
624          * provide to unmap command*/
625         dma_unmap_addr_set(out_meta, mapping, txcmd_phys);
626         dma_unmap_len_set(out_meta, len, len);
627
628         /* Add buffer containing Tx command and MAC(!) header to TFD's
629          * first entry */
630         priv->cfg->ops->lib->txq_attach_buf_to_tfd(priv, txq,
631                                                    txcmd_phys, len, 1, 0);
632
633
634         /* Set up TFD's 2nd entry to point directly to remainder of skb,
635          * if any (802.11 null frames have no payload). */
636         len = skb->len - hdr_len;
637         if (len) {
638                 phys_addr = pci_map_single(priv->pci_dev, skb->data + hdr_len,
639                                            len, PCI_DMA_TODEVICE);
640                 priv->cfg->ops->lib->txq_attach_buf_to_tfd(priv, txq,
641                                                            phys_addr, len,
642                                                            0, U32_PAD(len));
643         }
644
645
646         /* Tell device the write index *just past* this latest filled TFD */
647         q->write_ptr = iwl_queue_inc_wrap(q->write_ptr, q->n_bd);
648         iwl_txq_update_write_ptr(priv, txq);
649         spin_unlock_irqrestore(&priv->lock, flags);
650
651         if ((iwl_queue_space(q) < q->high_mark)
652             && priv->mac80211_registered) {
653                 if (wait_write_ptr) {
654                         spin_lock_irqsave(&priv->lock, flags);
655                         txq->need_update = 1;
656                         iwl_txq_update_write_ptr(priv, txq);
657                         spin_unlock_irqrestore(&priv->lock, flags);
658                 }
659
660                 iwl_stop_queue(priv, skb_get_queue_mapping(skb));
661         }
662
663         return 0;
664
665 drop_unlock:
666         spin_unlock_irqrestore(&priv->lock, flags);
667 drop:
668         return -1;
669 }
670
671 static int iwl3945_get_measurement(struct iwl_priv *priv,
672                                struct ieee80211_measurement_params *params,
673                                u8 type)
674 {
675         struct iwl_spectrum_cmd spectrum;
676         struct iwl_rx_packet *pkt;
677         struct iwl_host_cmd cmd = {
678                 .id = REPLY_SPECTRUM_MEASUREMENT_CMD,
679                 .data = (void *)&spectrum,
680                 .flags = CMD_WANT_SKB,
681         };
682         u32 add_time = le64_to_cpu(params->start_time);
683         int rc;
684         int spectrum_resp_status;
685         int duration = le16_to_cpu(params->duration);
686         struct iwl_rxon_context *ctx = &priv->contexts[IWL_RXON_CTX_BSS];
687
688         if (iwl_is_associated(priv, IWL_RXON_CTX_BSS))
689                 add_time = iwl_usecs_to_beacons(priv,
690                         le64_to_cpu(params->start_time) - priv->_3945.last_tsf,
691                         le16_to_cpu(ctx->timing.beacon_interval));
692
693         memset(&spectrum, 0, sizeof(spectrum));
694
695         spectrum.channel_count = cpu_to_le16(1);
696         spectrum.flags =
697             RXON_FLG_TSF2HOST_MSK | RXON_FLG_ANT_A_MSK | RXON_FLG_DIS_DIV_MSK;
698         spectrum.filter_flags = MEASUREMENT_FILTER_FLAG;
699         cmd.len = sizeof(spectrum);
700         spectrum.len = cpu_to_le16(cmd.len - sizeof(spectrum.len));
701
702         if (iwl_is_associated(priv, IWL_RXON_CTX_BSS))
703                 spectrum.start_time =
704                         iwl_add_beacon_time(priv,
705                                 priv->_3945.last_beacon_time, add_time,
706                                 le16_to_cpu(ctx->timing.beacon_interval));
707         else
708                 spectrum.start_time = 0;
709
710         spectrum.channels[0].duration = cpu_to_le32(duration * TIME_UNIT);
711         spectrum.channels[0].channel = params->channel;
712         spectrum.channels[0].type = type;
713         if (ctx->active.flags & RXON_FLG_BAND_24G_MSK)
714                 spectrum.flags |= RXON_FLG_BAND_24G_MSK |
715                     RXON_FLG_AUTO_DETECT_MSK | RXON_FLG_TGG_PROTECT_MSK;
716
717         rc = iwl_send_cmd_sync(priv, &cmd);
718         if (rc)
719                 return rc;
720
721         pkt = (struct iwl_rx_packet *)cmd.reply_page;
722         if (pkt->hdr.flags & IWL_CMD_FAILED_MSK) {
723                 IWL_ERR(priv, "Bad return from REPLY_RX_ON_ASSOC command\n");
724                 rc = -EIO;
725         }
726
727         spectrum_resp_status = le16_to_cpu(pkt->u.spectrum.status);
728         switch (spectrum_resp_status) {
729         case 0:         /* Command will be handled */
730                 if (pkt->u.spectrum.id != 0xff) {
731                         IWL_DEBUG_INFO(priv, "Replaced existing measurement: %d\n",
732                                                 pkt->u.spectrum.id);
733                         priv->measurement_status &= ~MEASUREMENT_READY;
734                 }
735                 priv->measurement_status |= MEASUREMENT_ACTIVE;
736                 rc = 0;
737                 break;
738
739         case 1:         /* Command will not be handled */
740                 rc = -EAGAIN;
741                 break;
742         }
743
744         iwl_free_pages(priv, cmd.reply_page);
745
746         return rc;
747 }
748
749 static void iwl3945_rx_reply_alive(struct iwl_priv *priv,
750                                struct iwl_rx_mem_buffer *rxb)
751 {
752         struct iwl_rx_packet *pkt = rxb_addr(rxb);
753         struct iwl_alive_resp *palive;
754         struct delayed_work *pwork;
755
756         palive = &pkt->u.alive_frame;
757
758         IWL_DEBUG_INFO(priv, "Alive ucode status 0x%08X revision "
759                        "0x%01X 0x%01X\n",
760                        palive->is_valid, palive->ver_type,
761                        palive->ver_subtype);
762
763         if (palive->ver_subtype == INITIALIZE_SUBTYPE) {
764                 IWL_DEBUG_INFO(priv, "Initialization Alive received.\n");
765                 memcpy(&priv->card_alive_init, &pkt->u.alive_frame,
766                        sizeof(struct iwl_alive_resp));
767                 pwork = &priv->init_alive_start;
768         } else {
769                 IWL_DEBUG_INFO(priv, "Runtime Alive received.\n");
770                 memcpy(&priv->card_alive, &pkt->u.alive_frame,
771                        sizeof(struct iwl_alive_resp));
772                 pwork = &priv->alive_start;
773                 iwl3945_disable_events(priv);
774         }
775
776         /* We delay the ALIVE response by 5ms to
777          * give the HW RF Kill time to activate... */
778         if (palive->is_valid == UCODE_VALID_OK)
779                 queue_delayed_work(priv->workqueue, pwork,
780                                    msecs_to_jiffies(5));
781         else
782                 IWL_WARN(priv, "uCode did not respond OK.\n");
783 }
784
785 static void iwl3945_rx_reply_add_sta(struct iwl_priv *priv,
786                                  struct iwl_rx_mem_buffer *rxb)
787 {
788 #ifdef CONFIG_IWLWIFI_DEBUG
789         struct iwl_rx_packet *pkt = rxb_addr(rxb);
790 #endif
791
792         IWL_DEBUG_RX(priv, "Received REPLY_ADD_STA: 0x%02X\n", pkt->u.status);
793 }
794
795 static void iwl3945_bg_beacon_update(struct work_struct *work)
796 {
797         struct iwl_priv *priv =
798                 container_of(work, struct iwl_priv, beacon_update);
799         struct sk_buff *beacon;
800
801         /* Pull updated AP beacon from mac80211. will fail if not in AP mode */
802         beacon = ieee80211_beacon_get(priv->hw, priv->vif);
803
804         if (!beacon) {
805                 IWL_ERR(priv, "update beacon failed\n");
806                 return;
807         }
808
809         mutex_lock(&priv->mutex);
810         /* new beacon skb is allocated every time; dispose previous.*/
811         if (priv->ibss_beacon)
812                 dev_kfree_skb(priv->ibss_beacon);
813
814         priv->ibss_beacon = beacon;
815         mutex_unlock(&priv->mutex);
816
817         iwl3945_send_beacon_cmd(priv);
818 }
819
820 static void iwl3945_rx_beacon_notif(struct iwl_priv *priv,
821                                 struct iwl_rx_mem_buffer *rxb)
822 {
823         struct iwl_rx_packet *pkt = rxb_addr(rxb);
824         struct iwl3945_beacon_notif *beacon = &(pkt->u.beacon_status);
825 #ifdef CONFIG_IWLWIFI_DEBUG
826         u8 rate = beacon->beacon_notify_hdr.rate;
827
828         IWL_DEBUG_RX(priv, "beacon status %x retries %d iss %d "
829                 "tsf %d %d rate %d\n",
830                 le32_to_cpu(beacon->beacon_notify_hdr.status) & TX_STATUS_MSK,
831                 beacon->beacon_notify_hdr.failure_frame,
832                 le32_to_cpu(beacon->ibss_mgr_status),
833                 le32_to_cpu(beacon->high_tsf),
834                 le32_to_cpu(beacon->low_tsf), rate);
835 #endif
836
837         priv->ibss_manager = le32_to_cpu(beacon->ibss_mgr_status);
838
839         if ((priv->iw_mode == NL80211_IFTYPE_AP) &&
840             (!test_bit(STATUS_EXIT_PENDING, &priv->status)))
841                 queue_work(priv->workqueue, &priv->beacon_update);
842 }
843
844 /* Handle notification from uCode that card's power state is changing
845  * due to software, hardware, or critical temperature RFKILL */
846 static void iwl3945_rx_card_state_notif(struct iwl_priv *priv,
847                                     struct iwl_rx_mem_buffer *rxb)
848 {
849         struct iwl_rx_packet *pkt = rxb_addr(rxb);
850         u32 flags = le32_to_cpu(pkt->u.card_state_notif.flags);
851         unsigned long status = priv->status;
852
853         IWL_WARN(priv, "Card state received: HW:%s SW:%s\n",
854                           (flags & HW_CARD_DISABLED) ? "Kill" : "On",
855                           (flags & SW_CARD_DISABLED) ? "Kill" : "On");
856
857         iwl_write32(priv, CSR_UCODE_DRV_GP1_SET,
858                     CSR_UCODE_DRV_GP1_BIT_CMD_BLOCKED);
859
860         if (flags & HW_CARD_DISABLED)
861                 set_bit(STATUS_RF_KILL_HW, &priv->status);
862         else
863                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
864
865
866         iwl_scan_cancel(priv);
867
868         if ((test_bit(STATUS_RF_KILL_HW, &status) !=
869              test_bit(STATUS_RF_KILL_HW, &priv->status)))
870                 wiphy_rfkill_set_hw_state(priv->hw->wiphy,
871                                 test_bit(STATUS_RF_KILL_HW, &priv->status));
872         else
873                 wake_up_interruptible(&priv->wait_command_queue);
874 }
875
876 /**
877  * iwl3945_setup_rx_handlers - Initialize Rx handler callbacks
878  *
879  * Setup the RX handlers for each of the reply types sent from the uCode
880  * to the host.
881  *
882  * This function chains into the hardware specific files for them to setup
883  * any hardware specific handlers as well.
884  */
885 static void iwl3945_setup_rx_handlers(struct iwl_priv *priv)
886 {
887         priv->rx_handlers[REPLY_ALIVE] = iwl3945_rx_reply_alive;
888         priv->rx_handlers[REPLY_ADD_STA] = iwl3945_rx_reply_add_sta;
889         priv->rx_handlers[REPLY_ERROR] = iwl_rx_reply_error;
890         priv->rx_handlers[CHANNEL_SWITCH_NOTIFICATION] = iwl_rx_csa;
891         priv->rx_handlers[SPECTRUM_MEASURE_NOTIFICATION] =
892                         iwl_rx_spectrum_measure_notif;
893         priv->rx_handlers[PM_SLEEP_NOTIFICATION] = iwl_rx_pm_sleep_notif;
894         priv->rx_handlers[PM_DEBUG_STATISTIC_NOTIFIC] =
895             iwl_rx_pm_debug_statistics_notif;
896         priv->rx_handlers[BEACON_NOTIFICATION] = iwl3945_rx_beacon_notif;
897
898         /*
899          * The same handler is used for both the REPLY to a discrete
900          * statistics request from the host as well as for the periodic
901          * statistics notifications (after received beacons) from the uCode.
902          */
903         priv->rx_handlers[REPLY_STATISTICS_CMD] = iwl3945_reply_statistics;
904         priv->rx_handlers[STATISTICS_NOTIFICATION] = iwl3945_hw_rx_statistics;
905
906         iwl_setup_rx_scan_handlers(priv);
907         priv->rx_handlers[CARD_STATE_NOTIFICATION] = iwl3945_rx_card_state_notif;
908
909         /* Set up hardware specific Rx handlers */
910         iwl3945_hw_rx_handler_setup(priv);
911 }
912
913 /************************** RX-FUNCTIONS ****************************/
914 /*
915  * Rx theory of operation
916  *
917  * The host allocates 32 DMA target addresses and passes the host address
918  * to the firmware at register IWL_RFDS_TABLE_LOWER + N * RFD_SIZE where N is
919  * 0 to 31
920  *
921  * Rx Queue Indexes
922  * The host/firmware share two index registers for managing the Rx buffers.
923  *
924  * The READ index maps to the first position that the firmware may be writing
925  * to -- the driver can read up to (but not including) this position and get
926  * good data.
927  * The READ index is managed by the firmware once the card is enabled.
928  *
929  * The WRITE index maps to the last position the driver has read from -- the
930  * position preceding WRITE is the last slot the firmware can place a packet.
931  *
932  * The queue is empty (no good data) if WRITE = READ - 1, and is full if
933  * WRITE = READ.
934  *
935  * During initialization, the host sets up the READ queue position to the first
936  * INDEX position, and WRITE to the last (READ - 1 wrapped)
937  *
938  * When the firmware places a packet in a buffer, it will advance the READ index
939  * and fire the RX interrupt.  The driver can then query the READ index and
940  * process as many packets as possible, moving the WRITE index forward as it
941  * resets the Rx queue buffers with new memory.
942  *
943  * The management in the driver is as follows:
944  * + A list of pre-allocated SKBs is stored in iwl->rxq->rx_free.  When
945  *   iwl->rxq->free_count drops to or below RX_LOW_WATERMARK, work is scheduled
946  *   to replenish the iwl->rxq->rx_free.
947  * + In iwl3945_rx_replenish (scheduled) if 'processed' != 'read' then the
948  *   iwl->rxq is replenished and the READ INDEX is updated (updating the
949  *   'processed' and 'read' driver indexes as well)
950  * + A received packet is processed and handed to the kernel network stack,
951  *   detached from the iwl->rxq.  The driver 'processed' index is updated.
952  * + The Host/Firmware iwl->rxq is replenished at tasklet time from the rx_free
953  *   list. If there are no allocated buffers in iwl->rxq->rx_free, the READ
954  *   INDEX is not incremented and iwl->status(RX_STALLED) is set.  If there
955  *   were enough free buffers and RX_STALLED is set it is cleared.
956  *
957  *
958  * Driver sequence:
959  *
960  * iwl3945_rx_replenish()     Replenishes rx_free list from rx_used, and calls
961  *                            iwl3945_rx_queue_restock
962  * iwl3945_rx_queue_restock() Moves available buffers from rx_free into Rx
963  *                            queue, updates firmware pointers, and updates
964  *                            the WRITE index.  If insufficient rx_free buffers
965  *                            are available, schedules iwl3945_rx_replenish
966  *
967  * -- enable interrupts --
968  * ISR - iwl3945_rx()         Detach iwl_rx_mem_buffers from pool up to the
969  *                            READ INDEX, detaching the SKB from the pool.
970  *                            Moves the packet buffer from queue to rx_used.
971  *                            Calls iwl3945_rx_queue_restock to refill any empty
972  *                            slots.
973  * ...
974  *
975  */
976
977 /**
978  * iwl3945_dma_addr2rbd_ptr - convert a DMA address to a uCode read buffer ptr
979  */
980 static inline __le32 iwl3945_dma_addr2rbd_ptr(struct iwl_priv *priv,
981                                           dma_addr_t dma_addr)
982 {
983         return cpu_to_le32((u32)dma_addr);
984 }
985
986 /**
987  * iwl3945_rx_queue_restock - refill RX queue from pre-allocated pool
988  *
989  * If there are slots in the RX queue that need to be restocked,
990  * and we have free pre-allocated buffers, fill the ranks as much
991  * as we can, pulling from rx_free.
992  *
993  * This moves the 'write' index forward to catch up with 'processed', and
994  * also updates the memory address in the firmware to reference the new
995  * target buffer.
996  */
997 static void iwl3945_rx_queue_restock(struct iwl_priv *priv)
998 {
999         struct iwl_rx_queue *rxq = &priv->rxq;
1000         struct list_head *element;
1001         struct iwl_rx_mem_buffer *rxb;
1002         unsigned long flags;
1003         int write;
1004
1005         spin_lock_irqsave(&rxq->lock, flags);
1006         write = rxq->write & ~0x7;
1007         while ((iwl_rx_queue_space(rxq) > 0) && (rxq->free_count)) {
1008                 /* Get next free Rx buffer, remove from free list */
1009                 element = rxq->rx_free.next;
1010                 rxb = list_entry(element, struct iwl_rx_mem_buffer, list);
1011                 list_del(element);
1012
1013                 /* Point to Rx buffer via next RBD in circular buffer */
1014                 rxq->bd[rxq->write] = iwl3945_dma_addr2rbd_ptr(priv, rxb->page_dma);
1015                 rxq->queue[rxq->write] = rxb;
1016                 rxq->write = (rxq->write + 1) & RX_QUEUE_MASK;
1017                 rxq->free_count--;
1018         }
1019         spin_unlock_irqrestore(&rxq->lock, flags);
1020         /* If the pre-allocated buffer pool is dropping low, schedule to
1021          * refill it */
1022         if (rxq->free_count <= RX_LOW_WATERMARK)
1023                 queue_work(priv->workqueue, &priv->rx_replenish);
1024
1025
1026         /* If we've added more space for the firmware to place data, tell it.
1027          * Increment device's write pointer in multiples of 8. */
1028         if ((rxq->write_actual != (rxq->write & ~0x7))
1029             || (abs(rxq->write - rxq->read) > 7)) {
1030                 spin_lock_irqsave(&rxq->lock, flags);
1031                 rxq->need_update = 1;
1032                 spin_unlock_irqrestore(&rxq->lock, flags);
1033                 iwl_rx_queue_update_write_ptr(priv, rxq);
1034         }
1035 }
1036
1037 /**
1038  * iwl3945_rx_replenish - Move all used packet from rx_used to rx_free
1039  *
1040  * When moving to rx_free an SKB is allocated for the slot.
1041  *
1042  * Also restock the Rx queue via iwl3945_rx_queue_restock.
1043  * This is called as a scheduled work item (except for during initialization)
1044  */
1045 static void iwl3945_rx_allocate(struct iwl_priv *priv, gfp_t priority)
1046 {
1047         struct iwl_rx_queue *rxq = &priv->rxq;
1048         struct list_head *element;
1049         struct iwl_rx_mem_buffer *rxb;
1050         struct page *page;
1051         unsigned long flags;
1052         gfp_t gfp_mask = priority;
1053
1054         while (1) {
1055                 spin_lock_irqsave(&rxq->lock, flags);
1056
1057                 if (list_empty(&rxq->rx_used)) {
1058                         spin_unlock_irqrestore(&rxq->lock, flags);
1059                         return;
1060                 }
1061                 spin_unlock_irqrestore(&rxq->lock, flags);
1062
1063                 if (rxq->free_count > RX_LOW_WATERMARK)
1064                         gfp_mask |= __GFP_NOWARN;
1065
1066                 if (priv->hw_params.rx_page_order > 0)
1067                         gfp_mask |= __GFP_COMP;
1068
1069                 /* Alloc a new receive buffer */
1070                 page = alloc_pages(gfp_mask, priv->hw_params.rx_page_order);
1071                 if (!page) {
1072                         if (net_ratelimit())
1073                                 IWL_DEBUG_INFO(priv, "Failed to allocate SKB buffer.\n");
1074                         if ((rxq->free_count <= RX_LOW_WATERMARK) &&
1075                             net_ratelimit())
1076                                 IWL_CRIT(priv, "Failed to allocate SKB buffer with %s. Only %u free buffers remaining.\n",
1077                                          priority == GFP_ATOMIC ?  "GFP_ATOMIC" : "GFP_KERNEL",
1078                                          rxq->free_count);
1079                         /* We don't reschedule replenish work here -- we will
1080                          * call the restock method and if it still needs
1081                          * more buffers it will schedule replenish */
1082                         break;
1083                 }
1084
1085                 spin_lock_irqsave(&rxq->lock, flags);
1086                 if (list_empty(&rxq->rx_used)) {
1087                         spin_unlock_irqrestore(&rxq->lock, flags);
1088                         __free_pages(page, priv->hw_params.rx_page_order);
1089                         return;
1090                 }
1091                 element = rxq->rx_used.next;
1092                 rxb = list_entry(element, struct iwl_rx_mem_buffer, list);
1093                 list_del(element);
1094                 spin_unlock_irqrestore(&rxq->lock, flags);
1095
1096                 rxb->page = page;
1097                 /* Get physical address of RB/SKB */
1098                 rxb->page_dma = pci_map_page(priv->pci_dev, page, 0,
1099                                 PAGE_SIZE << priv->hw_params.rx_page_order,
1100                                 PCI_DMA_FROMDEVICE);
1101
1102                 spin_lock_irqsave(&rxq->lock, flags);
1103
1104                 list_add_tail(&rxb->list, &rxq->rx_free);
1105                 rxq->free_count++;
1106                 priv->alloc_rxb_page++;
1107
1108                 spin_unlock_irqrestore(&rxq->lock, flags);
1109         }
1110 }
1111
1112 void iwl3945_rx_queue_reset(struct iwl_priv *priv, struct iwl_rx_queue *rxq)
1113 {
1114         unsigned long flags;
1115         int i;
1116         spin_lock_irqsave(&rxq->lock, flags);
1117         INIT_LIST_HEAD(&rxq->rx_free);
1118         INIT_LIST_HEAD(&rxq->rx_used);
1119         /* Fill the rx_used queue with _all_ of the Rx buffers */
1120         for (i = 0; i < RX_FREE_BUFFERS + RX_QUEUE_SIZE; i++) {
1121                 /* In the reset function, these buffers may have been allocated
1122                  * to an SKB, so we need to unmap and free potential storage */
1123                 if (rxq->pool[i].page != NULL) {
1124                         pci_unmap_page(priv->pci_dev, rxq->pool[i].page_dma,
1125                                 PAGE_SIZE << priv->hw_params.rx_page_order,
1126                                 PCI_DMA_FROMDEVICE);
1127                         __iwl_free_pages(priv, rxq->pool[i].page);
1128                         rxq->pool[i].page = NULL;
1129                 }
1130                 list_add_tail(&rxq->pool[i].list, &rxq->rx_used);
1131         }
1132
1133         /* Set us so that we have processed and used all buffers, but have
1134          * not restocked the Rx queue with fresh buffers */
1135         rxq->read = rxq->write = 0;
1136         rxq->write_actual = 0;
1137         rxq->free_count = 0;
1138         spin_unlock_irqrestore(&rxq->lock, flags);
1139 }
1140
1141 void iwl3945_rx_replenish(void *data)
1142 {
1143         struct iwl_priv *priv = data;
1144         unsigned long flags;
1145
1146         iwl3945_rx_allocate(priv, GFP_KERNEL);
1147
1148         spin_lock_irqsave(&priv->lock, flags);
1149         iwl3945_rx_queue_restock(priv);
1150         spin_unlock_irqrestore(&priv->lock, flags);
1151 }
1152
1153 static void iwl3945_rx_replenish_now(struct iwl_priv *priv)
1154 {
1155         iwl3945_rx_allocate(priv, GFP_ATOMIC);
1156
1157         iwl3945_rx_queue_restock(priv);
1158 }
1159
1160
1161 /* Assumes that the skb field of the buffers in 'pool' is kept accurate.
1162  * If an SKB has been detached, the POOL needs to have its SKB set to NULL
1163  * This free routine walks the list of POOL entries and if SKB is set to
1164  * non NULL it is unmapped and freed
1165  */
1166 static void iwl3945_rx_queue_free(struct iwl_priv *priv, struct iwl_rx_queue *rxq)
1167 {
1168         int i;
1169         for (i = 0; i < RX_QUEUE_SIZE + RX_FREE_BUFFERS; i++) {
1170                 if (rxq->pool[i].page != NULL) {
1171                         pci_unmap_page(priv->pci_dev, rxq->pool[i].page_dma,
1172                                 PAGE_SIZE << priv->hw_params.rx_page_order,
1173                                 PCI_DMA_FROMDEVICE);
1174                         __iwl_free_pages(priv, rxq->pool[i].page);
1175                         rxq->pool[i].page = NULL;
1176                 }
1177         }
1178
1179         dma_free_coherent(&priv->pci_dev->dev, 4 * RX_QUEUE_SIZE, rxq->bd,
1180                           rxq->bd_dma);
1181         dma_free_coherent(&priv->pci_dev->dev, sizeof(struct iwl_rb_status),
1182                           rxq->rb_stts, rxq->rb_stts_dma);
1183         rxq->bd = NULL;
1184         rxq->rb_stts  = NULL;
1185 }
1186
1187
1188 /* Convert linear signal-to-noise ratio into dB */
1189 static u8 ratio2dB[100] = {
1190 /*       0   1   2   3   4   5   6   7   8   9 */
1191          0,  0,  6, 10, 12, 14, 16, 17, 18, 19, /* 00 - 09 */
1192         20, 21, 22, 22, 23, 23, 24, 25, 26, 26, /* 10 - 19 */
1193         26, 26, 26, 27, 27, 28, 28, 28, 29, 29, /* 20 - 29 */
1194         29, 30, 30, 30, 31, 31, 31, 31, 32, 32, /* 30 - 39 */
1195         32, 32, 32, 33, 33, 33, 33, 33, 34, 34, /* 40 - 49 */
1196         34, 34, 34, 34, 35, 35, 35, 35, 35, 35, /* 50 - 59 */
1197         36, 36, 36, 36, 36, 36, 36, 37, 37, 37, /* 60 - 69 */
1198         37, 37, 37, 37, 37, 38, 38, 38, 38, 38, /* 70 - 79 */
1199         38, 38, 38, 38, 38, 39, 39, 39, 39, 39, /* 80 - 89 */
1200         39, 39, 39, 39, 39, 40, 40, 40, 40, 40  /* 90 - 99 */
1201 };
1202
1203 /* Calculates a relative dB value from a ratio of linear
1204  *   (i.e. not dB) signal levels.
1205  * Conversion assumes that levels are voltages (20*log), not powers (10*log). */
1206 int iwl3945_calc_db_from_ratio(int sig_ratio)
1207 {
1208         /* 1000:1 or higher just report as 60 dB */
1209         if (sig_ratio >= 1000)
1210                 return 60;
1211
1212         /* 100:1 or higher, divide by 10 and use table,
1213          *   add 20 dB to make up for divide by 10 */
1214         if (sig_ratio >= 100)
1215                 return 20 + (int)ratio2dB[sig_ratio/10];
1216
1217         /* We shouldn't see this */
1218         if (sig_ratio < 1)
1219                 return 0;
1220
1221         /* Use table for ratios 1:1 - 99:1 */
1222         return (int)ratio2dB[sig_ratio];
1223 }
1224
1225 /**
1226  * iwl3945_rx_handle - Main entry function for receiving responses from uCode
1227  *
1228  * Uses the priv->rx_handlers callback function array to invoke
1229  * the appropriate handlers, including command responses,
1230  * frame-received notifications, and other notifications.
1231  */
1232 static void iwl3945_rx_handle(struct iwl_priv *priv)
1233 {
1234         struct iwl_rx_mem_buffer *rxb;
1235         struct iwl_rx_packet *pkt;
1236         struct iwl_rx_queue *rxq = &priv->rxq;
1237         u32 r, i;
1238         int reclaim;
1239         unsigned long flags;
1240         u8 fill_rx = 0;
1241         u32 count = 8;
1242         int total_empty = 0;
1243
1244         /* uCode's read index (stored in shared DRAM) indicates the last Rx
1245          * buffer that the driver may process (last buffer filled by ucode). */
1246         r = le16_to_cpu(rxq->rb_stts->closed_rb_num) &  0x0FFF;
1247         i = rxq->read;
1248
1249         /* calculate total frames need to be restock after handling RX */
1250         total_empty = r - rxq->write_actual;
1251         if (total_empty < 0)
1252                 total_empty += RX_QUEUE_SIZE;
1253
1254         if (total_empty > (RX_QUEUE_SIZE / 2))
1255                 fill_rx = 1;
1256         /* Rx interrupt, but nothing sent from uCode */
1257         if (i == r)
1258                 IWL_DEBUG_RX(priv, "r = %d, i = %d\n", r, i);
1259
1260         while (i != r) {
1261                 int len;
1262
1263                 rxb = rxq->queue[i];
1264
1265                 /* If an RXB doesn't have a Rx queue slot associated with it,
1266                  * then a bug has been introduced in the queue refilling
1267                  * routines -- catch it here */
1268                 BUG_ON(rxb == NULL);
1269
1270                 rxq->queue[i] = NULL;
1271
1272                 pci_unmap_page(priv->pci_dev, rxb->page_dma,
1273                                PAGE_SIZE << priv->hw_params.rx_page_order,
1274                                PCI_DMA_FROMDEVICE);
1275                 pkt = rxb_addr(rxb);
1276
1277                 len = le32_to_cpu(pkt->len_n_flags) & FH_RSCSR_FRAME_SIZE_MSK;
1278                 len += sizeof(u32); /* account for status word */
1279                 trace_iwlwifi_dev_rx(priv, pkt, len);
1280
1281                 /* Reclaim a command buffer only if this packet is a response
1282                  *   to a (driver-originated) command.
1283                  * If the packet (e.g. Rx frame) originated from uCode,
1284                  *   there is no command buffer to reclaim.
1285                  * Ucode should set SEQ_RX_FRAME bit if ucode-originated,
1286                  *   but apparently a few don't get set; catch them here. */
1287                 reclaim = !(pkt->hdr.sequence & SEQ_RX_FRAME) &&
1288                         (pkt->hdr.cmd != STATISTICS_NOTIFICATION) &&
1289                         (pkt->hdr.cmd != REPLY_TX);
1290
1291                 /* Based on type of command response or notification,
1292                  *   handle those that need handling via function in
1293                  *   rx_handlers table.  See iwl3945_setup_rx_handlers() */
1294                 if (priv->rx_handlers[pkt->hdr.cmd]) {
1295                         IWL_DEBUG_RX(priv, "r = %d, i = %d, %s, 0x%02x\n", r, i,
1296                                 get_cmd_string(pkt->hdr.cmd), pkt->hdr.cmd);
1297                         priv->isr_stats.rx_handlers[pkt->hdr.cmd]++;
1298                         priv->rx_handlers[pkt->hdr.cmd] (priv, rxb);
1299                 } else {
1300                         /* No handling needed */
1301                         IWL_DEBUG_RX(priv,
1302                                 "r %d i %d No handler needed for %s, 0x%02x\n",
1303                                 r, i, get_cmd_string(pkt->hdr.cmd),
1304                                 pkt->hdr.cmd);
1305                 }
1306
1307                 /*
1308                  * XXX: After here, we should always check rxb->page
1309                  * against NULL before touching it or its virtual
1310                  * memory (pkt). Because some rx_handler might have
1311                  * already taken or freed the pages.
1312                  */
1313
1314                 if (reclaim) {
1315                         /* Invoke any callbacks, transfer the buffer to caller,
1316                          * and fire off the (possibly) blocking iwl_send_cmd()
1317                          * as we reclaim the driver command queue */
1318                         if (rxb->page)
1319                                 iwl_tx_cmd_complete(priv, rxb);
1320                         else
1321                                 IWL_WARN(priv, "Claim null rxb?\n");
1322                 }
1323
1324                 /* Reuse the page if possible. For notification packets and
1325                  * SKBs that fail to Rx correctly, add them back into the
1326                  * rx_free list for reuse later. */
1327                 spin_lock_irqsave(&rxq->lock, flags);
1328                 if (rxb->page != NULL) {
1329                         rxb->page_dma = pci_map_page(priv->pci_dev, rxb->page,
1330                                 0, PAGE_SIZE << priv->hw_params.rx_page_order,
1331                                 PCI_DMA_FROMDEVICE);
1332                         list_add_tail(&rxb->list, &rxq->rx_free);
1333                         rxq->free_count++;
1334                 } else
1335                         list_add_tail(&rxb->list, &rxq->rx_used);
1336
1337                 spin_unlock_irqrestore(&rxq->lock, flags);
1338
1339                 i = (i + 1) & RX_QUEUE_MASK;
1340                 /* If there are a lot of unused frames,
1341                  * restock the Rx queue so ucode won't assert. */
1342                 if (fill_rx) {
1343                         count++;
1344                         if (count >= 8) {
1345                                 rxq->read = i;
1346                                 iwl3945_rx_replenish_now(priv);
1347                                 count = 0;
1348                         }
1349                 }
1350         }
1351
1352         /* Backtrack one entry */
1353         rxq->read = i;
1354         if (fill_rx)
1355                 iwl3945_rx_replenish_now(priv);
1356         else
1357                 iwl3945_rx_queue_restock(priv);
1358 }
1359
1360 /* call this function to flush any scheduled tasklet */
1361 static inline void iwl_synchronize_irq(struct iwl_priv *priv)
1362 {
1363         /* wait to make sure we flush pending tasklet*/
1364         synchronize_irq(priv->pci_dev->irq);
1365         tasklet_kill(&priv->irq_tasklet);
1366 }
1367
1368 static const char *desc_lookup(int i)
1369 {
1370         switch (i) {
1371         case 1:
1372                 return "FAIL";
1373         case 2:
1374                 return "BAD_PARAM";
1375         case 3:
1376                 return "BAD_CHECKSUM";
1377         case 4:
1378                 return "NMI_INTERRUPT";
1379         case 5:
1380                 return "SYSASSERT";
1381         case 6:
1382                 return "FATAL_ERROR";
1383         }
1384
1385         return "UNKNOWN";
1386 }
1387
1388 #define ERROR_START_OFFSET  (1 * sizeof(u32))
1389 #define ERROR_ELEM_SIZE     (7 * sizeof(u32))
1390
1391 void iwl3945_dump_nic_error_log(struct iwl_priv *priv)
1392 {
1393         u32 i;
1394         u32 desc, time, count, base, data1;
1395         u32 blink1, blink2, ilink1, ilink2;
1396
1397         base = le32_to_cpu(priv->card_alive.error_event_table_ptr);
1398
1399         if (!iwl3945_hw_valid_rtc_data_addr(base)) {
1400                 IWL_ERR(priv, "Not valid error log pointer 0x%08X\n", base);
1401                 return;
1402         }
1403
1404
1405         count = iwl_read_targ_mem(priv, base);
1406
1407         if (ERROR_START_OFFSET <= count * ERROR_ELEM_SIZE) {
1408                 IWL_ERR(priv, "Start IWL Error Log Dump:\n");
1409                 IWL_ERR(priv, "Status: 0x%08lX, count: %d\n",
1410                         priv->status, count);
1411         }
1412
1413         IWL_ERR(priv, "Desc       Time       asrtPC  blink2 "
1414                   "ilink1  nmiPC   Line\n");
1415         for (i = ERROR_START_OFFSET;
1416              i < (count * ERROR_ELEM_SIZE) + ERROR_START_OFFSET;
1417              i += ERROR_ELEM_SIZE) {
1418                 desc = iwl_read_targ_mem(priv, base + i);
1419                 time =
1420                     iwl_read_targ_mem(priv, base + i + 1 * sizeof(u32));
1421                 blink1 =
1422                     iwl_read_targ_mem(priv, base + i + 2 * sizeof(u32));
1423                 blink2 =
1424                     iwl_read_targ_mem(priv, base + i + 3 * sizeof(u32));
1425                 ilink1 =
1426                     iwl_read_targ_mem(priv, base + i + 4 * sizeof(u32));
1427                 ilink2 =
1428                     iwl_read_targ_mem(priv, base + i + 5 * sizeof(u32));
1429                 data1 =
1430                     iwl_read_targ_mem(priv, base + i + 6 * sizeof(u32));
1431
1432                 IWL_ERR(priv,
1433                         "%-13s (0x%X) %010u 0x%05X 0x%05X 0x%05X 0x%05X %u\n\n",
1434                         desc_lookup(desc), desc, time, blink1, blink2,
1435                         ilink1, ilink2, data1);
1436                 trace_iwlwifi_dev_ucode_error(priv, desc, time, data1, 0,
1437                                         0, blink1, blink2, ilink1, ilink2);
1438         }
1439 }
1440
1441 #define EVENT_START_OFFSET  (6 * sizeof(u32))
1442
1443 /**
1444  * iwl3945_print_event_log - Dump error event log to syslog
1445  *
1446  */
1447 static int iwl3945_print_event_log(struct iwl_priv *priv, u32 start_idx,
1448                                   u32 num_events, u32 mode,
1449                                   int pos, char **buf, size_t bufsz)
1450 {
1451         u32 i;
1452         u32 base;       /* SRAM byte address of event log header */
1453         u32 event_size; /* 2 u32s, or 3 u32s if timestamp recorded */
1454         u32 ptr;        /* SRAM byte address of log data */
1455         u32 ev, time, data; /* event log data */
1456         unsigned long reg_flags;
1457
1458         if (num_events == 0)
1459                 return pos;
1460
1461         base = le32_to_cpu(priv->card_alive.log_event_table_ptr);
1462
1463         if (mode == 0)
1464                 event_size = 2 * sizeof(u32);
1465         else
1466                 event_size = 3 * sizeof(u32);
1467
1468         ptr = base + EVENT_START_OFFSET + (start_idx * event_size);
1469
1470         /* Make sure device is powered up for SRAM reads */
1471         spin_lock_irqsave(&priv->reg_lock, reg_flags);
1472         iwl_grab_nic_access(priv);
1473
1474         /* Set starting address; reads will auto-increment */
1475         _iwl_write_direct32(priv, HBUS_TARG_MEM_RADDR, ptr);
1476         rmb();
1477
1478         /* "time" is actually "data" for mode 0 (no timestamp).
1479          * place event id # at far right for easier visual parsing. */
1480         for (i = 0; i < num_events; i++) {
1481                 ev = _iwl_read_direct32(priv, HBUS_TARG_MEM_RDAT);
1482                 time = _iwl_read_direct32(priv, HBUS_TARG_MEM_RDAT);
1483                 if (mode == 0) {
1484                         /* data, ev */
1485                         if (bufsz) {
1486                                 pos += scnprintf(*buf + pos, bufsz - pos,
1487                                                 "0x%08x:%04u\n",
1488                                                 time, ev);
1489                         } else {
1490                                 IWL_ERR(priv, "0x%08x\t%04u\n", time, ev);
1491                                 trace_iwlwifi_dev_ucode_event(priv, 0,
1492                                                               time, ev);
1493                         }
1494                 } else {
1495                         data = _iwl_read_direct32(priv, HBUS_TARG_MEM_RDAT);
1496                         if (bufsz) {
1497                                 pos += scnprintf(*buf + pos, bufsz - pos,
1498                                                 "%010u:0x%08x:%04u\n",
1499                                                  time, data, ev);
1500                         } else {
1501                                 IWL_ERR(priv, "%010u\t0x%08x\t%04u\n",
1502                                         time, data, ev);
1503                                 trace_iwlwifi_dev_ucode_event(priv, time,
1504                                                               data, ev);
1505                         }
1506                 }
1507         }
1508
1509         /* Allow device to power down */
1510         iwl_release_nic_access(priv);
1511         spin_unlock_irqrestore(&priv->reg_lock, reg_flags);
1512         return pos;
1513 }
1514
1515 /**
1516  * iwl3945_print_last_event_logs - Dump the newest # of event log to syslog
1517  */
1518 static int iwl3945_print_last_event_logs(struct iwl_priv *priv, u32 capacity,
1519                                       u32 num_wraps, u32 next_entry,
1520                                       u32 size, u32 mode,
1521                                       int pos, char **buf, size_t bufsz)
1522 {
1523         /*
1524          * display the newest DEFAULT_LOG_ENTRIES entries
1525          * i.e the entries just before the next ont that uCode would fill.
1526          */
1527         if (num_wraps) {
1528                 if (next_entry < size) {
1529                         pos = iwl3945_print_event_log(priv,
1530                                              capacity - (size - next_entry),
1531                                              size - next_entry, mode,
1532                                              pos, buf, bufsz);
1533                         pos = iwl3945_print_event_log(priv, 0,
1534                                                       next_entry, mode,
1535                                                       pos, buf, bufsz);
1536                 } else
1537                         pos = iwl3945_print_event_log(priv, next_entry - size,
1538                                                       size, mode,
1539                                                       pos, buf, bufsz);
1540         } else {
1541                 if (next_entry < size)
1542                         pos = iwl3945_print_event_log(priv, 0,
1543                                                       next_entry, mode,
1544                                                       pos, buf, bufsz);
1545                 else
1546                         pos = iwl3945_print_event_log(priv, next_entry - size,
1547                                                       size, mode,
1548                                                       pos, buf, bufsz);
1549         }
1550         return pos;
1551 }
1552
1553 #define DEFAULT_IWL3945_DUMP_EVENT_LOG_ENTRIES (20)
1554
1555 int iwl3945_dump_nic_event_log(struct iwl_priv *priv, bool full_log,
1556                             char **buf, bool display)
1557 {
1558         u32 base;       /* SRAM byte address of event log header */
1559         u32 capacity;   /* event log capacity in # entries */
1560         u32 mode;       /* 0 - no timestamp, 1 - timestamp recorded */
1561         u32 num_wraps;  /* # times uCode wrapped to top of log */
1562         u32 next_entry; /* index of next entry to be written by uCode */
1563         u32 size;       /* # entries that we'll print */
1564         int pos = 0;
1565         size_t bufsz = 0;
1566
1567         base = le32_to_cpu(priv->card_alive.log_event_table_ptr);
1568         if (!iwl3945_hw_valid_rtc_data_addr(base)) {
1569                 IWL_ERR(priv, "Invalid event log pointer 0x%08X\n", base);
1570                 return  -EINVAL;
1571         }
1572
1573         /* event log header */
1574         capacity = iwl_read_targ_mem(priv, base);
1575         mode = iwl_read_targ_mem(priv, base + (1 * sizeof(u32)));
1576         num_wraps = iwl_read_targ_mem(priv, base + (2 * sizeof(u32)));
1577         next_entry = iwl_read_targ_mem(priv, base + (3 * sizeof(u32)));
1578
1579         if (capacity > priv->cfg->max_event_log_size) {
1580                 IWL_ERR(priv, "Log capacity %d is bogus, limit to %d entries\n",
1581                         capacity, priv->cfg->max_event_log_size);
1582                 capacity = priv->cfg->max_event_log_size;
1583         }
1584
1585         if (next_entry > priv->cfg->max_event_log_size) {
1586                 IWL_ERR(priv, "Log write index %d is bogus, limit to %d\n",
1587                         next_entry, priv->cfg->max_event_log_size);
1588                 next_entry = priv->cfg->max_event_log_size;
1589         }
1590
1591         size = num_wraps ? capacity : next_entry;
1592
1593         /* bail out if nothing in log */
1594         if (size == 0) {
1595                 IWL_ERR(priv, "Start IWL Event Log Dump: nothing in log\n");
1596                 return pos;
1597         }
1598
1599 #ifdef CONFIG_IWLWIFI_DEBUG
1600         if (!(iwl_get_debug_level(priv) & IWL_DL_FW_ERRORS) && !full_log)
1601                 size = (size > DEFAULT_IWL3945_DUMP_EVENT_LOG_ENTRIES)
1602                         ? DEFAULT_IWL3945_DUMP_EVENT_LOG_ENTRIES : size;
1603 #else
1604         size = (size > DEFAULT_IWL3945_DUMP_EVENT_LOG_ENTRIES)
1605                 ? DEFAULT_IWL3945_DUMP_EVENT_LOG_ENTRIES : size;
1606 #endif
1607
1608         IWL_ERR(priv, "Start IWL Event Log Dump: display last %d count\n",
1609                   size);
1610
1611 #ifdef CONFIG_IWLWIFI_DEBUG
1612         if (display) {
1613                 if (full_log)
1614                         bufsz = capacity * 48;
1615                 else
1616                         bufsz = size * 48;
1617                 *buf = kmalloc(bufsz, GFP_KERNEL);
1618                 if (!*buf)
1619                         return -ENOMEM;
1620         }
1621         if ((iwl_get_debug_level(priv) & IWL_DL_FW_ERRORS) || full_log) {
1622                 /* if uCode has wrapped back to top of log,
1623                  * start at the oldest entry,
1624                  * i.e the next one that uCode would fill.
1625                  */
1626                 if (num_wraps)
1627                         pos = iwl3945_print_event_log(priv, next_entry,
1628                                                 capacity - next_entry, mode,
1629                                                 pos, buf, bufsz);
1630
1631                 /* (then/else) start at top of log */
1632                 pos = iwl3945_print_event_log(priv, 0, next_entry, mode,
1633                                               pos, buf, bufsz);
1634         } else
1635                 pos = iwl3945_print_last_event_logs(priv, capacity, num_wraps,
1636                                                     next_entry, size, mode,
1637                                                     pos, buf, bufsz);
1638 #else
1639         pos = iwl3945_print_last_event_logs(priv, capacity, num_wraps,
1640                                             next_entry, size, mode,
1641                                             pos, buf, bufsz);
1642 #endif
1643         return pos;
1644 }
1645
1646 static void iwl3945_irq_tasklet(struct iwl_priv *priv)
1647 {
1648         u32 inta, handled = 0;
1649         u32 inta_fh;
1650         unsigned long flags;
1651 #ifdef CONFIG_IWLWIFI_DEBUG
1652         u32 inta_mask;
1653 #endif
1654
1655         spin_lock_irqsave(&priv->lock, flags);
1656
1657         /* Ack/clear/reset pending uCode interrupts.
1658          * Note:  Some bits in CSR_INT are "OR" of bits in CSR_FH_INT_STATUS,
1659          *  and will clear only when CSR_FH_INT_STATUS gets cleared. */
1660         inta = iwl_read32(priv, CSR_INT);
1661         iwl_write32(priv, CSR_INT, inta);
1662
1663         /* Ack/clear/reset pending flow-handler (DMA) interrupts.
1664          * Any new interrupts that happen after this, either while we're
1665          * in this tasklet, or later, will show up in next ISR/tasklet. */
1666         inta_fh = iwl_read32(priv, CSR_FH_INT_STATUS);
1667         iwl_write32(priv, CSR_FH_INT_STATUS, inta_fh);
1668
1669 #ifdef CONFIG_IWLWIFI_DEBUG
1670         if (iwl_get_debug_level(priv) & IWL_DL_ISR) {
1671                 /* just for debug */
1672                 inta_mask = iwl_read32(priv, CSR_INT_MASK);
1673                 IWL_DEBUG_ISR(priv, "inta 0x%08x, enabled 0x%08x, fh 0x%08x\n",
1674                               inta, inta_mask, inta_fh);
1675         }
1676 #endif
1677
1678         spin_unlock_irqrestore(&priv->lock, flags);
1679
1680         /* Since CSR_INT and CSR_FH_INT_STATUS reads and clears are not
1681          * atomic, make sure that inta covers all the interrupts that
1682          * we've discovered, even if FH interrupt came in just after
1683          * reading CSR_INT. */
1684         if (inta_fh & CSR39_FH_INT_RX_MASK)
1685                 inta |= CSR_INT_BIT_FH_RX;
1686         if (inta_fh & CSR39_FH_INT_TX_MASK)
1687                 inta |= CSR_INT_BIT_FH_TX;
1688
1689         /* Now service all interrupt bits discovered above. */
1690         if (inta & CSR_INT_BIT_HW_ERR) {
1691                 IWL_ERR(priv, "Hardware error detected.  Restarting.\n");
1692
1693                 /* Tell the device to stop sending interrupts */
1694                 iwl_disable_interrupts(priv);
1695
1696                 priv->isr_stats.hw++;
1697                 iwl_irq_handle_error(priv);
1698
1699                 handled |= CSR_INT_BIT_HW_ERR;
1700
1701                 return;
1702         }
1703
1704 #ifdef CONFIG_IWLWIFI_DEBUG
1705         if (iwl_get_debug_level(priv) & (IWL_DL_ISR)) {
1706                 /* NIC fires this, but we don't use it, redundant with WAKEUP */
1707                 if (inta & CSR_INT_BIT_SCD) {
1708                         IWL_DEBUG_ISR(priv, "Scheduler finished to transmit "
1709                                       "the frame/frames.\n");
1710                         priv->isr_stats.sch++;
1711                 }
1712
1713                 /* Alive notification via Rx interrupt will do the real work */
1714                 if (inta & CSR_INT_BIT_ALIVE) {
1715                         IWL_DEBUG_ISR(priv, "Alive interrupt\n");
1716                         priv->isr_stats.alive++;
1717                 }
1718         }
1719 #endif
1720         /* Safely ignore these bits for debug checks below */
1721         inta &= ~(CSR_INT_BIT_SCD | CSR_INT_BIT_ALIVE);
1722
1723         /* Error detected by uCode */
1724         if (inta & CSR_INT_BIT_SW_ERR) {
1725                 IWL_ERR(priv, "Microcode SW error detected. "
1726                         "Restarting 0x%X.\n", inta);
1727                 priv->isr_stats.sw++;
1728                 priv->isr_stats.sw_err = inta;
1729                 iwl_irq_handle_error(priv);
1730                 handled |= CSR_INT_BIT_SW_ERR;
1731         }
1732
1733         /* uCode wakes up after power-down sleep */
1734         if (inta & CSR_INT_BIT_WAKEUP) {
1735                 IWL_DEBUG_ISR(priv, "Wakeup interrupt\n");
1736                 iwl_rx_queue_update_write_ptr(priv, &priv->rxq);
1737                 iwl_txq_update_write_ptr(priv, &priv->txq[0]);
1738                 iwl_txq_update_write_ptr(priv, &priv->txq[1]);
1739                 iwl_txq_update_write_ptr(priv, &priv->txq[2]);
1740                 iwl_txq_update_write_ptr(priv, &priv->txq[3]);
1741                 iwl_txq_update_write_ptr(priv, &priv->txq[4]);
1742                 iwl_txq_update_write_ptr(priv, &priv->txq[5]);
1743
1744                 priv->isr_stats.wakeup++;
1745                 handled |= CSR_INT_BIT_WAKEUP;
1746         }
1747
1748         /* All uCode command responses, including Tx command responses,
1749          * Rx "responses" (frame-received notification), and other
1750          * notifications from uCode come through here*/
1751         if (inta & (CSR_INT_BIT_FH_RX | CSR_INT_BIT_SW_RX)) {
1752                 iwl3945_rx_handle(priv);
1753                 priv->isr_stats.rx++;
1754                 handled |= (CSR_INT_BIT_FH_RX | CSR_INT_BIT_SW_RX);
1755         }
1756
1757         if (inta & CSR_INT_BIT_FH_TX) {
1758                 IWL_DEBUG_ISR(priv, "Tx interrupt\n");
1759                 priv->isr_stats.tx++;
1760
1761                 iwl_write32(priv, CSR_FH_INT_STATUS, (1 << 6));
1762                 iwl_write_direct32(priv, FH39_TCSR_CREDIT
1763                                         (FH39_SRVC_CHNL), 0x0);
1764                 handled |= CSR_INT_BIT_FH_TX;
1765         }
1766
1767         if (inta & ~handled) {
1768                 IWL_ERR(priv, "Unhandled INTA bits 0x%08x\n", inta & ~handled);
1769                 priv->isr_stats.unhandled++;
1770         }
1771
1772         if (inta & ~priv->inta_mask) {
1773                 IWL_WARN(priv, "Disabled INTA bits 0x%08x were pending\n",
1774                          inta & ~priv->inta_mask);
1775                 IWL_WARN(priv, "   with FH_INT = 0x%08x\n", inta_fh);
1776         }
1777
1778         /* Re-enable all interrupts */
1779         /* only Re-enable if disabled by irq */
1780         if (test_bit(STATUS_INT_ENABLED, &priv->status))
1781                 iwl_enable_interrupts(priv);
1782
1783 #ifdef CONFIG_IWLWIFI_DEBUG
1784         if (iwl_get_debug_level(priv) & (IWL_DL_ISR)) {
1785                 inta = iwl_read32(priv, CSR_INT);
1786                 inta_mask = iwl_read32(priv, CSR_INT_MASK);
1787                 inta_fh = iwl_read32(priv, CSR_FH_INT_STATUS);
1788                 IWL_DEBUG_ISR(priv, "End inta 0x%08x, enabled 0x%08x, fh 0x%08x, "
1789                         "flags 0x%08lx\n", inta, inta_mask, inta_fh, flags);
1790         }
1791 #endif
1792 }
1793
1794 static int iwl3945_get_single_channel_for_scan(struct iwl_priv *priv,
1795                                                struct ieee80211_vif *vif,
1796                                                enum ieee80211_band band,
1797                                                struct iwl3945_scan_channel *scan_ch)
1798 {
1799         const struct ieee80211_supported_band *sband;
1800         u16 passive_dwell = 0;
1801         u16 active_dwell = 0;
1802         int added = 0;
1803         u8 channel = 0;
1804
1805         sband = iwl_get_hw_mode(priv, band);
1806         if (!sband) {
1807                 IWL_ERR(priv, "invalid band\n");
1808                 return added;
1809         }
1810
1811         active_dwell = iwl_get_active_dwell_time(priv, band, 0);
1812         passive_dwell = iwl_get_passive_dwell_time(priv, band, vif);
1813
1814         if (passive_dwell <= active_dwell)
1815                 passive_dwell = active_dwell + 1;
1816
1817
1818         channel = iwl_get_single_channel_number(priv, band);
1819
1820         if (channel) {
1821                 scan_ch->channel = channel;
1822                 scan_ch->type = 0;      /* passive */
1823                 scan_ch->active_dwell = cpu_to_le16(active_dwell);
1824                 scan_ch->passive_dwell = cpu_to_le16(passive_dwell);
1825                 /* Set txpower levels to defaults */
1826                 scan_ch->tpc.dsp_atten = 110;
1827                 if (band == IEEE80211_BAND_5GHZ)
1828                         scan_ch->tpc.tx_gain = ((1 << 5) | (3 << 3)) | 3;
1829                 else
1830                         scan_ch->tpc.tx_gain = ((1 << 5) | (5 << 3));
1831                 added++;
1832         } else
1833                 IWL_ERR(priv, "no valid channel found\n");
1834         return added;
1835 }
1836
1837 static int iwl3945_get_channels_for_scan(struct iwl_priv *priv,
1838                                          enum ieee80211_band band,
1839                                      u8 is_active, u8 n_probes,
1840                                      struct iwl3945_scan_channel *scan_ch,
1841                                      struct ieee80211_vif *vif)
1842 {
1843         struct ieee80211_channel *chan;
1844         const struct ieee80211_supported_band *sband;
1845         const struct iwl_channel_info *ch_info;
1846         u16 passive_dwell = 0;
1847         u16 active_dwell = 0;
1848         int added, i;
1849
1850         sband = iwl_get_hw_mode(priv, band);
1851         if (!sband)
1852                 return 0;
1853
1854         active_dwell = iwl_get_active_dwell_time(priv, band, n_probes);
1855         passive_dwell = iwl_get_passive_dwell_time(priv, band, vif);
1856
1857         if (passive_dwell <= active_dwell)
1858                 passive_dwell = active_dwell + 1;
1859
1860         for (i = 0, added = 0; i < priv->scan_request->n_channels; i++) {
1861                 chan = priv->scan_request->channels[i];
1862
1863                 if (chan->band != band)
1864                         continue;
1865
1866                 scan_ch->channel = chan->hw_value;
1867
1868                 ch_info = iwl_get_channel_info(priv, band, scan_ch->channel);
1869                 if (!is_channel_valid(ch_info)) {
1870                         IWL_DEBUG_SCAN(priv, "Channel %d is INVALID for this band.\n",
1871                                        scan_ch->channel);
1872                         continue;
1873                 }
1874
1875                 scan_ch->active_dwell = cpu_to_le16(active_dwell);
1876                 scan_ch->passive_dwell = cpu_to_le16(passive_dwell);
1877                 /* If passive , set up for auto-switch
1878                  *  and use long active_dwell time.
1879                  */
1880                 if (!is_active || is_channel_passive(ch_info) ||
1881                     (chan->flags & IEEE80211_CHAN_PASSIVE_SCAN)) {
1882                         scan_ch->type = 0;      /* passive */
1883                         if (IWL_UCODE_API(priv->ucode_ver) == 1)
1884                                 scan_ch->active_dwell = cpu_to_le16(passive_dwell - 1);
1885                 } else {
1886                         scan_ch->type = 1;      /* active */
1887                 }
1888
1889                 /* Set direct probe bits. These may be used both for active
1890                  * scan channels (probes gets sent right away),
1891                  * or for passive channels (probes get se sent only after
1892                  * hearing clear Rx packet).*/
1893                 if (IWL_UCODE_API(priv->ucode_ver) >= 2) {
1894                         if (n_probes)
1895                                 scan_ch->type |= IWL39_SCAN_PROBE_MASK(n_probes);
1896                 } else {
1897                         /* uCode v1 does not allow setting direct probe bits on
1898                          * passive channel. */
1899                         if ((scan_ch->type & 1) && n_probes)
1900                                 scan_ch->type |= IWL39_SCAN_PROBE_MASK(n_probes);
1901                 }
1902
1903                 /* Set txpower levels to defaults */
1904                 scan_ch->tpc.dsp_atten = 110;
1905                 /* scan_pwr_info->tpc.dsp_atten; */
1906
1907                 /*scan_pwr_info->tpc.tx_gain; */
1908                 if (band == IEEE80211_BAND_5GHZ)
1909                         scan_ch->tpc.tx_gain = ((1 << 5) | (3 << 3)) | 3;
1910                 else {
1911                         scan_ch->tpc.tx_gain = ((1 << 5) | (5 << 3));
1912                         /* NOTE: if we were doing 6Mb OFDM for scans we'd use
1913                          * power level:
1914                          * scan_ch->tpc.tx_gain = ((1 << 5) | (2 << 3)) | 3;
1915                          */
1916                 }
1917
1918                 IWL_DEBUG_SCAN(priv, "Scanning %d [%s %d]\n",
1919                                scan_ch->channel,
1920                                (scan_ch->type & 1) ? "ACTIVE" : "PASSIVE",
1921                                (scan_ch->type & 1) ?
1922                                active_dwell : passive_dwell);
1923
1924                 scan_ch++;
1925                 added++;
1926         }
1927
1928         IWL_DEBUG_SCAN(priv, "total channels to scan %d\n", added);
1929         return added;
1930 }
1931
1932 static void iwl3945_init_hw_rates(struct iwl_priv *priv,
1933                               struct ieee80211_rate *rates)
1934 {
1935         int i;
1936
1937         for (i = 0; i < IWL_RATE_COUNT_LEGACY; i++) {
1938                 rates[i].bitrate = iwl3945_rates[i].ieee * 5;
1939                 rates[i].hw_value = i; /* Rate scaling will work on indexes */
1940                 rates[i].hw_value_short = i;
1941                 rates[i].flags = 0;
1942                 if ((i > IWL39_LAST_OFDM_RATE) || (i < IWL_FIRST_OFDM_RATE)) {
1943                         /*
1944                          * If CCK != 1M then set short preamble rate flag.
1945                          */
1946                         rates[i].flags |= (iwl3945_rates[i].plcp == 10) ?
1947                                 0 : IEEE80211_RATE_SHORT_PREAMBLE;
1948                 }
1949         }
1950 }
1951
1952 /******************************************************************************
1953  *
1954  * uCode download functions
1955  *
1956  ******************************************************************************/
1957
1958 static void iwl3945_dealloc_ucode_pci(struct iwl_priv *priv)
1959 {
1960         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_code);
1961         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_data);
1962         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_data_backup);
1963         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_init);
1964         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_init_data);
1965         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_boot);
1966 }
1967
1968 /**
1969  * iwl3945_verify_inst_full - verify runtime uCode image in card vs. host,
1970  *     looking at all data.
1971  */
1972 static int iwl3945_verify_inst_full(struct iwl_priv *priv, __le32 *image, u32 len)
1973 {
1974         u32 val;
1975         u32 save_len = len;
1976         int rc = 0;
1977         u32 errcnt;
1978
1979         IWL_DEBUG_INFO(priv, "ucode inst image size is %u\n", len);
1980
1981         iwl_write_direct32(priv, HBUS_TARG_MEM_RADDR,
1982                                IWL39_RTC_INST_LOWER_BOUND);
1983
1984         errcnt = 0;
1985         for (; len > 0; len -= sizeof(u32), image++) {
1986                 /* read data comes through single port, auto-incr addr */
1987                 /* NOTE: Use the debugless read so we don't flood kernel log
1988                  * if IWL_DL_IO is set */
1989                 val = _iwl_read_direct32(priv, HBUS_TARG_MEM_RDAT);
1990                 if (val != le32_to_cpu(*image)) {
1991                         IWL_ERR(priv, "uCode INST section is invalid at "
1992                                   "offset 0x%x, is 0x%x, s/b 0x%x\n",
1993                                   save_len - len, val, le32_to_cpu(*image));
1994                         rc = -EIO;
1995                         errcnt++;
1996                         if (errcnt >= 20)
1997                                 break;
1998                 }
1999         }
2000
2001
2002         if (!errcnt)
2003                 IWL_DEBUG_INFO(priv,
2004                         "ucode image in INSTRUCTION memory is good\n");
2005
2006         return rc;
2007 }
2008
2009
2010 /**
2011  * iwl3945_verify_inst_sparse - verify runtime uCode image in card vs. host,
2012  *   using sample data 100 bytes apart.  If these sample points are good,
2013  *   it's a pretty good bet that everything between them is good, too.
2014  */
2015 static int iwl3945_verify_inst_sparse(struct iwl_priv *priv, __le32 *image, u32 len)
2016 {
2017         u32 val;
2018         int rc = 0;
2019         u32 errcnt = 0;
2020         u32 i;
2021
2022         IWL_DEBUG_INFO(priv, "ucode inst image size is %u\n", len);
2023
2024         for (i = 0; i < len; i += 100, image += 100/sizeof(u32)) {
2025                 /* read data comes through single port, auto-incr addr */
2026                 /* NOTE: Use the debugless read so we don't flood kernel log
2027                  * if IWL_DL_IO is set */
2028                 iwl_write_direct32(priv, HBUS_TARG_MEM_RADDR,
2029                         i + IWL39_RTC_INST_LOWER_BOUND);
2030                 val = _iwl_read_direct32(priv, HBUS_TARG_MEM_RDAT);
2031                 if (val != le32_to_cpu(*image)) {
2032 #if 0 /* Enable this if you want to see details */
2033                         IWL_ERR(priv, "uCode INST section is invalid at "
2034                                   "offset 0x%x, is 0x%x, s/b 0x%x\n",
2035                                   i, val, *image);
2036 #endif
2037                         rc = -EIO;
2038                         errcnt++;
2039                         if (errcnt >= 3)
2040                                 break;
2041                 }
2042         }
2043
2044         return rc;
2045 }
2046
2047
2048 /**
2049  * iwl3945_verify_ucode - determine which instruction image is in SRAM,
2050  *    and verify its contents
2051  */
2052 static int iwl3945_verify_ucode(struct iwl_priv *priv)
2053 {
2054         __le32 *image;
2055         u32 len;
2056         int rc = 0;
2057
2058         /* Try bootstrap */
2059         image = (__le32 *)priv->ucode_boot.v_addr;
2060         len = priv->ucode_boot.len;
2061         rc = iwl3945_verify_inst_sparse(priv, image, len);
2062         if (rc == 0) {
2063                 IWL_DEBUG_INFO(priv, "Bootstrap uCode is good in inst SRAM\n");
2064                 return 0;
2065         }
2066
2067         /* Try initialize */
2068         image = (__le32 *)priv->ucode_init.v_addr;
2069         len = priv->ucode_init.len;
2070         rc = iwl3945_verify_inst_sparse(priv, image, len);
2071         if (rc == 0) {
2072                 IWL_DEBUG_INFO(priv, "Initialize uCode is good in inst SRAM\n");
2073                 return 0;
2074         }
2075
2076         /* Try runtime/protocol */
2077         image = (__le32 *)priv->ucode_code.v_addr;
2078         len = priv->ucode_code.len;
2079         rc = iwl3945_verify_inst_sparse(priv, image, len);
2080         if (rc == 0) {
2081                 IWL_DEBUG_INFO(priv, "Runtime uCode is good in inst SRAM\n");
2082                 return 0;
2083         }
2084
2085         IWL_ERR(priv, "NO VALID UCODE IMAGE IN INSTRUCTION SRAM!!\n");
2086
2087         /* Since nothing seems to match, show first several data entries in
2088          * instruction SRAM, so maybe visual inspection will give a clue.
2089          * Selection of bootstrap image (vs. other images) is arbitrary. */
2090         image = (__le32 *)priv->ucode_boot.v_addr;
2091         len = priv->ucode_boot.len;
2092         rc = iwl3945_verify_inst_full(priv, image, len);
2093
2094         return rc;
2095 }
2096
2097 static void iwl3945_nic_start(struct iwl_priv *priv)
2098 {
2099         /* Remove all resets to allow NIC to operate */
2100         iwl_write32(priv, CSR_RESET, 0);
2101 }
2102
2103 #define IWL3945_UCODE_GET(item)                                         \
2104 static u32 iwl3945_ucode_get_##item(const struct iwl_ucode_header *ucode)\
2105 {                                                                       \
2106         return le32_to_cpu(ucode->u.v1.item);                           \
2107 }
2108
2109 static u32 iwl3945_ucode_get_header_size(u32 api_ver)
2110 {
2111         return 24;
2112 }
2113
2114 static u8 *iwl3945_ucode_get_data(const struct iwl_ucode_header *ucode)
2115 {
2116         return (u8 *) ucode->u.v1.data;
2117 }
2118
2119 IWL3945_UCODE_GET(inst_size);
2120 IWL3945_UCODE_GET(data_size);
2121 IWL3945_UCODE_GET(init_size);
2122 IWL3945_UCODE_GET(init_data_size);
2123 IWL3945_UCODE_GET(boot_size);
2124
2125 /**
2126  * iwl3945_read_ucode - Read uCode images from disk file.
2127  *
2128  * Copy into buffers for card to fetch via bus-mastering
2129  */
2130 static int iwl3945_read_ucode(struct iwl_priv *priv)
2131 {
2132         const struct iwl_ucode_header *ucode;
2133         int ret = -EINVAL, index;
2134         const struct firmware *ucode_raw;
2135         /* firmware file name contains uCode/driver compatibility version */
2136         const char *name_pre = priv->cfg->fw_name_pre;
2137         const unsigned int api_max = priv->cfg->ucode_api_max;
2138         const unsigned int api_min = priv->cfg->ucode_api_min;
2139         char buf[25];
2140         u8 *src;
2141         size_t len;
2142         u32 api_ver, inst_size, data_size, init_size, init_data_size, boot_size;
2143
2144         /* Ask kernel firmware_class module to get the boot firmware off disk.
2145          * request_firmware() is synchronous, file is in memory on return. */
2146         for (index = api_max; index >= api_min; index--) {
2147                 sprintf(buf, "%s%u%s", name_pre, index, ".ucode");
2148                 ret = request_firmware(&ucode_raw, buf, &priv->pci_dev->dev);
2149                 if (ret < 0) {
2150                         IWL_ERR(priv, "%s firmware file req failed: %d\n",
2151                                   buf, ret);
2152                         if (ret == -ENOENT)
2153                                 continue;
2154                         else
2155                                 goto error;
2156                 } else {
2157                         if (index < api_max)
2158                                 IWL_ERR(priv, "Loaded firmware %s, "
2159                                         "which is deprecated. "
2160                                         " Please use API v%u instead.\n",
2161                                           buf, api_max);
2162                         IWL_DEBUG_INFO(priv, "Got firmware '%s' file "
2163                                        "(%zd bytes) from disk\n",
2164                                        buf, ucode_raw->size);
2165                         break;
2166                 }
2167         }
2168
2169         if (ret < 0)
2170                 goto error;
2171
2172         /* Make sure that we got at least our header! */
2173         if (ucode_raw->size <  iwl3945_ucode_get_header_size(1)) {
2174                 IWL_ERR(priv, "File size way too small!\n");
2175                 ret = -EINVAL;
2176                 goto err_release;
2177         }
2178
2179         /* Data from ucode file:  header followed by uCode images */
2180         ucode = (struct iwl_ucode_header *)ucode_raw->data;
2181
2182         priv->ucode_ver = le32_to_cpu(ucode->ver);
2183         api_ver = IWL_UCODE_API(priv->ucode_ver);
2184         inst_size = iwl3945_ucode_get_inst_size(ucode);
2185         data_size = iwl3945_ucode_get_data_size(ucode);
2186         init_size = iwl3945_ucode_get_init_size(ucode);
2187         init_data_size = iwl3945_ucode_get_init_data_size(ucode);
2188         boot_size = iwl3945_ucode_get_boot_size(ucode);
2189         src = iwl3945_ucode_get_data(ucode);
2190
2191         /* api_ver should match the api version forming part of the
2192          * firmware filename ... but we don't check for that and only rely
2193          * on the API version read from firmware header from here on forward */
2194
2195         if (api_ver < api_min || api_ver > api_max) {
2196                 IWL_ERR(priv, "Driver unable to support your firmware API. "
2197                           "Driver supports v%u, firmware is v%u.\n",
2198                           api_max, api_ver);
2199                 priv->ucode_ver = 0;
2200                 ret = -EINVAL;
2201                 goto err_release;
2202         }
2203         if (api_ver != api_max)
2204                 IWL_ERR(priv, "Firmware has old API version. Expected %u, "
2205                           "got %u. New firmware can be obtained "
2206                           "from http://www.intellinuxwireless.org.\n",
2207                           api_max, api_ver);
2208
2209         IWL_INFO(priv, "loaded firmware version %u.%u.%u.%u\n",
2210                 IWL_UCODE_MAJOR(priv->ucode_ver),
2211                 IWL_UCODE_MINOR(priv->ucode_ver),
2212                 IWL_UCODE_API(priv->ucode_ver),
2213                 IWL_UCODE_SERIAL(priv->ucode_ver));
2214
2215         snprintf(priv->hw->wiphy->fw_version,
2216                  sizeof(priv->hw->wiphy->fw_version),
2217                  "%u.%u.%u.%u",
2218                  IWL_UCODE_MAJOR(priv->ucode_ver),
2219                  IWL_UCODE_MINOR(priv->ucode_ver),
2220                  IWL_UCODE_API(priv->ucode_ver),
2221                  IWL_UCODE_SERIAL(priv->ucode_ver));
2222
2223         IWL_DEBUG_INFO(priv, "f/w package hdr ucode version raw = 0x%x\n",
2224                        priv->ucode_ver);
2225         IWL_DEBUG_INFO(priv, "f/w package hdr runtime inst size = %u\n",
2226                        inst_size);
2227         IWL_DEBUG_INFO(priv, "f/w package hdr runtime data size = %u\n",
2228                        data_size);
2229         IWL_DEBUG_INFO(priv, "f/w package hdr init inst size = %u\n",
2230                        init_size);
2231         IWL_DEBUG_INFO(priv, "f/w package hdr init data size = %u\n",
2232                        init_data_size);
2233         IWL_DEBUG_INFO(priv, "f/w package hdr boot inst size = %u\n",
2234                        boot_size);
2235
2236
2237         /* Verify size of file vs. image size info in file's header */
2238         if (ucode_raw->size != iwl3945_ucode_get_header_size(api_ver) +
2239                 inst_size + data_size + init_size +
2240                 init_data_size + boot_size) {
2241
2242                 IWL_DEBUG_INFO(priv,
2243                         "uCode file size %zd does not match expected size\n",
2244                         ucode_raw->size);
2245                 ret = -EINVAL;
2246                 goto err_release;
2247         }
2248
2249         /* Verify that uCode images will fit in card's SRAM */
2250         if (inst_size > IWL39_MAX_INST_SIZE) {
2251                 IWL_DEBUG_INFO(priv, "uCode instr len %d too large to fit in\n",
2252                                inst_size);
2253                 ret = -EINVAL;
2254                 goto err_release;
2255         }
2256
2257         if (data_size > IWL39_MAX_DATA_SIZE) {
2258                 IWL_DEBUG_INFO(priv, "uCode data len %d too large to fit in\n",
2259                                data_size);
2260                 ret = -EINVAL;
2261                 goto err_release;
2262         }
2263         if (init_size > IWL39_MAX_INST_SIZE) {
2264                 IWL_DEBUG_INFO(priv,
2265                                 "uCode init instr len %d too large to fit in\n",
2266                                 init_size);
2267                 ret = -EINVAL;
2268                 goto err_release;
2269         }
2270         if (init_data_size > IWL39_MAX_DATA_SIZE) {
2271                 IWL_DEBUG_INFO(priv,
2272                                 "uCode init data len %d too large to fit in\n",
2273                                 init_data_size);
2274                 ret = -EINVAL;
2275                 goto err_release;
2276         }
2277         if (boot_size > IWL39_MAX_BSM_SIZE) {
2278                 IWL_DEBUG_INFO(priv,
2279                                 "uCode boot instr len %d too large to fit in\n",
2280                                 boot_size);
2281                 ret = -EINVAL;
2282                 goto err_release;
2283         }
2284
2285         /* Allocate ucode buffers for card's bus-master loading ... */
2286
2287         /* Runtime instructions and 2 copies of data:
2288          * 1) unmodified from disk
2289          * 2) backup cache for save/restore during power-downs */
2290         priv->ucode_code.len = inst_size;
2291         iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_code);
2292
2293         priv->ucode_data.len = data_size;
2294         iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_data);
2295
2296         priv->ucode_data_backup.len = data_size;
2297         iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_data_backup);
2298
2299         if (!priv->ucode_code.v_addr || !priv->ucode_data.v_addr ||
2300             !priv->ucode_data_backup.v_addr)
2301                 goto err_pci_alloc;
2302
2303         /* Initialization instructions and data */
2304         if (init_size && init_data_size) {
2305                 priv->ucode_init.len = init_size;
2306                 iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_init);
2307
2308                 priv->ucode_init_data.len = init_data_size;
2309                 iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_init_data);
2310
2311                 if (!priv->ucode_init.v_addr || !priv->ucode_init_data.v_addr)
2312                         goto err_pci_alloc;
2313         }
2314
2315         /* Bootstrap (instructions only, no data) */
2316         if (boot_size) {
2317                 priv->ucode_boot.len = boot_size;
2318                 iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_boot);
2319
2320                 if (!priv->ucode_boot.v_addr)
2321                         goto err_pci_alloc;
2322         }
2323
2324         /* Copy images into buffers for card's bus-master reads ... */
2325
2326         /* Runtime instructions (first block of data in file) */
2327         len = inst_size;
2328         IWL_DEBUG_INFO(priv,
2329                 "Copying (but not loading) uCode instr len %zd\n", len);
2330         memcpy(priv->ucode_code.v_addr, src, len);
2331         src += len;
2332
2333         IWL_DEBUG_INFO(priv, "uCode instr buf vaddr = 0x%p, paddr = 0x%08x\n",
2334                 priv->ucode_code.v_addr, (u32)priv->ucode_code.p_addr);
2335
2336         /* Runtime data (2nd block)
2337          * NOTE:  Copy into backup buffer will be done in iwl3945_up()  */
2338         len = data_size;
2339         IWL_DEBUG_INFO(priv,
2340                 "Copying (but not loading) uCode data len %zd\n", len);
2341         memcpy(priv->ucode_data.v_addr, src, len);
2342         memcpy(priv->ucode_data_backup.v_addr, src, len);
2343         src += len;
2344
2345         /* Initialization instructions (3rd block) */
2346         if (init_size) {
2347                 len = init_size;
2348                 IWL_DEBUG_INFO(priv,
2349                         "Copying (but not loading) init instr len %zd\n", len);
2350                 memcpy(priv->ucode_init.v_addr, src, len);
2351                 src += len;
2352         }
2353
2354         /* Initialization data (4th block) */
2355         if (init_data_size) {
2356                 len = init_data_size;
2357                 IWL_DEBUG_INFO(priv,
2358                         "Copying (but not loading) init data len %zd\n", len);
2359                 memcpy(priv->ucode_init_data.v_addr, src, len);
2360                 src += len;
2361         }
2362
2363         /* Bootstrap instructions (5th block) */
2364         len = boot_size;
2365         IWL_DEBUG_INFO(priv,
2366                 "Copying (but not loading) boot instr len %zd\n", len);
2367         memcpy(priv->ucode_boot.v_addr, src, len);
2368
2369         /* We have our copies now, allow OS release its copies */
2370         release_firmware(ucode_raw);
2371         return 0;
2372
2373  err_pci_alloc:
2374         IWL_ERR(priv, "failed to allocate pci memory\n");
2375         ret = -ENOMEM;
2376         iwl3945_dealloc_ucode_pci(priv);
2377
2378  err_release:
2379         release_firmware(ucode_raw);
2380
2381  error:
2382         return ret;
2383 }
2384
2385
2386 /**
2387  * iwl3945_set_ucode_ptrs - Set uCode address location
2388  *
2389  * Tell initialization uCode where to find runtime uCode.
2390  *
2391  * BSM registers initially contain pointers to initialization uCode.
2392  * We need to replace them to load runtime uCode inst and data,
2393  * and to save runtime data when powering down.
2394  */
2395 static int iwl3945_set_ucode_ptrs(struct iwl_priv *priv)
2396 {
2397         dma_addr_t pinst;
2398         dma_addr_t pdata;
2399
2400         /* bits 31:0 for 3945 */
2401         pinst = priv->ucode_code.p_addr;
2402         pdata = priv->ucode_data_backup.p_addr;
2403
2404         /* Tell bootstrap uCode where to find image to load */
2405         iwl_write_prph(priv, BSM_DRAM_INST_PTR_REG, pinst);
2406         iwl_write_prph(priv, BSM_DRAM_DATA_PTR_REG, pdata);
2407         iwl_write_prph(priv, BSM_DRAM_DATA_BYTECOUNT_REG,
2408                                  priv->ucode_data.len);
2409
2410         /* Inst byte count must be last to set up, bit 31 signals uCode
2411          *   that all new ptr/size info is in place */
2412         iwl_write_prph(priv, BSM_DRAM_INST_BYTECOUNT_REG,
2413                                  priv->ucode_code.len | BSM_DRAM_INST_LOAD);
2414
2415         IWL_DEBUG_INFO(priv, "Runtime uCode pointers are set.\n");
2416
2417         return 0;
2418 }
2419
2420 /**
2421  * iwl3945_init_alive_start - Called after REPLY_ALIVE notification received
2422  *
2423  * Called after REPLY_ALIVE notification received from "initialize" uCode.
2424  *
2425  * Tell "initialize" uCode to go ahead and load the runtime uCode.
2426  */
2427 static void iwl3945_init_alive_start(struct iwl_priv *priv)
2428 {
2429         /* Check alive response for "valid" sign from uCode */
2430         if (priv->card_alive_init.is_valid != UCODE_VALID_OK) {
2431                 /* We had an error bringing up the hardware, so take it
2432                  * all the way back down so we can try again */
2433                 IWL_DEBUG_INFO(priv, "Initialize Alive failed.\n");
2434                 goto restart;
2435         }
2436
2437         /* Bootstrap uCode has loaded initialize uCode ... verify inst image.
2438          * This is a paranoid check, because we would not have gotten the
2439          * "initialize" alive if code weren't properly loaded.  */
2440         if (iwl3945_verify_ucode(priv)) {
2441                 /* Runtime instruction load was bad;
2442                  * take it all the way back down so we can try again */
2443                 IWL_DEBUG_INFO(priv, "Bad \"initialize\" uCode load.\n");
2444                 goto restart;
2445         }
2446
2447         /* Send pointers to protocol/runtime uCode image ... init code will
2448          * load and launch runtime uCode, which will send us another "Alive"
2449          * notification. */
2450         IWL_DEBUG_INFO(priv, "Initialization Alive received.\n");
2451         if (iwl3945_set_ucode_ptrs(priv)) {
2452                 /* Runtime instruction load won't happen;
2453                  * take it all the way back down so we can try again */
2454                 IWL_DEBUG_INFO(priv, "Couldn't set up uCode pointers.\n");
2455                 goto restart;
2456         }
2457         return;
2458
2459  restart:
2460         queue_work(priv->workqueue, &priv->restart);
2461 }
2462
2463 /**
2464  * iwl3945_alive_start - called after REPLY_ALIVE notification received
2465  *                   from protocol/runtime uCode (initialization uCode's
2466  *                   Alive gets handled by iwl3945_init_alive_start()).
2467  */
2468 static void iwl3945_alive_start(struct iwl_priv *priv)
2469 {
2470         int thermal_spin = 0;
2471         u32 rfkill;
2472         struct iwl_rxon_context *ctx = &priv->contexts[IWL_RXON_CTX_BSS];
2473
2474         IWL_DEBUG_INFO(priv, "Runtime Alive received.\n");
2475
2476         if (priv->card_alive.is_valid != UCODE_VALID_OK) {
2477                 /* We had an error bringing up the hardware, so take it
2478                  * all the way back down so we can try again */
2479                 IWL_DEBUG_INFO(priv, "Alive failed.\n");
2480                 goto restart;
2481         }
2482
2483         /* Initialize uCode has loaded Runtime uCode ... verify inst image.
2484          * This is a paranoid check, because we would not have gotten the
2485          * "runtime" alive if code weren't properly loaded.  */
2486         if (iwl3945_verify_ucode(priv)) {
2487                 /* Runtime instruction load was bad;
2488                  * take it all the way back down so we can try again */
2489                 IWL_DEBUG_INFO(priv, "Bad runtime uCode load.\n");
2490                 goto restart;
2491         }
2492
2493         rfkill = iwl_read_prph(priv, APMG_RFKILL_REG);
2494         IWL_DEBUG_INFO(priv, "RFKILL status: 0x%x\n", rfkill);
2495
2496         if (rfkill & 0x1) {
2497                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
2498                 /* if RFKILL is not on, then wait for thermal
2499                  * sensor in adapter to kick in */
2500                 while (iwl3945_hw_get_temperature(priv) == 0) {
2501                         thermal_spin++;
2502                         udelay(10);
2503                 }
2504
2505                 if (thermal_spin)
2506                         IWL_DEBUG_INFO(priv, "Thermal calibration took %dus\n",
2507                                        thermal_spin * 10);
2508         } else
2509                 set_bit(STATUS_RF_KILL_HW, &priv->status);
2510
2511         /* After the ALIVE response, we can send commands to 3945 uCode */
2512         set_bit(STATUS_ALIVE, &priv->status);
2513
2514         if (priv->cfg->ops->lib->recover_from_tx_stall) {
2515                 /* Enable timer to monitor the driver queues */
2516                 mod_timer(&priv->monitor_recover,
2517                         jiffies +
2518                         msecs_to_jiffies(priv->cfg->monitor_recover_period));
2519         }
2520
2521         if (iwl_is_rfkill(priv))
2522                 return;
2523
2524         ieee80211_wake_queues(priv->hw);
2525
2526         priv->active_rate = IWL_RATES_MASK;
2527
2528         iwl_power_update_mode(priv, true);
2529
2530         if (iwl_is_associated(priv, IWL_RXON_CTX_BSS)) {
2531                 struct iwl3945_rxon_cmd *active_rxon =
2532                                 (struct iwl3945_rxon_cmd *)(&ctx->active);
2533
2534                 ctx->staging.filter_flags |= RXON_FILTER_ASSOC_MSK;
2535                 active_rxon->filter_flags &= ~RXON_FILTER_ASSOC_MSK;
2536         } else {
2537                 /* Initialize our rx_config data */
2538                 iwl_connection_init_rx_config(priv, NULL);
2539         }
2540
2541         /* Configure Bluetooth device coexistence support */
2542         priv->cfg->ops->hcmd->send_bt_config(priv);
2543
2544         /* Configure the adapter for unassociated operation */
2545         iwlcore_commit_rxon(priv, ctx);
2546
2547         iwl3945_reg_txpower_periodic(priv);
2548
2549         iwl_leds_init(priv);
2550
2551         IWL_DEBUG_INFO(priv, "ALIVE processing complete.\n");
2552         set_bit(STATUS_READY, &priv->status);
2553         wake_up_interruptible(&priv->wait_command_queue);
2554
2555         return;
2556
2557  restart:
2558         queue_work(priv->workqueue, &priv->restart);
2559 }
2560
2561 static void iwl3945_cancel_deferred_work(struct iwl_priv *priv);
2562
2563 static void __iwl3945_down(struct iwl_priv *priv)
2564 {
2565         unsigned long flags;
2566         int exit_pending = test_bit(STATUS_EXIT_PENDING, &priv->status);
2567         struct ieee80211_conf *conf = NULL;
2568
2569         IWL_DEBUG_INFO(priv, DRV_NAME " is going down\n");
2570
2571         conf = ieee80211_get_hw_conf(priv->hw);
2572
2573         if (!exit_pending)
2574                 set_bit(STATUS_EXIT_PENDING, &priv->status);
2575
2576         /* Stop TX queues watchdog. We need to have STATUS_EXIT_PENDING bit set
2577          * to prevent rearm timer */
2578         if (priv->cfg->ops->lib->recover_from_tx_stall)
2579                 del_timer_sync(&priv->monitor_recover);
2580
2581         /* Station information will now be cleared in device */
2582         iwl_clear_ucode_stations(priv);
2583         iwl_dealloc_bcast_station(priv);
2584         iwl_clear_driver_stations(priv);
2585
2586         /* Unblock any waiting calls */
2587         wake_up_interruptible_all(&priv->wait_command_queue);
2588
2589         /* Wipe out the EXIT_PENDING status bit if we are not actually
2590          * exiting the module */
2591         if (!exit_pending)
2592                 clear_bit(STATUS_EXIT_PENDING, &priv->status);
2593
2594         /* stop and reset the on-board processor */
2595         iwl_write32(priv, CSR_RESET, CSR_RESET_REG_FLAG_NEVO_RESET);
2596
2597         /* tell the device to stop sending interrupts */
2598         spin_lock_irqsave(&priv->lock, flags);
2599         iwl_disable_interrupts(priv);
2600         spin_unlock_irqrestore(&priv->lock, flags);
2601         iwl_synchronize_irq(priv);
2602
2603         if (priv->mac80211_registered)
2604                 ieee80211_stop_queues(priv->hw);
2605
2606         /* If we have not previously called iwl3945_init() then
2607          * clear all bits but the RF Kill bits and return */
2608         if (!iwl_is_init(priv)) {
2609                 priv->status = test_bit(STATUS_RF_KILL_HW, &priv->status) <<
2610                                         STATUS_RF_KILL_HW |
2611                                test_bit(STATUS_GEO_CONFIGURED, &priv->status) <<
2612                                         STATUS_GEO_CONFIGURED |
2613                                 test_bit(STATUS_EXIT_PENDING, &priv->status) <<
2614                                         STATUS_EXIT_PENDING;
2615                 goto exit;
2616         }
2617
2618         /* ...otherwise clear out all the status bits but the RF Kill
2619          * bit and continue taking the NIC down. */
2620         priv->status &= test_bit(STATUS_RF_KILL_HW, &priv->status) <<
2621                                 STATUS_RF_KILL_HW |
2622                         test_bit(STATUS_GEO_CONFIGURED, &priv->status) <<
2623                                 STATUS_GEO_CONFIGURED |
2624                         test_bit(STATUS_FW_ERROR, &priv->status) <<
2625                                 STATUS_FW_ERROR |
2626                         test_bit(STATUS_EXIT_PENDING, &priv->status) <<
2627                                 STATUS_EXIT_PENDING;
2628
2629         iwl3945_hw_txq_ctx_stop(priv);
2630         iwl3945_hw_rxq_stop(priv);
2631
2632         /* Power-down device's busmaster DMA clocks */
2633         iwl_write_prph(priv, APMG_CLK_DIS_REG, APMG_CLK_VAL_DMA_CLK_RQT);
2634         udelay(5);
2635
2636         /* Stop the device, and put it in low power state */
2637         priv->cfg->ops->lib->apm_ops.stop(priv);
2638
2639  exit:
2640         memset(&priv->card_alive, 0, sizeof(struct iwl_alive_resp));
2641
2642         if (priv->ibss_beacon)
2643                 dev_kfree_skb(priv->ibss_beacon);
2644         priv->ibss_beacon = NULL;
2645
2646         /* clear out any free frames */
2647         iwl3945_clear_free_frames(priv);
2648 }
2649
2650 static void iwl3945_down(struct iwl_priv *priv)
2651 {
2652         mutex_lock(&priv->mutex);
2653         __iwl3945_down(priv);
2654         mutex_unlock(&priv->mutex);
2655
2656         iwl3945_cancel_deferred_work(priv);
2657 }
2658
2659 #define MAX_HW_RESTARTS 5
2660
2661 static int __iwl3945_up(struct iwl_priv *priv)
2662 {
2663         int rc, i;
2664
2665         rc = iwl_alloc_bcast_station(priv, false);
2666         if (rc)
2667                 return rc;
2668
2669         if (test_bit(STATUS_EXIT_PENDING, &priv->status)) {
2670                 IWL_WARN(priv, "Exit pending; will not bring the NIC up\n");
2671                 return -EIO;
2672         }
2673
2674         if (!priv->ucode_data_backup.v_addr || !priv->ucode_data.v_addr) {
2675                 IWL_ERR(priv, "ucode not available for device bring up\n");
2676                 return -EIO;
2677         }
2678
2679         /* If platform's RF_KILL switch is NOT set to KILL */
2680         if (iwl_read32(priv, CSR_GP_CNTRL) &
2681                                 CSR_GP_CNTRL_REG_FLAG_HW_RF_KILL_SW)
2682                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
2683         else {
2684                 set_bit(STATUS_RF_KILL_HW, &priv->status);
2685                 IWL_WARN(priv, "Radio disabled by HW RF Kill switch\n");
2686                 return -ENODEV;
2687         }
2688
2689         iwl_write32(priv, CSR_INT, 0xFFFFFFFF);
2690
2691         rc = iwl3945_hw_nic_init(priv);
2692         if (rc) {
2693                 IWL_ERR(priv, "Unable to int nic\n");
2694                 return rc;
2695         }
2696
2697         /* make sure rfkill handshake bits are cleared */
2698         iwl_write32(priv, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
2699         iwl_write32(priv, CSR_UCODE_DRV_GP1_CLR,
2700                     CSR_UCODE_DRV_GP1_BIT_CMD_BLOCKED);
2701
2702         /* clear (again), then enable host interrupts */
2703         iwl_write32(priv, CSR_INT, 0xFFFFFFFF);
2704         iwl_enable_interrupts(priv);
2705
2706         /* really make sure rfkill handshake bits are cleared */
2707         iwl_write32(priv, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
2708         iwl_write32(priv, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
2709
2710         /* Copy original ucode data image from disk into backup cache.
2711          * This will be used to initialize the on-board processor's
2712          * data SRAM for a clean start when the runtime program first loads. */
2713         memcpy(priv->ucode_data_backup.v_addr, priv->ucode_data.v_addr,
2714                priv->ucode_data.len);
2715
2716         /* We return success when we resume from suspend and rf_kill is on. */
2717         if (test_bit(STATUS_RF_KILL_HW, &priv->status))
2718                 return 0;
2719
2720         for (i = 0; i < MAX_HW_RESTARTS; i++) {
2721
2722                 /* load bootstrap state machine,
2723                  * load bootstrap program into processor's memory,
2724                  * prepare to load the "initialize" uCode */
2725                 rc = priv->cfg->ops->lib->load_ucode(priv);
2726
2727                 if (rc) {
2728                         IWL_ERR(priv,
2729                                 "Unable to set up bootstrap uCode: %d\n", rc);
2730                         continue;
2731                 }
2732
2733                 /* start card; "initialize" will load runtime ucode */
2734                 iwl3945_nic_start(priv);
2735
2736                 IWL_DEBUG_INFO(priv, DRV_NAME " is coming up\n");
2737
2738                 return 0;
2739         }
2740
2741         set_bit(STATUS_EXIT_PENDING, &priv->status);
2742         __iwl3945_down(priv);
2743         clear_bit(STATUS_EXIT_PENDING, &priv->status);
2744
2745         /* tried to restart and config the device for as long as our
2746          * patience could withstand */
2747         IWL_ERR(priv, "Unable to initialize device after %d attempts.\n", i);
2748         return -EIO;
2749 }
2750
2751
2752 /*****************************************************************************
2753  *
2754  * Workqueue callbacks
2755  *
2756  *****************************************************************************/
2757
2758 static void iwl3945_bg_init_alive_start(struct work_struct *data)
2759 {
2760         struct iwl_priv *priv =
2761             container_of(data, struct iwl_priv, init_alive_start.work);
2762
2763         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
2764                 return;
2765
2766         mutex_lock(&priv->mutex);
2767         iwl3945_init_alive_start(priv);
2768         mutex_unlock(&priv->mutex);
2769 }
2770
2771 static void iwl3945_bg_alive_start(struct work_struct *data)
2772 {
2773         struct iwl_priv *priv =
2774             container_of(data, struct iwl_priv, alive_start.work);
2775
2776         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
2777                 return;
2778
2779         mutex_lock(&priv->mutex);
2780         iwl3945_alive_start(priv);
2781         mutex_unlock(&priv->mutex);
2782 }
2783
2784 /*
2785  * 3945 cannot interrupt driver when hardware rf kill switch toggles;
2786  * driver must poll CSR_GP_CNTRL_REG register for change.  This register
2787  * *is* readable even when device has been SW_RESET into low power mode
2788  * (e.g. during RF KILL).
2789  */
2790 static void iwl3945_rfkill_poll(struct work_struct *data)
2791 {
2792         struct iwl_priv *priv =
2793             container_of(data, struct iwl_priv, _3945.rfkill_poll.work);
2794         bool old_rfkill = test_bit(STATUS_RF_KILL_HW, &priv->status);
2795         bool new_rfkill = !(iwl_read32(priv, CSR_GP_CNTRL)
2796                         & CSR_GP_CNTRL_REG_FLAG_HW_RF_KILL_SW);
2797
2798         if (new_rfkill != old_rfkill) {
2799                 if (new_rfkill)
2800                         set_bit(STATUS_RF_KILL_HW, &priv->status);
2801                 else
2802                         clear_bit(STATUS_RF_KILL_HW, &priv->status);
2803
2804                 wiphy_rfkill_set_hw_state(priv->hw->wiphy, new_rfkill);
2805
2806                 IWL_DEBUG_RF_KILL(priv, "RF_KILL bit toggled to %s.\n",
2807                                 new_rfkill ? "disable radio" : "enable radio");
2808         }
2809
2810         /* Keep this running, even if radio now enabled.  This will be
2811          * cancelled in mac_start() if system decides to start again */
2812         queue_delayed_work(priv->workqueue, &priv->_3945.rfkill_poll,
2813                            round_jiffies_relative(2 * HZ));
2814
2815 }
2816
2817 void iwl3945_request_scan(struct iwl_priv *priv, struct ieee80211_vif *vif)
2818 {
2819         struct iwl_host_cmd cmd = {
2820                 .id = REPLY_SCAN_CMD,
2821                 .len = sizeof(struct iwl3945_scan_cmd),
2822                 .flags = CMD_SIZE_HUGE,
2823         };
2824         struct iwl3945_scan_cmd *scan;
2825         struct ieee80211_conf *conf = NULL;
2826         u8 n_probes = 0;
2827         enum ieee80211_band band;
2828         bool is_active = false;
2829
2830         conf = ieee80211_get_hw_conf(priv->hw);
2831
2832         cancel_delayed_work(&priv->scan_check);
2833
2834         if (!iwl_is_ready(priv)) {
2835                 IWL_WARN(priv, "request scan called when driver not ready.\n");
2836                 goto done;
2837         }
2838
2839         /* Make sure the scan wasn't canceled before this queued work
2840          * was given the chance to run... */
2841         if (!test_bit(STATUS_SCANNING, &priv->status))
2842                 goto done;
2843
2844         /* This should never be called or scheduled if there is currently
2845          * a scan active in the hardware. */
2846         if (test_bit(STATUS_SCAN_HW, &priv->status)) {
2847                 IWL_DEBUG_INFO(priv, "Multiple concurrent scan requests  "
2848                                 "Ignoring second request.\n");
2849                 goto done;
2850         }
2851
2852         if (test_bit(STATUS_EXIT_PENDING, &priv->status)) {
2853                 IWL_DEBUG_SCAN(priv, "Aborting scan due to device shutdown\n");
2854                 goto done;
2855         }
2856
2857         if (test_bit(STATUS_SCAN_ABORTING, &priv->status)) {
2858                 IWL_DEBUG_HC(priv,
2859                         "Scan request while abort pending. Queuing.\n");
2860                 goto done;
2861         }
2862
2863         if (iwl_is_rfkill(priv)) {
2864                 IWL_DEBUG_HC(priv, "Aborting scan due to RF Kill activation\n");
2865                 goto done;
2866         }
2867
2868         if (!test_bit(STATUS_READY, &priv->status)) {
2869                 IWL_DEBUG_HC(priv,
2870                         "Scan request while uninitialized. Queuing.\n");
2871                 goto done;
2872         }
2873
2874         if (!priv->scan_cmd) {
2875                 priv->scan_cmd = kmalloc(sizeof(struct iwl3945_scan_cmd) +
2876                                          IWL_MAX_SCAN_SIZE, GFP_KERNEL);
2877                 if (!priv->scan_cmd) {
2878                         IWL_DEBUG_SCAN(priv, "Fail to allocate scan memory\n");
2879                         goto done;
2880                 }
2881         }
2882         scan = priv->scan_cmd;
2883         memset(scan, 0, sizeof(struct iwl3945_scan_cmd) + IWL_MAX_SCAN_SIZE);
2884
2885         scan->quiet_plcp_th = IWL_PLCP_QUIET_THRESH;
2886         scan->quiet_time = IWL_ACTIVE_QUIET_TIME;
2887
2888         if (iwl_is_associated(priv, IWL_RXON_CTX_BSS)) {
2889                 u16 interval = 0;
2890                 u32 extra;
2891                 u32 suspend_time = 100;
2892                 u32 scan_suspend_time = 100;
2893                 unsigned long flags;
2894
2895                 IWL_DEBUG_INFO(priv, "Scanning while associated...\n");
2896
2897                 spin_lock_irqsave(&priv->lock, flags);
2898                 if (priv->is_internal_short_scan)
2899                         interval = 0;
2900                 else
2901                         interval = vif->bss_conf.beacon_int;
2902                 spin_unlock_irqrestore(&priv->lock, flags);
2903
2904                 scan->suspend_time = 0;
2905                 scan->max_out_time = cpu_to_le32(200 * 1024);
2906                 if (!interval)
2907                         interval = suspend_time;
2908                 /*
2909                  * suspend time format:
2910                  *  0-19: beacon interval in usec (time before exec.)
2911                  * 20-23: 0
2912                  * 24-31: number of beacons (suspend between channels)
2913                  */
2914
2915                 extra = (suspend_time / interval) << 24;
2916                 scan_suspend_time = 0xFF0FFFFF &
2917                     (extra | ((suspend_time % interval) * 1024));
2918
2919                 scan->suspend_time = cpu_to_le32(scan_suspend_time);
2920                 IWL_DEBUG_SCAN(priv, "suspend_time 0x%X beacon interval %d\n",
2921                                scan_suspend_time, interval);
2922         }
2923
2924         if (priv->is_internal_short_scan) {
2925                 IWL_DEBUG_SCAN(priv, "Start internal passive scan.\n");
2926         } else if (priv->scan_request->n_ssids) {
2927                 int i, p = 0;
2928                 IWL_DEBUG_SCAN(priv, "Kicking off active scan\n");
2929                 for (i = 0; i < priv->scan_request->n_ssids; i++) {
2930                         /* always does wildcard anyway */
2931                         if (!priv->scan_request->ssids[i].ssid_len)
2932                                 continue;
2933                         scan->direct_scan[p].id = WLAN_EID_SSID;
2934                         scan->direct_scan[p].len =
2935                                 priv->scan_request->ssids[i].ssid_len;
2936                         memcpy(scan->direct_scan[p].ssid,
2937                                priv->scan_request->ssids[i].ssid,
2938                                priv->scan_request->ssids[i].ssid_len);
2939                         n_probes++;
2940                         p++;
2941                 }
2942                 is_active = true;
2943         } else
2944                 IWL_DEBUG_SCAN(priv, "Kicking off passive scan.\n");
2945
2946         /* We don't build a direct scan probe request; the uCode will do
2947          * that based on the direct_mask added to each channel entry */
2948         scan->tx_cmd.tx_flags = TX_CMD_FLG_SEQ_CTL_MSK;
2949         scan->tx_cmd.sta_id = priv->hw_params.bcast_sta_id;
2950         scan->tx_cmd.stop_time.life_time = TX_CMD_LIFE_TIME_INFINITE;
2951
2952         /* flags + rate selection */
2953
2954         switch (priv->scan_band) {
2955         case IEEE80211_BAND_2GHZ:
2956                 scan->flags = RXON_FLG_BAND_24G_MSK | RXON_FLG_AUTO_DETECT_MSK;
2957                 scan->tx_cmd.rate = IWL_RATE_1M_PLCP;
2958                 scan->good_CRC_th = 0;
2959                 band = IEEE80211_BAND_2GHZ;
2960                 break;
2961         case IEEE80211_BAND_5GHZ:
2962                 scan->tx_cmd.rate = IWL_RATE_6M_PLCP;
2963                 /*
2964                  * If active scaning is requested but a certain channel
2965                  * is marked passive, we can do active scanning if we
2966                  * detect transmissions.
2967                  */
2968                 scan->good_CRC_th = is_active ? IWL_GOOD_CRC_TH_DEFAULT :
2969                                                 IWL_GOOD_CRC_TH_DISABLED;
2970                 band = IEEE80211_BAND_5GHZ;
2971                 break;
2972         default:
2973                 IWL_WARN(priv, "Invalid scan band\n");
2974                 goto done;
2975         }
2976
2977         if (!priv->is_internal_short_scan) {
2978                 scan->tx_cmd.len = cpu_to_le16(
2979                         iwl_fill_probe_req(priv,
2980                                 (struct ieee80211_mgmt *)scan->data,
2981                                 vif->addr,
2982                                 priv->scan_request->ie,
2983                                 priv->scan_request->ie_len,
2984                                 IWL_MAX_SCAN_SIZE - sizeof(*scan)));
2985         } else {
2986                 /* use bcast addr, will not be transmitted but must be valid */
2987                 scan->tx_cmd.len = cpu_to_le16(
2988                         iwl_fill_probe_req(priv,
2989                                 (struct ieee80211_mgmt *)scan->data,
2990                                 iwl_bcast_addr, NULL, 0,
2991                                 IWL_MAX_SCAN_SIZE - sizeof(*scan)));
2992         }
2993         /* select Rx antennas */
2994         scan->flags |= iwl3945_get_antenna_flags(priv);
2995
2996         if (priv->is_internal_short_scan) {
2997                 scan->channel_count =
2998                         iwl3945_get_single_channel_for_scan(priv, vif, band,
2999                                 (void *)&scan->data[le16_to_cpu(
3000                                 scan->tx_cmd.len)]);
3001         } else {
3002                 scan->channel_count =
3003                         iwl3945_get_channels_for_scan(priv, band, is_active, n_probes,
3004                                 (void *)&scan->data[le16_to_cpu(scan->tx_cmd.len)], vif);
3005         }
3006
3007         if (scan->channel_count == 0) {
3008                 IWL_DEBUG_SCAN(priv, "channel count %d\n", scan->channel_count);
3009                 goto done;
3010         }
3011
3012         cmd.len += le16_to_cpu(scan->tx_cmd.len) +
3013             scan->channel_count * sizeof(struct iwl3945_scan_channel);
3014         cmd.data = scan;
3015         scan->len = cpu_to_le16(cmd.len);
3016
3017         set_bit(STATUS_SCAN_HW, &priv->status);
3018         if (iwl_send_cmd_sync(priv, &cmd))
3019                 goto done;
3020
3021         queue_delayed_work(priv->workqueue, &priv->scan_check,
3022                            IWL_SCAN_CHECK_WATCHDOG);
3023
3024         return;
3025
3026  done:
3027         /* can not perform scan make sure we clear scanning
3028          * bits from status so next scan request can be performed.
3029          * if we dont clear scanning status bit here all next scan
3030          * will fail
3031         */
3032         clear_bit(STATUS_SCAN_HW, &priv->status);
3033         clear_bit(STATUS_SCANNING, &priv->status);
3034
3035         /* inform mac80211 scan aborted */
3036         queue_work(priv->workqueue, &priv->scan_completed);
3037 }
3038
3039 static void iwl3945_bg_restart(struct work_struct *data)
3040 {
3041         struct iwl_priv *priv = container_of(data, struct iwl_priv, restart);
3042
3043         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
3044                 return;
3045
3046         if (test_and_clear_bit(STATUS_FW_ERROR, &priv->status)) {
3047                 mutex_lock(&priv->mutex);
3048                 priv->vif = NULL;
3049                 priv->is_open = 0;
3050                 mutex_unlock(&priv->mutex);
3051                 iwl3945_down(priv);
3052                 ieee80211_restart_hw(priv->hw);
3053         } else {
3054                 iwl3945_down(priv);
3055
3056                 if (test_bit(STATUS_EXIT_PENDING, &priv->status))
3057                         return;
3058
3059                 mutex_lock(&priv->mutex);
3060                 __iwl3945_up(priv);
3061                 mutex_unlock(&priv->mutex);
3062         }
3063 }
3064
3065 static void iwl3945_bg_rx_replenish(struct work_struct *data)
3066 {
3067         struct iwl_priv *priv =
3068             container_of(data, struct iwl_priv, rx_replenish);
3069
3070         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
3071                 return;
3072
3073         mutex_lock(&priv->mutex);
3074         iwl3945_rx_replenish(priv);
3075         mutex_unlock(&priv->mutex);
3076 }
3077
3078 void iwl3945_post_associate(struct iwl_priv *priv, struct ieee80211_vif *vif)
3079 {
3080         int rc = 0;
3081         struct ieee80211_conf *conf = NULL;
3082         struct iwl_rxon_context *ctx = &priv->contexts[IWL_RXON_CTX_BSS];
3083
3084         if (!vif || !priv->is_open)
3085                 return;
3086
3087         if (vif->type == NL80211_IFTYPE_AP) {
3088                 IWL_ERR(priv, "%s Should not be called in AP mode\n", __func__);
3089                 return;
3090         }
3091
3092         IWL_DEBUG_ASSOC(priv, "Associated as %d to: %pM\n",
3093                         vif->bss_conf.aid, ctx->active.bssid_addr);
3094
3095         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
3096                 return;
3097
3098         iwl_scan_cancel_timeout(priv, 200);
3099
3100         conf = ieee80211_get_hw_conf(priv->hw);
3101
3102         ctx->staging.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
3103         iwlcore_commit_rxon(priv, ctx);
3104
3105         rc = iwl_send_rxon_timing(priv, vif);
3106         if (rc)
3107                 IWL_WARN(priv, "REPLY_RXON_TIMING failed - "
3108                             "Attempting to continue.\n");
3109
3110         ctx->staging.filter_flags |= RXON_FILTER_ASSOC_MSK;
3111
3112         ctx->staging.assoc_id = cpu_to_le16(vif->bss_conf.aid);
3113
3114         IWL_DEBUG_ASSOC(priv, "assoc id %d beacon interval %d\n",
3115                         vif->bss_conf.aid, vif->bss_conf.beacon_int);
3116
3117         if (vif->bss_conf.use_short_preamble)
3118                 ctx->staging.flags |= RXON_FLG_SHORT_PREAMBLE_MSK;
3119         else
3120                 ctx->staging.flags &= ~RXON_FLG_SHORT_PREAMBLE_MSK;
3121
3122         if (ctx->staging.flags & RXON_FLG_BAND_24G_MSK) {
3123                 if (vif->bss_conf.use_short_slot)
3124                         ctx->staging.flags |= RXON_FLG_SHORT_SLOT_MSK;
3125                 else
3126                         ctx->staging.flags &= ~RXON_FLG_SHORT_SLOT_MSK;
3127         }
3128
3129         iwlcore_commit_rxon(priv, ctx);
3130
3131         switch (vif->type) {
3132         case NL80211_IFTYPE_STATION:
3133                 iwl3945_rate_scale_init(priv->hw, IWL_AP_ID);
3134                 break;
3135         case NL80211_IFTYPE_ADHOC:
3136                 iwl3945_send_beacon_cmd(priv);
3137                 break;
3138         default:
3139                 IWL_ERR(priv, "%s Should not be called in %d mode\n",
3140                         __func__, vif->type);
3141                 break;
3142         }
3143 }
3144
3145 /*****************************************************************************
3146  *
3147  * mac80211 entry point functions
3148  *
3149  *****************************************************************************/
3150
3151 #define UCODE_READY_TIMEOUT     (2 * HZ)
3152
3153 static int iwl3945_mac_start(struct ieee80211_hw *hw)
3154 {
3155         struct iwl_priv *priv = hw->priv;
3156         int ret;
3157
3158         IWL_DEBUG_MAC80211(priv, "enter\n");
3159
3160         /* we should be verifying the device is ready to be opened */
3161         mutex_lock(&priv->mutex);
3162
3163         /* fetch ucode file from disk, alloc and copy to bus-master buffers ...
3164          * ucode filename and max sizes are card-specific. */
3165
3166         if (!priv->ucode_code.len) {
3167                 ret = iwl3945_read_ucode(priv);
3168                 if (ret) {
3169                         IWL_ERR(priv, "Could not read microcode: %d\n", ret);
3170                         mutex_unlock(&priv->mutex);
3171                         goto out_release_irq;
3172                 }
3173         }
3174
3175         ret = __iwl3945_up(priv);
3176
3177         mutex_unlock(&priv->mutex);
3178
3179         if (ret)
3180                 goto out_release_irq;
3181
3182         IWL_DEBUG_INFO(priv, "Start UP work.\n");
3183
3184         /* Wait for START_ALIVE from ucode. Otherwise callbacks from
3185          * mac80211 will not be run successfully. */
3186         ret = wait_event_interruptible_timeout(priv->wait_command_queue,
3187                         test_bit(STATUS_READY, &priv->status),
3188                         UCODE_READY_TIMEOUT);
3189         if (!ret) {
3190                 if (!test_bit(STATUS_READY, &priv->status)) {
3191                         IWL_ERR(priv,
3192                                 "Wait for START_ALIVE timeout after %dms.\n",
3193                                 jiffies_to_msecs(UCODE_READY_TIMEOUT));
3194                         ret = -ETIMEDOUT;
3195                         goto out_release_irq;
3196                 }
3197         }
3198
3199         /* ucode is running and will send rfkill notifications,
3200          * no need to poll the killswitch state anymore */
3201         cancel_delayed_work(&priv->_3945.rfkill_poll);
3202
3203         iwl_led_start(priv);
3204
3205         priv->is_open = 1;
3206         IWL_DEBUG_MAC80211(priv, "leave\n");
3207         return 0;
3208
3209 out_release_irq:
3210         priv->is_open = 0;
3211         IWL_DEBUG_MAC80211(priv, "leave - failed\n");
3212         return ret;
3213 }
3214
3215 static void iwl3945_mac_stop(struct ieee80211_hw *hw)
3216 {
3217         struct iwl_priv *priv = hw->priv;
3218
3219         IWL_DEBUG_MAC80211(priv, "enter\n");
3220
3221         if (!priv->is_open) {
3222                 IWL_DEBUG_MAC80211(priv, "leave - skip\n");
3223                 return;
3224         }
3225
3226         priv->is_open = 0;
3227
3228         if (iwl_is_ready_rf(priv)) {
3229                 /* stop mac, cancel any scan request and clear
3230                  * RXON_FILTER_ASSOC_MSK BIT
3231                  */
3232                 mutex_lock(&priv->mutex);
3233                 iwl_scan_cancel_timeout(priv, 100);
3234                 mutex_unlock(&priv->mutex);
3235         }
3236
3237         iwl3945_down(priv);
3238
3239         flush_workqueue(priv->workqueue);
3240
3241         /* start polling the killswitch state again */
3242         queue_delayed_work(priv->workqueue, &priv->_3945.rfkill_poll,
3243                            round_jiffies_relative(2 * HZ));
3244
3245         IWL_DEBUG_MAC80211(priv, "leave\n");
3246 }
3247
3248 static int iwl3945_mac_tx(struct ieee80211_hw *hw, struct sk_buff *skb)
3249 {
3250         struct iwl_priv *priv = hw->priv;
3251
3252         IWL_DEBUG_MAC80211(priv, "enter\n");
3253
3254         IWL_DEBUG_TX(priv, "dev->xmit(%d bytes) at rate 0x%02x\n", skb->len,
3255                      ieee80211_get_tx_rate(hw, IEEE80211_SKB_CB(skb))->bitrate);
3256
3257         if (iwl3945_tx_skb(priv, skb))
3258                 dev_kfree_skb_any(skb);
3259
3260         IWL_DEBUG_MAC80211(priv, "leave\n");
3261         return NETDEV_TX_OK;
3262 }
3263
3264 void iwl3945_config_ap(struct iwl_priv *priv, struct ieee80211_vif *vif)
3265 {
3266         struct iwl_rxon_context *ctx = &priv->contexts[IWL_RXON_CTX_BSS];
3267         int rc = 0;
3268
3269         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
3270                 return;
3271
3272         /* The following should be done only at AP bring up */
3273         if (!(iwl_is_associated(priv, IWL_RXON_CTX_BSS))) {
3274
3275                 /* RXON - unassoc (to set timing command) */
3276                 ctx->staging.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
3277                 iwlcore_commit_rxon(priv, ctx);
3278
3279                 /* RXON Timing */
3280                 rc = iwl_send_rxon_timing(priv, vif);
3281                 if (rc)
3282                         IWL_WARN(priv, "REPLY_RXON_TIMING failed - "
3283                                         "Attempting to continue.\n");
3284
3285                 ctx->staging.assoc_id = 0;
3286
3287                 if (vif->bss_conf.use_short_preamble)
3288                         ctx->staging.flags |=
3289                                 RXON_FLG_SHORT_PREAMBLE_MSK;
3290                 else
3291                         ctx->staging.flags &=
3292                                 ~RXON_FLG_SHORT_PREAMBLE_MSK;
3293
3294                 if (ctx->staging.flags & RXON_FLG_BAND_24G_MSK) {
3295                         if (vif->bss_conf.use_short_slot)
3296                                 ctx->staging.flags |=
3297                                         RXON_FLG_SHORT_SLOT_MSK;
3298                         else
3299                                 ctx->staging.flags &=
3300                                         ~RXON_FLG_SHORT_SLOT_MSK;
3301                 }
3302                 /* restore RXON assoc */
3303                 ctx->staging.filter_flags |= RXON_FILTER_ASSOC_MSK;
3304                 iwlcore_commit_rxon(priv, ctx);
3305         }
3306         iwl3945_send_beacon_cmd(priv);
3307
3308         /* FIXME - we need to add code here to detect a totally new
3309          * configuration, reset the AP, unassoc, rxon timing, assoc,
3310          * clear sta table, add BCAST sta... */
3311 }
3312
3313 static int iwl3945_mac_set_key(struct ieee80211_hw *hw, enum set_key_cmd cmd,
3314                                struct ieee80211_vif *vif,
3315                                struct ieee80211_sta *sta,
3316                                struct ieee80211_key_conf *key)
3317 {
3318         struct iwl_priv *priv = hw->priv;
3319         int ret = 0;
3320         u8 sta_id = IWL_INVALID_STATION;
3321         u8 static_key;
3322
3323         IWL_DEBUG_MAC80211(priv, "enter\n");
3324
3325         if (iwl3945_mod_params.sw_crypto) {
3326                 IWL_DEBUG_MAC80211(priv, "leave - hwcrypto disabled\n");
3327                 return -EOPNOTSUPP;
3328         }
3329
3330         static_key = !iwl_is_associated(priv, IWL_RXON_CTX_BSS);
3331
3332         if (!static_key) {
3333                 sta_id = iwl_sta_id_or_broadcast(priv, sta);
3334                 if (sta_id == IWL_INVALID_STATION)
3335                         return -EINVAL;
3336         }
3337
3338         mutex_lock(&priv->mutex);
3339         iwl_scan_cancel_timeout(priv, 100);
3340
3341         switch (cmd) {
3342         case SET_KEY:
3343                 if (static_key)
3344                         ret = iwl3945_set_static_key(priv, key);
3345                 else
3346                         ret = iwl3945_set_dynamic_key(priv, key, sta_id);
3347                 IWL_DEBUG_MAC80211(priv, "enable hwcrypto key\n");
3348                 break;
3349         case DISABLE_KEY:
3350                 if (static_key)
3351                         ret = iwl3945_remove_static_key(priv);
3352                 else
3353                         ret = iwl3945_clear_sta_key_info(priv, sta_id);
3354                 IWL_DEBUG_MAC80211(priv, "disable hwcrypto key\n");
3355                 break;
3356         default:
3357                 ret = -EINVAL;
3358         }
3359
3360         mutex_unlock(&priv->mutex);
3361         IWL_DEBUG_MAC80211(priv, "leave\n");
3362
3363         return ret;
3364 }
3365
3366 static int iwl3945_mac_sta_add(struct ieee80211_hw *hw,
3367                                struct ieee80211_vif *vif,
3368                                struct ieee80211_sta *sta)
3369 {
3370         struct iwl_priv *priv = hw->priv;
3371         struct iwl3945_sta_priv *sta_priv = (void *)sta->drv_priv;
3372         int ret;
3373         bool is_ap = vif->type == NL80211_IFTYPE_STATION;
3374         u8 sta_id;
3375
3376         IWL_DEBUG_INFO(priv, "received request to add station %pM\n",
3377                         sta->addr);
3378         mutex_lock(&priv->mutex);
3379         IWL_DEBUG_INFO(priv, "proceeding to add station %pM\n",
3380                         sta->addr);
3381         sta_priv->common.sta_id = IWL_INVALID_STATION;
3382
3383
3384         ret = iwl_add_station_common(priv, sta->addr, is_ap, &sta->ht_cap,
3385                                      &sta_id);
3386         if (ret) {
3387                 IWL_ERR(priv, "Unable to add station %pM (%d)\n",
3388                         sta->addr, ret);
3389                 /* Should we return success if return code is EEXIST ? */
3390                 mutex_unlock(&priv->mutex);
3391                 return ret;
3392         }
3393
3394         sta_priv->common.sta_id = sta_id;
3395
3396         /* Initialize rate scaling */
3397         IWL_DEBUG_INFO(priv, "Initializing rate scaling for station %pM\n",
3398                        sta->addr);
3399         iwl3945_rs_rate_init(priv, sta, sta_id);
3400         mutex_unlock(&priv->mutex);
3401
3402         return 0;
3403 }
3404
3405 static void iwl3945_configure_filter(struct ieee80211_hw *hw,
3406                                      unsigned int changed_flags,
3407                                      unsigned int *total_flags,
3408                                      u64 multicast)
3409 {
3410         struct iwl_priv *priv = hw->priv;
3411         __le32 filter_or = 0, filter_nand = 0;
3412         struct iwl_rxon_context *ctx = &priv->contexts[IWL_RXON_CTX_BSS];
3413
3414 #define CHK(test, flag) do { \
3415         if (*total_flags & (test))              \
3416                 filter_or |= (flag);            \
3417         else                                    \
3418                 filter_nand |= (flag);          \
3419         } while (0)
3420
3421         IWL_DEBUG_MAC80211(priv, "Enter: changed: 0x%x, total: 0x%x\n",
3422                         changed_flags, *total_flags);
3423
3424         CHK(FIF_OTHER_BSS | FIF_PROMISC_IN_BSS, RXON_FILTER_PROMISC_MSK);
3425         CHK(FIF_CONTROL, RXON_FILTER_CTL2HOST_MSK);
3426         CHK(FIF_BCN_PRBRESP_PROMISC, RXON_FILTER_BCON_AWARE_MSK);
3427
3428 #undef CHK
3429
3430         mutex_lock(&priv->mutex);
3431
3432         ctx->staging.filter_flags &= ~filter_nand;
3433         ctx->staging.filter_flags |= filter_or;
3434
3435         /*
3436          * Committing directly here breaks for some reason,
3437          * but we'll eventually commit the filter flags
3438          * change anyway.
3439          */
3440
3441         mutex_unlock(&priv->mutex);
3442
3443         /*
3444          * Receiving all multicast frames is always enabled by the
3445          * default flags setup in iwl_connection_init_rx_config()
3446          * since we currently do not support programming multicast
3447          * filters into the device.
3448          */
3449         *total_flags &= FIF_OTHER_BSS | FIF_ALLMULTI | FIF_PROMISC_IN_BSS |
3450                         FIF_BCN_PRBRESP_PROMISC | FIF_CONTROL;
3451 }
3452
3453
3454 /*****************************************************************************
3455  *
3456  * sysfs attributes
3457  *
3458  *****************************************************************************/
3459
3460 #ifdef CONFIG_IWLWIFI_DEBUG
3461
3462 /*
3463  * The following adds a new attribute to the sysfs representation
3464  * of this device driver (i.e. a new file in /sys/bus/pci/drivers/iwl/)
3465  * used for controlling the debug level.
3466  *
3467  * See the level definitions in iwl for details.
3468  *
3469  * The debug_level being managed using sysfs below is a per device debug
3470  * level that is used instead of the global debug level if it (the per
3471  * device debug level) is set.
3472  */
3473 static ssize_t show_debug_level(struct device *d,
3474                                 struct device_attribute *attr, char *buf)
3475 {
3476         struct iwl_priv *priv = dev_get_drvdata(d);
3477         return sprintf(buf, "0x%08X\n", iwl_get_debug_level(priv));
3478 }
3479 static ssize_t store_debug_level(struct device *d,
3480                                 struct device_attribute *attr,
3481                                  const char *buf, size_t count)
3482 {
3483         struct iwl_priv *priv = dev_get_drvdata(d);
3484         unsigned long val;
3485         int ret;
3486
3487         ret = strict_strtoul(buf, 0, &val);
3488         if (ret)
3489                 IWL_INFO(priv, "%s is not in hex or decimal form.\n", buf);
3490         else {
3491                 priv->debug_level = val;
3492                 if (iwl_alloc_traffic_mem(priv))
3493                         IWL_ERR(priv,
3494                                 "Not enough memory to generate traffic log\n");
3495         }
3496         return strnlen(buf, count);
3497 }
3498
3499 static DEVICE_ATTR(debug_level, S_IWUSR | S_IRUGO,
3500                         show_debug_level, store_debug_level);
3501
3502 #endif /* CONFIG_IWLWIFI_DEBUG */
3503
3504 static ssize_t show_temperature(struct device *d,
3505                                 struct device_attribute *attr, char *buf)
3506 {
3507         struct iwl_priv *priv = dev_get_drvdata(d);
3508
3509         if (!iwl_is_alive(priv))
3510                 return -EAGAIN;
3511
3512         return sprintf(buf, "%d\n", iwl3945_hw_get_temperature(priv));
3513 }
3514
3515 static DEVICE_ATTR(temperature, S_IRUGO, show_temperature, NULL);
3516
3517 static ssize_t show_tx_power(struct device *d,
3518                              struct device_attribute *attr, char *buf)
3519 {
3520         struct iwl_priv *priv = dev_get_drvdata(d);
3521         return sprintf(buf, "%d\n", priv->tx_power_user_lmt);
3522 }
3523
3524 static ssize_t store_tx_power(struct device *d,
3525                               struct device_attribute *attr,
3526                               const char *buf, size_t count)
3527 {
3528         struct iwl_priv *priv = dev_get_drvdata(d);
3529         char *p = (char *)buf;
3530         u32 val;
3531
3532         val = simple_strtoul(p, &p, 10);
3533         if (p == buf)
3534                 IWL_INFO(priv, ": %s is not in decimal form.\n", buf);
3535         else
3536                 iwl3945_hw_reg_set_txpower(priv, val);
3537
3538         return count;
3539 }
3540
3541 static DEVICE_ATTR(tx_power, S_IWUSR | S_IRUGO, show_tx_power, store_tx_power);
3542
3543 static ssize_t show_flags(struct device *d,
3544                           struct device_attribute *attr, char *buf)
3545 {
3546         struct iwl_priv *priv = dev_get_drvdata(d);
3547         struct iwl_rxon_context *ctx = &priv->contexts[IWL_RXON_CTX_BSS];
3548
3549         return sprintf(buf, "0x%04X\n", ctx->active.flags);
3550 }
3551
3552 static ssize_t store_flags(struct device *d,
3553                            struct device_attribute *attr,
3554                            const char *buf, size_t count)
3555 {
3556         struct iwl_priv *priv = dev_get_drvdata(d);
3557         u32 flags = simple_strtoul(buf, NULL, 0);
3558         struct iwl_rxon_context *ctx = &priv->contexts[IWL_RXON_CTX_BSS];
3559
3560         mutex_lock(&priv->mutex);
3561         if (le32_to_cpu(ctx->staging.flags) != flags) {
3562                 /* Cancel any currently running scans... */
3563                 if (iwl_scan_cancel_timeout(priv, 100))
3564                         IWL_WARN(priv, "Could not cancel scan.\n");
3565                 else {
3566                         IWL_DEBUG_INFO(priv, "Committing rxon.flags = 0x%04X\n",
3567                                        flags);
3568                         ctx->staging.flags = cpu_to_le32(flags);
3569                         iwlcore_commit_rxon(priv, ctx);
3570                 }
3571         }
3572         mutex_unlock(&priv->mutex);
3573
3574         return count;
3575 }
3576
3577 static DEVICE_ATTR(flags, S_IWUSR | S_IRUGO, show_flags, store_flags);
3578
3579 static ssize_t show_filter_flags(struct device *d,
3580                                  struct device_attribute *attr, char *buf)
3581 {
3582         struct iwl_priv *priv = dev_get_drvdata(d);
3583         struct iwl_rxon_context *ctx = &priv->contexts[IWL_RXON_CTX_BSS];
3584
3585         return sprintf(buf, "0x%04X\n",
3586                 le32_to_cpu(ctx->active.filter_flags));
3587 }
3588
3589 static ssize_t store_filter_flags(struct device *d,
3590                                   struct device_attribute *attr,
3591                                   const char *buf, size_t count)
3592 {
3593         struct iwl_priv *priv = dev_get_drvdata(d);
3594         struct iwl_rxon_context *ctx = &priv->contexts[IWL_RXON_CTX_BSS];
3595         u32 filter_flags = simple_strtoul(buf, NULL, 0);
3596
3597         mutex_lock(&priv->mutex);
3598         if (le32_to_cpu(ctx->staging.filter_flags) != filter_flags) {
3599                 /* Cancel any currently running scans... */
3600                 if (iwl_scan_cancel_timeout(priv, 100))
3601                         IWL_WARN(priv, "Could not cancel scan.\n");
3602                 else {
3603                         IWL_DEBUG_INFO(priv, "Committing rxon.filter_flags = "
3604                                        "0x%04X\n", filter_flags);
3605                         ctx->staging.filter_flags =
3606                                 cpu_to_le32(filter_flags);
3607                         iwlcore_commit_rxon(priv, ctx);
3608                 }
3609         }
3610         mutex_unlock(&priv->mutex);
3611
3612         return count;
3613 }
3614
3615 static DEVICE_ATTR(filter_flags, S_IWUSR | S_IRUGO, show_filter_flags,
3616                    store_filter_flags);
3617
3618 static ssize_t show_measurement(struct device *d,
3619                                 struct device_attribute *attr, char *buf)
3620 {
3621         struct iwl_priv *priv = dev_get_drvdata(d);
3622         struct iwl_spectrum_notification measure_report;
3623         u32 size = sizeof(measure_report), len = 0, ofs = 0;
3624         u8 *data = (u8 *)&measure_report;
3625         unsigned long flags;
3626
3627         spin_lock_irqsave(&priv->lock, flags);
3628         if (!(priv->measurement_status & MEASUREMENT_READY)) {
3629                 spin_unlock_irqrestore(&priv->lock, flags);
3630                 return 0;
3631         }
3632         memcpy(&measure_report, &priv->measure_report, size);
3633         priv->measurement_status = 0;
3634         spin_unlock_irqrestore(&priv->lock, flags);
3635
3636         while (size && (PAGE_SIZE - len)) {
3637                 hex_dump_to_buffer(data + ofs, size, 16, 1, buf + len,
3638                                    PAGE_SIZE - len, 1);
3639                 len = strlen(buf);
3640                 if (PAGE_SIZE - len)
3641                         buf[len++] = '\n';
3642
3643                 ofs += 16;
3644                 size -= min(size, 16U);
3645         }
3646
3647         return len;
3648 }
3649
3650 static ssize_t store_measurement(struct device *d,
3651                                  struct device_attribute *attr,
3652                                  const char *buf, size_t count)
3653 {
3654         struct iwl_priv *priv = dev_get_drvdata(d);
3655         struct iwl_rxon_context *ctx = &priv->contexts[IWL_RXON_CTX_BSS];
3656         struct ieee80211_measurement_params params = {
3657                 .channel = le16_to_cpu(ctx->active.channel),
3658                 .start_time = cpu_to_le64(priv->_3945.last_tsf),
3659                 .duration = cpu_to_le16(1),
3660         };
3661         u8 type = IWL_MEASURE_BASIC;
3662         u8 buffer[32];
3663         u8 channel;
3664
3665         if (count) {
3666                 char *p = buffer;
3667                 strncpy(buffer, buf, min(sizeof(buffer), count));
3668                 channel = simple_strtoul(p, NULL, 0);
3669                 if (channel)
3670                         params.channel = channel;
3671
3672                 p = buffer;
3673                 while (*p && *p != ' ')
3674                         p++;
3675                 if (*p)
3676                         type = simple_strtoul(p + 1, NULL, 0);
3677         }
3678
3679         IWL_DEBUG_INFO(priv, "Invoking measurement of type %d on "
3680                        "channel %d (for '%s')\n", type, params.channel, buf);
3681         iwl3945_get_measurement(priv, &params, type);
3682
3683         return count;
3684 }
3685
3686 static DEVICE_ATTR(measurement, S_IRUSR | S_IWUSR,
3687                    show_measurement, store_measurement);
3688
3689 static ssize_t store_retry_rate(struct device *d,
3690                                 struct device_attribute *attr,
3691                                 const char *buf, size_t count)
3692 {
3693         struct iwl_priv *priv = dev_get_drvdata(d);
3694
3695         priv->retry_rate = simple_strtoul(buf, NULL, 0);
3696         if (priv->retry_rate <= 0)
3697                 priv->retry_rate = 1;
3698
3699         return count;
3700 }
3701
3702 static ssize_t show_retry_rate(struct device *d,
3703                                struct device_attribute *attr, char *buf)
3704 {
3705         struct iwl_priv *priv = dev_get_drvdata(d);
3706         return sprintf(buf, "%d", priv->retry_rate);
3707 }
3708
3709 static DEVICE_ATTR(retry_rate, S_IWUSR | S_IRUSR, show_retry_rate,
3710                    store_retry_rate);
3711
3712
3713 static ssize_t show_channels(struct device *d,
3714                              struct device_attribute *attr, char *buf)
3715 {
3716         /* all this shit doesn't belong into sysfs anyway */
3717         return 0;
3718 }
3719
3720 static DEVICE_ATTR(channels, S_IRUSR, show_channels, NULL);
3721
3722 static ssize_t show_antenna(struct device *d,
3723                             struct device_attribute *attr, char *buf)
3724 {
3725         struct iwl_priv *priv = dev_get_drvdata(d);
3726
3727         if (!iwl_is_alive(priv))
3728                 return -EAGAIN;
3729
3730         return sprintf(buf, "%d\n", iwl3945_mod_params.antenna);
3731 }
3732
3733 static ssize_t store_antenna(struct device *d,
3734                              struct device_attribute *attr,
3735                              const char *buf, size_t count)
3736 {
3737         struct iwl_priv *priv __maybe_unused = dev_get_drvdata(d);
3738         int ant;
3739
3740         if (count == 0)
3741                 return 0;
3742
3743         if (sscanf(buf, "%1i", &ant) != 1) {
3744                 IWL_DEBUG_INFO(priv, "not in hex or decimal form.\n");
3745                 return count;
3746         }
3747
3748         if ((ant >= 0) && (ant <= 2)) {
3749                 IWL_DEBUG_INFO(priv, "Setting antenna select to %d.\n", ant);
3750                 iwl3945_mod_params.antenna = (enum iwl3945_antenna)ant;
3751         } else
3752                 IWL_DEBUG_INFO(priv, "Bad antenna select value %d.\n", ant);
3753
3754
3755         return count;
3756 }
3757
3758 static DEVICE_ATTR(antenna, S_IWUSR | S_IRUGO, show_antenna, store_antenna);
3759
3760 static ssize_t show_status(struct device *d,
3761                            struct device_attribute *attr, char *buf)
3762 {
3763         struct iwl_priv *priv = dev_get_drvdata(d);
3764         if (!iwl_is_alive(priv))
3765                 return -EAGAIN;
3766         return sprintf(buf, "0x%08x\n", (int)priv->status);
3767 }
3768
3769 static DEVICE_ATTR(status, S_IRUGO, show_status, NULL);
3770
3771 static ssize_t dump_error_log(struct device *d,
3772                               struct device_attribute *attr,
3773                               const char *buf, size_t count)
3774 {
3775         struct iwl_priv *priv = dev_get_drvdata(d);
3776         char *p = (char *)buf;
3777
3778         if (p[0] == '1')
3779                 iwl3945_dump_nic_error_log(priv);
3780
3781         return strnlen(buf, count);
3782 }
3783
3784 static DEVICE_ATTR(dump_errors, S_IWUSR, NULL, dump_error_log);
3785
3786 /*****************************************************************************
3787  *
3788  * driver setup and tear down
3789  *
3790  *****************************************************************************/
3791
3792 static void iwl3945_setup_deferred_work(struct iwl_priv *priv)
3793 {
3794         priv->workqueue = create_singlethread_workqueue(DRV_NAME);
3795
3796         init_waitqueue_head(&priv->wait_command_queue);
3797
3798         INIT_WORK(&priv->restart, iwl3945_bg_restart);
3799         INIT_WORK(&priv->rx_replenish, iwl3945_bg_rx_replenish);
3800         INIT_WORK(&priv->beacon_update, iwl3945_bg_beacon_update);
3801         INIT_DELAYED_WORK(&priv->init_alive_start, iwl3945_bg_init_alive_start);
3802         INIT_DELAYED_WORK(&priv->alive_start, iwl3945_bg_alive_start);
3803         INIT_DELAYED_WORK(&priv->_3945.rfkill_poll, iwl3945_rfkill_poll);
3804
3805         iwl_setup_scan_deferred_work(priv);
3806
3807         iwl3945_hw_setup_deferred_work(priv);
3808
3809         if (priv->cfg->ops->lib->recover_from_tx_stall) {
3810                 init_timer(&priv->monitor_recover);
3811                 priv->monitor_recover.data = (unsigned long)priv;
3812                 priv->monitor_recover.function =
3813                         priv->cfg->ops->lib->recover_from_tx_stall;
3814         }
3815
3816         tasklet_init(&priv->irq_tasklet, (void (*)(unsigned long))
3817                      iwl3945_irq_tasklet, (unsigned long)priv);
3818 }
3819
3820 static void iwl3945_cancel_deferred_work(struct iwl_priv *priv)
3821 {
3822         iwl3945_hw_cancel_deferred_work(priv);
3823
3824         cancel_delayed_work_sync(&priv->init_alive_start);
3825         cancel_delayed_work(&priv->scan_check);
3826         cancel_delayed_work(&priv->alive_start);
3827         cancel_work_sync(&priv->start_internal_scan);
3828         cancel_work_sync(&priv->beacon_update);
3829 }
3830
3831 static struct attribute *iwl3945_sysfs_entries[] = {
3832         &dev_attr_antenna.attr,
3833         &dev_attr_channels.attr,
3834         &dev_attr_dump_errors.attr,
3835         &dev_attr_flags.attr,
3836         &dev_attr_filter_flags.attr,
3837         &dev_attr_measurement.attr,
3838         &dev_attr_retry_rate.attr,
3839         &dev_attr_status.attr,
3840         &dev_attr_temperature.attr,
3841         &dev_attr_tx_power.attr,
3842 #ifdef CONFIG_IWLWIFI_DEBUG
3843         &dev_attr_debug_level.attr,
3844 #endif
3845         NULL
3846 };
3847
3848 static struct attribute_group iwl3945_attribute_group = {
3849         .name = NULL,           /* put in device directory */
3850         .attrs = iwl3945_sysfs_entries,
3851 };
3852
3853 static struct ieee80211_ops iwl3945_hw_ops = {
3854         .tx = iwl3945_mac_tx,
3855         .start = iwl3945_mac_start,
3856         .stop = iwl3945_mac_stop,
3857         .add_interface = iwl_mac_add_interface,
3858         .remove_interface = iwl_mac_remove_interface,
3859         .config = iwl_mac_config,
3860         .configure_filter = iwl3945_configure_filter,
3861         .set_key = iwl3945_mac_set_key,
3862         .conf_tx = iwl_mac_conf_tx,
3863         .reset_tsf = iwl_mac_reset_tsf,
3864         .bss_info_changed = iwl_bss_info_changed,
3865         .hw_scan = iwl_mac_hw_scan,
3866         .sta_add = iwl3945_mac_sta_add,
3867         .sta_remove = iwl_mac_sta_remove,
3868         .tx_last_beacon = iwl_mac_tx_last_beacon,
3869 };
3870
3871 static int iwl3945_init_drv(struct iwl_priv *priv)
3872 {
3873         int ret;
3874         struct iwl3945_eeprom *eeprom = (struct iwl3945_eeprom *)priv->eeprom;
3875
3876         priv->retry_rate = 1;
3877         priv->ibss_beacon = NULL;
3878
3879         spin_lock_init(&priv->sta_lock);
3880         spin_lock_init(&priv->hcmd_lock);
3881
3882         INIT_LIST_HEAD(&priv->free_frames);
3883
3884         mutex_init(&priv->mutex);
3885         mutex_init(&priv->sync_cmd_mutex);
3886
3887         priv->ieee_channels = NULL;
3888         priv->ieee_rates = NULL;
3889         priv->band = IEEE80211_BAND_2GHZ;
3890
3891         priv->iw_mode = NL80211_IFTYPE_STATION;
3892         priv->missed_beacon_threshold = IWL_MISSED_BEACON_THRESHOLD_DEF;
3893
3894         priv->tx_power_user_lmt = IWL_DEFAULT_TX_POWER;
3895
3896         if (eeprom->version < EEPROM_3945_EEPROM_VERSION) {
3897                 IWL_WARN(priv, "Unsupported EEPROM version: 0x%04X\n",
3898                          eeprom->version);
3899                 ret = -EINVAL;
3900                 goto err;
3901         }
3902         ret = iwl_init_channel_map(priv);
3903         if (ret) {
3904                 IWL_ERR(priv, "initializing regulatory failed: %d\n", ret);
3905                 goto err;
3906         }
3907
3908         /* Set up txpower settings in driver for all channels */
3909         if (iwl3945_txpower_set_from_eeprom(priv)) {
3910                 ret = -EIO;
3911                 goto err_free_channel_map;
3912         }
3913
3914         ret = iwlcore_init_geos(priv);
3915         if (ret) {
3916                 IWL_ERR(priv, "initializing geos failed: %d\n", ret);
3917                 goto err_free_channel_map;
3918         }
3919         iwl3945_init_hw_rates(priv, priv->ieee_rates);
3920
3921         return 0;
3922
3923 err_free_channel_map:
3924         iwl_free_channel_map(priv);
3925 err:
3926         return ret;
3927 }
3928
3929 #define IWL3945_MAX_PROBE_REQUEST       200
3930
3931 static int iwl3945_setup_mac(struct iwl_priv *priv)
3932 {
3933         int ret;
3934         struct ieee80211_hw *hw = priv->hw;
3935
3936         hw->rate_control_algorithm = "iwl-3945-rs";
3937         hw->sta_data_size = sizeof(struct iwl3945_sta_priv);
3938         hw->vif_data_size = sizeof(struct iwl_vif_priv);
3939
3940         /* Tell mac80211 our characteristics */
3941         hw->flags = IEEE80211_HW_SIGNAL_DBM |
3942                     IEEE80211_HW_SPECTRUM_MGMT;
3943
3944         if (!priv->cfg->broken_powersave)
3945                 hw->flags |= IEEE80211_HW_SUPPORTS_PS |
3946                              IEEE80211_HW_SUPPORTS_DYNAMIC_PS;
3947
3948         hw->wiphy->interface_modes =
3949                 BIT(NL80211_IFTYPE_STATION) |
3950                 BIT(NL80211_IFTYPE_ADHOC);
3951
3952         hw->wiphy->flags |= WIPHY_FLAG_CUSTOM_REGULATORY |
3953                             WIPHY_FLAG_DISABLE_BEACON_HINTS;
3954
3955         hw->wiphy->max_scan_ssids = PROBE_OPTION_MAX_3945;
3956         /* we create the 802.11 header and a zero-length SSID element */
3957         hw->wiphy->max_scan_ie_len = IWL3945_MAX_PROBE_REQUEST - 24 - 2;
3958
3959         /* Default value; 4 EDCA QOS priorities */
3960         hw->queues = 4;
3961
3962         if (priv->bands[IEEE80211_BAND_2GHZ].n_channels)
3963                 priv->hw->wiphy->bands[IEEE80211_BAND_2GHZ] =
3964                         &priv->bands[IEEE80211_BAND_2GHZ];
3965
3966         if (priv->bands[IEEE80211_BAND_5GHZ].n_channels)
3967                 priv->hw->wiphy->bands[IEEE80211_BAND_5GHZ] =
3968                         &priv->bands[IEEE80211_BAND_5GHZ];
3969
3970         ret = ieee80211_register_hw(priv->hw);
3971         if (ret) {
3972                 IWL_ERR(priv, "Failed to register hw (error %d)\n", ret);
3973                 return ret;
3974         }
3975         priv->mac80211_registered = 1;
3976
3977         return 0;
3978 }
3979
3980 static int iwl3945_pci_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
3981 {
3982         int err = 0, i;
3983         struct iwl_priv *priv;
3984         struct ieee80211_hw *hw;
3985         struct iwl_cfg *cfg = (struct iwl_cfg *)(ent->driver_data);
3986         struct iwl3945_eeprom *eeprom;
3987         unsigned long flags;
3988
3989         /***********************
3990          * 1. Allocating HW data
3991          * ********************/
3992
3993         /* mac80211 allocates memory for this device instance, including
3994          *   space for this driver's private structure */
3995         hw = iwl_alloc_all(cfg, &iwl3945_hw_ops);
3996         if (hw == NULL) {
3997                 pr_err("Can not allocate network device\n");
3998                 err = -ENOMEM;
3999                 goto out;
4000         }
4001         priv = hw->priv;
4002         SET_IEEE80211_DEV(hw, &pdev->dev);
4003
4004         priv->cmd_queue = IWL39_CMD_QUEUE_NUM;
4005
4006         /* 3945 has only one valid context */
4007         priv->valid_contexts = BIT(IWL_RXON_CTX_BSS);
4008
4009         for (i = 0; i < NUM_IWL_RXON_CTX; i++)
4010                 priv->contexts[i].ctxid = i;
4011
4012         /*
4013          * Disabling hardware scan means that mac80211 will perform scans
4014          * "the hard way", rather than using device's scan.
4015          */
4016         if (iwl3945_mod_params.disable_hw_scan) {
4017                 IWL_DEBUG_INFO(priv, "Disabling hw_scan\n");
4018                 iwl3945_hw_ops.hw_scan = NULL;
4019         }
4020
4021
4022         IWL_DEBUG_INFO(priv, "*** LOAD DRIVER ***\n");
4023         priv->cfg = cfg;
4024         priv->pci_dev = pdev;
4025         priv->inta_mask = CSR_INI_SET_MASK;
4026
4027         if (iwl_alloc_traffic_mem(priv))
4028                 IWL_ERR(priv, "Not enough memory to generate traffic log\n");
4029
4030         /***************************
4031          * 2. Initializing PCI bus
4032          * *************************/
4033         pci_disable_link_state(pdev, PCIE_LINK_STATE_L0S | PCIE_LINK_STATE_L1 |
4034                                 PCIE_LINK_STATE_CLKPM);
4035
4036         if (pci_enable_device(pdev)) {
4037                 err = -ENODEV;
4038                 goto out_ieee80211_free_hw;
4039         }
4040
4041         pci_set_master(pdev);
4042
4043         err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
4044         if (!err)
4045                 err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
4046         if (err) {
4047                 IWL_WARN(priv, "No suitable DMA available.\n");
4048                 goto out_pci_disable_device;
4049         }
4050
4051         pci_set_drvdata(pdev, priv);
4052         err = pci_request_regions(pdev, DRV_NAME);
4053         if (err)
4054                 goto out_pci_disable_device;
4055
4056         /***********************
4057          * 3. Read REV Register
4058          * ********************/
4059         priv->hw_base = pci_iomap(pdev, 0, 0);
4060         if (!priv->hw_base) {
4061                 err = -ENODEV;
4062                 goto out_pci_release_regions;
4063         }
4064
4065         IWL_DEBUG_INFO(priv, "pci_resource_len = 0x%08llx\n",
4066                         (unsigned long long) pci_resource_len(pdev, 0));
4067         IWL_DEBUG_INFO(priv, "pci_resource_base = %p\n", priv->hw_base);
4068
4069         /* We disable the RETRY_TIMEOUT register (0x41) to keep
4070          * PCI Tx retries from interfering with C3 CPU state */
4071         pci_write_config_byte(pdev, 0x41, 0x00);
4072
4073         /* these spin locks will be used in apm_ops.init and EEPROM access
4074          * we should init now
4075          */
4076         spin_lock_init(&priv->reg_lock);
4077         spin_lock_init(&priv->lock);
4078
4079         /*
4080          * stop and reset the on-board processor just in case it is in a
4081          * strange state ... like being left stranded by a primary kernel
4082          * and this is now the kdump kernel trying to start up
4083          */
4084         iwl_write32(priv, CSR_RESET, CSR_RESET_REG_FLAG_NEVO_RESET);
4085
4086         /***********************
4087          * 4. Read EEPROM
4088          * ********************/
4089
4090         /* Read the EEPROM */
4091         err = iwl_eeprom_init(priv);
4092         if (err) {
4093                 IWL_ERR(priv, "Unable to init EEPROM\n");
4094                 goto out_iounmap;
4095         }
4096         /* MAC Address location in EEPROM same for 3945/4965 */
4097         eeprom = (struct iwl3945_eeprom *)priv->eeprom;
4098         IWL_DEBUG_INFO(priv, "MAC address: %pM\n", eeprom->mac_address);
4099         SET_IEEE80211_PERM_ADDR(priv->hw, eeprom->mac_address);
4100
4101         /***********************
4102          * 5. Setup HW Constants
4103          * ********************/
4104         /* Device-specific setup */
4105         if (iwl3945_hw_set_hw_params(priv)) {
4106                 IWL_ERR(priv, "failed to set hw settings\n");
4107                 goto out_eeprom_free;
4108         }
4109
4110         /***********************
4111          * 6. Setup priv
4112          * ********************/
4113
4114         err = iwl3945_init_drv(priv);
4115         if (err) {
4116                 IWL_ERR(priv, "initializing driver failed\n");
4117                 goto out_unset_hw_params;
4118         }
4119
4120         IWL_INFO(priv, "Detected Intel Wireless WiFi Link %s\n",
4121                 priv->cfg->name);
4122
4123         /***********************
4124          * 7. Setup Services
4125          * ********************/
4126
4127         spin_lock_irqsave(&priv->lock, flags);
4128         iwl_disable_interrupts(priv);
4129         spin_unlock_irqrestore(&priv->lock, flags);
4130
4131         pci_enable_msi(priv->pci_dev);
4132
4133         err = request_irq(priv->pci_dev->irq, priv->cfg->ops->lib->isr,
4134                           IRQF_SHARED, DRV_NAME, priv);
4135         if (err) {
4136                 IWL_ERR(priv, "Error allocating IRQ %d\n", priv->pci_dev->irq);
4137                 goto out_disable_msi;
4138         }
4139
4140         err = sysfs_create_group(&pdev->dev.kobj, &iwl3945_attribute_group);
4141         if (err) {
4142                 IWL_ERR(priv, "failed to create sysfs device attributes\n");
4143                 goto out_release_irq;
4144         }
4145
4146         iwl_set_rxon_channel(priv,
4147                              &priv->bands[IEEE80211_BAND_2GHZ].channels[5],
4148                              &priv->contexts[IWL_RXON_CTX_BSS]);
4149         iwl3945_setup_deferred_work(priv);
4150         iwl3945_setup_rx_handlers(priv);
4151         iwl_power_initialize(priv);
4152
4153         /*********************************
4154          * 8. Setup and Register mac80211
4155          * *******************************/
4156
4157         iwl_enable_interrupts(priv);
4158
4159         err = iwl3945_setup_mac(priv);
4160         if (err)
4161                 goto  out_remove_sysfs;
4162
4163         err = iwl_dbgfs_register(priv, DRV_NAME);
4164         if (err)
4165                 IWL_ERR(priv, "failed to create debugfs files. Ignoring error: %d\n", err);
4166
4167         /* Start monitoring the killswitch */
4168         queue_delayed_work(priv->workqueue, &priv->_3945.rfkill_poll,
4169                            2 * HZ);
4170
4171         return 0;
4172
4173  out_remove_sysfs:
4174         destroy_workqueue(priv->workqueue);
4175         priv->workqueue = NULL;
4176         sysfs_remove_group(&pdev->dev.kobj, &iwl3945_attribute_group);
4177  out_release_irq:
4178         free_irq(priv->pci_dev->irq, priv);
4179  out_disable_msi:
4180         pci_disable_msi(priv->pci_dev);
4181         iwlcore_free_geos(priv);
4182         iwl_free_channel_map(priv);
4183  out_unset_hw_params:
4184         iwl3945_unset_hw_params(priv);
4185  out_eeprom_free:
4186         iwl_eeprom_free(priv);
4187  out_iounmap:
4188         pci_iounmap(pdev, priv->hw_base);
4189  out_pci_release_regions:
4190         pci_release_regions(pdev);
4191  out_pci_disable_device:
4192         pci_set_drvdata(pdev, NULL);
4193         pci_disable_device(pdev);
4194  out_ieee80211_free_hw:
4195         iwl_free_traffic_mem(priv);
4196         ieee80211_free_hw(priv->hw);
4197  out:
4198         return err;
4199 }
4200
4201 static void __devexit iwl3945_pci_remove(struct pci_dev *pdev)
4202 {
4203         struct iwl_priv *priv = pci_get_drvdata(pdev);
4204         unsigned long flags;
4205
4206         if (!priv)
4207                 return;
4208
4209         IWL_DEBUG_INFO(priv, "*** UNLOAD DRIVER ***\n");
4210
4211         iwl_dbgfs_unregister(priv);
4212
4213         set_bit(STATUS_EXIT_PENDING, &priv->status);
4214
4215         if (priv->mac80211_registered) {
4216                 ieee80211_unregister_hw(priv->hw);
4217                 priv->mac80211_registered = 0;
4218         } else {
4219                 iwl3945_down(priv);
4220         }
4221
4222         /*
4223          * Make sure device is reset to low power before unloading driver.
4224          * This may be redundant with iwl_down(), but there are paths to
4225          * run iwl_down() without calling apm_ops.stop(), and there are
4226          * paths to avoid running iwl_down() at all before leaving driver.
4227          * This (inexpensive) call *makes sure* device is reset.
4228          */
4229         priv->cfg->ops->lib->apm_ops.stop(priv);
4230
4231         /* make sure we flush any pending irq or
4232          * tasklet for the driver
4233          */
4234         spin_lock_irqsave(&priv->lock, flags);
4235         iwl_disable_interrupts(priv);
4236         spin_unlock_irqrestore(&priv->lock, flags);
4237
4238         iwl_synchronize_irq(priv);
4239
4240         sysfs_remove_group(&pdev->dev.kobj, &iwl3945_attribute_group);
4241
4242         cancel_delayed_work_sync(&priv->_3945.rfkill_poll);
4243
4244         iwl3945_dealloc_ucode_pci(priv);
4245
4246         if (priv->rxq.bd)
4247                 iwl3945_rx_queue_free(priv, &priv->rxq);
4248         iwl3945_hw_txq_ctx_free(priv);
4249
4250         iwl3945_unset_hw_params(priv);
4251
4252         /*netif_stop_queue(dev); */
4253         flush_workqueue(priv->workqueue);
4254
4255         /* ieee80211_unregister_hw calls iwl3945_mac_stop, which flushes
4256          * priv->workqueue... so we can't take down the workqueue
4257          * until now... */
4258         destroy_workqueue(priv->workqueue);
4259         priv->workqueue = NULL;
4260         iwl_free_traffic_mem(priv);
4261
4262         free_irq(pdev->irq, priv);
4263         pci_disable_msi(pdev);
4264
4265         pci_iounmap(pdev, priv->hw_base);
4266         pci_release_regions(pdev);
4267         pci_disable_device(pdev);
4268         pci_set_drvdata(pdev, NULL);
4269
4270         iwl_free_channel_map(priv);
4271         iwlcore_free_geos(priv);
4272         kfree(priv->scan_cmd);
4273         if (priv->ibss_beacon)
4274                 dev_kfree_skb(priv->ibss_beacon);
4275
4276         ieee80211_free_hw(priv->hw);
4277 }
4278
4279
4280 /*****************************************************************************
4281  *
4282  * driver and module entry point
4283  *
4284  *****************************************************************************/
4285
4286 static struct pci_driver iwl3945_driver = {
4287         .name = DRV_NAME,
4288         .id_table = iwl3945_hw_card_ids,
4289         .probe = iwl3945_pci_probe,
4290         .remove = __devexit_p(iwl3945_pci_remove),
4291 #ifdef CONFIG_PM
4292         .suspend = iwl_pci_suspend,
4293         .resume = iwl_pci_resume,
4294 #endif
4295 };
4296
4297 static int __init iwl3945_init(void)
4298 {
4299
4300         int ret;
4301         pr_info(DRV_DESCRIPTION ", " DRV_VERSION "\n");
4302         pr_info(DRV_COPYRIGHT "\n");
4303
4304         ret = iwl3945_rate_control_register();
4305         if (ret) {
4306                 pr_err("Unable to register rate control algorithm: %d\n", ret);
4307                 return ret;
4308         }
4309
4310         ret = pci_register_driver(&iwl3945_driver);
4311         if (ret) {
4312                 pr_err("Unable to initialize PCI module\n");
4313                 goto error_register;
4314         }
4315
4316         return ret;
4317
4318 error_register:
4319         iwl3945_rate_control_unregister();
4320         return ret;
4321 }
4322
4323 static void __exit iwl3945_exit(void)
4324 {
4325         pci_unregister_driver(&iwl3945_driver);
4326         iwl3945_rate_control_unregister();
4327 }
4328
4329 MODULE_FIRMWARE(IWL3945_MODULE_FIRMWARE(IWL3945_UCODE_API_MAX));
4330
4331 module_param_named(antenna, iwl3945_mod_params.antenna, int, S_IRUGO);
4332 MODULE_PARM_DESC(antenna, "select antenna (1=Main, 2=Aux, default 0 [both])");
4333 module_param_named(swcrypto, iwl3945_mod_params.sw_crypto, int, S_IRUGO);
4334 MODULE_PARM_DESC(swcrypto,
4335                  "using software crypto (default 1 [software])\n");
4336 #ifdef CONFIG_IWLWIFI_DEBUG
4337 module_param_named(debug, iwl_debug_level, uint, S_IRUGO | S_IWUSR);
4338 MODULE_PARM_DESC(debug, "debug output mask");
4339 #endif
4340 module_param_named(disable_hw_scan, iwl3945_mod_params.disable_hw_scan,
4341                    int, S_IRUGO);
4342 MODULE_PARM_DESC(disable_hw_scan, "disable hardware scanning (default 0)");
4343 module_param_named(fw_restart3945, iwl3945_mod_params.restart_fw, int, S_IRUGO);
4344 MODULE_PARM_DESC(fw_restart3945, "restart firmware in case of error");
4345
4346 module_exit(iwl3945_exit);
4347 module_init(iwl3945_init);