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