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