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