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