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