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