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