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