1 /******************************************************************************
2  *
3  * Copyright(c) 2005 - 2014 Intel Corporation. All rights reserved.
4  * Copyright(c) 2013 - 2015 Intel Mobile Communications GmbH
5  * Copyright(c) 2016 Intel Deutschland GmbH
6  *
7  * This program is free software; you can redistribute it and/or modify it
8  * under the terms of version 2 of the GNU General Public License as
9  * published by the Free Software Foundation.
10  *
11  * This program is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
14  * more details.
15  *
16  * You should have received a copy of the GNU General Public License along with
17  * this program; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
19  *
20  * The full GNU General Public License is included in this distribution in the
21  * file called LICENSE.
22  *
23  * Contact Information:
24  *  Intel Linux Wireless <linuxwifi@intel.com>
25  * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
26  *
27  *****************************************************************************/
28 #include <linux/kernel.h>
29 #include <linux/skbuff.h>
30 #include <linux/slab.h>
31 #include <net/mac80211.h>
32 
33 #include <linux/netdevice.h>
34 #include <linux/etherdevice.h>
35 #include <linux/delay.h>
36 
37 #include <linux/workqueue.h>
38 #include "rs.h"
39 #include "fw-api.h"
40 #include "sta.h"
41 #include "iwl-op-mode.h"
42 #include "mvm.h"
43 #include "debugfs.h"
44 
45 #define RS_NAME "iwl-mvm-rs"
46 
47 #define IWL_RATE_MAX_WINDOW		62	/* # tx in history window */
48 
49 /* Calculations of success ratio are done in fixed point where 12800 is 100%.
50  * Use this macro when dealing with thresholds consts set as a percentage
51  */
52 #define RS_PERCENT(x) (128 * x)
53 
54 static u8 rs_ht_to_legacy[] = {
55 	[IWL_RATE_MCS_0_INDEX] = IWL_RATE_6M_INDEX,
56 	[IWL_RATE_MCS_1_INDEX] = IWL_RATE_9M_INDEX,
57 	[IWL_RATE_MCS_2_INDEX] = IWL_RATE_12M_INDEX,
58 	[IWL_RATE_MCS_3_INDEX] = IWL_RATE_18M_INDEX,
59 	[IWL_RATE_MCS_4_INDEX] = IWL_RATE_24M_INDEX,
60 	[IWL_RATE_MCS_5_INDEX] = IWL_RATE_36M_INDEX,
61 	[IWL_RATE_MCS_6_INDEX] = IWL_RATE_48M_INDEX,
62 	[IWL_RATE_MCS_7_INDEX] = IWL_RATE_54M_INDEX,
63 	[IWL_RATE_MCS_8_INDEX] = IWL_RATE_54M_INDEX,
64 	[IWL_RATE_MCS_9_INDEX] = IWL_RATE_54M_INDEX,
65 };
66 
67 static const u8 ant_toggle_lookup[] = {
68 	[ANT_NONE] = ANT_NONE,
69 	[ANT_A] = ANT_B,
70 	[ANT_B] = ANT_C,
71 	[ANT_AB] = ANT_BC,
72 	[ANT_C] = ANT_A,
73 	[ANT_AC] = ANT_AB,
74 	[ANT_BC] = ANT_AC,
75 	[ANT_ABC] = ANT_ABC,
76 };
77 
78 #define IWL_DECLARE_RATE_INFO(r, s, rp, rn)			      \
79 	[IWL_RATE_##r##M_INDEX] = { IWL_RATE_##r##M_PLCP,	      \
80 				    IWL_RATE_HT_SISO_MCS_##s##_PLCP,  \
81 				    IWL_RATE_HT_MIMO2_MCS_##s##_PLCP, \
82 				    IWL_RATE_VHT_SISO_MCS_##s##_PLCP, \
83 				    IWL_RATE_VHT_MIMO2_MCS_##s##_PLCP,\
84 				    IWL_RATE_##rp##M_INDEX,	      \
85 				    IWL_RATE_##rn##M_INDEX }
86 
87 #define IWL_DECLARE_MCS_RATE(s)						  \
88 	[IWL_RATE_MCS_##s##_INDEX] = { IWL_RATE_INVM_PLCP,		  \
89 				       IWL_RATE_HT_SISO_MCS_##s##_PLCP,	  \
90 				       IWL_RATE_HT_MIMO2_MCS_##s##_PLCP,  \
91 				       IWL_RATE_VHT_SISO_MCS_##s##_PLCP,  \
92 				       IWL_RATE_VHT_MIMO2_MCS_##s##_PLCP, \
93 				       IWL_RATE_INVM_INDEX,	          \
94 				       IWL_RATE_INVM_INDEX }
95 
96 /*
97  * Parameter order:
98  *   rate, ht rate, prev rate, next rate
99  *
100  * If there isn't a valid next or previous rate then INV is used which
101  * maps to IWL_RATE_INVALID
102  *
103  */
104 static const struct iwl_rs_rate_info iwl_rates[IWL_RATE_COUNT] = {
105 	IWL_DECLARE_RATE_INFO(1, INV, INV, 2),   /*  1mbps */
106 	IWL_DECLARE_RATE_INFO(2, INV, 1, 5),     /*  2mbps */
107 	IWL_DECLARE_RATE_INFO(5, INV, 2, 11),    /*5.5mbps */
108 	IWL_DECLARE_RATE_INFO(11, INV, 9, 12),   /* 11mbps */
109 	IWL_DECLARE_RATE_INFO(6, 0, 5, 11),      /*  6mbps ; MCS 0 */
110 	IWL_DECLARE_RATE_INFO(9, INV, 6, 11),    /*  9mbps */
111 	IWL_DECLARE_RATE_INFO(12, 1, 11, 18),    /* 12mbps ; MCS 1 */
112 	IWL_DECLARE_RATE_INFO(18, 2, 12, 24),    /* 18mbps ; MCS 2 */
113 	IWL_DECLARE_RATE_INFO(24, 3, 18, 36),    /* 24mbps ; MCS 3 */
114 	IWL_DECLARE_RATE_INFO(36, 4, 24, 48),    /* 36mbps ; MCS 4 */
115 	IWL_DECLARE_RATE_INFO(48, 5, 36, 54),    /* 48mbps ; MCS 5 */
116 	IWL_DECLARE_RATE_INFO(54, 6, 48, INV),   /* 54mbps ; MCS 6 */
117 	IWL_DECLARE_MCS_RATE(7),                 /* MCS 7 */
118 	IWL_DECLARE_MCS_RATE(8),                 /* MCS 8 */
119 	IWL_DECLARE_MCS_RATE(9),                 /* MCS 9 */
120 };
121 
122 enum rs_action {
123 	RS_ACTION_STAY = 0,
124 	RS_ACTION_DOWNSCALE = -1,
125 	RS_ACTION_UPSCALE = 1,
126 };
127 
128 enum rs_column_mode {
129 	RS_INVALID = 0,
130 	RS_LEGACY,
131 	RS_SISO,
132 	RS_MIMO2,
133 };
134 
135 #define MAX_NEXT_COLUMNS 7
136 #define MAX_COLUMN_CHECKS 3
137 
138 struct rs_tx_column;
139 
140 typedef bool (*allow_column_func_t) (struct iwl_mvm *mvm,
141 				     struct ieee80211_sta *sta,
142 				     struct rs_rate *rate,
143 				     const struct rs_tx_column *next_col);
144 
145 struct rs_tx_column {
146 	enum rs_column_mode mode;
147 	u8 ant;
148 	bool sgi;
149 	enum rs_column next_columns[MAX_NEXT_COLUMNS];
150 	allow_column_func_t checks[MAX_COLUMN_CHECKS];
151 };
152 
153 static bool rs_ant_allow(struct iwl_mvm *mvm, struct ieee80211_sta *sta,
154 			 struct rs_rate *rate,
155 			 const struct rs_tx_column *next_col)
156 {
157 	return iwl_mvm_bt_coex_is_ant_avail(mvm, next_col->ant);
158 }
159 
160 static bool rs_mimo_allow(struct iwl_mvm *mvm, struct ieee80211_sta *sta,
161 			  struct rs_rate *rate,
162 			  const struct rs_tx_column *next_col)
163 {
164 	struct iwl_mvm_sta *mvmsta;
165 	struct iwl_mvm_vif *mvmvif;
166 
167 	if (!sta->ht_cap.ht_supported)
168 		return false;
169 
170 	if (sta->smps_mode == IEEE80211_SMPS_STATIC)
171 		return false;
172 
173 	if (num_of_ant(iwl_mvm_get_valid_tx_ant(mvm)) < 2)
174 		return false;
175 
176 	if (!iwl_mvm_bt_coex_is_mimo_allowed(mvm, sta))
177 		return false;
178 
179 	mvmsta = iwl_mvm_sta_from_mac80211(sta);
180 	mvmvif = iwl_mvm_vif_from_mac80211(mvmsta->vif);
181 
182 	if (mvm->nvm_data->sku_cap_mimo_disabled)
183 		return false;
184 
185 	return true;
186 }
187 
188 static bool rs_siso_allow(struct iwl_mvm *mvm, struct ieee80211_sta *sta,
189 			  struct rs_rate *rate,
190 			  const struct rs_tx_column *next_col)
191 {
192 	if (!sta->ht_cap.ht_supported)
193 		return false;
194 
195 	return true;
196 }
197 
198 static bool rs_sgi_allow(struct iwl_mvm *mvm, struct ieee80211_sta *sta,
199 			 struct rs_rate *rate,
200 			 const struct rs_tx_column *next_col)
201 {
202 	struct ieee80211_sta_ht_cap *ht_cap = &sta->ht_cap;
203 	struct ieee80211_sta_vht_cap *vht_cap = &sta->vht_cap;
204 
205 	if (is_ht20(rate) && (ht_cap->cap &
206 			     IEEE80211_HT_CAP_SGI_20))
207 		return true;
208 	if (is_ht40(rate) && (ht_cap->cap &
209 			     IEEE80211_HT_CAP_SGI_40))
210 		return true;
211 	if (is_ht80(rate) && (vht_cap->cap &
212 			     IEEE80211_VHT_CAP_SHORT_GI_80))
213 		return true;
214 
215 	return false;
216 }
217 
218 static const struct rs_tx_column rs_tx_columns[] = {
219 	[RS_COLUMN_LEGACY_ANT_A] = {
220 		.mode = RS_LEGACY,
221 		.ant = ANT_A,
222 		.next_columns = {
223 			RS_COLUMN_LEGACY_ANT_B,
224 			RS_COLUMN_SISO_ANT_A,
225 			RS_COLUMN_MIMO2,
226 			RS_COLUMN_INVALID,
227 			RS_COLUMN_INVALID,
228 			RS_COLUMN_INVALID,
229 			RS_COLUMN_INVALID,
230 		},
231 		.checks = {
232 			rs_ant_allow,
233 		},
234 	},
235 	[RS_COLUMN_LEGACY_ANT_B] = {
236 		.mode = RS_LEGACY,
237 		.ant = ANT_B,
238 		.next_columns = {
239 			RS_COLUMN_LEGACY_ANT_A,
240 			RS_COLUMN_SISO_ANT_B,
241 			RS_COLUMN_MIMO2,
242 			RS_COLUMN_INVALID,
243 			RS_COLUMN_INVALID,
244 			RS_COLUMN_INVALID,
245 			RS_COLUMN_INVALID,
246 		},
247 		.checks = {
248 			rs_ant_allow,
249 		},
250 	},
251 	[RS_COLUMN_SISO_ANT_A] = {
252 		.mode = RS_SISO,
253 		.ant = ANT_A,
254 		.next_columns = {
255 			RS_COLUMN_SISO_ANT_B,
256 			RS_COLUMN_MIMO2,
257 			RS_COLUMN_SISO_ANT_A_SGI,
258 			RS_COLUMN_LEGACY_ANT_A,
259 			RS_COLUMN_LEGACY_ANT_B,
260 			RS_COLUMN_INVALID,
261 			RS_COLUMN_INVALID,
262 		},
263 		.checks = {
264 			rs_siso_allow,
265 			rs_ant_allow,
266 		},
267 	},
268 	[RS_COLUMN_SISO_ANT_B] = {
269 		.mode = RS_SISO,
270 		.ant = ANT_B,
271 		.next_columns = {
272 			RS_COLUMN_SISO_ANT_A,
273 			RS_COLUMN_MIMO2,
274 			RS_COLUMN_SISO_ANT_B_SGI,
275 			RS_COLUMN_LEGACY_ANT_A,
276 			RS_COLUMN_LEGACY_ANT_B,
277 			RS_COLUMN_INVALID,
278 			RS_COLUMN_INVALID,
279 		},
280 		.checks = {
281 			rs_siso_allow,
282 			rs_ant_allow,
283 		},
284 	},
285 	[RS_COLUMN_SISO_ANT_A_SGI] = {
286 		.mode = RS_SISO,
287 		.ant = ANT_A,
288 		.sgi = true,
289 		.next_columns = {
290 			RS_COLUMN_SISO_ANT_B_SGI,
291 			RS_COLUMN_MIMO2_SGI,
292 			RS_COLUMN_SISO_ANT_A,
293 			RS_COLUMN_LEGACY_ANT_A,
294 			RS_COLUMN_LEGACY_ANT_B,
295 			RS_COLUMN_INVALID,
296 			RS_COLUMN_INVALID,
297 		},
298 		.checks = {
299 			rs_siso_allow,
300 			rs_ant_allow,
301 			rs_sgi_allow,
302 		},
303 	},
304 	[RS_COLUMN_SISO_ANT_B_SGI] = {
305 		.mode = RS_SISO,
306 		.ant = ANT_B,
307 		.sgi = true,
308 		.next_columns = {
309 			RS_COLUMN_SISO_ANT_A_SGI,
310 			RS_COLUMN_MIMO2_SGI,
311 			RS_COLUMN_SISO_ANT_B,
312 			RS_COLUMN_LEGACY_ANT_A,
313 			RS_COLUMN_LEGACY_ANT_B,
314 			RS_COLUMN_INVALID,
315 			RS_COLUMN_INVALID,
316 		},
317 		.checks = {
318 			rs_siso_allow,
319 			rs_ant_allow,
320 			rs_sgi_allow,
321 		},
322 	},
323 	[RS_COLUMN_MIMO2] = {
324 		.mode = RS_MIMO2,
325 		.ant = ANT_AB,
326 		.next_columns = {
327 			RS_COLUMN_SISO_ANT_A,
328 			RS_COLUMN_MIMO2_SGI,
329 			RS_COLUMN_LEGACY_ANT_A,
330 			RS_COLUMN_LEGACY_ANT_B,
331 			RS_COLUMN_INVALID,
332 			RS_COLUMN_INVALID,
333 			RS_COLUMN_INVALID,
334 		},
335 		.checks = {
336 			rs_mimo_allow,
337 		},
338 	},
339 	[RS_COLUMN_MIMO2_SGI] = {
340 		.mode = RS_MIMO2,
341 		.ant = ANT_AB,
342 		.sgi = true,
343 		.next_columns = {
344 			RS_COLUMN_SISO_ANT_A_SGI,
345 			RS_COLUMN_MIMO2,
346 			RS_COLUMN_LEGACY_ANT_A,
347 			RS_COLUMN_LEGACY_ANT_B,
348 			RS_COLUMN_INVALID,
349 			RS_COLUMN_INVALID,
350 			RS_COLUMN_INVALID,
351 		},
352 		.checks = {
353 			rs_mimo_allow,
354 			rs_sgi_allow,
355 		},
356 	},
357 };
358 
359 static inline u8 rs_extract_rate(u32 rate_n_flags)
360 {
361 	/* also works for HT because bits 7:6 are zero there */
362 	return (u8)(rate_n_flags & RATE_LEGACY_RATE_MSK);
363 }
364 
365 static int iwl_hwrate_to_plcp_idx(u32 rate_n_flags)
366 {
367 	int idx = 0;
368 
369 	if (rate_n_flags & RATE_MCS_HT_MSK) {
370 		idx = rate_n_flags & RATE_HT_MCS_RATE_CODE_MSK;
371 		idx += IWL_RATE_MCS_0_INDEX;
372 
373 		/* skip 9M not supported in HT*/
374 		if (idx >= IWL_RATE_9M_INDEX)
375 			idx += 1;
376 		if ((idx >= IWL_FIRST_HT_RATE) && (idx <= IWL_LAST_HT_RATE))
377 			return idx;
378 	} else if (rate_n_flags & RATE_MCS_VHT_MSK) {
379 		idx = rate_n_flags & RATE_VHT_MCS_RATE_CODE_MSK;
380 		idx += IWL_RATE_MCS_0_INDEX;
381 
382 		/* skip 9M not supported in VHT*/
383 		if (idx >= IWL_RATE_9M_INDEX)
384 			idx++;
385 		if ((idx >= IWL_FIRST_VHT_RATE) && (idx <= IWL_LAST_VHT_RATE))
386 			return idx;
387 	} else {
388 		/* legacy rate format, search for match in table */
389 
390 		u8 legacy_rate = rs_extract_rate(rate_n_flags);
391 		for (idx = 0; idx < ARRAY_SIZE(iwl_rates); idx++)
392 			if (iwl_rates[idx].plcp == legacy_rate)
393 				return idx;
394 	}
395 
396 	return IWL_RATE_INVALID;
397 }
398 
399 static void rs_rate_scale_perform(struct iwl_mvm *mvm,
400 				  struct ieee80211_sta *sta,
401 				  struct iwl_lq_sta *lq_sta,
402 				  int tid);
403 static void rs_fill_lq_cmd(struct iwl_mvm *mvm,
404 			   struct ieee80211_sta *sta,
405 			   struct iwl_lq_sta *lq_sta,
406 			   const struct rs_rate *initial_rate);
407 static void rs_stay_in_table(struct iwl_lq_sta *lq_sta, bool force_search);
408 
409 /**
410  * The following tables contain the expected throughput metrics for all rates
411  *
412  *	1, 2, 5.5, 11, 6, 9, 12, 18, 24, 36, 48, 54, 60 MBits
413  *
414  * where invalid entries are zeros.
415  *
416  * CCK rates are only valid in legacy table and will only be used in G
417  * (2.4 GHz) band.
418  */
419 
420 static const u16 expected_tpt_legacy[IWL_RATE_COUNT] = {
421 	7, 13, 35, 58, 40, 57, 72, 98, 121, 154, 177, 186, 0, 0, 0
422 };
423 
424 /* Expected TpT tables. 4 indexes:
425  * 0 - NGI, 1 - SGI, 2 - AGG+NGI, 3 - AGG+SGI
426  */
427 static const u16 expected_tpt_siso_20MHz[4][IWL_RATE_COUNT] = {
428 	{0, 0, 0, 0, 42, 0,  76, 102, 124, 159, 183, 193, 202, 216, 0},
429 	{0, 0, 0, 0, 46, 0,  82, 110, 132, 168, 192, 202, 210, 225, 0},
430 	{0, 0, 0, 0, 49, 0,  97, 145, 192, 285, 375, 420, 464, 551, 0},
431 	{0, 0, 0, 0, 54, 0, 108, 160, 213, 315, 415, 465, 513, 608, 0},
432 };
433 
434 static const u16 expected_tpt_siso_40MHz[4][IWL_RATE_COUNT] = {
435 	{0, 0, 0, 0,  77, 0, 127, 160, 184, 220, 242, 250,  257,  269,  275},
436 	{0, 0, 0, 0,  83, 0, 135, 169, 193, 229, 250, 257,  264,  275,  280},
437 	{0, 0, 0, 0, 101, 0, 199, 295, 389, 570, 744, 828,  911, 1070, 1173},
438 	{0, 0, 0, 0, 112, 0, 220, 326, 429, 629, 819, 912, 1000, 1173, 1284},
439 };
440 
441 static const u16 expected_tpt_siso_80MHz[4][IWL_RATE_COUNT] = {
442 	{0, 0, 0, 0, 130, 0, 191, 223, 244,  273,  288,  294,  298,  305,  308},
443 	{0, 0, 0, 0, 138, 0, 200, 231, 251,  279,  293,  298,  302,  308,  312},
444 	{0, 0, 0, 0, 217, 0, 429, 634, 834, 1220, 1585, 1760, 1931, 2258, 2466},
445 	{0, 0, 0, 0, 241, 0, 475, 701, 921, 1343, 1741, 1931, 2117, 2468, 2691},
446 };
447 
448 static const u16 expected_tpt_mimo2_20MHz[4][IWL_RATE_COUNT] = {
449 	{0, 0, 0, 0,  74, 0, 123, 155, 179, 213, 235, 243, 250,  261, 0},
450 	{0, 0, 0, 0,  81, 0, 131, 164, 187, 221, 242, 250, 256,  267, 0},
451 	{0, 0, 0, 0,  98, 0, 193, 286, 375, 550, 718, 799, 878, 1032, 0},
452 	{0, 0, 0, 0, 109, 0, 214, 316, 414, 607, 790, 879, 965, 1132, 0},
453 };
454 
455 static const u16 expected_tpt_mimo2_40MHz[4][IWL_RATE_COUNT] = {
456 	{0, 0, 0, 0, 123, 0, 182, 214, 235,  264,  279,  285,  289,  296,  300},
457 	{0, 0, 0, 0, 131, 0, 191, 222, 242,  270,  284,  289,  293,  300,  303},
458 	{0, 0, 0, 0, 200, 0, 390, 571, 741, 1067, 1365, 1505, 1640, 1894, 2053},
459 	{0, 0, 0, 0, 221, 0, 430, 630, 816, 1169, 1490, 1641, 1784, 2053, 2221},
460 };
461 
462 static const u16 expected_tpt_mimo2_80MHz[4][IWL_RATE_COUNT] = {
463 	{0, 0, 0, 0, 182, 0, 240,  264,  278,  299,  308,  311,  313,  317,  319},
464 	{0, 0, 0, 0, 190, 0, 247,  269,  282,  302,  310,  313,  315,  319,  320},
465 	{0, 0, 0, 0, 428, 0, 833, 1215, 1577, 2254, 2863, 3147, 3418, 3913, 4219},
466 	{0, 0, 0, 0, 474, 0, 920, 1338, 1732, 2464, 3116, 3418, 3705, 4225, 4545},
467 };
468 
469 /* mbps, mcs */
470 static const struct iwl_rate_mcs_info iwl_rate_mcs[IWL_RATE_COUNT] = {
471 	{  "1", "BPSK DSSS"},
472 	{  "2", "QPSK DSSS"},
473 	{"5.5", "BPSK CCK"},
474 	{ "11", "QPSK CCK"},
475 	{  "6", "BPSK 1/2"},
476 	{  "9", "BPSK 1/2"},
477 	{ "12", "QPSK 1/2"},
478 	{ "18", "QPSK 3/4"},
479 	{ "24", "16QAM 1/2"},
480 	{ "36", "16QAM 3/4"},
481 	{ "48", "64QAM 2/3"},
482 	{ "54", "64QAM 3/4"},
483 	{ "60", "64QAM 5/6"},
484 };
485 
486 #define MCS_INDEX_PER_STREAM	(8)
487 
488 static const char *rs_pretty_ant(u8 ant)
489 {
490 	static const char * const ant_name[] = {
491 		[ANT_NONE] = "None",
492 		[ANT_A]    = "A",
493 		[ANT_B]    = "B",
494 		[ANT_AB]   = "AB",
495 		[ANT_C]    = "C",
496 		[ANT_AC]   = "AC",
497 		[ANT_BC]   = "BC",
498 		[ANT_ABC]  = "ABC",
499 	};
500 
501 	if (ant > ANT_ABC)
502 		return "UNKNOWN";
503 
504 	return ant_name[ant];
505 }
506 
507 static const char *rs_pretty_lq_type(enum iwl_table_type type)
508 {
509 	static const char * const lq_types[] = {
510 		[LQ_NONE] = "NONE",
511 		[LQ_LEGACY_A] = "LEGACY_A",
512 		[LQ_LEGACY_G] = "LEGACY_G",
513 		[LQ_HT_SISO] = "HT SISO",
514 		[LQ_HT_MIMO2] = "HT MIMO",
515 		[LQ_VHT_SISO] = "VHT SISO",
516 		[LQ_VHT_MIMO2] = "VHT MIMO",
517 	};
518 
519 	if (type < LQ_NONE || type >= LQ_MAX)
520 		return "UNKNOWN";
521 
522 	return lq_types[type];
523 }
524 
525 static char *rs_pretty_rate(const struct rs_rate *rate)
526 {
527 	static char buf[40];
528 	static const char * const legacy_rates[] = {
529 		[IWL_RATE_1M_INDEX] = "1M",
530 		[IWL_RATE_2M_INDEX] = "2M",
531 		[IWL_RATE_5M_INDEX] = "5.5M",
532 		[IWL_RATE_11M_INDEX] = "11M",
533 		[IWL_RATE_6M_INDEX] = "6M",
534 		[IWL_RATE_9M_INDEX] = "9M",
535 		[IWL_RATE_12M_INDEX] = "12M",
536 		[IWL_RATE_18M_INDEX] = "18M",
537 		[IWL_RATE_24M_INDEX] = "24M",
538 		[IWL_RATE_36M_INDEX] = "36M",
539 		[IWL_RATE_48M_INDEX] = "48M",
540 		[IWL_RATE_54M_INDEX] = "54M",
541 	};
542 	static const char *const ht_vht_rates[] = {
543 		[IWL_RATE_MCS_0_INDEX] = "MCS0",
544 		[IWL_RATE_MCS_1_INDEX] = "MCS1",
545 		[IWL_RATE_MCS_2_INDEX] = "MCS2",
546 		[IWL_RATE_MCS_3_INDEX] = "MCS3",
547 		[IWL_RATE_MCS_4_INDEX] = "MCS4",
548 		[IWL_RATE_MCS_5_INDEX] = "MCS5",
549 		[IWL_RATE_MCS_6_INDEX] = "MCS6",
550 		[IWL_RATE_MCS_7_INDEX] = "MCS7",
551 		[IWL_RATE_MCS_8_INDEX] = "MCS8",
552 		[IWL_RATE_MCS_9_INDEX] = "MCS9",
553 	};
554 	const char *rate_str;
555 
556 	if (is_type_legacy(rate->type) && (rate->index <= IWL_RATE_54M_INDEX))
557 		rate_str = legacy_rates[rate->index];
558 	else if ((is_type_ht(rate->type) || is_type_vht(rate->type)) &&
559 		 (rate->index >= IWL_RATE_MCS_0_INDEX) &&
560 		 (rate->index <= IWL_RATE_MCS_9_INDEX))
561 		rate_str = ht_vht_rates[rate->index];
562 	else
563 		rate_str = "BAD_RATE";
564 
565 	sprintf(buf, "(%s|%s|%s)", rs_pretty_lq_type(rate->type),
566 		rs_pretty_ant(rate->ant), rate_str);
567 	return buf;
568 }
569 
570 static inline void rs_dump_rate(struct iwl_mvm *mvm, const struct rs_rate *rate,
571 				const char *prefix)
572 {
573 	IWL_DEBUG_RATE(mvm,
574 		       "%s: %s BW: %d SGI: %d LDPC: %d STBC: %d\n",
575 		       prefix, rs_pretty_rate(rate), rate->bw,
576 		       rate->sgi, rate->ldpc, rate->stbc);
577 }
578 
579 static void rs_rate_scale_clear_window(struct iwl_rate_scale_data *window)
580 {
581 	window->data = 0;
582 	window->success_counter = 0;
583 	window->success_ratio = IWL_INVALID_VALUE;
584 	window->counter = 0;
585 	window->average_tpt = IWL_INVALID_VALUE;
586 }
587 
588 static void rs_rate_scale_clear_tbl_windows(struct iwl_mvm *mvm,
589 					    struct iwl_scale_tbl_info *tbl)
590 {
591 	int i;
592 
593 	IWL_DEBUG_RATE(mvm, "Clearing up window stats\n");
594 	for (i = 0; i < IWL_RATE_COUNT; i++)
595 		rs_rate_scale_clear_window(&tbl->win[i]);
596 
597 	for (i = 0; i < ARRAY_SIZE(tbl->tpc_win); i++)
598 		rs_rate_scale_clear_window(&tbl->tpc_win[i]);
599 }
600 
601 static inline u8 rs_is_valid_ant(u8 valid_antenna, u8 ant_type)
602 {
603 	return (ant_type & valid_antenna) == ant_type;
604 }
605 
606 static int rs_tl_turn_on_agg_for_tid(struct iwl_mvm *mvm,
607 				     struct iwl_lq_sta *lq_data, u8 tid,
608 				     struct ieee80211_sta *sta)
609 {
610 	int ret = -EAGAIN;
611 
612 	IWL_DEBUG_HT(mvm, "Starting Tx agg: STA: %pM tid: %d\n",
613 		     sta->addr, tid);
614 	ret = ieee80211_start_tx_ba_session(sta, tid, 5000);
615 	if (ret == -EAGAIN) {
616 		/*
617 		 * driver and mac80211 is out of sync
618 		 * this might be cause by reloading firmware
619 		 * stop the tx ba session here
620 		 */
621 		IWL_ERR(mvm, "Fail start Tx agg on tid: %d\n",
622 			tid);
623 		ieee80211_stop_tx_ba_session(sta, tid);
624 	}
625 	return ret;
626 }
627 
628 static void rs_tl_turn_on_agg(struct iwl_mvm *mvm, u8 tid,
629 			      struct iwl_lq_sta *lq_data,
630 			      struct ieee80211_sta *sta)
631 {
632 	if (tid < IWL_MAX_TID_COUNT)
633 		rs_tl_turn_on_agg_for_tid(mvm, lq_data, tid, sta);
634 	else
635 		IWL_ERR(mvm, "tid exceeds max TID count: %d/%d\n",
636 			tid, IWL_MAX_TID_COUNT);
637 }
638 
639 static inline int get_num_of_ant_from_rate(u32 rate_n_flags)
640 {
641 	return !!(rate_n_flags & RATE_MCS_ANT_A_MSK) +
642 	       !!(rate_n_flags & RATE_MCS_ANT_B_MSK) +
643 	       !!(rate_n_flags & RATE_MCS_ANT_C_MSK);
644 }
645 
646 /*
647  * Static function to get the expected throughput from an iwl_scale_tbl_info
648  * that wraps a NULL pointer check
649  */
650 static s32 get_expected_tpt(struct iwl_scale_tbl_info *tbl, int rs_index)
651 {
652 	if (tbl->expected_tpt)
653 		return tbl->expected_tpt[rs_index];
654 	return 0;
655 }
656 
657 /**
658  * rs_collect_tx_data - Update the success/failure sliding window
659  *
660  * We keep a sliding window of the last 62 packets transmitted
661  * at this rate.  window->data contains the bitmask of successful
662  * packets.
663  */
664 static int _rs_collect_tx_data(struct iwl_mvm *mvm,
665 			       struct iwl_scale_tbl_info *tbl,
666 			       int scale_index, int attempts, int successes,
667 			       struct iwl_rate_scale_data *window)
668 {
669 	static const u64 mask = (((u64)1) << (IWL_RATE_MAX_WINDOW - 1));
670 	s32 fail_count, tpt;
671 
672 	/* Get expected throughput */
673 	tpt = get_expected_tpt(tbl, scale_index);
674 
675 	/*
676 	 * Keep track of only the latest 62 tx frame attempts in this rate's
677 	 * history window; anything older isn't really relevant any more.
678 	 * If we have filled up the sliding window, drop the oldest attempt;
679 	 * if the oldest attempt (highest bit in bitmap) shows "success",
680 	 * subtract "1" from the success counter (this is the main reason
681 	 * we keep these bitmaps!).
682 	 */
683 	while (attempts > 0) {
684 		if (window->counter >= IWL_RATE_MAX_WINDOW) {
685 			/* remove earliest */
686 			window->counter = IWL_RATE_MAX_WINDOW - 1;
687 
688 			if (window->data & mask) {
689 				window->data &= ~mask;
690 				window->success_counter--;
691 			}
692 		}
693 
694 		/* Increment frames-attempted counter */
695 		window->counter++;
696 
697 		/* Shift bitmap by one frame to throw away oldest history */
698 		window->data <<= 1;
699 
700 		/* Mark the most recent #successes attempts as successful */
701 		if (successes > 0) {
702 			window->success_counter++;
703 			window->data |= 0x1;
704 			successes--;
705 		}
706 
707 		attempts--;
708 	}
709 
710 	/* Calculate current success ratio, avoid divide-by-0! */
711 	if (window->counter > 0)
712 		window->success_ratio = 128 * (100 * window->success_counter)
713 					/ window->counter;
714 	else
715 		window->success_ratio = IWL_INVALID_VALUE;
716 
717 	fail_count = window->counter - window->success_counter;
718 
719 	/* Calculate average throughput, if we have enough history. */
720 	if ((fail_count >= IWL_MVM_RS_RATE_MIN_FAILURE_TH) ||
721 	    (window->success_counter >= IWL_MVM_RS_RATE_MIN_SUCCESS_TH))
722 		window->average_tpt = (window->success_ratio * tpt + 64) / 128;
723 	else
724 		window->average_tpt = IWL_INVALID_VALUE;
725 
726 	return 0;
727 }
728 
729 static int rs_collect_tpc_data(struct iwl_mvm *mvm,
730 			       struct iwl_lq_sta *lq_sta,
731 			       struct iwl_scale_tbl_info *tbl,
732 			       int scale_index, int attempts, int successes,
733 			       u8 reduced_txp)
734 {
735 	struct iwl_rate_scale_data *window = NULL;
736 
737 	if (WARN_ON_ONCE(reduced_txp > TPC_MAX_REDUCTION))
738 		return -EINVAL;
739 
740 	window = &tbl->tpc_win[reduced_txp];
741 	return  _rs_collect_tx_data(mvm, tbl, scale_index, attempts, successes,
742 				    window);
743 }
744 
745 static int rs_collect_tlc_data(struct iwl_mvm *mvm,
746 			       struct iwl_lq_sta *lq_sta,
747 			       struct iwl_scale_tbl_info *tbl,
748 			       int scale_index, int attempts, int successes)
749 {
750 	struct iwl_rate_scale_data *window = NULL;
751 
752 	if (scale_index < 0 || scale_index >= IWL_RATE_COUNT)
753 		return -EINVAL;
754 
755 	if (tbl->column != RS_COLUMN_INVALID) {
756 		struct lq_sta_pers *pers = &lq_sta->pers;
757 
758 		pers->tx_stats[tbl->column][scale_index].total += attempts;
759 		pers->tx_stats[tbl->column][scale_index].success += successes;
760 	}
761 
762 	/* Select window for current tx bit rate */
763 	window = &(tbl->win[scale_index]);
764 	return _rs_collect_tx_data(mvm, tbl, scale_index, attempts, successes,
765 				   window);
766 }
767 
768 /* Convert rs_rate object into ucode rate bitmask */
769 static u32 ucode_rate_from_rs_rate(struct iwl_mvm *mvm,
770 				  struct rs_rate *rate)
771 {
772 	u32 ucode_rate = 0;
773 	int index = rate->index;
774 
775 	ucode_rate |= ((rate->ant << RATE_MCS_ANT_POS) &
776 			 RATE_MCS_ANT_ABC_MSK);
777 
778 	if (is_legacy(rate)) {
779 		ucode_rate |= iwl_rates[index].plcp;
780 		if (index >= IWL_FIRST_CCK_RATE && index <= IWL_LAST_CCK_RATE)
781 			ucode_rate |= RATE_MCS_CCK_MSK;
782 		return ucode_rate;
783 	}
784 
785 	if (is_ht(rate)) {
786 		if (index < IWL_FIRST_HT_RATE || index > IWL_LAST_HT_RATE) {
787 			IWL_ERR(mvm, "Invalid HT rate index %d\n", index);
788 			index = IWL_LAST_HT_RATE;
789 		}
790 		ucode_rate |= RATE_MCS_HT_MSK;
791 
792 		if (is_ht_siso(rate))
793 			ucode_rate |= iwl_rates[index].plcp_ht_siso;
794 		else if (is_ht_mimo2(rate))
795 			ucode_rate |= iwl_rates[index].plcp_ht_mimo2;
796 		else
797 			WARN_ON_ONCE(1);
798 	} else if (is_vht(rate)) {
799 		if (index < IWL_FIRST_VHT_RATE || index > IWL_LAST_VHT_RATE) {
800 			IWL_ERR(mvm, "Invalid VHT rate index %d\n", index);
801 			index = IWL_LAST_VHT_RATE;
802 		}
803 		ucode_rate |= RATE_MCS_VHT_MSK;
804 		if (is_vht_siso(rate))
805 			ucode_rate |= iwl_rates[index].plcp_vht_siso;
806 		else if (is_vht_mimo2(rate))
807 			ucode_rate |= iwl_rates[index].plcp_vht_mimo2;
808 		else
809 			WARN_ON_ONCE(1);
810 
811 	} else {
812 		IWL_ERR(mvm, "Invalid rate->type %d\n", rate->type);
813 	}
814 
815 	if (is_siso(rate) && rate->stbc) {
816 		/* To enable STBC we need to set both a flag and ANT_AB */
817 		ucode_rate |= RATE_MCS_ANT_AB_MSK;
818 		ucode_rate |= RATE_MCS_VHT_STBC_MSK;
819 	}
820 
821 	ucode_rate |= rate->bw;
822 	if (rate->sgi)
823 		ucode_rate |= RATE_MCS_SGI_MSK;
824 	if (rate->ldpc)
825 		ucode_rate |= RATE_MCS_LDPC_MSK;
826 
827 	return ucode_rate;
828 }
829 
830 /* Convert a ucode rate into an rs_rate object */
831 static int rs_rate_from_ucode_rate(const u32 ucode_rate,
832 				   enum nl80211_band band,
833 				   struct rs_rate *rate)
834 {
835 	u32 ant_msk = ucode_rate & RATE_MCS_ANT_ABC_MSK;
836 	u8 num_of_ant = get_num_of_ant_from_rate(ucode_rate);
837 	u8 nss;
838 
839 	memset(rate, 0, sizeof(*rate));
840 	rate->index = iwl_hwrate_to_plcp_idx(ucode_rate);
841 
842 	if (rate->index == IWL_RATE_INVALID)
843 		return -EINVAL;
844 
845 	rate->ant = (ant_msk >> RATE_MCS_ANT_POS);
846 
847 	/* Legacy */
848 	if (!(ucode_rate & RATE_MCS_HT_MSK) &&
849 	    !(ucode_rate & RATE_MCS_VHT_MSK)) {
850 		if (num_of_ant == 1) {
851 			if (band == NL80211_BAND_5GHZ)
852 				rate->type = LQ_LEGACY_A;
853 			else
854 				rate->type = LQ_LEGACY_G;
855 		}
856 
857 		return 0;
858 	}
859 
860 	/* HT or VHT */
861 	if (ucode_rate & RATE_MCS_SGI_MSK)
862 		rate->sgi = true;
863 	if (ucode_rate & RATE_MCS_LDPC_MSK)
864 		rate->ldpc = true;
865 	if (ucode_rate & RATE_MCS_VHT_STBC_MSK)
866 		rate->stbc = true;
867 	if (ucode_rate & RATE_MCS_BF_MSK)
868 		rate->bfer = true;
869 
870 	rate->bw = ucode_rate & RATE_MCS_CHAN_WIDTH_MSK;
871 
872 	if (ucode_rate & RATE_MCS_HT_MSK) {
873 		nss = ((ucode_rate & RATE_HT_MCS_NSS_MSK) >>
874 		       RATE_HT_MCS_NSS_POS) + 1;
875 
876 		if (nss == 1) {
877 			rate->type = LQ_HT_SISO;
878 			WARN_ONCE(!rate->stbc && !rate->bfer && num_of_ant != 1,
879 				  "stbc %d bfer %d",
880 				  rate->stbc, rate->bfer);
881 		} else if (nss == 2) {
882 			rate->type = LQ_HT_MIMO2;
883 			WARN_ON_ONCE(num_of_ant != 2);
884 		} else {
885 			WARN_ON_ONCE(1);
886 		}
887 	} else if (ucode_rate & RATE_MCS_VHT_MSK) {
888 		nss = ((ucode_rate & RATE_VHT_MCS_NSS_MSK) >>
889 		       RATE_VHT_MCS_NSS_POS) + 1;
890 
891 		if (nss == 1) {
892 			rate->type = LQ_VHT_SISO;
893 			WARN_ONCE(!rate->stbc && !rate->bfer && num_of_ant != 1,
894 				  "stbc %d bfer %d",
895 				  rate->stbc, rate->bfer);
896 		} else if (nss == 2) {
897 			rate->type = LQ_VHT_MIMO2;
898 			WARN_ON_ONCE(num_of_ant != 2);
899 		} else {
900 			WARN_ON_ONCE(1);
901 		}
902 	}
903 
904 	WARN_ON_ONCE(rate->bw == RATE_MCS_CHAN_WIDTH_160);
905 	WARN_ON_ONCE(rate->bw == RATE_MCS_CHAN_WIDTH_80 &&
906 		     !is_vht(rate));
907 
908 	return 0;
909 }
910 
911 /* switch to another antenna/antennas and return 1 */
912 /* if no other valid antenna found, return 0 */
913 static int rs_toggle_antenna(u32 valid_ant, struct rs_rate *rate)
914 {
915 	u8 new_ant_type;
916 
917 	if (!rate->ant || rate->ant > ANT_ABC)
918 		return 0;
919 
920 	if (!rs_is_valid_ant(valid_ant, rate->ant))
921 		return 0;
922 
923 	new_ant_type = ant_toggle_lookup[rate->ant];
924 
925 	while ((new_ant_type != rate->ant) &&
926 	       !rs_is_valid_ant(valid_ant, new_ant_type))
927 		new_ant_type = ant_toggle_lookup[new_ant_type];
928 
929 	if (new_ant_type == rate->ant)
930 		return 0;
931 
932 	rate->ant = new_ant_type;
933 
934 	return 1;
935 }
936 
937 static u16 rs_get_supported_rates(struct iwl_lq_sta *lq_sta,
938 				  struct rs_rate *rate)
939 {
940 	if (is_legacy(rate))
941 		return lq_sta->active_legacy_rate;
942 	else if (is_siso(rate))
943 		return lq_sta->active_siso_rate;
944 	else if (is_mimo2(rate))
945 		return lq_sta->active_mimo2_rate;
946 
947 	WARN_ON_ONCE(1);
948 	return 0;
949 }
950 
951 static u16 rs_get_adjacent_rate(struct iwl_mvm *mvm, u8 index, u16 rate_mask,
952 				int rate_type)
953 {
954 	u8 high = IWL_RATE_INVALID;
955 	u8 low = IWL_RATE_INVALID;
956 
957 	/* 802.11A or ht walks to the next literal adjacent rate in
958 	 * the rate table */
959 	if (is_type_a_band(rate_type) || !is_type_legacy(rate_type)) {
960 		int i;
961 		u32 mask;
962 
963 		/* Find the previous rate that is in the rate mask */
964 		i = index - 1;
965 		for (mask = (1 << i); i >= 0; i--, mask >>= 1) {
966 			if (rate_mask & mask) {
967 				low = i;
968 				break;
969 			}
970 		}
971 
972 		/* Find the next rate that is in the rate mask */
973 		i = index + 1;
974 		for (mask = (1 << i); i < IWL_RATE_COUNT; i++, mask <<= 1) {
975 			if (rate_mask & mask) {
976 				high = i;
977 				break;
978 			}
979 		}
980 
981 		return (high << 8) | low;
982 	}
983 
984 	low = index;
985 	while (low != IWL_RATE_INVALID) {
986 		low = iwl_rates[low].prev_rs;
987 		if (low == IWL_RATE_INVALID)
988 			break;
989 		if (rate_mask & (1 << low))
990 			break;
991 	}
992 
993 	high = index;
994 	while (high != IWL_RATE_INVALID) {
995 		high = iwl_rates[high].next_rs;
996 		if (high == IWL_RATE_INVALID)
997 			break;
998 		if (rate_mask & (1 << high))
999 			break;
1000 	}
1001 
1002 	return (high << 8) | low;
1003 }
1004 
1005 static inline bool rs_rate_supported(struct iwl_lq_sta *lq_sta,
1006 				     struct rs_rate *rate)
1007 {
1008 	return BIT(rate->index) & rs_get_supported_rates(lq_sta, rate);
1009 }
1010 
1011 /* Get the next supported lower rate in the current column.
1012  * Return true if bottom rate in the current column was reached
1013  */
1014 static bool rs_get_lower_rate_in_column(struct iwl_lq_sta *lq_sta,
1015 					struct rs_rate *rate)
1016 {
1017 	u8 low;
1018 	u16 high_low;
1019 	u16 rate_mask;
1020 	struct iwl_mvm *mvm = lq_sta->pers.drv;
1021 
1022 	rate_mask = rs_get_supported_rates(lq_sta, rate);
1023 	high_low = rs_get_adjacent_rate(mvm, rate->index, rate_mask,
1024 					rate->type);
1025 	low = high_low & 0xff;
1026 
1027 	/* Bottom rate of column reached */
1028 	if (low == IWL_RATE_INVALID)
1029 		return true;
1030 
1031 	rate->index = low;
1032 	return false;
1033 }
1034 
1035 /* Get the next rate to use following a column downgrade */
1036 static void rs_get_lower_rate_down_column(struct iwl_lq_sta *lq_sta,
1037 					  struct rs_rate *rate)
1038 {
1039 	struct iwl_mvm *mvm = lq_sta->pers.drv;
1040 
1041 	if (is_legacy(rate)) {
1042 		/* No column to downgrade from Legacy */
1043 		return;
1044 	} else if (is_siso(rate)) {
1045 		/* Downgrade to Legacy if we were in SISO */
1046 		if (lq_sta->band == NL80211_BAND_5GHZ)
1047 			rate->type = LQ_LEGACY_A;
1048 		else
1049 			rate->type = LQ_LEGACY_G;
1050 
1051 		rate->bw = RATE_MCS_CHAN_WIDTH_20;
1052 
1053 		WARN_ON_ONCE(rate->index < IWL_RATE_MCS_0_INDEX ||
1054 			     rate->index > IWL_RATE_MCS_9_INDEX);
1055 
1056 		rate->index = rs_ht_to_legacy[rate->index];
1057 		rate->ldpc = false;
1058 	} else {
1059 		/* Downgrade to SISO with same MCS if in MIMO  */
1060 		rate->type = is_vht_mimo2(rate) ?
1061 			LQ_VHT_SISO : LQ_HT_SISO;
1062 	}
1063 
1064 	if (num_of_ant(rate->ant) > 1)
1065 		rate->ant = first_antenna(iwl_mvm_get_valid_tx_ant(mvm));
1066 
1067 	/* Relevant in both switching to SISO or Legacy */
1068 	rate->sgi = false;
1069 
1070 	if (!rs_rate_supported(lq_sta, rate))
1071 		rs_get_lower_rate_in_column(lq_sta, rate);
1072 }
1073 
1074 /* Check if both rates are identical
1075  * allow_ant_mismatch enables matching a SISO rate on ANT_A or ANT_B
1076  * with a rate indicating STBC/BFER and ANT_AB.
1077  */
1078 static inline bool rs_rate_equal(struct rs_rate *a,
1079 				 struct rs_rate *b,
1080 				 bool allow_ant_mismatch)
1081 
1082 {
1083 	bool ant_match = (a->ant == b->ant) && (a->stbc == b->stbc) &&
1084 		(a->bfer == b->bfer);
1085 
1086 	if (allow_ant_mismatch) {
1087 		if (a->stbc || a->bfer) {
1088 			WARN_ONCE(a->ant != ANT_AB, "stbc %d bfer %d ant %d",
1089 				  a->stbc, a->bfer, a->ant);
1090 			ant_match |= (b->ant == ANT_A || b->ant == ANT_B);
1091 		} else if (b->stbc || b->bfer) {
1092 			WARN_ONCE(b->ant != ANT_AB, "stbc %d bfer %d ant %d",
1093 				  b->stbc, b->bfer, b->ant);
1094 			ant_match |= (a->ant == ANT_A || a->ant == ANT_B);
1095 		}
1096 	}
1097 
1098 	return (a->type == b->type) && (a->bw == b->bw) && (a->sgi == b->sgi) &&
1099 		(a->ldpc == b->ldpc) && (a->index == b->index) && ant_match;
1100 }
1101 
1102 /* Check if both rates share the same column */
1103 static inline bool rs_rate_column_match(struct rs_rate *a,
1104 					struct rs_rate *b)
1105 {
1106 	bool ant_match;
1107 
1108 	if (a->stbc || a->bfer)
1109 		ant_match = (b->ant == ANT_A || b->ant == ANT_B);
1110 	else
1111 		ant_match = (a->ant == b->ant);
1112 
1113 	return (a->type == b->type) && (a->bw == b->bw) && (a->sgi == b->sgi)
1114 		&& ant_match;
1115 }
1116 
1117 static inline enum rs_column rs_get_column_from_rate(struct rs_rate *rate)
1118 {
1119 	if (is_legacy(rate)) {
1120 		if (rate->ant == ANT_A)
1121 			return RS_COLUMN_LEGACY_ANT_A;
1122 
1123 		if (rate->ant == ANT_B)
1124 			return RS_COLUMN_LEGACY_ANT_B;
1125 
1126 		goto err;
1127 	}
1128 
1129 	if (is_siso(rate)) {
1130 		if (rate->ant == ANT_A || rate->stbc || rate->bfer)
1131 			return rate->sgi ? RS_COLUMN_SISO_ANT_A_SGI :
1132 				RS_COLUMN_SISO_ANT_A;
1133 
1134 		if (rate->ant == ANT_B)
1135 			return rate->sgi ? RS_COLUMN_SISO_ANT_B_SGI :
1136 				RS_COLUMN_SISO_ANT_B;
1137 
1138 		goto err;
1139 	}
1140 
1141 	if (is_mimo(rate))
1142 		return rate->sgi ? RS_COLUMN_MIMO2_SGI : RS_COLUMN_MIMO2;
1143 
1144 err:
1145 	return RS_COLUMN_INVALID;
1146 }
1147 
1148 static u8 rs_get_tid(struct ieee80211_hdr *hdr)
1149 {
1150 	u8 tid = IWL_MAX_TID_COUNT;
1151 
1152 	if (ieee80211_is_data_qos(hdr->frame_control)) {
1153 		u8 *qc = ieee80211_get_qos_ctl(hdr);
1154 		tid = qc[0] & 0xf;
1155 	}
1156 
1157 	if (unlikely(tid > IWL_MAX_TID_COUNT))
1158 		tid = IWL_MAX_TID_COUNT;
1159 
1160 	return tid;
1161 }
1162 
1163 void iwl_mvm_rs_tx_status(struct iwl_mvm *mvm, struct ieee80211_sta *sta,
1164 			  int tid, struct ieee80211_tx_info *info)
1165 {
1166 	int legacy_success;
1167 	int retries;
1168 	int i;
1169 	struct iwl_lq_cmd *table;
1170 	u32 lq_hwrate;
1171 	struct rs_rate lq_rate, tx_resp_rate;
1172 	struct iwl_scale_tbl_info *curr_tbl, *other_tbl, *tmp_tbl;
1173 	u8 reduced_txp = (uintptr_t)info->status.status_driver_data[0];
1174 	u32 tx_resp_hwrate = (uintptr_t)info->status.status_driver_data[1];
1175 	struct iwl_mvm_sta *mvmsta = iwl_mvm_sta_from_mac80211(sta);
1176 	struct iwl_lq_sta *lq_sta = &mvmsta->lq_sta;
1177 	bool allow_ant_mismatch = fw_has_api(&mvm->fw->ucode_capa,
1178 					     IWL_UCODE_TLV_API_LQ_SS_PARAMS);
1179 
1180 	/* Treat uninitialized rate scaling data same as non-existing. */
1181 	if (!lq_sta) {
1182 		IWL_DEBUG_RATE(mvm, "Station rate scaling not created yet.\n");
1183 		return;
1184 	} else if (!lq_sta->pers.drv) {
1185 		IWL_DEBUG_RATE(mvm, "Rate scaling not initialized yet.\n");
1186 		return;
1187 	}
1188 
1189 	/* This packet was aggregated but doesn't carry status info */
1190 	if ((info->flags & IEEE80211_TX_CTL_AMPDU) &&
1191 	    !(info->flags & IEEE80211_TX_STAT_AMPDU))
1192 		return;
1193 
1194 	rs_rate_from_ucode_rate(tx_resp_hwrate, info->band, &tx_resp_rate);
1195 
1196 #ifdef CONFIG_MAC80211_DEBUGFS
1197 	/* Disable last tx check if we are debugging with fixed rate but
1198 	 * update tx stats */
1199 	if (lq_sta->pers.dbg_fixed_rate) {
1200 		int index = tx_resp_rate.index;
1201 		enum rs_column column;
1202 		int attempts, success;
1203 
1204 		column = rs_get_column_from_rate(&tx_resp_rate);
1205 		if (WARN_ONCE(column == RS_COLUMN_INVALID,
1206 			      "Can't map rate 0x%x to column",
1207 			      tx_resp_hwrate))
1208 			return;
1209 
1210 		if (info->flags & IEEE80211_TX_STAT_AMPDU) {
1211 			attempts = info->status.ampdu_len;
1212 			success = info->status.ampdu_ack_len;
1213 		} else {
1214 			attempts = info->status.rates[0].count;
1215 			success = !!(info->flags & IEEE80211_TX_STAT_ACK);
1216 		}
1217 
1218 		lq_sta->pers.tx_stats[column][index].total += attempts;
1219 		lq_sta->pers.tx_stats[column][index].success += success;
1220 
1221 		IWL_DEBUG_RATE(mvm, "Fixed rate 0x%x success %d attempts %d\n",
1222 			       tx_resp_hwrate, success, attempts);
1223 		return;
1224 	}
1225 #endif
1226 
1227 	if (time_after(jiffies,
1228 		       (unsigned long)(lq_sta->last_tx +
1229 				       (IWL_MVM_RS_IDLE_TIMEOUT * HZ)))) {
1230 		int t;
1231 
1232 		IWL_DEBUG_RATE(mvm, "Tx idle for too long. reinit rs\n");
1233 		for (t = 0; t < IWL_MAX_TID_COUNT; t++)
1234 			ieee80211_stop_tx_ba_session(sta, t);
1235 
1236 		iwl_mvm_rs_rate_init(mvm, sta, info->band, false);
1237 		return;
1238 	}
1239 	lq_sta->last_tx = jiffies;
1240 
1241 	/* Ignore this Tx frame response if its initial rate doesn't match
1242 	 * that of latest Link Quality command.  There may be stragglers
1243 	 * from a previous Link Quality command, but we're no longer interested
1244 	 * in those; they're either from the "active" mode while we're trying
1245 	 * to check "search" mode, or a prior "search" mode after we've moved
1246 	 * to a new "search" mode (which might become the new "active" mode).
1247 	 */
1248 	table = &lq_sta->lq;
1249 	lq_hwrate = le32_to_cpu(table->rs_table[0]);
1250 	rs_rate_from_ucode_rate(lq_hwrate, info->band, &lq_rate);
1251 
1252 	/* Here we actually compare this rate to the latest LQ command */
1253 	if (!rs_rate_equal(&tx_resp_rate, &lq_rate, allow_ant_mismatch)) {
1254 		IWL_DEBUG_RATE(mvm,
1255 			       "initial tx resp rate 0x%x does not match 0x%x\n",
1256 			       tx_resp_hwrate, lq_hwrate);
1257 
1258 		/*
1259 		 * Since rates mis-match, the last LQ command may have failed.
1260 		 * After IWL_MISSED_RATE_MAX mis-matches, resync the uCode with
1261 		 * ... driver.
1262 		 */
1263 		lq_sta->missed_rate_counter++;
1264 		if (lq_sta->missed_rate_counter > IWL_MVM_RS_MISSED_RATE_MAX) {
1265 			lq_sta->missed_rate_counter = 0;
1266 			IWL_DEBUG_RATE(mvm,
1267 				       "Too many rates mismatch. Send sync LQ. rs_state %d\n",
1268 				       lq_sta->rs_state);
1269 			iwl_mvm_send_lq_cmd(mvm, &lq_sta->lq, false);
1270 		}
1271 		/* Regardless, ignore this status info for outdated rate */
1272 		return;
1273 	} else
1274 		/* Rate did match, so reset the missed_rate_counter */
1275 		lq_sta->missed_rate_counter = 0;
1276 
1277 	if (!lq_sta->search_better_tbl) {
1278 		curr_tbl = &(lq_sta->lq_info[lq_sta->active_tbl]);
1279 		other_tbl = &(lq_sta->lq_info[1 - lq_sta->active_tbl]);
1280 	} else {
1281 		curr_tbl = &(lq_sta->lq_info[1 - lq_sta->active_tbl]);
1282 		other_tbl = &(lq_sta->lq_info[lq_sta->active_tbl]);
1283 	}
1284 
1285 	if (WARN_ON_ONCE(!rs_rate_column_match(&lq_rate, &curr_tbl->rate))) {
1286 		IWL_DEBUG_RATE(mvm,
1287 			       "Neither active nor search matches tx rate\n");
1288 		tmp_tbl = &(lq_sta->lq_info[lq_sta->active_tbl]);
1289 		rs_dump_rate(mvm, &tmp_tbl->rate, "ACTIVE");
1290 		tmp_tbl = &(lq_sta->lq_info[1 - lq_sta->active_tbl]);
1291 		rs_dump_rate(mvm, &tmp_tbl->rate, "SEARCH");
1292 		rs_dump_rate(mvm, &lq_rate, "ACTUAL");
1293 
1294 		/*
1295 		 * no matching table found, let's by-pass the data collection
1296 		 * and continue to perform rate scale to find the rate table
1297 		 */
1298 		rs_stay_in_table(lq_sta, true);
1299 		goto done;
1300 	}
1301 
1302 	/*
1303 	 * Updating the frame history depends on whether packets were
1304 	 * aggregated.
1305 	 *
1306 	 * For aggregation, all packets were transmitted at the same rate, the
1307 	 * first index into rate scale table.
1308 	 */
1309 	if (info->flags & IEEE80211_TX_STAT_AMPDU) {
1310 		rs_collect_tpc_data(mvm, lq_sta, curr_tbl, lq_rate.index,
1311 				    info->status.ampdu_len,
1312 				    info->status.ampdu_ack_len,
1313 				    reduced_txp);
1314 
1315 		/* ampdu_ack_len = 0 marks no BA was received. For TLC, treat
1316 		 * it as a single frame loss as we don't want the success ratio
1317 		 * to dip too quickly because a BA wasn't received.
1318 		 * For TPC, there's no need for this optimisation since we want
1319 		 * to recover very quickly from a bad power reduction and,
1320 		 * therefore we'd like the success ratio to get an immediate hit
1321 		 * when failing to get a BA, so we'd switch back to a lower or
1322 		 * zero power reduction. When FW transmits agg with a rate
1323 		 * different from the initial rate, it will not use reduced txp
1324 		 * and will send BA notification twice (one empty with reduced
1325 		 * txp equal to the value from LQ and one with reduced txp 0).
1326 		 * We need to update counters for each txp level accordingly.
1327 		 */
1328 		if (info->status.ampdu_ack_len == 0)
1329 			info->status.ampdu_len = 1;
1330 
1331 		rs_collect_tlc_data(mvm, lq_sta, curr_tbl, lq_rate.index,
1332 				    info->status.ampdu_len,
1333 				    info->status.ampdu_ack_len);
1334 
1335 		/* Update success/fail counts if not searching for new mode */
1336 		if (lq_sta->rs_state == RS_STATE_STAY_IN_COLUMN) {
1337 			lq_sta->total_success += info->status.ampdu_ack_len;
1338 			lq_sta->total_failed += (info->status.ampdu_len -
1339 					info->status.ampdu_ack_len);
1340 		}
1341 	} else {
1342 		/* For legacy, update frame history with for each Tx retry. */
1343 		retries = info->status.rates[0].count - 1;
1344 		/* HW doesn't send more than 15 retries */
1345 		retries = min(retries, 15);
1346 
1347 		/* The last transmission may have been successful */
1348 		legacy_success = !!(info->flags & IEEE80211_TX_STAT_ACK);
1349 		/* Collect data for each rate used during failed TX attempts */
1350 		for (i = 0; i <= retries; ++i) {
1351 			lq_hwrate = le32_to_cpu(table->rs_table[i]);
1352 			rs_rate_from_ucode_rate(lq_hwrate, info->band,
1353 						&lq_rate);
1354 			/*
1355 			 * Only collect stats if retried rate is in the same RS
1356 			 * table as active/search.
1357 			 */
1358 			if (rs_rate_column_match(&lq_rate, &curr_tbl->rate))
1359 				tmp_tbl = curr_tbl;
1360 			else if (rs_rate_column_match(&lq_rate,
1361 						      &other_tbl->rate))
1362 				tmp_tbl = other_tbl;
1363 			else
1364 				continue;
1365 
1366 			rs_collect_tpc_data(mvm, lq_sta, tmp_tbl,
1367 					    lq_rate.index, 1,
1368 					    i < retries ? 0 : legacy_success,
1369 					    reduced_txp);
1370 			rs_collect_tlc_data(mvm, lq_sta, tmp_tbl,
1371 					    lq_rate.index, 1,
1372 					    i < retries ? 0 : legacy_success);
1373 		}
1374 
1375 		/* Update success/fail counts if not searching for new mode */
1376 		if (lq_sta->rs_state == RS_STATE_STAY_IN_COLUMN) {
1377 			lq_sta->total_success += legacy_success;
1378 			lq_sta->total_failed += retries + (1 - legacy_success);
1379 		}
1380 	}
1381 	/* The last TX rate is cached in lq_sta; it's set in if/else above */
1382 	lq_sta->last_rate_n_flags = lq_hwrate;
1383 	IWL_DEBUG_RATE(mvm, "reduced txpower: %d\n", reduced_txp);
1384 done:
1385 	/* See if there's a better rate or modulation mode to try. */
1386 	if (sta->supp_rates[info->band])
1387 		rs_rate_scale_perform(mvm, sta, lq_sta, tid);
1388 }
1389 
1390 /*
1391  * mac80211 sends us Tx status
1392  */
1393 static void rs_mac80211_tx_status(void *mvm_r,
1394 				  struct ieee80211_supported_band *sband,
1395 				  struct ieee80211_sta *sta, void *priv_sta,
1396 				  struct sk_buff *skb)
1397 {
1398 	struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
1399 	struct iwl_op_mode *op_mode = (struct iwl_op_mode *)mvm_r;
1400 	struct iwl_mvm *mvm = IWL_OP_MODE_GET_MVM(op_mode);
1401 	struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
1402 
1403 	if (!iwl_mvm_sta_from_mac80211(sta)->vif)
1404 		return;
1405 
1406 	if (!ieee80211_is_data(hdr->frame_control) ||
1407 	    info->flags & IEEE80211_TX_CTL_NO_ACK)
1408 		return;
1409 
1410 	iwl_mvm_rs_tx_status(mvm, sta, rs_get_tid(hdr), info);
1411 }
1412 
1413 /*
1414  * Begin a period of staying with a selected modulation mode.
1415  * Set "stay_in_tbl" flag to prevent any mode switches.
1416  * Set frame tx success limits according to legacy vs. high-throughput,
1417  * and reset overall (spanning all rates) tx success history statistics.
1418  * These control how long we stay using same modulation mode before
1419  * searching for a new mode.
1420  */
1421 static void rs_set_stay_in_table(struct iwl_mvm *mvm, u8 is_legacy,
1422 				 struct iwl_lq_sta *lq_sta)
1423 {
1424 	IWL_DEBUG_RATE(mvm, "Moving to RS_STATE_STAY_IN_COLUMN\n");
1425 	lq_sta->rs_state = RS_STATE_STAY_IN_COLUMN;
1426 	if (is_legacy) {
1427 		lq_sta->table_count_limit = IWL_MVM_RS_LEGACY_TABLE_COUNT;
1428 		lq_sta->max_failure_limit = IWL_MVM_RS_LEGACY_FAILURE_LIMIT;
1429 		lq_sta->max_success_limit = IWL_MVM_RS_LEGACY_SUCCESS_LIMIT;
1430 	} else {
1431 		lq_sta->table_count_limit = IWL_MVM_RS_NON_LEGACY_TABLE_COUNT;
1432 		lq_sta->max_failure_limit = IWL_MVM_RS_NON_LEGACY_FAILURE_LIMIT;
1433 		lq_sta->max_success_limit = IWL_MVM_RS_NON_LEGACY_SUCCESS_LIMIT;
1434 	}
1435 	lq_sta->table_count = 0;
1436 	lq_sta->total_failed = 0;
1437 	lq_sta->total_success = 0;
1438 	lq_sta->flush_timer = jiffies;
1439 	lq_sta->visited_columns = 0;
1440 }
1441 
1442 static inline int rs_get_max_rate_from_mask(unsigned long rate_mask)
1443 {
1444 	if (rate_mask)
1445 		return find_last_bit(&rate_mask, BITS_PER_LONG);
1446 	return IWL_RATE_INVALID;
1447 }
1448 
1449 static int rs_get_max_allowed_rate(struct iwl_lq_sta *lq_sta,
1450 				   const struct rs_tx_column *column)
1451 {
1452 	switch (column->mode) {
1453 	case RS_LEGACY:
1454 		return lq_sta->max_legacy_rate_idx;
1455 	case RS_SISO:
1456 		return lq_sta->max_siso_rate_idx;
1457 	case RS_MIMO2:
1458 		return lq_sta->max_mimo2_rate_idx;
1459 	default:
1460 		WARN_ON_ONCE(1);
1461 	}
1462 
1463 	return lq_sta->max_legacy_rate_idx;
1464 }
1465 
1466 static const u16 *rs_get_expected_tpt_table(struct iwl_lq_sta *lq_sta,
1467 					    const struct rs_tx_column *column,
1468 					    u32 bw)
1469 {
1470 	/* Used to choose among HT tables */
1471 	const u16 (*ht_tbl_pointer)[IWL_RATE_COUNT];
1472 
1473 	if (WARN_ON_ONCE(column->mode != RS_LEGACY &&
1474 			 column->mode != RS_SISO &&
1475 			 column->mode != RS_MIMO2))
1476 		return expected_tpt_legacy;
1477 
1478 	/* Legacy rates have only one table */
1479 	if (column->mode == RS_LEGACY)
1480 		return expected_tpt_legacy;
1481 
1482 	ht_tbl_pointer = expected_tpt_mimo2_20MHz;
1483 	/* Choose among many HT tables depending on number of streams
1484 	 * (SISO/MIMO2), channel width (20/40/80), SGI, and aggregation
1485 	 * status */
1486 	if (column->mode == RS_SISO) {
1487 		switch (bw) {
1488 		case RATE_MCS_CHAN_WIDTH_20:
1489 			ht_tbl_pointer = expected_tpt_siso_20MHz;
1490 			break;
1491 		case RATE_MCS_CHAN_WIDTH_40:
1492 			ht_tbl_pointer = expected_tpt_siso_40MHz;
1493 			break;
1494 		case RATE_MCS_CHAN_WIDTH_80:
1495 			ht_tbl_pointer = expected_tpt_siso_80MHz;
1496 			break;
1497 		default:
1498 			WARN_ON_ONCE(1);
1499 		}
1500 	} else if (column->mode == RS_MIMO2) {
1501 		switch (bw) {
1502 		case RATE_MCS_CHAN_WIDTH_20:
1503 			ht_tbl_pointer = expected_tpt_mimo2_20MHz;
1504 			break;
1505 		case RATE_MCS_CHAN_WIDTH_40:
1506 			ht_tbl_pointer = expected_tpt_mimo2_40MHz;
1507 			break;
1508 		case RATE_MCS_CHAN_WIDTH_80:
1509 			ht_tbl_pointer = expected_tpt_mimo2_80MHz;
1510 			break;
1511 		default:
1512 			WARN_ON_ONCE(1);
1513 		}
1514 	} else {
1515 		WARN_ON_ONCE(1);
1516 	}
1517 
1518 	if (!column->sgi && !lq_sta->is_agg)		/* Normal */
1519 		return ht_tbl_pointer[0];
1520 	else if (column->sgi && !lq_sta->is_agg)        /* SGI */
1521 		return ht_tbl_pointer[1];
1522 	else if (!column->sgi && lq_sta->is_agg)        /* AGG */
1523 		return ht_tbl_pointer[2];
1524 	else						/* AGG+SGI */
1525 		return ht_tbl_pointer[3];
1526 }
1527 
1528 static void rs_set_expected_tpt_table(struct iwl_lq_sta *lq_sta,
1529 				      struct iwl_scale_tbl_info *tbl)
1530 {
1531 	struct rs_rate *rate = &tbl->rate;
1532 	const struct rs_tx_column *column = &rs_tx_columns[tbl->column];
1533 
1534 	tbl->expected_tpt = rs_get_expected_tpt_table(lq_sta, column, rate->bw);
1535 }
1536 
1537 static s32 rs_get_best_rate(struct iwl_mvm *mvm,
1538 			    struct iwl_lq_sta *lq_sta,
1539 			    struct iwl_scale_tbl_info *tbl,	/* "search" */
1540 			    unsigned long rate_mask, s8 index)
1541 {
1542 	struct iwl_scale_tbl_info *active_tbl =
1543 	    &(lq_sta->lq_info[lq_sta->active_tbl]);
1544 	s32 success_ratio = active_tbl->win[index].success_ratio;
1545 	u16 expected_current_tpt = active_tbl->expected_tpt[index];
1546 	const u16 *tpt_tbl = tbl->expected_tpt;
1547 	u16 high_low;
1548 	u32 target_tpt;
1549 	int rate_idx;
1550 
1551 	if (success_ratio >= RS_PERCENT(IWL_MVM_RS_SR_NO_DECREASE)) {
1552 		target_tpt = 100 * expected_current_tpt;
1553 		IWL_DEBUG_RATE(mvm,
1554 			       "SR %d high. Find rate exceeding EXPECTED_CURRENT %d\n",
1555 			       success_ratio, target_tpt);
1556 	} else {
1557 		target_tpt = lq_sta->last_tpt;
1558 		IWL_DEBUG_RATE(mvm,
1559 			       "SR %d not that good. Find rate exceeding ACTUAL_TPT %d\n",
1560 			       success_ratio, target_tpt);
1561 	}
1562 
1563 	rate_idx = find_first_bit(&rate_mask, BITS_PER_LONG);
1564 
1565 	while (rate_idx != IWL_RATE_INVALID) {
1566 		if (target_tpt < (100 * tpt_tbl[rate_idx]))
1567 			break;
1568 
1569 		high_low = rs_get_adjacent_rate(mvm, rate_idx, rate_mask,
1570 						tbl->rate.type);
1571 
1572 		rate_idx = (high_low >> 8) & 0xff;
1573 	}
1574 
1575 	IWL_DEBUG_RATE(mvm, "Best rate found %d target_tp %d expected_new %d\n",
1576 		       rate_idx, target_tpt,
1577 		       rate_idx != IWL_RATE_INVALID ?
1578 		       100 * tpt_tbl[rate_idx] : IWL_INVALID_VALUE);
1579 
1580 	return rate_idx;
1581 }
1582 
1583 static u32 rs_bw_from_sta_bw(struct ieee80211_sta *sta)
1584 {
1585 	if (sta->bandwidth >= IEEE80211_STA_RX_BW_80)
1586 		return RATE_MCS_CHAN_WIDTH_80;
1587 	else if (sta->bandwidth >= IEEE80211_STA_RX_BW_40)
1588 		return RATE_MCS_CHAN_WIDTH_40;
1589 
1590 	return RATE_MCS_CHAN_WIDTH_20;
1591 }
1592 
1593 /*
1594  * Check whether we should continue using same modulation mode, or
1595  * begin search for a new mode, based on:
1596  * 1) # tx successes or failures while using this mode
1597  * 2) # times calling this function
1598  * 3) elapsed time in this mode (not used, for now)
1599  */
1600 static void rs_stay_in_table(struct iwl_lq_sta *lq_sta, bool force_search)
1601 {
1602 	struct iwl_scale_tbl_info *tbl;
1603 	int active_tbl;
1604 	int flush_interval_passed = 0;
1605 	struct iwl_mvm *mvm;
1606 
1607 	mvm = lq_sta->pers.drv;
1608 	active_tbl = lq_sta->active_tbl;
1609 
1610 	tbl = &(lq_sta->lq_info[active_tbl]);
1611 
1612 	/* If we've been disallowing search, see if we should now allow it */
1613 	if (lq_sta->rs_state == RS_STATE_STAY_IN_COLUMN) {
1614 		/* Elapsed time using current modulation mode */
1615 		if (lq_sta->flush_timer)
1616 			flush_interval_passed =
1617 				time_after(jiffies,
1618 					   (unsigned long)(lq_sta->flush_timer +
1619 							   (IWL_MVM_RS_STAY_IN_COLUMN_TIMEOUT * HZ)));
1620 
1621 		/*
1622 		 * Check if we should allow search for new modulation mode.
1623 		 * If many frames have failed or succeeded, or we've used
1624 		 * this same modulation for a long time, allow search, and
1625 		 * reset history stats that keep track of whether we should
1626 		 * allow a new search.  Also (below) reset all bitmaps and
1627 		 * stats in active history.
1628 		 */
1629 		if (force_search ||
1630 		    (lq_sta->total_failed > lq_sta->max_failure_limit) ||
1631 		    (lq_sta->total_success > lq_sta->max_success_limit) ||
1632 		    ((!lq_sta->search_better_tbl) &&
1633 		     (lq_sta->flush_timer) && (flush_interval_passed))) {
1634 			IWL_DEBUG_RATE(mvm,
1635 				       "LQ: stay is expired %d %d %d\n",
1636 				     lq_sta->total_failed,
1637 				     lq_sta->total_success,
1638 				     flush_interval_passed);
1639 
1640 			/* Allow search for new mode */
1641 			lq_sta->rs_state = RS_STATE_SEARCH_CYCLE_STARTED;
1642 			IWL_DEBUG_RATE(mvm,
1643 				       "Moving to RS_STATE_SEARCH_CYCLE_STARTED\n");
1644 			lq_sta->total_failed = 0;
1645 			lq_sta->total_success = 0;
1646 			lq_sta->flush_timer = 0;
1647 			/* mark the current column as visited */
1648 			lq_sta->visited_columns = BIT(tbl->column);
1649 		/*
1650 		 * Else if we've used this modulation mode enough repetitions
1651 		 * (regardless of elapsed time or success/failure), reset
1652 		 * history bitmaps and rate-specific stats for all rates in
1653 		 * active table.
1654 		 */
1655 		} else {
1656 			lq_sta->table_count++;
1657 			if (lq_sta->table_count >=
1658 			    lq_sta->table_count_limit) {
1659 				lq_sta->table_count = 0;
1660 
1661 				IWL_DEBUG_RATE(mvm,
1662 					       "LQ: stay in table clear win\n");
1663 				rs_rate_scale_clear_tbl_windows(mvm, tbl);
1664 			}
1665 		}
1666 
1667 		/* If transitioning to allow "search", reset all history
1668 		 * bitmaps and stats in active table (this will become the new
1669 		 * "search" table). */
1670 		if (lq_sta->rs_state == RS_STATE_SEARCH_CYCLE_STARTED) {
1671 			rs_rate_scale_clear_tbl_windows(mvm, tbl);
1672 		}
1673 	}
1674 }
1675 
1676 static void rs_set_amsdu_len(struct iwl_mvm *mvm, struct ieee80211_sta *sta,
1677 			     struct iwl_scale_tbl_info *tbl,
1678 			     enum rs_action scale_action)
1679 {
1680 	struct iwl_mvm_sta *sta_priv = iwl_mvm_sta_from_mac80211(sta);
1681 
1682 	if ((!is_vht(&tbl->rate) && !is_ht(&tbl->rate)) ||
1683 	    tbl->rate.index < IWL_RATE_MCS_5_INDEX ||
1684 	    scale_action == RS_ACTION_DOWNSCALE)
1685 		sta_priv->tlc_amsdu = false;
1686 	else
1687 		sta_priv->tlc_amsdu = true;
1688 }
1689 
1690 /*
1691  * setup rate table in uCode
1692  */
1693 static void rs_update_rate_tbl(struct iwl_mvm *mvm,
1694 			       struct ieee80211_sta *sta,
1695 			       struct iwl_lq_sta *lq_sta,
1696 			       struct iwl_scale_tbl_info *tbl)
1697 {
1698 	rs_fill_lq_cmd(mvm, sta, lq_sta, &tbl->rate);
1699 	iwl_mvm_send_lq_cmd(mvm, &lq_sta->lq, false);
1700 }
1701 
1702 static bool rs_tweak_rate_tbl(struct iwl_mvm *mvm,
1703 			      struct ieee80211_sta *sta,
1704 			      struct iwl_lq_sta *lq_sta,
1705 			      struct iwl_scale_tbl_info *tbl,
1706 			      enum rs_action scale_action)
1707 {
1708 	if (sta->bandwidth != IEEE80211_STA_RX_BW_80)
1709 		return false;
1710 
1711 	if (!is_vht_siso(&tbl->rate))
1712 		return false;
1713 
1714 	if ((tbl->rate.bw == RATE_MCS_CHAN_WIDTH_80) &&
1715 	    (tbl->rate.index == IWL_RATE_MCS_0_INDEX) &&
1716 	    (scale_action == RS_ACTION_DOWNSCALE)) {
1717 		tbl->rate.bw = RATE_MCS_CHAN_WIDTH_20;
1718 		tbl->rate.index = IWL_RATE_MCS_4_INDEX;
1719 		IWL_DEBUG_RATE(mvm, "Switch 80Mhz SISO MCS0 -> 20Mhz MCS4\n");
1720 		goto tweaked;
1721 	}
1722 
1723 	/* Go back to 80Mhz MCS1 only if we've established that 20Mhz MCS5 is
1724 	 * sustainable, i.e. we're past the test window. We can't go back
1725 	 * if MCS5 is just tested as this will happen always after switching
1726 	 * to 20Mhz MCS4 because the rate stats are cleared.
1727 	 */
1728 	if ((tbl->rate.bw == RATE_MCS_CHAN_WIDTH_20) &&
1729 	    (((tbl->rate.index == IWL_RATE_MCS_5_INDEX) &&
1730 	     (scale_action == RS_ACTION_STAY)) ||
1731 	     ((tbl->rate.index > IWL_RATE_MCS_5_INDEX) &&
1732 	      (scale_action == RS_ACTION_UPSCALE)))) {
1733 		tbl->rate.bw = RATE_MCS_CHAN_WIDTH_80;
1734 		tbl->rate.index = IWL_RATE_MCS_1_INDEX;
1735 		IWL_DEBUG_RATE(mvm, "Switch 20Mhz SISO MCS5 -> 80Mhz MCS1\n");
1736 		goto tweaked;
1737 	}
1738 
1739 	return false;
1740 
1741 tweaked:
1742 	rs_set_expected_tpt_table(lq_sta, tbl);
1743 	rs_rate_scale_clear_tbl_windows(mvm, tbl);
1744 	return true;
1745 }
1746 
1747 static enum rs_column rs_get_next_column(struct iwl_mvm *mvm,
1748 					 struct iwl_lq_sta *lq_sta,
1749 					 struct ieee80211_sta *sta,
1750 					 struct iwl_scale_tbl_info *tbl)
1751 {
1752 	int i, j, max_rate;
1753 	enum rs_column next_col_id;
1754 	const struct rs_tx_column *curr_col = &rs_tx_columns[tbl->column];
1755 	const struct rs_tx_column *next_col;
1756 	allow_column_func_t allow_func;
1757 	u8 valid_ants = iwl_mvm_get_valid_tx_ant(mvm);
1758 	const u16 *expected_tpt_tbl;
1759 	u16 tpt, max_expected_tpt;
1760 
1761 	for (i = 0; i < MAX_NEXT_COLUMNS; i++) {
1762 		next_col_id = curr_col->next_columns[i];
1763 
1764 		if (next_col_id == RS_COLUMN_INVALID)
1765 			continue;
1766 
1767 		if (lq_sta->visited_columns & BIT(next_col_id)) {
1768 			IWL_DEBUG_RATE(mvm, "Skip already visited column %d\n",
1769 				       next_col_id);
1770 			continue;
1771 		}
1772 
1773 		next_col = &rs_tx_columns[next_col_id];
1774 
1775 		if (!rs_is_valid_ant(valid_ants, next_col->ant)) {
1776 			IWL_DEBUG_RATE(mvm,
1777 				       "Skip column %d as ANT config isn't supported by chip. valid_ants 0x%x column ant 0x%x\n",
1778 				       next_col_id, valid_ants, next_col->ant);
1779 			continue;
1780 		}
1781 
1782 		for (j = 0; j < MAX_COLUMN_CHECKS; j++) {
1783 			allow_func = next_col->checks[j];
1784 			if (allow_func && !allow_func(mvm, sta, &tbl->rate,
1785 						      next_col))
1786 				break;
1787 		}
1788 
1789 		if (j != MAX_COLUMN_CHECKS) {
1790 			IWL_DEBUG_RATE(mvm,
1791 				       "Skip column %d: not allowed (check %d failed)\n",
1792 				       next_col_id, j);
1793 
1794 			continue;
1795 		}
1796 
1797 		tpt = lq_sta->last_tpt / 100;
1798 		expected_tpt_tbl = rs_get_expected_tpt_table(lq_sta, next_col,
1799 						     rs_bw_from_sta_bw(sta));
1800 		if (WARN_ON_ONCE(!expected_tpt_tbl))
1801 			continue;
1802 
1803 		max_rate = rs_get_max_allowed_rate(lq_sta, next_col);
1804 		if (max_rate == IWL_RATE_INVALID) {
1805 			IWL_DEBUG_RATE(mvm,
1806 				       "Skip column %d: no rate is allowed in this column\n",
1807 				       next_col_id);
1808 			continue;
1809 		}
1810 
1811 		max_expected_tpt = expected_tpt_tbl[max_rate];
1812 		if (tpt >= max_expected_tpt) {
1813 			IWL_DEBUG_RATE(mvm,
1814 				       "Skip column %d: can't beat current TPT. Max expected %d current %d\n",
1815 				       next_col_id, max_expected_tpt, tpt);
1816 			continue;
1817 		}
1818 
1819 		IWL_DEBUG_RATE(mvm,
1820 			       "Found potential column %d. Max expected %d current %d\n",
1821 			       next_col_id, max_expected_tpt, tpt);
1822 		break;
1823 	}
1824 
1825 	if (i == MAX_NEXT_COLUMNS)
1826 		return RS_COLUMN_INVALID;
1827 
1828 	return next_col_id;
1829 }
1830 
1831 static int rs_switch_to_column(struct iwl_mvm *mvm,
1832 			       struct iwl_lq_sta *lq_sta,
1833 			       struct ieee80211_sta *sta,
1834 			       enum rs_column col_id)
1835 {
1836 	struct iwl_scale_tbl_info *tbl = &(lq_sta->lq_info[lq_sta->active_tbl]);
1837 	struct iwl_scale_tbl_info *search_tbl =
1838 				&(lq_sta->lq_info[(1 - lq_sta->active_tbl)]);
1839 	struct rs_rate *rate = &search_tbl->rate;
1840 	const struct rs_tx_column *column = &rs_tx_columns[col_id];
1841 	const struct rs_tx_column *curr_column = &rs_tx_columns[tbl->column];
1842 	u32 sz = (sizeof(struct iwl_scale_tbl_info) -
1843 		  (sizeof(struct iwl_rate_scale_data) * IWL_RATE_COUNT));
1844 	unsigned long rate_mask = 0;
1845 	u32 rate_idx = 0;
1846 
1847 	memcpy(search_tbl, tbl, sz);
1848 
1849 	rate->sgi = column->sgi;
1850 	rate->ant = column->ant;
1851 
1852 	if (column->mode == RS_LEGACY) {
1853 		if (lq_sta->band == NL80211_BAND_5GHZ)
1854 			rate->type = LQ_LEGACY_A;
1855 		else
1856 			rate->type = LQ_LEGACY_G;
1857 
1858 		rate->bw = RATE_MCS_CHAN_WIDTH_20;
1859 		rate->ldpc = false;
1860 		rate_mask = lq_sta->active_legacy_rate;
1861 	} else if (column->mode == RS_SISO) {
1862 		rate->type = lq_sta->is_vht ? LQ_VHT_SISO : LQ_HT_SISO;
1863 		rate_mask = lq_sta->active_siso_rate;
1864 	} else if (column->mode == RS_MIMO2) {
1865 		rate->type = lq_sta->is_vht ? LQ_VHT_MIMO2 : LQ_HT_MIMO2;
1866 		rate_mask = lq_sta->active_mimo2_rate;
1867 	} else {
1868 		WARN_ONCE(1, "Bad column mode");
1869 	}
1870 
1871 	if (column->mode != RS_LEGACY) {
1872 		rate->bw = rs_bw_from_sta_bw(sta);
1873 		rate->ldpc = lq_sta->ldpc;
1874 	}
1875 
1876 	search_tbl->column = col_id;
1877 	rs_set_expected_tpt_table(lq_sta, search_tbl);
1878 
1879 	lq_sta->visited_columns |= BIT(col_id);
1880 
1881 	/* Get the best matching rate if we're changing modes. e.g.
1882 	 * SISO->MIMO, LEGACY->SISO, MIMO->SISO
1883 	 */
1884 	if (curr_column->mode != column->mode) {
1885 		rate_idx = rs_get_best_rate(mvm, lq_sta, search_tbl,
1886 					    rate_mask, rate->index);
1887 
1888 		if ((rate_idx == IWL_RATE_INVALID) ||
1889 		    !(BIT(rate_idx) & rate_mask)) {
1890 			IWL_DEBUG_RATE(mvm,
1891 				       "can not switch with index %d"
1892 				       " rate mask %lx\n",
1893 				       rate_idx, rate_mask);
1894 
1895 			goto err;
1896 		}
1897 
1898 		rate->index = rate_idx;
1899 	}
1900 
1901 	IWL_DEBUG_RATE(mvm, "Switched to column %d: Index %d\n",
1902 		       col_id, rate->index);
1903 
1904 	return 0;
1905 
1906 err:
1907 	rate->type = LQ_NONE;
1908 	return -1;
1909 }
1910 
1911 static enum rs_action rs_get_rate_action(struct iwl_mvm *mvm,
1912 					 struct iwl_scale_tbl_info *tbl,
1913 					 s32 sr, int low, int high,
1914 					 int current_tpt,
1915 					 int low_tpt, int high_tpt)
1916 {
1917 	enum rs_action action = RS_ACTION_STAY;
1918 
1919 	if ((sr <= RS_PERCENT(IWL_MVM_RS_SR_FORCE_DECREASE)) ||
1920 	    (current_tpt == 0)) {
1921 		IWL_DEBUG_RATE(mvm,
1922 			       "Decrease rate because of low SR\n");
1923 		return RS_ACTION_DOWNSCALE;
1924 	}
1925 
1926 	if ((low_tpt == IWL_INVALID_VALUE) &&
1927 	    (high_tpt == IWL_INVALID_VALUE) &&
1928 	    (high != IWL_RATE_INVALID)) {
1929 		IWL_DEBUG_RATE(mvm,
1930 			       "No data about high/low rates. Increase rate\n");
1931 		return RS_ACTION_UPSCALE;
1932 	}
1933 
1934 	if ((high_tpt == IWL_INVALID_VALUE) &&
1935 	    (high != IWL_RATE_INVALID) &&
1936 	    (low_tpt != IWL_INVALID_VALUE) &&
1937 	    (low_tpt < current_tpt)) {
1938 		IWL_DEBUG_RATE(mvm,
1939 			       "No data about high rate and low rate is worse. Increase rate\n");
1940 		return RS_ACTION_UPSCALE;
1941 	}
1942 
1943 	if ((high_tpt != IWL_INVALID_VALUE) &&
1944 	    (high_tpt > current_tpt)) {
1945 		IWL_DEBUG_RATE(mvm,
1946 			       "Higher rate is better. Increate rate\n");
1947 		return RS_ACTION_UPSCALE;
1948 	}
1949 
1950 	if ((low_tpt != IWL_INVALID_VALUE) &&
1951 	    (high_tpt != IWL_INVALID_VALUE) &&
1952 	    (low_tpt < current_tpt) &&
1953 	    (high_tpt < current_tpt)) {
1954 		IWL_DEBUG_RATE(mvm,
1955 			       "Both high and low are worse. Maintain rate\n");
1956 		return RS_ACTION_STAY;
1957 	}
1958 
1959 	if ((low_tpt != IWL_INVALID_VALUE) &&
1960 	    (low_tpt > current_tpt)) {
1961 		IWL_DEBUG_RATE(mvm,
1962 			       "Lower rate is better\n");
1963 		action = RS_ACTION_DOWNSCALE;
1964 		goto out;
1965 	}
1966 
1967 	if ((low_tpt == IWL_INVALID_VALUE) &&
1968 	    (low != IWL_RATE_INVALID)) {
1969 		IWL_DEBUG_RATE(mvm,
1970 			       "No data about lower rate\n");
1971 		action = RS_ACTION_DOWNSCALE;
1972 		goto out;
1973 	}
1974 
1975 	IWL_DEBUG_RATE(mvm, "Maintain rate\n");
1976 
1977 out:
1978 	if ((action == RS_ACTION_DOWNSCALE) && (low != IWL_RATE_INVALID)) {
1979 		if (sr >= RS_PERCENT(IWL_MVM_RS_SR_NO_DECREASE)) {
1980 			IWL_DEBUG_RATE(mvm,
1981 				       "SR is above NO DECREASE. Avoid downscale\n");
1982 			action = RS_ACTION_STAY;
1983 		} else if (current_tpt > (100 * tbl->expected_tpt[low])) {
1984 			IWL_DEBUG_RATE(mvm,
1985 				       "Current TPT is higher than max expected in low rate. Avoid downscale\n");
1986 			action = RS_ACTION_STAY;
1987 		} else {
1988 			IWL_DEBUG_RATE(mvm, "Decrease rate\n");
1989 		}
1990 	}
1991 
1992 	return action;
1993 }
1994 
1995 static bool rs_stbc_allow(struct iwl_mvm *mvm, struct ieee80211_sta *sta,
1996 			  struct iwl_lq_sta *lq_sta)
1997 {
1998 	/* Our chip supports Tx STBC and the peer is an HT/VHT STA which
1999 	 * supports STBC of at least 1*SS
2000 	 */
2001 	if (!lq_sta->stbc_capable)
2002 		return false;
2003 
2004 	if (!iwl_mvm_bt_coex_is_mimo_allowed(mvm, sta))
2005 		return false;
2006 
2007 	return true;
2008 }
2009 
2010 static void rs_get_adjacent_txp(struct iwl_mvm *mvm, int index,
2011 				int *weaker, int *stronger)
2012 {
2013 	*weaker = index + IWL_MVM_RS_TPC_TX_POWER_STEP;
2014 	if (*weaker > TPC_MAX_REDUCTION)
2015 		*weaker = TPC_INVALID;
2016 
2017 	*stronger = index - IWL_MVM_RS_TPC_TX_POWER_STEP;
2018 	if (*stronger < 0)
2019 		*stronger = TPC_INVALID;
2020 }
2021 
2022 static bool rs_tpc_allowed(struct iwl_mvm *mvm, struct ieee80211_vif *vif,
2023 			   struct rs_rate *rate, enum nl80211_band band)
2024 {
2025 	int index = rate->index;
2026 	bool cam = (iwlmvm_mod_params.power_scheme == IWL_POWER_SCHEME_CAM);
2027 	bool sta_ps_disabled = (vif->type == NL80211_IFTYPE_STATION &&
2028 				!vif->bss_conf.ps);
2029 
2030 	IWL_DEBUG_RATE(mvm, "cam: %d sta_ps_disabled %d\n",
2031 		       cam, sta_ps_disabled);
2032 	/*
2033 	 * allow tpc only if power management is enabled, or bt coex
2034 	 * activity grade allows it and we are on 2.4Ghz.
2035 	 */
2036 	if ((cam || sta_ps_disabled) &&
2037 	    !iwl_mvm_bt_coex_is_tpc_allowed(mvm, band))
2038 		return false;
2039 
2040 	IWL_DEBUG_RATE(mvm, "check rate, table type: %d\n", rate->type);
2041 	if (is_legacy(rate))
2042 		return index == IWL_RATE_54M_INDEX;
2043 	if (is_ht(rate))
2044 		return index == IWL_RATE_MCS_7_INDEX;
2045 	if (is_vht(rate))
2046 		return index == IWL_RATE_MCS_7_INDEX ||
2047 		       index == IWL_RATE_MCS_8_INDEX ||
2048 		       index == IWL_RATE_MCS_9_INDEX;
2049 
2050 	WARN_ON_ONCE(1);
2051 	return false;
2052 }
2053 
2054 enum tpc_action {
2055 	TPC_ACTION_STAY,
2056 	TPC_ACTION_DECREASE,
2057 	TPC_ACTION_INCREASE,
2058 	TPC_ACTION_NO_RESTIRCTION,
2059 };
2060 
2061 static enum tpc_action rs_get_tpc_action(struct iwl_mvm *mvm,
2062 					 s32 sr, int weak, int strong,
2063 					 int current_tpt,
2064 					 int weak_tpt, int strong_tpt)
2065 {
2066 	/* stay until we have valid tpt */
2067 	if (current_tpt == IWL_INVALID_VALUE) {
2068 		IWL_DEBUG_RATE(mvm, "no current tpt. stay.\n");
2069 		return TPC_ACTION_STAY;
2070 	}
2071 
2072 	/* Too many failures, increase txp */
2073 	if (sr <= RS_PERCENT(IWL_MVM_RS_TPC_SR_FORCE_INCREASE) ||
2074 	    current_tpt == 0) {
2075 		IWL_DEBUG_RATE(mvm, "increase txp because of weak SR\n");
2076 		return TPC_ACTION_NO_RESTIRCTION;
2077 	}
2078 
2079 	/* try decreasing first if applicable */
2080 	if (sr >= RS_PERCENT(IWL_MVM_RS_TPC_SR_NO_INCREASE) &&
2081 	    weak != TPC_INVALID) {
2082 		if (weak_tpt == IWL_INVALID_VALUE &&
2083 		    (strong_tpt == IWL_INVALID_VALUE ||
2084 		     current_tpt >= strong_tpt)) {
2085 			IWL_DEBUG_RATE(mvm,
2086 				       "no weak txp measurement. decrease txp\n");
2087 			return TPC_ACTION_DECREASE;
2088 		}
2089 
2090 		if (weak_tpt > current_tpt) {
2091 			IWL_DEBUG_RATE(mvm,
2092 				       "lower txp has better tpt. decrease txp\n");
2093 			return TPC_ACTION_DECREASE;
2094 		}
2095 	}
2096 
2097 	/* next, increase if needed */
2098 	if (sr < RS_PERCENT(IWL_MVM_RS_TPC_SR_NO_INCREASE) &&
2099 	    strong != TPC_INVALID) {
2100 		if (weak_tpt == IWL_INVALID_VALUE &&
2101 		    strong_tpt != IWL_INVALID_VALUE &&
2102 		    current_tpt < strong_tpt) {
2103 			IWL_DEBUG_RATE(mvm,
2104 				       "higher txp has better tpt. increase txp\n");
2105 			return TPC_ACTION_INCREASE;
2106 		}
2107 
2108 		if (weak_tpt < current_tpt &&
2109 		    (strong_tpt == IWL_INVALID_VALUE ||
2110 		     strong_tpt > current_tpt)) {
2111 			IWL_DEBUG_RATE(mvm,
2112 				       "lower txp has worse tpt. increase txp\n");
2113 			return TPC_ACTION_INCREASE;
2114 		}
2115 	}
2116 
2117 	IWL_DEBUG_RATE(mvm, "no need to increase or decrease txp - stay\n");
2118 	return TPC_ACTION_STAY;
2119 }
2120 
2121 static bool rs_tpc_perform(struct iwl_mvm *mvm,
2122 			   struct ieee80211_sta *sta,
2123 			   struct iwl_lq_sta *lq_sta,
2124 			   struct iwl_scale_tbl_info *tbl)
2125 {
2126 	struct iwl_mvm_sta *mvm_sta = iwl_mvm_sta_from_mac80211(sta);
2127 	struct ieee80211_vif *vif = mvm_sta->vif;
2128 	struct ieee80211_chanctx_conf *chanctx_conf;
2129 	enum nl80211_band band;
2130 	struct iwl_rate_scale_data *window;
2131 	struct rs_rate *rate = &tbl->rate;
2132 	enum tpc_action action;
2133 	s32 sr;
2134 	u8 cur = lq_sta->lq.reduced_tpc;
2135 	int current_tpt;
2136 	int weak, strong;
2137 	int weak_tpt = IWL_INVALID_VALUE, strong_tpt = IWL_INVALID_VALUE;
2138 
2139 #ifdef CONFIG_MAC80211_DEBUGFS
2140 	if (lq_sta->pers.dbg_fixed_txp_reduction <= TPC_MAX_REDUCTION) {
2141 		IWL_DEBUG_RATE(mvm, "fixed tpc: %d\n",
2142 			       lq_sta->pers.dbg_fixed_txp_reduction);
2143 		lq_sta->lq.reduced_tpc = lq_sta->pers.dbg_fixed_txp_reduction;
2144 		return cur != lq_sta->pers.dbg_fixed_txp_reduction;
2145 	}
2146 #endif
2147 
2148 	rcu_read_lock();
2149 	chanctx_conf = rcu_dereference(vif->chanctx_conf);
2150 	if (WARN_ON(!chanctx_conf))
2151 		band = NUM_NL80211_BANDS;
2152 	else
2153 		band = chanctx_conf->def.chan->band;
2154 	rcu_read_unlock();
2155 
2156 	if (!rs_tpc_allowed(mvm, vif, rate, band)) {
2157 		IWL_DEBUG_RATE(mvm,
2158 			       "tpc is not allowed. remove txp restrictions\n");
2159 		lq_sta->lq.reduced_tpc = TPC_NO_REDUCTION;
2160 		return cur != TPC_NO_REDUCTION;
2161 	}
2162 
2163 	rs_get_adjacent_txp(mvm, cur, &weak, &strong);
2164 
2165 	/* Collect measured throughputs for current and adjacent rates */
2166 	window = tbl->tpc_win;
2167 	sr = window[cur].success_ratio;
2168 	current_tpt = window[cur].average_tpt;
2169 	if (weak != TPC_INVALID)
2170 		weak_tpt = window[weak].average_tpt;
2171 	if (strong != TPC_INVALID)
2172 		strong_tpt = window[strong].average_tpt;
2173 
2174 	IWL_DEBUG_RATE(mvm,
2175 		       "(TPC: %d): cur_tpt %d SR %d weak %d strong %d weak_tpt %d strong_tpt %d\n",
2176 		       cur, current_tpt, sr, weak, strong,
2177 		       weak_tpt, strong_tpt);
2178 
2179 	action = rs_get_tpc_action(mvm, sr, weak, strong,
2180 				   current_tpt, weak_tpt, strong_tpt);
2181 
2182 	/* override actions if we are on the edge */
2183 	if (weak == TPC_INVALID && action == TPC_ACTION_DECREASE) {
2184 		IWL_DEBUG_RATE(mvm, "already in lowest txp, stay\n");
2185 		action = TPC_ACTION_STAY;
2186 	} else if (strong == TPC_INVALID &&
2187 		   (action == TPC_ACTION_INCREASE ||
2188 		    action == TPC_ACTION_NO_RESTIRCTION)) {
2189 		IWL_DEBUG_RATE(mvm, "already in highest txp, stay\n");
2190 		action = TPC_ACTION_STAY;
2191 	}
2192 
2193 	switch (action) {
2194 	case TPC_ACTION_DECREASE:
2195 		lq_sta->lq.reduced_tpc = weak;
2196 		return true;
2197 	case TPC_ACTION_INCREASE:
2198 		lq_sta->lq.reduced_tpc = strong;
2199 		return true;
2200 	case TPC_ACTION_NO_RESTIRCTION:
2201 		lq_sta->lq.reduced_tpc = TPC_NO_REDUCTION;
2202 		return true;
2203 	case TPC_ACTION_STAY:
2204 		/* do nothing */
2205 		break;
2206 	}
2207 	return false;
2208 }
2209 
2210 /*
2211  * Do rate scaling and search for new modulation mode.
2212  */
2213 static void rs_rate_scale_perform(struct iwl_mvm *mvm,
2214 				  struct ieee80211_sta *sta,
2215 				  struct iwl_lq_sta *lq_sta,
2216 				  int tid)
2217 {
2218 	int low = IWL_RATE_INVALID;
2219 	int high = IWL_RATE_INVALID;
2220 	int index;
2221 	struct iwl_rate_scale_data *window = NULL;
2222 	int current_tpt = IWL_INVALID_VALUE;
2223 	int low_tpt = IWL_INVALID_VALUE;
2224 	int high_tpt = IWL_INVALID_VALUE;
2225 	u32 fail_count;
2226 	enum rs_action scale_action = RS_ACTION_STAY;
2227 	u16 rate_mask;
2228 	u8 update_lq = 0;
2229 	struct iwl_scale_tbl_info *tbl, *tbl1;
2230 	u8 active_tbl = 0;
2231 	u8 done_search = 0;
2232 	u16 high_low;
2233 	s32 sr;
2234 	u8 prev_agg = lq_sta->is_agg;
2235 	struct iwl_mvm_sta *sta_priv = iwl_mvm_sta_from_mac80211(sta);
2236 	struct iwl_mvm_tid_data *tid_data;
2237 	struct rs_rate *rate;
2238 
2239 	lq_sta->is_agg = !!sta_priv->agg_tids;
2240 
2241 	/*
2242 	 * Select rate-scale / modulation-mode table to work with in
2243 	 * the rest of this function:  "search" if searching for better
2244 	 * modulation mode, or "active" if doing rate scaling within a mode.
2245 	 */
2246 	if (!lq_sta->search_better_tbl)
2247 		active_tbl = lq_sta->active_tbl;
2248 	else
2249 		active_tbl = 1 - lq_sta->active_tbl;
2250 
2251 	tbl = &(lq_sta->lq_info[active_tbl]);
2252 	rate = &tbl->rate;
2253 
2254 	if (prev_agg != lq_sta->is_agg) {
2255 		IWL_DEBUG_RATE(mvm,
2256 			       "Aggregation changed: prev %d current %d. Update expected TPT table\n",
2257 			       prev_agg, lq_sta->is_agg);
2258 		rs_set_expected_tpt_table(lq_sta, tbl);
2259 		rs_rate_scale_clear_tbl_windows(mvm, tbl);
2260 	}
2261 
2262 	/* current tx rate */
2263 	index = rate->index;
2264 
2265 	/* rates available for this association, and for modulation mode */
2266 	rate_mask = rs_get_supported_rates(lq_sta, rate);
2267 
2268 	if (!(BIT(index) & rate_mask)) {
2269 		IWL_ERR(mvm, "Current Rate is not valid\n");
2270 		if (lq_sta->search_better_tbl) {
2271 			/* revert to active table if search table is not valid*/
2272 			rate->type = LQ_NONE;
2273 			lq_sta->search_better_tbl = 0;
2274 			tbl = &(lq_sta->lq_info[lq_sta->active_tbl]);
2275 			rs_update_rate_tbl(mvm, sta, lq_sta, tbl);
2276 		}
2277 		return;
2278 	}
2279 
2280 	/* Get expected throughput table and history window for current rate */
2281 	if (!tbl->expected_tpt) {
2282 		IWL_ERR(mvm, "tbl->expected_tpt is NULL\n");
2283 		return;
2284 	}
2285 
2286 	/* TODO: handle rate_idx_mask and rate_idx_mcs_mask */
2287 	window = &(tbl->win[index]);
2288 
2289 	/*
2290 	 * If there is not enough history to calculate actual average
2291 	 * throughput, keep analyzing results of more tx frames, without
2292 	 * changing rate or mode (bypass most of the rest of this function).
2293 	 * Set up new rate table in uCode only if old rate is not supported
2294 	 * in current association (use new rate found above).
2295 	 */
2296 	fail_count = window->counter - window->success_counter;
2297 	if ((fail_count < IWL_MVM_RS_RATE_MIN_FAILURE_TH) &&
2298 	    (window->success_counter < IWL_MVM_RS_RATE_MIN_SUCCESS_TH)) {
2299 		IWL_DEBUG_RATE(mvm,
2300 			       "%s: Test Window: succ %d total %d\n",
2301 			       rs_pretty_rate(rate),
2302 			       window->success_counter, window->counter);
2303 
2304 		/* Can't calculate this yet; not enough history */
2305 		window->average_tpt = IWL_INVALID_VALUE;
2306 
2307 		/* Should we stay with this modulation mode,
2308 		 * or search for a new one? */
2309 		rs_stay_in_table(lq_sta, false);
2310 
2311 		return;
2312 	}
2313 
2314 	/* If we are searching for better modulation mode, check success. */
2315 	if (lq_sta->search_better_tbl) {
2316 		/* If good success, continue using the "search" mode;
2317 		 * no need to send new link quality command, since we're
2318 		 * continuing to use the setup that we've been trying. */
2319 		if (window->average_tpt > lq_sta->last_tpt) {
2320 			IWL_DEBUG_RATE(mvm,
2321 				       "SWITCHING TO NEW TABLE SR: %d "
2322 				       "cur-tpt %d old-tpt %d\n",
2323 				       window->success_ratio,
2324 				       window->average_tpt,
2325 				       lq_sta->last_tpt);
2326 
2327 			/* Swap tables; "search" becomes "active" */
2328 			lq_sta->active_tbl = active_tbl;
2329 			current_tpt = window->average_tpt;
2330 		/* Else poor success; go back to mode in "active" table */
2331 		} else {
2332 			IWL_DEBUG_RATE(mvm,
2333 				       "GOING BACK TO THE OLD TABLE: SR %d "
2334 				       "cur-tpt %d old-tpt %d\n",
2335 				       window->success_ratio,
2336 				       window->average_tpt,
2337 				       lq_sta->last_tpt);
2338 
2339 			/* Nullify "search" table */
2340 			rate->type = LQ_NONE;
2341 
2342 			/* Revert to "active" table */
2343 			active_tbl = lq_sta->active_tbl;
2344 			tbl = &(lq_sta->lq_info[active_tbl]);
2345 
2346 			/* Revert to "active" rate and throughput info */
2347 			index = tbl->rate.index;
2348 			current_tpt = lq_sta->last_tpt;
2349 
2350 			/* Need to set up a new rate table in uCode */
2351 			update_lq = 1;
2352 		}
2353 
2354 		/* Either way, we've made a decision; modulation mode
2355 		 * search is done, allow rate adjustment next time. */
2356 		lq_sta->search_better_tbl = 0;
2357 		done_search = 1;	/* Don't switch modes below! */
2358 		goto lq_update;
2359 	}
2360 
2361 	/* (Else) not in search of better modulation mode, try for better
2362 	 * starting rate, while staying in this mode. */
2363 	high_low = rs_get_adjacent_rate(mvm, index, rate_mask, rate->type);
2364 	low = high_low & 0xff;
2365 	high = (high_low >> 8) & 0xff;
2366 
2367 	/* TODO: handle rate_idx_mask and rate_idx_mcs_mask */
2368 
2369 	sr = window->success_ratio;
2370 
2371 	/* Collect measured throughputs for current and adjacent rates */
2372 	current_tpt = window->average_tpt;
2373 	if (low != IWL_RATE_INVALID)
2374 		low_tpt = tbl->win[low].average_tpt;
2375 	if (high != IWL_RATE_INVALID)
2376 		high_tpt = tbl->win[high].average_tpt;
2377 
2378 	IWL_DEBUG_RATE(mvm,
2379 		       "%s: cur_tpt %d SR %d low %d high %d low_tpt %d high_tpt %d\n",
2380 		       rs_pretty_rate(rate), current_tpt, sr,
2381 		       low, high, low_tpt, high_tpt);
2382 
2383 	scale_action = rs_get_rate_action(mvm, tbl, sr, low, high,
2384 					  current_tpt, low_tpt, high_tpt);
2385 
2386 	/* Force a search in case BT doesn't like us being in MIMO */
2387 	if (is_mimo(rate) &&
2388 	    !iwl_mvm_bt_coex_is_mimo_allowed(mvm, sta)) {
2389 		IWL_DEBUG_RATE(mvm,
2390 			       "BT Coex forbids MIMO. Search for new config\n");
2391 		rs_stay_in_table(lq_sta, true);
2392 		goto lq_update;
2393 	}
2394 
2395 	switch (scale_action) {
2396 	case RS_ACTION_DOWNSCALE:
2397 		/* Decrease starting rate, update uCode's rate table */
2398 		if (low != IWL_RATE_INVALID) {
2399 			update_lq = 1;
2400 			index = low;
2401 		} else {
2402 			IWL_DEBUG_RATE(mvm,
2403 				       "At the bottom rate. Can't decrease\n");
2404 		}
2405 
2406 		break;
2407 	case RS_ACTION_UPSCALE:
2408 		/* Increase starting rate, update uCode's rate table */
2409 		if (high != IWL_RATE_INVALID) {
2410 			update_lq = 1;
2411 			index = high;
2412 		} else {
2413 			IWL_DEBUG_RATE(mvm,
2414 				       "At the top rate. Can't increase\n");
2415 		}
2416 
2417 		break;
2418 	case RS_ACTION_STAY:
2419 		/* No change */
2420 		if (lq_sta->rs_state == RS_STATE_STAY_IN_COLUMN)
2421 			update_lq = rs_tpc_perform(mvm, sta, lq_sta, tbl);
2422 		break;
2423 	default:
2424 		break;
2425 	}
2426 
2427 lq_update:
2428 	/* Replace uCode's rate table for the destination station. */
2429 	if (update_lq) {
2430 		tbl->rate.index = index;
2431 		if (IWL_MVM_RS_80_20_FAR_RANGE_TWEAK)
2432 			rs_tweak_rate_tbl(mvm, sta, lq_sta, tbl, scale_action);
2433 		rs_set_amsdu_len(mvm, sta, tbl, scale_action);
2434 		rs_update_rate_tbl(mvm, sta, lq_sta, tbl);
2435 	}
2436 
2437 	rs_stay_in_table(lq_sta, false);
2438 
2439 	/*
2440 	 * Search for new modulation mode if we're:
2441 	 * 1)  Not changing rates right now
2442 	 * 2)  Not just finishing up a search
2443 	 * 3)  Allowing a new search
2444 	 */
2445 	if (!update_lq && !done_search &&
2446 	    lq_sta->rs_state == RS_STATE_SEARCH_CYCLE_STARTED
2447 	    && window->counter) {
2448 		enum rs_column next_column;
2449 
2450 		/* Save current throughput to compare with "search" throughput*/
2451 		lq_sta->last_tpt = current_tpt;
2452 
2453 		IWL_DEBUG_RATE(mvm,
2454 			       "Start Search: update_lq %d done_search %d rs_state %d win->counter %d\n",
2455 			       update_lq, done_search, lq_sta->rs_state,
2456 			       window->counter);
2457 
2458 		next_column = rs_get_next_column(mvm, lq_sta, sta, tbl);
2459 		if (next_column != RS_COLUMN_INVALID) {
2460 			int ret = rs_switch_to_column(mvm, lq_sta, sta,
2461 						      next_column);
2462 			if (!ret)
2463 				lq_sta->search_better_tbl = 1;
2464 		} else {
2465 			IWL_DEBUG_RATE(mvm,
2466 				       "No more columns to explore in search cycle. Go to RS_STATE_SEARCH_CYCLE_ENDED\n");
2467 			lq_sta->rs_state = RS_STATE_SEARCH_CYCLE_ENDED;
2468 		}
2469 
2470 		/* If new "search" mode was selected, set up in uCode table */
2471 		if (lq_sta->search_better_tbl) {
2472 			/* Access the "search" table, clear its history. */
2473 			tbl = &(lq_sta->lq_info[(1 - lq_sta->active_tbl)]);
2474 			rs_rate_scale_clear_tbl_windows(mvm, tbl);
2475 
2476 			/* Use new "search" start rate */
2477 			index = tbl->rate.index;
2478 
2479 			rs_dump_rate(mvm, &tbl->rate,
2480 				     "Switch to SEARCH TABLE:");
2481 			rs_update_rate_tbl(mvm, sta, lq_sta, tbl);
2482 		} else {
2483 			done_search = 1;
2484 		}
2485 	}
2486 
2487 	if (done_search && lq_sta->rs_state == RS_STATE_SEARCH_CYCLE_ENDED) {
2488 		/* If the "active" (non-search) mode was legacy,
2489 		 * and we've tried switching antennas,
2490 		 * but we haven't been able to try HT modes (not available),
2491 		 * stay with best antenna legacy modulation for a while
2492 		 * before next round of mode comparisons. */
2493 		tbl1 = &(lq_sta->lq_info[lq_sta->active_tbl]);
2494 		if (is_legacy(&tbl1->rate)) {
2495 			IWL_DEBUG_RATE(mvm, "LQ: STAY in legacy table\n");
2496 
2497 			if (tid != IWL_MAX_TID_COUNT) {
2498 				tid_data = &sta_priv->tid_data[tid];
2499 				if (tid_data->state != IWL_AGG_OFF) {
2500 					IWL_DEBUG_RATE(mvm,
2501 						       "Stop aggregation on tid %d\n",
2502 						       tid);
2503 					ieee80211_stop_tx_ba_session(sta, tid);
2504 				}
2505 			}
2506 			rs_set_stay_in_table(mvm, 1, lq_sta);
2507 		} else {
2508 		/* If we're in an HT mode, and all 3 mode switch actions
2509 		 * have been tried and compared, stay in this best modulation
2510 		 * mode for a while before next round of mode comparisons. */
2511 			if ((lq_sta->last_tpt > IWL_AGG_TPT_THREHOLD) &&
2512 			    (lq_sta->tx_agg_tid_en & (1 << tid)) &&
2513 			    (tid != IWL_MAX_TID_COUNT)) {
2514 				tid_data = &sta_priv->tid_data[tid];
2515 				if (tid_data->state == IWL_AGG_OFF) {
2516 					IWL_DEBUG_RATE(mvm,
2517 						       "try to aggregate tid %d\n",
2518 						       tid);
2519 					rs_tl_turn_on_agg(mvm, tid,
2520 							  lq_sta, sta);
2521 				}
2522 			}
2523 			rs_set_stay_in_table(mvm, 0, lq_sta);
2524 		}
2525 	}
2526 }
2527 
2528 struct rs_init_rate_info {
2529 	s8 rssi;
2530 	u8 rate_idx;
2531 };
2532 
2533 static const struct rs_init_rate_info rs_optimal_rates_24ghz_legacy[] = {
2534 	{ -60, IWL_RATE_54M_INDEX },
2535 	{ -64, IWL_RATE_48M_INDEX },
2536 	{ -68, IWL_RATE_36M_INDEX },
2537 	{ -80, IWL_RATE_24M_INDEX },
2538 	{ -84, IWL_RATE_18M_INDEX },
2539 	{ -85, IWL_RATE_12M_INDEX },
2540 	{ -86, IWL_RATE_11M_INDEX },
2541 	{ -88, IWL_RATE_5M_INDEX  },
2542 	{ -90, IWL_RATE_2M_INDEX  },
2543 	{ S8_MIN, IWL_RATE_1M_INDEX },
2544 };
2545 
2546 static const struct rs_init_rate_info rs_optimal_rates_5ghz_legacy[] = {
2547 	{ -60, IWL_RATE_54M_INDEX },
2548 	{ -64, IWL_RATE_48M_INDEX },
2549 	{ -72, IWL_RATE_36M_INDEX },
2550 	{ -80, IWL_RATE_24M_INDEX },
2551 	{ -84, IWL_RATE_18M_INDEX },
2552 	{ -85, IWL_RATE_12M_INDEX },
2553 	{ -87, IWL_RATE_9M_INDEX  },
2554 	{ S8_MIN, IWL_RATE_6M_INDEX },
2555 };
2556 
2557 static const struct rs_init_rate_info rs_optimal_rates_ht[] = {
2558 	{ -60, IWL_RATE_MCS_7_INDEX },
2559 	{ -64, IWL_RATE_MCS_6_INDEX },
2560 	{ -68, IWL_RATE_MCS_5_INDEX },
2561 	{ -72, IWL_RATE_MCS_4_INDEX },
2562 	{ -80, IWL_RATE_MCS_3_INDEX },
2563 	{ -84, IWL_RATE_MCS_2_INDEX },
2564 	{ -85, IWL_RATE_MCS_1_INDEX },
2565 	{ S8_MIN, IWL_RATE_MCS_0_INDEX},
2566 };
2567 
2568 static const struct rs_init_rate_info rs_optimal_rates_vht_20mhz[] = {
2569 	{ -60, IWL_RATE_MCS_8_INDEX },
2570 	{ -64, IWL_RATE_MCS_7_INDEX },
2571 	{ -68, IWL_RATE_MCS_6_INDEX },
2572 	{ -72, IWL_RATE_MCS_5_INDEX },
2573 	{ -80, IWL_RATE_MCS_4_INDEX },
2574 	{ -84, IWL_RATE_MCS_3_INDEX },
2575 	{ -85, IWL_RATE_MCS_2_INDEX },
2576 	{ -87, IWL_RATE_MCS_1_INDEX },
2577 	{ S8_MIN, IWL_RATE_MCS_0_INDEX},
2578 };
2579 
2580 static const struct rs_init_rate_info rs_optimal_rates_vht_40_80mhz[] = {
2581 	{ -60, IWL_RATE_MCS_9_INDEX },
2582 	{ -64, IWL_RATE_MCS_8_INDEX },
2583 	{ -68, IWL_RATE_MCS_7_INDEX },
2584 	{ -72, IWL_RATE_MCS_6_INDEX },
2585 	{ -80, IWL_RATE_MCS_5_INDEX },
2586 	{ -84, IWL_RATE_MCS_4_INDEX },
2587 	{ -85, IWL_RATE_MCS_3_INDEX },
2588 	{ -87, IWL_RATE_MCS_2_INDEX },
2589 	{ -88, IWL_RATE_MCS_1_INDEX },
2590 	{ S8_MIN, IWL_RATE_MCS_0_INDEX },
2591 };
2592 
2593 #define IWL_RS_LOW_RSSI_THRESHOLD (-76) /* dBm */
2594 
2595 /* Init the optimal rate based on STA caps
2596  * This combined with rssi is used to report the last tx rate
2597  * to userspace when we haven't transmitted enough frames.
2598  */
2599 static void rs_init_optimal_rate(struct iwl_mvm *mvm,
2600 				 struct ieee80211_sta *sta,
2601 				 struct iwl_lq_sta *lq_sta)
2602 {
2603 	struct rs_rate *rate = &lq_sta->optimal_rate;
2604 
2605 	if (lq_sta->max_mimo2_rate_idx != IWL_RATE_INVALID)
2606 		rate->type = lq_sta->is_vht ? LQ_VHT_MIMO2 : LQ_HT_MIMO2;
2607 	else if (lq_sta->max_siso_rate_idx != IWL_RATE_INVALID)
2608 		rate->type = lq_sta->is_vht ? LQ_VHT_SISO : LQ_HT_SISO;
2609 	else if (lq_sta->band == NL80211_BAND_5GHZ)
2610 		rate->type = LQ_LEGACY_A;
2611 	else
2612 		rate->type = LQ_LEGACY_G;
2613 
2614 	rate->bw = rs_bw_from_sta_bw(sta);
2615 	rate->sgi = rs_sgi_allow(mvm, sta, rate, NULL);
2616 
2617 	/* ANT/LDPC/STBC aren't relevant for the rate reported to userspace */
2618 
2619 	if (is_mimo(rate)) {
2620 		lq_sta->optimal_rate_mask = lq_sta->active_mimo2_rate;
2621 	} else if (is_siso(rate)) {
2622 		lq_sta->optimal_rate_mask = lq_sta->active_siso_rate;
2623 	} else {
2624 		lq_sta->optimal_rate_mask = lq_sta->active_legacy_rate;
2625 
2626 		if (lq_sta->band == NL80211_BAND_5GHZ) {
2627 			lq_sta->optimal_rates = rs_optimal_rates_5ghz_legacy;
2628 			lq_sta->optimal_nentries =
2629 				ARRAY_SIZE(rs_optimal_rates_5ghz_legacy);
2630 		} else {
2631 			lq_sta->optimal_rates = rs_optimal_rates_24ghz_legacy;
2632 			lq_sta->optimal_nentries =
2633 				ARRAY_SIZE(rs_optimal_rates_24ghz_legacy);
2634 		}
2635 	}
2636 
2637 	if (is_vht(rate)) {
2638 		if (rate->bw == RATE_MCS_CHAN_WIDTH_20) {
2639 			lq_sta->optimal_rates = rs_optimal_rates_vht_20mhz;
2640 			lq_sta->optimal_nentries =
2641 				ARRAY_SIZE(rs_optimal_rates_vht_20mhz);
2642 		} else {
2643 			lq_sta->optimal_rates = rs_optimal_rates_vht_40_80mhz;
2644 			lq_sta->optimal_nentries =
2645 				ARRAY_SIZE(rs_optimal_rates_vht_40_80mhz);
2646 		}
2647 	} else if (is_ht(rate)) {
2648 		lq_sta->optimal_rates = rs_optimal_rates_ht;
2649 		lq_sta->optimal_nentries = ARRAY_SIZE(rs_optimal_rates_ht);
2650 	}
2651 }
2652 
2653 /* Compute the optimal rate index based on RSSI */
2654 static struct rs_rate *rs_get_optimal_rate(struct iwl_mvm *mvm,
2655 					   struct iwl_lq_sta *lq_sta)
2656 {
2657 	struct rs_rate *rate = &lq_sta->optimal_rate;
2658 	int i;
2659 
2660 	rate->index = find_first_bit(&lq_sta->optimal_rate_mask,
2661 				     BITS_PER_LONG);
2662 
2663 	for (i = 0; i < lq_sta->optimal_nentries; i++) {
2664 		int rate_idx = lq_sta->optimal_rates[i].rate_idx;
2665 
2666 		if ((lq_sta->pers.last_rssi >= lq_sta->optimal_rates[i].rssi) &&
2667 		    (BIT(rate_idx) & lq_sta->optimal_rate_mask)) {
2668 			rate->index = rate_idx;
2669 			break;
2670 		}
2671 	}
2672 
2673 	return rate;
2674 }
2675 
2676 /* Choose an initial legacy rate and antenna to use based on the RSSI
2677  * of last Rx
2678  */
2679 static void rs_get_initial_rate(struct iwl_mvm *mvm,
2680 				struct ieee80211_sta *sta,
2681 				struct iwl_lq_sta *lq_sta,
2682 				enum nl80211_band band,
2683 				struct rs_rate *rate)
2684 {
2685 	int i, nentries;
2686 	unsigned long active_rate;
2687 	s8 best_rssi = S8_MIN;
2688 	u8 best_ant = ANT_NONE;
2689 	u8 valid_tx_ant = iwl_mvm_get_valid_tx_ant(mvm);
2690 	const struct rs_init_rate_info *initial_rates;
2691 
2692 	for (i = 0; i < ARRAY_SIZE(lq_sta->pers.chain_signal); i++) {
2693 		if (!(lq_sta->pers.chains & BIT(i)))
2694 			continue;
2695 
2696 		if (lq_sta->pers.chain_signal[i] > best_rssi) {
2697 			best_rssi = lq_sta->pers.chain_signal[i];
2698 			best_ant = BIT(i);
2699 		}
2700 	}
2701 
2702 	IWL_DEBUG_RATE(mvm, "Best ANT: %s Best RSSI: %d\n",
2703 		       rs_pretty_ant(best_ant), best_rssi);
2704 
2705 	if (best_ant != ANT_A && best_ant != ANT_B)
2706 		rate->ant = first_antenna(valid_tx_ant);
2707 	else
2708 		rate->ant = best_ant;
2709 
2710 	rate->sgi = false;
2711 	rate->ldpc = false;
2712 	rate->bw = RATE_MCS_CHAN_WIDTH_20;
2713 
2714 	rate->index = find_first_bit(&lq_sta->active_legacy_rate,
2715 				     BITS_PER_LONG);
2716 
2717 	if (band == NL80211_BAND_5GHZ) {
2718 		rate->type = LQ_LEGACY_A;
2719 		initial_rates = rs_optimal_rates_5ghz_legacy;
2720 		nentries = ARRAY_SIZE(rs_optimal_rates_5ghz_legacy);
2721 	} else {
2722 		rate->type = LQ_LEGACY_G;
2723 		initial_rates = rs_optimal_rates_24ghz_legacy;
2724 		nentries = ARRAY_SIZE(rs_optimal_rates_24ghz_legacy);
2725 	}
2726 
2727 	if (!IWL_MVM_RS_RSSI_BASED_INIT_RATE)
2728 		goto out;
2729 
2730 	/* Start from a higher rate if the corresponding debug capability
2731 	 * is enabled. The rate is chosen according to AP capabilities.
2732 	 * In case of VHT/HT when the rssi is low fallback to the case of
2733 	 * legacy rates.
2734 	 */
2735 	if (sta->vht_cap.vht_supported &&
2736 	    best_rssi > IWL_RS_LOW_RSSI_THRESHOLD) {
2737 		if (sta->bandwidth >= IEEE80211_STA_RX_BW_40) {
2738 			initial_rates = rs_optimal_rates_vht_40_80mhz;
2739 			nentries = ARRAY_SIZE(rs_optimal_rates_vht_40_80mhz);
2740 			if (sta->bandwidth >= IEEE80211_STA_RX_BW_80)
2741 				rate->bw = RATE_MCS_CHAN_WIDTH_80;
2742 			else
2743 				rate->bw = RATE_MCS_CHAN_WIDTH_40;
2744 		} else if (sta->bandwidth == IEEE80211_STA_RX_BW_20) {
2745 			initial_rates = rs_optimal_rates_vht_20mhz;
2746 			nentries = ARRAY_SIZE(rs_optimal_rates_vht_20mhz);
2747 			rate->bw = RATE_MCS_CHAN_WIDTH_20;
2748 		} else {
2749 			IWL_ERR(mvm, "Invalid BW %d\n", sta->bandwidth);
2750 			goto out;
2751 		}
2752 		active_rate = lq_sta->active_siso_rate;
2753 		rate->type = LQ_VHT_SISO;
2754 	} else if (sta->ht_cap.ht_supported &&
2755 		   best_rssi > IWL_RS_LOW_RSSI_THRESHOLD) {
2756 		initial_rates = rs_optimal_rates_ht;
2757 		nentries = ARRAY_SIZE(rs_optimal_rates_ht);
2758 		active_rate = lq_sta->active_siso_rate;
2759 		rate->type = LQ_HT_SISO;
2760 	} else {
2761 		active_rate = lq_sta->active_legacy_rate;
2762 	}
2763 
2764 	for (i = 0; i < nentries; i++) {
2765 		int rate_idx = initial_rates[i].rate_idx;
2766 
2767 		if ((best_rssi >= initial_rates[i].rssi) &&
2768 		    (BIT(rate_idx) & active_rate)) {
2769 			rate->index = rate_idx;
2770 			break;
2771 		}
2772 	}
2773 
2774 out:
2775 	rs_dump_rate(mvm, rate, "INITIAL");
2776 }
2777 
2778 /* Save info about RSSI of last Rx */
2779 void rs_update_last_rssi(struct iwl_mvm *mvm,
2780 			 struct iwl_lq_sta *lq_sta,
2781 			 struct ieee80211_rx_status *rx_status)
2782 {
2783 	int i;
2784 
2785 	lq_sta->pers.chains = rx_status->chains;
2786 	lq_sta->pers.chain_signal[0] = rx_status->chain_signal[0];
2787 	lq_sta->pers.chain_signal[1] = rx_status->chain_signal[1];
2788 	lq_sta->pers.chain_signal[2] = rx_status->chain_signal[2];
2789 	lq_sta->pers.last_rssi = S8_MIN;
2790 
2791 	for (i = 0; i < ARRAY_SIZE(lq_sta->pers.chain_signal); i++) {
2792 		if (!(lq_sta->pers.chains & BIT(i)))
2793 			continue;
2794 
2795 		if (lq_sta->pers.chain_signal[i] > lq_sta->pers.last_rssi)
2796 			lq_sta->pers.last_rssi = lq_sta->pers.chain_signal[i];
2797 	}
2798 }
2799 
2800 /**
2801  * rs_initialize_lq - Initialize a station's hardware rate table
2802  *
2803  * The uCode's station table contains a table of fallback rates
2804  * for automatic fallback during transmission.
2805  *
2806  * NOTE: This sets up a default set of values.  These will be replaced later
2807  *       if the driver's iwl-agn-rs rate scaling algorithm is used, instead of
2808  *       rc80211_simple.
2809  *
2810  * NOTE: Run REPLY_ADD_STA command to set up station table entry, before
2811  *       calling this function (which runs REPLY_TX_LINK_QUALITY_CMD,
2812  *       which requires station table entry to exist).
2813  */
2814 static void rs_initialize_lq(struct iwl_mvm *mvm,
2815 			     struct ieee80211_sta *sta,
2816 			     struct iwl_lq_sta *lq_sta,
2817 			     enum nl80211_band band,
2818 			     bool init)
2819 {
2820 	struct iwl_scale_tbl_info *tbl;
2821 	struct rs_rate *rate;
2822 	u8 active_tbl = 0;
2823 
2824 	if (!sta || !lq_sta)
2825 		return;
2826 
2827 	if (!lq_sta->search_better_tbl)
2828 		active_tbl = lq_sta->active_tbl;
2829 	else
2830 		active_tbl = 1 - lq_sta->active_tbl;
2831 
2832 	tbl = &(lq_sta->lq_info[active_tbl]);
2833 	rate = &tbl->rate;
2834 
2835 	rs_get_initial_rate(mvm, sta, lq_sta, band, rate);
2836 	rs_init_optimal_rate(mvm, sta, lq_sta);
2837 
2838 	WARN_ON_ONCE(rate->ant != ANT_A && rate->ant != ANT_B);
2839 	tbl->column = rs_get_column_from_rate(rate);
2840 
2841 	rs_set_expected_tpt_table(lq_sta, tbl);
2842 	rs_fill_lq_cmd(mvm, sta, lq_sta, rate);
2843 	/* TODO restore station should remember the lq cmd */
2844 	iwl_mvm_send_lq_cmd(mvm, &lq_sta->lq, init);
2845 }
2846 
2847 static void rs_get_rate(void *mvm_r, struct ieee80211_sta *sta, void *mvm_sta,
2848 			struct ieee80211_tx_rate_control *txrc)
2849 {
2850 	struct sk_buff *skb = txrc->skb;
2851 	struct iwl_op_mode *op_mode __maybe_unused =
2852 			(struct iwl_op_mode *)mvm_r;
2853 	struct iwl_mvm *mvm __maybe_unused = IWL_OP_MODE_GET_MVM(op_mode);
2854 	struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
2855 	struct iwl_lq_sta *lq_sta = mvm_sta;
2856 	struct rs_rate *optimal_rate;
2857 	u32 last_ucode_rate;
2858 
2859 	if (sta && !iwl_mvm_sta_from_mac80211(sta)->vif) {
2860 		/* if vif isn't initialized mvm doesn't know about
2861 		 * this station, so don't do anything with the it
2862 		 */
2863 		sta = NULL;
2864 		mvm_sta = NULL;
2865 	}
2866 
2867 	/* TODO: handle rate_idx_mask and rate_idx_mcs_mask */
2868 
2869 	/* Treat uninitialized rate scaling data same as non-existing. */
2870 	if (lq_sta && !lq_sta->pers.drv) {
2871 		IWL_DEBUG_RATE(mvm, "Rate scaling not initialized yet.\n");
2872 		mvm_sta = NULL;
2873 	}
2874 
2875 	/* Send management frames and NO_ACK data using lowest rate. */
2876 	if (rate_control_send_low(sta, mvm_sta, txrc))
2877 		return;
2878 
2879 	iwl_mvm_hwrate_to_tx_rate(lq_sta->last_rate_n_flags,
2880 				  info->band, &info->control.rates[0]);
2881 	info->control.rates[0].count = 1;
2882 
2883 	/* Report the optimal rate based on rssi and STA caps if we haven't
2884 	 * converged yet (too little traffic) or exploring other modulations
2885 	 */
2886 	if (lq_sta->rs_state != RS_STATE_STAY_IN_COLUMN) {
2887 		optimal_rate = rs_get_optimal_rate(mvm, lq_sta);
2888 		last_ucode_rate = ucode_rate_from_rs_rate(mvm,
2889 							  optimal_rate);
2890 		iwl_mvm_hwrate_to_tx_rate(last_ucode_rate, info->band,
2891 					  &txrc->reported_rate);
2892 	}
2893 }
2894 
2895 static void *rs_alloc_sta(void *mvm_rate, struct ieee80211_sta *sta,
2896 			  gfp_t gfp)
2897 {
2898 	struct iwl_mvm_sta *sta_priv = iwl_mvm_sta_from_mac80211(sta);
2899 	struct iwl_op_mode *op_mode = (struct iwl_op_mode *)mvm_rate;
2900 	struct iwl_mvm *mvm  = IWL_OP_MODE_GET_MVM(op_mode);
2901 	struct iwl_lq_sta *lq_sta = &sta_priv->lq_sta;
2902 
2903 	IWL_DEBUG_RATE(mvm, "create station rate scale window\n");
2904 
2905 	lq_sta->pers.drv = mvm;
2906 #ifdef CONFIG_MAC80211_DEBUGFS
2907 	lq_sta->pers.dbg_fixed_rate = 0;
2908 	lq_sta->pers.dbg_fixed_txp_reduction = TPC_INVALID;
2909 	lq_sta->pers.ss_force = RS_SS_FORCE_NONE;
2910 #endif
2911 	lq_sta->pers.chains = 0;
2912 	memset(lq_sta->pers.chain_signal, 0, sizeof(lq_sta->pers.chain_signal));
2913 	lq_sta->pers.last_rssi = S8_MIN;
2914 
2915 	return &sta_priv->lq_sta;
2916 }
2917 
2918 static int rs_vht_highest_rx_mcs_index(struct ieee80211_sta_vht_cap *vht_cap,
2919 				       int nss)
2920 {
2921 	u16 rx_mcs = le16_to_cpu(vht_cap->vht_mcs.rx_mcs_map) &
2922 		(0x3 << (2 * (nss - 1)));
2923 	rx_mcs >>= (2 * (nss - 1));
2924 
2925 	if (rx_mcs == IEEE80211_VHT_MCS_SUPPORT_0_7)
2926 		return IWL_RATE_MCS_7_INDEX;
2927 	else if (rx_mcs == IEEE80211_VHT_MCS_SUPPORT_0_8)
2928 		return IWL_RATE_MCS_8_INDEX;
2929 	else if (rx_mcs == IEEE80211_VHT_MCS_SUPPORT_0_9)
2930 		return IWL_RATE_MCS_9_INDEX;
2931 
2932 	WARN_ON_ONCE(rx_mcs != IEEE80211_VHT_MCS_NOT_SUPPORTED);
2933 	return -1;
2934 }
2935 
2936 static void rs_vht_set_enabled_rates(struct ieee80211_sta *sta,
2937 				     struct ieee80211_sta_vht_cap *vht_cap,
2938 				     struct iwl_lq_sta *lq_sta)
2939 {
2940 	int i;
2941 	int highest_mcs = rs_vht_highest_rx_mcs_index(vht_cap, 1);
2942 
2943 	if (highest_mcs >= IWL_RATE_MCS_0_INDEX) {
2944 		for (i = IWL_RATE_MCS_0_INDEX; i <= highest_mcs; i++) {
2945 			if (i == IWL_RATE_9M_INDEX)
2946 				continue;
2947 
2948 			/* VHT MCS9 isn't valid for 20Mhz for NSS=1,2 */
2949 			if (i == IWL_RATE_MCS_9_INDEX &&
2950 			    sta->bandwidth == IEEE80211_STA_RX_BW_20)
2951 				continue;
2952 
2953 			lq_sta->active_siso_rate |= BIT(i);
2954 		}
2955 	}
2956 
2957 	if (sta->rx_nss < 2)
2958 		return;
2959 
2960 	highest_mcs = rs_vht_highest_rx_mcs_index(vht_cap, 2);
2961 	if (highest_mcs >= IWL_RATE_MCS_0_INDEX) {
2962 		for (i = IWL_RATE_MCS_0_INDEX; i <= highest_mcs; i++) {
2963 			if (i == IWL_RATE_9M_INDEX)
2964 				continue;
2965 
2966 			/* VHT MCS9 isn't valid for 20Mhz for NSS=1,2 */
2967 			if (i == IWL_RATE_MCS_9_INDEX &&
2968 			    sta->bandwidth == IEEE80211_STA_RX_BW_20)
2969 				continue;
2970 
2971 			lq_sta->active_mimo2_rate |= BIT(i);
2972 		}
2973 	}
2974 }
2975 
2976 static void rs_ht_init(struct iwl_mvm *mvm,
2977 		       struct ieee80211_sta *sta,
2978 		       struct iwl_lq_sta *lq_sta,
2979 		       struct ieee80211_sta_ht_cap *ht_cap)
2980 {
2981 	/* active_siso_rate mask includes 9 MBits (bit 5),
2982 	 * and CCK (bits 0-3), supp_rates[] does not;
2983 	 * shift to convert format, force 9 MBits off.
2984 	 */
2985 	lq_sta->active_siso_rate = ht_cap->mcs.rx_mask[0] << 1;
2986 	lq_sta->active_siso_rate |= ht_cap->mcs.rx_mask[0] & 0x1;
2987 	lq_sta->active_siso_rate &= ~((u16)0x2);
2988 	lq_sta->active_siso_rate <<= IWL_FIRST_OFDM_RATE;
2989 
2990 	lq_sta->active_mimo2_rate = ht_cap->mcs.rx_mask[1] << 1;
2991 	lq_sta->active_mimo2_rate |= ht_cap->mcs.rx_mask[1] & 0x1;
2992 	lq_sta->active_mimo2_rate &= ~((u16)0x2);
2993 	lq_sta->active_mimo2_rate <<= IWL_FIRST_OFDM_RATE;
2994 
2995 	if (mvm->cfg->ht_params->ldpc &&
2996 	    (ht_cap->cap & IEEE80211_HT_CAP_LDPC_CODING))
2997 		lq_sta->ldpc = true;
2998 
2999 	if (mvm->cfg->ht_params->stbc &&
3000 	    (num_of_ant(iwl_mvm_get_valid_tx_ant(mvm)) > 1) &&
3001 	    (ht_cap->cap & IEEE80211_HT_CAP_RX_STBC))
3002 		lq_sta->stbc_capable = true;
3003 
3004 	lq_sta->is_vht = false;
3005 }
3006 
3007 static void rs_vht_init(struct iwl_mvm *mvm,
3008 			struct ieee80211_sta *sta,
3009 			struct iwl_lq_sta *lq_sta,
3010 			struct ieee80211_sta_vht_cap *vht_cap)
3011 {
3012 	rs_vht_set_enabled_rates(sta, vht_cap, lq_sta);
3013 
3014 	if (mvm->cfg->ht_params->ldpc &&
3015 	    (vht_cap->cap & IEEE80211_VHT_CAP_RXLDPC))
3016 		lq_sta->ldpc = true;
3017 
3018 	if (mvm->cfg->ht_params->stbc &&
3019 	    (num_of_ant(iwl_mvm_get_valid_tx_ant(mvm)) > 1) &&
3020 	    (vht_cap->cap & IEEE80211_VHT_CAP_RXSTBC_MASK))
3021 		lq_sta->stbc_capable = true;
3022 
3023 	if (fw_has_capa(&mvm->fw->ucode_capa, IWL_UCODE_TLV_CAPA_BEAMFORMER) &&
3024 	    (num_of_ant(iwl_mvm_get_valid_tx_ant(mvm)) > 1) &&
3025 	    (vht_cap->cap & IEEE80211_VHT_CAP_SU_BEAMFORMEE_CAPABLE))
3026 		lq_sta->bfer_capable = true;
3027 
3028 	lq_sta->is_vht = true;
3029 }
3030 
3031 #ifdef CONFIG_IWLWIFI_DEBUGFS
3032 static void iwl_mvm_reset_frame_stats(struct iwl_mvm *mvm)
3033 {
3034 	spin_lock_bh(&mvm->drv_stats_lock);
3035 	memset(&mvm->drv_rx_stats, 0, sizeof(mvm->drv_rx_stats));
3036 	spin_unlock_bh(&mvm->drv_stats_lock);
3037 }
3038 
3039 void iwl_mvm_update_frame_stats(struct iwl_mvm *mvm, u32 rate, bool agg)
3040 {
3041 	u8 nss = 0, mcs = 0;
3042 
3043 	spin_lock(&mvm->drv_stats_lock);
3044 
3045 	if (agg)
3046 		mvm->drv_rx_stats.agg_frames++;
3047 
3048 	mvm->drv_rx_stats.success_frames++;
3049 
3050 	switch (rate & RATE_MCS_CHAN_WIDTH_MSK) {
3051 	case RATE_MCS_CHAN_WIDTH_20:
3052 		mvm->drv_rx_stats.bw_20_frames++;
3053 		break;
3054 	case RATE_MCS_CHAN_WIDTH_40:
3055 		mvm->drv_rx_stats.bw_40_frames++;
3056 		break;
3057 	case RATE_MCS_CHAN_WIDTH_80:
3058 		mvm->drv_rx_stats.bw_80_frames++;
3059 		break;
3060 	default:
3061 		WARN_ONCE(1, "bad BW. rate 0x%x", rate);
3062 	}
3063 
3064 	if (rate & RATE_MCS_HT_MSK) {
3065 		mvm->drv_rx_stats.ht_frames++;
3066 		mcs = rate & RATE_HT_MCS_RATE_CODE_MSK;
3067 		nss = ((rate & RATE_HT_MCS_NSS_MSK) >> RATE_HT_MCS_NSS_POS) + 1;
3068 	} else if (rate & RATE_MCS_VHT_MSK) {
3069 		mvm->drv_rx_stats.vht_frames++;
3070 		mcs = rate & RATE_VHT_MCS_RATE_CODE_MSK;
3071 		nss = ((rate & RATE_VHT_MCS_NSS_MSK) >>
3072 		       RATE_VHT_MCS_NSS_POS) + 1;
3073 	} else {
3074 		mvm->drv_rx_stats.legacy_frames++;
3075 	}
3076 
3077 	if (nss == 1)
3078 		mvm->drv_rx_stats.siso_frames++;
3079 	else if (nss == 2)
3080 		mvm->drv_rx_stats.mimo2_frames++;
3081 
3082 	if (rate & RATE_MCS_SGI_MSK)
3083 		mvm->drv_rx_stats.sgi_frames++;
3084 	else
3085 		mvm->drv_rx_stats.ngi_frames++;
3086 
3087 	mvm->drv_rx_stats.last_rates[mvm->drv_rx_stats.last_frame_idx] = rate;
3088 	mvm->drv_rx_stats.last_frame_idx =
3089 		(mvm->drv_rx_stats.last_frame_idx + 1) %
3090 			ARRAY_SIZE(mvm->drv_rx_stats.last_rates);
3091 
3092 	spin_unlock(&mvm->drv_stats_lock);
3093 }
3094 #endif
3095 
3096 /*
3097  * Called after adding a new station to initialize rate scaling
3098  */
3099 void iwl_mvm_rs_rate_init(struct iwl_mvm *mvm, struct ieee80211_sta *sta,
3100 			  enum nl80211_band band, bool init)
3101 {
3102 	int i, j;
3103 	struct ieee80211_hw *hw = mvm->hw;
3104 	struct ieee80211_sta_ht_cap *ht_cap = &sta->ht_cap;
3105 	struct ieee80211_sta_vht_cap *vht_cap = &sta->vht_cap;
3106 	struct iwl_mvm_sta *sta_priv = iwl_mvm_sta_from_mac80211(sta);
3107 	struct iwl_lq_sta *lq_sta = &sta_priv->lq_sta;
3108 	struct ieee80211_supported_band *sband;
3109 	unsigned long supp; /* must be unsigned long for for_each_set_bit */
3110 
3111 	/* clear all non-persistent lq data */
3112 	memset(lq_sta, 0, offsetof(typeof(*lq_sta), pers));
3113 
3114 	sband = hw->wiphy->bands[band];
3115 
3116 	lq_sta->lq.sta_id = sta_priv->sta_id;
3117 	sta_priv->tlc_amsdu = false;
3118 
3119 	for (j = 0; j < LQ_SIZE; j++)
3120 		rs_rate_scale_clear_tbl_windows(mvm, &lq_sta->lq_info[j]);
3121 
3122 	lq_sta->flush_timer = 0;
3123 	lq_sta->last_tx = jiffies;
3124 
3125 	IWL_DEBUG_RATE(mvm,
3126 		       "LQ: *** rate scale station global init for station %d ***\n",
3127 		       sta_priv->sta_id);
3128 	/* TODO: what is a good starting rate for STA? About middle? Maybe not
3129 	 * the lowest or the highest rate.. Could consider using RSSI from
3130 	 * previous packets? Need to have IEEE 802.1X auth succeed immediately
3131 	 * after assoc.. */
3132 
3133 	lq_sta->missed_rate_counter = IWL_MVM_RS_MISSED_RATE_MAX;
3134 	lq_sta->band = sband->band;
3135 	/*
3136 	 * active legacy rates as per supported rates bitmap
3137 	 */
3138 	supp = sta->supp_rates[sband->band];
3139 	lq_sta->active_legacy_rate = 0;
3140 	for_each_set_bit(i, &supp, BITS_PER_LONG)
3141 		lq_sta->active_legacy_rate |= BIT(sband->bitrates[i].hw_value);
3142 
3143 	/* TODO: should probably account for rx_highest for both HT/VHT */
3144 	if (!vht_cap || !vht_cap->vht_supported)
3145 		rs_ht_init(mvm, sta, lq_sta, ht_cap);
3146 	else
3147 		rs_vht_init(mvm, sta, lq_sta, vht_cap);
3148 
3149 	lq_sta->max_legacy_rate_idx =
3150 		rs_get_max_rate_from_mask(lq_sta->active_legacy_rate);
3151 	lq_sta->max_siso_rate_idx =
3152 		rs_get_max_rate_from_mask(lq_sta->active_siso_rate);
3153 	lq_sta->max_mimo2_rate_idx =
3154 		rs_get_max_rate_from_mask(lq_sta->active_mimo2_rate);
3155 
3156 	IWL_DEBUG_RATE(mvm,
3157 		       "LEGACY=%lX SISO=%lX MIMO2=%lX VHT=%d LDPC=%d STBC=%d BFER=%d\n",
3158 		       lq_sta->active_legacy_rate,
3159 		       lq_sta->active_siso_rate,
3160 		       lq_sta->active_mimo2_rate,
3161 		       lq_sta->is_vht, lq_sta->ldpc, lq_sta->stbc_capable,
3162 		       lq_sta->bfer_capable);
3163 	IWL_DEBUG_RATE(mvm, "MAX RATE: LEGACY=%d SISO=%d MIMO2=%d\n",
3164 		       lq_sta->max_legacy_rate_idx,
3165 		       lq_sta->max_siso_rate_idx,
3166 		       lq_sta->max_mimo2_rate_idx);
3167 
3168 	/* These values will be overridden later */
3169 	lq_sta->lq.single_stream_ant_msk =
3170 		first_antenna(iwl_mvm_get_valid_tx_ant(mvm));
3171 	lq_sta->lq.dual_stream_ant_msk = ANT_AB;
3172 
3173 	/* as default allow aggregation for all tids */
3174 	lq_sta->tx_agg_tid_en = IWL_AGG_ALL_TID;
3175 	lq_sta->is_agg = 0;
3176 #ifdef CONFIG_IWLWIFI_DEBUGFS
3177 	iwl_mvm_reset_frame_stats(mvm);
3178 #endif
3179 	rs_initialize_lq(mvm, sta, lq_sta, band, init);
3180 }
3181 
3182 static void rs_rate_update(void *mvm_r,
3183 			   struct ieee80211_supported_band *sband,
3184 			   struct cfg80211_chan_def *chandef,
3185 			   struct ieee80211_sta *sta, void *priv_sta,
3186 			   u32 changed)
3187 {
3188 	u8 tid;
3189 	struct iwl_op_mode *op_mode  =
3190 			(struct iwl_op_mode *)mvm_r;
3191 	struct iwl_mvm *mvm = IWL_OP_MODE_GET_MVM(op_mode);
3192 
3193 	if (!iwl_mvm_sta_from_mac80211(sta)->vif)
3194 		return;
3195 
3196 	/* Stop any ongoing aggregations as rs starts off assuming no agg */
3197 	for (tid = 0; tid < IWL_MAX_TID_COUNT; tid++)
3198 		ieee80211_stop_tx_ba_session(sta, tid);
3199 
3200 	iwl_mvm_rs_rate_init(mvm, sta, sband->band, false);
3201 }
3202 
3203 #ifdef CONFIG_MAC80211_DEBUGFS
3204 static void rs_build_rates_table_from_fixed(struct iwl_mvm *mvm,
3205 					    struct iwl_lq_cmd *lq_cmd,
3206 					    enum nl80211_band band,
3207 					    u32 ucode_rate)
3208 {
3209 	struct rs_rate rate;
3210 	int i;
3211 	int num_rates = ARRAY_SIZE(lq_cmd->rs_table);
3212 	__le32 ucode_rate_le32 = cpu_to_le32(ucode_rate);
3213 	u8 ant = (ucode_rate & RATE_MCS_ANT_ABC_MSK) >> RATE_MCS_ANT_POS;
3214 
3215 	for (i = 0; i < num_rates; i++)
3216 		lq_cmd->rs_table[i] = ucode_rate_le32;
3217 
3218 	rs_rate_from_ucode_rate(ucode_rate, band, &rate);
3219 
3220 	if (is_mimo(&rate))
3221 		lq_cmd->mimo_delim = num_rates - 1;
3222 	else
3223 		lq_cmd->mimo_delim = 0;
3224 
3225 	lq_cmd->reduced_tpc = 0;
3226 
3227 	if (num_of_ant(ant) == 1)
3228 		lq_cmd->single_stream_ant_msk = ant;
3229 
3230 	lq_cmd->agg_frame_cnt_limit = LINK_QUAL_AGG_FRAME_LIMIT_DEF;
3231 }
3232 #endif /* CONFIG_MAC80211_DEBUGFS */
3233 
3234 static void rs_fill_rates_for_column(struct iwl_mvm *mvm,
3235 				     struct iwl_lq_sta *lq_sta,
3236 				     struct rs_rate *rate,
3237 				     __le32 *rs_table, int *rs_table_index,
3238 				     int num_rates, int num_retries,
3239 				     u8 valid_tx_ant, bool toggle_ant)
3240 {
3241 	int i, j;
3242 	__le32 ucode_rate;
3243 	bool bottom_reached = false;
3244 	int prev_rate_idx = rate->index;
3245 	int end = LINK_QUAL_MAX_RETRY_NUM;
3246 	int index = *rs_table_index;
3247 
3248 	for (i = 0; i < num_rates && index < end; i++) {
3249 		for (j = 0; j < num_retries && index < end; j++, index++) {
3250 			ucode_rate = cpu_to_le32(ucode_rate_from_rs_rate(mvm,
3251 									 rate));
3252 			rs_table[index] = ucode_rate;
3253 			if (toggle_ant)
3254 				rs_toggle_antenna(valid_tx_ant, rate);
3255 		}
3256 
3257 		prev_rate_idx = rate->index;
3258 		bottom_reached = rs_get_lower_rate_in_column(lq_sta, rate);
3259 		if (bottom_reached && !is_legacy(rate))
3260 			break;
3261 	}
3262 
3263 	if (!bottom_reached && !is_legacy(rate))
3264 		rate->index = prev_rate_idx;
3265 
3266 	*rs_table_index = index;
3267 }
3268 
3269 /* Building the rate table is non trivial. When we're in MIMO2/VHT/80Mhz/SGI
3270  * column the rate table should look like this:
3271  *
3272  * rate[0] 0x400D019 VHT | ANT: AB BW: 80Mhz MCS: 9 NSS: 2 SGI
3273  * rate[1] 0x400D019 VHT | ANT: AB BW: 80Mhz MCS: 9 NSS: 2 SGI
3274  * rate[2] 0x400D018 VHT | ANT: AB BW: 80Mhz MCS: 8 NSS: 2 SGI
3275  * rate[3] 0x400D018 VHT | ANT: AB BW: 80Mhz MCS: 8 NSS: 2 SGI
3276  * rate[4] 0x400D017 VHT | ANT: AB BW: 80Mhz MCS: 7 NSS: 2 SGI
3277  * rate[5] 0x400D017 VHT | ANT: AB BW: 80Mhz MCS: 7 NSS: 2 SGI
3278  * rate[6] 0x4005007 VHT | ANT: A BW: 80Mhz MCS: 7 NSS: 1 NGI
3279  * rate[7] 0x4009006 VHT | ANT: B BW: 80Mhz MCS: 6 NSS: 1 NGI
3280  * rate[8] 0x4005005 VHT | ANT: A BW: 80Mhz MCS: 5 NSS: 1 NGI
3281  * rate[9] 0x800B Legacy | ANT: B Rate: 36 Mbps
3282  * rate[10] 0x4009 Legacy | ANT: A Rate: 24 Mbps
3283  * rate[11] 0x8007 Legacy | ANT: B Rate: 18 Mbps
3284  * rate[12] 0x4005 Legacy | ANT: A Rate: 12 Mbps
3285  * rate[13] 0x800F Legacy | ANT: B Rate: 9 Mbps
3286  * rate[14] 0x400D Legacy | ANT: A Rate: 6 Mbps
3287  * rate[15] 0x800D Legacy | ANT: B Rate: 6 Mbps
3288  */
3289 static void rs_build_rates_table(struct iwl_mvm *mvm,
3290 				 struct ieee80211_sta *sta,
3291 				 struct iwl_lq_sta *lq_sta,
3292 				 const struct rs_rate *initial_rate)
3293 {
3294 	struct rs_rate rate;
3295 	int num_rates, num_retries, index = 0;
3296 	u8 valid_tx_ant = 0;
3297 	struct iwl_lq_cmd *lq_cmd = &lq_sta->lq;
3298 	bool toggle_ant = false;
3299 
3300 	memcpy(&rate, initial_rate, sizeof(rate));
3301 
3302 	valid_tx_ant = iwl_mvm_get_valid_tx_ant(mvm);
3303 
3304 	/* TODO: remove old API when min FW API hits 14 */
3305 	if (!fw_has_api(&mvm->fw->ucode_capa, IWL_UCODE_TLV_API_LQ_SS_PARAMS) &&
3306 	    rs_stbc_allow(mvm, sta, lq_sta))
3307 		rate.stbc = true;
3308 
3309 	if (is_siso(&rate)) {
3310 		num_rates = IWL_MVM_RS_INITIAL_SISO_NUM_RATES;
3311 		num_retries = IWL_MVM_RS_HT_VHT_RETRIES_PER_RATE;
3312 	} else if (is_mimo(&rate)) {
3313 		num_rates = IWL_MVM_RS_INITIAL_MIMO_NUM_RATES;
3314 		num_retries = IWL_MVM_RS_HT_VHT_RETRIES_PER_RATE;
3315 	} else {
3316 		num_rates = IWL_MVM_RS_INITIAL_LEGACY_NUM_RATES;
3317 		num_retries = IWL_MVM_RS_INITIAL_LEGACY_RETRIES;
3318 		toggle_ant = true;
3319 	}
3320 
3321 	rs_fill_rates_for_column(mvm, lq_sta, &rate, lq_cmd->rs_table, &index,
3322 				 num_rates, num_retries, valid_tx_ant,
3323 				 toggle_ant);
3324 
3325 	rs_get_lower_rate_down_column(lq_sta, &rate);
3326 
3327 	if (is_siso(&rate)) {
3328 		num_rates = IWL_MVM_RS_SECONDARY_SISO_NUM_RATES;
3329 		num_retries = IWL_MVM_RS_SECONDARY_SISO_RETRIES;
3330 		lq_cmd->mimo_delim = index;
3331 	} else if (is_legacy(&rate)) {
3332 		num_rates = IWL_MVM_RS_SECONDARY_LEGACY_NUM_RATES;
3333 		num_retries = IWL_MVM_RS_SECONDARY_LEGACY_RETRIES;
3334 	} else {
3335 		WARN_ON_ONCE(1);
3336 	}
3337 
3338 	toggle_ant = true;
3339 
3340 	rs_fill_rates_for_column(mvm, lq_sta, &rate, lq_cmd->rs_table, &index,
3341 				 num_rates, num_retries, valid_tx_ant,
3342 				 toggle_ant);
3343 
3344 	rs_get_lower_rate_down_column(lq_sta, &rate);
3345 
3346 	num_rates = IWL_MVM_RS_SECONDARY_LEGACY_NUM_RATES;
3347 	num_retries = IWL_MVM_RS_SECONDARY_LEGACY_RETRIES;
3348 
3349 	rs_fill_rates_for_column(mvm, lq_sta, &rate, lq_cmd->rs_table, &index,
3350 				 num_rates, num_retries, valid_tx_ant,
3351 				 toggle_ant);
3352 
3353 }
3354 
3355 struct rs_bfer_active_iter_data {
3356 	struct ieee80211_sta *exclude_sta;
3357 	struct iwl_mvm_sta *bfer_mvmsta;
3358 };
3359 
3360 static void rs_bfer_active_iter(void *_data,
3361 				struct ieee80211_sta *sta)
3362 {
3363 	struct rs_bfer_active_iter_data *data = _data;
3364 	struct iwl_mvm_sta *mvmsta = iwl_mvm_sta_from_mac80211(sta);
3365 	struct iwl_lq_cmd *lq_cmd = &mvmsta->lq_sta.lq;
3366 	u32 ss_params = le32_to_cpu(lq_cmd->ss_params);
3367 
3368 	if (sta == data->exclude_sta)
3369 		return;
3370 
3371 	/* The current sta has BFER allowed */
3372 	if (ss_params & LQ_SS_BFER_ALLOWED) {
3373 		WARN_ON_ONCE(data->bfer_mvmsta != NULL);
3374 
3375 		data->bfer_mvmsta = mvmsta;
3376 	}
3377 }
3378 
3379 static int rs_bfer_priority(struct iwl_mvm_sta *sta)
3380 {
3381 	int prio = -1;
3382 	enum nl80211_iftype viftype = ieee80211_vif_type_p2p(sta->vif);
3383 
3384 	switch (viftype) {
3385 	case NL80211_IFTYPE_AP:
3386 	case NL80211_IFTYPE_P2P_GO:
3387 		prio = 3;
3388 		break;
3389 	case NL80211_IFTYPE_P2P_CLIENT:
3390 		prio = 2;
3391 		break;
3392 	case NL80211_IFTYPE_STATION:
3393 		prio = 1;
3394 		break;
3395 	default:
3396 		WARN_ONCE(true, "viftype %d sta_id %d", viftype, sta->sta_id);
3397 		prio = -1;
3398 	}
3399 
3400 	return prio;
3401 }
3402 
3403 /* Returns >0 if sta1 has a higher BFER priority compared to sta2 */
3404 static int rs_bfer_priority_cmp(struct iwl_mvm_sta *sta1,
3405 				struct iwl_mvm_sta *sta2)
3406 {
3407 	int prio1 = rs_bfer_priority(sta1);
3408 	int prio2 = rs_bfer_priority(sta2);
3409 
3410 	if (prio1 > prio2)
3411 		return 1;
3412 	if (prio1 < prio2)
3413 		return -1;
3414 	return 0;
3415 }
3416 
3417 static void rs_set_lq_ss_params(struct iwl_mvm *mvm,
3418 				struct ieee80211_sta *sta,
3419 				struct iwl_lq_sta *lq_sta,
3420 				const struct rs_rate *initial_rate)
3421 {
3422 	struct iwl_lq_cmd *lq_cmd = &lq_sta->lq;
3423 	struct iwl_mvm_sta *mvmsta = iwl_mvm_sta_from_mac80211(sta);
3424 	struct rs_bfer_active_iter_data data = {
3425 		.exclude_sta = sta,
3426 		.bfer_mvmsta = NULL,
3427 	};
3428 	struct iwl_mvm_sta *bfer_mvmsta = NULL;
3429 	u32 ss_params = LQ_SS_PARAMS_VALID;
3430 
3431 	if (!iwl_mvm_bt_coex_is_mimo_allowed(mvm, sta))
3432 		goto out;
3433 
3434 #ifdef CONFIG_MAC80211_DEBUGFS
3435 	/* Check if forcing the decision is configured.
3436 	 * Note that SISO is forced by not allowing STBC or BFER
3437 	 */
3438 	if (lq_sta->pers.ss_force == RS_SS_FORCE_STBC)
3439 		ss_params |= (LQ_SS_STBC_1SS_ALLOWED | LQ_SS_FORCE);
3440 	else if (lq_sta->pers.ss_force == RS_SS_FORCE_BFER)
3441 		ss_params |= (LQ_SS_BFER_ALLOWED | LQ_SS_FORCE);
3442 
3443 	if (lq_sta->pers.ss_force != RS_SS_FORCE_NONE) {
3444 		IWL_DEBUG_RATE(mvm, "Forcing single stream Tx decision %d\n",
3445 			       lq_sta->pers.ss_force);
3446 		goto out;
3447 	}
3448 #endif
3449 
3450 	if (lq_sta->stbc_capable)
3451 		ss_params |= LQ_SS_STBC_1SS_ALLOWED;
3452 
3453 	if (!lq_sta->bfer_capable)
3454 		goto out;
3455 
3456 	ieee80211_iterate_stations_atomic(mvm->hw,
3457 					  rs_bfer_active_iter,
3458 					  &data);
3459 	bfer_mvmsta = data.bfer_mvmsta;
3460 
3461 	/* This code is safe as it doesn't run concurrently for different
3462 	 * stations. This is guaranteed by the fact that calls to
3463 	 * ieee80211_tx_status wouldn't run concurrently for a single HW.
3464 	 */
3465 	if (!bfer_mvmsta) {
3466 		IWL_DEBUG_RATE(mvm, "No sta with BFER allowed found. Allow\n");
3467 
3468 		ss_params |= LQ_SS_BFER_ALLOWED;
3469 		goto out;
3470 	}
3471 
3472 	IWL_DEBUG_RATE(mvm, "Found existing sta %d with BFER activated\n",
3473 		       bfer_mvmsta->sta_id);
3474 
3475 	/* Disallow BFER on another STA if active and we're a higher priority */
3476 	if (rs_bfer_priority_cmp(mvmsta, bfer_mvmsta) > 0) {
3477 		struct iwl_lq_cmd *bfersta_lq_cmd = &bfer_mvmsta->lq_sta.lq;
3478 		u32 bfersta_ss_params = le32_to_cpu(bfersta_lq_cmd->ss_params);
3479 
3480 		bfersta_ss_params &= ~LQ_SS_BFER_ALLOWED;
3481 		bfersta_lq_cmd->ss_params = cpu_to_le32(bfersta_ss_params);
3482 		iwl_mvm_send_lq_cmd(mvm, bfersta_lq_cmd, false);
3483 
3484 		ss_params |= LQ_SS_BFER_ALLOWED;
3485 		IWL_DEBUG_RATE(mvm,
3486 			       "Lower priority BFER sta found (%d). Switch BFER\n",
3487 			       bfer_mvmsta->sta_id);
3488 	}
3489 out:
3490 	lq_cmd->ss_params = cpu_to_le32(ss_params);
3491 }
3492 
3493 static void rs_fill_lq_cmd(struct iwl_mvm *mvm,
3494 			   struct ieee80211_sta *sta,
3495 			   struct iwl_lq_sta *lq_sta,
3496 			   const struct rs_rate *initial_rate)
3497 {
3498 	struct iwl_lq_cmd *lq_cmd = &lq_sta->lq;
3499 	struct iwl_mvm_sta *mvmsta;
3500 	struct iwl_mvm_vif *mvmvif;
3501 
3502 	lq_cmd->agg_disable_start_th = IWL_MVM_RS_AGG_DISABLE_START;
3503 	lq_cmd->agg_time_limit =
3504 		cpu_to_le16(IWL_MVM_RS_AGG_TIME_LIMIT);
3505 
3506 #ifdef CONFIG_MAC80211_DEBUGFS
3507 	if (lq_sta->pers.dbg_fixed_rate) {
3508 		rs_build_rates_table_from_fixed(mvm, lq_cmd,
3509 						lq_sta->band,
3510 						lq_sta->pers.dbg_fixed_rate);
3511 		return;
3512 	}
3513 #endif
3514 	if (WARN_ON_ONCE(!sta || !initial_rate))
3515 		return;
3516 
3517 	rs_build_rates_table(mvm, sta, lq_sta, initial_rate);
3518 
3519 	if (fw_has_api(&mvm->fw->ucode_capa, IWL_UCODE_TLV_API_LQ_SS_PARAMS))
3520 		rs_set_lq_ss_params(mvm, sta, lq_sta, initial_rate);
3521 
3522 	mvmsta = iwl_mvm_sta_from_mac80211(sta);
3523 	mvmvif = iwl_mvm_vif_from_mac80211(mvmsta->vif);
3524 
3525 	if (num_of_ant(initial_rate->ant) == 1)
3526 		lq_cmd->single_stream_ant_msk = initial_rate->ant;
3527 
3528 	lq_cmd->agg_frame_cnt_limit = mvmsta->max_agg_bufsize;
3529 
3530 	/*
3531 	 * In case of low latency, tell the firmware to leave a frame in the
3532 	 * Tx Fifo so that it can start a transaction in the same TxOP. This
3533 	 * basically allows the firmware to send bursts.
3534 	 */
3535 	if (iwl_mvm_vif_low_latency(mvmvif))
3536 		lq_cmd->agg_frame_cnt_limit--;
3537 
3538 	if (mvmsta->vif->p2p)
3539 		lq_cmd->flags |= LQ_FLAG_USE_RTS_MSK;
3540 
3541 	lq_cmd->agg_time_limit =
3542 			cpu_to_le16(iwl_mvm_coex_agg_time_limit(mvm, sta));
3543 }
3544 
3545 static void *rs_alloc(struct ieee80211_hw *hw, struct dentry *debugfsdir)
3546 {
3547 	return hw->priv;
3548 }
3549 /* rate scale requires free function to be implemented */
3550 static void rs_free(void *mvm_rate)
3551 {
3552 	return;
3553 }
3554 
3555 static void rs_free_sta(void *mvm_r, struct ieee80211_sta *sta,
3556 			void *mvm_sta)
3557 {
3558 	struct iwl_op_mode *op_mode __maybe_unused = mvm_r;
3559 	struct iwl_mvm *mvm __maybe_unused = IWL_OP_MODE_GET_MVM(op_mode);
3560 
3561 	IWL_DEBUG_RATE(mvm, "enter\n");
3562 	IWL_DEBUG_RATE(mvm, "leave\n");
3563 }
3564 
3565 #ifdef CONFIG_MAC80211_DEBUGFS
3566 int rs_pretty_print_rate(char *buf, const u32 rate)
3567 {
3568 
3569 	char *type, *bw;
3570 	u8 mcs = 0, nss = 0;
3571 	u8 ant = (rate & RATE_MCS_ANT_ABC_MSK) >> RATE_MCS_ANT_POS;
3572 
3573 	if (!(rate & RATE_MCS_HT_MSK) &&
3574 	    !(rate & RATE_MCS_VHT_MSK)) {
3575 		int index = iwl_hwrate_to_plcp_idx(rate);
3576 
3577 		return sprintf(buf, "Legacy | ANT: %s Rate: %s Mbps\n",
3578 			       rs_pretty_ant(ant),
3579 			       index == IWL_RATE_INVALID ? "BAD" :
3580 			       iwl_rate_mcs[index].mbps);
3581 	}
3582 
3583 	if (rate & RATE_MCS_VHT_MSK) {
3584 		type = "VHT";
3585 		mcs = rate & RATE_VHT_MCS_RATE_CODE_MSK;
3586 		nss = ((rate & RATE_VHT_MCS_NSS_MSK)
3587 		       >> RATE_VHT_MCS_NSS_POS) + 1;
3588 	} else if (rate & RATE_MCS_HT_MSK) {
3589 		type = "HT";
3590 		mcs = rate & RATE_HT_MCS_INDEX_MSK;
3591 	} else {
3592 		type = "Unknown"; /* shouldn't happen */
3593 	}
3594 
3595 	switch (rate & RATE_MCS_CHAN_WIDTH_MSK) {
3596 	case RATE_MCS_CHAN_WIDTH_20:
3597 		bw = "20Mhz";
3598 		break;
3599 	case RATE_MCS_CHAN_WIDTH_40:
3600 		bw = "40Mhz";
3601 		break;
3602 	case RATE_MCS_CHAN_WIDTH_80:
3603 		bw = "80Mhz";
3604 		break;
3605 	case RATE_MCS_CHAN_WIDTH_160:
3606 		bw = "160Mhz";
3607 		break;
3608 	default:
3609 		bw = "BAD BW";
3610 	}
3611 
3612 	return sprintf(buf, "%s | ANT: %s BW: %s MCS: %d NSS: %d %s%s%s%s%s\n",
3613 		       type, rs_pretty_ant(ant), bw, mcs, nss,
3614 		       (rate & RATE_MCS_SGI_MSK) ? "SGI " : "NGI ",
3615 		       (rate & RATE_MCS_HT_STBC_MSK) ? "STBC " : "",
3616 		       (rate & RATE_MCS_LDPC_MSK) ? "LDPC " : "",
3617 		       (rate & RATE_MCS_BF_MSK) ? "BF " : "",
3618 		       (rate & RATE_MCS_ZLF_MSK) ? "ZLF " : "");
3619 }
3620 
3621 /**
3622  * Program the device to use fixed rate for frame transmit
3623  * This is for debugging/testing only
3624  * once the device start use fixed rate, we need to reload the module
3625  * to being back the normal operation.
3626  */
3627 static void rs_program_fix_rate(struct iwl_mvm *mvm,
3628 				struct iwl_lq_sta *lq_sta)
3629 {
3630 	lq_sta->active_legacy_rate = 0x0FFF;	/* 1 - 54 MBits, includes CCK */
3631 	lq_sta->active_siso_rate   = 0x1FD0;	/* 6 - 60 MBits, no 9, no CCK */
3632 	lq_sta->active_mimo2_rate  = 0x1FD0;	/* 6 - 60 MBits, no 9, no CCK */
3633 
3634 	IWL_DEBUG_RATE(mvm, "sta_id %d rate 0x%X\n",
3635 		       lq_sta->lq.sta_id, lq_sta->pers.dbg_fixed_rate);
3636 
3637 	if (lq_sta->pers.dbg_fixed_rate) {
3638 		rs_fill_lq_cmd(mvm, NULL, lq_sta, NULL);
3639 		iwl_mvm_send_lq_cmd(lq_sta->pers.drv, &lq_sta->lq, false);
3640 	}
3641 }
3642 
3643 static ssize_t rs_sta_dbgfs_scale_table_write(struct file *file,
3644 			const char __user *user_buf, size_t count, loff_t *ppos)
3645 {
3646 	struct iwl_lq_sta *lq_sta = file->private_data;
3647 	struct iwl_mvm *mvm;
3648 	char buf[64];
3649 	size_t buf_size;
3650 	u32 parsed_rate;
3651 
3652 	mvm = lq_sta->pers.drv;
3653 	memset(buf, 0, sizeof(buf));
3654 	buf_size = min(count, sizeof(buf) -  1);
3655 	if (copy_from_user(buf, user_buf, buf_size))
3656 		return -EFAULT;
3657 
3658 	if (sscanf(buf, "%x", &parsed_rate) == 1)
3659 		lq_sta->pers.dbg_fixed_rate = parsed_rate;
3660 	else
3661 		lq_sta->pers.dbg_fixed_rate = 0;
3662 
3663 	rs_program_fix_rate(mvm, lq_sta);
3664 
3665 	return count;
3666 }
3667 
3668 static ssize_t rs_sta_dbgfs_scale_table_read(struct file *file,
3669 			char __user *user_buf, size_t count, loff_t *ppos)
3670 {
3671 	char *buff;
3672 	int desc = 0;
3673 	int i = 0;
3674 	ssize_t ret;
3675 
3676 	struct iwl_lq_sta *lq_sta = file->private_data;
3677 	struct iwl_mvm_sta *mvmsta =
3678 		container_of(lq_sta, struct iwl_mvm_sta, lq_sta);
3679 	struct iwl_mvm *mvm;
3680 	struct iwl_scale_tbl_info *tbl = &(lq_sta->lq_info[lq_sta->active_tbl]);
3681 	struct rs_rate *rate = &tbl->rate;
3682 	u32 ss_params;
3683 
3684 	mvm = lq_sta->pers.drv;
3685 	buff = kmalloc(2048, GFP_KERNEL);
3686 	if (!buff)
3687 		return -ENOMEM;
3688 
3689 	desc += sprintf(buff+desc, "sta_id %d\n", lq_sta->lq.sta_id);
3690 	desc += sprintf(buff+desc, "failed=%d success=%d rate=0%lX\n",
3691 			lq_sta->total_failed, lq_sta->total_success,
3692 			lq_sta->active_legacy_rate);
3693 	desc += sprintf(buff+desc, "fixed rate 0x%X\n",
3694 			lq_sta->pers.dbg_fixed_rate);
3695 	desc += sprintf(buff+desc, "valid_tx_ant %s%s%s\n",
3696 	    (iwl_mvm_get_valid_tx_ant(mvm) & ANT_A) ? "ANT_A," : "",
3697 	    (iwl_mvm_get_valid_tx_ant(mvm) & ANT_B) ? "ANT_B," : "",
3698 	    (iwl_mvm_get_valid_tx_ant(mvm) & ANT_C) ? "ANT_C" : "");
3699 	desc += sprintf(buff+desc, "lq type %s\n",
3700 			(is_legacy(rate)) ? "legacy" :
3701 			is_vht(rate) ? "VHT" : "HT");
3702 	if (!is_legacy(rate)) {
3703 		desc += sprintf(buff + desc, " %s",
3704 		   (is_siso(rate)) ? "SISO" : "MIMO2");
3705 		desc += sprintf(buff + desc, " %s",
3706 				(is_ht20(rate)) ? "20MHz" :
3707 				(is_ht40(rate)) ? "40MHz" :
3708 				(is_ht80(rate)) ? "80Mhz" : "BAD BW");
3709 		desc += sprintf(buff + desc, " %s %s %s %s\n",
3710 				(rate->sgi) ? "SGI" : "NGI",
3711 				(rate->ldpc) ? "LDPC" : "BCC",
3712 				(lq_sta->is_agg) ? "AGG on" : "",
3713 				(mvmsta->tlc_amsdu) ? "AMSDU on" : "");
3714 	}
3715 	desc += sprintf(buff+desc, "last tx rate=0x%X\n",
3716 			lq_sta->last_rate_n_flags);
3717 	desc += sprintf(buff+desc,
3718 			"general: flags=0x%X mimo-d=%d s-ant=0x%x d-ant=0x%x\n",
3719 			lq_sta->lq.flags,
3720 			lq_sta->lq.mimo_delim,
3721 			lq_sta->lq.single_stream_ant_msk,
3722 			lq_sta->lq.dual_stream_ant_msk);
3723 
3724 	desc += sprintf(buff+desc,
3725 			"agg: time_limit=%d dist_start_th=%d frame_cnt_limit=%d\n",
3726 			le16_to_cpu(lq_sta->lq.agg_time_limit),
3727 			lq_sta->lq.agg_disable_start_th,
3728 			lq_sta->lq.agg_frame_cnt_limit);
3729 
3730 	desc += sprintf(buff+desc, "reduced tpc=%d\n", lq_sta->lq.reduced_tpc);
3731 	ss_params = le32_to_cpu(lq_sta->lq.ss_params);
3732 	desc += sprintf(buff+desc, "single stream params: %s%s%s%s\n",
3733 			(ss_params & LQ_SS_PARAMS_VALID) ?
3734 			"VALID" : "INVALID",
3735 			(ss_params & LQ_SS_BFER_ALLOWED) ?
3736 			", BFER" : "",
3737 			(ss_params & LQ_SS_STBC_1SS_ALLOWED) ?
3738 			", STBC" : "",
3739 			(ss_params & LQ_SS_FORCE) ?
3740 			", FORCE" : "");
3741 	desc += sprintf(buff+desc,
3742 			"Start idx [0]=0x%x [1]=0x%x [2]=0x%x [3]=0x%x\n",
3743 			lq_sta->lq.initial_rate_index[0],
3744 			lq_sta->lq.initial_rate_index[1],
3745 			lq_sta->lq.initial_rate_index[2],
3746 			lq_sta->lq.initial_rate_index[3]);
3747 
3748 	for (i = 0; i < LINK_QUAL_MAX_RETRY_NUM; i++) {
3749 		u32 r = le32_to_cpu(lq_sta->lq.rs_table[i]);
3750 
3751 		desc += sprintf(buff+desc, " rate[%d] 0x%X ", i, r);
3752 		desc += rs_pretty_print_rate(buff+desc, r);
3753 	}
3754 
3755 	ret = simple_read_from_buffer(user_buf, count, ppos, buff, desc);
3756 	kfree(buff);
3757 	return ret;
3758 }
3759 
3760 static const struct file_operations rs_sta_dbgfs_scale_table_ops = {
3761 	.write = rs_sta_dbgfs_scale_table_write,
3762 	.read = rs_sta_dbgfs_scale_table_read,
3763 	.open = simple_open,
3764 	.llseek = default_llseek,
3765 };
3766 static ssize_t rs_sta_dbgfs_stats_table_read(struct file *file,
3767 			char __user *user_buf, size_t count, loff_t *ppos)
3768 {
3769 	char *buff;
3770 	int desc = 0;
3771 	int i, j;
3772 	ssize_t ret;
3773 	struct iwl_scale_tbl_info *tbl;
3774 	struct rs_rate *rate;
3775 	struct iwl_lq_sta *lq_sta = file->private_data;
3776 
3777 	buff = kmalloc(1024, GFP_KERNEL);
3778 	if (!buff)
3779 		return -ENOMEM;
3780 
3781 	for (i = 0; i < LQ_SIZE; i++) {
3782 		tbl = &(lq_sta->lq_info[i]);
3783 		rate = &tbl->rate;
3784 		desc += sprintf(buff+desc,
3785 				"%s type=%d SGI=%d BW=%s DUP=0\n"
3786 				"index=%d\n",
3787 				lq_sta->active_tbl == i ? "*" : "x",
3788 				rate->type,
3789 				rate->sgi,
3790 				is_ht20(rate) ? "20Mhz" :
3791 				is_ht40(rate) ? "40Mhz" :
3792 				is_ht80(rate) ? "80Mhz" : "ERR",
3793 				rate->index);
3794 		for (j = 0; j < IWL_RATE_COUNT; j++) {
3795 			desc += sprintf(buff+desc,
3796 				"counter=%d success=%d %%=%d\n",
3797 				tbl->win[j].counter,
3798 				tbl->win[j].success_counter,
3799 				tbl->win[j].success_ratio);
3800 		}
3801 	}
3802 	ret = simple_read_from_buffer(user_buf, count, ppos, buff, desc);
3803 	kfree(buff);
3804 	return ret;
3805 }
3806 
3807 static const struct file_operations rs_sta_dbgfs_stats_table_ops = {
3808 	.read = rs_sta_dbgfs_stats_table_read,
3809 	.open = simple_open,
3810 	.llseek = default_llseek,
3811 };
3812 
3813 static ssize_t rs_sta_dbgfs_drv_tx_stats_read(struct file *file,
3814 					      char __user *user_buf,
3815 					      size_t count, loff_t *ppos)
3816 {
3817 	static const char * const column_name[] = {
3818 		[RS_COLUMN_LEGACY_ANT_A] = "LEGACY_ANT_A",
3819 		[RS_COLUMN_LEGACY_ANT_B] = "LEGACY_ANT_B",
3820 		[RS_COLUMN_SISO_ANT_A] = "SISO_ANT_A",
3821 		[RS_COLUMN_SISO_ANT_B] = "SISO_ANT_B",
3822 		[RS_COLUMN_SISO_ANT_A_SGI] = "SISO_ANT_A_SGI",
3823 		[RS_COLUMN_SISO_ANT_B_SGI] = "SISO_ANT_B_SGI",
3824 		[RS_COLUMN_MIMO2] = "MIMO2",
3825 		[RS_COLUMN_MIMO2_SGI] = "MIMO2_SGI",
3826 	};
3827 
3828 	static const char * const rate_name[] = {
3829 		[IWL_RATE_1M_INDEX] = "1M",
3830 		[IWL_RATE_2M_INDEX] = "2M",
3831 		[IWL_RATE_5M_INDEX] = "5.5M",
3832 		[IWL_RATE_11M_INDEX] = "11M",
3833 		[IWL_RATE_6M_INDEX] = "6M|MCS0",
3834 		[IWL_RATE_9M_INDEX] = "9M",
3835 		[IWL_RATE_12M_INDEX] = "12M|MCS1",
3836 		[IWL_RATE_18M_INDEX] = "18M|MCS2",
3837 		[IWL_RATE_24M_INDEX] = "24M|MCS3",
3838 		[IWL_RATE_36M_INDEX] = "36M|MCS4",
3839 		[IWL_RATE_48M_INDEX] = "48M|MCS5",
3840 		[IWL_RATE_54M_INDEX] = "54M|MCS6",
3841 		[IWL_RATE_MCS_7_INDEX] = "MCS7",
3842 		[IWL_RATE_MCS_8_INDEX] = "MCS8",
3843 		[IWL_RATE_MCS_9_INDEX] = "MCS9",
3844 	};
3845 
3846 	char *buff, *pos, *endpos;
3847 	int col, rate;
3848 	ssize_t ret;
3849 	struct iwl_lq_sta *lq_sta = file->private_data;
3850 	struct rs_rate_stats *stats;
3851 	static const size_t bufsz = 1024;
3852 
3853 	buff = kmalloc(bufsz, GFP_KERNEL);
3854 	if (!buff)
3855 		return -ENOMEM;
3856 
3857 	pos = buff;
3858 	endpos = pos + bufsz;
3859 
3860 	pos += scnprintf(pos, endpos - pos, "COLUMN,");
3861 	for (rate = 0; rate < IWL_RATE_COUNT; rate++)
3862 		pos += scnprintf(pos, endpos - pos, "%s,", rate_name[rate]);
3863 	pos += scnprintf(pos, endpos - pos, "\n");
3864 
3865 	for (col = 0; col < RS_COLUMN_COUNT; col++) {
3866 		pos += scnprintf(pos, endpos - pos,
3867 				 "%s,", column_name[col]);
3868 
3869 		for (rate = 0; rate < IWL_RATE_COUNT; rate++) {
3870 			stats = &(lq_sta->pers.tx_stats[col][rate]);
3871 			pos += scnprintf(pos, endpos - pos,
3872 					 "%llu/%llu,",
3873 					 stats->success,
3874 					 stats->total);
3875 		}
3876 		pos += scnprintf(pos, endpos - pos, "\n");
3877 	}
3878 
3879 	ret = simple_read_from_buffer(user_buf, count, ppos, buff, pos - buff);
3880 	kfree(buff);
3881 	return ret;
3882 }
3883 
3884 static ssize_t rs_sta_dbgfs_drv_tx_stats_write(struct file *file,
3885 					       const char __user *user_buf,
3886 					       size_t count, loff_t *ppos)
3887 {
3888 	struct iwl_lq_sta *lq_sta = file->private_data;
3889 	memset(lq_sta->pers.tx_stats, 0, sizeof(lq_sta->pers.tx_stats));
3890 
3891 	return count;
3892 }
3893 
3894 static const struct file_operations rs_sta_dbgfs_drv_tx_stats_ops = {
3895 	.read = rs_sta_dbgfs_drv_tx_stats_read,
3896 	.write = rs_sta_dbgfs_drv_tx_stats_write,
3897 	.open = simple_open,
3898 	.llseek = default_llseek,
3899 };
3900 
3901 static ssize_t iwl_dbgfs_ss_force_read(struct file *file,
3902 				       char __user *user_buf,
3903 				       size_t count, loff_t *ppos)
3904 {
3905 	struct iwl_lq_sta *lq_sta = file->private_data;
3906 	char buf[12];
3907 	int bufsz = sizeof(buf);
3908 	int pos = 0;
3909 	static const char * const ss_force_name[] = {
3910 		[RS_SS_FORCE_NONE] = "none",
3911 		[RS_SS_FORCE_STBC] = "stbc",
3912 		[RS_SS_FORCE_BFER] = "bfer",
3913 		[RS_SS_FORCE_SISO] = "siso",
3914 	};
3915 
3916 	pos += scnprintf(buf+pos, bufsz-pos, "%s\n",
3917 			 ss_force_name[lq_sta->pers.ss_force]);
3918 	return simple_read_from_buffer(user_buf, count, ppos, buf, pos);
3919 }
3920 
3921 static ssize_t iwl_dbgfs_ss_force_write(struct iwl_lq_sta *lq_sta, char *buf,
3922 					size_t count, loff_t *ppos)
3923 {
3924 	struct iwl_mvm *mvm = lq_sta->pers.drv;
3925 	int ret = 0;
3926 
3927 	if (!strncmp("none", buf, 4)) {
3928 		lq_sta->pers.ss_force = RS_SS_FORCE_NONE;
3929 	} else if (!strncmp("siso", buf, 4)) {
3930 		lq_sta->pers.ss_force = RS_SS_FORCE_SISO;
3931 	} else if (!strncmp("stbc", buf, 4)) {
3932 		if (lq_sta->stbc_capable) {
3933 			lq_sta->pers.ss_force = RS_SS_FORCE_STBC;
3934 		} else {
3935 			IWL_ERR(mvm,
3936 				"can't force STBC. peer doesn't support\n");
3937 			ret = -EINVAL;
3938 		}
3939 	} else if (!strncmp("bfer", buf, 4)) {
3940 		if (lq_sta->bfer_capable) {
3941 			lq_sta->pers.ss_force = RS_SS_FORCE_BFER;
3942 		} else {
3943 			IWL_ERR(mvm,
3944 				"can't force BFER. peer doesn't support\n");
3945 			ret = -EINVAL;
3946 		}
3947 	} else {
3948 		IWL_ERR(mvm, "valid values none|siso|stbc|bfer\n");
3949 		ret = -EINVAL;
3950 	}
3951 	return ret ?: count;
3952 }
3953 
3954 #define MVM_DEBUGFS_READ_WRITE_FILE_OPS(name, bufsz) \
3955 	_MVM_DEBUGFS_READ_WRITE_FILE_OPS(name, bufsz, struct iwl_lq_sta)
3956 #define MVM_DEBUGFS_ADD_FILE_RS(name, parent, mode) do {		\
3957 		if (!debugfs_create_file(#name, mode, parent, lq_sta,	\
3958 					 &iwl_dbgfs_##name##_ops))	\
3959 			goto err;					\
3960 	} while (0)
3961 
3962 MVM_DEBUGFS_READ_WRITE_FILE_OPS(ss_force, 32);
3963 
3964 static void rs_add_debugfs(void *mvm, void *priv_sta, struct dentry *dir)
3965 {
3966 	struct iwl_lq_sta *lq_sta = priv_sta;
3967 	struct iwl_mvm_sta *mvmsta;
3968 
3969 	mvmsta = container_of(lq_sta, struct iwl_mvm_sta, lq_sta);
3970 
3971 	if (!mvmsta->vif)
3972 		return;
3973 
3974 	debugfs_create_file("rate_scale_table", S_IRUSR | S_IWUSR, dir,
3975 			    lq_sta, &rs_sta_dbgfs_scale_table_ops);
3976 	debugfs_create_file("rate_stats_table", S_IRUSR, dir,
3977 			    lq_sta, &rs_sta_dbgfs_stats_table_ops);
3978 	debugfs_create_file("drv_tx_stats", S_IRUSR | S_IWUSR, dir,
3979 			    lq_sta, &rs_sta_dbgfs_drv_tx_stats_ops);
3980 	debugfs_create_u8("tx_agg_tid_enable", S_IRUSR | S_IWUSR, dir,
3981 			  &lq_sta->tx_agg_tid_en);
3982 	debugfs_create_u8("reduced_tpc", S_IRUSR | S_IWUSR, dir,
3983 			  &lq_sta->pers.dbg_fixed_txp_reduction);
3984 
3985 	MVM_DEBUGFS_ADD_FILE_RS(ss_force, dir, S_IRUSR | S_IWUSR);
3986 	return;
3987 err:
3988 	IWL_ERR((struct iwl_mvm *)mvm, "Can't create debugfs entity\n");
3989 }
3990 
3991 static void rs_remove_debugfs(void *mvm, void *mvm_sta)
3992 {
3993 }
3994 #endif
3995 
3996 /*
3997  * Initialization of rate scaling information is done by driver after
3998  * the station is added. Since mac80211 calls this function before a
3999  * station is added we ignore it.
4000  */
4001 static void rs_rate_init_stub(void *mvm_r,
4002 			      struct ieee80211_supported_band *sband,
4003 			      struct cfg80211_chan_def *chandef,
4004 			      struct ieee80211_sta *sta, void *mvm_sta)
4005 {
4006 }
4007 
4008 static const struct rate_control_ops rs_mvm_ops = {
4009 	.name = RS_NAME,
4010 	.tx_status = rs_mac80211_tx_status,
4011 	.get_rate = rs_get_rate,
4012 	.rate_init = rs_rate_init_stub,
4013 	.alloc = rs_alloc,
4014 	.free = rs_free,
4015 	.alloc_sta = rs_alloc_sta,
4016 	.free_sta = rs_free_sta,
4017 	.rate_update = rs_rate_update,
4018 #ifdef CONFIG_MAC80211_DEBUGFS
4019 	.add_sta_debugfs = rs_add_debugfs,
4020 	.remove_sta_debugfs = rs_remove_debugfs,
4021 #endif
4022 };
4023 
4024 int iwl_mvm_rate_control_register(void)
4025 {
4026 	return ieee80211_rate_control_register(&rs_mvm_ops);
4027 }
4028 
4029 void iwl_mvm_rate_control_unregister(void)
4030 {
4031 	ieee80211_rate_control_unregister(&rs_mvm_ops);
4032 }
4033 
4034 /**
4035  * iwl_mvm_tx_protection - Gets LQ command, change it to enable/disable
4036  * Tx protection, according to this request and previous requests,
4037  * and send the LQ command.
4038  * @mvmsta: The station
4039  * @enable: Enable Tx protection?
4040  */
4041 int iwl_mvm_tx_protection(struct iwl_mvm *mvm, struct iwl_mvm_sta *mvmsta,
4042 			  bool enable)
4043 {
4044 	struct iwl_lq_cmd *lq = &mvmsta->lq_sta.lq;
4045 
4046 	lockdep_assert_held(&mvm->mutex);
4047 
4048 	if (enable) {
4049 		if (mvmsta->tx_protection == 0)
4050 			lq->flags |= LQ_FLAG_USE_RTS_MSK;
4051 		mvmsta->tx_protection++;
4052 	} else {
4053 		mvmsta->tx_protection--;
4054 		if (mvmsta->tx_protection == 0)
4055 			lq->flags &= ~LQ_FLAG_USE_RTS_MSK;
4056 	}
4057 
4058 	return iwl_mvm_send_lq_cmd(mvm, lq, false);
4059 }
4060