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