1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2010-2013 Felix Fietkau <nbd@openwrt.org>
4  * Copyright (C) 2019-2020 Intel Corporation
5  */
6 #include <linux/netdevice.h>
7 #include <linux/types.h>
8 #include <linux/skbuff.h>
9 #include <linux/debugfs.h>
10 #include <linux/random.h>
11 #include <linux/moduleparam.h>
12 #include <linux/ieee80211.h>
13 #include <net/mac80211.h>
14 #include "rate.h"
15 #include "sta_info.h"
16 #include "rc80211_minstrel_ht.h"
17 
18 #define AVG_AMPDU_SIZE	16
19 #define AVG_PKT_SIZE	1200
20 
21 #define SAMPLE_SWITCH_THR	100
22 
23 /* Number of bits for an average sized packet */
24 #define MCS_NBITS ((AVG_PKT_SIZE * AVG_AMPDU_SIZE) << 3)
25 
26 /* Number of symbols for a packet with (bps) bits per symbol */
27 #define MCS_NSYMS(bps) DIV_ROUND_UP(MCS_NBITS, (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) \
38 	(MCS_SYMBOL_TIME(sgi, MCS_NSYMS((streams) * (bps))) / AVG_AMPDU_SIZE)
39 
40 #define BW_20			0
41 #define BW_40			1
42 #define BW_80			2
43 
44 /*
45  * Define group sort order: HT40 -> SGI -> #streams
46  */
47 #define GROUP_IDX(_streams, _sgi, _ht40)	\
48 	MINSTREL_HT_GROUP_0 +			\
49 	MINSTREL_MAX_STREAMS * 2 * _ht40 +	\
50 	MINSTREL_MAX_STREAMS * _sgi +	\
51 	_streams - 1
52 
53 #define _MAX(a, b) (((a)>(b))?(a):(b))
54 
55 #define GROUP_SHIFT(duration)						\
56 	_MAX(0, 16 - __builtin_clz(duration))
57 
58 /* MCS rate information for an MCS group */
59 #define __MCS_GROUP(_streams, _sgi, _ht40, _s)				\
60 	[GROUP_IDX(_streams, _sgi, _ht40)] = {				\
61 	.streams = _streams,						\
62 	.shift = _s,							\
63 	.bw = _ht40,							\
64 	.flags =							\
65 		IEEE80211_TX_RC_MCS |					\
66 		(_sgi ? IEEE80211_TX_RC_SHORT_GI : 0) |			\
67 		(_ht40 ? IEEE80211_TX_RC_40_MHZ_WIDTH : 0),		\
68 	.duration = {							\
69 		MCS_DURATION(_streams, _sgi, _ht40 ? 54 : 26) >> _s,	\
70 		MCS_DURATION(_streams, _sgi, _ht40 ? 108 : 52) >> _s,	\
71 		MCS_DURATION(_streams, _sgi, _ht40 ? 162 : 78) >> _s,	\
72 		MCS_DURATION(_streams, _sgi, _ht40 ? 216 : 104) >> _s,	\
73 		MCS_DURATION(_streams, _sgi, _ht40 ? 324 : 156) >> _s,	\
74 		MCS_DURATION(_streams, _sgi, _ht40 ? 432 : 208) >> _s,	\
75 		MCS_DURATION(_streams, _sgi, _ht40 ? 486 : 234) >> _s,	\
76 		MCS_DURATION(_streams, _sgi, _ht40 ? 540 : 260) >> _s	\
77 	}								\
78 }
79 
80 #define MCS_GROUP_SHIFT(_streams, _sgi, _ht40)				\
81 	GROUP_SHIFT(MCS_DURATION(_streams, _sgi, _ht40 ? 54 : 26))
82 
83 #define MCS_GROUP(_streams, _sgi, _ht40)				\
84 	__MCS_GROUP(_streams, _sgi, _ht40,				\
85 		    MCS_GROUP_SHIFT(_streams, _sgi, _ht40))
86 
87 #define VHT_GROUP_IDX(_streams, _sgi, _bw)				\
88 	(MINSTREL_VHT_GROUP_0 +						\
89 	 MINSTREL_MAX_STREAMS * 2 * (_bw) +				\
90 	 MINSTREL_MAX_STREAMS * (_sgi) +				\
91 	 (_streams) - 1)
92 
93 #define BW2VBPS(_bw, r3, r2, r1)					\
94 	(_bw == BW_80 ? r3 : _bw == BW_40 ? r2 : r1)
95 
96 #define __VHT_GROUP(_streams, _sgi, _bw, _s)				\
97 	[VHT_GROUP_IDX(_streams, _sgi, _bw)] = {			\
98 	.streams = _streams,						\
99 	.shift = _s,							\
100 	.bw = _bw,							\
101 	.flags =							\
102 		IEEE80211_TX_RC_VHT_MCS |				\
103 		(_sgi ? IEEE80211_TX_RC_SHORT_GI : 0) |			\
104 		(_bw == BW_80 ? IEEE80211_TX_RC_80_MHZ_WIDTH :		\
105 		 _bw == BW_40 ? IEEE80211_TX_RC_40_MHZ_WIDTH : 0),	\
106 	.duration = {							\
107 		MCS_DURATION(_streams, _sgi,				\
108 			     BW2VBPS(_bw,  117,  54,  26)) >> _s,	\
109 		MCS_DURATION(_streams, _sgi,				\
110 			     BW2VBPS(_bw,  234, 108,  52)) >> _s,	\
111 		MCS_DURATION(_streams, _sgi,				\
112 			     BW2VBPS(_bw,  351, 162,  78)) >> _s,	\
113 		MCS_DURATION(_streams, _sgi,				\
114 			     BW2VBPS(_bw,  468, 216, 104)) >> _s,	\
115 		MCS_DURATION(_streams, _sgi,				\
116 			     BW2VBPS(_bw,  702, 324, 156)) >> _s,	\
117 		MCS_DURATION(_streams, _sgi,				\
118 			     BW2VBPS(_bw,  936, 432, 208)) >> _s,	\
119 		MCS_DURATION(_streams, _sgi,				\
120 			     BW2VBPS(_bw, 1053, 486, 234)) >> _s,	\
121 		MCS_DURATION(_streams, _sgi,				\
122 			     BW2VBPS(_bw, 1170, 540, 260)) >> _s,	\
123 		MCS_DURATION(_streams, _sgi,				\
124 			     BW2VBPS(_bw, 1404, 648, 312)) >> _s,	\
125 		MCS_DURATION(_streams, _sgi,				\
126 			     BW2VBPS(_bw, 1560, 720, 346)) >> _s	\
127 	}								\
128 }
129 
130 #define VHT_GROUP_SHIFT(_streams, _sgi, _bw)				\
131 	GROUP_SHIFT(MCS_DURATION(_streams, _sgi,			\
132 				 BW2VBPS(_bw,  117,  54,  26)))
133 
134 #define VHT_GROUP(_streams, _sgi, _bw)					\
135 	__VHT_GROUP(_streams, _sgi, _bw,				\
136 		    VHT_GROUP_SHIFT(_streams, _sgi, _bw))
137 
138 #define CCK_DURATION(_bitrate, _short)			\
139 	(1000 * (10 /* SIFS */ +			\
140 	 (_short ? 72 + 24 : 144 + 48) +		\
141 	 (8 * (AVG_PKT_SIZE + 4) * 10) / (_bitrate)))
142 
143 #define CCK_DURATION_LIST(_short, _s)			\
144 	CCK_DURATION(10, _short) >> _s,			\
145 	CCK_DURATION(20, _short) >> _s,			\
146 	CCK_DURATION(55, _short) >> _s,			\
147 	CCK_DURATION(110, _short) >> _s
148 
149 #define __CCK_GROUP(_s)					\
150 	[MINSTREL_CCK_GROUP] = {			\
151 		.streams = 1,				\
152 		.flags = 0,				\
153 		.shift = _s,				\
154 		.duration = {				\
155 			CCK_DURATION_LIST(false, _s),	\
156 			CCK_DURATION_LIST(true, _s)	\
157 		}					\
158 	}
159 
160 #define CCK_GROUP_SHIFT					\
161 	GROUP_SHIFT(CCK_DURATION(10, false))
162 
163 #define CCK_GROUP __CCK_GROUP(CCK_GROUP_SHIFT)
164 
165 #define OFDM_DURATION(_bitrate)				\
166 	(1000 * (16 /* SIFS + signal ext */ +		\
167 	 16 /* T_PREAMBLE */ +				\
168 	 4 /* T_SIGNAL */ +				\
169 	 4 * (((16 + 80 * (AVG_PKT_SIZE + 4) + 6) /	\
170 	      ((_bitrate) * 4)))))
171 
172 #define OFDM_DURATION_LIST(_s)				\
173 	OFDM_DURATION(60) >> _s,			\
174 	OFDM_DURATION(90) >> _s,			\
175 	OFDM_DURATION(120) >> _s,			\
176 	OFDM_DURATION(180) >> _s,			\
177 	OFDM_DURATION(240) >> _s,			\
178 	OFDM_DURATION(360) >> _s,			\
179 	OFDM_DURATION(480) >> _s,			\
180 	OFDM_DURATION(540) >> _s
181 
182 #define __OFDM_GROUP(_s)				\
183 	[MINSTREL_OFDM_GROUP] = {			\
184 		.streams = 1,				\
185 		.flags = 0,				\
186 		.shift = _s,				\
187 		.duration = {				\
188 			OFDM_DURATION_LIST(_s),		\
189 		}					\
190 	}
191 
192 #define OFDM_GROUP_SHIFT				\
193 	GROUP_SHIFT(OFDM_DURATION(60))
194 
195 #define OFDM_GROUP __OFDM_GROUP(OFDM_GROUP_SHIFT)
196 
197 
198 static bool minstrel_vht_only = true;
199 module_param(minstrel_vht_only, bool, 0644);
200 MODULE_PARM_DESC(minstrel_vht_only,
201 		 "Use only VHT rates when VHT is supported by sta.");
202 
203 /*
204  * To enable sufficiently targeted rate sampling, MCS rates are divided into
205  * groups, based on the number of streams and flags (HT40, SGI) that they
206  * use.
207  *
208  * Sortorder has to be fixed for GROUP_IDX macro to be applicable:
209  * BW -> SGI -> #streams
210  */
211 const struct mcs_group minstrel_mcs_groups[] = {
212 	MCS_GROUP(1, 0, BW_20),
213 	MCS_GROUP(2, 0, BW_20),
214 	MCS_GROUP(3, 0, BW_20),
215 	MCS_GROUP(4, 0, BW_20),
216 
217 	MCS_GROUP(1, 1, BW_20),
218 	MCS_GROUP(2, 1, BW_20),
219 	MCS_GROUP(3, 1, BW_20),
220 	MCS_GROUP(4, 1, BW_20),
221 
222 	MCS_GROUP(1, 0, BW_40),
223 	MCS_GROUP(2, 0, BW_40),
224 	MCS_GROUP(3, 0, BW_40),
225 	MCS_GROUP(4, 0, BW_40),
226 
227 	MCS_GROUP(1, 1, BW_40),
228 	MCS_GROUP(2, 1, BW_40),
229 	MCS_GROUP(3, 1, BW_40),
230 	MCS_GROUP(4, 1, BW_40),
231 
232 	CCK_GROUP,
233 	OFDM_GROUP,
234 
235 	VHT_GROUP(1, 0, BW_20),
236 	VHT_GROUP(2, 0, BW_20),
237 	VHT_GROUP(3, 0, BW_20),
238 	VHT_GROUP(4, 0, BW_20),
239 
240 	VHT_GROUP(1, 1, BW_20),
241 	VHT_GROUP(2, 1, BW_20),
242 	VHT_GROUP(3, 1, BW_20),
243 	VHT_GROUP(4, 1, BW_20),
244 
245 	VHT_GROUP(1, 0, BW_40),
246 	VHT_GROUP(2, 0, BW_40),
247 	VHT_GROUP(3, 0, BW_40),
248 	VHT_GROUP(4, 0, BW_40),
249 
250 	VHT_GROUP(1, 1, BW_40),
251 	VHT_GROUP(2, 1, BW_40),
252 	VHT_GROUP(3, 1, BW_40),
253 	VHT_GROUP(4, 1, BW_40),
254 
255 	VHT_GROUP(1, 0, BW_80),
256 	VHT_GROUP(2, 0, BW_80),
257 	VHT_GROUP(3, 0, BW_80),
258 	VHT_GROUP(4, 0, BW_80),
259 
260 	VHT_GROUP(1, 1, BW_80),
261 	VHT_GROUP(2, 1, BW_80),
262 	VHT_GROUP(3, 1, BW_80),
263 	VHT_GROUP(4, 1, BW_80),
264 };
265 
266 const s16 minstrel_cck_bitrates[4] = { 10, 20, 55, 110 };
267 const s16 minstrel_ofdm_bitrates[8] = { 60, 90, 120, 180, 240, 360, 480, 540 };
268 static u8 sample_table[SAMPLE_COLUMNS][MCS_GROUP_RATES] __read_mostly;
269 
270 static void
271 minstrel_ht_update_rates(struct minstrel_priv *mp, struct minstrel_ht_sta *mi);
272 
273 /*
274  * Some VHT MCSes are invalid (when Ndbps / Nes is not an integer)
275  * e.g for MCS9@20MHzx1Nss: Ndbps=8x52*(5/6) Nes=1
276  *
277  * Returns the valid mcs map for struct minstrel_mcs_group_data.supported
278  */
279 static u16
280 minstrel_get_valid_vht_rates(int bw, int nss, __le16 mcs_map)
281 {
282 	u16 mask = 0;
283 
284 	if (bw == BW_20) {
285 		if (nss != 3 && nss != 6)
286 			mask = BIT(9);
287 	} else if (bw == BW_80) {
288 		if (nss == 3 || nss == 7)
289 			mask = BIT(6);
290 		else if (nss == 6)
291 			mask = BIT(9);
292 	} else {
293 		WARN_ON(bw != BW_40);
294 	}
295 
296 	switch ((le16_to_cpu(mcs_map) >> (2 * (nss - 1))) & 3) {
297 	case IEEE80211_VHT_MCS_SUPPORT_0_7:
298 		mask |= 0x300;
299 		break;
300 	case IEEE80211_VHT_MCS_SUPPORT_0_8:
301 		mask |= 0x200;
302 		break;
303 	case IEEE80211_VHT_MCS_SUPPORT_0_9:
304 		break;
305 	default:
306 		mask = 0x3ff;
307 	}
308 
309 	return 0x3ff & ~mask;
310 }
311 
312 static bool
313 minstrel_ht_is_legacy_group(int group)
314 {
315 	return group == MINSTREL_CCK_GROUP ||
316 	       group == MINSTREL_OFDM_GROUP;
317 }
318 
319 /*
320  * Look up an MCS group index based on mac80211 rate information
321  */
322 static int
323 minstrel_ht_get_group_idx(struct ieee80211_tx_rate *rate)
324 {
325 	return GROUP_IDX((rate->idx / 8) + 1,
326 			 !!(rate->flags & IEEE80211_TX_RC_SHORT_GI),
327 			 !!(rate->flags & IEEE80211_TX_RC_40_MHZ_WIDTH));
328 }
329 
330 static int
331 minstrel_vht_get_group_idx(struct ieee80211_tx_rate *rate)
332 {
333 	return VHT_GROUP_IDX(ieee80211_rate_get_vht_nss(rate),
334 			     !!(rate->flags & IEEE80211_TX_RC_SHORT_GI),
335 			     !!(rate->flags & IEEE80211_TX_RC_40_MHZ_WIDTH) +
336 			     2*!!(rate->flags & IEEE80211_TX_RC_80_MHZ_WIDTH));
337 }
338 
339 static struct minstrel_rate_stats *
340 minstrel_ht_get_stats(struct minstrel_priv *mp, struct minstrel_ht_sta *mi,
341 		      struct ieee80211_tx_rate *rate)
342 {
343 	int group, idx;
344 
345 	if (rate->flags & IEEE80211_TX_RC_MCS) {
346 		group = minstrel_ht_get_group_idx(rate);
347 		idx = rate->idx % 8;
348 		goto out;
349 	}
350 
351 	if (rate->flags & IEEE80211_TX_RC_VHT_MCS) {
352 		group = minstrel_vht_get_group_idx(rate);
353 		idx = ieee80211_rate_get_vht_mcs(rate);
354 		goto out;
355 	}
356 
357 	group = MINSTREL_CCK_GROUP;
358 	for (idx = 0; idx < ARRAY_SIZE(mp->cck_rates); idx++) {
359 		if (rate->idx != mp->cck_rates[idx])
360 			continue;
361 
362 		/* short preamble */
363 		if ((mi->supported[group] & BIT(idx + 4)) &&
364 		    (rate->flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE))
365 				idx += 4;
366 		goto out;
367 	}
368 
369 	group = MINSTREL_OFDM_GROUP;
370 	for (idx = 0; idx < ARRAY_SIZE(mp->ofdm_rates[0]); idx++)
371 		if (rate->idx == mp->ofdm_rates[mi->band][idx])
372 			goto out;
373 
374 	idx = 0;
375 out:
376 	return &mi->groups[group].rates[idx];
377 }
378 
379 static inline struct minstrel_rate_stats *
380 minstrel_get_ratestats(struct minstrel_ht_sta *mi, int index)
381 {
382 	return &mi->groups[index / MCS_GROUP_RATES].rates[index % MCS_GROUP_RATES];
383 }
384 
385 static inline int minstrel_get_duration(int index)
386 {
387 	const struct mcs_group *group = &minstrel_mcs_groups[index / MCS_GROUP_RATES];
388 	unsigned int duration = group->duration[index % MCS_GROUP_RATES];
389 
390 	return duration << group->shift;
391 }
392 
393 static unsigned int
394 minstrel_ht_avg_ampdu_len(struct minstrel_ht_sta *mi)
395 {
396 	int duration;
397 
398 	if (mi->avg_ampdu_len)
399 		return MINSTREL_TRUNC(mi->avg_ampdu_len);
400 
401 	if (minstrel_ht_is_legacy_group(mi->max_tp_rate[0] / MCS_GROUP_RATES))
402 		return 1;
403 
404 	duration = minstrel_get_duration(mi->max_tp_rate[0]);
405 
406 	if (duration > 400 * 1000)
407 		return 2;
408 
409 	if (duration > 250 * 1000)
410 		return 4;
411 
412 	if (duration > 150 * 1000)
413 		return 8;
414 
415 	return 16;
416 }
417 
418 /*
419  * Return current throughput based on the average A-MPDU length, taking into
420  * account the expected number of retransmissions and their expected length
421  */
422 int
423 minstrel_ht_get_tp_avg(struct minstrel_ht_sta *mi, int group, int rate,
424 		       int prob_avg)
425 {
426 	unsigned int nsecs = 0, overhead = mi->overhead;
427 	unsigned int ampdu_len = 1;
428 
429 	/* do not account throughput if sucess prob is below 10% */
430 	if (prob_avg < MINSTREL_FRAC(10, 100))
431 		return 0;
432 
433 	if (minstrel_ht_is_legacy_group(group))
434 		overhead = mi->overhead_legacy;
435 	else
436 		ampdu_len = minstrel_ht_avg_ampdu_len(mi);
437 
438 	nsecs = 1000 * overhead / ampdu_len;
439 	nsecs += minstrel_mcs_groups[group].duration[rate] <<
440 		 minstrel_mcs_groups[group].shift;
441 
442 	/*
443 	 * For the throughput calculation, limit the probability value to 90% to
444 	 * account for collision related packet error rate fluctuation
445 	 * (prob is scaled - see MINSTREL_FRAC above)
446 	 */
447 	if (prob_avg > MINSTREL_FRAC(90, 100))
448 		prob_avg = MINSTREL_FRAC(90, 100);
449 
450 	return MINSTREL_TRUNC(100 * ((prob_avg * 1000000) / nsecs));
451 }
452 
453 /*
454  * Find & sort topmost throughput rates
455  *
456  * If multiple rates provide equal throughput the sorting is based on their
457  * current success probability. Higher success probability is preferred among
458  * MCS groups, CCK rates do not provide aggregation and are therefore at last.
459  */
460 static void
461 minstrel_ht_sort_best_tp_rates(struct minstrel_ht_sta *mi, u16 index,
462 			       u16 *tp_list)
463 {
464 	int cur_group, cur_idx, cur_tp_avg, cur_prob;
465 	int tmp_group, tmp_idx, tmp_tp_avg, tmp_prob;
466 	int j = MAX_THR_RATES;
467 
468 	cur_group = index / MCS_GROUP_RATES;
469 	cur_idx = index  % MCS_GROUP_RATES;
470 	cur_prob = mi->groups[cur_group].rates[cur_idx].prob_avg;
471 	cur_tp_avg = minstrel_ht_get_tp_avg(mi, cur_group, cur_idx, cur_prob);
472 
473 	do {
474 		tmp_group = tp_list[j - 1] / MCS_GROUP_RATES;
475 		tmp_idx = tp_list[j - 1] % MCS_GROUP_RATES;
476 		tmp_prob = mi->groups[tmp_group].rates[tmp_idx].prob_avg;
477 		tmp_tp_avg = minstrel_ht_get_tp_avg(mi, tmp_group, tmp_idx,
478 						    tmp_prob);
479 		if (cur_tp_avg < tmp_tp_avg ||
480 		    (cur_tp_avg == tmp_tp_avg && cur_prob <= tmp_prob))
481 			break;
482 		j--;
483 	} while (j > 0);
484 
485 	if (j < MAX_THR_RATES - 1) {
486 		memmove(&tp_list[j + 1], &tp_list[j], (sizeof(*tp_list) *
487 		       (MAX_THR_RATES - (j + 1))));
488 	}
489 	if (j < MAX_THR_RATES)
490 		tp_list[j] = index;
491 }
492 
493 /*
494  * Find and set the topmost probability rate per sta and per group
495  */
496 static void
497 minstrel_ht_set_best_prob_rate(struct minstrel_ht_sta *mi, u16 *dest, u16 index)
498 {
499 	struct minstrel_mcs_group_data *mg;
500 	struct minstrel_rate_stats *mrs;
501 	int tmp_group, tmp_idx, tmp_tp_avg, tmp_prob;
502 	int max_tp_group, max_tp_idx, max_tp_prob;
503 	int cur_tp_avg, cur_group, cur_idx;
504 	int max_gpr_group, max_gpr_idx;
505 	int max_gpr_tp_avg, max_gpr_prob;
506 
507 	cur_group = index / MCS_GROUP_RATES;
508 	cur_idx = index % MCS_GROUP_RATES;
509 	mg = &mi->groups[index / MCS_GROUP_RATES];
510 	mrs = &mg->rates[index % MCS_GROUP_RATES];
511 
512 	tmp_group = *dest / MCS_GROUP_RATES;
513 	tmp_idx = *dest % MCS_GROUP_RATES;
514 	tmp_prob = mi->groups[tmp_group].rates[tmp_idx].prob_avg;
515 	tmp_tp_avg = minstrel_ht_get_tp_avg(mi, tmp_group, tmp_idx, tmp_prob);
516 
517 	/* if max_tp_rate[0] is from MCS_GROUP max_prob_rate get selected from
518 	 * MCS_GROUP as well as CCK_GROUP rates do not allow aggregation */
519 	max_tp_group = mi->max_tp_rate[0] / MCS_GROUP_RATES;
520 	max_tp_idx = mi->max_tp_rate[0] % MCS_GROUP_RATES;
521 	max_tp_prob = mi->groups[max_tp_group].rates[max_tp_idx].prob_avg;
522 
523 	if (minstrel_ht_is_legacy_group(index / MCS_GROUP_RATES) &&
524 	    !minstrel_ht_is_legacy_group(max_tp_group))
525 		return;
526 
527 	/* skip rates faster than max tp rate with lower prob */
528 	if (minstrel_get_duration(mi->max_tp_rate[0]) > minstrel_get_duration(index) &&
529 	    mrs->prob_avg < max_tp_prob)
530 		return;
531 
532 	max_gpr_group = mg->max_group_prob_rate / MCS_GROUP_RATES;
533 	max_gpr_idx = mg->max_group_prob_rate % MCS_GROUP_RATES;
534 	max_gpr_prob = mi->groups[max_gpr_group].rates[max_gpr_idx].prob_avg;
535 
536 	if (mrs->prob_avg > MINSTREL_FRAC(75, 100)) {
537 		cur_tp_avg = minstrel_ht_get_tp_avg(mi, cur_group, cur_idx,
538 						    mrs->prob_avg);
539 		if (cur_tp_avg > tmp_tp_avg)
540 			*dest = index;
541 
542 		max_gpr_tp_avg = minstrel_ht_get_tp_avg(mi, max_gpr_group,
543 							max_gpr_idx,
544 							max_gpr_prob);
545 		if (cur_tp_avg > max_gpr_tp_avg)
546 			mg->max_group_prob_rate = index;
547 	} else {
548 		if (mrs->prob_avg > tmp_prob)
549 			*dest = index;
550 		if (mrs->prob_avg > max_gpr_prob)
551 			mg->max_group_prob_rate = index;
552 	}
553 }
554 
555 
556 /*
557  * Assign new rate set per sta and use CCK rates only if the fastest
558  * rate (max_tp_rate[0]) is from CCK group. This prohibits such sorted
559  * rate sets where MCS and CCK rates are mixed, because CCK rates can
560  * not use aggregation.
561  */
562 static void
563 minstrel_ht_assign_best_tp_rates(struct minstrel_ht_sta *mi,
564 				 u16 tmp_mcs_tp_rate[MAX_THR_RATES],
565 				 u16 tmp_legacy_tp_rate[MAX_THR_RATES])
566 {
567 	unsigned int tmp_group, tmp_idx, tmp_cck_tp, tmp_mcs_tp, tmp_prob;
568 	int i;
569 
570 	tmp_group = tmp_legacy_tp_rate[0] / MCS_GROUP_RATES;
571 	tmp_idx = tmp_legacy_tp_rate[0] % MCS_GROUP_RATES;
572 	tmp_prob = mi->groups[tmp_group].rates[tmp_idx].prob_avg;
573 	tmp_cck_tp = minstrel_ht_get_tp_avg(mi, tmp_group, tmp_idx, tmp_prob);
574 
575 	tmp_group = tmp_mcs_tp_rate[0] / MCS_GROUP_RATES;
576 	tmp_idx = tmp_mcs_tp_rate[0] % MCS_GROUP_RATES;
577 	tmp_prob = mi->groups[tmp_group].rates[tmp_idx].prob_avg;
578 	tmp_mcs_tp = minstrel_ht_get_tp_avg(mi, tmp_group, tmp_idx, tmp_prob);
579 
580 	if (tmp_cck_tp > tmp_mcs_tp) {
581 		for(i = 0; i < MAX_THR_RATES; i++) {
582 			minstrel_ht_sort_best_tp_rates(mi, tmp_legacy_tp_rate[i],
583 						       tmp_mcs_tp_rate);
584 		}
585 	}
586 
587 }
588 
589 /*
590  * Try to increase robustness of max_prob rate by decrease number of
591  * streams if possible.
592  */
593 static inline void
594 minstrel_ht_prob_rate_reduce_streams(struct minstrel_ht_sta *mi)
595 {
596 	struct minstrel_mcs_group_data *mg;
597 	int tmp_max_streams, group, tmp_idx, tmp_prob;
598 	int tmp_tp = 0;
599 
600 	if (!mi->sta->ht_cap.ht_supported)
601 		return;
602 
603 	tmp_max_streams = minstrel_mcs_groups[mi->max_tp_rate[0] /
604 			  MCS_GROUP_RATES].streams;
605 	for (group = 0; group < ARRAY_SIZE(minstrel_mcs_groups); group++) {
606 		mg = &mi->groups[group];
607 		if (!mi->supported[group] || group == MINSTREL_CCK_GROUP)
608 			continue;
609 
610 		tmp_idx = mg->max_group_prob_rate % MCS_GROUP_RATES;
611 		tmp_prob = mi->groups[group].rates[tmp_idx].prob_avg;
612 
613 		if (tmp_tp < minstrel_ht_get_tp_avg(mi, group, tmp_idx, tmp_prob) &&
614 		   (minstrel_mcs_groups[group].streams < tmp_max_streams)) {
615 				mi->max_prob_rate = mg->max_group_prob_rate;
616 				tmp_tp = minstrel_ht_get_tp_avg(mi, group,
617 								tmp_idx,
618 								tmp_prob);
619 		}
620 	}
621 }
622 
623 static bool
624 minstrel_ht_probe_group(struct minstrel_ht_sta *mi, const struct mcs_group *tp_group,
625 						int tp_idx, const struct mcs_group *group)
626 {
627 	if (group->bw < tp_group->bw)
628 		return false;
629 
630 	if (group->streams == tp_group->streams)
631 		return true;
632 
633 	if (tp_idx < 4 && group->streams == tp_group->streams - 1)
634 		return true;
635 
636 	return group->streams == tp_group->streams + 1;
637 }
638 
639 static void
640 minstrel_ht_find_probe_rates(struct minstrel_ht_sta *mi, u16 *rates, int *n_rates,
641 			     bool faster_rate)
642 {
643 	const struct mcs_group *group, *tp_group;
644 	int i, g, max_dur;
645 	int tp_idx;
646 
647 	tp_group = &minstrel_mcs_groups[mi->max_tp_rate[0] / MCS_GROUP_RATES];
648 	tp_idx = mi->max_tp_rate[0] % MCS_GROUP_RATES;
649 
650 	max_dur = minstrel_get_duration(mi->max_tp_rate[0]);
651 	if (faster_rate)
652 		max_dur -= max_dur / 16;
653 
654 	for (g = 0; g < MINSTREL_GROUPS_NB; g++) {
655 		u16 supported = mi->supported[g];
656 
657 		if (!supported)
658 			continue;
659 
660 		group = &minstrel_mcs_groups[g];
661 		if (!minstrel_ht_probe_group(mi, tp_group, tp_idx, group))
662 			continue;
663 
664 		for (i = 0; supported; supported >>= 1, i++) {
665 			int idx;
666 
667 			if (!(supported & 1))
668 				continue;
669 
670 			if ((group->duration[i] << group->shift) > max_dur)
671 				continue;
672 
673 			idx = g * MCS_GROUP_RATES + i;
674 			if (idx == mi->max_tp_rate[0])
675 				continue;
676 
677 			rates[(*n_rates)++] = idx;
678 			break;
679 		}
680 	}
681 }
682 
683 static void
684 minstrel_ht_rate_sample_switch(struct minstrel_priv *mp,
685 			       struct minstrel_ht_sta *mi)
686 {
687 	struct minstrel_rate_stats *mrs;
688 	u16 rates[MINSTREL_GROUPS_NB];
689 	int n_rates = 0;
690 	int probe_rate = 0;
691 	bool faster_rate;
692 	int i;
693 	u8 random;
694 
695 	/*
696 	 * Use rate switching instead of probing packets for devices with
697 	 * little control over retry fallback behavior
698 	 */
699 	if (mp->hw->max_rates > 1)
700 		return;
701 
702 	/*
703 	 * If the current EWMA prob is >75%, look for a rate that's 6.25%
704 	 * faster than the max tp rate.
705 	 * If that fails, look again for a rate that is at least as fast
706 	 */
707 	mrs = minstrel_get_ratestats(mi, mi->max_tp_rate[0]);
708 	faster_rate = mrs->prob_avg > MINSTREL_FRAC(75, 100);
709 	minstrel_ht_find_probe_rates(mi, rates, &n_rates, faster_rate);
710 	if (!n_rates && faster_rate)
711 		minstrel_ht_find_probe_rates(mi, rates, &n_rates, false);
712 
713 	/* If no suitable rate was found, try to pick the next one in the group */
714 	if (!n_rates) {
715 		int g_idx = mi->max_tp_rate[0] / MCS_GROUP_RATES;
716 		u16 supported = mi->supported[g_idx];
717 
718 		supported >>= mi->max_tp_rate[0] % MCS_GROUP_RATES;
719 		for (i = 0; supported; supported >>= 1, i++) {
720 			if (!(supported & 1))
721 				continue;
722 
723 			probe_rate = mi->max_tp_rate[0] + i;
724 			goto out;
725 		}
726 
727 		return;
728 	}
729 
730 	i = 0;
731 	if (n_rates > 1) {
732 		random = prandom_u32();
733 		i = random % n_rates;
734 	}
735 	probe_rate = rates[i];
736 
737 out:
738 	mi->sample_rate = probe_rate;
739 	mi->sample_mode = MINSTREL_SAMPLE_ACTIVE;
740 }
741 
742 static inline int
743 minstrel_ewma(int old, int new, int weight)
744 {
745 	int diff, incr;
746 
747 	diff = new - old;
748 	incr = (EWMA_DIV - weight) * diff / EWMA_DIV;
749 
750 	return old + incr;
751 }
752 
753 static inline int minstrel_filter_avg_add(u16 *prev_1, u16 *prev_2, s32 in)
754 {
755 	s32 out_1 = *prev_1;
756 	s32 out_2 = *prev_2;
757 	s32 val;
758 
759 	if (!in)
760 		in += 1;
761 
762 	if (!out_1) {
763 		val = out_1 = in;
764 		goto out;
765 	}
766 
767 	val = MINSTREL_AVG_COEFF1 * in;
768 	val += MINSTREL_AVG_COEFF2 * out_1;
769 	val += MINSTREL_AVG_COEFF3 * out_2;
770 	val >>= MINSTREL_SCALE;
771 
772 	if (val > 1 << MINSTREL_SCALE)
773 		val = 1 << MINSTREL_SCALE;
774 	if (val < 0)
775 		val = 1;
776 
777 out:
778 	*prev_2 = out_1;
779 	*prev_1 = val;
780 
781 	return val;
782 }
783 
784 /*
785 * Recalculate statistics and counters of a given rate
786 */
787 static void
788 minstrel_ht_calc_rate_stats(struct minstrel_priv *mp,
789 			    struct minstrel_rate_stats *mrs)
790 {
791 	unsigned int cur_prob;
792 
793 	if (unlikely(mrs->attempts > 0)) {
794 		mrs->sample_skipped = 0;
795 		cur_prob = MINSTREL_FRAC(mrs->success, mrs->attempts);
796 		minstrel_filter_avg_add(&mrs->prob_avg,
797 					&mrs->prob_avg_1, cur_prob);
798 		mrs->att_hist += mrs->attempts;
799 		mrs->succ_hist += mrs->success;
800 	} else {
801 		mrs->sample_skipped++;
802 	}
803 
804 	mrs->last_success = mrs->success;
805 	mrs->last_attempts = mrs->attempts;
806 	mrs->success = 0;
807 	mrs->attempts = 0;
808 }
809 
810 /*
811  * Update rate statistics and select new primary rates
812  *
813  * Rules for rate selection:
814  *  - max_prob_rate must use only one stream, as a tradeoff between delivery
815  *    probability and throughput during strong fluctuations
816  *  - as long as the max prob rate has a probability of more than 75%, pick
817  *    higher throughput rates, even if the probablity is a bit lower
818  */
819 static void
820 minstrel_ht_update_stats(struct minstrel_priv *mp, struct minstrel_ht_sta *mi,
821 			 bool sample)
822 {
823 	struct minstrel_mcs_group_data *mg;
824 	struct minstrel_rate_stats *mrs;
825 	int group, i, j, cur_prob;
826 	u16 tmp_mcs_tp_rate[MAX_THR_RATES], tmp_group_tp_rate[MAX_THR_RATES];
827 	u16 tmp_legacy_tp_rate[MAX_THR_RATES], tmp_max_prob_rate;
828 	u16 index;
829 	bool ht_supported = mi->sta->ht_cap.ht_supported;
830 
831 	mi->sample_mode = MINSTREL_SAMPLE_IDLE;
832 
833 	if (sample) {
834 		mi->total_packets_cur = mi->total_packets -
835 					mi->total_packets_last;
836 		mi->total_packets_last = mi->total_packets;
837 	}
838 	if (!mp->sample_switch)
839 		sample = false;
840 	if (mi->total_packets_cur < SAMPLE_SWITCH_THR && mp->sample_switch != 1)
841 	    sample = false;
842 
843 	if (mi->ampdu_packets > 0) {
844 		if (!ieee80211_hw_check(mp->hw, TX_STATUS_NO_AMPDU_LEN))
845 			mi->avg_ampdu_len = minstrel_ewma(mi->avg_ampdu_len,
846 				MINSTREL_FRAC(mi->ampdu_len, mi->ampdu_packets),
847 					      EWMA_LEVEL);
848 		else
849 			mi->avg_ampdu_len = 0;
850 		mi->ampdu_len = 0;
851 		mi->ampdu_packets = 0;
852 	}
853 
854 	mi->sample_slow = 0;
855 	mi->sample_count = 0;
856 
857 	memset(tmp_mcs_tp_rate, 0, sizeof(tmp_mcs_tp_rate));
858 	memset(tmp_legacy_tp_rate, 0, sizeof(tmp_legacy_tp_rate));
859 	if (mi->supported[MINSTREL_CCK_GROUP])
860 		for (j = 0; j < ARRAY_SIZE(tmp_legacy_tp_rate); j++)
861 			tmp_legacy_tp_rate[j] = MINSTREL_CCK_GROUP * MCS_GROUP_RATES;
862 	else if (mi->supported[MINSTREL_OFDM_GROUP])
863 		for (j = 0; j < ARRAY_SIZE(tmp_legacy_tp_rate); j++)
864 			tmp_legacy_tp_rate[j] = MINSTREL_OFDM_GROUP * MCS_GROUP_RATES;
865 
866 	if (mi->supported[MINSTREL_VHT_GROUP_0])
867 		index = MINSTREL_VHT_GROUP_0 * MCS_GROUP_RATES;
868 	else if (ht_supported)
869 		index = MINSTREL_HT_GROUP_0 * MCS_GROUP_RATES;
870 	else if (mi->supported[MINSTREL_CCK_GROUP])
871 		index = MINSTREL_CCK_GROUP * MCS_GROUP_RATES;
872 	else
873 		index = MINSTREL_OFDM_GROUP * MCS_GROUP_RATES;
874 
875 	tmp_max_prob_rate = index;
876 	for (j = 0; j < ARRAY_SIZE(tmp_mcs_tp_rate); j++)
877 		tmp_mcs_tp_rate[j] = index;
878 
879 	/* Find best rate sets within all MCS groups*/
880 	for (group = 0; group < ARRAY_SIZE(minstrel_mcs_groups); group++) {
881 		u16 *tp_rate = tmp_mcs_tp_rate;
882 
883 		mg = &mi->groups[group];
884 		if (!mi->supported[group])
885 			continue;
886 
887 		mi->sample_count++;
888 
889 		/* (re)Initialize group rate indexes */
890 		for(j = 0; j < MAX_THR_RATES; j++)
891 			tmp_group_tp_rate[j] = MCS_GROUP_RATES * group;
892 
893 		if (group == MINSTREL_CCK_GROUP && ht_supported)
894 			tp_rate = tmp_legacy_tp_rate;
895 
896 		for (i = 0; i < MCS_GROUP_RATES; i++) {
897 			if (!(mi->supported[group] & BIT(i)))
898 				continue;
899 
900 			index = MCS_GROUP_RATES * group + i;
901 
902 			mrs = &mg->rates[i];
903 			mrs->retry_updated = false;
904 			minstrel_ht_calc_rate_stats(mp, mrs);
905 			cur_prob = mrs->prob_avg;
906 
907 			if (minstrel_ht_get_tp_avg(mi, group, i, cur_prob) == 0)
908 				continue;
909 
910 			/* Find max throughput rate set */
911 			minstrel_ht_sort_best_tp_rates(mi, index, tp_rate);
912 
913 			/* Find max throughput rate set within a group */
914 			minstrel_ht_sort_best_tp_rates(mi, index,
915 						       tmp_group_tp_rate);
916 		}
917 
918 		memcpy(mg->max_group_tp_rate, tmp_group_tp_rate,
919 		       sizeof(mg->max_group_tp_rate));
920 	}
921 
922 	/* Assign new rate set per sta */
923 	minstrel_ht_assign_best_tp_rates(mi, tmp_mcs_tp_rate,
924 					 tmp_legacy_tp_rate);
925 	memcpy(mi->max_tp_rate, tmp_mcs_tp_rate, sizeof(mi->max_tp_rate));
926 
927 	for (group = 0; group < ARRAY_SIZE(minstrel_mcs_groups); group++) {
928 		if (!mi->supported[group])
929 			continue;
930 
931 		mg = &mi->groups[group];
932 		mg->max_group_prob_rate = MCS_GROUP_RATES * group;
933 
934 		for (i = 0; i < MCS_GROUP_RATES; i++) {
935 			if (!(mi->supported[group] & BIT(i)))
936 				continue;
937 
938 			index = MCS_GROUP_RATES * group + i;
939 
940 			/* Find max probability rate per group and global */
941 			minstrel_ht_set_best_prob_rate(mi, &tmp_max_prob_rate,
942 						       index);
943 		}
944 	}
945 
946 	mi->max_prob_rate = tmp_max_prob_rate;
947 
948 	/* Try to increase robustness of max_prob_rate*/
949 	minstrel_ht_prob_rate_reduce_streams(mi);
950 
951 	/* try to sample half of all available rates during each interval */
952 	mi->sample_count *= 4;
953 
954 	if (sample)
955 		minstrel_ht_rate_sample_switch(mp, mi);
956 
957 #ifdef CONFIG_MAC80211_DEBUGFS
958 	/* use fixed index if set */
959 	if (mp->fixed_rate_idx != -1) {
960 		for (i = 0; i < 4; i++)
961 			mi->max_tp_rate[i] = mp->fixed_rate_idx;
962 		mi->max_prob_rate = mp->fixed_rate_idx;
963 		mi->sample_mode = MINSTREL_SAMPLE_IDLE;
964 	}
965 #endif
966 
967 	/* Reset update timer */
968 	mi->last_stats_update = jiffies;
969 }
970 
971 static bool
972 minstrel_ht_txstat_valid(struct minstrel_priv *mp, struct minstrel_ht_sta *mi,
973 			 struct ieee80211_tx_rate *rate)
974 {
975 	int i;
976 
977 	if (rate->idx < 0)
978 		return false;
979 
980 	if (!rate->count)
981 		return false;
982 
983 	if (rate->flags & IEEE80211_TX_RC_MCS ||
984 	    rate->flags & IEEE80211_TX_RC_VHT_MCS)
985 		return true;
986 
987 	for (i = 0; i < ARRAY_SIZE(mp->cck_rates); i++)
988 		if (rate->idx == mp->cck_rates[i])
989 			return true;
990 
991 	for (i = 0; i < ARRAY_SIZE(mp->ofdm_rates[0]); i++)
992 		if (rate->idx == mp->ofdm_rates[mi->band][i])
993 			return true;
994 
995 	return false;
996 }
997 
998 static void
999 minstrel_set_next_sample_idx(struct minstrel_ht_sta *mi)
1000 {
1001 	struct minstrel_mcs_group_data *mg;
1002 
1003 	for (;;) {
1004 		mi->sample_group++;
1005 		mi->sample_group %= ARRAY_SIZE(minstrel_mcs_groups);
1006 		mg = &mi->groups[mi->sample_group];
1007 
1008 		if (!mi->supported[mi->sample_group])
1009 			continue;
1010 
1011 		if (++mg->index >= MCS_GROUP_RATES) {
1012 			mg->index = 0;
1013 			if (++mg->column >= ARRAY_SIZE(sample_table))
1014 				mg->column = 0;
1015 		}
1016 		break;
1017 	}
1018 }
1019 
1020 static void
1021 minstrel_downgrade_rate(struct minstrel_ht_sta *mi, u16 *idx, bool primary)
1022 {
1023 	int group, orig_group;
1024 
1025 	orig_group = group = *idx / MCS_GROUP_RATES;
1026 	while (group > 0) {
1027 		group--;
1028 
1029 		if (!mi->supported[group])
1030 			continue;
1031 
1032 		if (minstrel_mcs_groups[group].streams >
1033 		    minstrel_mcs_groups[orig_group].streams)
1034 			continue;
1035 
1036 		if (primary)
1037 			*idx = mi->groups[group].max_group_tp_rate[0];
1038 		else
1039 			*idx = mi->groups[group].max_group_tp_rate[1];
1040 		break;
1041 	}
1042 }
1043 
1044 static void
1045 minstrel_aggr_check(struct ieee80211_sta *pubsta, struct sk_buff *skb)
1046 {
1047 	struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) skb->data;
1048 	struct sta_info *sta = container_of(pubsta, struct sta_info, sta);
1049 	u16 tid;
1050 
1051 	if (skb_get_queue_mapping(skb) == IEEE80211_AC_VO)
1052 		return;
1053 
1054 	if (unlikely(!ieee80211_is_data_qos(hdr->frame_control)))
1055 		return;
1056 
1057 	if (unlikely(skb->protocol == cpu_to_be16(ETH_P_PAE)))
1058 		return;
1059 
1060 	tid = ieee80211_get_tid(hdr);
1061 	if (likely(sta->ampdu_mlme.tid_tx[tid]))
1062 		return;
1063 
1064 	ieee80211_start_tx_ba_session(pubsta, tid, 0);
1065 }
1066 
1067 static void
1068 minstrel_ht_tx_status(void *priv, struct ieee80211_supported_band *sband,
1069                       void *priv_sta, struct ieee80211_tx_status *st)
1070 {
1071 	struct ieee80211_tx_info *info = st->info;
1072 	struct minstrel_ht_sta *mi = priv_sta;
1073 	struct ieee80211_tx_rate *ar = info->status.rates;
1074 	struct minstrel_rate_stats *rate, *rate2, *rate_sample = NULL;
1075 	struct minstrel_priv *mp = priv;
1076 	u32 update_interval = mp->update_interval;
1077 	bool last, update = false;
1078 	bool sample_status = false;
1079 	int i;
1080 
1081 	/* This packet was aggregated but doesn't carry status info */
1082 	if ((info->flags & IEEE80211_TX_CTL_AMPDU) &&
1083 	    !(info->flags & IEEE80211_TX_STAT_AMPDU))
1084 		return;
1085 
1086 	if (!(info->flags & IEEE80211_TX_STAT_AMPDU)) {
1087 		info->status.ampdu_ack_len =
1088 			(info->flags & IEEE80211_TX_STAT_ACK ? 1 : 0);
1089 		info->status.ampdu_len = 1;
1090 	}
1091 
1092 	mi->ampdu_packets++;
1093 	mi->ampdu_len += info->status.ampdu_len;
1094 
1095 	if (!mi->sample_wait && !mi->sample_tries && mi->sample_count > 0) {
1096 		int avg_ampdu_len = minstrel_ht_avg_ampdu_len(mi);
1097 
1098 		mi->sample_wait = 16 + 2 * avg_ampdu_len;
1099 		mi->sample_tries = 1;
1100 		mi->sample_count--;
1101 	}
1102 
1103 	if (info->flags & IEEE80211_TX_CTL_RATE_CTRL_PROBE)
1104 		mi->sample_packets += info->status.ampdu_len;
1105 
1106 	if (mi->sample_mode != MINSTREL_SAMPLE_IDLE)
1107 		rate_sample = minstrel_get_ratestats(mi, mi->sample_rate);
1108 
1109 	last = !minstrel_ht_txstat_valid(mp, mi, &ar[0]);
1110 	for (i = 0; !last; i++) {
1111 		last = (i == IEEE80211_TX_MAX_RATES - 1) ||
1112 		       !minstrel_ht_txstat_valid(mp, mi, &ar[i + 1]);
1113 
1114 		rate = minstrel_ht_get_stats(mp, mi, &ar[i]);
1115 		if (rate == rate_sample)
1116 			sample_status = true;
1117 
1118 		if (last)
1119 			rate->success += info->status.ampdu_ack_len;
1120 
1121 		rate->attempts += ar[i].count * info->status.ampdu_len;
1122 	}
1123 
1124 	switch (mi->sample_mode) {
1125 	case MINSTREL_SAMPLE_IDLE:
1126 		if (mp->hw->max_rates > 1 ||
1127 		     mi->total_packets_cur < SAMPLE_SWITCH_THR)
1128 			update_interval /= 2;
1129 		break;
1130 
1131 	case MINSTREL_SAMPLE_ACTIVE:
1132 		if (!sample_status)
1133 			break;
1134 
1135 		mi->sample_mode = MINSTREL_SAMPLE_PENDING;
1136 		update = true;
1137 		break;
1138 
1139 	case MINSTREL_SAMPLE_PENDING:
1140 		if (sample_status)
1141 			break;
1142 
1143 		update = true;
1144 		minstrel_ht_update_stats(mp, mi, false);
1145 		break;
1146 	}
1147 
1148 
1149 	if (mp->hw->max_rates > 1) {
1150 		/*
1151 		 * check for sudden death of spatial multiplexing,
1152 		 * downgrade to a lower number of streams if necessary.
1153 		 */
1154 		rate = minstrel_get_ratestats(mi, mi->max_tp_rate[0]);
1155 		if (rate->attempts > 30 &&
1156 		    rate->success < rate->attempts / 4) {
1157 			minstrel_downgrade_rate(mi, &mi->max_tp_rate[0], true);
1158 			update = true;
1159 		}
1160 
1161 		rate2 = minstrel_get_ratestats(mi, mi->max_tp_rate[1]);
1162 		if (rate2->attempts > 30 &&
1163 		    rate2->success < rate2->attempts / 4) {
1164 			minstrel_downgrade_rate(mi, &mi->max_tp_rate[1], false);
1165 			update = true;
1166 		}
1167 	}
1168 
1169 	if (time_after(jiffies, mi->last_stats_update + update_interval)) {
1170 		update = true;
1171 		minstrel_ht_update_stats(mp, mi, true);
1172 	}
1173 
1174 	if (update)
1175 		minstrel_ht_update_rates(mp, mi);
1176 }
1177 
1178 static void
1179 minstrel_calc_retransmit(struct minstrel_priv *mp, struct minstrel_ht_sta *mi,
1180                          int index)
1181 {
1182 	struct minstrel_rate_stats *mrs;
1183 	unsigned int tx_time, tx_time_rtscts, tx_time_data;
1184 	unsigned int cw = mp->cw_min;
1185 	unsigned int ctime = 0;
1186 	unsigned int t_slot = 9; /* FIXME */
1187 	unsigned int ampdu_len = minstrel_ht_avg_ampdu_len(mi);
1188 	unsigned int overhead = 0, overhead_rtscts = 0;
1189 
1190 	mrs = minstrel_get_ratestats(mi, index);
1191 	if (mrs->prob_avg < MINSTREL_FRAC(1, 10)) {
1192 		mrs->retry_count = 1;
1193 		mrs->retry_count_rtscts = 1;
1194 		return;
1195 	}
1196 
1197 	mrs->retry_count = 2;
1198 	mrs->retry_count_rtscts = 2;
1199 	mrs->retry_updated = true;
1200 
1201 	tx_time_data = minstrel_get_duration(index) * ampdu_len / 1000;
1202 
1203 	/* Contention time for first 2 tries */
1204 	ctime = (t_slot * cw) >> 1;
1205 	cw = min((cw << 1) | 1, mp->cw_max);
1206 	ctime += (t_slot * cw) >> 1;
1207 	cw = min((cw << 1) | 1, mp->cw_max);
1208 
1209 	if (minstrel_ht_is_legacy_group(index / MCS_GROUP_RATES)) {
1210 		overhead = mi->overhead_legacy;
1211 		overhead_rtscts = mi->overhead_legacy_rtscts;
1212 	} else {
1213 		overhead = mi->overhead;
1214 		overhead_rtscts = mi->overhead_rtscts;
1215 	}
1216 
1217 	/* Total TX time for data and Contention after first 2 tries */
1218 	tx_time = ctime + 2 * (overhead + tx_time_data);
1219 	tx_time_rtscts = ctime + 2 * (overhead_rtscts + tx_time_data);
1220 
1221 	/* See how many more tries we can fit inside segment size */
1222 	do {
1223 		/* Contention time for this try */
1224 		ctime = (t_slot * cw) >> 1;
1225 		cw = min((cw << 1) | 1, mp->cw_max);
1226 
1227 		/* Total TX time after this try */
1228 		tx_time += ctime + overhead + tx_time_data;
1229 		tx_time_rtscts += ctime + overhead_rtscts + tx_time_data;
1230 
1231 		if (tx_time_rtscts < mp->segment_size)
1232 			mrs->retry_count_rtscts++;
1233 	} while ((tx_time < mp->segment_size) &&
1234 	         (++mrs->retry_count < mp->max_retry));
1235 }
1236 
1237 
1238 static void
1239 minstrel_ht_set_rate(struct minstrel_priv *mp, struct minstrel_ht_sta *mi,
1240                      struct ieee80211_sta_rates *ratetbl, int offset, int index)
1241 {
1242 	int group_idx = index / MCS_GROUP_RATES;
1243 	const struct mcs_group *group = &minstrel_mcs_groups[group_idx];
1244 	struct minstrel_rate_stats *mrs;
1245 	u8 idx;
1246 	u16 flags = group->flags;
1247 
1248 	mrs = minstrel_get_ratestats(mi, index);
1249 	if (!mrs->retry_updated)
1250 		minstrel_calc_retransmit(mp, mi, index);
1251 
1252 	if (mrs->prob_avg < MINSTREL_FRAC(20, 100) || !mrs->retry_count) {
1253 		ratetbl->rate[offset].count = 2;
1254 		ratetbl->rate[offset].count_rts = 2;
1255 		ratetbl->rate[offset].count_cts = 2;
1256 	} else {
1257 		ratetbl->rate[offset].count = mrs->retry_count;
1258 		ratetbl->rate[offset].count_cts = mrs->retry_count;
1259 		ratetbl->rate[offset].count_rts = mrs->retry_count_rtscts;
1260 	}
1261 
1262 	index %= MCS_GROUP_RATES;
1263 	if (group_idx == MINSTREL_CCK_GROUP)
1264 		idx = mp->cck_rates[index % ARRAY_SIZE(mp->cck_rates)];
1265 	else if (group_idx == MINSTREL_OFDM_GROUP)
1266 		idx = mp->ofdm_rates[mi->band][index %
1267 					       ARRAY_SIZE(mp->ofdm_rates[0])];
1268 	else if (flags & IEEE80211_TX_RC_VHT_MCS)
1269 		idx = ((group->streams - 1) << 4) |
1270 		      (index & 0xF);
1271 	else
1272 		idx = index + (group->streams - 1) * 8;
1273 
1274 	/* enable RTS/CTS if needed:
1275 	 *  - if station is in dynamic SMPS (and streams > 1)
1276 	 *  - for fallback rates, to increase chances of getting through
1277 	 */
1278 	if (offset > 0 ||
1279 	    (mi->sta->smps_mode == IEEE80211_SMPS_DYNAMIC &&
1280 	     group->streams > 1)) {
1281 		ratetbl->rate[offset].count = ratetbl->rate[offset].count_rts;
1282 		flags |= IEEE80211_TX_RC_USE_RTS_CTS;
1283 	}
1284 
1285 	ratetbl->rate[offset].idx = idx;
1286 	ratetbl->rate[offset].flags = flags;
1287 }
1288 
1289 static inline int
1290 minstrel_ht_get_prob_avg(struct minstrel_ht_sta *mi, int rate)
1291 {
1292 	int group = rate / MCS_GROUP_RATES;
1293 	rate %= MCS_GROUP_RATES;
1294 	return mi->groups[group].rates[rate].prob_avg;
1295 }
1296 
1297 static int
1298 minstrel_ht_get_max_amsdu_len(struct minstrel_ht_sta *mi)
1299 {
1300 	int group = mi->max_prob_rate / MCS_GROUP_RATES;
1301 	const struct mcs_group *g = &minstrel_mcs_groups[group];
1302 	int rate = mi->max_prob_rate % MCS_GROUP_RATES;
1303 	unsigned int duration;
1304 
1305 	/* Disable A-MSDU if max_prob_rate is bad */
1306 	if (mi->groups[group].rates[rate].prob_avg < MINSTREL_FRAC(50, 100))
1307 		return 1;
1308 
1309 	duration = g->duration[rate];
1310 	duration <<= g->shift;
1311 
1312 	/* If the rate is slower than single-stream MCS1, make A-MSDU limit small */
1313 	if (duration > MCS_DURATION(1, 0, 52))
1314 		return 500;
1315 
1316 	/*
1317 	 * If the rate is slower than single-stream MCS4, limit A-MSDU to usual
1318 	 * data packet size
1319 	 */
1320 	if (duration > MCS_DURATION(1, 0, 104))
1321 		return 1600;
1322 
1323 	/*
1324 	 * If the rate is slower than single-stream MCS7, or if the max throughput
1325 	 * rate success probability is less than 75%, limit A-MSDU to twice the usual
1326 	 * data packet size
1327 	 */
1328 	if (duration > MCS_DURATION(1, 0, 260) ||
1329 	    (minstrel_ht_get_prob_avg(mi, mi->max_tp_rate[0]) <
1330 	     MINSTREL_FRAC(75, 100)))
1331 		return 3200;
1332 
1333 	/*
1334 	 * HT A-MPDU limits maximum MPDU size under BA agreement to 4095 bytes.
1335 	 * Since aggregation sessions are started/stopped without txq flush, use
1336 	 * the limit here to avoid the complexity of having to de-aggregate
1337 	 * packets in the queue.
1338 	 */
1339 	if (!mi->sta->vht_cap.vht_supported)
1340 		return IEEE80211_MAX_MPDU_LEN_HT_BA;
1341 
1342 	/* unlimited */
1343 	return 0;
1344 }
1345 
1346 static void
1347 minstrel_ht_update_rates(struct minstrel_priv *mp, struct minstrel_ht_sta *mi)
1348 {
1349 	struct ieee80211_sta_rates *rates;
1350 	u16 first_rate = mi->max_tp_rate[0];
1351 	int i = 0;
1352 
1353 	if (mi->sample_mode == MINSTREL_SAMPLE_ACTIVE)
1354 		first_rate = mi->sample_rate;
1355 
1356 	rates = kzalloc(sizeof(*rates), GFP_ATOMIC);
1357 	if (!rates)
1358 		return;
1359 
1360 	/* Start with max_tp_rate[0] */
1361 	minstrel_ht_set_rate(mp, mi, rates, i++, first_rate);
1362 
1363 	if (mp->hw->max_rates >= 3) {
1364 		/* At least 3 tx rates supported, use max_tp_rate[1] next */
1365 		minstrel_ht_set_rate(mp, mi, rates, i++, mi->max_tp_rate[1]);
1366 	}
1367 
1368 	if (mp->hw->max_rates >= 2) {
1369 		minstrel_ht_set_rate(mp, mi, rates, i++, mi->max_prob_rate);
1370 	}
1371 
1372 	mi->sta->max_rc_amsdu_len = minstrel_ht_get_max_amsdu_len(mi);
1373 	rates->rate[i].idx = -1;
1374 	rate_control_set_rates(mp->hw, mi->sta, rates);
1375 }
1376 
1377 static int
1378 minstrel_get_sample_rate(struct minstrel_priv *mp, struct minstrel_ht_sta *mi)
1379 {
1380 	struct minstrel_rate_stats *mrs;
1381 	struct minstrel_mcs_group_data *mg;
1382 	unsigned int sample_dur, sample_group, cur_max_tp_streams;
1383 	int tp_rate1, tp_rate2;
1384 	int sample_idx = 0;
1385 
1386 	if (mp->hw->max_rates == 1 && mp->sample_switch &&
1387 	    (mi->total_packets_cur >= SAMPLE_SWITCH_THR ||
1388 	     mp->sample_switch == 1))
1389 		return -1;
1390 
1391 	if (mi->sample_wait > 0) {
1392 		mi->sample_wait--;
1393 		return -1;
1394 	}
1395 
1396 	if (!mi->sample_tries)
1397 		return -1;
1398 
1399 	sample_group = mi->sample_group;
1400 	mg = &mi->groups[sample_group];
1401 	sample_idx = sample_table[mg->column][mg->index];
1402 	minstrel_set_next_sample_idx(mi);
1403 
1404 	if (!(mi->supported[sample_group] & BIT(sample_idx)))
1405 		return -1;
1406 
1407 	mrs = &mg->rates[sample_idx];
1408 	sample_idx += sample_group * MCS_GROUP_RATES;
1409 
1410 	tp_rate1 = mi->max_tp_rate[0];
1411 
1412 	/* Set tp_rate2 to the second highest max_tp_rate */
1413 	if (minstrel_get_duration(mi->max_tp_rate[0]) >
1414 	    minstrel_get_duration(mi->max_tp_rate[1])) {
1415 		tp_rate2 = mi->max_tp_rate[0];
1416 	} else {
1417 		tp_rate2 = mi->max_tp_rate[1];
1418 	}
1419 
1420 	/*
1421 	 * Sampling might add some overhead (RTS, no aggregation)
1422 	 * to the frame. Hence, don't use sampling for the highest currently
1423 	 * used highest throughput or probability rate.
1424 	 */
1425 	if (sample_idx == mi->max_tp_rate[0] || sample_idx == mi->max_prob_rate)
1426 		return -1;
1427 
1428 	/*
1429 	 * Do not sample if the probability is already higher than 95%,
1430 	 * or if the rate is 3 times slower than the current max probability
1431 	 * rate, to avoid wasting airtime.
1432 	 */
1433 	sample_dur = minstrel_get_duration(sample_idx);
1434 	if (mrs->prob_avg > MINSTREL_FRAC(95, 100) ||
1435 	    minstrel_get_duration(mi->max_prob_rate) * 3 < sample_dur)
1436 		return -1;
1437 
1438 
1439 	/*
1440 	 * For devices with no configurable multi-rate retry, skip sampling
1441 	 * below the per-group max throughput rate, and only use one sampling
1442 	 * attempt per rate
1443 	 */
1444 	if (mp->hw->max_rates == 1 &&
1445 	    (minstrel_get_duration(mg->max_group_tp_rate[0]) < sample_dur ||
1446 	     mrs->attempts))
1447 		return -1;
1448 
1449 	/* Skip already sampled slow rates */
1450 	if (sample_dur >= minstrel_get_duration(tp_rate1) && mrs->attempts)
1451 		return -1;
1452 
1453 	/*
1454 	 * Make sure that lower rates get sampled only occasionally,
1455 	 * if the link is working perfectly.
1456 	 */
1457 
1458 	cur_max_tp_streams = minstrel_mcs_groups[tp_rate1 /
1459 		MCS_GROUP_RATES].streams;
1460 	if (sample_dur >= minstrel_get_duration(tp_rate2) &&
1461 	    (cur_max_tp_streams - 1 <
1462 	     minstrel_mcs_groups[sample_group].streams ||
1463 	     sample_dur >= minstrel_get_duration(mi->max_prob_rate))) {
1464 		if (mrs->sample_skipped < 20)
1465 			return -1;
1466 
1467 		if (mi->sample_slow++ > 2)
1468 			return -1;
1469 	}
1470 	mi->sample_tries--;
1471 
1472 	return sample_idx;
1473 }
1474 
1475 static void
1476 minstrel_ht_get_rate(void *priv, struct ieee80211_sta *sta, void *priv_sta,
1477                      struct ieee80211_tx_rate_control *txrc)
1478 {
1479 	const struct mcs_group *sample_group;
1480 	struct ieee80211_tx_info *info = IEEE80211_SKB_CB(txrc->skb);
1481 	struct ieee80211_tx_rate *rate = &info->status.rates[0];
1482 	struct minstrel_ht_sta *mi = priv_sta;
1483 	struct minstrel_priv *mp = priv;
1484 	int sample_idx;
1485 
1486 	if (!(info->flags & IEEE80211_TX_CTL_AMPDU) &&
1487 	    !minstrel_ht_is_legacy_group(mi->max_prob_rate / MCS_GROUP_RATES))
1488 		minstrel_aggr_check(sta, txrc->skb);
1489 
1490 	info->flags |= mi->tx_flags;
1491 
1492 #ifdef CONFIG_MAC80211_DEBUGFS
1493 	if (mp->fixed_rate_idx != -1)
1494 		return;
1495 #endif
1496 
1497 	/* Don't use EAPOL frames for sampling on non-mrr hw */
1498 	if (mp->hw->max_rates == 1 &&
1499 	    (info->control.flags & IEEE80211_TX_CTRL_PORT_CTRL_PROTO))
1500 		sample_idx = -1;
1501 	else
1502 		sample_idx = minstrel_get_sample_rate(mp, mi);
1503 
1504 	mi->total_packets++;
1505 
1506 	/* wraparound */
1507 	if (mi->total_packets == ~0) {
1508 		mi->total_packets = 0;
1509 		mi->sample_packets = 0;
1510 	}
1511 
1512 	if (sample_idx < 0)
1513 		return;
1514 
1515 	sample_group = &minstrel_mcs_groups[sample_idx / MCS_GROUP_RATES];
1516 	sample_idx %= MCS_GROUP_RATES;
1517 
1518 	if (sample_group == &minstrel_mcs_groups[MINSTREL_CCK_GROUP] &&
1519 	    (sample_idx >= 4) != txrc->short_preamble)
1520 		return;
1521 
1522 	info->flags |= IEEE80211_TX_CTL_RATE_CTRL_PROBE;
1523 	rate->count = 1;
1524 
1525 	if (sample_group == &minstrel_mcs_groups[MINSTREL_CCK_GROUP]) {
1526 		int idx = sample_idx % ARRAY_SIZE(mp->cck_rates);
1527 		rate->idx = mp->cck_rates[idx];
1528 	} else if (sample_group == &minstrel_mcs_groups[MINSTREL_OFDM_GROUP]) {
1529 		int idx = sample_idx % ARRAY_SIZE(mp->ofdm_rates[0]);
1530 		rate->idx = mp->ofdm_rates[mi->band][idx];
1531 	} else if (sample_group->flags & IEEE80211_TX_RC_VHT_MCS) {
1532 		ieee80211_rate_set_vht(rate, sample_idx % MCS_GROUP_RATES,
1533 				       sample_group->streams);
1534 	} else {
1535 		rate->idx = sample_idx + (sample_group->streams - 1) * 8;
1536 	}
1537 
1538 	rate->flags = sample_group->flags;
1539 }
1540 
1541 static void
1542 minstrel_ht_update_cck(struct minstrel_priv *mp, struct minstrel_ht_sta *mi,
1543 		       struct ieee80211_supported_band *sband,
1544 		       struct ieee80211_sta *sta)
1545 {
1546 	int i;
1547 
1548 	if (sband->band != NL80211_BAND_2GHZ)
1549 		return;
1550 
1551 	if (sta->ht_cap.ht_supported &&
1552 	    !ieee80211_hw_check(mp->hw, SUPPORTS_HT_CCK_RATES))
1553 		return;
1554 
1555 	for (i = 0; i < 4; i++) {
1556 		if (mp->cck_rates[i] == 0xff ||
1557 		    !rate_supported(sta, sband->band, mp->cck_rates[i]))
1558 			continue;
1559 
1560 		mi->supported[MINSTREL_CCK_GROUP] |= BIT(i);
1561 		if (sband->bitrates[i].flags & IEEE80211_RATE_SHORT_PREAMBLE)
1562 			mi->supported[MINSTREL_CCK_GROUP] |= BIT(i + 4);
1563 	}
1564 }
1565 
1566 static void
1567 minstrel_ht_update_ofdm(struct minstrel_priv *mp, struct minstrel_ht_sta *mi,
1568 			struct ieee80211_supported_band *sband,
1569 			struct ieee80211_sta *sta)
1570 {
1571 	const u8 *rates;
1572 	int i;
1573 
1574 	if (sta->ht_cap.ht_supported)
1575 		return;
1576 
1577 	rates = mp->ofdm_rates[sband->band];
1578 	for (i = 0; i < ARRAY_SIZE(mp->ofdm_rates[0]); i++) {
1579 		if (rates[i] == 0xff ||
1580 		    !rate_supported(sta, sband->band, rates[i]))
1581 			continue;
1582 
1583 		mi->supported[MINSTREL_OFDM_GROUP] |= BIT(i);
1584 	}
1585 }
1586 
1587 static void
1588 minstrel_ht_update_caps(void *priv, struct ieee80211_supported_band *sband,
1589 			struct cfg80211_chan_def *chandef,
1590 			struct ieee80211_sta *sta, void *priv_sta)
1591 {
1592 	struct minstrel_priv *mp = priv;
1593 	struct minstrel_ht_sta *mi = priv_sta;
1594 	struct ieee80211_mcs_info *mcs = &sta->ht_cap.mcs;
1595 	u16 ht_cap = sta->ht_cap.cap;
1596 	struct ieee80211_sta_vht_cap *vht_cap = &sta->vht_cap;
1597 	const struct ieee80211_rate *ctl_rate;
1598 	bool ldpc, erp;
1599 	int use_vht;
1600 	int n_supported = 0;
1601 	int ack_dur;
1602 	int stbc;
1603 	int i;
1604 
1605 	BUILD_BUG_ON(ARRAY_SIZE(minstrel_mcs_groups) != MINSTREL_GROUPS_NB);
1606 
1607 	if (vht_cap->vht_supported)
1608 		use_vht = vht_cap->vht_mcs.tx_mcs_map != cpu_to_le16(~0);
1609 	else
1610 		use_vht = 0;
1611 
1612 	memset(mi, 0, sizeof(*mi));
1613 
1614 	mi->sta = sta;
1615 	mi->band = sband->band;
1616 	mi->last_stats_update = jiffies;
1617 
1618 	ack_dur = ieee80211_frame_duration(sband->band, 10, 60, 1, 1, 0);
1619 	mi->overhead = ieee80211_frame_duration(sband->band, 0, 60, 1, 1, 0);
1620 	mi->overhead += ack_dur;
1621 	mi->overhead_rtscts = mi->overhead + 2 * ack_dur;
1622 
1623 	ctl_rate = &sband->bitrates[rate_lowest_index(sband, sta)];
1624 	erp = ctl_rate->flags & IEEE80211_RATE_ERP_G;
1625 	ack_dur = ieee80211_frame_duration(sband->band, 10,
1626 					   ctl_rate->bitrate, erp, 1,
1627 					   ieee80211_chandef_get_shift(chandef));
1628 	mi->overhead_legacy = ack_dur;
1629 	mi->overhead_legacy_rtscts = mi->overhead_legacy + 2 * ack_dur;
1630 
1631 	mi->avg_ampdu_len = MINSTREL_FRAC(1, 1);
1632 
1633 	/* When using MRR, sample more on the first attempt, without delay */
1634 	if (mp->has_mrr) {
1635 		mi->sample_count = 16;
1636 		mi->sample_wait = 0;
1637 	} else {
1638 		mi->sample_count = 8;
1639 		mi->sample_wait = 8;
1640 	}
1641 	mi->sample_tries = 4;
1642 
1643 	if (!use_vht) {
1644 		stbc = (ht_cap & IEEE80211_HT_CAP_RX_STBC) >>
1645 			IEEE80211_HT_CAP_RX_STBC_SHIFT;
1646 
1647 		ldpc = ht_cap & IEEE80211_HT_CAP_LDPC_CODING;
1648 	} else {
1649 		stbc = (vht_cap->cap & IEEE80211_VHT_CAP_RXSTBC_MASK) >>
1650 			IEEE80211_VHT_CAP_RXSTBC_SHIFT;
1651 
1652 		ldpc = vht_cap->cap & IEEE80211_VHT_CAP_RXLDPC;
1653 	}
1654 
1655 	mi->tx_flags |= stbc << IEEE80211_TX_CTL_STBC_SHIFT;
1656 	if (ldpc)
1657 		mi->tx_flags |= IEEE80211_TX_CTL_LDPC;
1658 
1659 	for (i = 0; i < ARRAY_SIZE(mi->groups); i++) {
1660 		u32 gflags = minstrel_mcs_groups[i].flags;
1661 		int bw, nss;
1662 
1663 		mi->supported[i] = 0;
1664 		if (minstrel_ht_is_legacy_group(i))
1665 			continue;
1666 
1667 		if (gflags & IEEE80211_TX_RC_SHORT_GI) {
1668 			if (gflags & IEEE80211_TX_RC_40_MHZ_WIDTH) {
1669 				if (!(ht_cap & IEEE80211_HT_CAP_SGI_40))
1670 					continue;
1671 			} else {
1672 				if (!(ht_cap & IEEE80211_HT_CAP_SGI_20))
1673 					continue;
1674 			}
1675 		}
1676 
1677 		if (gflags & IEEE80211_TX_RC_40_MHZ_WIDTH &&
1678 		    sta->bandwidth < IEEE80211_STA_RX_BW_40)
1679 			continue;
1680 
1681 		nss = minstrel_mcs_groups[i].streams;
1682 
1683 		/* Mark MCS > 7 as unsupported if STA is in static SMPS mode */
1684 		if (sta->smps_mode == IEEE80211_SMPS_STATIC && nss > 1)
1685 			continue;
1686 
1687 		/* HT rate */
1688 		if (gflags & IEEE80211_TX_RC_MCS) {
1689 			if (use_vht && minstrel_vht_only)
1690 				continue;
1691 
1692 			mi->supported[i] = mcs->rx_mask[nss - 1];
1693 			if (mi->supported[i])
1694 				n_supported++;
1695 			continue;
1696 		}
1697 
1698 		/* VHT rate */
1699 		if (!vht_cap->vht_supported ||
1700 		    WARN_ON(!(gflags & IEEE80211_TX_RC_VHT_MCS)) ||
1701 		    WARN_ON(gflags & IEEE80211_TX_RC_160_MHZ_WIDTH))
1702 			continue;
1703 
1704 		if (gflags & IEEE80211_TX_RC_80_MHZ_WIDTH) {
1705 			if (sta->bandwidth < IEEE80211_STA_RX_BW_80 ||
1706 			    ((gflags & IEEE80211_TX_RC_SHORT_GI) &&
1707 			     !(vht_cap->cap & IEEE80211_VHT_CAP_SHORT_GI_80))) {
1708 				continue;
1709 			}
1710 		}
1711 
1712 		if (gflags & IEEE80211_TX_RC_40_MHZ_WIDTH)
1713 			bw = BW_40;
1714 		else if (gflags & IEEE80211_TX_RC_80_MHZ_WIDTH)
1715 			bw = BW_80;
1716 		else
1717 			bw = BW_20;
1718 
1719 		mi->supported[i] = minstrel_get_valid_vht_rates(bw, nss,
1720 				vht_cap->vht_mcs.tx_mcs_map);
1721 
1722 		if (mi->supported[i])
1723 			n_supported++;
1724 	}
1725 
1726 	minstrel_ht_update_cck(mp, mi, sband, sta);
1727 	minstrel_ht_update_ofdm(mp, mi, sband, sta);
1728 
1729 	/* create an initial rate table with the lowest supported rates */
1730 	minstrel_ht_update_stats(mp, mi, true);
1731 	minstrel_ht_update_rates(mp, mi);
1732 }
1733 
1734 static void
1735 minstrel_ht_rate_init(void *priv, struct ieee80211_supported_band *sband,
1736 		      struct cfg80211_chan_def *chandef,
1737                       struct ieee80211_sta *sta, void *priv_sta)
1738 {
1739 	minstrel_ht_update_caps(priv, sband, chandef, sta, priv_sta);
1740 }
1741 
1742 static void
1743 minstrel_ht_rate_update(void *priv, struct ieee80211_supported_band *sband,
1744 			struct cfg80211_chan_def *chandef,
1745                         struct ieee80211_sta *sta, void *priv_sta,
1746                         u32 changed)
1747 {
1748 	minstrel_ht_update_caps(priv, sband, chandef, sta, priv_sta);
1749 }
1750 
1751 static void *
1752 minstrel_ht_alloc_sta(void *priv, struct ieee80211_sta *sta, gfp_t gfp)
1753 {
1754 	struct ieee80211_supported_band *sband;
1755 	struct minstrel_ht_sta *mi;
1756 	struct minstrel_priv *mp = priv;
1757 	struct ieee80211_hw *hw = mp->hw;
1758 	int max_rates = 0;
1759 	int i;
1760 
1761 	for (i = 0; i < NUM_NL80211_BANDS; i++) {
1762 		sband = hw->wiphy->bands[i];
1763 		if (sband && sband->n_bitrates > max_rates)
1764 			max_rates = sband->n_bitrates;
1765 	}
1766 
1767 	return kzalloc(sizeof(*mi), gfp);
1768 }
1769 
1770 static void
1771 minstrel_ht_free_sta(void *priv, struct ieee80211_sta *sta, void *priv_sta)
1772 {
1773 	kfree(priv_sta);
1774 }
1775 
1776 static void
1777 minstrel_ht_fill_rate_array(u8 *dest, struct ieee80211_supported_band *sband,
1778 			    const s16 *bitrates, int n_rates, u32 rate_flags)
1779 {
1780 	int i, j;
1781 
1782 	for (i = 0; i < sband->n_bitrates; i++) {
1783 		struct ieee80211_rate *rate = &sband->bitrates[i];
1784 
1785 		if ((rate_flags & sband->bitrates[i].flags) != rate_flags)
1786 			continue;
1787 
1788 		for (j = 0; j < n_rates; j++) {
1789 			if (rate->bitrate != bitrates[j])
1790 				continue;
1791 
1792 			dest[j] = i;
1793 			break;
1794 		}
1795 	}
1796 }
1797 
1798 static void
1799 minstrel_ht_init_cck_rates(struct minstrel_priv *mp)
1800 {
1801 	static const s16 bitrates[4] = { 10, 20, 55, 110 };
1802 	struct ieee80211_supported_band *sband;
1803 	u32 rate_flags = ieee80211_chandef_rate_flags(&mp->hw->conf.chandef);
1804 
1805 	memset(mp->cck_rates, 0xff, sizeof(mp->cck_rates));
1806 	sband = mp->hw->wiphy->bands[NL80211_BAND_2GHZ];
1807 	if (!sband)
1808 		return;
1809 
1810 	BUILD_BUG_ON(ARRAY_SIZE(mp->cck_rates) != ARRAY_SIZE(bitrates));
1811 	minstrel_ht_fill_rate_array(mp->cck_rates, sband,
1812 				    minstrel_cck_bitrates,
1813 				    ARRAY_SIZE(minstrel_cck_bitrates),
1814 				    rate_flags);
1815 }
1816 
1817 static void
1818 minstrel_ht_init_ofdm_rates(struct minstrel_priv *mp, enum nl80211_band band)
1819 {
1820 	static const s16 bitrates[8] = { 60, 90, 120, 180, 240, 360, 480, 540 };
1821 	struct ieee80211_supported_band *sband;
1822 	u32 rate_flags = ieee80211_chandef_rate_flags(&mp->hw->conf.chandef);
1823 
1824 	memset(mp->ofdm_rates[band], 0xff, sizeof(mp->ofdm_rates[band]));
1825 	sband = mp->hw->wiphy->bands[band];
1826 	if (!sband)
1827 		return;
1828 
1829 	BUILD_BUG_ON(ARRAY_SIZE(mp->ofdm_rates[band]) != ARRAY_SIZE(bitrates));
1830 	minstrel_ht_fill_rate_array(mp->ofdm_rates[band], sband,
1831 				    minstrel_ofdm_bitrates,
1832 				    ARRAY_SIZE(minstrel_ofdm_bitrates),
1833 				    rate_flags);
1834 }
1835 
1836 static void *
1837 minstrel_ht_alloc(struct ieee80211_hw *hw)
1838 {
1839 	struct minstrel_priv *mp;
1840 	int i;
1841 
1842 	mp = kzalloc(sizeof(struct minstrel_priv), GFP_ATOMIC);
1843 	if (!mp)
1844 		return NULL;
1845 
1846 	mp->sample_switch = -1;
1847 
1848 	/* contention window settings
1849 	 * Just an approximation. Using the per-queue values would complicate
1850 	 * the calculations and is probably unnecessary */
1851 	mp->cw_min = 15;
1852 	mp->cw_max = 1023;
1853 
1854 	/* maximum time that the hw is allowed to stay in one MRR segment */
1855 	mp->segment_size = 6000;
1856 
1857 	if (hw->max_rate_tries > 0)
1858 		mp->max_retry = hw->max_rate_tries;
1859 	else
1860 		/* safe default, does not necessarily have to match hw properties */
1861 		mp->max_retry = 7;
1862 
1863 	if (hw->max_rates >= 4)
1864 		mp->has_mrr = true;
1865 
1866 	mp->hw = hw;
1867 	mp->update_interval = HZ / 10;
1868 
1869 	minstrel_ht_init_cck_rates(mp);
1870 	for (i = 0; i < ARRAY_SIZE(mp->hw->wiphy->bands); i++)
1871 	    minstrel_ht_init_ofdm_rates(mp, i);
1872 
1873 	return mp;
1874 }
1875 
1876 #ifdef CONFIG_MAC80211_DEBUGFS
1877 static void minstrel_ht_add_debugfs(struct ieee80211_hw *hw, void *priv,
1878 				    struct dentry *debugfsdir)
1879 {
1880 	struct minstrel_priv *mp = priv;
1881 
1882 	mp->fixed_rate_idx = (u32) -1;
1883 	debugfs_create_u32("fixed_rate_idx", S_IRUGO | S_IWUGO, debugfsdir,
1884 			   &mp->fixed_rate_idx);
1885 	debugfs_create_u32("sample_switch", S_IRUGO | S_IWUSR, debugfsdir,
1886 			   &mp->sample_switch);
1887 }
1888 #endif
1889 
1890 static void
1891 minstrel_ht_free(void *priv)
1892 {
1893 	kfree(priv);
1894 }
1895 
1896 static u32 minstrel_ht_get_expected_throughput(void *priv_sta)
1897 {
1898 	struct minstrel_ht_sta *mi = priv_sta;
1899 	int i, j, prob, tp_avg;
1900 
1901 	i = mi->max_tp_rate[0] / MCS_GROUP_RATES;
1902 	j = mi->max_tp_rate[0] % MCS_GROUP_RATES;
1903 	prob = mi->groups[i].rates[j].prob_avg;
1904 
1905 	/* convert tp_avg from pkt per second in kbps */
1906 	tp_avg = minstrel_ht_get_tp_avg(mi, i, j, prob) * 10;
1907 	tp_avg = tp_avg * AVG_PKT_SIZE * 8 / 1024;
1908 
1909 	return tp_avg;
1910 }
1911 
1912 static const struct rate_control_ops mac80211_minstrel_ht = {
1913 	.name = "minstrel_ht",
1914 	.tx_status_ext = minstrel_ht_tx_status,
1915 	.get_rate = minstrel_ht_get_rate,
1916 	.rate_init = minstrel_ht_rate_init,
1917 	.rate_update = minstrel_ht_rate_update,
1918 	.alloc_sta = minstrel_ht_alloc_sta,
1919 	.free_sta = minstrel_ht_free_sta,
1920 	.alloc = minstrel_ht_alloc,
1921 	.free = minstrel_ht_free,
1922 #ifdef CONFIG_MAC80211_DEBUGFS
1923 	.add_debugfs = minstrel_ht_add_debugfs,
1924 	.add_sta_debugfs = minstrel_ht_add_sta_debugfs,
1925 #endif
1926 	.get_expected_throughput = minstrel_ht_get_expected_throughput,
1927 };
1928 
1929 
1930 static void __init init_sample_table(void)
1931 {
1932 	int col, i, new_idx;
1933 	u8 rnd[MCS_GROUP_RATES];
1934 
1935 	memset(sample_table, 0xff, sizeof(sample_table));
1936 	for (col = 0; col < SAMPLE_COLUMNS; col++) {
1937 		prandom_bytes(rnd, sizeof(rnd));
1938 		for (i = 0; i < MCS_GROUP_RATES; i++) {
1939 			new_idx = (i + rnd[i]) % MCS_GROUP_RATES;
1940 			while (sample_table[col][new_idx] != 0xff)
1941 				new_idx = (new_idx + 1) % MCS_GROUP_RATES;
1942 
1943 			sample_table[col][new_idx] = i;
1944 		}
1945 	}
1946 }
1947 
1948 int __init
1949 rc80211_minstrel_init(void)
1950 {
1951 	init_sample_table();
1952 	return ieee80211_rate_control_register(&mac80211_minstrel_ht);
1953 }
1954 
1955 void
1956 rc80211_minstrel_exit(void)
1957 {
1958 	ieee80211_rate_control_unregister(&mac80211_minstrel_ht);
1959 }
1960