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