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