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