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