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