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