Linux kernel & device driver programming

Cross-Referenced Linux and Device Driver Code

[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ]
Version: [ 2.6.11.8 ] [ 2.6.25 ] [ 2.6.25.8 ] [ 2.6.31.13 ] Architecture: [ i386 ]
  1 /******************************************************************************
  2  *
  3  * Copyright(c) 2003 - 2009 Intel Corporation. All rights reserved.
  4  *
  5  * Portions of this file are derived from the ipw3945 project, as well
  6  * as portions of the ieee80211 subsystem header files.
  7  *
  8  * This program is free software; you can redistribute it and/or modify it
  9  * under the terms of version 2 of the GNU General Public License as
 10  * published by the Free Software Foundation.
 11  *
 12  * This program is distributed in the hope that it will be useful, but WITHOUT
 13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 15  * more details.
 16  *
 17  * You should have received a copy of the GNU General Public License along with
 18  * this program; if not, write to the Free Software Foundation, Inc.,
 19  * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
 20  *
 21  * The full GNU General Public License is included in this distribution in the
 22  * file called LICENSE.
 23  *
 24  * Contact Information:
 25  *  Intel Linux Wireless <ilw@linux.intel.com>
 26  * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
 27  *
 28  *****************************************************************************/
 29 
 30 #include <linux/kernel.h>
 31 #include <linux/module.h>
 32 #include <linux/init.h>
 33 #include <linux/pci.h>
 34 #include <linux/dma-mapping.h>
 35 #include <linux/delay.h>
 36 #include <linux/skbuff.h>
 37 #include <linux/netdevice.h>
 38 #include <linux/wireless.h>
 39 #include <linux/firmware.h>
 40 #include <linux/etherdevice.h>
 41 #include <linux/if_arp.h>
 42 
 43 #include <net/ieee80211_radiotap.h>
 44 #include <net/lib80211.h>
 45 #include <net/mac80211.h>
 46 
 47 #include <asm/div64.h>
 48 
 49 #define DRV_NAME        "iwl3945"
 50 
 51 #include "iwl-fh.h"
 52 #include "iwl-3945-fh.h"
 53 #include "iwl-commands.h"
 54 #include "iwl-sta.h"
 55 #include "iwl-3945.h"
 56 #include "iwl-helpers.h"
 57 #include "iwl-core.h"
 58 #include "iwl-dev.h"
 59 
 60 /*
 61  * module name, copyright, version, etc.
 62  */
 63 
 64 #define DRV_DESCRIPTION \
 65 "Intel(R) PRO/Wireless 3945ABG/BG Network Connection driver for Linux"
 66 
 67 #ifdef CONFIG_IWLWIFI_DEBUG
 68 #define VD "d"
 69 #else
 70 #define VD
 71 #endif
 72 
 73 #ifdef CONFIG_IWL3945_SPECTRUM_MEASUREMENT
 74 #define VS "s"
 75 #else
 76 #define VS
 77 #endif
 78 
 79 #define IWL39_VERSION "1.2.26k" VD VS
 80 #define DRV_COPYRIGHT   "Copyright(c) 2003-2009 Intel Corporation"
 81 #define DRV_AUTHOR     "<ilw@linux.intel.com>"
 82 #define DRV_VERSION     IWL39_VERSION
 83 
 84 
 85 MODULE_DESCRIPTION(DRV_DESCRIPTION);
 86 MODULE_VERSION(DRV_VERSION);
 87 MODULE_AUTHOR(DRV_COPYRIGHT " " DRV_AUTHOR);
 88 MODULE_LICENSE("GPL");
 89 
 90  /* module parameters */
 91 struct iwl_mod_params iwl3945_mod_params = {
 92         .num_of_queues = IWL39_MAX_NUM_QUEUES,
 93         .sw_crypto = 1,
 94         .restart_fw = 1,
 95         /* the rest are 0 by default */
 96 };
 97 
 98 /**
 99  * iwl3945_get_antenna_flags - Get antenna flags for RXON command
100  * @priv: eeprom and antenna fields are used to determine antenna flags
101  *
102  * priv->eeprom39  is used to determine if antenna AUX/MAIN are reversed
103  * iwl3945_mod_params.antenna specifies the antenna diversity mode:
104  *
105  * IWL_ANTENNA_DIVERSITY - NIC selects best antenna by itself
106  * IWL_ANTENNA_MAIN      - Force MAIN antenna
107  * IWL_ANTENNA_AUX       - Force AUX antenna
108  */
109 __le32 iwl3945_get_antenna_flags(const struct iwl_priv *priv)
110 {
111         struct iwl3945_eeprom *eeprom = (struct iwl3945_eeprom *)priv->eeprom;
112 
113         switch (iwl3945_mod_params.antenna) {
114         case IWL_ANTENNA_DIVERSITY:
115                 return 0;
116 
117         case IWL_ANTENNA_MAIN:
118                 if (eeprom->antenna_switch_type)
119                         return RXON_FLG_DIS_DIV_MSK | RXON_FLG_ANT_B_MSK;
120                 return RXON_FLG_DIS_DIV_MSK | RXON_FLG_ANT_A_MSK;
121 
122         case IWL_ANTENNA_AUX:
123                 if (eeprom->antenna_switch_type)
124                         return RXON_FLG_DIS_DIV_MSK | RXON_FLG_ANT_A_MSK;
125                 return RXON_FLG_DIS_DIV_MSK | RXON_FLG_ANT_B_MSK;
126         }
127 
128         /* bad antenna selector value */
129         IWL_ERR(priv, "Bad antenna selector value (0x%x)\n",
130                 iwl3945_mod_params.antenna);
131 
132         return 0;               /* "diversity" is default if error */
133 }
134 
135 static int iwl3945_set_ccmp_dynamic_key_info(struct iwl_priv *priv,
136                                    struct ieee80211_key_conf *keyconf,
137                                    u8 sta_id)
138 {
139         unsigned long flags;
140         __le16 key_flags = 0;
141         int ret;
142 
143         key_flags |= (STA_KEY_FLG_CCMP | STA_KEY_FLG_MAP_KEY_MSK);
144         key_flags |= cpu_to_le16(keyconf->keyidx << STA_KEY_FLG_KEYID_POS);
145 
146         if (sta_id == priv->hw_params.bcast_sta_id)
147                 key_flags |= STA_KEY_MULTICAST_MSK;
148 
149         keyconf->flags |= IEEE80211_KEY_FLAG_GENERATE_IV;
150         keyconf->hw_key_idx = keyconf->keyidx;
151         key_flags &= ~STA_KEY_FLG_INVALID;
152 
153         spin_lock_irqsave(&priv->sta_lock, flags);
154         priv->stations[sta_id].keyinfo.alg = keyconf->alg;
155         priv->stations[sta_id].keyinfo.keylen = keyconf->keylen;
156         memcpy(priv->stations[sta_id].keyinfo.key, keyconf->key,
157                keyconf->keylen);
158 
159         memcpy(priv->stations[sta_id].sta.key.key, keyconf->key,
160                keyconf->keylen);
161 
162         if ((priv->stations[sta_id].sta.key.key_flags & STA_KEY_FLG_ENCRYPT_MSK)
163                         == STA_KEY_FLG_NO_ENC)
164                 priv->stations[sta_id].sta.key.key_offset =
165                                  iwl_get_free_ucode_key_index(priv);
166         /* else, we are overriding an existing key => no need to allocated room
167         * in uCode. */
168 
169         WARN(priv->stations[sta_id].sta.key.key_offset == WEP_INVALID_OFFSET,
170                 "no space for a new key");
171 
172         priv->stations[sta_id].sta.key.key_flags = key_flags;
173         priv->stations[sta_id].sta.sta.modify_mask = STA_MODIFY_KEY_MASK;
174         priv->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
175 
176         IWL_DEBUG_INFO(priv, "hwcrypto: modify ucode station key info\n");
177 
178         ret = iwl_send_add_sta(priv, &priv->stations[sta_id].sta, CMD_ASYNC);
179 
180         spin_unlock_irqrestore(&priv->sta_lock, flags);
181 
182         return ret;
183 }
184 
185 static int iwl3945_set_tkip_dynamic_key_info(struct iwl_priv *priv,
186                                   struct ieee80211_key_conf *keyconf,
187                                   u8 sta_id)
188 {
189         return -EOPNOTSUPP;
190 }
191 
192 static int iwl3945_set_wep_dynamic_key_info(struct iwl_priv *priv,
193                                   struct ieee80211_key_conf *keyconf,
194                                   u8 sta_id)
195 {
196         return -EOPNOTSUPP;
197 }
198 
199 static int iwl3945_clear_sta_key_info(struct iwl_priv *priv, u8 sta_id)
200 {
201         unsigned long flags;
202 
203         spin_lock_irqsave(&priv->sta_lock, flags);
204         memset(&priv->stations[sta_id].keyinfo, 0, sizeof(struct iwl_hw_key));
205         memset(&priv->stations[sta_id].sta.key, 0,
206                 sizeof(struct iwl4965_keyinfo));
207         priv->stations[sta_id].sta.key.key_flags = STA_KEY_FLG_NO_ENC;
208         priv->stations[sta_id].sta.sta.modify_mask = STA_MODIFY_KEY_MASK;
209         priv->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
210         spin_unlock_irqrestore(&priv->sta_lock, flags);
211 
212         IWL_DEBUG_INFO(priv, "hwcrypto: clear ucode station key info\n");
213         iwl_send_add_sta(priv, &priv->stations[sta_id].sta, 0);
214         return 0;
215 }
216 
217 static int iwl3945_set_dynamic_key(struct iwl_priv *priv,
218                         struct ieee80211_key_conf *keyconf, u8 sta_id)
219 {
220         int ret = 0;
221 
222         keyconf->hw_key_idx = HW_KEY_DYNAMIC;
223 
224         switch (keyconf->alg) {
225         case ALG_CCMP:
226                 ret = iwl3945_set_ccmp_dynamic_key_info(priv, keyconf, sta_id);
227                 break;
228         case ALG_TKIP:
229                 ret = iwl3945_set_tkip_dynamic_key_info(priv, keyconf, sta_id);
230                 break;
231         case ALG_WEP:
232                 ret = iwl3945_set_wep_dynamic_key_info(priv, keyconf, sta_id);
233                 break;
234         default:
235                 IWL_ERR(priv, "Unknown alg: %s alg = %d\n", __func__, keyconf->alg);
236                 ret = -EINVAL;
237         }
238 
239         IWL_DEBUG_WEP(priv, "Set dynamic key: alg= %d len=%d idx=%d sta=%d ret=%d\n",
240                       keyconf->alg, keyconf->keylen, keyconf->keyidx,
241                       sta_id, ret);
242 
243         return ret;
244 }
245 
246 static int iwl3945_remove_static_key(struct iwl_priv *priv)
247 {
248         int ret = -EOPNOTSUPP;
249 
250         return ret;
251 }
252 
253 static int iwl3945_set_static_key(struct iwl_priv *priv,
254                                 struct ieee80211_key_conf *key)
255 {
256         if (key->alg == ALG_WEP)
257                 return -EOPNOTSUPP;
258 
259         IWL_ERR(priv, "Static key invalid: alg %d\n", key->alg);
260         return -EINVAL;
261 }
262 
263 static void iwl3945_clear_free_frames(struct iwl_priv *priv)
264 {
265         struct list_head *element;
266 
267         IWL_DEBUG_INFO(priv, "%d frames on pre-allocated heap on clear.\n",
268                        priv->frames_count);
269 
270         while (!list_empty(&priv->free_frames)) {
271                 element = priv->free_frames.next;
272                 list_del(element);
273                 kfree(list_entry(element, struct iwl3945_frame, list));
274                 priv->frames_count--;
275         }
276 
277         if (priv->frames_count) {
278                 IWL_WARN(priv, "%d frames still in use.  Did we lose one?\n",
279                             priv->frames_count);
280                 priv->frames_count = 0;
281         }
282 }
283 
284 static struct iwl3945_frame *iwl3945_get_free_frame(struct iwl_priv *priv)
285 {
286         struct iwl3945_frame *frame;
287         struct list_head *element;
288         if (list_empty(&priv->free_frames)) {
289                 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
290                 if (!frame) {
291                         IWL_ERR(priv, "Could not allocate frame!\n");
292                         return NULL;
293                 }
294 
295                 priv->frames_count++;
296                 return frame;
297         }
298 
299         element = priv->free_frames.next;
300         list_del(element);
301         return list_entry(element, struct iwl3945_frame, list);
302 }
303 
304 static void iwl3945_free_frame(struct iwl_priv *priv, struct iwl3945_frame *frame)
305 {
306         memset(frame, 0, sizeof(*frame));
307         list_add(&frame->list, &priv->free_frames);
308 }
309 
310 unsigned int iwl3945_fill_beacon_frame(struct iwl_priv *priv,
311                                 struct ieee80211_hdr *hdr,
312                                 int left)
313 {
314 
315         if (!iwl_is_associated(priv) || !priv->ibss_beacon ||
316             ((priv->iw_mode != NL80211_IFTYPE_ADHOC) &&
317              (priv->iw_mode != NL80211_IFTYPE_AP)))
318                 return 0;
319 
320         if (priv->ibss_beacon->len > left)
321                 return 0;
322 
323         memcpy(hdr, priv->ibss_beacon->data, priv->ibss_beacon->len);
324 
325         return priv->ibss_beacon->len;
326 }
327 
328 static int iwl3945_send_beacon_cmd(struct iwl_priv *priv)
329 {
330         struct iwl3945_frame *frame;
331         unsigned int frame_size;
332         int rc;
333         u8 rate;
334 
335         frame = iwl3945_get_free_frame(priv);
336 
337         if (!frame) {
338                 IWL_ERR(priv, "Could not obtain free frame buffer for beacon "
339                           "command.\n");
340                 return -ENOMEM;
341         }
342 
343         rate = iwl_rate_get_lowest_plcp(priv);
344 
345         frame_size = iwl3945_hw_get_beacon_cmd(priv, frame, rate);
346 
347         rc = iwl_send_cmd_pdu(priv, REPLY_TX_BEACON, frame_size,
348                               &frame->u.cmd[0]);
349 
350         iwl3945_free_frame(priv, frame);
351 
352         return rc;
353 }
354 
355 static void iwl3945_unset_hw_params(struct iwl_priv *priv)
356 {
357         if (priv->shared_virt)
358                 pci_free_consistent(priv->pci_dev,
359                                     sizeof(struct iwl3945_shared),
360                                     priv->shared_virt,
361                                     priv->shared_phys);
362 }
363 
364 #define MAX_UCODE_BEACON_INTERVAL       1024
365 #define INTEL_CONN_LISTEN_INTERVAL      cpu_to_le16(0xA)
366 
367 static __le16 iwl3945_adjust_beacon_interval(u16 beacon_val)
368 {
369         u16 new_val = 0;
370         u16 beacon_factor = 0;
371 
372         beacon_factor =
373             (beacon_val + MAX_UCODE_BEACON_INTERVAL)
374                 / MAX_UCODE_BEACON_INTERVAL;
375         new_val = beacon_val / beacon_factor;
376 
377         return cpu_to_le16(new_val);
378 }
379 
380 static void iwl3945_setup_rxon_timing(struct iwl_priv *priv)
381 {
382         u64 interval_tm_unit;
383         u64 tsf, result;
384         unsigned long flags;
385         struct ieee80211_conf *conf = NULL;
386         u16 beacon_int = 0;
387 
388         conf = ieee80211_get_hw_conf(priv->hw);
389 
390         spin_lock_irqsave(&priv->lock, flags);
391         priv->rxon_timing.timestamp = cpu_to_le64(priv->timestamp);
392         priv->rxon_timing.listen_interval = INTEL_CONN_LISTEN_INTERVAL;
393 
394         tsf = priv->timestamp;
395 
396         beacon_int = priv->beacon_int;
397         spin_unlock_irqrestore(&priv->lock, flags);
398 
399         if (priv->iw_mode == NL80211_IFTYPE_STATION) {
400                 if (beacon_int == 0) {
401                         priv->rxon_timing.beacon_interval = cpu_to_le16(100);
402                         priv->rxon_timing.beacon_init_val = cpu_to_le32(102400);
403                 } else {
404                         priv->rxon_timing.beacon_interval =
405                                 cpu_to_le16(beacon_int);
406                         priv->rxon_timing.beacon_interval =
407                             iwl3945_adjust_beacon_interval(
408                                 le16_to_cpu(priv->rxon_timing.beacon_interval));
409                 }
410 
411                 priv->rxon_timing.atim_window = 0;
412         } else {
413                 priv->rxon_timing.beacon_interval =
414                         iwl3945_adjust_beacon_interval(
415                                 priv->vif->bss_conf.beacon_int);
416                 /* TODO: we need to get atim_window from upper stack
417                  * for now we set to 0 */
418                 priv->rxon_timing.atim_window = 0;
419         }
420 
421         interval_tm_unit =
422                 (le16_to_cpu(priv->rxon_timing.beacon_interval) * 1024);
423         result = do_div(tsf, interval_tm_unit);
424         priv->rxon_timing.beacon_init_val =
425             cpu_to_le32((u32) ((u64) interval_tm_unit - result));
426 
427         IWL_DEBUG_ASSOC(priv,
428                 "beacon interval %d beacon timer %d beacon tim %d\n",
429                 le16_to_cpu(priv->rxon_timing.beacon_interval),
430                 le32_to_cpu(priv->rxon_timing.beacon_init_val),
431                 le16_to_cpu(priv->rxon_timing.atim_window));
432 }
433 
434 static void iwl3945_build_tx_cmd_hwcrypto(struct iwl_priv *priv,
435                                       struct ieee80211_tx_info *info,
436                                       struct iwl_cmd *cmd,
437                                       struct sk_buff *skb_frag,
438                                       int sta_id)
439 {
440         struct iwl3945_tx_cmd *tx = (struct iwl3945_tx_cmd *)cmd->cmd.payload;
441         struct iwl_hw_key *keyinfo = &priv->stations[sta_id].keyinfo;
442 
443         switch (keyinfo->alg) {
444         case ALG_CCMP:
445                 tx->sec_ctl = TX_CMD_SEC_CCM;
446                 memcpy(tx->key, keyinfo->key, keyinfo->keylen);
447                 IWL_DEBUG_TX(priv, "tx_cmd with AES hwcrypto\n");
448                 break;
449 
450         case ALG_TKIP:
451                 break;
452 
453         case ALG_WEP:
454                 tx->sec_ctl = TX_CMD_SEC_WEP |
455                     (info->control.hw_key->hw_key_idx & TX_CMD_SEC_MSK) << TX_CMD_SEC_SHIFT;
456 
457                 if (keyinfo->keylen == 13)
458                         tx->sec_ctl |= TX_CMD_SEC_KEY128;
459 
460                 memcpy(&tx->key[3], keyinfo->key, keyinfo->keylen);
461 
462                 IWL_DEBUG_TX(priv, "Configuring packet for WEP encryption "
463                              "with key %d\n", info->control.hw_key->hw_key_idx);
464                 break;
465 
466         default:
467                 IWL_ERR(priv, "Unknown encode alg %d\n", keyinfo->alg);
468                 break;
469         }
470 }
471 
472 /*
473  * handle build REPLY_TX command notification.
474  */
475 static void iwl3945_build_tx_cmd_basic(struct iwl_priv *priv,
476                                   struct iwl_cmd *cmd,
477                                   struct ieee80211_tx_info *info,
478                                   struct ieee80211_hdr *hdr, u8 std_id)
479 {
480         struct iwl3945_tx_cmd *tx = (struct iwl3945_tx_cmd *)cmd->cmd.payload;
481         __le32 tx_flags = tx->tx_flags;
482         __le16 fc = hdr->frame_control;
483         u8 rc_flags = info->control.rates[0].flags;
484 
485         tx->stop_time.life_time = TX_CMD_LIFE_TIME_INFINITE;
486         if (!(info->flags & IEEE80211_TX_CTL_NO_ACK)) {
487                 tx_flags |= TX_CMD_FLG_ACK_MSK;
488                 if (ieee80211_is_mgmt(fc))
489                         tx_flags |= TX_CMD_FLG_SEQ_CTL_MSK;
490                 if (ieee80211_is_probe_resp(fc) &&
491                     !(le16_to_cpu(hdr->seq_ctrl) & 0xf))
492                         tx_flags |= TX_CMD_FLG_TSF_MSK;
493         } else {
494                 tx_flags &= (~TX_CMD_FLG_ACK_MSK);
495                 tx_flags |= TX_CMD_FLG_SEQ_CTL_MSK;
496         }
497 
498         tx->sta_id = std_id;
499         if (ieee80211_has_morefrags(fc))
500                 tx_flags |= TX_CMD_FLG_MORE_FRAG_MSK;
501 
502         if (ieee80211_is_data_qos(fc)) {
503                 u8 *qc = ieee80211_get_qos_ctl(hdr);
504                 tx->tid_tspec = qc[0] & 0xf;
505                 tx_flags &= ~TX_CMD_FLG_SEQ_CTL_MSK;
506         } else {
507                 tx_flags |= TX_CMD_FLG_SEQ_CTL_MSK;
508         }
509 
510         if (rc_flags & IEEE80211_TX_RC_USE_RTS_CTS) {
511                 tx_flags |= TX_CMD_FLG_RTS_MSK;
512                 tx_flags &= ~TX_CMD_FLG_CTS_MSK;
513         } else if (rc_flags & IEEE80211_TX_RC_USE_CTS_PROTECT) {
514                 tx_flags &= ~TX_CMD_FLG_RTS_MSK;
515                 tx_flags |= TX_CMD_FLG_CTS_MSK;
516         }
517 
518         if ((tx_flags & TX_CMD_FLG_RTS_MSK) || (tx_flags & TX_CMD_FLG_CTS_MSK))
519                 tx_flags |= TX_CMD_FLG_FULL_TXOP_PROT_MSK;
520 
521         tx_flags &= ~(TX_CMD_FLG_ANT_SEL_MSK);
522         if (ieee80211_is_mgmt(fc)) {
523                 if (ieee80211_is_assoc_req(fc) || ieee80211_is_reassoc_req(fc))
524                         tx->timeout.pm_frame_timeout = cpu_to_le16(3);
525                 else
526                         tx->timeout.pm_frame_timeout = cpu_to_le16(2);
527         } else {
528                 tx->timeout.pm_frame_timeout = 0;
529 #ifdef CONFIG_IWLWIFI_LEDS
530                 priv->rxtxpackets += le16_to_cpu(cmd->cmd.tx.len);
531 #endif
532         }
533 
534         tx->driver_txop = 0;
535         tx->tx_flags = tx_flags;
536         tx->next_frame_len = 0;
537 }
538 
539 /*
540  * start REPLY_TX command process
541  */
542 static int iwl3945_tx_skb(struct iwl_priv *priv, struct sk_buff *skb)
543 {
544         struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
545         struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
546         struct iwl3945_tx_cmd *tx;
547         struct iwl_tx_queue *txq = NULL;
548         struct iwl_queue *q = NULL;
549         struct iwl_cmd *out_cmd = NULL;
550         dma_addr_t phys_addr;
551         dma_addr_t txcmd_phys;
552         int txq_id = skb_get_queue_mapping(skb);
553         u16 len, idx, len_org, hdr_len; /* TODO: len_org is not used */
554         u8 id;
555         u8 unicast;
556         u8 sta_id;
557         u8 tid = 0;
558         u16 seq_number = 0;
559         __le16 fc;
560         u8 wait_write_ptr = 0;
561         u8 *qc = NULL;
562         unsigned long flags;
563         int rc;
564 
565         spin_lock_irqsave(&priv->lock, flags);
566         if (iwl_is_rfkill(priv)) {
567                 IWL_DEBUG_DROP(priv, "Dropping - RF KILL\n");
568                 goto drop_unlock;
569         }
570 
571         if ((ieee80211_get_tx_rate(priv->hw, info)->hw_value & 0xFF) == IWL_INVALID_RATE) {
572                 IWL_ERR(priv, "ERROR: No TX rate available.\n");
573                 goto drop_unlock;
574         }
575 
576         unicast = !is_multicast_ether_addr(hdr->addr1);
577         id = 0;
578 
579         fc = hdr->frame_control;
580 
581 #ifdef CONFIG_IWLWIFI_DEBUG
582         if (ieee80211_is_auth(fc))
583                 IWL_DEBUG_TX(priv, "Sending AUTH frame\n");
584         else if (ieee80211_is_assoc_req(fc))
585                 IWL_DEBUG_TX(priv, "Sending ASSOC frame\n");
586         else if (ieee80211_is_reassoc_req(fc))
587                 IWL_DEBUG_TX(priv, "Sending REASSOC frame\n");
588 #endif
589 
590         /* drop all data frame if we are not associated */
591         if (ieee80211_is_data(fc) &&
592             (!iwl_is_monitor_mode(priv)) && /* packet injection */
593             (!iwl_is_associated(priv) ||
594              ((priv->iw_mode == NL80211_IFTYPE_STATION) && !priv->assoc_id))) {
595                 IWL_DEBUG_DROP(priv, "Dropping - !iwl_is_associated\n");
596                 goto drop_unlock;
597         }
598 
599         spin_unlock_irqrestore(&priv->lock, flags);
600 
601         hdr_len = ieee80211_hdrlen(fc);
602 
603         /* Find (or create) index into station table for destination station */
604         sta_id = iwl_get_sta_id(priv, hdr);
605         if (sta_id == IWL_INVALID_STATION) {
606                 IWL_DEBUG_DROP(priv, "Dropping - INVALID STATION: %pM\n",
607                                hdr->addr1);
608                 goto drop;
609         }
610 
611         IWL_DEBUG_RATE(priv, "station Id %d\n", sta_id);
612 
613         if (ieee80211_is_data_qos(fc)) {
614                 qc = ieee80211_get_qos_ctl(hdr);
615                 tid = qc[0] & IEEE80211_QOS_CTL_TID_MASK;
616                 seq_number = priv->stations[sta_id].tid[tid].seq_number &
617                                 IEEE80211_SCTL_SEQ;
618                 hdr->seq_ctrl = cpu_to_le16(seq_number) |
619                         (hdr->seq_ctrl &
620                                 cpu_to_le16(IEEE80211_SCTL_FRAG));
621                 seq_number += 0x10;
622         }
623 
624         /* Descriptor for chosen Tx queue */
625         txq = &priv->txq[txq_id];
626         q = &txq->q;
627 
628         spin_lock_irqsave(&priv->lock, flags);
629 
630         idx = get_cmd_index(q, q->write_ptr, 0);
631 
632         /* Set up driver data for this TFD */
633         memset(&(txq->txb[q->write_ptr]), 0, sizeof(struct iwl_tx_info));
634         txq->txb[q->write_ptr].skb[0] = skb;
635 
636         /* Init first empty entry in queue's array of Tx/cmd buffers */
637         out_cmd = txq->cmd[idx];
638         tx = (struct iwl3945_tx_cmd *)out_cmd->cmd.payload;
639         memset(&out_cmd->hdr, 0, sizeof(out_cmd->hdr));
640         memset(tx, 0, sizeof(*tx));
641 
642         /*
643          * Set up the Tx-command (not MAC!) header.
644          * Store the chosen Tx queue and TFD index within the sequence field;
645          * after Tx, uCode's Tx response will return this value so driver can
646          * locate the frame within the tx queue and do post-tx processing.
647          */
648         out_cmd->hdr.cmd = REPLY_TX;
649         out_cmd->hdr.sequence = cpu_to_le16((u16)(QUEUE_TO_SEQ(txq_id) |
650                                 INDEX_TO_SEQ(q->write_ptr)));
651 
652         /* Copy MAC header from skb into command buffer */
653         memcpy(tx->hdr, hdr, hdr_len);
654 
655 
656         if (info->control.hw_key)
657                 iwl3945_build_tx_cmd_hwcrypto(priv, info, out_cmd, skb, sta_id);
658 
659         /* TODO need this for burst mode later on */
660         iwl3945_build_tx_cmd_basic(priv, out_cmd, info, hdr, sta_id);
661 
662         /* set is_hcca to 0; it probably will never be implemented */
663         iwl3945_hw_build_tx_cmd_rate(priv, out_cmd, info, hdr, sta_id, 0);
664 
665         /* Total # bytes to be transmitted */
666         len = (u16)skb->len;
667         tx->len = cpu_to_le16(len);
668 
669 
670         tx->tx_flags &= ~TX_CMD_FLG_ANT_A_MSK;
671         tx->tx_flags &= ~TX_CMD_FLG_ANT_B_MSK;
672 
673         if (!ieee80211_has_morefrags(hdr->frame_control)) {
674                 txq->need_update = 1;
675                 if (qc)
676                         priv->stations[sta_id].tid[tid].seq_number = seq_number;
677         } else {
678                 wait_write_ptr = 1;
679                 txq->need_update = 0;
680         }
681 
682         IWL_DEBUG_TX(priv, "sequence nr = 0X%x \n",
683                      le16_to_cpu(out_cmd->hdr.sequence));
684         IWL_DEBUG_TX(priv, "tx_flags = 0X%x \n", le32_to_cpu(tx->tx_flags));
685         iwl_print_hex_dump(priv, IWL_DL_TX, tx, sizeof(*tx));
686         iwl_print_hex_dump(priv, IWL_DL_TX, (u8 *)tx->hdr,
687                            ieee80211_hdrlen(fc));
688 
689         /*
690          * Use the first empty entry in this queue's command buffer array
691          * to contain the Tx command and MAC header concatenated together
692          * (payload data will be in another buffer).
693          * Size of this varies, due to varying MAC header length.
694          * If end is not dword aligned, we'll have 2 extra bytes at the end
695          * of the MAC header (device reads on dword boundaries).
696          * We'll tell device about this padding later.
697          */
698         len = sizeof(struct iwl3945_tx_cmd) +
699                         sizeof(struct iwl_cmd_header) + hdr_len;
700 
701         len_org = len;
702         len = (len + 3) & ~3;
703 
704         if (len_org != len)
705                 len_org = 1;
706         else
707                 len_org = 0;
708 
709         /* Physical address of this Tx command's header (not MAC header!),
710          * within command buffer array. */
711         txcmd_phys = pci_map_single(priv->pci_dev, &out_cmd->hdr,
712                                     len, PCI_DMA_TODEVICE);
713         /* we do not map meta data ... so we can safely access address to
714          * provide to unmap command*/
715         pci_unmap_addr_set(&out_cmd->meta, mapping, txcmd_phys);
716         pci_unmap_len_set(&out_cmd->meta, len, len);
717 
718         /* Add buffer containing Tx command and MAC(!) header to TFD's
719          * first entry */
720         priv->cfg->ops->lib->txq_attach_buf_to_tfd(priv, txq,
721                                                    txcmd_phys, len, 1, 0);
722 
723 
724         /* Set up TFD's 2nd entry to point directly to remainder of skb,
725          * if any (802.11 null frames have no payload). */
726         len = skb->len - hdr_len;
727         if (len) {
728                 phys_addr = pci_map_single(priv->pci_dev, skb->data + hdr_len,
729                                            len, PCI_DMA_TODEVICE);
730                 priv->cfg->ops->lib->txq_attach_buf_to_tfd(priv, txq,
731                                                            phys_addr, len,
732                                                            0, U32_PAD(len));
733         }
734 
735 
736         /* Tell device the write index *just past* this latest filled TFD */
737         q->write_ptr = iwl_queue_inc_wrap(q->write_ptr, q->n_bd);
738         rc = iwl_txq_update_write_ptr(priv, txq);
739         spin_unlock_irqrestore(&priv->lock, flags);
740 
741         if (rc)
742                 return rc;
743 
744         if ((iwl_queue_space(q) < q->high_mark)
745             && priv->mac80211_registered) {
746                 if (wait_write_ptr) {
747                         spin_lock_irqsave(&priv->lock, flags);
748                         txq->need_update = 1;
749                         iwl_txq_update_write_ptr(priv, txq);
750                         spin_unlock_irqrestore(&priv->lock, flags);
751                 }
752 
753                 iwl_stop_queue(priv, skb_get_queue_mapping(skb));
754         }
755 
756         return 0;
757 
758 drop_unlock:
759         spin_unlock_irqrestore(&priv->lock, flags);
760 drop:
761         return -1;
762 }
763 
764 #ifdef CONFIG_IWL3945_SPECTRUM_MEASUREMENT
765 
766 #include "iwl-spectrum.h"
767 
768 #define BEACON_TIME_MASK_LOW    0x00FFFFFF
769 #define BEACON_TIME_MASK_HIGH   0xFF000000
770 #define TIME_UNIT               1024
771 
772 /*
773  * extended beacon time format
774  * time in usec will be changed into a 32-bit value in 8:24 format
775  * the high 1 byte is the beacon counts
776  * the lower 3 bytes is the time in usec within one beacon interval
777  */
778 
779 static u32 iwl3945_usecs_to_beacons(u32 usec, u32 beacon_interval)
780 {
781         u32 quot;
782         u32 rem;
783         u32 interval = beacon_interval * 1024;
784 
785         if (!interval || !usec)
786                 return 0;
787 
788         quot = (usec / interval) & (BEACON_TIME_MASK_HIGH >> 24);
789         rem = (usec % interval) & BEACON_TIME_MASK_LOW;
790 
791         return (quot << 24) + rem;
792 }
793 
794 /* base is usually what we get from ucode with each received frame,
795  * the same as HW timer counter counting down
796  */
797 
798 static __le32 iwl3945_add_beacon_time(u32 base, u32 addon, u32 beacon_interval)
799 {
800         u32 base_low = base & BEACON_TIME_MASK_LOW;
801         u32 addon_low = addon & BEACON_TIME_MASK_LOW;
802         u32 interval = beacon_interval * TIME_UNIT;
803         u32 res = (base & BEACON_TIME_MASK_HIGH) +
804             (addon & BEACON_TIME_MASK_HIGH);
805 
806         if (base_low > addon_low)
807                 res += base_low - addon_low;
808         else if (base_low < addon_low) {
809                 res += interval + base_low - addon_low;
810                 res += (1 << 24);
811         } else
812                 res += (1 << 24);
813 
814         return cpu_to_le32(res);
815 }
816 
817 static int iwl3945_get_measurement(struct iwl_priv *priv,
818                                struct ieee80211_measurement_params *params,
819                                u8 type)
820 {
821         struct iwl_spectrum_cmd spectrum;
822         struct iwl_rx_packet *res;
823         struct iwl_host_cmd cmd = {
824                 .id = REPLY_SPECTRUM_MEASUREMENT_CMD,
825                 .data = (void *)&spectrum,
826                 .meta.flags = CMD_WANT_SKB,
827         };
828         u32 add_time = le64_to_cpu(params->start_time);
829         int rc;
830         int spectrum_resp_status;
831         int duration = le16_to_cpu(params->duration);
832 
833         if (iwl_is_associated(priv))
834                 add_time =
835                     iwl3945_usecs_to_beacons(
836                         le64_to_cpu(params->start_time) - priv->last_tsf,
837                         le16_to_cpu(priv->rxon_timing.beacon_interval));
838 
839         memset(&spectrum, 0, sizeof(spectrum));
840 
841         spectrum.channel_count = cpu_to_le16(1);
842         spectrum.flags =
843             RXON_FLG_TSF2HOST_MSK | RXON_FLG_ANT_A_MSK | RXON_FLG_DIS_DIV_MSK;
844         spectrum.filter_flags = MEASUREMENT_FILTER_FLAG;
845         cmd.len = sizeof(spectrum);
846         spectrum.len = cpu_to_le16(cmd.len - sizeof(spectrum.len));
847 
848         if (iwl_is_associated(priv))
849                 spectrum.start_time =
850                     iwl3945_add_beacon_time(priv->last_beacon_time,
851                                 add_time,
852                                 le16_to_cpu(priv->rxon_timing.beacon_interval));
853         else
854                 spectrum.start_time = 0;
855 
856         spectrum.channels[0].duration = cpu_to_le32(duration * TIME_UNIT);
857         spectrum.channels[0].channel = params->channel;
858         spectrum.channels[0].type = type;
859         if (priv->active_rxon.flags & RXON_FLG_BAND_24G_MSK)
860                 spectrum.flags |= RXON_FLG_BAND_24G_MSK |
861                     RXON_FLG_AUTO_DETECT_MSK | RXON_FLG_TGG_PROTECT_MSK;
862 
863         rc = iwl_send_cmd_sync(priv, &cmd);
864         if (rc)
865                 return rc;
866 
867         res = (struct iwl_rx_packet *)cmd.meta.u.skb->data;
868         if (res->hdr.flags & IWL_CMD_FAILED_MSK) {
869                 IWL_ERR(priv, "Bad return from REPLY_RX_ON_ASSOC command\n");
870                 rc = -EIO;
871         }
872 
873         spectrum_resp_status = le16_to_cpu(res->u.spectrum.status);
874         switch (spectrum_resp_status) {
875         case 0:         /* Command will be handled */
876                 if (res->u.spectrum.id != 0xff) {
877                         IWL_DEBUG_INFO(priv, "Replaced existing measurement: %d\n",
878                                                 res->u.spectrum.id);
879                         priv->measurement_status &= ~MEASUREMENT_READY;
880                 }
881                 priv->measurement_status |= MEASUREMENT_ACTIVE;
882                 rc = 0;
883                 break;
884 
885         case 1:         /* Command will not be handled */
886                 rc = -EAGAIN;
887                 break;
888         }
889 
890         dev_kfree_skb_any(cmd.meta.u.skb);
891 
892         return rc;
893 }
894 #endif
895 
896 static void iwl3945_rx_reply_alive(struct iwl_priv *priv,
897                                struct iwl_rx_mem_buffer *rxb)
898 {
899         struct iwl_rx_packet *pkt = (void *)rxb->skb->data;
900         struct iwl_alive_resp *palive;
901         struct delayed_work *pwork;
902 
903         palive = &pkt->u.alive_frame;
904 
905         IWL_DEBUG_INFO(priv, "Alive ucode status 0x%08X revision "
906                        "0x%01X 0x%01X\n",
907                        palive->is_valid, palive->ver_type,
908                        palive->ver_subtype);
909 
910         if (palive->ver_subtype == INITIALIZE_SUBTYPE) {
911                 IWL_DEBUG_INFO(priv, "Initialization Alive received.\n");
912                 memcpy(&priv->card_alive_init, &pkt->u.alive_frame,
913                        sizeof(struct iwl_alive_resp));
914                 pwork = &priv->init_alive_start;
915         } else {
916                 IWL_DEBUG_INFO(priv, "Runtime Alive received.\n");
917                 memcpy(&priv->card_alive, &pkt->u.alive_frame,
918                        sizeof(struct iwl_alive_resp));
919                 pwork = &priv->alive_start;
920                 iwl3945_disable_events(priv);
921         }
922 
923         /* We delay the ALIVE response by 5ms to
924          * give the HW RF Kill time to activate... */
925         if (palive->is_valid == UCODE_VALID_OK)
926                 queue_delayed_work(priv->workqueue, pwork,
927                                    msecs_to_jiffies(5));
928         else
929                 IWL_WARN(priv, "uCode did not respond OK.\n");
930 }
931 
932 static void iwl3945_rx_reply_add_sta(struct iwl_priv *priv,
933                                  struct iwl_rx_mem_buffer *rxb)
934 {
935 #ifdef CONFIG_IWLWIFI_DEBUG
936         struct iwl_rx_packet *pkt = (void *)rxb->skb->data;
937 #endif
938 
939         IWL_DEBUG_RX(priv, "Received REPLY_ADD_STA: 0x%02X\n", pkt->u.status);
940         return;
941 }
942 
943 static void iwl3945_bg_beacon_update(struct work_struct *work)
944 {
945         struct iwl_priv *priv =
946                 container_of(work, struct iwl_priv, beacon_update);
947         struct sk_buff *beacon;
948 
949         /* Pull updated AP beacon from mac80211. will fail if not in AP mode */
950         beacon = ieee80211_beacon_get(priv->hw, priv->vif);
951 
952         if (!beacon) {
953                 IWL_ERR(priv, "update beacon failed\n");
954                 return;
955         }
956 
957         mutex_lock(&priv->mutex);
958         /* new beacon skb is allocated every time; dispose previous.*/
959         if (priv->ibss_beacon)
960                 dev_kfree_skb(priv->ibss_beacon);
961 
962         priv->ibss_beacon = beacon;
963         mutex_unlock(&priv->mutex);
964 
965         iwl3945_send_beacon_cmd(priv);
966 }
967 
968 static void iwl3945_rx_beacon_notif(struct iwl_priv *priv,
969                                 struct iwl_rx_mem_buffer *rxb)
970 {
971 #ifdef CONFIG_IWLWIFI_DEBUG
972         struct iwl_rx_packet *pkt = (void *)rxb->skb->data;
973         struct iwl3945_beacon_notif *beacon = &(pkt->u.beacon_status);
974         u8 rate = beacon->beacon_notify_hdr.rate;
975 
976         IWL_DEBUG_RX(priv, "beacon status %x retries %d iss %d "
977                 "tsf %d %d rate %d\n",
978                 le32_to_cpu(beacon->beacon_notify_hdr.status) & TX_STATUS_MSK,
979                 beacon->beacon_notify_hdr.failure_frame,
980                 le32_to_cpu(beacon->ibss_mgr_status),
981                 le32_to_cpu(beacon->high_tsf),
982                 le32_to_cpu(beacon->low_tsf), rate);
983 #endif
984 
985         if ((priv->iw_mode == NL80211_IFTYPE_AP) &&
986             (!test_bit(STATUS_EXIT_PENDING, &priv->status)))
987                 queue_work(priv->workqueue, &priv->beacon_update);
988 }
989 
990 /* Handle notification from uCode that card's power state is changing
991  * due to software, hardware, or critical temperature RFKILL */
992 static void iwl3945_rx_card_state_notif(struct iwl_priv *priv,
993                                     struct iwl_rx_mem_buffer *rxb)
994 {
995         struct iwl_rx_packet *pkt = (void *)rxb->skb->data;
996         u32 flags = le32_to_cpu(pkt->u.card_state_notif.flags);
997         unsigned long status = priv->status;
998 
999         IWL_DEBUG_RF_KILL(priv, "Card state received: HW:%s SW:%s\n",
1000                           (flags & HW_CARD_DISABLED) ? "Kill" : "On",
1001                           (flags & SW_CARD_DISABLED) ? "Kill" : "On");
1002 
1003         iwl_write32(priv, CSR_UCODE_DRV_GP1_SET,
1004                     CSR_UCODE_DRV_GP1_BIT_CMD_BLOCKED);
1005 
1006         if (flags & HW_CARD_DISABLED)
1007                 set_bit(STATUS_RF_KILL_HW, &priv->status);
1008         else
1009                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
1010 
1011 
1012         iwl_scan_cancel(priv);
1013 
1014         if ((test_bit(STATUS_RF_KILL_HW, &status) !=
1015              test_bit(STATUS_RF_KILL_HW, &priv->status)))
1016                 wiphy_rfkill_set_hw_state(priv->hw->wiphy,
1017                                 test_bit(STATUS_RF_KILL_HW, &priv->status));
1018         else
1019                 wake_up_interruptible(&priv->wait_command_queue);
1020 }
1021 
1022 /**
1023  * iwl3945_setup_rx_handlers - Initialize Rx handler callbacks
1024  *
1025  * Setup the RX handlers for each of the reply types sent from the uCode
1026  * to the host.
1027  *
1028  * This function chains into the hardware specific files for them to setup
1029  * any hardware specific handlers as well.
1030  */
1031 static void iwl3945_setup_rx_handlers(struct iwl_priv *priv)
1032 {
1033         priv->rx_handlers[REPLY_ALIVE] = iwl3945_rx_reply_alive;
1034         priv->rx_handlers[REPLY_ADD_STA] = iwl3945_rx_reply_add_sta;
1035         priv->rx_handlers[REPLY_ERROR] = iwl_rx_reply_error;
1036         priv->rx_handlers[CHANNEL_SWITCH_NOTIFICATION] = iwl_rx_csa;
1037         priv->rx_handlers[PM_SLEEP_NOTIFICATION] = iwl_rx_pm_sleep_notif;
1038         priv->rx_handlers[PM_DEBUG_STATISTIC_NOTIFIC] =
1039             iwl_rx_pm_debug_statistics_notif;
1040         priv->rx_handlers[BEACON_NOTIFICATION] = iwl3945_rx_beacon_notif;
1041 
1042         /*
1043          * The same handler is used for both the REPLY to a discrete
1044          * statistics request from the host as well as for the periodic
1045          * statistics notifications (after received beacons) from the uCode.
1046          */
1047         priv->rx_handlers[REPLY_STATISTICS_CMD] = iwl3945_hw_rx_statistics;
1048         priv->rx_handlers[STATISTICS_NOTIFICATION] = iwl3945_hw_rx_statistics;
1049 
1050         iwl_setup_spectrum_handlers(priv);
1051         iwl_setup_rx_scan_handlers(priv);
1052         priv->rx_handlers[CARD_STATE_NOTIFICATION] = iwl3945_rx_card_state_notif;
1053 
1054         /* Set up hardware specific Rx handlers */
1055         iwl3945_hw_rx_handler_setup(priv);
1056 }
1057 
1058 /************************** RX-FUNCTIONS ****************************/
1059 /*
1060  * Rx theory of operation
1061  *
1062  * The host allocates 32 DMA target addresses and passes the host address
1063  * to the firmware at register IWL_RFDS_TABLE_LOWER + N * RFD_SIZE where N is
1064  * 0 to 31
1065  *
1066  * Rx Queue Indexes
1067  * The host/firmware share two index registers for managing the Rx buffers.
1068  *
1069  * The READ index maps to the first position that the firmware may be writing
1070  * to -- the driver can read up to (but not including) this position and get
1071  * good data.
1072  * The READ index is managed by the firmware once the card is enabled.
1073  *
1074  * The WRITE index maps to the last position the driver has read from -- the
1075  * position preceding WRITE is the last slot the firmware can place a packet.
1076  *
1077  * The queue is empty (no good data) if WRITE = READ - 1, and is full if
1078  * WRITE = READ.
1079  *
1080  * During initialization, the host sets up the READ queue position to the first
1081  * INDEX position, and WRITE to the last (READ - 1 wrapped)
1082  *
1083  * When the firmware places a packet in a buffer, it will advance the READ index
1084  * and fire the RX interrupt.  The driver can then query the READ index and
1085  * process as many packets as possible, moving the WRITE index forward as it
1086  * resets the Rx queue buffers with new memory.
1087  *
1088  * The management in the driver is as follows:
1089  * + A list of pre-allocated SKBs is stored in iwl->rxq->rx_free.  When
1090  *   iwl->rxq->free_count drops to or below RX_LOW_WATERMARK, work is scheduled
1091  *   to replenish the iwl->rxq->rx_free.
1092  * + In iwl3945_rx_replenish (scheduled) if 'processed' != 'read' then the
1093  *   iwl->rxq is replenished and the READ INDEX is updated (updating the
1094  *   'processed' and 'read' driver indexes as well)
1095  * + A received packet is processed and handed to the kernel network stack,
1096  *   detached from the iwl->rxq.  The driver 'processed' index is updated.
1097  * + The Host/Firmware iwl->rxq is replenished at tasklet time from the rx_free
1098  *   list. If there are no allocated buffers in iwl->rxq->rx_free, the READ
1099  *   INDEX is not incremented and iwl->status(RX_STALLED) is set.  If there
1100  *   were enough free buffers and RX_STALLED is set it is cleared.
1101  *
1102  *
1103  * Driver sequence:
1104  *
1105  * iwl3945_rx_replenish()     Replenishes rx_free list from rx_used, and calls
1106  *                            iwl3945_rx_queue_restock
1107  * iwl3945_rx_queue_restock() Moves available buffers from rx_free into Rx
1108  *                            queue, updates firmware pointers, and updates
1109  *                            the WRITE index.  If insufficient rx_free buffers
1110  *                            are available, schedules iwl3945_rx_replenish
1111  *
1112  * -- enable interrupts --
1113  * ISR - iwl3945_rx()         Detach iwl_rx_mem_buffers from pool up to the
1114  *                            READ INDEX, detaching the SKB from the pool.
1115  *                            Moves the packet buffer from queue to rx_used.
1116  *                            Calls iwl3945_rx_queue_restock to refill any empty
1117  *                            slots.
1118  * ...
1119  *
1120  */
1121 
1122 /**
1123  * iwl3945_dma_addr2rbd_ptr - convert a DMA address to a uCode read buffer ptr
1124  */
1125 static inline __le32 iwl3945_dma_addr2rbd_ptr(struct iwl_priv *priv,
1126                                           dma_addr_t dma_addr)
1127 {
1128         return cpu_to_le32((u32)dma_addr);
1129 }
1130 
1131 /**
1132  * iwl3945_rx_queue_restock - refill RX queue from pre-allocated pool
1133  *
1134  * If there are slots in the RX queue that need to be restocked,
1135  * and we have free pre-allocated buffers, fill the ranks as much
1136  * as we can, pulling from rx_free.
1137  *
1138  * This moves the 'write' index forward to catch up with 'processed', and
1139  * also updates the memory address in the firmware to reference the new
1140  * target buffer.
1141  */
1142 static int iwl3945_rx_queue_restock(struct iwl_priv *priv)
1143 {
1144         struct iwl_rx_queue *rxq = &priv->rxq;
1145         struct list_head *element;
1146         struct iwl_rx_mem_buffer *rxb;
1147         unsigned long flags;
1148         int write, rc;
1149 
1150         spin_lock_irqsave(&rxq->lock, flags);
1151         write = rxq->write & ~0x7;
1152         while ((iwl_rx_queue_space(rxq) > 0) && (rxq->free_count)) {
1153                 /* Get next free Rx buffer, remove from free list */
1154                 element = rxq->rx_free.next;
1155                 rxb = list_entry(element, struct iwl_rx_mem_buffer, list);
1156                 list_del(element);
1157 
1158                 /* Point to Rx buffer via next RBD in circular buffer */
1159                 rxq->bd[rxq->write] = iwl3945_dma_addr2rbd_ptr(priv, rxb->real_dma_addr);
1160                 rxq->queue[rxq->write] = rxb;
1161                 rxq->write = (rxq->write + 1) & RX_QUEUE_MASK;
1162                 rxq->free_count--;
1163         }
1164         spin_unlock_irqrestore(&rxq->lock, flags);
1165         /* If the pre-allocated buffer pool is dropping low, schedule to
1166          * refill it */
1167         if (rxq->free_count <= RX_LOW_WATERMARK)
1168                 queue_work(priv->workqueue, &priv->rx_replenish);
1169 
1170 
1171         /* If we've added more space for the firmware to place data, tell it.
1172          * Increment device's write pointer in multiples of 8. */
1173         if ((rxq->write_actual != (rxq->write & ~0x7))
1174             || (abs(rxq->write - rxq->read) > 7)) {
1175                 spin_lock_irqsave(&rxq->lock, flags);
1176                 rxq->need_update = 1;
1177                 spin_unlock_irqrestore(&rxq->lock, flags);
1178                 rc = iwl_rx_queue_update_write_ptr(priv, rxq);
1179                 if (rc)
1180                         return rc;
1181         }
1182 
1183         return 0;
1184 }
1185 
1186 /**
1187  * iwl3945_rx_replenish - Move all used packet from rx_used to rx_free
1188  *
1189  * When moving to rx_free an SKB is allocated for the slot.
1190  *
1191  * Also restock the Rx queue via iwl3945_rx_queue_restock.
1192  * This is called as a scheduled work item (except for during initialization)
1193  */
1194 static void iwl3945_rx_allocate(struct iwl_priv *priv, gfp_t priority)
1195 {
1196         struct iwl_rx_queue *rxq = &priv->rxq;
1197         struct list_head *element;
1198         struct iwl_rx_mem_buffer *rxb;
1199         struct sk_buff *skb;
1200         unsigned long flags;
1201 
1202         while (1) {
1203                 spin_lock_irqsave(&rxq->lock, flags);
1204 
1205                 if (list_empty(&rxq->rx_used)) {
1206                         spin_unlock_irqrestore(&rxq->lock, flags);
1207                         return;
1208                 }
1209                 spin_unlock_irqrestore(&rxq->lock, flags);
1210 
1211                 if (rxq->free_count > RX_LOW_WATERMARK)
1212                         priority |= __GFP_NOWARN;
1213                 /* Alloc a new receive buffer */
1214                 skb = alloc_skb(priv->hw_params.rx_buf_size, priority);
1215                 if (!skb) {
1216                         if (net_ratelimit())
1217                                 IWL_DEBUG_INFO(priv, "Failed to allocate SKB buffer.\n");
1218                         if ((rxq->free_count <= RX_LOW_WATERMARK) &&
1219                             net_ratelimit())
1220                                 IWL_CRIT(priv, "Failed to allocate SKB buffer with %s. Only %u free buffers remaining.\n",
1221                                          priority == GFP_ATOMIC ?  "GFP_ATOMIC" : "GFP_KERNEL",
1222                                          rxq->free_count);
1223                         /* We don't reschedule replenish work here -- we will
1224                          * call the restock method and if it still needs
1225                          * more buffers it will schedule replenish */
1226                         break;
1227                 }
1228 
1229                 spin_lock_irqsave(&rxq->lock, flags);
1230                 if (list_empty(&rxq->rx_used)) {
1231                         spin_unlock_irqrestore(&rxq->lock, flags);
1232                         dev_kfree_skb_any(skb);
1233                         return;
1234                 }
1235                 element = rxq->rx_used.next;
1236                 rxb = list_entry(element, struct iwl_rx_mem_buffer, list);
1237                 list_del(element);
1238                 spin_unlock_irqrestore(&rxq->lock, flags);
1239 
1240                 rxb->skb = skb;
1241 
1242                 /* If radiotap head is required, reserve some headroom here.
1243                  * The physical head count is a variable rx_stats->phy_count.
1244                  * We reserve 4 bytes here. Plus these extra bytes, the
1245                  * headroom of the physical head should be enough for the
1246                  * radiotap head that iwl3945 supported. See iwl3945_rt.
1247                  */
1248                 skb_reserve(rxb->skb, 4);
1249 
1250                 /* Get physical address of RB/SKB */
1251                 rxb->real_dma_addr = pci_map_single(priv->pci_dev,
1252                                                 rxb->skb->data,
1253                                                 priv->hw_params.rx_buf_size,
1254                                                 PCI_DMA_FROMDEVICE);
1255 
1256                 spin_lock_irqsave(&rxq->lock, flags);
1257                 list_add_tail(&rxb->list, &rxq->rx_free);
1258                 priv->alloc_rxb_skb++;
1259                 rxq->free_count++;
1260                 spin_unlock_irqrestore(&rxq->lock, flags);
1261         }
1262 }
1263 
1264 void iwl3945_rx_queue_reset(struct iwl_priv *priv, struct iwl_rx_queue *rxq)
1265 {
1266         unsigned long flags;
1267         int i;
1268         spin_lock_irqsave(&rxq->lock, flags);
1269         INIT_LIST_HEAD(&rxq->rx_free);
1270         INIT_LIST_HEAD(&rxq->rx_used);
1271         /* Fill the rx_used queue with _all_ of the Rx buffers */
1272         for (i = 0; i < RX_FREE_BUFFERS + RX_QUEUE_SIZE; i++) {
1273                 /* In the reset function, these buffers may have been allocated
1274                  * to an SKB, so we need to unmap and free potential storage */
1275                 if (rxq->pool[i].skb != NULL) {
1276                         pci_unmap_single(priv->pci_dev,
1277                                          rxq->pool[i].real_dma_addr,
1278                                          priv->hw_params.rx_buf_size,
1279                                          PCI_DMA_FROMDEVICE);
1280                         priv->alloc_rxb_skb--;
1281                         dev_kfree_skb(rxq->pool[i].skb);
1282                         rxq->pool[i].skb = NULL;
1283                 }
1284                 list_add_tail(&rxq->pool[i].list, &rxq->rx_used);
1285         }
1286 
1287         /* Set us so that we have processed and used all buffers, but have
1288          * not restocked the Rx queue with fresh buffers */
1289         rxq->read = rxq->write = 0;
1290         rxq->free_count = 0;
1291         rxq->write_actual = 0;
1292         spin_unlock_irqrestore(&rxq->lock, flags);
1293 }
1294 
1295 void iwl3945_rx_replenish(void *data)
1296 {
1297         struct iwl_priv *priv = data;
1298         unsigned long flags;
1299 
1300         iwl3945_rx_allocate(priv, GFP_KERNEL);
1301 
1302         spin_lock_irqsave(&priv->lock, flags);
1303         iwl3945_rx_queue_restock(priv);
1304         spin_unlock_irqrestore(&priv->lock, flags);
1305 }
1306 
1307 static void iwl3945_rx_replenish_now(struct iwl_priv *priv)
1308 {
1309         iwl3945_rx_allocate(priv, GFP_ATOMIC);
1310 
1311         iwl3945_rx_queue_restock(priv);
1312 }
1313 
1314 
1315 /* Assumes that the skb field of the buffers in 'pool' is kept accurate.
1316  * If an SKB has been detached, the POOL needs to have its SKB set to NULL
1317  * This free routine walks the list of POOL entries and if SKB is set to
1318  * non NULL it is unmapped and freed
1319  */
1320 static void iwl3945_rx_queue_free(struct iwl_priv *priv, struct iwl_rx_queue *rxq)
1321 {
1322         int i;
1323         for (i = 0; i < RX_QUEUE_SIZE + RX_FREE_BUFFERS; i++) {
1324                 if (rxq->pool[i].skb != NULL) {
1325                         pci_unmap_single(priv->pci_dev,
1326                                          rxq->pool[i].real_dma_addr,
1327                                          priv->hw_params.rx_buf_size,
1328                                          PCI_DMA_FROMDEVICE);
1329                         dev_kfree_skb(rxq->pool[i].skb);
1330                 }
1331         }
1332 
1333         pci_free_consistent(priv->pci_dev, 4 * RX_QUEUE_SIZE, rxq->bd,
1334                             rxq->dma_addr);
1335         pci_free_consistent(priv->pci_dev, sizeof(struct iwl_rb_status),
1336                             rxq->rb_stts, rxq->rb_stts_dma);
1337         rxq->bd = NULL;
1338         rxq->rb_stts  = NULL;
1339 }
1340 
1341 
1342 /* Convert linear signal-to-noise ratio into dB */
1343 static u8 ratio2dB[100] = {
1344 /*       0   1   2   3   4   5   6   7   8   9 */
1345          0,  0,  6, 10, 12, 14, 16, 17, 18, 19, /* 00 - 09 */
1346         20, 21, 22, 22, 23, 23, 24, 25, 26, 26, /* 10 - 19 */
1347         26, 26, 26, 27, 27, 28, 28, 28, 29, 29, /* 20 - 29 */
1348         29, 30, 30, 30, 31, 31, 31, 31, 32, 32, /* 30 - 39 */
1349         32, 32, 32, 33, 33, 33, 33, 33, 34, 34, /* 40 - 49 */
1350         34, 34, 34, 34, 35, 35, 35, 35, 35, 35, /* 50 - 59 */
1351         36, 36, 36, 36, 36, 36, 36, 37, 37, 37, /* 60 - 69 */
1352         37, 37, 37, 37, 37, 38, 38, 38, 38, 38, /* 70 - 79 */
1353         38, 38, 38, 38, 38, 39, 39, 39, 39, 39, /* 80 - 89 */
1354         39, 39, 39, 39, 39, 40, 40, 40, 40, 40  /* 90 - 99 */
1355 };
1356 
1357 /* Calculates a relative dB value from a ratio of linear
1358  *   (i.e. not dB) signal levels.
1359  * Conversion assumes that levels are voltages (20*log), not powers (10*log). */
1360 int iwl3945_calc_db_from_ratio(int sig_ratio)
1361 {
1362         /* 1000:1 or higher just report as 60 dB */
1363         if (sig_ratio >= 1000)
1364                 return 60;
1365 
1366         /* 100:1 or higher, divide by 10 and use table,
1367          *   add 20 dB to make up for divide by 10 */
1368         if (sig_ratio >= 100)
1369                 return 20 + (int)ratio2dB[sig_ratio/10];
1370 
1371         /* We shouldn't see this */
1372         if (sig_ratio < 1)
1373                 return 0;
1374 
1375         /* Use table for ratios 1:1 - 99:1 */
1376         return (int)ratio2dB[sig_ratio];
1377 }
1378 
1379 #define PERFECT_RSSI (-20) /* dBm */
1380 #define WORST_RSSI (-95)   /* dBm */
1381 #define RSSI_RANGE (PERFECT_RSSI - WORST_RSSI)
1382 
1383 /* Calculate an indication of rx signal quality (a percentage, not dBm!).
1384  * See http://www.ces.clemson.edu/linux/signal_quality.shtml for info
1385  *   about formulas used below. */
1386 int iwl3945_calc_sig_qual(int rssi_dbm, int noise_dbm)
1387 {
1388         int sig_qual;
1389         int degradation = PERFECT_RSSI - rssi_dbm;
1390 
1391         /* If we get a noise measurement, use signal-to-noise ratio (SNR)
1392          * as indicator; formula is (signal dbm - noise dbm).
1393          * SNR at or above 40 is a great signal (100%).
1394          * Below that, scale to fit SNR of 0 - 40 dB within 0 - 100% indicator.
1395          * Weakest usable signal is usually 10 - 15 dB SNR. */
1396         if (noise_dbm) {
1397                 if (rssi_dbm - noise_dbm >= 40)
1398                         return 100;
1399                 else if (rssi_dbm < noise_dbm)
1400                         return 0;
1401                 sig_qual = ((rssi_dbm - noise_dbm) * 5) / 2;
1402 
1403         /* Else use just the signal level.
1404          * This formula is a least squares fit of data points collected and
1405          *   compared with a reference system that had a percentage (%) display
1406          *   for signal quality. */
1407         } else
1408                 sig_qual = (100 * (RSSI_RANGE * RSSI_RANGE) - degradation *
1409                             (15 * RSSI_RANGE + 62 * degradation)) /
1410                            (RSSI_RANGE * RSSI_RANGE);
1411 
1412         if (sig_qual > 100)
1413                 sig_qual = 100;
1414         else if (sig_qual < 1)
1415                 sig_qual = 0;
1416 
1417         return sig_qual;
1418 }
1419 
1420 /**
1421  * iwl3945_rx_handle - Main entry function for receiving responses from uCode
1422  *
1423  * Uses the priv->rx_handlers callback function array to invoke
1424  * the appropriate handlers, including command responses,
1425  * frame-received notifications, and other notifications.
1426  */
1427 static void iwl3945_rx_handle(struct iwl_priv *priv)
1428 {
1429         struct iwl_rx_mem_buffer *rxb;
1430         struct iwl_rx_packet *pkt;
1431         struct iwl_rx_queue *rxq = &priv->rxq;
1432         u32 r, i;
1433         int reclaim;
1434         unsigned long flags;
1435         u8 fill_rx = 0;
1436         u32 count = 8;
1437         int total_empty = 0;
1438 
1439         /* uCode's read index (stored in shared DRAM) indicates the last Rx
1440          * buffer that the driver may process (last buffer filled by ucode). */
1441         r = le16_to_cpu(rxq->rb_stts->closed_rb_num) &  0x0FFF;
1442         i = rxq->read;
1443 
1444         /* calculate total frames need to be restock after handling RX */
1445         total_empty = r - priv->rxq.write_actual;
1446         if (total_empty < 0)
1447                 total_empty += RX_QUEUE_SIZE;
1448 
1449         if (total_empty > (RX_QUEUE_SIZE / 2))
1450                 fill_rx = 1;
1451         /* Rx interrupt, but nothing sent from uCode */
1452         if (i == r)
1453                 IWL_DEBUG(priv, IWL_DL_RX | IWL_DL_ISR, "r = %d, i = %d\n", r, i);
1454 
1455         while (i != r) {
1456                 rxb = rxq->queue[i];
1457 
1458                 /* If an RXB doesn't have a Rx queue slot associated with it,
1459                  * then a bug has been introduced in the queue refilling
1460                  * routines -- catch it here */
1461                 BUG_ON(rxb == NULL);
1462 
1463                 rxq->queue[i] = NULL;
1464 
1465                 pci_unmap_single(priv->pci_dev, rxb->real_dma_addr,
1466                                 priv->hw_params.rx_buf_size,
1467                                 PCI_DMA_FROMDEVICE);
1468                 pkt = (struct iwl_rx_packet *)rxb->skb->data;
1469 
1470                 /* Reclaim a command buffer only if this packet is a response
1471                  *   to a (driver-originated) command.
1472                  * If the packet (e.g. Rx frame) originated from uCode,
1473                  *   there is no command buffer to reclaim.
1474                  * Ucode should set SEQ_RX_FRAME bit if ucode-originated,
1475                  *   but apparently a few don't get set; catch them here. */
1476                 reclaim = !(pkt->hdr.sequence & SEQ_RX_FRAME) &&
1477                         (pkt->hdr.cmd != STATISTICS_NOTIFICATION) &&
1478                         (pkt->hdr.cmd != REPLY_TX);
1479 
1480                 /* Based on type of command response or notification,
1481                  *   handle those that need handling via function in
1482                  *   rx_handlers table.  See iwl3945_setup_rx_handlers() */
1483                 if (priv->rx_handlers[pkt->hdr.cmd]) {
1484                         IWL_DEBUG(priv, IWL_DL_HCMD | IWL_DL_RX | IWL_DL_ISR,
1485                                 "r = %d, i = %d, %s, 0x%02x\n", r, i,
1486                                 get_cmd_string(pkt->hdr.cmd), pkt->hdr.cmd);
1487                         priv->rx_handlers[pkt->hdr.cmd] (priv, rxb);
1488                         priv->isr_stats.rx_handlers[pkt->hdr.cmd]++;
1489                 } else {
1490                         /* No handling needed */
1491                         IWL_DEBUG(priv, IWL_DL_HCMD | IWL_DL_RX | IWL_DL_ISR,
1492                                 "r %d i %d No handler needed for %s, 0x%02x\n",
1493                                 r, i, get_cmd_string(pkt->hdr.cmd),
1494                                 pkt->hdr.cmd);
1495                 }
1496 
1497                 if (reclaim) {
1498                         /* Invoke any callbacks, transfer the skb to caller, and
1499                          * fire off the (possibly) blocking iwl_send_cmd()
1500                          * as we reclaim the driver command queue */
1501                         if (rxb && rxb->skb)
1502                                 iwl_tx_cmd_complete(priv, rxb);
1503                         else
1504                                 IWL_WARN(priv, "Claim null rxb?\n");
1505                 }
1506 
1507                 /* For now we just don't re-use anything.  We can tweak this
1508                  * later to try and re-use notification packets and SKBs that
1509                  * fail to Rx correctly */
1510                 if (rxb->skb != NULL) {
1511                         priv->alloc_rxb_skb--;
1512                         dev_kfree_skb_any(rxb->skb);
1513                         rxb->skb = NULL;
1514                 }
1515 
1516                 spin_lock_irqsave(&rxq->lock, flags);
1517                 list_add_tail(&rxb->list, &priv->rxq.rx_used);
1518                 spin_unlock_irqrestore(&rxq->lock, flags);
1519                 i = (i + 1) & RX_QUEUE_MASK;
1520                 /* If there are a lot of unused frames,
1521                  * restock the Rx queue so ucode won't assert. */
1522                 if (fill_rx) {
1523                         count++;
1524                         if (count >= 8) {
1525                                 priv->rxq.read = i;
1526                                 iwl3945_rx_replenish_now(priv);
1527                                 count = 0;
1528                         }
1529                 }
1530         }
1531 
1532         /* Backtrack one entry */
1533         priv->rxq.read = i;
1534         if (fill_rx)
1535                 iwl3945_rx_replenish_now(priv);
1536         else
1537                 iwl3945_rx_queue_restock(priv);
1538 }
1539 
1540 /* call this function to flush any scheduled tasklet */
1541 static inline void iwl_synchronize_irq(struct iwl_priv *priv)
1542 {
1543         /* wait to make sure we flush pending tasklet*/
1544         synchronize_irq(priv->pci_dev->irq);
1545         tasklet_kill(&priv->irq_tasklet);
1546 }
1547 
1548 static const char *desc_lookup(int i)
1549 {
1550         switch (i) {
1551         case 1:
1552                 return "FAIL";
1553         case 2:
1554                 return "BAD_PARAM";
1555         case 3:
1556                 return "BAD_CHECKSUM";
1557         case 4:
1558                 return "NMI_INTERRUPT";
1559         case 5:
1560                 return "SYSASSERT";
1561         case 6:
1562                 return "FATAL_ERROR";
1563         }
1564 
1565         return "UNKNOWN";
1566 }
1567 
1568 #define ERROR_START_OFFSET  (1 * sizeof(u32))
1569 #define ERROR_ELEM_SIZE     (7 * sizeof(u32))
1570 
1571 static void iwl3945_dump_nic_error_log(struct iwl_priv *priv)
1572 {
1573         u32 i;
1574         u32 desc, time, count, base, data1;
1575         u32 blink1, blink2, ilink1, ilink2;
1576 
1577         base = le32_to_cpu(priv->card_alive.error_event_table_ptr);
1578 
1579         if (!iwl3945_hw_valid_rtc_data_addr(base)) {
1580                 IWL_ERR(priv, "Not valid error log pointer 0x%08X\n", base);
1581                 return;
1582         }
1583 
1584 
1585         count = iwl_read_targ_mem(priv, base);
1586 
1587         if (ERROR_START_OFFSET <= count * ERROR_ELEM_SIZE) {
1588                 IWL_ERR(priv, "Start IWL Error Log Dump:\n");
1589                 IWL_ERR(priv, "Status: 0x%08lX, count: %d\n",
1590                         priv->status, count);
1591         }
1592 
1593         IWL_ERR(priv, "Desc       Time       asrtPC  blink2 "
1594                   "ilink1  nmiPC   Line\n");
1595         for (i = ERROR_START_OFFSET;
1596              i < (count * ERROR_ELEM_SIZE) + ERROR_START_OFFSET;
1597              i += ERROR_ELEM_SIZE) {
1598                 desc = iwl_read_targ_mem(priv, base + i);
1599                 time =
1600                     iwl_read_targ_mem(priv, base + i + 1 * sizeof(u32));
1601                 blink1 =
1602                     iwl_read_targ_mem(priv, base + i + 2 * sizeof(u32));
1603                 blink2 =
1604                     iwl_read_targ_mem(priv, base + i + 3 * sizeof(u32));
1605                 ilink1 =
1606                     iwl_read_targ_mem(priv, base + i + 4 * sizeof(u32));
1607                 ilink2 =
1608                     iwl_read_targ_mem(priv, base + i + 5 * sizeof(u32));
1609                 data1 =
1610                     iwl_read_targ_mem(priv, base + i + 6 * sizeof(u32));
1611 
1612                 IWL_ERR(priv,
1613                         "%-13s (#%d) %010u 0x%05X 0x%05X 0x%05X 0x%05X %u\n\n",
1614                         desc_lookup(desc), desc, time, blink1, blink2,
1615                         ilink1, ilink2, data1);
1616         }
1617 
1618 }
1619 
1620 #define EVENT_START_OFFSET  (6 * sizeof(u32))
1621 
1622 /**
1623  * iwl3945_print_event_log - Dump error event log to syslog
1624  *
1625  */
1626 static void iwl3945_print_event_log(struct iwl_priv *priv, u32 start_idx,
1627                                 u32 num_events, u32 mode)
1628 {
1629         u32 i;
1630         u32 base;       /* SRAM byte address of event log header */
1631         u32 event_size; /* 2 u32s, or 3 u32s if timestamp recorded */
1632         u32 ptr;        /* SRAM byte address of log data */
1633         u32 ev, time, data; /* event log data */
1634 
1635         if (num_events == 0)
1636                 return;
1637 
1638         base = le32_to_cpu(priv->card_alive.log_event_table_ptr);
1639 
1640         if (mode == 0)
1641                 event_size = 2 * sizeof(u32);
1642         else
1643                 event_size = 3 * sizeof(u32);
1644 
1645         ptr = base + EVENT_START_OFFSET + (start_idx * event_size);
1646 
1647         /* "time" is actually "data" for mode 0 (no timestamp).
1648          * place event id # at far right for easier visual parsing. */
1649         for (i = 0; i < num_events; i++) {
1650                 ev = iwl_read_targ_mem(priv, ptr);
1651                 ptr += sizeof(u32);
1652                 time = iwl_read_targ_mem(priv, ptr);
1653                 ptr += sizeof(u32);
1654                 if (mode == 0) {
1655                         /* data, ev */
1656                         IWL_ERR(priv, "0x%08x\t%04u\n", time, ev);
1657                 } else {
1658                         data = iwl_read_targ_mem(priv, ptr);
1659                         ptr += sizeof(u32);
1660                         IWL_ERR(priv, "%010u\t0x%08x\t%04u\n", time, data, ev);
1661                 }
1662         }
1663 }
1664 
1665 static void iwl3945_dump_nic_event_log(struct iwl_priv *priv)
1666 {
1667         u32 base;       /* SRAM byte address of event log header */
1668         u32 capacity;   /* event log capacity in # entries */
1669         u32 mode;       /* 0 - no timestamp, 1 - timestamp recorded */
1670         u32 num_wraps;  /* # times uCode wrapped to top of log */
1671         u32 next_entry; /* index of next entry to be written by uCode */
1672         u32 size;       /* # entries that we'll print */
1673 
1674         base = le32_to_cpu(priv->card_alive.log_event_table_ptr);
1675         if (!iwl3945_hw_valid_rtc_data_addr(base)) {
1676                 IWL_ERR(priv, "Invalid event log pointer 0x%08X\n", base);
1677                 return;
1678         }
1679 
1680         /* event log header */
1681         capacity = iwl_read_targ_mem(priv, base);
1682         mode = iwl_read_targ_mem(priv, base + (1 * sizeof(u32)));
1683         num_wraps = iwl_read_targ_mem(priv, base + (2 * sizeof(u32)));
1684         next_entry = iwl_read_targ_mem(priv, base + (3 * sizeof(u32)));
1685 
1686         size = num_wraps ? capacity : next_entry;
1687 
1688         /* bail out if nothing in log */
1689         if (size == 0) {
1690                 IWL_ERR(priv, "Start IWL Event Log Dump: nothing in log\n");
1691                 return;
1692         }
1693 
1694         IWL_ERR(priv, "Start IWL Event Log Dump: display count %d, wraps %d\n",
1695                   size, num_wraps);
1696 
1697         /* if uCode has wrapped back to top of log, start at the oldest entry,
1698          * i.e the next one that uCode would fill. */
1699         if (num_wraps)
1700                 iwl3945_print_event_log(priv, next_entry,
1701                                     capacity - next_entry, mode);
1702 
1703         /* (then/else) start at top of log */
1704         iwl3945_print_event_log(priv, 0, next_entry, mode);
1705 
1706 }
1707 
1708 static void iwl3945_irq_tasklet(struct iwl_priv *priv)
1709 {
1710         u32 inta, handled = 0;
1711         u32 inta_fh;
1712         unsigned long flags;
1713 #ifdef CONFIG_IWLWIFI_DEBUG
1714         u32 inta_mask;
1715 #endif
1716 
1717         spin_lock_irqsave(&priv->lock, flags);
1718 
1719         /* Ack/clear/reset pending uCode interrupts.
1720          * Note:  Some bits in CSR_INT are "OR" of bits in CSR_FH_INT_STATUS,
1721          *  and will clear only when CSR_FH_INT_STATUS gets cleared. */
1722         inta = iwl_read32(priv, CSR_INT);
1723         iwl_write32(priv, CSR_INT, inta);
1724 
1725         /* Ack/clear/reset pending flow-handler (DMA) interrupts.
1726          * Any new interrupts that happen after this, either while we're
1727          * in this tasklet, or later, will show up in next ISR/tasklet. */
1728         inta_fh = iwl_read32(priv, CSR_FH_INT_STATUS);
1729         iwl_write32(priv, CSR_FH_INT_STATUS, inta_fh);
1730 
1731 #ifdef CONFIG_IWLWIFI_DEBUG
1732         if (priv->debug_level & IWL_DL_ISR) {
1733                 /* just for debug */
1734                 inta_mask = iwl_read32(priv, CSR_INT_MASK);
1735                 IWL_DEBUG_ISR(priv, "inta 0x%08x, enabled 0x%08x, fh 0x%08x\n",
1736                               inta, inta_mask, inta_fh);
1737         }
1738 #endif
1739 
1740         /* Since CSR_INT and CSR_FH_INT_STATUS reads and clears are not
1741          * atomic, make sure that inta covers all the interrupts that
1742          * we've discovered, even if FH interrupt came in just after
1743          * reading CSR_INT. */
1744         if (inta_fh & CSR39_FH_INT_RX_MASK)
1745                 inta |= CSR_INT_BIT_FH_RX;
1746         if (inta_fh & CSR39_FH_INT_TX_MASK)
1747                 inta |= CSR_INT_BIT_FH_TX;
1748 
1749         /* Now service all interrupt bits discovered above. */
1750         if (inta & CSR_INT_BIT_HW_ERR) {
1751                 IWL_ERR(priv, "Microcode HW error detected.  Restarting.\n");
1752 
1753                 /* Tell the device to stop sending interrupts */
1754                 iwl_disable_interrupts(priv);
1755 
1756                 priv->isr_stats.hw++;
1757                 iwl_irq_handle_error(priv);
1758 
1759                 handled |= CSR_INT_BIT_HW_ERR;
1760 
1761                 spin_unlock_irqrestore(&priv->lock, flags);
1762 
1763                 return;
1764         }
1765 
1766 #ifdef CONFIG_IWLWIFI_DEBUG
1767         if (priv->debug_level & (IWL_DL_ISR)) {
1768                 /* NIC fires this, but we don't use it, redundant with WAKEUP */
1769                 if (inta & CSR_INT_BIT_SCD) {
1770                         IWL_DEBUG_ISR(priv, "Scheduler finished to transmit "
1771                                       "the frame/frames.\n");
1772                         priv->isr_stats.sch++;
1773                 }
1774 
1775                 /* Alive notification via Rx interrupt will do the real work */
1776                 if (inta & CSR_INT_BIT_ALIVE) {
1777                         IWL_DEBUG_ISR(priv, "Alive interrupt\n");
1778                         priv->isr_stats.alive++;
1779                 }
1780         }
1781 #endif
1782         /* Safely ignore these bits for debug checks below */
1783         inta &= ~(CSR_INT_BIT_SCD | CSR_INT_BIT_ALIVE);
1784 
1785         /* Error detected by uCode */
1786         if (inta & CSR_INT_BIT_SW_ERR) {
1787                 IWL_ERR(priv, "Microcode SW error detected. "
1788                         "Restarting 0x%X.\n", inta);
1789                 priv->isr_stats.sw++;
1790                 priv->isr_stats.sw_err = inta;
1791                 iwl_irq_handle_error(priv);
1792                 handled |= CSR_INT_BIT_SW_ERR;
1793         }
1794 
1795         /* uCode wakes up after power-down sleep */
1796         if (inta & CSR_INT_BIT_WAKEUP) {
1797                 IWL_DEBUG_ISR(priv, "Wakeup interrupt\n");
1798                 iwl_rx_queue_update_write_ptr(priv, &priv->rxq);
1799                 iwl_txq_update_write_ptr(priv, &priv->txq[0]);
1800                 iwl_txq_update_write_ptr(priv, &priv->txq[1]);
1801                 iwl_txq_update_write_ptr(priv, &priv->txq[2]);
1802                 iwl_txq_update_write_ptr(priv, &priv->txq[3]);
1803                 iwl_txq_update_write_ptr(priv, &priv->txq[4]);
1804                 iwl_txq_update_write_ptr(priv, &priv->txq[5]);
1805 
1806                 priv->isr_stats.wakeup++;
1807                 handled |= CSR_INT_BIT_WAKEUP;
1808         }
1809 
1810         /* All uCode command responses, including Tx command responses,
1811          * Rx "responses" (frame-received notification), and other
1812          * notifications from uCode come through here*/
1813         if (inta & (CSR_INT_BIT_FH_RX | CSR_INT_BIT_SW_RX)) {
1814                 iwl3945_rx_handle(priv);
1815                 priv->isr_stats.rx++;
1816                 handled |= (CSR_INT_BIT_FH_RX | CSR_INT_BIT_SW_RX);
1817         }
1818 
1819         if (inta & CSR_INT_BIT_FH_TX) {
1820                 IWL_DEBUG_ISR(priv, "Tx interrupt\n");
1821                 priv->isr_stats.tx++;
1822 
1823                 iwl_write32(priv, CSR_FH_INT_STATUS, (1 << 6));
1824                 iwl_write_direct32(priv, FH39_TCSR_CREDIT
1825                                         (FH39_SRVC_CHNL), 0x0);
1826                 handled |= CSR_INT_BIT_FH_TX;
1827         }
1828 
1829         if (inta & ~handled) {
1830                 IWL_ERR(priv, "Unhandled INTA bits 0x%08x\n", inta & ~handled);
1831                 priv->isr_stats.unhandled++;
1832         }
1833 
1834         if (inta & ~priv->inta_mask) {
1835                 IWL_WARN(priv, "Disabled INTA bits 0x%08x were pending\n",
1836                          inta & ~priv->inta_mask);
1837                 IWL_WARN(priv, "   with FH_INT = 0x%08x\n", inta_fh);
1838         }
1839 
1840         /* Re-enable all interrupts */
1841         /* only Re-enable if disabled by irq */
1842         if (test_bit(STATUS_INT_ENABLED, &priv->status))
1843                 iwl_enable_interrupts(priv);
1844 
1845 #ifdef CONFIG_IWLWIFI_DEBUG
1846         if (priv->debug_level & (IWL_DL_ISR)) {
1847                 inta = iwl_read32(priv, CSR_INT);
1848                 inta_mask = iwl_read32(priv, CSR_INT_MASK);
1849                 inta_fh = iwl_read32(priv, CSR_FH_INT_STATUS);
1850                 IWL_DEBUG_ISR(priv, "End inta 0x%08x, enabled 0x%08x, fh 0x%08x, "
1851                         "flags 0x%08lx\n", inta, inta_mask, inta_fh, flags);
1852         }
1853 #endif
1854         spin_unlock_irqrestore(&priv->lock, flags);
1855 }
1856 
1857 static int iwl3945_get_channels_for_scan(struct iwl_priv *priv,
1858                                          enum ieee80211_band band,
1859                                      u8 is_active, u8 n_probes,
1860                                      struct iwl3945_scan_channel *scan_ch)
1861 {
1862         const struct ieee80211_channel *channels = NULL;
1863         const struct ieee80211_supported_band *sband;
1864         const struct iwl_channel_info *ch_info;
1865         u16 passive_dwell = 0;
1866         u16 active_dwell = 0;
1867         int added, i;
1868 
1869         sband = iwl_get_hw_mode(priv, band);
1870         if (!sband)
1871                 return 0;
1872 
1873         channels = sband->channels;
1874 
1875         active_dwell = iwl_get_active_dwell_time(priv, band, n_probes);
1876         passive_dwell = iwl_get_passive_dwell_time(priv, band);
1877 
1878         if (passive_dwell <= active_dwell)
1879                 passive_dwell = active_dwell + 1;
1880 
1881         for (i = 0, added = 0; i < sband->n_channels; i++) {
1882                 if (channels[i].flags & IEEE80211_CHAN_DISABLED)
1883                         continue;
1884 
1885                 scan_ch->channel = channels[i].hw_value;
1886 
1887                 ch_info = iwl_get_channel_info(priv, band, scan_ch->channel);
1888                 if (!is_channel_valid(ch_info)) {
1889                         IWL_DEBUG_SCAN(priv, "Channel %d is INVALID for this band.\n",
1890                                        scan_ch->channel);
1891                         continue;
1892                 }
1893 
1894                 scan_ch->active_dwell = cpu_to_le16(active_dwell);
1895                 scan_ch->passive_dwell = cpu_to_le16(passive_dwell);
1896                 /* If passive , set up for auto-switch
1897                  *  and use long active_dwell time.
1898                  */
1899                 if (!is_active || is_channel_passive(ch_info) ||
1900                     (channels[i].flags & IEEE80211_CHAN_PASSIVE_SCAN)) {
1901                         scan_ch->type = 0;      /* passive */
1902                         if (IWL_UCODE_API(priv->ucode_ver) == 1)
1903                                 scan_ch->active_dwell = cpu_to_le16(passive_dwell - 1);
1904                 } else {
1905                         scan_ch->type = 1;      /* active */
1906                 }
1907 
1908                 /* Set direct probe bits. These may be used both for active
1909                  * scan channels (probes gets sent right away),
1910                  * or for passive channels (probes get se sent only after
1911                  * hearing clear Rx packet).*/
1912                 if (IWL_UCODE_API(priv->ucode_ver) >= 2) {
1913                         if (n_probes)
1914                                 scan_ch->type |= IWL39_SCAN_PROBE_MASK(n_probes);
1915                 } else {
1916                         /* uCode v1 does not allow setting direct probe bits on
1917                          * passive channel. */
1918                         if ((scan_ch->type & 1) && n_probes)
1919                                 scan_ch->type |= IWL39_SCAN_PROBE_MASK(n_probes);
1920                 }
1921 
1922                 /* Set txpower levels to defaults */
1923                 scan_ch->tpc.dsp_atten = 110;
1924                 /* scan_pwr_info->tpc.dsp_atten; */
1925 
1926                 /*scan_pwr_info->tpc.tx_gain; */
1927                 if (band == IEEE80211_BAND_5GHZ)
1928                         scan_ch->tpc.tx_gain = ((1 << 5) | (3 << 3)) | 3;
1929                 else {
1930                         scan_ch->tpc.tx_gain = ((1 << 5) | (5 << 3));
1931                         /* NOTE: if we were doing 6Mb OFDM for scans we'd use
1932                          * power level:
1933                          * scan_ch->tpc.tx_gain = ((1 << 5) | (2 << 3)) | 3;
1934                          */
1935                 }
1936 
1937                 IWL_DEBUG_SCAN(priv, "Scanning %d [%s %d]\n",
1938                                scan_ch->channel,
1939                                (scan_ch->type & 1) ? "ACTIVE" : "PASSIVE",
1940                                (scan_ch->type & 1) ?
1941                                active_dwell : passive_dwell);
1942 
1943                 scan_ch++;
1944                 added++;
1945         }
1946 
1947         IWL_DEBUG_SCAN(priv, "total channels to scan %d \n", added);
1948         return added;
1949 }
1950 
1951 static void iwl3945_init_hw_rates(struct iwl_priv *priv,
1952                               struct ieee80211_rate *rates)
1953 {
1954         int i;
1955 
1956         for (i = 0; i < IWL_RATE_COUNT; i++) {
1957                 rates[i].bitrate = iwl3945_rates[i].ieee * 5;
1958                 rates[i].hw_value = i; /* Rate scaling will work on indexes */
1959                 rates[i].hw_value_short = i;
1960                 rates[i].flags = 0;
1961                 if ((i > IWL39_LAST_OFDM_RATE) || (i < IWL_FIRST_OFDM_RATE)) {
1962                         /*
1963                          * If CCK != 1M then set short preamble rate flag.
1964                          */
1965                         rates[i].flags |= (iwl3945_rates[i].plcp == 10) ?
1966                                 0 : IEEE80211_RATE_SHORT_PREAMBLE;
1967                 }
1968         }
1969 }
1970 
1971 /******************************************************************************
1972  *
1973  * uCode download functions
1974  *
1975  ******************************************************************************/
1976 
1977 static void iwl3945_dealloc_ucode_pci(struct iwl_priv *priv)
1978 {
1979         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_code);
1980         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_data);
1981         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_data_backup);
1982         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_init);
1983         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_init_data);
1984         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_boot);
1985 }
1986 
1987 /**
1988  * iwl3945_verify_inst_full - verify runtime uCode image in card vs. host,
1989  *     looking at all data.
1990  */
1991 static int iwl3945_verify_inst_full(struct iwl_priv *priv, __le32 *image, u32 len)
1992 {
1993         u32 val;
1994         u32 save_len = len;
1995         int rc = 0;
1996         u32 errcnt;
1997 
1998         IWL_DEBUG_INFO(priv, "ucode inst image size is %u\n", len);
1999 
2000         iwl_write_direct32(priv, HBUS_TARG_MEM_RADDR,
2001                                IWL39_RTC_INST_LOWER_BOUND);
2002 
2003         errcnt = 0;
2004         for (; len > 0; len -= sizeof(u32), image++) {
2005                 /* read data comes through single port, auto-incr addr */
2006                 /* NOTE: Use the debugless read so we don't flood kernel log
2007                  * if IWL_DL_IO is set */
2008                 val = _iwl_read_direct32(priv, HBUS_TARG_MEM_RDAT);
2009                 if (val != le32_to_cpu(*image)) {
2010                         IWL_ERR(priv, "uCode INST section is invalid at "
2011                                   "offset 0x%x, is 0x%x, s/b 0x%x\n",
2012                                   save_len - len, val, le32_to_cpu(*image));
2013                         rc = -EIO;
2014                         errcnt++;
2015                         if (errcnt >= 20)
2016                                 break;
2017                 }
2018         }
2019 
2020 
2021         if (!errcnt)
2022                 IWL_DEBUG_INFO(priv,
2023                         "ucode image in INSTRUCTION memory is good\n");
2024 
2025         return rc;
2026 }
2027 
2028 
2029 /**
2030  * iwl3945_verify_inst_sparse - verify runtime uCode image in card vs. host,
2031  *   using sample data 100 bytes apart.  If these sample points are good,
2032  *   it's a pretty good bet that everything between them is good, too.
2033  */
2034 static int iwl3945_verify_inst_sparse(struct iwl_priv *priv, __le32 *image, u32 len)
2035 {
2036         u32 val;
2037         int rc = 0;
2038         u32 errcnt = 0;
2039         u32 i;
2040 
2041         IWL_DEBUG_INFO(priv, "ucode inst image size is %u\n", len);
2042 
2043         for (i = 0; i < len; i += 100, image += 100/sizeof(u32)) {
2044                 /* read data comes through single port, auto-incr addr */
2045                 /* NOTE: Use the debugless read so we don't flood kernel log
2046                  * if IWL_DL_IO is set */
2047                 iwl_write_direct32(priv, HBUS_TARG_MEM_RADDR,
2048                         i + IWL39_RTC_INST_LOWER_BOUND);
2049                 val = _iwl_read_direct32(priv, HBUS_TARG_MEM_RDAT);
2050                 if (val != le32_to_cpu(*image)) {
2051 #if 0 /* Enable this if you want to see details */
2052                         IWL_ERR(priv, "uCode INST section is invalid at "
2053                                   "offset 0x%x, is 0x%x, s/b 0x%x\n",
2054                                   i, val, *image);
2055 #endif
2056                         rc = -EIO;
2057                         errcnt++;
2058                         if (errcnt >= 3)
2059                                 break;
2060                 }
2061         }
2062 
2063         return rc;
2064 }
2065 
2066 
2067 /**
2068  * iwl3945_verify_ucode - determine which instruction image is in SRAM,
2069  *    and verify its contents
2070  */
2071 static int iwl3945_verify_ucode(struct iwl_priv *priv)
2072 {
2073         __le32 *image;
2074         u32 len;
2075         int rc = 0;
2076 
2077         /* Try bootstrap */
2078         image = (__le32 *)priv->ucode_boot.v_addr;
2079         len = priv->ucode_boot.len;
2080         rc = iwl3945_verify_inst_sparse(priv, image, len);
2081         if (rc == 0) {
2082                 IWL_DEBUG_INFO(priv, "Bootstrap uCode is good in inst SRAM\n");
2083                 return 0;
2084         }
2085 
2086         /* Try initialize */
2087         image = (__le32 *)priv->ucode_init.v_addr;
2088         len = priv->ucode_init.len;
2089         rc = iwl3945_verify_inst_sparse(priv, image, len);
2090         if (rc == 0) {
2091                 IWL_DEBUG_INFO(priv, "Initialize uCode is good in inst SRAM\n");
2092                 return 0;
2093         }
2094 
2095         /* Try runtime/protocol */
2096         image = (__le32 *)priv->ucode_code.v_addr;
2097         len = priv->ucode_code.len;
2098         rc = iwl3945_verify_inst_sparse(priv, image, len);
2099         if (rc == 0) {
2100                 IWL_DEBUG_INFO(priv, "Runtime uCode is good in inst SRAM\n");
2101                 return 0;
2102         }
2103 
2104         IWL_ERR(priv, "NO VALID UCODE IMAGE IN INSTRUCTION SRAM!!\n");
2105 
2106         /* Since nothing seems to match, show first several data entries in
2107          * instruction SRAM, so maybe visual inspection will give a clue.
2108          * Selection of bootstrap image (vs. other images) is arbitrary. */
2109         image = (__le32 *)priv->ucode_boot.v_addr;
2110         len = priv->ucode_boot.len;
2111         rc = iwl3945_verify_inst_full(priv, image, len);
2112 
2113         return rc;
2114 }
2115 
2116 static void iwl3945_nic_start(struct iwl_priv *priv)
2117 {
2118         /* Remove all resets to allow NIC to operate */
2119         iwl_write32(priv, CSR_RESET, 0);
2120 }
2121 
2122 /**
2123  * iwl3945_read_ucode - Read uCode images from disk file.
2124  *
2125  * Copy into buffers for card to fetch via bus-mastering
2126  */
2127 static int iwl3945_read_ucode(struct iwl_priv *priv)
2128 {
2129         const struct iwl_ucode_header *ucode;
2130         int ret = -EINVAL, index;
2131         const struct firmware *ucode_raw;
2132         /* firmware file name contains uCode/driver compatibility version */
2133         const char *name_pre = priv->cfg->fw_name_pre;
2134         const unsigned int api_max = priv->cfg->ucode_api_max;
2135         const unsigned int api_min = priv->cfg->ucode_api_min;
2136         char buf[25];
2137         u8 *src;
2138         size_t len;
2139         u32 api_ver, inst_size, data_size, init_size, init_data_size, boot_size;
2140 
2141         /* Ask kernel firmware_class module to get the boot firmware off disk.
2142          * request_firmware() is synchronous, file is in memory on return. */
2143         for (index = api_max; index >= api_min; index--) {
2144                 sprintf(buf, "%s%u%s", name_pre, index, ".ucode");
2145                 ret = request_firmware(&ucode_raw, buf, &priv->pci_dev->dev);
2146                 if (ret < 0) {
2147                         IWL_ERR(priv, "%s firmware file req failed: %d\n",
2148                                   buf, ret);
2149                         if (ret == -ENOENT)
2150                                 continue;
2151                         else
2152                                 goto error;
2153                 } else {
2154                         if (index < api_max)
2155                                 IWL_ERR(priv, "Loaded firmware %s, "
2156                                         "which is deprecated. "
2157                                         " Please use API v%u instead.\n",
2158                                           buf, api_max);
2159                         IWL_DEBUG_INFO(priv, "Got firmware '%s' file "
2160                                        "(%zd bytes) from disk\n",
2161                                        buf, ucode_raw->size);
2162                         break;
2163                 }
2164         }
2165 
2166         if (ret < 0)
2167                 goto error;
2168 
2169         /* Make sure that we got at least our header! */
2170         if (ucode_raw->size <  priv->cfg->ops->ucode->get_header_size(1)) {
2171                 IWL_ERR(priv, "File size way too small!\n");
2172                 ret = -EINVAL;
2173                 goto err_release;
2174         }
2175 
2176         /* Data from ucode file:  header followed by uCode images */
2177         ucode = (struct iwl_ucode_header *)ucode_raw->data;
2178 
2179         priv->ucode_ver = le32_to_cpu(ucode->ver);
2180         api_ver = IWL_UCODE_API(priv->ucode_ver);
2181         inst_size = priv->cfg->ops->ucode->get_inst_size(ucode, api_ver);
2182         data_size = priv->cfg->ops->ucode->get_data_size(ucode, api_ver);
2183         init_size = priv->cfg->ops->ucode->get_init_size(ucode, api_ver);
2184         init_data_size =
2185                 priv->cfg->ops->ucode->get_init_data_size(ucode, api_ver);
2186         boot_size = priv->cfg->ops->ucode->get_boot_size(ucode, api_ver);
2187         src = priv->cfg->ops->ucode->get_data(ucode, api_ver);
2188 
2189         /* api_ver should match the api version forming part of the
2190          * firmware filename ... but we don't check for that and only rely
2191          * on the API version read from firmware header from here on forward */
2192 
2193         if (api_ver < api_min || api_ver > api_max) {
2194                 IWL_ERR(priv, "Driver unable to support your firmware API. "
2195                           "Driver supports v%u, firmware is v%u.\n",
2196                           api_max, api_ver);
2197                 priv->ucode_ver = 0;
2198                 ret = -EINVAL;
2199                 goto err_release;
2200         }
2201         if (api_ver != api_max)
2202                 IWL_ERR(priv, "Firmware has old API version. Expected %u, "
2203                           "got %u. New firmware can be obtained "
2204                           "from http://www.intellinuxwireless.org.\n",
2205                           api_max, api_ver);
2206 
2207         IWL_INFO(priv, "loaded firmware version %u.%u.%u.%u\n",
2208                 IWL_UCODE_MAJOR(priv->ucode_ver),
2209                 IWL_UCODE_MINOR(priv->ucode_ver),
2210                 IWL_UCODE_API(priv->ucode_ver),
2211                 IWL_UCODE_SERIAL(priv->ucode_ver));
2212 
2213         IWL_DEBUG_INFO(priv, "f/w package hdr ucode version raw = 0x%x\n",
2214                        priv->ucode_ver);
2215         IWL_DEBUG_INFO(priv, "f/w package hdr runtime inst size = %u\n",
2216                        inst_size);
2217         IWL_DEBUG_INFO(priv, "f/w package hdr runtime data size = %u\n",
2218                        data_size);
2219         IWL_DEBUG_INFO(priv, "f/w package hdr init inst size = %u\n",
2220                        init_size);
2221         IWL_DEBUG_INFO(priv, "f/w package hdr init data size = %u\n",
2222                        init_data_size);
2223         IWL_DEBUG_INFO(priv, "f/w package hdr boot inst size = %u\n",
2224                        boot_size);
2225 
2226 
2227         /* Verify size of file vs. image size info in file's header */
2228         if (ucode_raw->size != priv->cfg->ops->ucode->get_header_size(api_ver) +
2229                 inst_size + data_size + init_size +
2230                 init_data_size + boot_size) {
2231 
2232                 IWL_DEBUG_INFO(priv,
2233                         "uCode file size %zd does not match expected size\n",
2234                         ucode_raw->size);
2235                 ret = -EINVAL;
2236                 goto err_release;
2237         }
2238 
2239         /* Verify that uCode images will fit in card's SRAM */
2240         if (inst_size > IWL39_MAX_INST_SIZE) {
2241                 IWL_DEBUG_INFO(priv, "uCode instr len %d too large to fit in\n",
2242                                inst_size);
2243                 ret = -EINVAL;
2244                 goto err_release;
2245         }
2246 
2247         if (data_size > IWL39_MAX_DATA_SIZE) {
2248                 IWL_DEBUG_INFO(priv, "uCode data len %d too large to fit in\n",
2249                                data_size);
2250                 ret = -EINVAL;
2251                 goto err_release;
2252         }
2253         if (init_size > IWL39_MAX_INST_SIZE) {
2254                 IWL_DEBUG_INFO(priv,
2255                                 "uCode init instr len %d too large to fit in\n",
2256                                 init_size);
2257                 ret = -EINVAL;
2258                 goto err_release;
2259         }
2260         if (init_data_size > IWL39_MAX_DATA_SIZE) {
2261                 IWL_DEBUG_INFO(priv,
2262                                 "uCode init data len %d too large to fit in\n",
2263                                 init_data_size);
2264                 ret = -EINVAL;
2265                 goto err_release;
2266         }
2267         if (boot_size > IWL39_MAX_BSM_SIZE) {
2268                 IWL_DEBUG_INFO(priv,
2269                                 "uCode boot instr len %d too large to fit in\n",
2270                                 boot_size);
2271                 ret = -EINVAL;
2272                 goto err_release;
2273         }
2274 
2275         /* Allocate ucode buffers for card's bus-master loading ... */
2276 
2277         /* Runtime instructions and 2 copies of data:
2278          * 1) unmodified from disk
2279          * 2) backup cache for save/restore during power-downs */
2280         priv->ucode_code.len = inst_size;
2281         iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_code);
2282 
2283         priv->ucode_data.len = data_size;
2284         iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_data);
2285 
2286         priv->ucode_data_backup.len = data_size;
2287         iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_data_backup);
2288 
2289         if (!priv->ucode_code.v_addr || !priv->ucode_data.v_addr ||
2290             !priv->ucode_data_backup.v_addr)
2291                 goto err_pci_alloc;
2292 
2293         /* Initialization instructions and data */
2294         if (init_size && init_data_size) {
2295                 priv->ucode_init.len = init_size;
2296                 iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_init);
2297 
2298                 priv->ucode_init_data.len = init_data_size;
2299                 iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_init_data);
2300 
2301                 if (!priv->ucode_init.v_addr || !priv->ucode_init_data.v_addr)
2302                         goto err_pci_alloc;
2303         }
2304 
2305         /* Bootstrap (instructions only, no data) */
2306         if (boot_size) {
2307                 priv->ucode_boot.len = boot_size;
2308                 iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_boot);
2309 
2310                 if (!priv->ucode_boot.v_addr)
2311                         goto err_pci_alloc;
2312         }
2313 
2314         /* Copy images into buffers for card's bus-master reads ... */
2315 
2316         /* Runtime instructions (first block of data in file) */
2317         len = inst_size;
2318         IWL_DEBUG_INFO(priv,
2319                 "Copying (but not loading) uCode instr len %zd\n", len);
2320         memcpy(priv->ucode_code.v_addr, src, len);
2321         src += len;
2322 
2323         IWL_DEBUG_INFO(priv, "uCode instr buf vaddr = 0x%p, paddr = 0x%08x\n",
2324                 priv->ucode_code.v_addr, (u32)priv->ucode_code.p_addr);
2325 
2326         /* Runtime data (2nd block)
2327          * NOTE:  Copy into backup buffer will be done in iwl3945_up()  */
2328         len = data_size;
2329         IWL_DEBUG_INFO(priv,
2330                 "Copying (but not loading) uCode data len %zd\n", len);
2331         memcpy(priv->ucode_data.v_addr, src, len);
2332         memcpy(priv->ucode_data_backup.v_addr, src, len);
2333         src += len;
2334 
2335         /* Initialization instructions (3rd block) */
2336         if (init_size) {
2337                 len = init_size;
2338                 IWL_DEBUG_INFO(priv,
2339                         "Copying (but not loading) init instr len %zd\n", len);
2340                 memcpy(priv->ucode_init.v_addr, src, len);
2341                 src += len;
2342         }
2343 
2344         /* Initialization data (4th block) */
2345         if (init_data_size) {
2346                 len = init_data_size;
2347                 IWL_DEBUG_INFO(priv,
2348                         "Copying (but not loading) init data len %zd\n", len);
2349                 memcpy(priv->ucode_init_data.v_addr, src, len);
2350                 src += len;
2351         }
2352 
2353         /* Bootstrap instructions (5th block) */
2354         len = boot_size;
2355         IWL_DEBUG_INFO(priv,
2356                 "Copying (but not loading) boot instr len %zd\n", len);
2357         memcpy(priv->ucode_boot.v_addr, src, len);
2358 
2359         /* We have our copies now, allow OS release its copies */
2360         release_firmware(ucode_raw);
2361         return 0;
2362 
2363  err_pci_alloc:
2364         IWL_ERR(priv, "failed to allocate pci memory\n");
2365         ret = -ENOMEM;
2366         iwl3945_dealloc_ucode_pci(priv);
2367 
2368  err_release:
2369         release_firmware(ucode_raw);
2370 
2371  error:
2372         return ret;
2373 }
2374 
2375 
2376 /**
2377  * iwl3945_set_ucode_ptrs - Set uCode address location
2378  *
2379  * Tell initialization uCode where to find runtime uCode.
2380  *
2381  * BSM registers initially contain pointers to initialization uCode.
2382  * We need to replace them to load runtime uCode inst and data,
2383  * and to save runtime data when powering down.
2384  */
2385 static int iwl3945_set_ucode_ptrs(struct iwl_priv *priv)
2386 {
2387         dma_addr_t pinst;
2388         dma_addr_t pdata;
2389 
2390         /* bits 31:0 for 3945 */
2391         pinst = priv->ucode_code.p_addr;
2392         pdata = priv->ucode_data_backup.p_addr;
2393 
2394         /* Tell bootstrap uCode where to find image to load */
2395         iwl_write_prph(priv, BSM_DRAM_INST_PTR_REG, pinst);
2396         iwl_write_prph(priv, BSM_DRAM_DATA_PTR_REG, pdata);
2397         iwl_write_prph(priv, BSM_DRAM_DATA_BYTECOUNT_REG,
2398                                  priv->ucode_data.len);
2399 
2400         /* Inst byte count must be last to set up, bit 31 signals uCode
2401          *   that all new ptr/size info is in place */
2402         iwl_write_prph(priv, BSM_DRAM_INST_BYTECOUNT_REG,
2403                                  priv->ucode_code.len | BSM_DRAM_INST_LOAD);
2404 
2405         IWL_DEBUG_INFO(priv, "Runtime uCode pointers are set.\n");
2406 
2407         return 0;
2408 }
2409 
2410 /**
2411  * iwl3945_init_alive_start - Called after REPLY_ALIVE notification received
2412  *
2413  * Called after REPLY_ALIVE notification received from "initialize" uCode.
2414  *
2415  * Tell "initialize" uCode to go ahead and load the runtime uCode.
2416  */
2417 static void iwl3945_init_alive_start(struct iwl_priv *priv)
2418 {
2419         /* Check alive response for "valid" sign from uCode */
2420         if (priv->card_alive_init.is_valid != UCODE_VALID_OK) {
2421                 /* We had an error bringing up the hardware, so take it
2422                  * all the way back down so we can try again */
2423                 IWL_DEBUG_INFO(priv, "Initialize Alive failed.\n");
2424                 goto restart;
2425         }
2426 
2427         /* Bootstrap uCode has loaded initialize uCode ... verify inst image.
2428          * This is a paranoid check, because we would not have gotten the
2429          * "initialize" alive if code weren't properly loaded.  */
2430         if (iwl3945_verify_ucode(priv)) {
2431                 /* Runtime instruction load was bad;
2432                  * take it all the way back down so we can try again */
2433                 IWL_DEBUG_INFO(priv, "Bad \"initialize\" uCode load.\n");
2434                 goto restart;
2435         }
2436 
2437         /* Send pointers to protocol/runtime uCode image ... init code will
2438          * load and launch runtime uCode, which will send us another "Alive"
2439          * notification. */
2440         IWL_DEBUG_INFO(priv, "Initialization Alive received.\n");
2441         if (iwl3945_set_ucode_ptrs(priv)) {
2442                 /* Runtime instruction load won't happen;
2443                  * take it all the way back down so we can try again */
2444                 IWL_DEBUG_INFO(priv, "Couldn't set up uCode pointers.\n");
2445                 goto restart;
2446         }
2447         return;
2448 
2449  restart:
2450         queue_work(priv->workqueue, &priv->restart);
2451 }
2452 
2453 /**
2454  * iwl3945_alive_start - called after REPLY_ALIVE notification received
2455  *                   from protocol/runtime uCode (initialization uCode's
2456  *                   Alive gets handled by iwl3945_init_alive_start()).
2457  */
2458 static void iwl3945_alive_start(struct iwl_priv *priv)
2459 {
2460         int thermal_spin = 0;
2461         u32 rfkill;
2462 
2463         IWL_DEBUG_INFO(priv, "Runtime Alive received.\n");
2464 
2465         if (priv->card_alive.is_valid != UCODE_VALID_OK) {
2466                 /* We had an error bringing up the hardware, so take it
2467                  * all the way back down so we can try again */
2468                 IWL_DEBUG_INFO(priv, "Alive failed.\n");
2469                 goto restart;
2470         }
2471 
2472         /* Initialize uCode has loaded Runtime uCode ... verify inst image.
2473          * This is a paranoid check, because we would not have gotten the
2474          * "runtime" alive if code weren't properly loaded.  */
2475         if (iwl3945_verify_ucode(priv)) {
2476                 /* Runtime instruction load was bad;
2477                  * take it all the way back down so we can try again */
2478                 IWL_DEBUG_INFO(priv, "Bad runtime uCode load.\n");
2479                 goto restart;
2480         }
2481 
2482         iwl_clear_stations_table(priv);
2483 
2484         rfkill = iwl_read_prph(priv, APMG_RFKILL_REG);
2485         IWL_DEBUG_INFO(priv, "RFKILL status: 0x%x\n", rfkill);
2486 
2487         if (rfkill & 0x1) {
2488                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
2489                 /* if RFKILL is not on, then wait for thermal
2490                  * sensor in adapter to kick in */
2491                 while (iwl3945_hw_get_temperature(priv) == 0) {
2492                         thermal_spin++;
2493                         udelay(10);
2494                 }
2495 
2496                 if (thermal_spin)
2497                         IWL_DEBUG_INFO(priv, "Thermal calibration took %dus\n",
2498                                        thermal_spin * 10);
2499         } else
2500                 set_bit(STATUS_RF_KILL_HW, &priv->status);
2501 
2502         /* After the ALIVE response, we can send commands to 3945 uCode */
2503         set_bit(STATUS_ALIVE, &priv->status);
2504 
2505         if (iwl_is_rfkill(priv))
2506                 return;
2507 
2508         ieee80211_wake_queues(priv->hw);
2509 
2510         priv->active_rate = priv->rates_mask;
2511         priv->active_rate_basic = priv->rates_mask & IWL_BASIC_RATES_MASK;
2512 
2513         iwl_power_update_mode(priv, false);
2514 
2515         if (iwl_is_associated(priv)) {
2516                 struct iwl3945_rxon_cmd *active_rxon =
2517                                 (struct iwl3945_rxon_cmd *)(&priv->active_rxon);
2518 
2519                 priv->staging_rxon.filter_flags |= RXON_FILTER_ASSOC_MSK;
2520                 active_rxon->filter_flags &= ~RXON_FILTER_ASSOC_MSK;
2521         } else {
2522                 /* Initialize our rx_config data */
2523                 iwl_connection_init_rx_config(priv, priv->iw_mode);
2524         }
2525 
2526         /* Configure Bluetooth device coexistence support */
2527         iwl_send_bt_config(priv);
2528 
2529         /* Configure the adapter for unassociated operation */
2530         iwlcore_commit_rxon(priv);
2531 
2532         iwl3945_reg_txpower_periodic(priv);
2533 
2534         iwl3945_led_register(priv);
2535 
2536         IWL_DEBUG_INFO(priv, "ALIVE processing complete.\n");
2537         set_bit(STATUS_READY, &priv->status);
2538         wake_up_interruptible(&priv->wait_command_queue);
2539 
2540         /* reassociate for ADHOC mode */
2541         if (priv->vif && (priv->iw_mode == NL80211_IFTYPE_ADHOC)) {
2542                 struct sk_buff *beacon = ieee80211_beacon_get(priv->hw,
2543                                                                 priv->vif);
2544                 if (beacon)
2545                         iwl_mac_beacon_update(priv->hw, beacon);
2546         }
2547 
2548         if (test_and_clear_bit(STATUS_MODE_PENDING, &priv->status))
2549                 iwl_set_mode(priv, priv->iw_mode);
2550 
2551         return;
2552 
2553  restart:
2554         queue_work(priv->workqueue, &priv->restart);
2555 }
2556 
2557 static void iwl3945_cancel_deferred_work(struct iwl_priv *priv);
2558 
2559 static void __iwl3945_down(struct iwl_priv *priv)
2560 {
2561         unsigned long flags;
2562         int exit_pending = test_bit(STATUS_EXIT_PENDING, &priv->status);
2563         struct ieee80211_conf *conf = NULL;
2564 
2565         IWL_DEBUG_INFO(priv, DRV_NAME " is going down\n");
2566 
2567         conf = ieee80211_get_hw_conf(priv->hw);
2568 
2569         if (!exit_pending)
2570                 set_bit(STATUS_EXIT_PENDING, &priv->status);
2571 
2572         iwl3945_led_unregister(priv);
2573         iwl_clear_stations_table(priv);
2574 
2575         /* Unblock any waiting calls */
2576         wake_up_interruptible_all(&priv->wait_command_queue);
2577 
2578         /* Wipe out the EXIT_PENDING status bit if we are not actually
2579          * exiting the module */
2580         if (!exit_pending)
2581                 clear_bit(STATUS_EXIT_PENDING, &priv->status);
2582 
2583         /* stop and reset the on-board processor */
2584         iwl_write32(priv, CSR_RESET, CSR_RESET_REG_FLAG_NEVO_RESET);
2585 
2586         /* tell the device to stop sending interrupts */
2587         spin_lock_irqsave(&priv->lock, flags);
2588         iwl_disable_interrupts(priv);
2589         spin_unlock_irqrestore(&priv->lock, flags);
2590         iwl_synchronize_irq(priv);
2591 
2592         if (priv->mac80211_registered)
2593                 ieee80211_stop_queues(priv->hw);
2594 
2595         /* If we have not previously called iwl3945_init() then
2596          * clear all bits but the RF Kill bits and return */
2597         if (!iwl_is_init(priv)) {
2598                 priv->status = test_bit(STATUS_RF_KILL_HW, &priv->status) <<
2599                                         STATUS_RF_KILL_HW |
2600                                test_bit(STATUS_GEO_CONFIGURED, &priv->status) <<
2601                                         STATUS_GEO_CONFIGURED |
2602                                 test_bit(STATUS_EXIT_PENDING, &priv->status) <<
2603                                         STATUS_EXIT_PENDING;
2604                 goto exit;
2605         }
2606 
2607         /* ...otherwise clear out all the status bits but the RF Kill
2608          * bit and continue taking the NIC down. */
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_FW_ERROR, &priv->status) <<
2614                                 STATUS_FW_ERROR |
2615                         test_bit(STATUS_EXIT_PENDING, &priv->status) <<
2616                                 STATUS_EXIT_PENDING;
2617 
2618         priv->cfg->ops->lib->apm_ops.reset(priv);
2619         spin_lock_irqsave(&priv->lock, flags);
2620         iwl_clear_bit(priv, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
2621         spin_unlock_irqrestore(&priv->lock, flags);
2622 
2623         iwl3945_hw_txq_ctx_stop(priv);
2624         iwl3945_hw_rxq_stop(priv);
2625 
2626         iwl_write_prph(priv, APMG_CLK_DIS_REG,
2627                                 APMG_CLK_VAL_DMA_CLK_RQT);
2628 
2629         udelay(5);
2630 
2631         if (exit_pending)
2632                 priv->cfg->ops->lib->apm_ops.stop(priv);
2633         else
2634                 priv->cfg->ops->lib->apm_ops.reset(priv);
2635 
2636  exit:
2637         memset(&priv->card_alive, 0, sizeof(struct iwl_alive_resp));
2638 
2639         if (priv->ibss_beacon)
2640                 dev_kfree_skb(priv->ibss_beacon);
2641         priv->ibss_beacon = NULL;
2642 
2643         /* clear out any free frames */
2644         iwl3945_clear_free_frames(priv);
2645 }
2646 
2647 static void iwl3945_down(struct iwl_priv *priv)
2648 {
2649         mutex_lock(&priv->mutex);
2650         __iwl3945_down(priv);
2651         mutex_unlock(&priv->mutex);
2652 
2653         iwl3945_cancel_deferred_work(priv);
2654 }
2655 
2656 #define MAX_HW_RESTARTS 5
2657 
2658 static int __iwl3945_up(struct iwl_priv *priv)
2659 {
2660         int rc, i;
2661 
2662         if (test_bit(STATUS_EXIT_PENDING, &priv->status)) {
2663                 IWL_WARN(priv, "Exit pending; will not bring the NIC up\n");
2664                 return -EIO;
2665         }
2666 
2667         if (!priv->ucode_data_backup.v_addr || !priv->ucode_data.v_addr) {
2668                 IWL_ERR(priv, "ucode not available for device bring up\n");
2669                 return -EIO;
2670         }
2671 
2672         /* If platform's RF_KILL switch is NOT set to KILL */
2673         if (iwl_read32(priv, CSR_GP_CNTRL) &
2674                                 CSR_GP_CNTRL_REG_FLAG_HW_RF_KILL_SW)
2675                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
2676         else {
2677                 set_bit(STATUS_RF_KILL_HW, &priv->status);
2678                 IWL_WARN(priv, "Radio disabled by HW RF Kill switch\n");
2679                 return -ENODEV;
2680         }
2681 
2682         iwl_write32(priv, CSR_INT, 0xFFFFFFFF);
2683 
2684         rc = iwl3945_hw_nic_init(priv);
2685         if (rc) {
2686                 IWL_ERR(priv, "Unable to int nic\n");
2687                 return rc;
2688         }
2689 
2690         /* make sure rfkill handshake bits are cleared */
2691         iwl_write32(priv, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
2692         iwl_write32(priv, CSR_UCODE_DRV_GP1_CLR,
2693                     CSR_UCODE_DRV_GP1_BIT_CMD_BLOCKED);
2694 
2695         /* clear (again), then enable host interrupts */
2696         iwl_write32(priv, CSR_INT, 0xFFFFFFFF);
2697         iwl_enable_interrupts(priv);
2698 
2699         /* really make sure rfkill handshake bits are cleared */
2700         iwl_write32(priv, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
2701         iwl_write32(priv, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
2702 
2703         /* Copy original ucode data image from disk into backup cache.
2704          * This will be used to initialize the on-board processor's
2705          * data SRAM for a clean start when the runtime program first loads. */
2706         memcpy(priv->ucode_data_backup.v_addr, priv->ucode_data.v_addr,
2707                priv->ucode_data.len);
2708 
2709         /* We return success when we resume from suspend and rf_kill is on. */
2710         if (test_bit(STATUS_RF_KILL_HW, &priv->status))
2711                 return 0;
2712 
2713         for (i = 0; i < MAX_HW_RESTARTS; i++) {
2714 
2715                 iwl_clear_stations_table(priv);
2716 
2717                 /* load bootstrap state machine,
2718                  * load bootstrap program into processor's memory,
2719                  * prepare to load the "initialize" uCode */
2720                 priv->cfg->ops->lib->load_ucode(priv);
2721 
2722                 if (rc) {
2723                         IWL_ERR(priv,
2724                                 "Unable to set up bootstrap uCode: %d\n", rc);
2725                         continue;
2726                 }
2727 
2728                 /* start card; "initialize" will load runtime ucode */
2729                 iwl3945_nic_start(priv);
2730 
2731                 IWL_DEBUG_INFO(priv, DRV_NAME " is coming up\n");
2732 
2733                 return 0;
2734         }
2735 
2736         set_bit(STATUS_EXIT_PENDING, &priv->status);
2737         __iwl3945_down(priv);
2738         clear_bit(STATUS_EXIT_PENDING, &priv->status);
2739 
2740         /* tried to restart and config the device for as long as our
2741          * patience could withstand */
2742         IWL_ERR(priv, "Unable to initialize device after %d attempts.\n", i);
2743         return -EIO;
2744 }
2745 
2746 
2747 /*****************************************************************************
2748  *
2749  * Workqueue callbacks
2750  *
2751  *****************************************************************************/
2752 
2753 static void iwl3945_bg_init_alive_start(struct work_struct *data)
2754 {
2755         struct iwl_priv *priv =
2756             container_of(data, struct iwl_priv, init_alive_start.work);
2757 
2758         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
2759                 return;
2760 
2761         mutex_lock(&priv->mutex);
2762         iwl3945_init_alive_start(priv);
2763         mutex_unlock(&priv->mutex);
2764 }
2765 
2766 static void iwl3945_bg_alive_start(struct work_struct *data)
2767 {
2768         struct iwl_priv *priv =
2769             container_of(data, struct iwl_priv, alive_start.work);
2770 
2771         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
2772                 return;
2773 
2774         mutex_lock(&priv->mutex);
2775         iwl3945_alive_start(priv);
2776         mutex_unlock(&priv->mutex);
2777 }
2778 
2779 static void iwl3945_rfkill_poll(struct work_struct *data)
2780 {
2781         struct iwl_priv *priv =
2782             container_of(data, struct iwl_priv, rfkill_poll.work);
2783 
2784         if (iwl_read32(priv, CSR_GP_CNTRL) & CSR_GP_CNTRL_REG_FLAG_HW_RF_KILL_SW)
2785                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
2786         else
2787                 set_bit(STATUS_RF_KILL_HW, &priv->status);
2788 
2789         wiphy_rfkill_set_hw_state(priv->hw->wiphy,
2790                         test_bit(STATUS_RF_KILL_HW, &priv->status));
2791 
2792         queue_delayed_work(priv->workqueue, &priv->rfkill_poll,
2793                            round_jiffies_relative(2 * HZ));
2794 
2795 }
2796 
2797 #define IWL_SCAN_CHECK_WATCHDOG (7 * HZ)
2798 static void iwl3945_bg_request_scan(struct work_struct *data)
2799 {
2800         struct iwl_priv *priv =
2801             container_of(data, struct iwl_priv, request_scan);
2802         struct iwl_host_cmd cmd = {
2803                 .id = REPLY_SCAN_CMD,
2804                 .len = sizeof(struct iwl3945_scan_cmd),
2805                 .meta.flags = CMD_SIZE_HUGE,
2806         };
2807         int rc = 0;
2808         struct iwl3945_scan_cmd *scan;
2809         struct ieee80211_conf *conf = NULL;
2810         u8 n_probes = 0;
2811         enum ieee80211_band band;
2812         bool is_active = false;
2813 
2814         conf = ieee80211_get_hw_conf(priv->hw);
2815 
2816         mutex_lock(&priv->mutex);
2817 
2818         cancel_delayed_work(&priv->scan_check);
2819 
2820         if (!iwl_is_ready(priv)) {
2821                 IWL_WARN(priv, "request scan called when driver not ready.\n");
2822                 goto done;
2823         }
2824 
2825         /* Make sure the scan wasn't canceled before this queued work
2826          * was given the chance to run... */
2827         if (!test_bit(STATUS_SCANNING, &priv->status))
2828                 goto done;
2829 
2830         /* This should never be called or scheduled if there is currently
2831          * a scan active in the hardware. */
2832         if (test_bit(STATUS_SCAN_HW, &priv->status)) {
2833                 IWL_DEBUG_INFO(priv, "Multiple concurrent scan requests  "
2834                                 "Ignoring second request.\n");
2835                 rc = -EIO;
2836                 goto done;
2837         }
2838 
2839         if (test_bit(STATUS_EXIT_PENDING, &priv->status)) {
2840                 IWL_DEBUG_SCAN(priv, "Aborting scan due to device shutdown\n");
2841                 goto done;
2842         }
2843 
2844         if (test_bit(STATUS_SCAN_ABORTING, &priv->status)) {
2845                 IWL_DEBUG_HC(priv,
2846                         "Scan request while abort pending. Queuing.\n");
2847                 goto done;
2848         }
2849 
2850         if (iwl_is_rfkill(priv)) {
2851                 IWL_DEBUG_HC(priv, "Aborting scan due to RF Kill activation\n");
2852                 goto done;
2853         }
2854 
2855         if (!test_bit(STATUS_READY, &priv->status)) {
2856                 IWL_DEBUG_HC(priv,
2857                         "Scan request while uninitialized. Queuing.\n");
2858                 goto done;
2859         }
2860 
2861         if (!priv->scan_bands) {
2862                 IWL_DEBUG_HC(priv, "Aborting scan due to no requested bands\n");
2863                 goto done;
2864         }
2865 
2866         if (!priv->scan) {
2867                 priv->scan = kmalloc(sizeof(struct iwl3945_scan_cmd) +
2868                                      IWL_MAX_SCAN_SIZE, GFP_KERNEL);
2869                 if (!priv->scan) {
2870                         rc = -ENOMEM;
2871                         goto done;
2872                 }
2873         }
2874         scan = priv->scan;
2875         memset(scan, 0, sizeof(struct iwl3945_scan_cmd) + IWL_MAX_SCAN_SIZE);
2876 
2877         scan->quiet_plcp_th = IWL_PLCP_QUIET_THRESH;
2878         scan->quiet_time = IWL_ACTIVE_QUIET_TIME;
2879 
2880         if (iwl_is_associated(priv)) {
2881                 u16 interval = 0;
2882                 u32 extra;
2883                 u32 suspend_time = 100;
2884                 u32 scan_suspend_time = 100;
2885                 unsigned long flags;
2886 
2887                 IWL_DEBUG_INFO(priv, "Scanning while associated...\n");
2888 
2889                 spin_lock_irqsave(&priv->lock, flags);
2890                 interval = priv->beacon_int;
2891                 spin_unlock_irqrestore(&priv->lock, flags);
2892 
2893                 scan->suspend_time = 0;
2894                 scan->max_out_time = cpu_to_le32(200 * 1024);
2895                 if (!interval)
2896                         interval = suspend_time;
2897                 /*
2898                  * suspend time format:
2899                  *  0-19: beacon interval in usec (time before exec.)
2900                  * 20-23: 0
2901                  * 24-31: number of beacons (suspend between channels)
2902                  */
2903 
2904                 extra = (suspend_time / interval) << 24;
2905                 scan_suspend_time = 0xFF0FFFFF &
2906                     (extra | ((suspend_time % interval) * 1024));
2907 
2908                 scan->suspend_time = cpu_to_le32(scan_suspend_time);
2909                 IWL_DEBUG_SCAN(priv, "suspend_time 0x%X beacon interval %d\n",
2910                                scan_suspend_time, interval);
2911         }
2912 
2913         if (priv->scan_request->n_ssids) {
2914                 int i, p = 0;
2915                 IWL_DEBUG_SCAN(priv, "Kicking off active scan\n");
2916                 for (i = 0; i < priv->scan_request->n_ssids; i++) {
2917                         /* always does wildcard anyway */
2918                         if (!priv->scan_request->ssids[i].ssid_len)
2919                                 continue;
2920                         scan->direct_scan[p].id = WLAN_EID_SSID;
2921                         scan->direct_scan[p].len =
2922                                 priv->scan_request->ssids[i].ssid_len;
2923                         memcpy(scan->direct_scan[p].ssid,
2924                                priv->scan_request->ssids[i].ssid,
2925                                priv->scan_request->ssids[i].ssid_len);
2926                         n_probes++;
2927                         p++;
2928                 }
2929                 is_active = true;
2930         } else
2931                 IWL_DEBUG_SCAN(priv, "Kicking off passive scan.\n");
2932 
2933         /* We don't build a direct scan probe request; the uCode will do
2934          * that based on the direct_mask added to each channel entry */
2935         scan->tx_cmd.tx_flags = TX_CMD_FLG_SEQ_CTL_MSK;
2936         scan->tx_cmd.sta_id = priv->hw_params.bcast_sta_id;
2937         scan->tx_cmd.stop_time.life_time = TX_CMD_LIFE_TIME_INFINITE;
2938 
2939         /* flags + rate selection */
2940 
2941         if (priv->scan_bands & BIT(IEEE80211_BAND_2GHZ)) {
2942                 scan->flags = RXON_FLG_BAND_24G_MSK | RXON_FLG_AUTO_DETECT_MSK;
2943                 scan->tx_cmd.rate = IWL_RATE_1M_PLCP;
2944                 scan->good_CRC_th = 0;
2945                 band = IEEE80211_BAND_2GHZ;
2946         } else if (priv->scan_bands & BIT(IEEE80211_BAND_5GHZ)) {
2947                 scan->tx_cmd.rate = IWL_RATE_6M_PLCP;
2948                 /*
2949                  * If active scaning is requested but a certain channel
2950                  * is marked passive, we can do active scanning if we
2951                  * detect transmissions.
2952                  */
2953                 scan->good_CRC_th = is_active ? IWL_GOOD_CRC_TH : 0;
2954                 band = IEEE80211_BAND_5GHZ;
2955         } else {
2956                 IWL_WARN(priv, "Invalid scan band count\n");
2957                 goto done;
2958         }
2959 
2960         scan->tx_cmd.len = cpu_to_le16(
2961                         iwl_fill_probe_req(priv,
2962                                 (struct ieee80211_mgmt *)scan->data,
2963                                 priv->scan_request->ie,
2964                                 priv->scan_request->ie_len,
2965                                 IWL_MAX_SCAN_SIZE - sizeof(*scan)));
2966 
2967         /* select Rx antennas */
2968         scan->flags |= iwl3945_get_antenna_flags(priv);
2969 
2970         if (iwl_is_monitor_mode(priv))
2971                 scan->filter_flags = RXON_FILTER_PROMISC_MSK;
2972 
2973         scan->channel_count =
2974                 iwl3945_get_channels_for_scan(priv, band, is_active, n_probes,
2975                         (void *)&scan->data[le16_to_cpu(scan->tx_cmd.len)]);
2976 
2977         if (scan->channel_count == 0) {
2978                 IWL_DEBUG_SCAN(priv, "channel count %d\n", scan->channel_count);
2979                 goto done;
2980         }
2981 
2982         cmd.len += le16_to_cpu(scan->tx_cmd.len) +
2983             scan->channel_count * sizeof(struct iwl3945_scan_channel);
2984         cmd.data = scan;
2985         scan->len = cpu_to_le16(cmd.len);
2986 
2987         set_bit(STATUS_SCAN_HW, &priv->status);
2988         rc = iwl_send_cmd_sync(priv, &cmd);
2989         if (rc)
2990                 goto done;
2991 
2992         queue_delayed_work(priv->workqueue, &priv->scan_check,
2993                            IWL_SCAN_CHECK_WATCHDOG);
2994 
2995         mutex_unlock(&priv->mutex);
2996         return;
2997 
2998  done:
2999         /* can not perform scan make sure we clear scanning
3000          * bits from status so next scan request can be performed.
3001          * if we dont clear scanning status bit here all next scan
3002          * will fail
3003         */
3004         clear_bit(STATUS_SCAN_HW, &priv->status);
3005         clear_bit(STATUS_SCANNING, &priv->status);
3006 
3007         /* inform mac80211 scan aborted */
3008         queue_work(priv->workqueue, &priv->scan_completed);
3009         mutex_unlock(&priv->mutex);
3010 }
3011 
3012 static void iwl3945_bg_up(struct work_struct *data)
3013 {
3014         struct iwl_priv *priv = container_of(data, struct iwl_priv, up);
3015 
3016         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
3017                 return;
3018 
3019         mutex_lock(&priv->mutex);
3020         __iwl3945_up(priv);
3021         mutex_unlock(&priv->mutex);
3022 }
3023 
3024 static void iwl3945_bg_restart(struct work_struct *data)
3025 {
3026         struct iwl_priv *priv = container_of(data, struct iwl_priv, restart);
3027 
3028         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
3029                 return;
3030 
3031         if (test_and_clear_bit(STATUS_FW_ERROR, &priv->status)) {
3032                 mutex_lock(&priv->mutex);
3033                 priv->vif = NULL;
3034                 priv->is_open = 0;
3035                 mutex_unlock(&priv->mutex);
3036                 iwl3945_down(priv);
3037                 ieee80211_restart_hw(priv->hw);
3038         } else {
3039                 iwl3945_down(priv);
3040                 queue_work(priv->workqueue, &priv->up);
3041         }
3042 }
3043 
3044 static void iwl3945_bg_rx_replenish(struct work_struct *data)
3045 {
3046         struct iwl_priv *priv =
3047             container_of(data, struct iwl_priv, rx_replenish);
3048 
3049         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
3050                 return;
3051 
3052         mutex_lock(&priv->mutex);
3053         iwl3945_rx_replenish(priv);
3054         mutex_unlock(&priv->mutex);
3055 }
3056 
3057 #define IWL_DELAY_NEXT_SCAN (HZ*2)
3058 
3059 void iwl3945_post_associate(struct iwl_priv *priv)
3060 {
3061         int rc = 0;
3062         struct ieee80211_conf *conf = NULL;
3063 
3064         if (priv->iw_mode == NL80211_IFTYPE_AP) {
3065                 IWL_ERR(priv, "%s Should not be called in AP mode\n", __func__);
3066                 return;
3067         }
3068 
3069 
3070         IWL_DEBUG_ASSOC(priv, "Associated as %d to: %pM\n",
3071                         priv->assoc_id, priv->active_rxon.bssid_addr);
3072 
3073         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
3074                 return;
3075 
3076         if (!priv->vif || !priv->is_open)
3077                 return;
3078 
3079         iwl_scan_cancel_timeout(priv, 200);
3080 
3081         conf = ieee80211_get_hw_conf(priv->hw);
3082 
3083         priv->staging_rxon.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
3084         iwlcore_commit_rxon(priv);
3085 
3086         memset(&priv->rxon_timing, 0, sizeof(struct iwl_rxon_time_cmd));
3087         iwl3945_setup_rxon_timing(priv);
3088         rc = iwl_send_cmd_pdu(priv, REPLY_RXON_TIMING,
3089                               sizeof(priv->rxon_timing), &priv->rxon_timing);
3090         if (rc)
3091                 IWL_WARN(priv, "REPLY_RXON_TIMING failed - "
3092                             "Attempting to continue.\n");
3093 
3094         priv->staging_rxon.filter_flags |= RXON_FILTER_ASSOC_MSK;
3095 
3096         priv->staging_rxon.assoc_id = cpu_to_le16(priv->assoc_id);
3097 
3098         IWL_DEBUG_ASSOC(priv, "assoc id %d beacon interval %d\n",