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