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