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