Merge branch 'master' into net80211-update
[dragonfly.git] / sys / dev / netif / ath / hal / ath_hal / ar5416 / ar5416_ani.c
1 /*
2  * Copyright (c) 2002-2009 Sam Leffler, Errno Consulting
3  * Copyright (c) 2002-2008 Atheros Communications, Inc.
4  *
5  * Permission to use, copy, modify, and/or distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  *
17  * $FreeBSD: head/sys/dev/ath/ath_hal/ar5416/ar5416_ani.c 203159 2010-01-29 10:10:14Z rpaulo $
18  * $DragonFly$
19  */
20 #include "opt_ah.h"
21
22 /*
23  * XXX this is virtually the same code as for 5212; we reuse
24  * storage in the 5212 state block; need to refactor.
25  */
26 #include "ah.h"
27 #include "ah_internal.h"
28 #include "ah_desc.h"
29
30 #include "ar5416/ar5416.h"
31 #include "ar5416/ar5416reg.h"
32 #include "ar5416/ar5416phy.h"
33
34 /*
35  * Anti noise immunity support.  We track phy errors and react
36  * to excessive errors by adjusting the noise immunity parameters.
37  */
38
39 #define HAL_EP_RND(x, mul) \
40         ((((x)%(mul)) >= ((mul)/2)) ? ((x) + ((mul) - 1)) / (mul) : (x)/(mul))
41 #define BEACON_RSSI(ahp) \
42         HAL_EP_RND(ahp->ah_stats.ast_nodestats.ns_avgbrssi, \
43                 HAL_RSSI_EP_MULTIPLIER)
44
45 /*
46  * ANI processing tunes radio parameters according to PHY errors
47  * and related information.  This is done for for noise and spur
48  * immunity in all operating modes if the device indicates it's
49  * capable at attach time.  In addition, when there is a reference
50  * rssi value (e.g. beacon frames from an ap in station mode)
51  * further tuning is done.
52  *
53  * ANI_ENA indicates whether any ANI processing should be done;
54  * this is specified at attach time.
55  *
56  * ANI_ENA_RSSI indicates whether rssi-based processing should
57  * done, this is enabled based on operating mode and is meaningful
58  * only if ANI_ENA is true.
59  *
60  * ANI parameters are typically controlled only by the hal.  The
61  * AniControl interface however permits manual tuning through the
62  * diagnostic api.
63  */
64 #define ANI_ENA(ah) \
65         (AH5212(ah)->ah_procPhyErr & HAL_ANI_ENA)
66 #define ANI_ENA_RSSI(ah) \
67         (AH5212(ah)->ah_procPhyErr & HAL_RSSI_ANI_ENA)
68
69 #define ah_mibStats     ah_stats.ast_mibstats
70
71 static void
72 enableAniMIBCounters(struct ath_hal *ah, const struct ar5212AniParams *params)
73 {
74         struct ath_hal_5212 *ahp = AH5212(ah);
75
76         HALDEBUG(ah, HAL_DEBUG_ANI, "%s: Enable mib counters: "
77             "OfdmPhyErrBase 0x%x cckPhyErrBase 0x%x\n",
78             __func__, params->ofdmPhyErrBase, params->cckPhyErrBase);
79
80         OS_REG_WRITE(ah, AR_FILTOFDM, 0);
81         OS_REG_WRITE(ah, AR_FILTCCK, 0);
82
83         OS_REG_WRITE(ah, AR_PHYCNT1, params->ofdmPhyErrBase);
84         OS_REG_WRITE(ah, AR_PHYCNT2, params->cckPhyErrBase);
85         OS_REG_WRITE(ah, AR_PHY_ERR_MASK_1, AR_PHY_ERR_OFDM_TIMING);
86         OS_REG_WRITE(ah, AR_PHY_ERR_MASK_2, AR_PHY_ERR_CCK_TIMING);
87
88         ar5212UpdateMibCounters(ah, &ahp->ah_mibStats); /* save+clear counters*/
89         ar5212EnableMibCounters(ah);                    /* enable everything */
90 }
91
92 static void 
93 disableAniMIBCounters(struct ath_hal *ah)
94 {
95         struct ath_hal_5212 *ahp = AH5212(ah);
96
97         HALDEBUG(ah, HAL_DEBUG_ANI, "Disable MIB counters\n");
98
99         ar5212UpdateMibCounters(ah, &ahp->ah_mibStats); /* save stats */
100         ar5212DisableMibCounters(ah);                   /* disable everything */
101
102         OS_REG_WRITE(ah, AR_PHY_ERR_MASK_1, 0);
103         OS_REG_WRITE(ah, AR_PHY_ERR_MASK_2, 0);
104 }
105
106 static void
107 setPhyErrBase(struct ath_hal *ah, struct ar5212AniParams *params)
108 {
109         if (params->ofdmTrigHigh >= AR_PHY_COUNTMAX) {
110                 HALDEBUG(ah, HAL_DEBUG_ANY,
111                     "OFDM Trigger %d is too high for hw counters, using max\n",
112                     params->ofdmTrigHigh);
113                 params->ofdmPhyErrBase = 0;
114         } else
115                 params->ofdmPhyErrBase = AR_PHY_COUNTMAX - params->ofdmTrigHigh;
116         if (params->cckTrigHigh >= AR_PHY_COUNTMAX) {
117                 HALDEBUG(ah, HAL_DEBUG_ANY,
118                     "CCK Trigger %d is too high for hw counters, using max\n",
119                     params->cckTrigHigh);
120                 params->cckPhyErrBase = 0;
121         } else
122                 params->cckPhyErrBase = AR_PHY_COUNTMAX - params->cckTrigHigh;
123 }
124
125 /*
126  * Setup ANI handling.  Sets all thresholds and reset the
127  * channel statistics.  Note that ar5416AniReset should be
128  * called by ar5416Reset before anything else happens and
129  * that's where we force initial settings.
130  */
131 void
132 ar5416AniAttach(struct ath_hal *ah, const struct ar5212AniParams *params24,
133         const struct ar5212AniParams *params5, HAL_BOOL enable)
134 {
135         struct ath_hal_5212 *ahp = AH5212(ah);
136
137         if (params24 != AH_NULL) {
138                 OS_MEMCPY(&ahp->ah_aniParams24, params24, sizeof(*params24));
139                 setPhyErrBase(ah, &ahp->ah_aniParams24);
140         }
141         if (params5 != AH_NULL) {
142                 OS_MEMCPY(&ahp->ah_aniParams5, params5, sizeof(*params5));
143                 setPhyErrBase(ah, &ahp->ah_aniParams5);
144         }
145
146         OS_MEMZERO(ahp->ah_ani, sizeof(ahp->ah_ani));
147         /* Enable MIB Counters */
148         enableAniMIBCounters(ah, &ahp->ah_aniParams24 /*XXX*/);
149
150         if (enable) {           /* Enable ani now */
151                 HALASSERT(params24 != AH_NULL && params5 != AH_NULL);
152                 ahp->ah_procPhyErr |= HAL_ANI_ENA;
153         } else {
154                 ahp->ah_procPhyErr &= ~HAL_ANI_ENA;
155         }
156 }
157
158 /*
159  * Cleanup any ANI state setup.
160  */
161 void
162 ar5416AniDetach(struct ath_hal *ah)
163 {
164         HALDEBUG(ah, HAL_DEBUG_ANI, "Detaching Ani\n");
165         disableAniMIBCounters(ah);
166 }
167
168 /*
169  * Control Adaptive Noise Immunity Parameters
170  */
171 HAL_BOOL
172 ar5416AniControl(struct ath_hal *ah, HAL_ANI_CMD cmd, int param)
173 {
174         typedef int TABLE[];
175         struct ath_hal_5212 *ahp = AH5212(ah);
176         struct ar5212AniState *aniState = ahp->ah_curani;
177         const struct ar5212AniParams *params = aniState->params;
178
179         OS_MARK(ah, AH_MARK_ANI_CONTROL, cmd);
180
181         switch (cmd) {
182         case HAL_ANI_NOISE_IMMUNITY_LEVEL: {
183                 u_int level = param;
184
185                 if (level >= params->maxNoiseImmunityLevel) {
186                         HALDEBUG(ah, HAL_DEBUG_ANY,
187                             "%s: immunity level out of range (%u > %u)\n",
188                             __func__, level, params->maxNoiseImmunityLevel);
189                         return AH_FALSE;
190                 }
191
192                 OS_REG_RMW_FIELD(ah, AR_PHY_DESIRED_SZ,
193                     AR_PHY_DESIRED_SZ_TOT_DES, params->totalSizeDesired[level]);
194                 OS_REG_RMW_FIELD(ah, AR_PHY_AGC_CTL1,
195                     AR_PHY_AGC_CTL1_COARSE_LOW, params->coarseLow[level]);
196                 OS_REG_RMW_FIELD(ah, AR_PHY_AGC_CTL1,
197                     AR_PHY_AGC_CTL1_COARSE_HIGH, params->coarseHigh[level]);
198                 OS_REG_RMW_FIELD(ah, AR_PHY_FIND_SIG,
199                     AR_PHY_FIND_SIG_FIRPWR, params->firpwr[level]);
200
201                 if (level > aniState->noiseImmunityLevel)
202                         ahp->ah_stats.ast_ani_niup++;
203                 else if (level < aniState->noiseImmunityLevel)
204                         ahp->ah_stats.ast_ani_nidown++;
205                 aniState->noiseImmunityLevel = level;
206                 break;
207         }
208         case HAL_ANI_OFDM_WEAK_SIGNAL_DETECTION: {
209                 static const TABLE m1ThreshLow   = { 127,   50 };
210                 static const TABLE m2ThreshLow   = { 127,   40 };
211                 static const TABLE m1Thresh      = { 127, 0x4d };
212                 static const TABLE m2Thresh      = { 127, 0x40 };
213                 static const TABLE m2CountThr    = {  31,   16 };
214                 static const TABLE m2CountThrLow = {  63,   48 };
215                 u_int on = param ? 1 : 0;
216
217                 OS_REG_RMW_FIELD(ah, AR_PHY_SFCORR_LOW,
218                         AR_PHY_SFCORR_LOW_M1_THRESH_LOW, m1ThreshLow[on]);
219                 OS_REG_RMW_FIELD(ah, AR_PHY_SFCORR_LOW,
220                         AR_PHY_SFCORR_LOW_M2_THRESH_LOW, m2ThreshLow[on]);
221                 OS_REG_RMW_FIELD(ah, AR_PHY_SFCORR,
222                         AR_PHY_SFCORR_M1_THRESH, m1Thresh[on]);
223                 OS_REG_RMW_FIELD(ah, AR_PHY_SFCORR,
224                         AR_PHY_SFCORR_M2_THRESH, m2Thresh[on]);
225                 OS_REG_RMW_FIELD(ah, AR_PHY_SFCORR,
226                         AR_PHY_SFCORR_M2COUNT_THR, m2CountThr[on]);
227                 OS_REG_RMW_FIELD(ah, AR_PHY_SFCORR_LOW,
228                         AR_PHY_SFCORR_LOW_M2COUNT_THR_LOW, m2CountThrLow[on]);
229
230                 OS_REG_RMW_FIELD(ah, AR_PHY_SFCORR_EXT,
231                         AR_PHY_SFCORR_EXT_M1_THRESH_LOW, m1ThreshLow[on]);
232                 OS_REG_RMW_FIELD(ah, AR_PHY_SFCORR_EXT,
233                         AR_PHY_SFCORR_EXT_M2_THRESH_LOW, m2ThreshLow[on]);
234                 OS_REG_RMW_FIELD(ah, AR_PHY_SFCORR_EXT,
235                         AR_PHY_SFCORR_EXT_M1_THRESH, m1Thresh[on]);
236                 OS_REG_RMW_FIELD(ah, AR_PHY_SFCORR_EXT,
237                         AR_PHY_SFCORR_EXT_M2_THRESH, m2Thresh[on]);
238
239                 if (on) {
240                         OS_REG_SET_BIT(ah, AR_PHY_SFCORR_LOW,
241                                 AR_PHY_SFCORR_LOW_USE_SELF_CORR_LOW);
242                 } else {
243                         OS_REG_CLR_BIT(ah, AR_PHY_SFCORR_LOW,
244                                 AR_PHY_SFCORR_LOW_USE_SELF_CORR_LOW);
245                 }
246                 if (on)
247                         ahp->ah_stats.ast_ani_ofdmon++;
248                 else
249                         ahp->ah_stats.ast_ani_ofdmoff++;
250                 aniState->ofdmWeakSigDetectOff = !on;
251                 break;
252         }
253         case HAL_ANI_CCK_WEAK_SIGNAL_THR: {
254                 static const TABLE weakSigThrCck = { 8, 6 };
255                 u_int high = param ? 1 : 0;
256
257                 OS_REG_RMW_FIELD(ah, AR_PHY_CCK_DETECT,
258                     AR_PHY_CCK_DETECT_WEAK_SIG_THR_CCK, weakSigThrCck[high]);
259                 if (high)
260                         ahp->ah_stats.ast_ani_cckhigh++;
261                 else
262                         ahp->ah_stats.ast_ani_ccklow++;
263                 aniState->cckWeakSigThreshold = high;
264                 break;
265         }
266         case HAL_ANI_FIRSTEP_LEVEL: {
267                 u_int level = param;
268
269                 if (level >= params->maxFirstepLevel) {
270                         HALDEBUG(ah, HAL_DEBUG_ANY,
271                             "%s: firstep level out of range (%u > %u)\n",
272                             __func__, level, params->maxFirstepLevel);
273                         return AH_FALSE;
274                 }
275                 OS_REG_RMW_FIELD(ah, AR_PHY_FIND_SIG,
276                     AR_PHY_FIND_SIG_FIRSTEP, params->firstep[level]);
277                 if (level > aniState->firstepLevel)
278                         ahp->ah_stats.ast_ani_stepup++;
279                 else if (level < aniState->firstepLevel)
280                         ahp->ah_stats.ast_ani_stepdown++;
281                 aniState->firstepLevel = level;
282                 break;
283         }
284         case HAL_ANI_SPUR_IMMUNITY_LEVEL: {
285                 u_int level = param;
286
287                 if (level >= params->maxSpurImmunityLevel) {
288                         HALDEBUG(ah, HAL_DEBUG_ANY,
289                             "%s: spur immunity level out of range (%u > %u)\n",
290                             __func__, level, params->maxSpurImmunityLevel);
291                         return AH_FALSE;
292                 }
293                 OS_REG_RMW_FIELD(ah, AR_PHY_TIMING5,
294                     AR_PHY_TIMING5_CYCPWR_THR1, params->cycPwrThr1[level]);
295                 if (level > aniState->spurImmunityLevel)
296                         ahp->ah_stats.ast_ani_spurup++;
297                 else if (level < aniState->spurImmunityLevel)
298                         ahp->ah_stats.ast_ani_spurdown++;
299                 aniState->spurImmunityLevel = level;
300                 break;
301         }
302         case HAL_ANI_PRESENT:
303                 break;
304         case HAL_ANI_MODE:
305                 if (param == 0) {
306                         ahp->ah_procPhyErr &= ~HAL_ANI_ENA;
307                         /* Turn off HW counters if we have them */
308                         ar5416AniDetach(ah);
309                         ar5212SetRxFilter(ah,
310                                 ar5212GetRxFilter(ah) &~ HAL_RX_FILTER_PHYERR);
311                 } else {                        /* normal/auto mode */
312                         /* don't mess with state if already enabled */
313                         if (ahp->ah_procPhyErr & HAL_ANI_ENA)
314                                 break;
315                         ar5212SetRxFilter(ah,
316                                 ar5212GetRxFilter(ah) &~ HAL_RX_FILTER_PHYERR);
317                         /* Enable MIB Counters */
318                         enableAniMIBCounters(ah, ahp->ah_curani != AH_NULL ?
319                             ahp->ah_curani->params: &ahp->ah_aniParams24 /*XXX*/);
320                         ahp->ah_procPhyErr |= HAL_ANI_ENA;
321                 }
322                 break;
323 #ifdef AH_PRIVATE_DIAG
324         case HAL_ANI_PHYERR_RESET:
325                 ahp->ah_stats.ast_ani_ofdmerrs = 0;
326                 ahp->ah_stats.ast_ani_cckerrs = 0;
327                 break;
328 #endif /* AH_PRIVATE_DIAG */
329         default:
330                 HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid cmd %u\n",
331                     __func__, cmd);
332                 return AH_FALSE;
333         }
334         return AH_TRUE;
335 }
336
337 static void
338 ar5416AniOfdmErrTrigger(struct ath_hal *ah)
339 {
340         struct ath_hal_5212 *ahp = AH5212(ah);
341         const struct ieee80211_channel *chan = AH_PRIVATE(ah)->ah_curchan;
342         struct ar5212AniState *aniState;
343         const struct ar5212AniParams *params;
344
345         HALASSERT(chan != AH_NULL);
346
347         if (!ANI_ENA(ah))
348                 return;
349
350         aniState = ahp->ah_curani;
351         params = aniState->params;
352         /* First, raise noise immunity level, up to max */
353         if (aniState->noiseImmunityLevel+1 < params->maxNoiseImmunityLevel) {
354                 ar5416AniControl(ah, HAL_ANI_NOISE_IMMUNITY_LEVEL, 
355                                  aniState->noiseImmunityLevel + 1);
356                 return;
357         }
358         /* then, raise spur immunity level, up to max */
359         if (aniState->spurImmunityLevel+1 < params->maxSpurImmunityLevel) {
360                 ar5416AniControl(ah, HAL_ANI_SPUR_IMMUNITY_LEVEL,
361                                  aniState->spurImmunityLevel + 1);
362                 return;
363         }
364
365         if (ANI_ENA_RSSI(ah)) {
366                 int32_t rssi = BEACON_RSSI(ahp);
367                 if (rssi > params->rssiThrHigh) {
368                         /*
369                          * Beacon rssi is high, can turn off ofdm
370                          * weak sig detect.
371                          */
372                         if (!aniState->ofdmWeakSigDetectOff) {
373                                 ar5416AniControl(ah,
374                                     HAL_ANI_OFDM_WEAK_SIGNAL_DETECTION,
375                                     AH_FALSE);
376                                 ar5416AniControl(ah,
377                                     HAL_ANI_SPUR_IMMUNITY_LEVEL, 0);
378                                 return;
379                         }
380                         /* 
381                          * If weak sig detect is already off, as last resort,
382                          * raise firstep level 
383                          */
384                         if (aniState->firstepLevel+1 < params->maxFirstepLevel) {
385                                 ar5416AniControl(ah, HAL_ANI_FIRSTEP_LEVEL,
386                                                  aniState->firstepLevel + 1);
387                                 return;
388                         }
389                 } else if (rssi > params->rssiThrLow) {
390                         /* 
391                          * Beacon rssi in mid range, need ofdm weak signal
392                          * detect, but we can raise firststepLevel.
393                          */
394                         if (aniState->ofdmWeakSigDetectOff)
395                                 ar5416AniControl(ah,
396                                     HAL_ANI_OFDM_WEAK_SIGNAL_DETECTION,
397                                     AH_TRUE);
398                         if (aniState->firstepLevel+1 < params->maxFirstepLevel)
399                                 ar5416AniControl(ah, HAL_ANI_FIRSTEP_LEVEL,
400                                      aniState->firstepLevel + 1);
401                         return;
402                 } else {
403                         /* 
404                          * Beacon rssi is low, if in 11b/g mode, turn off ofdm
405                          * weak signal detection and zero firstepLevel to
406                          * maximize CCK sensitivity 
407                          */
408                         if (IEEE80211_IS_CHAN_CCK(chan)) {
409                                 if (!aniState->ofdmWeakSigDetectOff)
410                                         ar5416AniControl(ah,
411                                             HAL_ANI_OFDM_WEAK_SIGNAL_DETECTION,
412                                             AH_FALSE);
413                                 if (aniState->firstepLevel > 0)
414                                         ar5416AniControl(ah,
415                                              HAL_ANI_FIRSTEP_LEVEL, 0);
416                                 return;
417                         }
418                 }
419         }
420 }
421
422 static void
423 ar5416AniCckErrTrigger(struct ath_hal *ah)
424 {
425         struct ath_hal_5212 *ahp = AH5212(ah);
426         const struct ieee80211_channel *chan = AH_PRIVATE(ah)->ah_curchan;
427         struct ar5212AniState *aniState;
428         const struct ar5212AniParams *params;
429
430         HALASSERT(chan != AH_NULL);
431
432         if (!ANI_ENA(ah))
433                 return;
434
435         /* first, raise noise immunity level, up to max */
436         aniState = ahp->ah_curani;
437         params = aniState->params;
438         if (aniState->noiseImmunityLevel+1 < params->maxNoiseImmunityLevel) {
439                 ar5416AniControl(ah, HAL_ANI_NOISE_IMMUNITY_LEVEL,
440                                  aniState->noiseImmunityLevel + 1);
441                 return;
442         }
443
444         if (ANI_ENA_RSSI(ah)) {
445                 int32_t rssi = BEACON_RSSI(ahp);
446                 if (rssi >  params->rssiThrLow) {
447                         /*
448                          * Beacon signal in mid and high range,
449                          * raise firstep level.
450                          */
451                         if (aniState->firstepLevel+1 < params->maxFirstepLevel)
452                                 ar5416AniControl(ah, HAL_ANI_FIRSTEP_LEVEL,
453                                                  aniState->firstepLevel + 1);
454                 } else {
455                         /*
456                          * Beacon rssi is low, zero firstep level to maximize
457                          * CCK sensitivity in 11b/g mode.
458                          */
459                         if (IEEE80211_IS_CHAN_CCK(chan)) {
460                                 if (aniState->firstepLevel > 0)
461                                         ar5416AniControl(ah,
462                                             HAL_ANI_FIRSTEP_LEVEL, 0);
463                         }
464                 }
465         }
466 }
467
468 static void
469 ar5416AniRestart(struct ath_hal *ah, struct ar5212AniState *aniState)
470 {
471         struct ath_hal_5212 *ahp = AH5212(ah);
472         const struct ar5212AniParams *params = aniState->params;
473
474         aniState->listenTime = 0;
475         /*
476          * NB: these are written on reset based on the
477          *     ini so we must re-write them!
478          */
479         HALDEBUG(ah, HAL_DEBUG_ANI,
480             "%s: Writing ofdmbase=%u   cckbase=%u\n", __func__,
481             params->ofdmPhyErrBase, params->cckPhyErrBase);
482         OS_REG_WRITE(ah, AR_PHY_ERR_1, params->ofdmPhyErrBase);
483         OS_REG_WRITE(ah, AR_PHY_ERR_2, params->cckPhyErrBase);
484         OS_REG_WRITE(ah, AR_PHY_ERR_MASK_1, AR_PHY_ERR_OFDM_TIMING);
485         OS_REG_WRITE(ah, AR_PHY_ERR_MASK_1, AR_PHY_ERR_CCK_TIMING);
486
487         /* Clear the mib counters and save them in the stats */
488         ar5212UpdateMibCounters(ah, &ahp->ah_mibStats);
489         aniState->ofdmPhyErrCount = 0;
490         aniState->cckPhyErrCount = 0;
491 }
492
493 /*
494  * Restore/reset the ANI parameters and reset the statistics.
495  * This routine must be called for every channel change.
496  *
497  * NOTE: This is where ah_curani is set; other ani code assumes
498  *       it is setup to reflect the current channel.
499  */
500 void
501 ar5416AniReset(struct ath_hal *ah, const struct ieee80211_channel *chan,
502         HAL_OPMODE opmode, int restore)
503 {
504         struct ath_hal_5212 *ahp = AH5212(ah);
505         HAL_CHANNEL_INTERNAL *ichan = ath_hal_checkchannel(ah, chan);
506         /* XXX bounds check ic_devdata */
507         struct ar5212AniState *aniState = &ahp->ah_ani[chan->ic_devdata];
508         uint32_t rxfilter;
509
510         if ((ichan->privFlags & CHANNEL_ANI_INIT) == 0) {
511                 OS_MEMZERO(aniState, sizeof(*aniState));
512                 if (IEEE80211_IS_CHAN_2GHZ(chan))
513                         aniState->params = &ahp->ah_aniParams24;
514                 else
515                         aniState->params = &ahp->ah_aniParams5;
516                 ichan->privFlags |= CHANNEL_ANI_INIT;
517                 HALASSERT((ichan->privFlags & CHANNEL_ANI_SETUP) == 0);
518         }
519         ahp->ah_curani = aniState;
520 #if 0
521         ath_hal_printf(ah,"%s: chan %u/0x%x restore %d opmode %u%s\n",
522             __func__, chan->ic_freq, chan->ic_flags, restore, opmode,
523             ichan->privFlags & CHANNEL_ANI_SETUP ? " setup" : "");
524 #else
525         HALDEBUG(ah, HAL_DEBUG_ANI, "%s: chan %u/0x%x restore %d opmode %u%s\n",
526             __func__, chan->ic_freq, chan->ic_flags, restore, opmode,
527             ichan->privFlags & CHANNEL_ANI_SETUP ? " setup" : "");
528 #endif
529         OS_MARK(ah, AH_MARK_ANI_RESET, opmode);
530
531         /*
532          * Turn off PHY error frame delivery while we futz with settings.
533          */
534         rxfilter = ar5212GetRxFilter(ah);
535         ar5212SetRxFilter(ah, rxfilter &~ HAL_RX_FILTER_PHYERR);
536         /*
537          * Automatic processing is done only in station mode right now.
538          */
539         if (opmode == HAL_M_STA)
540                 ahp->ah_procPhyErr |= HAL_RSSI_ANI_ENA;
541         else
542                 ahp->ah_procPhyErr &= ~HAL_RSSI_ANI_ENA;
543         /*
544          * Set all ani parameters.  We either set them to initial
545          * values or restore the previous ones for the channel.
546          * XXX if ANI follows hardware, we don't care what mode we're
547          * XXX in, we should keep the ani parameters
548          */
549         if (restore && (ichan->privFlags & CHANNEL_ANI_SETUP)) {
550                 ar5416AniControl(ah, HAL_ANI_NOISE_IMMUNITY_LEVEL,
551                                  aniState->noiseImmunityLevel);
552                 ar5416AniControl(ah, HAL_ANI_SPUR_IMMUNITY_LEVEL,
553                                  aniState->spurImmunityLevel);
554                 ar5416AniControl(ah, HAL_ANI_OFDM_WEAK_SIGNAL_DETECTION,
555                                  !aniState->ofdmWeakSigDetectOff);
556                 ar5416AniControl(ah, HAL_ANI_CCK_WEAK_SIGNAL_THR,
557                                  aniState->cckWeakSigThreshold);
558                 ar5416AniControl(ah, HAL_ANI_FIRSTEP_LEVEL,
559                                  aniState->firstepLevel);
560         } else {
561                 ar5416AniControl(ah, HAL_ANI_NOISE_IMMUNITY_LEVEL, 0);
562                 ar5416AniControl(ah, HAL_ANI_SPUR_IMMUNITY_LEVEL, 0);
563                 ar5416AniControl(ah, HAL_ANI_OFDM_WEAK_SIGNAL_DETECTION,
564                         AH_TRUE);
565                 ar5416AniControl(ah, HAL_ANI_CCK_WEAK_SIGNAL_THR, AH_FALSE);
566                 ar5416AniControl(ah, HAL_ANI_FIRSTEP_LEVEL, 0);
567                 ichan->privFlags |= CHANNEL_ANI_SETUP;
568         }
569         ar5416AniRestart(ah, aniState);
570
571         /* restore RX filter mask */
572         ar5212SetRxFilter(ah, rxfilter);
573 }
574
575 /*
576  * Process a MIB interrupt.  We may potentially be invoked because
577  * any of the MIB counters overflow/trigger so don't assume we're
578  * here because a PHY error counter triggered.
579  */
580 void
581 ar5416ProcessMibIntr(struct ath_hal *ah, const HAL_NODE_STATS *stats)
582 {
583         struct ath_hal_5212 *ahp = AH5212(ah);
584         uint32_t phyCnt1, phyCnt2;
585
586         HALDEBUG(ah, HAL_DEBUG_ANI, "%s: mibc 0x%x phyCnt1 0x%x phyCnt2 0x%x "
587             "filtofdm 0x%x filtcck 0x%x\n",
588             __func__, OS_REG_READ(ah, AR_MIBC),
589             OS_REG_READ(ah, AR_PHYCNT1), OS_REG_READ(ah, AR_PHYCNT2),
590             OS_REG_READ(ah, AR_FILTOFDM), OS_REG_READ(ah, AR_FILTCCK));
591
592         /*
593          * First order of business is to clear whatever caused
594          * the interrupt so we don't keep getting interrupted.
595          * We have the usual mib counters that are reset-on-read
596          * and the additional counters that appeared starting in
597          * Hainan.  We collect the mib counters and explicitly
598          * zero additional counters we are not using.  Anything
599          * else is reset only if it caused the interrupt.
600          */
601         /* NB: these are not reset-on-read */
602         phyCnt1 = OS_REG_READ(ah, AR_PHY_ERR_1);
603         phyCnt2 = OS_REG_READ(ah, AR_PHY_ERR_2);
604         /* not used, always reset them in case they are the cause */
605         OS_REG_WRITE(ah, AR_FILTOFDM, 0);
606         OS_REG_WRITE(ah, AR_FILTCCK, 0);
607         if ((OS_REG_READ(ah, AR_SLP_MIB_CTRL) & AR_SLP_MIB_PENDING) == 0)
608                 OS_REG_WRITE(ah, AR_SLP_MIB_CTRL, AR_SLP_MIB_CLEAR);
609
610         /* Clear the mib counters and save them in the stats */
611         ar5212UpdateMibCounters(ah, &ahp->ah_mibStats);
612         ahp->ah_stats.ast_nodestats = *stats;
613
614         /*
615          * Check for an ani stat hitting the trigger threshold.
616          * When this happens we get a MIB interrupt and the top
617          * 2 bits of the counter register will be 0b11, hence
618          * the mask check of phyCnt?.
619          */
620         if (((phyCnt1 & AR_MIBCNT_INTRMASK) == AR_MIBCNT_INTRMASK) || 
621             ((phyCnt2 & AR_MIBCNT_INTRMASK) == AR_MIBCNT_INTRMASK)) {
622                 struct ar5212AniState *aniState = ahp->ah_curani;
623                 const struct ar5212AniParams *params = aniState->params;
624                 uint32_t ofdmPhyErrCnt, cckPhyErrCnt;
625
626                 ofdmPhyErrCnt = phyCnt1 - params->ofdmPhyErrBase;
627                 ahp->ah_stats.ast_ani_ofdmerrs +=
628                         ofdmPhyErrCnt - aniState->ofdmPhyErrCount;
629                 aniState->ofdmPhyErrCount = ofdmPhyErrCnt;
630
631                 cckPhyErrCnt = phyCnt2 - params->cckPhyErrBase;
632                 ahp->ah_stats.ast_ani_cckerrs +=
633                         cckPhyErrCnt - aniState->cckPhyErrCount;
634                 aniState->cckPhyErrCount = cckPhyErrCnt;
635
636                 /*
637                  * NB: figure out which counter triggered.  If both
638                  * trigger we'll only deal with one as the processing
639                  * clobbers the error counter so the trigger threshold
640                  * check will never be true.
641                  */
642                 if (aniState->ofdmPhyErrCount > params->ofdmTrigHigh)
643                         ar5416AniOfdmErrTrigger(ah);
644                 if (aniState->cckPhyErrCount > params->cckTrigHigh)
645                         ar5416AniCckErrTrigger(ah);
646                 /* NB: always restart to insure the h/w counters are reset */
647                 ar5416AniRestart(ah, aniState);
648         }
649 }
650
651 static void
652 ar5416AniLowerImmunity(struct ath_hal *ah)
653 {
654         struct ath_hal_5212 *ahp = AH5212(ah);
655         struct ar5212AniState *aniState;
656         const struct ar5212AniParams *params;
657         
658         HALASSERT(ANI_ENA(ah));
659
660         aniState = ahp->ah_curani;
661         params = aniState->params;
662         if (ANI_ENA_RSSI(ah)) {
663                 int32_t rssi = BEACON_RSSI(ahp);
664                 if (rssi > params->rssiThrHigh) {
665                         /* 
666                          * Beacon signal is high, leave ofdm weak signal
667                          * detection off or it may oscillate.  Let it fall
668                          * through.
669                          */
670                 } else if (rssi > params->rssiThrLow) {
671                         /*
672                          * Beacon rssi in mid range, turn on ofdm weak signal
673                          * detection or lower firstep level.
674                          */
675                         if (aniState->ofdmWeakSigDetectOff) {
676                                 ar5416AniControl(ah,
677                                     HAL_ANI_OFDM_WEAK_SIGNAL_DETECTION,
678                                     AH_TRUE);
679                                 return;
680                         }
681                         if (aniState->firstepLevel > 0) {
682                                 ar5416AniControl(ah, HAL_ANI_FIRSTEP_LEVEL,
683                                                  aniState->firstepLevel - 1);
684                                 return;
685                         }
686                 } else {
687                         /*
688                          * Beacon rssi is low, reduce firstep level.
689                          */
690                         if (aniState->firstepLevel > 0) {
691                                 ar5416AniControl(ah, HAL_ANI_FIRSTEP_LEVEL,
692                                                  aniState->firstepLevel - 1);
693                                 return;
694                         }
695                 }
696         }
697         /* then lower spur immunity level, down to zero */
698         if (aniState->spurImmunityLevel > 0) {
699                 ar5416AniControl(ah, HAL_ANI_SPUR_IMMUNITY_LEVEL,
700                                  aniState->spurImmunityLevel - 1);
701                 return;
702         }
703         /* 
704          * if all else fails, lower noise immunity level down to a min value
705          * zero for now
706          */
707         if (aniState->noiseImmunityLevel > 0) {
708                 ar5416AniControl(ah, HAL_ANI_NOISE_IMMUNITY_LEVEL,
709                                  aniState->noiseImmunityLevel - 1);
710                 return;
711         }
712 }
713
714 #define CLOCK_RATE 44000        /* XXX use mac_usec or similar */
715 /* convert HW counter values to ms using 11g clock rate, goo9d enough
716    for 11a and Turbo */
717
718 /* 
719  * Return an approximation of the time spent ``listening'' by
720  * deducting the cycles spent tx'ing and rx'ing from the total
721  * cycle count since our last call.  A return value <0 indicates
722  * an invalid/inconsistent time.
723  */
724 static int32_t
725 ar5416AniGetListenTime(struct ath_hal *ah)
726 {
727         struct ath_hal_5212 *ahp = AH5212(ah);
728         struct ar5212AniState *aniState;
729         uint32_t txFrameCount, rxFrameCount, cycleCount;
730         int32_t listenTime;
731
732         txFrameCount = OS_REG_READ(ah, AR_TFCNT);
733         rxFrameCount = OS_REG_READ(ah, AR_RFCNT);
734         cycleCount = OS_REG_READ(ah, AR_CCCNT);
735
736         aniState = ahp->ah_curani;
737         if (aniState->cycleCount == 0 || aniState->cycleCount > cycleCount) {
738                 /*
739                  * Cycle counter wrap (or initial call); it's not possible
740                  * to accurately calculate a value because the registers
741                  * right shift rather than wrap--so punt and return 0.
742                  */
743                 listenTime = 0;
744                 ahp->ah_stats.ast_ani_lzero++;
745         } else {
746                 int32_t ccdelta = cycleCount - aniState->cycleCount;
747                 int32_t rfdelta = rxFrameCount - aniState->rxFrameCount;
748                 int32_t tfdelta = txFrameCount - aniState->txFrameCount;
749                 listenTime = (ccdelta - rfdelta - tfdelta) / CLOCK_RATE;
750         }
751         aniState->cycleCount = cycleCount;
752         aniState->txFrameCount = txFrameCount;
753         aniState->rxFrameCount = rxFrameCount;
754         return listenTime;
755 }
756
757 /*
758  * Update ani stats in preparation for listen time processing.
759  */
760 static void
761 updateMIBStats(struct ath_hal *ah, struct ar5212AniState *aniState)
762 {
763         struct ath_hal_5212 *ahp = AH5212(ah);
764         const struct ar5212AniParams *params = aniState->params;
765         uint32_t phyCnt1, phyCnt2;
766         int32_t ofdmPhyErrCnt, cckPhyErrCnt;
767
768         /* Clear the mib counters and save them in the stats */
769         ar5212UpdateMibCounters(ah, &ahp->ah_mibStats);
770
771         /* NB: these are not reset-on-read */
772         phyCnt1 = OS_REG_READ(ah, AR_PHY_ERR_1);
773         phyCnt2 = OS_REG_READ(ah, AR_PHY_ERR_2);
774
775         /* NB: these are spec'd to never roll-over */
776         ofdmPhyErrCnt = phyCnt1 - params->ofdmPhyErrBase;
777         if (ofdmPhyErrCnt < 0) {
778                 HALDEBUG(ah, HAL_DEBUG_ANI, "OFDM phyErrCnt %d phyCnt1 0x%x\n",
779                     ofdmPhyErrCnt, phyCnt1);
780                 ofdmPhyErrCnt = AR_PHY_COUNTMAX;
781         }
782         ahp->ah_stats.ast_ani_ofdmerrs +=
783              ofdmPhyErrCnt - aniState->ofdmPhyErrCount;
784         aniState->ofdmPhyErrCount = ofdmPhyErrCnt;
785
786         cckPhyErrCnt = phyCnt2 - params->cckPhyErrBase;
787         if (cckPhyErrCnt < 0) {
788                 HALDEBUG(ah, HAL_DEBUG_ANI, "CCK phyErrCnt %d phyCnt2 0x%x\n",
789                     cckPhyErrCnt, phyCnt2);
790                 cckPhyErrCnt = AR_PHY_COUNTMAX;
791         }
792         ahp->ah_stats.ast_ani_cckerrs +=
793                 cckPhyErrCnt - aniState->cckPhyErrCount;
794         aniState->cckPhyErrCount = cckPhyErrCnt;
795 }
796
797 /*
798  * Do periodic processing.  This routine is called from the
799  * driver's rx interrupt handler after processing frames.
800  */
801 void
802 ar5416AniPoll(struct ath_hal *ah, const HAL_NODE_STATS *stats,
803                 const struct ieee80211_channel *chan)
804 {
805         struct ath_hal_5212 *ahp = AH5212(ah);
806         struct ar5212AniState *aniState = ahp->ah_curani;
807         const struct ar5212AniParams *params;
808         int32_t listenTime;
809
810         ahp->ah_stats.ast_nodestats.ns_avgbrssi = stats->ns_avgbrssi;
811
812         /* XXX can aniState be null? */
813         if (aniState == AH_NULL)
814                 return;
815         if (!ANI_ENA(ah))
816                 return;
817
818         listenTime = ar5416AniGetListenTime(ah);
819         if (listenTime < 0) {
820                 ahp->ah_stats.ast_ani_lneg++;
821                 /* restart ANI period if listenTime is invalid */
822                 ar5416AniRestart(ah, aniState);
823         }
824         /* XXX beware of overflow? */
825         aniState->listenTime += listenTime;
826
827         OS_MARK(ah, AH_MARK_ANI_POLL, aniState->listenTime);
828
829         params = aniState->params;
830         if (aniState->listenTime > 5*params->period) {
831                 /* 
832                  * Check to see if need to lower immunity if
833                  * 5 aniPeriods have passed
834                  */
835                 updateMIBStats(ah, aniState);
836                 if (aniState->ofdmPhyErrCount <= aniState->listenTime *
837                     params->ofdmTrigLow/1000 &&
838                     aniState->cckPhyErrCount <= aniState->listenTime *
839                     params->cckTrigLow/1000)
840                         ar5416AniLowerImmunity(ah);
841                 ar5416AniRestart(ah, aniState);
842         } else if (aniState->listenTime > params->period) {
843                 updateMIBStats(ah, aniState);
844                 /* check to see if need to raise immunity */
845                 if (aniState->ofdmPhyErrCount > aniState->listenTime *
846                     params->ofdmTrigHigh / 1000) {
847                         ar5416AniOfdmErrTrigger(ah);
848                         ar5416AniRestart(ah, aniState);
849                 } else if (aniState->cckPhyErrCount > aniState->listenTime *
850                            params->cckTrigHigh / 1000) {
851                         ar5416AniCckErrTrigger(ah);
852                         ar5416AniRestart(ah, aniState);
853                 }
854         }
855 }