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/moduleparam.h>
14 #include <linux/ieee80211.h>
15 #include <net/mac80211.h>
16 #include "rate.h"
17 #include "sta_info.h"
18 #include "rc80211_minstrel.h"
19 #include "rc80211_minstrel_ht.h"
20 
21 #define AVG_AMPDU_SIZE	16
22 #define AVG_PKT_SIZE	1200
23 
24 /* Number of bits for an average sized packet */
25 #define MCS_NBITS ((AVG_PKT_SIZE * AVG_AMPDU_SIZE) << 3)
26 
27 /* Number of symbols for a packet with (bps) bits per symbol */
28 #define MCS_NSYMS(bps) DIV_ROUND_UP(MCS_NBITS, (bps))
29 
30 /* Transmission time (nanoseconds) for a packet containing (syms) symbols */
31 #define MCS_SYMBOL_TIME(sgi, syms)					\
32 	(sgi ?								\
33 	  ((syms) * 18000 + 4000) / 5 :	/* syms * 3.6 us */		\
34 	  ((syms) * 1000) << 2		/* syms * 4 us */		\
35 	)
36 
37 /* Transmit duration for the raw data part of an average sized packet */
38 #define MCS_DURATION(streams, sgi, bps) \
39 	(MCS_SYMBOL_TIME(sgi, MCS_NSYMS((streams) * (bps))) / AVG_AMPDU_SIZE)
40 
41 #define BW_20			0
42 #define BW_40			1
43 #define BW_80			2
44 
45 /*
46  * Define group sort order: HT40 -> SGI -> #streams
47  */
48 #define GROUP_IDX(_streams, _sgi, _ht40)	\
49 	MINSTREL_HT_GROUP_0 +			\
50 	MINSTREL_MAX_STREAMS * 2 * _ht40 +	\
51 	MINSTREL_MAX_STREAMS * _sgi +	\
52 	_streams - 1
53 
54 /* MCS rate information for an MCS group */
55 #define MCS_GROUP(_streams, _sgi, _ht40, _s)				\
56 	[GROUP_IDX(_streams, _sgi, _ht40)] = {				\
57 	.streams = _streams,						\
58 	.shift = _s,							\
59 	.flags =							\
60 		IEEE80211_TX_RC_MCS |					\
61 		(_sgi ? IEEE80211_TX_RC_SHORT_GI : 0) |			\
62 		(_ht40 ? IEEE80211_TX_RC_40_MHZ_WIDTH : 0),		\
63 	.duration = {							\
64 		MCS_DURATION(_streams, _sgi, _ht40 ? 54 : 26) >> _s,	\
65 		MCS_DURATION(_streams, _sgi, _ht40 ? 108 : 52) >> _s,	\
66 		MCS_DURATION(_streams, _sgi, _ht40 ? 162 : 78) >> _s,	\
67 		MCS_DURATION(_streams, _sgi, _ht40 ? 216 : 104) >> _s,	\
68 		MCS_DURATION(_streams, _sgi, _ht40 ? 324 : 156) >> _s,	\
69 		MCS_DURATION(_streams, _sgi, _ht40 ? 432 : 208) >> _s,	\
70 		MCS_DURATION(_streams, _sgi, _ht40 ? 486 : 234) >> _s,	\
71 		MCS_DURATION(_streams, _sgi, _ht40 ? 540 : 260) >> _s	\
72 	}								\
73 }
74 
75 #define VHT_GROUP_IDX(_streams, _sgi, _bw)				\
76 	(MINSTREL_VHT_GROUP_0 +						\
77 	 MINSTREL_MAX_STREAMS * 2 * (_bw) +				\
78 	 MINSTREL_MAX_STREAMS * (_sgi) +				\
79 	 (_streams) - 1)
80 
81 #define BW2VBPS(_bw, r3, r2, r1)					\
82 	(_bw == BW_80 ? r3 : _bw == BW_40 ? r2 : r1)
83 
84 #define VHT_GROUP(_streams, _sgi, _bw, _s)				\
85 	[VHT_GROUP_IDX(_streams, _sgi, _bw)] = {			\
86 	.streams = _streams,						\
87 	.shift = _s,							\
88 	.flags =							\
89 		IEEE80211_TX_RC_VHT_MCS |				\
90 		(_sgi ? IEEE80211_TX_RC_SHORT_GI : 0) |			\
91 		(_bw == BW_80 ? IEEE80211_TX_RC_80_MHZ_WIDTH :		\
92 		 _bw == BW_40 ? IEEE80211_TX_RC_40_MHZ_WIDTH : 0),	\
93 	.duration = {							\
94 		MCS_DURATION(_streams, _sgi,				\
95 			     BW2VBPS(_bw,  117,  54,  26)) >> _s,	\
96 		MCS_DURATION(_streams, _sgi,				\
97 			     BW2VBPS(_bw,  234, 108,  52)) >> _s,	\
98 		MCS_DURATION(_streams, _sgi,				\
99 			     BW2VBPS(_bw,  351, 162,  78)) >> _s,	\
100 		MCS_DURATION(_streams, _sgi,				\
101 			     BW2VBPS(_bw,  468, 216, 104)) >> _s,	\
102 		MCS_DURATION(_streams, _sgi,				\
103 			     BW2VBPS(_bw,  702, 324, 156)) >> _s,	\
104 		MCS_DURATION(_streams, _sgi,				\
105 			     BW2VBPS(_bw,  936, 432, 208)) >> _s,	\
106 		MCS_DURATION(_streams, _sgi,				\
107 			     BW2VBPS(_bw, 1053, 486, 234)) >> _s,	\
108 		MCS_DURATION(_streams, _sgi,				\
109 			     BW2VBPS(_bw, 1170, 540, 260)) >> _s,	\
110 		MCS_DURATION(_streams, _sgi,				\
111 			     BW2VBPS(_bw, 1404, 648, 312)) >> _s,	\
112 		MCS_DURATION(_streams, _sgi,				\
113 			     BW2VBPS(_bw, 1560, 720, 346)) >> _s	\
114 	}								\
115 }
116 
117 #define CCK_DURATION(_bitrate, _short, _len)		\
118 	(1000 * (10 /* SIFS */ +			\
119 	 (_short ? 72 + 24 : 144 + 48) +		\
120 	 (8 * (_len + 4) * 10) / (_bitrate)))
121 
122 #define CCK_ACK_DURATION(_bitrate, _short)			\
123 	(CCK_DURATION((_bitrate > 10 ? 20 : 10), false, 60) +	\
124 	 CCK_DURATION(_bitrate, _short, AVG_PKT_SIZE))
125 
126 #define CCK_DURATION_LIST(_short, _s)			\
127 	CCK_ACK_DURATION(10, _short) >> _s,		\
128 	CCK_ACK_DURATION(20, _short) >> _s,		\
129 	CCK_ACK_DURATION(55, _short) >> _s,		\
130 	CCK_ACK_DURATION(110, _short) >> _s
131 
132 #define CCK_GROUP(_s)					\
133 	[MINSTREL_CCK_GROUP] = {			\
134 		.streams = 1,				\
135 		.flags = 0,				\
136 		.shift = _s,				\
137 		.duration = {				\
138 			CCK_DURATION_LIST(false, _s),	\
139 			CCK_DURATION_LIST(true, _s)	\
140 		}					\
141 	}
142 
143 static bool minstrel_vht_only = true;
144 module_param(minstrel_vht_only, bool, 0644);
145 MODULE_PARM_DESC(minstrel_vht_only,
146 		 "Use only VHT rates when VHT is supported by sta.");
147 
148 /*
149  * To enable sufficiently targeted rate sampling, MCS rates are divided into
150  * groups, based on the number of streams and flags (HT40, SGI) that they
151  * use.
152  *
153  * Sortorder has to be fixed for GROUP_IDX macro to be applicable:
154  * BW -> SGI -> #streams
155  */
156 const struct mcs_group minstrel_mcs_groups[] = {
157 	MCS_GROUP(1, 0, BW_20, 5),
158 	MCS_GROUP(2, 0, BW_20, 4),
159 	MCS_GROUP(3, 0, BW_20, 4),
160 
161 	MCS_GROUP(1, 1, BW_20, 5),
162 	MCS_GROUP(2, 1, BW_20, 4),
163 	MCS_GROUP(3, 1, BW_20, 4),
164 
165 	MCS_GROUP(1, 0, BW_40, 4),
166 	MCS_GROUP(2, 0, BW_40, 4),
167 	MCS_GROUP(3, 0, BW_40, 4),
168 
169 	MCS_GROUP(1, 1, BW_40, 4),
170 	MCS_GROUP(2, 1, BW_40, 4),
171 	MCS_GROUP(3, 1, BW_40, 4),
172 
173 	CCK_GROUP(8),
174 
175 	VHT_GROUP(1, 0, BW_20, 5),
176 	VHT_GROUP(2, 0, BW_20, 4),
177 	VHT_GROUP(3, 0, BW_20, 4),
178 
179 	VHT_GROUP(1, 1, BW_20, 5),
180 	VHT_GROUP(2, 1, BW_20, 4),
181 	VHT_GROUP(3, 1, BW_20, 4),
182 
183 	VHT_GROUP(1, 0, BW_40, 4),
184 	VHT_GROUP(2, 0, BW_40, 4),
185 	VHT_GROUP(3, 0, BW_40, 4),
186 
187 	VHT_GROUP(1, 1, BW_40, 4),
188 	VHT_GROUP(2, 1, BW_40, 4),
189 	VHT_GROUP(3, 1, BW_40, 4),
190 
191 	VHT_GROUP(1, 0, BW_80, 4),
192 	VHT_GROUP(2, 0, BW_80, 4),
193 	VHT_GROUP(3, 0, BW_80, 4),
194 
195 	VHT_GROUP(1, 1, BW_80, 4),
196 	VHT_GROUP(2, 1, BW_80, 4),
197 	VHT_GROUP(3, 1, BW_80, 4),
198 };
199 
200 static u8 sample_table[SAMPLE_COLUMNS][MCS_GROUP_RATES] __read_mostly;
201 
202 static void
203 minstrel_ht_update_rates(struct minstrel_priv *mp, struct minstrel_ht_sta *mi);
204 
205 /*
206  * Some VHT MCSes are invalid (when Ndbps / Nes is not an integer)
207  * e.g for MCS9@20MHzx1Nss: Ndbps=8x52*(5/6) Nes=1
208  *
209  * Returns the valid mcs map for struct minstrel_mcs_group_data.supported
210  */
211 static u16
212 minstrel_get_valid_vht_rates(int bw, int nss, __le16 mcs_map)
213 {
214 	u16 mask = 0;
215 
216 	if (bw == BW_20) {
217 		if (nss != 3 && nss != 6)
218 			mask = BIT(9);
219 	} else if (bw == BW_80) {
220 		if (nss == 3 || nss == 7)
221 			mask = BIT(6);
222 		else if (nss == 6)
223 			mask = BIT(9);
224 	} else {
225 		WARN_ON(bw != BW_40);
226 	}
227 
228 	switch ((le16_to_cpu(mcs_map) >> (2 * (nss - 1))) & 3) {
229 	case IEEE80211_VHT_MCS_SUPPORT_0_7:
230 		mask |= 0x300;
231 		break;
232 	case IEEE80211_VHT_MCS_SUPPORT_0_8:
233 		mask |= 0x200;
234 		break;
235 	case IEEE80211_VHT_MCS_SUPPORT_0_9:
236 		break;
237 	default:
238 		mask = 0x3ff;
239 	}
240 
241 	return 0x3ff & ~mask;
242 }
243 
244 /*
245  * Look up an MCS group index based on mac80211 rate information
246  */
247 static int
248 minstrel_ht_get_group_idx(struct ieee80211_tx_rate *rate)
249 {
250 	return GROUP_IDX((rate->idx / 8) + 1,
251 			 !!(rate->flags & IEEE80211_TX_RC_SHORT_GI),
252 			 !!(rate->flags & IEEE80211_TX_RC_40_MHZ_WIDTH));
253 }
254 
255 static int
256 minstrel_vht_get_group_idx(struct ieee80211_tx_rate *rate)
257 {
258 	return VHT_GROUP_IDX(ieee80211_rate_get_vht_nss(rate),
259 			     !!(rate->flags & IEEE80211_TX_RC_SHORT_GI),
260 			     !!(rate->flags & IEEE80211_TX_RC_40_MHZ_WIDTH) +
261 			     2*!!(rate->flags & IEEE80211_TX_RC_80_MHZ_WIDTH));
262 }
263 
264 static struct minstrel_rate_stats *
265 minstrel_ht_get_stats(struct minstrel_priv *mp, struct minstrel_ht_sta *mi,
266 		      struct ieee80211_tx_rate *rate)
267 {
268 	int group, idx;
269 
270 	if (rate->flags & IEEE80211_TX_RC_MCS) {
271 		group = minstrel_ht_get_group_idx(rate);
272 		idx = rate->idx % 8;
273 	} else if (rate->flags & IEEE80211_TX_RC_VHT_MCS) {
274 		group = minstrel_vht_get_group_idx(rate);
275 		idx = ieee80211_rate_get_vht_mcs(rate);
276 	} else {
277 		group = MINSTREL_CCK_GROUP;
278 
279 		for (idx = 0; idx < ARRAY_SIZE(mp->cck_rates); idx++)
280 			if (rate->idx == mp->cck_rates[idx])
281 				break;
282 
283 		/* short preamble */
284 		if ((mi->supported[group] & BIT(idx + 4)) &&
285 		    (rate->flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE))
286 			idx += 4;
287 	}
288 	return &mi->groups[group].rates[idx];
289 }
290 
291 static inline struct minstrel_rate_stats *
292 minstrel_get_ratestats(struct minstrel_ht_sta *mi, int index)
293 {
294 	return &mi->groups[index / MCS_GROUP_RATES].rates[index % MCS_GROUP_RATES];
295 }
296 
297 static unsigned int
298 minstrel_ht_avg_ampdu_len(struct minstrel_ht_sta *mi)
299 {
300 	if (!mi->avg_ampdu_len)
301 		return AVG_AMPDU_SIZE;
302 
303 	return MINSTREL_TRUNC(mi->avg_ampdu_len);
304 }
305 
306 /*
307  * Return current throughput based on the average A-MPDU length, taking into
308  * account the expected number of retransmissions and their expected length
309  */
310 int
311 minstrel_ht_get_tp_avg(struct minstrel_ht_sta *mi, int group, int rate,
312 		       int prob_ewma)
313 {
314 	unsigned int nsecs = 0;
315 
316 	/* do not account throughput if sucess prob is below 10% */
317 	if (prob_ewma < MINSTREL_FRAC(10, 100))
318 		return 0;
319 
320 	if (group != MINSTREL_CCK_GROUP)
321 		nsecs = 1000 * mi->overhead / minstrel_ht_avg_ampdu_len(mi);
322 
323 	nsecs += minstrel_mcs_groups[group].duration[rate] <<
324 		 minstrel_mcs_groups[group].shift;
325 
326 	/*
327 	 * For the throughput calculation, limit the probability value to 90% to
328 	 * account for collision related packet error rate fluctuation
329 	 * (prob is scaled - see MINSTREL_FRAC above)
330 	 */
331 	if (prob_ewma > MINSTREL_FRAC(90, 100))
332 		return MINSTREL_TRUNC(100000 * ((MINSTREL_FRAC(90, 100) * 1000)
333 								      / nsecs));
334 	else
335 		return MINSTREL_TRUNC(100000 * ((prob_ewma * 1000) / nsecs));
336 }
337 
338 /*
339  * Find & sort topmost throughput rates
340  *
341  * If multiple rates provide equal throughput the sorting is based on their
342  * current success probability. Higher success probability is preferred among
343  * MCS groups, CCK rates do not provide aggregation and are therefore at last.
344  */
345 static void
346 minstrel_ht_sort_best_tp_rates(struct minstrel_ht_sta *mi, u16 index,
347 			       u16 *tp_list)
348 {
349 	int cur_group, cur_idx, cur_tp_avg, cur_prob;
350 	int tmp_group, tmp_idx, tmp_tp_avg, tmp_prob;
351 	int j = MAX_THR_RATES;
352 
353 	cur_group = index / MCS_GROUP_RATES;
354 	cur_idx = index  % MCS_GROUP_RATES;
355 	cur_prob = mi->groups[cur_group].rates[cur_idx].prob_ewma;
356 	cur_tp_avg = minstrel_ht_get_tp_avg(mi, cur_group, cur_idx, cur_prob);
357 
358 	do {
359 		tmp_group = tp_list[j - 1] / MCS_GROUP_RATES;
360 		tmp_idx = tp_list[j - 1] % MCS_GROUP_RATES;
361 		tmp_prob = mi->groups[tmp_group].rates[tmp_idx].prob_ewma;
362 		tmp_tp_avg = minstrel_ht_get_tp_avg(mi, tmp_group, tmp_idx,
363 						    tmp_prob);
364 		if (cur_tp_avg < tmp_tp_avg ||
365 		    (cur_tp_avg == tmp_tp_avg && cur_prob <= tmp_prob))
366 			break;
367 		j--;
368 	} while (j > 0);
369 
370 	if (j < MAX_THR_RATES - 1) {
371 		memmove(&tp_list[j + 1], &tp_list[j], (sizeof(*tp_list) *
372 		       (MAX_THR_RATES - (j + 1))));
373 	}
374 	if (j < MAX_THR_RATES)
375 		tp_list[j] = index;
376 }
377 
378 /*
379  * Find and set the topmost probability rate per sta and per group
380  */
381 static void
382 minstrel_ht_set_best_prob_rate(struct minstrel_ht_sta *mi, u16 index)
383 {
384 	struct minstrel_mcs_group_data *mg;
385 	struct minstrel_rate_stats *mrs;
386 	int tmp_group, tmp_idx, tmp_tp_avg, tmp_prob;
387 	int max_tp_group, cur_tp_avg, cur_group, cur_idx;
388 	int max_gpr_group, max_gpr_idx;
389 	int max_gpr_tp_avg, max_gpr_prob;
390 
391 	cur_group = index / MCS_GROUP_RATES;
392 	cur_idx = index % MCS_GROUP_RATES;
393 	mg = &mi->groups[index / MCS_GROUP_RATES];
394 	mrs = &mg->rates[index % MCS_GROUP_RATES];
395 
396 	tmp_group = mi->max_prob_rate / MCS_GROUP_RATES;
397 	tmp_idx = mi->max_prob_rate % MCS_GROUP_RATES;
398 	tmp_prob = mi->groups[tmp_group].rates[tmp_idx].prob_ewma;
399 	tmp_tp_avg = minstrel_ht_get_tp_avg(mi, tmp_group, tmp_idx, tmp_prob);
400 
401 	/* if max_tp_rate[0] is from MCS_GROUP max_prob_rate get selected from
402 	 * MCS_GROUP as well as CCK_GROUP rates do not allow aggregation */
403 	max_tp_group = mi->max_tp_rate[0] / MCS_GROUP_RATES;
404 	if((index / MCS_GROUP_RATES == MINSTREL_CCK_GROUP) &&
405 	    (max_tp_group != MINSTREL_CCK_GROUP))
406 		return;
407 
408 	max_gpr_group = mg->max_group_prob_rate / MCS_GROUP_RATES;
409 	max_gpr_idx = mg->max_group_prob_rate % MCS_GROUP_RATES;
410 	max_gpr_prob = mi->groups[max_gpr_group].rates[max_gpr_idx].prob_ewma;
411 
412 	if (mrs->prob_ewma > MINSTREL_FRAC(75, 100)) {
413 		cur_tp_avg = minstrel_ht_get_tp_avg(mi, cur_group, cur_idx,
414 						    mrs->prob_ewma);
415 		if (cur_tp_avg > tmp_tp_avg)
416 			mi->max_prob_rate = index;
417 
418 		max_gpr_tp_avg = minstrel_ht_get_tp_avg(mi, max_gpr_group,
419 							max_gpr_idx,
420 							max_gpr_prob);
421 		if (cur_tp_avg > max_gpr_tp_avg)
422 			mg->max_group_prob_rate = index;
423 	} else {
424 		if (mrs->prob_ewma > tmp_prob)
425 			mi->max_prob_rate = index;
426 		if (mrs->prob_ewma > max_gpr_prob)
427 			mg->max_group_prob_rate = index;
428 	}
429 }
430 
431 
432 /*
433  * Assign new rate set per sta and use CCK rates only if the fastest
434  * rate (max_tp_rate[0]) is from CCK group. This prohibits such sorted
435  * rate sets where MCS and CCK rates are mixed, because CCK rates can
436  * not use aggregation.
437  */
438 static void
439 minstrel_ht_assign_best_tp_rates(struct minstrel_ht_sta *mi,
440 				 u16 tmp_mcs_tp_rate[MAX_THR_RATES],
441 				 u16 tmp_cck_tp_rate[MAX_THR_RATES])
442 {
443 	unsigned int tmp_group, tmp_idx, tmp_cck_tp, tmp_mcs_tp, tmp_prob;
444 	int i;
445 
446 	tmp_group = tmp_cck_tp_rate[0] / MCS_GROUP_RATES;
447 	tmp_idx = tmp_cck_tp_rate[0] % MCS_GROUP_RATES;
448 	tmp_prob = mi->groups[tmp_group].rates[tmp_idx].prob_ewma;
449 	tmp_cck_tp = minstrel_ht_get_tp_avg(mi, tmp_group, tmp_idx, tmp_prob);
450 
451 	tmp_group = tmp_mcs_tp_rate[0] / MCS_GROUP_RATES;
452 	tmp_idx = tmp_mcs_tp_rate[0] % MCS_GROUP_RATES;
453 	tmp_prob = mi->groups[tmp_group].rates[tmp_idx].prob_ewma;
454 	tmp_mcs_tp = minstrel_ht_get_tp_avg(mi, tmp_group, tmp_idx, tmp_prob);
455 
456 	if (tmp_cck_tp > tmp_mcs_tp) {
457 		for(i = 0; i < MAX_THR_RATES; i++) {
458 			minstrel_ht_sort_best_tp_rates(mi, tmp_cck_tp_rate[i],
459 						       tmp_mcs_tp_rate);
460 		}
461 	}
462 
463 }
464 
465 /*
466  * Try to increase robustness of max_prob rate by decrease number of
467  * streams if possible.
468  */
469 static inline void
470 minstrel_ht_prob_rate_reduce_streams(struct minstrel_ht_sta *mi)
471 {
472 	struct minstrel_mcs_group_data *mg;
473 	int tmp_max_streams, group, tmp_idx, tmp_prob;
474 	int tmp_tp = 0;
475 
476 	tmp_max_streams = minstrel_mcs_groups[mi->max_tp_rate[0] /
477 			  MCS_GROUP_RATES].streams;
478 	for (group = 0; group < ARRAY_SIZE(minstrel_mcs_groups); group++) {
479 		mg = &mi->groups[group];
480 		if (!mi->supported[group] || group == MINSTREL_CCK_GROUP)
481 			continue;
482 
483 		tmp_idx = mg->max_group_prob_rate % MCS_GROUP_RATES;
484 		tmp_prob = mi->groups[group].rates[tmp_idx].prob_ewma;
485 
486 		if (tmp_tp < minstrel_ht_get_tp_avg(mi, group, tmp_idx, tmp_prob) &&
487 		   (minstrel_mcs_groups[group].streams < tmp_max_streams)) {
488 				mi->max_prob_rate = mg->max_group_prob_rate;
489 				tmp_tp = minstrel_ht_get_tp_avg(mi, group,
490 								tmp_idx,
491 								tmp_prob);
492 		}
493 	}
494 }
495 
496 /*
497  * Update rate statistics and select new primary rates
498  *
499  * Rules for rate selection:
500  *  - max_prob_rate must use only one stream, as a tradeoff between delivery
501  *    probability and throughput during strong fluctuations
502  *  - as long as the max prob rate has a probability of more than 75%, pick
503  *    higher throughput rates, even if the probablity is a bit lower
504  */
505 static void
506 minstrel_ht_update_stats(struct minstrel_priv *mp, struct minstrel_ht_sta *mi)
507 {
508 	struct minstrel_mcs_group_data *mg;
509 	struct minstrel_rate_stats *mrs;
510 	int group, i, j, cur_prob;
511 	u16 tmp_mcs_tp_rate[MAX_THR_RATES], tmp_group_tp_rate[MAX_THR_RATES];
512 	u16 tmp_cck_tp_rate[MAX_THR_RATES], index;
513 
514 	if (mi->ampdu_packets > 0) {
515 		if (!ieee80211_hw_check(mp->hw, TX_STATUS_NO_AMPDU_LEN))
516 			mi->avg_ampdu_len = minstrel_ewma(mi->avg_ampdu_len,
517 				MINSTREL_FRAC(mi->ampdu_len, mi->ampdu_packets),
518 					      EWMA_LEVEL);
519 		else
520 			mi->avg_ampdu_len = 0;
521 		mi->ampdu_len = 0;
522 		mi->ampdu_packets = 0;
523 	}
524 
525 	mi->sample_slow = 0;
526 	mi->sample_count = 0;
527 
528 	/* Initialize global rate indexes */
529 	for(j = 0; j < MAX_THR_RATES; j++){
530 		tmp_mcs_tp_rate[j] = 0;
531 		tmp_cck_tp_rate[j] = 0;
532 	}
533 
534 	/* Find best rate sets within all MCS groups*/
535 	for (group = 0; group < ARRAY_SIZE(minstrel_mcs_groups); group++) {
536 
537 		mg = &mi->groups[group];
538 		if (!mi->supported[group])
539 			continue;
540 
541 		mi->sample_count++;
542 
543 		/* (re)Initialize group rate indexes */
544 		for(j = 0; j < MAX_THR_RATES; j++)
545 			tmp_group_tp_rate[j] = group;
546 
547 		for (i = 0; i < MCS_GROUP_RATES; i++) {
548 			if (!(mi->supported[group] & BIT(i)))
549 				continue;
550 
551 			index = MCS_GROUP_RATES * group + i;
552 
553 			mrs = &mg->rates[i];
554 			mrs->retry_updated = false;
555 			minstrel_calc_rate_stats(mrs);
556 			cur_prob = mrs->prob_ewma;
557 
558 			if (minstrel_ht_get_tp_avg(mi, group, i, cur_prob) == 0)
559 				continue;
560 
561 			/* Find max throughput rate set */
562 			if (group != MINSTREL_CCK_GROUP) {
563 				minstrel_ht_sort_best_tp_rates(mi, index,
564 							       tmp_mcs_tp_rate);
565 			} else if (group == MINSTREL_CCK_GROUP) {
566 				minstrel_ht_sort_best_tp_rates(mi, index,
567 							       tmp_cck_tp_rate);
568 			}
569 
570 			/* Find max throughput rate set within a group */
571 			minstrel_ht_sort_best_tp_rates(mi, index,
572 						       tmp_group_tp_rate);
573 
574 			/* Find max probability rate per group and global */
575 			minstrel_ht_set_best_prob_rate(mi, index);
576 		}
577 
578 		memcpy(mg->max_group_tp_rate, tmp_group_tp_rate,
579 		       sizeof(mg->max_group_tp_rate));
580 	}
581 
582 	/* Assign new rate set per sta */
583 	minstrel_ht_assign_best_tp_rates(mi, tmp_mcs_tp_rate, tmp_cck_tp_rate);
584 	memcpy(mi->max_tp_rate, tmp_mcs_tp_rate, sizeof(mi->max_tp_rate));
585 
586 	/* Try to increase robustness of max_prob_rate*/
587 	minstrel_ht_prob_rate_reduce_streams(mi);
588 
589 	/* try to sample all available rates during each interval */
590 	mi->sample_count *= 8;
591 
592 #ifdef CONFIG_MAC80211_DEBUGFS
593 	/* use fixed index if set */
594 	if (mp->fixed_rate_idx != -1) {
595 		for (i = 0; i < 4; i++)
596 			mi->max_tp_rate[i] = mp->fixed_rate_idx;
597 		mi->max_prob_rate = mp->fixed_rate_idx;
598 	}
599 #endif
600 
601 	/* Reset update timer */
602 	mi->last_stats_update = jiffies;
603 }
604 
605 static bool
606 minstrel_ht_txstat_valid(struct minstrel_priv *mp, struct ieee80211_tx_rate *rate)
607 {
608 	if (rate->idx < 0)
609 		return false;
610 
611 	if (!rate->count)
612 		return false;
613 
614 	if (rate->flags & IEEE80211_TX_RC_MCS ||
615 	    rate->flags & IEEE80211_TX_RC_VHT_MCS)
616 		return true;
617 
618 	return rate->idx == mp->cck_rates[0] ||
619 	       rate->idx == mp->cck_rates[1] ||
620 	       rate->idx == mp->cck_rates[2] ||
621 	       rate->idx == mp->cck_rates[3];
622 }
623 
624 static void
625 minstrel_set_next_sample_idx(struct minstrel_ht_sta *mi)
626 {
627 	struct minstrel_mcs_group_data *mg;
628 
629 	for (;;) {
630 		mi->sample_group++;
631 		mi->sample_group %= ARRAY_SIZE(minstrel_mcs_groups);
632 		mg = &mi->groups[mi->sample_group];
633 
634 		if (!mi->supported[mi->sample_group])
635 			continue;
636 
637 		if (++mg->index >= MCS_GROUP_RATES) {
638 			mg->index = 0;
639 			if (++mg->column >= ARRAY_SIZE(sample_table))
640 				mg->column = 0;
641 		}
642 		break;
643 	}
644 }
645 
646 static void
647 minstrel_downgrade_rate(struct minstrel_ht_sta *mi, u16 *idx, bool primary)
648 {
649 	int group, orig_group;
650 
651 	orig_group = group = *idx / MCS_GROUP_RATES;
652 	while (group > 0) {
653 		group--;
654 
655 		if (!mi->supported[group])
656 			continue;
657 
658 		if (minstrel_mcs_groups[group].streams >
659 		    minstrel_mcs_groups[orig_group].streams)
660 			continue;
661 
662 		if (primary)
663 			*idx = mi->groups[group].max_group_tp_rate[0];
664 		else
665 			*idx = mi->groups[group].max_group_tp_rate[1];
666 		break;
667 	}
668 }
669 
670 static void
671 minstrel_aggr_check(struct ieee80211_sta *pubsta, struct sk_buff *skb)
672 {
673 	struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) skb->data;
674 	struct sta_info *sta = container_of(pubsta, struct sta_info, sta);
675 	u16 tid;
676 
677 	if (skb_get_queue_mapping(skb) == IEEE80211_AC_VO)
678 		return;
679 
680 	if (unlikely(!ieee80211_is_data_qos(hdr->frame_control)))
681 		return;
682 
683 	if (unlikely(skb->protocol == cpu_to_be16(ETH_P_PAE)))
684 		return;
685 
686 	tid = ieee80211_get_tid(hdr);
687 	if (likely(sta->ampdu_mlme.tid_tx[tid]))
688 		return;
689 
690 	ieee80211_start_tx_ba_session(pubsta, tid, 0);
691 }
692 
693 static void
694 minstrel_ht_tx_status(void *priv, struct ieee80211_supported_band *sband,
695                       void *priv_sta, struct ieee80211_tx_status *st)
696 {
697 	struct ieee80211_tx_info *info = st->info;
698 	struct minstrel_ht_sta_priv *msp = priv_sta;
699 	struct minstrel_ht_sta *mi = &msp->ht;
700 	struct ieee80211_tx_rate *ar = info->status.rates;
701 	struct minstrel_rate_stats *rate, *rate2;
702 	struct minstrel_priv *mp = priv;
703 	bool last, update = false;
704 	int i;
705 
706 	if (!msp->is_ht)
707 		return mac80211_minstrel.tx_status_ext(priv, sband,
708 						       &msp->legacy, st);
709 
710 	/* This packet was aggregated but doesn't carry status info */
711 	if ((info->flags & IEEE80211_TX_CTL_AMPDU) &&
712 	    !(info->flags & IEEE80211_TX_STAT_AMPDU))
713 		return;
714 
715 	if (!(info->flags & IEEE80211_TX_STAT_AMPDU)) {
716 		info->status.ampdu_ack_len =
717 			(info->flags & IEEE80211_TX_STAT_ACK ? 1 : 0);
718 		info->status.ampdu_len = 1;
719 	}
720 
721 	mi->ampdu_packets++;
722 	mi->ampdu_len += info->status.ampdu_len;
723 
724 	if (!mi->sample_wait && !mi->sample_tries && mi->sample_count > 0) {
725 		int avg_ampdu_len = minstrel_ht_avg_ampdu_len(mi);
726 
727 		mi->sample_wait = 16 + 2 * avg_ampdu_len;
728 		mi->sample_tries = 1;
729 		mi->sample_count--;
730 	}
731 
732 	if (info->flags & IEEE80211_TX_CTL_RATE_CTRL_PROBE)
733 		mi->sample_packets += info->status.ampdu_len;
734 
735 	last = !minstrel_ht_txstat_valid(mp, &ar[0]);
736 	for (i = 0; !last; i++) {
737 		last = (i == IEEE80211_TX_MAX_RATES - 1) ||
738 		       !minstrel_ht_txstat_valid(mp, &ar[i + 1]);
739 
740 		rate = minstrel_ht_get_stats(mp, mi, &ar[i]);
741 
742 		if (last)
743 			rate->success += info->status.ampdu_ack_len;
744 
745 		rate->attempts += ar[i].count * info->status.ampdu_len;
746 	}
747 
748 	/*
749 	 * check for sudden death of spatial multiplexing,
750 	 * downgrade to a lower number of streams if necessary.
751 	 */
752 	rate = minstrel_get_ratestats(mi, mi->max_tp_rate[0]);
753 	if (rate->attempts > 30 &&
754 	    MINSTREL_FRAC(rate->success, rate->attempts) <
755 	    MINSTREL_FRAC(20, 100)) {
756 		minstrel_downgrade_rate(mi, &mi->max_tp_rate[0], true);
757 		update = true;
758 	}
759 
760 	rate2 = minstrel_get_ratestats(mi, mi->max_tp_rate[1]);
761 	if (rate2->attempts > 30 &&
762 	    MINSTREL_FRAC(rate2->success, rate2->attempts) <
763 	    MINSTREL_FRAC(20, 100)) {
764 		minstrel_downgrade_rate(mi, &mi->max_tp_rate[1], false);
765 		update = true;
766 	}
767 
768 	if (time_after(jiffies, mi->last_stats_update +
769 				(mp->update_interval / 2 * HZ) / 1000)) {
770 		update = true;
771 		minstrel_ht_update_stats(mp, mi);
772 	}
773 
774 	if (update)
775 		minstrel_ht_update_rates(mp, mi);
776 }
777 
778 static inline int
779 minstrel_get_duration(int index)
780 {
781 	const struct mcs_group *group = &minstrel_mcs_groups[index / MCS_GROUP_RATES];
782 	unsigned int duration = group->duration[index % MCS_GROUP_RATES];
783 	return duration << group->shift;
784 }
785 
786 static void
787 minstrel_calc_retransmit(struct minstrel_priv *mp, struct minstrel_ht_sta *mi,
788                          int index)
789 {
790 	struct minstrel_rate_stats *mrs;
791 	unsigned int tx_time, tx_time_rtscts, tx_time_data;
792 	unsigned int cw = mp->cw_min;
793 	unsigned int ctime = 0;
794 	unsigned int t_slot = 9; /* FIXME */
795 	unsigned int ampdu_len = minstrel_ht_avg_ampdu_len(mi);
796 	unsigned int overhead = 0, overhead_rtscts = 0;
797 
798 	mrs = minstrel_get_ratestats(mi, index);
799 	if (mrs->prob_ewma < MINSTREL_FRAC(1, 10)) {
800 		mrs->retry_count = 1;
801 		mrs->retry_count_rtscts = 1;
802 		return;
803 	}
804 
805 	mrs->retry_count = 2;
806 	mrs->retry_count_rtscts = 2;
807 	mrs->retry_updated = true;
808 
809 	tx_time_data = minstrel_get_duration(index) * ampdu_len / 1000;
810 
811 	/* Contention time for first 2 tries */
812 	ctime = (t_slot * cw) >> 1;
813 	cw = min((cw << 1) | 1, mp->cw_max);
814 	ctime += (t_slot * cw) >> 1;
815 	cw = min((cw << 1) | 1, mp->cw_max);
816 
817 	if (index / MCS_GROUP_RATES != MINSTREL_CCK_GROUP) {
818 		overhead = mi->overhead;
819 		overhead_rtscts = mi->overhead_rtscts;
820 	}
821 
822 	/* Total TX time for data and Contention after first 2 tries */
823 	tx_time = ctime + 2 * (overhead + tx_time_data);
824 	tx_time_rtscts = ctime + 2 * (overhead_rtscts + tx_time_data);
825 
826 	/* See how many more tries we can fit inside segment size */
827 	do {
828 		/* Contention time for this try */
829 		ctime = (t_slot * cw) >> 1;
830 		cw = min((cw << 1) | 1, mp->cw_max);
831 
832 		/* Total TX time after this try */
833 		tx_time += ctime + overhead + tx_time_data;
834 		tx_time_rtscts += ctime + overhead_rtscts + tx_time_data;
835 
836 		if (tx_time_rtscts < mp->segment_size)
837 			mrs->retry_count_rtscts++;
838 	} while ((tx_time < mp->segment_size) &&
839 	         (++mrs->retry_count < mp->max_retry));
840 }
841 
842 
843 static void
844 minstrel_ht_set_rate(struct minstrel_priv *mp, struct minstrel_ht_sta *mi,
845                      struct ieee80211_sta_rates *ratetbl, int offset, int index)
846 {
847 	const struct mcs_group *group = &minstrel_mcs_groups[index / MCS_GROUP_RATES];
848 	struct minstrel_rate_stats *mrs;
849 	u8 idx;
850 	u16 flags = group->flags;
851 
852 	mrs = minstrel_get_ratestats(mi, index);
853 	if (!mrs->retry_updated)
854 		minstrel_calc_retransmit(mp, mi, index);
855 
856 	if (mrs->prob_ewma < MINSTREL_FRAC(20, 100) || !mrs->retry_count) {
857 		ratetbl->rate[offset].count = 2;
858 		ratetbl->rate[offset].count_rts = 2;
859 		ratetbl->rate[offset].count_cts = 2;
860 	} else {
861 		ratetbl->rate[offset].count = mrs->retry_count;
862 		ratetbl->rate[offset].count_cts = mrs->retry_count;
863 		ratetbl->rate[offset].count_rts = mrs->retry_count_rtscts;
864 	}
865 
866 	if (index / MCS_GROUP_RATES == MINSTREL_CCK_GROUP)
867 		idx = mp->cck_rates[index % ARRAY_SIZE(mp->cck_rates)];
868 	else if (flags & IEEE80211_TX_RC_VHT_MCS)
869 		idx = ((group->streams - 1) << 4) |
870 		      ((index % MCS_GROUP_RATES) & 0xF);
871 	else
872 		idx = index % MCS_GROUP_RATES + (group->streams - 1) * 8;
873 
874 	/* enable RTS/CTS if needed:
875 	 *  - if station is in dynamic SMPS (and streams > 1)
876 	 *  - for fallback rates, to increase chances of getting through
877 	 */
878 	if (offset > 0 ||
879 	    (mi->sta->smps_mode == IEEE80211_SMPS_DYNAMIC &&
880 	     group->streams > 1)) {
881 		ratetbl->rate[offset].count = ratetbl->rate[offset].count_rts;
882 		flags |= IEEE80211_TX_RC_USE_RTS_CTS;
883 	}
884 
885 	ratetbl->rate[offset].idx = idx;
886 	ratetbl->rate[offset].flags = flags;
887 }
888 
889 static inline int
890 minstrel_ht_get_prob_ewma(struct minstrel_ht_sta *mi, int rate)
891 {
892 	int group = rate / MCS_GROUP_RATES;
893 	rate %= MCS_GROUP_RATES;
894 	return mi->groups[group].rates[rate].prob_ewma;
895 }
896 
897 static int
898 minstrel_ht_get_max_amsdu_len(struct minstrel_ht_sta *mi)
899 {
900 	int group = mi->max_prob_rate / MCS_GROUP_RATES;
901 	const struct mcs_group *g = &minstrel_mcs_groups[group];
902 	int rate = mi->max_prob_rate % MCS_GROUP_RATES;
903 	unsigned int duration;
904 
905 	/* Disable A-MSDU if max_prob_rate is bad */
906 	if (mi->groups[group].rates[rate].prob_ewma < MINSTREL_FRAC(50, 100))
907 		return 1;
908 
909 	duration = g->duration[rate];
910 	duration <<= g->shift;
911 
912 	/* If the rate is slower than single-stream MCS1, make A-MSDU limit small */
913 	if (duration > MCS_DURATION(1, 0, 52))
914 		return 500;
915 
916 	/*
917 	 * If the rate is slower than single-stream MCS4, limit A-MSDU to usual
918 	 * data packet size
919 	 */
920 	if (duration > MCS_DURATION(1, 0, 104))
921 		return 1600;
922 
923 	/*
924 	 * If the rate is slower than single-stream MCS7, or if the max throughput
925 	 * rate success probability is less than 75%, limit A-MSDU to twice the usual
926 	 * data packet size
927 	 */
928 	if (duration > MCS_DURATION(1, 0, 260) ||
929 	    (minstrel_ht_get_prob_ewma(mi, mi->max_tp_rate[0]) <
930 	     MINSTREL_FRAC(75, 100)))
931 		return 3200;
932 
933 	/*
934 	 * HT A-MPDU limits maximum MPDU size under BA agreement to 4095 bytes.
935 	 * Since aggregation sessions are started/stopped without txq flush, use
936 	 * the limit here to avoid the complexity of having to de-aggregate
937 	 * packets in the queue.
938 	 */
939 	if (!mi->sta->vht_cap.vht_supported)
940 		return IEEE80211_MAX_MPDU_LEN_HT_BA;
941 
942 	/* unlimited */
943 	return 0;
944 }
945 
946 static void
947 minstrel_ht_update_rates(struct minstrel_priv *mp, struct minstrel_ht_sta *mi)
948 {
949 	struct ieee80211_sta_rates *rates;
950 	int i = 0;
951 
952 	rates = kzalloc(sizeof(*rates), GFP_ATOMIC);
953 	if (!rates)
954 		return;
955 
956 	/* Start with max_tp_rate[0] */
957 	minstrel_ht_set_rate(mp, mi, rates, i++, mi->max_tp_rate[0]);
958 
959 	if (mp->hw->max_rates >= 3) {
960 		/* At least 3 tx rates supported, use max_tp_rate[1] next */
961 		minstrel_ht_set_rate(mp, mi, rates, i++, mi->max_tp_rate[1]);
962 	}
963 
964 	if (mp->hw->max_rates >= 2) {
965 		/*
966 		 * At least 2 tx rates supported, use max_prob_rate next */
967 		minstrel_ht_set_rate(mp, mi, rates, i++, mi->max_prob_rate);
968 	}
969 
970 	mi->sta->max_rc_amsdu_len = minstrel_ht_get_max_amsdu_len(mi);
971 	rates->rate[i].idx = -1;
972 	rate_control_set_rates(mp->hw, mi->sta, rates);
973 }
974 
975 static int
976 minstrel_get_sample_rate(struct minstrel_priv *mp, struct minstrel_ht_sta *mi)
977 {
978 	struct minstrel_rate_stats *mrs;
979 	struct minstrel_mcs_group_data *mg;
980 	unsigned int sample_dur, sample_group, cur_max_tp_streams;
981 	int tp_rate1, tp_rate2;
982 	int sample_idx = 0;
983 
984 	if (mi->sample_wait > 0) {
985 		mi->sample_wait--;
986 		return -1;
987 	}
988 
989 	if (!mi->sample_tries)
990 		return -1;
991 
992 	sample_group = mi->sample_group;
993 	mg = &mi->groups[sample_group];
994 	sample_idx = sample_table[mg->column][mg->index];
995 	minstrel_set_next_sample_idx(mi);
996 
997 	if (!(mi->supported[sample_group] & BIT(sample_idx)))
998 		return -1;
999 
1000 	mrs = &mg->rates[sample_idx];
1001 	sample_idx += sample_group * MCS_GROUP_RATES;
1002 
1003 	/* Set tp_rate1, tp_rate2 to the highest / second highest max_tp_rate */
1004 	if (minstrel_get_duration(mi->max_tp_rate[0]) >
1005 	    minstrel_get_duration(mi->max_tp_rate[1])) {
1006 		tp_rate1 = mi->max_tp_rate[1];
1007 		tp_rate2 = mi->max_tp_rate[0];
1008 	} else {
1009 		tp_rate1 = mi->max_tp_rate[0];
1010 		tp_rate2 = mi->max_tp_rate[1];
1011 	}
1012 
1013 	/*
1014 	 * Sampling might add some overhead (RTS, no aggregation)
1015 	 * to the frame. Hence, don't use sampling for the highest currently
1016 	 * used highest throughput or probability rate.
1017 	 */
1018 	if (sample_idx == mi->max_tp_rate[0] || sample_idx == mi->max_prob_rate)
1019 		return -1;
1020 
1021 	/*
1022 	 * Do not sample if the probability is already higher than 95%,
1023 	 * or if the rate is 3 times slower than the current max probability
1024 	 * rate, to avoid wasting airtime.
1025 	 */
1026 	sample_dur = minstrel_get_duration(sample_idx);
1027 	if (mrs->prob_ewma > MINSTREL_FRAC(95, 100) ||
1028 	    minstrel_get_duration(mi->max_prob_rate) * 3 < sample_dur)
1029 		return -1;
1030 
1031 	/*
1032 	 * Make sure that lower rates get sampled only occasionally,
1033 	 * if the link is working perfectly.
1034 	 */
1035 
1036 	cur_max_tp_streams = minstrel_mcs_groups[tp_rate1 /
1037 		MCS_GROUP_RATES].streams;
1038 	if (sample_dur >= minstrel_get_duration(tp_rate2) &&
1039 	    (cur_max_tp_streams - 1 <
1040 	     minstrel_mcs_groups[sample_group].streams ||
1041 	     sample_dur >= minstrel_get_duration(mi->max_prob_rate))) {
1042 		if (mrs->sample_skipped < 20)
1043 			return -1;
1044 
1045 		if (mi->sample_slow++ > 2)
1046 			return -1;
1047 	}
1048 	mi->sample_tries--;
1049 
1050 	return sample_idx;
1051 }
1052 
1053 static void
1054 minstrel_ht_get_rate(void *priv, struct ieee80211_sta *sta, void *priv_sta,
1055                      struct ieee80211_tx_rate_control *txrc)
1056 {
1057 	const struct mcs_group *sample_group;
1058 	struct ieee80211_tx_info *info = IEEE80211_SKB_CB(txrc->skb);
1059 	struct ieee80211_tx_rate *rate = &info->status.rates[0];
1060 	struct minstrel_ht_sta_priv *msp = priv_sta;
1061 	struct minstrel_ht_sta *mi = &msp->ht;
1062 	struct minstrel_priv *mp = priv;
1063 	int sample_idx;
1064 
1065 	if (rate_control_send_low(sta, priv_sta, txrc))
1066 		return;
1067 
1068 	if (!msp->is_ht)
1069 		return mac80211_minstrel.get_rate(priv, sta, &msp->legacy, txrc);
1070 
1071 	if (!(info->flags & IEEE80211_TX_CTL_AMPDU) &&
1072 	    mi->max_prob_rate / MCS_GROUP_RATES != MINSTREL_CCK_GROUP)
1073 		minstrel_aggr_check(sta, txrc->skb);
1074 
1075 	info->flags |= mi->tx_flags;
1076 
1077 #ifdef CONFIG_MAC80211_DEBUGFS
1078 	if (mp->fixed_rate_idx != -1)
1079 		return;
1080 #endif
1081 
1082 	/* Don't use EAPOL frames for sampling on non-mrr hw */
1083 	if (mp->hw->max_rates == 1 &&
1084 	    (info->control.flags & IEEE80211_TX_CTRL_PORT_CTRL_PROTO))
1085 		sample_idx = -1;
1086 	else
1087 		sample_idx = minstrel_get_sample_rate(mp, mi);
1088 
1089 	mi->total_packets++;
1090 
1091 	/* wraparound */
1092 	if (mi->total_packets == ~0) {
1093 		mi->total_packets = 0;
1094 		mi->sample_packets = 0;
1095 	}
1096 
1097 	if (sample_idx < 0)
1098 		return;
1099 
1100 	sample_group = &minstrel_mcs_groups[sample_idx / MCS_GROUP_RATES];
1101 	sample_idx %= MCS_GROUP_RATES;
1102 
1103 	if (sample_group == &minstrel_mcs_groups[MINSTREL_CCK_GROUP] &&
1104 	    (sample_idx >= 4) != txrc->short_preamble)
1105 		return;
1106 
1107 	info->flags |= IEEE80211_TX_CTL_RATE_CTRL_PROBE;
1108 	rate->count = 1;
1109 
1110 	if (sample_group == &minstrel_mcs_groups[MINSTREL_CCK_GROUP]) {
1111 		int idx = sample_idx % ARRAY_SIZE(mp->cck_rates);
1112 		rate->idx = mp->cck_rates[idx];
1113 	} else if (sample_group->flags & IEEE80211_TX_RC_VHT_MCS) {
1114 		ieee80211_rate_set_vht(rate, sample_idx % MCS_GROUP_RATES,
1115 				       sample_group->streams);
1116 	} else {
1117 		rate->idx = sample_idx + (sample_group->streams - 1) * 8;
1118 	}
1119 
1120 	rate->flags = sample_group->flags;
1121 }
1122 
1123 static void
1124 minstrel_ht_update_cck(struct minstrel_priv *mp, struct minstrel_ht_sta *mi,
1125 		       struct ieee80211_supported_band *sband,
1126 		       struct ieee80211_sta *sta)
1127 {
1128 	int i;
1129 
1130 	if (sband->band != NL80211_BAND_2GHZ)
1131 		return;
1132 
1133 	if (!ieee80211_hw_check(mp->hw, SUPPORTS_HT_CCK_RATES))
1134 		return;
1135 
1136 	mi->cck_supported = 0;
1137 	mi->cck_supported_short = 0;
1138 	for (i = 0; i < 4; i++) {
1139 		if (!rate_supported(sta, sband->band, mp->cck_rates[i]))
1140 			continue;
1141 
1142 		mi->cck_supported |= BIT(i);
1143 		if (sband->bitrates[i].flags & IEEE80211_RATE_SHORT_PREAMBLE)
1144 			mi->cck_supported_short |= BIT(i);
1145 	}
1146 
1147 	mi->supported[MINSTREL_CCK_GROUP] = mi->cck_supported;
1148 }
1149 
1150 static void
1151 minstrel_ht_update_caps(void *priv, struct ieee80211_supported_band *sband,
1152 			struct cfg80211_chan_def *chandef,
1153                         struct ieee80211_sta *sta, void *priv_sta)
1154 {
1155 	struct minstrel_priv *mp = priv;
1156 	struct minstrel_ht_sta_priv *msp = priv_sta;
1157 	struct minstrel_ht_sta *mi = &msp->ht;
1158 	struct ieee80211_mcs_info *mcs = &sta->ht_cap.mcs;
1159 	u16 ht_cap = sta->ht_cap.cap;
1160 	struct ieee80211_sta_vht_cap *vht_cap = &sta->vht_cap;
1161 	int use_vht;
1162 	int n_supported = 0;
1163 	int ack_dur;
1164 	int stbc;
1165 	int i;
1166 	bool ldpc;
1167 
1168 	/* fall back to the old minstrel for legacy stations */
1169 	if (!sta->ht_cap.ht_supported)
1170 		goto use_legacy;
1171 
1172 	BUILD_BUG_ON(ARRAY_SIZE(minstrel_mcs_groups) != MINSTREL_GROUPS_NB);
1173 
1174 	if (vht_cap->vht_supported)
1175 		use_vht = vht_cap->vht_mcs.tx_mcs_map != cpu_to_le16(~0);
1176 	else
1177 		use_vht = 0;
1178 
1179 	msp->is_ht = true;
1180 	memset(mi, 0, sizeof(*mi));
1181 
1182 	mi->sta = sta;
1183 	mi->last_stats_update = jiffies;
1184 
1185 	ack_dur = ieee80211_frame_duration(sband->band, 10, 60, 1, 1, 0);
1186 	mi->overhead = ieee80211_frame_duration(sband->band, 0, 60, 1, 1, 0);
1187 	mi->overhead += ack_dur;
1188 	mi->overhead_rtscts = mi->overhead + 2 * ack_dur;
1189 
1190 	mi->avg_ampdu_len = MINSTREL_FRAC(1, 1);
1191 
1192 	/* When using MRR, sample more on the first attempt, without delay */
1193 	if (mp->has_mrr) {
1194 		mi->sample_count = 16;
1195 		mi->sample_wait = 0;
1196 	} else {
1197 		mi->sample_count = 8;
1198 		mi->sample_wait = 8;
1199 	}
1200 	mi->sample_tries = 4;
1201 
1202 	if (!use_vht) {
1203 		stbc = (ht_cap & IEEE80211_HT_CAP_RX_STBC) >>
1204 			IEEE80211_HT_CAP_RX_STBC_SHIFT;
1205 
1206 		ldpc = ht_cap & IEEE80211_HT_CAP_LDPC_CODING;
1207 	} else {
1208 		stbc = (vht_cap->cap & IEEE80211_VHT_CAP_RXSTBC_MASK) >>
1209 			IEEE80211_VHT_CAP_RXSTBC_SHIFT;
1210 
1211 		ldpc = vht_cap->cap & IEEE80211_VHT_CAP_RXLDPC;
1212 	}
1213 
1214 	mi->tx_flags |= stbc << IEEE80211_TX_CTL_STBC_SHIFT;
1215 	if (ldpc)
1216 		mi->tx_flags |= IEEE80211_TX_CTL_LDPC;
1217 
1218 	for (i = 0; i < ARRAY_SIZE(mi->groups); i++) {
1219 		u32 gflags = minstrel_mcs_groups[i].flags;
1220 		int bw, nss;
1221 
1222 		mi->supported[i] = 0;
1223 		if (i == MINSTREL_CCK_GROUP) {
1224 			minstrel_ht_update_cck(mp, mi, sband, sta);
1225 			continue;
1226 		}
1227 
1228 		if (gflags & IEEE80211_TX_RC_SHORT_GI) {
1229 			if (gflags & IEEE80211_TX_RC_40_MHZ_WIDTH) {
1230 				if (!(ht_cap & IEEE80211_HT_CAP_SGI_40))
1231 					continue;
1232 			} else {
1233 				if (!(ht_cap & IEEE80211_HT_CAP_SGI_20))
1234 					continue;
1235 			}
1236 		}
1237 
1238 		if (gflags & IEEE80211_TX_RC_40_MHZ_WIDTH &&
1239 		    sta->bandwidth < IEEE80211_STA_RX_BW_40)
1240 			continue;
1241 
1242 		nss = minstrel_mcs_groups[i].streams;
1243 
1244 		/* Mark MCS > 7 as unsupported if STA is in static SMPS mode */
1245 		if (sta->smps_mode == IEEE80211_SMPS_STATIC && nss > 1)
1246 			continue;
1247 
1248 		/* HT rate */
1249 		if (gflags & IEEE80211_TX_RC_MCS) {
1250 			if (use_vht && minstrel_vht_only)
1251 				continue;
1252 
1253 			mi->supported[i] = mcs->rx_mask[nss - 1];
1254 			if (mi->supported[i])
1255 				n_supported++;
1256 			continue;
1257 		}
1258 
1259 		/* VHT rate */
1260 		if (!vht_cap->vht_supported ||
1261 		    WARN_ON(!(gflags & IEEE80211_TX_RC_VHT_MCS)) ||
1262 		    WARN_ON(gflags & IEEE80211_TX_RC_160_MHZ_WIDTH))
1263 			continue;
1264 
1265 		if (gflags & IEEE80211_TX_RC_80_MHZ_WIDTH) {
1266 			if (sta->bandwidth < IEEE80211_STA_RX_BW_80 ||
1267 			    ((gflags & IEEE80211_TX_RC_SHORT_GI) &&
1268 			     !(vht_cap->cap & IEEE80211_VHT_CAP_SHORT_GI_80))) {
1269 				continue;
1270 			}
1271 		}
1272 
1273 		if (gflags & IEEE80211_TX_RC_40_MHZ_WIDTH)
1274 			bw = BW_40;
1275 		else if (gflags & IEEE80211_TX_RC_80_MHZ_WIDTH)
1276 			bw = BW_80;
1277 		else
1278 			bw = BW_20;
1279 
1280 		mi->supported[i] = minstrel_get_valid_vht_rates(bw, nss,
1281 				vht_cap->vht_mcs.tx_mcs_map);
1282 
1283 		if (mi->supported[i])
1284 			n_supported++;
1285 	}
1286 
1287 	if (!n_supported)
1288 		goto use_legacy;
1289 
1290 	mi->supported[MINSTREL_CCK_GROUP] |= mi->cck_supported_short << 4;
1291 
1292 	/* create an initial rate table with the lowest supported rates */
1293 	minstrel_ht_update_stats(mp, mi);
1294 	minstrel_ht_update_rates(mp, mi);
1295 
1296 	return;
1297 
1298 use_legacy:
1299 	msp->is_ht = false;
1300 	memset(&msp->legacy, 0, sizeof(msp->legacy));
1301 	msp->legacy.r = msp->ratelist;
1302 	msp->legacy.sample_table = msp->sample_table;
1303 	return mac80211_minstrel.rate_init(priv, sband, chandef, sta,
1304 					   &msp->legacy);
1305 }
1306 
1307 static void
1308 minstrel_ht_rate_init(void *priv, struct ieee80211_supported_band *sband,
1309 		      struct cfg80211_chan_def *chandef,
1310                       struct ieee80211_sta *sta, void *priv_sta)
1311 {
1312 	minstrel_ht_update_caps(priv, sband, chandef, sta, priv_sta);
1313 }
1314 
1315 static void
1316 minstrel_ht_rate_update(void *priv, struct ieee80211_supported_band *sband,
1317 			struct cfg80211_chan_def *chandef,
1318                         struct ieee80211_sta *sta, void *priv_sta,
1319                         u32 changed)
1320 {
1321 	minstrel_ht_update_caps(priv, sband, chandef, sta, priv_sta);
1322 }
1323 
1324 static void *
1325 minstrel_ht_alloc_sta(void *priv, struct ieee80211_sta *sta, gfp_t gfp)
1326 {
1327 	struct ieee80211_supported_band *sband;
1328 	struct minstrel_ht_sta_priv *msp;
1329 	struct minstrel_priv *mp = priv;
1330 	struct ieee80211_hw *hw = mp->hw;
1331 	int max_rates = 0;
1332 	int i;
1333 
1334 	for (i = 0; i < NUM_NL80211_BANDS; i++) {
1335 		sband = hw->wiphy->bands[i];
1336 		if (sband && sband->n_bitrates > max_rates)
1337 			max_rates = sband->n_bitrates;
1338 	}
1339 
1340 	msp = kzalloc(sizeof(*msp), gfp);
1341 	if (!msp)
1342 		return NULL;
1343 
1344 	msp->ratelist = kcalloc(max_rates, sizeof(struct minstrel_rate), gfp);
1345 	if (!msp->ratelist)
1346 		goto error;
1347 
1348 	msp->sample_table = kmalloc_array(max_rates, SAMPLE_COLUMNS, gfp);
1349 	if (!msp->sample_table)
1350 		goto error1;
1351 
1352 	return msp;
1353 
1354 error1:
1355 	kfree(msp->ratelist);
1356 error:
1357 	kfree(msp);
1358 	return NULL;
1359 }
1360 
1361 static void
1362 minstrel_ht_free_sta(void *priv, struct ieee80211_sta *sta, void *priv_sta)
1363 {
1364 	struct minstrel_ht_sta_priv *msp = priv_sta;
1365 
1366 	kfree(msp->sample_table);
1367 	kfree(msp->ratelist);
1368 	kfree(msp);
1369 }
1370 
1371 static void
1372 minstrel_ht_init_cck_rates(struct minstrel_priv *mp)
1373 {
1374 	static const int bitrates[4] = { 10, 20, 55, 110 };
1375 	struct ieee80211_supported_band *sband;
1376 	u32 rate_flags = ieee80211_chandef_rate_flags(&mp->hw->conf.chandef);
1377 	int i, j;
1378 
1379 	sband = mp->hw->wiphy->bands[NL80211_BAND_2GHZ];
1380 	if (!sband)
1381 		return;
1382 
1383 	for (i = 0; i < sband->n_bitrates; i++) {
1384 		struct ieee80211_rate *rate = &sband->bitrates[i];
1385 
1386 		if (rate->flags & IEEE80211_RATE_ERP_G)
1387 			continue;
1388 
1389 		if ((rate_flags & sband->bitrates[i].flags) != rate_flags)
1390 			continue;
1391 
1392 		for (j = 0; j < ARRAY_SIZE(bitrates); j++) {
1393 			if (rate->bitrate != bitrates[j])
1394 				continue;
1395 
1396 			mp->cck_rates[j] = i;
1397 			break;
1398 		}
1399 	}
1400 }
1401 
1402 static void *
1403 minstrel_ht_alloc(struct ieee80211_hw *hw, struct dentry *debugfsdir)
1404 {
1405 	struct minstrel_priv *mp;
1406 
1407 	mp = kzalloc(sizeof(struct minstrel_priv), GFP_ATOMIC);
1408 	if (!mp)
1409 		return NULL;
1410 
1411 	/* contention window settings
1412 	 * Just an approximation. Using the per-queue values would complicate
1413 	 * the calculations and is probably unnecessary */
1414 	mp->cw_min = 15;
1415 	mp->cw_max = 1023;
1416 
1417 	/* number of packets (in %) to use for sampling other rates
1418 	 * sample less often for non-mrr packets, because the overhead
1419 	 * is much higher than with mrr */
1420 	mp->lookaround_rate = 5;
1421 	mp->lookaround_rate_mrr = 10;
1422 
1423 	/* maximum time that the hw is allowed to stay in one MRR segment */
1424 	mp->segment_size = 6000;
1425 
1426 	if (hw->max_rate_tries > 0)
1427 		mp->max_retry = hw->max_rate_tries;
1428 	else
1429 		/* safe default, does not necessarily have to match hw properties */
1430 		mp->max_retry = 7;
1431 
1432 	if (hw->max_rates >= 4)
1433 		mp->has_mrr = true;
1434 
1435 	mp->hw = hw;
1436 	mp->update_interval = 100;
1437 
1438 #ifdef CONFIG_MAC80211_DEBUGFS
1439 	mp->fixed_rate_idx = (u32) -1;
1440 	debugfs_create_u32("fixed_rate_idx", S_IRUGO | S_IWUGO, debugfsdir,
1441 			   &mp->fixed_rate_idx);
1442 #endif
1443 
1444 	minstrel_ht_init_cck_rates(mp);
1445 
1446 	return mp;
1447 }
1448 
1449 static void
1450 minstrel_ht_free(void *priv)
1451 {
1452 	kfree(priv);
1453 }
1454 
1455 static u32 minstrel_ht_get_expected_throughput(void *priv_sta)
1456 {
1457 	struct minstrel_ht_sta_priv *msp = priv_sta;
1458 	struct minstrel_ht_sta *mi = &msp->ht;
1459 	int i, j, prob, tp_avg;
1460 
1461 	if (!msp->is_ht)
1462 		return mac80211_minstrel.get_expected_throughput(priv_sta);
1463 
1464 	i = mi->max_tp_rate[0] / MCS_GROUP_RATES;
1465 	j = mi->max_tp_rate[0] % MCS_GROUP_RATES;
1466 	prob = mi->groups[i].rates[j].prob_ewma;
1467 
1468 	/* convert tp_avg from pkt per second in kbps */
1469 	tp_avg = minstrel_ht_get_tp_avg(mi, i, j, prob) * 10;
1470 	tp_avg = tp_avg * AVG_PKT_SIZE * 8 / 1024;
1471 
1472 	return tp_avg;
1473 }
1474 
1475 static const struct rate_control_ops mac80211_minstrel_ht = {
1476 	.name = "minstrel_ht",
1477 	.tx_status_ext = minstrel_ht_tx_status,
1478 	.get_rate = minstrel_ht_get_rate,
1479 	.rate_init = minstrel_ht_rate_init,
1480 	.rate_update = minstrel_ht_rate_update,
1481 	.alloc_sta = minstrel_ht_alloc_sta,
1482 	.free_sta = minstrel_ht_free_sta,
1483 	.alloc = minstrel_ht_alloc,
1484 	.free = minstrel_ht_free,
1485 #ifdef CONFIG_MAC80211_DEBUGFS
1486 	.add_sta_debugfs = minstrel_ht_add_sta_debugfs,
1487 #endif
1488 	.get_expected_throughput = minstrel_ht_get_expected_throughput,
1489 };
1490 
1491 
1492 static void __init init_sample_table(void)
1493 {
1494 	int col, i, new_idx;
1495 	u8 rnd[MCS_GROUP_RATES];
1496 
1497 	memset(sample_table, 0xff, sizeof(sample_table));
1498 	for (col = 0; col < SAMPLE_COLUMNS; col++) {
1499 		prandom_bytes(rnd, sizeof(rnd));
1500 		for (i = 0; i < MCS_GROUP_RATES; i++) {
1501 			new_idx = (i + rnd[i]) % MCS_GROUP_RATES;
1502 			while (sample_table[col][new_idx] != 0xff)
1503 				new_idx = (new_idx + 1) % MCS_GROUP_RATES;
1504 
1505 			sample_table[col][new_idx] = i;
1506 		}
1507 	}
1508 }
1509 
1510 int __init
1511 rc80211_minstrel_init(void)
1512 {
1513 	init_sample_table();
1514 	return ieee80211_rate_control_register(&mac80211_minstrel_ht);
1515 }
1516 
1517 void
1518 rc80211_minstrel_exit(void)
1519 {
1520 	ieee80211_rate_control_unregister(&mac80211_minstrel_ht);
1521 }
1522