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