Merge branch 'for_linus' of git://git.kernel.org/pub/scm/linux/kernel/git/tytso/ext4
[sfrench/cifs-2.6.git] / drivers / net / wireless / iwlwifi / iwl3945-base.c
1 /******************************************************************************
2  *
3  * Copyright(c) 2003 - 2009 Intel Corporation. All rights reserved.
4  *
5  * Portions of this file are derived from the ipw3945 project, as well
6  * as portions of the ieee80211 subsystem header files.
7  *
8  * This program is free software; you can redistribute it and/or modify it
9  * under the terms of version 2 of the GNU General Public License as
10  * published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
15  * more details.
16  *
17  * You should have received a copy of the GNU General Public License along with
18  * this program; if not, write to the Free Software Foundation, Inc.,
19  * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
20  *
21  * The full GNU General Public License is included in this distribution in the
22  * file called LICENSE.
23  *
24  * Contact Information:
25  *  Intel Linux Wireless <ilw@linux.intel.com>
26  * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
27  *
28  *****************************************************************************/
29
30 #include <linux/kernel.h>
31 #include <linux/module.h>
32 #include <linux/init.h>
33 #include <linux/pci.h>
34 #include <linux/dma-mapping.h>
35 #include <linux/delay.h>
36 #include <linux/skbuff.h>
37 #include <linux/netdevice.h>
38 #include <linux/wireless.h>
39 #include <linux/firmware.h>
40 #include <linux/etherdevice.h>
41 #include <linux/if_arp.h>
42
43 #include <net/ieee80211_radiotap.h>
44 #include <net/lib80211.h>
45 #include <net/mac80211.h>
46
47 #include <asm/div64.h>
48
49 #define DRV_NAME        "iwl3945"
50
51 #include "iwl-fh.h"
52 #include "iwl-3945-fh.h"
53 #include "iwl-commands.h"
54 #include "iwl-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 /*************** STATION TABLE MANAGEMENT ****
99  * mac80211 should be examined to determine if sta_info is duplicating
100  * the functionality provided here
101  */
102
103 /**************************************************************/
104 #if 0 /* temporary disable till we add real remove station */
105 /**
106  * iwl3945_remove_station - Remove driver's knowledge of station.
107  *
108  * NOTE:  This does not remove station from device's station table.
109  */
110 static u8 iwl3945_remove_station(struct iwl_priv *priv, const u8 *addr, int is_ap)
111 {
112         int index = IWL_INVALID_STATION;
113         int i;
114         unsigned long flags;
115
116         spin_lock_irqsave(&priv->sta_lock, flags);
117
118         if (is_ap)
119                 index = IWL_AP_ID;
120         else if (is_broadcast_ether_addr(addr))
121                 index = priv->hw_params.bcast_sta_id;
122         else
123                 for (i = IWL_STA_ID; i < priv->hw_params.max_stations; i++)
124                         if (priv->stations_39[i].used &&
125                             !compare_ether_addr(priv->stations_39[i].sta.sta.addr,
126                                                 addr)) {
127                                 index = i;
128                                 break;
129                         }
130
131         if (unlikely(index == IWL_INVALID_STATION))
132                 goto out;
133
134         if (priv->stations_39[index].used) {
135                 priv->stations_39[index].used = 0;
136                 priv->num_stations--;
137         }
138
139         BUG_ON(priv->num_stations < 0);
140
141 out:
142         spin_unlock_irqrestore(&priv->sta_lock, flags);
143         return 0;
144 }
145 #endif
146
147 /**
148  * iwl3945_clear_stations_table - Clear the driver's station table
149  *
150  * NOTE:  This does not clear or otherwise alter the device's station table.
151  */
152 static void iwl3945_clear_stations_table(struct iwl_priv *priv)
153 {
154         unsigned long flags;
155
156         spin_lock_irqsave(&priv->sta_lock, flags);
157
158         priv->num_stations = 0;
159         memset(priv->stations_39, 0, sizeof(priv->stations_39));
160
161         spin_unlock_irqrestore(&priv->sta_lock, flags);
162 }
163
164 /**
165  * iwl3945_add_station - Add station to station tables in driver and device
166  */
167 u8 iwl3945_add_station(struct iwl_priv *priv, const u8 *addr, int is_ap, u8 flags)
168 {
169         int i;
170         int index = IWL_INVALID_STATION;
171         struct iwl3945_station_entry *station;
172         unsigned long flags_spin;
173         u8 rate;
174
175         spin_lock_irqsave(&priv->sta_lock, flags_spin);
176         if (is_ap)
177                 index = IWL_AP_ID;
178         else if (is_broadcast_ether_addr(addr))
179                 index = priv->hw_params.bcast_sta_id;
180         else
181                 for (i = IWL_STA_ID; i < priv->hw_params.max_stations; i++) {
182                         if (!compare_ether_addr(priv->stations_39[i].sta.sta.addr,
183                                                 addr)) {
184                                 index = i;
185                                 break;
186                         }
187
188                         if (!priv->stations_39[i].used &&
189                             index == IWL_INVALID_STATION)
190                                 index = i;
191                 }
192
193         /* These two conditions has the same outcome but keep them separate
194           since they have different meaning */
195         if (unlikely(index == IWL_INVALID_STATION)) {
196                 spin_unlock_irqrestore(&priv->sta_lock, flags_spin);
197                 return index;
198         }
199
200         if (priv->stations_39[index].used &&
201            !compare_ether_addr(priv->stations_39[index].sta.sta.addr, addr)) {
202                 spin_unlock_irqrestore(&priv->sta_lock, flags_spin);
203                 return index;
204         }
205
206         IWL_DEBUG_ASSOC(priv, "Add STA ID %d: %pM\n", index, addr);
207         station = &priv->stations_39[index];
208         station->used = 1;
209         priv->num_stations++;
210
211         /* Set up the REPLY_ADD_STA command to send to device */
212         memset(&station->sta, 0, sizeof(struct iwl3945_addsta_cmd));
213         memcpy(station->sta.sta.addr, addr, ETH_ALEN);
214         station->sta.mode = 0;
215         station->sta.sta.sta_id = index;
216         station->sta.station_flags = 0;
217
218         if (priv->band == IEEE80211_BAND_5GHZ)
219                 rate = IWL_RATE_6M_PLCP;
220         else
221                 rate =  IWL_RATE_1M_PLCP;
222
223         /* Turn on both antennas for the station... */
224         station->sta.rate_n_flags =
225                         iwl3945_hw_set_rate_n_flags(rate, RATE_MCS_ANT_AB_MSK);
226
227         spin_unlock_irqrestore(&priv->sta_lock, flags_spin);
228
229         /* Add station to device's station table */
230         iwl_send_add_sta(priv,
231                          (struct iwl_addsta_cmd *)&station->sta, flags);
232         return index;
233
234 }
235
236 static int iwl3945_send_rxon_assoc(struct iwl_priv *priv)
237 {
238         int rc = 0;
239         struct iwl_rx_packet *res = NULL;
240         struct iwl3945_rxon_assoc_cmd rxon_assoc;
241         struct iwl_host_cmd cmd = {
242                 .id = REPLY_RXON_ASSOC,
243                 .len = sizeof(rxon_assoc),
244                 .meta.flags = CMD_WANT_SKB,
245                 .data = &rxon_assoc,
246         };
247         const struct iwl_rxon_cmd *rxon1 = &priv->staging_rxon;
248         const struct iwl_rxon_cmd *rxon2 = &priv->active_rxon;
249
250         if ((rxon1->flags == rxon2->flags) &&
251             (rxon1->filter_flags == rxon2->filter_flags) &&
252             (rxon1->cck_basic_rates == rxon2->cck_basic_rates) &&
253             (rxon1->ofdm_basic_rates == rxon2->ofdm_basic_rates)) {
254                 IWL_DEBUG_INFO(priv, "Using current RXON_ASSOC.  Not resending.\n");
255                 return 0;
256         }
257
258         rxon_assoc.flags = priv->staging_rxon.flags;
259         rxon_assoc.filter_flags = priv->staging_rxon.filter_flags;
260         rxon_assoc.ofdm_basic_rates = priv->staging_rxon.ofdm_basic_rates;
261         rxon_assoc.cck_basic_rates = priv->staging_rxon.cck_basic_rates;
262         rxon_assoc.reserved = 0;
263
264         rc = iwl_send_cmd_sync(priv, &cmd);
265         if (rc)
266                 return rc;
267
268         res = (struct iwl_rx_packet *)cmd.meta.u.skb->data;
269         if (res->hdr.flags & IWL_CMD_FAILED_MSK) {
270                 IWL_ERR(priv, "Bad return from REPLY_RXON_ASSOC command\n");
271                 rc = -EIO;
272         }
273
274         priv->alloc_rxb_skb--;
275         dev_kfree_skb_any(cmd.meta.u.skb);
276
277         return rc;
278 }
279
280 /**
281  * iwl3945_get_antenna_flags - Get antenna flags for RXON command
282  * @priv: eeprom and antenna fields are used to determine antenna flags
283  *
284  * priv->eeprom39  is used to determine if antenna AUX/MAIN are reversed
285  * iwl3945_mod_params.antenna specifies the antenna diversity mode:
286  *
287  * IWL_ANTENNA_DIVERSITY - NIC selects best antenna by itself
288  * IWL_ANTENNA_MAIN      - Force MAIN antenna
289  * IWL_ANTENNA_AUX       - Force AUX antenna
290  */
291 __le32 iwl3945_get_antenna_flags(const struct iwl_priv *priv)
292 {
293         struct iwl3945_eeprom *eeprom = (struct iwl3945_eeprom *)priv->eeprom;
294
295         switch (iwl3945_mod_params.antenna) {
296         case IWL_ANTENNA_DIVERSITY:
297                 return 0;
298
299         case IWL_ANTENNA_MAIN:
300                 if (eeprom->antenna_switch_type)
301                         return RXON_FLG_DIS_DIV_MSK | RXON_FLG_ANT_B_MSK;
302                 return RXON_FLG_DIS_DIV_MSK | RXON_FLG_ANT_A_MSK;
303
304         case IWL_ANTENNA_AUX:
305                 if (eeprom->antenna_switch_type)
306                         return RXON_FLG_DIS_DIV_MSK | RXON_FLG_ANT_A_MSK;
307                 return RXON_FLG_DIS_DIV_MSK | RXON_FLG_ANT_B_MSK;
308         }
309
310         /* bad antenna selector value */
311         IWL_ERR(priv, "Bad antenna selector value (0x%x)\n",
312                 iwl3945_mod_params.antenna);
313
314         return 0;               /* "diversity" is default if error */
315 }
316
317 /**
318  * iwl3945_commit_rxon - commit staging_rxon to hardware
319  *
320  * The RXON command in staging_rxon is committed to the hardware and
321  * the active_rxon structure is updated with the new data.  This
322  * function correctly transitions out of the RXON_ASSOC_MSK state if
323  * a HW tune is required based on the RXON structure changes.
324  */
325 static int iwl3945_commit_rxon(struct iwl_priv *priv)
326 {
327         /* cast away the const for active_rxon in this function */
328         struct iwl3945_rxon_cmd *active_rxon = (void *)&priv->active_rxon;
329         struct iwl3945_rxon_cmd *staging_rxon = (void *)&priv->staging_rxon;
330         int rc = 0;
331         bool new_assoc =
332                 !!(priv->staging_rxon.filter_flags & RXON_FILTER_ASSOC_MSK);
333
334         if (!iwl_is_alive(priv))
335                 return -1;
336
337         /* always get timestamp with Rx frame */
338         staging_rxon->flags |= RXON_FLG_TSF2HOST_MSK;
339
340         /* select antenna */
341         staging_rxon->flags &=
342             ~(RXON_FLG_DIS_DIV_MSK | RXON_FLG_ANT_SEL_MSK);
343         staging_rxon->flags |= iwl3945_get_antenna_flags(priv);
344
345         rc = iwl_check_rxon_cmd(priv);
346         if (rc) {
347                 IWL_ERR(priv, "Invalid RXON configuration.  Not committing.\n");
348                 return -EINVAL;
349         }
350
351         /* If we don't need to send a full RXON, we can use
352          * iwl3945_rxon_assoc_cmd which is used to reconfigure filter
353          * and other flags for the current radio configuration. */
354         if (!iwl_full_rxon_required(priv)) {
355                 rc = iwl3945_send_rxon_assoc(priv);
356                 if (rc) {
357                         IWL_ERR(priv, "Error setting RXON_ASSOC "
358                                   "configuration (%d).\n", rc);
359                         return rc;
360                 }
361
362                 memcpy(active_rxon, staging_rxon, sizeof(*active_rxon));
363
364                 return 0;
365         }
366
367         /* If we are currently associated and the new config requires
368          * an RXON_ASSOC and the new config wants the associated mask enabled,
369          * we must clear the associated from the active configuration
370          * before we apply the new config */
371         if (iwl_is_associated(priv) && new_assoc) {
372                 IWL_DEBUG_INFO(priv, "Toggling associated bit on current RXON\n");
373                 active_rxon->filter_flags &= ~RXON_FILTER_ASSOC_MSK;
374
375                 /*
376                  * reserved4 and 5 could have been filled by the iwlcore code.
377                  * Let's clear them before pushing to the 3945.
378                  */
379                 active_rxon->reserved4 = 0;
380                 active_rxon->reserved5 = 0;
381                 rc = iwl_send_cmd_pdu(priv, REPLY_RXON,
382                                       sizeof(struct iwl3945_rxon_cmd),
383                                       &priv->active_rxon);
384
385                 /* If the mask clearing failed then we set
386                  * active_rxon back to what it was previously */
387                 if (rc) {
388                         active_rxon->filter_flags |= RXON_FILTER_ASSOC_MSK;
389                         IWL_ERR(priv, "Error clearing ASSOC_MSK on current "
390                                   "configuration (%d).\n", rc);
391                         return rc;
392                 }
393         }
394
395         IWL_DEBUG_INFO(priv, "Sending RXON\n"
396                        "* with%s RXON_FILTER_ASSOC_MSK\n"
397                        "* channel = %d\n"
398                        "* bssid = %pM\n",
399                        (new_assoc ? "" : "out"),
400                        le16_to_cpu(staging_rxon->channel),
401                        staging_rxon->bssid_addr);
402
403         /*
404          * reserved4 and 5 could have been filled by the iwlcore code.
405          * Let's clear them before pushing to the 3945.
406          */
407         staging_rxon->reserved4 = 0;
408         staging_rxon->reserved5 = 0;
409
410         iwl_set_rxon_hwcrypto(priv, !priv->hw_params.sw_crypto);
411
412         /* Apply the new configuration */
413         rc = iwl_send_cmd_pdu(priv, REPLY_RXON,
414                               sizeof(struct iwl3945_rxon_cmd),
415                               staging_rxon);
416         if (rc) {
417                 IWL_ERR(priv, "Error setting new configuration (%d).\n", rc);
418                 return rc;
419         }
420
421         memcpy(active_rxon, staging_rxon, sizeof(*active_rxon));
422
423         iwl3945_clear_stations_table(priv);
424
425         /* If we issue a new RXON command which required a tune then we must
426          * send a new TXPOWER command or we won't be able to Tx any frames */
427         rc = priv->cfg->ops->lib->send_tx_power(priv);
428         if (rc) {
429                 IWL_ERR(priv, "Error setting Tx power (%d).\n", rc);
430                 return rc;
431         }
432
433         /* Add the broadcast address so we can send broadcast frames */
434         if (iwl3945_add_station(priv, iwl_bcast_addr, 0, 0) ==
435             IWL_INVALID_STATION) {
436                 IWL_ERR(priv, "Error adding BROADCAST address for transmit.\n");
437                 return -EIO;
438         }
439
440         /* If we have set the ASSOC_MSK and we are in BSS mode then
441          * add the IWL_AP_ID to the station rate table */
442         if (iwl_is_associated(priv) &&
443             (priv->iw_mode == NL80211_IFTYPE_STATION))
444                 if (iwl3945_add_station(priv, priv->active_rxon.bssid_addr,
445                                         1, 0)
446                     == IWL_INVALID_STATION) {
447                         IWL_ERR(priv, "Error adding AP address for transmit\n");
448                         return -EIO;
449                 }
450
451         /* Init the hardware's rate fallback order based on the band */
452         rc = iwl3945_init_hw_rate_table(priv);
453         if (rc) {
454                 IWL_ERR(priv, "Error setting HW rate table: %02X\n", rc);
455                 return -EIO;
456         }
457
458         return 0;
459 }
460
461 static int iwl3945_set_ccmp_dynamic_key_info(struct iwl_priv *priv,
462                                    struct ieee80211_key_conf *keyconf,
463                                    u8 sta_id)
464 {
465         unsigned long flags;
466         __le16 key_flags = 0;
467         int ret;
468
469         key_flags |= (STA_KEY_FLG_CCMP | STA_KEY_FLG_MAP_KEY_MSK);
470         key_flags |= cpu_to_le16(keyconf->keyidx << STA_KEY_FLG_KEYID_POS);
471
472         if (sta_id == priv->hw_params.bcast_sta_id)
473                 key_flags |= STA_KEY_MULTICAST_MSK;
474
475         keyconf->flags |= IEEE80211_KEY_FLAG_GENERATE_IV;
476         keyconf->hw_key_idx = keyconf->keyidx;
477         key_flags &= ~STA_KEY_FLG_INVALID;
478
479         spin_lock_irqsave(&priv->sta_lock, flags);
480         priv->stations_39[sta_id].keyinfo.alg = keyconf->alg;
481         priv->stations_39[sta_id].keyinfo.keylen = keyconf->keylen;
482         memcpy(priv->stations_39[sta_id].keyinfo.key, keyconf->key,
483                keyconf->keylen);
484
485         memcpy(priv->stations_39[sta_id].sta.key.key, keyconf->key,
486                keyconf->keylen);
487
488         if ((priv->stations_39[sta_id].sta.key.key_flags & STA_KEY_FLG_ENCRYPT_MSK)
489                         == STA_KEY_FLG_NO_ENC)
490                 priv->stations_39[sta_id].sta.key.key_offset =
491                                  iwl_get_free_ucode_key_index(priv);
492         /* else, we are overriding an existing key => no need to allocated room
493         * in uCode. */
494
495         WARN(priv->stations_39[sta_id].sta.key.key_offset == WEP_INVALID_OFFSET,
496                 "no space for a new key");
497
498         priv->stations_39[sta_id].sta.key.key_flags = key_flags;
499         priv->stations_39[sta_id].sta.sta.modify_mask = STA_MODIFY_KEY_MASK;
500         priv->stations_39[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
501
502         IWL_DEBUG_INFO(priv, "hwcrypto: modify ucode station key info\n");
503
504         ret = iwl_send_add_sta(priv,
505                 (struct iwl_addsta_cmd *)&priv->stations_39[sta_id].sta, CMD_ASYNC);
506
507         spin_unlock_irqrestore(&priv->sta_lock, flags);
508
509         return ret;
510 }
511
512 static int iwl3945_set_tkip_dynamic_key_info(struct iwl_priv *priv,
513                                   struct ieee80211_key_conf *keyconf,
514                                   u8 sta_id)
515 {
516         return -EOPNOTSUPP;
517 }
518
519 static int iwl3945_set_wep_dynamic_key_info(struct iwl_priv *priv,
520                                   struct ieee80211_key_conf *keyconf,
521                                   u8 sta_id)
522 {
523         return -EOPNOTSUPP;
524 }
525
526 static int iwl3945_clear_sta_key_info(struct iwl_priv *priv, u8 sta_id)
527 {
528         unsigned long flags;
529
530         spin_lock_irqsave(&priv->sta_lock, flags);
531         memset(&priv->stations_39[sta_id].keyinfo, 0, sizeof(struct iwl3945_hw_key));
532         memset(&priv->stations_39[sta_id].sta.key, 0,
533                 sizeof(struct iwl4965_keyinfo));
534         priv->stations_39[sta_id].sta.key.key_flags = STA_KEY_FLG_NO_ENC;
535         priv->stations_39[sta_id].sta.sta.modify_mask = STA_MODIFY_KEY_MASK;
536         priv->stations_39[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
537         spin_unlock_irqrestore(&priv->sta_lock, flags);
538
539         IWL_DEBUG_INFO(priv, "hwcrypto: clear ucode station key info\n");
540         iwl_send_add_sta(priv,
541                 (struct iwl_addsta_cmd *)&priv->stations_39[sta_id].sta, 0);
542         return 0;
543 }
544
545 static int iwl3945_set_dynamic_key(struct iwl_priv *priv,
546                         struct ieee80211_key_conf *keyconf, u8 sta_id)
547 {
548         int ret = 0;
549
550         keyconf->hw_key_idx = HW_KEY_DYNAMIC;
551
552         switch (keyconf->alg) {
553         case ALG_CCMP:
554                 ret = iwl3945_set_ccmp_dynamic_key_info(priv, keyconf, sta_id);
555                 break;
556         case ALG_TKIP:
557                 ret = iwl3945_set_tkip_dynamic_key_info(priv, keyconf, sta_id);
558                 break;
559         case ALG_WEP:
560                 ret = iwl3945_set_wep_dynamic_key_info(priv, keyconf, sta_id);
561                 break;
562         default:
563                 IWL_ERR(priv, "Unknown alg: %s alg = %d\n", __func__, keyconf->alg);
564                 ret = -EINVAL;
565         }
566
567         IWL_DEBUG_WEP(priv, "Set dynamic key: alg= %d len=%d idx=%d sta=%d ret=%d\n",
568                       keyconf->alg, keyconf->keylen, keyconf->keyidx,
569                       sta_id, ret);
570
571         return ret;
572 }
573
574 static int iwl3945_remove_static_key(struct iwl_priv *priv)
575 {
576         int ret = -EOPNOTSUPP;
577
578         return ret;
579 }
580
581 static int iwl3945_set_static_key(struct iwl_priv *priv,
582                                 struct ieee80211_key_conf *key)
583 {
584         if (key->alg == ALG_WEP)
585                 return -EOPNOTSUPP;
586
587         IWL_ERR(priv, "Static key invalid: alg %d\n", key->alg);
588         return -EINVAL;
589 }
590
591 static void iwl3945_clear_free_frames(struct iwl_priv *priv)
592 {
593         struct list_head *element;
594
595         IWL_DEBUG_INFO(priv, "%d frames on pre-allocated heap on clear.\n",
596                        priv->frames_count);
597
598         while (!list_empty(&priv->free_frames)) {
599                 element = priv->free_frames.next;
600                 list_del(element);
601                 kfree(list_entry(element, struct iwl3945_frame, list));
602                 priv->frames_count--;
603         }
604
605         if (priv->frames_count) {
606                 IWL_WARN(priv, "%d frames still in use.  Did we lose one?\n",
607                             priv->frames_count);
608                 priv->frames_count = 0;
609         }
610 }
611
612 static struct iwl3945_frame *iwl3945_get_free_frame(struct iwl_priv *priv)
613 {
614         struct iwl3945_frame *frame;
615         struct list_head *element;
616         if (list_empty(&priv->free_frames)) {
617                 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
618                 if (!frame) {
619                         IWL_ERR(priv, "Could not allocate frame!\n");
620                         return NULL;
621                 }
622
623                 priv->frames_count++;
624                 return frame;
625         }
626
627         element = priv->free_frames.next;
628         list_del(element);
629         return list_entry(element, struct iwl3945_frame, list);
630 }
631
632 static void iwl3945_free_frame(struct iwl_priv *priv, struct iwl3945_frame *frame)
633 {
634         memset(frame, 0, sizeof(*frame));
635         list_add(&frame->list, &priv->free_frames);
636 }
637
638 unsigned int iwl3945_fill_beacon_frame(struct iwl_priv *priv,
639                                 struct ieee80211_hdr *hdr,
640                                 int left)
641 {
642
643         if (!iwl_is_associated(priv) || !priv->ibss_beacon ||
644             ((priv->iw_mode != NL80211_IFTYPE_ADHOC) &&
645              (priv->iw_mode != NL80211_IFTYPE_AP)))
646                 return 0;
647
648         if (priv->ibss_beacon->len > left)
649                 return 0;
650
651         memcpy(hdr, priv->ibss_beacon->data, priv->ibss_beacon->len);
652
653         return priv->ibss_beacon->len;
654 }
655
656 static int iwl3945_send_beacon_cmd(struct iwl_priv *priv)
657 {
658         struct iwl3945_frame *frame;
659         unsigned int frame_size;
660         int rc;
661         u8 rate;
662
663         frame = iwl3945_get_free_frame(priv);
664
665         if (!frame) {
666                 IWL_ERR(priv, "Could not obtain free frame buffer for beacon "
667                           "command.\n");
668                 return -ENOMEM;
669         }
670
671         rate = iwl_rate_get_lowest_plcp(priv);
672
673         frame_size = iwl3945_hw_get_beacon_cmd(priv, frame, rate);
674
675         rc = iwl_send_cmd_pdu(priv, REPLY_TX_BEACON, frame_size,
676                               &frame->u.cmd[0]);
677
678         iwl3945_free_frame(priv, frame);
679
680         return rc;
681 }
682
683 static void iwl3945_unset_hw_params(struct iwl_priv *priv)
684 {
685         if (priv->shared_virt)
686                 pci_free_consistent(priv->pci_dev,
687                                     sizeof(struct iwl3945_shared),
688                                     priv->shared_virt,
689                                     priv->shared_phys);
690 }
691
692 #define MAX_UCODE_BEACON_INTERVAL       1024
693 #define INTEL_CONN_LISTEN_INTERVAL      cpu_to_le16(0xA)
694
695 static __le16 iwl3945_adjust_beacon_interval(u16 beacon_val)
696 {
697         u16 new_val = 0;
698         u16 beacon_factor = 0;
699
700         beacon_factor =
701             (beacon_val + MAX_UCODE_BEACON_INTERVAL)
702                 / MAX_UCODE_BEACON_INTERVAL;
703         new_val = beacon_val / beacon_factor;
704
705         return cpu_to_le16(new_val);
706 }
707
708 static void iwl3945_setup_rxon_timing(struct iwl_priv *priv)
709 {
710         u64 interval_tm_unit;
711         u64 tsf, result;
712         unsigned long flags;
713         struct ieee80211_conf *conf = NULL;
714         u16 beacon_int = 0;
715
716         conf = ieee80211_get_hw_conf(priv->hw);
717
718         spin_lock_irqsave(&priv->lock, flags);
719         priv->rxon_timing.timestamp = cpu_to_le64(priv->timestamp);
720         priv->rxon_timing.listen_interval = INTEL_CONN_LISTEN_INTERVAL;
721
722         tsf = priv->timestamp;
723
724         beacon_int = priv->beacon_int;
725         spin_unlock_irqrestore(&priv->lock, flags);
726
727         if (priv->iw_mode == NL80211_IFTYPE_STATION) {
728                 if (beacon_int == 0) {
729                         priv->rxon_timing.beacon_interval = cpu_to_le16(100);
730                         priv->rxon_timing.beacon_init_val = cpu_to_le32(102400);
731                 } else {
732                         priv->rxon_timing.beacon_interval =
733                                 cpu_to_le16(beacon_int);
734                         priv->rxon_timing.beacon_interval =
735                             iwl3945_adjust_beacon_interval(
736                                 le16_to_cpu(priv->rxon_timing.beacon_interval));
737                 }
738
739                 priv->rxon_timing.atim_window = 0;
740         } else {
741                 priv->rxon_timing.beacon_interval =
742                         iwl3945_adjust_beacon_interval(conf->beacon_int);
743                 /* TODO: we need to get atim_window from upper stack
744                  * for now we set to 0 */
745                 priv->rxon_timing.atim_window = 0;
746         }
747
748         interval_tm_unit =
749                 (le16_to_cpu(priv->rxon_timing.beacon_interval) * 1024);
750         result = do_div(tsf, interval_tm_unit);
751         priv->rxon_timing.beacon_init_val =
752             cpu_to_le32((u32) ((u64) interval_tm_unit - result));
753
754         IWL_DEBUG_ASSOC(priv,
755                 "beacon interval %d beacon timer %d beacon tim %d\n",
756                 le16_to_cpu(priv->rxon_timing.beacon_interval),
757                 le32_to_cpu(priv->rxon_timing.beacon_init_val),
758                 le16_to_cpu(priv->rxon_timing.atim_window));
759 }
760
761 static int iwl3945_set_mode(struct iwl_priv *priv, int mode)
762 {
763         if (mode == NL80211_IFTYPE_ADHOC) {
764                 const struct iwl_channel_info *ch_info;
765
766                 ch_info = iwl_get_channel_info(priv,
767                         priv->band,
768                         le16_to_cpu(priv->staging_rxon.channel));
769
770                 if (!ch_info || !is_channel_ibss(ch_info)) {
771                         IWL_ERR(priv, "channel %d not IBSS channel\n",
772                                   le16_to_cpu(priv->staging_rxon.channel));
773                         return -EINVAL;
774                 }
775         }
776
777         iwl_connection_init_rx_config(priv, mode);
778
779         iwl3945_clear_stations_table(priv);
780
781         /* don't commit rxon if rf-kill is on*/
782         if (!iwl_is_ready_rf(priv))
783                 return -EAGAIN;
784
785         cancel_delayed_work(&priv->scan_check);
786         if (iwl_scan_cancel_timeout(priv, 100)) {
787                 IWL_WARN(priv, "Aborted scan still in progress after 100ms\n");
788                 IWL_DEBUG_MAC80211(priv, "leaving - scan abort failed.\n");
789                 return -EAGAIN;
790         }
791
792         iwl3945_commit_rxon(priv);
793
794         return 0;
795 }
796
797 static void iwl3945_build_tx_cmd_hwcrypto(struct iwl_priv *priv,
798                                       struct ieee80211_tx_info *info,
799                                       struct iwl_cmd *cmd,
800                                       struct sk_buff *skb_frag,
801                                       int sta_id)
802 {
803         struct iwl3945_tx_cmd *tx = (struct iwl3945_tx_cmd *)cmd->cmd.payload;
804         struct iwl3945_hw_key *keyinfo =
805             &priv->stations_39[sta_id].keyinfo;
806
807         switch (keyinfo->alg) {
808         case ALG_CCMP:
809                 tx->sec_ctl = TX_CMD_SEC_CCM;
810                 memcpy(tx->key, keyinfo->key, keyinfo->keylen);
811                 IWL_DEBUG_TX(priv, "tx_cmd with AES hwcrypto\n");
812                 break;
813
814         case ALG_TKIP:
815                 break;
816
817         case ALG_WEP:
818                 tx->sec_ctl = TX_CMD_SEC_WEP |
819                     (info->control.hw_key->hw_key_idx & TX_CMD_SEC_MSK) << TX_CMD_SEC_SHIFT;
820
821                 if (keyinfo->keylen == 13)
822                         tx->sec_ctl |= TX_CMD_SEC_KEY128;
823
824                 memcpy(&tx->key[3], keyinfo->key, keyinfo->keylen);
825
826                 IWL_DEBUG_TX(priv, "Configuring packet for WEP encryption "
827                              "with key %d\n", info->control.hw_key->hw_key_idx);
828                 break;
829
830         default:
831                 IWL_ERR(priv, "Unknown encode alg %d\n", keyinfo->alg);
832                 break;
833         }
834 }
835
836 /*
837  * handle build REPLY_TX command notification.
838  */
839 static void iwl3945_build_tx_cmd_basic(struct iwl_priv *priv,
840                                   struct iwl_cmd *cmd,
841                                   struct ieee80211_tx_info *info,
842                                   struct ieee80211_hdr *hdr, u8 std_id)
843 {
844         struct iwl3945_tx_cmd *tx = (struct iwl3945_tx_cmd *)cmd->cmd.payload;
845         __le32 tx_flags = tx->tx_flags;
846         __le16 fc = hdr->frame_control;
847         u8 rc_flags = info->control.rates[0].flags;
848
849         tx->stop_time.life_time = TX_CMD_LIFE_TIME_INFINITE;
850         if (!(info->flags & IEEE80211_TX_CTL_NO_ACK)) {
851                 tx_flags |= TX_CMD_FLG_ACK_MSK;
852                 if (ieee80211_is_mgmt(fc))
853                         tx_flags |= TX_CMD_FLG_SEQ_CTL_MSK;
854                 if (ieee80211_is_probe_resp(fc) &&
855                     !(le16_to_cpu(hdr->seq_ctrl) & 0xf))
856                         tx_flags |= TX_CMD_FLG_TSF_MSK;
857         } else {
858                 tx_flags &= (~TX_CMD_FLG_ACK_MSK);
859                 tx_flags |= TX_CMD_FLG_SEQ_CTL_MSK;
860         }
861
862         tx->sta_id = std_id;
863         if (ieee80211_has_morefrags(fc))
864                 tx_flags |= TX_CMD_FLG_MORE_FRAG_MSK;
865
866         if (ieee80211_is_data_qos(fc)) {
867                 u8 *qc = ieee80211_get_qos_ctl(hdr);
868                 tx->tid_tspec = qc[0] & 0xf;
869                 tx_flags &= ~TX_CMD_FLG_SEQ_CTL_MSK;
870         } else {
871                 tx_flags |= TX_CMD_FLG_SEQ_CTL_MSK;
872         }
873
874         if (rc_flags & IEEE80211_TX_RC_USE_RTS_CTS) {
875                 tx_flags |= TX_CMD_FLG_RTS_MSK;
876                 tx_flags &= ~TX_CMD_FLG_CTS_MSK;
877         } else if (rc_flags & IEEE80211_TX_RC_USE_CTS_PROTECT) {
878                 tx_flags &= ~TX_CMD_FLG_RTS_MSK;
879                 tx_flags |= TX_CMD_FLG_CTS_MSK;
880         }
881
882         if ((tx_flags & TX_CMD_FLG_RTS_MSK) || (tx_flags & TX_CMD_FLG_CTS_MSK))
883                 tx_flags |= TX_CMD_FLG_FULL_TXOP_PROT_MSK;
884
885         tx_flags &= ~(TX_CMD_FLG_ANT_SEL_MSK);
886         if (ieee80211_is_mgmt(fc)) {
887                 if (ieee80211_is_assoc_req(fc) || ieee80211_is_reassoc_req(fc))
888                         tx->timeout.pm_frame_timeout = cpu_to_le16(3);
889                 else
890                         tx->timeout.pm_frame_timeout = cpu_to_le16(2);
891         } else {
892                 tx->timeout.pm_frame_timeout = 0;
893 #ifdef CONFIG_IWLWIFI_LEDS
894                 priv->rxtxpackets += le16_to_cpu(cmd->cmd.tx.len);
895 #endif
896         }
897
898         tx->driver_txop = 0;
899         tx->tx_flags = tx_flags;
900         tx->next_frame_len = 0;
901 }
902
903 /**
904  * iwl3945_get_sta_id - Find station's index within station table
905  */
906 static int iwl3945_get_sta_id(struct iwl_priv *priv, struct ieee80211_hdr *hdr)
907 {
908         int sta_id;
909         u16 fc = le16_to_cpu(hdr->frame_control);
910
911         /* If this frame is broadcast or management, use broadcast station id */
912         if (((fc & IEEE80211_FCTL_FTYPE) != IEEE80211_FTYPE_DATA) ||
913             is_multicast_ether_addr(hdr->addr1))
914                 return priv->hw_params.bcast_sta_id;
915
916         switch (priv->iw_mode) {
917
918         /* If we are a client station in a BSS network, use the special
919          * AP station entry (that's the only station we communicate with) */
920         case NL80211_IFTYPE_STATION:
921                 return IWL_AP_ID;
922
923         /* If we are an AP, then find the station, or use BCAST */
924         case NL80211_IFTYPE_AP:
925                 sta_id = iwl3945_hw_find_station(priv, hdr->addr1);
926                 if (sta_id != IWL_INVALID_STATION)
927                         return sta_id;
928                 return priv->hw_params.bcast_sta_id;
929
930         /* If this frame is going out to an IBSS network, find the station,
931          * or create a new station table entry */
932         case NL80211_IFTYPE_ADHOC: {
933                 /* Create new station table entry */
934                 sta_id = iwl3945_hw_find_station(priv, hdr->addr1);
935                 if (sta_id != IWL_INVALID_STATION)
936                         return sta_id;
937
938                 sta_id = iwl3945_add_station(priv, hdr->addr1, 0, CMD_ASYNC);
939
940                 if (sta_id != IWL_INVALID_STATION)
941                         return sta_id;
942
943                 IWL_DEBUG_DROP(priv, "Station %pM not in station map. "
944                                "Defaulting to broadcast...\n",
945                                hdr->addr1);
946                 iwl_print_hex_dump(priv, IWL_DL_DROP, (u8 *) hdr, sizeof(*hdr));
947                 return priv->hw_params.bcast_sta_id;
948         }
949         /* If we are in monitor mode, use BCAST. This is required for
950          * packet injection. */
951         case NL80211_IFTYPE_MONITOR:
952                 return priv->hw_params.bcast_sta_id;
953
954         default:
955                 IWL_WARN(priv, "Unknown mode of operation: %d\n",
956                         priv->iw_mode);
957                 return priv->hw_params.bcast_sta_id;
958         }
959 }
960
961 /*
962  * start REPLY_TX command process
963  */
964 static int iwl3945_tx_skb(struct iwl_priv *priv, struct sk_buff *skb)
965 {
966         struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
967         struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
968         struct iwl3945_tx_cmd *tx;
969         struct iwl_tx_queue *txq = NULL;
970         struct iwl_queue *q = NULL;
971         struct iwl_cmd *out_cmd = NULL;
972         dma_addr_t phys_addr;
973         dma_addr_t txcmd_phys;
974         int txq_id = skb_get_queue_mapping(skb);
975         u16 len, idx, len_org, hdr_len; /* TODO: len_org is not used */
976         u8 id;
977         u8 unicast;
978         u8 sta_id;
979         u8 tid = 0;
980         u16 seq_number = 0;
981         __le16 fc;
982         u8 wait_write_ptr = 0;
983         u8 *qc = NULL;
984         unsigned long flags;
985         int rc;
986
987         spin_lock_irqsave(&priv->lock, flags);
988         if (iwl_is_rfkill(priv)) {
989                 IWL_DEBUG_DROP(priv, "Dropping - RF KILL\n");
990                 goto drop_unlock;
991         }
992
993         if ((ieee80211_get_tx_rate(priv->hw, info)->hw_value & 0xFF) == IWL_INVALID_RATE) {
994                 IWL_ERR(priv, "ERROR: No TX rate available.\n");
995                 goto drop_unlock;
996         }
997
998         unicast = !is_multicast_ether_addr(hdr->addr1);
999         id = 0;
1000
1001         fc = hdr->frame_control;
1002
1003 #ifdef CONFIG_IWLWIFI_DEBUG
1004         if (ieee80211_is_auth(fc))
1005                 IWL_DEBUG_TX(priv, "Sending AUTH frame\n");
1006         else if (ieee80211_is_assoc_req(fc))
1007                 IWL_DEBUG_TX(priv, "Sending ASSOC frame\n");
1008         else if (ieee80211_is_reassoc_req(fc))
1009                 IWL_DEBUG_TX(priv, "Sending REASSOC frame\n");
1010 #endif
1011
1012         /* drop all data frame if we are not associated */
1013         if (ieee80211_is_data(fc) &&
1014             (priv->iw_mode != NL80211_IFTYPE_MONITOR) && /* packet injection */
1015             (!iwl_is_associated(priv) ||
1016              ((priv->iw_mode == NL80211_IFTYPE_STATION) && !priv->assoc_id))) {
1017                 IWL_DEBUG_DROP(priv, "Dropping - !iwl_is_associated\n");
1018                 goto drop_unlock;
1019         }
1020
1021         spin_unlock_irqrestore(&priv->lock, flags);
1022
1023         hdr_len = ieee80211_hdrlen(fc);
1024
1025         /* Find (or create) index into station table for destination station */
1026         sta_id = iwl3945_get_sta_id(priv, hdr);
1027         if (sta_id == IWL_INVALID_STATION) {
1028                 IWL_DEBUG_DROP(priv, "Dropping - INVALID STATION: %pM\n",
1029                                hdr->addr1);
1030                 goto drop;
1031         }
1032
1033         IWL_DEBUG_RATE(priv, "station Id %d\n", sta_id);
1034
1035         if (ieee80211_is_data_qos(fc)) {
1036                 qc = ieee80211_get_qos_ctl(hdr);
1037                 tid = qc[0] & IEEE80211_QOS_CTL_TID_MASK;
1038                 seq_number = priv->stations_39[sta_id].tid[tid].seq_number &
1039                                 IEEE80211_SCTL_SEQ;
1040                 hdr->seq_ctrl = cpu_to_le16(seq_number) |
1041                         (hdr->seq_ctrl &
1042                                 cpu_to_le16(IEEE80211_SCTL_FRAG));
1043                 seq_number += 0x10;
1044         }
1045
1046         /* Descriptor for chosen Tx queue */
1047         txq = &priv->txq[txq_id];
1048         q = &txq->q;
1049
1050         spin_lock_irqsave(&priv->lock, flags);
1051
1052         idx = get_cmd_index(q, q->write_ptr, 0);
1053
1054         /* Set up driver data for this TFD */
1055         memset(&(txq->txb[q->write_ptr]), 0, sizeof(struct iwl_tx_info));
1056         txq->txb[q->write_ptr].skb[0] = skb;
1057
1058         /* Init first empty entry in queue's array of Tx/cmd buffers */
1059         out_cmd = txq->cmd[idx];
1060         tx = (struct iwl3945_tx_cmd *)out_cmd->cmd.payload;
1061         memset(&out_cmd->hdr, 0, sizeof(out_cmd->hdr));
1062         memset(tx, 0, sizeof(*tx));
1063
1064         /*
1065          * Set up the Tx-command (not MAC!) header.
1066          * Store the chosen Tx queue and TFD index within the sequence field;
1067          * after Tx, uCode's Tx response will return this value so driver can
1068          * locate the frame within the tx queue and do post-tx processing.
1069          */
1070         out_cmd->hdr.cmd = REPLY_TX;
1071         out_cmd->hdr.sequence = cpu_to_le16((u16)(QUEUE_TO_SEQ(txq_id) |
1072                                 INDEX_TO_SEQ(q->write_ptr)));
1073
1074         /* Copy MAC header from skb into command buffer */
1075         memcpy(tx->hdr, hdr, hdr_len);
1076
1077
1078         if (info->control.hw_key)
1079                 iwl3945_build_tx_cmd_hwcrypto(priv, info, out_cmd, skb, sta_id);
1080
1081         /* TODO need this for burst mode later on */
1082         iwl3945_build_tx_cmd_basic(priv, out_cmd, info, hdr, sta_id);
1083
1084         /* set is_hcca to 0; it probably will never be implemented */
1085         iwl3945_hw_build_tx_cmd_rate(priv, out_cmd, info, hdr, sta_id, 0);
1086
1087         /* Total # bytes to be transmitted */
1088         len = (u16)skb->len;
1089         tx->len = cpu_to_le16(len);
1090
1091
1092         tx->tx_flags &= ~TX_CMD_FLG_ANT_A_MSK;
1093         tx->tx_flags &= ~TX_CMD_FLG_ANT_B_MSK;
1094
1095         if (!ieee80211_has_morefrags(hdr->frame_control)) {
1096                 txq->need_update = 1;
1097                 if (qc)
1098                         priv->stations_39[sta_id].tid[tid].seq_number = seq_number;
1099         } else {
1100                 wait_write_ptr = 1;
1101                 txq->need_update = 0;
1102         }
1103
1104         IWL_DEBUG_TX(priv, "sequence nr = 0X%x \n",
1105                      le16_to_cpu(out_cmd->hdr.sequence));
1106         IWL_DEBUG_TX(priv, "tx_flags = 0X%x \n", le32_to_cpu(tx->tx_flags));
1107         iwl_print_hex_dump(priv, IWL_DL_TX, tx, sizeof(*tx));
1108         iwl_print_hex_dump(priv, IWL_DL_TX, (u8 *)tx->hdr,
1109                            ieee80211_hdrlen(fc));
1110
1111         /*
1112          * Use the first empty entry in this queue's command buffer array
1113          * to contain the Tx command and MAC header concatenated together
1114          * (payload data will be in another buffer).
1115          * Size of this varies, due to varying MAC header length.
1116          * If end is not dword aligned, we'll have 2 extra bytes at the end
1117          * of the MAC header (device reads on dword boundaries).
1118          * We'll tell device about this padding later.
1119          */
1120         len = sizeof(struct iwl3945_tx_cmd) +
1121                         sizeof(struct iwl_cmd_header) + hdr_len;
1122
1123         len_org = len;
1124         len = (len + 3) & ~3;
1125
1126         if (len_org != len)
1127                 len_org = 1;
1128         else
1129                 len_org = 0;
1130
1131         /* Physical address of this Tx command's header (not MAC header!),
1132          * within command buffer array. */
1133         txcmd_phys = pci_map_single(priv->pci_dev, &out_cmd->hdr,
1134                                     len, PCI_DMA_TODEVICE);
1135         /* we do not map meta data ... so we can safely access address to
1136          * provide to unmap command*/
1137         pci_unmap_addr_set(&out_cmd->meta, mapping, txcmd_phys);
1138         pci_unmap_len_set(&out_cmd->meta, len, len);
1139
1140         /* Add buffer containing Tx command and MAC(!) header to TFD's
1141          * first entry */
1142         priv->cfg->ops->lib->txq_attach_buf_to_tfd(priv, txq,
1143                                                    txcmd_phys, len, 1, 0);
1144
1145
1146         /* Set up TFD's 2nd entry to point directly to remainder of skb,
1147          * if any (802.11 null frames have no payload). */
1148         len = skb->len - hdr_len;
1149         if (len) {
1150                 phys_addr = pci_map_single(priv->pci_dev, skb->data + hdr_len,
1151                                            len, PCI_DMA_TODEVICE);
1152                 priv->cfg->ops->lib->txq_attach_buf_to_tfd(priv, txq,
1153                                                            phys_addr, len,
1154                                                            0, U32_PAD(len));
1155         }
1156
1157
1158         /* Tell device the write index *just past* this latest filled TFD */
1159         q->write_ptr = iwl_queue_inc_wrap(q->write_ptr, q->n_bd);
1160         rc = iwl_txq_update_write_ptr(priv, txq);
1161         spin_unlock_irqrestore(&priv->lock, flags);
1162
1163         if (rc)
1164                 return rc;
1165
1166         if ((iwl_queue_space(q) < q->high_mark)
1167             && priv->mac80211_registered) {
1168                 if (wait_write_ptr) {
1169                         spin_lock_irqsave(&priv->lock, flags);
1170                         txq->need_update = 1;
1171                         iwl_txq_update_write_ptr(priv, txq);
1172                         spin_unlock_irqrestore(&priv->lock, flags);
1173                 }
1174
1175                 iwl_stop_queue(priv, skb_get_queue_mapping(skb));
1176         }
1177
1178         return 0;
1179
1180 drop_unlock:
1181         spin_unlock_irqrestore(&priv->lock, flags);
1182 drop:
1183         return -1;
1184 }
1185
1186 #ifdef CONFIG_IWL3945_SPECTRUM_MEASUREMENT
1187
1188 #include "iwl-spectrum.h"
1189
1190 #define BEACON_TIME_MASK_LOW    0x00FFFFFF
1191 #define BEACON_TIME_MASK_HIGH   0xFF000000
1192 #define TIME_UNIT               1024
1193
1194 /*
1195  * extended beacon time format
1196  * time in usec will be changed into a 32-bit value in 8:24 format
1197  * the high 1 byte is the beacon counts
1198  * the lower 3 bytes is the time in usec within one beacon interval
1199  */
1200
1201 static u32 iwl3945_usecs_to_beacons(u32 usec, u32 beacon_interval)
1202 {
1203         u32 quot;
1204         u32 rem;
1205         u32 interval = beacon_interval * 1024;
1206
1207         if (!interval || !usec)
1208                 return 0;
1209
1210         quot = (usec / interval) & (BEACON_TIME_MASK_HIGH >> 24);
1211         rem = (usec % interval) & BEACON_TIME_MASK_LOW;
1212
1213         return (quot << 24) + rem;
1214 }
1215
1216 /* base is usually what we get from ucode with each received frame,
1217  * the same as HW timer counter counting down
1218  */
1219
1220 static __le32 iwl3945_add_beacon_time(u32 base, u32 addon, u32 beacon_interval)
1221 {
1222         u32 base_low = base & BEACON_TIME_MASK_LOW;
1223         u32 addon_low = addon & BEACON_TIME_MASK_LOW;
1224         u32 interval = beacon_interval * TIME_UNIT;
1225         u32 res = (base & BEACON_TIME_MASK_HIGH) +
1226             (addon & BEACON_TIME_MASK_HIGH);
1227
1228         if (base_low > addon_low)
1229                 res += base_low - addon_low;
1230         else if (base_low < addon_low) {
1231                 res += interval + base_low - addon_low;
1232                 res += (1 << 24);
1233         } else
1234                 res += (1 << 24);
1235
1236         return cpu_to_le32(res);
1237 }
1238
1239 static int iwl3945_get_measurement(struct iwl_priv *priv,
1240                                struct ieee80211_measurement_params *params,
1241                                u8 type)
1242 {
1243         struct iwl_spectrum_cmd spectrum;
1244         struct iwl_rx_packet *res;
1245         struct iwl_host_cmd cmd = {
1246                 .id = REPLY_SPECTRUM_MEASUREMENT_CMD,
1247                 .data = (void *)&spectrum,
1248                 .meta.flags = CMD_WANT_SKB,
1249         };
1250         u32 add_time = le64_to_cpu(params->start_time);
1251         int rc;
1252         int spectrum_resp_status;
1253         int duration = le16_to_cpu(params->duration);
1254
1255         if (iwl_is_associated(priv))
1256                 add_time =
1257                     iwl3945_usecs_to_beacons(
1258                         le64_to_cpu(params->start_time) - priv->last_tsf,
1259                         le16_to_cpu(priv->rxon_timing.beacon_interval));
1260
1261         memset(&spectrum, 0, sizeof(spectrum));
1262
1263         spectrum.channel_count = cpu_to_le16(1);
1264         spectrum.flags =
1265             RXON_FLG_TSF2HOST_MSK | RXON_FLG_ANT_A_MSK | RXON_FLG_DIS_DIV_MSK;
1266         spectrum.filter_flags = MEASUREMENT_FILTER_FLAG;
1267         cmd.len = sizeof(spectrum);
1268         spectrum.len = cpu_to_le16(cmd.len - sizeof(spectrum.len));
1269
1270         if (iwl_is_associated(priv))
1271                 spectrum.start_time =
1272                     iwl3945_add_beacon_time(priv->last_beacon_time,
1273                                 add_time,
1274                                 le16_to_cpu(priv->rxon_timing.beacon_interval));
1275         else
1276                 spectrum.start_time = 0;
1277
1278         spectrum.channels[0].duration = cpu_to_le32(duration * TIME_UNIT);
1279         spectrum.channels[0].channel = params->channel;
1280         spectrum.channels[0].type = type;
1281         if (priv->active_rxon.flags & RXON_FLG_BAND_24G_MSK)
1282                 spectrum.flags |= RXON_FLG_BAND_24G_MSK |
1283                     RXON_FLG_AUTO_DETECT_MSK | RXON_FLG_TGG_PROTECT_MSK;
1284
1285         rc = iwl_send_cmd_sync(priv, &cmd);
1286         if (rc)
1287                 return rc;
1288
1289         res = (struct iwl_rx_packet *)cmd.meta.u.skb->data;
1290         if (res->hdr.flags & IWL_CMD_FAILED_MSK) {
1291                 IWL_ERR(priv, "Bad return from REPLY_RX_ON_ASSOC command\n");
1292                 rc = -EIO;
1293         }
1294
1295         spectrum_resp_status = le16_to_cpu(res->u.spectrum.status);
1296         switch (spectrum_resp_status) {
1297         case 0:         /* Command will be handled */
1298                 if (res->u.spectrum.id != 0xff) {
1299                         IWL_DEBUG_INFO(priv, "Replaced existing measurement: %d\n",
1300                                                 res->u.spectrum.id);
1301                         priv->measurement_status &= ~MEASUREMENT_READY;
1302                 }
1303                 priv->measurement_status |= MEASUREMENT_ACTIVE;
1304                 rc = 0;
1305                 break;
1306
1307         case 1:         /* Command will not be handled */
1308                 rc = -EAGAIN;
1309                 break;
1310         }
1311
1312         dev_kfree_skb_any(cmd.meta.u.skb);
1313
1314         return rc;
1315 }
1316 #endif
1317
1318 static void iwl3945_rx_reply_alive(struct iwl_priv *priv,
1319                                struct iwl_rx_mem_buffer *rxb)
1320 {
1321         struct iwl_rx_packet *pkt = (void *)rxb->skb->data;
1322         struct iwl_alive_resp *palive;
1323         struct delayed_work *pwork;
1324
1325         palive = &pkt->u.alive_frame;
1326
1327         IWL_DEBUG_INFO(priv, "Alive ucode status 0x%08X revision "
1328                        "0x%01X 0x%01X\n",
1329                        palive->is_valid, palive->ver_type,
1330                        palive->ver_subtype);
1331
1332         if (palive->ver_subtype == INITIALIZE_SUBTYPE) {
1333                 IWL_DEBUG_INFO(priv, "Initialization Alive received.\n");
1334                 memcpy(&priv->card_alive_init, &pkt->u.alive_frame,
1335                        sizeof(struct iwl_alive_resp));
1336                 pwork = &priv->init_alive_start;
1337         } else {
1338                 IWL_DEBUG_INFO(priv, "Runtime Alive received.\n");
1339                 memcpy(&priv->card_alive, &pkt->u.alive_frame,
1340                        sizeof(struct iwl_alive_resp));
1341                 pwork = &priv->alive_start;
1342                 iwl3945_disable_events(priv);
1343         }
1344
1345         /* We delay the ALIVE response by 5ms to
1346          * give the HW RF Kill time to activate... */
1347         if (palive->is_valid == UCODE_VALID_OK)
1348                 queue_delayed_work(priv->workqueue, pwork,
1349                                    msecs_to_jiffies(5));
1350         else
1351                 IWL_WARN(priv, "uCode did not respond OK.\n");
1352 }
1353
1354 static void iwl3945_rx_reply_add_sta(struct iwl_priv *priv,
1355                                  struct iwl_rx_mem_buffer *rxb)
1356 {
1357 #ifdef CONFIG_IWLWIFI_DEBUG
1358         struct iwl_rx_packet *pkt = (void *)rxb->skb->data;
1359 #endif
1360
1361         IWL_DEBUG_RX(priv, "Received REPLY_ADD_STA: 0x%02X\n", pkt->u.status);
1362         return;
1363 }
1364
1365 static void iwl3945_bg_beacon_update(struct work_struct *work)
1366 {
1367         struct iwl_priv *priv =
1368                 container_of(work, struct iwl_priv, beacon_update);
1369         struct sk_buff *beacon;
1370
1371         /* Pull updated AP beacon from mac80211. will fail if not in AP mode */
1372         beacon = ieee80211_beacon_get(priv->hw, priv->vif);
1373
1374         if (!beacon) {
1375                 IWL_ERR(priv, "update beacon failed\n");
1376                 return;
1377         }
1378
1379         mutex_lock(&priv->mutex);
1380         /* new beacon skb is allocated every time; dispose previous.*/
1381         if (priv->ibss_beacon)
1382                 dev_kfree_skb(priv->ibss_beacon);
1383
1384         priv->ibss_beacon = beacon;
1385         mutex_unlock(&priv->mutex);
1386
1387         iwl3945_send_beacon_cmd(priv);
1388 }
1389
1390 static void iwl3945_rx_beacon_notif(struct iwl_priv *priv,
1391                                 struct iwl_rx_mem_buffer *rxb)
1392 {
1393 #ifdef CONFIG_IWLWIFI_DEBUG
1394         struct iwl_rx_packet *pkt = (void *)rxb->skb->data;
1395         struct iwl3945_beacon_notif *beacon = &(pkt->u.beacon_status);
1396         u8 rate = beacon->beacon_notify_hdr.rate;
1397
1398         IWL_DEBUG_RX(priv, "beacon status %x retries %d iss %d "
1399                 "tsf %d %d rate %d\n",
1400                 le32_to_cpu(beacon->beacon_notify_hdr.status) & TX_STATUS_MSK,
1401                 beacon->beacon_notify_hdr.failure_frame,
1402                 le32_to_cpu(beacon->ibss_mgr_status),
1403                 le32_to_cpu(beacon->high_tsf),
1404                 le32_to_cpu(beacon->low_tsf), rate);
1405 #endif
1406
1407         if ((priv->iw_mode == NL80211_IFTYPE_AP) &&
1408             (!test_bit(STATUS_EXIT_PENDING, &priv->status)))
1409                 queue_work(priv->workqueue, &priv->beacon_update);
1410 }
1411
1412 /* Handle notification from uCode that card's power state is changing
1413  * due to software, hardware, or critical temperature RFKILL */
1414 static void iwl3945_rx_card_state_notif(struct iwl_priv *priv,
1415                                     struct iwl_rx_mem_buffer *rxb)
1416 {
1417         struct iwl_rx_packet *pkt = (void *)rxb->skb->data;
1418         u32 flags = le32_to_cpu(pkt->u.card_state_notif.flags);
1419         unsigned long status = priv->status;
1420
1421         IWL_DEBUG_RF_KILL(priv, "Card state received: HW:%s SW:%s\n",
1422                           (flags & HW_CARD_DISABLED) ? "Kill" : "On",
1423                           (flags & SW_CARD_DISABLED) ? "Kill" : "On");
1424
1425         iwl_write32(priv, CSR_UCODE_DRV_GP1_SET,
1426                     CSR_UCODE_DRV_GP1_BIT_CMD_BLOCKED);
1427
1428         if (flags & HW_CARD_DISABLED)
1429                 set_bit(STATUS_RF_KILL_HW, &priv->status);
1430         else
1431                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
1432
1433
1434         if (flags & SW_CARD_DISABLED)
1435                 set_bit(STATUS_RF_KILL_SW, &priv->status);
1436         else
1437                 clear_bit(STATUS_RF_KILL_SW, &priv->status);
1438
1439         iwl_scan_cancel(priv);
1440
1441         if ((test_bit(STATUS_RF_KILL_HW, &status) !=
1442              test_bit(STATUS_RF_KILL_HW, &priv->status)) ||
1443             (test_bit(STATUS_RF_KILL_SW, &status) !=
1444              test_bit(STATUS_RF_KILL_SW, &priv->status)))
1445                 queue_work(priv->workqueue, &priv->rf_kill);
1446         else
1447                 wake_up_interruptible(&priv->wait_command_queue);
1448 }
1449
1450 /**
1451  * iwl3945_setup_rx_handlers - Initialize Rx handler callbacks
1452  *
1453  * Setup the RX handlers for each of the reply types sent from the uCode
1454  * to the host.
1455  *
1456  * This function chains into the hardware specific files for them to setup
1457  * any hardware specific handlers as well.
1458  */
1459 static void iwl3945_setup_rx_handlers(struct iwl_priv *priv)
1460 {
1461         priv->rx_handlers[REPLY_ALIVE] = iwl3945_rx_reply_alive;
1462         priv->rx_handlers[REPLY_ADD_STA] = iwl3945_rx_reply_add_sta;
1463         priv->rx_handlers[REPLY_ERROR] = iwl_rx_reply_error;
1464         priv->rx_handlers[CHANNEL_SWITCH_NOTIFICATION] = iwl_rx_csa;
1465         priv->rx_handlers[PM_SLEEP_NOTIFICATION] = iwl_rx_pm_sleep_notif;
1466         priv->rx_handlers[PM_DEBUG_STATISTIC_NOTIFIC] =
1467             iwl_rx_pm_debug_statistics_notif;
1468         priv->rx_handlers[BEACON_NOTIFICATION] = iwl3945_rx_beacon_notif;
1469
1470         /*
1471          * The same handler is used for both the REPLY to a discrete
1472          * statistics request from the host as well as for the periodic
1473          * statistics notifications (after received beacons) from the uCode.
1474          */
1475         priv->rx_handlers[REPLY_STATISTICS_CMD] = iwl3945_hw_rx_statistics;
1476         priv->rx_handlers[STATISTICS_NOTIFICATION] = iwl3945_hw_rx_statistics;
1477
1478         iwl_setup_spectrum_handlers(priv);
1479         iwl_setup_rx_scan_handlers(priv);
1480         priv->rx_handlers[CARD_STATE_NOTIFICATION] = iwl3945_rx_card_state_notif;
1481
1482         /* Set up hardware specific Rx handlers */
1483         iwl3945_hw_rx_handler_setup(priv);
1484 }
1485
1486 /************************** RX-FUNCTIONS ****************************/
1487 /*
1488  * Rx theory of operation
1489  *
1490  * The host allocates 32 DMA target addresses and passes the host address
1491  * to the firmware at register IWL_RFDS_TABLE_LOWER + N * RFD_SIZE where N is
1492  * 0 to 31
1493  *
1494  * Rx Queue Indexes
1495  * The host/firmware share two index registers for managing the Rx buffers.
1496  *
1497  * The READ index maps to the first position that the firmware may be writing
1498  * to -- the driver can read up to (but not including) this position and get
1499  * good data.
1500  * The READ index is managed by the firmware once the card is enabled.
1501  *
1502  * The WRITE index maps to the last position the driver has read from -- the
1503  * position preceding WRITE is the last slot the firmware can place a packet.
1504  *
1505  * The queue is empty (no good data) if WRITE = READ - 1, and is full if
1506  * WRITE = READ.
1507  *
1508  * During initialization, the host sets up the READ queue position to the first
1509  * INDEX position, and WRITE to the last (READ - 1 wrapped)
1510  *
1511  * When the firmware places a packet in a buffer, it will advance the READ index
1512  * and fire the RX interrupt.  The driver can then query the READ index and
1513  * process as many packets as possible, moving the WRITE index forward as it
1514  * resets the Rx queue buffers with new memory.
1515  *
1516  * The management in the driver is as follows:
1517  * + A list of pre-allocated SKBs is stored in iwl->rxq->rx_free.  When
1518  *   iwl->rxq->free_count drops to or below RX_LOW_WATERMARK, work is scheduled
1519  *   to replenish the iwl->rxq->rx_free.
1520  * + In iwl3945_rx_replenish (scheduled) if 'processed' != 'read' then the
1521  *   iwl->rxq is replenished and the READ INDEX is updated (updating the
1522  *   'processed' and 'read' driver indexes as well)
1523  * + A received packet is processed and handed to the kernel network stack,
1524  *   detached from the iwl->rxq.  The driver 'processed' index is updated.
1525  * + The Host/Firmware iwl->rxq is replenished at tasklet time from the rx_free
1526  *   list. If there are no allocated buffers in iwl->rxq->rx_free, the READ
1527  *   INDEX is not incremented and iwl->status(RX_STALLED) is set.  If there
1528  *   were enough free buffers and RX_STALLED is set it is cleared.
1529  *
1530  *
1531  * Driver sequence:
1532  *
1533  * iwl3945_rx_replenish()     Replenishes rx_free list from rx_used, and calls
1534  *                            iwl3945_rx_queue_restock
1535  * iwl3945_rx_queue_restock() Moves available buffers from rx_free into Rx
1536  *                            queue, updates firmware pointers, and updates
1537  *                            the WRITE index.  If insufficient rx_free buffers
1538  *                            are available, schedules iwl3945_rx_replenish
1539  *
1540  * -- enable interrupts --
1541  * ISR - iwl3945_rx()         Detach iwl_rx_mem_buffers from pool up to the
1542  *                            READ INDEX, detaching the SKB from the pool.
1543  *                            Moves the packet buffer from queue to rx_used.
1544  *                            Calls iwl3945_rx_queue_restock to refill any empty
1545  *                            slots.
1546  * ...
1547  *
1548  */
1549
1550 /**
1551  * iwl3945_dma_addr2rbd_ptr - convert a DMA address to a uCode read buffer ptr
1552  */
1553 static inline __le32 iwl3945_dma_addr2rbd_ptr(struct iwl_priv *priv,
1554                                           dma_addr_t dma_addr)
1555 {
1556         return cpu_to_le32((u32)dma_addr);
1557 }
1558
1559 /**
1560  * iwl3945_rx_queue_restock - refill RX queue from pre-allocated pool
1561  *
1562  * If there are slots in the RX queue that need to be restocked,
1563  * and we have free pre-allocated buffers, fill the ranks as much
1564  * as we can, pulling from rx_free.
1565  *
1566  * This moves the 'write' index forward to catch up with 'processed', and
1567  * also updates the memory address in the firmware to reference the new
1568  * target buffer.
1569  */
1570 static int iwl3945_rx_queue_restock(struct iwl_priv *priv)
1571 {
1572         struct iwl_rx_queue *rxq = &priv->rxq;
1573         struct list_head *element;
1574         struct iwl_rx_mem_buffer *rxb;
1575         unsigned long flags;
1576         int write, rc;
1577
1578         spin_lock_irqsave(&rxq->lock, flags);
1579         write = rxq->write & ~0x7;
1580         while ((iwl_rx_queue_space(rxq) > 0) && (rxq->free_count)) {
1581                 /* Get next free Rx buffer, remove from free list */
1582                 element = rxq->rx_free.next;
1583                 rxb = list_entry(element, struct iwl_rx_mem_buffer, list);
1584                 list_del(element);
1585
1586                 /* Point to Rx buffer via next RBD in circular buffer */
1587                 rxq->bd[rxq->write] = iwl3945_dma_addr2rbd_ptr(priv, rxb->real_dma_addr);
1588                 rxq->queue[rxq->write] = rxb;
1589                 rxq->write = (rxq->write + 1) & RX_QUEUE_MASK;
1590                 rxq->free_count--;
1591         }
1592         spin_unlock_irqrestore(&rxq->lock, flags);
1593         /* If the pre-allocated buffer pool is dropping low, schedule to
1594          * refill it */
1595         if (rxq->free_count <= RX_LOW_WATERMARK)
1596                 queue_work(priv->workqueue, &priv->rx_replenish);
1597
1598
1599         /* If we've added more space for the firmware to place data, tell it.
1600          * Increment device's write pointer in multiples of 8. */
1601         if ((write != (rxq->write & ~0x7))
1602             || (abs(rxq->write - rxq->read) > 7)) {
1603                 spin_lock_irqsave(&rxq->lock, flags);
1604                 rxq->need_update = 1;
1605                 spin_unlock_irqrestore(&rxq->lock, flags);
1606                 rc = iwl_rx_queue_update_write_ptr(priv, rxq);
1607                 if (rc)
1608                         return rc;
1609         }
1610
1611         return 0;
1612 }
1613
1614 /**
1615  * iwl3945_rx_replenish - Move all used packet from rx_used to rx_free
1616  *
1617  * When moving to rx_free an SKB is allocated for the slot.
1618  *
1619  * Also restock the Rx queue via iwl3945_rx_queue_restock.
1620  * This is called as a scheduled work item (except for during initialization)
1621  */
1622 static void iwl3945_rx_allocate(struct iwl_priv *priv)
1623 {
1624         struct iwl_rx_queue *rxq = &priv->rxq;
1625         struct list_head *element;
1626         struct iwl_rx_mem_buffer *rxb;
1627         unsigned long flags;
1628         spin_lock_irqsave(&rxq->lock, flags);
1629         while (!list_empty(&rxq->rx_used)) {
1630                 element = rxq->rx_used.next;
1631                 rxb = list_entry(element, struct iwl_rx_mem_buffer, list);
1632
1633                 /* Alloc a new receive buffer */
1634                 rxb->skb =
1635                     alloc_skb(priv->hw_params.rx_buf_size,
1636                                 __GFP_NOWARN | GFP_ATOMIC);
1637                 if (!rxb->skb) {
1638                         if (net_ratelimit())
1639                                 IWL_CRIT(priv, ": Can not allocate SKB buffers\n");
1640                         /* We don't reschedule replenish work here -- we will
1641                          * call the restock method and if it still needs
1642                          * more buffers it will schedule replenish */
1643                         break;
1644                 }
1645
1646                 /* If radiotap head is required, reserve some headroom here.
1647                  * The physical head count is a variable rx_stats->phy_count.
1648                  * We reserve 4 bytes here. Plus these extra bytes, the
1649                  * headroom of the physical head should be enough for the
1650                  * radiotap head that iwl3945 supported. See iwl3945_rt.
1651                  */
1652                 skb_reserve(rxb->skb, 4);
1653
1654                 priv->alloc_rxb_skb++;
1655                 list_del(element);
1656
1657                 /* Get physical address of RB/SKB */
1658                 rxb->real_dma_addr = pci_map_single(priv->pci_dev,
1659                                                 rxb->skb->data,
1660                                                 priv->hw_params.rx_buf_size,
1661                                                 PCI_DMA_FROMDEVICE);
1662                 list_add_tail(&rxb->list, &rxq->rx_free);
1663                 rxq->free_count++;
1664         }
1665         spin_unlock_irqrestore(&rxq->lock, flags);
1666 }
1667
1668 void iwl3945_rx_queue_reset(struct iwl_priv *priv, struct iwl_rx_queue *rxq)
1669 {
1670         unsigned long flags;
1671         int i;
1672         spin_lock_irqsave(&rxq->lock, flags);
1673         INIT_LIST_HEAD(&rxq->rx_free);
1674         INIT_LIST_HEAD(&rxq->rx_used);
1675         /* Fill the rx_used queue with _all_ of the Rx buffers */
1676         for (i = 0; i < RX_FREE_BUFFERS + RX_QUEUE_SIZE; i++) {
1677                 /* In the reset function, these buffers may have been allocated
1678                  * to an SKB, so we need to unmap and free potential storage */
1679                 if (rxq->pool[i].skb != NULL) {
1680                         pci_unmap_single(priv->pci_dev,
1681                                          rxq->pool[i].real_dma_addr,
1682                                          priv->hw_params.rx_buf_size,
1683                                          PCI_DMA_FROMDEVICE);
1684                         priv->alloc_rxb_skb--;
1685                         dev_kfree_skb(rxq->pool[i].skb);
1686                         rxq->pool[i].skb = NULL;
1687                 }
1688                 list_add_tail(&rxq->pool[i].list, &rxq->rx_used);
1689         }
1690
1691         /* Set us so that we have processed and used all buffers, but have
1692          * not restocked the Rx queue with fresh buffers */
1693         rxq->read = rxq->write = 0;
1694         rxq->free_count = 0;
1695         spin_unlock_irqrestore(&rxq->lock, flags);
1696 }
1697
1698 /*
1699  * this should be called while priv->lock is locked
1700  */
1701 static void __iwl3945_rx_replenish(void *data)
1702 {
1703         struct iwl_priv *priv = data;
1704
1705         iwl3945_rx_allocate(priv);
1706         iwl3945_rx_queue_restock(priv);
1707 }
1708
1709
1710 void iwl3945_rx_replenish(void *data)
1711 {
1712         struct iwl_priv *priv = data;
1713         unsigned long flags;
1714
1715         iwl3945_rx_allocate(priv);
1716
1717         spin_lock_irqsave(&priv->lock, flags);
1718         iwl3945_rx_queue_restock(priv);
1719         spin_unlock_irqrestore(&priv->lock, flags);
1720 }
1721
1722 /* Assumes that the skb field of the buffers in 'pool' is kept accurate.
1723  * If an SKB has been detached, the POOL needs to have its SKB set to NULL
1724  * This free routine walks the list of POOL entries and if SKB is set to
1725  * non NULL it is unmapped and freed
1726  */
1727 static void iwl3945_rx_queue_free(struct iwl_priv *priv, struct iwl_rx_queue *rxq)
1728 {
1729         int i;
1730         for (i = 0; i < RX_QUEUE_SIZE + RX_FREE_BUFFERS; i++) {
1731                 if (rxq->pool[i].skb != NULL) {
1732                         pci_unmap_single(priv->pci_dev,
1733                                          rxq->pool[i].real_dma_addr,
1734                                          priv->hw_params.rx_buf_size,
1735                                          PCI_DMA_FROMDEVICE);
1736                         dev_kfree_skb(rxq->pool[i].skb);
1737                 }
1738         }
1739
1740         pci_free_consistent(priv->pci_dev, 4 * RX_QUEUE_SIZE, rxq->bd,
1741                             rxq->dma_addr);
1742         pci_free_consistent(priv->pci_dev, sizeof(struct iwl_rb_status),
1743                             rxq->rb_stts, rxq->rb_stts_dma);
1744         rxq->bd = NULL;
1745         rxq->rb_stts  = NULL;
1746 }
1747
1748
1749 /* Convert linear signal-to-noise ratio into dB */
1750 static u8 ratio2dB[100] = {
1751 /*       0   1   2   3   4   5   6   7   8   9 */
1752          0,  0,  6, 10, 12, 14, 16, 17, 18, 19, /* 00 - 09 */
1753         20, 21, 22, 22, 23, 23, 24, 25, 26, 26, /* 10 - 19 */
1754         26, 26, 26, 27, 27, 28, 28, 28, 29, 29, /* 20 - 29 */
1755         29, 30, 30, 30, 31, 31, 31, 31, 32, 32, /* 30 - 39 */
1756         32, 32, 32, 33, 33, 33, 33, 33, 34, 34, /* 40 - 49 */
1757         34, 34, 34, 34, 35, 35, 35, 35, 35, 35, /* 50 - 59 */
1758         36, 36, 36, 36, 36, 36, 36, 37, 37, 37, /* 60 - 69 */
1759         37, 37, 37, 37, 37, 38, 38, 38, 38, 38, /* 70 - 79 */
1760         38, 38, 38, 38, 38, 39, 39, 39, 39, 39, /* 80 - 89 */
1761         39, 39, 39, 39, 39, 40, 40, 40, 40, 40  /* 90 - 99 */
1762 };
1763
1764 /* Calculates a relative dB value from a ratio of linear
1765  *   (i.e. not dB) signal levels.
1766  * Conversion assumes that levels are voltages (20*log), not powers (10*log). */
1767 int iwl3945_calc_db_from_ratio(int sig_ratio)
1768 {
1769         /* 1000:1 or higher just report as 60 dB */
1770         if (sig_ratio >= 1000)
1771                 return 60;
1772
1773         /* 100:1 or higher, divide by 10 and use table,
1774          *   add 20 dB to make up for divide by 10 */
1775         if (sig_ratio >= 100)
1776                 return 20 + (int)ratio2dB[sig_ratio/10];
1777
1778         /* We shouldn't see this */
1779         if (sig_ratio < 1)
1780                 return 0;
1781
1782         /* Use table for ratios 1:1 - 99:1 */
1783         return (int)ratio2dB[sig_ratio];
1784 }
1785
1786 #define PERFECT_RSSI (-20) /* dBm */
1787 #define WORST_RSSI (-95)   /* dBm */
1788 #define RSSI_RANGE (PERFECT_RSSI - WORST_RSSI)
1789
1790 /* Calculate an indication of rx signal quality (a percentage, not dBm!).
1791  * See http://www.ces.clemson.edu/linux/signal_quality.shtml for info
1792  *   about formulas used below. */
1793 int iwl3945_calc_sig_qual(int rssi_dbm, int noise_dbm)
1794 {
1795         int sig_qual;
1796         int degradation = PERFECT_RSSI - rssi_dbm;
1797
1798         /* If we get a noise measurement, use signal-to-noise ratio (SNR)
1799          * as indicator; formula is (signal dbm - noise dbm).
1800          * SNR at or above 40 is a great signal (100%).
1801          * Below that, scale to fit SNR of 0 - 40 dB within 0 - 100% indicator.
1802          * Weakest usable signal is usually 10 - 15 dB SNR. */
1803         if (noise_dbm) {
1804                 if (rssi_dbm - noise_dbm >= 40)
1805                         return 100;
1806                 else if (rssi_dbm < noise_dbm)
1807                         return 0;
1808                 sig_qual = ((rssi_dbm - noise_dbm) * 5) / 2;
1809
1810         /* Else use just the signal level.
1811          * This formula is a least squares fit of data points collected and
1812          *   compared with a reference system that had a percentage (%) display
1813          *   for signal quality. */
1814         } else
1815                 sig_qual = (100 * (RSSI_RANGE * RSSI_RANGE) - degradation *
1816                             (15 * RSSI_RANGE + 62 * degradation)) /
1817                            (RSSI_RANGE * RSSI_RANGE);
1818
1819         if (sig_qual > 100)
1820                 sig_qual = 100;
1821         else if (sig_qual < 1)
1822                 sig_qual = 0;
1823
1824         return sig_qual;
1825 }
1826
1827 /**
1828  * iwl3945_rx_handle - Main entry function for receiving responses from uCode
1829  *
1830  * Uses the priv->rx_handlers callback function array to invoke
1831  * the appropriate handlers, including command responses,
1832  * frame-received notifications, and other notifications.
1833  */
1834 static void iwl3945_rx_handle(struct iwl_priv *priv)
1835 {
1836         struct iwl_rx_mem_buffer *rxb;
1837         struct iwl_rx_packet *pkt;
1838         struct iwl_rx_queue *rxq = &priv->rxq;
1839         u32 r, i;
1840         int reclaim;
1841         unsigned long flags;
1842         u8 fill_rx = 0;
1843         u32 count = 8;
1844
1845         /* uCode's read index (stored in shared DRAM) indicates the last Rx
1846          * buffer that the driver may process (last buffer filled by ucode). */
1847         r = le16_to_cpu(rxq->rb_stts->closed_rb_num) &  0x0FFF;
1848         i = rxq->read;
1849
1850         if (iwl_rx_queue_space(rxq) > (RX_QUEUE_SIZE / 2))
1851                 fill_rx = 1;
1852         /* Rx interrupt, but nothing sent from uCode */
1853         if (i == r)
1854                 IWL_DEBUG(priv, IWL_DL_RX | IWL_DL_ISR, "r = %d, i = %d\n", r, i);
1855
1856         while (i != r) {
1857                 rxb = rxq->queue[i];
1858
1859                 /* If an RXB doesn't have a Rx queue slot associated with it,
1860                  * then a bug has been introduced in the queue refilling
1861                  * routines -- catch it here */
1862                 BUG_ON(rxb == NULL);
1863
1864                 rxq->queue[i] = NULL;
1865
1866                 pci_unmap_single(priv->pci_dev, rxb->real_dma_addr,
1867                                 priv->hw_params.rx_buf_size,
1868                                 PCI_DMA_FROMDEVICE);
1869                 pkt = (struct iwl_rx_packet *)rxb->skb->data;
1870
1871                 /* Reclaim a command buffer only if this packet is a response
1872                  *   to a (driver-originated) command.
1873                  * If the packet (e.g. Rx frame) originated from uCode,
1874                  *   there is no command buffer to reclaim.
1875                  * Ucode should set SEQ_RX_FRAME bit if ucode-originated,
1876                  *   but apparently a few don't get set; catch them here. */
1877                 reclaim = !(pkt->hdr.sequence & SEQ_RX_FRAME) &&
1878                         (pkt->hdr.cmd != STATISTICS_NOTIFICATION) &&
1879                         (pkt->hdr.cmd != REPLY_TX);
1880
1881                 /* Based on type of command response or notification,
1882                  *   handle those that need handling via function in
1883                  *   rx_handlers table.  See iwl3945_setup_rx_handlers() */
1884                 if (priv->rx_handlers[pkt->hdr.cmd]) {
1885                         IWL_DEBUG(priv, IWL_DL_HCMD | IWL_DL_RX | IWL_DL_ISR,
1886                                 "r = %d, i = %d, %s, 0x%02x\n", r, i,
1887                                 get_cmd_string(pkt->hdr.cmd), pkt->hdr.cmd);
1888                         priv->rx_handlers[pkt->hdr.cmd] (priv, rxb);
1889                 } else {
1890                         /* No handling needed */
1891                         IWL_DEBUG(priv, IWL_DL_HCMD | IWL_DL_RX | IWL_DL_ISR,
1892                                 "r %d i %d No handler needed for %s, 0x%02x\n",
1893                                 r, i, get_cmd_string(pkt->hdr.cmd),
1894                                 pkt->hdr.cmd);
1895                 }
1896
1897                 if (reclaim) {
1898                         /* Invoke any callbacks, transfer the skb to caller, and
1899                          * fire off the (possibly) blocking iwl_send_cmd()
1900                          * as we reclaim the driver command queue */
1901                         if (rxb && rxb->skb)
1902                                 iwl_tx_cmd_complete(priv, rxb);
1903                         else
1904                                 IWL_WARN(priv, "Claim null rxb?\n");
1905                 }
1906
1907                 /* For now we just don't re-use anything.  We can tweak this
1908                  * later to try and re-use notification packets and SKBs that
1909                  * fail to Rx correctly */
1910                 if (rxb->skb != NULL) {
1911                         priv->alloc_rxb_skb--;
1912                         dev_kfree_skb_any(rxb->skb);
1913                         rxb->skb = NULL;
1914                 }
1915
1916                 spin_lock_irqsave(&rxq->lock, flags);
1917                 list_add_tail(&rxb->list, &priv->rxq.rx_used);
1918                 spin_unlock_irqrestore(&rxq->lock, flags);
1919                 i = (i + 1) & RX_QUEUE_MASK;
1920                 /* If there are a lot of unused frames,
1921                  * restock the Rx queue so ucode won't assert. */
1922                 if (fill_rx) {
1923                         count++;
1924                         if (count >= 8) {
1925                                 priv->rxq.read = i;
1926                                 __iwl3945_rx_replenish(priv);
1927                                 count = 0;
1928                         }
1929                 }
1930         }
1931
1932         /* Backtrack one entry */
1933         priv->rxq.read = i;
1934         iwl3945_rx_queue_restock(priv);
1935 }
1936
1937 /* call this function to flush any scheduled tasklet */
1938 static inline void iwl_synchronize_irq(struct iwl_priv *priv)
1939 {
1940         /* wait to make sure we flush pending tasklet*/
1941         synchronize_irq(priv->pci_dev->irq);
1942         tasklet_kill(&priv->irq_tasklet);
1943 }
1944
1945 static const char *desc_lookup(int i)
1946 {
1947         switch (i) {
1948         case 1:
1949                 return "FAIL";
1950         case 2:
1951                 return "BAD_PARAM";
1952         case 3:
1953                 return "BAD_CHECKSUM";
1954         case 4:
1955                 return "NMI_INTERRUPT";
1956         case 5:
1957                 return "SYSASSERT";
1958         case 6:
1959                 return "FATAL_ERROR";
1960         }
1961
1962         return "UNKNOWN";
1963 }
1964
1965 #define ERROR_START_OFFSET  (1 * sizeof(u32))
1966 #define ERROR_ELEM_SIZE     (7 * sizeof(u32))
1967
1968 static void iwl3945_dump_nic_error_log(struct iwl_priv *priv)
1969 {
1970         u32 i;
1971         u32 desc, time, count, base, data1;
1972         u32 blink1, blink2, ilink1, ilink2;
1973         int rc;
1974
1975         base = le32_to_cpu(priv->card_alive.error_event_table_ptr);
1976
1977         if (!iwl3945_hw_valid_rtc_data_addr(base)) {
1978                 IWL_ERR(priv, "Not valid error log pointer 0x%08X\n", base);
1979                 return;
1980         }
1981
1982         rc = iwl_grab_nic_access(priv);
1983         if (rc) {
1984                 IWL_WARN(priv, "Can not read from adapter at this time.\n");
1985                 return;
1986         }
1987
1988         count = iwl_read_targ_mem(priv, base);
1989
1990         if (ERROR_START_OFFSET <= count * ERROR_ELEM_SIZE) {
1991                 IWL_ERR(priv, "Start IWL Error Log Dump:\n");
1992                 IWL_ERR(priv, "Status: 0x%08lX, count: %d\n",
1993                         priv->status, count);
1994         }
1995
1996         IWL_ERR(priv, "Desc       Time       asrtPC  blink2 "
1997                   "ilink1  nmiPC   Line\n");
1998         for (i = ERROR_START_OFFSET;
1999              i < (count * ERROR_ELEM_SIZE) + ERROR_START_OFFSET;
2000              i += ERROR_ELEM_SIZE) {
2001                 desc = iwl_read_targ_mem(priv, base + i);
2002                 time =
2003                     iwl_read_targ_mem(priv, base + i + 1 * sizeof(u32));
2004                 blink1 =
2005                     iwl_read_targ_mem(priv, base + i + 2 * sizeof(u32));
2006                 blink2 =
2007                     iwl_read_targ_mem(priv, base + i + 3 * sizeof(u32));
2008                 ilink1 =
2009                     iwl_read_targ_mem(priv, base + i + 4 * sizeof(u32));
2010                 ilink2 =
2011                     iwl_read_targ_mem(priv, base + i + 5 * sizeof(u32));
2012                 data1 =
2013                     iwl_read_targ_mem(priv, base + i + 6 * sizeof(u32));
2014
2015                 IWL_ERR(priv,
2016                         "%-13s (#%d) %010u 0x%05X 0x%05X 0x%05X 0x%05X %u\n\n",
2017                         desc_lookup(desc), desc, time, blink1, blink2,
2018                         ilink1, ilink2, data1);
2019         }
2020
2021         iwl_release_nic_access(priv);
2022
2023 }
2024
2025 #define EVENT_START_OFFSET  (6 * sizeof(u32))
2026
2027 /**
2028  * iwl3945_print_event_log - Dump error event log to syslog
2029  *
2030  * NOTE: Must be called with iwl_grab_nic_access() already obtained!
2031  */
2032 static void iwl3945_print_event_log(struct iwl_priv *priv, u32 start_idx,
2033                                 u32 num_events, u32 mode)
2034 {
2035         u32 i;
2036         u32 base;       /* SRAM byte address of event log header */
2037         u32 event_size; /* 2 u32s, or 3 u32s if timestamp recorded */
2038         u32 ptr;        /* SRAM byte address of log data */
2039         u32 ev, time, data; /* event log data */
2040
2041         if (num_events == 0)
2042                 return;
2043
2044         base = le32_to_cpu(priv->card_alive.log_event_table_ptr);
2045
2046         if (mode == 0)
2047                 event_size = 2 * sizeof(u32);
2048         else
2049                 event_size = 3 * sizeof(u32);
2050
2051         ptr = base + EVENT_START_OFFSET + (start_idx * event_size);
2052
2053         /* "time" is actually "data" for mode 0 (no timestamp).
2054          * place event id # at far right for easier visual parsing. */
2055         for (i = 0; i < num_events; i++) {
2056                 ev = iwl_read_targ_mem(priv, ptr);
2057                 ptr += sizeof(u32);
2058                 time = iwl_read_targ_mem(priv, ptr);
2059                 ptr += sizeof(u32);
2060                 if (mode == 0) {
2061                         /* data, ev */
2062                         IWL_ERR(priv, "0x%08x\t%04u\n", time, ev);
2063                 } else {
2064                         data = iwl_read_targ_mem(priv, ptr);
2065                         ptr += sizeof(u32);
2066                         IWL_ERR(priv, "%010u\t0x%08x\t%04u\n", time, data, ev);
2067                 }
2068         }
2069 }
2070
2071 static void iwl3945_dump_nic_event_log(struct iwl_priv *priv)
2072 {
2073         int rc;
2074         u32 base;       /* SRAM byte address of event log header */
2075         u32 capacity;   /* event log capacity in # entries */
2076         u32 mode;       /* 0 - no timestamp, 1 - timestamp recorded */
2077         u32 num_wraps;  /* # times uCode wrapped to top of log */
2078         u32 next_entry; /* index of next entry to be written by uCode */
2079         u32 size;       /* # entries that we'll print */
2080
2081         base = le32_to_cpu(priv->card_alive.log_event_table_ptr);
2082         if (!iwl3945_hw_valid_rtc_data_addr(base)) {
2083                 IWL_ERR(priv, "Invalid event log pointer 0x%08X\n", base);
2084                 return;
2085         }
2086
2087         rc = iwl_grab_nic_access(priv);
2088         if (rc) {
2089                 IWL_WARN(priv, "Can not read from adapter at this time.\n");
2090                 return;
2091         }
2092
2093         /* event log header */
2094         capacity = iwl_read_targ_mem(priv, base);
2095         mode = iwl_read_targ_mem(priv, base + (1 * sizeof(u32)));
2096         num_wraps = iwl_read_targ_mem(priv, base + (2 * sizeof(u32)));
2097         next_entry = iwl_read_targ_mem(priv, base + (3 * sizeof(u32)));
2098
2099         size = num_wraps ? capacity : next_entry;
2100
2101         /* bail out if nothing in log */
2102         if (size == 0) {
2103                 IWL_ERR(priv, "Start IWL Event Log Dump: nothing in log\n");
2104                 iwl_release_nic_access(priv);
2105                 return;
2106         }
2107
2108         IWL_ERR(priv, "Start IWL Event Log Dump: display count %d, wraps %d\n",
2109                   size, num_wraps);
2110
2111         /* if uCode has wrapped back to top of log, start at the oldest entry,
2112          * i.e the next one that uCode would fill. */
2113         if (num_wraps)
2114                 iwl3945_print_event_log(priv, next_entry,
2115                                     capacity - next_entry, mode);
2116
2117         /* (then/else) start at top of log */
2118         iwl3945_print_event_log(priv, 0, next_entry, mode);
2119
2120         iwl_release_nic_access(priv);
2121 }
2122
2123 static void iwl3945_error_recovery(struct iwl_priv *priv)
2124 {
2125         unsigned long flags;
2126
2127         memcpy(&priv->staging_rxon, &priv->recovery_rxon,
2128                sizeof(priv->staging_rxon));
2129         priv->staging_rxon.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
2130         iwl3945_commit_rxon(priv);
2131
2132         iwl3945_add_station(priv, priv->bssid, 1, 0);
2133
2134         spin_lock_irqsave(&priv->lock, flags);
2135         priv->assoc_id = le16_to_cpu(priv->staging_rxon.assoc_id);
2136         priv->error_recovering = 0;
2137         spin_unlock_irqrestore(&priv->lock, flags);
2138 }
2139
2140 static void iwl3945_irq_tasklet(struct iwl_priv *priv)
2141 {
2142         u32 inta, handled = 0;
2143         u32 inta_fh;
2144         unsigned long flags;
2145 #ifdef CONFIG_IWLWIFI_DEBUG
2146         u32 inta_mask;
2147 #endif
2148
2149         spin_lock_irqsave(&priv->lock, flags);
2150
2151         /* Ack/clear/reset pending uCode interrupts.
2152          * Note:  Some bits in CSR_INT are "OR" of bits in CSR_FH_INT_STATUS,
2153          *  and will clear only when CSR_FH_INT_STATUS gets cleared. */
2154         inta = iwl_read32(priv, CSR_INT);
2155         iwl_write32(priv, CSR_INT, inta);
2156
2157         /* Ack/clear/reset pending flow-handler (DMA) interrupts.
2158          * Any new interrupts that happen after this, either while we're
2159          * in this tasklet, or later, will show up in next ISR/tasklet. */
2160         inta_fh = iwl_read32(priv, CSR_FH_INT_STATUS);
2161         iwl_write32(priv, CSR_FH_INT_STATUS, inta_fh);
2162
2163 #ifdef CONFIG_IWLWIFI_DEBUG
2164         if (priv->debug_level & IWL_DL_ISR) {
2165                 /* just for debug */
2166                 inta_mask = iwl_read32(priv, CSR_INT_MASK);
2167                 IWL_DEBUG_ISR(priv, "inta 0x%08x, enabled 0x%08x, fh 0x%08x\n",
2168                               inta, inta_mask, inta_fh);
2169         }
2170 #endif
2171
2172         /* Since CSR_INT and CSR_FH_INT_STATUS reads and clears are not
2173          * atomic, make sure that inta covers all the interrupts that
2174          * we've discovered, even if FH interrupt came in just after
2175          * reading CSR_INT. */
2176         if (inta_fh & CSR39_FH_INT_RX_MASK)
2177                 inta |= CSR_INT_BIT_FH_RX;
2178         if (inta_fh & CSR39_FH_INT_TX_MASK)
2179                 inta |= CSR_INT_BIT_FH_TX;
2180
2181         /* Now service all interrupt bits discovered above. */
2182         if (inta & CSR_INT_BIT_HW_ERR) {
2183                 IWL_ERR(priv, "Microcode HW error detected.  Restarting.\n");
2184
2185                 /* Tell the device to stop sending interrupts */
2186                 iwl_disable_interrupts(priv);
2187
2188                 iwl_irq_handle_error(priv);
2189
2190                 handled |= CSR_INT_BIT_HW_ERR;
2191
2192                 spin_unlock_irqrestore(&priv->lock, flags);
2193
2194                 return;
2195         }
2196
2197 #ifdef CONFIG_IWLWIFI_DEBUG
2198         if (priv->debug_level & (IWL_DL_ISR)) {
2199                 /* NIC fires this, but we don't use it, redundant with WAKEUP */
2200                 if (inta & CSR_INT_BIT_SCD)
2201                         IWL_DEBUG_ISR(priv, "Scheduler finished to transmit "
2202                                       "the frame/frames.\n");
2203
2204                 /* Alive notification via Rx interrupt will do the real work */
2205                 if (inta & CSR_INT_BIT_ALIVE)
2206                         IWL_DEBUG_ISR(priv, "Alive interrupt\n");
2207         }
2208 #endif
2209         /* Safely ignore these bits for debug checks below */
2210         inta &= ~(CSR_INT_BIT_SCD | CSR_INT_BIT_ALIVE);
2211
2212         /* Error detected by uCode */
2213         if (inta & CSR_INT_BIT_SW_ERR) {
2214                 IWL_ERR(priv, "Microcode SW error detected. "
2215                         "Restarting 0x%X.\n", inta);
2216                 iwl_irq_handle_error(priv);
2217                 handled |= CSR_INT_BIT_SW_ERR;
2218         }
2219
2220         /* uCode wakes up after power-down sleep */
2221         if (inta & CSR_INT_BIT_WAKEUP) {
2222                 IWL_DEBUG_ISR(priv, "Wakeup interrupt\n");
2223                 iwl_rx_queue_update_write_ptr(priv, &priv->rxq);
2224                 iwl_txq_update_write_ptr(priv, &priv->txq[0]);
2225                 iwl_txq_update_write_ptr(priv, &priv->txq[1]);
2226                 iwl_txq_update_write_ptr(priv, &priv->txq[2]);
2227                 iwl_txq_update_write_ptr(priv, &priv->txq[3]);
2228                 iwl_txq_update_write_ptr(priv, &priv->txq[4]);
2229                 iwl_txq_update_write_ptr(priv, &priv->txq[5]);
2230
2231                 handled |= CSR_INT_BIT_WAKEUP;
2232         }
2233
2234         /* All uCode command responses, including Tx command responses,
2235          * Rx "responses" (frame-received notification), and other
2236          * notifications from uCode come through here*/
2237         if (inta & (CSR_INT_BIT_FH_RX | CSR_INT_BIT_SW_RX)) {
2238                 iwl3945_rx_handle(priv);
2239                 handled |= (CSR_INT_BIT_FH_RX | CSR_INT_BIT_SW_RX);
2240         }
2241
2242         if (inta & CSR_INT_BIT_FH_TX) {
2243                 IWL_DEBUG_ISR(priv, "Tx interrupt\n");
2244
2245                 iwl_write32(priv, CSR_FH_INT_STATUS, (1 << 6));
2246                 if (!iwl_grab_nic_access(priv)) {
2247                         iwl_write_direct32(priv, FH39_TCSR_CREDIT
2248                                              (FH39_SRVC_CHNL), 0x0);
2249                         iwl_release_nic_access(priv);
2250                 }
2251                 handled |= CSR_INT_BIT_FH_TX;
2252         }
2253
2254         if (inta & ~handled)
2255                 IWL_ERR(priv, "Unhandled INTA bits 0x%08x\n", inta & ~handled);
2256
2257         if (inta & ~CSR_INI_SET_MASK) {
2258                 IWL_WARN(priv, "Disabled INTA bits 0x%08x were pending\n",
2259                          inta & ~CSR_INI_SET_MASK);
2260                 IWL_WARN(priv, "   with FH_INT = 0x%08x\n", inta_fh);
2261         }
2262
2263         /* Re-enable all interrupts */
2264         /* only Re-enable if disabled by irq */
2265         if (test_bit(STATUS_INT_ENABLED, &priv->status))
2266                 iwl_enable_interrupts(priv);
2267
2268 #ifdef CONFIG_IWLWIFI_DEBUG
2269         if (priv->debug_level & (IWL_DL_ISR)) {
2270                 inta = iwl_read32(priv, CSR_INT);
2271                 inta_mask = iwl_read32(priv, CSR_INT_MASK);
2272                 inta_fh = iwl_read32(priv, CSR_FH_INT_STATUS);
2273                 IWL_DEBUG_ISR(priv, "End inta 0x%08x, enabled 0x%08x, fh 0x%08x, "
2274                         "flags 0x%08lx\n", inta, inta_mask, inta_fh, flags);
2275         }
2276 #endif
2277         spin_unlock_irqrestore(&priv->lock, flags);
2278 }
2279
2280 static int iwl3945_get_channels_for_scan(struct iwl_priv *priv,
2281                                          enum ieee80211_band band,
2282                                      u8 is_active, u8 n_probes,
2283                                      struct iwl3945_scan_channel *scan_ch)
2284 {
2285         const struct ieee80211_channel *channels = NULL;
2286         const struct ieee80211_supported_band *sband;
2287         const struct iwl_channel_info *ch_info;
2288         u16 passive_dwell = 0;
2289         u16 active_dwell = 0;
2290         int added, i;
2291
2292         sband = iwl_get_hw_mode(priv, band);
2293         if (!sband)
2294                 return 0;
2295
2296         channels = sband->channels;
2297
2298         active_dwell = iwl_get_active_dwell_time(priv, band, n_probes);
2299         passive_dwell = iwl_get_passive_dwell_time(priv, band);
2300
2301         if (passive_dwell <= active_dwell)
2302                 passive_dwell = active_dwell + 1;
2303
2304         for (i = 0, added = 0; i < sband->n_channels; i++) {
2305                 if (channels[i].flags & IEEE80211_CHAN_DISABLED)
2306                         continue;
2307
2308                 scan_ch->channel = channels[i].hw_value;
2309
2310                 ch_info = iwl_get_channel_info(priv, band, scan_ch->channel);
2311                 if (!is_channel_valid(ch_info)) {
2312                         IWL_DEBUG_SCAN(priv, "Channel %d is INVALID for this band.\n",
2313                                        scan_ch->channel);
2314                         continue;
2315                 }
2316
2317                 scan_ch->active_dwell = cpu_to_le16(active_dwell);
2318                 scan_ch->passive_dwell = cpu_to_le16(passive_dwell);
2319                 /* If passive , set up for auto-switch
2320                  *  and use long active_dwell time.
2321                  */
2322                 if (!is_active || is_channel_passive(ch_info) ||
2323                     (channels[i].flags & IEEE80211_CHAN_PASSIVE_SCAN)) {
2324                         scan_ch->type = 0;      /* passive */
2325                         if (IWL_UCODE_API(priv->ucode_ver) == 1)
2326                                 scan_ch->active_dwell = cpu_to_le16(passive_dwell - 1);
2327                 } else {
2328                         scan_ch->type = 1;      /* active */
2329                 }
2330
2331                 /* Set direct probe bits. These may be used both for active
2332                  * scan channels (probes gets sent right away),
2333                  * or for passive channels (probes get se sent only after
2334                  * hearing clear Rx packet).*/
2335                 if (IWL_UCODE_API(priv->ucode_ver) >= 2) {
2336                         if (n_probes)
2337                                 scan_ch->type |= IWL39_SCAN_PROBE_MASK(n_probes);
2338                 } else {
2339                         /* uCode v1 does not allow setting direct probe bits on
2340                          * passive channel. */
2341                         if ((scan_ch->type & 1) && n_probes)
2342                                 scan_ch->type |= IWL39_SCAN_PROBE_MASK(n_probes);
2343                 }
2344
2345                 /* Set txpower levels to defaults */
2346                 scan_ch->tpc.dsp_atten = 110;
2347                 /* scan_pwr_info->tpc.dsp_atten; */
2348
2349                 /*scan_pwr_info->tpc.tx_gain; */
2350                 if (band == IEEE80211_BAND_5GHZ)
2351                         scan_ch->tpc.tx_gain = ((1 << 5) | (3 << 3)) | 3;
2352                 else {
2353                         scan_ch->tpc.tx_gain = ((1 << 5) | (5 << 3));
2354                         /* NOTE: if we were doing 6Mb OFDM for scans we'd use
2355                          * power level:
2356                          * scan_ch->tpc.tx_gain = ((1 << 5) | (2 << 3)) | 3;
2357                          */
2358                 }
2359
2360                 IWL_DEBUG_SCAN(priv, "Scanning %d [%s %d]\n",
2361                                scan_ch->channel,
2362                                (scan_ch->type & 1) ? "ACTIVE" : "PASSIVE",
2363                                (scan_ch->type & 1) ?
2364                                active_dwell : passive_dwell);
2365
2366                 scan_ch++;
2367                 added++;
2368         }
2369
2370         IWL_DEBUG_SCAN(priv, "total channels to scan %d \n", added);
2371         return added;
2372 }
2373
2374 static void iwl3945_init_hw_rates(struct iwl_priv *priv,
2375                               struct ieee80211_rate *rates)
2376 {
2377         int i;
2378
2379         for (i = 0; i < IWL_RATE_COUNT; i++) {
2380                 rates[i].bitrate = iwl3945_rates[i].ieee * 5;
2381                 rates[i].hw_value = i; /* Rate scaling will work on indexes */
2382                 rates[i].hw_value_short = i;
2383                 rates[i].flags = 0;
2384                 if ((i > IWL39_LAST_OFDM_RATE) || (i < IWL_FIRST_OFDM_RATE)) {
2385                         /*
2386                          * If CCK != 1M then set short preamble rate flag.
2387                          */
2388                         rates[i].flags |= (iwl3945_rates[i].plcp == 10) ?
2389                                 0 : IEEE80211_RATE_SHORT_PREAMBLE;
2390                 }
2391         }
2392 }
2393
2394 /******************************************************************************
2395  *
2396  * uCode download functions
2397  *
2398  ******************************************************************************/
2399
2400 static void iwl3945_dealloc_ucode_pci(struct iwl_priv *priv)
2401 {
2402         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_code);
2403         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_data);
2404         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_data_backup);
2405         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_init);
2406         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_init_data);
2407         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_boot);
2408 }
2409
2410 /**
2411  * iwl3945_verify_inst_full - verify runtime uCode image in card vs. host,
2412  *     looking at all data.
2413  */
2414 static int iwl3945_verify_inst_full(struct iwl_priv *priv, __le32 *image, u32 len)
2415 {
2416         u32 val;
2417         u32 save_len = len;
2418         int rc = 0;
2419         u32 errcnt;
2420
2421         IWL_DEBUG_INFO(priv, "ucode inst image size is %u\n", len);
2422
2423         rc = iwl_grab_nic_access(priv);
2424         if (rc)
2425                 return rc;
2426
2427         iwl_write_direct32(priv, HBUS_TARG_MEM_RADDR,
2428                                IWL39_RTC_INST_LOWER_BOUND);
2429
2430         errcnt = 0;
2431         for (; len > 0; len -= sizeof(u32), image++) {
2432                 /* read data comes through single port, auto-incr addr */
2433                 /* NOTE: Use the debugless read so we don't flood kernel log
2434                  * if IWL_DL_IO is set */
2435                 val = _iwl_read_direct32(priv, HBUS_TARG_MEM_RDAT);
2436                 if (val != le32_to_cpu(*image)) {
2437                         IWL_ERR(priv, "uCode INST section is invalid at "
2438                                   "offset 0x%x, is 0x%x, s/b 0x%x\n",
2439                                   save_len - len, val, le32_to_cpu(*image));
2440                         rc = -EIO;
2441                         errcnt++;
2442                         if (errcnt >= 20)
2443                                 break;
2444                 }
2445         }
2446
2447         iwl_release_nic_access(priv);
2448
2449         if (!errcnt)
2450                 IWL_DEBUG_INFO(priv,
2451                         "ucode image in INSTRUCTION memory is good\n");
2452
2453         return rc;
2454 }
2455
2456
2457 /**
2458  * iwl3945_verify_inst_sparse - verify runtime uCode image in card vs. host,
2459  *   using sample data 100 bytes apart.  If these sample points are good,
2460  *   it's a pretty good bet that everything between them is good, too.
2461  */
2462 static int iwl3945_verify_inst_sparse(struct iwl_priv *priv, __le32 *image, u32 len)
2463 {
2464         u32 val;
2465         int rc = 0;
2466         u32 errcnt = 0;
2467         u32 i;
2468
2469         IWL_DEBUG_INFO(priv, "ucode inst image size is %u\n", len);
2470
2471         rc = iwl_grab_nic_access(priv);
2472         if (rc)
2473                 return rc;
2474
2475         for (i = 0; i < len; i += 100, image += 100/sizeof(u32)) {
2476                 /* read data comes through single port, auto-incr addr */
2477                 /* NOTE: Use the debugless read so we don't flood kernel log
2478                  * if IWL_DL_IO is set */
2479                 iwl_write_direct32(priv, HBUS_TARG_MEM_RADDR,
2480                         i + IWL39_RTC_INST_LOWER_BOUND);
2481                 val = _iwl_read_direct32(priv, HBUS_TARG_MEM_RDAT);
2482                 if (val != le32_to_cpu(*image)) {
2483 #if 0 /* Enable this if you want to see details */
2484                         IWL_ERR(priv, "uCode INST section is invalid at "
2485                                   "offset 0x%x, is 0x%x, s/b 0x%x\n",
2486                                   i, val, *image);
2487 #endif
2488                         rc = -EIO;
2489                         errcnt++;
2490                         if (errcnt >= 3)
2491                                 break;
2492                 }
2493         }
2494
2495         iwl_release_nic_access(priv);
2496
2497         return rc;
2498 }
2499
2500
2501 /**
2502  * iwl3945_verify_ucode - determine which instruction image is in SRAM,
2503  *    and verify its contents
2504  */
2505 static int iwl3945_verify_ucode(struct iwl_priv *priv)
2506 {
2507         __le32 *image;
2508         u32 len;
2509         int rc = 0;
2510
2511         /* Try bootstrap */
2512         image = (__le32 *)priv->ucode_boot.v_addr;
2513         len = priv->ucode_boot.len;
2514         rc = iwl3945_verify_inst_sparse(priv, image, len);
2515         if (rc == 0) {
2516                 IWL_DEBUG_INFO(priv, "Bootstrap uCode is good in inst SRAM\n");
2517                 return 0;
2518         }
2519
2520         /* Try initialize */
2521         image = (__le32 *)priv->ucode_init.v_addr;
2522         len = priv->ucode_init.len;
2523         rc = iwl3945_verify_inst_sparse(priv, image, len);
2524         if (rc == 0) {
2525                 IWL_DEBUG_INFO(priv, "Initialize uCode is good in inst SRAM\n");
2526                 return 0;
2527         }
2528
2529         /* Try runtime/protocol */
2530         image = (__le32 *)priv->ucode_code.v_addr;
2531         len = priv->ucode_code.len;
2532         rc = iwl3945_verify_inst_sparse(priv, image, len);
2533         if (rc == 0) {
2534                 IWL_DEBUG_INFO(priv, "Runtime uCode is good in inst SRAM\n");
2535                 return 0;
2536         }
2537
2538         IWL_ERR(priv, "NO VALID UCODE IMAGE IN INSTRUCTION SRAM!!\n");
2539
2540         /* Since nothing seems to match, show first several data entries in
2541          * instruction SRAM, so maybe visual inspection will give a clue.
2542          * Selection of bootstrap image (vs. other images) is arbitrary. */
2543         image = (__le32 *)priv->ucode_boot.v_addr;
2544         len = priv->ucode_boot.len;
2545         rc = iwl3945_verify_inst_full(priv, image, len);
2546
2547         return rc;
2548 }
2549
2550 static void iwl3945_nic_start(struct iwl_priv *priv)
2551 {
2552         /* Remove all resets to allow NIC to operate */
2553         iwl_write32(priv, CSR_RESET, 0);
2554 }
2555
2556 /**
2557  * iwl3945_read_ucode - Read uCode images from disk file.
2558  *
2559  * Copy into buffers for card to fetch via bus-mastering
2560  */
2561 static int iwl3945_read_ucode(struct iwl_priv *priv)
2562 {
2563         struct iwl_ucode *ucode;
2564         int ret = -EINVAL, index;
2565         const struct firmware *ucode_raw;
2566         /* firmware file name contains uCode/driver compatibility version */
2567         const char *name_pre = priv->cfg->fw_name_pre;
2568         const unsigned int api_max = priv->cfg->ucode_api_max;
2569         const unsigned int api_min = priv->cfg->ucode_api_min;
2570         char buf[25];
2571         u8 *src;
2572         size_t len;
2573         u32 api_ver, inst_size, data_size, init_size, init_data_size, boot_size;
2574
2575         /* Ask kernel firmware_class module to get the boot firmware off disk.
2576          * request_firmware() is synchronous, file is in memory on return. */
2577         for (index = api_max; index >= api_min; index--) {
2578                 sprintf(buf, "%s%u%s", name_pre, index, ".ucode");
2579                 ret = request_firmware(&ucode_raw, buf, &priv->pci_dev->dev);
2580                 if (ret < 0) {
2581                         IWL_ERR(priv, "%s firmware file req failed: %d\n",
2582                                   buf, ret);
2583                         if (ret == -ENOENT)
2584                                 continue;
2585                         else
2586                                 goto error;
2587                 } else {
2588                         if (index < api_max)
2589                                 IWL_ERR(priv, "Loaded firmware %s, "
2590                                         "which is deprecated. "
2591                                         " Please use API v%u instead.\n",
2592                                           buf, api_max);
2593                         IWL_DEBUG_INFO(priv, "Got firmware '%s' file "
2594                                        "(%zd bytes) from disk\n",
2595                                        buf, ucode_raw->size);
2596                         break;
2597                 }
2598         }
2599
2600         if (ret < 0)
2601                 goto error;
2602
2603         /* Make sure that we got at least our header! */
2604         if (ucode_raw->size < sizeof(*ucode)) {
2605                 IWL_ERR(priv, "File size way too small!\n");
2606                 ret = -EINVAL;
2607                 goto err_release;
2608         }
2609
2610         /* Data from ucode file:  header followed by uCode images */
2611         ucode = (void *)ucode_raw->data;
2612
2613         priv->ucode_ver = le32_to_cpu(ucode->ver);
2614         api_ver = IWL_UCODE_API(priv->ucode_ver);
2615         inst_size = le32_to_cpu(ucode->inst_size);
2616         data_size = le32_to_cpu(ucode->data_size);
2617         init_size = le32_to_cpu(ucode->init_size);
2618         init_data_size = le32_to_cpu(ucode->init_data_size);
2619         boot_size = le32_to_cpu(ucode->boot_size);
2620
2621         /* api_ver should match the api version forming part of the
2622          * firmware filename ... but we don't check for that and only rely
2623          * on the API version read from firmware header from here on forward */
2624
2625         if (api_ver < api_min || api_ver > api_max) {
2626                 IWL_ERR(priv, "Driver unable to support your firmware API. "
2627                           "Driver supports v%u, firmware is v%u.\n",
2628                           api_max, api_ver);
2629                 priv->ucode_ver = 0;
2630                 ret = -EINVAL;
2631                 goto err_release;
2632         }
2633         if (api_ver != api_max)
2634                 IWL_ERR(priv, "Firmware has old API version. Expected %u, "
2635                           "got %u. New firmware can be obtained "
2636                           "from http://www.intellinuxwireless.org.\n",
2637                           api_max, api_ver);
2638
2639         IWL_INFO(priv, "loaded firmware version %u.%u.%u.%u\n",
2640                 IWL_UCODE_MAJOR(priv->ucode_ver),
2641                 IWL_UCODE_MINOR(priv->ucode_ver),
2642                 IWL_UCODE_API(priv->ucode_ver),
2643                 IWL_UCODE_SERIAL(priv->ucode_ver));
2644
2645         IWL_DEBUG_INFO(priv, "f/w package hdr ucode version raw = 0x%x\n",
2646                        priv->ucode_ver);
2647         IWL_DEBUG_INFO(priv, "f/w package hdr runtime inst size = %u\n",
2648                        inst_size);
2649         IWL_DEBUG_INFO(priv, "f/w package hdr runtime data size = %u\n",
2650                        data_size);
2651         IWL_DEBUG_INFO(priv, "f/w package hdr init inst size = %u\n",
2652                        init_size);
2653         IWL_DEBUG_INFO(priv, "f/w package hdr init data size = %u\n",
2654                        init_data_size);
2655         IWL_DEBUG_INFO(priv, "f/w package hdr boot inst size = %u\n",
2656                        boot_size);
2657
2658
2659         /* Verify size of file vs. image size info in file's header */
2660         if (ucode_raw->size < sizeof(*ucode) +
2661                 inst_size + data_size + init_size +
2662                 init_data_size + boot_size) {
2663
2664                 IWL_DEBUG_INFO(priv, "uCode file size %zd too small\n",
2665                                ucode_raw->size);
2666                 ret = -EINVAL;
2667                 goto err_release;
2668         }
2669
2670         /* Verify that uCode images will fit in card's SRAM */
2671         if (inst_size > IWL39_MAX_INST_SIZE) {
2672                 IWL_DEBUG_INFO(priv, "uCode instr len %d too large to fit in\n",
2673                                inst_size);
2674                 ret = -EINVAL;
2675                 goto err_release;
2676         }
2677
2678         if (data_size > IWL39_MAX_DATA_SIZE) {
2679                 IWL_DEBUG_INFO(priv, "uCode data len %d too large to fit in\n",
2680                                data_size);
2681                 ret = -EINVAL;
2682                 goto err_release;
2683         }
2684         if (init_size > IWL39_MAX_INST_SIZE) {
2685                 IWL_DEBUG_INFO(priv,
2686                                 "uCode init instr len %d too large to fit in\n",
2687                                 init_size);
2688                 ret = -EINVAL;
2689                 goto err_release;
2690         }
2691         if (init_data_size > IWL39_MAX_DATA_SIZE) {
2692                 IWL_DEBUG_INFO(priv,
2693                                 "uCode init data len %d too large to fit in\n",
2694                                 init_data_size);
2695                 ret = -EINVAL;
2696                 goto err_release;
2697         }
2698         if (boot_size > IWL39_MAX_BSM_SIZE) {
2699                 IWL_DEBUG_INFO(priv,
2700                                 "uCode boot instr len %d too large to fit in\n",
2701                                 boot_size);
2702                 ret = -EINVAL;
2703                 goto err_release;
2704         }
2705
2706         /* Allocate ucode buffers for card's bus-master loading ... */
2707
2708         /* Runtime instructions and 2 copies of data:
2709          * 1) unmodified from disk
2710          * 2) backup cache for save/restore during power-downs */
2711         priv->ucode_code.len = inst_size;
2712         iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_code);
2713
2714         priv->ucode_data.len = data_size;
2715         iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_data);
2716
2717         priv->ucode_data_backup.len = data_size;
2718         iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_data_backup);
2719
2720         if (!priv->ucode_code.v_addr || !priv->ucode_data.v_addr ||
2721             !priv->ucode_data_backup.v_addr)
2722                 goto err_pci_alloc;
2723
2724         /* Initialization instructions and data */
2725         if (init_size && init_data_size) {
2726                 priv->ucode_init.len = init_size;
2727                 iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_init);
2728
2729                 priv->ucode_init_data.len = init_data_size;
2730                 iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_init_data);
2731
2732                 if (!priv->ucode_init.v_addr || !priv->ucode_init_data.v_addr)
2733                         goto err_pci_alloc;
2734         }
2735
2736         /* Bootstrap (instructions only, no data) */
2737         if (boot_size) {
2738                 priv->ucode_boot.len = boot_size;
2739                 iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_boot);
2740
2741                 if (!priv->ucode_boot.v_addr)
2742                         goto err_pci_alloc;
2743         }
2744
2745         /* Copy images into buffers for card's bus-master reads ... */
2746
2747         /* Runtime instructions (first block of data in file) */
2748         src = &ucode->data[0];
2749         len = priv->ucode_code.len;
2750         IWL_DEBUG_INFO(priv,
2751                 "Copying (but not loading) uCode instr len %zd\n", len);
2752         memcpy(priv->ucode_code.v_addr, src, len);
2753         IWL_DEBUG_INFO(priv, "uCode instr buf vaddr = 0x%p, paddr = 0x%08x\n",
2754                 priv->ucode_code.v_addr, (u32)priv->ucode_code.p_addr);
2755
2756         /* Runtime data (2nd block)
2757          * NOTE:  Copy into backup buffer will be done in iwl3945_up()  */
2758         src = &ucode->data[inst_size];
2759         len = priv->ucode_data.len;
2760         IWL_DEBUG_INFO(priv,
2761                 "Copying (but not loading) uCode data len %zd\n", len);
2762         memcpy(priv->ucode_data.v_addr, src, len);
2763         memcpy(priv->ucode_data_backup.v_addr, src, len);
2764
2765         /* Initialization instructions (3rd block) */
2766         if (init_size) {
2767                 src = &ucode->data[inst_size + data_size];
2768                 len = priv->ucode_init.len;
2769                 IWL_DEBUG_INFO(priv,
2770                         "Copying (but not loading) init instr len %zd\n", len);
2771                 memcpy(priv->ucode_init.v_addr, src, len);
2772         }
2773
2774         /* Initialization data (4th block) */
2775         if (init_data_size) {
2776                 src = &ucode->data[inst_size + data_size + init_size];
2777                 len = priv->ucode_init_data.len;
2778                 IWL_DEBUG_INFO(priv,
2779                         "Copying (but not loading) init data len %zd\n", len);
2780                 memcpy(priv->ucode_init_data.v_addr, src, len);
2781         }
2782
2783         /* Bootstrap instructions (5th block) */
2784         src = &ucode->data[inst_size + data_size + init_size + init_data_size];
2785         len = priv->ucode_boot.len;
2786         IWL_DEBUG_INFO(priv,
2787                 "Copying (but not loading) boot instr len %zd\n", len);
2788         memcpy(priv->ucode_boot.v_addr, src, len);
2789
2790         /* We have our copies now, allow OS release its copies */
2791         release_firmware(ucode_raw);
2792         return 0;
2793
2794  err_pci_alloc:
2795         IWL_ERR(priv, "failed to allocate pci memory\n");
2796         ret = -ENOMEM;
2797         iwl3945_dealloc_ucode_pci(priv);
2798
2799  err_release:
2800         release_firmware(ucode_raw);
2801
2802  error:
2803         return ret;
2804 }
2805
2806
2807 /**
2808  * iwl3945_set_ucode_ptrs - Set uCode address location
2809  *
2810  * Tell initialization uCode where to find runtime uCode.
2811  *
2812  * BSM registers initially contain pointers to initialization uCode.
2813  * We need to replace them to load runtime uCode inst and data,
2814  * and to save runtime data when powering down.
2815  */
2816 static int iwl3945_set_ucode_ptrs(struct iwl_priv *priv)
2817 {
2818         dma_addr_t pinst;
2819         dma_addr_t pdata;
2820         int rc = 0;
2821         unsigned long flags;
2822
2823         /* bits 31:0 for 3945 */
2824         pinst = priv->ucode_code.p_addr;
2825         pdata = priv->ucode_data_backup.p_addr;
2826
2827         spin_lock_irqsave(&priv->lock, flags);
2828         rc = iwl_grab_nic_access(priv);
2829         if (rc) {
2830                 spin_unlock_irqrestore(&priv->lock, flags);
2831                 return rc;
2832         }
2833
2834         /* Tell bootstrap uCode where to find image to load */
2835         iwl_write_prph(priv, BSM_DRAM_INST_PTR_REG, pinst);
2836         iwl_write_prph(priv, BSM_DRAM_DATA_PTR_REG, pdata);
2837         iwl_write_prph(priv, BSM_DRAM_DATA_BYTECOUNT_REG,
2838                                  priv->ucode_data.len);
2839
2840         /* Inst byte count must be last to set up, bit 31 signals uCode
2841          *   that all new ptr/size info is in place */
2842         iwl_write_prph(priv, BSM_DRAM_INST_BYTECOUNT_REG,
2843                                  priv->ucode_code.len | BSM_DRAM_INST_LOAD);
2844
2845         iwl_release_nic_access(priv);
2846
2847         spin_unlock_irqrestore(&priv->lock, flags);
2848
2849         IWL_DEBUG_INFO(priv, "Runtime uCode pointers are set.\n");
2850
2851         return rc;
2852 }
2853
2854 /**
2855  * iwl3945_init_alive_start - Called after REPLY_ALIVE notification received
2856  *
2857  * Called after REPLY_ALIVE notification received from "initialize" uCode.
2858  *
2859  * Tell "initialize" uCode to go ahead and load the runtime uCode.
2860  */
2861 static void iwl3945_init_alive_start(struct iwl_priv *priv)
2862 {
2863         /* Check alive response for "valid" sign from uCode */
2864         if (priv->card_alive_init.is_valid != UCODE_VALID_OK) {
2865                 /* We had an error bringing up the hardware, so take it
2866                  * all the way back down so we can try again */
2867                 IWL_DEBUG_INFO(priv, "Initialize Alive failed.\n");
2868                 goto restart;
2869         }
2870
2871         /* Bootstrap uCode has loaded initialize uCode ... verify inst image.
2872          * This is a paranoid check, because we would not have gotten the
2873          * "initialize" alive if code weren't properly loaded.  */
2874         if (iwl3945_verify_ucode(priv)) {
2875                 /* Runtime instruction load was bad;
2876                  * take it all the way back down so we can try again */
2877                 IWL_DEBUG_INFO(priv, "Bad \"initialize\" uCode load.\n");
2878                 goto restart;
2879         }
2880
2881         /* Send pointers to protocol/runtime uCode image ... init code will
2882          * load and launch runtime uCode, which will send us another "Alive"
2883          * notification. */
2884         IWL_DEBUG_INFO(priv, "Initialization Alive received.\n");
2885         if (iwl3945_set_ucode_ptrs(priv)) {
2886                 /* Runtime instruction load won't happen;
2887                  * take it all the way back down so we can try again */
2888                 IWL_DEBUG_INFO(priv, "Couldn't set up uCode pointers.\n");
2889                 goto restart;
2890         }
2891         return;
2892
2893  restart:
2894         queue_work(priv->workqueue, &priv->restart);
2895 }
2896
2897
2898 /* temporary */
2899 static int iwl3945_mac_beacon_update(struct ieee80211_hw *hw,
2900                                      struct sk_buff *skb);
2901
2902 /**
2903  * iwl3945_alive_start - called after REPLY_ALIVE notification received
2904  *                   from protocol/runtime uCode (initialization uCode's
2905  *                   Alive gets handled by iwl3945_init_alive_start()).
2906  */
2907 static void iwl3945_alive_start(struct iwl_priv *priv)
2908 {
2909         int rc = 0;
2910         int thermal_spin = 0;
2911         u32 rfkill;
2912
2913         IWL_DEBUG_INFO(priv, "Runtime Alive received.\n");
2914
2915         if (priv->card_alive.is_valid != UCODE_VALID_OK) {
2916                 /* We had an error bringing up the hardware, so take it
2917                  * all the way back down so we can try again */
2918                 IWL_DEBUG_INFO(priv, "Alive failed.\n");
2919                 goto restart;
2920         }
2921
2922         /* Initialize uCode has loaded Runtime uCode ... verify inst image.
2923          * This is a paranoid check, because we would not have gotten the
2924          * "runtime" alive if code weren't properly loaded.  */
2925         if (iwl3945_verify_ucode(priv)) {
2926                 /* Runtime instruction load was bad;
2927                  * take it all the way back down so we can try again */
2928                 IWL_DEBUG_INFO(priv, "Bad runtime uCode load.\n");
2929                 goto restart;
2930         }
2931
2932         iwl3945_clear_stations_table(priv);
2933
2934         rc = iwl_grab_nic_access(priv);
2935         if (rc) {
2936                 IWL_WARN(priv, "Can not read RFKILL status from adapter\n");
2937                 return;
2938         }
2939
2940         rfkill = iwl_read_prph(priv, APMG_RFKILL_REG);
2941         IWL_DEBUG_INFO(priv, "RFKILL status: 0x%x\n", rfkill);
2942         iwl_release_nic_access(priv);
2943
2944         if (rfkill & 0x1) {
2945                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
2946                 /* if RFKILL is not on, then wait for thermal
2947                  * sensor in adapter to kick in */
2948                 while (iwl3945_hw_get_temperature(priv) == 0) {
2949                         thermal_spin++;
2950                         udelay(10);
2951                 }
2952
2953                 if (thermal_spin)
2954                         IWL_DEBUG_INFO(priv, "Thermal calibration took %dus\n",
2955                                        thermal_spin * 10);
2956         } else
2957                 set_bit(STATUS_RF_KILL_HW, &priv->status);
2958
2959         /* After the ALIVE response, we can send commands to 3945 uCode */
2960         set_bit(STATUS_ALIVE, &priv->status);
2961
2962         /* Clear out the uCode error bit if it is set */
2963         clear_bit(STATUS_FW_ERROR, &priv->status);
2964
2965         if (iwl_is_rfkill(priv))
2966                 return;
2967
2968         ieee80211_wake_queues(priv->hw);
2969
2970         priv->active_rate = priv->rates_mask;
2971         priv->active_rate_basic = priv->rates_mask & IWL_BASIC_RATES_MASK;
2972
2973         iwl_power_update_mode(priv, false);
2974
2975         if (iwl_is_associated(priv)) {
2976                 struct iwl3945_rxon_cmd *active_rxon =
2977                                 (struct iwl3945_rxon_cmd *)(&priv->active_rxon);
2978
2979                 memcpy(&priv->staging_rxon, &priv->active_rxon,
2980                        sizeof(priv->staging_rxon));
2981                 active_rxon->filter_flags &= ~RXON_FILTER_ASSOC_MSK;
2982         } else {
2983                 /* Initialize our rx_config data */
2984                 iwl_connection_init_rx_config(priv, priv->iw_mode);
2985         }
2986
2987         /* Configure Bluetooth device coexistence support */
2988         iwl_send_bt_config(priv);
2989
2990         /* Configure the adapter for unassociated operation */
2991         iwl3945_commit_rxon(priv);
2992
2993         iwl3945_reg_txpower_periodic(priv);
2994
2995         iwl3945_led_register(priv);
2996
2997         IWL_DEBUG_INFO(priv, "ALIVE processing complete.\n");
2998         set_bit(STATUS_READY, &priv->status);
2999         wake_up_interruptible(&priv->wait_command_queue);
3000
3001         if (priv->error_recovering)
3002                 iwl3945_error_recovery(priv);
3003
3004         /* reassociate for ADHOC mode */
3005         if (priv->vif && (priv->iw_mode == NL80211_IFTYPE_ADHOC)) {
3006                 struct sk_buff *beacon = ieee80211_beacon_get(priv->hw,
3007                                                                 priv->vif);
3008                 if (beacon)
3009                         iwl3945_mac_beacon_update(priv->hw, beacon);
3010         }
3011
3012         return;
3013
3014  restart:
3015         queue_work(priv->workqueue, &priv->restart);
3016 }
3017
3018 static void iwl3945_cancel_deferred_work(struct iwl_priv *priv);
3019
3020 static void __iwl3945_down(struct iwl_priv *priv)
3021 {
3022         unsigned long flags;
3023         int exit_pending = test_bit(STATUS_EXIT_PENDING, &priv->status);
3024         struct ieee80211_conf *conf = NULL;
3025
3026         IWL_DEBUG_INFO(priv, DRV_NAME " is going down\n");
3027
3028         conf = ieee80211_get_hw_conf(priv->hw);
3029
3030         if (!exit_pending)
3031                 set_bit(STATUS_EXIT_PENDING, &priv->status);
3032
3033         iwl3945_led_unregister(priv);
3034         iwl3945_clear_stations_table(priv);
3035
3036         /* Unblock any waiting calls */
3037         wake_up_interruptible_all(&priv->wait_command_queue);
3038
3039         /* Wipe out the EXIT_PENDING status bit if we are not actually
3040          * exiting the module */
3041         if (!exit_pending)
3042                 clear_bit(STATUS_EXIT_PENDING, &priv->status);
3043
3044         /* stop and reset the on-board processor */
3045         iwl_write32(priv, CSR_RESET, CSR_RESET_REG_FLAG_NEVO_RESET);
3046
3047         /* tell the device to stop sending interrupts */
3048         spin_lock_irqsave(&priv->lock, flags);
3049         iwl_disable_interrupts(priv);
3050         spin_unlock_irqrestore(&priv->lock, flags);
3051         iwl_synchronize_irq(priv);
3052
3053         if (priv->mac80211_registered)
3054                 ieee80211_stop_queues(priv->hw);
3055
3056         /* If we have not previously called iwl3945_init() then
3057          * clear all bits but the RF Kill and SUSPEND bits and return */
3058         if (!iwl_is_init(priv)) {
3059                 priv->status = test_bit(STATUS_RF_KILL_HW, &priv->status) <<
3060                                         STATUS_RF_KILL_HW |
3061                                test_bit(STATUS_RF_KILL_SW, &priv->status) <<
3062                                         STATUS_RF_KILL_SW |
3063                                test_bit(STATUS_GEO_CONFIGURED, &priv->status) <<
3064                                         STATUS_GEO_CONFIGURED |
3065                                test_bit(STATUS_IN_SUSPEND, &priv->status) <<
3066                                         STATUS_IN_SUSPEND |
3067                                 test_bit(STATUS_EXIT_PENDING, &priv->status) <<
3068                                         STATUS_EXIT_PENDING;
3069                 goto exit;
3070         }
3071
3072         /* ...otherwise clear out all the status bits but the RF Kill and
3073          * SUSPEND bits and continue taking the NIC down. */
3074         priv->status &= test_bit(STATUS_RF_KILL_HW, &priv->status) <<
3075                                 STATUS_RF_KILL_HW |
3076                         test_bit(STATUS_RF_KILL_SW, &priv->status) <<
3077                                 STATUS_RF_KILL_SW |
3078                         test_bit(STATUS_GEO_CONFIGURED, &priv->status) <<
3079                                 STATUS_GEO_CONFIGURED |
3080                         test_bit(STATUS_IN_SUSPEND, &priv->status) <<
3081                                 STATUS_IN_SUSPEND |
3082                         test_bit(STATUS_FW_ERROR, &priv->status) <<
3083                                 STATUS_FW_ERROR |
3084                         test_bit(STATUS_EXIT_PENDING, &priv->status) <<
3085                                 STATUS_EXIT_PENDING;
3086
3087         priv->cfg->ops->lib->apm_ops.reset(priv);
3088         spin_lock_irqsave(&priv->lock, flags);
3089         iwl_clear_bit(priv, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
3090         spin_unlock_irqrestore(&priv->lock, flags);
3091
3092         iwl3945_hw_txq_ctx_stop(priv);
3093         iwl3945_hw_rxq_stop(priv);
3094
3095         spin_lock_irqsave(&priv->lock, flags);
3096         if (!iwl_grab_nic_access(priv)) {
3097                 iwl_write_prph(priv, APMG_CLK_DIS_REG,
3098                                          APMG_CLK_VAL_DMA_CLK_RQT);
3099                 iwl_release_nic_access(priv);
3100         }
3101         spin_unlock_irqrestore(&priv->lock, flags);
3102
3103         udelay(5);
3104
3105         if (exit_pending || test_bit(STATUS_IN_SUSPEND, &priv->status))
3106                 priv->cfg->ops->lib->apm_ops.stop(priv);
3107         else
3108                 priv->cfg->ops->lib->apm_ops.reset(priv);
3109
3110  exit:
3111         memset(&priv->card_alive, 0, sizeof(struct iwl_alive_resp));
3112
3113         if (priv->ibss_beacon)
3114                 dev_kfree_skb(priv->ibss_beacon);
3115         priv->ibss_beacon = NULL;
3116
3117         /* clear out any free frames */
3118         iwl3945_clear_free_frames(priv);
3119 }
3120
3121 static void iwl3945_down(struct iwl_priv *priv)
3122 {
3123         mutex_lock(&priv->mutex);
3124         __iwl3945_down(priv);
3125         mutex_unlock(&priv->mutex);
3126
3127         iwl3945_cancel_deferred_work(priv);
3128 }
3129
3130 #define MAX_HW_RESTARTS 5
3131
3132 static int __iwl3945_up(struct iwl_priv *priv)
3133 {
3134         int rc, i;
3135
3136         if (test_bit(STATUS_EXIT_PENDING, &priv->status)) {
3137                 IWL_WARN(priv, "Exit pending; will not bring the NIC up\n");
3138                 return -EIO;
3139         }
3140
3141         if (test_bit(STATUS_RF_KILL_SW, &priv->status)) {
3142                 IWL_WARN(priv, "Radio disabled by SW RF kill (module "
3143                             "parameter)\n");
3144                 return -ENODEV;
3145         }
3146
3147         if (!priv->ucode_data_backup.v_addr || !priv->ucode_data.v_addr) {
3148                 IWL_ERR(priv, "ucode not available for device bring up\n");
3149                 return -EIO;
3150         }
3151
3152         /* If platform's RF_KILL switch is NOT set to KILL */
3153         if (iwl_read32(priv, CSR_GP_CNTRL) &
3154                                 CSR_GP_CNTRL_REG_FLAG_HW_RF_KILL_SW)
3155                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
3156         else {
3157                 set_bit(STATUS_RF_KILL_HW, &priv->status);
3158                 if (!test_bit(STATUS_IN_SUSPEND, &priv->status)) {
3159                         IWL_WARN(priv, "Radio disabled by HW RF Kill switch\n");
3160                         return -ENODEV;
3161                 }
3162         }
3163
3164         iwl_write32(priv, CSR_INT, 0xFFFFFFFF);
3165
3166         rc = iwl3945_hw_nic_init(priv);
3167         if (rc) {
3168                 IWL_ERR(priv, "Unable to int nic\n");
3169                 return rc;
3170         }
3171
3172         /* make sure rfkill handshake bits are cleared */
3173         iwl_write32(priv, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
3174         iwl_write32(priv, CSR_UCODE_DRV_GP1_CLR,
3175                     CSR_UCODE_DRV_GP1_BIT_CMD_BLOCKED);
3176
3177         /* clear (again), then enable host interrupts */
3178         iwl_write32(priv, CSR_INT, 0xFFFFFFFF);
3179         iwl_enable_interrupts(priv);
3180
3181         /* really make sure rfkill handshake bits are cleared */
3182         iwl_write32(priv, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
3183         iwl_write32(priv, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
3184
3185         /* Copy original ucode data image from disk into backup cache.
3186          * This will be used to initialize the on-board processor's
3187          * data SRAM for a clean start when the runtime program first loads. */
3188         memcpy(priv->ucode_data_backup.v_addr, priv->ucode_data.v_addr,
3189                priv->ucode_data.len);
3190
3191         /* We return success when we resume from suspend and rf_kill is on. */
3192         if (test_bit(STATUS_RF_KILL_HW, &priv->status))
3193                 return 0;
3194
3195         for (i = 0; i < MAX_HW_RESTARTS; i++) {
3196
3197                 iwl3945_clear_stations_table(priv);
3198
3199                 /* load bootstrap state machine,
3200                  * load bootstrap program into processor's memory,
3201                  * prepare to load the "initialize" uCode */
3202                 priv->cfg->ops->lib->load_ucode(priv);
3203
3204                 if (rc) {
3205                         IWL_ERR(priv,
3206                                 "Unable to set up bootstrap uCode: %d\n", rc);
3207                         continue;
3208                 }
3209
3210                 /* start card; "initialize" will load runtime ucode */
3211                 iwl3945_nic_start(priv);
3212
3213                 IWL_DEBUG_INFO(priv, DRV_NAME " is coming up\n");
3214
3215                 return 0;
3216         }
3217
3218         set_bit(STATUS_EXIT_PENDING, &priv->status);
3219         __iwl3945_down(priv);
3220         clear_bit(STATUS_EXIT_PENDING, &priv->status);
3221
3222         /* tried to restart and config the device for as long as our
3223          * patience could withstand */
3224         IWL_ERR(priv, "Unable to initialize device after %d attempts.\n", i);
3225         return -EIO;
3226 }
3227
3228
3229 /*****************************************************************************
3230  *
3231  * Workqueue callbacks
3232  *
3233  *****************************************************************************/
3234
3235 static void iwl3945_bg_init_alive_start(struct work_struct *data)
3236 {
3237         struct iwl_priv *priv =
3238             container_of(data, struct iwl_priv, init_alive_start.work);
3239
3240         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
3241                 return;
3242
3243         mutex_lock(&priv->mutex);
3244         iwl3945_init_alive_start(priv);
3245         mutex_unlock(&priv->mutex);
3246 }
3247
3248 static void iwl3945_bg_alive_start(struct work_struct *data)
3249 {
3250         struct iwl_priv *priv =
3251             container_of(data, struct iwl_priv, alive_start.work);
3252
3253         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
3254                 return;
3255
3256         mutex_lock(&priv->mutex);
3257         iwl3945_alive_start(priv);
3258         mutex_unlock(&priv->mutex);
3259 }
3260
3261 static void iwl3945_rfkill_poll(struct work_struct *data)
3262 {
3263         struct iwl_priv *priv =
3264             container_of(data, struct iwl_priv, rfkill_poll.work);
3265         unsigned long status = priv->status;
3266
3267         if (iwl_read32(priv, CSR_GP_CNTRL) & CSR_GP_CNTRL_REG_FLAG_HW_RF_KILL_SW)
3268                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
3269         else
3270                 set_bit(STATUS_RF_KILL_HW, &priv->status);
3271
3272         if (test_bit(STATUS_RF_KILL_HW, &status) != test_bit(STATUS_RF_KILL_HW, &priv->status))
3273                 queue_work(priv->workqueue, &priv->rf_kill);
3274
3275         queue_delayed_work(priv->workqueue, &priv->rfkill_poll,
3276                            round_jiffies_relative(2 * HZ));
3277
3278 }
3279
3280 #define IWL_SCAN_CHECK_WATCHDOG (7 * HZ)
3281 static void iwl3945_bg_request_scan(struct work_struct *data)
3282 {
3283         struct iwl_priv *priv =
3284             container_of(data, struct iwl_priv, request_scan);
3285         struct iwl_host_cmd cmd = {
3286                 .id = REPLY_SCAN_CMD,
3287                 .len = sizeof(struct iwl3945_scan_cmd),
3288                 .meta.flags = CMD_SIZE_HUGE,
3289         };
3290         int rc = 0;
3291         struct iwl3945_scan_cmd *scan;
3292         struct ieee80211_conf *conf = NULL;
3293         u8 n_probes = 2;
3294         enum ieee80211_band band;
3295         DECLARE_SSID_BUF(ssid);
3296
3297         conf = ieee80211_get_hw_conf(priv->hw);
3298
3299         mutex_lock(&priv->mutex);
3300
3301         if (!iwl_is_ready(priv)) {
3302                 IWL_WARN(priv, "request scan called when driver not ready.\n");
3303                 goto done;
3304         }
3305
3306         /* Make sure the scan wasn't canceled before this queued work
3307          * was given the chance to run... */
3308         if (!test_bit(STATUS_SCANNING, &priv->status))
3309                 goto done;
3310
3311         /* This should never be called or scheduled if there is currently
3312          * a scan active in the hardware. */
3313         if (test_bit(STATUS_SCAN_HW, &priv->status)) {
3314                 IWL_DEBUG_INFO(priv, "Multiple concurrent scan requests  "
3315                                 "Ignoring second request.\n");
3316                 rc = -EIO;
3317                 goto done;
3318         }
3319
3320         if (test_bit(STATUS_EXIT_PENDING, &priv->status)) {
3321                 IWL_DEBUG_SCAN(priv, "Aborting scan due to device shutdown\n");
3322                 goto done;
3323         }
3324
3325         if (test_bit(STATUS_SCAN_ABORTING, &priv->status)) {
3326                 IWL_DEBUG_HC(priv,
3327                         "Scan request while abort pending. Queuing.\n");
3328                 goto done;
3329         }
3330
3331         if (iwl_is_rfkill(priv)) {
3332                 IWL_DEBUG_HC(priv, "Aborting scan due to RF Kill activation\n");
3333                 goto done;
3334         }
3335
3336         if (!test_bit(STATUS_READY, &priv->status)) {
3337                 IWL_DEBUG_HC(priv,
3338                         "Scan request while uninitialized. Queuing.\n");
3339                 goto done;
3340         }
3341
3342         if (!priv->scan_bands) {
3343                 IWL_DEBUG_HC(priv, "Aborting scan due to no requested bands\n");
3344                 goto done;
3345         }
3346
3347         if (!priv->scan) {
3348                 priv->scan = kmalloc(sizeof(struct iwl3945_scan_cmd) +
3349                                      IWL_MAX_SCAN_SIZE, GFP_KERNEL);
3350                 if (!priv->scan) {
3351                         rc = -ENOMEM;
3352                         goto done;
3353                 }
3354         }
3355         scan = priv->scan;
3356         memset(scan, 0, sizeof(struct iwl3945_scan_cmd) + IWL_MAX_SCAN_SIZE);
3357
3358         scan->quiet_plcp_th = IWL_PLCP_QUIET_THRESH;
3359         scan->quiet_time = IWL_ACTIVE_QUIET_TIME;
3360
3361         if (iwl_is_associated(priv)) {
3362                 u16 interval = 0;
3363                 u32 extra;
3364                 u32 suspend_time = 100;
3365                 u32 scan_suspend_time = 100;
3366                 unsigned long flags;
3367
3368                 IWL_DEBUG_INFO(priv, "Scanning while associated...\n");
3369
3370                 spin_lock_irqsave(&priv->lock, flags);
3371                 interval = priv->beacon_int;
3372                 spin_unlock_irqrestore(&priv->lock, flags);
3373
3374                 scan->suspend_time = 0;
3375                 scan->max_out_time = cpu_to_le32(200 * 1024);
3376                 if (!interval)
3377                         interval = suspend_time;
3378                 /*
3379                  * suspend time format:
3380                  *  0-19: beacon interval in usec (time before exec.)
3381                  * 20-23: 0
3382                  * 24-31: number of beacons (suspend between channels)
3383                  */
3384
3385                 extra = (suspend_time / interval) << 24;
3386                 scan_suspend_time = 0xFF0FFFFF &
3387                     (extra | ((suspend_time % interval) * 1024));
3388
3389                 scan->suspend_time = cpu_to_le32(scan_suspend_time);
3390                 IWL_DEBUG_SCAN(priv, "suspend_time 0x%X beacon interval %d\n",
3391                                scan_suspend_time, interval);
3392         }
3393
3394         /* We should add the ability for user to lock to PASSIVE ONLY */
3395         if (priv->one_direct_scan) {
3396                 IWL_DEBUG_SCAN(priv, "Kicking off one direct scan for '%s'\n",
3397                                 print_ssid(ssid, priv->direct_ssid,
3398                                 priv->direct_ssid_len));
3399                 scan->direct_scan[0].id = WLAN_EID_SSID;
3400                 scan->direct_scan[0].len = priv->direct_ssid_len;
3401                 memcpy(scan->direct_scan[0].ssid,
3402                        priv->direct_ssid, priv->direct_ssid_len);
3403                 n_probes++;
3404         } else
3405                 IWL_DEBUG_SCAN(priv, "Kicking off one indirect scan.\n");
3406
3407         /* We don't build a direct scan probe request; the uCode will do
3408          * that based on the direct_mask added to each channel entry */
3409         scan->tx_cmd.tx_flags = TX_CMD_FLG_SEQ_CTL_MSK;
3410         scan->tx_cmd.sta_id = priv->hw_params.bcast_sta_id;
3411         scan->tx_cmd.stop_time.life_time = TX_CMD_LIFE_TIME_INFINITE;
3412
3413         /* flags + rate selection */
3414
3415         if (priv->scan_bands & BIT(IEEE80211_BAND_2GHZ)) {
3416                 scan->flags = RXON_FLG_BAND_24G_MSK | RXON_FLG_AUTO_DETECT_MSK;
3417                 scan->tx_cmd.rate = IWL_RATE_1M_PLCP;
3418                 scan->good_CRC_th = 0;
3419                 band = IEEE80211_BAND_2GHZ;
3420         } else if (priv->scan_bands & BIT(IEEE80211_BAND_5GHZ)) {
3421                 scan->tx_cmd.rate = IWL_RATE_6M_PLCP;
3422                 scan->good_CRC_th = IWL_GOOD_CRC_TH;
3423                 band = IEEE80211_BAND_5GHZ;
3424         } else {
3425                 IWL_WARN(priv, "Invalid scan band count\n");
3426                 goto done;
3427         }
3428
3429         scan->tx_cmd.len = cpu_to_le16(
3430                 iwl_fill_probe_req(priv, band,
3431                                    (struct ieee80211_mgmt *)scan->data,
3432                                    IWL_MAX_SCAN_SIZE - sizeof(*scan)));
3433
3434         /* select Rx antennas */
3435         scan->flags |= iwl3945_get_antenna_flags(priv);
3436
3437         if (priv->iw_mode == NL80211_IFTYPE_MONITOR)
3438                 scan->filter_flags = RXON_FILTER_PROMISC_MSK;
3439
3440         scan->channel_count =
3441                 iwl3945_get_channels_for_scan(priv, band, 1, /* active */
3442                                               n_probes,
3443                         (void *)&scan->data[le16_to_cpu(scan->tx_cmd.len)]);
3444
3445         if (scan->channel_count == 0) {
3446                 IWL_DEBUG_SCAN(priv, "channel count %d\n", scan->channel_count);
3447                 goto done;
3448         }
3449
3450         cmd.len += le16_to_cpu(scan->tx_cmd.len) +
3451             scan->channel_count * sizeof(struct iwl3945_scan_channel);
3452         cmd.data = scan;
3453         scan->len = cpu_to_le16(cmd.len);
3454
3455         set_bit(STATUS_SCAN_HW, &priv->status);
3456         rc = iwl_send_cmd_sync(priv, &cmd);
3457         if (rc)
3458                 goto done;
3459
3460         queue_delayed_work(priv->workqueue, &priv->scan_check,
3461                            IWL_SCAN_CHECK_WATCHDOG);
3462
3463         mutex_unlock(&priv->mutex);
3464         return;
3465
3466  done:
3467         /* can not perform scan make sure we clear scanning
3468          * bits from status so next scan request can be performed.
3469          * if we dont clear scanning status bit here all next scan
3470          * will fail
3471         */
3472         clear_bit(STATUS_SCAN_HW, &priv->status);
3473         clear_bit(STATUS_SCANNING, &priv->status);
3474
3475         /* inform mac80211 scan aborted */
3476         queue_work(priv->workqueue, &priv->scan_completed);
3477         mutex_unlock(&priv->mutex);
3478 }
3479
3480 static void iwl3945_bg_up(struct work_struct *data)
3481 {
3482         struct iwl_priv *priv = container_of(data, struct iwl_priv, up);
3483
3484         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
3485                 return;
3486
3487         mutex_lock(&priv->mutex);
3488         __iwl3945_up(priv);
3489         mutex_unlock(&priv->mutex);
3490         iwl_rfkill_set_hw_state(priv);
3491 }
3492
3493 static void iwl3945_bg_restart(struct work_struct *data)
3494 {
3495         struct iwl_priv *priv = container_of(data, struct iwl_priv, restart);
3496
3497         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
3498                 return;
3499
3500         iwl3945_down(priv);
3501         queue_work(priv->workqueue, &priv->up);
3502 }
3503
3504 static void iwl3945_bg_rx_replenish(struct work_struct *data)
3505 {
3506         struct iwl_priv *priv =
3507             container_of(data, struct iwl_priv, rx_replenish);
3508
3509         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
3510                 return;
3511
3512         mutex_lock(&priv->mutex);
3513         iwl3945_rx_replenish(priv);
3514         mutex_unlock(&priv->mutex);
3515 }
3516
3517 #define IWL_DELAY_NEXT_SCAN (HZ*2)
3518
3519 static void iwl3945_post_associate(struct iwl_priv *priv)
3520 {
3521         int rc = 0;
3522         struct ieee80211_conf *conf = NULL;
3523
3524         if (priv->iw_mode == NL80211_IFTYPE_AP) {
3525                 IWL_ERR(priv, "%s Should not be called in AP mode\n", __func__);
3526                 return;
3527         }
3528
3529
3530         IWL_DEBUG_ASSOC(priv, "Associated as %d to: %pM\n",
3531                         priv->assoc_id, priv->active_rxon.bssid_addr);
3532
3533         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
3534                 return;
3535
3536         if (!priv->vif || !priv->is_open)
3537                 return;
3538
3539         iwl_scan_cancel_timeout(priv, 200);
3540
3541         conf = ieee80211_get_hw_conf(priv->hw);
3542
3543         priv->staging_rxon.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
3544         iwl3945_commit_rxon(priv);
3545
3546         memset(&priv->rxon_timing, 0, sizeof(struct iwl_rxon_time_cmd));
3547         iwl3945_setup_rxon_timing(priv);
3548         rc = iwl_send_cmd_pdu(priv, REPLY_RXON_TIMING,
3549                               sizeof(priv->rxon_timing), &priv->rxon_timing);
3550         if (rc)
3551                 IWL_WARN(priv, "REPLY_RXON_TIMING failed - "
3552                             "Attempting to continue.\n");
3553
3554         priv->staging_rxon.filter_flags |= RXON_FILTER_ASSOC_MSK;
3555
3556         priv->staging_rxon.assoc_id = cpu_to_le16(priv->assoc_id);
3557
3558         IWL_DEBUG_ASSOC(priv, "assoc id %d beacon interval %d\n",
3559                         priv->assoc_id, priv->beacon_int);
3560
3561         if (priv->assoc_capability & WLAN_CAPABILITY_SHORT_PREAMBLE)
3562                 priv->staging_rxon.flags |= RXON_FLG_SHORT_PREAMBLE_MSK;
3563         else
3564                 priv->staging_rxon.flags &= ~RXON_FLG_SHORT_PREAMBLE_MSK;
3565
3566         if (priv->staging_rxon.flags & RXON_FLG_BAND_24G_MSK) {
3567                 if (priv->assoc_capability & WLAN_CAPABILITY_SHORT_SLOT_TIME)
3568                         priv->staging_rxon.flags |= RXON_FLG_SHORT_SLOT_MSK;
3569                 else
3570                         priv->staging_rxon.flags &= ~RXON_FLG_SHORT_SLOT_MSK;
3571
3572                 if (priv->iw_mode == NL80211_IFTYPE_ADHOC)
3573                         priv->staging_rxon.flags &= ~RXON_FLG_SHORT_SLOT_MSK;
3574
3575         }
3576
3577         iwl3945_commit_rxon(priv);
3578
3579         switch (priv->iw_mode) {
3580         case NL80211_IFTYPE_STATION:
3581                 iwl3945_rate_scale_init(priv->hw, IWL_AP_ID);
3582                 break;
3583
3584         case NL80211_IFTYPE_ADHOC:
3585
3586                 priv->assoc_id = 1;
3587                 iwl3945_add_station(priv, priv->bssid, 0, 0);
3588                 iwl3945_sync_sta(priv, IWL_STA_ID,
3589                                  (priv->band == IEEE80211_BAND_5GHZ) ?
3590                                  IWL_RATE_6M_PLCP : IWL_RATE_1M_PLCP,
3591                                  CMD_ASYNC);
3592                 iwl3945_rate_scale_init(priv->hw, IWL_STA_ID);
3593                 iwl3945_send_beacon_cmd(priv);
3594
3595                 break;
3596
3597         default:
3598                  IWL_ERR(priv, "%s Should not be called in %d mode\n",
3599                            __func__, priv->iw_mode);
3600                 break;
3601         }
3602
3603         iwl_activate_qos(priv, 0);
3604
3605         /* we have just associated, don't start scan too early */
3606         priv->next_scan_jiffies = jiffies + IWL_DELAY_NEXT_SCAN;
3607 }
3608
3609 static int iwl3945_mac_config(struct ieee80211_hw *hw, u32 changed);
3610
3611 /*****************************************************************************
3612  *
3613  * mac80211 entry point functions
3614  *
3615  *****************************************************************************/
3616
3617 #define UCODE_READY_TIMEOUT     (2 * HZ)
3618
3619 static int iwl3945_mac_start(struct ieee80211_hw *hw)
3620 {
3621         struct iwl_priv *priv = hw->priv;
3622         int ret;
3623
3624         IWL_DEBUG_MAC80211(priv, "enter\n");
3625
3626         /* we should be verifying the device is ready to be opened */
3627         mutex_lock(&priv->mutex);
3628
3629         memset(&priv->staging_rxon, 0, sizeof(priv->staging_rxon));
3630         /* fetch ucode file from disk, alloc and copy to bus-master buffers ...
3631          * ucode filename and max sizes are card-specific. */
3632
3633         if (!priv->ucode_code.len) {
3634                 ret = iwl3945_read_ucode(priv);
3635                 if (ret) {
3636                         IWL_ERR(priv, "Could not read microcode: %d\n", ret);
3637                         mutex_unlock(&priv->mutex);
3638                         goto out_release_irq;
3639                 }
3640         }
3641
3642         ret = __iwl3945_up(priv);
3643
3644         mutex_unlock(&priv->mutex);
3645
3646         iwl_rfkill_set_hw_state(priv);
3647
3648         if (ret)
3649                 goto out_release_irq;
3650
3651         IWL_DEBUG_INFO(priv, "Start UP work.\n");
3652
3653         if (test_bit(STATUS_IN_SUSPEND, &priv->status))
3654                 return 0;
3655
3656         /* Wait for START_ALIVE from ucode. Otherwise callbacks from
3657          * mac80211 will not be run successfully. */
3658         ret = wait_event_interruptible_timeout(priv->wait_command_queue,
3659                         test_bit(STATUS_READY, &priv->status),
3660                         UCODE_READY_TIMEOUT);
3661         if (!ret) {
3662                 if (!test_bit(STATUS_READY, &priv->status)) {
3663                         IWL_ERR(priv,
3664                                 "Wait for START_ALIVE timeout after %dms.\n",
3665                                 jiffies_to_msecs(UCODE_READY_TIMEOUT));
3666                         ret = -ETIMEDOUT;
3667                         goto out_release_irq;
3668                 }
3669         }
3670
3671         /* ucode is running and will send rfkill notifications,
3672          * no need to poll the killswitch state anymore */
3673         cancel_delayed_work(&priv->rfkill_poll);
3674
3675         priv->is_open = 1;
3676         IWL_DEBUG_MAC80211(priv, "leave\n");
3677         return 0;
3678
3679 out_release_irq:
3680         priv->is_open = 0;
3681         IWL_DEBUG_MAC80211(priv, "leave - failed\n");
3682         return ret;
3683 }
3684
3685 static void iwl3945_mac_stop(struct ieee80211_hw *hw)
3686 {
3687         struct iwl_priv *priv = hw->priv;
3688
3689         IWL_DEBUG_MAC80211(priv, "enter\n");
3690
3691         if (!priv->is_open) {
3692                 IWL_DEBUG_MAC80211(priv, "leave - skip\n");
3693                 return;
3694         }
3695
3696         priv->is_open = 0;
3697
3698         if (iwl_is_ready_rf(priv)) {
3699                 /* stop mac, cancel any scan request and clear
3700                  * RXON_FILTER_ASSOC_MSK BIT
3701                  */
3702                 mutex_lock(&priv->mutex);
3703                 iwl_scan_cancel_timeout(priv, 100);
3704                 mutex_unlock(&priv->mutex);
3705         }
3706
3707         iwl3945_down(priv);
3708
3709         flush_workqueue(priv->workqueue);
3710
3711         /* start polling the killswitch state again */
3712         queue_delayed_work(priv->workqueue, &priv->rfkill_poll,
3713                            round_jiffies_relative(2 * HZ));
3714
3715         IWL_DEBUG_MAC80211(priv, "leave\n");
3716 }
3717
3718 static int iwl3945_mac_tx(struct ieee80211_hw *hw, struct sk_buff *skb)
3719 {
3720         struct iwl_priv *priv = hw->priv;
3721
3722         IWL_DEBUG_MAC80211(priv, "enter\n");
3723
3724         IWL_DEBUG_TX(priv, "dev->xmit(%d bytes) at rate 0x%02x\n", skb->len,
3725                      ieee80211_get_tx_rate(hw, IEEE80211_SKB_CB(skb))->bitrate);
3726
3727         if (iwl3945_tx_skb(priv, skb))
3728                 dev_kfree_skb_any(skb);
3729
3730         IWL_DEBUG_MAC80211(priv, "leave\n");
3731         return NETDEV_TX_OK;
3732 }
3733
3734 static int iwl3945_mac_add_interface(struct ieee80211_hw *hw,
3735                                  struct ieee80211_if_init_conf *conf)
3736 {
3737         struct iwl_priv *priv = hw->priv;
3738         unsigned long flags;
3739
3740         IWL_DEBUG_MAC80211(priv, "enter: type %d\n", conf->type);
3741
3742         if (priv->vif) {
3743                 IWL_DEBUG_MAC80211(priv, "leave - vif != NULL\n");
3744                 return -EOPNOTSUPP;
3745         }
3746
3747         spin_lock_irqsave(&priv->lock, flags);
3748         priv->vif = conf->vif;
3749         priv->iw_mode = conf->type;
3750
3751         spin_unlock_irqrestore(&priv->lock, flags);
3752
3753         mutex_lock(&priv->mutex);
3754
3755         if (conf->mac_addr) {
3756                 IWL_DEBUG_MAC80211(priv, "Set: %pM\n", conf->mac_addr);
3757                 memcpy(priv->mac_addr, conf->mac_addr, ETH_ALEN);
3758         }
3759
3760         if (iwl_is_ready(priv))
3761                 iwl3945_set_mode(priv, conf->type);
3762
3763         mutex_unlock(&priv->mutex);
3764
3765         IWL_DEBUG_MAC80211(priv, "leave\n");
3766         return 0;
3767 }
3768
3769 /**
3770  * iwl3945_mac_config - mac80211 config callback
3771  *
3772  * We ignore conf->flags & IEEE80211_CONF_SHORT_SLOT_TIME since it seems to
3773  * be set inappropriately and the driver currently sets the hardware up to
3774  * use it whenever needed.
3775  */
3776 static int iwl3945_mac_config(struct ieee80211_hw *hw, u32 changed)
3777 {
3778         struct iwl_priv *priv = hw->priv;
3779         const struct iwl_channel_info *ch_info;
3780         struct ieee80211_conf *conf = &hw->conf;
3781         unsigned long flags;
3782         int ret = 0;
3783
3784         mutex_lock(&priv->mutex);
3785         IWL_DEBUG_MAC80211(priv, "enter to channel %d\n",
3786                                 conf->channel->hw_value);
3787
3788         if (!iwl_is_ready(priv)) {
3789                 IWL_DEBUG_MAC80211(priv, "leave - not ready\n");
3790                 ret = -EIO;
3791                 goto out;
3792         }
3793
3794         if (unlikely(!iwl3945_mod_params.disable_hw_scan &&
3795                      test_bit(STATUS_SCANNING, &priv->status))) {
3796                 IWL_DEBUG_MAC80211(priv, "leave - scanning\n");
3797                 set_bit(STATUS_CONF_PENDING, &priv->status);
3798                 mutex_unlock(&priv->mutex);
3799                 return 0;
3800         }
3801
3802         spin_lock_irqsave(&priv->lock, flags);
3803
3804         ch_info = iwl_get_channel_info(priv, conf->channel->band,
3805                                        conf->channel->hw_value);
3806         if (!is_channel_valid(ch_info)) {
3807                 IWL_DEBUG_SCAN(priv,
3808                                 "Channel %d [%d] is INVALID for this band.\n",
3809                                 conf->channel->hw_value, conf->channel->band);
3810                 IWL_DEBUG_MAC80211(priv, "leave - invalid channel\n");
3811                 spin_unlock_irqrestore(&priv->lock, flags);
3812                 ret = -EINVAL;
3813                 goto out;
3814         }
3815
3816         iwl_set_rxon_channel(priv, conf->channel);
3817
3818         iwl_set_flags_for_band(priv, conf->channel->band);
3819
3820         /* The list of supported rates and rate mask can be different
3821          * for each phymode; since the phymode may have changed, reset
3822          * the rate mask to what mac80211 lists */
3823         iwl_set_rate(priv);
3824
3825         spin_unlock_irqrestore(&priv->lock, flags);
3826
3827 #ifdef IEEE80211_CONF_CHANNEL_SWITCH
3828         if (conf->flags & IEEE80211_CONF_CHANNEL_SWITCH) {
3829                 iwl3945_hw_channel_switch(priv, conf->channel);
3830                 goto out;
3831         }
3832 #endif
3833
3834         if (changed & IEEE80211_CONF_CHANGE_RADIO_ENABLED) {
3835                 if (conf->radio_enabled &&
3836                     iwl_radio_kill_sw_enable_radio(priv)) {
3837                         IWL_DEBUG_MAC80211(priv, "leave - RF-KILL - "
3838                                                  "waiting for uCode\n");
3839                         goto out;
3840                 }
3841
3842                 if (!conf->radio_enabled) {
3843                         iwl_radio_kill_sw_disable_radio(priv);
3844                         IWL_DEBUG_MAC80211(priv, "leave - radio disabled\n");
3845                         goto out;
3846                 }
3847         }
3848
3849         if (iwl_is_rfkill(priv)) {
3850                 IWL_DEBUG_MAC80211(priv, "leave - RF kill\n");
3851                 ret = -EIO;
3852                 goto out;
3853         }
3854
3855         iwl_set_rate(priv);
3856
3857         if (memcmp(&priv->active_rxon,
3858                    &priv->staging_rxon, sizeof(priv->staging_rxon)))
3859                 iwl3945_commit_rxon(priv);
3860         else
3861                 IWL_DEBUG_INFO(priv, "Not re-sending same RXON configuration\n");
3862
3863         IWL_DEBUG_MAC80211(priv, "leave\n");
3864
3865 out:
3866         clear_bit(STATUS_CONF_PENDING, &priv->status);
3867         mutex_unlock(&priv->mutex);
3868         return ret;
3869 }
3870
3871 static void iwl3945_config_ap(struct iwl_priv *priv)
3872 {
3873         int rc = 0;
3874
3875         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
3876                 return;
3877
3878         /* The following should be done only at AP bring up */
3879         if (!(iwl_is_associated(priv))) {
3880
3881                 /* RXON - unassoc (to set timing command) */
3882                 priv->staging_rxon.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
3883                 iwl3945_commit_rxon(priv);
3884
3885                 /* RXON Timing */
3886                 memset(&priv->rxon_timing, 0, sizeof(struct iwl_rxon_time_cmd));
3887                 iwl3945_setup_rxon_timing(priv);
3888                 rc = iwl_send_cmd_pdu(priv, REPLY_RXON_TIMING,
3889                                       sizeof(priv->rxon_timing),
3890                                       &priv->rxon_timing);
3891                 if (rc)
3892                         IWL_WARN(priv, "REPLY_RXON_TIMING failed - "
3893                                         "Attempting to continue.\n");
3894
3895                 /* FIXME: what should be the assoc_id for AP? */
3896                 priv->staging_rxon.assoc_id = cpu_to_le16(priv->assoc_id);
3897                 if (priv->assoc_capability & WLAN_CAPABILITY_SHORT_PREAMBLE)
3898                         priv->staging_rxon.flags |=
3899                                 RXON_FLG_SHORT_PREAMBLE_MSK;
3900                 else
3901                         priv->staging_rxon.flags &=
3902                                 ~RXON_FLG_SHORT_PREAMBLE_MSK;
3903
3904                 if (priv->staging_rxon.flags & RXON_FLG_BAND_24G_MSK) {
3905                         if (priv->assoc_capability &
3906                                 WLAN_CAPABILITY_SHORT_SLOT_TIME)
3907                                 priv->staging_rxon.flags |=
3908                                         RXON_FLG_SHORT_SLOT_MSK;
3909                         else
3910                                 priv->staging_rxon.flags &=
3911                                         ~RXON_FLG_SHORT_SLOT_MSK;
3912
3913                         if (priv->iw_mode == NL80211_IFTYPE_ADHOC)
3914                                 priv->staging_rxon.flags &=
3915                                         ~RXON_FLG_SHORT_SLOT_MSK;
3916                 }
3917                 /* restore RXON assoc */
3918                 priv->staging_rxon.filter_flags |= RXON_FILTER_ASSOC_MSK;
3919                 iwl3945_commit_rxon(priv);
3920                 iwl3945_add_station(priv, iwl_bcast_addr, 0, 0);
3921         }
3922         iwl3945_send_beacon_cmd(priv);
3923
3924         /* FIXME - we need to add code here to detect a totally new
3925          * configuration, reset the AP, unassoc, rxon timing, assoc,
3926          * clear sta table, add BCAST sta... */
3927 }
3928
3929 static int iwl3945_mac_config_interface(struct ieee80211_hw *hw,
3930                                         struct ieee80211_vif *vif,
3931                                         struct ieee80211_if_conf *conf)
3932 {
3933         struct iwl_priv *priv = hw->priv;
3934         int rc;
3935
3936         if (conf == NULL)
3937                 return -EIO;
3938
3939         if (priv->vif != vif) {
3940                 IWL_DEBUG_MAC80211(priv, "leave - priv->vif != vif\n");
3941                 return 0;
3942         }
3943
3944         /* handle this temporarily here */
3945         if (priv->iw_mode == NL80211_IFTYPE_ADHOC &&
3946             conf->changed & IEEE80211_IFCC_BEACON) {
3947                 struct sk_buff *beacon = ieee80211_beacon_get(hw, vif);
3948                 if (!beacon)
3949                         return -ENOMEM;
3950                 mutex_lock(&priv->mutex);
3951                 rc = iwl3945_mac_beacon_update(hw, beacon);
3952                 mutex_unlock(&priv->mutex);
3953                 if (rc)
3954                         return rc;
3955         }
3956
3957         if (!iwl_is_alive(priv))
3958                 return -EAGAIN;
3959
3960         mutex_lock(&priv->mutex);
3961
3962         if (conf->bssid)
3963                 IWL_DEBUG_MAC80211(priv, "bssid: %pM\n", conf->bssid);
3964
3965 /*
3966  * very dubious code was here; the probe filtering flag is never set:
3967  *
3968         if (unlikely(test_bit(STATUS_SCANNING, &priv->status)) &&
3969             !(priv->hw->flags & IEEE80211_HW_NO_PROBE_FILTERING)) {
3970  */
3971
3972         if (priv->iw_mode == NL80211_IFTYPE_AP) {
3973                 if (!conf->bssid) {
3974                         conf->bssid = priv->mac_addr;
3975                         memcpy(priv->bssid, priv->mac_addr, ETH_ALEN);
3976                         IWL_DEBUG_MAC80211(priv, "bssid was set to: %pM\n",
3977                                            conf->bssid);
3978                 }
3979                 if (priv->ibss_beacon)
3980                         dev_kfree_skb(priv->ibss_beacon);
3981
3982                 priv->ibss_beacon = ieee80211_beacon_get(hw, vif);
3983         }
3984
3985         if (iwl_is_rfkill(priv))
3986                 goto done;
3987
3988         if (conf->bssid && !is_zero_ether_addr(conf->bssid) &&
3989             !is_multicast_ether_addr(conf->bssid)) {
3990                 /* If there is currently a HW scan going on in the background
3991                  * then we need to cancel it else the RXON below will fail. */
3992                 if (iwl_scan_cancel_timeout(priv, 100)) {
3993                         IWL_WARN(priv, "Aborted scan still in progress "
3994                                     "after 100ms\n");
3995                         IWL_DEBUG_MAC80211(priv, "leaving:scan abort failed\n");
3996                         mutex_unlock(&priv->mutex);
3997                         return -EAGAIN;
3998                 }
3999                 memcpy(priv->staging_rxon.bssid_addr, conf->bssid, ETH_ALEN);
4000
4001                 /* TODO: Audit driver for usage of these members and see
4002                  * if mac80211 deprecates them (priv->bssid looks like it
4003                  * shouldn't be there, but I haven't scanned the IBSS code
4004                  * to verify) - jpk */
4005                 memcpy(priv->bssid, conf->bssid, ETH_ALEN);
4006
4007                 if (priv->iw_mode == NL80211_IFTYPE_AP)
4008                         iwl3945_config_ap(priv);
4009                 else {
4010                         rc = iwl3945_commit_rxon(priv);
4011                         if ((priv->iw_mode == NL80211_IFTYPE_STATION) && rc)
4012                                 iwl3945_add_station(priv,
4013                                         priv->active_rxon.bssid_addr, 1, 0);
4014                 }
4015
4016         } else {
4017                 iwl_scan_cancel_timeout(priv, 100);
4018                 priv->staging_rxon.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
4019                 iwl3945_commit_rxon(priv);
4020         }
4021
4022  done:
4023         IWL_DEBUG_MAC80211(priv, "leave\n");
4024         mutex_unlock(&priv->mutex);
4025
4026         return 0;
4027 }
4028
4029 static void iwl3945_mac_remove_interface(struct ieee80211_hw *hw,
4030                                      struct ieee80211_if_init_conf *conf)
4031 {
4032         struct iwl_priv *priv = hw->priv;
4033
4034         IWL_DEBUG_MAC80211(priv, "enter\n");
4035
4036         mutex_lock(&priv->mutex);
4037
4038         if (iwl_is_ready_rf(priv)) {
4039                 iwl_scan_cancel_timeout(priv, 100);
4040                 priv->staging_rxon.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
4041                 iwl3945_commit_rxon(priv);
4042         }
4043         if (priv->vif == conf->vif) {
4044                 priv->vif = NULL;
4045                 memset(priv->bssid, 0, ETH_ALEN);
4046         }
4047         mutex_unlock(&priv->mutex);
4048
4049         IWL_DEBUG_MAC80211(priv, "leave\n");
4050 }
4051
4052 #define IWL_DELAY_NEXT_SCAN_AFTER_ASSOC (HZ*6)
4053
4054 static void iwl3945_bss_info_changed(struct ieee80211_hw *hw,
4055                                      struct ieee80211_vif *vif,
4056                                      struct ieee80211_bss_conf *bss_conf,
4057                                      u32 changes)
4058 {
4059         struct iwl_priv *priv = hw->priv;
4060
4061         IWL_DEBUG_MAC80211(priv, "changes = 0x%X\n", changes);
4062
4063         if (changes & BSS_CHANGED_ERP_PREAMBLE) {
4064                 IWL_DEBUG_MAC80211(priv, "ERP_PREAMBLE %d\n",
4065                                    bss_conf->use_short_preamble);
4066                 if (bss_conf->use_short_preamble)
4067                         priv->staging_rxon.flags |= RXON_FLG_SHORT_PREAMBLE_MSK;
4068                 else
4069                         priv->staging_rxon.flags &=
4070                                 ~RXON_FLG_SHORT_PREAMBLE_MSK;
4071         }
4072
4073         if (changes & BSS_CHANGED_ERP_CTS_PROT) {
4074                 IWL_DEBUG_MAC80211(priv, "ERP_CTS %d\n",
4075                                    bss_conf->use_cts_prot);
4076                 if (bss_conf->use_cts_prot && (priv->band != IEEE80211_BAND_5GHZ))
4077                         priv->staging_rxon.flags |= RXON_FLG_TGG_PROTECT_MSK;
4078                 else
4079                         priv->staging_rxon.flags &= ~RXON_FLG_TGG_PROTECT_MSK;
4080         }
4081
4082         if (changes & BSS_CHANGED_ASSOC) {
4083                 IWL_DEBUG_MAC80211(priv, "ASSOC %d\n", bss_conf->assoc);
4084                 /* This should never happen as this function should
4085                  * never be called from interrupt context. */
4086                 if (WARN_ON_ONCE(in_interrupt()))
4087                         return;
4088                 if (bss_conf->assoc) {
4089                         priv->assoc_id = bss_conf->aid;
4090                         priv->beacon_int = bss_conf->beacon_int;
4091                         priv->timestamp = bss_conf->timestamp;
4092                         priv->assoc_capability = bss_conf->assoc_capability;
4093                         priv->power_data.dtim_period = bss_conf->dtim_period;
4094                         priv->next_scan_jiffies = jiffies +
4095                                         IWL_DELAY_NEXT_SCAN_AFTER_ASSOC;
4096                         mutex_lock(&priv->mutex);
4097                         iwl3945_post_associate(priv);
4098                         mutex_unlock(&priv->mutex);
4099                 } else {
4100                         priv->assoc_id = 0;
4101                         IWL_DEBUG_MAC80211(priv,
4102                                         "DISASSOC %d\n", bss_conf->assoc);
4103                 }
4104         } else if (changes && iwl_is_associated(priv) && priv->assoc_id) {
4105                         IWL_DEBUG_MAC80211(priv,
4106                                         "Associated Changes %d\n", changes);
4107                         iwl3945_send_rxon_assoc(priv);
4108         }
4109
4110 }
4111
4112 static int iwl3945_mac_set_key(struct ieee80211_hw *hw, enum set_key_cmd cmd,
4113                                struct ieee80211_vif *vif,
4114                                struct ieee80211_sta *sta,
4115                                struct ieee80211_key_conf *key)
4116 {
4117         struct iwl_priv *priv = hw->priv;
4118         const u8 *addr;
4119         int ret = 0;
4120         u8 sta_id = IWL_INVALID_STATION;
4121         u8 static_key;
4122
4123         IWL_DEBUG_MAC80211(priv, "enter\n");
4124
4125         if (iwl3945_mod_params.sw_crypto) {
4126                 IWL_DEBUG_MAC80211(priv, "leave - hwcrypto disabled\n");
4127                 return -EOPNOTSUPP;
4128         }
4129
4130         addr = sta ? sta->addr : iwl_bcast_addr;
4131         static_key = !iwl_is_associated(priv);
4132
4133         if (!static_key) {
4134                 sta_id = iwl3945_hw_find_station(priv, addr);
4135                 if (sta_id == IWL_INVALID_STATION) {
4136                         IWL_DEBUG_MAC80211(priv, "leave - %pM not in station map.\n",
4137                                             addr);
4138                         return -EINVAL;
4139                 }
4140         }
4141
4142         mutex_lock(&priv->mutex);
4143         iwl_scan_cancel_timeout(priv, 100);
4144         mutex_unlock(&priv->mutex);
4145
4146         switch (cmd) {
4147         case SET_KEY:
4148                 if (static_key)
4149                         ret = iwl3945_set_static_key(priv, key);
4150                 else
4151                         ret = iwl3945_set_dynamic_key(priv, key, sta_id);
4152                 IWL_DEBUG_MAC80211(priv, "enable hwcrypto key\n");
4153                 break;
4154         case DISABLE_KEY:
4155                 if (static_key)
4156                         ret = iwl3945_remove_static_key(priv);
4157                 else
4158                         ret = iwl3945_clear_sta_key_info(priv, sta_id);
4159                 IWL_DEBUG_MAC80211(priv, "disable hwcrypto key\n");
4160                 break;
4161         default:
4162                 ret = -EINVAL;
4163         }
4164
4165         IWL_DEBUG_MAC80211(priv, "leave\n");
4166
4167         return ret;
4168 }
4169
4170 static int iwl3945_mac_conf_tx(struct ieee80211_hw *hw, u16 queue,
4171                            const struct ieee80211_tx_queue_params *params)
4172 {
4173         struct iwl_priv *priv = hw->priv;
4174         unsigned long flags;
4175         int q;
4176
4177         IWL_DEBUG_MAC80211(priv, "enter\n");
4178
4179         if (!iwl_is_ready_rf(priv)) {
4180                 IWL_DEBUG_MAC80211(priv, "leave - RF not ready\n");
4181                 return -EIO;
4182         }
4183
4184         if (queue >= AC_NUM) {
4185                 IWL_DEBUG_MAC80211(priv, "leave - queue >= AC_NUM %d\n", queue);
4186                 return 0;
4187         }
4188
4189         q = AC_NUM - 1 - queue;
4190
4191         spin_lock_irqsave(&priv->lock, flags);
4192
4193         priv->qos_data.def_qos_parm.ac[q].cw_min = cpu_to_le16(params->cw_min);
4194         priv->qos_data.def_qos_parm.ac[q].cw_max = cpu_to_le16(params->cw_max);
4195         priv->qos_data.def_qos_parm.ac[q].aifsn = params->aifs;
4196         priv->qos_data.def_qos_parm.ac[q].edca_txop =
4197                         cpu_to_le16((params->txop * 32));
4198
4199         priv->qos_data.def_qos_parm.ac[q].reserved1 = 0;
4200         priv->qos_data.qos_active = 1;
4201
4202         spin_unlock_irqrestore(&priv->lock, flags);
4203
4204         mutex_lock(&priv->mutex);
4205         if (priv->iw_mode == NL80211_IFTYPE_AP)
4206                 iwl_activate_qos(priv, 1);
4207         else if (priv->assoc_id && iwl_is_associated(priv))
4208                 iwl_activate_qos(priv, 0);
4209
4210         mutex_unlock(&priv->mutex);
4211
4212         IWL_DEBUG_MAC80211(priv, "leave\n");
4213         return 0;
4214 }
4215
4216 static int iwl3945_mac_get_tx_stats(struct ieee80211_hw *hw,
4217                                 struct ieee80211_tx_queue_stats *stats)
4218 {
4219         struct iwl_priv *priv = hw->priv;
4220         int i, avail;
4221         struct iwl_tx_queue *txq;
4222         struct iwl_queue *q;
4223         unsigned long flags;
4224
4225         IWL_DEBUG_MAC80211(priv, "enter\n");
4226
4227         if (!iwl_is_ready_rf(priv)) {
4228                 IWL_DEBUG_MAC80211(priv, "leave - RF not ready\n");
4229                 return -EIO;
4230         }
4231
4232         spin_lock_irqsave(&priv->lock, flags);
4233
4234         for (i = 0; i < AC_NUM; i++) {
4235                 txq = &priv->txq[i];
4236                 q = &txq->q;
4237                 avail = iwl_queue_space(q);
4238
4239                 stats[i].len = q->n_window - avail;
4240                 stats[i].limit = q->n_window - q->high_mark;
4241                 stats[i].count = q->n_window;
4242
4243         }
4244         spin_unlock_irqrestore(&priv->lock, flags);
4245
4246         IWL_DEBUG_MAC80211(priv, "leave\n");
4247
4248         return 0;
4249 }
4250
4251 static void iwl3945_mac_reset_tsf(struct ieee80211_hw *hw)
4252 {
4253         struct iwl_priv *priv = hw->priv;
4254         unsigned long flags;
4255
4256         mutex_lock(&priv->mutex);
4257         IWL_DEBUG_MAC80211(priv, "enter\n");
4258
4259         iwl_reset_qos(priv);
4260
4261         spin_lock_irqsave(&priv->lock, flags);
4262         priv->assoc_id = 0;
4263         priv->assoc_capability = 0;
4264
4265         /* new association get rid of ibss beacon skb */
4266         if (priv->ibss_beacon)
4267                 dev_kfree_skb(priv->ibss_beacon);
4268
4269         priv->ibss_beacon = NULL;
4270
4271         priv->beacon_int = priv->hw->conf.beacon_int;
4272         priv->timestamp = 0;
4273         if ((priv->iw_mode == NL80211_IFTYPE_STATION))
4274                 priv->beacon_int = 0;
4275
4276         spin_unlock_irqrestore(&priv->lock, flags);
4277
4278         if (!iwl_is_ready_rf(priv)) {
4279                 IWL_DEBUG_MAC80211(priv, "leave - not ready\n");
4280                 mutex_unlock(&priv->mutex);
4281                 return;
4282         }
4283
4284         /* we are restarting association process
4285          * clear RXON_FILTER_ASSOC_MSK bit
4286         */
4287         if (priv->iw_mode != NL80211_IFTYPE_AP) {
4288                 iwl_scan_cancel_timeout(priv, 100);
4289                 priv->staging_rxon.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
4290                 iwl3945_commit_rxon(priv);
4291         }
4292
4293         /* Per mac80211.h: This is only used in IBSS mode... */
4294         if (priv->iw_mode != NL80211_IFTYPE_ADHOC) {
4295
4296                 IWL_DEBUG_MAC80211(priv, "leave - not in IBSS\n");
4297                 mutex_unlock(&priv->mutex);
4298                 return;
4299         }
4300
4301         iwl_set_rate(priv);
4302
4303         mutex_unlock(&priv->mutex);
4304
4305         IWL_DEBUG_MAC80211(priv, "leave\n");
4306
4307 }
4308
4309 static int iwl3945_mac_beacon_update(struct ieee80211_hw *hw, struct sk_buff *skb)
4310 {
4311         struct iwl_priv *priv = hw->priv;
4312         unsigned long flags;
4313         __le64 timestamp;
4314
4315         IWL_DEBUG_MAC80211(priv, "enter\n");
4316
4317         if (!iwl_is_ready_rf(priv)) {
4318                 IWL_DEBUG_MAC80211(priv, "leave - RF not ready\n");
4319                 return -EIO;
4320         }
4321
4322         if (priv->iw_mode != NL80211_IFTYPE_ADHOC) {
4323                 IWL_DEBUG_MAC80211(priv, "leave - not IBSS\n");
4324                 return -EIO;
4325         }
4326
4327         spin_lock_irqsave(&priv->lock, flags);
4328
4329         if (priv->ibss_beacon)
4330                 dev_kfree_skb(priv->ibss_beacon);
4331
4332         priv->ibss_beacon = skb;
4333
4334         priv->assoc_id = 0;
4335         timestamp = ((struct ieee80211_mgmt *)skb->data)->u.beacon.timestamp;
4336         priv->timestamp = le64_to_cpu(timestamp);
4337
4338         IWL_DEBUG_MAC80211(priv, "leave\n");
4339         spin_unlock_irqrestore(&priv->lock, flags);
4340
4341         iwl_reset_qos(priv);
4342
4343         iwl3945_post_associate(priv);
4344
4345
4346         return 0;
4347 }
4348
4349 /*****************************************************************************
4350  *
4351  * sysfs attributes
4352  *
4353  *****************************************************************************/
4354
4355 #ifdef CONFIG_IWLWIFI_DEBUG
4356
4357 /*
4358  * The following adds a new attribute to the sysfs representation
4359  * of this device driver (i.e. a new file in /sys/bus/pci/drivers/iwl/)
4360  * used for controlling the debug level.
4361  *
4362  * See the level definitions in iwl for details.
4363  */
4364 static ssize_t show_debug_level(struct device *d,
4365                                 struct device_attribute *attr, char *buf)
4366 {
4367         struct iwl_priv *priv = d->driver_data;
4368
4369         return sprintf(buf, "0x%08X\n", priv->debug_level);
4370 }
4371 static ssize_t store_debug_level(struct device *d,
4372                                 struct device_attribute *attr,
4373                                  const char *buf, size_t count)
4374 {
4375         struct iwl_priv *priv = d->driver_data;
4376         unsigned long val;
4377         int ret;
4378
4379         ret = strict_strtoul(buf, 0, &val);
4380         if (ret)
4381                 IWL_INFO(priv, "%s is not in hex or decimal form.\n", buf);
4382         else
4383                 priv->debug_level = val;
4384
4385         return strnlen(buf, count);
4386 }
4387
4388 static DEVICE_ATTR(debug_level, S_IWUSR | S_IRUGO,
4389                         show_debug_level, store_debug_level);
4390
4391 #endif /* CONFIG_IWLWIFI_DEBUG */
4392
4393 static ssize_t show_temperature(struct device *d,
4394                                 struct device_attribute *attr, char *buf)
4395 {
4396         struct iwl_priv *priv = (struct iwl_priv *)d->driver_data;
4397
4398         if (!iwl_is_alive(priv))
4399                 return -EAGAIN;
4400
4401         return sprintf(buf, "%d\n", iwl3945_hw_get_temperature(priv));
4402 }
4403
4404 static DEVICE_ATTR(temperature, S_IRUGO, show_temperature, NULL);
4405
4406 static ssize_t show_tx_power(struct device *d,
4407                              struct device_attribute *attr, char *buf)
4408 {
4409         struct iwl_priv *priv = (struct iwl_priv *)d->driver_data;
4410         return sprintf(buf, "%d\n", priv->tx_power_user_lmt);
4411 }
4412
4413 static ssize_t store_tx_power(struct device *d,
4414                               struct device_attribute *attr,
4415                               const char *buf, size_t count)
4416 {
4417         struct iwl_priv *priv = (struct iwl_priv *)d->driver_data;
4418         char *p = (char *)buf;
4419         u32 val;
4420
4421         val = simple_strtoul(p, &p, 10);
4422         if (p == buf)
4423                 IWL_INFO(priv, ": %s is not in decimal form.\n", buf);
4424         else
4425                 iwl3945_hw_reg_set_txpower(priv, val);
4426
4427         return count;
4428 }
4429
4430 static DEVICE_ATTR(tx_power, S_IWUSR | S_IRUGO, show_tx_power, store_tx_power);
4431
4432 static ssize_t show_flags(struct device *d,
4433                           struct device_attribute *attr, char *buf)
4434 {
4435         struct iwl_priv *priv = (struct iwl_priv *)d->driver_data;
4436
4437         return sprintf(buf, "0x%04X\n", priv->active_rxon.flags);
4438 }
4439
4440 static ssize_t store_flags(struct device *d,
4441                            struct device_attribute *attr,
4442                            const char *buf, size_t count)
4443 {
4444         struct iwl_priv *priv = (struct iwl_priv *)d->driver_data;
4445         u32 flags = simple_strtoul(buf, NULL, 0);
4446
4447         mutex_lock(&priv->mutex);
4448         if (le32_to_cpu(priv->staging_rxon.flags) != flags) {
4449                 /* Cancel any currently running scans... */
4450                 if (iwl_scan_cancel_timeout(priv, 100))
4451                         IWL_WARN(priv, "Could not cancel scan.\n");
4452                 else {
4453                         IWL_DEBUG_INFO(priv, "Committing rxon.flags = 0x%04X\n",
4454                                        flags);
4455                         priv->staging_rxon.flags = cpu_to_le32(flags);
4456                         iwl3945_commit_rxon(priv);
4457                 }
4458         }
4459         mutex_unlock(&priv->mutex);
4460
4461         return count;
4462 }
4463
4464 static DEVICE_ATTR(flags, S_IWUSR | S_IRUGO, show_flags, store_flags);
4465
4466 static ssize_t show_filter_flags(struct device *d,
4467                                  struct device_attribute *attr, char *buf)
4468 {
4469         struct iwl_priv *priv = (struct iwl_priv *)d->driver_data;
4470
4471         return sprintf(buf, "0x%04X\n",
4472                 le32_to_cpu(priv->active_rxon.filter_flags));
4473 }
4474
4475 static ssize_t store_filter_flags(struct device *d,
4476                                   struct device_attribute *attr,
4477                                   const char *buf, size_t count)
4478 {
4479         struct iwl_priv *priv = (struct iwl_priv *)d->driver_data;
4480         u32 filter_flags = simple_strtoul(buf, NULL, 0);
4481
4482         mutex_lock(&priv->mutex);
4483         if (le32_to_cpu(priv->staging_rxon.filter_flags) != filter_flags) {
4484                 /* Cancel any currently running scans... */
4485                 if (iwl_scan_cancel_timeout(priv, 100))
4486                         IWL_WARN(priv, "Could not cancel scan.\n");
4487                 else {
4488                         IWL_DEBUG_INFO(priv, "Committing rxon.filter_flags = "
4489                                        "0x%04X\n", filter_flags);
4490                         priv->staging_rxon.filter_flags =
4491                                 cpu_to_le32(filter_flags);
4492                         iwl3945_commit_rxon(priv);
4493                 }
4494         }
4495         mutex_unlock(&priv->mutex);
4496
4497         return count;
4498 }
4499
4500 static DEVICE_ATTR(filter_flags, S_IWUSR | S_IRUGO, show_filter_flags,
4501                    store_filter_flags);
4502
4503 #ifdef CONFIG_IWL3945_SPECTRUM_MEASUREMENT
4504
4505 static ssize_t show_measurement(struct device *d,
4506                                 struct device_attribute *attr, char *buf)
4507 {
4508         struct iwl_priv *priv = dev_get_drvdata(d);
4509         struct iwl_spectrum_notification measure_report;
4510         u32 size = sizeof(measure_report), len = 0, ofs = 0;
4511         u8 *data = (u8 *)&measure_report;
4512         unsigned long flags;
4513
4514         spin_lock_irqsave(&priv->lock, flags);
4515         if (!(priv->measurement_status & MEASUREMENT_READY)) {
4516                 spin_unlock_irqrestore(&priv->lock, flags);
4517                 return 0;
4518         }
4519         memcpy(&measure_report, &priv->measure_report, size);
4520         priv->measurement_status = 0;
4521         spin_unlock_irqrestore(&priv->lock, flags);
4522
4523         while (size && (PAGE_SIZE - len)) {
4524                 hex_dump_to_buffer(data + ofs, size, 16, 1, buf + len,
4525                                    PAGE_SIZE - len, 1);
4526                 len = strlen(buf);
4527                 if (PAGE_SIZE - len)
4528                         buf[len++] = '\n';
4529
4530                 ofs += 16;
4531                 size -= min(size, 16U);
4532         }
4533
4534         return len;
4535 }
4536
4537 static ssize_t store_measurement(struct device *d,
4538                                  struct device_attribute *attr,
4539                                  const char *buf, size_t count)
4540 {
4541         struct iwl_priv *priv = dev_get_drvdata(d);
4542         struct ieee80211_measurement_params params = {
4543                 .channel = le16_to_cpu(priv->active_rxon.channel),
4544                 .start_time = cpu_to_le64(priv->last_tsf),
4545                 .duration = cpu_to_le16(1),
4546         };
4547         u8 type = IWL_MEASURE_BASIC;
4548         u8 buffer[32];
4549         u8 channel;
4550
4551         if (count) {
4552                 char *p = buffer;
4553                 strncpy(buffer, buf, min(sizeof(buffer), count));
4554                 channel = simple_strtoul(p, NULL, 0);
4555                 if (channel)
4556                         params.channel = channel;
4557
4558                 p = buffer;
4559                 while (*p && *p != ' ')
4560                         p++;
4561                 if (*p)
4562                         type = simple_strtoul(p + 1, NULL, 0);
4563         }
4564
4565         IWL_DEBUG_INFO(priv, "Invoking measurement of type %d on "
4566                        "channel %d (for '%s')\n", type, params.channel, buf);
4567         iwl3945_get_measurement(priv, &params, type);
4568
4569         return count;
4570 }
4571
4572 static DEVICE_ATTR(measurement, S_IRUSR | S_IWUSR,
4573                    show_measurement, store_measurement);
4574 #endif /* CONFIG_IWL3945_SPECTRUM_MEASUREMENT */
4575
4576 static ssize_t store_retry_rate(struct device *d,
4577                                 struct device_attribute *attr,
4578                                 const char *buf, size_t count)
4579 {
4580         struct iwl_priv *priv = dev_get_drvdata(d);
4581
4582         priv->retry_rate = simple_strtoul(buf, NULL, 0);
4583         if (priv->retry_rate <= 0)
4584                 priv->retry_rate = 1;
4585
4586         return count;
4587 }
4588
4589 static ssize_t show_retry_rate(struct device *d,
4590                                struct device_attribute *attr, char *buf)
4591 {
4592         struct iwl_priv *priv = dev_get_drvdata(d);
4593         return sprintf(buf, "%d", priv->retry_rate);
4594 }
4595
4596 static DEVICE_ATTR(retry_rate, S_IWUSR | S_IRUSR, show_retry_rate,
4597                    store_retry_rate);
4598
4599
4600 static ssize_t store_power_level(struct device *d,
4601                                  struct device_attribute *attr,
4602                                  const char *buf, size_t count)
4603 {
4604         struct iwl_priv *priv = dev_get_drvdata(d);
4605         int ret;
4606         unsigned long mode;
4607
4608
4609         mutex_lock(&priv->mutex);
4610
4611         ret = strict_strtoul(buf, 10, &mode);
4612         if (ret)
4613                 goto out;
4614
4615         ret = iwl_power_set_user_mode(priv, mode);
4616         if (ret) {
4617                 IWL_DEBUG_MAC80211(priv, "failed setting power mode.\n");
4618                 goto out;
4619         }
4620         ret = count;
4621
4622  out:
4623         mutex_unlock(&priv->mutex);
4624         return ret;
4625 }
4626
4627 static ssize_t show_power_level(struct device *d,
4628                                 struct device_attribute *attr, char *buf)
4629 {
4630         struct iwl_priv *priv = dev_get_drvdata(d);
4631         int mode = priv->power_data.user_power_setting;
4632         int system = priv->power_data.system_power_setting;
4633         int level = priv->power_data.power_mode;
4634         char *p = buf;
4635
4636         switch (system) {
4637         case IWL_POWER_SYS_AUTO:
4638                 p += sprintf(p, "SYSTEM:auto");
4639                 break;
4640         case IWL_POWER_SYS_AC:
4641                 p += sprintf(p, "SYSTEM:ac");
4642                 break;
4643         case IWL_POWER_SYS_BATTERY:
4644                 p += sprintf(p, "SYSTEM:battery");
4645                 break;
4646         }
4647
4648         p += sprintf(p, "\tMODE:%s", (mode < IWL_POWER_AUTO) ?
4649                         "fixed" : "auto");
4650         p += sprintf(p, "\tINDEX:%d", level);
4651         p += sprintf(p, "\n");
4652         return p - buf + 1;
4653 }
4654
4655 static DEVICE_ATTR(power_level, S_IWUSR | S_IRUSR,
4656                    show_power_level, store_power_level);
4657
4658 #define MAX_WX_STRING 80
4659
4660 /* Values are in microsecond */
4661 static const s32 timeout_duration[] = {
4662         350000,
4663         250000,
4664         75000,
4665         37000,
4666         25000,
4667 };
4668 static const s32 period_duration[] = {
4669         400000,
4670         700000,
4671         1000000,
4672         1000000,
4673         1000000
4674 };
4675
4676 static ssize_t show_channels(struct device *d,
4677                              struct device_attribute *attr, char *buf)
4678 {
4679         /* all this shit doesn't belong into sysfs anyway */
4680         return 0;
4681 }
4682
4683 static DEVICE_ATTR(channels, S_IRUSR, show_channels, NULL);
4684
4685 static ssize_t show_statistics(struct device *d,
4686                                struct device_attribute *attr, char *buf)
4687 {
4688         struct iwl_priv *priv = dev_get_drvdata(d);
4689         u32 size = sizeof(struct iwl3945_notif_statistics);
4690         u32 len = 0, ofs = 0;
4691         u8 *data = (u8 *)&priv->statistics_39;
4692         int rc = 0;
4693
4694         if (!iwl_is_alive(priv))
4695                 return -EAGAIN;
4696
4697         mutex_lock(&priv->mutex);
4698         rc = iwl_send_statistics_request(priv, 0);
4699         mutex_unlock(&priv->mutex);
4700
4701         if (rc) {
4702                 len = sprintf(buf,
4703                               "Error sending statistics request: 0x%08X\n", rc);
4704                 return len;
4705         }
4706
4707         while (size && (PAGE_SIZE - len)) {
4708                 hex_dump_to_buffer(data + ofs, size, 16, 1, buf + len,
4709                                    PAGE_SIZE - len, 1);
4710                 len = strlen(buf);
4711                 if (PAGE_SIZE - len)
4712                         buf[len++] = '\n';
4713
4714                 ofs += 16;
4715                 size -= min(size, 16U);
4716         }
4717
4718         return len;
4719 }
4720
4721 static DEVICE_ATTR(statistics, S_IRUGO, show_statistics, NULL);
4722
4723 static ssize_t show_antenna(struct device *d,
4724                             struct device_attribute *attr, char *buf)
4725 {
4726         struct iwl_priv *priv = dev_get_drvdata(d);
4727
4728         if (!iwl_is_alive(priv))
4729                 return -EAGAIN;
4730
4731         return sprintf(buf, "%d\n", iwl3945_mod_params.antenna);
4732 }
4733
4734 static ssize_t store_antenna(struct device *d,
4735                              struct device_attribute *attr,
4736                              const char *buf, size_t count)
4737 {
4738         struct iwl_priv *priv __maybe_unused = dev_get_drvdata(d);
4739         int ant;
4740
4741         if (count == 0)
4742                 return 0;
4743
4744         if (sscanf(buf, "%1i", &ant) != 1) {
4745                 IWL_DEBUG_INFO(priv, "not in hex or decimal form.\n");
4746                 return count;
4747         }
4748
4749         if ((ant >= 0) && (ant <= 2)) {
4750                 IWL_DEBUG_INFO(priv, "Setting antenna select to %d.\n", ant);
4751                 iwl3945_mod_params.antenna = (enum iwl3945_antenna)ant;
4752         } else
4753                 IWL_DEBUG_INFO(priv, "Bad antenna select value %d.\n", ant);
4754
4755
4756         return count;
4757 }
4758
4759 static DEVICE_ATTR(antenna, S_IWUSR | S_IRUGO, show_antenna, store_antenna);
4760
4761 static ssize_t show_status(struct device *d,
4762                            struct device_attribute *attr, char *buf)
4763 {
4764         struct iwl_priv *priv = (struct iwl_priv *)d->driver_data;
4765         if (!iwl_is_alive(priv))
4766                 return -EAGAIN;
4767         return sprintf(buf, "0x%08x\n", (int)priv->status);
4768 }
4769
4770 static DEVICE_ATTR(status, S_IRUGO, show_status, NULL);
4771
4772 static ssize_t dump_error_log(struct device *d,
4773                               struct device_attribute *attr,
4774                               const char *buf, size_t count)
4775 {
4776         char *p = (char *)buf;
4777
4778         if (p[0] == '1')
4779                 iwl3945_dump_nic_error_log((struct iwl_priv *)d->driver_data);
4780
4781         return strnlen(buf, count);
4782 }
4783
4784 static DEVICE_ATTR(dump_errors, S_IWUSR, NULL, dump_error_log);
4785
4786 static ssize_t dump_event_log(struct device *d,
4787                               struct device_attribute *attr,
4788                               const char *buf, size_t count)
4789 {
4790         char *p = (char *)buf;
4791
4792         if (p[0] == '1')
4793                 iwl3945_dump_nic_event_log((struct iwl_priv *)d->driver_data);
4794
4795         return strnlen(buf, count);
4796 }
4797
4798 static DEVICE_ATTR(dump_events, S_IWUSR, NULL, dump_event_log);
4799
4800 /*****************************************************************************
4801  *
4802  * driver setup and tear down
4803  *
4804  *****************************************************************************/
4805
4806 static void iwl3945_setup_deferred_work(struct iwl_priv *priv)
4807 {
4808         priv->workqueue = create_singlethread_workqueue(DRV_NAME);
4809
4810         init_waitqueue_head(&priv->wait_command_queue);
4811
4812         INIT_WORK(&priv->up, iwl3945_bg_up);
4813         INIT_WORK(&priv->restart, iwl3945_bg_restart);
4814         INIT_WORK(&priv->rx_replenish, iwl3945_bg_rx_replenish);
4815         INIT_WORK(&priv->rf_kill, iwl_bg_rf_kill);
4816         INIT_WORK(&priv->beacon_update, iwl3945_bg_beacon_update);
4817         INIT_DELAYED_WORK(&priv->init_alive_start, iwl3945_bg_init_alive_start);
4818         INIT_DELAYED_WORK(&priv->alive_start, iwl3945_bg_alive_start);
4819         INIT_DELAYED_WORK(&priv->rfkill_poll, iwl3945_rfkill_poll);
4820         INIT_WORK(&priv->scan_completed, iwl_bg_scan_completed);
4821         INIT_WORK(&priv->request_scan, iwl3945_bg_request_scan);
4822         INIT_WORK(&priv->abort_scan, iwl_bg_abort_scan);
4823         INIT_DELAYED_WORK(&priv->scan_check, iwl_bg_scan_check);
4824
4825         iwl3945_hw_setup_deferred_work(priv);
4826
4827         tasklet_init(&priv->irq_tasklet, (void (*)(unsigned long))
4828                      iwl3945_irq_tasklet, (unsigned long)priv);
4829 }
4830
4831 static void iwl3945_cancel_deferred_work(struct iwl_priv *priv)
4832 {
4833         iwl3945_hw_cancel_deferred_work(priv);
4834
4835         cancel_delayed_work_sync(&priv->init_alive_start);
4836         cancel_delayed_work(&priv->scan_check);
4837         cancel_delayed_work(&priv->alive_start);
4838         cancel_work_sync(&priv->beacon_update);
4839 }
4840
4841 static struct attribute *iwl3945_sysfs_entries[] = {
4842         &dev_attr_antenna.attr,
4843         &dev_attr_channels.attr,
4844         &dev_attr_dump_errors.attr,
4845         &dev_attr_dump_events.attr,
4846         &dev_attr_flags.attr,
4847         &dev_attr_filter_flags.attr,
4848 #ifdef CONFIG_IWL3945_SPECTRUM_MEASUREMENT
4849         &dev_attr_measurement.attr,
4850 #endif
4851         &dev_attr_power_level.attr,
4852         &dev_attr_retry_rate.attr,
4853         &dev_attr_statistics.attr,
4854         &dev_attr_status.attr,
4855         &dev_attr_temperature.attr,
4856         &dev_attr_tx_power.attr,
4857 #ifdef CONFIG_IWLWIFI_DEBUG
4858         &dev_attr_debug_level.attr,
4859 #endif
4860         NULL
4861 };
4862
4863 static struct attribute_group iwl3945_attribute_group = {
4864         .name = NULL,           /* put in device directory */
4865         .attrs = iwl3945_sysfs_entries,
4866 };
4867
4868 static struct ieee80211_ops iwl3945_hw_ops = {
4869         .tx = iwl3945_mac_tx,
4870         .start = iwl3945_mac_start,
4871         .stop = iwl3945_mac_stop,
4872         .add_interface = iwl3945_mac_add_interface,
4873         .remove_interface = iwl3945_mac_remove_interface,
4874         .config = iwl3945_mac_config,
4875         .config_interface = iwl3945_mac_config_interface,
4876         .configure_filter = iwl_configure_filter,
4877         .set_key = iwl3945_mac_set_key,
4878         .get_tx_stats = iwl3945_mac_get_tx_stats,
4879         .conf_tx = iwl3945_mac_conf_tx,
4880         .reset_tsf = iwl3945_mac_reset_tsf,
4881         .bss_info_changed = iwl3945_bss_info_changed,
4882         .hw_scan = iwl_mac_hw_scan
4883 };
4884
4885 static int iwl3945_init_drv(struct iwl_priv *priv)
4886 {
4887         int ret;
4888         struct iwl3945_eeprom *eeprom = (struct iwl3945_eeprom *)priv->eeprom;
4889
4890         priv->retry_rate = 1;
4891         priv->ibss_beacon = NULL;
4892
4893         spin_lock_init(&priv->lock);
4894         spin_lock_init(&priv->power_data.lock);
4895         spin_lock_init(&priv->sta_lock);
4896         spin_lock_init(&priv->hcmd_lock);
4897
4898         INIT_LIST_HEAD(&priv->free_frames);
4899
4900         mutex_init(&priv->mutex);
4901
4902         /* Clear the driver's (not device's) station table */
4903         iwl3945_clear_stations_table(priv);
4904
4905         priv->data_retry_limit = -1;
4906         priv->ieee_channels = NULL;
4907         priv->ieee_rates = NULL;
4908         priv->band = IEEE80211_BAND_2GHZ;
4909
4910         priv->iw_mode = NL80211_IFTYPE_STATION;
4911
4912         iwl_reset_qos(priv);
4913
4914         priv->qos_data.qos_active = 0;
4915         priv->qos_data.qos_cap.val = 0;
4916
4917         priv->rates_mask = IWL_RATES_MASK;
4918         /* If power management is turned on, default to CAM mode */
4919         priv->power_mode = IWL_POWER_MODE_CAM;
4920         priv->tx_power_user_lmt = IWL_DEFAULT_TX_POWER;
4921
4922         if (eeprom->version < EEPROM_3945_EEPROM_VERSION) {
4923                 IWL_WARN(priv, "Unsupported EEPROM version: 0x%04X\n",
4924                          eeprom->version);
4925                 ret = -EINVAL;
4926                 goto err;
4927         }
4928         ret = iwl_init_channel_map(priv);
4929         if (ret) {
4930                 IWL_ERR(priv, "initializing regulatory failed: %d\n", ret);
4931                 goto err;
4932         }
4933
4934         /* Set up txpower settings in driver for all channels */
4935         if (iwl3945_txpower_set_from_eeprom(priv)) {
4936                 ret = -EIO;
4937                 goto err_free_channel_map;
4938         }
4939
4940         ret = iwlcore_init_geos(priv);
4941         if (ret) {
4942                 IWL_ERR(priv, "initializing geos failed: %d\n", ret);
4943                 goto err_free_channel_map;
4944         }
4945         iwl3945_init_hw_rates(priv, priv->ieee_rates);
4946
4947         return 0;
4948
4949 err_free_channel_map:
4950         iwl_free_channel_map(priv);
4951 err:
4952         return ret;
4953 }
4954
4955 static int iwl3945_setup_mac(struct iwl_priv *priv)
4956 {
4957         int ret;
4958         struct ieee80211_hw *hw = priv->hw;
4959
4960         hw->rate_control_algorithm = "iwl-3945-rs";
4961         hw->sta_data_size = sizeof(struct iwl3945_sta_priv);
4962
4963         /* Tell mac80211 our characteristics */
4964         hw->flags = IEEE80211_HW_SIGNAL_DBM |
4965                     IEEE80211_HW_NOISE_DBM |
4966                     IEEE80211_HW_SPECTRUM_MGMT;
4967
4968         hw->wiphy->interface_modes =
4969                 BIT(NL80211_IFTYPE_STATION) |
4970                 BIT(NL80211_IFTYPE_ADHOC);
4971
4972         hw->wiphy->custom_regulatory = true;
4973
4974         hw->wiphy->max_scan_ssids = 1; /* WILL FIX */
4975
4976         /* Default value; 4 EDCA QOS priorities */
4977         hw->queues = 4;
4978
4979         hw->conf.beacon_int = 100;
4980
4981         if (priv->bands[IEEE80211_BAND_2GHZ].n_channels)
4982                 priv->hw->wiphy->bands[IEEE80211_BAND_2GHZ] =
4983                         &priv->bands[IEEE80211_BAND_2GHZ];
4984
4985         if (priv->bands[IEEE80211_BAND_5GHZ].n_channels)
4986                 priv->hw->wiphy->bands[IEEE80211_BAND_5GHZ] =
4987                         &priv->bands[IEEE80211_BAND_5GHZ];
4988
4989         ret = ieee80211_register_hw(priv->hw);
4990         if (ret) {
4991                 IWL_ERR(priv, "Failed to register hw (error %d)\n", ret);
4992                 return ret;
4993         }
4994         priv->mac80211_registered = 1;
4995
4996         return 0;
4997 }
4998
4999 static int iwl3945_pci_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
5000 {
5001         int err = 0;
5002         struct iwl_priv *priv;
5003         struct ieee80211_hw *hw;
5004         struct iwl_cfg *cfg = (struct iwl_cfg *)(ent->driver_data);
5005         struct iwl3945_eeprom *eeprom;
5006         unsigned long flags;
5007
5008         /***********************
5009          * 1. Allocating HW data
5010          * ********************/
5011
5012         /* mac80211 allocates memory for this device instance, including
5013          *   space for this driver's private structure */
5014         hw = iwl_alloc_all(cfg, &iwl3945_hw_ops);
5015         if (hw == NULL) {
5016                 printk(KERN_ERR DRV_NAME "Can not allocate network device\n");
5017                 err = -ENOMEM;
5018                 goto out;
5019         }
5020         priv = hw->priv;
5021         SET_IEEE80211_DEV(hw, &pdev->dev);
5022
5023         if ((iwl3945_mod_params.num_of_queues > IWL39_MAX_NUM_QUEUES) ||
5024              (iwl3945_mod_params.num_of_queues < IWL_MIN_NUM_QUEUES)) {
5025                 IWL_ERR(priv,
5026                         "invalid queues_num, should be between %d and %d\n",
5027                         IWL_MIN_NUM_QUEUES, IWL39_MAX_NUM_QUEUES);
5028                 err = -EINVAL;
5029                 goto out_ieee80211_free_hw;
5030         }
5031
5032         /*
5033          * Disabling hardware scan means that mac80211 will perform scans
5034          * "the hard way", rather than using device's scan.
5035          */
5036         if (iwl3945_mod_params.disable_hw_scan) {
5037                 IWL_DEBUG_INFO(priv, "Disabling hw_scan\n");
5038                 iwl3945_hw_ops.hw_scan = NULL;
5039         }
5040
5041
5042         IWL_DEBUG_INFO(priv, "*** LOAD DRIVER ***\n");
5043         priv->cfg = cfg;
5044         priv->pci_dev = pdev;
5045
5046 #ifdef CONFIG_IWLWIFI_DEBUG
5047         priv->debug_level = iwl3945_mod_params.debug;
5048         atomic_set(&priv->restrict_refcnt, 0);
5049 #endif
5050
5051         /***************************
5052          * 2. Initializing PCI bus
5053          * *************************/
5054         if (pci_enable_device(pdev)) {
5055                 err = -ENODEV;
5056                 goto out_ieee80211_free_hw;
5057         }
5058
5059         pci_set_master(pdev);
5060
5061         err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
5062         if (!err)
5063                 err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
5064         if (err) {
5065                 IWL_WARN(priv, "No suitable DMA available.\n");
5066                 goto out_pci_disable_device;
5067         }
5068
5069         pci_set_drvdata(pdev, priv);
5070         err = pci_request_regions(pdev, DRV_NAME);
5071         if (err)
5072                 goto out_pci_disable_device;
5073
5074         /***********************
5075          * 3. Read REV Register
5076          * ********************/
5077         priv->hw_base = pci_iomap(pdev, 0, 0);
5078         if (!priv->hw_base) {
5079                 err = -ENODEV;
5080                 goto out_pci_release_regions;
5081         }
5082
5083         IWL_DEBUG_INFO(priv, "pci_resource_len = 0x%08llx\n",
5084                         (unsigned long long) pci_resource_len(pdev, 0));
5085         IWL_DEBUG_INFO(priv, "pci_resource_base = %p\n", priv->hw_base);
5086
5087         /* We disable the RETRY_TIMEOUT register (0x41) to keep
5088          * PCI Tx retries from interfering with C3 CPU state */
5089         pci_write_config_byte(pdev, 0x41, 0x00);
5090
5091         /* amp init */
5092         err = priv->cfg->ops->lib->apm_ops.init(priv);
5093         if (err < 0) {
5094                 IWL_DEBUG_INFO(priv, "Failed to init the card\n");
5095                 goto out_iounmap;
5096         }
5097
5098         /***********************
5099          * 4. Read EEPROM
5100          * ********************/
5101
5102         /* Read the EEPROM */
5103         err = iwl_eeprom_init(priv);
5104         if (err) {
5105                 IWL_ERR(priv, "Unable to init EEPROM\n");
5106                 goto out_iounmap;
5107         }
5108         /* MAC Address location in EEPROM same for 3945/4965 */
5109         eeprom = (struct iwl3945_eeprom *)priv->eeprom;
5110         memcpy(priv->mac_addr, eeprom->mac_address, ETH_ALEN);
5111         IWL_DEBUG_INFO(priv, "MAC address: %pM\n", priv->mac_addr);
5112         SET_IEEE80211_PERM_ADDR(priv->hw, priv->mac_addr);
5113
5114         /***********************
5115          * 5. Setup HW Constants
5116          * ********************/
5117         /* Device-specific setup */
5118         if (iwl3945_hw_set_hw_params(priv)) {
5119                 IWL_ERR(priv, "failed to set hw settings\n");
5120                 goto out_eeprom_free;
5121         }
5122
5123         /***********************
5124          * 6. Setup priv
5125          * ********************/
5126
5127         err = iwl3945_init_drv(priv);
5128         if (err) {
5129                 IWL_ERR(priv, "initializing driver failed\n");
5130                 goto out_unset_hw_params;
5131         }
5132
5133         IWL_INFO(priv, "Detected Intel Wireless WiFi Link %s\n",
5134                 priv->cfg->name);
5135
5136         /***********************************
5137          * 7. Initialize Module Parameters
5138          * **********************************/
5139
5140         /* Initialize module parameter values here */
5141         /* Disable radio (SW RF KILL) via parameter when loading driver */
5142         if (iwl3945_mod_params.disable) {
5143                 set_bit(STATUS_RF_KILL_SW, &priv->status);
5144                 IWL_DEBUG_INFO(priv, "Radio disabled.\n");
5145         }
5146
5147
5148         /***********************
5149          * 8. Setup Services
5150          * ********************/
5151
5152         spin_lock_irqsave(&priv->lock, flags);
5153         iwl_disable_interrupts(priv);
5154         spin_unlock_irqrestore(&priv->lock, flags);
5155
5156         pci_enable_msi(priv->pci_dev);
5157
5158         err = request_irq(priv->pci_dev->irq, iwl_isr, IRQF_SHARED,
5159                           DRV_NAME, priv);
5160         if (err) {
5161                 IWL_ERR(priv, "Error allocating IRQ %d\n", priv->pci_dev->irq);
5162                 goto out_disable_msi;
5163         }
5164
5165         err = sysfs_create_group(&pdev->dev.kobj, &iwl3945_attribute_group);
5166         if (err) {
5167                 IWL_ERR(priv, "failed to create sysfs device attributes\n");
5168                 goto out_release_irq;
5169         }
5170
5171         iwl_set_rxon_channel(priv,
5172                              &priv->bands[IEEE80211_BAND_2GHZ].channels[5]);
5173         iwl3945_setup_deferred_work(priv);
5174         iwl3945_setup_rx_handlers(priv);
5175
5176         /*********************************
5177          * 9. Setup and Register mac80211
5178          * *******************************/
5179
5180         iwl_enable_interrupts(priv);
5181
5182         err = iwl3945_setup_mac(priv);
5183         if (err)
5184                 goto  out_remove_sysfs;
5185
5186         err = iwl_rfkill_init(priv);
5187         if (err)
5188                 IWL_ERR(priv, "Unable to initialize RFKILL system. "
5189                                   "Ignoring error: %d\n", err);
5190         else
5191                 iwl_rfkill_set_hw_state(priv);
5192
5193         /* Start monitoring the killswitch */
5194         queue_delayed_work(priv->workqueue, &priv->rfkill_poll,
5195                            2 * HZ);
5196
5197         return 0;
5198
5199  out_remove_sysfs:
5200         destroy_workqueue(priv->workqueue);
5201         priv->workqueue = NULL;
5202         sysfs_remove_group(&pdev->dev.kobj, &iwl3945_attribute_group);
5203  out_release_irq:
5204         free_irq(priv->pci_dev->irq, priv);
5205  out_disable_msi:
5206         pci_disable_msi(priv->pci_dev);
5207         iwlcore_free_geos(priv);
5208         iwl_free_channel_map(priv);
5209  out_unset_hw_params:
5210         iwl3945_unset_hw_params(priv);
5211  out_eeprom_free:
5212         iwl_eeprom_free(priv);
5213  out_iounmap:
5214         pci_iounmap(pdev, priv->hw_base);
5215  out_pci_release_regions:
5216         pci_release_regions(pdev);
5217  out_pci_disable_device:
5218         pci_set_drvdata(pdev, NULL);
5219         pci_disable_device(pdev);
5220  out_ieee80211_free_hw:
5221         ieee80211_free_hw(priv->hw);
5222  out:
5223         return err;
5224 }
5225
5226 static void __devexit iwl3945_pci_remove(struct pci_dev *pdev)
5227 {
5228         struct iwl_priv *priv = pci_get_drvdata(pdev);
5229         unsigned long flags;
5230
5231         if (!priv)
5232                 return;
5233
5234         IWL_DEBUG_INFO(priv, "*** UNLOAD DRIVER ***\n");
5235
5236         set_bit(STATUS_EXIT_PENDING, &priv->status);
5237
5238         if (priv->mac80211_registered) {
5239                 ieee80211_unregister_hw(priv->hw);
5240                 priv->mac80211_registered = 0;
5241         } else {
5242                 iwl3945_down(priv);
5243         }
5244
5245         /* make sure we flush any pending irq or
5246          * tasklet for the driver
5247          */
5248         spin_lock_irqsave(&priv->lock, flags);
5249         iwl_disable_interrupts(priv);
5250         spin_unlock_irqrestore(&priv->lock, flags);
5251
5252         iwl_synchronize_irq(priv);
5253
5254         sysfs_remove_group(&pdev->dev.kobj, &iwl3945_attribute_group);
5255
5256         iwl_rfkill_unregister(priv);
5257         cancel_delayed_work_sync(&priv->rfkill_poll);
5258
5259         iwl3945_dealloc_ucode_pci(priv);
5260
5261         if (priv->rxq.bd)
5262                 iwl3945_rx_queue_free(priv, &priv->rxq);
5263         iwl3945_hw_txq_ctx_free(priv);
5264
5265         iwl3945_unset_hw_params(priv);
5266         iwl3945_clear_stations_table(priv);
5267
5268         /*netif_stop_queue(dev); */
5269         flush_workqueue(priv->workqueue);
5270
5271         /* ieee80211_unregister_hw calls iwl3945_mac_stop, which flushes
5272          * priv->workqueue... so we can't take down the workqueue
5273          * until now... */
5274         destroy_workqueue(priv->workqueue);
5275         priv->workqueue = NULL;
5276
5277         free_irq(pdev->irq, priv);
5278         pci_disable_msi(pdev);
5279
5280         pci_iounmap(pdev, priv->hw_base);
5281         pci_release_regions(pdev);
5282         pci_disable_device(pdev);
5283         pci_set_drvdata(pdev, NULL);
5284
5285         iwl_free_channel_map(priv);
5286         iwlcore_free_geos(priv);
5287         kfree(priv->scan);
5288         if (priv->ibss_beacon)
5289                 dev_kfree_skb(priv->ibss_beacon);
5290
5291         ieee80211_free_hw(priv->hw);
5292 }
5293
5294 #ifdef CONFIG_PM
5295
5296 static int iwl3945_pci_suspend(struct pci_dev *pdev, pm_message_t state)
5297 {
5298         struct iwl_priv *priv = pci_get_drvdata(pdev);
5299
5300         if (priv->is_open) {
5301                 set_bit(STATUS_IN_SUSPEND, &priv->status);
5302                 iwl3945_mac_stop(priv->hw);
5303                 priv->is_open = 1;
5304         }
5305         pci_save_state(pdev);
5306         pci_disable_device(pdev);
5307         pci_set_power_state(pdev, PCI_D3hot);
5308
5309         return 0;
5310 }
5311
5312 static int iwl3945_pci_resume(struct pci_dev *pdev)
5313 {
5314         struct iwl_priv *priv = pci_get_drvdata(pdev);
5315         int ret;
5316
5317         pci_set_power_state(pdev, PCI_D0);
5318         ret = pci_enable_device(pdev);
5319         if (ret)
5320                 return ret;
5321         pci_restore_state(pdev);
5322
5323         if (priv->is_open)
5324                 iwl3945_mac_start(priv->hw);
5325
5326         clear_bit(STATUS_IN_SUSPEND, &priv->status);
5327         return 0;
5328 }
5329
5330 #endif /* CONFIG_PM */
5331
5332 /*****************************************************************************
5333  *
5334  * driver and module entry point
5335  *
5336  *****************************************************************************/
5337
5338 static struct pci_driver iwl3945_driver = {
5339         .name = DRV_NAME,
5340         .id_table = iwl3945_hw_card_ids,
5341         .probe = iwl3945_pci_probe,
5342         .remove = __devexit_p(iwl3945_pci_remove),
5343 #ifdef CONFIG_PM
5344         .suspend = iwl3945_pci_suspend,
5345         .resume = iwl3945_pci_resume,
5346 #endif
5347 };
5348
5349 static int __init iwl3945_init(void)
5350 {
5351
5352         int ret;
5353         printk(KERN_INFO DRV_NAME ": " DRV_DESCRIPTION ", " DRV_VERSION "\n");
5354         printk(KERN_INFO DRV_NAME ": " DRV_COPYRIGHT "\n");
5355
5356         ret = iwl3945_rate_control_register();
5357         if (ret) {
5358                 printk(KERN_ERR DRV_NAME
5359                        "Unable to register rate control algorithm: %d\n", ret);
5360                 return ret;
5361         }
5362
5363         ret = pci_register_driver(&iwl3945_driver);
5364         if (ret) {
5365                 printk(KERN_ERR DRV_NAME "Unable to initialize PCI module\n");
5366                 goto error_register;
5367         }
5368
5369         return ret;
5370
5371 error_register:
5372         iwl3945_rate_control_unregister();
5373         return ret;
5374 }
5375
5376 static void __exit iwl3945_exit(void)
5377 {
5378         pci_unregister_driver(&iwl3945_driver);
5379         iwl3945_rate_control_unregister();
5380 }
5381
5382 MODULE_FIRMWARE(IWL3945_MODULE_FIRMWARE(IWL3945_UCODE_API_MAX));
5383
5384 module_param_named(antenna, iwl3945_mod_params.antenna, int, 0444);
5385 MODULE_PARM_DESC(antenna, "select antenna (1=Main, 2=Aux, default 0 [both])");
5386 module_param_named(disable, iwl3945_mod_params.disable, int, 0444);
5387 MODULE_PARM_DESC(disable, "manually disable the radio (default 0 [radio on])");
5388 module_param_named(swcrypto, iwl3945_mod_params.sw_crypto, int, 0444);
5389 MODULE_PARM_DESC(swcrypto,
5390                  "using software crypto (default 1 [software])\n");
5391 module_param_named(debug, iwl3945_mod_params.debug, uint, 0444);
5392 MODULE_PARM_DESC(debug, "debug output mask");
5393 module_param_named(disable_hw_scan, iwl3945_mod_params.disable_hw_scan, int, 0444);
5394 MODULE_PARM_DESC(disable_hw_scan, "disable hardware scanning (default 0)");
5395
5396 module_param_named(queues_num, iwl3945_mod_params.num_of_queues, int, 0444);
5397 MODULE_PARM_DESC(queues_num, "number of hw queues.");
5398
5399 module_param_named(fw_restart3945, iwl3945_mod_params.restart_fw, int, 0444);
5400 MODULE_PARM_DESC(fw_restart3945, "restart firmware in case of error");
5401
5402 module_exit(iwl3945_exit);
5403 module_init(iwl3945_init);