iwl3945: use iwl_mac_beacon_update
[safe/jmp/linux-2.6] / drivers / net / wireless / iwlwifi / iwl3945-base.c
1 /******************************************************************************
2  *
3  * Copyright(c) 2003 - 2009 Intel Corporation. All rights reserved.
4  *
5  * Portions of this file are derived from the ipw3945 project, as well
6  * as portions of the ieee80211 subsystem header files.
7  *
8  * This program is free software; you can redistribute it and/or modify it
9  * under the terms of version 2 of the GNU General Public License as
10  * published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
15  * more details.
16  *
17  * You should have received a copy of the GNU General Public License along with
18  * this program; if not, write to the Free Software Foundation, Inc.,
19  * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
20  *
21  * The full GNU General Public License is included in this distribution in the
22  * file called LICENSE.
23  *
24  * Contact Information:
25  *  Intel Linux Wireless <ilw@linux.intel.com>
26  * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
27  *
28  *****************************************************************************/
29
30 #include <linux/kernel.h>
31 #include <linux/module.h>
32 #include <linux/init.h>
33 #include <linux/pci.h>
34 #include <linux/dma-mapping.h>
35 #include <linux/delay.h>
36 #include <linux/skbuff.h>
37 #include <linux/netdevice.h>
38 #include <linux/wireless.h>
39 #include <linux/firmware.h>
40 #include <linux/etherdevice.h>
41 #include <linux/if_arp.h>
42
43 #include <net/ieee80211_radiotap.h>
44 #include <net/lib80211.h>
45 #include <net/mac80211.h>
46
47 #include <asm/div64.h>
48
49 #define DRV_NAME        "iwl3945"
50
51 #include "iwl-fh.h"
52 #include "iwl-3945-fh.h"
53 #include "iwl-commands.h"
54 #include "iwl-sta.h"
55 #include "iwl-3945.h"
56 #include "iwl-helpers.h"
57 #include "iwl-core.h"
58 #include "iwl-dev.h"
59
60 /*
61  * module name, copyright, version, etc.
62  */
63
64 #define DRV_DESCRIPTION \
65 "Intel(R) PRO/Wireless 3945ABG/BG Network Connection driver for Linux"
66
67 #ifdef CONFIG_IWLWIFI_DEBUG
68 #define VD "d"
69 #else
70 #define VD
71 #endif
72
73 #ifdef CONFIG_IWL3945_SPECTRUM_MEASUREMENT
74 #define VS "s"
75 #else
76 #define VS
77 #endif
78
79 #define IWL39_VERSION "1.2.26k" VD VS
80 #define DRV_COPYRIGHT   "Copyright(c) 2003-2009 Intel Corporation"
81 #define DRV_AUTHOR     "<ilw@linux.intel.com>"
82 #define DRV_VERSION     IWL39_VERSION
83
84
85 MODULE_DESCRIPTION(DRV_DESCRIPTION);
86 MODULE_VERSION(DRV_VERSION);
87 MODULE_AUTHOR(DRV_COPYRIGHT " " DRV_AUTHOR);
88 MODULE_LICENSE("GPL");
89
90  /* module parameters */
91 struct iwl_mod_params iwl3945_mod_params = {
92         .num_of_queues = IWL39_MAX_NUM_QUEUES,
93         .sw_crypto = 1,
94         .restart_fw = 1,
95         /* the rest are 0 by default */
96 };
97
98 /*************** STATION TABLE MANAGEMENT ****
99  * mac80211 should be examined to determine if sta_info is duplicating
100  * the functionality provided here
101  */
102
103 /**************************************************************/
104 #if 0 /* temporary disable till we add real remove station */
105 /**
106  * iwl3945_remove_station - Remove driver's knowledge of station.
107  *
108  * NOTE:  This does not remove station from device's station table.
109  */
110 static u8 iwl3945_remove_station(struct iwl_priv *priv, const u8 *addr, int is_ap)
111 {
112         int index = IWL_INVALID_STATION;
113         int i;
114         unsigned long flags;
115
116         spin_lock_irqsave(&priv->sta_lock, flags);
117
118         if (is_ap)
119                 index = IWL_AP_ID;
120         else if (is_broadcast_ether_addr(addr))
121                 index = priv->hw_params.bcast_sta_id;
122         else
123                 for (i = IWL_STA_ID; i < priv->hw_params.max_stations; i++)
124                         if (priv->stations_39[i].used &&
125                             !compare_ether_addr(priv->stations_39[i].sta.sta.addr,
126                                                 addr)) {
127                                 index = i;
128                                 break;
129                         }
130
131         if (unlikely(index == IWL_INVALID_STATION))
132                 goto out;
133
134         if (priv->stations_39[index].used) {
135                 priv->stations_39[index].used = 0;
136                 priv->num_stations--;
137         }
138
139         BUG_ON(priv->num_stations < 0);
140
141 out:
142         spin_unlock_irqrestore(&priv->sta_lock, flags);
143         return 0;
144 }
145 #endif
146
147 /**
148  * iwl3945_clear_stations_table - Clear the driver's station table
149  *
150  * NOTE:  This does not clear or otherwise alter the device's station table.
151  */
152 static void iwl3945_clear_stations_table(struct iwl_priv *priv)
153 {
154         unsigned long flags;
155
156         spin_lock_irqsave(&priv->sta_lock, flags);
157
158         priv->num_stations = 0;
159         memset(priv->stations_39, 0, sizeof(priv->stations_39));
160
161         spin_unlock_irqrestore(&priv->sta_lock, flags);
162 }
163
164 /**
165  * iwl3945_add_station - Add station to station tables in driver and device
166  */
167 u8 iwl3945_add_station(struct iwl_priv *priv, const u8 *addr, int is_ap, u8 flags)
168 {
169         int i;
170         int index = IWL_INVALID_STATION;
171         struct iwl3945_station_entry *station;
172         unsigned long flags_spin;
173         u8 rate;
174
175         spin_lock_irqsave(&priv->sta_lock, flags_spin);
176         if (is_ap)
177                 index = IWL_AP_ID;
178         else if (is_broadcast_ether_addr(addr))
179                 index = priv->hw_params.bcast_sta_id;
180         else
181                 for (i = IWL_STA_ID; i < priv->hw_params.max_stations; i++) {
182                         if (!compare_ether_addr(priv->stations_39[i].sta.sta.addr,
183                                                 addr)) {
184                                 index = i;
185                                 break;
186                         }
187
188                         if (!priv->stations_39[i].used &&
189                             index == IWL_INVALID_STATION)
190                                 index = i;
191                 }
192
193         /* These two conditions has the same outcome but keep them separate
194           since they have different meaning */
195         if (unlikely(index == IWL_INVALID_STATION)) {
196                 spin_unlock_irqrestore(&priv->sta_lock, flags_spin);
197                 return index;
198         }
199
200         if (priv->stations_39[index].used &&
201            !compare_ether_addr(priv->stations_39[index].sta.sta.addr, addr)) {
202                 spin_unlock_irqrestore(&priv->sta_lock, flags_spin);
203                 return index;
204         }
205
206         IWL_DEBUG_ASSOC(priv, "Add STA ID %d: %pM\n", index, addr);
207         station = &priv->stations_39[index];
208         station->used = 1;
209         priv->num_stations++;
210
211         /* Set up the REPLY_ADD_STA command to send to device */
212         memset(&station->sta, 0, sizeof(struct iwl3945_addsta_cmd));
213         memcpy(station->sta.sta.addr, addr, ETH_ALEN);
214         station->sta.mode = 0;
215         station->sta.sta.sta_id = index;
216         station->sta.station_flags = 0;
217
218         if (priv->band == IEEE80211_BAND_5GHZ)
219                 rate = IWL_RATE_6M_PLCP;
220         else
221                 rate =  IWL_RATE_1M_PLCP;
222
223         /* Turn on both antennas for the station... */
224         station->sta.rate_n_flags =
225                         iwl3945_hw_set_rate_n_flags(rate, RATE_MCS_ANT_AB_MSK);
226
227         spin_unlock_irqrestore(&priv->sta_lock, flags_spin);
228
229         /* Add station to device's station table */
230         iwl_send_add_sta(priv,
231                          (struct iwl_addsta_cmd *)&station->sta, flags);
232         return index;
233
234 }
235
236 /**
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  * iwl3945_alive_start - called after REPLY_ALIVE notification received
2797  *                   from protocol/runtime uCode (initialization uCode's
2798  *                   Alive gets handled by iwl3945_init_alive_start()).
2799  */
2800 static void iwl3945_alive_start(struct iwl_priv *priv)
2801 {
2802         int rc = 0;
2803         int thermal_spin = 0;
2804         u32 rfkill;
2805
2806         IWL_DEBUG_INFO(priv, "Runtime Alive received.\n");
2807
2808         if (priv->card_alive.is_valid != UCODE_VALID_OK) {
2809                 /* We had an error bringing up the hardware, so take it
2810                  * all the way back down so we can try again */
2811                 IWL_DEBUG_INFO(priv, "Alive failed.\n");
2812                 goto restart;
2813         }
2814
2815         /* Initialize uCode has loaded Runtime uCode ... verify inst image.
2816          * This is a paranoid check, because we would not have gotten the
2817          * "runtime" alive if code weren't properly loaded.  */
2818         if (iwl3945_verify_ucode(priv)) {
2819                 /* Runtime instruction load was bad;
2820                  * take it all the way back down so we can try again */
2821                 IWL_DEBUG_INFO(priv, "Bad runtime uCode load.\n");
2822                 goto restart;
2823         }
2824
2825         iwl3945_clear_stations_table(priv);
2826
2827         rc = iwl_grab_nic_access(priv);
2828         if (rc) {
2829                 IWL_WARN(priv, "Can not read RFKILL status from adapter\n");
2830                 return;
2831         }
2832
2833         rfkill = iwl_read_prph(priv, APMG_RFKILL_REG);
2834         IWL_DEBUG_INFO(priv, "RFKILL status: 0x%x\n", rfkill);
2835         iwl_release_nic_access(priv);
2836
2837         if (rfkill & 0x1) {
2838                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
2839                 /* if RFKILL is not on, then wait for thermal
2840                  * sensor in adapter to kick in */
2841                 while (iwl3945_hw_get_temperature(priv) == 0) {
2842                         thermal_spin++;
2843                         udelay(10);
2844                 }
2845
2846                 if (thermal_spin)
2847                         IWL_DEBUG_INFO(priv, "Thermal calibration took %dus\n",
2848                                        thermal_spin * 10);
2849         } else
2850                 set_bit(STATUS_RF_KILL_HW, &priv->status);
2851
2852         /* After the ALIVE response, we can send commands to 3945 uCode */
2853         set_bit(STATUS_ALIVE, &priv->status);
2854
2855         /* Clear out the uCode error bit if it is set */
2856         clear_bit(STATUS_FW_ERROR, &priv->status);
2857
2858         if (iwl_is_rfkill(priv))
2859                 return;
2860
2861         ieee80211_wake_queues(priv->hw);
2862
2863         priv->active_rate = priv->rates_mask;
2864         priv->active_rate_basic = priv->rates_mask & IWL_BASIC_RATES_MASK;
2865
2866         iwl_power_update_mode(priv, false);
2867
2868         if (iwl_is_associated(priv)) {
2869                 struct iwl3945_rxon_cmd *active_rxon =
2870                                 (struct iwl3945_rxon_cmd *)(&priv->active_rxon);
2871
2872                 memcpy(&priv->staging_rxon, &priv->active_rxon,
2873                        sizeof(priv->staging_rxon));
2874                 active_rxon->filter_flags &= ~RXON_FILTER_ASSOC_MSK;
2875         } else {
2876                 /* Initialize our rx_config data */
2877                 iwl_connection_init_rx_config(priv, priv->iw_mode);
2878         }
2879
2880         /* Configure Bluetooth device coexistence support */
2881         iwl_send_bt_config(priv);
2882
2883         /* Configure the adapter for unassociated operation */
2884         iwl3945_commit_rxon(priv);
2885
2886         iwl3945_reg_txpower_periodic(priv);
2887
2888         iwl3945_led_register(priv);
2889
2890         IWL_DEBUG_INFO(priv, "ALIVE processing complete.\n");
2891         set_bit(STATUS_READY, &priv->status);
2892         wake_up_interruptible(&priv->wait_command_queue);
2893
2894         if (priv->error_recovering)
2895                 iwl3945_error_recovery(priv);
2896
2897         /* reassociate for ADHOC mode */
2898         if (priv->vif && (priv->iw_mode == NL80211_IFTYPE_ADHOC)) {
2899                 struct sk_buff *beacon = ieee80211_beacon_get(priv->hw,
2900                                                                 priv->vif);
2901                 if (beacon)
2902                         iwl_mac_beacon_update(priv->hw, beacon);
2903         }
2904
2905         return;
2906
2907  restart:
2908         queue_work(priv->workqueue, &priv->restart);
2909 }
2910
2911 static void iwl3945_cancel_deferred_work(struct iwl_priv *priv);
2912
2913 static void __iwl3945_down(struct iwl_priv *priv)
2914 {
2915         unsigned long flags;
2916         int exit_pending = test_bit(STATUS_EXIT_PENDING, &priv->status);
2917         struct ieee80211_conf *conf = NULL;
2918
2919         IWL_DEBUG_INFO(priv, DRV_NAME " is going down\n");
2920
2921         conf = ieee80211_get_hw_conf(priv->hw);
2922
2923         if (!exit_pending)
2924                 set_bit(STATUS_EXIT_PENDING, &priv->status);
2925
2926         iwl3945_led_unregister(priv);
2927         iwl3945_clear_stations_table(priv);
2928
2929         /* Unblock any waiting calls */
2930         wake_up_interruptible_all(&priv->wait_command_queue);
2931
2932         /* Wipe out the EXIT_PENDING status bit if we are not actually
2933          * exiting the module */
2934         if (!exit_pending)
2935                 clear_bit(STATUS_EXIT_PENDING, &priv->status);
2936
2937         /* stop and reset the on-board processor */
2938         iwl_write32(priv, CSR_RESET, CSR_RESET_REG_FLAG_NEVO_RESET);
2939
2940         /* tell the device to stop sending interrupts */
2941         spin_lock_irqsave(&priv->lock, flags);
2942         iwl_disable_interrupts(priv);
2943         spin_unlock_irqrestore(&priv->lock, flags);
2944         iwl_synchronize_irq(priv);
2945
2946         if (priv->mac80211_registered)
2947                 ieee80211_stop_queues(priv->hw);
2948
2949         /* If we have not previously called iwl3945_init() then
2950          * clear all bits but the RF Kill bits and return */
2951         if (!iwl_is_init(priv)) {
2952                 priv->status = test_bit(STATUS_RF_KILL_HW, &priv->status) <<
2953                                         STATUS_RF_KILL_HW |
2954                                test_bit(STATUS_RF_KILL_SW, &priv->status) <<
2955                                         STATUS_RF_KILL_SW |
2956                                test_bit(STATUS_GEO_CONFIGURED, &priv->status) <<
2957                                         STATUS_GEO_CONFIGURED |
2958                                 test_bit(STATUS_EXIT_PENDING, &priv->status) <<
2959                                         STATUS_EXIT_PENDING;
2960                 goto exit;
2961         }
2962
2963         /* ...otherwise clear out all the status bits but the RF Kill
2964          * bits and continue taking the NIC down. */
2965         priv->status &= test_bit(STATUS_RF_KILL_HW, &priv->status) <<
2966                                 STATUS_RF_KILL_HW |
2967                         test_bit(STATUS_RF_KILL_SW, &priv->status) <<
2968                                 STATUS_RF_KILL_SW |
2969                         test_bit(STATUS_GEO_CONFIGURED, &priv->status) <<
2970                                 STATUS_GEO_CONFIGURED |
2971                         test_bit(STATUS_FW_ERROR, &priv->status) <<
2972                                 STATUS_FW_ERROR |
2973                         test_bit(STATUS_EXIT_PENDING, &priv->status) <<
2974                                 STATUS_EXIT_PENDING;
2975
2976         priv->cfg->ops->lib->apm_ops.reset(priv);
2977         spin_lock_irqsave(&priv->lock, flags);
2978         iwl_clear_bit(priv, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
2979         spin_unlock_irqrestore(&priv->lock, flags);
2980
2981         iwl3945_hw_txq_ctx_stop(priv);
2982         iwl3945_hw_rxq_stop(priv);
2983
2984         spin_lock_irqsave(&priv->lock, flags);
2985         if (!iwl_grab_nic_access(priv)) {
2986                 iwl_write_prph(priv, APMG_CLK_DIS_REG,
2987                                          APMG_CLK_VAL_DMA_CLK_RQT);
2988                 iwl_release_nic_access(priv);
2989         }
2990         spin_unlock_irqrestore(&priv->lock, flags);
2991
2992         udelay(5);
2993
2994         if (exit_pending)
2995                 priv->cfg->ops->lib->apm_ops.stop(priv);
2996         else
2997                 priv->cfg->ops->lib->apm_ops.reset(priv);
2998
2999  exit:
3000         memset(&priv->card_alive, 0, sizeof(struct iwl_alive_resp));
3001
3002         if (priv->ibss_beacon)
3003                 dev_kfree_skb(priv->ibss_beacon);
3004         priv->ibss_beacon = NULL;
3005
3006         /* clear out any free frames */
3007         iwl3945_clear_free_frames(priv);
3008 }
3009
3010 static void iwl3945_down(struct iwl_priv *priv)
3011 {
3012         mutex_lock(&priv->mutex);
3013         __iwl3945_down(priv);
3014         mutex_unlock(&priv->mutex);
3015
3016         iwl3945_cancel_deferred_work(priv);
3017 }
3018
3019 #define MAX_HW_RESTARTS 5
3020
3021 static int __iwl3945_up(struct iwl_priv *priv)
3022 {
3023         int rc, i;
3024
3025         if (test_bit(STATUS_EXIT_PENDING, &priv->status)) {
3026                 IWL_WARN(priv, "Exit pending; will not bring the NIC up\n");
3027                 return -EIO;
3028         }
3029
3030         if (test_bit(STATUS_RF_KILL_SW, &priv->status)) {
3031                 IWL_WARN(priv, "Radio disabled by SW RF kill (module "
3032                             "parameter)\n");
3033                 return -ENODEV;
3034         }
3035
3036         if (!priv->ucode_data_backup.v_addr || !priv->ucode_data.v_addr) {
3037                 IWL_ERR(priv, "ucode not available for device bring up\n");
3038                 return -EIO;
3039         }
3040
3041         /* If platform's RF_KILL switch is NOT set to KILL */
3042         if (iwl_read32(priv, CSR_GP_CNTRL) &
3043                                 CSR_GP_CNTRL_REG_FLAG_HW_RF_KILL_SW)
3044                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
3045         else {
3046                 set_bit(STATUS_RF_KILL_HW, &priv->status);
3047                 IWL_WARN(priv, "Radio disabled by HW RF Kill switch\n");
3048                 return -ENODEV;
3049         }
3050
3051         iwl_write32(priv, CSR_INT, 0xFFFFFFFF);
3052
3053         rc = iwl3945_hw_nic_init(priv);
3054         if (rc) {
3055                 IWL_ERR(priv, "Unable to int nic\n");
3056                 return rc;
3057         }
3058
3059         /* make sure rfkill handshake bits are cleared */
3060         iwl_write32(priv, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
3061         iwl_write32(priv, CSR_UCODE_DRV_GP1_CLR,
3062                     CSR_UCODE_DRV_GP1_BIT_CMD_BLOCKED);
3063
3064         /* clear (again), then enable host interrupts */
3065         iwl_write32(priv, CSR_INT, 0xFFFFFFFF);
3066         iwl_enable_interrupts(priv);
3067
3068         /* really make sure rfkill handshake bits are cleared */
3069         iwl_write32(priv, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
3070         iwl_write32(priv, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
3071
3072         /* Copy original ucode data image from disk into backup cache.
3073          * This will be used to initialize the on-board processor's
3074          * data SRAM for a clean start when the runtime program first loads. */
3075         memcpy(priv->ucode_data_backup.v_addr, priv->ucode_data.v_addr,
3076                priv->ucode_data.len);
3077
3078         /* We return success when we resume from suspend and rf_kill is on. */
3079         if (test_bit(STATUS_RF_KILL_HW, &priv->status))
3080                 return 0;
3081
3082         for (i = 0; i < MAX_HW_RESTARTS; i++) {
3083
3084                 iwl3945_clear_stations_table(priv);
3085
3086                 /* load bootstrap state machine,
3087                  * load bootstrap program into processor's memory,
3088                  * prepare to load the "initialize" uCode */
3089                 priv->cfg->ops->lib->load_ucode(priv);
3090
3091                 if (rc) {
3092                         IWL_ERR(priv,
3093                                 "Unable to set up bootstrap uCode: %d\n", rc);
3094                         continue;
3095                 }
3096
3097                 /* start card; "initialize" will load runtime ucode */
3098                 iwl3945_nic_start(priv);
3099
3100                 IWL_DEBUG_INFO(priv, DRV_NAME " is coming up\n");
3101
3102                 return 0;
3103         }
3104
3105         set_bit(STATUS_EXIT_PENDING, &priv->status);
3106         __iwl3945_down(priv);
3107         clear_bit(STATUS_EXIT_PENDING, &priv->status);
3108
3109         /* tried to restart and config the device for as long as our
3110          * patience could withstand */
3111         IWL_ERR(priv, "Unable to initialize device after %d attempts.\n", i);
3112         return -EIO;
3113 }
3114
3115
3116 /*****************************************************************************
3117  *
3118  * Workqueue callbacks
3119  *
3120  *****************************************************************************/
3121
3122 static void iwl3945_bg_init_alive_start(struct work_struct *data)
3123 {
3124         struct iwl_priv *priv =
3125             container_of(data, struct iwl_priv, init_alive_start.work);
3126
3127         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
3128                 return;
3129
3130         mutex_lock(&priv->mutex);
3131         iwl3945_init_alive_start(priv);
3132         mutex_unlock(&priv->mutex);
3133 }
3134
3135 static void iwl3945_bg_alive_start(struct work_struct *data)
3136 {
3137         struct iwl_priv *priv =
3138             container_of(data, struct iwl_priv, alive_start.work);
3139
3140         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
3141                 return;
3142
3143         mutex_lock(&priv->mutex);
3144         iwl3945_alive_start(priv);
3145         mutex_unlock(&priv->mutex);
3146 }
3147
3148 static void iwl3945_rfkill_poll(struct work_struct *data)
3149 {
3150         struct iwl_priv *priv =
3151             container_of(data, struct iwl_priv, rfkill_poll.work);
3152         unsigned long status = priv->status;
3153
3154         if (iwl_read32(priv, CSR_GP_CNTRL) & CSR_GP_CNTRL_REG_FLAG_HW_RF_KILL_SW)
3155                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
3156         else
3157                 set_bit(STATUS_RF_KILL_HW, &priv->status);
3158
3159         if (test_bit(STATUS_RF_KILL_HW, &status) != test_bit(STATUS_RF_KILL_HW, &priv->status))
3160                 queue_work(priv->workqueue, &priv->rf_kill);
3161
3162         queue_delayed_work(priv->workqueue, &priv->rfkill_poll,
3163                            round_jiffies_relative(2 * HZ));
3164
3165 }
3166
3167 #define IWL_SCAN_CHECK_WATCHDOG (7 * HZ)
3168 static void iwl3945_bg_request_scan(struct work_struct *data)
3169 {
3170         struct iwl_priv *priv =
3171             container_of(data, struct iwl_priv, request_scan);
3172         struct iwl_host_cmd cmd = {
3173                 .id = REPLY_SCAN_CMD,
3174                 .len = sizeof(struct iwl3945_scan_cmd),
3175                 .meta.flags = CMD_SIZE_HUGE,
3176         };
3177         int rc = 0;
3178         struct iwl3945_scan_cmd *scan;
3179         struct ieee80211_conf *conf = NULL;
3180         u8 n_probes = 2;
3181         enum ieee80211_band band;
3182         DECLARE_SSID_BUF(ssid);
3183
3184         conf = ieee80211_get_hw_conf(priv->hw);
3185
3186         mutex_lock(&priv->mutex);
3187
3188         if (!iwl_is_ready(priv)) {
3189                 IWL_WARN(priv, "request scan called when driver not ready.\n");
3190                 goto done;
3191         }
3192
3193         /* Make sure the scan wasn't canceled before this queued work
3194          * was given the chance to run... */
3195         if (!test_bit(STATUS_SCANNING, &priv->status))
3196                 goto done;
3197
3198         /* This should never be called or scheduled if there is currently
3199          * a scan active in the hardware. */
3200         if (test_bit(STATUS_SCAN_HW, &priv->status)) {
3201                 IWL_DEBUG_INFO(priv, "Multiple concurrent scan requests  "
3202                                 "Ignoring second request.\n");
3203                 rc = -EIO;
3204                 goto done;
3205         }
3206
3207         if (test_bit(STATUS_EXIT_PENDING, &priv->status)) {
3208                 IWL_DEBUG_SCAN(priv, "Aborting scan due to device shutdown\n");
3209                 goto done;
3210         }
3211
3212         if (test_bit(STATUS_SCAN_ABORTING, &priv->status)) {
3213                 IWL_DEBUG_HC(priv,
3214                         "Scan request while abort pending. Queuing.\n");
3215                 goto done;
3216         }
3217
3218         if (iwl_is_rfkill(priv)) {
3219                 IWL_DEBUG_HC(priv, "Aborting scan due to RF Kill activation\n");
3220                 goto done;
3221         }
3222
3223         if (!test_bit(STATUS_READY, &priv->status)) {
3224                 IWL_DEBUG_HC(priv,
3225                         "Scan request while uninitialized. Queuing.\n");
3226                 goto done;
3227         }
3228
3229         if (!priv->scan_bands) {
3230                 IWL_DEBUG_HC(priv, "Aborting scan due to no requested bands\n");
3231                 goto done;
3232         }
3233
3234         if (!priv->scan) {
3235                 priv->scan = kmalloc(sizeof(struct iwl3945_scan_cmd) +
3236                                      IWL_MAX_SCAN_SIZE, GFP_KERNEL);
3237                 if (!priv->scan) {
3238                         rc = -ENOMEM;
3239                         goto done;
3240                 }
3241         }
3242         scan = priv->scan;
3243         memset(scan, 0, sizeof(struct iwl3945_scan_cmd) + IWL_MAX_SCAN_SIZE);
3244
3245         scan->quiet_plcp_th = IWL_PLCP_QUIET_THRESH;
3246         scan->quiet_time = IWL_ACTIVE_QUIET_TIME;
3247
3248         if (iwl_is_associated(priv)) {
3249                 u16 interval = 0;
3250                 u32 extra;
3251                 u32 suspend_time = 100;
3252                 u32 scan_suspend_time = 100;
3253                 unsigned long flags;
3254
3255                 IWL_DEBUG_INFO(priv, "Scanning while associated...\n");
3256
3257                 spin_lock_irqsave(&priv->lock, flags);
3258                 interval = priv->beacon_int;
3259                 spin_unlock_irqrestore(&priv->lock, flags);
3260
3261                 scan->suspend_time = 0;
3262                 scan->max_out_time = cpu_to_le32(200 * 1024);
3263                 if (!interval)
3264                         interval = suspend_time;
3265                 /*
3266                  * suspend time format:
3267                  *  0-19: beacon interval in usec (time before exec.)
3268                  * 20-23: 0
3269                  * 24-31: number of beacons (suspend between channels)
3270                  */
3271
3272                 extra = (suspend_time / interval) << 24;
3273                 scan_suspend_time = 0xFF0FFFFF &
3274                     (extra | ((suspend_time % interval) * 1024));
3275
3276                 scan->suspend_time = cpu_to_le32(scan_suspend_time);
3277                 IWL_DEBUG_SCAN(priv, "suspend_time 0x%X beacon interval %d\n",
3278                                scan_suspend_time, interval);
3279         }
3280
3281         /* We should add the ability for user to lock to PASSIVE ONLY */
3282         if (priv->one_direct_scan) {
3283                 IWL_DEBUG_SCAN(priv, "Kicking off one direct scan for '%s'\n",
3284                                 print_ssid(ssid, priv->direct_ssid,
3285                                 priv->direct_ssid_len));
3286                 scan->direct_scan[0].id = WLAN_EID_SSID;
3287                 scan->direct_scan[0].len = priv->direct_ssid_len;
3288                 memcpy(scan->direct_scan[0].ssid,
3289                        priv->direct_ssid, priv->direct_ssid_len);
3290                 n_probes++;
3291         } else
3292                 IWL_DEBUG_SCAN(priv, "Kicking off one indirect scan.\n");
3293
3294         /* We don't build a direct scan probe request; the uCode will do
3295          * that based on the direct_mask added to each channel entry */
3296         scan->tx_cmd.tx_flags = TX_CMD_FLG_SEQ_CTL_MSK;
3297         scan->tx_cmd.sta_id = priv->hw_params.bcast_sta_id;
3298         scan->tx_cmd.stop_time.life_time = TX_CMD_LIFE_TIME_INFINITE;
3299
3300         /* flags + rate selection */
3301
3302         if (priv->scan_bands & BIT(IEEE80211_BAND_2GHZ)) {
3303                 scan->flags = RXON_FLG_BAND_24G_MSK | RXON_FLG_AUTO_DETECT_MSK;
3304                 scan->tx_cmd.rate = IWL_RATE_1M_PLCP;
3305                 scan->good_CRC_th = 0;
3306                 band = IEEE80211_BAND_2GHZ;
3307         } else if (priv->scan_bands & BIT(IEEE80211_BAND_5GHZ)) {
3308                 scan->tx_cmd.rate = IWL_RATE_6M_PLCP;
3309                 scan->good_CRC_th = IWL_GOOD_CRC_TH;
3310                 band = IEEE80211_BAND_5GHZ;
3311         } else {
3312                 IWL_WARN(priv, "Invalid scan band count\n");
3313                 goto done;
3314         }
3315
3316         scan->tx_cmd.len = cpu_to_le16(
3317                 iwl_fill_probe_req(priv, band,
3318                                    (struct ieee80211_mgmt *)scan->data,
3319                                    IWL_MAX_SCAN_SIZE - sizeof(*scan)));
3320
3321         /* select Rx antennas */
3322         scan->flags |= iwl3945_get_antenna_flags(priv);
3323
3324         if (priv->iw_mode == NL80211_IFTYPE_MONITOR)
3325                 scan->filter_flags = RXON_FILTER_PROMISC_MSK;
3326
3327         scan->channel_count =
3328                 iwl3945_get_channels_for_scan(priv, band, 1, /* active */
3329                                               n_probes,
3330                         (void *)&scan->data[le16_to_cpu(scan->tx_cmd.len)]);
3331
3332         if (scan->channel_count == 0) {
3333                 IWL_DEBUG_SCAN(priv, "channel count %d\n", scan->channel_count);
3334                 goto done;
3335         }
3336
3337         cmd.len += le16_to_cpu(scan->tx_cmd.len) +
3338             scan->channel_count * sizeof(struct iwl3945_scan_channel);
3339         cmd.data = scan;
3340         scan->len = cpu_to_le16(cmd.len);
3341
3342         set_bit(STATUS_SCAN_HW, &priv->status);
3343         rc = iwl_send_cmd_sync(priv, &cmd);
3344         if (rc)
3345                 goto done;
3346
3347         queue_delayed_work(priv->workqueue, &priv->scan_check,
3348                            IWL_SCAN_CHECK_WATCHDOG);
3349
3350         mutex_unlock(&priv->mutex);
3351         return;
3352
3353  done:
3354         /* can not perform scan make sure we clear scanning
3355          * bits from status so next scan request can be performed.
3356          * if we dont clear scanning status bit here all next scan
3357          * will fail
3358         */
3359         clear_bit(STATUS_SCAN_HW, &priv->status);
3360         clear_bit(STATUS_SCANNING, &priv->status);
3361
3362         /* inform mac80211 scan aborted */
3363         queue_work(priv->workqueue, &priv->scan_completed);
3364         mutex_unlock(&priv->mutex);
3365 }
3366
3367 static void iwl3945_bg_up(struct work_struct *data)
3368 {
3369         struct iwl_priv *priv = container_of(data, struct iwl_priv, up);
3370
3371         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
3372                 return;
3373
3374         mutex_lock(&priv->mutex);
3375         __iwl3945_up(priv);
3376         mutex_unlock(&priv->mutex);
3377         iwl_rfkill_set_hw_state(priv);
3378 }
3379
3380 static void iwl3945_bg_restart(struct work_struct *data)
3381 {
3382         struct iwl_priv *priv = container_of(data, struct iwl_priv, restart);
3383
3384         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
3385                 return;
3386
3387         iwl3945_down(priv);
3388         queue_work(priv->workqueue, &priv->up);
3389 }
3390
3391 static void iwl3945_bg_rx_replenish(struct work_struct *data)
3392 {
3393         struct iwl_priv *priv =
3394             container_of(data, struct iwl_priv, rx_replenish);
3395
3396         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
3397                 return;
3398
3399         mutex_lock(&priv->mutex);
3400         iwl3945_rx_replenish(priv);
3401         mutex_unlock(&priv->mutex);
3402 }
3403
3404 static int iwl3945_mac_config(struct ieee80211_hw *hw, u32 changed);
3405
3406 #define IWL_DELAY_NEXT_SCAN (HZ*2)
3407
3408 void iwl3945_post_associate(struct iwl_priv *priv)
3409 {
3410         int rc = 0;
3411         struct ieee80211_conf *conf = NULL;
3412
3413         if (priv->iw_mode == NL80211_IFTYPE_AP) {
3414                 IWL_ERR(priv, "%s Should not be called in AP mode\n", __func__);
3415                 return;
3416         }
3417
3418
3419         IWL_DEBUG_ASSOC(priv, "Associated as %d to: %pM\n",
3420                         priv->assoc_id, priv->active_rxon.bssid_addr);
3421
3422         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
3423                 return;
3424
3425         if (!priv->vif || !priv->is_open)
3426                 return;
3427
3428         iwl_scan_cancel_timeout(priv, 200);
3429
3430         conf = ieee80211_get_hw_conf(priv->hw);
3431
3432         priv->staging_rxon.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
3433         iwl3945_commit_rxon(priv);
3434
3435         memset(&priv->rxon_timing, 0, sizeof(struct iwl_rxon_time_cmd));
3436         iwl3945_setup_rxon_timing(priv);
3437         rc = iwl_send_cmd_pdu(priv, REPLY_RXON_TIMING,
3438                               sizeof(priv->rxon_timing), &priv->rxon_timing);
3439         if (rc)
3440                 IWL_WARN(priv, "REPLY_RXON_TIMING failed - "
3441                             "Attempting to continue.\n");
3442
3443         priv->staging_rxon.filter_flags |= RXON_FILTER_ASSOC_MSK;
3444
3445         priv->staging_rxon.assoc_id = cpu_to_le16(priv->assoc_id);
3446
3447         IWL_DEBUG_ASSOC(priv, "assoc id %d beacon interval %d\n",
3448                         priv->assoc_id, priv->beacon_int);
3449
3450         if (priv->assoc_capability & WLAN_CAPABILITY_SHORT_PREAMBLE)
3451                 priv->staging_rxon.flags |= RXON_FLG_SHORT_PREAMBLE_MSK;
3452         else
3453                 priv->staging_rxon.flags &= ~RXON_FLG_SHORT_PREAMBLE_MSK;
3454
3455         if (priv->staging_rxon.flags & RXON_FLG_BAND_24G_MSK) {
3456                 if (priv->assoc_capability & WLAN_CAPABILITY_SHORT_SLOT_TIME)
3457                         priv->staging_rxon.flags |= RXON_FLG_SHORT_SLOT_MSK;
3458                 else
3459                         priv->staging_rxon.flags &= ~RXON_FLG_SHORT_SLOT_MSK;
3460
3461                 if (priv->iw_mode == NL80211_IFTYPE_ADHOC)
3462                         priv->staging_rxon.flags &= ~RXON_FLG_SHORT_SLOT_MSK;
3463
3464         }
3465
3466         iwl3945_commit_rxon(priv);
3467
3468         switch (priv->iw_mode) {
3469         case NL80211_IFTYPE_STATION:
3470                 iwl3945_rate_scale_init(priv->hw, IWL_AP_ID);
3471                 break;
3472
3473         case NL80211_IFTYPE_ADHOC:
3474
3475                 priv->assoc_id = 1;
3476                 iwl3945_add_station(priv, priv->bssid, 0, 0);
3477                 iwl3945_sync_sta(priv, IWL_STA_ID,
3478                                  (priv->band == IEEE80211_BAND_5GHZ) ?
3479                                  IWL_RATE_6M_PLCP : IWL_RATE_1M_PLCP,
3480                                  CMD_ASYNC);
3481                 iwl3945_rate_scale_init(priv->hw, IWL_STA_ID);
3482                 iwl3945_send_beacon_cmd(priv);
3483
3484                 break;
3485
3486         default:
3487                  IWL_ERR(priv, "%s Should not be called in %d mode\n",
3488                            __func__, priv->iw_mode);
3489                 break;
3490         }
3491
3492         iwl_activate_qos(priv, 0);
3493
3494         /* we have just associated, don't start scan too early */
3495         priv->next_scan_jiffies = jiffies + IWL_DELAY_NEXT_SCAN;
3496 }
3497
3498 /*****************************************************************************
3499  *
3500  * mac80211 entry point functions
3501  *
3502  *****************************************************************************/
3503
3504 #define UCODE_READY_TIMEOUT     (2 * HZ)
3505
3506 static int iwl3945_mac_start(struct ieee80211_hw *hw)
3507 {
3508         struct iwl_priv *priv = hw->priv;
3509         int ret;
3510
3511         IWL_DEBUG_MAC80211(priv, "enter\n");
3512
3513         /* we should be verifying the device is ready to be opened */
3514         mutex_lock(&priv->mutex);
3515
3516         memset(&priv->staging_rxon, 0, sizeof(priv->staging_rxon));
3517         /* fetch ucode file from disk, alloc and copy to bus-master buffers ...
3518          * ucode filename and max sizes are card-specific. */
3519
3520         if (!priv->ucode_code.len) {
3521                 ret = iwl3945_read_ucode(priv);
3522                 if (ret) {
3523                         IWL_ERR(priv, "Could not read microcode: %d\n", ret);
3524                         mutex_unlock(&priv->mutex);
3525                         goto out_release_irq;
3526                 }
3527         }
3528
3529         ret = __iwl3945_up(priv);
3530
3531         mutex_unlock(&priv->mutex);
3532
3533         iwl_rfkill_set_hw_state(priv);
3534
3535         if (ret)
3536                 goto out_release_irq;
3537
3538         IWL_DEBUG_INFO(priv, "Start UP work.\n");
3539
3540         /* Wait for START_ALIVE from ucode. Otherwise callbacks from
3541          * mac80211 will not be run successfully. */
3542         ret = wait_event_interruptible_timeout(priv->wait_command_queue,
3543                         test_bit(STATUS_READY, &priv->status),
3544                         UCODE_READY_TIMEOUT);
3545         if (!ret) {
3546                 if (!test_bit(STATUS_READY, &priv->status)) {
3547                         IWL_ERR(priv,
3548                                 "Wait for START_ALIVE timeout after %dms.\n",
3549                                 jiffies_to_msecs(UCODE_READY_TIMEOUT));
3550                         ret = -ETIMEDOUT;
3551                         goto out_release_irq;
3552                 }
3553         }
3554
3555         /* ucode is running and will send rfkill notifications,
3556          * no need to poll the killswitch state anymore */
3557         cancel_delayed_work(&priv->rfkill_poll);
3558
3559         priv->is_open = 1;
3560         IWL_DEBUG_MAC80211(priv, "leave\n");
3561         return 0;
3562
3563 out_release_irq:
3564         priv->is_open = 0;
3565         IWL_DEBUG_MAC80211(priv, "leave - failed\n");
3566         return ret;
3567 }
3568
3569 static void iwl3945_mac_stop(struct ieee80211_hw *hw)
3570 {
3571         struct iwl_priv *priv = hw->priv;
3572
3573         IWL_DEBUG_MAC80211(priv, "enter\n");
3574
3575         if (!priv->is_open) {
3576                 IWL_DEBUG_MAC80211(priv, "leave - skip\n");
3577                 return;
3578         }
3579
3580         priv->is_open = 0;
3581
3582         if (iwl_is_ready_rf(priv)) {
3583                 /* stop mac, cancel any scan request and clear
3584                  * RXON_FILTER_ASSOC_MSK BIT
3585                  */
3586                 mutex_lock(&priv->mutex);
3587                 iwl_scan_cancel_timeout(priv, 100);
3588                 mutex_unlock(&priv->mutex);
3589         }
3590
3591         iwl3945_down(priv);
3592
3593         flush_workqueue(priv->workqueue);
3594
3595         /* start polling the killswitch state again */
3596         queue_delayed_work(priv->workqueue, &priv->rfkill_poll,
3597                            round_jiffies_relative(2 * HZ));
3598
3599         IWL_DEBUG_MAC80211(priv, "leave\n");
3600 }
3601
3602 static int iwl3945_mac_tx(struct ieee80211_hw *hw, struct sk_buff *skb)
3603 {
3604         struct iwl_priv *priv = hw->priv;
3605
3606         IWL_DEBUG_MAC80211(priv, "enter\n");
3607
3608         IWL_DEBUG_TX(priv, "dev->xmit(%d bytes) at rate 0x%02x\n", skb->len,
3609                      ieee80211_get_tx_rate(hw, IEEE80211_SKB_CB(skb))->bitrate);
3610
3611         if (iwl3945_tx_skb(priv, skb))
3612                 dev_kfree_skb_any(skb);
3613
3614         IWL_DEBUG_MAC80211(priv, "leave\n");
3615         return NETDEV_TX_OK;
3616 }
3617
3618 static int iwl3945_mac_add_interface(struct ieee80211_hw *hw,
3619                                  struct ieee80211_if_init_conf *conf)
3620 {
3621         struct iwl_priv *priv = hw->priv;
3622         unsigned long flags;
3623
3624         IWL_DEBUG_MAC80211(priv, "enter: type %d\n", conf->type);
3625
3626         if (priv->vif) {
3627                 IWL_DEBUG_MAC80211(priv, "leave - vif != NULL\n");
3628                 return -EOPNOTSUPP;
3629         }
3630
3631         spin_lock_irqsave(&priv->lock, flags);
3632         priv->vif = conf->vif;
3633         priv->iw_mode = conf->type;
3634
3635         spin_unlock_irqrestore(&priv->lock, flags);
3636
3637         mutex_lock(&priv->mutex);
3638
3639         if (conf->mac_addr) {
3640                 IWL_DEBUG_MAC80211(priv, "Set: %pM\n", conf->mac_addr);
3641                 memcpy(priv->mac_addr, conf->mac_addr, ETH_ALEN);
3642         }
3643
3644         if (iwl_is_ready(priv))
3645                 iwl3945_set_mode(priv, conf->type);
3646
3647         mutex_unlock(&priv->mutex);
3648
3649         IWL_DEBUG_MAC80211(priv, "leave\n");
3650         return 0;
3651 }
3652
3653 /**
3654  * iwl3945_mac_config - mac80211 config callback
3655  *
3656  * We ignore conf->flags & IEEE80211_CONF_SHORT_SLOT_TIME since it seems to
3657  * be set inappropriately and the driver currently sets the hardware up to
3658  * use it whenever needed.
3659  */
3660 static int iwl3945_mac_config(struct ieee80211_hw *hw, u32 changed)
3661 {
3662         struct iwl_priv *priv = hw->priv;
3663         const struct iwl_channel_info *ch_info;
3664         struct ieee80211_conf *conf = &hw->conf;
3665         unsigned long flags;
3666         int ret = 0;
3667
3668         mutex_lock(&priv->mutex);
3669         IWL_DEBUG_MAC80211(priv, "enter to channel %d\n",
3670                                 conf->channel->hw_value);
3671
3672         if (!iwl_is_ready(priv)) {
3673                 IWL_DEBUG_MAC80211(priv, "leave - not ready\n");
3674                 ret = -EIO;
3675                 goto out;
3676         }
3677
3678         if (unlikely(!iwl3945_mod_params.disable_hw_scan &&
3679                      test_bit(STATUS_SCANNING, &priv->status))) {
3680                 IWL_DEBUG_MAC80211(priv, "leave - scanning\n");
3681                 set_bit(STATUS_CONF_PENDING, &priv->status);
3682                 mutex_unlock(&priv->mutex);
3683                 return 0;
3684         }
3685
3686         spin_lock_irqsave(&priv->lock, flags);
3687
3688         ch_info = iwl_get_channel_info(priv, conf->channel->band,
3689                                        conf->channel->hw_value);
3690         if (!is_channel_valid(ch_info)) {
3691                 IWL_DEBUG_SCAN(priv,
3692                                 "Channel %d [%d] is INVALID for this band.\n",
3693                                 conf->channel->hw_value, conf->channel->band);
3694                 IWL_DEBUG_MAC80211(priv, "leave - invalid channel\n");
3695                 spin_unlock_irqrestore(&priv->lock, flags);
3696                 ret = -EINVAL;
3697                 goto out;
3698         }
3699
3700         iwl_set_rxon_channel(priv, conf->channel);
3701
3702         iwl_set_flags_for_band(priv, conf->channel->band);
3703
3704         /* The list of supported rates and rate mask can be different
3705          * for each phymode; since the phymode may have changed, reset
3706          * the rate mask to what mac80211 lists */
3707         iwl_set_rate(priv);
3708
3709         spin_unlock_irqrestore(&priv->lock, flags);
3710
3711 #ifdef IEEE80211_CONF_CHANNEL_SWITCH
3712         if (conf->flags & IEEE80211_CONF_CHANNEL_SWITCH) {
3713                 iwl3945_hw_channel_switch(priv, conf->channel);
3714                 goto out;
3715         }
3716 #endif
3717
3718         if (changed & IEEE80211_CONF_CHANGE_RADIO_ENABLED) {
3719                 if (conf->radio_enabled &&
3720                     iwl_radio_kill_sw_enable_radio(priv)) {
3721                         IWL_DEBUG_MAC80211(priv, "leave - RF-KILL - "
3722                                                  "waiting for uCode\n");
3723                         goto out;
3724                 }
3725
3726                 if (!conf->radio_enabled) {
3727                         iwl_radio_kill_sw_disable_radio(priv);
3728                         IWL_DEBUG_MAC80211(priv, "leave - radio disabled\n");
3729                         goto out;
3730                 }
3731         }
3732
3733         if (iwl_is_rfkill(priv)) {
3734                 IWL_DEBUG_MAC80211(priv, "leave - RF kill\n");
3735                 ret = -EIO;
3736                 goto out;
3737         }
3738
3739         iwl_set_rate(priv);
3740
3741         if (memcmp(&priv->active_rxon,
3742                    &priv->staging_rxon, sizeof(priv->staging_rxon)))
3743                 iwl3945_commit_rxon(priv);
3744         else
3745                 IWL_DEBUG_INFO(priv, "Not re-sending same RXON configuration\n");
3746
3747         IWL_DEBUG_MAC80211(priv, "leave\n");
3748
3749 out:
3750         clear_bit(STATUS_CONF_PENDING, &priv->status);
3751         mutex_unlock(&priv->mutex);
3752         return ret;
3753 }
3754
3755 static void iwl3945_config_ap(struct iwl_priv *priv)
3756 {
3757         int rc = 0;
3758
3759         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
3760                 return;
3761
3762         /* The following should be done only at AP bring up */
3763         if (!(iwl_is_associated(priv))) {
3764
3765                 /* RXON - unassoc (to set timing command) */
3766                 priv->staging_rxon.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
3767                 iwl3945_commit_rxon(priv);
3768
3769                 /* RXON Timing */
3770                 memset(&priv->rxon_timing, 0, sizeof(struct iwl_rxon_time_cmd));
3771                 iwl3945_setup_rxon_timing(priv);
3772                 rc = iwl_send_cmd_pdu(priv, REPLY_RXON_TIMING,
3773                                       sizeof(priv->rxon_timing),
3774                                       &priv->rxon_timing);
3775                 if (rc)
3776                         IWL_WARN(priv, "REPLY_RXON_TIMING failed - "
3777                                         "Attempting to continue.\n");
3778
3779                 /* FIXME: what should be the assoc_id for AP? */
3780                 priv->staging_rxon.assoc_id = cpu_to_le16(priv->assoc_id);
3781                 if (priv->assoc_capability & WLAN_CAPABILITY_SHORT_PREAMBLE)
3782                         priv->staging_rxon.flags |=
3783                                 RXON_FLG_SHORT_PREAMBLE_MSK;
3784                 else
3785                         priv->staging_rxon.flags &=
3786                                 ~RXON_FLG_SHORT_PREAMBLE_MSK;
3787
3788                 if (priv->staging_rxon.flags & RXON_FLG_BAND_24G_MSK) {
3789                         if (priv->assoc_capability &
3790                                 WLAN_CAPABILITY_SHORT_SLOT_TIME)
3791                                 priv->staging_rxon.flags |=
3792                                         RXON_FLG_SHORT_SLOT_MSK;
3793                         else
3794                                 priv->staging_rxon.flags &=
3795                                         ~RXON_FLG_SHORT_SLOT_MSK;
3796
3797                         if (priv->iw_mode == NL80211_IFTYPE_ADHOC)
3798                                 priv->staging_rxon.flags &=
3799                                         ~RXON_FLG_SHORT_SLOT_MSK;
3800                 }
3801                 /* restore RXON assoc */
3802                 priv->staging_rxon.filter_flags |= RXON_FILTER_ASSOC_MSK;
3803                 iwl3945_commit_rxon(priv);
3804                 iwl3945_add_station(priv, iwl_bcast_addr, 0, 0);
3805         }
3806         iwl3945_send_beacon_cmd(priv);
3807
3808         /* FIXME - we need to add code here to detect a totally new
3809          * configuration, reset the AP, unassoc, rxon timing, assoc,
3810          * clear sta table, add BCAST sta... */
3811 }
3812
3813 static int iwl3945_mac_config_interface(struct ieee80211_hw *hw,
3814                                         struct ieee80211_vif *vif,
3815                                         struct ieee80211_if_conf *conf)
3816 {
3817         struct iwl_priv *priv = hw->priv;
3818         int rc;
3819
3820         if (conf == NULL)
3821                 return -EIO;
3822
3823         if (priv->vif != vif) {
3824                 IWL_DEBUG_MAC80211(priv, "leave - priv->vif != vif\n");
3825                 return 0;
3826         }
3827
3828         /* handle this temporarily here */
3829         if (priv->iw_mode == NL80211_IFTYPE_ADHOC &&
3830             conf->changed & IEEE80211_IFCC_BEACON) {
3831                 struct sk_buff *beacon = ieee80211_beacon_get(hw, vif);
3832                 if (!beacon)
3833                         return -ENOMEM;
3834                 mutex_lock(&priv->mutex);
3835                 rc = iwl_mac_beacon_update(hw, beacon);
3836                 mutex_unlock(&priv->mutex);
3837                 if (rc)
3838                         return rc;
3839         }
3840
3841         if (!iwl_is_alive(priv))
3842                 return -EAGAIN;
3843
3844         mutex_lock(&priv->mutex);
3845
3846         if (conf->bssid)
3847                 IWL_DEBUG_MAC80211(priv, "bssid: %pM\n", conf->bssid);
3848
3849 /*
3850  * very dubious code was here; the probe filtering flag is never set:
3851  *
3852         if (unlikely(test_bit(STATUS_SCANNING, &priv->status)) &&
3853             !(priv->hw->flags & IEEE80211_HW_NO_PROBE_FILTERING)) {
3854  */
3855
3856         if (priv->iw_mode == NL80211_IFTYPE_AP) {
3857                 if (!conf->bssid) {
3858                         conf->bssid = priv->mac_addr;
3859                         memcpy(priv->bssid, priv->mac_addr, ETH_ALEN);
3860                         IWL_DEBUG_MAC80211(priv, "bssid was set to: %pM\n",
3861                                            conf->bssid);
3862                 }
3863                 if (priv->ibss_beacon)
3864                         dev_kfree_skb(priv->ibss_beacon);
3865
3866                 priv->ibss_beacon = ieee80211_beacon_get(hw, vif);
3867         }
3868
3869         if (iwl_is_rfkill(priv))
3870                 goto done;
3871
3872         if (conf->bssid && !is_zero_ether_addr(conf->bssid) &&
3873             !is_multicast_ether_addr(conf->bssid)) {
3874                 /* If there is currently a HW scan going on in the background
3875                  * then we need to cancel it else the RXON below will fail. */
3876                 if (iwl_scan_cancel_timeout(priv, 100)) {
3877                         IWL_WARN(priv, "Aborted scan still in progress "
3878                                     "after 100ms\n");
3879                         IWL_DEBUG_MAC80211(priv, "leaving:scan abort failed\n");
3880                         mutex_unlock(&priv->mutex);
3881                         return -EAGAIN;
3882                 }
3883                 memcpy(priv->staging_rxon.bssid_addr, conf->bssid, ETH_ALEN);
3884
3885                 /* TODO: Audit driver for usage of these members and see
3886                  * if mac80211 deprecates them (priv->bssid looks like it
3887                  * shouldn't be there, but I haven't scanned the IBSS code
3888                  * to verify) - jpk */
3889                 memcpy(priv->bssid, conf->bssid, ETH_ALEN);
3890
3891                 if (priv->iw_mode == NL80211_IFTYPE_AP)
3892                         iwl3945_config_ap(priv);
3893                 else {
3894                         rc = iwl3945_commit_rxon(priv);
3895                         if ((priv->iw_mode == NL80211_IFTYPE_STATION) && rc)
3896                                 iwl3945_add_station(priv,
3897                                         priv->active_rxon.bssid_addr, 1, 0);
3898                 }
3899
3900         } else {
3901                 iwl_scan_cancel_timeout(priv, 100);
3902                 priv->staging_rxon.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
3903                 iwl3945_commit_rxon(priv);
3904         }
3905
3906  done:
3907         IWL_DEBUG_MAC80211(priv, "leave\n");
3908         mutex_unlock(&priv->mutex);
3909
3910         return 0;
3911 }
3912
3913 static void iwl3945_mac_remove_interface(struct ieee80211_hw *hw,
3914                                      struct ieee80211_if_init_conf *conf)
3915 {
3916         struct iwl_priv *priv = hw->priv;
3917
3918         IWL_DEBUG_MAC80211(priv, "enter\n");
3919
3920         mutex_lock(&priv->mutex);
3921
3922         if (iwl_is_ready_rf(priv)) {
3923                 iwl_scan_cancel_timeout(priv, 100);
3924                 priv->staging_rxon.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
3925                 iwl3945_commit_rxon(priv);
3926         }
3927         if (priv->vif == conf->vif) {
3928                 priv->vif = NULL;
3929                 memset(priv->bssid, 0, ETH_ALEN);
3930         }
3931         mutex_unlock(&priv->mutex);
3932
3933         IWL_DEBUG_MAC80211(priv, "leave\n");
3934 }
3935
3936 static int iwl3945_mac_set_key(struct ieee80211_hw *hw, enum set_key_cmd cmd,
3937                                struct ieee80211_vif *vif,
3938                                struct ieee80211_sta *sta,
3939                                struct ieee80211_key_conf *key)
3940 {
3941         struct iwl_priv *priv = hw->priv;
3942         const u8 *addr;
3943         int ret = 0;
3944         u8 sta_id = IWL_INVALID_STATION;
3945         u8 static_key;
3946
3947         IWL_DEBUG_MAC80211(priv, "enter\n");
3948
3949         if (iwl3945_mod_params.sw_crypto) {
3950                 IWL_DEBUG_MAC80211(priv, "leave - hwcrypto disabled\n");
3951                 return -EOPNOTSUPP;
3952         }
3953
3954         addr = sta ? sta->addr : iwl_bcast_addr;
3955         static_key = !iwl_is_associated(priv);
3956
3957         if (!static_key) {
3958                 sta_id = iwl3945_hw_find_station(priv, addr);
3959                 if (sta_id == IWL_INVALID_STATION) {
3960                         IWL_DEBUG_MAC80211(priv, "leave - %pM not in station map.\n",
3961                                             addr);
3962                         return -EINVAL;
3963                 }
3964         }
3965
3966         mutex_lock(&priv->mutex);
3967         iwl_scan_cancel_timeout(priv, 100);
3968         mutex_unlock(&priv->mutex);
3969
3970         switch (cmd) {
3971         case SET_KEY:
3972                 if (static_key)
3973                         ret = iwl3945_set_static_key(priv, key);
3974                 else
3975                         ret = iwl3945_set_dynamic_key(priv, key, sta_id);
3976                 IWL_DEBUG_MAC80211(priv, "enable hwcrypto key\n");
3977                 break;
3978         case DISABLE_KEY:
3979                 if (static_key)
3980                         ret = iwl3945_remove_static_key(priv);
3981                 else
3982                         ret = iwl3945_clear_sta_key_info(priv, sta_id);
3983                 IWL_DEBUG_MAC80211(priv, "disable hwcrypto key\n");
3984                 break;
3985         default:
3986                 ret = -EINVAL;
3987         }
3988
3989         IWL_DEBUG_MAC80211(priv, "leave\n");
3990
3991         return ret;
3992 }
3993
3994 static int iwl3945_mac_get_tx_stats(struct ieee80211_hw *hw,
3995                                 struct ieee80211_tx_queue_stats *stats)
3996 {
3997         struct iwl_priv *priv = hw->priv;
3998         int i, avail;
3999         struct iwl_tx_queue *txq;
4000         struct iwl_queue *q;
4001         unsigned long flags;
4002
4003         IWL_DEBUG_MAC80211(priv, "enter\n");
4004
4005         if (!iwl_is_ready_rf(priv)) {
4006                 IWL_DEBUG_MAC80211(priv, "leave - RF not ready\n");
4007                 return -EIO;
4008         }
4009
4010         spin_lock_irqsave(&priv->lock, flags);
4011
4012         for (i = 0; i < AC_NUM; i++) {
4013                 txq = &priv->txq[i];
4014                 q = &txq->q;
4015                 avail = iwl_queue_space(q);
4016
4017                 stats[i].len = q->n_window - avail;
4018                 stats[i].limit = q->n_window - q->high_mark;
4019                 stats[i].count = q->n_window;
4020
4021         }
4022         spin_unlock_irqrestore(&priv->lock, flags);
4023
4024         IWL_DEBUG_MAC80211(priv, "leave\n");
4025
4026         return 0;
4027 }
4028
4029 static void iwl3945_mac_reset_tsf(struct ieee80211_hw *hw)
4030 {
4031         struct iwl_priv *priv = hw->priv;
4032         unsigned long flags;
4033
4034         mutex_lock(&priv->mutex);
4035         IWL_DEBUG_MAC80211(priv, "enter\n");
4036
4037         iwl_reset_qos(priv);
4038
4039         spin_lock_irqsave(&priv->lock, flags);
4040         priv->assoc_id = 0;
4041         priv->assoc_capability = 0;
4042
4043         /* new association get rid of ibss beacon skb */
4044         if (priv->ibss_beacon)
4045                 dev_kfree_skb(priv->ibss_beacon);
4046
4047         priv->ibss_beacon = NULL;
4048
4049         priv->beacon_int = priv->hw->conf.beacon_int;
4050         priv->timestamp = 0;
4051         if ((priv->iw_mode == NL80211_IFTYPE_STATION))
4052                 priv->beacon_int = 0;
4053
4054         spin_unlock_irqrestore(&priv->lock, flags);
4055
4056         if (!iwl_is_ready_rf(priv)) {
4057                 IWL_DEBUG_MAC80211(priv, "leave - not ready\n");
4058                 mutex_unlock(&priv->mutex);
4059                 return;
4060         }
4061
4062         /* we are restarting association process
4063          * clear RXON_FILTER_ASSOC_MSK bit
4064         */
4065         if (priv->iw_mode != NL80211_IFTYPE_AP) {
4066                 iwl_scan_cancel_timeout(priv, 100);
4067                 priv->staging_rxon.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
4068                 iwl3945_commit_rxon(priv);
4069         }
4070
4071         /* Per mac80211.h: This is only used in IBSS mode... */
4072         if (priv->iw_mode != NL80211_IFTYPE_ADHOC) {
4073
4074                 IWL_DEBUG_MAC80211(priv, "leave - not in IBSS\n");
4075                 mutex_unlock(&priv->mutex);
4076                 return;
4077         }
4078
4079         iwl_set_rate(priv);
4080
4081         mutex_unlock(&priv->mutex);
4082
4083         IWL_DEBUG_MAC80211(priv, "leave\n");
4084
4085 }
4086
4087 /*****************************************************************************
4088  *
4089  * sysfs attributes
4090  *
4091  *****************************************************************************/
4092
4093 #ifdef CONFIG_IWLWIFI_DEBUG
4094
4095 /*
4096  * The following adds a new attribute to the sysfs representation
4097  * of this device driver (i.e. a new file in /sys/bus/pci/drivers/iwl/)
4098  * used for controlling the debug level.
4099  *
4100  * See the level definitions in iwl for details.
4101  */
4102 static ssize_t show_debug_level(struct device *d,
4103                                 struct device_attribute *attr, char *buf)
4104 {
4105         struct iwl_priv *priv = d->driver_data;
4106
4107         return sprintf(buf, "0x%08X\n", priv->debug_level);
4108 }
4109 static ssize_t store_debug_level(struct device *d,
4110                                 struct device_attribute *attr,
4111                                  const char *buf, size_t count)
4112 {
4113         struct iwl_priv *priv = d->driver_data;
4114         unsigned long val;
4115         int ret;
4116
4117         ret = strict_strtoul(buf, 0, &val);
4118         if (ret)
4119                 IWL_INFO(priv, "%s is not in hex or decimal form.\n", buf);
4120         else
4121                 priv->debug_level = val;
4122
4123         return strnlen(buf, count);
4124 }
4125
4126 static DEVICE_ATTR(debug_level, S_IWUSR | S_IRUGO,
4127                         show_debug_level, store_debug_level);
4128
4129 #endif /* CONFIG_IWLWIFI_DEBUG */
4130
4131 static ssize_t show_temperature(struct device *d,
4132                                 struct device_attribute *attr, char *buf)
4133 {
4134         struct iwl_priv *priv = (struct iwl_priv *)d->driver_data;
4135
4136         if (!iwl_is_alive(priv))
4137                 return -EAGAIN;
4138
4139         return sprintf(buf, "%d\n", iwl3945_hw_get_temperature(priv));
4140 }
4141
4142 static DEVICE_ATTR(temperature, S_IRUGO, show_temperature, NULL);
4143
4144 static ssize_t show_tx_power(struct device *d,
4145                              struct device_attribute *attr, char *buf)
4146 {
4147         struct iwl_priv *priv = (struct iwl_priv *)d->driver_data;
4148         return sprintf(buf, "%d\n", priv->tx_power_user_lmt);
4149 }
4150
4151 static ssize_t store_tx_power(struct device *d,
4152                               struct device_attribute *attr,
4153                               const char *buf, size_t count)
4154 {
4155         struct iwl_priv *priv = (struct iwl_priv *)d->driver_data;
4156         char *p = (char *)buf;
4157         u32 val;
4158
4159         val = simple_strtoul(p, &p, 10);
4160         if (p == buf)
4161                 IWL_INFO(priv, ": %s is not in decimal form.\n", buf);
4162         else
4163                 iwl3945_hw_reg_set_txpower(priv, val);
4164
4165         return count;
4166 }
4167
4168 static DEVICE_ATTR(tx_power, S_IWUSR | S_IRUGO, show_tx_power, store_tx_power);
4169
4170 static ssize_t show_flags(struct device *d,
4171                           struct device_attribute *attr, char *buf)
4172 {
4173         struct iwl_priv *priv = (struct iwl_priv *)d->driver_data;
4174
4175         return sprintf(buf, "0x%04X\n", priv->active_rxon.flags);
4176 }
4177
4178 static ssize_t store_flags(struct device *d,
4179                            struct device_attribute *attr,
4180                            const char *buf, size_t count)
4181 {
4182         struct iwl_priv *priv = (struct iwl_priv *)d->driver_data;
4183         u32 flags = simple_strtoul(buf, NULL, 0);
4184
4185         mutex_lock(&priv->mutex);
4186         if (le32_to_cpu(priv->staging_rxon.flags) != flags) {
4187                 /* Cancel any currently running scans... */
4188                 if (iwl_scan_cancel_timeout(priv, 100))
4189                         IWL_WARN(priv, "Could not cancel scan.\n");
4190                 else {
4191                         IWL_DEBUG_INFO(priv, "Committing rxon.flags = 0x%04X\n",
4192                                        flags);
4193                         priv->staging_rxon.flags = cpu_to_le32(flags);
4194                         iwl3945_commit_rxon(priv);
4195                 }
4196         }
4197         mutex_unlock(&priv->mutex);
4198
4199         return count;
4200 }
4201
4202 static DEVICE_ATTR(flags, S_IWUSR | S_IRUGO, show_flags, store_flags);
4203
4204 static ssize_t show_filter_flags(struct device *d,
4205                                  struct device_attribute *attr, char *buf)
4206 {
4207         struct iwl_priv *priv = (struct iwl_priv *)d->driver_data;
4208
4209         return sprintf(buf, "0x%04X\n",
4210                 le32_to_cpu(priv->active_rxon.filter_flags));
4211 }
4212
4213 static ssize_t store_filter_flags(struct device *d,
4214                                   struct device_attribute *attr,
4215                                   const char *buf, size_t count)
4216 {
4217         struct iwl_priv *priv = (struct iwl_priv *)d->driver_data;
4218         u32 filter_flags = simple_strtoul(buf, NULL, 0);
4219
4220         mutex_lock(&priv->mutex);
4221         if (le32_to_cpu(priv->staging_rxon.filter_flags) != filter_flags) {
4222                 /* Cancel any currently running scans... */
4223                 if (iwl_scan_cancel_timeout(priv, 100))
4224                         IWL_WARN(priv, "Could not cancel scan.\n");
4225                 else {
4226                         IWL_DEBUG_INFO(priv, "Committing rxon.filter_flags = "
4227                                        "0x%04X\n", filter_flags);
4228                         priv->staging_rxon.filter_flags =
4229                                 cpu_to_le32(filter_flags);
4230                         iwl3945_commit_rxon(priv);
4231                 }
4232         }
4233         mutex_unlock(&priv->mutex);
4234
4235         return count;
4236 }
4237
4238 static DEVICE_ATTR(filter_flags, S_IWUSR | S_IRUGO, show_filter_flags,
4239                    store_filter_flags);
4240
4241 #ifdef CONFIG_IWL3945_SPECTRUM_MEASUREMENT
4242
4243 static ssize_t show_measurement(struct device *d,
4244                                 struct device_attribute *attr, char *buf)
4245 {
4246         struct iwl_priv *priv = dev_get_drvdata(d);
4247         struct iwl_spectrum_notification measure_report;
4248         u32 size = sizeof(measure_report), len = 0, ofs = 0;
4249         u8 *data = (u8 *)&measure_report;
4250         unsigned long flags;
4251
4252         spin_lock_irqsave(&priv->lock, flags);
4253         if (!(priv->measurement_status & MEASUREMENT_READY)) {
4254                 spin_unlock_irqrestore(&priv->lock, flags);
4255                 return 0;
4256         }
4257         memcpy(&measure_report, &priv->measure_report, size);
4258         priv->measurement_status = 0;
4259         spin_unlock_irqrestore(&priv->lock, flags);
4260
4261         while (size && (PAGE_SIZE - len)) {
4262                 hex_dump_to_buffer(data + ofs, size, 16, 1, buf + len,
4263                                    PAGE_SIZE - len, 1);
4264                 len = strlen(buf);
4265                 if (PAGE_SIZE - len)
4266                         buf[len++] = '\n';
4267
4268                 ofs += 16;
4269                 size -= min(size, 16U);
4270         }
4271
4272         return len;
4273 }
4274
4275 static ssize_t store_measurement(struct device *d,
4276                                  struct device_attribute *attr,
4277                                  const char *buf, size_t count)
4278 {
4279         struct iwl_priv *priv = dev_get_drvdata(d);
4280         struct ieee80211_measurement_params params = {
4281                 .channel = le16_to_cpu(priv->active_rxon.channel),
4282                 .start_time = cpu_to_le64(priv->last_tsf),
4283                 .duration = cpu_to_le16(1),
4284         };
4285         u8 type = IWL_MEASURE_BASIC;
4286         u8 buffer[32];
4287         u8 channel;
4288
4289         if (count) {
4290                 char *p = buffer;
4291                 strncpy(buffer, buf, min(sizeof(buffer), count));
4292                 channel = simple_strtoul(p, NULL, 0);
4293                 if (channel)
4294                         params.channel = channel;
4295
4296                 p = buffer;
4297                 while (*p && *p != ' ')
4298                         p++;
4299                 if (*p)
4300                         type = simple_strtoul(p + 1, NULL, 0);
4301         }
4302
4303         IWL_DEBUG_INFO(priv, "Invoking measurement of type %d on "
4304                        "channel %d (for '%s')\n", type, params.channel, buf);
4305         iwl3945_get_measurement(priv, &params, type);
4306
4307         return count;
4308 }
4309
4310 static DEVICE_ATTR(measurement, S_IRUSR | S_IWUSR,
4311                    show_measurement, store_measurement);
4312 #endif /* CONFIG_IWL3945_SPECTRUM_MEASUREMENT */
4313
4314 static ssize_t store_retry_rate(struct device *d,
4315                                 struct device_attribute *attr,
4316                                 const char *buf, size_t count)
4317 {
4318         struct iwl_priv *priv = dev_get_drvdata(d);
4319
4320         priv->retry_rate = simple_strtoul(buf, NULL, 0);
4321         if (priv->retry_rate <= 0)
4322                 priv->retry_rate = 1;
4323
4324         return count;
4325 }
4326
4327 static ssize_t show_retry_rate(struct device *d,
4328                                struct device_attribute *attr, char *buf)
4329 {
4330         struct iwl_priv *priv = dev_get_drvdata(d);
4331         return sprintf(buf, "%d", priv->retry_rate);
4332 }
4333
4334 static DEVICE_ATTR(retry_rate, S_IWUSR | S_IRUSR, show_retry_rate,
4335                    store_retry_rate);
4336
4337
4338 static ssize_t store_power_level(struct device *d,
4339                                  struct device_attribute *attr,
4340                                  const char *buf, size_t count)
4341 {
4342         struct iwl_priv *priv = dev_get_drvdata(d);
4343         int ret;
4344         unsigned long mode;
4345
4346
4347         mutex_lock(&priv->mutex);
4348
4349         ret = strict_strtoul(buf, 10, &mode);
4350         if (ret)
4351                 goto out;
4352
4353         ret = iwl_power_set_user_mode(priv, mode);
4354         if (ret) {
4355                 IWL_DEBUG_MAC80211(priv, "failed setting power mode.\n");
4356                 goto out;
4357         }
4358         ret = count;
4359
4360  out:
4361         mutex_unlock(&priv->mutex);
4362         return ret;
4363 }
4364
4365 static ssize_t show_power_level(struct device *d,
4366                                 struct device_attribute *attr, char *buf)
4367 {
4368         struct iwl_priv *priv = dev_get_drvdata(d);
4369         int mode = priv->power_data.user_power_setting;
4370         int system = priv->power_data.system_power_setting;
4371         int level = priv->power_data.power_mode;
4372         char *p = buf;
4373
4374         switch (system) {
4375         case IWL_POWER_SYS_AUTO:
4376                 p += sprintf(p, "SYSTEM:auto");
4377                 break;
4378         case IWL_POWER_SYS_AC:
4379                 p += sprintf(p, "SYSTEM:ac");
4380                 break;
4381         case IWL_POWER_SYS_BATTERY:
4382                 p += sprintf(p, "SYSTEM:battery");
4383                 break;
4384         }
4385
4386         p += sprintf(p, "\tMODE:%s", (mode < IWL_POWER_AUTO) ?
4387                         "fixed" : "auto");
4388         p += sprintf(p, "\tINDEX:%d", level);
4389         p += sprintf(p, "\n");
4390         return p - buf + 1;
4391 }
4392
4393 static DEVICE_ATTR(power_level, S_IWUSR | S_IRUSR,
4394                    show_power_level, store_power_level);
4395
4396 #define MAX_WX_STRING 80
4397
4398 /* Values are in microsecond */
4399 static const s32 timeout_duration[] = {
4400         350000,
4401         250000,
4402         75000,
4403         37000,
4404         25000,
4405 };
4406 static const s32 period_duration[] = {
4407         400000,
4408         700000,
4409         1000000,
4410         1000000,
4411         1000000
4412 };
4413
4414 static ssize_t show_channels(struct device *d,
4415                              struct device_attribute *attr, char *buf)
4416 {
4417         /* all this shit doesn't belong into sysfs anyway */
4418         return 0;
4419 }
4420
4421 static DEVICE_ATTR(channels, S_IRUSR, show_channels, NULL);
4422
4423 static ssize_t show_statistics(struct device *d,
4424                                struct device_attribute *attr, char *buf)
4425 {
4426         struct iwl_priv *priv = dev_get_drvdata(d);
4427         u32 size = sizeof(struct iwl3945_notif_statistics);
4428         u32 len = 0, ofs = 0;
4429         u8 *data = (u8 *)&priv->statistics_39;
4430         int rc = 0;
4431
4432         if (!iwl_is_alive(priv))
4433                 return -EAGAIN;
4434
4435         mutex_lock(&priv->mutex);
4436         rc = iwl_send_statistics_request(priv, 0);
4437         mutex_unlock(&priv->mutex);
4438
4439         if (rc) {
4440                 len = sprintf(buf,
4441                               "Error sending statistics request: 0x%08X\n", rc);
4442                 return len;
4443         }
4444
4445         while (size && (PAGE_SIZE - len)) {
4446                 hex_dump_to_buffer(data + ofs, size, 16, 1, buf + len,
4447                                    PAGE_SIZE - len, 1);
4448                 len = strlen(buf);
4449                 if (PAGE_SIZE - len)
4450                         buf[len++] = '\n';
4451
4452                 ofs += 16;
4453                 size -= min(size, 16U);
4454         }
4455
4456         return len;
4457 }
4458
4459 static DEVICE_ATTR(statistics, S_IRUGO, show_statistics, NULL);
4460
4461 static ssize_t show_antenna(struct device *d,
4462                             struct device_attribute *attr, char *buf)
4463 {
4464         struct iwl_priv *priv = dev_get_drvdata(d);
4465
4466         if (!iwl_is_alive(priv))
4467                 return -EAGAIN;
4468
4469         return sprintf(buf, "%d\n", iwl3945_mod_params.antenna);
4470 }
4471
4472 static ssize_t store_antenna(struct device *d,
4473                              struct device_attribute *attr,
4474                              const char *buf, size_t count)
4475 {
4476         struct iwl_priv *priv __maybe_unused = dev_get_drvdata(d);
4477         int ant;
4478
4479         if (count == 0)
4480                 return 0;
4481
4482         if (sscanf(buf, "%1i", &ant) != 1) {
4483                 IWL_DEBUG_INFO(priv, "not in hex or decimal form.\n");
4484                 return count;
4485         }
4486
4487         if ((ant >= 0) && (ant <= 2)) {
4488                 IWL_DEBUG_INFO(priv, "Setting antenna select to %d.\n", ant);
4489                 iwl3945_mod_params.antenna = (enum iwl3945_antenna)ant;
4490         } else
4491                 IWL_DEBUG_INFO(priv, "Bad antenna select value %d.\n", ant);
4492
4493
4494         return count;
4495 }
4496
4497 static DEVICE_ATTR(antenna, S_IWUSR | S_IRUGO, show_antenna, store_antenna);
4498
4499 static ssize_t show_status(struct device *d,
4500                            struct device_attribute *attr, char *buf)
4501 {
4502         struct iwl_priv *priv = (struct iwl_priv *)d->driver_data;
4503         if (!iwl_is_alive(priv))
4504                 return -EAGAIN;
4505         return sprintf(buf, "0x%08x\n", (int)priv->status);
4506 }
4507
4508 static DEVICE_ATTR(status, S_IRUGO, show_status, NULL);
4509
4510 static ssize_t dump_error_log(struct device *d,
4511                               struct device_attribute *attr,
4512                               const char *buf, size_t count)
4513 {
4514         char *p = (char *)buf;
4515
4516         if (p[0] == '1')
4517                 iwl3945_dump_nic_error_log((struct iwl_priv *)d->driver_data);
4518
4519         return strnlen(buf, count);
4520 }
4521
4522 static DEVICE_ATTR(dump_errors, S_IWUSR, NULL, dump_error_log);
4523
4524 static ssize_t dump_event_log(struct device *d,
4525                               struct device_attribute *attr,
4526                               const char *buf, size_t count)
4527 {
4528         char *p = (char *)buf;
4529
4530         if (p[0] == '1')
4531                 iwl3945_dump_nic_event_log((struct iwl_priv *)d->driver_data);
4532
4533         return strnlen(buf, count);
4534 }
4535
4536 static DEVICE_ATTR(dump_events, S_IWUSR, NULL, dump_event_log);
4537
4538 /*****************************************************************************
4539  *
4540  * driver setup and tear down
4541  *
4542  *****************************************************************************/
4543
4544 static void iwl3945_setup_deferred_work(struct iwl_priv *priv)
4545 {
4546         priv->workqueue = create_singlethread_workqueue(DRV_NAME);
4547
4548         init_waitqueue_head(&priv->wait_command_queue);
4549
4550         INIT_WORK(&priv->up, iwl3945_bg_up);
4551         INIT_WORK(&priv->restart, iwl3945_bg_restart);
4552         INIT_WORK(&priv->rx_replenish, iwl3945_bg_rx_replenish);
4553         INIT_WORK(&priv->rf_kill, iwl_bg_rf_kill);
4554         INIT_WORK(&priv->beacon_update, iwl3945_bg_beacon_update);
4555         INIT_DELAYED_WORK(&priv->init_alive_start, iwl3945_bg_init_alive_start);
4556         INIT_DELAYED_WORK(&priv->alive_start, iwl3945_bg_alive_start);
4557         INIT_DELAYED_WORK(&priv->rfkill_poll, iwl3945_rfkill_poll);
4558         INIT_WORK(&priv->scan_completed, iwl_bg_scan_completed);
4559         INIT_WORK(&priv->request_scan, iwl3945_bg_request_scan);
4560         INIT_WORK(&priv->abort_scan, iwl_bg_abort_scan);
4561         INIT_DELAYED_WORK(&priv->scan_check, iwl_bg_scan_check);
4562
4563         iwl3945_hw_setup_deferred_work(priv);
4564
4565         tasklet_init(&priv->irq_tasklet, (void (*)(unsigned long))
4566                      iwl3945_irq_tasklet, (unsigned long)priv);
4567 }
4568
4569 static void iwl3945_cancel_deferred_work(struct iwl_priv *priv)
4570 {
4571         iwl3945_hw_cancel_deferred_work(priv);
4572
4573         cancel_delayed_work_sync(&priv->init_alive_start);
4574         cancel_delayed_work(&priv->scan_check);
4575         cancel_delayed_work(&priv->alive_start);
4576         cancel_work_sync(&priv->beacon_update);
4577 }
4578
4579 static struct attribute *iwl3945_sysfs_entries[] = {
4580         &dev_attr_antenna.attr,
4581         &dev_attr_channels.attr,
4582         &dev_attr_dump_errors.attr,
4583         &dev_attr_dump_events.attr,
4584         &dev_attr_flags.attr,
4585         &dev_attr_filter_flags.attr,
4586 #ifdef CONFIG_IWL3945_SPECTRUM_MEASUREMENT
4587         &dev_attr_measurement.attr,
4588 #endif
4589         &dev_attr_power_level.attr,
4590         &dev_attr_retry_rate.attr,
4591         &dev_attr_statistics.attr,
4592         &dev_attr_status.attr,
4593         &dev_attr_temperature.attr,
4594         &dev_attr_tx_power.attr,
4595 #ifdef CONFIG_IWLWIFI_DEBUG
4596         &dev_attr_debug_level.attr,
4597 #endif
4598         NULL
4599 };
4600
4601 static struct attribute_group iwl3945_attribute_group = {
4602         .name = NULL,           /* put in device directory */
4603         .attrs = iwl3945_sysfs_entries,
4604 };
4605
4606 static struct ieee80211_ops iwl3945_hw_ops = {
4607         .tx = iwl3945_mac_tx,
4608         .start = iwl3945_mac_start,
4609         .stop = iwl3945_mac_stop,
4610         .add_interface = iwl3945_mac_add_interface,
4611         .remove_interface = iwl3945_mac_remove_interface,
4612         .config = iwl3945_mac_config,
4613         .config_interface = iwl3945_mac_config_interface,
4614         .configure_filter = iwl_configure_filter,
4615         .set_key = iwl3945_mac_set_key,
4616         .get_tx_stats = iwl3945_mac_get_tx_stats,
4617         .conf_tx = iwl_mac_conf_tx,
4618         .reset_tsf = iwl3945_mac_reset_tsf,
4619         .bss_info_changed = iwl_bss_info_changed,
4620         .hw_scan = iwl_mac_hw_scan
4621 };
4622
4623 static int iwl3945_init_drv(struct iwl_priv *priv)
4624 {
4625         int ret;
4626         struct iwl3945_eeprom *eeprom = (struct iwl3945_eeprom *)priv->eeprom;
4627
4628         priv->retry_rate = 1;
4629         priv->ibss_beacon = NULL;
4630
4631         spin_lock_init(&priv->lock);
4632         spin_lock_init(&priv->power_data.lock);
4633         spin_lock_init(&priv->sta_lock);
4634         spin_lock_init(&priv->hcmd_lock);
4635
4636         INIT_LIST_HEAD(&priv->free_frames);
4637
4638         mutex_init(&priv->mutex);
4639
4640         /* Clear the driver's (not device's) station table */
4641         iwl3945_clear_stations_table(priv);
4642
4643         priv->data_retry_limit = -1;
4644         priv->ieee_channels = NULL;
4645         priv->ieee_rates = NULL;
4646         priv->band = IEEE80211_BAND_2GHZ;
4647
4648         priv->iw_mode = NL80211_IFTYPE_STATION;
4649
4650         iwl_reset_qos(priv);
4651
4652         priv->qos_data.qos_active = 0;
4653         priv->qos_data.qos_cap.val = 0;
4654
4655         priv->rates_mask = IWL_RATES_MASK;
4656         /* If power management is turned on, default to CAM mode */
4657         priv->power_mode = IWL_POWER_MODE_CAM;
4658         priv->tx_power_user_lmt = IWL_DEFAULT_TX_POWER;
4659
4660         if (eeprom->version < EEPROM_3945_EEPROM_VERSION) {
4661                 IWL_WARN(priv, "Unsupported EEPROM version: 0x%04X\n",
4662                          eeprom->version);
4663                 ret = -EINVAL;
4664                 goto err;
4665         }
4666         ret = iwl_init_channel_map(priv);
4667         if (ret) {
4668                 IWL_ERR(priv, "initializing regulatory failed: %d\n", ret);
4669                 goto err;
4670         }
4671
4672         /* Set up txpower settings in driver for all channels */
4673         if (iwl3945_txpower_set_from_eeprom(priv)) {
4674                 ret = -EIO;
4675                 goto err_free_channel_map;
4676         }
4677
4678         ret = iwlcore_init_geos(priv);
4679         if (ret) {
4680                 IWL_ERR(priv, "initializing geos failed: %d\n", ret);
4681                 goto err_free_channel_map;
4682         }
4683         iwl3945_init_hw_rates(priv, priv->ieee_rates);
4684
4685         return 0;
4686
4687 err_free_channel_map:
4688         iwl_free_channel_map(priv);
4689 err:
4690         return ret;
4691 }
4692
4693 static int iwl3945_setup_mac(struct iwl_priv *priv)
4694 {
4695         int ret;
4696         struct ieee80211_hw *hw = priv->hw;
4697
4698         hw->rate_control_algorithm = "iwl-3945-rs";
4699         hw->sta_data_size = sizeof(struct iwl3945_sta_priv);
4700
4701         /* Tell mac80211 our characteristics */
4702         hw->flags = IEEE80211_HW_SIGNAL_DBM |
4703                     IEEE80211_HW_NOISE_DBM |
4704                     IEEE80211_HW_SPECTRUM_MGMT;
4705
4706         hw->wiphy->interface_modes =
4707                 BIT(NL80211_IFTYPE_STATION) |
4708                 BIT(NL80211_IFTYPE_ADHOC);
4709
4710         hw->wiphy->custom_regulatory = true;
4711
4712         hw->wiphy->max_scan_ssids = 1; /* WILL FIX */
4713
4714         /* Default value; 4 EDCA QOS priorities */
4715         hw->queues = 4;
4716
4717         hw->conf.beacon_int = 100;
4718
4719         if (priv->bands[IEEE80211_BAND_2GHZ].n_channels)
4720                 priv->hw->wiphy->bands[IEEE80211_BAND_2GHZ] =
4721                         &priv->bands[IEEE80211_BAND_2GHZ];
4722
4723         if (priv->bands[IEEE80211_BAND_5GHZ].n_channels)
4724                 priv->hw->wiphy->bands[IEEE80211_BAND_5GHZ] =
4725                         &priv->bands[IEEE80211_BAND_5GHZ];
4726
4727         ret = ieee80211_register_hw(priv->hw);
4728         if (ret) {
4729                 IWL_ERR(priv, "Failed to register hw (error %d)\n", ret);
4730                 return ret;
4731         }
4732         priv->mac80211_registered = 1;
4733
4734         return 0;
4735 }
4736
4737 static int iwl3945_pci_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
4738 {
4739         int err = 0;
4740         struct iwl_priv *priv;
4741         struct ieee80211_hw *hw;
4742         struct iwl_cfg *cfg = (struct iwl_cfg *)(ent->driver_data);
4743         struct iwl3945_eeprom *eeprom;
4744         unsigned long flags;
4745
4746         /***********************
4747          * 1. Allocating HW data
4748          * ********************/
4749
4750         /* mac80211 allocates memory for this device instance, including
4751          *   space for this driver's private structure */
4752         hw = iwl_alloc_all(cfg, &iwl3945_hw_ops);
4753         if (hw == NULL) {
4754                 printk(KERN_ERR DRV_NAME "Can not allocate network device\n");
4755                 err = -ENOMEM;
4756                 goto out;
4757         }
4758         priv = hw->priv;
4759         SET_IEEE80211_DEV(hw, &pdev->dev);
4760
4761         if ((iwl3945_mod_params.num_of_queues > IWL39_MAX_NUM_QUEUES) ||
4762              (iwl3945_mod_params.num_of_queues < IWL_MIN_NUM_QUEUES)) {
4763                 IWL_ERR(priv,
4764                         "invalid queues_num, should be between %d and %d\n",
4765                         IWL_MIN_NUM_QUEUES, IWL39_MAX_NUM_QUEUES);
4766                 err = -EINVAL;
4767                 goto out_ieee80211_free_hw;
4768         }
4769
4770         /*
4771          * Disabling hardware scan means that mac80211 will perform scans
4772          * "the hard way", rather than using device's scan.
4773          */
4774         if (iwl3945_mod_params.disable_hw_scan) {
4775                 IWL_DEBUG_INFO(priv, "Disabling hw_scan\n");
4776                 iwl3945_hw_ops.hw_scan = NULL;
4777         }
4778
4779
4780         IWL_DEBUG_INFO(priv, "*** LOAD DRIVER ***\n");
4781         priv->cfg = cfg;
4782         priv->pci_dev = pdev;
4783
4784 #ifdef CONFIG_IWLWIFI_DEBUG
4785         priv->debug_level = iwl3945_mod_params.debug;
4786         atomic_set(&priv->restrict_refcnt, 0);
4787 #endif
4788
4789         /***************************
4790          * 2. Initializing PCI bus
4791          * *************************/
4792         if (pci_enable_device(pdev)) {
4793                 err = -ENODEV;
4794                 goto out_ieee80211_free_hw;
4795         }
4796
4797         pci_set_master(pdev);
4798
4799         err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
4800         if (!err)
4801                 err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
4802         if (err) {
4803                 IWL_WARN(priv, "No suitable DMA available.\n");
4804                 goto out_pci_disable_device;
4805         }
4806
4807         pci_set_drvdata(pdev, priv);
4808         err = pci_request_regions(pdev, DRV_NAME);
4809         if (err)
4810                 goto out_pci_disable_device;
4811
4812         /***********************
4813          * 3. Read REV Register
4814          * ********************/
4815         priv->hw_base = pci_iomap(pdev, 0, 0);
4816         if (!priv->hw_base) {
4817                 err = -ENODEV;
4818                 goto out_pci_release_regions;
4819         }
4820
4821         IWL_DEBUG_INFO(priv, "pci_resource_len = 0x%08llx\n",
4822                         (unsigned long long) pci_resource_len(pdev, 0));
4823         IWL_DEBUG_INFO(priv, "pci_resource_base = %p\n", priv->hw_base);
4824
4825         /* We disable the RETRY_TIMEOUT register (0x41) to keep
4826          * PCI Tx retries from interfering with C3 CPU state */
4827         pci_write_config_byte(pdev, 0x41, 0x00);
4828
4829         /* amp init */
4830         err = priv->cfg->ops->lib->apm_ops.init(priv);
4831         if (err < 0) {
4832                 IWL_DEBUG_INFO(priv, "Failed to init the card\n");
4833                 goto out_iounmap;
4834         }
4835
4836         /***********************
4837          * 4. Read EEPROM
4838          * ********************/
4839
4840         /* Read the EEPROM */
4841         err = iwl_eeprom_init(priv);
4842         if (err) {
4843                 IWL_ERR(priv, "Unable to init EEPROM\n");
4844                 goto out_iounmap;
4845         }
4846         /* MAC Address location in EEPROM same for 3945/4965 */
4847         eeprom = (struct iwl3945_eeprom *)priv->eeprom;
4848         memcpy(priv->mac_addr, eeprom->mac_address, ETH_ALEN);
4849         IWL_DEBUG_INFO(priv, "MAC address: %pM\n", priv->mac_addr);
4850         SET_IEEE80211_PERM_ADDR(priv->hw, priv->mac_addr);
4851
4852         /***********************
4853          * 5. Setup HW Constants
4854          * ********************/
4855         /* Device-specific setup */
4856         if (iwl3945_hw_set_hw_params(priv)) {
4857                 IWL_ERR(priv, "failed to set hw settings\n");
4858                 goto out_eeprom_free;
4859         }
4860
4861         /***********************
4862          * 6. Setup priv
4863          * ********************/
4864
4865         err = iwl3945_init_drv(priv);
4866         if (err) {
4867                 IWL_ERR(priv, "initializing driver failed\n");
4868                 goto out_unset_hw_params;
4869         }
4870
4871         IWL_INFO(priv, "Detected Intel Wireless WiFi Link %s\n",
4872                 priv->cfg->name);
4873
4874         /***********************************
4875          * 7. Initialize Module Parameters
4876          * **********************************/
4877
4878         /* Initialize module parameter values here */
4879         /* Disable radio (SW RF KILL) via parameter when loading driver */
4880         if (iwl3945_mod_params.disable) {
4881                 set_bit(STATUS_RF_KILL_SW, &priv->status);
4882                 IWL_DEBUG_INFO(priv, "Radio disabled.\n");
4883         }
4884
4885
4886         /***********************
4887          * 8. Setup Services
4888          * ********************/
4889
4890         spin_lock_irqsave(&priv->lock, flags);
4891         iwl_disable_interrupts(priv);
4892         spin_unlock_irqrestore(&priv->lock, flags);
4893
4894         pci_enable_msi(priv->pci_dev);
4895
4896         err = request_irq(priv->pci_dev->irq, iwl_isr, IRQF_SHARED,
4897                           DRV_NAME, priv);
4898         if (err) {
4899                 IWL_ERR(priv, "Error allocating IRQ %d\n", priv->pci_dev->irq);
4900                 goto out_disable_msi;
4901         }
4902
4903         err = sysfs_create_group(&pdev->dev.kobj, &iwl3945_attribute_group);
4904         if (err) {
4905                 IWL_ERR(priv, "failed to create sysfs device attributes\n");
4906                 goto out_release_irq;
4907         }
4908
4909         iwl_set_rxon_channel(priv,
4910                              &priv->bands[IEEE80211_BAND_2GHZ].channels[5]);
4911         iwl3945_setup_deferred_work(priv);
4912         iwl3945_setup_rx_handlers(priv);
4913
4914         /*********************************
4915          * 9. Setup and Register mac80211
4916          * *******************************/
4917
4918         iwl_enable_interrupts(priv);
4919
4920         err = iwl3945_setup_mac(priv);
4921         if (err)
4922                 goto  out_remove_sysfs;
4923
4924         err = iwl_rfkill_init(priv);
4925         if (err)
4926                 IWL_ERR(priv, "Unable to initialize RFKILL system. "
4927                                   "Ignoring error: %d\n", err);
4928         else
4929                 iwl_rfkill_set_hw_state(priv);
4930
4931         /* Start monitoring the killswitch */
4932         queue_delayed_work(priv->workqueue, &priv->rfkill_poll,
4933                            2 * HZ);
4934
4935         return 0;
4936
4937  out_remove_sysfs:
4938         destroy_workqueue(priv->workqueue);
4939         priv->workqueue = NULL;
4940         sysfs_remove_group(&pdev->dev.kobj, &iwl3945_attribute_group);
4941  out_release_irq:
4942         free_irq(priv->pci_dev->irq, priv);
4943  out_disable_msi:
4944         pci_disable_msi(priv->pci_dev);
4945         iwlcore_free_geos(priv);
4946         iwl_free_channel_map(priv);
4947  out_unset_hw_params:
4948         iwl3945_unset_hw_params(priv);
4949  out_eeprom_free:
4950         iwl_eeprom_free(priv);
4951  out_iounmap:
4952         pci_iounmap(pdev, priv->hw_base);
4953  out_pci_release_regions:
4954         pci_release_regions(pdev);
4955  out_pci_disable_device:
4956         pci_set_drvdata(pdev, NULL);
4957         pci_disable_device(pdev);
4958  out_ieee80211_free_hw:
4959         ieee80211_free_hw(priv->hw);
4960  out:
4961         return err;
4962 }
4963
4964 static void __devexit iwl3945_pci_remove(struct pci_dev *pdev)
4965 {
4966         struct iwl_priv *priv = pci_get_drvdata(pdev);
4967         unsigned long flags;
4968
4969         if (!priv)
4970                 return;
4971
4972         IWL_DEBUG_INFO(priv, "*** UNLOAD DRIVER ***\n");
4973
4974         set_bit(STATUS_EXIT_PENDING, &priv->status);
4975
4976         if (priv->mac80211_registered) {
4977                 ieee80211_unregister_hw(priv->hw);
4978                 priv->mac80211_registered = 0;
4979         } else {
4980                 iwl3945_down(priv);
4981         }
4982
4983         /* make sure we flush any pending irq or
4984          * tasklet for the driver
4985          */
4986         spin_lock_irqsave(&priv->lock, flags);
4987         iwl_disable_interrupts(priv);
4988         spin_unlock_irqrestore(&priv->lock, flags);
4989
4990         iwl_synchronize_irq(priv);
4991
4992         sysfs_remove_group(&pdev->dev.kobj, &iwl3945_attribute_group);
4993
4994         iwl_rfkill_unregister(priv);
4995         cancel_delayed_work(&priv->rfkill_poll);
4996
4997         iwl3945_dealloc_ucode_pci(priv);
4998
4999         if (priv->rxq.bd)
5000                 iwl_rx_queue_free(priv, &priv->rxq);
5001         iwl3945_hw_txq_ctx_free(priv);
5002
5003         iwl3945_unset_hw_params(priv);
5004         iwl3945_clear_stations_table(priv);
5005
5006         /*netif_stop_queue(dev); */
5007         flush_workqueue(priv->workqueue);
5008
5009         /* ieee80211_unregister_hw calls iwl3945_mac_stop, which flushes
5010          * priv->workqueue... so we can't take down the workqueue
5011          * until now... */
5012         destroy_workqueue(priv->workqueue);
5013         priv->workqueue = NULL;
5014
5015         free_irq(pdev->irq, priv);
5016         pci_disable_msi(pdev);
5017
5018         pci_iounmap(pdev, priv->hw_base);
5019         pci_release_regions(pdev);
5020         pci_disable_device(pdev);
5021         pci_set_drvdata(pdev, NULL);
5022
5023         iwl_free_channel_map(priv);
5024         iwlcore_free_geos(priv);
5025         kfree(priv->scan);
5026         if (priv->ibss_beacon)
5027                 dev_kfree_skb(priv->ibss_beacon);
5028
5029         ieee80211_free_hw(priv->hw);
5030 }
5031
5032
5033 /*****************************************************************************
5034  *
5035  * driver and module entry point
5036  *
5037  *****************************************************************************/
5038
5039 static struct pci_driver iwl3945_driver = {
5040         .name = DRV_NAME,
5041         .id_table = iwl3945_hw_card_ids,
5042         .probe = iwl3945_pci_probe,
5043         .remove = __devexit_p(iwl3945_pci_remove),
5044 #ifdef CONFIG_PM
5045         .suspend = iwl_pci_suspend,
5046         .resume = iwl_pci_resume,
5047 #endif
5048 };
5049
5050 static int __init iwl3945_init(void)
5051 {
5052
5053         int ret;
5054         printk(KERN_INFO DRV_NAME ": " DRV_DESCRIPTION ", " DRV_VERSION "\n");
5055         printk(KERN_INFO DRV_NAME ": " DRV_COPYRIGHT "\n");
5056
5057         ret = iwl3945_rate_control_register();
5058         if (ret) {
5059                 printk(KERN_ERR DRV_NAME
5060                        "Unable to register rate control algorithm: %d\n", ret);
5061                 return ret;
5062         }
5063
5064         ret = pci_register_driver(&iwl3945_driver);
5065         if (ret) {
5066                 printk(KERN_ERR DRV_NAME "Unable to initialize PCI module\n");
5067                 goto error_register;
5068         }
5069
5070         return ret;
5071
5072 error_register:
5073         iwl3945_rate_control_unregister();
5074         return ret;
5075 }
5076
5077 static void __exit iwl3945_exit(void)
5078 {
5079         pci_unregister_driver(&iwl3945_driver);
5080         iwl3945_rate_control_unregister();
5081 }
5082
5083 MODULE_FIRMWARE(IWL3945_MODULE_FIRMWARE(IWL3945_UCODE_API_MAX));
5084
5085 module_param_named(antenna, iwl3945_mod_params.antenna, int, 0444);
5086 MODULE_PARM_DESC(antenna, "select antenna (1=Main, 2=Aux, default 0 [both])");
5087 module_param_named(disable, iwl3945_mod_params.disable, int, 0444);
5088 MODULE_PARM_DESC(disable, "manually disable the radio (default 0 [radio on])");
5089 module_param_named(swcrypto, iwl3945_mod_params.sw_crypto, int, 0444);
5090 MODULE_PARM_DESC(swcrypto,
5091                  "using software crypto (default 1 [software])\n");
5092 module_param_named(debug, iwl3945_mod_params.debug, uint, 0444);
5093 MODULE_PARM_DESC(debug, "debug output mask");
5094 module_param_named(disable_hw_scan, iwl3945_mod_params.disable_hw_scan, int, 0444);
5095 MODULE_PARM_DESC(disable_hw_scan, "disable hardware scanning (default 0)");
5096
5097 module_param_named(queues_num, iwl3945_mod_params.num_of_queues, int, 0444);
5098 MODULE_PARM_DESC(queues_num, "number of hw queues.");
5099
5100 module_param_named(fw_restart3945, iwl3945_mod_params.restart_fw, int, 0444);
5101 MODULE_PARM_DESC(fw_restart3945, "restart firmware in case of error");
5102
5103 module_exit(iwl3945_exit);
5104 module_init(iwl3945_init);