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