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