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