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