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