iwlagn: remove the indirection for the dma channel num
[pandora-kernel.git] / drivers / net / wireless / iwlwifi / iwl-agn-calib.c
1 /******************************************************************************
2  *
3  * This file is provided under a dual BSD/GPLv2 license.  When using or
4  * redistributing this file, you may do so under either license.
5  *
6  * GPL LICENSE SUMMARY
7  *
8  * Copyright(c) 2008 - 2011 Intel Corporation. All rights reserved.
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of version 2 of the GNU General Public License as
12  * published by the Free Software Foundation.
13  *
14  * This program is distributed in the hope that it will be useful, but
15  * WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110,
22  * USA
23  *
24  * The full GNU General Public License is included in this distribution
25  * in the file called LICENSE.GPL.
26  *
27  * Contact Information:
28  *  Intel Linux Wireless <ilw@linux.intel.com>
29  * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
30  *
31  * BSD LICENSE
32  *
33  * Copyright(c) 2005 - 2011 Intel Corporation. All rights reserved.
34  * All rights reserved.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions
38  * are met:
39  *
40  *  * Redistributions of source code must retain the above copyright
41  *    notice, this list of conditions and the following disclaimer.
42  *  * Redistributions in binary form must reproduce the above copyright
43  *    notice, this list of conditions and the following disclaimer in
44  *    the documentation and/or other materials provided with the
45  *    distribution.
46  *  * Neither the name Intel Corporation nor the names of its
47  *    contributors may be used to endorse or promote products derived
48  *    from this software without specific prior written permission.
49  *
50  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
51  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
52  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
53  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
54  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
55  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
56  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
57  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
58  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
59  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
60  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
61  *****************************************************************************/
62
63 #include <linux/slab.h>
64 #include <net/mac80211.h>
65
66 #include "iwl-dev.h"
67 #include "iwl-core.h"
68 #include "iwl-agn-calib.h"
69
70 /*****************************************************************************
71  * INIT calibrations framework
72  *****************************************************************************/
73
74 struct statistics_general_data {
75         u32 beacon_silence_rssi_a;
76         u32 beacon_silence_rssi_b;
77         u32 beacon_silence_rssi_c;
78         u32 beacon_energy_a;
79         u32 beacon_energy_b;
80         u32 beacon_energy_c;
81 };
82
83 int iwl_send_calib_results(struct iwl_priv *priv)
84 {
85         int ret = 0;
86         int i = 0;
87
88         struct iwl_host_cmd hcmd = {
89                 .id = REPLY_PHY_CALIBRATION_CMD,
90                 .flags = CMD_SYNC,
91         };
92
93         for (i = 0; i < IWL_CALIB_MAX; i++) {
94                 if ((BIT(i) & priv->hw_params.calib_init_cfg) &&
95                     priv->calib_results[i].buf) {
96                         hcmd.len[0] = priv->calib_results[i].buf_len;
97                         hcmd.data[0] = priv->calib_results[i].buf;
98                         hcmd.dataflags[0] = IWL_HCMD_DFL_NOCOPY;
99                         ret = priv->trans.ops->send_cmd(priv, &hcmd);
100                         if (ret) {
101                                 IWL_ERR(priv, "Error %d iteration %d\n",
102                                         ret, i);
103                                 break;
104                         }
105                 }
106         }
107
108         return ret;
109 }
110
111 int iwl_calib_set(struct iwl_calib_result *res, const u8 *buf, int len)
112 {
113         if (res->buf_len != len) {
114                 kfree(res->buf);
115                 res->buf = kzalloc(len, GFP_ATOMIC);
116         }
117         if (unlikely(res->buf == NULL))
118                 return -ENOMEM;
119
120         res->buf_len = len;
121         memcpy(res->buf, buf, len);
122         return 0;
123 }
124
125 void iwl_calib_free_results(struct iwl_priv *priv)
126 {
127         int i;
128
129         for (i = 0; i < IWL_CALIB_MAX; i++) {
130                 kfree(priv->calib_results[i].buf);
131                 priv->calib_results[i].buf = NULL;
132                 priv->calib_results[i].buf_len = 0;
133         }
134 }
135
136 /*****************************************************************************
137  * RUNTIME calibrations framework
138  *****************************************************************************/
139
140 /* "false alarms" are signals that our DSP tries to lock onto,
141  *   but then determines that they are either noise, or transmissions
142  *   from a distant wireless network (also "noise", really) that get
143  *   "stepped on" by stronger transmissions within our own network.
144  * This algorithm attempts to set a sensitivity level that is high
145  *   enough to receive all of our own network traffic, but not so
146  *   high that our DSP gets too busy trying to lock onto non-network
147  *   activity/noise. */
148 static int iwl_sens_energy_cck(struct iwl_priv *priv,
149                                    u32 norm_fa,
150                                    u32 rx_enable_time,
151                                    struct statistics_general_data *rx_info)
152 {
153         u32 max_nrg_cck = 0;
154         int i = 0;
155         u8 max_silence_rssi = 0;
156         u32 silence_ref = 0;
157         u8 silence_rssi_a = 0;
158         u8 silence_rssi_b = 0;
159         u8 silence_rssi_c = 0;
160         u32 val;
161
162         /* "false_alarms" values below are cross-multiplications to assess the
163          *   numbers of false alarms within the measured period of actual Rx
164          *   (Rx is off when we're txing), vs the min/max expected false alarms
165          *   (some should be expected if rx is sensitive enough) in a
166          *   hypothetical listening period of 200 time units (TU), 204.8 msec:
167          *
168          * MIN_FA/fixed-time < false_alarms/actual-rx-time < MAX_FA/beacon-time
169          *
170          * */
171         u32 false_alarms = norm_fa * 200 * 1024;
172         u32 max_false_alarms = MAX_FA_CCK * rx_enable_time;
173         u32 min_false_alarms = MIN_FA_CCK * rx_enable_time;
174         struct iwl_sensitivity_data *data = NULL;
175         const struct iwl_sensitivity_ranges *ranges = priv->hw_params.sens;
176
177         data = &(priv->sensitivity_data);
178
179         data->nrg_auto_corr_silence_diff = 0;
180
181         /* Find max silence rssi among all 3 receivers.
182          * This is background noise, which may include transmissions from other
183          *    networks, measured during silence before our network's beacon */
184         silence_rssi_a = (u8)((rx_info->beacon_silence_rssi_a &
185                             ALL_BAND_FILTER) >> 8);
186         silence_rssi_b = (u8)((rx_info->beacon_silence_rssi_b &
187                             ALL_BAND_FILTER) >> 8);
188         silence_rssi_c = (u8)((rx_info->beacon_silence_rssi_c &
189                             ALL_BAND_FILTER) >> 8);
190
191         val = max(silence_rssi_b, silence_rssi_c);
192         max_silence_rssi = max(silence_rssi_a, (u8) val);
193
194         /* Store silence rssi in 20-beacon history table */
195         data->nrg_silence_rssi[data->nrg_silence_idx] = max_silence_rssi;
196         data->nrg_silence_idx++;
197         if (data->nrg_silence_idx >= NRG_NUM_PREV_STAT_L)
198                 data->nrg_silence_idx = 0;
199
200         /* Find max silence rssi across 20 beacon history */
201         for (i = 0; i < NRG_NUM_PREV_STAT_L; i++) {
202                 val = data->nrg_silence_rssi[i];
203                 silence_ref = max(silence_ref, val);
204         }
205         IWL_DEBUG_CALIB(priv, "silence a %u, b %u, c %u, 20-bcn max %u\n",
206                         silence_rssi_a, silence_rssi_b, silence_rssi_c,
207                         silence_ref);
208
209         /* Find max rx energy (min value!) among all 3 receivers,
210          *   measured during beacon frame.
211          * Save it in 10-beacon history table. */
212         i = data->nrg_energy_idx;
213         val = min(rx_info->beacon_energy_b, rx_info->beacon_energy_c);
214         data->nrg_value[i] = min(rx_info->beacon_energy_a, val);
215
216         data->nrg_energy_idx++;
217         if (data->nrg_energy_idx >= 10)
218                 data->nrg_energy_idx = 0;
219
220         /* Find min rx energy (max value) across 10 beacon history.
221          * This is the minimum signal level that we want to receive well.
222          * Add backoff (margin so we don't miss slightly lower energy frames).
223          * This establishes an upper bound (min value) for energy threshold. */
224         max_nrg_cck = data->nrg_value[0];
225         for (i = 1; i < 10; i++)
226                 max_nrg_cck = (u32) max(max_nrg_cck, (data->nrg_value[i]));
227         max_nrg_cck += 6;
228
229         IWL_DEBUG_CALIB(priv, "rx energy a %u, b %u, c %u, 10-bcn max/min %u\n",
230                         rx_info->beacon_energy_a, rx_info->beacon_energy_b,
231                         rx_info->beacon_energy_c, max_nrg_cck - 6);
232
233         /* Count number of consecutive beacons with fewer-than-desired
234          *   false alarms. */
235         if (false_alarms < min_false_alarms)
236                 data->num_in_cck_no_fa++;
237         else
238                 data->num_in_cck_no_fa = 0;
239         IWL_DEBUG_CALIB(priv, "consecutive bcns with few false alarms = %u\n",
240                         data->num_in_cck_no_fa);
241
242         /* If we got too many false alarms this time, reduce sensitivity */
243         if ((false_alarms > max_false_alarms) &&
244                 (data->auto_corr_cck > AUTO_CORR_MAX_TH_CCK)) {
245                 IWL_DEBUG_CALIB(priv, "norm FA %u > max FA %u\n",
246                      false_alarms, max_false_alarms);
247                 IWL_DEBUG_CALIB(priv, "... reducing sensitivity\n");
248                 data->nrg_curr_state = IWL_FA_TOO_MANY;
249                 /* Store for "fewer than desired" on later beacon */
250                 data->nrg_silence_ref = silence_ref;
251
252                 /* increase energy threshold (reduce nrg value)
253                  *   to decrease sensitivity */
254                 data->nrg_th_cck = data->nrg_th_cck - NRG_STEP_CCK;
255         /* Else if we got fewer than desired, increase sensitivity */
256         } else if (false_alarms < min_false_alarms) {
257                 data->nrg_curr_state = IWL_FA_TOO_FEW;
258
259                 /* Compare silence level with silence level for most recent
260                  *   healthy number or too many false alarms */
261                 data->nrg_auto_corr_silence_diff = (s32)data->nrg_silence_ref -
262                                                    (s32)silence_ref;
263
264                 IWL_DEBUG_CALIB(priv, "norm FA %u < min FA %u, silence diff %d\n",
265                          false_alarms, min_false_alarms,
266                          data->nrg_auto_corr_silence_diff);
267
268                 /* Increase value to increase sensitivity, but only if:
269                  * 1a) previous beacon did *not* have *too many* false alarms
270                  * 1b) AND there's a significant difference in Rx levels
271                  *      from a previous beacon with too many, or healthy # FAs
272                  * OR 2) We've seen a lot of beacons (100) with too few
273                  *       false alarms */
274                 if ((data->nrg_prev_state != IWL_FA_TOO_MANY) &&
275                         ((data->nrg_auto_corr_silence_diff > NRG_DIFF) ||
276                         (data->num_in_cck_no_fa > MAX_NUMBER_CCK_NO_FA))) {
277
278                         IWL_DEBUG_CALIB(priv, "... increasing sensitivity\n");
279                         /* Increase nrg value to increase sensitivity */
280                         val = data->nrg_th_cck + NRG_STEP_CCK;
281                         data->nrg_th_cck = min((u32)ranges->min_nrg_cck, val);
282                 } else {
283                         IWL_DEBUG_CALIB(priv, "... but not changing sensitivity\n");
284                 }
285
286         /* Else we got a healthy number of false alarms, keep status quo */
287         } else {
288                 IWL_DEBUG_CALIB(priv, " FA in safe zone\n");
289                 data->nrg_curr_state = IWL_FA_GOOD_RANGE;
290
291                 /* Store for use in "fewer than desired" with later beacon */
292                 data->nrg_silence_ref = silence_ref;
293
294                 /* If previous beacon had too many false alarms,
295                  *   give it some extra margin by reducing sensitivity again
296                  *   (but don't go below measured energy of desired Rx) */
297                 if (IWL_FA_TOO_MANY == data->nrg_prev_state) {
298                         IWL_DEBUG_CALIB(priv, "... increasing margin\n");
299                         if (data->nrg_th_cck > (max_nrg_cck + NRG_MARGIN))
300                                 data->nrg_th_cck -= NRG_MARGIN;
301                         else
302                                 data->nrg_th_cck = max_nrg_cck;
303                 }
304         }
305
306         /* Make sure the energy threshold does not go above the measured
307          * energy of the desired Rx signals (reduced by backoff margin),
308          * or else we might start missing Rx frames.
309          * Lower value is higher energy, so we use max()!
310          */
311         data->nrg_th_cck = max(max_nrg_cck, data->nrg_th_cck);
312         IWL_DEBUG_CALIB(priv, "new nrg_th_cck %u\n", data->nrg_th_cck);
313
314         data->nrg_prev_state = data->nrg_curr_state;
315
316         /* Auto-correlation CCK algorithm */
317         if (false_alarms > min_false_alarms) {
318
319                 /* increase auto_corr values to decrease sensitivity
320                  * so the DSP won't be disturbed by the noise
321                  */
322                 if (data->auto_corr_cck < AUTO_CORR_MAX_TH_CCK)
323                         data->auto_corr_cck = AUTO_CORR_MAX_TH_CCK + 1;
324                 else {
325                         val = data->auto_corr_cck + AUTO_CORR_STEP_CCK;
326                         data->auto_corr_cck =
327                                 min((u32)ranges->auto_corr_max_cck, val);
328                 }
329                 val = data->auto_corr_cck_mrc + AUTO_CORR_STEP_CCK;
330                 data->auto_corr_cck_mrc =
331                         min((u32)ranges->auto_corr_max_cck_mrc, val);
332         } else if ((false_alarms < min_false_alarms) &&
333            ((data->nrg_auto_corr_silence_diff > NRG_DIFF) ||
334            (data->num_in_cck_no_fa > MAX_NUMBER_CCK_NO_FA))) {
335
336                 /* Decrease auto_corr values to increase sensitivity */
337                 val = data->auto_corr_cck - AUTO_CORR_STEP_CCK;
338                 data->auto_corr_cck =
339                         max((u32)ranges->auto_corr_min_cck, val);
340                 val = data->auto_corr_cck_mrc - AUTO_CORR_STEP_CCK;
341                 data->auto_corr_cck_mrc =
342                         max((u32)ranges->auto_corr_min_cck_mrc, val);
343         }
344
345         return 0;
346 }
347
348
349 static int iwl_sens_auto_corr_ofdm(struct iwl_priv *priv,
350                                        u32 norm_fa,
351                                        u32 rx_enable_time)
352 {
353         u32 val;
354         u32 false_alarms = norm_fa * 200 * 1024;
355         u32 max_false_alarms = MAX_FA_OFDM * rx_enable_time;
356         u32 min_false_alarms = MIN_FA_OFDM * rx_enable_time;
357         struct iwl_sensitivity_data *data = NULL;
358         const struct iwl_sensitivity_ranges *ranges = priv->hw_params.sens;
359
360         data = &(priv->sensitivity_data);
361
362         /* If we got too many false alarms this time, reduce sensitivity */
363         if (false_alarms > max_false_alarms) {
364
365                 IWL_DEBUG_CALIB(priv, "norm FA %u > max FA %u)\n",
366                              false_alarms, max_false_alarms);
367
368                 val = data->auto_corr_ofdm + AUTO_CORR_STEP_OFDM;
369                 data->auto_corr_ofdm =
370                         min((u32)ranges->auto_corr_max_ofdm, val);
371
372                 val = data->auto_corr_ofdm_mrc + AUTO_CORR_STEP_OFDM;
373                 data->auto_corr_ofdm_mrc =
374                         min((u32)ranges->auto_corr_max_ofdm_mrc, val);
375
376                 val = data->auto_corr_ofdm_x1 + AUTO_CORR_STEP_OFDM;
377                 data->auto_corr_ofdm_x1 =
378                         min((u32)ranges->auto_corr_max_ofdm_x1, val);
379
380                 val = data->auto_corr_ofdm_mrc_x1 + AUTO_CORR_STEP_OFDM;
381                 data->auto_corr_ofdm_mrc_x1 =
382                         min((u32)ranges->auto_corr_max_ofdm_mrc_x1, val);
383         }
384
385         /* Else if we got fewer than desired, increase sensitivity */
386         else if (false_alarms < min_false_alarms) {
387
388                 IWL_DEBUG_CALIB(priv, "norm FA %u < min FA %u\n",
389                              false_alarms, min_false_alarms);
390
391                 val = data->auto_corr_ofdm - AUTO_CORR_STEP_OFDM;
392                 data->auto_corr_ofdm =
393                         max((u32)ranges->auto_corr_min_ofdm, val);
394
395                 val = data->auto_corr_ofdm_mrc - AUTO_CORR_STEP_OFDM;
396                 data->auto_corr_ofdm_mrc =
397                         max((u32)ranges->auto_corr_min_ofdm_mrc, val);
398
399                 val = data->auto_corr_ofdm_x1 - AUTO_CORR_STEP_OFDM;
400                 data->auto_corr_ofdm_x1 =
401                         max((u32)ranges->auto_corr_min_ofdm_x1, val);
402
403                 val = data->auto_corr_ofdm_mrc_x1 - AUTO_CORR_STEP_OFDM;
404                 data->auto_corr_ofdm_mrc_x1 =
405                         max((u32)ranges->auto_corr_min_ofdm_mrc_x1, val);
406         } else {
407                 IWL_DEBUG_CALIB(priv, "min FA %u < norm FA %u < max FA %u OK\n",
408                          min_false_alarms, false_alarms, max_false_alarms);
409         }
410         return 0;
411 }
412
413 static void iwl_prepare_legacy_sensitivity_tbl(struct iwl_priv *priv,
414                                 struct iwl_sensitivity_data *data,
415                                 __le16 *tbl)
416 {
417         tbl[HD_AUTO_CORR32_X4_TH_ADD_MIN_INDEX] =
418                                 cpu_to_le16((u16)data->auto_corr_ofdm);
419         tbl[HD_AUTO_CORR32_X4_TH_ADD_MIN_MRC_INDEX] =
420                                 cpu_to_le16((u16)data->auto_corr_ofdm_mrc);
421         tbl[HD_AUTO_CORR32_X1_TH_ADD_MIN_INDEX] =
422                                 cpu_to_le16((u16)data->auto_corr_ofdm_x1);
423         tbl[HD_AUTO_CORR32_X1_TH_ADD_MIN_MRC_INDEX] =
424                                 cpu_to_le16((u16)data->auto_corr_ofdm_mrc_x1);
425
426         tbl[HD_AUTO_CORR40_X4_TH_ADD_MIN_INDEX] =
427                                 cpu_to_le16((u16)data->auto_corr_cck);
428         tbl[HD_AUTO_CORR40_X4_TH_ADD_MIN_MRC_INDEX] =
429                                 cpu_to_le16((u16)data->auto_corr_cck_mrc);
430
431         tbl[HD_MIN_ENERGY_CCK_DET_INDEX] =
432                                 cpu_to_le16((u16)data->nrg_th_cck);
433         tbl[HD_MIN_ENERGY_OFDM_DET_INDEX] =
434                                 cpu_to_le16((u16)data->nrg_th_ofdm);
435
436         tbl[HD_BARKER_CORR_TH_ADD_MIN_INDEX] =
437                                 cpu_to_le16(data->barker_corr_th_min);
438         tbl[HD_BARKER_CORR_TH_ADD_MIN_MRC_INDEX] =
439                                 cpu_to_le16(data->barker_corr_th_min_mrc);
440         tbl[HD_OFDM_ENERGY_TH_IN_INDEX] =
441                                 cpu_to_le16(data->nrg_th_cca);
442
443         IWL_DEBUG_CALIB(priv, "ofdm: ac %u mrc %u x1 %u mrc_x1 %u thresh %u\n",
444                         data->auto_corr_ofdm, data->auto_corr_ofdm_mrc,
445                         data->auto_corr_ofdm_x1, data->auto_corr_ofdm_mrc_x1,
446                         data->nrg_th_ofdm);
447
448         IWL_DEBUG_CALIB(priv, "cck: ac %u mrc %u thresh %u\n",
449                         data->auto_corr_cck, data->auto_corr_cck_mrc,
450                         data->nrg_th_cck);
451 }
452
453 /* Prepare a SENSITIVITY_CMD, send to uCode if values have changed */
454 static int iwl_sensitivity_write(struct iwl_priv *priv)
455 {
456         struct iwl_sensitivity_cmd cmd;
457         struct iwl_sensitivity_data *data = NULL;
458         struct iwl_host_cmd cmd_out = {
459                 .id = SENSITIVITY_CMD,
460                 .len = { sizeof(struct iwl_sensitivity_cmd), },
461                 .flags = CMD_ASYNC,
462                 .data = { &cmd, },
463         };
464
465         data = &(priv->sensitivity_data);
466
467         memset(&cmd, 0, sizeof(cmd));
468
469         iwl_prepare_legacy_sensitivity_tbl(priv, data, &cmd.table[0]);
470
471         /* Update uCode's "work" table, and copy it to DSP */
472         cmd.control = SENSITIVITY_CMD_CONTROL_WORK_TABLE;
473
474         /* Don't send command to uCode if nothing has changed */
475         if (!memcmp(&cmd.table[0], &(priv->sensitivity_tbl[0]),
476                     sizeof(u16)*HD_TABLE_SIZE)) {
477                 IWL_DEBUG_CALIB(priv, "No change in SENSITIVITY_CMD\n");
478                 return 0;
479         }
480
481         /* Copy table for comparison next time */
482         memcpy(&(priv->sensitivity_tbl[0]), &(cmd.table[0]),
483                sizeof(u16)*HD_TABLE_SIZE);
484
485         return priv->trans.ops->send_cmd(priv, &cmd_out);
486 }
487
488 /* Prepare a SENSITIVITY_CMD, send to uCode if values have changed */
489 static int iwl_enhance_sensitivity_write(struct iwl_priv *priv)
490 {
491         struct iwl_enhance_sensitivity_cmd cmd;
492         struct iwl_sensitivity_data *data = NULL;
493         struct iwl_host_cmd cmd_out = {
494                 .id = SENSITIVITY_CMD,
495                 .len = { sizeof(struct iwl_enhance_sensitivity_cmd), },
496                 .flags = CMD_ASYNC,
497                 .data = { &cmd, },
498         };
499
500         data = &(priv->sensitivity_data);
501
502         memset(&cmd, 0, sizeof(cmd));
503
504         iwl_prepare_legacy_sensitivity_tbl(priv, data, &cmd.enhance_table[0]);
505
506         cmd.enhance_table[HD_INA_NON_SQUARE_DET_OFDM_INDEX] =
507                 HD_INA_NON_SQUARE_DET_OFDM_DATA;
508         cmd.enhance_table[HD_INA_NON_SQUARE_DET_CCK_INDEX] =
509                 HD_INA_NON_SQUARE_DET_CCK_DATA;
510         cmd.enhance_table[HD_CORR_11_INSTEAD_OF_CORR_9_EN_INDEX] =
511                 HD_CORR_11_INSTEAD_OF_CORR_9_EN_DATA;
512         cmd.enhance_table[HD_OFDM_NON_SQUARE_DET_SLOPE_MRC_INDEX] =
513                 HD_OFDM_NON_SQUARE_DET_SLOPE_MRC_DATA;
514         cmd.enhance_table[HD_OFDM_NON_SQUARE_DET_INTERCEPT_MRC_INDEX] =
515                 HD_OFDM_NON_SQUARE_DET_INTERCEPT_MRC_DATA;
516         cmd.enhance_table[HD_OFDM_NON_SQUARE_DET_SLOPE_INDEX] =
517                 HD_OFDM_NON_SQUARE_DET_SLOPE_DATA;
518         cmd.enhance_table[HD_OFDM_NON_SQUARE_DET_INTERCEPT_INDEX] =
519                 HD_OFDM_NON_SQUARE_DET_INTERCEPT_DATA;
520         cmd.enhance_table[HD_CCK_NON_SQUARE_DET_SLOPE_MRC_INDEX] =
521                 HD_CCK_NON_SQUARE_DET_SLOPE_MRC_DATA;
522         cmd.enhance_table[HD_CCK_NON_SQUARE_DET_INTERCEPT_MRC_INDEX] =
523                 HD_CCK_NON_SQUARE_DET_INTERCEPT_MRC_DATA;
524         cmd.enhance_table[HD_CCK_NON_SQUARE_DET_SLOPE_INDEX] =
525                 HD_CCK_NON_SQUARE_DET_SLOPE_DATA;
526         cmd.enhance_table[HD_CCK_NON_SQUARE_DET_INTERCEPT_INDEX] =
527                 HD_CCK_NON_SQUARE_DET_INTERCEPT_DATA;
528
529         /* Update uCode's "work" table, and copy it to DSP */
530         cmd.control = SENSITIVITY_CMD_CONTROL_WORK_TABLE;
531
532         /* Don't send command to uCode if nothing has changed */
533         if (!memcmp(&cmd.enhance_table[0], &(priv->sensitivity_tbl[0]),
534                     sizeof(u16)*HD_TABLE_SIZE) &&
535             !memcmp(&cmd.enhance_table[HD_INA_NON_SQUARE_DET_OFDM_INDEX],
536                     &(priv->enhance_sensitivity_tbl[0]),
537                     sizeof(u16)*ENHANCE_HD_TABLE_ENTRIES)) {
538                 IWL_DEBUG_CALIB(priv, "No change in SENSITIVITY_CMD\n");
539                 return 0;
540         }
541
542         /* Copy table for comparison next time */
543         memcpy(&(priv->sensitivity_tbl[0]), &(cmd.enhance_table[0]),
544                sizeof(u16)*HD_TABLE_SIZE);
545         memcpy(&(priv->enhance_sensitivity_tbl[0]),
546                &(cmd.enhance_table[HD_INA_NON_SQUARE_DET_OFDM_INDEX]),
547                sizeof(u16)*ENHANCE_HD_TABLE_ENTRIES);
548
549         return priv->trans.ops->send_cmd(priv, &cmd_out);
550 }
551
552 void iwl_init_sensitivity(struct iwl_priv *priv)
553 {
554         int ret = 0;
555         int i;
556         struct iwl_sensitivity_data *data = NULL;
557         const struct iwl_sensitivity_ranges *ranges = priv->hw_params.sens;
558
559         if (priv->disable_sens_cal)
560                 return;
561
562         IWL_DEBUG_CALIB(priv, "Start iwl_init_sensitivity\n");
563
564         /* Clear driver's sensitivity algo data */
565         data = &(priv->sensitivity_data);
566
567         if (ranges == NULL)
568                 return;
569
570         memset(data, 0, sizeof(struct iwl_sensitivity_data));
571
572         data->num_in_cck_no_fa = 0;
573         data->nrg_curr_state = IWL_FA_TOO_MANY;
574         data->nrg_prev_state = IWL_FA_TOO_MANY;
575         data->nrg_silence_ref = 0;
576         data->nrg_silence_idx = 0;
577         data->nrg_energy_idx = 0;
578
579         for (i = 0; i < 10; i++)
580                 data->nrg_value[i] = 0;
581
582         for (i = 0; i < NRG_NUM_PREV_STAT_L; i++)
583                 data->nrg_silence_rssi[i] = 0;
584
585         data->auto_corr_ofdm =  ranges->auto_corr_min_ofdm;
586         data->auto_corr_ofdm_mrc = ranges->auto_corr_min_ofdm_mrc;
587         data->auto_corr_ofdm_x1  = ranges->auto_corr_min_ofdm_x1;
588         data->auto_corr_ofdm_mrc_x1 = ranges->auto_corr_min_ofdm_mrc_x1;
589         data->auto_corr_cck = AUTO_CORR_CCK_MIN_VAL_DEF;
590         data->auto_corr_cck_mrc = ranges->auto_corr_min_cck_mrc;
591         data->nrg_th_cck = ranges->nrg_th_cck;
592         data->nrg_th_ofdm = ranges->nrg_th_ofdm;
593         data->barker_corr_th_min = ranges->barker_corr_th_min;
594         data->barker_corr_th_min_mrc = ranges->barker_corr_th_min_mrc;
595         data->nrg_th_cca = ranges->nrg_th_cca;
596
597         data->last_bad_plcp_cnt_ofdm = 0;
598         data->last_fa_cnt_ofdm = 0;
599         data->last_bad_plcp_cnt_cck = 0;
600         data->last_fa_cnt_cck = 0;
601
602         if (priv->enhance_sensitivity_table)
603                 ret |= iwl_enhance_sensitivity_write(priv);
604         else
605                 ret |= iwl_sensitivity_write(priv);
606         IWL_DEBUG_CALIB(priv, "<<return 0x%X\n", ret);
607 }
608
609 void iwl_sensitivity_calibration(struct iwl_priv *priv)
610 {
611         u32 rx_enable_time;
612         u32 fa_cck;
613         u32 fa_ofdm;
614         u32 bad_plcp_cck;
615         u32 bad_plcp_ofdm;
616         u32 norm_fa_ofdm;
617         u32 norm_fa_cck;
618         struct iwl_sensitivity_data *data = NULL;
619         struct statistics_rx_non_phy *rx_info;
620         struct statistics_rx_phy *ofdm, *cck;
621         unsigned long flags;
622         struct statistics_general_data statis;
623
624         if (priv->disable_sens_cal)
625                 return;
626
627         data = &(priv->sensitivity_data);
628
629         if (!iwl_is_any_associated(priv)) {
630                 IWL_DEBUG_CALIB(priv, "<< - not associated\n");
631                 return;
632         }
633
634         spin_lock_irqsave(&priv->lock, flags);
635         rx_info = &priv->statistics.rx_non_phy;
636         ofdm = &priv->statistics.rx_ofdm;
637         cck = &priv->statistics.rx_cck;
638         if (rx_info->interference_data_flag != INTERFERENCE_DATA_AVAILABLE) {
639                 IWL_DEBUG_CALIB(priv, "<< invalid data.\n");
640                 spin_unlock_irqrestore(&priv->lock, flags);
641                 return;
642         }
643
644         /* Extract Statistics: */
645         rx_enable_time = le32_to_cpu(rx_info->channel_load);
646         fa_cck = le32_to_cpu(cck->false_alarm_cnt);
647         fa_ofdm = le32_to_cpu(ofdm->false_alarm_cnt);
648         bad_plcp_cck = le32_to_cpu(cck->plcp_err);
649         bad_plcp_ofdm = le32_to_cpu(ofdm->plcp_err);
650
651         statis.beacon_silence_rssi_a =
652                         le32_to_cpu(rx_info->beacon_silence_rssi_a);
653         statis.beacon_silence_rssi_b =
654                         le32_to_cpu(rx_info->beacon_silence_rssi_b);
655         statis.beacon_silence_rssi_c =
656                         le32_to_cpu(rx_info->beacon_silence_rssi_c);
657         statis.beacon_energy_a =
658                         le32_to_cpu(rx_info->beacon_energy_a);
659         statis.beacon_energy_b =
660                         le32_to_cpu(rx_info->beacon_energy_b);
661         statis.beacon_energy_c =
662                         le32_to_cpu(rx_info->beacon_energy_c);
663
664         spin_unlock_irqrestore(&priv->lock, flags);
665
666         IWL_DEBUG_CALIB(priv, "rx_enable_time = %u usecs\n", rx_enable_time);
667
668         if (!rx_enable_time) {
669                 IWL_DEBUG_CALIB(priv, "<< RX Enable Time == 0!\n");
670                 return;
671         }
672
673         /* These statistics increase monotonically, and do not reset
674          *   at each beacon.  Calculate difference from last value, or just
675          *   use the new statistics value if it has reset or wrapped around. */
676         if (data->last_bad_plcp_cnt_cck > bad_plcp_cck)
677                 data->last_bad_plcp_cnt_cck = bad_plcp_cck;
678         else {
679                 bad_plcp_cck -= data->last_bad_plcp_cnt_cck;
680                 data->last_bad_plcp_cnt_cck += bad_plcp_cck;
681         }
682
683         if (data->last_bad_plcp_cnt_ofdm > bad_plcp_ofdm)
684                 data->last_bad_plcp_cnt_ofdm = bad_plcp_ofdm;
685         else {
686                 bad_plcp_ofdm -= data->last_bad_plcp_cnt_ofdm;
687                 data->last_bad_plcp_cnt_ofdm += bad_plcp_ofdm;
688         }
689
690         if (data->last_fa_cnt_ofdm > fa_ofdm)
691                 data->last_fa_cnt_ofdm = fa_ofdm;
692         else {
693                 fa_ofdm -= data->last_fa_cnt_ofdm;
694                 data->last_fa_cnt_ofdm += fa_ofdm;
695         }
696
697         if (data->last_fa_cnt_cck > fa_cck)
698                 data->last_fa_cnt_cck = fa_cck;
699         else {
700                 fa_cck -= data->last_fa_cnt_cck;
701                 data->last_fa_cnt_cck += fa_cck;
702         }
703
704         /* Total aborted signal locks */
705         norm_fa_ofdm = fa_ofdm + bad_plcp_ofdm;
706         norm_fa_cck = fa_cck + bad_plcp_cck;
707
708         IWL_DEBUG_CALIB(priv, "cck: fa %u badp %u  ofdm: fa %u badp %u\n", fa_cck,
709                         bad_plcp_cck, fa_ofdm, bad_plcp_ofdm);
710
711         iwl_sens_auto_corr_ofdm(priv, norm_fa_ofdm, rx_enable_time);
712         iwl_sens_energy_cck(priv, norm_fa_cck, rx_enable_time, &statis);
713         if (priv->enhance_sensitivity_table)
714                 iwl_enhance_sensitivity_write(priv);
715         else
716                 iwl_sensitivity_write(priv);
717 }
718
719 static inline u8 find_first_chain(u8 mask)
720 {
721         if (mask & ANT_A)
722                 return CHAIN_A;
723         if (mask & ANT_B)
724                 return CHAIN_B;
725         return CHAIN_C;
726 }
727
728 /**
729  * Run disconnected antenna algorithm to find out which antennas are
730  * disconnected.
731  */
732 static void iwl_find_disconn_antenna(struct iwl_priv *priv, u32* average_sig,
733                                      struct iwl_chain_noise_data *data)
734 {
735         u32 active_chains = 0;
736         u32 max_average_sig;
737         u16 max_average_sig_antenna_i;
738         u8 num_tx_chains;
739         u8 first_chain;
740         u16 i = 0;
741
742         average_sig[0] = data->chain_signal_a /
743                          priv->cfg->base_params->chain_noise_num_beacons;
744         average_sig[1] = data->chain_signal_b /
745                          priv->cfg->base_params->chain_noise_num_beacons;
746         average_sig[2] = data->chain_signal_c /
747                          priv->cfg->base_params->chain_noise_num_beacons;
748
749         if (average_sig[0] >= average_sig[1]) {
750                 max_average_sig = average_sig[0];
751                 max_average_sig_antenna_i = 0;
752                 active_chains = (1 << max_average_sig_antenna_i);
753         } else {
754                 max_average_sig = average_sig[1];
755                 max_average_sig_antenna_i = 1;
756                 active_chains = (1 << max_average_sig_antenna_i);
757         }
758
759         if (average_sig[2] >= max_average_sig) {
760                 max_average_sig = average_sig[2];
761                 max_average_sig_antenna_i = 2;
762                 active_chains = (1 << max_average_sig_antenna_i);
763         }
764
765         IWL_DEBUG_CALIB(priv, "average_sig: a %d b %d c %d\n",
766                      average_sig[0], average_sig[1], average_sig[2]);
767         IWL_DEBUG_CALIB(priv, "max_average_sig = %d, antenna %d\n",
768                      max_average_sig, max_average_sig_antenna_i);
769
770         /* Compare signal strengths for all 3 receivers. */
771         for (i = 0; i < NUM_RX_CHAINS; i++) {
772                 if (i != max_average_sig_antenna_i) {
773                         s32 rssi_delta = (max_average_sig - average_sig[i]);
774
775                         /* If signal is very weak, compared with
776                          * strongest, mark it as disconnected. */
777                         if (rssi_delta > MAXIMUM_ALLOWED_PATHLOSS)
778                                 data->disconn_array[i] = 1;
779                         else
780                                 active_chains |= (1 << i);
781                         IWL_DEBUG_CALIB(priv, "i = %d  rssiDelta = %d  "
782                              "disconn_array[i] = %d\n",
783                              i, rssi_delta, data->disconn_array[i]);
784                 }
785         }
786
787         /*
788          * The above algorithm sometimes fails when the ucode
789          * reports 0 for all chains. It's not clear why that
790          * happens to start with, but it is then causing trouble
791          * because this can make us enable more chains than the
792          * hardware really has.
793          *
794          * To be safe, simply mask out any chains that we know
795          * are not on the device.
796          */
797         active_chains &= priv->hw_params.valid_rx_ant;
798
799         num_tx_chains = 0;
800         for (i = 0; i < NUM_RX_CHAINS; i++) {
801                 /* loops on all the bits of
802                  * priv->hw_setting.valid_tx_ant */
803                 u8 ant_msk = (1 << i);
804                 if (!(priv->hw_params.valid_tx_ant & ant_msk))
805                         continue;
806
807                 num_tx_chains++;
808                 if (data->disconn_array[i] == 0)
809                         /* there is a Tx antenna connected */
810                         break;
811                 if (num_tx_chains == priv->hw_params.tx_chains_num &&
812                     data->disconn_array[i]) {
813                         /*
814                          * If all chains are disconnected
815                          * connect the first valid tx chain
816                          */
817                         first_chain =
818                                 find_first_chain(priv->cfg->valid_tx_ant);
819                         data->disconn_array[first_chain] = 0;
820                         active_chains |= BIT(first_chain);
821                         IWL_DEBUG_CALIB(priv,
822                                         "All Tx chains are disconnected W/A - declare %d as connected\n",
823                                         first_chain);
824                         break;
825                 }
826         }
827
828         if (active_chains != priv->hw_params.valid_rx_ant &&
829             active_chains != priv->chain_noise_data.active_chains)
830                 IWL_DEBUG_CALIB(priv,
831                                 "Detected that not all antennas are connected! "
832                                 "Connected: %#x, valid: %#x.\n",
833                                 active_chains, priv->hw_params.valid_rx_ant);
834
835         /* Save for use within RXON, TX, SCAN commands, etc. */
836         data->active_chains = active_chains;
837         IWL_DEBUG_CALIB(priv, "active_chains (bitwise) = 0x%x\n",
838                         active_chains);
839 }
840
841
842 /*
843  * Accumulate 16 beacons of signal and noise statistics for each of
844  *   3 receivers/antennas/rx-chains, then figure out:
845  * 1)  Which antennas are connected.
846  * 2)  Differential rx gain settings to balance the 3 receivers.
847  */
848 void iwl_chain_noise_calibration(struct iwl_priv *priv)
849 {
850         struct iwl_chain_noise_data *data = NULL;
851
852         u32 chain_noise_a;
853         u32 chain_noise_b;
854         u32 chain_noise_c;
855         u32 chain_sig_a;
856         u32 chain_sig_b;
857         u32 chain_sig_c;
858         u32 average_sig[NUM_RX_CHAINS] = {INITIALIZATION_VALUE};
859         u32 average_noise[NUM_RX_CHAINS] = {INITIALIZATION_VALUE};
860         u32 min_average_noise = MIN_AVERAGE_NOISE_MAX_VALUE;
861         u16 min_average_noise_antenna_i = INITIALIZATION_VALUE;
862         u16 i = 0;
863         u16 rxon_chnum = INITIALIZATION_VALUE;
864         u16 stat_chnum = INITIALIZATION_VALUE;
865         u8 rxon_band24;
866         u8 stat_band24;
867         unsigned long flags;
868         struct statistics_rx_non_phy *rx_info;
869
870         /*
871          * MULTI-FIXME:
872          * When we support multiple interfaces on different channels,
873          * this must be modified/fixed.
874          */
875         struct iwl_rxon_context *ctx = &priv->contexts[IWL_RXON_CTX_BSS];
876
877         if (priv->disable_chain_noise_cal)
878                 return;
879
880         data = &(priv->chain_noise_data);
881
882         /*
883          * Accumulate just the first "chain_noise_num_beacons" after
884          * the first association, then we're done forever.
885          */
886         if (data->state != IWL_CHAIN_NOISE_ACCUMULATE) {
887                 if (data->state == IWL_CHAIN_NOISE_ALIVE)
888                         IWL_DEBUG_CALIB(priv, "Wait for noise calib reset\n");
889                 return;
890         }
891
892         spin_lock_irqsave(&priv->lock, flags);
893
894         rx_info = &priv->statistics.rx_non_phy;
895
896         if (rx_info->interference_data_flag != INTERFERENCE_DATA_AVAILABLE) {
897                 IWL_DEBUG_CALIB(priv, " << Interference data unavailable\n");
898                 spin_unlock_irqrestore(&priv->lock, flags);
899                 return;
900         }
901
902         rxon_band24 = !!(ctx->staging.flags & RXON_FLG_BAND_24G_MSK);
903         rxon_chnum = le16_to_cpu(ctx->staging.channel);
904         stat_band24 =
905                 !!(priv->statistics.flag & STATISTICS_REPLY_FLG_BAND_24G_MSK);
906         stat_chnum = le32_to_cpu(priv->statistics.flag) >> 16;
907
908         /* Make sure we accumulate data for just the associated channel
909          *   (even if scanning). */
910         if ((rxon_chnum != stat_chnum) || (rxon_band24 != stat_band24)) {
911                 IWL_DEBUG_CALIB(priv, "Stats not from chan=%d, band24=%d\n",
912                                 rxon_chnum, rxon_band24);
913                 spin_unlock_irqrestore(&priv->lock, flags);
914                 return;
915         }
916
917         /*
918          *  Accumulate beacon statistics values across
919          * "chain_noise_num_beacons"
920          */
921         chain_noise_a = le32_to_cpu(rx_info->beacon_silence_rssi_a) &
922                                 IN_BAND_FILTER;
923         chain_noise_b = le32_to_cpu(rx_info->beacon_silence_rssi_b) &
924                                 IN_BAND_FILTER;
925         chain_noise_c = le32_to_cpu(rx_info->beacon_silence_rssi_c) &
926                                 IN_BAND_FILTER;
927
928         chain_sig_a = le32_to_cpu(rx_info->beacon_rssi_a) & IN_BAND_FILTER;
929         chain_sig_b = le32_to_cpu(rx_info->beacon_rssi_b) & IN_BAND_FILTER;
930         chain_sig_c = le32_to_cpu(rx_info->beacon_rssi_c) & IN_BAND_FILTER;
931
932         spin_unlock_irqrestore(&priv->lock, flags);
933
934         data->beacon_count++;
935
936         data->chain_noise_a = (chain_noise_a + data->chain_noise_a);
937         data->chain_noise_b = (chain_noise_b + data->chain_noise_b);
938         data->chain_noise_c = (chain_noise_c + data->chain_noise_c);
939
940         data->chain_signal_a = (chain_sig_a + data->chain_signal_a);
941         data->chain_signal_b = (chain_sig_b + data->chain_signal_b);
942         data->chain_signal_c = (chain_sig_c + data->chain_signal_c);
943
944         IWL_DEBUG_CALIB(priv, "chan=%d, band24=%d, beacon=%d\n",
945                         rxon_chnum, rxon_band24, data->beacon_count);
946         IWL_DEBUG_CALIB(priv, "chain_sig: a %d b %d c %d\n",
947                         chain_sig_a, chain_sig_b, chain_sig_c);
948         IWL_DEBUG_CALIB(priv, "chain_noise: a %d b %d c %d\n",
949                         chain_noise_a, chain_noise_b, chain_noise_c);
950
951         /* If this is the "chain_noise_num_beacons", determine:
952          * 1)  Disconnected antennas (using signal strengths)
953          * 2)  Differential gain (using silence noise) to balance receivers */
954         if (data->beacon_count !=
955                 priv->cfg->base_params->chain_noise_num_beacons)
956                 return;
957
958         /* Analyze signal for disconnected antenna */
959         if (priv->cfg->bt_params &&
960             priv->cfg->bt_params->advanced_bt_coexist) {
961                 /* Disable disconnected antenna algorithm for advanced
962                    bt coex, assuming valid antennas are connected */
963                 data->active_chains = priv->hw_params.valid_rx_ant;
964                 for (i = 0; i < NUM_RX_CHAINS; i++)
965                         if (!(data->active_chains & (1<<i)))
966                                 data->disconn_array[i] = 1;
967         } else
968                 iwl_find_disconn_antenna(priv, average_sig, data);
969
970         /* Analyze noise for rx balance */
971         average_noise[0] = data->chain_noise_a /
972                            priv->cfg->base_params->chain_noise_num_beacons;
973         average_noise[1] = data->chain_noise_b /
974                            priv->cfg->base_params->chain_noise_num_beacons;
975         average_noise[2] = data->chain_noise_c /
976                            priv->cfg->base_params->chain_noise_num_beacons;
977
978         for (i = 0; i < NUM_RX_CHAINS; i++) {
979                 if (!(data->disconn_array[i]) &&
980                    (average_noise[i] <= min_average_noise)) {
981                         /* This means that chain i is active and has
982                          * lower noise values so far: */
983                         min_average_noise = average_noise[i];
984                         min_average_noise_antenna_i = i;
985                 }
986         }
987
988         IWL_DEBUG_CALIB(priv, "average_noise: a %d b %d c %d\n",
989                         average_noise[0], average_noise[1],
990                         average_noise[2]);
991
992         IWL_DEBUG_CALIB(priv, "min_average_noise = %d, antenna %d\n",
993                         min_average_noise, min_average_noise_antenna_i);
994
995         if (priv->cfg->ops->utils->gain_computation)
996                 priv->cfg->ops->utils->gain_computation(priv, average_noise,
997                                 min_average_noise_antenna_i, min_average_noise,
998                                 find_first_chain(priv->cfg->valid_rx_ant));
999
1000         /* Some power changes may have been made during the calibration.
1001          * Update and commit the RXON
1002          */
1003         if (priv->cfg->ops->lib->update_chain_flags)
1004                 priv->cfg->ops->lib->update_chain_flags(priv);
1005
1006         data->state = IWL_CHAIN_NOISE_DONE;
1007         iwl_power_update_mode(priv, false);
1008 }
1009
1010 void iwl_reset_run_time_calib(struct iwl_priv *priv)
1011 {
1012         int i;
1013         memset(&(priv->sensitivity_data), 0,
1014                sizeof(struct iwl_sensitivity_data));
1015         memset(&(priv->chain_noise_data), 0,
1016                sizeof(struct iwl_chain_noise_data));
1017         for (i = 0; i < NUM_RX_CHAINS; i++)
1018                 priv->chain_noise_data.delta_gain_code[i] =
1019                                 CHAIN_NOISE_DELTA_GAIN_INIT_VAL;
1020
1021         /* Ask for statistics now, the uCode will send notification
1022          * periodically after association */
1023         iwl_send_statistics_request(priv, CMD_ASYNC, true);
1024 }