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