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