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