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