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