OSDN Git Service

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