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