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