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