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