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