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