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