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