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