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