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