ath9k_htc: Update to upstream's commit d19607454d656cb14d8c16dfbf161eebb542e8fe dated...
[linux-libre-firmware.git] / ath9k_htc / target_firmware / wlan / ratectrl_11n_ln.c
1 /*
2  * Copyright (c) 2013 Qualcomm Atheros, Inc.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted (subject to the limitations in the
7  * disclaimer below) provided that the following conditions are met:
8  *
9  *  * Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  *  * Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the
15  *    distribution.
16  *
17  *  * Neither the name of Qualcomm Atheros nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific prior written permission.
20  *
21  * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE
22  * GRANTED BY THIS LICENSE.  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT
23  * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
24  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
25  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
27  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
30  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
31  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
32  * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
33  * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35
36 #include <adf_os_types.h>
37 #include <adf_os_dma.h>
38 #include <adf_os_timer.h>
39 #include <adf_os_lock.h>
40 #include <adf_os_io.h>
41 #include <adf_os_mem.h>
42 #include <adf_os_module.h>
43 #include <adf_os_pci.h>
44 #include <adf_os_util.h>
45 #include <adf_os_stdtypes.h>
46 #include <adf_os_defer.h>
47 #include <adf_os_atomic.h>
48 #include <adf_nbuf.h>
49 #include <adf_net.h>
50
51 #include <ieee80211_var.h>
52
53 #include <if_athvar.h>
54 #include "ah_desc.h"
55
56 #include "ratectrl.h"
57 #include "ratectrl11n.h"
58
59 static void ath_rate_newassoc_11n(struct ath_softc_tgt *sc, struct ath_node_target *an, int isnew,
60                                   unsigned int capflag, struct ieee80211_rate *rs);
61
62
63 static void ath_rate_tx_complete_11n(struct ath_softc_tgt *sc, struct ath_node_target *an,
64                                      struct ath_tx_desc *ds,
65                                      struct ath_rc_series rcs[], int nframes,
66                                      int nbad);
67
68 static void ath_rate_findrate_11n(struct ath_softc_tgt *sc,
69                                   struct ath_node_target *an,
70                                   size_t frameLen,
71                                   int numTries,
72                                   int numRates,
73                                   int stepDnInc,
74                                   unsigned int rcflag,
75                                   struct ath_rc_series series[],
76                                   int *isProbe);
77
78 static void
79 rcSortValidRates(const RATE_TABLE_11N *pRateTable, TX_RATE_CTRL *pRc)
80 {
81         A_UINT8 i,j;
82
83         for (i=pRc->maxValidRate-1; i > 0; i--) {
84                 for (j=0; j <= i-1; j++) {
85 #ifdef MAGPIE_MERLIN
86                         if (pRateTable->info[pRc->validRateIndex[j]].rateKbps >
87                             pRateTable->info[pRc->validRateIndex[j+1]].rateKbps)
88 #else
89                                 // K2
90                                 if (pRateTable->info[pRc->validRateIndex[j]].userRateKbps >
91                                     pRateTable->info[pRc->validRateIndex[j+1]].userRateKbps)
92 #endif
93                                 {
94                                         A_UINT8 tmp=0;
95                                         tmp = pRc->validRateIndex[j];
96                                         pRc->validRateIndex[j] = pRc->validRateIndex[j+1];
97                                         pRc->validRateIndex[j+1] = tmp;
98                                 }
99                 }
100         }
101 }
102
103 /* Access functions for validTxRateMask */
104
105 static void
106 rcInitValidTxMask(TX_RATE_CTRL *pRc)
107 {
108         A_UINT8 i;
109
110         for (i = 0; i < pRc->rateTableSize; i++) {
111                 pRc->validRateIndex[i] = FALSE;
112         }
113 }
114
115 static INLINE void
116 rcSetValidTxMask(TX_RATE_CTRL *pRc, A_UINT8 index, A_BOOL validTxRate)
117 {
118         ASSERT(index < pRc->rateTableSize);
119         pRc->validRateIndex[index] = validTxRate ? TRUE : FALSE;
120
121 }
122
123 /* Iterators for validTxRateMask */
124 static INLINE A_BOOL
125 rcGetNextValidTxRate(const RATE_TABLE_11N *pRateTable, TX_RATE_CTRL *pRc,
126                      A_UINT8 curValidTxRate, A_UINT8 *pNextIndex)
127 {
128         A_UINT8 i;
129
130         for (i = 0; i < pRc->maxValidRate-1; i++) {
131                 if (pRc->validRateIndex[i] == curValidTxRate) {
132                         *pNextIndex = pRc->validRateIndex[i+1];
133                         return TRUE;
134                 }
135         }
136
137         /* No more valid rates */
138         *pNextIndex = 0;
139
140         return FALSE;
141 }
142
143 static INLINE A_BOOL
144 rcGetNextLowerValidTxRate(const RATE_TABLE_11N *pRateTable, TX_RATE_CTRL *pRc,
145                           A_UINT8 curValidTxRate, A_UINT8 *pNextIndex)
146 {
147         A_INT8 i;
148
149         for (i = 1; i < pRc->maxValidRate ; i++) {
150                 if (pRc->validRateIndex[i] == curValidTxRate) {
151                         *pNextIndex = pRc->validRateIndex[i-1];
152                         return TRUE;
153                 }
154         }
155
156         return FALSE;
157 }
158
159 /* Return true only for single stream */
160
161 static A_BOOL
162 rcIsValidPhyRate(A_UINT32 phy, A_UINT32 capflag, A_BOOL ignoreCW)
163 {
164         if (WLAN_RC_PHY_HT(phy) && !(capflag & WLAN_RC_HT_FLAG)) {
165                 return FALSE;
166         }
167
168         if (WLAN_RC_PHY_DS(phy) && !(capflag & WLAN_RC_DS_FLAG))  {
169                 return FALSE;
170         }
171         if (WLAN_RC_PHY_SGI(phy) && !(capflag & WLAN_RC_HT40_SGI_FLAG)) {
172                 return FALSE;
173         }
174
175         if (!ignoreCW && WLAN_RC_PHY_HT(phy)) {
176                 if (WLAN_RC_PHY_40(phy) && !(capflag & WLAN_RC_40_FLAG)) {
177                         return FALSE;
178                 }
179
180                 if (!WLAN_RC_PHY_40(phy) && (capflag & WLAN_RC_40_FLAG)) {
181                         return FALSE;
182                 }
183         }
184
185         return TRUE;
186 }
187
188 /*
189  * Initialize the Valid Rate Index from valid entries in Rate Table
190  */
191 static A_UINT8 rcSibInitValidRates(const RATE_TABLE_11N *pRateTable,
192                                    TX_RATE_CTRL *pRc,
193                                    A_UINT32 capflag,
194                                    PHY_STATE_CTRL *pPhyStateCtrl)
195 {
196         A_UINT8 i, hi = 0;
197         A_UINT8 singleStream = (capflag & WLAN_RC_DS_FLAG) ? 0 : 1;
198         A_UINT8 valid;
199
200         for (i = 0; i < pRateTable->rateCount; i++) {
201                 if (singleStream) {
202                         valid = pRateTable->info[i].validSingleStream;
203                 } else {
204                         valid = pRateTable->info[i].valid;
205                 }
206
207                 if (valid == TRUE) {
208                         A_UINT32 phy = pRateTable->info[i].phy;
209
210                         if (!rcIsValidPhyRate(phy, capflag, FALSE))
211                                 continue;
212
213                         pPhyStateCtrl->validPhyRateIndex[phy][pPhyStateCtrl->validPhyRateCount[phy]] = i;
214                         pPhyStateCtrl->validPhyRateCount[phy] += 1;
215
216                         rcSetValidTxMask(pRc, i, TRUE);
217
218                         hi = A_MAX(hi, i);
219                 }
220         }
221
222         return hi;
223 }
224
225 /*
226  * Initialize the Valid Rate Index from Rate Set
227  */
228 static A_UINT8
229 rcSibSetValidRates(const RATE_TABLE_11N *pRateTable,
230                    TX_RATE_CTRL *pRc,
231                    struct ieee80211_rateset *pRateSet,
232                    A_UINT32 capflag,
233                    struct ath_node_target *an,
234                    PHY_STATE_CTRL *pPhyStateCtrl)
235 {
236         A_UINT8 i, j, hi = 0;
237         A_UINT8 singleStream = (capflag & WLAN_RC_DS_FLAG) ? 0 : 1;
238         A_UINT32 valid;
239
240         /* Use intersection of working rates and valid rates */
241         for (i = 0; i < pRateSet->rs_nrates; i++) {
242                 for (j = 0; j < pRateTable->rateCount; j++) {
243                         A_UINT32 phy = pRateTable->info[j].phy;
244 #ifdef MAGPIE_MERLIN
245                         struct atheros_node *pSib = ATH_NODE_ATHEROS(an);
246
247                         if (pSib->stbc) {
248                                 valid = pRateTable->info[j].validSTBC;
249                         } else if (singleStream) {
250 #else
251                         if (singleStream) {
252 #endif
253                                 valid = pRateTable->info[j].validSingleStream;
254                         } else {
255                                 valid = pRateTable->info[j].valid;
256                         }
257
258                         /*
259                          * We allow a rate only if its valid and the capflag matches one of
260                          * the validity (TRUE/TRUE_20/TRUE_40) flags
261                          */
262
263                         if (((pRateSet->rs_rates[i] & 0x7F) ==
264                              (pRateTable->info[j].dot11Rate & 0x7F))
265                             && ((valid & WLAN_RC_CAP_MODE(capflag)) ==
266                                 WLAN_RC_CAP_MODE(capflag)) && !WLAN_RC_PHY_HT(phy)) {
267                                 if (!rcIsValidPhyRate(phy, capflag, FALSE))
268                                         continue;
269
270                                 pPhyStateCtrl->validPhyRateIndex[phy][pPhyStateCtrl->validPhyRateCount[phy]] = j;
271                                 pPhyStateCtrl->validPhyRateCount[phy] += 1;
272
273                                 rcSetValidTxMask(pRc, j, TRUE);
274                                 hi = A_MAX(hi, j);
275                         }
276                 }
277         }
278
279         return hi;
280 }
281
282 static A_UINT8
283 rcSibSetValidHtRates(const RATE_TABLE_11N *pRateTable,
284                      TX_RATE_CTRL *pRc,
285                      A_UINT8 *pMcsSet,
286                      A_UINT32 capflag,
287                      struct ath_node_target *an,
288                      PHY_STATE_CTRL *pPhyStateCtrl)
289 {
290         A_UINT8 i, j, hi = 0;
291         A_UINT8 singleStream = (capflag & WLAN_RC_DS_FLAG) ? 0 : 1;
292         A_UINT8 valid;
293
294         /* Use intersection of working rates and valid rates */
295         for (i = 0; i <  ((struct ieee80211_rateset *)pMcsSet)->rs_nrates; i++) {
296                 for (j = 0; j < pRateTable->rateCount; j++) {
297                         A_UINT32 phy = pRateTable->info[j].phy;
298 #ifdef MAGPIE_MERLIN
299                         struct atheros_node *pSib = ATH_NODE_ATHEROS(an);
300
301                         if (pSib->stbc) {
302                                 valid = pRateTable->info[j].validSTBC;
303                         } else if (singleStream) {
304 #else
305                         if (singleStream) {
306 #endif
307                                 valid = pRateTable->info[j].validSingleStream;
308                         } else {
309                                 valid = pRateTable->info[j].valid;
310                         }
311
312                         if (((((struct ieee80211_rateset *)pMcsSet)->rs_rates[i] & 0x7F)
313                              != (pRateTable->info[j].dot11Rate & 0x7F))
314                             || !WLAN_RC_PHY_HT(phy)
315                             || !WLAN_RC_PHY_HT_VALID(valid, capflag)
316                             || ((pRateTable->info[j].dot11Rate == 15) &&
317                                 (valid & TRUE_20) &&
318                                 (capflag & WLAN_RC_WEP_TKIP_FLAG)) )
319                         {
320                                 continue;
321                         }
322
323                         if (!rcIsValidPhyRate(phy, capflag, FALSE))
324                                 continue;
325
326                         pPhyStateCtrl->validPhyRateIndex[phy][pPhyStateCtrl->validPhyRateCount[phy]] = j;
327                         pPhyStateCtrl->validPhyRateCount[phy] += 1;
328
329                         rcSetValidTxMask(pRc, j, TRUE);
330                         hi = A_MAX(hi, j);
331                 }
332         }
333
334         return hi;
335 }
336
337 /*
338  *  Update the SIB's rate control information
339  *
340  *  This should be called when the supported rates change
341  *  (e.g. SME operation, wireless mode change)
342  *
343  *  It will determine which rates are valid for use.
344  */
345 static void
346 rcSibUpdate_ht(struct ath_softc_tgt *sc, struct ath_node_target *an,
347                A_UINT32 capflag, A_BOOL keepState, struct ieee80211_rate  *pRateSet)
348 {
349         RATE_TABLE_11N *pRateTable = 0;
350         struct atheros_node *pSib = ATH_NODE_ATHEROS(an);
351         struct atheros_softc *asc = (struct atheros_softc*)sc->sc_rc;
352         A_UINT8 *phtMcs = (A_UINT8*)&pRateSet->htrates;
353         TX_RATE_CTRL *pRc = (TX_RATE_CTRL *)(pSib);
354         PHY_STATE_CTRL mPhyCtrlState;
355
356         A_UINT8 i, j, k, hi = 0, htHi = 0;
357
358         pRateTable = (RATE_TABLE_11N*)asc->hwRateTable[sc->sc_curmode];
359
360         /* Initial rate table size. Will change depending on the working rate set */
361         pRc->rateTableSize = MAX_TX_RATE_TBL;
362
363         /* Initialize thresholds according to the global rate table */
364         for (i = 0 ; (i < pRc->rateTableSize) && (!keepState); i++) {
365                 pRc->state[i].per       = 0;
366         }
367
368         /* Determine the valid rates */
369         rcInitValidTxMask(pRc);
370
371         for (i = 0; i < WLAN_RC_PHY_MAX; i++) {
372                 for (j = 0; j < MAX_TX_RATE_TBL; j++) {
373                         mPhyCtrlState.validPhyRateIndex[i][j] = 0;
374                 }
375                 mPhyCtrlState.validPhyRateCount[i] = 0;
376         }
377
378         pRc->rcPhyMode = (capflag & WLAN_RC_40_FLAG);
379
380         if (pRateSet == NULL || !pRateSet->rates.rs_nrates) {
381                 /* No working rate, just initialize valid rates */
382                 hi = rcSibInitValidRates(pRateTable, pRc, capflag, &mPhyCtrlState);
383         } else {
384                 /* Use intersection of working rates and valid rates */
385                 hi = rcSibSetValidRates(pRateTable, pRc, &(pRateSet->rates),
386                                         capflag, an, &mPhyCtrlState);
387
388                 if (capflag & WLAN_RC_HT_FLAG) {
389                         htHi = rcSibSetValidHtRates(pRateTable, pRc, phtMcs,
390                                                     capflag, an, &mPhyCtrlState);
391                 }
392
393                 hi = A_MAX(hi, htHi);
394         }
395
396         pRc->rateTableSize = hi + 1;
397         pRc->rateMaxPhy    = 0;
398
399         ASSERT(pRc->rateTableSize <= MAX_TX_RATE_TBL);
400
401         for (i = 0, k = 0; i < WLAN_RC_PHY_MAX; i++) {
402                 for (j = 0; j < mPhyCtrlState.validPhyRateCount[i]; j++) {
403                         pRc->validRateIndex[k++] = mPhyCtrlState.validPhyRateIndex[i][j];
404                 }
405
406                 if (!rcIsValidPhyRate(i, pRateTable->initialRateMax, TRUE) ||
407                     !mPhyCtrlState.validPhyRateCount[i])
408                         continue;
409
410                 pRc->rateMaxPhy = mPhyCtrlState.validPhyRateIndex[i][j-1];
411         }
412
413         ASSERT(pRc->rateTableSize <= MAX_TX_RATE_TBL);
414         ASSERT(k <= MAX_TX_RATE_TBL);
415
416         pRc->rateMaxPhy = pRc->validRateIndex[k-4];
417         pRc->maxValidRate = k;
418
419         rcSortValidRates(pRateTable, pRc);
420 }
421
422 static A_UINT8
423 rcRateFind_ht(struct ath_softc_tgt *sc, struct atheros_node *pSib,
424               const RATE_TABLE_11N *pRateTable, A_BOOL probeAllowed, A_BOOL *isProbing)
425 {
426         A_UINT32             bestThruput, thisThruput;
427         A_UINT32             nowMsec;
428         A_UINT8              rate, nextRate, bestRate;
429         A_UINT8              maxIndex, minIndex;
430         A_INT8               index;
431         TX_RATE_CTRL         *pRc = NULL;
432
433         pRc = (TX_RATE_CTRL *)(pSib ? (pSib) : NULL);
434
435         *isProbing = FALSE;
436
437         /*
438          * Age (reduce) last ack rssi based on how old it is.
439          * The bizarre numbers are so the delta is 160msec,
440          * meaning we divide by 16.
441          *   0msec   <= dt <= 25msec:   don't derate
442          *   25msec  <= dt <= 185msec:  derate linearly from 0 to 10dB
443          *   185msec <= dt:             derate by 10dB
444          */
445
446         nowMsec = A_MS_TICKGET();
447
448         /*
449          * Now look up the rate in the rssi table and return it.
450          * If no rates match then we return 0 (lowest rate)
451          */
452
453         bestThruput = 0;
454         maxIndex = pRc->maxValidRate-1;
455
456         minIndex = 0;
457         bestRate = minIndex;
458
459         /*
460          * Try the higher rate first. It will reduce memory moving time
461          * if we have very good channel characteristics.
462          */
463         for (index = maxIndex; index >= minIndex ; index--) {
464                 A_UINT8 perThres;
465
466                 rate = pRc->validRateIndex[index];
467                 if (rate > pRc->rateMaxPhy) {
468                         continue;
469                 }
470
471                 /* if the best throughput is already larger than the userRateKbps..
472                  * then we could skip of rest of calculation..
473                  */
474                 if( bestThruput >= pRateTable->info[rate].userRateKbps)
475                         break;
476
477                 /*
478                  * For TCP the average collision rate is around 11%,
479                  * so we ignore PERs less than this.  This is to
480                  * prevent the rate we are currently using (whose
481                  * PER might be in the 10-15 range because of TCP
482                  * collisions) looking worse than the next lower
483                  * rate whose PER has decayed close to 0.  If we
484                  * used to next lower rate, its PER would grow to
485                  * 10-15 and we would be worse off then staying
486                  * at the current rate.
487                  */
488                 perThres = pRc->state[rate].per;
489                 if ( perThres < 12 ) {
490                         perThres = 12;
491                 }
492
493                 thisThruput = pRateTable->info[rate].userRateKbps * (100 - perThres);
494                 if (bestThruput <= thisThruput) {
495                         bestThruput = thisThruput;
496                         bestRate    = rate;
497                 }
498         }
499
500         rate = bestRate;
501
502         /*
503          * Must check the actual rate (rateKbps) to account for non-monoticity of
504          * 11g's rate table
505          */
506
507         if (rate >= pRc->rateMaxPhy && probeAllowed) {
508                 rate = pRc->rateMaxPhy;
509
510                 /* Probe the next allowed phy state */
511                 /* FIXME: Check to make sure ratMax is checked properly */
512                 if (rcGetNextValidTxRate( pRateTable, pRc, rate, &nextRate) &&
513                     (nowMsec - pRc->probeTime > pRateTable->probeInterval) &&
514                     (pRc->hwMaxRetryPktCnt >= 1))
515                 {
516                         rate                  = nextRate;
517                         pRc->probeRate        = rate;
518                         pRc->probeTime        = nowMsec;
519                         pRc->hwMaxRetryPktCnt = 0;
520                         *isProbing            = TRUE;
521
522                 }
523         }
524
525         /*
526          * Make sure rate is not higher than the allowed maximum.
527          * We should also enforce the min, but I suspect the min is
528          * normally 1 rather than 0 because of the rate 9 vs 6 issue
529          * in the old code.
530          */
531         if (rate > (pRc->rateTableSize - 1)) {
532                 rate = pRc->rateTableSize - 1;
533         }
534
535         /* record selected rate, which is used to decide if we want to do fast frame */
536         if (!(*isProbing) && pSib) {
537                 pSib->lastRateKbps = pRateTable->info[rate].rateKbps;
538                 ((struct atheros_softc*)sc->sc_rc)->currentTxRateKbps = pSib->lastRateKbps;
539                 ((struct atheros_softc*)sc->sc_rc)->currentTxRateIndex = rate;
540         }
541
542         return rate;
543 }
544
545 static void
546 rcRateSetseries(const RATE_TABLE_11N *pRateTable ,
547                 struct ath_rc_series *series,
548                 A_UINT8 tries, A_UINT8 rix,
549                 A_BOOL rtsctsenable, A_UINT32 chainmask,int stbc)
550 {
551         series->tries = tries;
552         series->flags = (rtsctsenable? ATH_RC_RTSCTS_FLAG : 0) |
553                 (WLAN_RC_PHY_DS(pRateTable->info[rix].phy) ? ATH_RC_DS_FLAG : 0) |
554                 (WLAN_RC_PHY_40(pRateTable->info[rix].phy) ? ATH_RC_CW40_FLAG : 0) |
555                 (WLAN_RC_PHY_SGI(pRateTable->info[rix].phy) ? ATH_RC_HT40_SGI_FLAG : 0);
556 #ifdef MAGPIE_MERLIN
557         if (stbc) {
558                 /* For now, only single stream STBC is supported */
559                 if (pRateTable->info[rix].rateCode >= 0x80 &&
560                     pRateTable->info[rix].rateCode <= 0x87)
561                 {
562                         series->flags |= ATH_RC_TX_STBC_FLAG;
563                 }
564         }
565 #endif
566         series->rix = pRateTable->info[rix].baseIndex;
567         series->max4msframelen = pRateTable->info[rix].max4msframelen;
568         series->txrateKbps = pRateTable->info[rix].rateKbps;
569
570         /* If the hardware is capable of multiple transmit chains (chainmask is 3, 5 or 7),
571          * then choose the number of transmit chains dynamically based on entries in the rate table.
572          */
573 #ifndef ATH_ENABLE_WLAN_FOR_K2
574         if(chainmask == 7)
575                 series->tx_chainmask = pRateTable->info[rix].txChainMask_3ch;
576         else if(chainmask == 1)
577                 series->tx_chainmask = 1;
578         else
579                 series->tx_chainmask = pRateTable->info[rix].txChainMask_2ch;  /*Chainmask is 3 or 5*/
580 #else
581         series->tx_chainmask = 1;
582 #endif
583 }
584
585 static A_UINT8
586 rcRateGetIndex(struct ath_softc_tgt *sc, struct ath_node_target *an,
587                const RATE_TABLE_11N *pRateTable ,
588                A_UINT8 rix, A_UINT16 stepDown, A_UINT16 minRate)
589 {
590         A_UINT32                j;
591         A_UINT8                 nextIndex;
592         struct atheros_node     *pSib = ATH_NODE_ATHEROS(an);
593         TX_RATE_CTRL            *pRc = (TX_RATE_CTRL *)(pSib);
594
595         if (minRate) {
596                 for (j = RATE_TABLE_11N_SIZE; j > 0; j-- ) {
597                         if (rcGetNextLowerValidTxRate(pRateTable, pRc, rix, &nextIndex)) {
598                                 rix = nextIndex;
599                         } else {
600                                 break;
601                         }
602                 }
603         } else {
604                 for (j = stepDown; j > 0; j-- ) {
605                         if (rcGetNextLowerValidTxRate(pRateTable, pRc, rix, &nextIndex)) {
606                                 rix = nextIndex;
607                         } else {
608                                 break;
609                         }
610                 }
611         }
612
613         return rix;
614 }
615
616 void rcRateFind_11n(struct ath_softc_tgt *sc, struct ath_node_target *an,
617                     int numTries, int numRates, int stepDnInc,
618                     unsigned int rcflag, struct ath_rc_series series[], int *isProbe)
619 {
620         A_UINT8 i = 0;
621         A_UINT8 tryPerRate  = 0;
622         struct atheros_softc *asc = (struct atheros_softc*)sc->sc_rc;
623         RATE_TABLE_11N *pRateTable = (RATE_TABLE_11N *)asc->hwRateTable[sc->sc_curmode];
624         struct atheros_node *asn = ATH_NODE_ATHEROS(an);
625         A_UINT8 rix, nrix;
626         A_UINT8 dot11Rate;
627         WLAN_PHY phy;
628
629         rix = rcRateFind_ht(sc, asn, pRateTable, (rcflag & ATH_RC_PROBE_ALLOWED) ? 1 : 0,
630                             isProbe);
631         nrix = rix;
632
633         if ((rcflag & ATH_RC_PROBE_ALLOWED) && (*isProbe)) {
634                 /* set one try for probe rates. For the probes don't enable rts */
635                 rcRateSetseries(pRateTable, &series[i++], 1, nrix,
636                                 FALSE, asc->tx_chainmask, asn->stbc);
637
638                 /*
639                  * Get the next tried/allowed rate. No RTS for the next series
640                  * after the probe rate
641                  */
642                 nrix = rcRateGetIndex( sc, an, pRateTable, nrix, 1, FALSE);
643         }
644
645         tryPerRate = (numTries/numRates);
646
647         /* Set the choosen rate. No RTS for first series entry. */
648         rcRateSetseries(pRateTable, &series[i++], tryPerRate,
649                         nrix, FALSE, asc->tx_chainmask, asn->stbc);
650
651         /* Fill in the other rates for multirate retry */
652         for (; i < numRates; i++) {
653                 A_UINT8 tryNum;
654                 A_UINT8 minRate;
655
656                 tryNum  = ((i + 1) == numRates) ? numTries - (tryPerRate * i) : tryPerRate ;
657                 minRate = (((i + 1) == numRates) && (rcflag & ATH_RC_MINRATE_LASTRATE)) ? 1 : 0;
658
659                 nrix = rcRateGetIndex(sc, an, pRateTable, nrix, stepDnInc, minRate);
660
661                 /* All other rates in the series have RTS enabled */
662                 rcRateSetseries(pRateTable, &series[i], tryNum,
663                                 nrix, TRUE, asc->tx_chainmask, asn->stbc);
664         }
665
666         /*
667          * BUG 26545:
668          * Change rate series to enable aggregation when operating at lower MCS rates.
669          * When first rate in series is MCS2 in HT40 @ 2.4GHz, series should look like:
670          *    {MCS2, MCS1, MCS0, MCS0}.
671          * When first rate in series is MCS3 in HT20 @ 2.4GHz, series should look like:
672          *    {MCS3, MCS2, MCS1, MCS1}
673          * So, set fourth rate in series to be same as third one for above conditions.
674          */
675         if (sc->sc_curmode == IEEE80211_MODE_11NG) {
676                 dot11Rate = pRateTable->info[rix].dot11Rate;
677                 phy = pRateTable->info[rix].phy;
678                 if (i == 4 &&
679                     ((dot11Rate == 2 && phy == WLAN_RC_PHY_HT_40_SS) ||
680                      (dot11Rate == 3 && phy == WLAN_RC_PHY_HT_20_SS)))
681                 {
682                         series[3].rix = series[2].rix;
683                         series[3].flags = series[2].flags;
684                         series[3].max4msframelen = series[2].max4msframelen;
685                 }
686         }
687
688         /*
689          * 2009/02/06
690          * AP91 Kite: NetGear OTA location-4 downlink.
691          *            Enable RTS/CTS at MCS 3-0 for downlink throughput.
692          */
693         if (sc->sc_curmode == IEEE80211_MODE_11NG) {
694                 dot11Rate = pRateTable->info[rix].dot11Rate;
695                 if (dot11Rate <= 3 ) {
696                         series[0].flags |= ATH_RC_RTSCTS_FLAG;
697                 }
698         }
699 }
700
701 static void
702 rcUpdate_ht(struct ath_softc_tgt *sc, struct ath_node_target *an, int txRate,
703             A_BOOL Xretries, int retries, A_UINT8 curTxAnt,
704             A_UINT16 nFrames, A_UINT16 nBad)
705 {
706         TX_RATE_CTRL *pRc;
707         A_UINT32 nowMsec = A_MS_TICKGET();
708         A_UINT8 lastPer;
709         int rate,count;
710         struct atheros_node *pSib = ATH_NODE_ATHEROS(an);
711         struct atheros_softc *asc = (struct atheros_softc*)sc->sc_rc;
712         RATE_TABLE_11N *pRateTable = (RATE_TABLE_11N *)asc->hwRateTable[sc->sc_curmode];
713
714         static A_UINT32 nRetry2PerLookup[10] = {
715                 100 * 0 / 1,    // 0
716                 100 * 1 / 4,    // 25
717                 100 * 1 / 2,    // 50
718                 100 * 3 / 4,    // 75
719                 100 * 4 / 5,    // 80
720                 100 * 5 / 6,    // 83.3
721                 100 * 6 / 7,    // 85.7
722                 100 * 7 / 8,    // 87.5
723                 100 * 8 / 9,    // 88.8
724                 100 * 9 / 10    // 90
725         };
726
727         if (!pSib)
728                 return;
729
730         pRc = (TX_RATE_CTRL *)(pSib);
731
732         ASSERT(retries >= 0 && retries < MAX_TX_RETRIES);
733         ASSERT(txRate >= 0);
734
735         if (txRate < 0) {
736                 return;
737         }
738
739         lastPer = pRc->state[txRate].per;
740
741         if (Xretries) {
742                 /* Update the PER. */
743                 if (Xretries == 1) {
744                         pRc->state[txRate].per += 30;
745                         if (pRc->state[txRate].per > 100) {
746                                 pRc->state[txRate].per = 100;
747                         }
748                 } else {
749                         /* Xretries == 2 */
750
751                         count = sizeof(nRetry2PerLookup) / sizeof(nRetry2PerLookup[0]);
752                         if (retries >= count) {
753                                 retries = count - 1;
754                         }
755
756                         /* new_PER = 7/8*old_PER + 1/8*(currentPER) */
757                         pRc->state[txRate].per = (A_UINT8)(pRc->state[txRate].per -
758                                                    (pRc->state[txRate].per / 8) + ((100) / 8));
759                 }
760
761                 /* Xretries == 1 or 2 */
762
763                 if (pRc->probeRate == txRate)
764                         pRc->probeRate = 0;
765         } else {
766                 /* Xretries == 0 */
767
768                 /*
769                  * Update the PER.  Make sure it doesn't index out of array's bounds.
770                  */
771                 count = sizeof(nRetry2PerLookup) / sizeof(nRetry2PerLookup[0]);
772                 if (retries >= count) {
773                         retries = count - 1;
774                 }
775
776                 if (nBad) {
777                         /* new_PER = 7/8*old_PER + 1/8*(currentPER)  */
778                         /*
779                          * Assuming that nFrames is not 0.  The current PER
780                          * from the retries is 100 * retries / (retries+1),
781                          * since the first retries attempts failed, and the
782                          * next one worked.  For the one that worked, nBad
783                          * subframes out of nFrames wored, so the PER for
784                          * that part is 100 * nBad / nFrames, and it contributes
785                          * 100 * nBad / (nFrames * (retries+1)) to the above
786                          * PER.  The expression below is a simplified version
787                          * of the sum of these two terms.
788                          */
789                         if (nFrames > 0)
790                                 pRc->state[txRate].per = (A_UINT8)(pRc->state[txRate].per -
791                                            (pRc->state[txRate].per / 8) +
792                                            ((100*(retries*nFrames + nBad)/(nFrames*(retries+1))) / 8));
793                 } else {
794                         /* new_PER = 7/8*old_PER + 1/8*(currentPER) */
795
796                         pRc->state[txRate].per = (A_UINT8)(pRc->state[txRate].per -
797                                    (pRc->state[txRate].per / 8) + (nRetry2PerLookup[retries] / 8));
798                 }
799
800                 /*
801                  * If we got at most one retry then increase the max rate if
802                  * this was a probe.  Otherwise, ignore the probe.
803                  */
804
805                 if (pRc->probeRate && pRc->probeRate == txRate) {
806                         if (retries > 0 || 2 * nBad > nFrames) {
807                                 /*
808                                  * Since we probed with just a single attempt,
809                                  * any retries means the probe failed.  Also,
810                                  * if the attempt worked, but more than half
811                                  * the subframes were bad then also consider
812                                  * the probe a failure.
813                                  */
814                                 pRc->probeRate = 0;
815                         } else {
816                                 pRc->rateMaxPhy = pRc->probeRate;
817
818                                 if (pRc->state[pRc->probeRate].per > 30) {
819                                         pRc->state[pRc->probeRate].per = 20;
820                                 }
821
822                                 pRc->probeRate = 0;
823
824                                 /*
825                                  * Since this probe succeeded, we allow the next probe
826                                  * twice as soon.  This allows the maxRate to move up
827                                  * faster if the probes are succesful.
828                                  */
829                                 pRc->probeTime = nowMsec - pRateTable->probeInterval / 2;
830                         }
831                 }
832
833                 if (retries > 0) {
834                         /*
835                          * Don't update anything.  We don't know if this was because
836                          * of collisions or poor signal.
837                          *
838                          * Later: if rssiAck is close to pRc->state[txRate].rssiThres
839                          * and we see lots of retries, then we could increase
840                          * pRc->state[txRate].rssiThres.
841                          */
842                         pRc->hwMaxRetryPktCnt = 0;
843                 } else {
844                         /*
845                          * It worked with no retries.  First ignore bogus (small)
846                          * rssiAck values.
847                          */
848                         if (txRate == pRc->rateMaxPhy && pRc->hwMaxRetryPktCnt < 255) {
849                                 pRc->hwMaxRetryPktCnt++;
850                         }
851
852                 }
853         }
854
855         /* For all cases */
856
857         ASSERT((pRc->rateMaxPhy >= 0 && pRc->rateMaxPhy <= pRc->rateTableSize &&
858                 pRc->rateMaxPhy != INVALID_RATE_MAX));
859
860         /*
861          * If this rate looks bad (high PER) then stop using it for
862          * a while (except if we are probing).
863          */
864         if (pRc->state[txRate].per >= 55 && txRate > 0 &&
865             pRateTable->info[txRate].rateKbps <=
866             pRateTable->info[pRc->rateMaxPhy].rateKbps)
867         {
868                 rcGetNextLowerValidTxRate(pRateTable, pRc, (A_UINT8) txRate,
869                                           &pRc->rateMaxPhy);
870
871                 /* Don't probe for a little while. */
872                 pRc->probeTime = nowMsec;
873         }
874
875         /* Make sure the rates below this have lower PER */
876         /* Monotonicity is kept only for rates below the current rate. */
877         if (pRc->state[txRate].per < lastPer) {
878                 for (rate = txRate - 1; rate >= 0; rate--) {
879                         if (pRateTable->info[rate].phy != pRateTable->info[txRate].phy) {
880                                 break;
881                         }
882
883                         if (pRc->state[rate].per > pRc->state[rate+1].per) {
884                                 pRc->state[rate].per = pRc->state[rate+1].per;
885                         }
886                 }
887         }
888
889         /* Maintain monotonicity for rates above the current rate*/
890         for (rate = txRate; rate < pRc->rateTableSize - 1; rate++) {
891                 if (pRc->state[rate+1].per < pRc->state[rate].per) {
892                         pRc->state[rate+1].per = pRc->state[rate].per;
893                 }
894         }
895
896         /* Every so often, we reduce the thresholds and PER (different for CCK and OFDM). */
897         if (nowMsec - pRc->perDownTime >= pRateTable->rssiReduceInterval) {
898                 for (rate = 0; rate < pRc->rateTableSize; rate++) {
899                         pRc->state[rate].per = 7*pRc->state[rate].per/8;
900                 }
901
902                 pRc->perDownTime = nowMsec;
903         }
904 }
905
906 /*
907  * This routine is called by the Tx interrupt service routine to give
908  * the status of previous frames.
909  */
910 void rcUpdate_11n(struct ath_softc_tgt *sc, struct ath_node_target *an,
911                   A_UINT8 curTxAnt,
912                   int finalTSIdx, int Xretries,
913                   struct ath_rc_series rcs[], int nFrames,
914                   int nBad, int long_retry)
915 {
916         A_UINT32 series = 0;
917         A_UINT32 rix;
918         struct atheros_softc *asc = (struct atheros_softc*)sc->sc_rc;
919         RATE_TABLE_11N *pRateTable = (RATE_TABLE_11N *)asc->hwRateTable[sc->sc_curmode];
920         struct atheros_node *pSib = ATH_NODE_ATHEROS(an);
921         TX_RATE_CTRL *pRc = (TX_RATE_CTRL *)(pSib);
922         A_UINT8 flags;
923
924         if (!an) {
925                 adf_os_assert(0);
926                 return;
927         }
928
929         ASSERT (rcs[0].tries != 0);
930
931         /*
932          * If the first rate is not the final index, there are intermediate rate failures
933          * to be processed.
934          */
935         if (finalTSIdx != 0) {
936
937                 /* Process intermediate rates that failed.*/
938                 for (series = 0; series < finalTSIdx ; series++) {
939                         if (rcs[series].tries != 0) {
940                                 flags = rcs[series].flags;
941                                 /* If HT40 and we have switched mode from 40 to 20 => don't update */
942                                 if ((flags & ATH_RC_CW40_FLAG) &&
943                                     (pRc->rcPhyMode != (flags & ATH_RC_CW40_FLAG))) {
944                                         return;
945                                 }
946                                 if ((flags & ATH_RC_CW40_FLAG) && (flags & ATH_RC_HT40_SGI_FLAG)) {
947                                         rix = pRateTable->info[rcs[series].rix].htIndex;
948                                 } else if (flags & ATH_RC_HT40_SGI_FLAG) {
949                                         rix = pRateTable->info[rcs[series].rix].sgiIndex;
950                                 } else if (flags & ATH_RC_CW40_FLAG) {
951                                         rix = pRateTable->info[rcs[series].rix].cw40Index;
952                                 } else {
953                                         rix = pRateTable->info[rcs[series].rix].baseIndex;
954                                 }
955
956                                 /* FIXME:XXXX, too many args! */
957                                 rcUpdate_ht(sc, an, rix, Xretries? 1 : 2, rcs[series].tries,
958                                             curTxAnt, nFrames, nFrames);
959                         }
960                 }
961         } else {
962                 /*
963                  * Handle the special case of MIMO PS burst, where the second aggregate is sent
964                  *  out with only one rate and one try. Treating it as an excessive retry penalizes
965                  * the rate inordinately.
966                  */
967                 if (rcs[0].tries == 1 && Xretries == 1) {
968                         Xretries = 2;
969                 }
970         }
971
972         flags = rcs[series].flags;
973         /* If HT40 and we have switched mode from 40 to 20 => don't update */
974         if ((flags & ATH_RC_CW40_FLAG) &&
975             (pRc->rcPhyMode != (flags & ATH_RC_CW40_FLAG))) {
976                 return;
977         }
978         if ((flags & ATH_RC_CW40_FLAG) && (flags & ATH_RC_HT40_SGI_FLAG)) {
979                 rix = pRateTable->info[rcs[series].rix].htIndex;
980         } else if (flags & ATH_RC_HT40_SGI_FLAG) {
981                 rix = pRateTable->info[rcs[series].rix].sgiIndex;
982         } else if (flags & ATH_RC_CW40_FLAG) {
983                 rix = pRateTable->info[rcs[series].rix].cw40Index;
984         } else {
985                 rix = pRateTable->info[rcs[series].rix].baseIndex;
986         }
987
988         /* FIXME:XXXX, too many args! */
989         rcUpdate_ht(sc, an, rix, Xretries, long_retry, curTxAnt,
990                     nFrames, nBad);
991 }
992
993 void ath_tx_status_update_rate(struct ath_softc_tgt *sc,
994                                struct ath_rc_series rcs[],
995                                int series,
996                                WMI_TXSTATUS_EVENT *txs)
997 {
998         struct atheros_softc *asc = (struct atheros_softc*)sc->sc_rc;
999         RATE_TABLE_11N *pRateTable = (RATE_TABLE_11N *)asc->hwRateTable[sc->sc_curmode];
1000
1001         /* HT Rate */
1002         if (pRateTable->info[rcs[series].rix].rateCode & 0x80) {
1003                 txs->txstatus[txs->cnt].ts_rate |= SM(pRateTable->info[rcs[series].rix].dot11Rate,
1004                                                                        ATH9K_HTC_TXSTAT_RATE);
1005                 txs->txstatus[txs->cnt].ts_flags |= ATH9K_HTC_TXSTAT_MCS;
1006
1007                 if (rcs[series].flags & ATH_RC_CW40_FLAG)
1008                         txs->txstatus[txs->cnt].ts_flags |= ATH9K_HTC_TXSTAT_CW40;
1009
1010                 if (rcs[series].flags & ATH_RC_HT40_SGI_FLAG)
1011                         txs->txstatus[txs->cnt].ts_flags |= ATH9K_HTC_TXSTAT_SGI;
1012
1013         } else {
1014                 txs->txstatus[txs->cnt].ts_rate |= SM(rcs[series].rix, ATH9K_HTC_TXSTAT_RATE);
1015         }
1016
1017         if (rcs[series].flags & ATH_RC_RTSCTS_FLAG)
1018                 txs->txstatus[txs->cnt].ts_flags |= ATH9K_HTC_TXSTAT_RTC_CTS;
1019
1020 }
1021
1022 struct ath_ratectrl *
1023 ath_rate_attach(struct ath_softc_tgt *sc)
1024 {
1025         struct atheros_softc *asc;
1026
1027         asc = adf_os_mem_alloc(sizeof(struct atheros_softc));
1028         if (asc == NULL)
1029                 return NULL;
1030
1031         adf_os_mem_set(asc, 0, sizeof(struct atheros_softc));
1032         asc->arc.arc_space = sizeof(struct atheros_node);
1033
1034         ar5416AttachRateTables(asc);
1035
1036         asc->tx_chainmask = 1;
1037
1038         return &asc->arc;
1039 }
1040
1041 void
1042 ath_rate_findrate(struct ath_softc_tgt *sc,
1043                   struct ath_node_target *an,
1044                   int shortPreamble,
1045                   size_t frameLen,
1046                   int numTries,
1047                   int numRates,
1048                   int stepDnInc,
1049                   unsigned int rcflag,
1050                   struct ath_rc_series series[],
1051                   int *isProbe)
1052 {
1053         *isProbe = 0;
1054
1055         if (!numRates || !numTries) {
1056                 return;
1057         }
1058
1059         ath_rate_findrate_11n(sc, an, frameLen, numTries, numRates, stepDnInc,
1060                               rcflag, series, isProbe);
1061 }
1062
1063 #define MS(_v, _f)  (((_v) & _f) >> _f##_S)
1064
1065 void
1066 ath_rate_tx_complete(struct ath_softc_tgt *sc,
1067                      struct ath_node_target *an,
1068                      struct ath_tx_desc *ds,
1069                      struct ath_rc_series rcs[],
1070                      int nframes, int nbad)
1071 {
1072         ath_rate_tx_complete_11n(sc, an, ds, rcs, nframes, nbad);
1073 }
1074
1075 void
1076 ath_rate_newassoc(struct ath_softc_tgt *sc, struct ath_node_target *an, int isnew,
1077                   unsigned int capflag, struct ieee80211_rate *rs)
1078 {
1079         ath_rate_newassoc_11n(sc, an, isnew, capflag, rs);
1080 }
1081
1082 void ath_rate_node_update(struct ath_softc_tgt *sc,
1083                           struct ath_node_target *an,
1084                           a_int32_t isnew,
1085                           a_uint32_t capflag,
1086                           struct ieee80211_rate *rs)
1087 {
1088         struct ieee80211_node_target *ni = &an->ni;
1089
1090         ath_rate_newassoc(sc, ATH_NODE_TARGET(ni), isnew, capflag, rs);
1091 }
1092
1093 static int init_ath_rate_atheros(void);
1094 static void exit_ath_rate_atheros(void);
1095
1096 void
1097 ath_rate_newstate(struct ath_softc_tgt *sc,
1098                   struct ieee80211vap_target *vap,
1099                   enum ieee80211_state state,
1100                   a_uint32_t capflag,
1101                   struct ieee80211_rate *rs)
1102 {
1103         struct ieee80211_node_target *ni = vap->iv_bss;
1104         struct atheros_softc *asc = (struct atheros_softc *) sc->sc_rc;
1105
1106         asc->tx_chainmask = sc->sc_ic.ic_tx_chainmask;
1107         ath_rate_newassoc(sc, ATH_NODE_TARGET(ni), 1, capflag, rs);
1108 }
1109
1110 static void
1111 ath_rate_findrate_11n(struct ath_softc_tgt *sc,
1112                       struct ath_node_target *an,
1113                       size_t frameLen,
1114                       int numTries,
1115                       int numRates,
1116                       int stepDnInc,
1117                       unsigned int rcflag,
1118                       struct ath_rc_series series[],
1119                       int *isProbe)
1120 {
1121         *isProbe = 0;
1122         if (!numRates || !numTries) {
1123                 return;
1124         }
1125
1126         rcRateFind_11n(sc, an, numTries, numRates, stepDnInc, rcflag, series, isProbe);
1127 }
1128
1129 static void
1130 ath_rate_tx_complete_11n(struct ath_softc_tgt *sc,
1131                          struct ath_node_target *an,
1132                          struct ath_tx_desc *ds,
1133                          struct ath_rc_series rcs[],
1134                          int nframes, int nbad)
1135 {
1136         int finalTSIdx = ds->ds_txstat.ts_rate;
1137         int tx_status = 0;
1138
1139         if ((ds->ds_txstat.ts_status & HAL_TXERR_XRETRY) ||
1140             (ds->ds_txstat.ts_status & HAL_TXERR_FIFO) ||
1141             (ds->ds_txstat.ts_flags & HAL_TX_DATA_UNDERRUN) ||
1142             (ds->ds_txstat.ts_flags & HAL_TX_DELIM_UNDERRUN)) {
1143                 tx_status = 1;
1144         }
1145
1146         rcUpdate_11n(sc, an,
1147                      ds->ds_txstat.ts_antenna, finalTSIdx,
1148                      tx_status, rcs, nframes , nbad,
1149                      ds->ds_txstat.ts_longretry);
1150 }
1151
1152 static void
1153 ath_rate_newassoc_11n(struct ath_softc_tgt *sc, struct ath_node_target *an, int isnew,
1154                       unsigned int capflag, struct ieee80211_rate *rs)
1155 {
1156         if (isnew) {
1157 #ifdef MAGPIE_MERLIN
1158                 struct atheros_node *oan = ATH_NODE_ATHEROS(an);
1159                 /* Only MERLIN can send STBC */
1160                 oan->stbc = (capflag & ATH_RC_TX_STBC_FLAG) ? 1 : 0;
1161 #endif
1162                 rcSibUpdate_ht(sc, an, capflag, 0, rs);
1163         }
1164 }