mac80211/minstrel_ht: fix spacing between sample attempts
[firefly-linux-kernel-4.4.55.git] / net / mac80211 / rc80211_minstrel_ht.c
1 /*
2  * Copyright (C) 2010-2013 Felix Fietkau <nbd@openwrt.org>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License version 2 as
6  * published by the Free Software Foundation.
7  */
8 #include <linux/netdevice.h>
9 #include <linux/types.h>
10 #include <linux/skbuff.h>
11 #include <linux/debugfs.h>
12 #include <linux/random.h>
13 #include <linux/ieee80211.h>
14 #include <net/mac80211.h>
15 #include "rate.h"
16 #include "rc80211_minstrel.h"
17 #include "rc80211_minstrel_ht.h"
18
19 #define AVG_PKT_SIZE    1200
20 #define SAMPLE_COLUMNS  10
21 #define EWMA_LEVEL              75
22
23 /* Number of bits for an average sized packet */
24 #define MCS_NBITS (AVG_PKT_SIZE << 3)
25
26 /* Number of symbols for a packet with (bps) bits per symbol */
27 #define MCS_NSYMS(bps) ((MCS_NBITS + (bps) - 1) / (bps))
28
29 /* Transmission time (nanoseconds) for a packet containing (syms) symbols */
30 #define MCS_SYMBOL_TIME(sgi, syms)                                      \
31         (sgi ?                                                          \
32           ((syms) * 18000 + 4000) / 5 : /* syms * 3.6 us */             \
33           ((syms) * 1000) << 2          /* syms * 4 us */               \
34         )
35
36 /* Transmit duration for the raw data part of an average sized packet */
37 #define MCS_DURATION(streams, sgi, bps) MCS_SYMBOL_TIME(sgi, MCS_NSYMS((streams) * (bps)))
38
39 /*
40  * Define group sort order: HT40 -> SGI -> #streams
41  */
42 #define GROUP_IDX(_streams, _sgi, _ht40)        \
43         MINSTREL_MAX_STREAMS * 2 * _ht40 +      \
44         MINSTREL_MAX_STREAMS * _sgi +           \
45         _streams - 1
46
47 /* MCS rate information for an MCS group */
48 #define MCS_GROUP(_streams, _sgi, _ht40)                                \
49         [GROUP_IDX(_streams, _sgi, _ht40)] = {                          \
50         .streams = _streams,                                            \
51         .flags =                                                        \
52                 (_sgi ? IEEE80211_TX_RC_SHORT_GI : 0) |                 \
53                 (_ht40 ? IEEE80211_TX_RC_40_MHZ_WIDTH : 0),             \
54         .duration = {                                                   \
55                 MCS_DURATION(_streams, _sgi, _ht40 ? 54 : 26),          \
56                 MCS_DURATION(_streams, _sgi, _ht40 ? 108 : 52),         \
57                 MCS_DURATION(_streams, _sgi, _ht40 ? 162 : 78),         \
58                 MCS_DURATION(_streams, _sgi, _ht40 ? 216 : 104),        \
59                 MCS_DURATION(_streams, _sgi, _ht40 ? 324 : 156),        \
60                 MCS_DURATION(_streams, _sgi, _ht40 ? 432 : 208),        \
61                 MCS_DURATION(_streams, _sgi, _ht40 ? 486 : 234),        \
62                 MCS_DURATION(_streams, _sgi, _ht40 ? 540 : 260)         \
63         }                                                               \
64 }
65
66 #define CCK_DURATION(_bitrate, _short, _len)            \
67         (1000 * (10 /* SIFS */ +                        \
68          (_short ? 72 + 24 : 144 + 48 ) +               \
69          (8 * (_len + 4) * 10) / (_bitrate)))
70
71 #define CCK_ACK_DURATION(_bitrate, _short)                      \
72         (CCK_DURATION((_bitrate > 10 ? 20 : 10), false, 60) +   \
73          CCK_DURATION(_bitrate, _short, AVG_PKT_SIZE))
74
75 #define CCK_DURATION_LIST(_short)                       \
76         CCK_ACK_DURATION(10, _short),                   \
77         CCK_ACK_DURATION(20, _short),                   \
78         CCK_ACK_DURATION(55, _short),                   \
79         CCK_ACK_DURATION(110, _short)
80
81 #define CCK_GROUP                                               \
82         [MINSTREL_MAX_STREAMS * MINSTREL_STREAM_GROUPS] = {     \
83                 .streams = 0,                                   \
84                 .duration = {                                   \
85                         CCK_DURATION_LIST(false),               \
86                         CCK_DURATION_LIST(true)                 \
87                 }                                               \
88         }
89
90 /*
91  * To enable sufficiently targeted rate sampling, MCS rates are divided into
92  * groups, based on the number of streams and flags (HT40, SGI) that they
93  * use.
94  *
95  * Sortorder has to be fixed for GROUP_IDX macro to be applicable:
96  * HT40 -> SGI -> #streams
97  */
98 const struct mcs_group minstrel_mcs_groups[] = {
99         MCS_GROUP(1, 0, 0),
100         MCS_GROUP(2, 0, 0),
101 #if MINSTREL_MAX_STREAMS >= 3
102         MCS_GROUP(3, 0, 0),
103 #endif
104
105         MCS_GROUP(1, 1, 0),
106         MCS_GROUP(2, 1, 0),
107 #if MINSTREL_MAX_STREAMS >= 3
108         MCS_GROUP(3, 1, 0),
109 #endif
110
111         MCS_GROUP(1, 0, 1),
112         MCS_GROUP(2, 0, 1),
113 #if MINSTREL_MAX_STREAMS >= 3
114         MCS_GROUP(3, 0, 1),
115 #endif
116
117         MCS_GROUP(1, 1, 1),
118         MCS_GROUP(2, 1, 1),
119 #if MINSTREL_MAX_STREAMS >= 3
120         MCS_GROUP(3, 1, 1),
121 #endif
122
123         /* must be last */
124         CCK_GROUP
125 };
126
127 #define MINSTREL_CCK_GROUP      (ARRAY_SIZE(minstrel_mcs_groups) - 1)
128
129 static u8 sample_table[SAMPLE_COLUMNS][MCS_GROUP_RATES];
130
131 /*
132  * Perform EWMA (Exponentially Weighted Moving Average) calculation
133  */
134 static int
135 minstrel_ewma(int old, int new, int weight)
136 {
137         return (new * (100 - weight) + old * weight) / 100;
138 }
139
140 /*
141  * Look up an MCS group index based on mac80211 rate information
142  */
143 static int
144 minstrel_ht_get_group_idx(struct ieee80211_tx_rate *rate)
145 {
146         return GROUP_IDX((rate->idx / MCS_GROUP_RATES) + 1,
147                          !!(rate->flags & IEEE80211_TX_RC_SHORT_GI),
148                          !!(rate->flags & IEEE80211_TX_RC_40_MHZ_WIDTH));
149 }
150
151 static struct minstrel_rate_stats *
152 minstrel_ht_get_stats(struct minstrel_priv *mp, struct minstrel_ht_sta *mi,
153                       struct ieee80211_tx_rate *rate)
154 {
155         int group, idx;
156
157         if (rate->flags & IEEE80211_TX_RC_MCS) {
158                 group = minstrel_ht_get_group_idx(rate);
159                 idx = rate->idx % MCS_GROUP_RATES;
160         } else {
161                 group = MINSTREL_CCK_GROUP;
162
163                 for (idx = 0; idx < ARRAY_SIZE(mp->cck_rates); idx++)
164                         if (rate->idx == mp->cck_rates[idx])
165                                 break;
166
167                 /* short preamble */
168                 if (!(mi->groups[group].supported & BIT(idx)))
169                         idx += 4;
170         }
171         return &mi->groups[group].rates[idx];
172 }
173
174 static inline struct minstrel_rate_stats *
175 minstrel_get_ratestats(struct minstrel_ht_sta *mi, int index)
176 {
177         return &mi->groups[index / MCS_GROUP_RATES].rates[index % MCS_GROUP_RATES];
178 }
179
180
181 /*
182  * Recalculate success probabilities and counters for a rate using EWMA
183  */
184 static void
185 minstrel_calc_rate_ewma(struct minstrel_rate_stats *mr)
186 {
187         if (unlikely(mr->attempts > 0)) {
188                 mr->sample_skipped = 0;
189                 mr->cur_prob = MINSTREL_FRAC(mr->success, mr->attempts);
190                 if (!mr->att_hist)
191                         mr->probability = mr->cur_prob;
192                 else
193                         mr->probability = minstrel_ewma(mr->probability,
194                                 mr->cur_prob, EWMA_LEVEL);
195                 mr->att_hist += mr->attempts;
196                 mr->succ_hist += mr->success;
197         } else {
198                 mr->sample_skipped++;
199         }
200         mr->last_success = mr->success;
201         mr->last_attempts = mr->attempts;
202         mr->success = 0;
203         mr->attempts = 0;
204 }
205
206 /*
207  * Calculate throughput based on the average A-MPDU length, taking into account
208  * the expected number of retransmissions and their expected length
209  */
210 static void
211 minstrel_ht_calc_tp(struct minstrel_ht_sta *mi, int group, int rate)
212 {
213         struct minstrel_rate_stats *mr;
214         unsigned int nsecs = 0;
215         unsigned int tp;
216
217         mr = &mi->groups[group].rates[rate];
218
219         if (mr->probability < MINSTREL_FRAC(1, 10)) {
220                 mr->cur_tp = 0;
221                 return;
222         }
223
224         if (group != MINSTREL_CCK_GROUP)
225                 nsecs = 1000 * mi->overhead / MINSTREL_TRUNC(mi->avg_ampdu_len);
226
227         nsecs += minstrel_mcs_groups[group].duration[rate];
228         tp = 1000000 * ((mr->probability * 1000) / nsecs);
229
230         mr->cur_tp = MINSTREL_TRUNC(tp);
231 }
232
233 /*
234  * Update rate statistics and select new primary rates
235  *
236  * Rules for rate selection:
237  *  - max_prob_rate must use only one stream, as a tradeoff between delivery
238  *    probability and throughput during strong fluctuations
239  *  - as long as the max prob rate has a probability of more than 3/4, pick
240  *    higher throughput rates, even if the probablity is a bit lower
241  */
242 static void
243 minstrel_ht_update_stats(struct minstrel_priv *mp, struct minstrel_ht_sta *mi)
244 {
245         struct minstrel_mcs_group_data *mg;
246         struct minstrel_rate_stats *mr;
247         int cur_prob, cur_prob_tp, cur_tp, cur_tp2;
248         int group, i, index;
249
250         if (mi->ampdu_packets > 0) {
251                 mi->avg_ampdu_len = minstrel_ewma(mi->avg_ampdu_len,
252                         MINSTREL_FRAC(mi->ampdu_len, mi->ampdu_packets), EWMA_LEVEL);
253                 mi->ampdu_len = 0;
254                 mi->ampdu_packets = 0;
255         }
256
257         mi->sample_slow = 0;
258         mi->sample_count = 0;
259         mi->max_tp_rate = 0;
260         mi->max_tp_rate2 = 0;
261         mi->max_prob_rate = 0;
262
263         for (group = 0; group < ARRAY_SIZE(minstrel_mcs_groups); group++) {
264                 cur_prob = 0;
265                 cur_prob_tp = 0;
266                 cur_tp = 0;
267                 cur_tp2 = 0;
268
269                 mg = &mi->groups[group];
270                 if (!mg->supported)
271                         continue;
272
273                 mg->max_tp_rate = 0;
274                 mg->max_tp_rate2 = 0;
275                 mg->max_prob_rate = 0;
276                 mi->sample_count++;
277
278                 for (i = 0; i < MCS_GROUP_RATES; i++) {
279                         if (!(mg->supported & BIT(i)))
280                                 continue;
281
282                         mr = &mg->rates[i];
283                         mr->retry_updated = false;
284                         index = MCS_GROUP_RATES * group + i;
285                         minstrel_calc_rate_ewma(mr);
286                         minstrel_ht_calc_tp(mi, group, i);
287
288                         if (!mr->cur_tp)
289                                 continue;
290
291                         if ((mr->cur_tp > cur_prob_tp && mr->probability >
292                              MINSTREL_FRAC(3, 4)) || mr->probability > cur_prob) {
293                                 mg->max_prob_rate = index;
294                                 cur_prob = mr->probability;
295                                 cur_prob_tp = mr->cur_tp;
296                         }
297
298                         if (mr->cur_tp > cur_tp) {
299                                 swap(index, mg->max_tp_rate);
300                                 cur_tp = mr->cur_tp;
301                                 mr = minstrel_get_ratestats(mi, index);
302                         }
303
304                         if (index >= mg->max_tp_rate)
305                                 continue;
306
307                         if (mr->cur_tp > cur_tp2) {
308                                 mg->max_tp_rate2 = index;
309                                 cur_tp2 = mr->cur_tp;
310                         }
311                 }
312         }
313
314         /* try to sample all available rates during each interval */
315         mi->sample_count *= 8;
316
317         cur_prob = 0;
318         cur_prob_tp = 0;
319         cur_tp = 0;
320         cur_tp2 = 0;
321         for (group = 0; group < ARRAY_SIZE(minstrel_mcs_groups); group++) {
322                 mg = &mi->groups[group];
323                 if (!mg->supported)
324                         continue;
325
326                 mr = minstrel_get_ratestats(mi, mg->max_tp_rate);
327                 if (cur_tp < mr->cur_tp) {
328                         mi->max_tp_rate2 = mi->max_tp_rate;
329                         cur_tp2 = cur_tp;
330                         mi->max_tp_rate = mg->max_tp_rate;
331                         cur_tp = mr->cur_tp;
332                         mi->max_prob_streams = minstrel_mcs_groups[group].streams - 1;
333                 }
334
335                 mr = minstrel_get_ratestats(mi, mg->max_tp_rate2);
336                 if (cur_tp2 < mr->cur_tp) {
337                         mi->max_tp_rate2 = mg->max_tp_rate2;
338                         cur_tp2 = mr->cur_tp;
339                 }
340         }
341
342         if (mi->max_prob_streams < 1)
343                 mi->max_prob_streams = 1;
344
345         for (group = 0; group < ARRAY_SIZE(minstrel_mcs_groups); group++) {
346                 mg = &mi->groups[group];
347                 if (!mg->supported)
348                         continue;
349                 mr = minstrel_get_ratestats(mi, mg->max_prob_rate);
350                 if (cur_prob_tp < mr->cur_tp &&
351                     minstrel_mcs_groups[group].streams <= mi->max_prob_streams) {
352                         mi->max_prob_rate = mg->max_prob_rate;
353                         cur_prob = mr->cur_prob;
354                         cur_prob_tp = mr->cur_tp;
355                 }
356         }
357
358
359         mi->stats_update = jiffies;
360 }
361
362 static bool
363 minstrel_ht_txstat_valid(struct minstrel_priv *mp, struct ieee80211_tx_rate *rate)
364 {
365         if (rate->idx < 0)
366                 return false;
367
368         if (!rate->count)
369                 return false;
370
371         if (rate->flags & IEEE80211_TX_RC_MCS)
372                 return true;
373
374         return rate->idx == mp->cck_rates[0] ||
375                rate->idx == mp->cck_rates[1] ||
376                rate->idx == mp->cck_rates[2] ||
377                rate->idx == mp->cck_rates[3];
378 }
379
380 static void
381 minstrel_next_sample_idx(struct minstrel_ht_sta *mi)
382 {
383         struct minstrel_mcs_group_data *mg;
384
385         for (;;) {
386                 mi->sample_group++;
387                 mi->sample_group %= ARRAY_SIZE(minstrel_mcs_groups);
388                 mg = &mi->groups[mi->sample_group];
389
390                 if (!mg->supported)
391                         continue;
392
393                 if (++mg->index >= MCS_GROUP_RATES) {
394                         mg->index = 0;
395                         if (++mg->column >= ARRAY_SIZE(sample_table))
396                                 mg->column = 0;
397                 }
398                 break;
399         }
400 }
401
402 static void
403 minstrel_downgrade_rate(struct minstrel_ht_sta *mi, unsigned int *idx,
404                         bool primary)
405 {
406         int group, orig_group;
407
408         orig_group = group = *idx / MCS_GROUP_RATES;
409         while (group > 0) {
410                 group--;
411
412                 if (!mi->groups[group].supported)
413                         continue;
414
415                 if (minstrel_mcs_groups[group].streams >
416                     minstrel_mcs_groups[orig_group].streams)
417                         continue;
418
419                 if (primary)
420                         *idx = mi->groups[group].max_tp_rate;
421                 else
422                         *idx = mi->groups[group].max_tp_rate2;
423                 break;
424         }
425 }
426
427 static void
428 minstrel_aggr_check(struct ieee80211_sta *pubsta, struct sk_buff *skb)
429 {
430         struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) skb->data;
431         struct sta_info *sta = container_of(pubsta, struct sta_info, sta);
432         u16 tid;
433
434         if (unlikely(!ieee80211_is_data_qos(hdr->frame_control)))
435                 return;
436
437         if (unlikely(skb->protocol == cpu_to_be16(ETH_P_PAE)))
438                 return;
439
440         tid = *ieee80211_get_qos_ctl(hdr) & IEEE80211_QOS_CTL_TID_MASK;
441         if (likely(sta->ampdu_mlme.tid_tx[tid]))
442                 return;
443
444         if (skb_get_queue_mapping(skb) == IEEE80211_AC_VO)
445                 return;
446
447         ieee80211_start_tx_ba_session(pubsta, tid, 5000);
448 }
449
450 static void
451 minstrel_ht_tx_status(void *priv, struct ieee80211_supported_band *sband,
452                       struct ieee80211_sta *sta, void *priv_sta,
453                       struct sk_buff *skb)
454 {
455         struct minstrel_ht_sta_priv *msp = priv_sta;
456         struct minstrel_ht_sta *mi = &msp->ht;
457         struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
458         struct ieee80211_tx_rate *ar = info->status.rates;
459         struct minstrel_rate_stats *rate, *rate2;
460         struct minstrel_priv *mp = priv;
461         bool last;
462         int i;
463
464         if (!msp->is_ht)
465                 return mac80211_minstrel.tx_status(priv, sband, sta, &msp->legacy, skb);
466
467         /* This packet was aggregated but doesn't carry status info */
468         if ((info->flags & IEEE80211_TX_CTL_AMPDU) &&
469             !(info->flags & IEEE80211_TX_STAT_AMPDU))
470                 return;
471
472         if (!(info->flags & IEEE80211_TX_STAT_AMPDU)) {
473                 info->status.ampdu_ack_len =
474                         (info->flags & IEEE80211_TX_STAT_ACK ? 1 : 0);
475                 info->status.ampdu_len = 1;
476         }
477
478         mi->ampdu_packets++;
479         mi->ampdu_len += info->status.ampdu_len;
480
481         if (!mi->sample_wait && !mi->sample_tries && mi->sample_count > 0) {
482                 mi->sample_wait = 16 + 2 * MINSTREL_TRUNC(mi->avg_ampdu_len);
483                 mi->sample_tries = 2;
484                 mi->sample_count--;
485         }
486
487         if (info->flags & IEEE80211_TX_CTL_RATE_CTRL_PROBE)
488                 mi->sample_packets += info->status.ampdu_len;
489
490         last = !minstrel_ht_txstat_valid(mp, &ar[0]);
491         for (i = 0; !last; i++) {
492                 last = (i == IEEE80211_TX_MAX_RATES - 1) ||
493                        !minstrel_ht_txstat_valid(mp, &ar[i + 1]);
494
495                 rate = minstrel_ht_get_stats(mp, mi, &ar[i]);
496
497                 if (last)
498                         rate->success += info->status.ampdu_ack_len;
499
500                 rate->attempts += ar[i].count * info->status.ampdu_len;
501         }
502
503         /*
504          * check for sudden death of spatial multiplexing,
505          * downgrade to a lower number of streams if necessary.
506          */
507         rate = minstrel_get_ratestats(mi, mi->max_tp_rate);
508         if (rate->attempts > 30 &&
509             MINSTREL_FRAC(rate->success, rate->attempts) <
510             MINSTREL_FRAC(20, 100))
511                 minstrel_downgrade_rate(mi, &mi->max_tp_rate, true);
512
513         rate2 = minstrel_get_ratestats(mi, mi->max_tp_rate2);
514         if (rate2->attempts > 30 &&
515             MINSTREL_FRAC(rate2->success, rate2->attempts) <
516             MINSTREL_FRAC(20, 100))
517                 minstrel_downgrade_rate(mi, &mi->max_tp_rate2, false);
518
519         if (time_after(jiffies, mi->stats_update + (mp->update_interval / 2 * HZ) / 1000)) {
520                 minstrel_ht_update_stats(mp, mi);
521                 if (!(info->flags & IEEE80211_TX_CTL_AMPDU) &&
522                     mi->max_prob_rate / MCS_GROUP_RATES != MINSTREL_CCK_GROUP)
523                         minstrel_aggr_check(sta, skb);
524         }
525 }
526
527 static void
528 minstrel_calc_retransmit(struct minstrel_priv *mp, struct minstrel_ht_sta *mi,
529                          int index)
530 {
531         struct minstrel_rate_stats *mr;
532         const struct mcs_group *group;
533         unsigned int tx_time, tx_time_rtscts, tx_time_data;
534         unsigned int cw = mp->cw_min;
535         unsigned int ctime = 0;
536         unsigned int t_slot = 9; /* FIXME */
537         unsigned int ampdu_len = MINSTREL_TRUNC(mi->avg_ampdu_len);
538         unsigned int overhead = 0, overhead_rtscts = 0;
539
540         mr = minstrel_get_ratestats(mi, index);
541         if (mr->probability < MINSTREL_FRAC(1, 10)) {
542                 mr->retry_count = 1;
543                 mr->retry_count_rtscts = 1;
544                 return;
545         }
546
547         mr->retry_count = 2;
548         mr->retry_count_rtscts = 2;
549         mr->retry_updated = true;
550
551         group = &minstrel_mcs_groups[index / MCS_GROUP_RATES];
552         tx_time_data = group->duration[index % MCS_GROUP_RATES] * ampdu_len / 1000;
553
554         /* Contention time for first 2 tries */
555         ctime = (t_slot * cw) >> 1;
556         cw = min((cw << 1) | 1, mp->cw_max);
557         ctime += (t_slot * cw) >> 1;
558         cw = min((cw << 1) | 1, mp->cw_max);
559
560         if (index / MCS_GROUP_RATES != MINSTREL_CCK_GROUP) {
561                 overhead = mi->overhead;
562                 overhead_rtscts = mi->overhead_rtscts;
563         }
564
565         /* Total TX time for data and Contention after first 2 tries */
566         tx_time = ctime + 2 * (overhead + tx_time_data);
567         tx_time_rtscts = ctime + 2 * (overhead_rtscts + tx_time_data);
568
569         /* See how many more tries we can fit inside segment size */
570         do {
571                 /* Contention time for this try */
572                 ctime = (t_slot * cw) >> 1;
573                 cw = min((cw << 1) | 1, mp->cw_max);
574
575                 /* Total TX time after this try */
576                 tx_time += ctime + overhead + tx_time_data;
577                 tx_time_rtscts += ctime + overhead_rtscts + tx_time_data;
578
579                 if (tx_time_rtscts < mp->segment_size)
580                         mr->retry_count_rtscts++;
581         } while ((tx_time < mp->segment_size) &&
582                  (++mr->retry_count < mp->max_retry));
583 }
584
585
586 static void
587 minstrel_ht_set_rate(struct minstrel_priv *mp, struct minstrel_ht_sta *mi,
588                      struct ieee80211_tx_rate *rate, int index,
589                      bool sample, bool rtscts)
590 {
591         const struct mcs_group *group = &minstrel_mcs_groups[index / MCS_GROUP_RATES];
592         struct minstrel_rate_stats *mr;
593
594         mr = minstrel_get_ratestats(mi, index);
595         if (!mr->retry_updated)
596                 minstrel_calc_retransmit(mp, mi, index);
597
598         if (sample)
599                 rate->count = 1;
600         else if (mr->probability < MINSTREL_FRAC(20, 100))
601                 rate->count = 2;
602         else if (rtscts)
603                 rate->count = mr->retry_count_rtscts;
604         else
605                 rate->count = mr->retry_count;
606
607         rate->flags = 0;
608         if (rtscts)
609                 rate->flags |= IEEE80211_TX_RC_USE_RTS_CTS;
610
611         if (index / MCS_GROUP_RATES == MINSTREL_CCK_GROUP) {
612                 rate->idx = mp->cck_rates[index % ARRAY_SIZE(mp->cck_rates)];
613                 return;
614         }
615
616         rate->flags |= IEEE80211_TX_RC_MCS | group->flags;
617         rate->idx = index % MCS_GROUP_RATES + (group->streams - 1) * MCS_GROUP_RATES;
618 }
619
620 static inline int
621 minstrel_get_duration(int index)
622 {
623         const struct mcs_group *group = &minstrel_mcs_groups[index / MCS_GROUP_RATES];
624         return group->duration[index % MCS_GROUP_RATES];
625 }
626
627 static int
628 minstrel_get_sample_rate(struct minstrel_priv *mp, struct minstrel_ht_sta *mi)
629 {
630         struct minstrel_rate_stats *mr;
631         struct minstrel_mcs_group_data *mg;
632         unsigned int sample_dur, sample_group;
633         int sample_idx = 0;
634
635         if (mi->sample_wait > 0) {
636                 mi->sample_wait--;
637                 return -1;
638         }
639
640         if (!mi->sample_tries)
641                 return -1;
642
643         mg = &mi->groups[mi->sample_group];
644         sample_idx = sample_table[mg->column][mg->index];
645         mr = &mg->rates[sample_idx];
646         sample_group = mi->sample_group;
647         sample_idx += sample_group * MCS_GROUP_RATES;
648         minstrel_next_sample_idx(mi);
649
650         /*
651          * Sampling might add some overhead (RTS, no aggregation)
652          * to the frame. Hence, don't use sampling for the currently
653          * used max TP rate.
654          */
655         if (sample_idx == mi->max_tp_rate)
656                 return -1;
657         /*
658          * When not using MRR, do not sample if the probability is already
659          * higher than 95% to avoid wasting airtime
660          */
661         if (!mp->has_mrr && (mr->probability > MINSTREL_FRAC(95, 100)))
662                 return -1;
663
664         /*
665          * Make sure that lower rates get sampled only occasionally,
666          * if the link is working perfectly.
667          */
668         sample_dur = minstrel_get_duration(sample_idx);
669         if (sample_dur >= minstrel_get_duration(mi->max_tp_rate2) &&
670             (mi->max_prob_streams <
671              minstrel_mcs_groups[sample_group].streams ||
672              sample_dur >= minstrel_get_duration(mi->max_prob_rate))) {
673                 if (mr->sample_skipped < 20)
674                         return -1;
675
676                 if (mi->sample_slow++ > 2)
677                         return -1;
678         }
679         mi->sample_tries--;
680
681         return sample_idx;
682 }
683
684 static void
685 minstrel_ht_check_cck_shortpreamble(struct minstrel_priv *mp,
686                                     struct minstrel_ht_sta *mi, bool val)
687 {
688         u8 supported = mi->groups[MINSTREL_CCK_GROUP].supported;
689
690         if (!supported || !mi->cck_supported_short)
691                 return;
692
693         if (supported & (mi->cck_supported_short << (val * 4)))
694                 return;
695
696         supported ^= mi->cck_supported_short | (mi->cck_supported_short << 4);
697         mi->groups[MINSTREL_CCK_GROUP].supported = supported;
698 }
699
700 static void
701 minstrel_ht_get_rate(void *priv, struct ieee80211_sta *sta, void *priv_sta,
702                      struct ieee80211_tx_rate_control *txrc)
703 {
704         struct ieee80211_tx_info *info = IEEE80211_SKB_CB(txrc->skb);
705         struct ieee80211_tx_rate *ar = info->status.rates;
706         struct minstrel_ht_sta_priv *msp = priv_sta;
707         struct minstrel_ht_sta *mi = &msp->ht;
708         struct minstrel_priv *mp = priv;
709         int sample_idx;
710         bool sample = false;
711
712         if (rate_control_send_low(sta, priv_sta, txrc))
713                 return;
714
715         if (!msp->is_ht)
716                 return mac80211_minstrel.get_rate(priv, sta, &msp->legacy, txrc);
717
718         info->flags |= mi->tx_flags;
719         minstrel_ht_check_cck_shortpreamble(mp, mi, txrc->short_preamble);
720
721         /* Don't use EAPOL frames for sampling on non-mrr hw */
722         if (mp->hw->max_rates == 1 &&
723             txrc->skb->protocol == cpu_to_be16(ETH_P_PAE))
724                 sample_idx = -1;
725         else
726                 sample_idx = minstrel_get_sample_rate(mp, mi);
727
728 #ifdef CONFIG_MAC80211_DEBUGFS
729         /* use fixed index if set */
730         if (mp->fixed_rate_idx != -1) {
731                 mi->max_tp_rate = mp->fixed_rate_idx;
732                 mi->max_tp_rate2 = mp->fixed_rate_idx;
733                 mi->max_prob_rate = mp->fixed_rate_idx;
734                 sample_idx = -1;
735         }
736 #endif
737
738         if (sample_idx >= 0) {
739                 sample = true;
740                 minstrel_ht_set_rate(mp, mi, &ar[0], sample_idx,
741                         true, false);
742                 info->flags |= IEEE80211_TX_CTL_RATE_CTRL_PROBE;
743         } else {
744                 minstrel_ht_set_rate(mp, mi, &ar[0], mi->max_tp_rate,
745                         false, false);
746         }
747
748         if (mp->hw->max_rates >= 3) {
749                 /*
750                  * At least 3 tx rates supported, use
751                  * sample_rate -> max_tp_rate -> max_prob_rate for sampling and
752                  * max_tp_rate -> max_tp_rate2 -> max_prob_rate by default.
753                  */
754                 if (sample_idx >= 0)
755                         minstrel_ht_set_rate(mp, mi, &ar[1], mi->max_tp_rate,
756                                 false, false);
757                 else
758                         minstrel_ht_set_rate(mp, mi, &ar[1], mi->max_tp_rate2,
759                                 false, true);
760
761                 minstrel_ht_set_rate(mp, mi, &ar[2], mi->max_prob_rate,
762                                      false, !sample);
763
764                 ar[3].count = 0;
765                 ar[3].idx = -1;
766         } else if (mp->hw->max_rates == 2) {
767                 /*
768                  * Only 2 tx rates supported, use
769                  * sample_rate -> max_prob_rate for sampling and
770                  * max_tp_rate -> max_prob_rate by default.
771                  */
772                 minstrel_ht_set_rate(mp, mi, &ar[1], mi->max_prob_rate,
773                                      false, !sample);
774
775                 ar[2].count = 0;
776                 ar[2].idx = -1;
777         } else {
778                 /* Not using MRR, only use the first rate */
779                 ar[1].count = 0;
780                 ar[1].idx = -1;
781         }
782
783         mi->total_packets++;
784
785         /* wraparound */
786         if (mi->total_packets == ~0) {
787                 mi->total_packets = 0;
788                 mi->sample_packets = 0;
789         }
790 }
791
792 static void
793 minstrel_ht_update_cck(struct minstrel_priv *mp, struct minstrel_ht_sta *mi,
794                        struct ieee80211_supported_band *sband,
795                        struct ieee80211_sta *sta)
796 {
797         int i;
798
799         if (sband->band != IEEE80211_BAND_2GHZ)
800                 return;
801
802         mi->cck_supported = 0;
803         mi->cck_supported_short = 0;
804         for (i = 0; i < 4; i++) {
805                 if (!rate_supported(sta, sband->band, mp->cck_rates[i]))
806                         continue;
807
808                 mi->cck_supported |= BIT(i);
809                 if (sband->bitrates[i].flags & IEEE80211_RATE_SHORT_PREAMBLE)
810                         mi->cck_supported_short |= BIT(i);
811         }
812
813         mi->groups[MINSTREL_CCK_GROUP].supported = mi->cck_supported;
814 }
815
816 static void
817 minstrel_ht_update_caps(void *priv, struct ieee80211_supported_band *sband,
818                         struct ieee80211_sta *sta, void *priv_sta)
819 {
820         struct minstrel_priv *mp = priv;
821         struct minstrel_ht_sta_priv *msp = priv_sta;
822         struct minstrel_ht_sta *mi = &msp->ht;
823         struct ieee80211_mcs_info *mcs = &sta->ht_cap.mcs;
824         u16 sta_cap = sta->ht_cap.cap;
825         int n_supported = 0;
826         int ack_dur;
827         int stbc;
828         int i;
829
830         /* fall back to the old minstrel for legacy stations */
831         if (!sta->ht_cap.ht_supported)
832                 goto use_legacy;
833
834         BUILD_BUG_ON(ARRAY_SIZE(minstrel_mcs_groups) !=
835                 MINSTREL_MAX_STREAMS * MINSTREL_STREAM_GROUPS + 1);
836
837         msp->is_ht = true;
838         memset(mi, 0, sizeof(*mi));
839         mi->stats_update = jiffies;
840
841         ack_dur = ieee80211_frame_duration(sband->band, 10, 60, 1, 1);
842         mi->overhead = ieee80211_frame_duration(sband->band, 0, 60, 1, 1) + ack_dur;
843         mi->overhead_rtscts = mi->overhead + 2 * ack_dur;
844
845         mi->avg_ampdu_len = MINSTREL_FRAC(1, 1);
846
847         /* When using MRR, sample more on the first attempt, without delay */
848         if (mp->has_mrr) {
849                 mi->sample_count = 16;
850                 mi->sample_wait = 0;
851         } else {
852                 mi->sample_count = 8;
853                 mi->sample_wait = 8;
854         }
855         mi->sample_tries = 4;
856
857         stbc = (sta_cap & IEEE80211_HT_CAP_RX_STBC) >>
858                 IEEE80211_HT_CAP_RX_STBC_SHIFT;
859         mi->tx_flags |= stbc << IEEE80211_TX_CTL_STBC_SHIFT;
860
861         if (sta_cap & IEEE80211_HT_CAP_LDPC_CODING)
862                 mi->tx_flags |= IEEE80211_TX_CTL_LDPC;
863
864         for (i = 0; i < ARRAY_SIZE(mi->groups); i++) {
865                 mi->groups[i].supported = 0;
866                 if (i == MINSTREL_CCK_GROUP) {
867                         minstrel_ht_update_cck(mp, mi, sband, sta);
868                         continue;
869                 }
870
871                 if (minstrel_mcs_groups[i].flags & IEEE80211_TX_RC_SHORT_GI) {
872                         if (minstrel_mcs_groups[i].flags & IEEE80211_TX_RC_40_MHZ_WIDTH) {
873                                 if (!(sta_cap & IEEE80211_HT_CAP_SGI_40))
874                                         continue;
875                         } else {
876                                 if (!(sta_cap & IEEE80211_HT_CAP_SGI_20))
877                                         continue;
878                         }
879                 }
880
881                 if (minstrel_mcs_groups[i].flags & IEEE80211_TX_RC_40_MHZ_WIDTH &&
882                     sta->bandwidth < IEEE80211_STA_RX_BW_40)
883                         continue;
884
885                 /* Mark MCS > 7 as unsupported if STA is in static SMPS mode */
886                 if (sta->smps_mode == IEEE80211_SMPS_STATIC &&
887                     minstrel_mcs_groups[i].streams > 1)
888                         continue;
889
890                 mi->groups[i].supported =
891                         mcs->rx_mask[minstrel_mcs_groups[i].streams - 1];
892
893                 if (mi->groups[i].supported)
894                         n_supported++;
895         }
896
897         if (!n_supported)
898                 goto use_legacy;
899
900         return;
901
902 use_legacy:
903         msp->is_ht = false;
904         memset(&msp->legacy, 0, sizeof(msp->legacy));
905         msp->legacy.r = msp->ratelist;
906         msp->legacy.sample_table = msp->sample_table;
907         return mac80211_minstrel.rate_init(priv, sband, sta, &msp->legacy);
908 }
909
910 static void
911 minstrel_ht_rate_init(void *priv, struct ieee80211_supported_band *sband,
912                       struct ieee80211_sta *sta, void *priv_sta)
913 {
914         minstrel_ht_update_caps(priv, sband, sta, priv_sta);
915 }
916
917 static void
918 minstrel_ht_rate_update(void *priv, struct ieee80211_supported_band *sband,
919                         struct ieee80211_sta *sta, void *priv_sta,
920                         u32 changed)
921 {
922         minstrel_ht_update_caps(priv, sband, sta, priv_sta);
923 }
924
925 static void *
926 minstrel_ht_alloc_sta(void *priv, struct ieee80211_sta *sta, gfp_t gfp)
927 {
928         struct ieee80211_supported_band *sband;
929         struct minstrel_ht_sta_priv *msp;
930         struct minstrel_priv *mp = priv;
931         struct ieee80211_hw *hw = mp->hw;
932         int max_rates = 0;
933         int i;
934
935         for (i = 0; i < IEEE80211_NUM_BANDS; i++) {
936                 sband = hw->wiphy->bands[i];
937                 if (sband && sband->n_bitrates > max_rates)
938                         max_rates = sband->n_bitrates;
939         }
940
941         msp = kzalloc(sizeof(*msp), gfp);
942         if (!msp)
943                 return NULL;
944
945         msp->ratelist = kzalloc(sizeof(struct minstrel_rate) * max_rates, gfp);
946         if (!msp->ratelist)
947                 goto error;
948
949         msp->sample_table = kmalloc(SAMPLE_COLUMNS * max_rates, gfp);
950         if (!msp->sample_table)
951                 goto error1;
952
953         return msp;
954
955 error1:
956         kfree(msp->ratelist);
957 error:
958         kfree(msp);
959         return NULL;
960 }
961
962 static void
963 minstrel_ht_free_sta(void *priv, struct ieee80211_sta *sta, void *priv_sta)
964 {
965         struct minstrel_ht_sta_priv *msp = priv_sta;
966
967         kfree(msp->sample_table);
968         kfree(msp->ratelist);
969         kfree(msp);
970 }
971
972 static void *
973 minstrel_ht_alloc(struct ieee80211_hw *hw, struct dentry *debugfsdir)
974 {
975         return mac80211_minstrel.alloc(hw, debugfsdir);
976 }
977
978 static void
979 minstrel_ht_free(void *priv)
980 {
981         mac80211_minstrel.free(priv);
982 }
983
984 static struct rate_control_ops mac80211_minstrel_ht = {
985         .name = "minstrel_ht",
986         .tx_status = minstrel_ht_tx_status,
987         .get_rate = minstrel_ht_get_rate,
988         .rate_init = minstrel_ht_rate_init,
989         .rate_update = minstrel_ht_rate_update,
990         .alloc_sta = minstrel_ht_alloc_sta,
991         .free_sta = minstrel_ht_free_sta,
992         .alloc = minstrel_ht_alloc,
993         .free = minstrel_ht_free,
994 #ifdef CONFIG_MAC80211_DEBUGFS
995         .add_sta_debugfs = minstrel_ht_add_sta_debugfs,
996         .remove_sta_debugfs = minstrel_ht_remove_sta_debugfs,
997 #endif
998 };
999
1000
1001 static void
1002 init_sample_table(void)
1003 {
1004         int col, i, new_idx;
1005         u8 rnd[MCS_GROUP_RATES];
1006
1007         memset(sample_table, 0xff, sizeof(sample_table));
1008         for (col = 0; col < SAMPLE_COLUMNS; col++) {
1009                 for (i = 0; i < MCS_GROUP_RATES; i++) {
1010                         get_random_bytes(rnd, sizeof(rnd));
1011                         new_idx = (i + rnd[i]) % MCS_GROUP_RATES;
1012
1013                         while (sample_table[col][new_idx] != 0xff)
1014                                 new_idx = (new_idx + 1) % MCS_GROUP_RATES;
1015
1016                         sample_table[col][new_idx] = i;
1017                 }
1018         }
1019 }
1020
1021 int __init
1022 rc80211_minstrel_ht_init(void)
1023 {
1024         init_sample_table();
1025         return ieee80211_rate_control_register(&mac80211_minstrel_ht);
1026 }
1027
1028 void
1029 rc80211_minstrel_ht_exit(void)
1030 {
1031         ieee80211_rate_control_unregister(&mac80211_minstrel_ht);
1032 }