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