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