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