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