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