d4500b5e0175380a7421c169e8795f62c34fdbed
[safe/jmp/linux-2.6] / drivers / net / wireless / iwlwifi / iwl-agn.c
1 /******************************************************************************
2  *
3  * Copyright(c) 2003 - 2010 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  *  Intel Linux Wireless <ilw@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/init.h>
33 #include <linux/pci.h>
34 #include <linux/dma-mapping.h>
35 #include <linux/delay.h>
36 #include <linux/sched.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 #define DRV_NAME        "iwlagn"
49
50 #include "iwl-eeprom.h"
51 #include "iwl-dev.h"
52 #include "iwl-core.h"
53 #include "iwl-io.h"
54 #include "iwl-helpers.h"
55 #include "iwl-sta.h"
56 #include "iwl-calib.h"
57
58
59 /******************************************************************************
60  *
61  * module boiler plate
62  *
63  ******************************************************************************/
64
65 /*
66  * module name, copyright, version, etc.
67  */
68 #define DRV_DESCRIPTION "Intel(R) Wireless WiFi Link AGN driver for Linux"
69
70 #ifdef CONFIG_IWLWIFI_DEBUG
71 #define VD "d"
72 #else
73 #define VD
74 #endif
75
76 #ifdef CONFIG_IWLWIFI_SPECTRUM_MEASUREMENT
77 #define VS "s"
78 #else
79 #define VS
80 #endif
81
82 #define DRV_VERSION     IWLWIFI_VERSION VD VS
83
84
85 MODULE_DESCRIPTION(DRV_DESCRIPTION);
86 MODULE_VERSION(DRV_VERSION);
87 MODULE_AUTHOR(DRV_COPYRIGHT " " DRV_AUTHOR);
88 MODULE_LICENSE("GPL");
89 MODULE_ALIAS("iwl4965");
90
91 /*************** STATION TABLE MANAGEMENT ****
92  * mac80211 should be examined to determine if sta_info is duplicating
93  * the functionality provided here
94  */
95
96 /**************************************************************/
97
98 /**
99  * iwl_commit_rxon - commit staging_rxon to hardware
100  *
101  * The RXON command in staging_rxon is committed to the hardware and
102  * the active_rxon structure is updated with the new data.  This
103  * function correctly transitions out of the RXON_ASSOC_MSK state if
104  * a HW tune is required based on the RXON structure changes.
105  */
106 int iwl_commit_rxon(struct iwl_priv *priv)
107 {
108         /* cast away the const for active_rxon in this function */
109         struct iwl_rxon_cmd *active_rxon = (void *)&priv->active_rxon;
110         int ret;
111         bool new_assoc =
112                 !!(priv->staging_rxon.filter_flags & RXON_FILTER_ASSOC_MSK);
113
114         if (!iwl_is_alive(priv))
115                 return -EBUSY;
116
117         /* always get timestamp with Rx frame */
118         priv->staging_rxon.flags |= RXON_FLG_TSF2HOST_MSK;
119
120         ret = iwl_check_rxon_cmd(priv);
121         if (ret) {
122                 IWL_ERR(priv, "Invalid RXON configuration.  Not committing.\n");
123                 return -EINVAL;
124         }
125
126         /*
127          * receive commit_rxon request
128          * abort any previous channel switch if still in process
129          */
130         if (priv->switch_rxon.switch_in_progress &&
131             (priv->switch_rxon.channel != priv->staging_rxon.channel)) {
132                 IWL_DEBUG_11H(priv, "abort channel switch on %d\n",
133                       le16_to_cpu(priv->switch_rxon.channel));
134                 priv->switch_rxon.switch_in_progress = false;
135         }
136
137         /* If we don't need to send a full RXON, we can use
138          * iwl_rxon_assoc_cmd which is used to reconfigure filter
139          * and other flags for the current radio configuration. */
140         if (!iwl_full_rxon_required(priv)) {
141                 ret = iwl_send_rxon_assoc(priv);
142                 if (ret) {
143                         IWL_ERR(priv, "Error setting RXON_ASSOC (%d)\n", ret);
144                         return ret;
145                 }
146
147                 memcpy(active_rxon, &priv->staging_rxon, sizeof(*active_rxon));
148                 iwl_print_rx_config_cmd(priv);
149                 return 0;
150         }
151
152         /* station table will be cleared */
153         priv->assoc_station_added = 0;
154
155         /* If we are currently associated and the new config requires
156          * an RXON_ASSOC and the new config wants the associated mask enabled,
157          * we must clear the associated from the active configuration
158          * before we apply the new config */
159         if (iwl_is_associated(priv) && new_assoc) {
160                 IWL_DEBUG_INFO(priv, "Toggling associated bit on current RXON\n");
161                 active_rxon->filter_flags &= ~RXON_FILTER_ASSOC_MSK;
162
163                 ret = iwl_send_cmd_pdu(priv, REPLY_RXON,
164                                       sizeof(struct iwl_rxon_cmd),
165                                       &priv->active_rxon);
166
167                 /* If the mask clearing failed then we set
168                  * active_rxon back to what it was previously */
169                 if (ret) {
170                         active_rxon->filter_flags |= RXON_FILTER_ASSOC_MSK;
171                         IWL_ERR(priv, "Error clearing ASSOC_MSK (%d)\n", ret);
172                         return ret;
173                 }
174         }
175
176         IWL_DEBUG_INFO(priv, "Sending RXON\n"
177                        "* with%s RXON_FILTER_ASSOC_MSK\n"
178                        "* channel = %d\n"
179                        "* bssid = %pM\n",
180                        (new_assoc ? "" : "out"),
181                        le16_to_cpu(priv->staging_rxon.channel),
182                        priv->staging_rxon.bssid_addr);
183
184         iwl_set_rxon_hwcrypto(priv, !priv->cfg->mod_params->sw_crypto);
185
186         /* Apply the new configuration
187          * RXON unassoc clears the station table in uCode, send it before
188          * we add the bcast station. If assoc bit is set, we will send RXON
189          * after having added the bcast and bssid station.
190          */
191         if (!new_assoc) {
192                 ret = iwl_send_cmd_pdu(priv, REPLY_RXON,
193                               sizeof(struct iwl_rxon_cmd), &priv->staging_rxon);
194                 if (ret) {
195                         IWL_ERR(priv, "Error setting new RXON (%d)\n", ret);
196                         return ret;
197                 }
198                 memcpy(active_rxon, &priv->staging_rxon, sizeof(*active_rxon));
199         }
200
201         iwl_clear_stations_table(priv);
202
203         priv->start_calib = 0;
204
205         /* Add the broadcast address so we can send broadcast frames */
206         priv->cfg->ops->lib->add_bcast_station(priv);
207
208
209         /* If we have set the ASSOC_MSK and we are in BSS mode then
210          * add the IWL_AP_ID to the station rate table */
211         if (new_assoc) {
212                 if (priv->iw_mode == NL80211_IFTYPE_STATION) {
213                         ret = iwl_rxon_add_station(priv,
214                                            priv->active_rxon.bssid_addr, 1);
215                         if (ret == IWL_INVALID_STATION) {
216                                 IWL_ERR(priv,
217                                         "Error adding AP address for TX.\n");
218                                 return -EIO;
219                         }
220                         priv->assoc_station_added = 1;
221                         if (priv->default_wep_key &&
222                             iwl_send_static_wepkey_cmd(priv, 0))
223                                 IWL_ERR(priv,
224                                         "Could not send WEP static key.\n");
225                 }
226
227                 /*
228                  * allow CTS-to-self if possible for new association.
229                  * this is relevant only for 5000 series and up,
230                  * but will not damage 4965
231                  */
232                 priv->staging_rxon.flags |= RXON_FLG_SELF_CTS_EN;
233
234                 /* Apply the new configuration
235                  * RXON assoc doesn't clear the station table in uCode,
236                  */
237                 ret = iwl_send_cmd_pdu(priv, REPLY_RXON,
238                               sizeof(struct iwl_rxon_cmd), &priv->staging_rxon);
239                 if (ret) {
240                         IWL_ERR(priv, "Error setting new RXON (%d)\n", ret);
241                         return ret;
242                 }
243                 memcpy(active_rxon, &priv->staging_rxon, sizeof(*active_rxon));
244         }
245         iwl_print_rx_config_cmd(priv);
246
247         iwl_init_sensitivity(priv);
248
249         /* If we issue a new RXON command which required a tune then we must
250          * send a new TXPOWER command or we won't be able to Tx any frames */
251         ret = iwl_set_tx_power(priv, priv->tx_power_user_lmt, true);
252         if (ret) {
253                 IWL_ERR(priv, "Error sending TX power (%d)\n", ret);
254                 return ret;
255         }
256
257         return 0;
258 }
259
260 void iwl_update_chain_flags(struct iwl_priv *priv)
261 {
262
263         if (priv->cfg->ops->hcmd->set_rxon_chain)
264                 priv->cfg->ops->hcmd->set_rxon_chain(priv);
265         iwlcore_commit_rxon(priv);
266 }
267
268 static void iwl_clear_free_frames(struct iwl_priv *priv)
269 {
270         struct list_head *element;
271
272         IWL_DEBUG_INFO(priv, "%d frames on pre-allocated heap on clear.\n",
273                        priv->frames_count);
274
275         while (!list_empty(&priv->free_frames)) {
276                 element = priv->free_frames.next;
277                 list_del(element);
278                 kfree(list_entry(element, struct iwl_frame, list));
279                 priv->frames_count--;
280         }
281
282         if (priv->frames_count) {
283                 IWL_WARN(priv, "%d frames still in use.  Did we lose one?\n",
284                             priv->frames_count);
285                 priv->frames_count = 0;
286         }
287 }
288
289 static struct iwl_frame *iwl_get_free_frame(struct iwl_priv *priv)
290 {
291         struct iwl_frame *frame;
292         struct list_head *element;
293         if (list_empty(&priv->free_frames)) {
294                 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
295                 if (!frame) {
296                         IWL_ERR(priv, "Could not allocate frame!\n");
297                         return NULL;
298                 }
299
300                 priv->frames_count++;
301                 return frame;
302         }
303
304         element = priv->free_frames.next;
305         list_del(element);
306         return list_entry(element, struct iwl_frame, list);
307 }
308
309 static void iwl_free_frame(struct iwl_priv *priv, struct iwl_frame *frame)
310 {
311         memset(frame, 0, sizeof(*frame));
312         list_add(&frame->list, &priv->free_frames);
313 }
314
315 static u32 iwl_fill_beacon_frame(struct iwl_priv *priv,
316                                           struct ieee80211_hdr *hdr,
317                                           int left)
318 {
319         if (!iwl_is_associated(priv) || !priv->ibss_beacon ||
320             ((priv->iw_mode != NL80211_IFTYPE_ADHOC) &&
321              (priv->iw_mode != NL80211_IFTYPE_AP)))
322                 return 0;
323
324         if (priv->ibss_beacon->len > left)
325                 return 0;
326
327         memcpy(hdr, priv->ibss_beacon->data, priv->ibss_beacon->len);
328
329         return priv->ibss_beacon->len;
330 }
331
332 /* Parse the beacon frame to find the TIM element and set tim_idx & tim_size */
333 static void iwl_set_beacon_tim(struct iwl_priv *priv,
334                 struct iwl_tx_beacon_cmd *tx_beacon_cmd,
335                 u8 *beacon, u32 frame_size)
336 {
337         u16 tim_idx;
338         struct ieee80211_mgmt *mgmt = (struct ieee80211_mgmt *)beacon;
339
340         /*
341          * The index is relative to frame start but we start looking at the
342          * variable-length part of the beacon.
343          */
344         tim_idx = mgmt->u.beacon.variable - beacon;
345
346         /* Parse variable-length elements of beacon to find WLAN_EID_TIM */
347         while ((tim_idx < (frame_size - 2)) &&
348                         (beacon[tim_idx] != WLAN_EID_TIM))
349                 tim_idx += beacon[tim_idx+1] + 2;
350
351         /* If TIM field was found, set variables */
352         if ((tim_idx < (frame_size - 1)) && (beacon[tim_idx] == WLAN_EID_TIM)) {
353                 tx_beacon_cmd->tim_idx = cpu_to_le16(tim_idx);
354                 tx_beacon_cmd->tim_size = beacon[tim_idx+1];
355         } else
356                 IWL_WARN(priv, "Unable to find TIM Element in beacon\n");
357 }
358
359 static unsigned int iwl_hw_get_beacon_cmd(struct iwl_priv *priv,
360                                        struct iwl_frame *frame)
361 {
362         struct iwl_tx_beacon_cmd *tx_beacon_cmd;
363         u32 frame_size;
364         u32 rate_flags;
365         u32 rate;
366         /*
367          * We have to set up the TX command, the TX Beacon command, and the
368          * beacon contents.
369          */
370
371         /* Initialize memory */
372         tx_beacon_cmd = &frame->u.beacon;
373         memset(tx_beacon_cmd, 0, sizeof(*tx_beacon_cmd));
374
375         /* Set up TX beacon contents */
376         frame_size = iwl_fill_beacon_frame(priv, tx_beacon_cmd->frame,
377                                 sizeof(frame->u) - sizeof(*tx_beacon_cmd));
378         if (WARN_ON_ONCE(frame_size > MAX_MPDU_SIZE))
379                 return 0;
380
381         /* Set up TX command fields */
382         tx_beacon_cmd->tx.len = cpu_to_le16((u16)frame_size);
383         tx_beacon_cmd->tx.sta_id = priv->hw_params.bcast_sta_id;
384         tx_beacon_cmd->tx.stop_time.life_time = TX_CMD_LIFE_TIME_INFINITE;
385         tx_beacon_cmd->tx.tx_flags = TX_CMD_FLG_SEQ_CTL_MSK |
386                 TX_CMD_FLG_TSF_MSK | TX_CMD_FLG_STA_RATE_MSK;
387
388         /* Set up TX beacon command fields */
389         iwl_set_beacon_tim(priv, tx_beacon_cmd, (u8 *)tx_beacon_cmd->frame,
390                         frame_size);
391
392         /* Set up packet rate and flags */
393         rate = iwl_rate_get_lowest_plcp(priv);
394         priv->mgmt_tx_ant = iwl_toggle_tx_ant(priv, priv->mgmt_tx_ant);
395         rate_flags = iwl_ant_idx_to_flags(priv->mgmt_tx_ant);
396         if ((rate >= IWL_FIRST_CCK_RATE) && (rate <= IWL_LAST_CCK_RATE))
397                 rate_flags |= RATE_MCS_CCK_MSK;
398         tx_beacon_cmd->tx.rate_n_flags = iwl_hw_set_rate_n_flags(rate,
399                         rate_flags);
400
401         return sizeof(*tx_beacon_cmd) + frame_size;
402 }
403 static int iwl_send_beacon_cmd(struct iwl_priv *priv)
404 {
405         struct iwl_frame *frame;
406         unsigned int frame_size;
407         int rc;
408
409         frame = iwl_get_free_frame(priv);
410         if (!frame) {
411                 IWL_ERR(priv, "Could not obtain free frame buffer for beacon "
412                           "command.\n");
413                 return -ENOMEM;
414         }
415
416         frame_size = iwl_hw_get_beacon_cmd(priv, frame);
417         if (!frame_size) {
418                 IWL_ERR(priv, "Error configuring the beacon command\n");
419                 iwl_free_frame(priv, frame);
420                 return -EINVAL;
421         }
422
423         rc = iwl_send_cmd_pdu(priv, REPLY_TX_BEACON, frame_size,
424                               &frame->u.cmd[0]);
425
426         iwl_free_frame(priv, frame);
427
428         return rc;
429 }
430
431 static inline dma_addr_t iwl_tfd_tb_get_addr(struct iwl_tfd *tfd, u8 idx)
432 {
433         struct iwl_tfd_tb *tb = &tfd->tbs[idx];
434
435         dma_addr_t addr = get_unaligned_le32(&tb->lo);
436         if (sizeof(dma_addr_t) > sizeof(u32))
437                 addr |=
438                 ((dma_addr_t)(le16_to_cpu(tb->hi_n_len) & 0xF) << 16) << 16;
439
440         return addr;
441 }
442
443 static inline u16 iwl_tfd_tb_get_len(struct iwl_tfd *tfd, u8 idx)
444 {
445         struct iwl_tfd_tb *tb = &tfd->tbs[idx];
446
447         return le16_to_cpu(tb->hi_n_len) >> 4;
448 }
449
450 static inline void iwl_tfd_set_tb(struct iwl_tfd *tfd, u8 idx,
451                                   dma_addr_t addr, u16 len)
452 {
453         struct iwl_tfd_tb *tb = &tfd->tbs[idx];
454         u16 hi_n_len = len << 4;
455
456         put_unaligned_le32(addr, &tb->lo);
457         if (sizeof(dma_addr_t) > sizeof(u32))
458                 hi_n_len |= ((addr >> 16) >> 16) & 0xF;
459
460         tb->hi_n_len = cpu_to_le16(hi_n_len);
461
462         tfd->num_tbs = idx + 1;
463 }
464
465 static inline u8 iwl_tfd_get_num_tbs(struct iwl_tfd *tfd)
466 {
467         return tfd->num_tbs & 0x1f;
468 }
469
470 /**
471  * iwl_hw_txq_free_tfd - Free all chunks referenced by TFD [txq->q.read_ptr]
472  * @priv - driver private data
473  * @txq - tx queue
474  *
475  * Does NOT advance any TFD circular buffer read/write indexes
476  * Does NOT free the TFD itself (which is within circular buffer)
477  */
478 void iwl_hw_txq_free_tfd(struct iwl_priv *priv, struct iwl_tx_queue *txq)
479 {
480         struct iwl_tfd *tfd_tmp = (struct iwl_tfd *)txq->tfds;
481         struct iwl_tfd *tfd;
482         struct pci_dev *dev = priv->pci_dev;
483         int index = txq->q.read_ptr;
484         int i;
485         int num_tbs;
486
487         tfd = &tfd_tmp[index];
488
489         /* Sanity check on number of chunks */
490         num_tbs = iwl_tfd_get_num_tbs(tfd);
491
492         if (num_tbs >= IWL_NUM_OF_TBS) {
493                 IWL_ERR(priv, "Too many chunks: %i\n", num_tbs);
494                 /* @todo issue fatal error, it is quite serious situation */
495                 return;
496         }
497
498         /* Unmap tx_cmd */
499         if (num_tbs)
500                 pci_unmap_single(dev,
501                                 pci_unmap_addr(&txq->meta[index], mapping),
502                                 pci_unmap_len(&txq->meta[index], len),
503                                 PCI_DMA_BIDIRECTIONAL);
504
505         /* Unmap chunks, if any. */
506         for (i = 1; i < num_tbs; i++) {
507                 pci_unmap_single(dev, iwl_tfd_tb_get_addr(tfd, i),
508                                 iwl_tfd_tb_get_len(tfd, i), PCI_DMA_TODEVICE);
509
510                 if (txq->txb) {
511                         dev_kfree_skb(txq->txb[txq->q.read_ptr].skb[i - 1]);
512                         txq->txb[txq->q.read_ptr].skb[i - 1] = NULL;
513                 }
514         }
515 }
516
517 int iwl_hw_txq_attach_buf_to_tfd(struct iwl_priv *priv,
518                                  struct iwl_tx_queue *txq,
519                                  dma_addr_t addr, u16 len,
520                                  u8 reset, u8 pad)
521 {
522         struct iwl_queue *q;
523         struct iwl_tfd *tfd, *tfd_tmp;
524         u32 num_tbs;
525
526         q = &txq->q;
527         tfd_tmp = (struct iwl_tfd *)txq->tfds;
528         tfd = &tfd_tmp[q->write_ptr];
529
530         if (reset)
531                 memset(tfd, 0, sizeof(*tfd));
532
533         num_tbs = iwl_tfd_get_num_tbs(tfd);
534
535         /* Each TFD can point to a maximum 20 Tx buffers */
536         if (num_tbs >= IWL_NUM_OF_TBS) {
537                 IWL_ERR(priv, "Error can not send more than %d chunks\n",
538                           IWL_NUM_OF_TBS);
539                 return -EINVAL;
540         }
541
542         BUG_ON(addr & ~DMA_BIT_MASK(36));
543         if (unlikely(addr & ~IWL_TX_DMA_MASK))
544                 IWL_ERR(priv, "Unaligned address = %llx\n",
545                           (unsigned long long)addr);
546
547         iwl_tfd_set_tb(tfd, num_tbs, addr, len);
548
549         return 0;
550 }
551
552 /*
553  * Tell nic where to find circular buffer of Tx Frame Descriptors for
554  * given Tx queue, and enable the DMA channel used for that queue.
555  *
556  * 4965 supports up to 16 Tx queues in DRAM, mapped to up to 8 Tx DMA
557  * channels supported in hardware.
558  */
559 int iwl_hw_tx_queue_init(struct iwl_priv *priv,
560                          struct iwl_tx_queue *txq)
561 {
562         int txq_id = txq->q.id;
563
564         /* Circular buffer (TFD queue in DRAM) physical base address */
565         iwl_write_direct32(priv, FH_MEM_CBBC_QUEUE(txq_id),
566                              txq->q.dma_addr >> 8);
567
568         return 0;
569 }
570
571 /******************************************************************************
572  *
573  * Generic RX handler implementations
574  *
575  ******************************************************************************/
576 static void iwl_rx_reply_alive(struct iwl_priv *priv,
577                                 struct iwl_rx_mem_buffer *rxb)
578 {
579         struct iwl_rx_packet *pkt = rxb_addr(rxb);
580         struct iwl_alive_resp *palive;
581         struct delayed_work *pwork;
582
583         palive = &pkt->u.alive_frame;
584
585         IWL_DEBUG_INFO(priv, "Alive ucode status 0x%08X revision "
586                        "0x%01X 0x%01X\n",
587                        palive->is_valid, palive->ver_type,
588                        palive->ver_subtype);
589
590         if (palive->ver_subtype == INITIALIZE_SUBTYPE) {
591                 IWL_DEBUG_INFO(priv, "Initialization Alive received.\n");
592                 memcpy(&priv->card_alive_init,
593                        &pkt->u.alive_frame,
594                        sizeof(struct iwl_init_alive_resp));
595                 pwork = &priv->init_alive_start;
596         } else {
597                 IWL_DEBUG_INFO(priv, "Runtime Alive received.\n");
598                 memcpy(&priv->card_alive, &pkt->u.alive_frame,
599                        sizeof(struct iwl_alive_resp));
600                 pwork = &priv->alive_start;
601         }
602
603         /* We delay the ALIVE response by 5ms to
604          * give the HW RF Kill time to activate... */
605         if (palive->is_valid == UCODE_VALID_OK)
606                 queue_delayed_work(priv->workqueue, pwork,
607                                    msecs_to_jiffies(5));
608         else
609                 IWL_WARN(priv, "uCode did not respond OK.\n");
610 }
611
612 static void iwl_bg_beacon_update(struct work_struct *work)
613 {
614         struct iwl_priv *priv =
615                 container_of(work, struct iwl_priv, beacon_update);
616         struct sk_buff *beacon;
617
618         /* Pull updated AP beacon from mac80211. will fail if not in AP mode */
619         beacon = ieee80211_beacon_get(priv->hw, priv->vif);
620
621         if (!beacon) {
622                 IWL_ERR(priv, "update beacon failed\n");
623                 return;
624         }
625
626         mutex_lock(&priv->mutex);
627         /* new beacon skb is allocated every time; dispose previous.*/
628         if (priv->ibss_beacon)
629                 dev_kfree_skb(priv->ibss_beacon);
630
631         priv->ibss_beacon = beacon;
632         mutex_unlock(&priv->mutex);
633
634         iwl_send_beacon_cmd(priv);
635 }
636
637 /**
638  * iwl_bg_statistics_periodic - Timer callback to queue statistics
639  *
640  * This callback is provided in order to send a statistics request.
641  *
642  * This timer function is continually reset to execute within
643  * REG_RECALIB_PERIOD seconds since the last STATISTICS_NOTIFICATION
644  * was received.  We need to ensure we receive the statistics in order
645  * to update the temperature used for calibrating the TXPOWER.
646  */
647 static void iwl_bg_statistics_periodic(unsigned long data)
648 {
649         struct iwl_priv *priv = (struct iwl_priv *)data;
650
651         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
652                 return;
653
654         /* dont send host command if rf-kill is on */
655         if (!iwl_is_ready_rf(priv))
656                 return;
657
658         iwl_send_statistics_request(priv, CMD_ASYNC, false);
659 }
660
661
662 static void iwl_print_cont_event_trace(struct iwl_priv *priv, u32 base,
663                                         u32 start_idx, u32 num_events,
664                                         u32 mode)
665 {
666         u32 i;
667         u32 ptr;        /* SRAM byte address of log data */
668         u32 ev, time, data; /* event log data */
669         unsigned long reg_flags;
670
671         if (mode == 0)
672                 ptr = base + (4 * sizeof(u32)) + (start_idx * 2 * sizeof(u32));
673         else
674                 ptr = base + (4 * sizeof(u32)) + (start_idx * 3 * sizeof(u32));
675
676         /* Make sure device is powered up for SRAM reads */
677         spin_lock_irqsave(&priv->reg_lock, reg_flags);
678         if (iwl_grab_nic_access(priv)) {
679                 spin_unlock_irqrestore(&priv->reg_lock, reg_flags);
680                 return;
681         }
682
683         /* Set starting address; reads will auto-increment */
684         _iwl_write_direct32(priv, HBUS_TARG_MEM_RADDR, ptr);
685         rmb();
686
687         /*
688          * "time" is actually "data" for mode 0 (no timestamp).
689          * place event id # at far right for easier visual parsing.
690          */
691         for (i = 0; i < num_events; i++) {
692                 ev = _iwl_read_direct32(priv, HBUS_TARG_MEM_RDAT);
693                 time = _iwl_read_direct32(priv, HBUS_TARG_MEM_RDAT);
694                 if (mode == 0) {
695                         trace_iwlwifi_dev_ucode_cont_event(priv,
696                                                         0, time, ev);
697                 } else {
698                         data = _iwl_read_direct32(priv, HBUS_TARG_MEM_RDAT);
699                         trace_iwlwifi_dev_ucode_cont_event(priv,
700                                                 time, data, ev);
701                 }
702         }
703         /* Allow device to power down */
704         iwl_release_nic_access(priv);
705         spin_unlock_irqrestore(&priv->reg_lock, reg_flags);
706 }
707
708 static void iwl_continuous_event_trace(struct iwl_priv *priv)
709 {
710         u32 capacity;   /* event log capacity in # entries */
711         u32 base;       /* SRAM byte address of event log header */
712         u32 mode;       /* 0 - no timestamp, 1 - timestamp recorded */
713         u32 num_wraps;  /* # times uCode wrapped to top of log */
714         u32 next_entry; /* index of next entry to be written by uCode */
715
716         if (priv->ucode_type == UCODE_INIT)
717                 base = le32_to_cpu(priv->card_alive_init.error_event_table_ptr);
718         else
719                 base = le32_to_cpu(priv->card_alive.log_event_table_ptr);
720         if (priv->cfg->ops->lib->is_valid_rtc_data_addr(base)) {
721                 capacity = iwl_read_targ_mem(priv, base);
722                 num_wraps = iwl_read_targ_mem(priv, base + (2 * sizeof(u32)));
723                 mode = iwl_read_targ_mem(priv, base + (1 * sizeof(u32)));
724                 next_entry = iwl_read_targ_mem(priv, base + (3 * sizeof(u32)));
725         } else
726                 return;
727
728         if (num_wraps == priv->event_log.num_wraps) {
729                 iwl_print_cont_event_trace(priv,
730                                        base, priv->event_log.next_entry,
731                                        next_entry - priv->event_log.next_entry,
732                                        mode);
733                 priv->event_log.non_wraps_count++;
734         } else {
735                 if ((num_wraps - priv->event_log.num_wraps) > 1)
736                         priv->event_log.wraps_more_count++;
737                 else
738                         priv->event_log.wraps_once_count++;
739                 trace_iwlwifi_dev_ucode_wrap_event(priv,
740                                 num_wraps - priv->event_log.num_wraps,
741                                 next_entry, priv->event_log.next_entry);
742                 if (next_entry < priv->event_log.next_entry) {
743                         iwl_print_cont_event_trace(priv, base,
744                                priv->event_log.next_entry,
745                                capacity - priv->event_log.next_entry,
746                                mode);
747
748                         iwl_print_cont_event_trace(priv, base, 0,
749                                 next_entry, mode);
750                 } else {
751                         iwl_print_cont_event_trace(priv, base,
752                                next_entry, capacity - next_entry,
753                                mode);
754
755                         iwl_print_cont_event_trace(priv, base, 0,
756                                 next_entry, mode);
757                 }
758         }
759         priv->event_log.num_wraps = num_wraps;
760         priv->event_log.next_entry = next_entry;
761 }
762
763 /**
764  * iwl_bg_ucode_trace - Timer callback to log ucode event
765  *
766  * The timer is continually set to execute every
767  * UCODE_TRACE_PERIOD milliseconds after the last timer expired
768  * this function is to perform continuous uCode event logging operation
769  * if enabled
770  */
771 static void iwl_bg_ucode_trace(unsigned long data)
772 {
773         struct iwl_priv *priv = (struct iwl_priv *)data;
774
775         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
776                 return;
777
778         if (priv->event_log.ucode_trace) {
779                 iwl_continuous_event_trace(priv);
780                 /* Reschedule the timer to occur in UCODE_TRACE_PERIOD */
781                 mod_timer(&priv->ucode_trace,
782                          jiffies + msecs_to_jiffies(UCODE_TRACE_PERIOD));
783         }
784 }
785
786 static void iwl_rx_beacon_notif(struct iwl_priv *priv,
787                                 struct iwl_rx_mem_buffer *rxb)
788 {
789 #ifdef CONFIG_IWLWIFI_DEBUG
790         struct iwl_rx_packet *pkt = rxb_addr(rxb);
791         struct iwl4965_beacon_notif *beacon =
792                 (struct iwl4965_beacon_notif *)pkt->u.raw;
793         u8 rate = iwl_hw_get_rate(beacon->beacon_notify_hdr.rate_n_flags);
794
795         IWL_DEBUG_RX(priv, "beacon status %x retries %d iss %d "
796                 "tsf %d %d rate %d\n",
797                 le32_to_cpu(beacon->beacon_notify_hdr.u.status) & TX_STATUS_MSK,
798                 beacon->beacon_notify_hdr.failure_frame,
799                 le32_to_cpu(beacon->ibss_mgr_status),
800                 le32_to_cpu(beacon->high_tsf),
801                 le32_to_cpu(beacon->low_tsf), rate);
802 #endif
803
804         if ((priv->iw_mode == NL80211_IFTYPE_AP) &&
805             (!test_bit(STATUS_EXIT_PENDING, &priv->status)))
806                 queue_work(priv->workqueue, &priv->beacon_update);
807 }
808
809 /* Handle notification from uCode that card's power state is changing
810  * due to software, hardware, or critical temperature RFKILL */
811 static void iwl_rx_card_state_notif(struct iwl_priv *priv,
812                                     struct iwl_rx_mem_buffer *rxb)
813 {
814         struct iwl_rx_packet *pkt = rxb_addr(rxb);
815         u32 flags = le32_to_cpu(pkt->u.card_state_notif.flags);
816         unsigned long status = priv->status;
817
818         IWL_DEBUG_RF_KILL(priv, "Card state received: HW:%s SW:%s CT:%s\n",
819                           (flags & HW_CARD_DISABLED) ? "Kill" : "On",
820                           (flags & SW_CARD_DISABLED) ? "Kill" : "On",
821                           (flags & CT_CARD_DISABLED) ?
822                           "Reached" : "Not reached");
823
824         if (flags & (SW_CARD_DISABLED | HW_CARD_DISABLED |
825                      CT_CARD_DISABLED)) {
826
827                 iwl_write32(priv, CSR_UCODE_DRV_GP1_SET,
828                             CSR_UCODE_DRV_GP1_BIT_CMD_BLOCKED);
829
830                 iwl_write_direct32(priv, HBUS_TARG_MBX_C,
831                                         HBUS_TARG_MBX_C_REG_BIT_CMD_BLOCKED);
832
833                 if (!(flags & RXON_CARD_DISABLED)) {
834                         iwl_write32(priv, CSR_UCODE_DRV_GP1_CLR,
835                                     CSR_UCODE_DRV_GP1_BIT_CMD_BLOCKED);
836                         iwl_write_direct32(priv, HBUS_TARG_MBX_C,
837                                         HBUS_TARG_MBX_C_REG_BIT_CMD_BLOCKED);
838                 }
839                 if (flags & CT_CARD_DISABLED)
840                         iwl_tt_enter_ct_kill(priv);
841         }
842         if (!(flags & CT_CARD_DISABLED))
843                 iwl_tt_exit_ct_kill(priv);
844
845         if (flags & HW_CARD_DISABLED)
846                 set_bit(STATUS_RF_KILL_HW, &priv->status);
847         else
848                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
849
850
851         if (!(flags & RXON_CARD_DISABLED))
852                 iwl_scan_cancel(priv);
853
854         if ((test_bit(STATUS_RF_KILL_HW, &status) !=
855              test_bit(STATUS_RF_KILL_HW, &priv->status)))
856                 wiphy_rfkill_set_hw_state(priv->hw->wiphy,
857                         test_bit(STATUS_RF_KILL_HW, &priv->status));
858         else
859                 wake_up_interruptible(&priv->wait_command_queue);
860 }
861
862 int iwl_set_pwr_src(struct iwl_priv *priv, enum iwl_pwr_src src)
863 {
864         if (src == IWL_PWR_SRC_VAUX) {
865                 if (pci_pme_capable(priv->pci_dev, PCI_D3cold))
866                         iwl_set_bits_mask_prph(priv, APMG_PS_CTRL_REG,
867                                                APMG_PS_CTRL_VAL_PWR_SRC_VAUX,
868                                                ~APMG_PS_CTRL_MSK_PWR_SRC);
869         } else {
870                 iwl_set_bits_mask_prph(priv, APMG_PS_CTRL_REG,
871                                        APMG_PS_CTRL_VAL_PWR_SRC_VMAIN,
872                                        ~APMG_PS_CTRL_MSK_PWR_SRC);
873         }
874
875         return 0;
876 }
877
878 /**
879  * iwl_setup_rx_handlers - Initialize Rx handler callbacks
880  *
881  * Setup the RX handlers for each of the reply types sent from the uCode
882  * to the host.
883  *
884  * This function chains into the hardware specific files for them to setup
885  * any hardware specific handlers as well.
886  */
887 static void iwl_setup_rx_handlers(struct iwl_priv *priv)
888 {
889         priv->rx_handlers[REPLY_ALIVE] = iwl_rx_reply_alive;
890         priv->rx_handlers[REPLY_ERROR] = iwl_rx_reply_error;
891         priv->rx_handlers[CHANNEL_SWITCH_NOTIFICATION] = iwl_rx_csa;
892         priv->rx_handlers[PM_SLEEP_NOTIFICATION] = iwl_rx_pm_sleep_notif;
893         priv->rx_handlers[PM_DEBUG_STATISTIC_NOTIFIC] =
894             iwl_rx_pm_debug_statistics_notif;
895         priv->rx_handlers[BEACON_NOTIFICATION] = iwl_rx_beacon_notif;
896
897         /*
898          * The same handler is used for both the REPLY to a discrete
899          * statistics request from the host as well as for the periodic
900          * statistics notifications (after received beacons) from the uCode.
901          */
902         priv->rx_handlers[REPLY_STATISTICS_CMD] = iwl_reply_statistics;
903         priv->rx_handlers[STATISTICS_NOTIFICATION] = iwl_rx_statistics;
904
905         iwl_setup_spectrum_handlers(priv);
906         iwl_setup_rx_scan_handlers(priv);
907
908         /* status change handler */
909         priv->rx_handlers[CARD_STATE_NOTIFICATION] = iwl_rx_card_state_notif;
910
911         priv->rx_handlers[MISSED_BEACONS_NOTIFICATION] =
912             iwl_rx_missed_beacon_notif;
913         /* Rx handlers */
914         priv->rx_handlers[REPLY_RX_PHY_CMD] = iwl_rx_reply_rx_phy;
915         priv->rx_handlers[REPLY_RX_MPDU_CMD] = iwl_rx_reply_rx;
916         /* block ack */
917         priv->rx_handlers[REPLY_COMPRESSED_BA] = iwl_rx_reply_compressed_ba;
918         /* Set up hardware specific Rx handlers */
919         priv->cfg->ops->lib->rx_handler_setup(priv);
920 }
921
922 /**
923  * iwl_rx_handle - Main entry function for receiving responses from uCode
924  *
925  * Uses the priv->rx_handlers callback function array to invoke
926  * the appropriate handlers, including command responses,
927  * frame-received notifications, and other notifications.
928  */
929 void iwl_rx_handle(struct iwl_priv *priv)
930 {
931         struct iwl_rx_mem_buffer *rxb;
932         struct iwl_rx_packet *pkt;
933         struct iwl_rx_queue *rxq = &priv->rxq;
934         u32 r, i;
935         int reclaim;
936         unsigned long flags;
937         u8 fill_rx = 0;
938         u32 count = 8;
939         int total_empty;
940
941         /* uCode's read index (stored in shared DRAM) indicates the last Rx
942          * buffer that the driver may process (last buffer filled by ucode). */
943         r = le16_to_cpu(rxq->rb_stts->closed_rb_num) &  0x0FFF;
944         i = rxq->read;
945
946         /* Rx interrupt, but nothing sent from uCode */
947         if (i == r)
948                 IWL_DEBUG_RX(priv, "r = %d, i = %d\n", r, i);
949
950         /* calculate total frames need to be restock after handling RX */
951         total_empty = r - rxq->write_actual;
952         if (total_empty < 0)
953                 total_empty += RX_QUEUE_SIZE;
954
955         if (total_empty > (RX_QUEUE_SIZE / 2))
956                 fill_rx = 1;
957
958         while (i != r) {
959                 rxb = rxq->queue[i];
960
961                 /* If an RXB doesn't have a Rx queue slot associated with it,
962                  * then a bug has been introduced in the queue refilling
963                  * routines -- catch it here */
964                 BUG_ON(rxb == NULL);
965
966                 rxq->queue[i] = NULL;
967
968                 pci_unmap_page(priv->pci_dev, rxb->page_dma,
969                                PAGE_SIZE << priv->hw_params.rx_page_order,
970                                PCI_DMA_FROMDEVICE);
971                 pkt = rxb_addr(rxb);
972
973                 trace_iwlwifi_dev_rx(priv, pkt,
974                         le32_to_cpu(pkt->len_n_flags) & FH_RSCSR_FRAME_SIZE_MSK);
975
976                 /* Reclaim a command buffer only if this packet is a response
977                  *   to a (driver-originated) command.
978                  * If the packet (e.g. Rx frame) originated from uCode,
979                  *   there is no command buffer to reclaim.
980                  * Ucode should set SEQ_RX_FRAME bit if ucode-originated,
981                  *   but apparently a few don't get set; catch them here. */
982                 reclaim = !(pkt->hdr.sequence & SEQ_RX_FRAME) &&
983                         (pkt->hdr.cmd != REPLY_RX_PHY_CMD) &&
984                         (pkt->hdr.cmd != REPLY_RX) &&
985                         (pkt->hdr.cmd != REPLY_RX_MPDU_CMD) &&
986                         (pkt->hdr.cmd != REPLY_COMPRESSED_BA) &&
987                         (pkt->hdr.cmd != STATISTICS_NOTIFICATION) &&
988                         (pkt->hdr.cmd != REPLY_TX);
989
990                 /* Based on type of command response or notification,
991                  *   handle those that need handling via function in
992                  *   rx_handlers table.  See iwl_setup_rx_handlers() */
993                 if (priv->rx_handlers[pkt->hdr.cmd]) {
994                         IWL_DEBUG_RX(priv, "r = %d, i = %d, %s, 0x%02x\n", r,
995                                 i, get_cmd_string(pkt->hdr.cmd), pkt->hdr.cmd);
996                         priv->isr_stats.rx_handlers[pkt->hdr.cmd]++;
997                         priv->rx_handlers[pkt->hdr.cmd] (priv, rxb);
998                 } else {
999                         /* No handling needed */
1000                         IWL_DEBUG_RX(priv,
1001                                 "r %d i %d No handler needed for %s, 0x%02x\n",
1002                                 r, i, get_cmd_string(pkt->hdr.cmd),
1003                                 pkt->hdr.cmd);
1004                 }
1005
1006                 /*
1007                  * XXX: After here, we should always check rxb->page
1008                  * against NULL before touching it or its virtual
1009                  * memory (pkt). Because some rx_handler might have
1010                  * already taken or freed the pages.
1011                  */
1012
1013                 if (reclaim) {
1014                         /* Invoke any callbacks, transfer the buffer to caller,
1015                          * and fire off the (possibly) blocking iwl_send_cmd()
1016                          * as we reclaim the driver command queue */
1017                         if (rxb->page)
1018                                 iwl_tx_cmd_complete(priv, rxb);
1019                         else
1020                                 IWL_WARN(priv, "Claim null rxb?\n");
1021                 }
1022
1023                 /* Reuse the page if possible. For notification packets and
1024                  * SKBs that fail to Rx correctly, add them back into the
1025                  * rx_free list for reuse later. */
1026                 spin_lock_irqsave(&rxq->lock, flags);
1027                 if (rxb->page != NULL) {
1028                         rxb->page_dma = pci_map_page(priv->pci_dev, rxb->page,
1029                                 0, PAGE_SIZE << priv->hw_params.rx_page_order,
1030                                 PCI_DMA_FROMDEVICE);
1031                         list_add_tail(&rxb->list, &rxq->rx_free);
1032                         rxq->free_count++;
1033                 } else
1034                         list_add_tail(&rxb->list, &rxq->rx_used);
1035
1036                 spin_unlock_irqrestore(&rxq->lock, flags);
1037
1038                 i = (i + 1) & RX_QUEUE_MASK;
1039                 /* If there are a lot of unused frames,
1040                  * restock the Rx queue so ucode wont assert. */
1041                 if (fill_rx) {
1042                         count++;
1043                         if (count >= 8) {
1044                                 rxq->read = i;
1045                                 iwl_rx_replenish_now(priv);
1046                                 count = 0;
1047                         }
1048                 }
1049         }
1050
1051         /* Backtrack one entry */
1052         rxq->read = i;
1053         if (fill_rx)
1054                 iwl_rx_replenish_now(priv);
1055         else
1056                 iwl_rx_queue_restock(priv);
1057 }
1058
1059 /* call this function to flush any scheduled tasklet */
1060 static inline void iwl_synchronize_irq(struct iwl_priv *priv)
1061 {
1062         /* wait to make sure we flush pending tasklet*/
1063         synchronize_irq(priv->pci_dev->irq);
1064         tasklet_kill(&priv->irq_tasklet);
1065 }
1066
1067 static void iwl_irq_tasklet_legacy(struct iwl_priv *priv)
1068 {
1069         u32 inta, handled = 0;
1070         u32 inta_fh;
1071         unsigned long flags;
1072         u32 i;
1073 #ifdef CONFIG_IWLWIFI_DEBUG
1074         u32 inta_mask;
1075 #endif
1076
1077         spin_lock_irqsave(&priv->lock, flags);
1078
1079         /* Ack/clear/reset pending uCode interrupts.
1080          * Note:  Some bits in CSR_INT are "OR" of bits in CSR_FH_INT_STATUS,
1081          *  and will clear only when CSR_FH_INT_STATUS gets cleared. */
1082         inta = iwl_read32(priv, CSR_INT);
1083         iwl_write32(priv, CSR_INT, inta);
1084
1085         /* Ack/clear/reset pending flow-handler (DMA) interrupts.
1086          * Any new interrupts that happen after this, either while we're
1087          * in this tasklet, or later, will show up in next ISR/tasklet. */
1088         inta_fh = iwl_read32(priv, CSR_FH_INT_STATUS);
1089         iwl_write32(priv, CSR_FH_INT_STATUS, inta_fh);
1090
1091 #ifdef CONFIG_IWLWIFI_DEBUG
1092         if (iwl_get_debug_level(priv) & IWL_DL_ISR) {
1093                 /* just for debug */
1094                 inta_mask = iwl_read32(priv, CSR_INT_MASK);
1095                 IWL_DEBUG_ISR(priv, "inta 0x%08x, enabled 0x%08x, fh 0x%08x\n",
1096                               inta, inta_mask, inta_fh);
1097         }
1098 #endif
1099
1100         spin_unlock_irqrestore(&priv->lock, flags);
1101
1102         /* Since CSR_INT and CSR_FH_INT_STATUS reads and clears are not
1103          * atomic, make sure that inta covers all the interrupts that
1104          * we've discovered, even if FH interrupt came in just after
1105          * reading CSR_INT. */
1106         if (inta_fh & CSR49_FH_INT_RX_MASK)
1107                 inta |= CSR_INT_BIT_FH_RX;
1108         if (inta_fh & CSR49_FH_INT_TX_MASK)
1109                 inta |= CSR_INT_BIT_FH_TX;
1110
1111         /* Now service all interrupt bits discovered above. */
1112         if (inta & CSR_INT_BIT_HW_ERR) {
1113                 IWL_ERR(priv, "Hardware error detected.  Restarting.\n");
1114
1115                 /* Tell the device to stop sending interrupts */
1116                 iwl_disable_interrupts(priv);
1117
1118                 priv->isr_stats.hw++;
1119                 iwl_irq_handle_error(priv);
1120
1121                 handled |= CSR_INT_BIT_HW_ERR;
1122
1123                 return;
1124         }
1125
1126 #ifdef CONFIG_IWLWIFI_DEBUG
1127         if (iwl_get_debug_level(priv) & (IWL_DL_ISR)) {
1128                 /* NIC fires this, but we don't use it, redundant with WAKEUP */
1129                 if (inta & CSR_INT_BIT_SCD) {
1130                         IWL_DEBUG_ISR(priv, "Scheduler finished to transmit "
1131                                       "the frame/frames.\n");
1132                         priv->isr_stats.sch++;
1133                 }
1134
1135                 /* Alive notification via Rx interrupt will do the real work */
1136                 if (inta & CSR_INT_BIT_ALIVE) {
1137                         IWL_DEBUG_ISR(priv, "Alive interrupt\n");
1138                         priv->isr_stats.alive++;
1139                 }
1140         }
1141 #endif
1142         /* Safely ignore these bits for debug checks below */
1143         inta &= ~(CSR_INT_BIT_SCD | CSR_INT_BIT_ALIVE);
1144
1145         /* HW RF KILL switch toggled */
1146         if (inta & CSR_INT_BIT_RF_KILL) {
1147                 int hw_rf_kill = 0;
1148                 if (!(iwl_read32(priv, CSR_GP_CNTRL) &
1149                                 CSR_GP_CNTRL_REG_FLAG_HW_RF_KILL_SW))
1150                         hw_rf_kill = 1;
1151
1152                 IWL_WARN(priv, "RF_KILL bit toggled to %s.\n",
1153                                 hw_rf_kill ? "disable radio" : "enable radio");
1154
1155                 priv->isr_stats.rfkill++;
1156
1157                 /* driver only loads ucode once setting the interface up.
1158                  * the driver allows loading the ucode even if the radio
1159                  * is killed. Hence update the killswitch state here. The
1160                  * rfkill handler will care about restarting if needed.
1161                  */
1162                 if (!test_bit(STATUS_ALIVE, &priv->status)) {
1163                         if (hw_rf_kill)
1164                                 set_bit(STATUS_RF_KILL_HW, &priv->status);
1165                         else
1166                                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
1167                         wiphy_rfkill_set_hw_state(priv->hw->wiphy, hw_rf_kill);
1168                 }
1169
1170                 handled |= CSR_INT_BIT_RF_KILL;
1171         }
1172
1173         /* Chip got too hot and stopped itself */
1174         if (inta & CSR_INT_BIT_CT_KILL) {
1175                 IWL_ERR(priv, "Microcode CT kill error detected.\n");
1176                 priv->isr_stats.ctkill++;
1177                 handled |= CSR_INT_BIT_CT_KILL;
1178         }
1179
1180         /* Error detected by uCode */
1181         if (inta & CSR_INT_BIT_SW_ERR) {
1182                 IWL_ERR(priv, "Microcode SW error detected. "
1183                         " Restarting 0x%X.\n", inta);
1184                 priv->isr_stats.sw++;
1185                 priv->isr_stats.sw_err = inta;
1186                 iwl_irq_handle_error(priv);
1187                 handled |= CSR_INT_BIT_SW_ERR;
1188         }
1189
1190         /*
1191          * uCode wakes up after power-down sleep.
1192          * Tell device about any new tx or host commands enqueued,
1193          * and about any Rx buffers made available while asleep.
1194          */
1195         if (inta & CSR_INT_BIT_WAKEUP) {
1196                 IWL_DEBUG_ISR(priv, "Wakeup interrupt\n");
1197                 iwl_rx_queue_update_write_ptr(priv, &priv->rxq);
1198                 for (i = 0; i < priv->hw_params.max_txq_num; i++)
1199                         iwl_txq_update_write_ptr(priv, &priv->txq[i]);
1200                 priv->isr_stats.wakeup++;
1201                 handled |= CSR_INT_BIT_WAKEUP;
1202         }
1203
1204         /* All uCode command responses, including Tx command responses,
1205          * Rx "responses" (frame-received notification), and other
1206          * notifications from uCode come through here*/
1207         if (inta & (CSR_INT_BIT_FH_RX | CSR_INT_BIT_SW_RX)) {
1208                 iwl_rx_handle(priv);
1209                 priv->isr_stats.rx++;
1210                 handled |= (CSR_INT_BIT_FH_RX | CSR_INT_BIT_SW_RX);
1211         }
1212
1213         /* This "Tx" DMA channel is used only for loading uCode */
1214         if (inta & CSR_INT_BIT_FH_TX) {
1215                 IWL_DEBUG_ISR(priv, "uCode load interrupt\n");
1216                 priv->isr_stats.tx++;
1217                 handled |= CSR_INT_BIT_FH_TX;
1218                 /* Wake up uCode load routine, now that load is complete */
1219                 priv->ucode_write_complete = 1;
1220                 wake_up_interruptible(&priv->wait_command_queue);
1221         }
1222
1223         if (inta & ~handled) {
1224                 IWL_ERR(priv, "Unhandled INTA bits 0x%08x\n", inta & ~handled);
1225                 priv->isr_stats.unhandled++;
1226         }
1227
1228         if (inta & ~(priv->inta_mask)) {
1229                 IWL_WARN(priv, "Disabled INTA bits 0x%08x were pending\n",
1230                          inta & ~priv->inta_mask);
1231                 IWL_WARN(priv, "   with FH_INT = 0x%08x\n", inta_fh);
1232         }
1233
1234         /* Re-enable all interrupts */
1235         /* only Re-enable if diabled by irq */
1236         if (test_bit(STATUS_INT_ENABLED, &priv->status))
1237                 iwl_enable_interrupts(priv);
1238
1239 #ifdef CONFIG_IWLWIFI_DEBUG
1240         if (iwl_get_debug_level(priv) & (IWL_DL_ISR)) {
1241                 inta = iwl_read32(priv, CSR_INT);
1242                 inta_mask = iwl_read32(priv, CSR_INT_MASK);
1243                 inta_fh = iwl_read32(priv, CSR_FH_INT_STATUS);
1244                 IWL_DEBUG_ISR(priv, "End inta 0x%08x, enabled 0x%08x, fh 0x%08x, "
1245                         "flags 0x%08lx\n", inta, inta_mask, inta_fh, flags);
1246         }
1247 #endif
1248 }
1249
1250 /* tasklet for iwlagn interrupt */
1251 static void iwl_irq_tasklet(struct iwl_priv *priv)
1252 {
1253         u32 inta = 0;
1254         u32 handled = 0;
1255         unsigned long flags;
1256         u32 i;
1257 #ifdef CONFIG_IWLWIFI_DEBUG
1258         u32 inta_mask;
1259 #endif
1260
1261         spin_lock_irqsave(&priv->lock, flags);
1262
1263         /* Ack/clear/reset pending uCode interrupts.
1264          * Note:  Some bits in CSR_INT are "OR" of bits in CSR_FH_INT_STATUS,
1265          */
1266         iwl_write32(priv, CSR_INT, priv->inta);
1267
1268         inta = priv->inta;
1269
1270 #ifdef CONFIG_IWLWIFI_DEBUG
1271         if (iwl_get_debug_level(priv) & IWL_DL_ISR) {
1272                 /* just for debug */
1273                 inta_mask = iwl_read32(priv, CSR_INT_MASK);
1274                 IWL_DEBUG_ISR(priv, "inta 0x%08x, enabled 0x%08x\n ",
1275                                 inta, inta_mask);
1276         }
1277 #endif
1278
1279         spin_unlock_irqrestore(&priv->lock, flags);
1280
1281         /* saved interrupt in inta variable now we can reset priv->inta */
1282         priv->inta = 0;
1283
1284         /* Now service all interrupt bits discovered above. */
1285         if (inta & CSR_INT_BIT_HW_ERR) {
1286                 IWL_ERR(priv, "Hardware error detected.  Restarting.\n");
1287
1288                 /* Tell the device to stop sending interrupts */
1289                 iwl_disable_interrupts(priv);
1290
1291                 priv->isr_stats.hw++;
1292                 iwl_irq_handle_error(priv);
1293
1294                 handled |= CSR_INT_BIT_HW_ERR;
1295
1296                 return;
1297         }
1298
1299 #ifdef CONFIG_IWLWIFI_DEBUG
1300         if (iwl_get_debug_level(priv) & (IWL_DL_ISR)) {
1301                 /* NIC fires this, but we don't use it, redundant with WAKEUP */
1302                 if (inta & CSR_INT_BIT_SCD) {
1303                         IWL_DEBUG_ISR(priv, "Scheduler finished to transmit "
1304                                       "the frame/frames.\n");
1305                         priv->isr_stats.sch++;
1306                 }
1307
1308                 /* Alive notification via Rx interrupt will do the real work */
1309                 if (inta & CSR_INT_BIT_ALIVE) {
1310                         IWL_DEBUG_ISR(priv, "Alive interrupt\n");
1311                         priv->isr_stats.alive++;
1312                 }
1313         }
1314 #endif
1315         /* Safely ignore these bits for debug checks below */
1316         inta &= ~(CSR_INT_BIT_SCD | CSR_INT_BIT_ALIVE);
1317
1318         /* HW RF KILL switch toggled */
1319         if (inta & CSR_INT_BIT_RF_KILL) {
1320                 int hw_rf_kill = 0;
1321                 if (!(iwl_read32(priv, CSR_GP_CNTRL) &
1322                                 CSR_GP_CNTRL_REG_FLAG_HW_RF_KILL_SW))
1323                         hw_rf_kill = 1;
1324
1325                 IWL_WARN(priv, "RF_KILL bit toggled to %s.\n",
1326                                 hw_rf_kill ? "disable radio" : "enable radio");
1327
1328                 priv->isr_stats.rfkill++;
1329
1330                 /* driver only loads ucode once setting the interface up.
1331                  * the driver allows loading the ucode even if the radio
1332                  * is killed. Hence update the killswitch state here. The
1333                  * rfkill handler will care about restarting if needed.
1334                  */
1335                 if (!test_bit(STATUS_ALIVE, &priv->status)) {
1336                         if (hw_rf_kill)
1337                                 set_bit(STATUS_RF_KILL_HW, &priv->status);
1338                         else
1339                                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
1340                         wiphy_rfkill_set_hw_state(priv->hw->wiphy, hw_rf_kill);
1341                 }
1342
1343                 handled |= CSR_INT_BIT_RF_KILL;
1344         }
1345
1346         /* Chip got too hot and stopped itself */
1347         if (inta & CSR_INT_BIT_CT_KILL) {
1348                 IWL_ERR(priv, "Microcode CT kill error detected.\n");
1349                 priv->isr_stats.ctkill++;
1350                 handled |= CSR_INT_BIT_CT_KILL;
1351         }
1352
1353         /* Error detected by uCode */
1354         if (inta & CSR_INT_BIT_SW_ERR) {
1355                 IWL_ERR(priv, "Microcode SW error detected. "
1356                         " Restarting 0x%X.\n", inta);
1357                 priv->isr_stats.sw++;
1358                 priv->isr_stats.sw_err = inta;
1359                 iwl_irq_handle_error(priv);
1360                 handled |= CSR_INT_BIT_SW_ERR;
1361         }
1362
1363         /* uCode wakes up after power-down sleep */
1364         if (inta & CSR_INT_BIT_WAKEUP) {
1365                 IWL_DEBUG_ISR(priv, "Wakeup interrupt\n");
1366                 iwl_rx_queue_update_write_ptr(priv, &priv->rxq);
1367                 for (i = 0; i < priv->hw_params.max_txq_num; i++)
1368                         iwl_txq_update_write_ptr(priv, &priv->txq[i]);
1369
1370                 priv->isr_stats.wakeup++;
1371
1372                 handled |= CSR_INT_BIT_WAKEUP;
1373         }
1374
1375         /* All uCode command responses, including Tx command responses,
1376          * Rx "responses" (frame-received notification), and other
1377          * notifications from uCode come through here*/
1378         if (inta & (CSR_INT_BIT_FH_RX | CSR_INT_BIT_SW_RX |
1379                         CSR_INT_BIT_RX_PERIODIC)) {
1380                 IWL_DEBUG_ISR(priv, "Rx interrupt\n");
1381                 if (inta & (CSR_INT_BIT_FH_RX | CSR_INT_BIT_SW_RX)) {
1382                         handled |= (CSR_INT_BIT_FH_RX | CSR_INT_BIT_SW_RX);
1383                         iwl_write32(priv, CSR_FH_INT_STATUS,
1384                                         CSR49_FH_INT_RX_MASK);
1385                 }
1386                 if (inta & CSR_INT_BIT_RX_PERIODIC) {
1387                         handled |= CSR_INT_BIT_RX_PERIODIC;
1388                         iwl_write32(priv, CSR_INT, CSR_INT_BIT_RX_PERIODIC);
1389                 }
1390                 /* Sending RX interrupt require many steps to be done in the
1391                  * the device:
1392                  * 1- write interrupt to current index in ICT table.
1393                  * 2- dma RX frame.
1394                  * 3- update RX shared data to indicate last write index.
1395                  * 4- send interrupt.
1396                  * This could lead to RX race, driver could receive RX interrupt
1397                  * but the shared data changes does not reflect this;
1398                  * periodic interrupt will detect any dangling Rx activity.
1399                  */
1400
1401                 /* Disable periodic interrupt; we use it as just a one-shot. */
1402                 iwl_write8(priv, CSR_INT_PERIODIC_REG,
1403                             CSR_INT_PERIODIC_DIS);
1404                 iwl_rx_handle(priv);
1405
1406                 /*
1407                  * Enable periodic interrupt in 8 msec only if we received
1408                  * real RX interrupt (instead of just periodic int), to catch
1409                  * any dangling Rx interrupt.  If it was just the periodic
1410                  * interrupt, there was no dangling Rx activity, and no need
1411                  * to extend the periodic interrupt; one-shot is enough.
1412                  */
1413                 if (inta & (CSR_INT_BIT_FH_RX | CSR_INT_BIT_SW_RX))
1414                         iwl_write8(priv, CSR_INT_PERIODIC_REG,
1415                                     CSR_INT_PERIODIC_ENA);
1416
1417                 priv->isr_stats.rx++;
1418         }
1419
1420         /* This "Tx" DMA channel is used only for loading uCode */
1421         if (inta & CSR_INT_BIT_FH_TX) {
1422                 iwl_write32(priv, CSR_FH_INT_STATUS, CSR49_FH_INT_TX_MASK);
1423                 IWL_DEBUG_ISR(priv, "uCode load interrupt\n");
1424                 priv->isr_stats.tx++;
1425                 handled |= CSR_INT_BIT_FH_TX;
1426                 /* Wake up uCode load routine, now that load is complete */
1427                 priv->ucode_write_complete = 1;
1428                 wake_up_interruptible(&priv->wait_command_queue);
1429         }
1430
1431         if (inta & ~handled) {
1432                 IWL_ERR(priv, "Unhandled INTA bits 0x%08x\n", inta & ~handled);
1433                 priv->isr_stats.unhandled++;
1434         }
1435
1436         if (inta & ~(priv->inta_mask)) {
1437                 IWL_WARN(priv, "Disabled INTA bits 0x%08x were pending\n",
1438                          inta & ~priv->inta_mask);
1439         }
1440
1441         /* Re-enable all interrupts */
1442         /* only Re-enable if diabled by irq */
1443         if (test_bit(STATUS_INT_ENABLED, &priv->status))
1444                 iwl_enable_interrupts(priv);
1445 }
1446
1447
1448 /******************************************************************************
1449  *
1450  * uCode download functions
1451  *
1452  ******************************************************************************/
1453
1454 static void iwl_dealloc_ucode_pci(struct iwl_priv *priv)
1455 {
1456         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_code);
1457         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_data);
1458         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_data_backup);
1459         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_init);
1460         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_init_data);
1461         iwl_free_fw_desc(priv->pci_dev, &priv->ucode_boot);
1462 }
1463
1464 static void iwl_nic_start(struct iwl_priv *priv)
1465 {
1466         /* Remove all resets to allow NIC to operate */
1467         iwl_write32(priv, CSR_RESET, 0);
1468 }
1469
1470
1471 /**
1472  * iwl_read_ucode - Read uCode images from disk file.
1473  *
1474  * Copy into buffers for card to fetch via bus-mastering
1475  */
1476 static int iwl_read_ucode(struct iwl_priv *priv)
1477 {
1478         struct iwl_ucode_header *ucode;
1479         int ret = -EINVAL, index;
1480         const struct firmware *ucode_raw;
1481         const char *name_pre = priv->cfg->fw_name_pre;
1482         const unsigned int api_max = priv->cfg->ucode_api_max;
1483         const unsigned int api_min = priv->cfg->ucode_api_min;
1484         char buf[25];
1485         u8 *src;
1486         size_t len;
1487         u32 api_ver, build;
1488         u32 inst_size, data_size, init_size, init_data_size, boot_size;
1489         u16 eeprom_ver;
1490
1491         /* Ask kernel firmware_class module to get the boot firmware off disk.
1492          * request_firmware() is synchronous, file is in memory on return. */
1493         for (index = api_max; index >= api_min; index--) {
1494                 sprintf(buf, "%s%d%s", name_pre, index, ".ucode");
1495                 ret = request_firmware(&ucode_raw, buf, &priv->pci_dev->dev);
1496                 if (ret < 0) {
1497                         IWL_ERR(priv, "%s firmware file req failed: %d\n",
1498                                   buf, ret);
1499                         if (ret == -ENOENT)
1500                                 continue;
1501                         else
1502                                 goto error;
1503                 } else {
1504                         if (index < api_max)
1505                                 IWL_ERR(priv, "Loaded firmware %s, "
1506                                         "which is deprecated. "
1507                                         "Please use API v%u instead.\n",
1508                                           buf, api_max);
1509
1510                         IWL_DEBUG_INFO(priv, "Got firmware '%s' file (%zd bytes) from disk\n",
1511                                        buf, ucode_raw->size);
1512                         break;
1513                 }
1514         }
1515
1516         if (ret < 0)
1517                 goto error;
1518
1519         /* Make sure that we got at least the v1 header! */
1520         if (ucode_raw->size < priv->cfg->ops->ucode->get_header_size(1)) {
1521                 IWL_ERR(priv, "File size way too small!\n");
1522                 ret = -EINVAL;
1523                 goto err_release;
1524         }
1525
1526         /* Data from ucode file:  header followed by uCode images */
1527         ucode = (struct iwl_ucode_header *)ucode_raw->data;
1528
1529         priv->ucode_ver = le32_to_cpu(ucode->ver);
1530         api_ver = IWL_UCODE_API(priv->ucode_ver);
1531         build = priv->cfg->ops->ucode->get_build(ucode, api_ver);
1532         inst_size = priv->cfg->ops->ucode->get_inst_size(ucode, api_ver);
1533         data_size = priv->cfg->ops->ucode->get_data_size(ucode, api_ver);
1534         init_size = priv->cfg->ops->ucode->get_init_size(ucode, api_ver);
1535         init_data_size =
1536                 priv->cfg->ops->ucode->get_init_data_size(ucode, api_ver);
1537         boot_size = priv->cfg->ops->ucode->get_boot_size(ucode, api_ver);
1538         src = priv->cfg->ops->ucode->get_data(ucode, api_ver);
1539
1540         /* api_ver should match the api version forming part of the
1541          * firmware filename ... but we don't check for that and only rely
1542          * on the API version read from firmware header from here on forward */
1543
1544         if (api_ver < api_min || api_ver > api_max) {
1545                 IWL_ERR(priv, "Driver unable to support your firmware API. "
1546                           "Driver supports v%u, firmware is v%u.\n",
1547                           api_max, api_ver);
1548                 priv->ucode_ver = 0;
1549                 ret = -EINVAL;
1550                 goto err_release;
1551         }
1552         if (api_ver != api_max)
1553                 IWL_ERR(priv, "Firmware has old API version. Expected v%u, "
1554                           "got v%u. New firmware can be obtained "
1555                           "from http://www.intellinuxwireless.org.\n",
1556                           api_max, api_ver);
1557
1558         IWL_INFO(priv, "loaded firmware version %u.%u.%u.%u\n",
1559                IWL_UCODE_MAJOR(priv->ucode_ver),
1560                IWL_UCODE_MINOR(priv->ucode_ver),
1561                IWL_UCODE_API(priv->ucode_ver),
1562                IWL_UCODE_SERIAL(priv->ucode_ver));
1563
1564         snprintf(priv->hw->wiphy->fw_version,
1565                  sizeof(priv->hw->wiphy->fw_version),
1566                  "%u.%u.%u.%u",
1567                  IWL_UCODE_MAJOR(priv->ucode_ver),
1568                  IWL_UCODE_MINOR(priv->ucode_ver),
1569                  IWL_UCODE_API(priv->ucode_ver),
1570                  IWL_UCODE_SERIAL(priv->ucode_ver));
1571
1572         if (build)
1573                 IWL_DEBUG_INFO(priv, "Build %u\n", build);
1574
1575         eeprom_ver = iwl_eeprom_query16(priv, EEPROM_VERSION);
1576         IWL_DEBUG_INFO(priv, "NVM Type: %s, version: 0x%x\n",
1577                        (priv->nvm_device_type == NVM_DEVICE_TYPE_OTP)
1578                        ? "OTP" : "EEPROM", eeprom_ver);
1579
1580         IWL_DEBUG_INFO(priv, "f/w package hdr ucode version raw = 0x%x\n",
1581                        priv->ucode_ver);
1582         IWL_DEBUG_INFO(priv, "f/w package hdr runtime inst size = %u\n",
1583                        inst_size);
1584         IWL_DEBUG_INFO(priv, "f/w package hdr runtime data size = %u\n",
1585                        data_size);
1586         IWL_DEBUG_INFO(priv, "f/w package hdr init inst size = %u\n",
1587                        init_size);
1588         IWL_DEBUG_INFO(priv, "f/w package hdr init data size = %u\n",
1589                        init_data_size);
1590         IWL_DEBUG_INFO(priv, "f/w package hdr boot inst size = %u\n",
1591                        boot_size);
1592
1593         /* Verify size of file vs. image size info in file's header */
1594         if (ucode_raw->size !=
1595                 priv->cfg->ops->ucode->get_header_size(api_ver) +
1596                 inst_size + data_size + init_size +
1597                 init_data_size + boot_size) {
1598
1599                 IWL_DEBUG_INFO(priv,
1600                         "uCode file size %d does not match expected size\n",
1601                         (int)ucode_raw->size);
1602                 ret = -EINVAL;
1603                 goto err_release;
1604         }
1605
1606         /* Verify that uCode images will fit in card's SRAM */
1607         if (inst_size > priv->hw_params.max_inst_size) {
1608                 IWL_DEBUG_INFO(priv, "uCode instr len %d too large to fit in\n",
1609                                inst_size);
1610                 ret = -EINVAL;
1611                 goto err_release;
1612         }
1613
1614         if (data_size > priv->hw_params.max_data_size) {
1615                 IWL_DEBUG_INFO(priv, "uCode data len %d too large to fit in\n",
1616                                 data_size);
1617                 ret = -EINVAL;
1618                 goto err_release;
1619         }
1620         if (init_size > priv->hw_params.max_inst_size) {
1621                 IWL_INFO(priv, "uCode init instr len %d too large to fit in\n",
1622                         init_size);
1623                 ret = -EINVAL;
1624                 goto err_release;
1625         }
1626         if (init_data_size > priv->hw_params.max_data_size) {
1627                 IWL_INFO(priv, "uCode init data len %d too large to fit in\n",
1628                       init_data_size);
1629                 ret = -EINVAL;
1630                 goto err_release;
1631         }
1632         if (boot_size > priv->hw_params.max_bsm_size) {
1633                 IWL_INFO(priv, "uCode boot instr len %d too large to fit in\n",
1634                         boot_size);
1635                 ret = -EINVAL;
1636                 goto err_release;
1637         }
1638
1639         /* Allocate ucode buffers for card's bus-master loading ... */
1640
1641         /* Runtime instructions and 2 copies of data:
1642          * 1) unmodified from disk
1643          * 2) backup cache for save/restore during power-downs */
1644         priv->ucode_code.len = inst_size;
1645         iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_code);
1646
1647         priv->ucode_data.len = data_size;
1648         iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_data);
1649
1650         priv->ucode_data_backup.len = data_size;
1651         iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_data_backup);
1652
1653         if (!priv->ucode_code.v_addr || !priv->ucode_data.v_addr ||
1654             !priv->ucode_data_backup.v_addr)
1655                 goto err_pci_alloc;
1656
1657         /* Initialization instructions and data */
1658         if (init_size && init_data_size) {
1659                 priv->ucode_init.len = init_size;
1660                 iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_init);
1661
1662                 priv->ucode_init_data.len = init_data_size;
1663                 iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_init_data);
1664
1665                 if (!priv->ucode_init.v_addr || !priv->ucode_init_data.v_addr)
1666                         goto err_pci_alloc;
1667         }
1668
1669         /* Bootstrap (instructions only, no data) */
1670         if (boot_size) {
1671                 priv->ucode_boot.len = boot_size;
1672                 iwl_alloc_fw_desc(priv->pci_dev, &priv->ucode_boot);
1673
1674                 if (!priv->ucode_boot.v_addr)
1675                         goto err_pci_alloc;
1676         }
1677
1678         /* Copy images into buffers for card's bus-master reads ... */
1679
1680         /* Runtime instructions (first block of data in file) */
1681         len = inst_size;
1682         IWL_DEBUG_INFO(priv, "Copying (but not loading) uCode instr len %Zd\n", len);
1683         memcpy(priv->ucode_code.v_addr, src, len);
1684         src += len;
1685
1686         IWL_DEBUG_INFO(priv, "uCode instr buf vaddr = 0x%p, paddr = 0x%08x\n",
1687                 priv->ucode_code.v_addr, (u32)priv->ucode_code.p_addr);
1688
1689         /* Runtime data (2nd block)
1690          * NOTE:  Copy into backup buffer will be done in iwl_up()  */
1691         len = data_size;
1692         IWL_DEBUG_INFO(priv, "Copying (but not loading) uCode data len %Zd\n", len);
1693         memcpy(priv->ucode_data.v_addr, src, len);
1694         memcpy(priv->ucode_data_backup.v_addr, src, len);
1695         src += len;
1696
1697         /* Initialization instructions (3rd block) */
1698         if (init_size) {
1699                 len = init_size;
1700                 IWL_DEBUG_INFO(priv, "Copying (but not loading) init instr len %Zd\n",
1701                                 len);
1702                 memcpy(priv->ucode_init.v_addr, src, len);
1703                 src += len;
1704         }
1705
1706         /* Initialization data (4th block) */
1707         if (init_data_size) {
1708                 len = init_data_size;
1709                 IWL_DEBUG_INFO(priv, "Copying (but not loading) init data len %Zd\n",
1710                                len);
1711                 memcpy(priv->ucode_init_data.v_addr, src, len);
1712                 src += len;
1713         }
1714
1715         /* Bootstrap instructions (5th block) */
1716         len = boot_size;
1717         IWL_DEBUG_INFO(priv, "Copying (but not loading) boot instr len %Zd\n", len);
1718         memcpy(priv->ucode_boot.v_addr, src, len);
1719
1720         /* We have our copies now, allow OS release its copies */
1721         release_firmware(ucode_raw);
1722         return 0;
1723
1724  err_pci_alloc:
1725         IWL_ERR(priv, "failed to allocate pci memory\n");
1726         ret = -ENOMEM;
1727         iwl_dealloc_ucode_pci(priv);
1728
1729  err_release:
1730         release_firmware(ucode_raw);
1731
1732  error:
1733         return ret;
1734 }
1735
1736 static const char *desc_lookup_text[] = {
1737         "OK",
1738         "FAIL",
1739         "BAD_PARAM",
1740         "BAD_CHECKSUM",
1741         "NMI_INTERRUPT_WDG",
1742         "SYSASSERT",
1743         "FATAL_ERROR",
1744         "BAD_COMMAND",
1745         "HW_ERROR_TUNE_LOCK",
1746         "HW_ERROR_TEMPERATURE",
1747         "ILLEGAL_CHAN_FREQ",
1748         "VCC_NOT_STABLE",
1749         "FH_ERROR",
1750         "NMI_INTERRUPT_HOST",
1751         "NMI_INTERRUPT_ACTION_PT",
1752         "NMI_INTERRUPT_UNKNOWN",
1753         "UCODE_VERSION_MISMATCH",
1754         "HW_ERROR_ABS_LOCK",
1755         "HW_ERROR_CAL_LOCK_FAIL",
1756         "NMI_INTERRUPT_INST_ACTION_PT",
1757         "NMI_INTERRUPT_DATA_ACTION_PT",
1758         "NMI_TRM_HW_ER",
1759         "NMI_INTERRUPT_TRM",
1760         "NMI_INTERRUPT_BREAK_POINT"
1761         "DEBUG_0",
1762         "DEBUG_1",
1763         "DEBUG_2",
1764         "DEBUG_3",
1765         "UNKNOWN"
1766 };
1767
1768 static const char *desc_lookup(int i)
1769 {
1770         int max = ARRAY_SIZE(desc_lookup_text) - 1;
1771
1772         if (i < 0 || i > max)
1773                 i = max;
1774
1775         return desc_lookup_text[i];
1776 }
1777
1778 #define ERROR_START_OFFSET  (1 * sizeof(u32))
1779 #define ERROR_ELEM_SIZE     (7 * sizeof(u32))
1780
1781 void iwl_dump_nic_error_log(struct iwl_priv *priv)
1782 {
1783         u32 data2, line;
1784         u32 desc, time, count, base, data1;
1785         u32 blink1, blink2, ilink1, ilink2;
1786
1787         if (priv->ucode_type == UCODE_INIT)
1788                 base = le32_to_cpu(priv->card_alive_init.error_event_table_ptr);
1789         else
1790                 base = le32_to_cpu(priv->card_alive.error_event_table_ptr);
1791
1792         if (!priv->cfg->ops->lib->is_valid_rtc_data_addr(base)) {
1793                 IWL_ERR(priv,
1794                         "Not valid error log pointer 0x%08X for %s uCode\n",
1795                         base, (priv->ucode_type == UCODE_INIT) ? "Init" : "RT");
1796                 return;
1797         }
1798
1799         count = iwl_read_targ_mem(priv, base);
1800
1801         if (ERROR_START_OFFSET <= count * ERROR_ELEM_SIZE) {
1802                 IWL_ERR(priv, "Start IWL Error Log Dump:\n");
1803                 IWL_ERR(priv, "Status: 0x%08lX, count: %d\n",
1804                         priv->status, count);
1805         }
1806
1807         desc = iwl_read_targ_mem(priv, base + 1 * sizeof(u32));
1808         blink1 = iwl_read_targ_mem(priv, base + 3 * sizeof(u32));
1809         blink2 = iwl_read_targ_mem(priv, base + 4 * sizeof(u32));
1810         ilink1 = iwl_read_targ_mem(priv, base + 5 * sizeof(u32));
1811         ilink2 = iwl_read_targ_mem(priv, base + 6 * sizeof(u32));
1812         data1 = iwl_read_targ_mem(priv, base + 7 * sizeof(u32));
1813         data2 = iwl_read_targ_mem(priv, base + 8 * sizeof(u32));
1814         line = iwl_read_targ_mem(priv, base + 9 * sizeof(u32));
1815         time = iwl_read_targ_mem(priv, base + 11 * sizeof(u32));
1816
1817         trace_iwlwifi_dev_ucode_error(priv, desc, time, data1, data2, line,
1818                                       blink1, blink2, ilink1, ilink2);
1819
1820         IWL_ERR(priv, "Desc                               Time       "
1821                 "data1      data2      line\n");
1822         IWL_ERR(priv, "%-28s (#%02d) %010u 0x%08X 0x%08X %u\n",
1823                 desc_lookup(desc), desc, time, data1, data2, line);
1824         IWL_ERR(priv, "blink1  blink2  ilink1  ilink2\n");
1825         IWL_ERR(priv, "0x%05X 0x%05X 0x%05X 0x%05X\n", blink1, blink2,
1826                 ilink1, ilink2);
1827
1828 }
1829
1830 #define EVENT_START_OFFSET  (4 * sizeof(u32))
1831
1832 /**
1833  * iwl_print_event_log - Dump error event log to syslog
1834  *
1835  */
1836 static int iwl_print_event_log(struct iwl_priv *priv, u32 start_idx,
1837                                u32 num_events, u32 mode,
1838                                int pos, char **buf, size_t bufsz)
1839 {
1840         u32 i;
1841         u32 base;       /* SRAM byte address of event log header */
1842         u32 event_size; /* 2 u32s, or 3 u32s if timestamp recorded */
1843         u32 ptr;        /* SRAM byte address of log data */
1844         u32 ev, time, data; /* event log data */
1845         unsigned long reg_flags;
1846
1847         if (num_events == 0)
1848                 return pos;
1849         if (priv->ucode_type == UCODE_INIT)
1850                 base = le32_to_cpu(priv->card_alive_init.log_event_table_ptr);
1851         else
1852                 base = le32_to_cpu(priv->card_alive.log_event_table_ptr);
1853
1854         if (mode == 0)
1855                 event_size = 2 * sizeof(u32);
1856         else
1857                 event_size = 3 * sizeof(u32);
1858
1859         ptr = base + EVENT_START_OFFSET + (start_idx * event_size);
1860
1861         /* Make sure device is powered up for SRAM reads */
1862         spin_lock_irqsave(&priv->reg_lock, reg_flags);
1863         iwl_grab_nic_access(priv);
1864
1865         /* Set starting address; reads will auto-increment */
1866         _iwl_write_direct32(priv, HBUS_TARG_MEM_RADDR, ptr);
1867         rmb();
1868
1869         /* "time" is actually "data" for mode 0 (no timestamp).
1870         * place event id # at far right for easier visual parsing. */
1871         for (i = 0; i < num_events; i++) {
1872                 ev = _iwl_read_direct32(priv, HBUS_TARG_MEM_RDAT);
1873                 time = _iwl_read_direct32(priv, HBUS_TARG_MEM_RDAT);
1874                 if (mode == 0) {
1875                         /* data, ev */
1876                         if (bufsz) {
1877                                 pos += scnprintf(*buf + pos, bufsz - pos,
1878                                                 "EVT_LOG:0x%08x:%04u\n",
1879                                                 time, ev);
1880                         } else {
1881                                 trace_iwlwifi_dev_ucode_event(priv, 0,
1882                                         time, ev);
1883                                 IWL_ERR(priv, "EVT_LOG:0x%08x:%04u\n",
1884                                         time, ev);
1885                         }
1886                 } else {
1887                         data = _iwl_read_direct32(priv, HBUS_TARG_MEM_RDAT);
1888                         if (bufsz) {
1889                                 pos += scnprintf(*buf + pos, bufsz - pos,
1890                                                 "EVT_LOGT:%010u:0x%08x:%04u\n",
1891                                                  time, data, ev);
1892                         } else {
1893                                 IWL_ERR(priv, "EVT_LOGT:%010u:0x%08x:%04u\n",
1894                                         time, data, ev);
1895                                 trace_iwlwifi_dev_ucode_event(priv, time,
1896                                         data, ev);
1897                         }
1898                 }
1899         }
1900
1901         /* Allow device to power down */
1902         iwl_release_nic_access(priv);
1903         spin_unlock_irqrestore(&priv->reg_lock, reg_flags);
1904         return pos;
1905 }
1906
1907 /**
1908  * iwl_print_last_event_logs - Dump the newest # of event log to syslog
1909  */
1910 static int iwl_print_last_event_logs(struct iwl_priv *priv, u32 capacity,
1911                                     u32 num_wraps, u32 next_entry,
1912                                     u32 size, u32 mode,
1913                                     int pos, char **buf, size_t bufsz)
1914 {
1915         /*
1916          * display the newest DEFAULT_LOG_ENTRIES entries
1917          * i.e the entries just before the next ont that uCode would fill.
1918          */
1919         if (num_wraps) {
1920                 if (next_entry < size) {
1921                         pos = iwl_print_event_log(priv,
1922                                                 capacity - (size - next_entry),
1923                                                 size - next_entry, mode,
1924                                                 pos, buf, bufsz);
1925                         pos = iwl_print_event_log(priv, 0,
1926                                                   next_entry, mode,
1927                                                   pos, buf, bufsz);
1928                 } else
1929                         pos = iwl_print_event_log(priv, next_entry - size,
1930                                                   size, mode, pos, buf, bufsz);
1931         } else {
1932                 if (next_entry < size) {
1933                         pos = iwl_print_event_log(priv, 0, next_entry,
1934                                                   mode, pos, buf, bufsz);
1935                 } else {
1936                         pos = iwl_print_event_log(priv, next_entry - size,
1937                                                   size, mode, pos, buf, bufsz);
1938                 }
1939         }
1940         return pos;
1941 }
1942
1943 /* For sanity check only.  Actual size is determined by uCode, typ. 512 */
1944 #define MAX_EVENT_LOG_SIZE (512)
1945
1946 #define DEFAULT_DUMP_EVENT_LOG_ENTRIES (20)
1947
1948 int iwl_dump_nic_event_log(struct iwl_priv *priv, bool full_log,
1949                             char **buf, bool display)
1950 {
1951         u32 base;       /* SRAM byte address of event log header */
1952         u32 capacity;   /* event log capacity in # entries */
1953         u32 mode;       /* 0 - no timestamp, 1 - timestamp recorded */
1954         u32 num_wraps;  /* # times uCode wrapped to top of log */
1955         u32 next_entry; /* index of next entry to be written by uCode */
1956         u32 size;       /* # entries that we'll print */
1957         int pos = 0;
1958         size_t bufsz = 0;
1959
1960         if (priv->ucode_type == UCODE_INIT)
1961                 base = le32_to_cpu(priv->card_alive_init.log_event_table_ptr);
1962         else
1963                 base = le32_to_cpu(priv->card_alive.log_event_table_ptr);
1964
1965         if (!priv->cfg->ops->lib->is_valid_rtc_data_addr(base)) {
1966                 IWL_ERR(priv,
1967                         "Invalid event log pointer 0x%08X for %s uCode\n",
1968                         base, (priv->ucode_type == UCODE_INIT) ? "Init" : "RT");
1969                 return -EINVAL;
1970         }
1971
1972         /* event log header */
1973         capacity = iwl_read_targ_mem(priv, base);
1974         mode = iwl_read_targ_mem(priv, base + (1 * sizeof(u32)));
1975         num_wraps = iwl_read_targ_mem(priv, base + (2 * sizeof(u32)));
1976         next_entry = iwl_read_targ_mem(priv, base + (3 * sizeof(u32)));
1977
1978         if (capacity > MAX_EVENT_LOG_SIZE) {
1979                 IWL_ERR(priv, "Log capacity %d is bogus, limit to %d entries\n",
1980                         capacity, MAX_EVENT_LOG_SIZE);
1981                 capacity = MAX_EVENT_LOG_SIZE;
1982         }
1983
1984         if (next_entry > MAX_EVENT_LOG_SIZE) {
1985                 IWL_ERR(priv, "Log write index %d is bogus, limit to %d\n",
1986                         next_entry, MAX_EVENT_LOG_SIZE);
1987                 next_entry = MAX_EVENT_LOG_SIZE;
1988         }
1989
1990         size = num_wraps ? capacity : next_entry;
1991
1992         /* bail out if nothing in log */
1993         if (size == 0) {
1994                 IWL_ERR(priv, "Start IWL Event Log Dump: nothing in log\n");
1995                 return pos;
1996         }
1997
1998 #ifdef CONFIG_IWLWIFI_DEBUG
1999         if (!(iwl_get_debug_level(priv) & IWL_DL_FW_ERRORS) && !full_log)
2000                 size = (size > DEFAULT_DUMP_EVENT_LOG_ENTRIES)
2001                         ? DEFAULT_DUMP_EVENT_LOG_ENTRIES : size;
2002 #else
2003         size = (size > DEFAULT_DUMP_EVENT_LOG_ENTRIES)
2004                 ? DEFAULT_DUMP_EVENT_LOG_ENTRIES : size;
2005 #endif
2006         IWL_ERR(priv, "Start IWL Event Log Dump: display last %u entries\n",
2007                 size);
2008
2009 #ifdef CONFIG_IWLWIFI_DEBUG
2010         if (display) {
2011                 if (full_log)
2012                         bufsz = capacity * 48;
2013                 else
2014                         bufsz = size * 48;
2015                 *buf = kmalloc(bufsz, GFP_KERNEL);
2016                 if (!*buf)
2017                         return -ENOMEM;
2018         }
2019         if ((iwl_get_debug_level(priv) & IWL_DL_FW_ERRORS) || full_log) {
2020                 /*
2021                  * if uCode has wrapped back to top of log,
2022                  * start at the oldest entry,
2023                  * i.e the next one that uCode would fill.
2024                  */
2025                 if (num_wraps)
2026                         pos = iwl_print_event_log(priv, next_entry,
2027                                                 capacity - next_entry, mode,
2028                                                 pos, buf, bufsz);
2029                 /* (then/else) start at top of log */
2030                 pos = iwl_print_event_log(priv, 0,
2031                                           next_entry, mode, pos, buf, bufsz);
2032         } else
2033                 pos = iwl_print_last_event_logs(priv, capacity, num_wraps,
2034                                                 next_entry, size, mode,
2035                                                 pos, buf, bufsz);
2036 #else
2037         pos = iwl_print_last_event_logs(priv, capacity, num_wraps,
2038                                         next_entry, size, mode,
2039                                         pos, buf, bufsz);
2040 #endif
2041         return pos;
2042 }
2043
2044 /**
2045  * iwl_alive_start - called after REPLY_ALIVE notification received
2046  *                   from protocol/runtime uCode (initialization uCode's
2047  *                   Alive gets handled by iwl_init_alive_start()).
2048  */
2049 static void iwl_alive_start(struct iwl_priv *priv)
2050 {
2051         int ret = 0;
2052
2053         IWL_DEBUG_INFO(priv, "Runtime Alive received.\n");
2054
2055         if (priv->card_alive.is_valid != UCODE_VALID_OK) {
2056                 /* We had an error bringing up the hardware, so take it
2057                  * all the way back down so we can try again */
2058                 IWL_DEBUG_INFO(priv, "Alive failed.\n");
2059                 goto restart;
2060         }
2061
2062         /* Initialize uCode has loaded Runtime uCode ... verify inst image.
2063          * This is a paranoid check, because we would not have gotten the
2064          * "runtime" alive if code weren't properly loaded.  */
2065         if (iwl_verify_ucode(priv)) {
2066                 /* Runtime instruction load was bad;
2067                  * take it all the way back down so we can try again */
2068                 IWL_DEBUG_INFO(priv, "Bad runtime uCode load.\n");
2069                 goto restart;
2070         }
2071
2072         iwl_clear_stations_table(priv);
2073         ret = priv->cfg->ops->lib->alive_notify(priv);
2074         if (ret) {
2075                 IWL_WARN(priv,
2076                         "Could not complete ALIVE transition [ntf]: %d\n", ret);
2077                 goto restart;
2078         }
2079
2080         /* After the ALIVE response, we can send host commands to the uCode */
2081         set_bit(STATUS_ALIVE, &priv->status);
2082
2083         if (iwl_is_rfkill(priv))
2084                 return;
2085
2086         ieee80211_wake_queues(priv->hw);
2087
2088         priv->active_rate = priv->rates_mask;
2089         priv->active_rate_basic = priv->rates_mask & IWL_BASIC_RATES_MASK;
2090
2091         /* Configure Tx antenna selection based on H/W config */
2092         if (priv->cfg->ops->hcmd->set_tx_ant)
2093                 priv->cfg->ops->hcmd->set_tx_ant(priv, priv->cfg->valid_tx_ant);
2094
2095         if (iwl_is_associated(priv)) {
2096                 struct iwl_rxon_cmd *active_rxon =
2097                                 (struct iwl_rxon_cmd *)&priv->active_rxon;
2098                 /* apply any changes in staging */
2099                 priv->staging_rxon.filter_flags |= RXON_FILTER_ASSOC_MSK;
2100                 active_rxon->filter_flags &= ~RXON_FILTER_ASSOC_MSK;
2101         } else {
2102                 /* Initialize our rx_config data */
2103                 iwl_connection_init_rx_config(priv, priv->iw_mode);
2104
2105                 if (priv->cfg->ops->hcmd->set_rxon_chain)
2106                         priv->cfg->ops->hcmd->set_rxon_chain(priv);
2107
2108                 memcpy(priv->staging_rxon.node_addr, priv->mac_addr, ETH_ALEN);
2109         }
2110
2111         /* Configure Bluetooth device coexistence support */
2112         iwl_send_bt_config(priv);
2113
2114         iwl_reset_run_time_calib(priv);
2115
2116         /* Configure the adapter for unassociated operation */
2117         iwlcore_commit_rxon(priv);
2118
2119         /* At this point, the NIC is initialized and operational */
2120         iwl_rf_kill_ct_config(priv);
2121
2122         iwl_leds_init(priv);
2123
2124         IWL_DEBUG_INFO(priv, "ALIVE processing complete.\n");
2125         set_bit(STATUS_READY, &priv->status);
2126         wake_up_interruptible(&priv->wait_command_queue);
2127
2128         iwl_power_update_mode(priv, true);
2129
2130         /* reassociate for ADHOC mode */
2131         if (priv->vif && (priv->iw_mode == NL80211_IFTYPE_ADHOC)) {
2132                 struct sk_buff *beacon = ieee80211_beacon_get(priv->hw,
2133                                                                 priv->vif);
2134                 if (beacon)
2135                         iwl_mac_beacon_update(priv->hw, beacon);
2136         }
2137
2138
2139         if (test_and_clear_bit(STATUS_MODE_PENDING, &priv->status))
2140                 iwl_set_mode(priv, priv->iw_mode);
2141
2142         return;
2143
2144  restart:
2145         queue_work(priv->workqueue, &priv->restart);
2146 }
2147
2148 static void iwl_cancel_deferred_work(struct iwl_priv *priv);
2149
2150 static void __iwl_down(struct iwl_priv *priv)
2151 {
2152         unsigned long flags;
2153         int exit_pending = test_bit(STATUS_EXIT_PENDING, &priv->status);
2154
2155         IWL_DEBUG_INFO(priv, DRV_NAME " is going down\n");
2156
2157         if (!exit_pending)
2158                 set_bit(STATUS_EXIT_PENDING, &priv->status);
2159
2160         iwl_clear_stations_table(priv);
2161
2162         /* Unblock any waiting calls */
2163         wake_up_interruptible_all(&priv->wait_command_queue);
2164
2165         /* Wipe out the EXIT_PENDING status bit if we are not actually
2166          * exiting the module */
2167         if (!exit_pending)
2168                 clear_bit(STATUS_EXIT_PENDING, &priv->status);
2169
2170         /* stop and reset the on-board processor */
2171         iwl_write32(priv, CSR_RESET, CSR_RESET_REG_FLAG_NEVO_RESET);
2172
2173         /* tell the device to stop sending interrupts */
2174         spin_lock_irqsave(&priv->lock, flags);
2175         iwl_disable_interrupts(priv);
2176         spin_unlock_irqrestore(&priv->lock, flags);
2177         iwl_synchronize_irq(priv);
2178
2179         if (priv->mac80211_registered)
2180                 ieee80211_stop_queues(priv->hw);
2181
2182         /* If we have not previously called iwl_init() then
2183          * clear all bits but the RF Kill bit and return */
2184         if (!iwl_is_init(priv)) {
2185                 priv->status = test_bit(STATUS_RF_KILL_HW, &priv->status) <<
2186                                         STATUS_RF_KILL_HW |
2187                                test_bit(STATUS_GEO_CONFIGURED, &priv->status) <<
2188                                         STATUS_GEO_CONFIGURED |
2189                                test_bit(STATUS_EXIT_PENDING, &priv->status) <<
2190                                         STATUS_EXIT_PENDING;
2191                 goto exit;
2192         }
2193
2194         /* ...otherwise clear out all the status bits but the RF Kill
2195          * bit and continue taking the NIC down. */
2196         priv->status &= test_bit(STATUS_RF_KILL_HW, &priv->status) <<
2197                                 STATUS_RF_KILL_HW |
2198                         test_bit(STATUS_GEO_CONFIGURED, &priv->status) <<
2199                                 STATUS_GEO_CONFIGURED |
2200                         test_bit(STATUS_FW_ERROR, &priv->status) <<
2201                                 STATUS_FW_ERROR |
2202                        test_bit(STATUS_EXIT_PENDING, &priv->status) <<
2203                                 STATUS_EXIT_PENDING;
2204
2205         /* device going down, Stop using ICT table */
2206         iwl_disable_ict(priv);
2207
2208         iwl_txq_ctx_stop(priv);
2209         iwl_rxq_stop(priv);
2210
2211         /* Power-down device's busmaster DMA clocks */
2212         iwl_write_prph(priv, APMG_CLK_DIS_REG, APMG_CLK_VAL_DMA_CLK_RQT);
2213         udelay(5);
2214
2215         /* Make sure (redundant) we've released our request to stay awake */
2216         iwl_clear_bit(priv, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
2217
2218         /* Stop the device, and put it in low power state */
2219         priv->cfg->ops->lib->apm_ops.stop(priv);
2220
2221  exit:
2222         memset(&priv->card_alive, 0, sizeof(struct iwl_alive_resp));
2223
2224         if (priv->ibss_beacon)
2225                 dev_kfree_skb(priv->ibss_beacon);
2226         priv->ibss_beacon = NULL;
2227
2228         /* clear out any free frames */
2229         iwl_clear_free_frames(priv);
2230 }
2231
2232 static void iwl_down(struct iwl_priv *priv)
2233 {
2234         mutex_lock(&priv->mutex);
2235         __iwl_down(priv);
2236         mutex_unlock(&priv->mutex);
2237
2238         iwl_cancel_deferred_work(priv);
2239 }
2240
2241 #define HW_READY_TIMEOUT (50)
2242
2243 static int iwl_set_hw_ready(struct iwl_priv *priv)
2244 {
2245         int ret = 0;
2246
2247         iwl_set_bit(priv, CSR_HW_IF_CONFIG_REG,
2248                 CSR_HW_IF_CONFIG_REG_BIT_NIC_READY);
2249
2250         /* See if we got it */
2251         ret = iwl_poll_bit(priv, CSR_HW_IF_CONFIG_REG,
2252                                 CSR_HW_IF_CONFIG_REG_BIT_NIC_READY,
2253                                 CSR_HW_IF_CONFIG_REG_BIT_NIC_READY,
2254                                 HW_READY_TIMEOUT);
2255         if (ret != -ETIMEDOUT)
2256                 priv->hw_ready = true;
2257         else
2258                 priv->hw_ready = false;
2259
2260         IWL_DEBUG_INFO(priv, "hardware %s\n",
2261                       (priv->hw_ready == 1) ? "ready" : "not ready");
2262         return ret;
2263 }
2264
2265 static int iwl_prepare_card_hw(struct iwl_priv *priv)
2266 {
2267         int ret = 0;
2268
2269         IWL_DEBUG_INFO(priv, "iwl_prepare_card_hw enter \n");
2270
2271         ret = iwl_set_hw_ready(priv);
2272         if (priv->hw_ready)
2273                 return ret;
2274
2275         /* If HW is not ready, prepare the conditions to check again */
2276         iwl_set_bit(priv, CSR_HW_IF_CONFIG_REG,
2277                         CSR_HW_IF_CONFIG_REG_PREPARE);
2278
2279         ret = iwl_poll_bit(priv, CSR_HW_IF_CONFIG_REG,
2280                         ~CSR_HW_IF_CONFIG_REG_BIT_NIC_PREPARE_DONE,
2281                         CSR_HW_IF_CONFIG_REG_BIT_NIC_PREPARE_DONE, 150000);
2282
2283         /* HW should be ready by now, check again. */
2284         if (ret != -ETIMEDOUT)
2285                 iwl_set_hw_ready(priv);
2286
2287         return ret;
2288 }
2289
2290 #define MAX_HW_RESTARTS 5
2291
2292 static int __iwl_up(struct iwl_priv *priv)
2293 {
2294         int i;
2295         int ret;
2296
2297         if (test_bit(STATUS_EXIT_PENDING, &priv->status)) {
2298                 IWL_WARN(priv, "Exit pending; will not bring the NIC up\n");
2299                 return -EIO;
2300         }
2301
2302         if (!priv->ucode_data_backup.v_addr || !priv->ucode_data.v_addr) {
2303                 IWL_ERR(priv, "ucode not available for device bringup\n");
2304                 return -EIO;
2305         }
2306
2307         iwl_prepare_card_hw(priv);
2308
2309         if (!priv->hw_ready) {
2310                 IWL_WARN(priv, "Exit HW not ready\n");
2311                 return -EIO;
2312         }
2313
2314         /* If platform's RF_KILL switch is NOT set to KILL */
2315         if (iwl_read32(priv, CSR_GP_CNTRL) & CSR_GP_CNTRL_REG_FLAG_HW_RF_KILL_SW)
2316                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
2317         else
2318                 set_bit(STATUS_RF_KILL_HW, &priv->status);
2319
2320         if (iwl_is_rfkill(priv)) {
2321                 wiphy_rfkill_set_hw_state(priv->hw->wiphy, true);
2322
2323                 iwl_enable_interrupts(priv);
2324                 IWL_WARN(priv, "Radio disabled by HW RF Kill switch\n");
2325                 return 0;
2326         }
2327
2328         iwl_write32(priv, CSR_INT, 0xFFFFFFFF);
2329
2330         ret = iwl_hw_nic_init(priv);
2331         if (ret) {
2332                 IWL_ERR(priv, "Unable to init nic\n");
2333                 return ret;
2334         }
2335
2336         /* make sure rfkill handshake bits are cleared */
2337         iwl_write32(priv, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
2338         iwl_write32(priv, CSR_UCODE_DRV_GP1_CLR,
2339                     CSR_UCODE_DRV_GP1_BIT_CMD_BLOCKED);
2340
2341         /* clear (again), then enable host interrupts */
2342         iwl_write32(priv, CSR_INT, 0xFFFFFFFF);
2343         iwl_enable_interrupts(priv);
2344
2345         /* really make sure rfkill handshake bits are cleared */
2346         iwl_write32(priv, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
2347         iwl_write32(priv, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
2348
2349         /* Copy original ucode data image from disk into backup cache.
2350          * This will be used to initialize the on-board processor's
2351          * data SRAM for a clean start when the runtime program first loads. */
2352         memcpy(priv->ucode_data_backup.v_addr, priv->ucode_data.v_addr,
2353                priv->ucode_data.len);
2354
2355         for (i = 0; i < MAX_HW_RESTARTS; i++) {
2356
2357                 iwl_clear_stations_table(priv);
2358
2359                 /* load bootstrap state machine,
2360                  * load bootstrap program into processor's memory,
2361                  * prepare to load the "initialize" uCode */
2362                 ret = priv->cfg->ops->lib->load_ucode(priv);
2363
2364                 if (ret) {
2365                         IWL_ERR(priv, "Unable to set up bootstrap uCode: %d\n",
2366                                 ret);
2367                         continue;
2368                 }
2369
2370                 /* start card; "initialize" will load runtime ucode */
2371                 iwl_nic_start(priv);
2372
2373                 IWL_DEBUG_INFO(priv, DRV_NAME " is coming up\n");
2374
2375                 return 0;
2376         }
2377
2378         set_bit(STATUS_EXIT_PENDING, &priv->status);
2379         __iwl_down(priv);
2380         clear_bit(STATUS_EXIT_PENDING, &priv->status);
2381
2382         /* tried to restart and config the device for as long as our
2383          * patience could withstand */
2384         IWL_ERR(priv, "Unable to initialize device after %d attempts.\n", i);
2385         return -EIO;
2386 }
2387
2388
2389 /*****************************************************************************
2390  *
2391  * Workqueue callbacks
2392  *
2393  *****************************************************************************/
2394
2395 static void iwl_bg_init_alive_start(struct work_struct *data)
2396 {
2397         struct iwl_priv *priv =
2398             container_of(data, struct iwl_priv, init_alive_start.work);
2399
2400         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
2401                 return;
2402
2403         mutex_lock(&priv->mutex);
2404         priv->cfg->ops->lib->init_alive_start(priv);
2405         mutex_unlock(&priv->mutex);
2406 }
2407
2408 static void iwl_bg_alive_start(struct work_struct *data)
2409 {
2410         struct iwl_priv *priv =
2411             container_of(data, struct iwl_priv, alive_start.work);
2412
2413         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
2414                 return;
2415
2416         /* enable dram interrupt */
2417         iwl_reset_ict(priv);
2418
2419         mutex_lock(&priv->mutex);
2420         iwl_alive_start(priv);
2421         mutex_unlock(&priv->mutex);
2422 }
2423
2424 static void iwl_bg_run_time_calib_work(struct work_struct *work)
2425 {
2426         struct iwl_priv *priv = container_of(work, struct iwl_priv,
2427                         run_time_calib_work);
2428
2429         mutex_lock(&priv->mutex);
2430
2431         if (test_bit(STATUS_EXIT_PENDING, &priv->status) ||
2432             test_bit(STATUS_SCANNING, &priv->status)) {
2433                 mutex_unlock(&priv->mutex);
2434                 return;
2435         }
2436
2437         if (priv->start_calib) {
2438                 iwl_chain_noise_calibration(priv, &priv->statistics);
2439
2440                 iwl_sensitivity_calibration(priv, &priv->statistics);
2441         }
2442
2443         mutex_unlock(&priv->mutex);
2444         return;
2445 }
2446
2447 static void iwl_bg_up(struct work_struct *data)
2448 {
2449         struct iwl_priv *priv = container_of(data, struct iwl_priv, up);
2450
2451         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
2452                 return;
2453
2454         mutex_lock(&priv->mutex);
2455         __iwl_up(priv);
2456         mutex_unlock(&priv->mutex);
2457 }
2458
2459 static void iwl_bg_restart(struct work_struct *data)
2460 {
2461         struct iwl_priv *priv = container_of(data, struct iwl_priv, restart);
2462
2463         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
2464                 return;
2465
2466         if (test_and_clear_bit(STATUS_FW_ERROR, &priv->status)) {
2467                 mutex_lock(&priv->mutex);
2468                 priv->vif = NULL;
2469                 priv->is_open = 0;
2470                 mutex_unlock(&priv->mutex);
2471                 iwl_down(priv);
2472                 ieee80211_restart_hw(priv->hw);
2473         } else {
2474                 iwl_down(priv);
2475                 queue_work(priv->workqueue, &priv->up);
2476         }
2477 }
2478
2479 static void iwl_bg_rx_replenish(struct work_struct *data)
2480 {
2481         struct iwl_priv *priv =
2482             container_of(data, struct iwl_priv, rx_replenish);
2483
2484         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
2485                 return;
2486
2487         mutex_lock(&priv->mutex);
2488         iwl_rx_replenish(priv);
2489         mutex_unlock(&priv->mutex);
2490 }
2491
2492 #define IWL_DELAY_NEXT_SCAN (HZ*2)
2493
2494 void iwl_post_associate(struct iwl_priv *priv)
2495 {
2496         struct ieee80211_conf *conf = NULL;
2497         int ret = 0;
2498         unsigned long flags;
2499
2500         if (priv->iw_mode == NL80211_IFTYPE_AP) {
2501                 IWL_ERR(priv, "%s Should not be called in AP mode\n", __func__);
2502                 return;
2503         }
2504
2505         IWL_DEBUG_ASSOC(priv, "Associated as %d to: %pM\n",
2506                         priv->assoc_id, priv->active_rxon.bssid_addr);
2507
2508
2509         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
2510                 return;
2511
2512
2513         if (!priv->vif || !priv->is_open)
2514                 return;
2515
2516         iwl_scan_cancel_timeout(priv, 200);
2517
2518         conf = ieee80211_get_hw_conf(priv->hw);
2519
2520         priv->staging_rxon.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
2521         iwlcore_commit_rxon(priv);
2522
2523         iwl_setup_rxon_timing(priv);
2524         ret = iwl_send_cmd_pdu(priv, REPLY_RXON_TIMING,
2525                               sizeof(priv->rxon_timing), &priv->rxon_timing);
2526         if (ret)
2527                 IWL_WARN(priv, "REPLY_RXON_TIMING failed - "
2528                             "Attempting to continue.\n");
2529
2530         priv->staging_rxon.filter_flags |= RXON_FILTER_ASSOC_MSK;
2531
2532         iwl_set_rxon_ht(priv, &priv->current_ht_config);
2533
2534         if (priv->cfg->ops->hcmd->set_rxon_chain)
2535                 priv->cfg->ops->hcmd->set_rxon_chain(priv);
2536
2537         priv->staging_rxon.assoc_id = cpu_to_le16(priv->assoc_id);
2538
2539         IWL_DEBUG_ASSOC(priv, "assoc id %d beacon interval %d\n",
2540                         priv->assoc_id, priv->beacon_int);
2541
2542         if (priv->assoc_capability & WLAN_CAPABILITY_SHORT_PREAMBLE)
2543                 priv->staging_rxon.flags |= RXON_FLG_SHORT_PREAMBLE_MSK;
2544         else
2545                 priv->staging_rxon.flags &= ~RXON_FLG_SHORT_PREAMBLE_MSK;
2546
2547         if (priv->staging_rxon.flags & RXON_FLG_BAND_24G_MSK) {
2548                 if (priv->assoc_capability & WLAN_CAPABILITY_SHORT_SLOT_TIME)
2549                         priv->staging_rxon.flags |= RXON_FLG_SHORT_SLOT_MSK;
2550                 else
2551                         priv->staging_rxon.flags &= ~RXON_FLG_SHORT_SLOT_MSK;
2552
2553                 if (priv->iw_mode == NL80211_IFTYPE_ADHOC)
2554                         priv->staging_rxon.flags &= ~RXON_FLG_SHORT_SLOT_MSK;
2555
2556         }
2557
2558         iwlcore_commit_rxon(priv);
2559
2560         switch (priv->iw_mode) {
2561         case NL80211_IFTYPE_STATION:
2562                 break;
2563
2564         case NL80211_IFTYPE_ADHOC:
2565
2566                 /* assume default assoc id */
2567                 priv->assoc_id = 1;
2568
2569                 iwl_rxon_add_station(priv, priv->bssid, 0);
2570                 iwl_send_beacon_cmd(priv);
2571
2572                 break;
2573
2574         default:
2575                 IWL_ERR(priv, "%s Should not be called in %d mode\n",
2576                           __func__, priv->iw_mode);
2577                 break;
2578         }
2579
2580         if (priv->iw_mode == NL80211_IFTYPE_ADHOC)
2581                 priv->assoc_station_added = 1;
2582
2583         spin_lock_irqsave(&priv->lock, flags);
2584         iwl_activate_qos(priv, 0);
2585         spin_unlock_irqrestore(&priv->lock, flags);
2586
2587         /* the chain noise calibration will enabled PM upon completion
2588          * If chain noise has already been run, then we need to enable
2589          * power management here */
2590         if (priv->chain_noise_data.state == IWL_CHAIN_NOISE_DONE)
2591                 iwl_power_update_mode(priv, false);
2592
2593         /* Enable Rx differential gain and sensitivity calibrations */
2594         iwl_chain_noise_reset(priv);
2595         priv->start_calib = 1;
2596
2597 }
2598
2599 /*****************************************************************************
2600  *
2601  * mac80211 entry point functions
2602  *
2603  *****************************************************************************/
2604
2605 #define UCODE_READY_TIMEOUT     (4 * HZ)
2606
2607 /*
2608  * Not a mac80211 entry point function, but it fits in with all the
2609  * other mac80211 functions grouped here.
2610  */
2611 static int iwl_mac_setup_register(struct iwl_priv *priv)
2612 {
2613         int ret;
2614         struct ieee80211_hw *hw = priv->hw;
2615         hw->rate_control_algorithm = "iwl-agn-rs";
2616
2617         /* Tell mac80211 our characteristics */
2618         hw->flags = IEEE80211_HW_SIGNAL_DBM |
2619                     IEEE80211_HW_NOISE_DBM |
2620                     IEEE80211_HW_AMPDU_AGGREGATION |
2621                     IEEE80211_HW_SPECTRUM_MGMT;
2622
2623         if (!priv->cfg->broken_powersave)
2624                 hw->flags |= IEEE80211_HW_SUPPORTS_PS |
2625                              IEEE80211_HW_SUPPORTS_DYNAMIC_PS;
2626
2627         if (priv->cfg->sku & IWL_SKU_N)
2628                 hw->flags |= IEEE80211_HW_SUPPORTS_DYNAMIC_SMPS |
2629                              IEEE80211_HW_SUPPORTS_STATIC_SMPS;
2630
2631         hw->sta_data_size = sizeof(struct iwl_station_priv);
2632         hw->wiphy->interface_modes =
2633                 BIT(NL80211_IFTYPE_STATION) |
2634                 BIT(NL80211_IFTYPE_ADHOC);
2635
2636         hw->wiphy->flags |= WIPHY_FLAG_STRICT_REGULATORY |
2637                             WIPHY_FLAG_DISABLE_BEACON_HINTS;
2638
2639         /*
2640          * For now, disable PS by default because it affects
2641          * RX performance significantly.
2642          */
2643         hw->wiphy->flags &= ~WIPHY_FLAG_PS_ON_BY_DEFAULT;
2644
2645         hw->wiphy->max_scan_ssids = PROBE_OPTION_MAX;
2646         /* we create the 802.11 header and a zero-length SSID element */
2647         hw->wiphy->max_scan_ie_len = IWL_MAX_PROBE_REQUEST - 24 - 2;
2648
2649         /* Default value; 4 EDCA QOS priorities */
2650         hw->queues = 4;
2651
2652         hw->max_listen_interval = IWL_CONN_MAX_LISTEN_INTERVAL;
2653
2654         if (priv->bands[IEEE80211_BAND_2GHZ].n_channels)
2655                 priv->hw->wiphy->bands[IEEE80211_BAND_2GHZ] =
2656                         &priv->bands[IEEE80211_BAND_2GHZ];
2657         if (priv->bands[IEEE80211_BAND_5GHZ].n_channels)
2658                 priv->hw->wiphy->bands[IEEE80211_BAND_5GHZ] =
2659                         &priv->bands[IEEE80211_BAND_5GHZ];
2660
2661         ret = ieee80211_register_hw(priv->hw);
2662         if (ret) {
2663                 IWL_ERR(priv, "Failed to register hw (error %d)\n", ret);
2664                 return ret;
2665         }
2666         priv->mac80211_registered = 1;
2667
2668         return 0;
2669 }
2670
2671
2672 static int iwl_mac_start(struct ieee80211_hw *hw)
2673 {
2674         struct iwl_priv *priv = hw->priv;
2675         int ret;
2676
2677         IWL_DEBUG_MAC80211(priv, "enter\n");
2678
2679         /* we should be verifying the device is ready to be opened */
2680         mutex_lock(&priv->mutex);
2681
2682         /* fetch ucode file from disk, alloc and copy to bus-master buffers ...
2683          * ucode filename and max sizes are card-specific. */
2684
2685         if (!priv->ucode_code.len) {
2686                 ret = iwl_read_ucode(priv);
2687                 if (ret) {
2688                         IWL_ERR(priv, "Could not read microcode: %d\n", ret);
2689                         mutex_unlock(&priv->mutex);
2690                         return ret;
2691                 }
2692         }
2693
2694         ret = __iwl_up(priv);
2695
2696         mutex_unlock(&priv->mutex);
2697
2698         if (ret)
2699                 return ret;
2700
2701         if (iwl_is_rfkill(priv))
2702                 goto out;
2703
2704         IWL_DEBUG_INFO(priv, "Start UP work done.\n");
2705
2706         /* Wait for START_ALIVE from Run Time ucode. Otherwise callbacks from
2707          * mac80211 will not be run successfully. */
2708         ret = wait_event_interruptible_timeout(priv->wait_command_queue,
2709                         test_bit(STATUS_READY, &priv->status),
2710                         UCODE_READY_TIMEOUT);
2711         if (!ret) {
2712                 if (!test_bit(STATUS_READY, &priv->status)) {
2713                         IWL_ERR(priv, "START_ALIVE timeout after %dms.\n",
2714                                 jiffies_to_msecs(UCODE_READY_TIMEOUT));
2715                         return -ETIMEDOUT;
2716                 }
2717         }
2718
2719         iwl_led_start(priv);
2720
2721 out:
2722         priv->is_open = 1;
2723         IWL_DEBUG_MAC80211(priv, "leave\n");
2724         return 0;
2725 }
2726
2727 static void iwl_mac_stop(struct ieee80211_hw *hw)
2728 {
2729         struct iwl_priv *priv = hw->priv;
2730
2731         IWL_DEBUG_MAC80211(priv, "enter\n");
2732
2733         if (!priv->is_open)
2734                 return;
2735
2736         priv->is_open = 0;
2737
2738         if (iwl_is_ready_rf(priv) || test_bit(STATUS_SCAN_HW, &priv->status)) {
2739                 /* stop mac, cancel any scan request and clear
2740                  * RXON_FILTER_ASSOC_MSK BIT
2741                  */
2742                 mutex_lock(&priv->mutex);
2743                 iwl_scan_cancel_timeout(priv, 100);
2744                 mutex_unlock(&priv->mutex);
2745         }
2746
2747         iwl_down(priv);
2748
2749         flush_workqueue(priv->workqueue);
2750
2751         /* enable interrupts again in order to receive rfkill changes */
2752         iwl_write32(priv, CSR_INT, 0xFFFFFFFF);
2753         iwl_enable_interrupts(priv);
2754
2755         IWL_DEBUG_MAC80211(priv, "leave\n");
2756 }
2757
2758 static int iwl_mac_tx(struct ieee80211_hw *hw, struct sk_buff *skb)
2759 {
2760         struct iwl_priv *priv = hw->priv;
2761
2762         IWL_DEBUG_MACDUMP(priv, "enter\n");
2763
2764         IWL_DEBUG_TX(priv, "dev->xmit(%d bytes) at rate 0x%02x\n", skb->len,
2765                      ieee80211_get_tx_rate(hw, IEEE80211_SKB_CB(skb))->bitrate);
2766
2767         if (iwl_tx_skb(priv, skb))
2768                 dev_kfree_skb_any(skb);
2769
2770         IWL_DEBUG_MACDUMP(priv, "leave\n");
2771         return NETDEV_TX_OK;
2772 }
2773
2774 void iwl_config_ap(struct iwl_priv *priv)
2775 {
2776         int ret = 0;
2777         unsigned long flags;
2778
2779         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
2780                 return;
2781
2782         /* The following should be done only at AP bring up */
2783         if (!iwl_is_associated(priv)) {
2784
2785                 /* RXON - unassoc (to set timing command) */
2786                 priv->staging_rxon.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
2787                 iwlcore_commit_rxon(priv);
2788
2789                 /* RXON Timing */
2790                 iwl_setup_rxon_timing(priv);
2791                 ret = iwl_send_cmd_pdu(priv, REPLY_RXON_TIMING,
2792                                 sizeof(priv->rxon_timing), &priv->rxon_timing);
2793                 if (ret)
2794                         IWL_WARN(priv, "REPLY_RXON_TIMING failed - "
2795                                         "Attempting to continue.\n");
2796
2797                 /* AP has all antennas */
2798                 priv->chain_noise_data.active_chains =
2799                         priv->hw_params.valid_rx_ant;
2800                 iwl_set_rxon_ht(priv, &priv->current_ht_config);
2801                 if (priv->cfg->ops->hcmd->set_rxon_chain)
2802                         priv->cfg->ops->hcmd->set_rxon_chain(priv);
2803
2804                 /* FIXME: what should be the assoc_id for AP? */
2805                 priv->staging_rxon.assoc_id = cpu_to_le16(priv->assoc_id);
2806                 if (priv->assoc_capability & WLAN_CAPABILITY_SHORT_PREAMBLE)
2807                         priv->staging_rxon.flags |=
2808                                 RXON_FLG_SHORT_PREAMBLE_MSK;
2809                 else
2810                         priv->staging_rxon.flags &=
2811                                 ~RXON_FLG_SHORT_PREAMBLE_MSK;
2812
2813                 if (priv->staging_rxon.flags & RXON_FLG_BAND_24G_MSK) {
2814                         if (priv->assoc_capability &
2815                                 WLAN_CAPABILITY_SHORT_SLOT_TIME)
2816                                 priv->staging_rxon.flags |=
2817                                         RXON_FLG_SHORT_SLOT_MSK;
2818                         else
2819                                 priv->staging_rxon.flags &=
2820                                         ~RXON_FLG_SHORT_SLOT_MSK;
2821
2822                         if (priv->iw_mode == NL80211_IFTYPE_ADHOC)
2823                                 priv->staging_rxon.flags &=
2824                                         ~RXON_FLG_SHORT_SLOT_MSK;
2825                 }
2826                 /* restore RXON assoc */
2827                 priv->staging_rxon.filter_flags |= RXON_FILTER_ASSOC_MSK;
2828                 iwlcore_commit_rxon(priv);
2829                 iwl_reset_qos(priv);
2830                 spin_lock_irqsave(&priv->lock, flags);
2831                 iwl_activate_qos(priv, 1);
2832                 spin_unlock_irqrestore(&priv->lock, flags);
2833                 iwl_add_bcast_station(priv);
2834         }
2835         iwl_send_beacon_cmd(priv);
2836
2837         /* FIXME - we need to add code here to detect a totally new
2838          * configuration, reset the AP, unassoc, rxon timing, assoc,
2839          * clear sta table, add BCAST sta... */
2840 }
2841
2842 static void iwl_mac_update_tkip_key(struct ieee80211_hw *hw,
2843                                     struct ieee80211_vif *vif,
2844                                     struct ieee80211_key_conf *keyconf,
2845                                     struct ieee80211_sta *sta,
2846                                     u32 iv32, u16 *phase1key)
2847 {
2848
2849         struct iwl_priv *priv = hw->priv;
2850         IWL_DEBUG_MAC80211(priv, "enter\n");
2851
2852         iwl_update_tkip_key(priv, keyconf,
2853                             sta ? sta->addr : iwl_bcast_addr,
2854                             iv32, phase1key);
2855
2856         IWL_DEBUG_MAC80211(priv, "leave\n");
2857 }
2858
2859 static int iwl_mac_set_key(struct ieee80211_hw *hw, enum set_key_cmd cmd,
2860                            struct ieee80211_vif *vif,
2861                            struct ieee80211_sta *sta,
2862                            struct ieee80211_key_conf *key)
2863 {
2864         struct iwl_priv *priv = hw->priv;
2865         const u8 *addr;
2866         int ret;
2867         u8 sta_id;
2868         bool is_default_wep_key = false;
2869
2870         IWL_DEBUG_MAC80211(priv, "enter\n");
2871
2872         if (priv->cfg->mod_params->sw_crypto) {
2873                 IWL_DEBUG_MAC80211(priv, "leave - hwcrypto disabled\n");
2874                 return -EOPNOTSUPP;
2875         }
2876         addr = sta ? sta->addr : iwl_bcast_addr;
2877         sta_id = iwl_find_station(priv, addr);
2878         if (sta_id == IWL_INVALID_STATION) {
2879                 IWL_DEBUG_MAC80211(priv, "leave - %pM not in station map.\n",
2880                                    addr);
2881                 return -EINVAL;
2882
2883         }
2884
2885         mutex_lock(&priv->mutex);
2886         iwl_scan_cancel_timeout(priv, 100);
2887         mutex_unlock(&priv->mutex);
2888
2889         /* If we are getting WEP group key and we didn't receive any key mapping
2890          * so far, we are in legacy wep mode (group key only), otherwise we are
2891          * in 1X mode.
2892          * In legacy wep mode, we use another host command to the uCode */
2893         if (key->alg == ALG_WEP && sta_id == priv->hw_params.bcast_sta_id &&
2894                 priv->iw_mode != NL80211_IFTYPE_AP) {
2895                 if (cmd == SET_KEY)
2896                         is_default_wep_key = !priv->key_mapping_key;
2897                 else
2898                         is_default_wep_key =
2899                                         (key->hw_key_idx == HW_KEY_DEFAULT);
2900         }
2901
2902         switch (cmd) {
2903         case SET_KEY:
2904                 if (is_default_wep_key)
2905                         ret = iwl_set_default_wep_key(priv, key);
2906                 else
2907                         ret = iwl_set_dynamic_key(priv, key, sta_id);
2908
2909                 IWL_DEBUG_MAC80211(priv, "enable hwcrypto key\n");
2910                 break;
2911         case DISABLE_KEY:
2912                 if (is_default_wep_key)
2913                         ret = iwl_remove_default_wep_key(priv, key);
2914                 else
2915                         ret = iwl_remove_dynamic_key(priv, key, sta_id);
2916
2917                 IWL_DEBUG_MAC80211(priv, "disable hwcrypto key\n");
2918                 break;
2919         default:
2920                 ret = -EINVAL;
2921         }
2922
2923         IWL_DEBUG_MAC80211(priv, "leave\n");
2924
2925         return ret;
2926 }
2927
2928 static int iwl_mac_ampdu_action(struct ieee80211_hw *hw,
2929                                 struct ieee80211_vif *vif,
2930                              enum ieee80211_ampdu_mlme_action action,
2931                              struct ieee80211_sta *sta, u16 tid, u16 *ssn)
2932 {
2933         struct iwl_priv *priv = hw->priv;
2934         int ret;
2935
2936         IWL_DEBUG_HT(priv, "A-MPDU action on addr %pM tid %d\n",
2937                      sta->addr, tid);
2938
2939         if (!(priv->cfg->sku & IWL_SKU_N))
2940                 return -EACCES;
2941
2942         switch (action) {
2943         case IEEE80211_AMPDU_RX_START:
2944                 IWL_DEBUG_HT(priv, "start Rx\n");
2945                 return iwl_sta_rx_agg_start(priv, sta->addr, tid, *ssn);
2946         case IEEE80211_AMPDU_RX_STOP:
2947                 IWL_DEBUG_HT(priv, "stop Rx\n");
2948                 ret = iwl_sta_rx_agg_stop(priv, sta->addr, tid);
2949                 if (test_bit(STATUS_EXIT_PENDING, &priv->status))
2950                         return 0;
2951                 else
2952                         return ret;
2953         case IEEE80211_AMPDU_TX_START:
2954                 IWL_DEBUG_HT(priv, "start Tx\n");
2955                 return iwl_tx_agg_start(priv, sta->addr, tid, ssn);
2956         case IEEE80211_AMPDU_TX_STOP:
2957                 IWL_DEBUG_HT(priv, "stop Tx\n");
2958                 ret = iwl_tx_agg_stop(priv, sta->addr, tid);
2959                 if (test_bit(STATUS_EXIT_PENDING, &priv->status))
2960                         return 0;
2961                 else
2962                         return ret;
2963         case IEEE80211_AMPDU_TX_OPERATIONAL:
2964                 /* do nothing */
2965                 return -EOPNOTSUPP;
2966         default:
2967                 IWL_DEBUG_HT(priv, "unknown\n");
2968                 return -EINVAL;
2969                 break;
2970         }
2971         return 0;
2972 }
2973
2974 static int iwl_mac_get_stats(struct ieee80211_hw *hw,
2975                              struct ieee80211_low_level_stats *stats)
2976 {
2977         struct iwl_priv *priv = hw->priv;
2978
2979         priv = hw->priv;
2980         IWL_DEBUG_MAC80211(priv, "enter\n");
2981         IWL_DEBUG_MAC80211(priv, "leave\n");
2982
2983         return 0;
2984 }
2985
2986 static void iwl_mac_sta_notify(struct ieee80211_hw *hw,
2987                                struct ieee80211_vif *vif,
2988                                enum sta_notify_cmd cmd,
2989                                struct ieee80211_sta *sta)
2990 {
2991         struct iwl_priv *priv = hw->priv;
2992         struct iwl_station_priv *sta_priv = (void *)sta->drv_priv;
2993         int sta_id;
2994
2995         /*
2996          * TODO: We really should use this callback to
2997          *       actually maintain the station table in
2998          *       the device.
2999          */
3000
3001         switch (cmd) {
3002         case STA_NOTIFY_ADD:
3003                 atomic_set(&sta_priv->pending_frames, 0);
3004                 if (vif->type == NL80211_IFTYPE_AP)
3005                         sta_priv->client = true;
3006                 break;
3007         case STA_NOTIFY_SLEEP:
3008                 WARN_ON(!sta_priv->client);
3009                 sta_priv->asleep = true;
3010                 if (atomic_read(&sta_priv->pending_frames) > 0)
3011                         ieee80211_sta_block_awake(hw, sta, true);
3012                 break;
3013         case STA_NOTIFY_AWAKE:
3014                 WARN_ON(!sta_priv->client);
3015                 sta_priv->asleep = false;
3016                 sta_id = iwl_find_station(priv, sta->addr);
3017                 if (sta_id != IWL_INVALID_STATION)
3018                         iwl_sta_modify_ps_wake(priv, sta_id);
3019                 break;
3020         default:
3021                 break;
3022         }
3023 }
3024
3025 /*****************************************************************************
3026  *
3027  * sysfs attributes
3028  *
3029  *****************************************************************************/
3030
3031 #ifdef CONFIG_IWLWIFI_DEBUG
3032
3033 /*
3034  * The following adds a new attribute to the sysfs representation
3035  * of this device driver (i.e. a new file in /sys/class/net/wlan0/device/)
3036  * used for controlling the debug level.
3037  *
3038  * See the level definitions in iwl for details.
3039  *
3040  * The debug_level being managed using sysfs below is a per device debug
3041  * level that is used instead of the global debug level if it (the per
3042  * device debug level) is set.
3043  */
3044 static ssize_t show_debug_level(struct device *d,
3045                                 struct device_attribute *attr, char *buf)
3046 {
3047         struct iwl_priv *priv = dev_get_drvdata(d);
3048         return sprintf(buf, "0x%08X\n", iwl_get_debug_level(priv));
3049 }
3050 static ssize_t store_debug_level(struct device *d,
3051                                 struct device_attribute *attr,
3052                                  const char *buf, size_t count)
3053 {
3054         struct iwl_priv *priv = dev_get_drvdata(d);
3055         unsigned long val;
3056         int ret;
3057
3058         ret = strict_strtoul(buf, 0, &val);
3059         if (ret)
3060                 IWL_ERR(priv, "%s is not in hex or decimal form.\n", buf);
3061         else {
3062                 priv->debug_level = val;
3063                 if (iwl_alloc_traffic_mem(priv))
3064                         IWL_ERR(priv,
3065                                 "Not enough memory to generate traffic log\n");
3066         }
3067         return strnlen(buf, count);
3068 }
3069
3070 static DEVICE_ATTR(debug_level, S_IWUSR | S_IRUGO,
3071                         show_debug_level, store_debug_level);
3072
3073
3074 #endif /* CONFIG_IWLWIFI_DEBUG */
3075
3076
3077 static ssize_t show_temperature(struct device *d,
3078                                 struct device_attribute *attr, char *buf)
3079 {
3080         struct iwl_priv *priv = dev_get_drvdata(d);
3081
3082         if (!iwl_is_alive(priv))
3083                 return -EAGAIN;
3084
3085         return sprintf(buf, "%d\n", priv->temperature);
3086 }
3087
3088 static DEVICE_ATTR(temperature, S_IRUGO, show_temperature, NULL);
3089
3090 static ssize_t show_tx_power(struct device *d,
3091                              struct device_attribute *attr, char *buf)
3092 {
3093         struct iwl_priv *priv = dev_get_drvdata(d);
3094
3095         if (!iwl_is_ready_rf(priv))
3096                 return sprintf(buf, "off\n");
3097         else
3098                 return sprintf(buf, "%d\n", priv->tx_power_user_lmt);
3099 }
3100
3101 static ssize_t store_tx_power(struct device *d,
3102                               struct device_attribute *attr,
3103                               const char *buf, size_t count)
3104 {
3105         struct iwl_priv *priv = dev_get_drvdata(d);
3106         unsigned long val;
3107         int ret;
3108
3109         ret = strict_strtoul(buf, 10, &val);
3110         if (ret)
3111                 IWL_INFO(priv, "%s is not in decimal form.\n", buf);
3112         else {
3113                 ret = iwl_set_tx_power(priv, val, false);
3114                 if (ret)
3115                         IWL_ERR(priv, "failed setting tx power (0x%d).\n",
3116                                 ret);
3117                 else
3118                         ret = count;
3119         }
3120         return ret;
3121 }
3122
3123 static DEVICE_ATTR(tx_power, S_IWUSR | S_IRUGO, show_tx_power, store_tx_power);
3124
3125 static ssize_t show_flags(struct device *d,
3126                           struct device_attribute *attr, char *buf)
3127 {
3128         struct iwl_priv *priv = dev_get_drvdata(d);
3129
3130         return sprintf(buf, "0x%04X\n", priv->active_rxon.flags);
3131 }
3132
3133 static ssize_t store_flags(struct device *d,
3134                            struct device_attribute *attr,
3135                            const char *buf, size_t count)
3136 {
3137         struct iwl_priv *priv = dev_get_drvdata(d);
3138         unsigned long val;
3139         u32 flags;
3140         int ret = strict_strtoul(buf, 0, &val);
3141         if (ret)
3142                 return ret;
3143         flags = (u32)val;
3144
3145         mutex_lock(&priv->mutex);
3146         if (le32_to_cpu(priv->staging_rxon.flags) != flags) {
3147                 /* Cancel any currently running scans... */
3148                 if (iwl_scan_cancel_timeout(priv, 100))
3149                         IWL_WARN(priv, "Could not cancel scan.\n");
3150                 else {
3151                         IWL_DEBUG_INFO(priv, "Commit rxon.flags = 0x%04X\n", flags);
3152                         priv->staging_rxon.flags = cpu_to_le32(flags);
3153                         iwlcore_commit_rxon(priv);
3154                 }
3155         }
3156         mutex_unlock(&priv->mutex);
3157
3158         return count;
3159 }
3160
3161 static DEVICE_ATTR(flags, S_IWUSR | S_IRUGO, show_flags, store_flags);
3162
3163 static ssize_t show_filter_flags(struct device *d,
3164                                  struct device_attribute *attr, char *buf)
3165 {
3166         struct iwl_priv *priv = dev_get_drvdata(d);
3167
3168         return sprintf(buf, "0x%04X\n",
3169                 le32_to_cpu(priv->active_rxon.filter_flags));
3170 }
3171
3172 static ssize_t store_filter_flags(struct device *d,
3173                                   struct device_attribute *attr,
3174                                   const char *buf, size_t count)
3175 {
3176         struct iwl_priv *priv = dev_get_drvdata(d);
3177         unsigned long val;
3178         u32 filter_flags;
3179         int ret = strict_strtoul(buf, 0, &val);
3180         if (ret)
3181                 return ret;
3182         filter_flags = (u32)val;
3183
3184         mutex_lock(&priv->mutex);
3185         if (le32_to_cpu(priv->staging_rxon.filter_flags) != filter_flags) {
3186                 /* Cancel any currently running scans... */
3187                 if (iwl_scan_cancel_timeout(priv, 100))
3188                         IWL_WARN(priv, "Could not cancel scan.\n");
3189                 else {
3190                         IWL_DEBUG_INFO(priv, "Committing rxon.filter_flags = "
3191                                        "0x%04X\n", filter_flags);
3192                         priv->staging_rxon.filter_flags =
3193                                 cpu_to_le32(filter_flags);
3194                         iwlcore_commit_rxon(priv);
3195                 }
3196         }
3197         mutex_unlock(&priv->mutex);
3198
3199         return count;
3200 }
3201
3202 static DEVICE_ATTR(filter_flags, S_IWUSR | S_IRUGO, show_filter_flags,
3203                    store_filter_flags);
3204
3205
3206 static ssize_t show_statistics(struct device *d,
3207                                struct device_attribute *attr, char *buf)
3208 {
3209         struct iwl_priv *priv = dev_get_drvdata(d);
3210         u32 size = sizeof(struct iwl_notif_statistics);
3211         u32 len = 0, ofs = 0;
3212         u8 *data = (u8 *)&priv->statistics;
3213         int rc = 0;
3214
3215         if (!iwl_is_alive(priv))
3216                 return -EAGAIN;
3217
3218         mutex_lock(&priv->mutex);
3219         rc = iwl_send_statistics_request(priv, CMD_SYNC, false);
3220         mutex_unlock(&priv->mutex);
3221
3222         if (rc) {
3223                 len = sprintf(buf,
3224                               "Error sending statistics request: 0x%08X\n", rc);
3225                 return len;
3226         }
3227
3228         while (size && (PAGE_SIZE - len)) {
3229                 hex_dump_to_buffer(data + ofs, size, 16, 1, buf + len,
3230                                    PAGE_SIZE - len, 1);
3231                 len = strlen(buf);
3232                 if (PAGE_SIZE - len)
3233                         buf[len++] = '\n';
3234
3235                 ofs += 16;
3236                 size -= min(size, 16U);
3237         }
3238
3239         return len;
3240 }
3241
3242 static DEVICE_ATTR(statistics, S_IRUGO, show_statistics, NULL);
3243
3244 static ssize_t show_rts_ht_protection(struct device *d,
3245                              struct device_attribute *attr, char *buf)
3246 {
3247         struct iwl_priv *priv = dev_get_drvdata(d);
3248
3249         return sprintf(buf, "%s\n",
3250                 priv->cfg->use_rts_for_ht ? "RTS/CTS" : "CTS-to-self");
3251 }
3252
3253 static ssize_t store_rts_ht_protection(struct device *d,
3254                               struct device_attribute *attr,
3255                               const char *buf, size_t count)
3256 {
3257         struct iwl_priv *priv = dev_get_drvdata(d);
3258         unsigned long val;
3259         int ret;
3260
3261         ret = strict_strtoul(buf, 10, &val);
3262         if (ret)
3263                 IWL_INFO(priv, "Input is not in decimal form.\n");
3264         else {
3265                 if (!iwl_is_associated(priv))
3266                         priv->cfg->use_rts_for_ht = val ? true : false;
3267                 else
3268                         IWL_ERR(priv, "Sta associated with AP - "
3269                                 "Change protection mechanism is not allowed\n");
3270                 ret = count;
3271         }
3272         return ret;
3273 }
3274
3275 static DEVICE_ATTR(rts_ht_protection, S_IWUSR | S_IRUGO,
3276                         show_rts_ht_protection, store_rts_ht_protection);
3277
3278
3279 /*****************************************************************************
3280  *
3281  * driver setup and teardown
3282  *
3283  *****************************************************************************/
3284
3285 static void iwl_setup_deferred_work(struct iwl_priv *priv)
3286 {
3287         priv->workqueue = create_singlethread_workqueue(DRV_NAME);
3288
3289         init_waitqueue_head(&priv->wait_command_queue);
3290
3291         INIT_WORK(&priv->up, iwl_bg_up);
3292         INIT_WORK(&priv->restart, iwl_bg_restart);
3293         INIT_WORK(&priv->rx_replenish, iwl_bg_rx_replenish);
3294         INIT_WORK(&priv->beacon_update, iwl_bg_beacon_update);
3295         INIT_WORK(&priv->run_time_calib_work, iwl_bg_run_time_calib_work);
3296         INIT_DELAYED_WORK(&priv->init_alive_start, iwl_bg_init_alive_start);
3297         INIT_DELAYED_WORK(&priv->alive_start, iwl_bg_alive_start);
3298
3299         iwl_setup_scan_deferred_work(priv);
3300
3301         if (priv->cfg->ops->lib->setup_deferred_work)
3302                 priv->cfg->ops->lib->setup_deferred_work(priv);
3303
3304         init_timer(&priv->statistics_periodic);
3305         priv->statistics_periodic.data = (unsigned long)priv;
3306         priv->statistics_periodic.function = iwl_bg_statistics_periodic;
3307
3308         init_timer(&priv->ucode_trace);
3309         priv->ucode_trace.data = (unsigned long)priv;
3310         priv->ucode_trace.function = iwl_bg_ucode_trace;
3311
3312         if (!priv->cfg->use_isr_legacy)
3313                 tasklet_init(&priv->irq_tasklet, (void (*)(unsigned long))
3314                         iwl_irq_tasklet, (unsigned long)priv);
3315         else
3316                 tasklet_init(&priv->irq_tasklet, (void (*)(unsigned long))
3317                         iwl_irq_tasklet_legacy, (unsigned long)priv);
3318 }
3319
3320 static void iwl_cancel_deferred_work(struct iwl_priv *priv)
3321 {
3322         if (priv->cfg->ops->lib->cancel_deferred_work)
3323                 priv->cfg->ops->lib->cancel_deferred_work(priv);
3324
3325         cancel_delayed_work_sync(&priv->init_alive_start);
3326         cancel_delayed_work(&priv->scan_check);
3327         cancel_delayed_work(&priv->alive_start);
3328         cancel_work_sync(&priv->beacon_update);
3329         del_timer_sync(&priv->statistics_periodic);
3330         del_timer_sync(&priv->ucode_trace);
3331 }
3332
3333 static void iwl_init_hw_rates(struct iwl_priv *priv,
3334                               struct ieee80211_rate *rates)
3335 {
3336         int i;
3337
3338         for (i = 0; i < IWL_RATE_COUNT_LEGACY; i++) {
3339                 rates[i].bitrate = iwl_rates[i].ieee * 5;
3340                 rates[i].hw_value = i; /* Rate scaling will work on indexes */
3341                 rates[i].hw_value_short = i;
3342                 rates[i].flags = 0;
3343                 if ((i >= IWL_FIRST_CCK_RATE) && (i <= IWL_LAST_CCK_RATE)) {
3344                         /*
3345                          * If CCK != 1M then set short preamble rate flag.
3346                          */
3347                         rates[i].flags |=
3348                                 (iwl_rates[i].plcp == IWL_RATE_1M_PLCP) ?
3349                                         0 : IEEE80211_RATE_SHORT_PREAMBLE;
3350                 }
3351         }
3352 }
3353
3354 static int iwl_init_drv(struct iwl_priv *priv)
3355 {
3356         int ret;
3357
3358         priv->ibss_beacon = NULL;
3359
3360         spin_lock_init(&priv->sta_lock);
3361         spin_lock_init(&priv->hcmd_lock);
3362
3363         INIT_LIST_HEAD(&priv->free_frames);
3364
3365         mutex_init(&priv->mutex);
3366
3367         /* Clear the driver's (not device's) station table */
3368         iwl_clear_stations_table(priv);
3369
3370         priv->ieee_channels = NULL;
3371         priv->ieee_rates = NULL;
3372         priv->band = IEEE80211_BAND_2GHZ;
3373
3374         priv->iw_mode = NL80211_IFTYPE_STATION;
3375         priv->current_ht_config.smps = IEEE80211_SMPS_STATIC;
3376         priv->missed_beacon_threshold = IWL_MISSED_BEACON_THRESHOLD_DEF;
3377
3378         /* Choose which receivers/antennas to use */
3379         if (priv->cfg->ops->hcmd->set_rxon_chain)
3380                 priv->cfg->ops->hcmd->set_rxon_chain(priv);
3381
3382         iwl_init_scan_params(priv);
3383
3384         iwl_reset_qos(priv);
3385
3386         priv->qos_data.qos_active = 0;
3387         priv->qos_data.qos_cap.val = 0;
3388
3389         priv->rates_mask = IWL_RATES_MASK;
3390         /* Set the tx_power_user_lmt to the lowest power level
3391          * this value will get overwritten by channel max power avg
3392          * from eeprom */
3393         priv->tx_power_user_lmt = IWL_TX_POWER_TARGET_POWER_MIN;
3394
3395         ret = iwl_init_channel_map(priv);
3396         if (ret) {
3397                 IWL_ERR(priv, "initializing regulatory failed: %d\n", ret);
3398                 goto err;
3399         }
3400
3401         ret = iwlcore_init_geos(priv);
3402         if (ret) {
3403                 IWL_ERR(priv, "initializing geos failed: %d\n", ret);
3404                 goto err_free_channel_map;
3405         }
3406         iwl_init_hw_rates(priv, priv->ieee_rates);
3407
3408         return 0;
3409
3410 err_free_channel_map:
3411         iwl_free_channel_map(priv);
3412 err:
3413         return ret;
3414 }
3415
3416 static void iwl_uninit_drv(struct iwl_priv *priv)
3417 {
3418         iwl_calib_free_results(priv);
3419         iwlcore_free_geos(priv);
3420         iwl_free_channel_map(priv);
3421         kfree(priv->scan);
3422 }
3423
3424 static struct attribute *iwl_sysfs_entries[] = {
3425         &dev_attr_flags.attr,
3426         &dev_attr_filter_flags.attr,
3427         &dev_attr_statistics.attr,
3428         &dev_attr_temperature.attr,
3429         &dev_attr_tx_power.attr,
3430         &dev_attr_rts_ht_protection.attr,
3431 #ifdef CONFIG_IWLWIFI_DEBUG
3432         &dev_attr_debug_level.attr,
3433 #endif
3434         NULL
3435 };
3436
3437 static struct attribute_group iwl_attribute_group = {
3438         .name = NULL,           /* put in device directory */
3439         .attrs = iwl_sysfs_entries,
3440 };
3441
3442 static struct ieee80211_ops iwl_hw_ops = {
3443         .tx = iwl_mac_tx,
3444         .start = iwl_mac_start,
3445         .stop = iwl_mac_stop,
3446         .add_interface = iwl_mac_add_interface,
3447         .remove_interface = iwl_mac_remove_interface,
3448         .config = iwl_mac_config,
3449         .configure_filter = iwl_configure_filter,
3450         .set_key = iwl_mac_set_key,
3451         .update_tkip_key = iwl_mac_update_tkip_key,
3452         .get_stats = iwl_mac_get_stats,
3453         .get_tx_stats = iwl_mac_get_tx_stats,
3454         .conf_tx = iwl_mac_conf_tx,
3455         .reset_tsf = iwl_mac_reset_tsf,
3456         .bss_info_changed = iwl_bss_info_changed,
3457         .ampdu_action = iwl_mac_ampdu_action,
3458         .hw_scan = iwl_mac_hw_scan,
3459         .sta_notify = iwl_mac_sta_notify,
3460 };
3461
3462 static int iwl_pci_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
3463 {
3464         int err = 0;
3465         struct iwl_priv *priv;
3466         struct ieee80211_hw *hw;
3467         struct iwl_cfg *cfg = (struct iwl_cfg *)(ent->driver_data);
3468         unsigned long flags;
3469         u16 pci_cmd;
3470
3471         /************************
3472          * 1. Allocating HW data
3473          ************************/
3474
3475         /* Disabling hardware scan means that mac80211 will perform scans
3476          * "the hard way", rather than using device's scan. */
3477         if (cfg->mod_params->disable_hw_scan) {
3478                 if (iwl_debug_level & IWL_DL_INFO)
3479                         dev_printk(KERN_DEBUG, &(pdev->dev),
3480                                    "Disabling hw_scan\n");
3481                 iwl_hw_ops.hw_scan = NULL;
3482         }
3483
3484         hw = iwl_alloc_all(cfg, &iwl_hw_ops);
3485         if (!hw) {
3486                 err = -ENOMEM;
3487                 goto out;
3488         }
3489         priv = hw->priv;
3490         /* At this point both hw and priv are allocated. */
3491
3492         SET_IEEE80211_DEV(hw, &pdev->dev);
3493
3494         IWL_DEBUG_INFO(priv, "*** LOAD DRIVER ***\n");
3495         priv->cfg = cfg;
3496         priv->pci_dev = pdev;
3497         priv->inta_mask = CSR_INI_SET_MASK;
3498
3499 #ifdef CONFIG_IWLWIFI_DEBUG
3500         atomic_set(&priv->restrict_refcnt, 0);
3501 #endif
3502         if (iwl_alloc_traffic_mem(priv))
3503                 IWL_ERR(priv, "Not enough memory to generate traffic log\n");
3504
3505         /**************************
3506          * 2. Initializing PCI bus
3507          **************************/
3508         if (pci_enable_device(pdev)) {
3509                 err = -ENODEV;
3510                 goto out_ieee80211_free_hw;
3511         }
3512
3513         pci_set_master(pdev);
3514
3515         err = pci_set_dma_mask(pdev, DMA_BIT_MASK(36));
3516         if (!err)
3517                 err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(36));
3518         if (err) {
3519                 err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
3520                 if (!err)
3521                         err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
3522                 /* both attempts failed: */
3523                 if (err) {
3524                         IWL_WARN(priv, "No suitable DMA available.\n");
3525                         goto out_pci_disable_device;
3526                 }
3527         }
3528
3529         err = pci_request_regions(pdev, DRV_NAME);
3530         if (err)
3531                 goto out_pci_disable_device;
3532
3533         pci_set_drvdata(pdev, priv);
3534
3535
3536         /***********************
3537          * 3. Read REV register
3538          ***********************/
3539         priv->hw_base = pci_iomap(pdev, 0, 0);
3540         if (!priv->hw_base) {
3541                 err = -ENODEV;
3542                 goto out_pci_release_regions;
3543         }
3544
3545         IWL_DEBUG_INFO(priv, "pci_resource_len = 0x%08llx\n",
3546                 (unsigned long long) pci_resource_len(pdev, 0));
3547         IWL_DEBUG_INFO(priv, "pci_resource_base = %p\n", priv->hw_base);
3548
3549         /* these spin locks will be used in apm_ops.init and EEPROM access
3550          * we should init now
3551          */
3552         spin_lock_init(&priv->reg_lock);
3553         spin_lock_init(&priv->lock);
3554         iwl_hw_detect(priv);
3555         IWL_INFO(priv, "Detected Intel Wireless WiFi Link %s REV=0x%X\n",
3556                 priv->cfg->name, priv->hw_rev);
3557
3558         /* We disable the RETRY_TIMEOUT register (0x41) to keep
3559          * PCI Tx retries from interfering with C3 CPU state */
3560         pci_write_config_byte(pdev, PCI_CFG_RETRY_TIMEOUT, 0x00);
3561
3562         iwl_prepare_card_hw(priv);
3563         if (!priv->hw_ready) {
3564                 IWL_WARN(priv, "Failed, HW not ready\n");
3565                 goto out_iounmap;
3566         }
3567
3568         /*****************
3569          * 4. Read EEPROM
3570          *****************/
3571         /* Read the EEPROM */
3572         err = iwl_eeprom_init(priv);
3573         if (err) {
3574                 IWL_ERR(priv, "Unable to init EEPROM\n");
3575                 goto out_iounmap;
3576         }
3577         err = iwl_eeprom_check_version(priv);
3578         if (err)
3579                 goto out_free_eeprom;
3580
3581         /* extract MAC Address */
3582         iwl_eeprom_get_mac(priv, priv->mac_addr);
3583         IWL_DEBUG_INFO(priv, "MAC address: %pM\n", priv->mac_addr);
3584         SET_IEEE80211_PERM_ADDR(priv->hw, priv->mac_addr);
3585
3586         /************************
3587          * 5. Setup HW constants
3588          ************************/
3589         if (iwl_set_hw_params(priv)) {
3590                 IWL_ERR(priv, "failed to set hw parameters\n");
3591                 goto out_free_eeprom;
3592         }
3593
3594         /*******************
3595          * 6. Setup priv
3596          *******************/
3597
3598         err = iwl_init_drv(priv);
3599         if (err)
3600                 goto out_free_eeprom;
3601         /* At this point both hw and priv are initialized. */
3602
3603         /********************
3604          * 7. Setup services
3605          ********************/
3606         spin_lock_irqsave(&priv->lock, flags);
3607         iwl_disable_interrupts(priv);
3608         spin_unlock_irqrestore(&priv->lock, flags);
3609
3610         pci_enable_msi(priv->pci_dev);
3611
3612         iwl_alloc_isr_ict(priv);
3613         err = request_irq(priv->pci_dev->irq, priv->cfg->ops->lib->isr,
3614                           IRQF_SHARED, DRV_NAME, priv);
3615         if (err) {
3616                 IWL_ERR(priv, "Error allocating IRQ %d\n", priv->pci_dev->irq);
3617                 goto out_disable_msi;
3618         }
3619         err = sysfs_create_group(&pdev->dev.kobj, &iwl_attribute_group);
3620         if (err) {
3621                 IWL_ERR(priv, "failed to create sysfs device attributes\n");
3622                 goto out_free_irq;
3623         }
3624
3625         iwl_setup_deferred_work(priv);
3626         iwl_setup_rx_handlers(priv);
3627
3628         /*********************************************
3629          * 8. Enable interrupts and read RFKILL state
3630          *********************************************/
3631
3632         /* enable interrupts if needed: hw bug w/a */
3633         pci_read_config_word(priv->pci_dev, PCI_COMMAND, &pci_cmd);
3634         if (pci_cmd & PCI_COMMAND_INTX_DISABLE) {
3635                 pci_cmd &= ~PCI_COMMAND_INTX_DISABLE;
3636                 pci_write_config_word(priv->pci_dev, PCI_COMMAND, pci_cmd);
3637         }
3638
3639         iwl_enable_interrupts(priv);
3640
3641         /* If platform's RF_KILL switch is NOT set to KILL */
3642         if (iwl_read32(priv, CSR_GP_CNTRL) & CSR_GP_CNTRL_REG_FLAG_HW_RF_KILL_SW)
3643                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
3644         else
3645                 set_bit(STATUS_RF_KILL_HW, &priv->status);
3646
3647         wiphy_rfkill_set_hw_state(priv->hw->wiphy,
3648                 test_bit(STATUS_RF_KILL_HW, &priv->status));
3649
3650         iwl_power_initialize(priv);
3651         iwl_tt_initialize(priv);
3652
3653         /**************************************************
3654          * 9. Setup and register with mac80211 and debugfs
3655          **************************************************/
3656         err = iwl_mac_setup_register(priv);
3657         if (err)
3658                 goto out_remove_sysfs;
3659
3660         err = iwl_dbgfs_register(priv, DRV_NAME);
3661         if (err)
3662                 IWL_ERR(priv, "failed to create debugfs files. Ignoring error: %d\n", err);
3663
3664         return 0;
3665
3666  out_remove_sysfs:
3667         destroy_workqueue(priv->workqueue);
3668         priv->workqueue = NULL;
3669         sysfs_remove_group(&pdev->dev.kobj, &iwl_attribute_group);
3670  out_free_irq:
3671         free_irq(priv->pci_dev->irq, priv);
3672         iwl_free_isr_ict(priv);
3673  out_disable_msi:
3674         pci_disable_msi(priv->pci_dev);
3675         iwl_uninit_drv(priv);
3676  out_free_eeprom:
3677         iwl_eeprom_free(priv);
3678  out_iounmap:
3679         pci_iounmap(pdev, priv->hw_base);
3680  out_pci_release_regions:
3681         pci_set_drvdata(pdev, NULL);
3682         pci_release_regions(pdev);
3683  out_pci_disable_device:
3684         pci_disable_device(pdev);
3685  out_ieee80211_free_hw:
3686         iwl_free_traffic_mem(priv);
3687         ieee80211_free_hw(priv->hw);
3688  out:
3689         return err;
3690 }
3691
3692 static void __devexit iwl_pci_remove(struct pci_dev *pdev)
3693 {
3694         struct iwl_priv *priv = pci_get_drvdata(pdev);
3695         unsigned long flags;
3696
3697         if (!priv)
3698                 return;
3699
3700         IWL_DEBUG_INFO(priv, "*** UNLOAD DRIVER ***\n");
3701
3702         iwl_dbgfs_unregister(priv);
3703         sysfs_remove_group(&pdev->dev.kobj, &iwl_attribute_group);
3704
3705         /* ieee80211_unregister_hw call wil cause iwl_mac_stop to
3706          * to be called and iwl_down since we are removing the device
3707          * we need to set STATUS_EXIT_PENDING bit.
3708          */
3709         set_bit(STATUS_EXIT_PENDING, &priv->status);
3710         if (priv->mac80211_registered) {
3711                 ieee80211_unregister_hw(priv->hw);
3712                 priv->mac80211_registered = 0;
3713         } else {
3714                 iwl_down(priv);
3715         }
3716
3717         /*
3718          * Make sure device is reset to low power before unloading driver.
3719          * This may be redundant with iwl_down(), but there are paths to
3720          * run iwl_down() without calling apm_ops.stop(), and there are
3721          * paths to avoid running iwl_down() at all before leaving driver.
3722          * This (inexpensive) call *makes sure* device is reset.
3723          */
3724         priv->cfg->ops->lib->apm_ops.stop(priv);
3725
3726         iwl_tt_exit(priv);
3727
3728         /* make sure we flush any pending irq or
3729          * tasklet for the driver
3730          */
3731         spin_lock_irqsave(&priv->lock, flags);
3732         iwl_disable_interrupts(priv);
3733         spin_unlock_irqrestore(&priv->lock, flags);
3734
3735         iwl_synchronize_irq(priv);
3736
3737         iwl_dealloc_ucode_pci(priv);
3738
3739         if (priv->rxq.bd)
3740                 iwl_rx_queue_free(priv, &priv->rxq);
3741         iwl_hw_txq_ctx_free(priv);
3742
3743         iwl_clear_stations_table(priv);
3744         iwl_eeprom_free(priv);
3745
3746
3747         /*netif_stop_queue(dev); */
3748         flush_workqueue(priv->workqueue);
3749
3750         /* ieee80211_unregister_hw calls iwl_mac_stop, which flushes
3751          * priv->workqueue... so we can't take down the workqueue
3752          * until now... */
3753         destroy_workqueue(priv->workqueue);
3754         priv->workqueue = NULL;
3755         iwl_free_traffic_mem(priv);
3756
3757         free_irq(priv->pci_dev->irq, priv);
3758         pci_disable_msi(priv->pci_dev);
3759         pci_iounmap(pdev, priv->hw_base);
3760         pci_release_regions(pdev);
3761         pci_disable_device(pdev);
3762         pci_set_drvdata(pdev, NULL);
3763
3764         iwl_uninit_drv(priv);
3765
3766         iwl_free_isr_ict(priv);
3767
3768         if (priv->ibss_beacon)
3769                 dev_kfree_skb(priv->ibss_beacon);
3770
3771         ieee80211_free_hw(priv->hw);
3772 }
3773
3774
3775 /*****************************************************************************
3776  *
3777  * driver and module entry point
3778  *
3779  *****************************************************************************/
3780
3781 /* Hardware specific file defines the PCI IDs table for that hardware module */
3782 static struct pci_device_id iwl_hw_card_ids[] = {
3783 #ifdef CONFIG_IWL4965
3784         {IWL_PCI_DEVICE(0x4229, PCI_ANY_ID, iwl4965_agn_cfg)},
3785         {IWL_PCI_DEVICE(0x4230, PCI_ANY_ID, iwl4965_agn_cfg)},
3786 #endif /* CONFIG_IWL4965 */
3787 #ifdef CONFIG_IWL5000
3788 /* 5100 Series WiFi */
3789         {IWL_PCI_DEVICE(0x4232, 0x1201, iwl5100_agn_cfg)}, /* Mini Card */
3790         {IWL_PCI_DEVICE(0x4232, 0x1301, iwl5100_agn_cfg)}, /* Half Mini Card */
3791         {IWL_PCI_DEVICE(0x4232, 0x1204, iwl5100_agn_cfg)}, /* Mini Card */
3792         {IWL_PCI_DEVICE(0x4232, 0x1304, iwl5100_agn_cfg)}, /* Half Mini Card */
3793         {IWL_PCI_DEVICE(0x4232, 0x1205, iwl5100_bgn_cfg)}, /* Mini Card */
3794         {IWL_PCI_DEVICE(0x4232, 0x1305, iwl5100_bgn_cfg)}, /* Half Mini Card */
3795         {IWL_PCI_DEVICE(0x4232, 0x1206, iwl5100_abg_cfg)}, /* Mini Card */
3796         {IWL_PCI_DEVICE(0x4232, 0x1306, iwl5100_abg_cfg)}, /* Half Mini Card */
3797         {IWL_PCI_DEVICE(0x4232, 0x1221, iwl5100_agn_cfg)}, /* Mini Card */
3798         {IWL_PCI_DEVICE(0x4232, 0x1321, iwl5100_agn_cfg)}, /* Half Mini Card */
3799         {IWL_PCI_DEVICE(0x4232, 0x1224, iwl5100_agn_cfg)}, /* Mini Card */
3800         {IWL_PCI_DEVICE(0x4232, 0x1324, iwl5100_agn_cfg)}, /* Half Mini Card */
3801         {IWL_PCI_DEVICE(0x4232, 0x1225, iwl5100_bgn_cfg)}, /* Mini Card */
3802         {IWL_PCI_DEVICE(0x4232, 0x1325, iwl5100_bgn_cfg)}, /* Half Mini Card */
3803         {IWL_PCI_DEVICE(0x4232, 0x1226, iwl5100_abg_cfg)}, /* Mini Card */
3804         {IWL_PCI_DEVICE(0x4232, 0x1326, iwl5100_abg_cfg)}, /* Half Mini Card */
3805         {IWL_PCI_DEVICE(0x4237, 0x1211, iwl5100_agn_cfg)}, /* Mini Card */
3806         {IWL_PCI_DEVICE(0x4237, 0x1311, iwl5100_agn_cfg)}, /* Half Mini Card */
3807         {IWL_PCI_DEVICE(0x4237, 0x1214, iwl5100_agn_cfg)}, /* Mini Card */
3808         {IWL_PCI_DEVICE(0x4237, 0x1314, iwl5100_agn_cfg)}, /* Half Mini Card */
3809         {IWL_PCI_DEVICE(0x4237, 0x1215, iwl5100_bgn_cfg)}, /* Mini Card */
3810         {IWL_PCI_DEVICE(0x4237, 0x1315, iwl5100_bgn_cfg)}, /* Half Mini Card */
3811         {IWL_PCI_DEVICE(0x4237, 0x1216, iwl5100_abg_cfg)}, /* Mini Card */
3812         {IWL_PCI_DEVICE(0x4237, 0x1316, iwl5100_abg_cfg)}, /* Half Mini Card */
3813
3814 /* 5300 Series WiFi */
3815         {IWL_PCI_DEVICE(0x4235, 0x1021, iwl5300_agn_cfg)}, /* Mini Card */
3816         {IWL_PCI_DEVICE(0x4235, 0x1121, iwl5300_agn_cfg)}, /* Half Mini Card */
3817         {IWL_PCI_DEVICE(0x4235, 0x1024, iwl5300_agn_cfg)}, /* Mini Card */
3818         {IWL_PCI_DEVICE(0x4235, 0x1124, iwl5300_agn_cfg)}, /* Half Mini Card */
3819         {IWL_PCI_DEVICE(0x4235, 0x1001, iwl5300_agn_cfg)}, /* Mini Card */
3820         {IWL_PCI_DEVICE(0x4235, 0x1101, iwl5300_agn_cfg)}, /* Half Mini Card */
3821         {IWL_PCI_DEVICE(0x4235, 0x1004, iwl5300_agn_cfg)}, /* Mini Card */
3822         {IWL_PCI_DEVICE(0x4235, 0x1104, iwl5300_agn_cfg)}, /* Half Mini Card */
3823         {IWL_PCI_DEVICE(0x4236, 0x1011, iwl5300_agn_cfg)}, /* Mini Card */
3824         {IWL_PCI_DEVICE(0x4236, 0x1111, iwl5300_agn_cfg)}, /* Half Mini Card */
3825         {IWL_PCI_DEVICE(0x4236, 0x1014, iwl5300_agn_cfg)}, /* Mini Card */
3826         {IWL_PCI_DEVICE(0x4236, 0x1114, iwl5300_agn_cfg)}, /* Half Mini Card */
3827
3828 /* 5350 Series WiFi/WiMax */
3829         {IWL_PCI_DEVICE(0x423A, 0x1001, iwl5350_agn_cfg)}, /* Mini Card */
3830         {IWL_PCI_DEVICE(0x423A, 0x1021, iwl5350_agn_cfg)}, /* Mini Card */
3831         {IWL_PCI_DEVICE(0x423B, 0x1011, iwl5350_agn_cfg)}, /* Mini Card */
3832
3833 /* 5150 Series Wifi/WiMax */
3834         {IWL_PCI_DEVICE(0x423C, 0x1201, iwl5150_agn_cfg)}, /* Mini Card */
3835         {IWL_PCI_DEVICE(0x423C, 0x1301, iwl5150_agn_cfg)}, /* Half Mini Card */
3836         {IWL_PCI_DEVICE(0x423C, 0x1206, iwl5150_abg_cfg)}, /* Mini Card */
3837         {IWL_PCI_DEVICE(0x423C, 0x1306, iwl5150_abg_cfg)}, /* Half Mini Card */
3838         {IWL_PCI_DEVICE(0x423C, 0x1221, iwl5150_agn_cfg)}, /* Mini Card */
3839         {IWL_PCI_DEVICE(0x423C, 0x1321, iwl5150_agn_cfg)}, /* Half Mini Card */
3840
3841         {IWL_PCI_DEVICE(0x423D, 0x1211, iwl5150_agn_cfg)}, /* Mini Card */
3842         {IWL_PCI_DEVICE(0x423D, 0x1311, iwl5150_agn_cfg)}, /* Half Mini Card */
3843         {IWL_PCI_DEVICE(0x423D, 0x1216, iwl5150_abg_cfg)}, /* Mini Card */
3844         {IWL_PCI_DEVICE(0x423D, 0x1316, iwl5150_abg_cfg)}, /* Half Mini Card */
3845
3846 /* 6x00 Series */
3847         {IWL_PCI_DEVICE(0x422B, 0x1101, iwl6000_3agn_cfg)},
3848         {IWL_PCI_DEVICE(0x422B, 0x1121, iwl6000_3agn_cfg)},
3849         {IWL_PCI_DEVICE(0x422C, 0x1301, iwl6000i_2agn_cfg)},
3850         {IWL_PCI_DEVICE(0x422C, 0x1306, iwl6000i_2abg_cfg)},
3851         {IWL_PCI_DEVICE(0x422C, 0x1307, iwl6000i_2bg_cfg)},
3852         {IWL_PCI_DEVICE(0x422C, 0x1321, iwl6000i_2agn_cfg)},
3853         {IWL_PCI_DEVICE(0x422C, 0x1326, iwl6000i_2abg_cfg)},
3854         {IWL_PCI_DEVICE(0x4238, 0x1111, iwl6000_3agn_cfg)},
3855         {IWL_PCI_DEVICE(0x4239, 0x1311, iwl6000i_2agn_cfg)},
3856         {IWL_PCI_DEVICE(0x4239, 0x1316, iwl6000i_2abg_cfg)},
3857
3858 /* 6x50 WiFi/WiMax Series */
3859         {IWL_PCI_DEVICE(0x0087, 0x1301, iwl6050_2agn_cfg)},
3860         {IWL_PCI_DEVICE(0x0087, 0x1306, iwl6050_2abg_cfg)},
3861         {IWL_PCI_DEVICE(0x0087, 0x1321, iwl6050_2agn_cfg)},
3862         {IWL_PCI_DEVICE(0x0087, 0x1326, iwl6050_2abg_cfg)},
3863         {IWL_PCI_DEVICE(0x0089, 0x1311, iwl6050_2agn_cfg)},
3864         {IWL_PCI_DEVICE(0x0089, 0x1316, iwl6050_2abg_cfg)},
3865
3866 /* 1000 Series WiFi */
3867         {IWL_PCI_DEVICE(0x0083, 0x1205, iwl1000_bgn_cfg)},
3868         {IWL_PCI_DEVICE(0x0083, 0x1305, iwl1000_bgn_cfg)},
3869         {IWL_PCI_DEVICE(0x0083, 0x1225, iwl1000_bgn_cfg)},
3870         {IWL_PCI_DEVICE(0x0083, 0x1325, iwl1000_bgn_cfg)},
3871         {IWL_PCI_DEVICE(0x0084, 0x1215, iwl1000_bgn_cfg)},
3872         {IWL_PCI_DEVICE(0x0084, 0x1315, iwl1000_bgn_cfg)},
3873         {IWL_PCI_DEVICE(0x0083, 0x1206, iwl1000_bg_cfg)},
3874         {IWL_PCI_DEVICE(0x0083, 0x1306, iwl1000_bg_cfg)},
3875         {IWL_PCI_DEVICE(0x0083, 0x1226, iwl1000_bg_cfg)},
3876         {IWL_PCI_DEVICE(0x0083, 0x1326, iwl1000_bg_cfg)},
3877         {IWL_PCI_DEVICE(0x0084, 0x1216, iwl1000_bg_cfg)},
3878         {IWL_PCI_DEVICE(0x0084, 0x1316, iwl1000_bg_cfg)},
3879 #endif /* CONFIG_IWL5000 */
3880
3881         {0}
3882 };
3883 MODULE_DEVICE_TABLE(pci, iwl_hw_card_ids);
3884
3885 static struct pci_driver iwl_driver = {
3886         .name = DRV_NAME,
3887         .id_table = iwl_hw_card_ids,
3888         .probe = iwl_pci_probe,
3889         .remove = __devexit_p(iwl_pci_remove),
3890 #ifdef CONFIG_PM
3891         .suspend = iwl_pci_suspend,
3892         .resume = iwl_pci_resume,
3893 #endif
3894 };
3895
3896 static int __init iwl_init(void)
3897 {
3898
3899         int ret;
3900         printk(KERN_INFO DRV_NAME ": " DRV_DESCRIPTION ", " DRV_VERSION "\n");
3901         printk(KERN_INFO DRV_NAME ": " DRV_COPYRIGHT "\n");
3902
3903         ret = iwlagn_rate_control_register();
3904         if (ret) {
3905                 printk(KERN_ERR DRV_NAME
3906                        "Unable to register rate control algorithm: %d\n", ret);
3907                 return ret;
3908         }
3909
3910         ret = pci_register_driver(&iwl_driver);
3911         if (ret) {
3912                 printk(KERN_ERR DRV_NAME "Unable to initialize PCI module\n");
3913                 goto error_register;
3914         }
3915
3916         return ret;
3917
3918 error_register:
3919         iwlagn_rate_control_unregister();
3920         return ret;
3921 }
3922
3923 static void __exit iwl_exit(void)
3924 {
3925         pci_unregister_driver(&iwl_driver);
3926         iwlagn_rate_control_unregister();
3927 }
3928
3929 module_exit(iwl_exit);
3930 module_init(iwl_init);
3931
3932 #ifdef CONFIG_IWLWIFI_DEBUG
3933 module_param_named(debug50, iwl_debug_level, uint, S_IRUGO);
3934 MODULE_PARM_DESC(debug50, "50XX debug output mask (deprecated)");
3935 module_param_named(debug, iwl_debug_level, uint, S_IRUGO | S_IWUSR);
3936 MODULE_PARM_DESC(debug, "debug output mask");
3937 #endif
3938