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