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