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