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