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