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