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