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