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