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