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