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