linux/drivers/net/wireless/iwlwifi/mvm/rs.c
<<
>>
Prefs
   1/******************************************************************************
   2 *
   3 * Copyright(c) 2005 - 2013 Intel Corporation. All rights reserved.
   4 *
   5 * This program is free software; you can redistribute it and/or modify it
   6 * under the terms of version 2 of the GNU General Public License as
   7 * published by the Free Software Foundation.
   8 *
   9 * This program is distributed in the hope that it will be useful, but WITHOUT
  10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
  12 * more details.
  13 *
  14 * You should have received a copy of the GNU General Public License along with
  15 * this program; if not, write to the Free Software Foundation, Inc.,
  16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
  17 *
  18 * The full GNU General Public License is included in this distribution in the
  19 * file called LICENSE.
  20 *
  21 * Contact Information:
  22 *  Intel Linux Wireless <ilw@linux.intel.com>
  23 * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
  24 *
  25 *****************************************************************************/
  26#include <linux/kernel.h>
  27#include <linux/init.h>
  28#include <linux/skbuff.h>
  29#include <linux/slab.h>
  30#include <net/mac80211.h>
  31
  32#include <linux/netdevice.h>
  33#include <linux/etherdevice.h>
  34#include <linux/delay.h>
  35
  36#include <linux/workqueue.h>
  37#include "rs.h"
  38#include "fw-api.h"
  39#include "sta.h"
  40#include "iwl-op-mode.h"
  41#include "mvm.h"
  42
  43#define RS_NAME "iwl-mvm-rs"
  44
  45#define NUM_TRY_BEFORE_ANT_TOGGLE 1
  46#define IWL_NUMBER_TRY      1
  47#define IWL_HT_NUMBER_TRY   3
  48
  49#define IWL_RATE_MAX_WINDOW             62      /* # tx in history window */
  50#define IWL_RATE_MIN_FAILURE_TH         6       /* min failures to calc tpt */
  51#define IWL_RATE_MIN_SUCCESS_TH         8       /* min successes to calc tpt */
  52
  53/* max allowed rate miss before sync LQ cmd */
  54#define IWL_MISSED_RATE_MAX             15
  55/* max time to accum history 2 seconds */
  56#define IWL_RATE_SCALE_FLUSH_INTVL   (3*HZ)
  57
  58static u8 rs_ht_to_legacy[] = {
  59        IWL_RATE_6M_INDEX, IWL_RATE_6M_INDEX,
  60        IWL_RATE_6M_INDEX, IWL_RATE_6M_INDEX,
  61        IWL_RATE_6M_INDEX,
  62        IWL_RATE_6M_INDEX, IWL_RATE_9M_INDEX,
  63        IWL_RATE_12M_INDEX, IWL_RATE_18M_INDEX,
  64        IWL_RATE_24M_INDEX, IWL_RATE_36M_INDEX,
  65        IWL_RATE_48M_INDEX, IWL_RATE_54M_INDEX
  66};
  67
  68static const u8 ant_toggle_lookup[] = {
  69        /*ANT_NONE -> */ ANT_NONE,
  70        /*ANT_A    -> */ ANT_B,
  71        /*ANT_B    -> */ ANT_C,
  72        /*ANT_AB   -> */ ANT_BC,
  73        /*ANT_C    -> */ ANT_A,
  74        /*ANT_AC   -> */ ANT_AB,
  75        /*ANT_BC   -> */ ANT_AC,
  76        /*ANT_ABC  -> */ ANT_ABC,
  77};
  78
  79#define IWL_DECLARE_RATE_INFO(r, s, ip, in, rp, rn, pp, np)    \
  80        [IWL_RATE_##r##M_INDEX] = { IWL_RATE_##r##M_PLCP,      \
  81                                    IWL_RATE_SISO_##s##M_PLCP, \
  82                                    IWL_RATE_MIMO2_##s##M_PLCP,\
  83                                    IWL_RATE_MIMO3_##s##M_PLCP,\
  84                                    IWL_RATE_##r##M_IEEE,      \
  85                                    IWL_RATE_##ip##M_INDEX,    \
  86                                    IWL_RATE_##in##M_INDEX,    \
  87                                    IWL_RATE_##rp##M_INDEX,    \
  88                                    IWL_RATE_##rn##M_INDEX,    \
  89                                    IWL_RATE_##pp##M_INDEX,    \
  90                                    IWL_RATE_##np##M_INDEX }
  91
  92/*
  93 * Parameter order:
  94 *   rate, ht rate, prev rate, next rate, prev tgg rate, next tgg rate
  95 *
  96 * If there isn't a valid next or previous rate then INV is used which
  97 * maps to IWL_RATE_INVALID
  98 *
  99 */
 100static const struct iwl_rs_rate_info iwl_rates[IWL_RATE_COUNT] = {
 101        IWL_DECLARE_RATE_INFO(1, INV, INV, 2, INV, 2, INV, 2),    /*  1mbps */
 102        IWL_DECLARE_RATE_INFO(2, INV, 1, 5, 1, 5, 1, 5),          /*  2mbps */
 103        IWL_DECLARE_RATE_INFO(5, INV, 2, 6, 2, 11, 2, 11),        /*5.5mbps */
 104        IWL_DECLARE_RATE_INFO(11, INV, 9, 12, 9, 12, 5, 18),      /* 11mbps */
 105        IWL_DECLARE_RATE_INFO(6, 6, 5, 9, 5, 11, 5, 11),        /*  6mbps */
 106        IWL_DECLARE_RATE_INFO(9, 6, 6, 11, 6, 11, 5, 11),       /*  9mbps */
 107        IWL_DECLARE_RATE_INFO(12, 12, 11, 18, 11, 18, 11, 18),   /* 12mbps */
 108        IWL_DECLARE_RATE_INFO(18, 18, 12, 24, 12, 24, 11, 24),   /* 18mbps */
 109        IWL_DECLARE_RATE_INFO(24, 24, 18, 36, 18, 36, 18, 36),   /* 24mbps */
 110        IWL_DECLARE_RATE_INFO(36, 36, 24, 48, 24, 48, 24, 48),   /* 36mbps */
 111        IWL_DECLARE_RATE_INFO(48, 48, 36, 54, 36, 54, 36, 54),   /* 48mbps */
 112        IWL_DECLARE_RATE_INFO(54, 54, 48, INV, 48, INV, 48, INV),/* 54mbps */
 113        IWL_DECLARE_RATE_INFO(60, 60, 48, INV, 48, INV, 48, INV),/* 60mbps */
 114        /* FIXME:RS:          ^^    should be INV (legacy) */
 115};
 116
 117static inline u8 rs_extract_rate(u32 rate_n_flags)
 118{
 119        /* also works for HT because bits 7:6 are zero there */
 120        return (u8)(rate_n_flags & RATE_LEGACY_RATE_MSK);
 121}
 122
 123static int iwl_hwrate_to_plcp_idx(u32 rate_n_flags)
 124{
 125        int idx = 0;
 126
 127        /* HT rate format */
 128        if (rate_n_flags & RATE_MCS_HT_MSK) {
 129                idx = rs_extract_rate(rate_n_flags);
 130
 131                if (idx >= IWL_RATE_MIMO3_6M_PLCP)
 132                        idx = idx - IWL_RATE_MIMO3_6M_PLCP;
 133                else if (idx >= IWL_RATE_MIMO2_6M_PLCP)
 134                        idx = idx - IWL_RATE_MIMO2_6M_PLCP;
 135
 136                idx += IWL_FIRST_OFDM_RATE;
 137                /* skip 9M not supported in ht*/
 138                if (idx >= IWL_RATE_9M_INDEX)
 139                        idx += 1;
 140                if ((idx >= IWL_FIRST_OFDM_RATE) && (idx <= IWL_LAST_OFDM_RATE))
 141                        return idx;
 142
 143        /* legacy rate format, search for match in table */
 144        } else {
 145                for (idx = 0; idx < ARRAY_SIZE(iwl_rates); idx++)
 146                        if (iwl_rates[idx].plcp ==
 147                                        rs_extract_rate(rate_n_flags))
 148                                return idx;
 149        }
 150
 151        return -1;
 152}
 153
 154static void rs_rate_scale_perform(struct iwl_mvm *mvm,
 155                                   struct sk_buff *skb,
 156                                   struct ieee80211_sta *sta,
 157                                   struct iwl_lq_sta *lq_sta);
 158static void rs_fill_link_cmd(struct iwl_mvm *mvm,
 159                             struct iwl_lq_sta *lq_sta, u32 rate_n_flags);
 160static void rs_stay_in_table(struct iwl_lq_sta *lq_sta, bool force_search);
 161
 162
 163#ifdef CONFIG_MAC80211_DEBUGFS
 164static void rs_dbgfs_set_mcs(struct iwl_lq_sta *lq_sta,
 165                             u32 *rate_n_flags, int index);
 166#else
 167static void rs_dbgfs_set_mcs(struct iwl_lq_sta *lq_sta,
 168                             u32 *rate_n_flags, int index)
 169{}
 170#endif
 171
 172/**
 173 * The following tables contain the expected throughput metrics for all rates
 174 *
 175 *      1, 2, 5.5, 11, 6, 9, 12, 18, 24, 36, 48, 54, 60 MBits
 176 *
 177 * where invalid entries are zeros.
 178 *
 179 * CCK rates are only valid in legacy table and will only be used in G
 180 * (2.4 GHz) band.
 181 */
 182
 183static s32 expected_tpt_legacy[IWL_RATE_COUNT] = {
 184        7, 13, 35, 58, 40, 57, 72, 98, 121, 154, 177, 186, 0
 185};
 186
 187static s32 expected_tpt_siso20MHz[4][IWL_RATE_COUNT] = {
 188        {0, 0, 0, 0, 42, 0,  76, 102, 124, 159, 183, 193, 202}, /* Norm */
 189        {0, 0, 0, 0, 46, 0,  82, 110, 132, 168, 192, 202, 210}, /* SGI */
 190        {0, 0, 0, 0, 47, 0,  91, 133, 171, 242, 305, 334, 362}, /* AGG */
 191        {0, 0, 0, 0, 52, 0, 101, 145, 187, 264, 330, 361, 390}, /* AGG+SGI */
 192};
 193
 194static s32 expected_tpt_siso40MHz[4][IWL_RATE_COUNT] = {
 195        {0, 0, 0, 0,  77, 0, 127, 160, 184, 220, 242, 250, 257}, /* Norm */
 196        {0, 0, 0, 0,  83, 0, 135, 169, 193, 229, 250, 257, 264}, /* SGI */
 197        {0, 0, 0, 0,  94, 0, 177, 249, 313, 423, 512, 550, 586}, /* AGG */
 198        {0, 0, 0, 0, 104, 0, 193, 270, 338, 454, 545, 584, 620}, /* AGG+SGI */
 199};
 200
 201static s32 expected_tpt_mimo2_20MHz[4][IWL_RATE_COUNT] = {
 202        {0, 0, 0, 0,  74, 0, 123, 155, 179, 214, 236, 244, 251}, /* Norm */
 203        {0, 0, 0, 0,  81, 0, 131, 164, 188, 223, 243, 251, 257}, /* SGI */
 204        {0, 0, 0, 0,  89, 0, 167, 235, 296, 402, 488, 526, 560}, /* AGG */
 205        {0, 0, 0, 0,  97, 0, 182, 255, 320, 431, 520, 558, 593}, /* AGG+SGI*/
 206};
 207
 208static s32 expected_tpt_mimo2_40MHz[4][IWL_RATE_COUNT] = {
 209        {0, 0, 0, 0, 123, 0, 182, 214, 235, 264, 279, 285, 289}, /* Norm */
 210        {0, 0, 0, 0, 131, 0, 191, 222, 242, 270, 284, 289, 293}, /* SGI */
 211        {0, 0, 0, 0, 171, 0, 305, 410, 496, 634, 731, 771, 805}, /* AGG */
 212        {0, 0, 0, 0, 186, 0, 329, 439, 527, 667, 764, 803, 838}, /* AGG+SGI */
 213};
 214
 215static s32 expected_tpt_mimo3_20MHz[4][IWL_RATE_COUNT] = {
 216        {0, 0, 0, 0,  99, 0, 153, 186, 208, 239, 256, 263, 268}, /* Norm */
 217        {0, 0, 0, 0, 106, 0, 162, 194, 215, 246, 262, 268, 273}, /* SGI */
 218        {0, 0, 0, 0, 134, 0, 249, 346, 431, 574, 685, 732, 775}, /* AGG */
 219        {0, 0, 0, 0, 148, 0, 272, 376, 465, 614, 727, 775, 818}, /* AGG+SGI */
 220};
 221
 222static s32 expected_tpt_mimo3_40MHz[4][IWL_RATE_COUNT] = {
 223        {0, 0, 0, 0, 152, 0, 211, 239, 255, 279,  290,  294,  297}, /* Norm */
 224        {0, 0, 0, 0, 160, 0, 219, 245, 261, 284,  294,  297,  300}, /* SGI */
 225        {0, 0, 0, 0, 254, 0, 443, 584, 695, 868,  984, 1030, 1070}, /* AGG */
 226        {0, 0, 0, 0, 277, 0, 478, 624, 737, 911, 1026, 1070, 1109}, /* AGG+SGI */
 227};
 228
 229/* mbps, mcs */
 230static const struct iwl_rate_mcs_info iwl_rate_mcs[IWL_RATE_COUNT] = {
 231        {  "1", "BPSK DSSS"},
 232        {  "2", "QPSK DSSS"},
 233        {"5.5", "BPSK CCK"},
 234        { "11", "QPSK CCK"},
 235        {  "6", "BPSK 1/2"},
 236        {  "9", "BPSK 1/2"},
 237        { "12", "QPSK 1/2"},
 238        { "18", "QPSK 3/4"},
 239        { "24", "16QAM 1/2"},
 240        { "36", "16QAM 3/4"},
 241        { "48", "64QAM 2/3"},
 242        { "54", "64QAM 3/4"},
 243        { "60", "64QAM 5/6"},
 244};
 245
 246#define MCS_INDEX_PER_STREAM    (8)
 247
 248static void rs_rate_scale_clear_window(struct iwl_rate_scale_data *window)
 249{
 250        window->data = 0;
 251        window->success_counter = 0;
 252        window->success_ratio = IWL_INVALID_VALUE;
 253        window->counter = 0;
 254        window->average_tpt = IWL_INVALID_VALUE;
 255        window->stamp = 0;
 256}
 257
 258static inline u8 rs_is_valid_ant(u8 valid_antenna, u8 ant_type)
 259{
 260        return (ant_type & valid_antenna) == ant_type;
 261}
 262
 263/*
 264 *      removes the old data from the statistics. All data that is older than
 265 *      TID_MAX_TIME_DIFF, will be deleted.
 266 */
 267static void rs_tl_rm_old_stats(struct iwl_traffic_load *tl, u32 curr_time)
 268{
 269        /* The oldest age we want to keep */
 270        u32 oldest_time = curr_time - TID_MAX_TIME_DIFF;
 271
 272        while (tl->queue_count &&
 273               (tl->time_stamp < oldest_time)) {
 274                tl->total -= tl->packet_count[tl->head];
 275                tl->packet_count[tl->head] = 0;
 276                tl->time_stamp += TID_QUEUE_CELL_SPACING;
 277                tl->queue_count--;
 278                tl->head++;
 279                if (tl->head >= TID_QUEUE_MAX_SIZE)
 280                        tl->head = 0;
 281        }
 282}
 283
 284/*
 285 *      increment traffic load value for tid and also remove
 286 *      any old values if passed the certain time period
 287 */
 288static u8 rs_tl_add_packet(struct iwl_lq_sta *lq_data,
 289                           struct ieee80211_hdr *hdr)
 290{
 291        u32 curr_time = jiffies_to_msecs(jiffies);
 292        u32 time_diff;
 293        s32 index;
 294        struct iwl_traffic_load *tl = NULL;
 295        u8 tid;
 296
 297        if (ieee80211_is_data_qos(hdr->frame_control)) {
 298                u8 *qc = ieee80211_get_qos_ctl(hdr);
 299                tid = qc[0] & 0xf;
 300        } else {
 301                return IWL_MAX_TID_COUNT;
 302        }
 303
 304        if (unlikely(tid >= IWL_MAX_TID_COUNT))
 305                return IWL_MAX_TID_COUNT;
 306
 307        tl = &lq_data->load[tid];
 308
 309        curr_time -= curr_time % TID_ROUND_VALUE;
 310
 311        /* Happens only for the first packet. Initialize the data */
 312        if (!(tl->queue_count)) {
 313                tl->total = 1;
 314                tl->time_stamp = curr_time;
 315                tl->queue_count = 1;
 316                tl->head = 0;
 317                tl->packet_count[0] = 1;
 318                return IWL_MAX_TID_COUNT;
 319        }
 320
 321        time_diff = TIME_WRAP_AROUND(tl->time_stamp, curr_time);
 322        index = time_diff / TID_QUEUE_CELL_SPACING;
 323
 324        /* The history is too long: remove data that is older than */
 325        /* TID_MAX_TIME_DIFF */
 326        if (index >= TID_QUEUE_MAX_SIZE)
 327                rs_tl_rm_old_stats(tl, curr_time);
 328
 329        index = (tl->head + index) % TID_QUEUE_MAX_SIZE;
 330        tl->packet_count[index] = tl->packet_count[index] + 1;
 331        tl->total = tl->total + 1;
 332
 333        if ((index + 1) > tl->queue_count)
 334                tl->queue_count = index + 1;
 335
 336        return tid;
 337}
 338
 339#ifdef CONFIG_MAC80211_DEBUGFS
 340/**
 341 * Program the device to use fixed rate for frame transmit
 342 * This is for debugging/testing only
 343 * once the device start use fixed rate, we need to reload the module
 344 * to being back the normal operation.
 345 */
 346static void rs_program_fix_rate(struct iwl_mvm *mvm,
 347                                struct iwl_lq_sta *lq_sta)
 348{
 349        lq_sta->active_legacy_rate = 0x0FFF;    /* 1 - 54 MBits, includes CCK */
 350        lq_sta->active_siso_rate   = 0x1FD0;    /* 6 - 60 MBits, no 9, no CCK */
 351        lq_sta->active_mimo2_rate  = 0x1FD0;    /* 6 - 60 MBits, no 9, no CCK */
 352        lq_sta->active_mimo3_rate  = 0x1FD0;    /* 6 - 60 MBits, no 9, no CCK */
 353
 354        IWL_DEBUG_RATE(mvm, "sta_id %d rate 0x%X\n",
 355                       lq_sta->lq.sta_id, lq_sta->dbg_fixed_rate);
 356
 357        if (lq_sta->dbg_fixed_rate) {
 358                rs_fill_link_cmd(NULL, lq_sta, lq_sta->dbg_fixed_rate);
 359                iwl_mvm_send_lq_cmd(lq_sta->drv, &lq_sta->lq, CMD_ASYNC, false);
 360        }
 361}
 362#endif
 363
 364/*
 365        get the traffic load value for tid
 366*/
 367static u32 rs_tl_get_load(struct iwl_lq_sta *lq_data, u8 tid)
 368{
 369        u32 curr_time = jiffies_to_msecs(jiffies);
 370        u32 time_diff;
 371        s32 index;
 372        struct iwl_traffic_load *tl = NULL;
 373
 374        if (tid >= IWL_MAX_TID_COUNT)
 375                return 0;
 376
 377        tl = &(lq_data->load[tid]);
 378
 379        curr_time -= curr_time % TID_ROUND_VALUE;
 380
 381        if (!(tl->queue_count))
 382                return 0;
 383
 384        time_diff = TIME_WRAP_AROUND(tl->time_stamp, curr_time);
 385        index = time_diff / TID_QUEUE_CELL_SPACING;
 386
 387        /* The history is too long: remove data that is older than */
 388        /* TID_MAX_TIME_DIFF */
 389        if (index >= TID_QUEUE_MAX_SIZE)
 390                rs_tl_rm_old_stats(tl, curr_time);
 391
 392        return tl->total;
 393}
 394
 395static int rs_tl_turn_on_agg_for_tid(struct iwl_mvm *mvm,
 396                                      struct iwl_lq_sta *lq_data, u8 tid,
 397                                      struct ieee80211_sta *sta)
 398{
 399        int ret = -EAGAIN;
 400        u32 load;
 401
 402        load = rs_tl_get_load(lq_data, tid);
 403
 404        /*
 405         * Don't create TX aggregation sessions when in high
 406         * BT traffic, as they would just be disrupted by BT.
 407         */
 408        if (BT_MBOX_MSG(&mvm->last_bt_notif, 3, TRAFFIC_LOAD) >= 2) {
 409                IWL_DEBUG_COEX(mvm, "BT traffic (%d), no aggregation allowed\n",
 410                               BT_MBOX_MSG(&mvm->last_bt_notif,
 411                                           3, TRAFFIC_LOAD));
 412                return ret;
 413        }
 414
 415        IWL_DEBUG_HT(mvm, "Starting Tx agg: STA: %pM tid: %d\n",
 416                     sta->addr, tid);
 417        ret = ieee80211_start_tx_ba_session(sta, tid, 5000);
 418        if (ret == -EAGAIN) {
 419                /*
 420                 * driver and mac80211 is out of sync
 421                 * this might be cause by reloading firmware
 422                 * stop the tx ba session here
 423                 */
 424                IWL_ERR(mvm, "Fail start Tx agg on tid: %d\n",
 425                        tid);
 426                ieee80211_stop_tx_ba_session(sta, tid);
 427        }
 428        return ret;
 429}
 430
 431static void rs_tl_turn_on_agg(struct iwl_mvm *mvm, u8 tid,
 432                              struct iwl_lq_sta *lq_data,
 433                              struct ieee80211_sta *sta)
 434{
 435        if (tid < IWL_MAX_TID_COUNT)
 436                rs_tl_turn_on_agg_for_tid(mvm, lq_data, tid, sta);
 437        else
 438                IWL_ERR(mvm, "tid exceeds max TID count: %d/%d\n",
 439                        tid, IWL_MAX_TID_COUNT);
 440}
 441
 442static inline int get_num_of_ant_from_rate(u32 rate_n_flags)
 443{
 444        return !!(rate_n_flags & RATE_MCS_ANT_A_MSK) +
 445               !!(rate_n_flags & RATE_MCS_ANT_B_MSK) +
 446               !!(rate_n_flags & RATE_MCS_ANT_C_MSK);
 447}
 448
 449/*
 450 * Static function to get the expected throughput from an iwl_scale_tbl_info
 451 * that wraps a NULL pointer check
 452 */
 453static s32 get_expected_tpt(struct iwl_scale_tbl_info *tbl, int rs_index)
 454{
 455        if (tbl->expected_tpt)
 456                return tbl->expected_tpt[rs_index];
 457        return 0;
 458}
 459
 460/**
 461 * rs_collect_tx_data - Update the success/failure sliding window
 462 *
 463 * We keep a sliding window of the last 62 packets transmitted
 464 * at this rate.  window->data contains the bitmask of successful
 465 * packets.
 466 */
 467static int rs_collect_tx_data(struct iwl_scale_tbl_info *tbl,
 468                              int scale_index, int attempts, int successes)
 469{
 470        struct iwl_rate_scale_data *window = NULL;
 471        static const u64 mask = (((u64)1) << (IWL_RATE_MAX_WINDOW - 1));
 472        s32 fail_count, tpt;
 473
 474        if (scale_index < 0 || scale_index >= IWL_RATE_COUNT)
 475                return -EINVAL;
 476
 477        /* Select window for current tx bit rate */
 478        window = &(tbl->win[scale_index]);
 479
 480        /* Get expected throughput */
 481        tpt = get_expected_tpt(tbl, scale_index);
 482
 483        /*
 484         * Keep track of only the latest 62 tx frame attempts in this rate's
 485         * history window; anything older isn't really relevant any more.
 486         * If we have filled up the sliding window, drop the oldest attempt;
 487         * if the oldest attempt (highest bit in bitmap) shows "success",
 488         * subtract "1" from the success counter (this is the main reason
 489         * we keep these bitmaps!).
 490         */
 491        while (attempts > 0) {
 492                if (window->counter >= IWL_RATE_MAX_WINDOW) {
 493                        /* remove earliest */
 494                        window->counter = IWL_RATE_MAX_WINDOW - 1;
 495
 496                        if (window->data & mask) {
 497                                window->data &= ~mask;
 498                                window->success_counter--;
 499                        }
 500                }
 501
 502                /* Increment frames-attempted counter */
 503                window->counter++;
 504
 505                /* Shift bitmap by one frame to throw away oldest history */
 506                window->data <<= 1;
 507
 508                /* Mark the most recent #successes attempts as successful */
 509                if (successes > 0) {
 510                        window->success_counter++;
 511                        window->data |= 0x1;
 512                        successes--;
 513                }
 514
 515                attempts--;
 516        }
 517
 518        /* Calculate current success ratio, avoid divide-by-0! */
 519        if (window->counter > 0)
 520                window->success_ratio = 128 * (100 * window->success_counter)
 521                                        / window->counter;
 522        else
 523                window->success_ratio = IWL_INVALID_VALUE;
 524
 525        fail_count = window->counter - window->success_counter;
 526
 527        /* Calculate average throughput, if we have enough history. */
 528        if ((fail_count >= IWL_RATE_MIN_FAILURE_TH) ||
 529            (window->success_counter >= IWL_RATE_MIN_SUCCESS_TH))
 530                window->average_tpt = (window->success_ratio * tpt + 64) / 128;
 531        else
 532                window->average_tpt = IWL_INVALID_VALUE;
 533
 534        /* Tag this window as having been updated */
 535        window->stamp = jiffies;
 536
 537        return 0;
 538}
 539
 540/*
 541 * Fill uCode API rate_n_flags field, based on "search" or "active" table.
 542 */
 543/* FIXME:RS:remove this function and put the flags statically in the table */
 544static u32 rate_n_flags_from_tbl(struct iwl_mvm *mvm,
 545                                 struct iwl_scale_tbl_info *tbl,
 546                                 int index, u8 use_green)
 547{
 548        u32 rate_n_flags = 0;
 549
 550        if (is_legacy(tbl->lq_type)) {
 551                rate_n_flags = iwl_rates[index].plcp;
 552                if (index >= IWL_FIRST_CCK_RATE && index <= IWL_LAST_CCK_RATE)
 553                        rate_n_flags |= RATE_MCS_CCK_MSK;
 554        } else if (is_Ht(tbl->lq_type)) {
 555                if (index > IWL_LAST_OFDM_RATE) {
 556                        IWL_ERR(mvm, "Invalid HT rate index %d\n", index);
 557                        index = IWL_LAST_OFDM_RATE;
 558                }
 559                rate_n_flags = RATE_MCS_HT_MSK;
 560
 561                if (is_siso(tbl->lq_type))
 562                        rate_n_flags |= iwl_rates[index].plcp_siso;
 563                else if (is_mimo2(tbl->lq_type))
 564                        rate_n_flags |= iwl_rates[index].plcp_mimo2;
 565                else
 566                        rate_n_flags |= iwl_rates[index].plcp_mimo3;
 567        } else {
 568                IWL_ERR(mvm, "Invalid tbl->lq_type %d\n", tbl->lq_type);
 569        }
 570
 571        rate_n_flags |= ((tbl->ant_type << RATE_MCS_ANT_POS) &
 572                                                     RATE_MCS_ANT_ABC_MSK);
 573
 574        if (is_Ht(tbl->lq_type)) {
 575                if (tbl->is_ht40)
 576                        rate_n_flags |= RATE_MCS_CHAN_WIDTH_40;
 577                if (tbl->is_SGI)
 578                        rate_n_flags |= RATE_MCS_SGI_MSK;
 579
 580                if (use_green) {
 581                        rate_n_flags |= RATE_HT_MCS_GF_MSK;
 582                        if (is_siso(tbl->lq_type) && tbl->is_SGI) {
 583                                rate_n_flags &= ~RATE_MCS_SGI_MSK;
 584                                IWL_ERR(mvm, "GF was set with SGI:SISO\n");
 585                        }
 586                }
 587        }
 588        return rate_n_flags;
 589}
 590
 591/*
 592 * Interpret uCode API's rate_n_flags format,
 593 * fill "search" or "active" tx mode table.
 594 */
 595static int rs_get_tbl_info_from_mcs(const u32 rate_n_flags,
 596                                    enum ieee80211_band band,
 597                                    struct iwl_scale_tbl_info *tbl,
 598                                    int *rate_idx)
 599{
 600        u32 ant_msk = (rate_n_flags & RATE_MCS_ANT_ABC_MSK);
 601        u8 num_of_ant = get_num_of_ant_from_rate(rate_n_flags);
 602        u8 mcs;
 603
 604        memset(tbl, 0, sizeof(struct iwl_scale_tbl_info));
 605        *rate_idx = iwl_hwrate_to_plcp_idx(rate_n_flags);
 606
 607        if (*rate_idx  == IWL_RATE_INVALID) {
 608                *rate_idx = -1;
 609                return -EINVAL;
 610        }
 611        tbl->is_SGI = 0;        /* default legacy setup */
 612        tbl->is_ht40 = 0;
 613        tbl->ant_type = (ant_msk >> RATE_MCS_ANT_POS);
 614        tbl->lq_type = LQ_NONE;
 615        tbl->max_search = IWL_MAX_SEARCH;
 616
 617        /* legacy rate format */
 618        if (!(rate_n_flags & RATE_MCS_HT_MSK)) {
 619                if (num_of_ant == 1) {
 620                        if (band == IEEE80211_BAND_5GHZ)
 621                                tbl->lq_type = LQ_A;
 622                        else
 623                                tbl->lq_type = LQ_G;
 624                }
 625        /* HT rate format */
 626        } else {
 627                if (rate_n_flags & RATE_MCS_SGI_MSK)
 628                        tbl->is_SGI = 1;
 629
 630                if (rate_n_flags & RATE_MCS_CHAN_WIDTH_40) /* TODO */
 631                        tbl->is_ht40 = 1;
 632
 633                mcs = rs_extract_rate(rate_n_flags);
 634
 635                /* SISO */
 636                if (mcs <= IWL_RATE_SISO_60M_PLCP) {
 637                        if (num_of_ant == 1)
 638                                tbl->lq_type = LQ_SISO; /*else NONE*/
 639                /* MIMO2 */
 640                } else if (mcs <= IWL_RATE_MIMO2_60M_PLCP) {
 641                        if (num_of_ant == 2)
 642                                tbl->lq_type = LQ_MIMO2;
 643                /* MIMO3 */
 644                } else {
 645                        if (num_of_ant == 3) {
 646                                tbl->max_search = IWL_MAX_11N_MIMO3_SEARCH;
 647                                tbl->lq_type = LQ_MIMO3;
 648                        }
 649                }
 650        }
 651        return 0;
 652}
 653
 654/* switch to another antenna/antennas and return 1 */
 655/* if no other valid antenna found, return 0 */
 656static int rs_toggle_antenna(u32 valid_ant, u32 *rate_n_flags,
 657                             struct iwl_scale_tbl_info *tbl)
 658{
 659        u8 new_ant_type;
 660
 661        if (!tbl->ant_type || tbl->ant_type > ANT_ABC)
 662                return 0;
 663
 664        if (!rs_is_valid_ant(valid_ant, tbl->ant_type))
 665                return 0;
 666
 667        new_ant_type = ant_toggle_lookup[tbl->ant_type];
 668
 669        while ((new_ant_type != tbl->ant_type) &&
 670               !rs_is_valid_ant(valid_ant, new_ant_type))
 671                new_ant_type = ant_toggle_lookup[new_ant_type];
 672
 673        if (new_ant_type == tbl->ant_type)
 674                return 0;
 675
 676        tbl->ant_type = new_ant_type;
 677        *rate_n_flags &= ~RATE_MCS_ANT_ABC_MSK;
 678        *rate_n_flags |= new_ant_type << RATE_MCS_ANT_POS;
 679        return 1;
 680}
 681
 682/**
 683 * Green-field mode is valid if the station supports it and
 684 * there are no non-GF stations present in the BSS.
 685 */
 686static bool rs_use_green(struct ieee80211_sta *sta)
 687{
 688        /*
 689         * There's a bug somewhere in this code that causes the
 690         * scaling to get stuck because GF+SGI can't be combined
 691         * in SISO rates. Until we find that bug, disable GF, it
 692         * has only limited benefit and we still interoperate with
 693         * GF APs since we can always receive GF transmissions.
 694         */
 695        return false;
 696}
 697
 698/**
 699 * rs_get_supported_rates - get the available rates
 700 *
 701 * if management frame or broadcast frame only return
 702 * basic available rates.
 703 *
 704 */
 705static u16 rs_get_supported_rates(struct iwl_lq_sta *lq_sta,
 706                                  struct ieee80211_hdr *hdr,
 707                                  enum iwl_table_type rate_type)
 708{
 709        if (is_legacy(rate_type)) {
 710                return lq_sta->active_legacy_rate;
 711        } else {
 712                if (is_siso(rate_type))
 713                        return lq_sta->active_siso_rate;
 714                else if (is_mimo2(rate_type))
 715                        return lq_sta->active_mimo2_rate;
 716                else
 717                        return lq_sta->active_mimo3_rate;
 718        }
 719}
 720
 721static u16 rs_get_adjacent_rate(struct iwl_mvm *mvm, u8 index, u16 rate_mask,
 722                                int rate_type)
 723{
 724        u8 high = IWL_RATE_INVALID;
 725        u8 low = IWL_RATE_INVALID;
 726
 727        /* 802.11A or ht walks to the next literal adjacent rate in
 728         * the rate table */
 729        if (is_a_band(rate_type) || !is_legacy(rate_type)) {
 730                int i;
 731                u32 mask;
 732
 733                /* Find the previous rate that is in the rate mask */
 734                i = index - 1;
 735                for (mask = (1 << i); i >= 0; i--, mask >>= 1) {
 736                        if (rate_mask & mask) {
 737                                low = i;
 738                                break;
 739                        }
 740                }
 741
 742                /* Find the next rate that is in the rate mask */
 743                i = index + 1;
 744                for (mask = (1 << i); i < IWL_RATE_COUNT; i++, mask <<= 1) {
 745                        if (rate_mask & mask) {
 746                                high = i;
 747                                break;
 748                        }
 749                }
 750
 751                return (high << 8) | low;
 752        }
 753
 754        low = index;
 755        while (low != IWL_RATE_INVALID) {
 756                low = iwl_rates[low].prev_rs;
 757                if (low == IWL_RATE_INVALID)
 758                        break;
 759                if (rate_mask & (1 << low))
 760                        break;
 761                IWL_DEBUG_RATE(mvm, "Skipping masked lower rate: %d\n", low);
 762        }
 763
 764        high = index;
 765        while (high != IWL_RATE_INVALID) {
 766                high = iwl_rates[high].next_rs;
 767                if (high == IWL_RATE_INVALID)
 768                        break;
 769                if (rate_mask & (1 << high))
 770                        break;
 771                IWL_DEBUG_RATE(mvm, "Skipping masked higher rate: %d\n", high);
 772        }
 773
 774        return (high << 8) | low;
 775}
 776
 777static u32 rs_get_lower_rate(struct iwl_lq_sta *lq_sta,
 778                             struct iwl_scale_tbl_info *tbl,
 779                             u8 scale_index, u8 ht_possible)
 780{
 781        s32 low;
 782        u16 rate_mask;
 783        u16 high_low;
 784        u8 switch_to_legacy = 0;
 785        u8 is_green = lq_sta->is_green;
 786        struct iwl_mvm *mvm = lq_sta->drv;
 787
 788        /* check if we need to switch from HT to legacy rates.
 789         * assumption is that mandatory rates (1Mbps or 6Mbps)
 790         * are always supported (spec demand) */
 791        if (!is_legacy(tbl->lq_type) && (!ht_possible || !scale_index)) {
 792                switch_to_legacy = 1;
 793                scale_index = rs_ht_to_legacy[scale_index];
 794                if (lq_sta->band == IEEE80211_BAND_5GHZ)
 795                        tbl->lq_type = LQ_A;
 796                else
 797                        tbl->lq_type = LQ_G;
 798
 799                if (num_of_ant(tbl->ant_type) > 1)
 800                        tbl->ant_type =
 801                            first_antenna(iwl_fw_valid_tx_ant(mvm->fw));
 802
 803                tbl->is_ht40 = 0;
 804                tbl->is_SGI = 0;
 805                tbl->max_search = IWL_MAX_SEARCH;
 806        }
 807
 808        rate_mask = rs_get_supported_rates(lq_sta, NULL, tbl->lq_type);
 809
 810        /* Mask with station rate restriction */
 811        if (is_legacy(tbl->lq_type)) {
 812                /* supp_rates has no CCK bits in A mode */
 813                if (lq_sta->band == IEEE80211_BAND_5GHZ)
 814                        rate_mask  = (u16)(rate_mask &
 815                           (lq_sta->supp_rates << IWL_FIRST_OFDM_RATE));
 816                else
 817                        rate_mask = (u16)(rate_mask & lq_sta->supp_rates);
 818        }
 819
 820        /* If we switched from HT to legacy, check current rate */
 821        if (switch_to_legacy && (rate_mask & (1 << scale_index))) {
 822                low = scale_index;
 823                goto out;
 824        }
 825
 826        high_low = rs_get_adjacent_rate(lq_sta->drv, scale_index, rate_mask,
 827                                        tbl->lq_type);
 828        low = high_low & 0xff;
 829
 830        if (low == IWL_RATE_INVALID)
 831                low = scale_index;
 832
 833out:
 834        return rate_n_flags_from_tbl(lq_sta->drv, tbl, low, is_green);
 835}
 836
 837/*
 838 * Simple function to compare two rate scale table types
 839 */
 840static bool table_type_matches(struct iwl_scale_tbl_info *a,
 841                               struct iwl_scale_tbl_info *b)
 842{
 843        return (a->lq_type == b->lq_type) && (a->ant_type == b->ant_type) &&
 844                (a->is_SGI == b->is_SGI);
 845}
 846
 847/*
 848 * mac80211 sends us Tx status
 849 */
 850static void rs_tx_status(void *mvm_r, struct ieee80211_supported_band *sband,
 851                         struct ieee80211_sta *sta, void *priv_sta,
 852                         struct sk_buff *skb)
 853{
 854        int legacy_success;
 855        int retries;
 856        int rs_index, mac_index, i;
 857        struct iwl_lq_sta *lq_sta = priv_sta;
 858        struct iwl_lq_cmd *table;
 859        struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
 860        struct iwl_op_mode *op_mode = (struct iwl_op_mode *)mvm_r;
 861        struct iwl_mvm *mvm = IWL_OP_MODE_GET_MVM(op_mode);
 862        struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
 863        enum mac80211_rate_control_flags mac_flags;
 864        u32 tx_rate;
 865        struct iwl_scale_tbl_info tbl_type;
 866        struct iwl_scale_tbl_info *curr_tbl, *other_tbl, *tmp_tbl;
 867
 868        IWL_DEBUG_RATE_LIMIT(mvm,
 869                             "get frame ack response, update rate scale window\n");
 870
 871        /* Treat uninitialized rate scaling data same as non-existing. */
 872        if (!lq_sta) {
 873                IWL_DEBUG_RATE(mvm, "Station rate scaling not created yet.\n");
 874                return;
 875        } else if (!lq_sta->drv) {
 876                IWL_DEBUG_RATE(mvm, "Rate scaling not initialized yet.\n");
 877                return;
 878        }
 879
 880        if (!ieee80211_is_data(hdr->frame_control) ||
 881            info->flags & IEEE80211_TX_CTL_NO_ACK)
 882                return;
 883
 884        /* This packet was aggregated but doesn't carry status info */
 885        if ((info->flags & IEEE80211_TX_CTL_AMPDU) &&
 886            !(info->flags & IEEE80211_TX_STAT_AMPDU))
 887                return;
 888
 889        /*
 890         * Ignore this Tx frame response if its initial rate doesn't match
 891         * that of latest Link Quality command.  There may be stragglers
 892         * from a previous Link Quality command, but we're no longer interested
 893         * in those; they're either from the "active" mode while we're trying
 894         * to check "search" mode, or a prior "search" mode after we've moved
 895         * to a new "search" mode (which might become the new "active" mode).
 896         */
 897        table = &lq_sta->lq;
 898        tx_rate = le32_to_cpu(table->rs_table[0]);
 899        rs_get_tbl_info_from_mcs(tx_rate, info->band, &tbl_type, &rs_index);
 900        if (info->band == IEEE80211_BAND_5GHZ)
 901                rs_index -= IWL_FIRST_OFDM_RATE;
 902        mac_flags = info->status.rates[0].flags;
 903        mac_index = info->status.rates[0].idx;
 904        /* For HT packets, map MCS to PLCP */
 905        if (mac_flags & IEEE80211_TX_RC_MCS) {
 906                /* Remove # of streams */
 907                mac_index &= RATE_HT_MCS_RATE_CODE_MSK;
 908                if (mac_index >= (IWL_RATE_9M_INDEX - IWL_FIRST_OFDM_RATE))
 909                        mac_index++;
 910                /*
 911                 * mac80211 HT index is always zero-indexed; we need to move
 912                 * HT OFDM rates after CCK rates in 2.4 GHz band
 913                 */
 914                if (info->band == IEEE80211_BAND_2GHZ)
 915                        mac_index += IWL_FIRST_OFDM_RATE;
 916        }
 917        /* Here we actually compare this rate to the latest LQ command */
 918        if ((mac_index < 0) ||
 919            (tbl_type.is_SGI != !!(mac_flags & IEEE80211_TX_RC_SHORT_GI)) ||
 920            (tbl_type.is_ht40 != !!(mac_flags & IEEE80211_TX_RC_40_MHZ_WIDTH)) ||
 921            (tbl_type.ant_type != info->status.antenna) ||
 922            (!!(tx_rate & RATE_MCS_HT_MSK) !=
 923                                !!(mac_flags & IEEE80211_TX_RC_MCS)) ||
 924            (!!(tx_rate & RATE_HT_MCS_GF_MSK) !=
 925                                !!(mac_flags & IEEE80211_TX_RC_GREEN_FIELD)) ||
 926            (rs_index != mac_index)) {
 927                IWL_DEBUG_RATE(mvm,
 928                               "initial rate %d does not match %d (0x%x)\n",
 929                               mac_index, rs_index, tx_rate);
 930                /*
 931                 * Since rates mis-match, the last LQ command may have failed.
 932                 * After IWL_MISSED_RATE_MAX mis-matches, resync the uCode with
 933                 * ... driver.
 934                 */
 935                lq_sta->missed_rate_counter++;
 936                if (lq_sta->missed_rate_counter > IWL_MISSED_RATE_MAX) {
 937                        lq_sta->missed_rate_counter = 0;
 938                        iwl_mvm_send_lq_cmd(mvm, &lq_sta->lq, CMD_ASYNC, false);
 939                }
 940                /* Regardless, ignore this status info for outdated rate */
 941                return;
 942        } else
 943                /* Rate did match, so reset the missed_rate_counter */
 944                lq_sta->missed_rate_counter = 0;
 945
 946        /* Figure out if rate scale algorithm is in active or search table */
 947        if (table_type_matches(&tbl_type,
 948                               &(lq_sta->lq_info[lq_sta->active_tbl]))) {
 949                curr_tbl = &(lq_sta->lq_info[lq_sta->active_tbl]);
 950                other_tbl = &(lq_sta->lq_info[1 - lq_sta->active_tbl]);
 951        } else if (table_type_matches(
 952                        &tbl_type, &lq_sta->lq_info[1 - lq_sta->active_tbl])) {
 953                curr_tbl = &(lq_sta->lq_info[1 - lq_sta->active_tbl]);
 954                other_tbl = &(lq_sta->lq_info[lq_sta->active_tbl]);
 955        } else {
 956                IWL_DEBUG_RATE(mvm,
 957                               "Neither active nor search matches tx rate\n");
 958                tmp_tbl = &(lq_sta->lq_info[lq_sta->active_tbl]);
 959                IWL_DEBUG_RATE(mvm, "active- lq:%x, ant:%x, SGI:%d\n",
 960                               tmp_tbl->lq_type, tmp_tbl->ant_type,
 961                               tmp_tbl->is_SGI);
 962                tmp_tbl = &(lq_sta->lq_info[1 - lq_sta->active_tbl]);
 963                IWL_DEBUG_RATE(mvm, "search- lq:%x, ant:%x, SGI:%d\n",
 964                               tmp_tbl->lq_type, tmp_tbl->ant_type,
 965                               tmp_tbl->is_SGI);
 966                IWL_DEBUG_RATE(mvm, "actual- lq:%x, ant:%x, SGI:%d\n",
 967                               tbl_type.lq_type, tbl_type.ant_type,
 968                               tbl_type.is_SGI);
 969                /*
 970                 * no matching table found, let's by-pass the data collection
 971                 * and continue to perform rate scale to find the rate table
 972                 */
 973                rs_stay_in_table(lq_sta, true);
 974                goto done;
 975        }
 976
 977        /*
 978         * Updating the frame history depends on whether packets were
 979         * aggregated.
 980         *
 981         * For aggregation, all packets were transmitted at the same rate, the
 982         * first index into rate scale table.
 983         */
 984        if (info->flags & IEEE80211_TX_STAT_AMPDU) {
 985                tx_rate = le32_to_cpu(table->rs_table[0]);
 986                rs_get_tbl_info_from_mcs(tx_rate, info->band, &tbl_type,
 987                                         &rs_index);
 988                rs_collect_tx_data(curr_tbl, rs_index,
 989                                   info->status.ampdu_len,
 990                                   info->status.ampdu_ack_len);
 991
 992                /* Update success/fail counts if not searching for new mode */
 993                if (lq_sta->stay_in_tbl) {
 994                        lq_sta->total_success += info->status.ampdu_ack_len;
 995                        lq_sta->total_failed += (info->status.ampdu_len -
 996                                        info->status.ampdu_ack_len);
 997                }
 998        } else {
 999        /*
1000         * For legacy, update frame history with for each Tx retry.
1001         */
1002                retries = info->status.rates[0].count - 1;
1003                /* HW doesn't send more than 15 retries */
1004                retries = min(retries, 15);
1005
1006                /* The last transmission may have been successful */
1007                legacy_success = !!(info->flags & IEEE80211_TX_STAT_ACK);
1008                /* Collect data for each rate used during failed TX attempts */
1009                for (i = 0; i <= retries; ++i) {
1010                        tx_rate = le32_to_cpu(table->rs_table[i]);
1011                        rs_get_tbl_info_from_mcs(tx_rate, info->band,
1012                                                 &tbl_type, &rs_index);
1013                        /*
1014                         * Only collect stats if retried rate is in the same RS
1015                         * table as active/search.
1016                         */
1017                        if (table_type_matches(&tbl_type, curr_tbl))
1018                                tmp_tbl = curr_tbl;
1019                        else if (table_type_matches(&tbl_type, other_tbl))
1020                                tmp_tbl = other_tbl;
1021                        else
1022                                continue;
1023                        rs_collect_tx_data(tmp_tbl, rs_index, 1,
1024                                           i < retries ? 0 : legacy_success);
1025                }
1026
1027                /* Update success/fail counts if not searching for new mode */
1028                if (lq_sta->stay_in_tbl) {
1029                        lq_sta->total_success += legacy_success;
1030                        lq_sta->total_failed += retries + (1 - legacy_success);
1031                }
1032        }
1033        /* The last TX rate is cached in lq_sta; it's set in if/else above */
1034        lq_sta->last_rate_n_flags = tx_rate;
1035done:
1036        /* See if there's a better rate or modulation mode to try. */
1037        if (sta && sta->supp_rates[sband->band])
1038                rs_rate_scale_perform(mvm, skb, sta, lq_sta);
1039}
1040
1041/*
1042 * Begin a period of staying with a selected modulation mode.
1043 * Set "stay_in_tbl" flag to prevent any mode switches.
1044 * Set frame tx success limits according to legacy vs. high-throughput,
1045 * and reset overall (spanning all rates) tx success history statistics.
1046 * These control how long we stay using same modulation mode before
1047 * searching for a new mode.
1048 */
1049static void rs_set_stay_in_table(struct iwl_mvm *mvm, u8 is_legacy,
1050                                 struct iwl_lq_sta *lq_sta)
1051{
1052        IWL_DEBUG_RATE(mvm, "we are staying in the same table\n");
1053        lq_sta->stay_in_tbl = 1;        /* only place this gets set */
1054        if (is_legacy) {
1055                lq_sta->table_count_limit = IWL_LEGACY_TABLE_COUNT;
1056                lq_sta->max_failure_limit = IWL_LEGACY_FAILURE_LIMIT;
1057                lq_sta->max_success_limit = IWL_LEGACY_SUCCESS_LIMIT;
1058        } else {
1059                lq_sta->table_count_limit = IWL_NONE_LEGACY_TABLE_COUNT;
1060                lq_sta->max_failure_limit = IWL_NONE_LEGACY_FAILURE_LIMIT;
1061                lq_sta->max_success_limit = IWL_NONE_LEGACY_SUCCESS_LIMIT;
1062        }
1063        lq_sta->table_count = 0;
1064        lq_sta->total_failed = 0;
1065        lq_sta->total_success = 0;
1066        lq_sta->flush_timer = jiffies;
1067        lq_sta->action_counter = 0;
1068}
1069
1070/*
1071 * Find correct throughput table for given mode of modulation
1072 */
1073static void rs_set_expected_tpt_table(struct iwl_lq_sta *lq_sta,
1074                                      struct iwl_scale_tbl_info *tbl)
1075{
1076        /* Used to choose among HT tables */
1077        s32 (*ht_tbl_pointer)[IWL_RATE_COUNT];
1078
1079        /* Check for invalid LQ type */
1080        if (WARN_ON_ONCE(!is_legacy(tbl->lq_type) && !is_Ht(tbl->lq_type))) {
1081                tbl->expected_tpt = expected_tpt_legacy;
1082                return;
1083        }
1084
1085        /* Legacy rates have only one table */
1086        if (is_legacy(tbl->lq_type)) {
1087                tbl->expected_tpt = expected_tpt_legacy;
1088                return;
1089        }
1090
1091        /* Choose among many HT tables depending on number of streams
1092         * (SISO/MIMO2/MIMO3), channel width (20/40), SGI, and aggregation
1093         * status */
1094        if (is_siso(tbl->lq_type) && !tbl->is_ht40)
1095                ht_tbl_pointer = expected_tpt_siso20MHz;
1096        else if (is_siso(tbl->lq_type))
1097                ht_tbl_pointer = expected_tpt_siso40MHz;
1098        else if (is_mimo2(tbl->lq_type) && !tbl->is_ht40)
1099                ht_tbl_pointer = expected_tpt_mimo2_20MHz;
1100        else if (is_mimo2(tbl->lq_type))
1101                ht_tbl_pointer = expected_tpt_mimo2_40MHz;
1102        else if (is_mimo3(tbl->lq_type) && !tbl->is_ht40)
1103                ht_tbl_pointer = expected_tpt_mimo3_20MHz;
1104        else /* if (is_mimo3(tbl->lq_type)) <-- must be true */
1105                ht_tbl_pointer = expected_tpt_mimo3_40MHz;
1106
1107        if (!tbl->is_SGI && !lq_sta->is_agg)            /* Normal */
1108                tbl->expected_tpt = ht_tbl_pointer[0];
1109        else if (tbl->is_SGI && !lq_sta->is_agg)        /* SGI */
1110                tbl->expected_tpt = ht_tbl_pointer[1];
1111        else if (!tbl->is_SGI && lq_sta->is_agg)        /* AGG */
1112                tbl->expected_tpt = ht_tbl_pointer[2];
1113        else                                            /* AGG+SGI */
1114                tbl->expected_tpt = ht_tbl_pointer[3];
1115}
1116
1117/*
1118 * Find starting rate for new "search" high-throughput mode of modulation.
1119 * Goal is to find lowest expected rate (under perfect conditions) that is
1120 * above the current measured throughput of "active" mode, to give new mode
1121 * a fair chance to prove itself without too many challenges.
1122 *
1123 * This gets called when transitioning to more aggressive modulation
1124 * (i.e. legacy to SISO or MIMO, or SISO to MIMO), as well as less aggressive
1125 * (i.e. MIMO to SISO).  When moving to MIMO, bit rate will typically need
1126 * to decrease to match "active" throughput.  When moving from MIMO to SISO,
1127 * bit rate will typically need to increase, but not if performance was bad.
1128 */
1129static s32 rs_get_best_rate(struct iwl_mvm *mvm,
1130                            struct iwl_lq_sta *lq_sta,
1131                            struct iwl_scale_tbl_info *tbl,     /* "search" */
1132                            u16 rate_mask, s8 index)
1133{
1134        /* "active" values */
1135        struct iwl_scale_tbl_info *active_tbl =
1136            &(lq_sta->lq_info[lq_sta->active_tbl]);
1137        s32 active_sr = active_tbl->win[index].success_ratio;
1138        s32 active_tpt = active_tbl->expected_tpt[index];
1139
1140        /* expected "search" throughput */
1141        s32 *tpt_tbl = tbl->expected_tpt;
1142
1143        s32 new_rate, high, low, start_hi;
1144        u16 high_low;
1145        s8 rate = index;
1146
1147        new_rate = high = low = start_hi = IWL_RATE_INVALID;
1148
1149        while (1) {
1150                high_low = rs_get_adjacent_rate(mvm, rate, rate_mask,
1151                                                tbl->lq_type);
1152
1153                low = high_low & 0xff;
1154                high = (high_low >> 8) & 0xff;
1155
1156                /*
1157                 * Lower the "search" bit rate, to give new "search" mode
1158                 * approximately the same throughput as "active" if:
1159                 *
1160                 * 1) "Active" mode has been working modestly well (but not
1161                 *    great), and expected "search" throughput (under perfect
1162                 *    conditions) at candidate rate is above the actual
1163                 *    measured "active" throughput (but less than expected
1164                 *    "active" throughput under perfect conditions).
1165                 * OR
1166                 * 2) "Active" mode has been working perfectly or very well
1167                 *    and expected "search" throughput (under perfect
1168                 *    conditions) at candidate rate is above expected
1169                 *    "active" throughput (under perfect conditions).
1170                 */
1171                if ((((100 * tpt_tbl[rate]) > lq_sta->last_tpt) &&
1172                     ((active_sr > IWL_RATE_DECREASE_TH) &&
1173                      (active_sr <= IWL_RATE_HIGH_TH) &&
1174                      (tpt_tbl[rate] <= active_tpt))) ||
1175                    ((active_sr >= IWL_RATE_SCALE_SWITCH) &&
1176                     (tpt_tbl[rate] > active_tpt))) {
1177                        /* (2nd or later pass)
1178                         * If we've already tried to raise the rate, and are
1179                         * now trying to lower it, use the higher rate. */
1180                        if (start_hi != IWL_RATE_INVALID) {
1181                                new_rate = start_hi;
1182                                break;
1183                        }
1184
1185                        new_rate = rate;
1186
1187                        /* Loop again with lower rate */
1188                        if (low != IWL_RATE_INVALID)
1189                                rate = low;
1190
1191                        /* Lower rate not available, use the original */
1192                        else
1193                                break;
1194
1195                /* Else try to raise the "search" rate to match "active" */
1196                } else {
1197                        /* (2nd or later pass)
1198                         * If we've already tried to lower the rate, and are
1199                         * now trying to raise it, use the lower rate. */
1200                        if (new_rate != IWL_RATE_INVALID)
1201                                break;
1202
1203                        /* Loop again with higher rate */
1204                        else if (high != IWL_RATE_INVALID) {
1205                                start_hi = high;
1206                                rate = high;
1207
1208                        /* Higher rate not available, use the original */
1209                        } else {
1210                                new_rate = rate;
1211                                break;
1212                        }
1213                }
1214        }
1215
1216        return new_rate;
1217}
1218
1219static bool iwl_is_ht40_tx_allowed(struct ieee80211_sta *sta)
1220{
1221        return sta->bandwidth >= IEEE80211_STA_RX_BW_40;
1222}
1223
1224/*
1225 * Set up search table for MIMO2
1226 */
1227static int rs_switch_to_mimo2(struct iwl_mvm *mvm,
1228                             struct iwl_lq_sta *lq_sta,
1229                             struct ieee80211_sta *sta,
1230                             struct iwl_scale_tbl_info *tbl, int index)
1231{
1232        u16 rate_mask;
1233        s32 rate;
1234        s8 is_green = lq_sta->is_green;
1235
1236        if (!sta->ht_cap.ht_supported)
1237                return -1;
1238
1239        if (sta->smps_mode == IEEE80211_SMPS_STATIC)
1240                return -1;
1241
1242        /* Need both Tx chains/antennas to support MIMO */
1243        if (num_of_ant(iwl_fw_valid_tx_ant(mvm->fw)) < 2)
1244                return -1;
1245
1246        IWL_DEBUG_RATE(mvm, "LQ: try to switch to MIMO2\n");
1247
1248        tbl->lq_type = LQ_MIMO2;
1249        tbl->action = 0;
1250        tbl->max_search = IWL_MAX_SEARCH;
1251        rate_mask = lq_sta->active_mimo2_rate;
1252
1253        if (iwl_is_ht40_tx_allowed(sta))
1254                tbl->is_ht40 = 1;
1255        else
1256                tbl->is_ht40 = 0;
1257
1258        rs_set_expected_tpt_table(lq_sta, tbl);
1259
1260        rate = rs_get_best_rate(mvm, lq_sta, tbl, rate_mask, index);
1261
1262        IWL_DEBUG_RATE(mvm, "LQ: MIMO2 best rate %d mask %X\n",
1263                       rate, rate_mask);
1264        if ((rate == IWL_RATE_INVALID) || !((1 << rate) & rate_mask)) {
1265                IWL_DEBUG_RATE(mvm, "Can't switch with index %d rate mask %x\n",
1266                               rate, rate_mask);
1267                return -1;
1268        }
1269        tbl->current_rate = rate_n_flags_from_tbl(mvm, tbl, rate, is_green);
1270
1271        IWL_DEBUG_RATE(mvm, "LQ: Switch to new mcs %X index is green %X\n",
1272                       tbl->current_rate, is_green);
1273        return 0;
1274}
1275
1276/*
1277 * Set up search table for MIMO3
1278 */
1279static int rs_switch_to_mimo3(struct iwl_mvm *mvm,
1280                             struct iwl_lq_sta *lq_sta,
1281                             struct ieee80211_sta *sta,
1282                             struct iwl_scale_tbl_info *tbl, int index)
1283{
1284        u16 rate_mask;
1285        s32 rate;
1286        s8 is_green = lq_sta->is_green;
1287
1288        if (!sta->ht_cap.ht_supported)
1289                return -1;
1290
1291        if (sta->smps_mode == IEEE80211_SMPS_STATIC)
1292                return -1;
1293
1294        /* Need both Tx chains/antennas to support MIMO */
1295        if (num_of_ant(iwl_fw_valid_tx_ant(mvm->fw)) < 3)
1296                return -1;
1297
1298        IWL_DEBUG_RATE(mvm, "LQ: try to switch to MIMO3\n");
1299
1300        tbl->lq_type = LQ_MIMO3;
1301        tbl->action = 0;
1302        tbl->max_search = IWL_MAX_11N_MIMO3_SEARCH;
1303        rate_mask = lq_sta->active_mimo3_rate;
1304
1305        if (iwl_is_ht40_tx_allowed(sta))
1306                tbl->is_ht40 = 1;
1307        else
1308                tbl->is_ht40 = 0;
1309
1310        rs_set_expected_tpt_table(lq_sta, tbl);
1311
1312        rate = rs_get_best_rate(mvm, lq_sta, tbl, rate_mask, index);
1313
1314        IWL_DEBUG_RATE(mvm, "LQ: MIMO3 best rate %d mask %X\n",
1315                       rate, rate_mask);
1316        if ((rate == IWL_RATE_INVALID) || !((1 << rate) & rate_mask)) {
1317                IWL_DEBUG_RATE(mvm, "Can't switch with index %d rate mask %x\n",
1318                               rate, rate_mask);
1319                return -1;
1320        }
1321        tbl->current_rate = rate_n_flags_from_tbl(mvm, tbl, rate, is_green);
1322
1323        IWL_DEBUG_RATE(mvm, "LQ: Switch to new mcs %X index is green %X\n",
1324                       tbl->current_rate, is_green);
1325        return 0;
1326}
1327
1328/*
1329 * Set up search table for SISO
1330 */
1331static int rs_switch_to_siso(struct iwl_mvm *mvm,
1332                             struct iwl_lq_sta *lq_sta,
1333                             struct ieee80211_sta *sta,
1334                             struct iwl_scale_tbl_info *tbl, int index)
1335{
1336        u16 rate_mask;
1337        u8 is_green = lq_sta->is_green;
1338        s32 rate;
1339
1340        if (!sta->ht_cap.ht_supported)
1341                return -1;
1342
1343        IWL_DEBUG_RATE(mvm, "LQ: try to switch to SISO\n");
1344
1345        tbl->lq_type = LQ_SISO;
1346        tbl->action = 0;
1347        tbl->max_search = IWL_MAX_SEARCH;
1348        rate_mask = lq_sta->active_siso_rate;
1349
1350        if (iwl_is_ht40_tx_allowed(sta))
1351                tbl->is_ht40 = 1;
1352        else
1353                tbl->is_ht40 = 0;
1354
1355        if (is_green)
1356                tbl->is_SGI = 0; /*11n spec: no SGI in SISO+Greenfield*/
1357
1358        rs_set_expected_tpt_table(lq_sta, tbl);
1359        rate = rs_get_best_rate(mvm, lq_sta, tbl, rate_mask, index);
1360
1361        IWL_DEBUG_RATE(mvm, "LQ: get best rate %d mask %X\n", rate, rate_mask);
1362        if ((rate == IWL_RATE_INVALID) || !((1 << rate) & rate_mask)) {
1363                IWL_DEBUG_RATE(mvm,
1364                               "can not switch with index %d rate mask %x\n",
1365                               rate, rate_mask);
1366                return -1;
1367        }
1368        tbl->current_rate = rate_n_flags_from_tbl(mvm, tbl, rate, is_green);
1369        IWL_DEBUG_RATE(mvm, "LQ: Switch to new mcs %X index is green %X\n",
1370                       tbl->current_rate, is_green);
1371        return 0;
1372}
1373
1374/*
1375 * Try to switch to new modulation mode from legacy
1376 */
1377static int rs_move_legacy_other(struct iwl_mvm *mvm,
1378                                struct iwl_lq_sta *lq_sta,
1379                                struct ieee80211_sta *sta,
1380                                int index)
1381{
1382        struct iwl_scale_tbl_info *tbl = &(lq_sta->lq_info[lq_sta->active_tbl]);
1383        struct iwl_scale_tbl_info *search_tbl =
1384                                &(lq_sta->lq_info[(1 - lq_sta->active_tbl)]);
1385        struct iwl_rate_scale_data *window = &(tbl->win[index]);
1386        u32 sz = (sizeof(struct iwl_scale_tbl_info) -
1387                  (sizeof(struct iwl_rate_scale_data) * IWL_RATE_COUNT));
1388        u8 start_action;
1389        u8 valid_tx_ant = iwl_fw_valid_tx_ant(mvm->fw);
1390        u8 tx_chains_num = num_of_ant(valid_tx_ant);
1391        int ret;
1392        u8 update_search_tbl_counter = 0;
1393
1394        start_action = tbl->action;
1395        while (1) {
1396                lq_sta->action_counter++;
1397                switch (tbl->action) {
1398                case IWL_LEGACY_SWITCH_ANTENNA1:
1399                case IWL_LEGACY_SWITCH_ANTENNA2:
1400                        IWL_DEBUG_RATE(mvm, "LQ: Legacy toggle Antenna\n");
1401
1402                        if ((tbl->action == IWL_LEGACY_SWITCH_ANTENNA1 &&
1403                             tx_chains_num <= 1) ||
1404                            (tbl->action == IWL_LEGACY_SWITCH_ANTENNA2 &&
1405                             tx_chains_num <= 2))
1406                                break;
1407
1408                        /* Don't change antenna if success has been great */
1409                        if (window->success_ratio >= IWL_RS_GOOD_RATIO)
1410                                break;
1411
1412                        /* Set up search table to try other antenna */
1413                        memcpy(search_tbl, tbl, sz);
1414
1415                        if (rs_toggle_antenna(valid_tx_ant,
1416                                              &search_tbl->current_rate,
1417                                              search_tbl)) {
1418                                update_search_tbl_counter = 1;
1419                                rs_set_expected_tpt_table(lq_sta, search_tbl);
1420                                goto out;
1421                        }
1422                        break;
1423                case IWL_LEGACY_SWITCH_SISO:
1424                        IWL_DEBUG_RATE(mvm, "LQ: Legacy switch to SISO\n");
1425
1426                        /* Set up search table to try SISO */
1427                        memcpy(search_tbl, tbl, sz);
1428                        search_tbl->is_SGI = 0;
1429                        ret = rs_switch_to_siso(mvm, lq_sta, sta,
1430                                                 search_tbl, index);
1431                        if (!ret) {
1432                                lq_sta->action_counter = 0;
1433                                goto out;
1434                        }
1435
1436                        break;
1437                case IWL_LEGACY_SWITCH_MIMO2_AB:
1438                case IWL_LEGACY_SWITCH_MIMO2_AC:
1439                case IWL_LEGACY_SWITCH_MIMO2_BC:
1440                        IWL_DEBUG_RATE(mvm, "LQ: Legacy switch to MIMO2\n");
1441
1442                        /* Set up search table to try MIMO */
1443                        memcpy(search_tbl, tbl, sz);
1444                        search_tbl->is_SGI = 0;
1445
1446                        if (tbl->action == IWL_LEGACY_SWITCH_MIMO2_AB)
1447                                search_tbl->ant_type = ANT_AB;
1448                        else if (tbl->action == IWL_LEGACY_SWITCH_MIMO2_AC)
1449                                search_tbl->ant_type = ANT_AC;
1450                        else
1451                                search_tbl->ant_type = ANT_BC;
1452
1453                        if (!rs_is_valid_ant(valid_tx_ant,
1454                                             search_tbl->ant_type))
1455                                break;
1456
1457                        ret = rs_switch_to_mimo2(mvm, lq_sta, sta,
1458                                                 search_tbl, index);
1459                        if (!ret) {
1460                                lq_sta->action_counter = 0;
1461                                goto out;
1462                        }
1463                        break;
1464
1465                case IWL_LEGACY_SWITCH_MIMO3_ABC:
1466                        IWL_DEBUG_RATE(mvm, "LQ: Legacy switch to MIMO3\n");
1467
1468                        /* Set up search table to try MIMO3 */
1469                        memcpy(search_tbl, tbl, sz);
1470                        search_tbl->is_SGI = 0;
1471
1472                        search_tbl->ant_type = ANT_ABC;
1473
1474                        if (!rs_is_valid_ant(valid_tx_ant,
1475                                             search_tbl->ant_type))
1476                                break;
1477
1478                        ret = rs_switch_to_mimo3(mvm, lq_sta, sta,
1479                                                 search_tbl, index);
1480                        if (!ret) {
1481                                lq_sta->action_counter = 0;
1482                                goto out;
1483                        }
1484                        break;
1485                }
1486                tbl->action++;
1487                if (tbl->action > IWL_LEGACY_SWITCH_MIMO3_ABC)
1488                        tbl->action = IWL_LEGACY_SWITCH_ANTENNA1;
1489
1490                if (tbl->action == start_action)
1491                        break;
1492        }
1493        search_tbl->lq_type = LQ_NONE;
1494        return 0;
1495
1496out:
1497        lq_sta->search_better_tbl = 1;
1498        tbl->action++;
1499        if (tbl->action > IWL_LEGACY_SWITCH_MIMO3_ABC)
1500                tbl->action = IWL_LEGACY_SWITCH_ANTENNA1;
1501        if (update_search_tbl_counter)
1502                search_tbl->action = tbl->action;
1503        return 0;
1504}
1505
1506/*
1507 * Try to switch to new modulation mode from SISO
1508 */
1509static int rs_move_siso_to_other(struct iwl_mvm *mvm,
1510                                 struct iwl_lq_sta *lq_sta,
1511                                 struct ieee80211_sta *sta, int index)
1512{
1513        u8 is_green = lq_sta->is_green;
1514        struct iwl_scale_tbl_info *tbl = &(lq_sta->lq_info[lq_sta->active_tbl]);
1515        struct iwl_scale_tbl_info *search_tbl =
1516                                &(lq_sta->lq_info[(1 - lq_sta->active_tbl)]);
1517        struct iwl_rate_scale_data *window = &(tbl->win[index]);
1518        struct ieee80211_sta_ht_cap *ht_cap = &sta->ht_cap;
1519        u32 sz = (sizeof(struct iwl_scale_tbl_info) -
1520                  (sizeof(struct iwl_rate_scale_data) * IWL_RATE_COUNT));
1521        u8 start_action;
1522        u8 valid_tx_ant = iwl_fw_valid_tx_ant(mvm->fw);
1523        u8 tx_chains_num = num_of_ant(valid_tx_ant);
1524        u8 update_search_tbl_counter = 0;
1525        int ret;
1526
1527        switch (BT_MBOX_MSG(&mvm->last_bt_notif, 3, TRAFFIC_LOAD)) {
1528        case IWL_BT_COEX_TRAFFIC_LOAD_NONE:
1529                /* nothing */
1530                break;
1531        case IWL_BT_COEX_TRAFFIC_LOAD_LOW:
1532                /* avoid antenna B unless MIMO */
1533                if (tbl->action == IWL_SISO_SWITCH_ANTENNA2)
1534                        tbl->action = IWL_SISO_SWITCH_MIMO2_AB;
1535                break;
1536        case IWL_BT_COEX_TRAFFIC_LOAD_HIGH:
1537        case IWL_BT_COEX_TRAFFIC_LOAD_CONTINUOUS:
1538                /* avoid antenna B and MIMO */
1539                valid_tx_ant =
1540                        first_antenna(iwl_fw_valid_tx_ant(mvm->fw));
1541                if (tbl->action != IWL_SISO_SWITCH_ANTENNA1)
1542                        tbl->action = IWL_SISO_SWITCH_ANTENNA1;
1543                break;
1544        default:
1545                IWL_ERR(mvm, "Invalid BT load %d",
1546                        BT_MBOX_MSG(&mvm->last_bt_notif, 3, TRAFFIC_LOAD));
1547                break;
1548        }
1549
1550        start_action = tbl->action;
1551        while (1) {
1552                lq_sta->action_counter++;
1553                switch (tbl->action) {
1554                case IWL_SISO_SWITCH_ANTENNA1:
1555                case IWL_SISO_SWITCH_ANTENNA2:
1556                        IWL_DEBUG_RATE(mvm, "LQ: SISO toggle Antenna\n");
1557                        if ((tbl->action == IWL_SISO_SWITCH_ANTENNA1 &&
1558                             tx_chains_num <= 1) ||
1559                            (tbl->action == IWL_SISO_SWITCH_ANTENNA2 &&
1560                             tx_chains_num <= 2))
1561                                break;
1562
1563                        if (window->success_ratio >= IWL_RS_GOOD_RATIO &&
1564                            BT_MBOX_MSG(&mvm->last_bt_notif, 3,
1565                                        TRAFFIC_LOAD) == 0)
1566                                break;
1567
1568                        memcpy(search_tbl, tbl, sz);
1569                        if (rs_toggle_antenna(valid_tx_ant,
1570                                              &search_tbl->current_rate,
1571                                              search_tbl)) {
1572                                update_search_tbl_counter = 1;
1573                                goto out;
1574                        }
1575                        break;
1576                case IWL_SISO_SWITCH_MIMO2_AB:
1577                case IWL_SISO_SWITCH_MIMO2_AC:
1578                case IWL_SISO_SWITCH_MIMO2_BC:
1579                        IWL_DEBUG_RATE(mvm, "LQ: SISO switch to MIMO2\n");
1580                        memcpy(search_tbl, tbl, sz);
1581                        search_tbl->is_SGI = 0;
1582
1583                        if (tbl->action == IWL_SISO_SWITCH_MIMO2_AB)
1584                                search_tbl->ant_type = ANT_AB;
1585                        else if (tbl->action == IWL_SISO_SWITCH_MIMO2_AC)
1586                                search_tbl->ant_type = ANT_AC;
1587                        else
1588                                search_tbl->ant_type = ANT_BC;
1589
1590                        if (!rs_is_valid_ant(valid_tx_ant,
1591                                             search_tbl->ant_type))
1592                                break;
1593
1594                        ret = rs_switch_to_mimo2(mvm, lq_sta, sta,
1595                                                 search_tbl, index);
1596                        if (!ret)
1597                                goto out;
1598                        break;
1599                case IWL_SISO_SWITCH_GI:
1600                        if (!tbl->is_ht40 && !(ht_cap->cap &
1601                                                IEEE80211_HT_CAP_SGI_20))
1602                                break;
1603                        if (tbl->is_ht40 && !(ht_cap->cap &
1604                                                IEEE80211_HT_CAP_SGI_40))
1605                                break;
1606
1607                        IWL_DEBUG_RATE(mvm, "LQ: SISO toggle SGI/NGI\n");
1608
1609                        memcpy(search_tbl, tbl, sz);
1610                        if (is_green) {
1611                                if (!tbl->is_SGI)
1612                                        break;
1613                                else
1614                                        IWL_ERR(mvm,
1615                                                "SGI was set in GF+SISO\n");
1616                        }
1617                        search_tbl->is_SGI = !tbl->is_SGI;
1618                        rs_set_expected_tpt_table(lq_sta, search_tbl);
1619                        if (tbl->is_SGI) {
1620                                s32 tpt = lq_sta->last_tpt / 100;
1621                                if (tpt >= search_tbl->expected_tpt[index])
1622                                        break;
1623                        }
1624                        search_tbl->current_rate =
1625                                rate_n_flags_from_tbl(mvm, search_tbl,
1626                                                      index, is_green);
1627                        update_search_tbl_counter = 1;
1628                        goto out;
1629                case IWL_SISO_SWITCH_MIMO3_ABC:
1630                        IWL_DEBUG_RATE(mvm, "LQ: SISO switch to MIMO3\n");
1631                        memcpy(search_tbl, tbl, sz);
1632                        search_tbl->is_SGI = 0;
1633                        search_tbl->ant_type = ANT_ABC;
1634
1635                        if (!rs_is_valid_ant(valid_tx_ant,
1636                                             search_tbl->ant_type))
1637                                break;
1638
1639                        ret = rs_switch_to_mimo3(mvm, lq_sta, sta,
1640                                                 search_tbl, index);
1641                        if (!ret)
1642                                goto out;
1643                        break;
1644                }
1645                tbl->action++;
1646                if (tbl->action > IWL_LEGACY_SWITCH_MIMO3_ABC)
1647                        tbl->action = IWL_SISO_SWITCH_ANTENNA1;
1648
1649                if (tbl->action == start_action)
1650                        break;
1651        }
1652        search_tbl->lq_type = LQ_NONE;
1653        return 0;
1654
1655 out:
1656        lq_sta->search_better_tbl = 1;
1657        tbl->action++;
1658        if (tbl->action > IWL_SISO_SWITCH_MIMO3_ABC)
1659                tbl->action = IWL_SISO_SWITCH_ANTENNA1;
1660        if (update_search_tbl_counter)
1661                search_tbl->action = tbl->action;
1662
1663        return 0;
1664}
1665
1666/*
1667 * Try to switch to new modulation mode from MIMO2
1668 */
1669static int rs_move_mimo2_to_other(struct iwl_mvm *mvm,
1670                                 struct iwl_lq_sta *lq_sta,
1671                                 struct ieee80211_sta *sta, int index)
1672{
1673        s8 is_green = lq_sta->is_green;
1674        struct iwl_scale_tbl_info *tbl = &(lq_sta->lq_info[lq_sta->active_tbl]);
1675        struct iwl_scale_tbl_info *search_tbl =
1676                                &(lq_sta->lq_info[(1 - lq_sta->active_tbl)]);
1677        struct iwl_rate_scale_data *window = &(tbl->win[index]);
1678        struct ieee80211_sta_ht_cap *ht_cap = &sta->ht_cap;
1679        u32 sz = (sizeof(struct iwl_scale_tbl_info) -
1680                  (sizeof(struct iwl_rate_scale_data) * IWL_RATE_COUNT));
1681        u8 start_action;
1682        u8 valid_tx_ant = iwl_fw_valid_tx_ant(mvm->fw);
1683        u8 tx_chains_num = num_of_ant(valid_tx_ant);
1684        u8 update_search_tbl_counter = 0;
1685        int ret;
1686
1687        switch (BT_MBOX_MSG(&mvm->last_bt_notif, 3, TRAFFIC_LOAD)) {
1688        case IWL_BT_COEX_TRAFFIC_LOAD_NONE:
1689                /* nothing */
1690                break;
1691        case IWL_BT_COEX_TRAFFIC_LOAD_HIGH:
1692        case IWL_BT_COEX_TRAFFIC_LOAD_CONTINUOUS:
1693                /* avoid antenna B and MIMO */
1694                if (tbl->action != IWL_MIMO2_SWITCH_SISO_A)
1695                        tbl->action = IWL_MIMO2_SWITCH_SISO_A;
1696                break;
1697        case IWL_BT_COEX_TRAFFIC_LOAD_LOW:
1698                /* avoid antenna B unless MIMO */
1699                if (tbl->action == IWL_MIMO2_SWITCH_SISO_B ||
1700                    tbl->action == IWL_MIMO2_SWITCH_SISO_C)
1701                        tbl->action = IWL_MIMO2_SWITCH_SISO_A;
1702                break;
1703        default:
1704                IWL_ERR(mvm, "Invalid BT load %d",
1705                        BT_MBOX_MSG(&mvm->last_bt_notif, 3, TRAFFIC_LOAD));
1706                break;
1707        }
1708
1709        start_action = tbl->action;
1710        while (1) {
1711                lq_sta->action_counter++;
1712                switch (tbl->action) {
1713                case IWL_MIMO2_SWITCH_ANTENNA1:
1714                case IWL_MIMO2_SWITCH_ANTENNA2:
1715                        IWL_DEBUG_RATE(mvm, "LQ: MIMO2 toggle Antennas\n");
1716
1717                        if (tx_chains_num <= 2)
1718                                break;
1719
1720                        if (window->success_ratio >= IWL_RS_GOOD_RATIO)
1721                                break;
1722
1723                        memcpy(search_tbl, tbl, sz);
1724                        if (rs_toggle_antenna(valid_tx_ant,
1725                                              &search_tbl->current_rate,
1726                                              search_tbl)) {
1727                                update_search_tbl_counter = 1;
1728                                goto out;
1729                        }
1730                        break;
1731                case IWL_MIMO2_SWITCH_SISO_A:
1732                case IWL_MIMO2_SWITCH_SISO_B:
1733                case IWL_MIMO2_SWITCH_SISO_C:
1734                        IWL_DEBUG_RATE(mvm, "LQ: MIMO2 switch to SISO\n");
1735
1736                        /* Set up new search table for SISO */
1737                        memcpy(search_tbl, tbl, sz);
1738
1739                        if (tbl->action == IWL_MIMO2_SWITCH_SISO_A)
1740                                search_tbl->ant_type = ANT_A;
1741                        else if (tbl->action == IWL_MIMO2_SWITCH_SISO_B)
1742                                search_tbl->ant_type = ANT_B;
1743                        else
1744                                search_tbl->ant_type = ANT_C;
1745
1746                        if (!rs_is_valid_ant(valid_tx_ant,
1747                                             search_tbl->ant_type))
1748                                break;
1749
1750                        ret = rs_switch_to_siso(mvm, lq_sta, sta,
1751                                                 search_tbl, index);
1752                        if (!ret)
1753                                goto out;
1754
1755                        break;
1756
1757                case IWL_MIMO2_SWITCH_GI:
1758                        if (!tbl->is_ht40 && !(ht_cap->cap &
1759                                                IEEE80211_HT_CAP_SGI_20))
1760                                break;
1761                        if (tbl->is_ht40 && !(ht_cap->cap &
1762                                                IEEE80211_HT_CAP_SGI_40))
1763                                break;
1764
1765                        IWL_DEBUG_RATE(mvm, "LQ: MIMO2 toggle SGI/NGI\n");
1766
1767                        /* Set up new search table for MIMO2 */
1768                        memcpy(search_tbl, tbl, sz);
1769                        search_tbl->is_SGI = !tbl->is_SGI;
1770                        rs_set_expected_tpt_table(lq_sta, search_tbl);
1771                        /*
1772                         * If active table already uses the fastest possible
1773                         * modulation (dual stream with short guard interval),
1774                         * and it's working well, there's no need to look
1775                         * for a better type of modulation!
1776                         */
1777                        if (tbl->is_SGI) {
1778                                s32 tpt = lq_sta->last_tpt / 100;
1779                                if (tpt >= search_tbl->expected_tpt[index])
1780                                        break;
1781                        }
1782                        search_tbl->current_rate =
1783                                rate_n_flags_from_tbl(mvm, search_tbl,
1784                                                      index, is_green);
1785                        update_search_tbl_counter = 1;
1786                        goto out;
1787
1788                case IWL_MIMO2_SWITCH_MIMO3_ABC:
1789                        IWL_DEBUG_RATE(mvm, "LQ: MIMO2 switch to MIMO3\n");
1790                        memcpy(search_tbl, tbl, sz);
1791                        search_tbl->is_SGI = 0;
1792                        search_tbl->ant_type = ANT_ABC;
1793
1794                        if (!rs_is_valid_ant(valid_tx_ant,
1795                                             search_tbl->ant_type))
1796                                break;
1797
1798                        ret = rs_switch_to_mimo3(mvm, lq_sta, sta,
1799                                                 search_tbl, index);
1800                        if (!ret)
1801                                goto out;
1802
1803                        break;
1804                }
1805                tbl->action++;
1806                if (tbl->action > IWL_MIMO2_SWITCH_MIMO3_ABC)
1807                        tbl->action = IWL_MIMO2_SWITCH_ANTENNA1;
1808
1809                if (tbl->action == start_action)
1810                        break;
1811        }
1812        search_tbl->lq_type = LQ_NONE;
1813        return 0;
1814 out:
1815        lq_sta->search_better_tbl = 1;
1816        tbl->action++;
1817        if (tbl->action > IWL_MIMO2_SWITCH_MIMO3_ABC)
1818                tbl->action = IWL_MIMO2_SWITCH_ANTENNA1;
1819        if (update_search_tbl_counter)
1820                search_tbl->action = tbl->action;
1821
1822        return 0;
1823}
1824
1825/*
1826 * Try to switch to new modulation mode from MIMO3
1827 */
1828static int rs_move_mimo3_to_other(struct iwl_mvm *mvm,
1829                                 struct iwl_lq_sta *lq_sta,
1830                                 struct ieee80211_sta *sta, int index)
1831{
1832        s8 is_green = lq_sta->is_green;
1833        struct iwl_scale_tbl_info *tbl = &(lq_sta->lq_info[lq_sta->active_tbl]);
1834        struct iwl_scale_tbl_info *search_tbl =
1835                                &(lq_sta->lq_info[(1 - lq_sta->active_tbl)]);
1836        struct iwl_rate_scale_data *window = &(tbl->win[index]);
1837        struct ieee80211_sta_ht_cap *ht_cap = &sta->ht_cap;
1838        u32 sz = (sizeof(struct iwl_scale_tbl_info) -
1839                  (sizeof(struct iwl_rate_scale_data) * IWL_RATE_COUNT));
1840        u8 start_action;
1841        u8 valid_tx_ant = iwl_fw_valid_tx_ant(mvm->fw);
1842        u8 tx_chains_num = num_of_ant(valid_tx_ant);
1843        int ret;
1844        u8 update_search_tbl_counter = 0;
1845
1846        switch (BT_MBOX_MSG(&mvm->last_bt_notif, 3, TRAFFIC_LOAD)) {
1847        case IWL_BT_COEX_TRAFFIC_LOAD_NONE:
1848                /* nothing */
1849                break;
1850        case IWL_BT_COEX_TRAFFIC_LOAD_HIGH:
1851        case IWL_BT_COEX_TRAFFIC_LOAD_CONTINUOUS:
1852                /* avoid antenna B and MIMO */
1853                if (tbl->action != IWL_MIMO3_SWITCH_SISO_A)
1854                        tbl->action = IWL_MIMO3_SWITCH_SISO_A;
1855                break;
1856        case IWL_BT_COEX_TRAFFIC_LOAD_LOW:
1857                /* avoid antenna B unless MIMO */
1858                if (tbl->action == IWL_MIMO3_SWITCH_SISO_B ||
1859                    tbl->action == IWL_MIMO3_SWITCH_SISO_C)
1860                        tbl->action = IWL_MIMO3_SWITCH_SISO_A;
1861                break;
1862        default:
1863                IWL_ERR(mvm, "Invalid BT load %d",
1864                        BT_MBOX_MSG(&mvm->last_bt_notif, 3, TRAFFIC_LOAD));
1865                break;
1866        }
1867
1868        start_action = tbl->action;
1869        while (1) {
1870                lq_sta->action_counter++;
1871                switch (tbl->action) {
1872                case IWL_MIMO3_SWITCH_ANTENNA1:
1873                case IWL_MIMO3_SWITCH_ANTENNA2:
1874                        IWL_DEBUG_RATE(mvm, "LQ: MIMO3 toggle Antennas\n");
1875
1876                        if (tx_chains_num <= 3)
1877                                break;
1878
1879                        if (window->success_ratio >= IWL_RS_GOOD_RATIO)
1880                                break;
1881
1882                        memcpy(search_tbl, tbl, sz);
1883                        if (rs_toggle_antenna(valid_tx_ant,
1884                                              &search_tbl->current_rate,
1885                                              search_tbl))
1886                                goto out;
1887                        break;
1888                case IWL_MIMO3_SWITCH_SISO_A:
1889                case IWL_MIMO3_SWITCH_SISO_B:
1890                case IWL_MIMO3_SWITCH_SISO_C:
1891                        IWL_DEBUG_RATE(mvm, "LQ: MIMO3 switch to SISO\n");
1892
1893                        /* Set up new search table for SISO */
1894                        memcpy(search_tbl, tbl, sz);
1895
1896                        if (tbl->action == IWL_MIMO3_SWITCH_SISO_A)
1897                                search_tbl->ant_type = ANT_A;
1898                        else if (tbl->action == IWL_MIMO3_SWITCH_SISO_B)
1899                                search_tbl->ant_type = ANT_B;
1900                        else
1901                                search_tbl->ant_type = ANT_C;
1902
1903                        if (!rs_is_valid_ant(valid_tx_ant,
1904                                             search_tbl->ant_type))
1905                                break;
1906
1907                        ret = rs_switch_to_siso(mvm, lq_sta, sta,
1908                                                search_tbl, index);
1909                        if (!ret)
1910                                goto out;
1911
1912                        break;
1913
1914                case IWL_MIMO3_SWITCH_MIMO2_AB:
1915                case IWL_MIMO3_SWITCH_MIMO2_AC:
1916                case IWL_MIMO3_SWITCH_MIMO2_BC:
1917                        IWL_DEBUG_RATE(mvm, "LQ: MIMO3 switch to MIMO2\n");
1918
1919                        memcpy(search_tbl, tbl, sz);
1920                        search_tbl->is_SGI = 0;
1921                        if (tbl->action == IWL_MIMO3_SWITCH_MIMO2_AB)
1922                                search_tbl->ant_type = ANT_AB;
1923                        else if (tbl->action == IWL_MIMO3_SWITCH_MIMO2_AC)
1924                                search_tbl->ant_type = ANT_AC;
1925                        else
1926                                search_tbl->ant_type = ANT_BC;
1927
1928                        if (!rs_is_valid_ant(valid_tx_ant,
1929                                             search_tbl->ant_type))
1930                                break;
1931
1932                        ret = rs_switch_to_mimo2(mvm, lq_sta, sta,
1933                                                 search_tbl, index);
1934                        if (!ret)
1935                                goto out;
1936
1937                        break;
1938
1939                case IWL_MIMO3_SWITCH_GI:
1940                        if (!tbl->is_ht40 && !(ht_cap->cap &
1941                                                IEEE80211_HT_CAP_SGI_20))
1942                                break;
1943                        if (tbl->is_ht40 && !(ht_cap->cap &
1944                                                IEEE80211_HT_CAP_SGI_40))
1945                                break;
1946
1947                        IWL_DEBUG_RATE(mvm, "LQ: MIMO3 toggle SGI/NGI\n");
1948
1949                        /* Set up new search table for MIMO */
1950                        memcpy(search_tbl, tbl, sz);
1951                        search_tbl->is_SGI = !tbl->is_SGI;
1952                        rs_set_expected_tpt_table(lq_sta, search_tbl);
1953                        /*
1954                         * If active table already uses the fastest possible
1955                         * modulation (dual stream with short guard interval),
1956                         * and it's working well, there's no need to look
1957                         * for a better type of modulation!
1958                         */
1959                        if (tbl->is_SGI) {
1960                                s32 tpt = lq_sta->last_tpt / 100;
1961                                if (tpt >= search_tbl->expected_tpt[index])
1962                                        break;
1963                        }
1964                        search_tbl->current_rate =
1965                                rate_n_flags_from_tbl(mvm, search_tbl,
1966                                                      index, is_green);
1967                        update_search_tbl_counter = 1;
1968                        goto out;
1969                }
1970                tbl->action++;
1971                if (tbl->action > IWL_MIMO3_SWITCH_GI)
1972                        tbl->action = IWL_MIMO3_SWITCH_ANTENNA1;
1973
1974                if (tbl->action == start_action)
1975                        break;
1976        }
1977        search_tbl->lq_type = LQ_NONE;
1978        return 0;
1979 out:
1980        lq_sta->search_better_tbl = 1;
1981        tbl->action++;
1982        if (tbl->action > IWL_MIMO3_SWITCH_GI)
1983                tbl->action = IWL_MIMO3_SWITCH_ANTENNA1;
1984        if (update_search_tbl_counter)
1985                search_tbl->action = tbl->action;
1986
1987        return 0;
1988}
1989
1990/*
1991 * Check whether we should continue using same modulation mode, or
1992 * begin search for a new mode, based on:
1993 * 1) # tx successes or failures while using this mode
1994 * 2) # times calling this function
1995 * 3) elapsed time in this mode (not used, for now)
1996 */
1997static void rs_stay_in_table(struct iwl_lq_sta *lq_sta, bool force_search)
1998{
1999        struct iwl_scale_tbl_info *tbl;
2000        int i;
2001        int active_tbl;
2002        int flush_interval_passed = 0;
2003        struct iwl_mvm *mvm;
2004
2005        mvm = lq_sta->drv;
2006        active_tbl = lq_sta->active_tbl;
2007
2008        tbl = &(lq_sta->lq_info[active_tbl]);
2009
2010        /* If we've been disallowing search, see if we should now allow it */
2011        if (lq_sta->stay_in_tbl) {
2012                /* Elapsed time using current modulation mode */
2013                if (lq_sta->flush_timer)
2014                        flush_interval_passed =
2015                                time_after(jiffies,
2016                                           (unsigned long)(lq_sta->flush_timer +
2017                                                IWL_RATE_SCALE_FLUSH_INTVL));
2018
2019                /*
2020                 * Check if we should allow search for new modulation mode.
2021                 * If many frames have failed or succeeded, or we've used
2022                 * this same modulation for a long time, allow search, and
2023                 * reset history stats that keep track of whether we should
2024                 * allow a new search.  Also (below) reset all bitmaps and
2025                 * stats in active history.
2026                 */
2027                if (force_search ||
2028                    (lq_sta->total_failed > lq_sta->max_failure_limit) ||
2029                    (lq_sta->total_success > lq_sta->max_success_limit) ||
2030                    ((!lq_sta->search_better_tbl) &&
2031                     (lq_sta->flush_timer) && (flush_interval_passed))) {
2032                        IWL_DEBUG_RATE(mvm,
2033                                       "LQ: stay is expired %d %d %d\n",
2034                                     lq_sta->total_failed,
2035                                     lq_sta->total_success,
2036                                     flush_interval_passed);
2037
2038                        /* Allow search for new mode */
2039                        lq_sta->stay_in_tbl = 0;        /* only place reset */
2040                        lq_sta->total_failed = 0;
2041                        lq_sta->total_success = 0;
2042                        lq_sta->flush_timer = 0;
2043                /*
2044                 * Else if we've used this modulation mode enough repetitions
2045                 * (regardless of elapsed time or success/failure), reset
2046                 * history bitmaps and rate-specific stats for all rates in
2047                 * active table.
2048                 */
2049                } else {
2050                        lq_sta->table_count++;
2051                        if (lq_sta->table_count >=
2052                            lq_sta->table_count_limit) {
2053                                lq_sta->table_count = 0;
2054
2055                                IWL_DEBUG_RATE(mvm,
2056                                               "LQ: stay in table clear win\n");
2057                                for (i = 0; i < IWL_RATE_COUNT; i++)
2058                                        rs_rate_scale_clear_window(
2059                                                &(tbl->win[i]));
2060                        }
2061                }
2062
2063                /* If transitioning to allow "search", reset all history
2064                 * bitmaps and stats in active table (this will become the new
2065                 * "search" table). */
2066                if (!lq_sta->stay_in_tbl) {
2067                        for (i = 0; i < IWL_RATE_COUNT; i++)
2068                                rs_rate_scale_clear_window(&(tbl->win[i]));
2069                }
2070        }
2071}
2072
2073/*
2074 * setup rate table in uCode
2075 */
2076static void rs_update_rate_tbl(struct iwl_mvm *mvm,
2077                               struct iwl_lq_sta *lq_sta,
2078                               struct iwl_scale_tbl_info *tbl,
2079                               int index, u8 is_green)
2080{
2081        u32 rate;
2082
2083        /* Update uCode's rate table. */
2084        rate = rate_n_flags_from_tbl(mvm, tbl, index, is_green);
2085        rs_fill_link_cmd(mvm, lq_sta, rate);
2086        iwl_mvm_send_lq_cmd(mvm, &lq_sta->lq, CMD_ASYNC, false);
2087}
2088
2089/*
2090 * Do rate scaling and search for new modulation mode.
2091 */
2092static void rs_rate_scale_perform(struct iwl_mvm *mvm,
2093                                  struct sk_buff *skb,
2094                                  struct ieee80211_sta *sta,
2095                                  struct iwl_lq_sta *lq_sta)
2096{
2097        struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
2098        struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
2099        int low = IWL_RATE_INVALID;
2100        int high = IWL_RATE_INVALID;
2101        int index;
2102        int i;
2103        struct iwl_rate_scale_data *window = NULL;
2104        int current_tpt = IWL_INVALID_VALUE;
2105        int low_tpt = IWL_INVALID_VALUE;
2106        int high_tpt = IWL_INVALID_VALUE;
2107        u32 fail_count;
2108        s8 scale_action = 0;
2109        u16 rate_mask;
2110        u8 update_lq = 0;
2111        struct iwl_scale_tbl_info *tbl, *tbl1;
2112        u16 rate_scale_index_msk = 0;
2113        u8 is_green = 0;
2114        u8 active_tbl = 0;
2115        u8 done_search = 0;
2116        u16 high_low;
2117        s32 sr;
2118        u8 tid = IWL_MAX_TID_COUNT;
2119        struct iwl_mvm_sta *sta_priv = (void *)sta->drv_priv;
2120        struct iwl_mvm_tid_data *tid_data;
2121
2122        IWL_DEBUG_RATE(mvm, "rate scale calculate new rate for skb\n");
2123
2124        /* Send management frames and NO_ACK data using lowest rate. */
2125        /* TODO: this could probably be improved.. */
2126        if (!ieee80211_is_data(hdr->frame_control) ||
2127            info->flags & IEEE80211_TX_CTL_NO_ACK)
2128                return;
2129
2130        lq_sta->supp_rates = sta->supp_rates[lq_sta->band];
2131
2132        tid = rs_tl_add_packet(lq_sta, hdr);
2133        if ((tid != IWL_MAX_TID_COUNT) &&
2134            (lq_sta->tx_agg_tid_en & (1 << tid))) {
2135                tid_data = &sta_priv->tid_data[tid];
2136                if (tid_data->state == IWL_AGG_OFF)
2137                        lq_sta->is_agg = 0;
2138                else
2139                        lq_sta->is_agg = 1;
2140        } else {
2141                lq_sta->is_agg = 0;
2142        }
2143
2144        /*
2145         * Select rate-scale / modulation-mode table to work with in
2146         * the rest of this function:  "search" if searching for better
2147         * modulation mode, or "active" if doing rate scaling within a mode.
2148         */
2149        if (!lq_sta->search_better_tbl)
2150                active_tbl = lq_sta->active_tbl;
2151        else
2152                active_tbl = 1 - lq_sta->active_tbl;
2153
2154        tbl = &(lq_sta->lq_info[active_tbl]);
2155        if (is_legacy(tbl->lq_type))
2156                lq_sta->is_green = 0;
2157        else
2158                lq_sta->is_green = rs_use_green(sta);
2159        is_green = lq_sta->is_green;
2160
2161        /* current tx rate */
2162        index = lq_sta->last_txrate_idx;
2163
2164        IWL_DEBUG_RATE(mvm, "Rate scale index %d for type %d\n", index,
2165                       tbl->lq_type);
2166
2167        /* rates available for this association, and for modulation mode */
2168        rate_mask = rs_get_supported_rates(lq_sta, hdr, tbl->lq_type);
2169
2170        IWL_DEBUG_RATE(mvm, "mask 0x%04X\n", rate_mask);
2171
2172        /* mask with station rate restriction */
2173        if (is_legacy(tbl->lq_type)) {
2174                if (lq_sta->band == IEEE80211_BAND_5GHZ)
2175                        /* supp_rates has no CCK bits in A mode */
2176                        rate_scale_index_msk = (u16) (rate_mask &
2177                                (lq_sta->supp_rates << IWL_FIRST_OFDM_RATE));
2178                else
2179                        rate_scale_index_msk = (u16) (rate_mask &
2180                                                      lq_sta->supp_rates);
2181
2182        } else {
2183                rate_scale_index_msk = rate_mask;
2184        }
2185
2186        if (!rate_scale_index_msk)
2187                rate_scale_index_msk = rate_mask;
2188
2189        if (!((1 << index) & rate_scale_index_msk)) {
2190                IWL_ERR(mvm, "Current Rate is not valid\n");
2191                if (lq_sta->search_better_tbl) {
2192                        /* revert to active table if search table is not valid*/
2193                        tbl->lq_type = LQ_NONE;
2194                        lq_sta->search_better_tbl = 0;
2195                        tbl = &(lq_sta->lq_info[lq_sta->active_tbl]);
2196                        /* get "active" rate info */
2197                        index = iwl_hwrate_to_plcp_idx(tbl->current_rate);
2198                        rs_update_rate_tbl(mvm, lq_sta, tbl, index, is_green);
2199                }
2200                return;
2201        }
2202
2203        /* Get expected throughput table and history window for current rate */
2204        if (!tbl->expected_tpt) {
2205                IWL_ERR(mvm, "tbl->expected_tpt is NULL\n");
2206                return;
2207        }
2208
2209        /* force user max rate if set by user */
2210        if ((lq_sta->max_rate_idx != -1) &&
2211            (lq_sta->max_rate_idx < index)) {
2212                index = lq_sta->max_rate_idx;
2213                update_lq = 1;
2214                window = &(tbl->win[index]);
2215                goto lq_update;
2216        }
2217
2218        window = &(tbl->win[index]);
2219
2220        /*
2221         * If there is not enough history to calculate actual average
2222         * throughput, keep analyzing results of more tx frames, without
2223         * changing rate or mode (bypass most of the rest of this function).
2224         * Set up new rate table in uCode only if old rate is not supported
2225         * in current association (use new rate found above).
2226         */
2227        fail_count = window->counter - window->success_counter;
2228        if ((fail_count < IWL_RATE_MIN_FAILURE_TH) &&
2229            (window->success_counter < IWL_RATE_MIN_SUCCESS_TH)) {
2230                IWL_DEBUG_RATE(mvm,
2231                               "LQ: still below TH. succ=%d total=%d for index %d\n",
2232                               window->success_counter, window->counter, index);
2233
2234                /* Can't calculate this yet; not enough history */
2235                window->average_tpt = IWL_INVALID_VALUE;
2236
2237                /* Should we stay with this modulation mode,
2238                 * or search for a new one? */
2239                rs_stay_in_table(lq_sta, false);
2240
2241                goto out;
2242        }
2243        /* Else we have enough samples; calculate estimate of
2244         * actual average throughput */
2245        if (window->average_tpt != ((window->success_ratio *
2246                        tbl->expected_tpt[index] + 64) / 128)) {
2247                IWL_ERR(mvm,
2248                        "expected_tpt should have been calculated by now\n");
2249                window->average_tpt = ((window->success_ratio *
2250                                        tbl->expected_tpt[index] + 64) / 128);
2251        }
2252
2253        /* If we are searching for better modulation mode, check success. */
2254        if (lq_sta->search_better_tbl) {
2255                /* If good success, continue using the "search" mode;
2256                 * no need to send new link quality command, since we're
2257                 * continuing to use the setup that we've been trying. */
2258                if (window->average_tpt > lq_sta->last_tpt) {
2259                        IWL_DEBUG_RATE(mvm,
2260                                       "LQ: SWITCHING TO NEW TABLE suc=%d cur-tpt=%d old-tpt=%d\n",
2261                                       window->success_ratio,
2262                                       window->average_tpt,
2263                                       lq_sta->last_tpt);
2264
2265                        if (!is_legacy(tbl->lq_type))
2266                                lq_sta->enable_counter = 1;
2267
2268                        /* Swap tables; "search" becomes "active" */
2269                        lq_sta->active_tbl = active_tbl;
2270                        current_tpt = window->average_tpt;
2271                /* Else poor success; go back to mode in "active" table */
2272                } else {
2273                        IWL_DEBUG_RATE(mvm,
2274                                       "LQ: GOING BACK TO THE OLD TABLE suc=%d cur-tpt=%d old-tpt=%d\n",
2275                                       window->success_ratio,
2276                                       window->average_tpt,
2277                                       lq_sta->last_tpt);
2278
2279                        /* Nullify "search" table */
2280                        tbl->lq_type = LQ_NONE;
2281
2282                        /* Revert to "active" table */
2283                        active_tbl = lq_sta->active_tbl;
2284                        tbl = &(lq_sta->lq_info[active_tbl]);
2285
2286                        /* Revert to "active" rate and throughput info */
2287                        index = iwl_hwrate_to_plcp_idx(tbl->current_rate);
2288                        current_tpt = lq_sta->last_tpt;
2289
2290                        /* Need to set up a new rate table in uCode */
2291                        update_lq = 1;
2292                }
2293
2294                /* Either way, we've made a decision; modulation mode
2295                 * search is done, allow rate adjustment next time. */
2296                lq_sta->search_better_tbl = 0;
2297                done_search = 1;        /* Don't switch modes below! */
2298                goto lq_update;
2299        }
2300
2301        /* (Else) not in search of better modulation mode, try for better
2302         * starting rate, while staying in this mode. */
2303        high_low = rs_get_adjacent_rate(mvm, index, rate_scale_index_msk,
2304                                        tbl->lq_type);
2305        low = high_low & 0xff;
2306        high = (high_low >> 8) & 0xff;
2307
2308        /* If user set max rate, dont allow higher than user constrain */
2309        if ((lq_sta->max_rate_idx != -1) &&
2310            (lq_sta->max_rate_idx < high))
2311                high = IWL_RATE_INVALID;
2312
2313        sr = window->success_ratio;
2314
2315        /* Collect measured throughputs for current and adjacent rates */
2316        current_tpt = window->average_tpt;
2317        if (low != IWL_RATE_INVALID)
2318                low_tpt = tbl->win[low].average_tpt;
2319        if (high != IWL_RATE_INVALID)
2320                high_tpt = tbl->win[high].average_tpt;
2321
2322        scale_action = 0;
2323
2324        /* Too many failures, decrease rate */
2325        if ((sr <= IWL_RATE_DECREASE_TH) || (current_tpt == 0)) {
2326                IWL_DEBUG_RATE(mvm,
2327                               "decrease rate because of low success_ratio\n");
2328                scale_action = -1;
2329        /* No throughput measured yet for adjacent rates; try increase. */
2330        } else if ((low_tpt == IWL_INVALID_VALUE) &&
2331                   (high_tpt == IWL_INVALID_VALUE)) {
2332                if (high != IWL_RATE_INVALID && sr >= IWL_RATE_INCREASE_TH)
2333                        scale_action = 1;
2334                else if (low != IWL_RATE_INVALID)
2335                        scale_action = 0;
2336        }
2337
2338        /* Both adjacent throughputs are measured, but neither one has better
2339         * throughput; we're using the best rate, don't change it! */
2340        else if ((low_tpt != IWL_INVALID_VALUE) &&
2341                 (high_tpt != IWL_INVALID_VALUE) &&
2342                 (low_tpt < current_tpt) &&
2343                 (high_tpt < current_tpt))
2344                scale_action = 0;
2345
2346        /* At least one adjacent rate's throughput is measured,
2347         * and may have better performance. */
2348        else {
2349                /* Higher adjacent rate's throughput is measured */
2350                if (high_tpt != IWL_INVALID_VALUE) {
2351                        /* Higher rate has better throughput */
2352                        if (high_tpt > current_tpt &&
2353                            sr >= IWL_RATE_INCREASE_TH) {
2354                                scale_action = 1;
2355                        } else {
2356                                scale_action = 0;
2357                        }
2358
2359                /* Lower adjacent rate's throughput is measured */
2360                } else if (low_tpt != IWL_INVALID_VALUE) {
2361                        /* Lower rate has better throughput */
2362                        if (low_tpt > current_tpt) {
2363                                IWL_DEBUG_RATE(mvm,
2364                                               "decrease rate because of low tpt\n");
2365                                scale_action = -1;
2366                        } else if (sr >= IWL_RATE_INCREASE_TH) {
2367                                scale_action = 1;
2368                        }
2369                }
2370        }
2371
2372        /* Sanity check; asked for decrease, but success rate or throughput
2373         * has been good at old rate.  Don't change it. */
2374        if ((scale_action == -1) && (low != IWL_RATE_INVALID) &&
2375            ((sr > IWL_RATE_HIGH_TH) ||
2376             (current_tpt > (100 * tbl->expected_tpt[low]))))
2377                scale_action = 0;
2378
2379        if ((BT_MBOX_MSG(&mvm->last_bt_notif, 3, TRAFFIC_LOAD) >=
2380             IWL_BT_COEX_TRAFFIC_LOAD_HIGH) &&
2381             (is_mimo2(tbl->lq_type) || is_mimo3(tbl->lq_type))) {
2382                if (lq_sta->last_bt_traffic >
2383                    BT_MBOX_MSG(&mvm->last_bt_notif, 3, TRAFFIC_LOAD)) {
2384                        /*
2385                         * don't set scale_action, don't want to scale up if
2386                         * the rate scale doesn't otherwise think that is a
2387                         * good idea.
2388                         */
2389                } else if (lq_sta->last_bt_traffic <=
2390                           BT_MBOX_MSG(&mvm->last_bt_notif, 3, TRAFFIC_LOAD)) {
2391                        scale_action = -1;
2392                }
2393        }
2394        lq_sta->last_bt_traffic =
2395                BT_MBOX_MSG(&mvm->last_bt_notif, 3, TRAFFIC_LOAD);
2396
2397        if ((BT_MBOX_MSG(&mvm->last_bt_notif, 3, TRAFFIC_LOAD) >=
2398             IWL_BT_COEX_TRAFFIC_LOAD_HIGH) &&
2399             (is_mimo2(tbl->lq_type) || is_mimo3(tbl->lq_type))) {
2400                /* search for a new modulation */
2401                rs_stay_in_table(lq_sta, true);
2402                goto lq_update;
2403        }
2404
2405        switch (scale_action) {
2406        case -1:
2407                /* Decrease starting rate, update uCode's rate table */
2408                if (low != IWL_RATE_INVALID) {
2409                        update_lq = 1;
2410                        index = low;
2411                }
2412
2413                break;
2414        case 1:
2415                /* Increase starting rate, update uCode's rate table */
2416                if (high != IWL_RATE_INVALID) {
2417                        update_lq = 1;
2418                        index = high;
2419                }
2420
2421                break;
2422        case 0:
2423                /* No change */
2424        default:
2425                break;
2426        }
2427
2428        IWL_DEBUG_RATE(mvm,
2429                       "choose rate scale index %d action %d low %d high %d type %d\n",
2430                       index, scale_action, low, high, tbl->lq_type);
2431
2432lq_update:
2433        /* Replace uCode's rate table for the destination station. */
2434        if (update_lq)
2435                rs_update_rate_tbl(mvm, lq_sta, tbl, index, is_green);
2436
2437        rs_stay_in_table(lq_sta, false);
2438
2439        /*
2440         * Search for new modulation mode if we're:
2441         * 1)  Not changing rates right now
2442         * 2)  Not just finishing up a search
2443         * 3)  Allowing a new search
2444         */
2445        if (!update_lq && !done_search &&
2446            !lq_sta->stay_in_tbl && window->counter) {
2447                /* Save current throughput to compare with "search" throughput*/
2448                lq_sta->last_tpt = current_tpt;
2449
2450                /* Select a new "search" modulation mode to try.
2451                 * If one is found, set up the new "search" table. */
2452                if (is_legacy(tbl->lq_type))
2453                        rs_move_legacy_other(mvm, lq_sta, sta, index);
2454                else if (is_siso(tbl->lq_type))
2455                        rs_move_siso_to_other(mvm, lq_sta, sta, index);
2456                else if (is_mimo2(tbl->lq_type))
2457                        rs_move_mimo2_to_other(mvm, lq_sta, sta, index);
2458                else
2459                        rs_move_mimo3_to_other(mvm, lq_sta, sta, index);
2460
2461                /* If new "search" mode was selected, set up in uCode table */
2462                if (lq_sta->search_better_tbl) {
2463                        /* Access the "search" table, clear its history. */
2464                        tbl = &(lq_sta->lq_info[(1 - lq_sta->active_tbl)]);
2465                        for (i = 0; i < IWL_RATE_COUNT; i++)
2466                                rs_rate_scale_clear_window(&(tbl->win[i]));
2467
2468                        /* Use new "search" start rate */
2469                        index = iwl_hwrate_to_plcp_idx(tbl->current_rate);
2470
2471                        IWL_DEBUG_RATE(mvm,
2472                                       "Switch current  mcs: %X index: %d\n",
2473                                       tbl->current_rate, index);
2474                        rs_fill_link_cmd(mvm, lq_sta, tbl->current_rate);
2475                        iwl_mvm_send_lq_cmd(mvm, &lq_sta->lq, CMD_ASYNC, false);
2476                } else {
2477                        done_search = 1;
2478                }
2479        }
2480
2481        if (done_search && !lq_sta->stay_in_tbl) {
2482                /* If the "active" (non-search) mode was legacy,
2483                 * and we've tried switching antennas,
2484                 * but we haven't been able to try HT modes (not available),
2485                 * stay with best antenna legacy modulation for a while
2486                 * before next round of mode comparisons. */
2487                tbl1 = &(lq_sta->lq_info[lq_sta->active_tbl]);
2488                if (is_legacy(tbl1->lq_type) && !sta->ht_cap.ht_supported &&
2489                    lq_sta->action_counter > tbl1->max_search) {
2490                        IWL_DEBUG_RATE(mvm, "LQ: STAY in legacy table\n");
2491                        rs_set_stay_in_table(mvm, 1, lq_sta);
2492                }
2493
2494                /* If we're in an HT mode, and all 3 mode switch actions
2495                 * have been tried and compared, stay in this best modulation
2496                 * mode for a while before next round of mode comparisons. */
2497                if (lq_sta->enable_counter &&
2498                    (lq_sta->action_counter >= tbl1->max_search)) {
2499                        if ((lq_sta->last_tpt > IWL_AGG_TPT_THREHOLD) &&
2500                            (lq_sta->tx_agg_tid_en & (1 << tid)) &&
2501                            (tid != IWL_MAX_TID_COUNT)) {
2502                                tid_data = &sta_priv->tid_data[tid];
2503                                if (tid_data->state == IWL_AGG_OFF) {
2504                                        IWL_DEBUG_RATE(mvm,
2505                                                       "try to aggregate tid %d\n",
2506                                                       tid);
2507                                        rs_tl_turn_on_agg(mvm, tid,
2508                                                          lq_sta, sta);
2509                                }
2510                        }
2511                        rs_set_stay_in_table(mvm, 0, lq_sta);
2512                }
2513        }
2514
2515out:
2516        tbl->current_rate = rate_n_flags_from_tbl(mvm, tbl, index, is_green);
2517        lq_sta->last_txrate_idx = index;
2518}
2519
2520/**
2521 * rs_initialize_lq - Initialize a station's hardware rate table
2522 *
2523 * The uCode's station table contains a table of fallback rates
2524 * for automatic fallback during transmission.
2525 *
2526 * NOTE: This sets up a default set of values.  These will be replaced later
2527 *       if the driver's iwl-agn-rs rate scaling algorithm is used, instead of
2528 *       rc80211_simple.
2529 *
2530 * NOTE: Run REPLY_ADD_STA command to set up station table entry, before
2531 *       calling this function (which runs REPLY_TX_LINK_QUALITY_CMD,
2532 *       which requires station table entry to exist).
2533 */
2534static void rs_initialize_lq(struct iwl_mvm *mvm,
2535                             struct ieee80211_sta *sta,
2536                             struct iwl_lq_sta *lq_sta,
2537                             enum ieee80211_band band)
2538{
2539        struct iwl_scale_tbl_info *tbl;
2540        int rate_idx;
2541        int i;
2542        u32 rate;
2543        u8 use_green = rs_use_green(sta);
2544        u8 active_tbl = 0;
2545        u8 valid_tx_ant;
2546
2547        if (!sta || !lq_sta)
2548                return;
2549
2550        i = lq_sta->last_txrate_idx;
2551
2552        valid_tx_ant = iwl_fw_valid_tx_ant(mvm->fw);
2553
2554        if (!lq_sta->search_better_tbl)
2555                active_tbl = lq_sta->active_tbl;
2556        else
2557                active_tbl = 1 - lq_sta->active_tbl;
2558
2559        tbl = &(lq_sta->lq_info[active_tbl]);
2560
2561        if ((i < 0) || (i >= IWL_RATE_COUNT))
2562                i = 0;
2563
2564        rate = iwl_rates[i].plcp;
2565        tbl->ant_type = first_antenna(valid_tx_ant);
2566        rate |= tbl->ant_type << RATE_MCS_ANT_POS;
2567
2568        if (i >= IWL_FIRST_CCK_RATE && i <= IWL_LAST_CCK_RATE)
2569                rate |= RATE_MCS_CCK_MSK;
2570
2571        rs_get_tbl_info_from_mcs(rate, band, tbl, &rate_idx);
2572        if (!rs_is_valid_ant(valid_tx_ant, tbl->ant_type))
2573                rs_toggle_antenna(valid_tx_ant, &rate, tbl);
2574
2575        rate = rate_n_flags_from_tbl(mvm, tbl, rate_idx, use_green);
2576        tbl->current_rate = rate;
2577        rs_set_expected_tpt_table(lq_sta, tbl);
2578        rs_fill_link_cmd(NULL, lq_sta, rate);
2579        /* TODO restore station should remember the lq cmd */
2580        iwl_mvm_send_lq_cmd(mvm, &lq_sta->lq, CMD_SYNC, true);
2581}
2582
2583static void rs_get_rate(void *mvm_r, struct ieee80211_sta *sta, void *mvm_sta,
2584                        struct ieee80211_tx_rate_control *txrc)
2585{
2586        struct sk_buff *skb = txrc->skb;
2587        struct ieee80211_supported_band *sband = txrc->sband;
2588        struct iwl_op_mode *op_mode __maybe_unused =
2589                        (struct iwl_op_mode *)mvm_r;
2590        struct iwl_mvm *mvm __maybe_unused = IWL_OP_MODE_GET_MVM(op_mode);
2591        struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
2592        struct iwl_lq_sta *lq_sta = mvm_sta;
2593        int rate_idx;
2594
2595        IWL_DEBUG_RATE_LIMIT(mvm, "rate scale calculate new rate for skb\n");
2596
2597        /* Get max rate if user set max rate */
2598        if (lq_sta) {
2599                lq_sta->max_rate_idx = txrc->max_rate_idx;
2600                if ((sband->band == IEEE80211_BAND_5GHZ) &&
2601                    (lq_sta->max_rate_idx != -1))
2602                        lq_sta->max_rate_idx += IWL_FIRST_OFDM_RATE;
2603                if ((lq_sta->max_rate_idx < 0) ||
2604                    (lq_sta->max_rate_idx >= IWL_RATE_COUNT))
2605                        lq_sta->max_rate_idx = -1;
2606        }
2607
2608        /* Treat uninitialized rate scaling data same as non-existing. */
2609        if (lq_sta && !lq_sta->drv) {
2610                IWL_DEBUG_RATE(mvm, "Rate scaling not initialized yet.\n");
2611                mvm_sta = NULL;
2612        }
2613
2614        /* Send management frames and NO_ACK data using lowest rate. */
2615        if (rate_control_send_low(sta, mvm_sta, txrc))
2616                return;
2617
2618        rate_idx  = lq_sta->last_txrate_idx;
2619
2620        if (lq_sta->last_rate_n_flags & RATE_MCS_HT_MSK) {
2621                rate_idx -= IWL_FIRST_OFDM_RATE;
2622                /* 6M and 9M shared same MCS index */
2623                rate_idx = (rate_idx > 0) ? (rate_idx - 1) : 0;
2624                if (rs_extract_rate(lq_sta->last_rate_n_flags) >=
2625                    IWL_RATE_MIMO3_6M_PLCP)
2626                        rate_idx = rate_idx + (2 * MCS_INDEX_PER_STREAM);
2627                else if (rs_extract_rate(lq_sta->last_rate_n_flags) >=
2628                         IWL_RATE_MIMO2_6M_PLCP)
2629                        rate_idx = rate_idx + MCS_INDEX_PER_STREAM;
2630                info->control.rates[0].flags = IEEE80211_TX_RC_MCS;
2631                if (lq_sta->last_rate_n_flags & RATE_MCS_SGI_MSK)
2632                        info->control.rates[0].flags |= IEEE80211_TX_RC_SHORT_GI;
2633                if (lq_sta->last_rate_n_flags & RATE_MCS_CHAN_WIDTH_40) /* TODO */
2634                        info->control.rates[0].flags |= IEEE80211_TX_RC_40_MHZ_WIDTH;
2635                if (lq_sta->last_rate_n_flags & RATE_HT_MCS_GF_MSK)
2636                        info->control.rates[0].flags |= IEEE80211_TX_RC_GREEN_FIELD;
2637        } else {
2638                /* Check for invalid rates */
2639                if ((rate_idx < 0) || (rate_idx >= IWL_RATE_COUNT_LEGACY) ||
2640                    ((sband->band == IEEE80211_BAND_5GHZ) &&
2641                     (rate_idx < IWL_FIRST_OFDM_RATE)))
2642                        rate_idx = rate_lowest_index(sband, sta);
2643                /* On valid 5 GHz rate, adjust index */
2644                else if (sband->band == IEEE80211_BAND_5GHZ)
2645                        rate_idx -= IWL_FIRST_OFDM_RATE;
2646                info->control.rates[0].flags = 0;
2647        }
2648        info->control.rates[0].idx = rate_idx;
2649        info->control.rates[0].count = 1;
2650}
2651
2652static void *rs_alloc_sta(void *mvm_rate, struct ieee80211_sta *sta,
2653                          gfp_t gfp)
2654{
2655        struct iwl_mvm_sta *sta_priv = (struct iwl_mvm_sta *)sta->drv_priv;
2656        struct iwl_op_mode *op_mode __maybe_unused =
2657                        (struct iwl_op_mode *)mvm_rate;
2658        struct iwl_mvm *mvm __maybe_unused = IWL_OP_MODE_GET_MVM(op_mode);
2659
2660        IWL_DEBUG_RATE(mvm, "create station rate scale window\n");
2661
2662        return &sta_priv->lq_sta;
2663}
2664
2665/*
2666 * Called after adding a new station to initialize rate scaling
2667 */
2668void iwl_mvm_rs_rate_init(struct iwl_mvm *mvm, struct ieee80211_sta *sta,
2669                          enum ieee80211_band band)
2670{
2671        int i, j;
2672        struct ieee80211_hw *hw = mvm->hw;
2673        struct ieee80211_sta_ht_cap *ht_cap = &sta->ht_cap;
2674        struct iwl_mvm_sta *sta_priv;
2675        struct iwl_lq_sta *lq_sta;
2676        struct ieee80211_supported_band *sband;
2677        unsigned long supp; /* must be unsigned long for for_each_set_bit */
2678
2679        sta_priv = (struct iwl_mvm_sta *)sta->drv_priv;
2680        lq_sta = &sta_priv->lq_sta;
2681        sband = hw->wiphy->bands[band];
2682
2683        lq_sta->lq.sta_id = sta_priv->sta_id;
2684
2685        for (j = 0; j < LQ_SIZE; j++)
2686                for (i = 0; i < IWL_RATE_COUNT; i++)
2687                        rs_rate_scale_clear_window(&lq_sta->lq_info[j].win[i]);
2688
2689        lq_sta->flush_timer = 0;
2690        lq_sta->supp_rates = sta->supp_rates[sband->band];
2691        for (j = 0; j < LQ_SIZE; j++)
2692                for (i = 0; i < IWL_RATE_COUNT; i++)
2693                        rs_rate_scale_clear_window(&lq_sta->lq_info[j].win[i]);
2694
2695        IWL_DEBUG_RATE(mvm,
2696                       "LQ: *** rate scale station global init for station %d ***\n",
2697                       sta_priv->sta_id);
2698        /* TODO: what is a good starting rate for STA? About middle? Maybe not
2699         * the lowest or the highest rate.. Could consider using RSSI from
2700         * previous packets? Need to have IEEE 802.1X auth succeed immediately
2701         * after assoc.. */
2702
2703        lq_sta->max_rate_idx = -1;
2704        lq_sta->missed_rate_counter = IWL_MISSED_RATE_MAX;
2705        lq_sta->is_green = rs_use_green(sta);
2706        lq_sta->band = sband->band;
2707        /*
2708         * active legacy rates as per supported rates bitmap
2709         */
2710        supp = sta->supp_rates[sband->band];
2711        lq_sta->active_legacy_rate = 0;
2712        for_each_set_bit(i, &supp, BITS_PER_LONG)
2713                lq_sta->active_legacy_rate |= BIT(sband->bitrates[i].hw_value);
2714
2715        /*
2716         * active_siso_rate mask includes 9 MBits (bit 5), and CCK (bits 0-3),
2717         * supp_rates[] does not; shift to convert format, force 9 MBits off.
2718         */
2719        lq_sta->active_siso_rate = ht_cap->mcs.rx_mask[0] << 1;
2720        lq_sta->active_siso_rate |= ht_cap->mcs.rx_mask[0] & 0x1;
2721        lq_sta->active_siso_rate &= ~((u16)0x2);
2722        lq_sta->active_siso_rate <<= IWL_FIRST_OFDM_RATE;
2723
2724        /* Same here */
2725        lq_sta->active_mimo2_rate = ht_cap->mcs.rx_mask[1] << 1;
2726        lq_sta->active_mimo2_rate |= ht_cap->mcs.rx_mask[1] & 0x1;
2727        lq_sta->active_mimo2_rate &= ~((u16)0x2);
2728        lq_sta->active_mimo2_rate <<= IWL_FIRST_OFDM_RATE;
2729
2730        lq_sta->active_mimo3_rate = ht_cap->mcs.rx_mask[2] << 1;
2731        lq_sta->active_mimo3_rate |= ht_cap->mcs.rx_mask[2] & 0x1;
2732        lq_sta->active_mimo3_rate &= ~((u16)0x2);
2733        lq_sta->active_mimo3_rate <<= IWL_FIRST_OFDM_RATE;
2734
2735        IWL_DEBUG_RATE(mvm,
2736                       "SISO-RATE=%X MIMO2-RATE=%X MIMO3-RATE=%X\n",
2737                       lq_sta->active_siso_rate,
2738                       lq_sta->active_mimo2_rate,
2739                       lq_sta->active_mimo3_rate);
2740
2741        /* These values will be overridden later */
2742        lq_sta->lq.single_stream_ant_msk =
2743                first_antenna(iwl_fw_valid_tx_ant(mvm->fw));
2744        lq_sta->lq.dual_stream_ant_msk =
2745                iwl_fw_valid_tx_ant(mvm->fw) &
2746                ~first_antenna(iwl_fw_valid_tx_ant(mvm->fw));
2747        if (!lq_sta->lq.dual_stream_ant_msk) {
2748                lq_sta->lq.dual_stream_ant_msk = ANT_AB;
2749        } else if (num_of_ant(iwl_fw_valid_tx_ant(mvm->fw)) == 2) {
2750                lq_sta->lq.dual_stream_ant_msk =
2751                        iwl_fw_valid_tx_ant(mvm->fw);
2752        }
2753
2754        /* as default allow aggregation for all tids */
2755        lq_sta->tx_agg_tid_en = IWL_AGG_ALL_TID;
2756        lq_sta->drv = mvm;
2757
2758        /* Set last_txrate_idx to lowest rate */
2759        lq_sta->last_txrate_idx = rate_lowest_index(sband, sta);
2760        if (sband->band == IEEE80211_BAND_5GHZ)
2761                lq_sta->last_txrate_idx += IWL_FIRST_OFDM_RATE;
2762        lq_sta->is_agg = 0;
2763#ifdef CONFIG_MAC80211_DEBUGFS
2764        lq_sta->dbg_fixed_rate = 0;
2765#endif
2766
2767        rs_initialize_lq(mvm, sta, lq_sta, band);
2768}
2769
2770static void rs_fill_link_cmd(struct iwl_mvm *mvm,
2771                             struct iwl_lq_sta *lq_sta, u32 new_rate)
2772{
2773        struct iwl_scale_tbl_info tbl_type;
2774        int index = 0;
2775        int rate_idx;
2776        int repeat_rate = 0;
2777        u8 ant_toggle_cnt = 0;
2778        u8 use_ht_possible = 1;
2779        u8 valid_tx_ant = 0;
2780        struct iwl_lq_cmd *lq_cmd = &lq_sta->lq;
2781
2782        /* Override starting rate (index 0) if needed for debug purposes */
2783        rs_dbgfs_set_mcs(lq_sta, &new_rate, index);
2784
2785        /* Interpret new_rate (rate_n_flags) */
2786        rs_get_tbl_info_from_mcs(new_rate, lq_sta->band,
2787                                 &tbl_type, &rate_idx);
2788
2789        /* How many times should we repeat the initial rate? */
2790        if (is_legacy(tbl_type.lq_type)) {
2791                ant_toggle_cnt = 1;
2792                repeat_rate = IWL_NUMBER_TRY;
2793        } else {
2794                repeat_rate = min(IWL_HT_NUMBER_TRY,
2795                                  LINK_QUAL_AGG_DISABLE_START_DEF - 1);
2796        }
2797
2798        lq_cmd->mimo_delim = is_mimo(tbl_type.lq_type) ? 1 : 0;
2799
2800        /* Fill 1st table entry (index 0) */
2801        lq_cmd->rs_table[index] = cpu_to_le32(new_rate);
2802
2803        if (num_of_ant(tbl_type.ant_type) == 1)
2804                lq_cmd->single_stream_ant_msk = tbl_type.ant_type;
2805        else if (num_of_ant(tbl_type.ant_type) == 2)
2806                lq_cmd->dual_stream_ant_msk = tbl_type.ant_type;
2807        /* otherwise we don't modify the existing value */
2808
2809        index++;
2810        repeat_rate--;
2811        if (mvm)
2812                valid_tx_ant = iwl_fw_valid_tx_ant(mvm->fw);
2813
2814        /* Fill rest of rate table */
2815        while (index < LINK_QUAL_MAX_RETRY_NUM) {
2816                /* Repeat initial/next rate.
2817                 * For legacy IWL_NUMBER_TRY == 1, this loop will not execute.
2818                 * For HT IWL_HT_NUMBER_TRY == 3, this executes twice. */
2819                while (repeat_rate > 0 && (index < LINK_QUAL_MAX_RETRY_NUM)) {
2820                        if (is_legacy(tbl_type.lq_type)) {
2821                                if (ant_toggle_cnt < NUM_TRY_BEFORE_ANT_TOGGLE)
2822                                        ant_toggle_cnt++;
2823                                else if (mvm &&
2824                                         rs_toggle_antenna(valid_tx_ant,
2825                                                        &new_rate, &tbl_type))
2826                                        ant_toggle_cnt = 1;
2827                        }
2828
2829                        /* Override next rate if needed for debug purposes */
2830                        rs_dbgfs_set_mcs(lq_sta, &new_rate, index);
2831
2832                        /* Fill next table entry */
2833                        lq_cmd->rs_table[index] =
2834                                        cpu_to_le32(new_rate);
2835                        repeat_rate--;
2836                        index++;
2837                }
2838
2839                rs_get_tbl_info_from_mcs(new_rate, lq_sta->band, &tbl_type,
2840                                         &rate_idx);
2841
2842
2843                /* Indicate to uCode which entries might be MIMO.
2844                 * If initial rate was MIMO, this will finally end up
2845                 * as (IWL_HT_NUMBER_TRY * 2), after 2nd pass, otherwise 0. */
2846                if (is_mimo(tbl_type.lq_type))
2847                        lq_cmd->mimo_delim = index;
2848
2849                /* Get next rate */
2850                new_rate = rs_get_lower_rate(lq_sta, &tbl_type, rate_idx,
2851                                             use_ht_possible);
2852
2853                /* How many times should we repeat the next rate? */
2854                if (is_legacy(tbl_type.lq_type)) {
2855                        if (ant_toggle_cnt < NUM_TRY_BEFORE_ANT_TOGGLE)
2856                                ant_toggle_cnt++;
2857                        else if (mvm &&
2858                                 rs_toggle_antenna(valid_tx_ant,
2859                                                   &new_rate, &tbl_type))
2860                                ant_toggle_cnt = 1;
2861
2862                        repeat_rate = IWL_NUMBER_TRY;
2863                } else {
2864                        repeat_rate = IWL_HT_NUMBER_TRY;
2865                }
2866
2867                /* Don't allow HT rates after next pass.
2868                 * rs_get_lower_rate() will change type to LQ_A or LQ_G. */
2869                use_ht_possible = 0;
2870
2871                /* Override next rate if needed for debug purposes */
2872                rs_dbgfs_set_mcs(lq_sta, &new_rate, index);
2873
2874                /* Fill next table entry */
2875                lq_cmd->rs_table[index] = cpu_to_le32(new_rate);
2876
2877                index++;
2878                repeat_rate--;
2879        }
2880
2881        lq_cmd->agg_frame_cnt_limit = LINK_QUAL_AGG_FRAME_LIMIT_DEF;
2882        lq_cmd->agg_disable_start_th = LINK_QUAL_AGG_DISABLE_START_DEF;
2883
2884        lq_cmd->agg_time_limit =
2885                cpu_to_le16(LINK_QUAL_AGG_TIME_LIMIT_DEF);
2886
2887        /*
2888         * overwrite if needed, pass aggregation time limit
2889         * to uCode in uSec - This is racy - but heh, at least it helps...
2890         */
2891        if (mvm && BT_MBOX_MSG(&mvm->last_bt_notif, 3, TRAFFIC_LOAD) >= 2)
2892                lq_cmd->agg_time_limit = cpu_to_le16(1200);
2893}
2894
2895static void *rs_alloc(struct ieee80211_hw *hw, struct dentry *debugfsdir)
2896{
2897        return hw->priv;
2898}
2899/* rate scale requires free function to be implemented */
2900static void rs_free(void *mvm_rate)
2901{
2902        return;
2903}
2904
2905static void rs_free_sta(void *mvm_r, struct ieee80211_sta *sta,
2906                        void *mvm_sta)
2907{
2908        struct iwl_op_mode *op_mode __maybe_unused = mvm_r;
2909        struct iwl_mvm *mvm __maybe_unused = IWL_OP_MODE_GET_MVM(op_mode);
2910
2911        IWL_DEBUG_RATE(mvm, "enter\n");
2912        IWL_DEBUG_RATE(mvm, "leave\n");
2913}
2914
2915#ifdef CONFIG_MAC80211_DEBUGFS
2916static void rs_dbgfs_set_mcs(struct iwl_lq_sta *lq_sta,
2917                             u32 *rate_n_flags, int index)
2918{
2919        struct iwl_mvm *mvm;
2920        u8 valid_tx_ant;
2921        u8 ant_sel_tx;
2922
2923        mvm = lq_sta->drv;
2924        valid_tx_ant = iwl_fw_valid_tx_ant(mvm->fw);
2925        if (lq_sta->dbg_fixed_rate) {
2926                ant_sel_tx =
2927                  ((lq_sta->dbg_fixed_rate & RATE_MCS_ANT_ABC_MSK)
2928                  >> RATE_MCS_ANT_POS);
2929                if ((valid_tx_ant & ant_sel_tx) == ant_sel_tx) {
2930                        *rate_n_flags = lq_sta->dbg_fixed_rate;
2931                        IWL_DEBUG_RATE(mvm, "Fixed rate ON\n");
2932                } else {
2933                        lq_sta->dbg_fixed_rate = 0;
2934                        IWL_ERR(mvm,
2935                                "Invalid antenna selection 0x%X, Valid is 0x%X\n",
2936                                ant_sel_tx, valid_tx_ant);
2937                        IWL_DEBUG_RATE(mvm, "Fixed rate OFF\n");
2938                }
2939        } else {
2940                IWL_DEBUG_RATE(mvm, "Fixed rate OFF\n");
2941        }
2942}
2943
2944static ssize_t rs_sta_dbgfs_scale_table_write(struct file *file,
2945                        const char __user *user_buf, size_t count, loff_t *ppos)
2946{
2947        struct iwl_lq_sta *lq_sta = file->private_data;
2948        struct iwl_mvm *mvm;
2949        char buf[64];
2950        size_t buf_size;
2951        u32 parsed_rate;
2952
2953
2954        mvm = lq_sta->drv;
2955        memset(buf, 0, sizeof(buf));
2956        buf_size = min(count, sizeof(buf) -  1);
2957        if (copy_from_user(buf, user_buf, buf_size))
2958                return -EFAULT;
2959
2960        if (sscanf(buf, "%x", &parsed_rate) == 1)
2961                lq_sta->dbg_fixed_rate = parsed_rate;
2962        else
2963                lq_sta->dbg_fixed_rate = 0;
2964
2965        rs_program_fix_rate(mvm, lq_sta);
2966
2967        return count;
2968}
2969
2970static ssize_t rs_sta_dbgfs_scale_table_read(struct file *file,
2971                        char __user *user_buf, size_t count, loff_t *ppos)
2972{
2973        char *buff;
2974        int desc = 0;
2975        int i = 0;
2976        int index = 0;
2977        ssize_t ret;
2978
2979        struct iwl_lq_sta *lq_sta = file->private_data;
2980        struct iwl_mvm *mvm;
2981        struct iwl_scale_tbl_info *tbl = &(lq_sta->lq_info[lq_sta->active_tbl]);
2982
2983        mvm = lq_sta->drv;
2984        buff = kmalloc(1024, GFP_KERNEL);
2985        if (!buff)
2986                return -ENOMEM;
2987
2988        desc += sprintf(buff+desc, "sta_id %d\n", lq_sta->lq.sta_id);
2989        desc += sprintf(buff+desc, "failed=%d success=%d rate=0%X\n",
2990                        lq_sta->total_failed, lq_sta->total_success,
2991                        lq_sta->active_legacy_rate);
2992        desc += sprintf(buff+desc, "fixed rate 0x%X\n",
2993                        lq_sta->dbg_fixed_rate);
2994        desc += sprintf(buff+desc, "valid_tx_ant %s%s%s\n",
2995            (iwl_fw_valid_tx_ant(mvm->fw) & ANT_A) ? "ANT_A," : "",
2996            (iwl_fw_valid_tx_ant(mvm->fw) & ANT_B) ? "ANT_B," : "",
2997            (iwl_fw_valid_tx_ant(mvm->fw) & ANT_C) ? "ANT_C" : "");
2998        desc += sprintf(buff+desc, "lq type %s\n",
2999           (is_legacy(tbl->lq_type)) ? "legacy" : "HT");
3000        if (is_Ht(tbl->lq_type)) {
3001                desc += sprintf(buff+desc, " %s",
3002                   (is_siso(tbl->lq_type)) ? "SISO" :
3003                   ((is_mimo2(tbl->lq_type)) ? "MIMO2" : "MIMO3"));
3004                   desc += sprintf(buff+desc, " %s",
3005                   (tbl->is_ht40) ? "40MHz" : "20MHz");
3006                   desc += sprintf(buff+desc, " %s %s %s\n",
3007                                   (tbl->is_SGI) ? "SGI" : "",
3008                   (lq_sta->is_green) ? "GF enabled" : "",
3009                   (lq_sta->is_agg) ? "AGG on" : "");
3010        }
3011        desc += sprintf(buff+desc, "last tx rate=0x%X\n",
3012                        lq_sta->last_rate_n_flags);
3013        desc += sprintf(buff+desc,
3014                        "general: flags=0x%X mimo-d=%d s-ant0x%x d-ant=0x%x\n",
3015                        lq_sta->lq.flags,
3016                        lq_sta->lq.mimo_delim,
3017                        lq_sta->lq.single_stream_ant_msk,
3018                        lq_sta->lq.dual_stream_ant_msk);
3019
3020        desc += sprintf(buff+desc,
3021                        "agg: time_limit=%d dist_start_th=%d frame_cnt_limit=%d\n",
3022                        le16_to_cpu(lq_sta->lq.agg_time_limit),
3023                        lq_sta->lq.agg_disable_start_th,
3024                        lq_sta->lq.agg_frame_cnt_limit);
3025
3026        desc += sprintf(buff+desc,
3027                        "Start idx [0]=0x%x [1]=0x%x [2]=0x%x [3]=0x%x\n",
3028                        lq_sta->lq.initial_rate_index[0],
3029                        lq_sta->lq.initial_rate_index[1],
3030                        lq_sta->lq.initial_rate_index[2],
3031                        lq_sta->lq.initial_rate_index[3]);
3032
3033        for (i = 0; i < LINK_QUAL_MAX_RETRY_NUM; i++) {
3034                index = iwl_hwrate_to_plcp_idx(
3035                        le32_to_cpu(lq_sta->lq.rs_table[i]));
3036                if (is_legacy(tbl->lq_type)) {
3037                        desc += sprintf(buff+desc, " rate[%d] 0x%X %smbps\n",
3038                                        i, le32_to_cpu(lq_sta->lq.rs_table[i]),
3039                                        iwl_rate_mcs[index].mbps);
3040                } else {
3041                        desc += sprintf(buff+desc,
3042                                        " rate[%d] 0x%X %smbps (%s)\n",
3043                                        i, le32_to_cpu(lq_sta->lq.rs_table[i]),
3044                                        iwl_rate_mcs[index].mbps,
3045                                        iwl_rate_mcs[index].mcs);
3046                }
3047        }
3048
3049        ret = simple_read_from_buffer(user_buf, count, ppos, buff, desc);
3050        kfree(buff);
3051        return ret;
3052}
3053
3054static const struct file_operations rs_sta_dbgfs_scale_table_ops = {
3055        .write = rs_sta_dbgfs_scale_table_write,
3056        .read = rs_sta_dbgfs_scale_table_read,
3057        .open = simple_open,
3058        .llseek = default_llseek,
3059};
3060static ssize_t rs_sta_dbgfs_stats_table_read(struct file *file,
3061                        char __user *user_buf, size_t count, loff_t *ppos)
3062{
3063        char *buff;
3064        int desc = 0;
3065        int i, j;
3066        ssize_t ret;
3067
3068        struct iwl_lq_sta *lq_sta = file->private_data;
3069
3070        buff = kmalloc(1024, GFP_KERNEL);
3071        if (!buff)
3072                return -ENOMEM;
3073
3074        for (i = 0; i < LQ_SIZE; i++) {
3075                desc += sprintf(buff+desc,
3076                                "%s type=%d SGI=%d HT40=%d DUP=0 GF=%d\n"
3077                                "rate=0x%X\n",
3078                                lq_sta->active_tbl == i ? "*" : "x",
3079                                lq_sta->lq_info[i].lq_type,
3080                                lq_sta->lq_info[i].is_SGI,
3081                                lq_sta->lq_info[i].is_ht40,
3082                                lq_sta->is_green,
3083                                lq_sta->lq_info[i].current_rate);
3084                for (j = 0; j < IWL_RATE_COUNT; j++) {
3085                        desc += sprintf(buff+desc,
3086                                "counter=%d success=%d %%=%d\n",
3087                                lq_sta->lq_info[i].win[j].counter,
3088                                lq_sta->lq_info[i].win[j].success_counter,
3089                                lq_sta->lq_info[i].win[j].success_ratio);
3090                }
3091        }
3092        ret = simple_read_from_buffer(user_buf, count, ppos, buff, desc);
3093        kfree(buff);
3094        return ret;
3095}
3096
3097static const struct file_operations rs_sta_dbgfs_stats_table_ops = {
3098        .read = rs_sta_dbgfs_stats_table_read,
3099        .open = simple_open,
3100        .llseek = default_llseek,
3101};
3102
3103static ssize_t rs_sta_dbgfs_rate_scale_data_read(struct file *file,
3104                        char __user *user_buf, size_t count, loff_t *ppos)
3105{
3106        struct iwl_lq_sta *lq_sta = file->private_data;
3107        struct iwl_scale_tbl_info *tbl = &lq_sta->lq_info[lq_sta->active_tbl];
3108        char buff[120];
3109        int desc = 0;
3110
3111        if (is_Ht(tbl->lq_type))
3112                desc += sprintf(buff+desc,
3113                                "Bit Rate= %d Mb/s\n",
3114                                tbl->expected_tpt[lq_sta->last_txrate_idx]);
3115        else
3116                desc += sprintf(buff+desc,
3117                                "Bit Rate= %d Mb/s\n",
3118                                iwl_rates[lq_sta->last_txrate_idx].ieee >> 1);
3119
3120        return simple_read_from_buffer(user_buf, count, ppos, buff, desc);
3121}
3122
3123static const struct file_operations rs_sta_dbgfs_rate_scale_data_ops = {
3124        .read = rs_sta_dbgfs_rate_scale_data_read,
3125        .open = simple_open,
3126        .llseek = default_llseek,
3127};
3128
3129static void rs_add_debugfs(void *mvm, void *mvm_sta, struct dentry *dir)
3130{
3131        struct iwl_lq_sta *lq_sta = mvm_sta;
3132        lq_sta->rs_sta_dbgfs_scale_table_file =
3133                debugfs_create_file("rate_scale_table", S_IRUSR | S_IWUSR, dir,
3134                                    lq_sta, &rs_sta_dbgfs_scale_table_ops);
3135        lq_sta->rs_sta_dbgfs_stats_table_file =
3136                debugfs_create_file("rate_stats_table", S_IRUSR, dir,
3137                                    lq_sta, &rs_sta_dbgfs_stats_table_ops);
3138        lq_sta->rs_sta_dbgfs_rate_scale_data_file =
3139                debugfs_create_file("rate_scale_data", S_IRUSR, dir,
3140                                    lq_sta, &rs_sta_dbgfs_rate_scale_data_ops);
3141        lq_sta->rs_sta_dbgfs_tx_agg_tid_en_file =
3142                debugfs_create_u8("tx_agg_tid_enable", S_IRUSR | S_IWUSR, dir,
3143                                  &lq_sta->tx_agg_tid_en);
3144}
3145
3146static void rs_remove_debugfs(void *mvm, void *mvm_sta)
3147{
3148        struct iwl_lq_sta *lq_sta = mvm_sta;
3149        debugfs_remove(lq_sta->rs_sta_dbgfs_scale_table_file);
3150        debugfs_remove(lq_sta->rs_sta_dbgfs_stats_table_file);
3151        debugfs_remove(lq_sta->rs_sta_dbgfs_rate_scale_data_file);
3152        debugfs_remove(lq_sta->rs_sta_dbgfs_tx_agg_tid_en_file);
3153}
3154#endif
3155
3156/*
3157 * Initialization of rate scaling information is done by driver after
3158 * the station is added. Since mac80211 calls this function before a
3159 * station is added we ignore it.
3160 */
3161static void rs_rate_init_stub(void *mvm_r,
3162                                 struct ieee80211_supported_band *sband,
3163                                 struct ieee80211_sta *sta, void *mvm_sta)
3164{
3165}
3166static struct rate_control_ops rs_mvm_ops = {
3167        .module = NULL,
3168        .name = RS_NAME,
3169        .tx_status = rs_tx_status,
3170        .get_rate = rs_get_rate,
3171        .rate_init = rs_rate_init_stub,
3172        .alloc = rs_alloc,
3173        .free = rs_free,
3174        .alloc_sta = rs_alloc_sta,
3175        .free_sta = rs_free_sta,
3176#ifdef CONFIG_MAC80211_DEBUGFS
3177        .add_sta_debugfs = rs_add_debugfs,
3178        .remove_sta_debugfs = rs_remove_debugfs,
3179#endif
3180};
3181
3182int iwl_mvm_rate_control_register(void)
3183{
3184        return ieee80211_rate_control_register(&rs_mvm_ops);
3185}
3186
3187void iwl_mvm_rate_control_unregister(void)
3188{
3189        ieee80211_rate_control_unregister(&rs_mvm_ops);
3190}
3191
3192/**
3193 * iwl_mvm_tx_protection - Gets LQ command, change it to enable/disable
3194 * Tx protection, according to this rquest and previous requests,
3195 * and send the LQ command.
3196 * @lq: The LQ command
3197 * @mvmsta: The station
3198 * @enable: Enable Tx protection?
3199 */
3200int iwl_mvm_tx_protection(struct iwl_mvm *mvm, struct iwl_lq_cmd *lq,
3201                          struct iwl_mvm_sta *mvmsta, bool enable)
3202{
3203        lockdep_assert_held(&mvm->mutex);
3204
3205        if (enable) {
3206                if (mvmsta->tx_protection == 0)
3207                        lq->flags |= LQ_FLAG_SET_STA_TLC_RTS_MSK;
3208                mvmsta->tx_protection++;
3209        } else {
3210                mvmsta->tx_protection--;
3211                if (mvmsta->tx_protection == 0)
3212                        lq->flags &= ~LQ_FLAG_SET_STA_TLC_RTS_MSK;
3213        }
3214
3215        return iwl_mvm_send_lq_cmd(mvm, lq, CMD_ASYNC, false);
3216}
3217