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