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