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