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