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