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