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