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