Merge branch 'x86-urgent-for-linus' of git://git.kernel.org/pub/scm/linux/kernel...
[pandora-kernel.git] / drivers / net / wireless / iwlwifi / iwl-core.c
1 /******************************************************************************
2  *
3  * GPL LICENSE SUMMARY
4  *
5  * Copyright(c) 2008 - 2011 Intel Corporation. All rights reserved.
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of version 2 of the GNU General Public License as
9  * published by the Free Software Foundation.
10  *
11  * This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110,
19  * USA
20  *
21  * The full GNU General Public License is included in this distribution
22  * in the file called LICENSE.GPL.
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 #include <linux/kernel.h>
30 #include <linux/module.h>
31 #include <linux/etherdevice.h>
32 #include <linux/sched.h>
33 #include <linux/slab.h>
34 #include <net/mac80211.h>
35
36 #include "iwl-eeprom.h"
37 #include "iwl-dev.h" /* FIXME: remove */
38 #include "iwl-debug.h"
39 #include "iwl-core.h"
40 #include "iwl-io.h"
41 #include "iwl-power.h"
42 #include "iwl-sta.h"
43 #include "iwl-helpers.h"
44 #include "iwl-agn.h"
45
46
47 /*
48  * set bt_coex_active to true, uCode will do kill/defer
49  * every time the priority line is asserted (BT is sending signals on the
50  * priority line in the PCIx).
51  * set bt_coex_active to false, uCode will ignore the BT activity and
52  * perform the normal operation
53  *
54  * User might experience transmit issue on some platform due to WiFi/BT
55  * co-exist problem. The possible behaviors are:
56  *   Able to scan and finding all the available AP
57  *   Not able to associate with any AP
58  * On those platforms, WiFi communication can be restored by set
59  * "bt_coex_active" module parameter to "false"
60  *
61  * default: bt_coex_active = true (BT_COEX_ENABLE)
62  */
63 bool bt_coex_active = true;
64 module_param(bt_coex_active, bool, S_IRUGO);
65 MODULE_PARM_DESC(bt_coex_active, "enable wifi/bluetooth co-exist");
66
67 u32 iwl_debug_level;
68
69 const u8 iwl_bcast_addr[ETH_ALEN] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
70
71 #define MAX_BIT_RATE_40_MHZ 150 /* Mbps */
72 #define MAX_BIT_RATE_20_MHZ 72 /* Mbps */
73 static void iwlcore_init_ht_hw_capab(const struct iwl_priv *priv,
74                               struct ieee80211_sta_ht_cap *ht_info,
75                               enum ieee80211_band band)
76 {
77         u16 max_bit_rate = 0;
78         u8 rx_chains_num = priv->hw_params.rx_chains_num;
79         u8 tx_chains_num = priv->hw_params.tx_chains_num;
80
81         ht_info->cap = 0;
82         memset(&ht_info->mcs, 0, sizeof(ht_info->mcs));
83
84         ht_info->ht_supported = true;
85
86         if (priv->cfg->ht_params &&
87             priv->cfg->ht_params->ht_greenfield_support)
88                 ht_info->cap |= IEEE80211_HT_CAP_GRN_FLD;
89         ht_info->cap |= IEEE80211_HT_CAP_SGI_20;
90         max_bit_rate = MAX_BIT_RATE_20_MHZ;
91         if (priv->hw_params.ht40_channel & BIT(band)) {
92                 ht_info->cap |= IEEE80211_HT_CAP_SUP_WIDTH_20_40;
93                 ht_info->cap |= IEEE80211_HT_CAP_SGI_40;
94                 ht_info->mcs.rx_mask[4] = 0x01;
95                 max_bit_rate = MAX_BIT_RATE_40_MHZ;
96         }
97
98         if (iwlagn_mod_params.amsdu_size_8K)
99                 ht_info->cap |= IEEE80211_HT_CAP_MAX_AMSDU;
100
101         ht_info->ampdu_factor = CFG_HT_RX_AMPDU_FACTOR_DEF;
102         if (priv->cfg->bt_params && priv->cfg->bt_params->ampdu_factor)
103                 ht_info->ampdu_factor = priv->cfg->bt_params->ampdu_factor;
104         ht_info->ampdu_density = CFG_HT_MPDU_DENSITY_DEF;
105         if (priv->cfg->bt_params && priv->cfg->bt_params->ampdu_density)
106                 ht_info->ampdu_density = priv->cfg->bt_params->ampdu_density;
107
108         ht_info->mcs.rx_mask[0] = 0xFF;
109         if (rx_chains_num >= 2)
110                 ht_info->mcs.rx_mask[1] = 0xFF;
111         if (rx_chains_num >= 3)
112                 ht_info->mcs.rx_mask[2] = 0xFF;
113
114         /* Highest supported Rx data rate */
115         max_bit_rate *= rx_chains_num;
116         WARN_ON(max_bit_rate & ~IEEE80211_HT_MCS_RX_HIGHEST_MASK);
117         ht_info->mcs.rx_highest = cpu_to_le16(max_bit_rate);
118
119         /* Tx MCS capabilities */
120         ht_info->mcs.tx_params = IEEE80211_HT_MCS_TX_DEFINED;
121         if (tx_chains_num != rx_chains_num) {
122                 ht_info->mcs.tx_params |= IEEE80211_HT_MCS_TX_RX_DIFF;
123                 ht_info->mcs.tx_params |= ((tx_chains_num - 1) <<
124                                 IEEE80211_HT_MCS_TX_MAX_STREAMS_SHIFT);
125         }
126 }
127
128 /**
129  * iwlcore_init_geos - Initialize mac80211's geo/channel info based from eeprom
130  */
131 int iwlcore_init_geos(struct iwl_priv *priv)
132 {
133         struct iwl_channel_info *ch;
134         struct ieee80211_supported_band *sband;
135         struct ieee80211_channel *channels;
136         struct ieee80211_channel *geo_ch;
137         struct ieee80211_rate *rates;
138         int i = 0;
139         s8 max_tx_power = IWLAGN_TX_POWER_TARGET_POWER_MIN;
140
141         if (priv->bands[IEEE80211_BAND_2GHZ].n_bitrates ||
142             priv->bands[IEEE80211_BAND_5GHZ].n_bitrates) {
143                 IWL_DEBUG_INFO(priv, "Geography modes already initialized.\n");
144                 set_bit(STATUS_GEO_CONFIGURED, &priv->status);
145                 return 0;
146         }
147
148         channels = kzalloc(sizeof(struct ieee80211_channel) *
149                            priv->channel_count, GFP_KERNEL);
150         if (!channels)
151                 return -ENOMEM;
152
153         rates = kzalloc((sizeof(struct ieee80211_rate) * IWL_RATE_COUNT_LEGACY),
154                         GFP_KERNEL);
155         if (!rates) {
156                 kfree(channels);
157                 return -ENOMEM;
158         }
159
160         /* 5.2GHz channels start after the 2.4GHz channels */
161         sband = &priv->bands[IEEE80211_BAND_5GHZ];
162         sband->channels = &channels[ARRAY_SIZE(iwl_eeprom_band_1)];
163         /* just OFDM */
164         sband->bitrates = &rates[IWL_FIRST_OFDM_RATE];
165         sband->n_bitrates = IWL_RATE_COUNT_LEGACY - IWL_FIRST_OFDM_RATE;
166
167         if (priv->cfg->sku & IWL_SKU_N)
168                 iwlcore_init_ht_hw_capab(priv, &sband->ht_cap,
169                                          IEEE80211_BAND_5GHZ);
170
171         sband = &priv->bands[IEEE80211_BAND_2GHZ];
172         sband->channels = channels;
173         /* OFDM & CCK */
174         sband->bitrates = rates;
175         sband->n_bitrates = IWL_RATE_COUNT_LEGACY;
176
177         if (priv->cfg->sku & IWL_SKU_N)
178                 iwlcore_init_ht_hw_capab(priv, &sband->ht_cap,
179                                          IEEE80211_BAND_2GHZ);
180
181         priv->ieee_channels = channels;
182         priv->ieee_rates = rates;
183
184         for (i = 0;  i < priv->channel_count; i++) {
185                 ch = &priv->channel_info[i];
186
187                 /* FIXME: might be removed if scan is OK */
188                 if (!is_channel_valid(ch))
189                         continue;
190
191                 sband =  &priv->bands[ch->band];
192
193                 geo_ch = &sband->channels[sband->n_channels++];
194
195                 geo_ch->center_freq =
196                         ieee80211_channel_to_frequency(ch->channel, ch->band);
197                 geo_ch->max_power = ch->max_power_avg;
198                 geo_ch->max_antenna_gain = 0xff;
199                 geo_ch->hw_value = ch->channel;
200
201                 if (is_channel_valid(ch)) {
202                         if (!(ch->flags & EEPROM_CHANNEL_IBSS))
203                                 geo_ch->flags |= IEEE80211_CHAN_NO_IBSS;
204
205                         if (!(ch->flags & EEPROM_CHANNEL_ACTIVE))
206                                 geo_ch->flags |= IEEE80211_CHAN_PASSIVE_SCAN;
207
208                         if (ch->flags & EEPROM_CHANNEL_RADAR)
209                                 geo_ch->flags |= IEEE80211_CHAN_RADAR;
210
211                         geo_ch->flags |= ch->ht40_extension_channel;
212
213                         if (ch->max_power_avg > max_tx_power)
214                                 max_tx_power = ch->max_power_avg;
215                 } else {
216                         geo_ch->flags |= IEEE80211_CHAN_DISABLED;
217                 }
218
219                 IWL_DEBUG_INFO(priv, "Channel %d Freq=%d[%sGHz] %s flag=0x%X\n",
220                                 ch->channel, geo_ch->center_freq,
221                                 is_channel_a_band(ch) ?  "5.2" : "2.4",
222                                 geo_ch->flags & IEEE80211_CHAN_DISABLED ?
223                                 "restricted" : "valid",
224                                  geo_ch->flags);
225         }
226
227         priv->tx_power_device_lmt = max_tx_power;
228         priv->tx_power_user_lmt = max_tx_power;
229         priv->tx_power_next = max_tx_power;
230
231         if ((priv->bands[IEEE80211_BAND_5GHZ].n_channels == 0) &&
232              priv->cfg->sku & IWL_SKU_A) {
233                 IWL_INFO(priv, "Incorrectly detected BG card as ABG. "
234                         "Please send your PCI ID 0x%04X:0x%04X to maintainer.\n",
235                            priv->pci_dev->device,
236                            priv->pci_dev->subsystem_device);
237                 priv->cfg->sku &= ~IWL_SKU_A;
238         }
239
240         IWL_INFO(priv, "Tunable channels: %d 802.11bg, %d 802.11a channels\n",
241                    priv->bands[IEEE80211_BAND_2GHZ].n_channels,
242                    priv->bands[IEEE80211_BAND_5GHZ].n_channels);
243
244         set_bit(STATUS_GEO_CONFIGURED, &priv->status);
245
246         return 0;
247 }
248
249 /*
250  * iwlcore_free_geos - undo allocations in iwlcore_init_geos
251  */
252 void iwlcore_free_geos(struct iwl_priv *priv)
253 {
254         kfree(priv->ieee_channels);
255         kfree(priv->ieee_rates);
256         clear_bit(STATUS_GEO_CONFIGURED, &priv->status);
257 }
258
259 static bool iwl_is_channel_extension(struct iwl_priv *priv,
260                                      enum ieee80211_band band,
261                                      u16 channel, u8 extension_chan_offset)
262 {
263         const struct iwl_channel_info *ch_info;
264
265         ch_info = iwl_get_channel_info(priv, band, channel);
266         if (!is_channel_valid(ch_info))
267                 return false;
268
269         if (extension_chan_offset == IEEE80211_HT_PARAM_CHA_SEC_ABOVE)
270                 return !(ch_info->ht40_extension_channel &
271                                         IEEE80211_CHAN_NO_HT40PLUS);
272         else if (extension_chan_offset == IEEE80211_HT_PARAM_CHA_SEC_BELOW)
273                 return !(ch_info->ht40_extension_channel &
274                                         IEEE80211_CHAN_NO_HT40MINUS);
275
276         return false;
277 }
278
279 bool iwl_is_ht40_tx_allowed(struct iwl_priv *priv,
280                             struct iwl_rxon_context *ctx,
281                             struct ieee80211_sta_ht_cap *ht_cap)
282 {
283         if (!ctx->ht.enabled || !ctx->ht.is_40mhz)
284                 return false;
285
286         /*
287          * We do not check for IEEE80211_HT_CAP_SUP_WIDTH_20_40
288          * the bit will not set if it is pure 40MHz case
289          */
290         if (ht_cap && !ht_cap->ht_supported)
291                 return false;
292
293 #ifdef CONFIG_IWLWIFI_DEBUGFS
294         if (priv->disable_ht40)
295                 return false;
296 #endif
297
298         return iwl_is_channel_extension(priv, priv->band,
299                         le16_to_cpu(ctx->staging.channel),
300                         ctx->ht.extension_chan_offset);
301 }
302
303 static u16 iwl_adjust_beacon_interval(u16 beacon_val, u16 max_beacon_val)
304 {
305         u16 new_val;
306         u16 beacon_factor;
307
308         /*
309          * If mac80211 hasn't given us a beacon interval, program
310          * the default into the device (not checking this here
311          * would cause the adjustment below to return the maximum
312          * value, which may break PAN.)
313          */
314         if (!beacon_val)
315                 return DEFAULT_BEACON_INTERVAL;
316
317         /*
318          * If the beacon interval we obtained from the peer
319          * is too large, we'll have to wake up more often
320          * (and in IBSS case, we'll beacon too much)
321          *
322          * For example, if max_beacon_val is 4096, and the
323          * requested beacon interval is 7000, we'll have to
324          * use 3500 to be able to wake up on the beacons.
325          *
326          * This could badly influence beacon detection stats.
327          */
328
329         beacon_factor = (beacon_val + max_beacon_val) / max_beacon_val;
330         new_val = beacon_val / beacon_factor;
331
332         if (!new_val)
333                 new_val = max_beacon_val;
334
335         return new_val;
336 }
337
338 int iwl_send_rxon_timing(struct iwl_priv *priv, struct iwl_rxon_context *ctx)
339 {
340         u64 tsf;
341         s32 interval_tm, rem;
342         struct ieee80211_conf *conf = NULL;
343         u16 beacon_int;
344         struct ieee80211_vif *vif = ctx->vif;
345
346         conf = ieee80211_get_hw_conf(priv->hw);
347
348         lockdep_assert_held(&priv->mutex);
349
350         memset(&ctx->timing, 0, sizeof(struct iwl_rxon_time_cmd));
351
352         ctx->timing.timestamp = cpu_to_le64(priv->timestamp);
353         ctx->timing.listen_interval = cpu_to_le16(conf->listen_interval);
354
355         beacon_int = vif ? vif->bss_conf.beacon_int : 0;
356
357         /*
358          * TODO: For IBSS we need to get atim_window from mac80211,
359          *       for now just always use 0
360          */
361         ctx->timing.atim_window = 0;
362
363         if (ctx->ctxid == IWL_RXON_CTX_PAN &&
364             (!ctx->vif || ctx->vif->type != NL80211_IFTYPE_STATION) &&
365             iwl_is_associated(priv, IWL_RXON_CTX_BSS) &&
366             priv->contexts[IWL_RXON_CTX_BSS].vif &&
367             priv->contexts[IWL_RXON_CTX_BSS].vif->bss_conf.beacon_int) {
368                 ctx->timing.beacon_interval =
369                         priv->contexts[IWL_RXON_CTX_BSS].timing.beacon_interval;
370                 beacon_int = le16_to_cpu(ctx->timing.beacon_interval);
371         } else if (ctx->ctxid == IWL_RXON_CTX_BSS &&
372                    iwl_is_associated(priv, IWL_RXON_CTX_PAN) &&
373                    priv->contexts[IWL_RXON_CTX_PAN].vif &&
374                    priv->contexts[IWL_RXON_CTX_PAN].vif->bss_conf.beacon_int &&
375                    (!iwl_is_associated_ctx(ctx) || !ctx->vif ||
376                     !ctx->vif->bss_conf.beacon_int)) {
377                 ctx->timing.beacon_interval =
378                         priv->contexts[IWL_RXON_CTX_PAN].timing.beacon_interval;
379                 beacon_int = le16_to_cpu(ctx->timing.beacon_interval);
380         } else {
381                 beacon_int = iwl_adjust_beacon_interval(beacon_int,
382                                 priv->hw_params.max_beacon_itrvl * TIME_UNIT);
383                 ctx->timing.beacon_interval = cpu_to_le16(beacon_int);
384         }
385
386         tsf = priv->timestamp; /* tsf is modifed by do_div: copy it */
387         interval_tm = beacon_int * TIME_UNIT;
388         rem = do_div(tsf, interval_tm);
389         ctx->timing.beacon_init_val = cpu_to_le32(interval_tm - rem);
390
391         ctx->timing.dtim_period = vif ? (vif->bss_conf.dtim_period ?: 1) : 1;
392
393         IWL_DEBUG_ASSOC(priv,
394                         "beacon interval %d beacon timer %d beacon tim %d\n",
395                         le16_to_cpu(ctx->timing.beacon_interval),
396                         le32_to_cpu(ctx->timing.beacon_init_val),
397                         le16_to_cpu(ctx->timing.atim_window));
398
399         return iwl_send_cmd_pdu(priv, ctx->rxon_timing_cmd,
400                                 sizeof(ctx->timing), &ctx->timing);
401 }
402
403 void iwl_set_rxon_hwcrypto(struct iwl_priv *priv, struct iwl_rxon_context *ctx,
404                            int hw_decrypt)
405 {
406         struct iwl_rxon_cmd *rxon = &ctx->staging;
407
408         if (hw_decrypt)
409                 rxon->filter_flags &= ~RXON_FILTER_DIS_DECRYPT_MSK;
410         else
411                 rxon->filter_flags |= RXON_FILTER_DIS_DECRYPT_MSK;
412
413 }
414
415 /* validate RXON structure is valid */
416 int iwl_check_rxon_cmd(struct iwl_priv *priv, struct iwl_rxon_context *ctx)
417 {
418         struct iwl_rxon_cmd *rxon = &ctx->staging;
419         u32 errors = 0;
420
421         if (rxon->flags & RXON_FLG_BAND_24G_MSK) {
422                 if (rxon->flags & RXON_FLG_TGJ_NARROW_BAND_MSK) {
423                         IWL_WARN(priv, "check 2.4G: wrong narrow\n");
424                         errors |= BIT(0);
425                 }
426                 if (rxon->flags & RXON_FLG_RADAR_DETECT_MSK) {
427                         IWL_WARN(priv, "check 2.4G: wrong radar\n");
428                         errors |= BIT(1);
429                 }
430         } else {
431                 if (!(rxon->flags & RXON_FLG_SHORT_SLOT_MSK)) {
432                         IWL_WARN(priv, "check 5.2G: not short slot!\n");
433                         errors |= BIT(2);
434                 }
435                 if (rxon->flags & RXON_FLG_CCK_MSK) {
436                         IWL_WARN(priv, "check 5.2G: CCK!\n");
437                         errors |= BIT(3);
438                 }
439         }
440         if ((rxon->node_addr[0] | rxon->bssid_addr[0]) & 0x1) {
441                 IWL_WARN(priv, "mac/bssid mcast!\n");
442                 errors |= BIT(4);
443         }
444
445         /* make sure basic rates 6Mbps and 1Mbps are supported */
446         if ((rxon->ofdm_basic_rates & IWL_RATE_6M_MASK) == 0 &&
447             (rxon->cck_basic_rates & IWL_RATE_1M_MASK) == 0) {
448                 IWL_WARN(priv, "neither 1 nor 6 are basic\n");
449                 errors |= BIT(5);
450         }
451
452         if (le16_to_cpu(rxon->assoc_id) > 2007) {
453                 IWL_WARN(priv, "aid > 2007\n");
454                 errors |= BIT(6);
455         }
456
457         if ((rxon->flags & (RXON_FLG_CCK_MSK | RXON_FLG_SHORT_SLOT_MSK))
458                         == (RXON_FLG_CCK_MSK | RXON_FLG_SHORT_SLOT_MSK)) {
459                 IWL_WARN(priv, "CCK and short slot\n");
460                 errors |= BIT(7);
461         }
462
463         if ((rxon->flags & (RXON_FLG_CCK_MSK | RXON_FLG_AUTO_DETECT_MSK))
464                         == (RXON_FLG_CCK_MSK | RXON_FLG_AUTO_DETECT_MSK)) {
465                 IWL_WARN(priv, "CCK and auto detect");
466                 errors |= BIT(8);
467         }
468
469         if ((rxon->flags & (RXON_FLG_AUTO_DETECT_MSK |
470                             RXON_FLG_TGG_PROTECT_MSK)) ==
471                             RXON_FLG_TGG_PROTECT_MSK) {
472                 IWL_WARN(priv, "TGg but no auto-detect\n");
473                 errors |= BIT(9);
474         }
475
476         if (rxon->channel == 0) {
477                 IWL_WARN(priv, "zero channel is invalid\n");
478                 errors |= BIT(10);
479         }
480
481         WARN(errors, "Invalid RXON (%#x), channel %d",
482              errors, le16_to_cpu(rxon->channel));
483
484         return errors ? -EINVAL : 0;
485 }
486
487 /**
488  * iwl_full_rxon_required - check if full RXON (vs RXON_ASSOC) cmd is needed
489  * @priv: staging_rxon is compared to active_rxon
490  *
491  * If the RXON structure is changing enough to require a new tune,
492  * or is clearing the RXON_FILTER_ASSOC_MSK, then return 1 to indicate that
493  * a new tune (full RXON command, rather than RXON_ASSOC cmd) is required.
494  */
495 int iwl_full_rxon_required(struct iwl_priv *priv,
496                            struct iwl_rxon_context *ctx)
497 {
498         const struct iwl_rxon_cmd *staging = &ctx->staging;
499         const struct iwl_rxon_cmd *active = &ctx->active;
500
501 #define CHK(cond)                                                       \
502         if ((cond)) {                                                   \
503                 IWL_DEBUG_INFO(priv, "need full RXON - " #cond "\n");   \
504                 return 1;                                               \
505         }
506
507 #define CHK_NEQ(c1, c2)                                         \
508         if ((c1) != (c2)) {                                     \
509                 IWL_DEBUG_INFO(priv, "need full RXON - "        \
510                                #c1 " != " #c2 " - %d != %d\n",  \
511                                (c1), (c2));                     \
512                 return 1;                                       \
513         }
514
515         /* These items are only settable from the full RXON command */
516         CHK(!iwl_is_associated_ctx(ctx));
517         CHK(compare_ether_addr(staging->bssid_addr, active->bssid_addr));
518         CHK(compare_ether_addr(staging->node_addr, active->node_addr));
519         CHK(compare_ether_addr(staging->wlap_bssid_addr,
520                                 active->wlap_bssid_addr));
521         CHK_NEQ(staging->dev_type, active->dev_type);
522         CHK_NEQ(staging->channel, active->channel);
523         CHK_NEQ(staging->air_propagation, active->air_propagation);
524         CHK_NEQ(staging->ofdm_ht_single_stream_basic_rates,
525                 active->ofdm_ht_single_stream_basic_rates);
526         CHK_NEQ(staging->ofdm_ht_dual_stream_basic_rates,
527                 active->ofdm_ht_dual_stream_basic_rates);
528         CHK_NEQ(staging->ofdm_ht_triple_stream_basic_rates,
529                 active->ofdm_ht_triple_stream_basic_rates);
530         CHK_NEQ(staging->assoc_id, active->assoc_id);
531
532         /* flags, filter_flags, ofdm_basic_rates, and cck_basic_rates can
533          * be updated with the RXON_ASSOC command -- however only some
534          * flag transitions are allowed using RXON_ASSOC */
535
536         /* Check if we are not switching bands */
537         CHK_NEQ(staging->flags & RXON_FLG_BAND_24G_MSK,
538                 active->flags & RXON_FLG_BAND_24G_MSK);
539
540         /* Check if we are switching association toggle */
541         CHK_NEQ(staging->filter_flags & RXON_FILTER_ASSOC_MSK,
542                 active->filter_flags & RXON_FILTER_ASSOC_MSK);
543
544 #undef CHK
545 #undef CHK_NEQ
546
547         return 0;
548 }
549
550 u8 iwl_rate_get_lowest_plcp(struct iwl_priv *priv,
551                             struct iwl_rxon_context *ctx)
552 {
553         /*
554          * Assign the lowest rate -- should really get this from
555          * the beacon skb from mac80211.
556          */
557         if (ctx->staging.flags & RXON_FLG_BAND_24G_MSK)
558                 return IWL_RATE_1M_PLCP;
559         else
560                 return IWL_RATE_6M_PLCP;
561 }
562
563 static void _iwl_set_rxon_ht(struct iwl_priv *priv,
564                              struct iwl_ht_config *ht_conf,
565                              struct iwl_rxon_context *ctx)
566 {
567         struct iwl_rxon_cmd *rxon = &ctx->staging;
568
569         if (!ctx->ht.enabled) {
570                 rxon->flags &= ~(RXON_FLG_CHANNEL_MODE_MSK |
571                         RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK |
572                         RXON_FLG_HT40_PROT_MSK |
573                         RXON_FLG_HT_PROT_MSK);
574                 return;
575         }
576
577         /* FIXME: if the definition of ht.protection changed, the "translation"
578          * will be needed for rxon->flags
579          */
580         rxon->flags |= cpu_to_le32(ctx->ht.protection << RXON_FLG_HT_OPERATING_MODE_POS);
581
582         /* Set up channel bandwidth:
583          * 20 MHz only, 20/40 mixed or pure 40 if ht40 ok */
584         /* clear the HT channel mode before set the mode */
585         rxon->flags &= ~(RXON_FLG_CHANNEL_MODE_MSK |
586                          RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK);
587         if (iwl_is_ht40_tx_allowed(priv, ctx, NULL)) {
588                 /* pure ht40 */
589                 if (ctx->ht.protection == IEEE80211_HT_OP_MODE_PROTECTION_20MHZ) {
590                         rxon->flags |= RXON_FLG_CHANNEL_MODE_PURE_40;
591                         /* Note: control channel is opposite of extension channel */
592                         switch (ctx->ht.extension_chan_offset) {
593                         case IEEE80211_HT_PARAM_CHA_SEC_ABOVE:
594                                 rxon->flags &= ~RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK;
595                                 break;
596                         case IEEE80211_HT_PARAM_CHA_SEC_BELOW:
597                                 rxon->flags |= RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK;
598                                 break;
599                         }
600                 } else {
601                         /* Note: control channel is opposite of extension channel */
602                         switch (ctx->ht.extension_chan_offset) {
603                         case IEEE80211_HT_PARAM_CHA_SEC_ABOVE:
604                                 rxon->flags &= ~(RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK);
605                                 rxon->flags |= RXON_FLG_CHANNEL_MODE_MIXED;
606                                 break;
607                         case IEEE80211_HT_PARAM_CHA_SEC_BELOW:
608                                 rxon->flags |= RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK;
609                                 rxon->flags |= RXON_FLG_CHANNEL_MODE_MIXED;
610                                 break;
611                         case IEEE80211_HT_PARAM_CHA_SEC_NONE:
612                         default:
613                                 /* channel location only valid if in Mixed mode */
614                                 IWL_ERR(priv, "invalid extension channel offset\n");
615                                 break;
616                         }
617                 }
618         } else {
619                 rxon->flags |= RXON_FLG_CHANNEL_MODE_LEGACY;
620         }
621
622         if (priv->cfg->ops->hcmd->set_rxon_chain)
623                 priv->cfg->ops->hcmd->set_rxon_chain(priv, ctx);
624
625         IWL_DEBUG_ASSOC(priv, "rxon flags 0x%X operation mode :0x%X "
626                         "extension channel offset 0x%x\n",
627                         le32_to_cpu(rxon->flags), ctx->ht.protection,
628                         ctx->ht.extension_chan_offset);
629 }
630
631 void iwl_set_rxon_ht(struct iwl_priv *priv, struct iwl_ht_config *ht_conf)
632 {
633         struct iwl_rxon_context *ctx;
634
635         for_each_context(priv, ctx)
636                 _iwl_set_rxon_ht(priv, ht_conf, ctx);
637 }
638
639 /* Return valid, unused, channel for a passive scan to reset the RF */
640 u8 iwl_get_single_channel_number(struct iwl_priv *priv,
641                                  enum ieee80211_band band)
642 {
643         const struct iwl_channel_info *ch_info;
644         int i;
645         u8 channel = 0;
646         u8 min, max;
647         struct iwl_rxon_context *ctx;
648
649         if (band == IEEE80211_BAND_5GHZ) {
650                 min = 14;
651                 max = priv->channel_count;
652         } else {
653                 min = 0;
654                 max = 14;
655         }
656
657         for (i = min; i < max; i++) {
658                 bool busy = false;
659
660                 for_each_context(priv, ctx) {
661                         busy = priv->channel_info[i].channel ==
662                                 le16_to_cpu(ctx->staging.channel);
663                         if (busy)
664                                 break;
665                 }
666
667                 if (busy)
668                         continue;
669
670                 channel = priv->channel_info[i].channel;
671                 ch_info = iwl_get_channel_info(priv, band, channel);
672                 if (is_channel_valid(ch_info))
673                         break;
674         }
675
676         return channel;
677 }
678
679 /**
680  * iwl_set_rxon_channel - Set the band and channel values in staging RXON
681  * @ch: requested channel as a pointer to struct ieee80211_channel
682
683  * NOTE:  Does not commit to the hardware; it sets appropriate bit fields
684  * in the staging RXON flag structure based on the ch->band
685  */
686 int iwl_set_rxon_channel(struct iwl_priv *priv, struct ieee80211_channel *ch,
687                          struct iwl_rxon_context *ctx)
688 {
689         enum ieee80211_band band = ch->band;
690         u16 channel = ch->hw_value;
691
692         if ((le16_to_cpu(ctx->staging.channel) == channel) &&
693             (priv->band == band))
694                 return 0;
695
696         ctx->staging.channel = cpu_to_le16(channel);
697         if (band == IEEE80211_BAND_5GHZ)
698                 ctx->staging.flags &= ~RXON_FLG_BAND_24G_MSK;
699         else
700                 ctx->staging.flags |= RXON_FLG_BAND_24G_MSK;
701
702         priv->band = band;
703
704         IWL_DEBUG_INFO(priv, "Staging channel set to %d [%d]\n", channel, band);
705
706         return 0;
707 }
708
709 void iwl_set_flags_for_band(struct iwl_priv *priv,
710                             struct iwl_rxon_context *ctx,
711                             enum ieee80211_band band,
712                             struct ieee80211_vif *vif)
713 {
714         if (band == IEEE80211_BAND_5GHZ) {
715                 ctx->staging.flags &=
716                     ~(RXON_FLG_BAND_24G_MSK | RXON_FLG_AUTO_DETECT_MSK
717                       | RXON_FLG_CCK_MSK);
718                 ctx->staging.flags |= RXON_FLG_SHORT_SLOT_MSK;
719         } else {
720                 /* Copied from iwl_post_associate() */
721                 if (vif && vif->bss_conf.use_short_slot)
722                         ctx->staging.flags |= RXON_FLG_SHORT_SLOT_MSK;
723                 else
724                         ctx->staging.flags &= ~RXON_FLG_SHORT_SLOT_MSK;
725
726                 ctx->staging.flags |= RXON_FLG_BAND_24G_MSK;
727                 ctx->staging.flags |= RXON_FLG_AUTO_DETECT_MSK;
728                 ctx->staging.flags &= ~RXON_FLG_CCK_MSK;
729         }
730 }
731
732 /*
733  * initialize rxon structure with default values from eeprom
734  */
735 void iwl_connection_init_rx_config(struct iwl_priv *priv,
736                                    struct iwl_rxon_context *ctx)
737 {
738         const struct iwl_channel_info *ch_info;
739
740         memset(&ctx->staging, 0, sizeof(ctx->staging));
741
742         if (!ctx->vif) {
743                 ctx->staging.dev_type = ctx->unused_devtype;
744         } else switch (ctx->vif->type) {
745         case NL80211_IFTYPE_AP:
746                 ctx->staging.dev_type = ctx->ap_devtype;
747                 break;
748
749         case NL80211_IFTYPE_STATION:
750                 ctx->staging.dev_type = ctx->station_devtype;
751                 ctx->staging.filter_flags = RXON_FILTER_ACCEPT_GRP_MSK;
752                 break;
753
754         case NL80211_IFTYPE_ADHOC:
755                 ctx->staging.dev_type = ctx->ibss_devtype;
756                 ctx->staging.flags = RXON_FLG_SHORT_PREAMBLE_MSK;
757                 ctx->staging.filter_flags = RXON_FILTER_BCON_AWARE_MSK |
758                                                   RXON_FILTER_ACCEPT_GRP_MSK;
759                 break;
760
761         default:
762                 IWL_ERR(priv, "Unsupported interface type %d\n",
763                         ctx->vif->type);
764                 break;
765         }
766
767 #if 0
768         /* TODO:  Figure out when short_preamble would be set and cache from
769          * that */
770         if (!hw_to_local(priv->hw)->short_preamble)
771                 ctx->staging.flags &= ~RXON_FLG_SHORT_PREAMBLE_MSK;
772         else
773                 ctx->staging.flags |= RXON_FLG_SHORT_PREAMBLE_MSK;
774 #endif
775
776         ch_info = iwl_get_channel_info(priv, priv->band,
777                                        le16_to_cpu(ctx->active.channel));
778
779         if (!ch_info)
780                 ch_info = &priv->channel_info[0];
781
782         ctx->staging.channel = cpu_to_le16(ch_info->channel);
783         priv->band = ch_info->band;
784
785         iwl_set_flags_for_band(priv, ctx, priv->band, ctx->vif);
786
787         ctx->staging.ofdm_basic_rates =
788             (IWL_OFDM_RATES_MASK >> IWL_FIRST_OFDM_RATE) & 0xFF;
789         ctx->staging.cck_basic_rates =
790             (IWL_CCK_RATES_MASK >> IWL_FIRST_CCK_RATE) & 0xF;
791
792         /* clear both MIX and PURE40 mode flag */
793         ctx->staging.flags &= ~(RXON_FLG_CHANNEL_MODE_MIXED |
794                                         RXON_FLG_CHANNEL_MODE_PURE_40);
795         if (ctx->vif)
796                 memcpy(ctx->staging.node_addr, ctx->vif->addr, ETH_ALEN);
797
798         ctx->staging.ofdm_ht_single_stream_basic_rates = 0xff;
799         ctx->staging.ofdm_ht_dual_stream_basic_rates = 0xff;
800         ctx->staging.ofdm_ht_triple_stream_basic_rates = 0xff;
801 }
802
803 void iwl_set_rate(struct iwl_priv *priv)
804 {
805         const struct ieee80211_supported_band *hw = NULL;
806         struct ieee80211_rate *rate;
807         struct iwl_rxon_context *ctx;
808         int i;
809
810         hw = iwl_get_hw_mode(priv, priv->band);
811         if (!hw) {
812                 IWL_ERR(priv, "Failed to set rate: unable to get hw mode\n");
813                 return;
814         }
815
816         priv->active_rate = 0;
817
818         for (i = 0; i < hw->n_bitrates; i++) {
819                 rate = &(hw->bitrates[i]);
820                 if (rate->hw_value < IWL_RATE_COUNT_LEGACY)
821                         priv->active_rate |= (1 << rate->hw_value);
822         }
823
824         IWL_DEBUG_RATE(priv, "Set active_rate = %0x\n", priv->active_rate);
825
826         for_each_context(priv, ctx) {
827                 ctx->staging.cck_basic_rates =
828                     (IWL_CCK_BASIC_RATES_MASK >> IWL_FIRST_CCK_RATE) & 0xF;
829
830                 ctx->staging.ofdm_basic_rates =
831                    (IWL_OFDM_BASIC_RATES_MASK >> IWL_FIRST_OFDM_RATE) & 0xFF;
832         }
833 }
834
835 void iwl_chswitch_done(struct iwl_priv *priv, bool is_success)
836 {
837         /*
838          * MULTI-FIXME
839          * See iwl_mac_channel_switch.
840          */
841         struct iwl_rxon_context *ctx = &priv->contexts[IWL_RXON_CTX_BSS];
842
843         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
844                 return;
845
846         if (priv->switch_rxon.switch_in_progress) {
847                 ieee80211_chswitch_done(ctx->vif, is_success);
848                 mutex_lock(&priv->mutex);
849                 priv->switch_rxon.switch_in_progress = false;
850                 mutex_unlock(&priv->mutex);
851         }
852 }
853
854 #ifdef CONFIG_IWLWIFI_DEBUG
855 void iwl_print_rx_config_cmd(struct iwl_priv *priv,
856                              struct iwl_rxon_context *ctx)
857 {
858         struct iwl_rxon_cmd *rxon = &ctx->staging;
859
860         IWL_DEBUG_RADIO(priv, "RX CONFIG:\n");
861         iwl_print_hex_dump(priv, IWL_DL_RADIO, (u8 *) rxon, sizeof(*rxon));
862         IWL_DEBUG_RADIO(priv, "u16 channel: 0x%x\n", le16_to_cpu(rxon->channel));
863         IWL_DEBUG_RADIO(priv, "u32 flags: 0x%08X\n", le32_to_cpu(rxon->flags));
864         IWL_DEBUG_RADIO(priv, "u32 filter_flags: 0x%08x\n",
865                         le32_to_cpu(rxon->filter_flags));
866         IWL_DEBUG_RADIO(priv, "u8 dev_type: 0x%x\n", rxon->dev_type);
867         IWL_DEBUG_RADIO(priv, "u8 ofdm_basic_rates: 0x%02x\n",
868                         rxon->ofdm_basic_rates);
869         IWL_DEBUG_RADIO(priv, "u8 cck_basic_rates: 0x%02x\n", rxon->cck_basic_rates);
870         IWL_DEBUG_RADIO(priv, "u8[6] node_addr: %pM\n", rxon->node_addr);
871         IWL_DEBUG_RADIO(priv, "u8[6] bssid_addr: %pM\n", rxon->bssid_addr);
872         IWL_DEBUG_RADIO(priv, "u16 assoc_id: 0x%x\n", le16_to_cpu(rxon->assoc_id));
873 }
874 #endif
875
876 static void iwlagn_abort_notification_waits(struct iwl_priv *priv)
877 {
878         unsigned long flags;
879         struct iwl_notification_wait *wait_entry;
880
881         spin_lock_irqsave(&priv->_agn.notif_wait_lock, flags);
882         list_for_each_entry(wait_entry, &priv->_agn.notif_waits, list)
883                 wait_entry->aborted = true;
884         spin_unlock_irqrestore(&priv->_agn.notif_wait_lock, flags);
885
886         wake_up_all(&priv->_agn.notif_waitq);
887 }
888
889 void iwlagn_fw_error(struct iwl_priv *priv, bool ondemand)
890 {
891         unsigned int reload_msec;
892         unsigned long reload_jiffies;
893
894         /* Set the FW error flag -- cleared on iwl_down */
895         set_bit(STATUS_FW_ERROR, &priv->status);
896
897         /* Cancel currently queued command. */
898         clear_bit(STATUS_HCMD_ACTIVE, &priv->status);
899
900         iwlagn_abort_notification_waits(priv);
901
902         /* Keep the restart process from trying to send host
903          * commands by clearing the ready bit */
904         clear_bit(STATUS_READY, &priv->status);
905
906         wake_up_interruptible(&priv->wait_command_queue);
907
908         if (!ondemand) {
909                 /*
910                  * If firmware keep reloading, then it indicate something
911                  * serious wrong and firmware having problem to recover
912                  * from it. Instead of keep trying which will fill the syslog
913                  * and hang the system, let's just stop it
914                  */
915                 reload_jiffies = jiffies;
916                 reload_msec = jiffies_to_msecs((long) reload_jiffies -
917                                         (long) priv->reload_jiffies);
918                 priv->reload_jiffies = reload_jiffies;
919                 if (reload_msec <= IWL_MIN_RELOAD_DURATION) {
920                         priv->reload_count++;
921                         if (priv->reload_count >= IWL_MAX_CONTINUE_RELOAD_CNT) {
922                                 IWL_ERR(priv, "BUG_ON, Stop restarting\n");
923                                 return;
924                         }
925                 } else
926                         priv->reload_count = 0;
927         }
928
929         if (!test_bit(STATUS_EXIT_PENDING, &priv->status)) {
930                 if (iwlagn_mod_params.restart_fw) {
931                         IWL_DEBUG(priv, IWL_DL_FW_ERRORS,
932                                   "Restarting adapter due to uCode error.\n");
933                         queue_work(priv->workqueue, &priv->restart);
934                 } else
935                         IWL_DEBUG(priv, IWL_DL_FW_ERRORS,
936                                   "Detected FW error, but not restarting\n");
937         }
938 }
939
940 /**
941  * iwl_irq_handle_error - called for HW or SW error interrupt from card
942  */
943 void iwl_irq_handle_error(struct iwl_priv *priv)
944 {
945         /* W/A for WiFi/WiMAX coex and WiMAX own the RF */
946         if (priv->cfg->internal_wimax_coex &&
947             (!(iwl_read_prph(priv, APMG_CLK_CTRL_REG) &
948                         APMS_CLK_VAL_MRB_FUNC_MODE) ||
949              (iwl_read_prph(priv, APMG_PS_CTRL_REG) &
950                         APMG_PS_CTRL_VAL_RESET_REQ))) {
951                 /*
952                  * Keep the restart process from trying to send host
953                  * commands by clearing the ready bit.
954                  */
955                 clear_bit(STATUS_READY, &priv->status);
956                 clear_bit(STATUS_HCMD_ACTIVE, &priv->status);
957                 wake_up_interruptible(&priv->wait_command_queue);
958                 IWL_ERR(priv, "RF is used by WiMAX\n");
959                 return;
960         }
961
962         IWL_ERR(priv, "Loaded firmware version: %s\n",
963                 priv->hw->wiphy->fw_version);
964
965         iwl_dump_nic_error_log(priv);
966         iwl_dump_csr(priv);
967         iwl_dump_fh(priv, NULL, false);
968         iwl_dump_nic_event_log(priv, false, NULL, false);
969 #ifdef CONFIG_IWLWIFI_DEBUG
970         if (iwl_get_debug_level(priv) & IWL_DL_FW_ERRORS)
971                 iwl_print_rx_config_cmd(priv,
972                                         &priv->contexts[IWL_RXON_CTX_BSS]);
973 #endif
974
975         iwlagn_fw_error(priv, false);
976 }
977
978 static int iwl_apm_stop_master(struct iwl_priv *priv)
979 {
980         int ret = 0;
981
982         /* stop device's busmaster DMA activity */
983         iwl_set_bit(priv, CSR_RESET, CSR_RESET_REG_FLAG_STOP_MASTER);
984
985         ret = iwl_poll_bit(priv, CSR_RESET, CSR_RESET_REG_FLAG_MASTER_DISABLED,
986                         CSR_RESET_REG_FLAG_MASTER_DISABLED, 100);
987         if (ret)
988                 IWL_WARN(priv, "Master Disable Timed Out, 100 usec\n");
989
990         IWL_DEBUG_INFO(priv, "stop master\n");
991
992         return ret;
993 }
994
995 void iwl_apm_stop(struct iwl_priv *priv)
996 {
997         IWL_DEBUG_INFO(priv, "Stop card, put in low power state\n");
998
999         clear_bit(STATUS_DEVICE_ENABLED, &priv->status);
1000
1001         /* Stop device's DMA activity */
1002         iwl_apm_stop_master(priv);
1003
1004         /* Reset the entire device */
1005         iwl_set_bit(priv, CSR_RESET, CSR_RESET_REG_FLAG_SW_RESET);
1006
1007         udelay(10);
1008
1009         /*
1010          * Clear "initialization complete" bit to move adapter from
1011          * D0A* (powered-up Active) --> D0U* (Uninitialized) state.
1012          */
1013         iwl_clear_bit(priv, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_INIT_DONE);
1014 }
1015
1016
1017 /*
1018  * Start up NIC's basic functionality after it has been reset
1019  * (e.g. after platform boot, or shutdown via iwl_apm_stop())
1020  * NOTE:  This does not load uCode nor start the embedded processor
1021  */
1022 int iwl_apm_init(struct iwl_priv *priv)
1023 {
1024         int ret = 0;
1025         u16 lctl;
1026
1027         IWL_DEBUG_INFO(priv, "Init card's basic functions\n");
1028
1029         /*
1030          * Use "set_bit" below rather than "write", to preserve any hardware
1031          * bits already set by default after reset.
1032          */
1033
1034         /* Disable L0S exit timer (platform NMI Work/Around) */
1035         iwl_set_bit(priv, CSR_GIO_CHICKEN_BITS,
1036                           CSR_GIO_CHICKEN_BITS_REG_BIT_DIS_L0S_EXIT_TIMER);
1037
1038         /*
1039          * Disable L0s without affecting L1;
1040          *  don't wait for ICH L0s (ICH bug W/A)
1041          */
1042         iwl_set_bit(priv, CSR_GIO_CHICKEN_BITS,
1043                           CSR_GIO_CHICKEN_BITS_REG_BIT_L1A_NO_L0S_RX);
1044
1045         /* Set FH wait threshold to maximum (HW error during stress W/A) */
1046         iwl_set_bit(priv, CSR_DBG_HPET_MEM_REG, CSR_DBG_HPET_MEM_REG_VAL);
1047
1048         /*
1049          * Enable HAP INTA (interrupt from management bus) to
1050          * wake device's PCI Express link L1a -> L0s
1051          */
1052         iwl_set_bit(priv, CSR_HW_IF_CONFIG_REG,
1053                                     CSR_HW_IF_CONFIG_REG_BIT_HAP_WAKE_L1A);
1054
1055         /*
1056          * HW bug W/A for instability in PCIe bus L0->L0S->L1 transition.
1057          * Check if BIOS (or OS) enabled L1-ASPM on this device.
1058          * If so (likely), disable L0S, so device moves directly L0->L1;
1059          *    costs negligible amount of power savings.
1060          * If not (unlikely), enable L0S, so there is at least some
1061          *    power savings, even without L1.
1062          */
1063         lctl = iwl_pcie_link_ctl(priv);
1064         if ((lctl & PCI_CFG_LINK_CTRL_VAL_L1_EN) ==
1065                                 PCI_CFG_LINK_CTRL_VAL_L1_EN) {
1066                 /* L1-ASPM enabled; disable(!) L0S  */
1067                 iwl_set_bit(priv, CSR_GIO_REG,
1068                                 CSR_GIO_REG_VAL_L0S_ENABLED);
1069                 IWL_DEBUG_POWER(priv, "L1 Enabled; Disabling L0S\n");
1070         } else {
1071                 /* L1-ASPM disabled; enable(!) L0S */
1072                 iwl_clear_bit(priv, CSR_GIO_REG,
1073                                 CSR_GIO_REG_VAL_L0S_ENABLED);
1074                 IWL_DEBUG_POWER(priv, "L1 Disabled; Enabling L0S\n");
1075         }
1076
1077         /* Configure analog phase-lock-loop before activating to D0A */
1078         if (priv->cfg->base_params->pll_cfg_val)
1079                 iwl_set_bit(priv, CSR_ANA_PLL_CFG,
1080                             priv->cfg->base_params->pll_cfg_val);
1081
1082         /*
1083          * Set "initialization complete" bit to move adapter from
1084          * D0U* --> D0A* (powered-up active) state.
1085          */
1086         iwl_set_bit(priv, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_INIT_DONE);
1087
1088         /*
1089          * Wait for clock stabilization; once stabilized, access to
1090          * device-internal resources is supported, e.g. iwl_write_prph()
1091          * and accesses to uCode SRAM.
1092          */
1093         ret = iwl_poll_bit(priv, CSR_GP_CNTRL,
1094                         CSR_GP_CNTRL_REG_FLAG_MAC_CLOCK_READY,
1095                         CSR_GP_CNTRL_REG_FLAG_MAC_CLOCK_READY, 25000);
1096         if (ret < 0) {
1097                 IWL_DEBUG_INFO(priv, "Failed to init the card\n");
1098                 goto out;
1099         }
1100
1101         /*
1102          * Enable DMA clock and wait for it to stabilize.
1103          *
1104          * Write to "CLK_EN_REG"; "1" bits enable clocks, while "0" bits
1105          * do not disable clocks.  This preserves any hardware bits already
1106          * set by default in "CLK_CTRL_REG" after reset.
1107          */
1108         iwl_write_prph(priv, APMG_CLK_EN_REG, APMG_CLK_VAL_DMA_CLK_RQT);
1109         udelay(20);
1110
1111         /* Disable L1-Active */
1112         iwl_set_bits_prph(priv, APMG_PCIDEV_STT_REG,
1113                           APMG_PCIDEV_STT_VAL_L1_ACT_DIS);
1114
1115         set_bit(STATUS_DEVICE_ENABLED, &priv->status);
1116
1117 out:
1118         return ret;
1119 }
1120
1121
1122 int iwl_set_tx_power(struct iwl_priv *priv, s8 tx_power, bool force)
1123 {
1124         int ret;
1125         s8 prev_tx_power;
1126         bool defer;
1127         struct iwl_rxon_context *ctx = &priv->contexts[IWL_RXON_CTX_BSS];
1128
1129         lockdep_assert_held(&priv->mutex);
1130
1131         if (priv->tx_power_user_lmt == tx_power && !force)
1132                 return 0;
1133
1134         if (!priv->cfg->ops->lib->send_tx_power)
1135                 return -EOPNOTSUPP;
1136
1137         if (tx_power < IWLAGN_TX_POWER_TARGET_POWER_MIN) {
1138                 IWL_WARN(priv,
1139                          "Requested user TXPOWER %d below lower limit %d.\n",
1140                          tx_power,
1141                          IWLAGN_TX_POWER_TARGET_POWER_MIN);
1142                 return -EINVAL;
1143         }
1144
1145         if (tx_power > priv->tx_power_device_lmt) {
1146                 IWL_WARN(priv,
1147                         "Requested user TXPOWER %d above upper limit %d.\n",
1148                          tx_power, priv->tx_power_device_lmt);
1149                 return -EINVAL;
1150         }
1151
1152         if (!iwl_is_ready_rf(priv))
1153                 return -EIO;
1154
1155         /* scan complete and commit_rxon use tx_power_next value,
1156          * it always need to be updated for newest request */
1157         priv->tx_power_next = tx_power;
1158
1159         /* do not set tx power when scanning or channel changing */
1160         defer = test_bit(STATUS_SCANNING, &priv->status) ||
1161                 memcmp(&ctx->active, &ctx->staging, sizeof(ctx->staging));
1162         if (defer && !force) {
1163                 IWL_DEBUG_INFO(priv, "Deferring tx power set\n");
1164                 return 0;
1165         }
1166
1167         prev_tx_power = priv->tx_power_user_lmt;
1168         priv->tx_power_user_lmt = tx_power;
1169
1170         ret = priv->cfg->ops->lib->send_tx_power(priv);
1171
1172         /* if fail to set tx_power, restore the orig. tx power */
1173         if (ret) {
1174                 priv->tx_power_user_lmt = prev_tx_power;
1175                 priv->tx_power_next = prev_tx_power;
1176         }
1177         return ret;
1178 }
1179
1180 void iwl_send_bt_config(struct iwl_priv *priv)
1181 {
1182         struct iwl_bt_cmd bt_cmd = {
1183                 .lead_time = BT_LEAD_TIME_DEF,
1184                 .max_kill = BT_MAX_KILL_DEF,
1185                 .kill_ack_mask = 0,
1186                 .kill_cts_mask = 0,
1187         };
1188
1189         if (!bt_coex_active)
1190                 bt_cmd.flags = BT_COEX_DISABLE;
1191         else
1192                 bt_cmd.flags = BT_COEX_ENABLE;
1193
1194         priv->bt_enable_flag = bt_cmd.flags;
1195         IWL_DEBUG_INFO(priv, "BT coex %s\n",
1196                 (bt_cmd.flags == BT_COEX_DISABLE) ? "disable" : "active");
1197
1198         if (iwl_send_cmd_pdu(priv, REPLY_BT_CONFIG,
1199                              sizeof(struct iwl_bt_cmd), &bt_cmd))
1200                 IWL_ERR(priv, "failed to send BT Coex Config\n");
1201 }
1202
1203 int iwl_send_statistics_request(struct iwl_priv *priv, u8 flags, bool clear)
1204 {
1205         struct iwl_statistics_cmd statistics_cmd = {
1206                 .configuration_flags =
1207                         clear ? IWL_STATS_CONF_CLEAR_STATS : 0,
1208         };
1209
1210         if (flags & CMD_ASYNC)
1211                 return iwl_send_cmd_pdu_async(priv, REPLY_STATISTICS_CMD,
1212                                                sizeof(struct iwl_statistics_cmd),
1213                                                &statistics_cmd, NULL);
1214         else
1215                 return iwl_send_cmd_pdu(priv, REPLY_STATISTICS_CMD,
1216                                         sizeof(struct iwl_statistics_cmd),
1217                                         &statistics_cmd);
1218 }
1219
1220 void iwl_clear_isr_stats(struct iwl_priv *priv)
1221 {
1222         memset(&priv->isr_stats, 0, sizeof(priv->isr_stats));
1223 }
1224
1225 int iwl_mac_conf_tx(struct ieee80211_hw *hw, u16 queue,
1226                            const struct ieee80211_tx_queue_params *params)
1227 {
1228         struct iwl_priv *priv = hw->priv;
1229         struct iwl_rxon_context *ctx;
1230         unsigned long flags;
1231         int q;
1232
1233         IWL_DEBUG_MAC80211(priv, "enter\n");
1234
1235         if (!iwl_is_ready_rf(priv)) {
1236                 IWL_DEBUG_MAC80211(priv, "leave - RF not ready\n");
1237                 return -EIO;
1238         }
1239
1240         if (queue >= AC_NUM) {
1241                 IWL_DEBUG_MAC80211(priv, "leave - queue >= AC_NUM %d\n", queue);
1242                 return 0;
1243         }
1244
1245         q = AC_NUM - 1 - queue;
1246
1247         spin_lock_irqsave(&priv->lock, flags);
1248
1249         /*
1250          * MULTI-FIXME
1251          * This may need to be done per interface in nl80211/cfg80211/mac80211.
1252          */
1253         for_each_context(priv, ctx) {
1254                 ctx->qos_data.def_qos_parm.ac[q].cw_min =
1255                         cpu_to_le16(params->cw_min);
1256                 ctx->qos_data.def_qos_parm.ac[q].cw_max =
1257                         cpu_to_le16(params->cw_max);
1258                 ctx->qos_data.def_qos_parm.ac[q].aifsn = params->aifs;
1259                 ctx->qos_data.def_qos_parm.ac[q].edca_txop =
1260                                 cpu_to_le16((params->txop * 32));
1261
1262                 ctx->qos_data.def_qos_parm.ac[q].reserved1 = 0;
1263         }
1264
1265         spin_unlock_irqrestore(&priv->lock, flags);
1266
1267         IWL_DEBUG_MAC80211(priv, "leave\n");
1268         return 0;
1269 }
1270
1271 int iwl_mac_tx_last_beacon(struct ieee80211_hw *hw)
1272 {
1273         struct iwl_priv *priv = hw->priv;
1274
1275         return priv->ibss_manager == IWL_IBSS_MANAGER;
1276 }
1277
1278 static int iwl_set_mode(struct iwl_priv *priv, struct iwl_rxon_context *ctx)
1279 {
1280         iwl_connection_init_rx_config(priv, ctx);
1281
1282         if (priv->cfg->ops->hcmd->set_rxon_chain)
1283                 priv->cfg->ops->hcmd->set_rxon_chain(priv, ctx);
1284
1285         return iwlcore_commit_rxon(priv, ctx);
1286 }
1287
1288 static int iwl_setup_interface(struct iwl_priv *priv,
1289                                struct iwl_rxon_context *ctx)
1290 {
1291         struct ieee80211_vif *vif = ctx->vif;
1292         int err;
1293
1294         lockdep_assert_held(&priv->mutex);
1295
1296         /*
1297          * This variable will be correct only when there's just
1298          * a single context, but all code using it is for hardware
1299          * that supports only one context.
1300          */
1301         priv->iw_mode = vif->type;
1302
1303         ctx->is_active = true;
1304
1305         err = iwl_set_mode(priv, ctx);
1306         if (err) {
1307                 if (!ctx->always_active)
1308                         ctx->is_active = false;
1309                 return err;
1310         }
1311
1312         if (priv->cfg->bt_params && priv->cfg->bt_params->advanced_bt_coexist &&
1313             vif->type == NL80211_IFTYPE_ADHOC) {
1314                 /*
1315                  * pretend to have high BT traffic as long as we
1316                  * are operating in IBSS mode, as this will cause
1317                  * the rate scaling etc. to behave as intended.
1318                  */
1319                 priv->bt_traffic_load = IWL_BT_COEX_TRAFFIC_LOAD_HIGH;
1320         }
1321
1322         return 0;
1323 }
1324
1325 int iwl_mac_add_interface(struct ieee80211_hw *hw, struct ieee80211_vif *vif)
1326 {
1327         struct iwl_priv *priv = hw->priv;
1328         struct iwl_vif_priv *vif_priv = (void *)vif->drv_priv;
1329         struct iwl_rxon_context *tmp, *ctx = NULL;
1330         int err;
1331         enum nl80211_iftype viftype = ieee80211_vif_type_p2p(vif);
1332
1333         IWL_DEBUG_MAC80211(priv, "enter: type %d, addr %pM\n",
1334                            viftype, vif->addr);
1335
1336         mutex_lock(&priv->mutex);
1337
1338         if (!iwl_is_ready_rf(priv)) {
1339                 IWL_WARN(priv, "Try to add interface when device not ready\n");
1340                 err = -EINVAL;
1341                 goto out;
1342         }
1343
1344         for_each_context(priv, tmp) {
1345                 u32 possible_modes =
1346                         tmp->interface_modes | tmp->exclusive_interface_modes;
1347
1348                 if (tmp->vif) {
1349                         /* check if this busy context is exclusive */
1350                         if (tmp->exclusive_interface_modes &
1351                                                 BIT(tmp->vif->type)) {
1352                                 err = -EINVAL;
1353                                 goto out;
1354                         }
1355                         continue;
1356                 }
1357
1358                 if (!(possible_modes & BIT(viftype)))
1359                         continue;
1360
1361                 /* have maybe usable context w/o interface */
1362                 ctx = tmp;
1363                 break;
1364         }
1365
1366         if (!ctx) {
1367                 err = -EOPNOTSUPP;
1368                 goto out;
1369         }
1370
1371         vif_priv->ctx = ctx;
1372         ctx->vif = vif;
1373
1374         err = iwl_setup_interface(priv, ctx);
1375         if (!err)
1376                 goto out;
1377
1378         ctx->vif = NULL;
1379         priv->iw_mode = NL80211_IFTYPE_STATION;
1380  out:
1381         mutex_unlock(&priv->mutex);
1382
1383         IWL_DEBUG_MAC80211(priv, "leave\n");
1384         return err;
1385 }
1386
1387 static void iwl_teardown_interface(struct iwl_priv *priv,
1388                                    struct ieee80211_vif *vif,
1389                                    bool mode_change)
1390 {
1391         struct iwl_rxon_context *ctx = iwl_rxon_ctx_from_vif(vif);
1392
1393         lockdep_assert_held(&priv->mutex);
1394
1395         if (priv->scan_vif == vif) {
1396                 iwl_scan_cancel_timeout(priv, 200);
1397                 iwl_force_scan_end(priv);
1398         }
1399
1400         if (!mode_change) {
1401                 iwl_set_mode(priv, ctx);
1402                 if (!ctx->always_active)
1403                         ctx->is_active = false;
1404         }
1405
1406         /*
1407          * When removing the IBSS interface, overwrite the
1408          * BT traffic load with the stored one from the last
1409          * notification, if any. If this is a device that
1410          * doesn't implement this, this has no effect since
1411          * both values are the same and zero.
1412          */
1413         if (vif->type == NL80211_IFTYPE_ADHOC)
1414                 priv->bt_traffic_load = priv->last_bt_traffic_load;
1415 }
1416
1417 void iwl_mac_remove_interface(struct ieee80211_hw *hw,
1418                               struct ieee80211_vif *vif)
1419 {
1420         struct iwl_priv *priv = hw->priv;
1421         struct iwl_rxon_context *ctx = iwl_rxon_ctx_from_vif(vif);
1422
1423         IWL_DEBUG_MAC80211(priv, "enter\n");
1424
1425         mutex_lock(&priv->mutex);
1426
1427         WARN_ON(ctx->vif != vif);
1428         ctx->vif = NULL;
1429
1430         iwl_teardown_interface(priv, vif, false);
1431
1432         mutex_unlock(&priv->mutex);
1433
1434         IWL_DEBUG_MAC80211(priv, "leave\n");
1435
1436 }
1437
1438 int iwl_alloc_txq_mem(struct iwl_priv *priv)
1439 {
1440         if (!priv->txq)
1441                 priv->txq = kzalloc(
1442                         sizeof(struct iwl_tx_queue) *
1443                                 priv->cfg->base_params->num_of_queues,
1444                         GFP_KERNEL);
1445         if (!priv->txq) {
1446                 IWL_ERR(priv, "Not enough memory for txq\n");
1447                 return -ENOMEM;
1448         }
1449         return 0;
1450 }
1451
1452 void iwl_free_txq_mem(struct iwl_priv *priv)
1453 {
1454         kfree(priv->txq);
1455         priv->txq = NULL;
1456 }
1457
1458 #ifdef CONFIG_IWLWIFI_DEBUGFS
1459
1460 #define IWL_TRAFFIC_DUMP_SIZE   (IWL_TRAFFIC_ENTRY_SIZE * IWL_TRAFFIC_ENTRIES)
1461
1462 void iwl_reset_traffic_log(struct iwl_priv *priv)
1463 {
1464         priv->tx_traffic_idx = 0;
1465         priv->rx_traffic_idx = 0;
1466         if (priv->tx_traffic)
1467                 memset(priv->tx_traffic, 0, IWL_TRAFFIC_DUMP_SIZE);
1468         if (priv->rx_traffic)
1469                 memset(priv->rx_traffic, 0, IWL_TRAFFIC_DUMP_SIZE);
1470 }
1471
1472 int iwl_alloc_traffic_mem(struct iwl_priv *priv)
1473 {
1474         u32 traffic_size = IWL_TRAFFIC_DUMP_SIZE;
1475
1476         if (iwl_debug_level & IWL_DL_TX) {
1477                 if (!priv->tx_traffic) {
1478                         priv->tx_traffic =
1479                                 kzalloc(traffic_size, GFP_KERNEL);
1480                         if (!priv->tx_traffic)
1481                                 return -ENOMEM;
1482                 }
1483         }
1484         if (iwl_debug_level & IWL_DL_RX) {
1485                 if (!priv->rx_traffic) {
1486                         priv->rx_traffic =
1487                                 kzalloc(traffic_size, GFP_KERNEL);
1488                         if (!priv->rx_traffic)
1489                                 return -ENOMEM;
1490                 }
1491         }
1492         iwl_reset_traffic_log(priv);
1493         return 0;
1494 }
1495
1496 void iwl_free_traffic_mem(struct iwl_priv *priv)
1497 {
1498         kfree(priv->tx_traffic);
1499         priv->tx_traffic = NULL;
1500
1501         kfree(priv->rx_traffic);
1502         priv->rx_traffic = NULL;
1503 }
1504
1505 void iwl_dbg_log_tx_data_frame(struct iwl_priv *priv,
1506                       u16 length, struct ieee80211_hdr *header)
1507 {
1508         __le16 fc;
1509         u16 len;
1510
1511         if (likely(!(iwl_debug_level & IWL_DL_TX)))
1512                 return;
1513
1514         if (!priv->tx_traffic)
1515                 return;
1516
1517         fc = header->frame_control;
1518         if (ieee80211_is_data(fc)) {
1519                 len = (length > IWL_TRAFFIC_ENTRY_SIZE)
1520                        ? IWL_TRAFFIC_ENTRY_SIZE : length;
1521                 memcpy((priv->tx_traffic +
1522                        (priv->tx_traffic_idx * IWL_TRAFFIC_ENTRY_SIZE)),
1523                        header, len);
1524                 priv->tx_traffic_idx =
1525                         (priv->tx_traffic_idx + 1) % IWL_TRAFFIC_ENTRIES;
1526         }
1527 }
1528
1529 void iwl_dbg_log_rx_data_frame(struct iwl_priv *priv,
1530                       u16 length, struct ieee80211_hdr *header)
1531 {
1532         __le16 fc;
1533         u16 len;
1534
1535         if (likely(!(iwl_debug_level & IWL_DL_RX)))
1536                 return;
1537
1538         if (!priv->rx_traffic)
1539                 return;
1540
1541         fc = header->frame_control;
1542         if (ieee80211_is_data(fc)) {
1543                 len = (length > IWL_TRAFFIC_ENTRY_SIZE)
1544                        ? IWL_TRAFFIC_ENTRY_SIZE : length;
1545                 memcpy((priv->rx_traffic +
1546                        (priv->rx_traffic_idx * IWL_TRAFFIC_ENTRY_SIZE)),
1547                        header, len);
1548                 priv->rx_traffic_idx =
1549                         (priv->rx_traffic_idx + 1) % IWL_TRAFFIC_ENTRIES;
1550         }
1551 }
1552
1553 const char *get_mgmt_string(int cmd)
1554 {
1555         switch (cmd) {
1556                 IWL_CMD(MANAGEMENT_ASSOC_REQ);
1557                 IWL_CMD(MANAGEMENT_ASSOC_RESP);
1558                 IWL_CMD(MANAGEMENT_REASSOC_REQ);
1559                 IWL_CMD(MANAGEMENT_REASSOC_RESP);
1560                 IWL_CMD(MANAGEMENT_PROBE_REQ);
1561                 IWL_CMD(MANAGEMENT_PROBE_RESP);
1562                 IWL_CMD(MANAGEMENT_BEACON);
1563                 IWL_CMD(MANAGEMENT_ATIM);
1564                 IWL_CMD(MANAGEMENT_DISASSOC);
1565                 IWL_CMD(MANAGEMENT_AUTH);
1566                 IWL_CMD(MANAGEMENT_DEAUTH);
1567                 IWL_CMD(MANAGEMENT_ACTION);
1568         default:
1569                 return "UNKNOWN";
1570
1571         }
1572 }
1573
1574 const char *get_ctrl_string(int cmd)
1575 {
1576         switch (cmd) {
1577                 IWL_CMD(CONTROL_BACK_REQ);
1578                 IWL_CMD(CONTROL_BACK);
1579                 IWL_CMD(CONTROL_PSPOLL);
1580                 IWL_CMD(CONTROL_RTS);
1581                 IWL_CMD(CONTROL_CTS);
1582                 IWL_CMD(CONTROL_ACK);
1583                 IWL_CMD(CONTROL_CFEND);
1584                 IWL_CMD(CONTROL_CFENDACK);
1585         default:
1586                 return "UNKNOWN";
1587
1588         }
1589 }
1590
1591 void iwl_clear_traffic_stats(struct iwl_priv *priv)
1592 {
1593         memset(&priv->tx_stats, 0, sizeof(struct traffic_stats));
1594         memset(&priv->rx_stats, 0, sizeof(struct traffic_stats));
1595 }
1596
1597 /*
1598  * if CONFIG_IWLWIFI_DEBUGFS defined, iwl_update_stats function will
1599  * record all the MGMT, CTRL and DATA pkt for both TX and Rx pass.
1600  * Use debugFs to display the rx/rx_statistics
1601  * if CONFIG_IWLWIFI_DEBUGFS not being defined, then no MGMT and CTRL
1602  * information will be recorded, but DATA pkt still will be recorded
1603  * for the reason of iwl_led.c need to control the led blinking based on
1604  * number of tx and rx data.
1605  *
1606  */
1607 void iwl_update_stats(struct iwl_priv *priv, bool is_tx, __le16 fc, u16 len)
1608 {
1609         struct traffic_stats    *stats;
1610
1611         if (is_tx)
1612                 stats = &priv->tx_stats;
1613         else
1614                 stats = &priv->rx_stats;
1615
1616         if (ieee80211_is_mgmt(fc)) {
1617                 switch (fc & cpu_to_le16(IEEE80211_FCTL_STYPE)) {
1618                 case cpu_to_le16(IEEE80211_STYPE_ASSOC_REQ):
1619                         stats->mgmt[MANAGEMENT_ASSOC_REQ]++;
1620                         break;
1621                 case cpu_to_le16(IEEE80211_STYPE_ASSOC_RESP):
1622                         stats->mgmt[MANAGEMENT_ASSOC_RESP]++;
1623                         break;
1624                 case cpu_to_le16(IEEE80211_STYPE_REASSOC_REQ):
1625                         stats->mgmt[MANAGEMENT_REASSOC_REQ]++;
1626                         break;
1627                 case cpu_to_le16(IEEE80211_STYPE_REASSOC_RESP):
1628                         stats->mgmt[MANAGEMENT_REASSOC_RESP]++;
1629                         break;
1630                 case cpu_to_le16(IEEE80211_STYPE_PROBE_REQ):
1631                         stats->mgmt[MANAGEMENT_PROBE_REQ]++;
1632                         break;
1633                 case cpu_to_le16(IEEE80211_STYPE_PROBE_RESP):
1634                         stats->mgmt[MANAGEMENT_PROBE_RESP]++;
1635                         break;
1636                 case cpu_to_le16(IEEE80211_STYPE_BEACON):
1637                         stats->mgmt[MANAGEMENT_BEACON]++;
1638                         break;
1639                 case cpu_to_le16(IEEE80211_STYPE_ATIM):
1640                         stats->mgmt[MANAGEMENT_ATIM]++;
1641                         break;
1642                 case cpu_to_le16(IEEE80211_STYPE_DISASSOC):
1643                         stats->mgmt[MANAGEMENT_DISASSOC]++;
1644                         break;
1645                 case cpu_to_le16(IEEE80211_STYPE_AUTH):
1646                         stats->mgmt[MANAGEMENT_AUTH]++;
1647                         break;
1648                 case cpu_to_le16(IEEE80211_STYPE_DEAUTH):
1649                         stats->mgmt[MANAGEMENT_DEAUTH]++;
1650                         break;
1651                 case cpu_to_le16(IEEE80211_STYPE_ACTION):
1652                         stats->mgmt[MANAGEMENT_ACTION]++;
1653                         break;
1654                 }
1655         } else if (ieee80211_is_ctl(fc)) {
1656                 switch (fc & cpu_to_le16(IEEE80211_FCTL_STYPE)) {
1657                 case cpu_to_le16(IEEE80211_STYPE_BACK_REQ):
1658                         stats->ctrl[CONTROL_BACK_REQ]++;
1659                         break;
1660                 case cpu_to_le16(IEEE80211_STYPE_BACK):
1661                         stats->ctrl[CONTROL_BACK]++;
1662                         break;
1663                 case cpu_to_le16(IEEE80211_STYPE_PSPOLL):
1664                         stats->ctrl[CONTROL_PSPOLL]++;
1665                         break;
1666                 case cpu_to_le16(IEEE80211_STYPE_RTS):
1667                         stats->ctrl[CONTROL_RTS]++;
1668                         break;
1669                 case cpu_to_le16(IEEE80211_STYPE_CTS):
1670                         stats->ctrl[CONTROL_CTS]++;
1671                         break;
1672                 case cpu_to_le16(IEEE80211_STYPE_ACK):
1673                         stats->ctrl[CONTROL_ACK]++;
1674                         break;
1675                 case cpu_to_le16(IEEE80211_STYPE_CFEND):
1676                         stats->ctrl[CONTROL_CFEND]++;
1677                         break;
1678                 case cpu_to_le16(IEEE80211_STYPE_CFENDACK):
1679                         stats->ctrl[CONTROL_CFENDACK]++;
1680                         break;
1681                 }
1682         } else {
1683                 /* data */
1684                 stats->data_cnt++;
1685                 stats->data_bytes += len;
1686         }
1687 }
1688 #endif
1689
1690 static void iwl_force_rf_reset(struct iwl_priv *priv)
1691 {
1692         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
1693                 return;
1694
1695         if (!iwl_is_any_associated(priv)) {
1696                 IWL_DEBUG_SCAN(priv, "force reset rejected: not associated\n");
1697                 return;
1698         }
1699         /*
1700          * There is no easy and better way to force reset the radio,
1701          * the only known method is switching channel which will force to
1702          * reset and tune the radio.
1703          * Use internal short scan (single channel) operation to should
1704          * achieve this objective.
1705          * Driver should reset the radio when number of consecutive missed
1706          * beacon, or any other uCode error condition detected.
1707          */
1708         IWL_DEBUG_INFO(priv, "perform radio reset.\n");
1709         iwl_internal_short_hw_scan(priv);
1710 }
1711
1712
1713 int iwl_force_reset(struct iwl_priv *priv, int mode, bool external)
1714 {
1715         struct iwl_force_reset *force_reset;
1716
1717         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
1718                 return -EINVAL;
1719
1720         if (mode >= IWL_MAX_FORCE_RESET) {
1721                 IWL_DEBUG_INFO(priv, "invalid reset request.\n");
1722                 return -EINVAL;
1723         }
1724         force_reset = &priv->force_reset[mode];
1725         force_reset->reset_request_count++;
1726         if (!external) {
1727                 if (force_reset->last_force_reset_jiffies &&
1728                     time_after(force_reset->last_force_reset_jiffies +
1729                     force_reset->reset_duration, jiffies)) {
1730                         IWL_DEBUG_INFO(priv, "force reset rejected\n");
1731                         force_reset->reset_reject_count++;
1732                         return -EAGAIN;
1733                 }
1734         }
1735         force_reset->reset_success_count++;
1736         force_reset->last_force_reset_jiffies = jiffies;
1737         IWL_DEBUG_INFO(priv, "perform force reset (%d)\n", mode);
1738         switch (mode) {
1739         case IWL_RF_RESET:
1740                 iwl_force_rf_reset(priv);
1741                 break;
1742         case IWL_FW_RESET:
1743                 /*
1744                  * if the request is from external(ex: debugfs),
1745                  * then always perform the request in regardless the module
1746                  * parameter setting
1747                  * if the request is from internal (uCode error or driver
1748                  * detect failure), then fw_restart module parameter
1749                  * need to be check before performing firmware reload
1750                  */
1751                 if (!external && !iwlagn_mod_params.restart_fw) {
1752                         IWL_DEBUG_INFO(priv, "Cancel firmware reload based on "
1753                                        "module parameter setting\n");
1754                         break;
1755                 }
1756                 IWL_ERR(priv, "On demand firmware reload\n");
1757                 iwlagn_fw_error(priv, true);
1758                 break;
1759         }
1760         return 0;
1761 }
1762
1763 int iwl_mac_change_interface(struct ieee80211_hw *hw, struct ieee80211_vif *vif,
1764                              enum nl80211_iftype newtype, bool newp2p)
1765 {
1766         struct iwl_priv *priv = hw->priv;
1767         struct iwl_rxon_context *ctx = iwl_rxon_ctx_from_vif(vif);
1768         struct iwl_rxon_context *bss_ctx = &priv->contexts[IWL_RXON_CTX_BSS];
1769         struct iwl_rxon_context *tmp;
1770         u32 interface_modes;
1771         int err;
1772
1773         newtype = ieee80211_iftype_p2p(newtype, newp2p);
1774
1775         mutex_lock(&priv->mutex);
1776
1777         if (!ctx->vif || !iwl_is_ready_rf(priv)) {
1778                 /*
1779                  * Huh? But wait ... this can maybe happen when
1780                  * we're in the middle of a firmware restart!
1781                  */
1782                 err = -EBUSY;
1783                 goto out;
1784         }
1785
1786         interface_modes = ctx->interface_modes | ctx->exclusive_interface_modes;
1787
1788         if (!(interface_modes & BIT(newtype))) {
1789                 err = -EBUSY;
1790                 goto out;
1791         }
1792
1793         /*
1794          * Refuse a change that should be done by moving from the PAN
1795          * context to the BSS context instead, if the BSS context is
1796          * available and can support the new interface type.
1797          */
1798         if (ctx->ctxid == IWL_RXON_CTX_PAN && !bss_ctx->vif &&
1799             (bss_ctx->interface_modes & BIT(newtype) ||
1800              bss_ctx->exclusive_interface_modes & BIT(newtype))) {
1801                 BUILD_BUG_ON(NUM_IWL_RXON_CTX != 2);
1802                 err = -EBUSY;
1803                 goto out;
1804         }
1805
1806         if (ctx->exclusive_interface_modes & BIT(newtype)) {
1807                 for_each_context(priv, tmp) {
1808                         if (ctx == tmp)
1809                                 continue;
1810
1811                         if (!tmp->vif)
1812                                 continue;
1813
1814                         /*
1815                          * The current mode switch would be exclusive, but
1816                          * another context is active ... refuse the switch.
1817                          */
1818                         err = -EBUSY;
1819                         goto out;
1820                 }
1821         }
1822
1823         /* success */
1824         iwl_teardown_interface(priv, vif, true);
1825         vif->type = newtype;
1826         vif->p2p = newp2p;
1827         err = iwl_setup_interface(priv, ctx);
1828         WARN_ON(err);
1829         /*
1830          * We've switched internally, but submitting to the
1831          * device may have failed for some reason. Mask this
1832          * error, because otherwise mac80211 will not switch
1833          * (and set the interface type back) and we'll be
1834          * out of sync with it.
1835          */
1836         err = 0;
1837
1838  out:
1839         mutex_unlock(&priv->mutex);
1840         return err;
1841 }
1842
1843 /*
1844  * On every watchdog tick we check (latest) time stamp. If it does not
1845  * change during timeout period and queue is not empty we reset firmware.
1846  */
1847 static int iwl_check_stuck_queue(struct iwl_priv *priv, int cnt)
1848 {
1849         struct iwl_tx_queue *txq = &priv->txq[cnt];
1850         struct iwl_queue *q = &txq->q;
1851         unsigned long timeout;
1852         int ret;
1853
1854         if (q->read_ptr == q->write_ptr) {
1855                 txq->time_stamp = jiffies;
1856                 return 0;
1857         }
1858
1859         timeout = txq->time_stamp +
1860                   msecs_to_jiffies(priv->cfg->base_params->wd_timeout);
1861
1862         if (time_after(jiffies, timeout)) {
1863                 IWL_ERR(priv, "Queue %d stuck for %u ms.\n",
1864                                 q->id, priv->cfg->base_params->wd_timeout);
1865                 ret = iwl_force_reset(priv, IWL_FW_RESET, false);
1866                 return (ret == -EAGAIN) ? 0 : 1;
1867         }
1868
1869         return 0;
1870 }
1871
1872 /*
1873  * Making watchdog tick be a quarter of timeout assure we will
1874  * discover the queue hung between timeout and 1.25*timeout
1875  */
1876 #define IWL_WD_TICK(timeout) ((timeout) / 4)
1877
1878 /*
1879  * Watchdog timer callback, we check each tx queue for stuck, if if hung
1880  * we reset the firmware. If everything is fine just rearm the timer.
1881  */
1882 void iwl_bg_watchdog(unsigned long data)
1883 {
1884         struct iwl_priv *priv = (struct iwl_priv *)data;
1885         int cnt;
1886         unsigned long timeout;
1887
1888         if (test_bit(STATUS_EXIT_PENDING, &priv->status))
1889                 return;
1890
1891         timeout = priv->cfg->base_params->wd_timeout;
1892         if (timeout == 0)
1893                 return;
1894
1895         /* monitor and check for stuck cmd queue */
1896         if (iwl_check_stuck_queue(priv, priv->cmd_queue))
1897                 return;
1898
1899         /* monitor and check for other stuck queues */
1900         if (iwl_is_any_associated(priv)) {
1901                 for (cnt = 0; cnt < priv->hw_params.max_txq_num; cnt++) {
1902                         /* skip as we already checked the command queue */
1903                         if (cnt == priv->cmd_queue)
1904                                 continue;
1905                         if (iwl_check_stuck_queue(priv, cnt))
1906                                 return;
1907                 }
1908         }
1909
1910         mod_timer(&priv->watchdog, jiffies +
1911                   msecs_to_jiffies(IWL_WD_TICK(timeout)));
1912 }
1913
1914 void iwl_setup_watchdog(struct iwl_priv *priv)
1915 {
1916         unsigned int timeout = priv->cfg->base_params->wd_timeout;
1917
1918         if (timeout)
1919                 mod_timer(&priv->watchdog,
1920                           jiffies + msecs_to_jiffies(IWL_WD_TICK(timeout)));
1921         else
1922                 del_timer(&priv->watchdog);
1923 }
1924
1925 /*
1926  * extended beacon time format
1927  * time in usec will be changed into a 32-bit value in extended:internal format
1928  * the extended part is the beacon counts
1929  * the internal part is the time in usec within one beacon interval
1930  */
1931 u32 iwl_usecs_to_beacons(struct iwl_priv *priv, u32 usec, u32 beacon_interval)
1932 {
1933         u32 quot;
1934         u32 rem;
1935         u32 interval = beacon_interval * TIME_UNIT;
1936
1937         if (!interval || !usec)
1938                 return 0;
1939
1940         quot = (usec / interval) &
1941                 (iwl_beacon_time_mask_high(priv,
1942                 priv->hw_params.beacon_time_tsf_bits) >>
1943                 priv->hw_params.beacon_time_tsf_bits);
1944         rem = (usec % interval) & iwl_beacon_time_mask_low(priv,
1945                                    priv->hw_params.beacon_time_tsf_bits);
1946
1947         return (quot << priv->hw_params.beacon_time_tsf_bits) + rem;
1948 }
1949
1950 /* base is usually what we get from ucode with each received frame,
1951  * the same as HW timer counter counting down
1952  */
1953 __le32 iwl_add_beacon_time(struct iwl_priv *priv, u32 base,
1954                            u32 addon, u32 beacon_interval)
1955 {
1956         u32 base_low = base & iwl_beacon_time_mask_low(priv,
1957                                         priv->hw_params.beacon_time_tsf_bits);
1958         u32 addon_low = addon & iwl_beacon_time_mask_low(priv,
1959                                         priv->hw_params.beacon_time_tsf_bits);
1960         u32 interval = beacon_interval * TIME_UNIT;
1961         u32 res = (base & iwl_beacon_time_mask_high(priv,
1962                                 priv->hw_params.beacon_time_tsf_bits)) +
1963                                 (addon & iwl_beacon_time_mask_high(priv,
1964                                 priv->hw_params.beacon_time_tsf_bits));
1965
1966         if (base_low > addon_low)
1967                 res += base_low - addon_low;
1968         else if (base_low < addon_low) {
1969                 res += interval + base_low - addon_low;
1970                 res += (1 << priv->hw_params.beacon_time_tsf_bits);
1971         } else
1972                 res += (1 << priv->hw_params.beacon_time_tsf_bits);
1973
1974         return cpu_to_le32(res);
1975 }
1976
1977 #ifdef CONFIG_PM
1978
1979 int iwl_pci_suspend(struct device *device)
1980 {
1981         struct pci_dev *pdev = to_pci_dev(device);
1982         struct iwl_priv *priv = pci_get_drvdata(pdev);
1983
1984         /*
1985          * This function is called when system goes into suspend state
1986          * mac80211 will call iwl_mac_stop() from the mac80211 suspend function
1987          * first but since iwl_mac_stop() has no knowledge of who the caller is,
1988          * it will not call apm_ops.stop() to stop the DMA operation.
1989          * Calling apm_ops.stop here to make sure we stop the DMA.
1990          */
1991         iwl_apm_stop(priv);
1992
1993         return 0;
1994 }
1995
1996 int iwl_pci_resume(struct device *device)
1997 {
1998         struct pci_dev *pdev = to_pci_dev(device);
1999         struct iwl_priv *priv = pci_get_drvdata(pdev);
2000         bool hw_rfkill = false;
2001
2002         /*
2003          * We disable the RETRY_TIMEOUT register (0x41) to keep
2004          * PCI Tx retries from interfering with C3 CPU state.
2005          */
2006         pci_write_config_byte(pdev, PCI_CFG_RETRY_TIMEOUT, 0x00);
2007
2008         iwl_enable_interrupts(priv);
2009
2010         if (!(iwl_read32(priv, CSR_GP_CNTRL) &
2011                                 CSR_GP_CNTRL_REG_FLAG_HW_RF_KILL_SW))
2012                 hw_rfkill = true;
2013
2014         if (hw_rfkill)
2015                 set_bit(STATUS_RF_KILL_HW, &priv->status);
2016         else
2017                 clear_bit(STATUS_RF_KILL_HW, &priv->status);
2018
2019         wiphy_rfkill_set_hw_state(priv->hw->wiphy, hw_rfkill);
2020
2021         return 0;
2022 }
2023
2024 const struct dev_pm_ops iwl_pm_ops = {
2025         .suspend = iwl_pci_suspend,
2026         .resume = iwl_pci_resume,
2027         .freeze = iwl_pci_suspend,
2028         .thaw = iwl_pci_resume,
2029         .poweroff = iwl_pci_suspend,
2030         .restore = iwl_pci_resume,
2031 };
2032
2033 #endif /* CONFIG_PM */