xref: /openbmc/linux/drivers/net/wireless/realtek/rtw89/phy.c (revision c9933d494c54f72290831191c09bb8488bfd5905)
1 // SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
2 /* Copyright(c) 2019-2020  Realtek Corporation
3  */
4 
5 #include "debug.h"
6 #include "fw.h"
7 #include "mac.h"
8 #include "phy.h"
9 #include "ps.h"
10 #include "reg.h"
11 #include "sar.h"
12 #include "coex.h"
13 
14 static u16 get_max_amsdu_len(struct rtw89_dev *rtwdev,
15 			     const struct rtw89_ra_report *report)
16 {
17 	const struct rate_info *txrate = &report->txrate;
18 	u32 bit_rate = report->bit_rate;
19 	u8 mcs;
20 
21 	/* lower than ofdm, do not aggregate */
22 	if (bit_rate < 550)
23 		return 1;
24 
25 	/* prevent hardware rate fallback to G mode rate */
26 	if (txrate->flags & RATE_INFO_FLAGS_MCS)
27 		mcs = txrate->mcs & 0x07;
28 	else if (txrate->flags & (RATE_INFO_FLAGS_VHT_MCS | RATE_INFO_FLAGS_HE_MCS))
29 		mcs = txrate->mcs;
30 	else
31 		mcs = 0;
32 
33 	if (mcs <= 2)
34 		return 1;
35 
36 	/* lower than 20M vht 2ss mcs8, make it small */
37 	if (bit_rate < 1800)
38 		return 1200;
39 
40 	/* lower than 40M vht 2ss mcs9, make it medium */
41 	if (bit_rate < 4000)
42 		return 2600;
43 
44 	/* not yet 80M vht 2ss mcs8/9, make it twice regular packet size */
45 	if (bit_rate < 7000)
46 		return 3500;
47 
48 	return rtwdev->chip->max_amsdu_limit;
49 }
50 
51 static u64 get_mcs_ra_mask(u16 mcs_map, u8 highest_mcs, u8 gap)
52 {
53 	u64 ra_mask = 0;
54 	u8 mcs_cap;
55 	int i, nss;
56 
57 	for (i = 0, nss = 12; i < 4; i++, mcs_map >>= 2, nss += 12) {
58 		mcs_cap = mcs_map & 0x3;
59 		switch (mcs_cap) {
60 		case 2:
61 			ra_mask |= GENMASK_ULL(highest_mcs, 0) << nss;
62 			break;
63 		case 1:
64 			ra_mask |= GENMASK_ULL(highest_mcs - gap, 0) << nss;
65 			break;
66 		case 0:
67 			ra_mask |= GENMASK_ULL(highest_mcs - gap * 2, 0) << nss;
68 			break;
69 		default:
70 			break;
71 		}
72 	}
73 
74 	return ra_mask;
75 }
76 
77 static u64 get_he_ra_mask(struct ieee80211_sta *sta)
78 {
79 	struct ieee80211_sta_he_cap cap = sta->deflink.he_cap;
80 	u16 mcs_map;
81 
82 	switch (sta->deflink.bandwidth) {
83 	case IEEE80211_STA_RX_BW_160:
84 		if (cap.he_cap_elem.phy_cap_info[0] &
85 		    IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_80PLUS80_MHZ_IN_5G)
86 			mcs_map = le16_to_cpu(cap.he_mcs_nss_supp.rx_mcs_80p80);
87 		else
88 			mcs_map = le16_to_cpu(cap.he_mcs_nss_supp.rx_mcs_160);
89 		break;
90 	default:
91 		mcs_map = le16_to_cpu(cap.he_mcs_nss_supp.rx_mcs_80);
92 	}
93 
94 	/* MCS11, MCS9, MCS7 */
95 	return get_mcs_ra_mask(mcs_map, 11, 2);
96 }
97 
98 #define RA_FLOOR_TABLE_SIZE	7
99 #define RA_FLOOR_UP_GAP		3
100 static u64 rtw89_phy_ra_mask_rssi(struct rtw89_dev *rtwdev, u8 rssi,
101 				  u8 ratr_state)
102 {
103 	u8 rssi_lv_t[RA_FLOOR_TABLE_SIZE] = {30, 44, 48, 52, 56, 60, 100};
104 	u8 rssi_lv = 0;
105 	u8 i;
106 
107 	rssi >>= 1;
108 	for (i = 0; i < RA_FLOOR_TABLE_SIZE; i++) {
109 		if (i >= ratr_state)
110 			rssi_lv_t[i] += RA_FLOOR_UP_GAP;
111 		if (rssi < rssi_lv_t[i]) {
112 			rssi_lv = i;
113 			break;
114 		}
115 	}
116 	if (rssi_lv == 0)
117 		return 0xffffffffffffffffULL;
118 	else if (rssi_lv == 1)
119 		return 0xfffffffffffffff0ULL;
120 	else if (rssi_lv == 2)
121 		return 0xffffffffffffefe0ULL;
122 	else if (rssi_lv == 3)
123 		return 0xffffffffffffcfc0ULL;
124 	else if (rssi_lv == 4)
125 		return 0xffffffffffff8f80ULL;
126 	else if (rssi_lv >= 5)
127 		return 0xffffffffffff0f00ULL;
128 
129 	return 0xffffffffffffffffULL;
130 }
131 
132 static u64 rtw89_phy_ra_mask_recover(u64 ra_mask, u64 ra_mask_bak)
133 {
134 	if ((ra_mask & ~(RA_MASK_CCK_RATES | RA_MASK_OFDM_RATES)) == 0)
135 		ra_mask |= (ra_mask_bak & ~(RA_MASK_CCK_RATES | RA_MASK_OFDM_RATES));
136 
137 	if (ra_mask == 0)
138 		ra_mask |= (ra_mask_bak & (RA_MASK_CCK_RATES | RA_MASK_OFDM_RATES));
139 
140 	return ra_mask;
141 }
142 
143 static u64 rtw89_phy_ra_mask_cfg(struct rtw89_dev *rtwdev, struct rtw89_sta *rtwsta)
144 {
145 	struct rtw89_hal *hal = &rtwdev->hal;
146 	struct ieee80211_sta *sta = rtwsta_to_sta(rtwsta);
147 	struct cfg80211_bitrate_mask *mask = &rtwsta->mask;
148 	enum nl80211_band band;
149 	u64 cfg_mask;
150 
151 	if (!rtwsta->use_cfg_mask)
152 		return -1;
153 
154 	switch (hal->current_band_type) {
155 	case RTW89_BAND_2G:
156 		band = NL80211_BAND_2GHZ;
157 		cfg_mask = u64_encode_bits(mask->control[NL80211_BAND_2GHZ].legacy,
158 					   RA_MASK_CCK_RATES | RA_MASK_OFDM_RATES);
159 		break;
160 	case RTW89_BAND_5G:
161 		band = NL80211_BAND_5GHZ;
162 		cfg_mask = u64_encode_bits(mask->control[NL80211_BAND_5GHZ].legacy,
163 					   RA_MASK_OFDM_RATES);
164 		break;
165 	case RTW89_BAND_6G:
166 		band = NL80211_BAND_6GHZ;
167 		cfg_mask = u64_encode_bits(mask->control[NL80211_BAND_6GHZ].legacy,
168 					   RA_MASK_OFDM_RATES);
169 		break;
170 	default:
171 		rtw89_warn(rtwdev, "unhandled band type %d\n", hal->current_band_type);
172 		return -1;
173 	}
174 
175 	if (sta->deflink.he_cap.has_he) {
176 		cfg_mask |= u64_encode_bits(mask->control[band].he_mcs[0],
177 					    RA_MASK_HE_1SS_RATES);
178 		cfg_mask |= u64_encode_bits(mask->control[band].he_mcs[1],
179 					    RA_MASK_HE_2SS_RATES);
180 	} else if (sta->deflink.vht_cap.vht_supported) {
181 		cfg_mask |= u64_encode_bits(mask->control[band].vht_mcs[0],
182 					    RA_MASK_VHT_1SS_RATES);
183 		cfg_mask |= u64_encode_bits(mask->control[band].vht_mcs[1],
184 					    RA_MASK_VHT_2SS_RATES);
185 	} else if (sta->deflink.ht_cap.ht_supported) {
186 		cfg_mask |= u64_encode_bits(mask->control[band].ht_mcs[0],
187 					    RA_MASK_HT_1SS_RATES);
188 		cfg_mask |= u64_encode_bits(mask->control[band].ht_mcs[1],
189 					    RA_MASK_HT_2SS_RATES);
190 	}
191 
192 	return cfg_mask;
193 }
194 
195 static const u64
196 rtw89_ra_mask_ht_rates[4] = {RA_MASK_HT_1SS_RATES, RA_MASK_HT_2SS_RATES,
197 			     RA_MASK_HT_3SS_RATES, RA_MASK_HT_4SS_RATES};
198 static const u64
199 rtw89_ra_mask_vht_rates[4] = {RA_MASK_VHT_1SS_RATES, RA_MASK_VHT_2SS_RATES,
200 			      RA_MASK_VHT_3SS_RATES, RA_MASK_VHT_4SS_RATES};
201 static const u64
202 rtw89_ra_mask_he_rates[4] = {RA_MASK_HE_1SS_RATES, RA_MASK_HE_2SS_RATES,
203 			     RA_MASK_HE_3SS_RATES, RA_MASK_HE_4SS_RATES};
204 
205 static void rtw89_phy_ra_sta_update(struct rtw89_dev *rtwdev,
206 				    struct ieee80211_sta *sta, bool csi)
207 {
208 	struct rtw89_sta *rtwsta = (struct rtw89_sta *)sta->drv_priv;
209 	struct rtw89_vif *rtwvif = rtwsta->rtwvif;
210 	struct rtw89_phy_rate_pattern *rate_pattern = &rtwvif->rate_pattern;
211 	struct rtw89_ra_info *ra = &rtwsta->ra;
212 	const u64 *high_rate_masks = rtw89_ra_mask_ht_rates;
213 	u8 rssi = ewma_rssi_read(&rtwsta->avg_rssi);
214 	u64 ra_mask = 0;
215 	u64 ra_mask_bak;
216 	u8 mode = 0;
217 	u8 csi_mode = RTW89_RA_RPT_MODE_LEGACY;
218 	u8 bw_mode = 0;
219 	u8 stbc_en = 0;
220 	u8 ldpc_en = 0;
221 	u8 i;
222 	bool sgi = false;
223 
224 	memset(ra, 0, sizeof(*ra));
225 	/* Set the ra mask from sta's capability */
226 	if (sta->deflink.he_cap.has_he) {
227 		mode |= RTW89_RA_MODE_HE;
228 		csi_mode = RTW89_RA_RPT_MODE_HE;
229 		ra_mask |= get_he_ra_mask(sta);
230 		high_rate_masks = rtw89_ra_mask_he_rates;
231 		if (sta->deflink.he_cap.he_cap_elem.phy_cap_info[2] &
232 		    IEEE80211_HE_PHY_CAP2_STBC_RX_UNDER_80MHZ)
233 			stbc_en = 1;
234 		if (sta->deflink.he_cap.he_cap_elem.phy_cap_info[1] &
235 		    IEEE80211_HE_PHY_CAP1_LDPC_CODING_IN_PAYLOAD)
236 			ldpc_en = 1;
237 	} else if (sta->deflink.vht_cap.vht_supported) {
238 		u16 mcs_map = le16_to_cpu(sta->deflink.vht_cap.vht_mcs.rx_mcs_map);
239 
240 		mode |= RTW89_RA_MODE_VHT;
241 		csi_mode = RTW89_RA_RPT_MODE_VHT;
242 		/* MCS9, MCS8, MCS7 */
243 		ra_mask |= get_mcs_ra_mask(mcs_map, 9, 1);
244 		high_rate_masks = rtw89_ra_mask_vht_rates;
245 		if (sta->deflink.vht_cap.cap & IEEE80211_VHT_CAP_RXSTBC_MASK)
246 			stbc_en = 1;
247 		if (sta->deflink.vht_cap.cap & IEEE80211_VHT_CAP_RXLDPC)
248 			ldpc_en = 1;
249 	} else if (sta->deflink.ht_cap.ht_supported) {
250 		mode |= RTW89_RA_MODE_HT;
251 		csi_mode = RTW89_RA_RPT_MODE_HT;
252 		ra_mask |= ((u64)sta->deflink.ht_cap.mcs.rx_mask[3] << 48) |
253 			   ((u64)sta->deflink.ht_cap.mcs.rx_mask[2] << 36) |
254 			   (sta->deflink.ht_cap.mcs.rx_mask[1] << 24) |
255 			   (sta->deflink.ht_cap.mcs.rx_mask[0] << 12);
256 		high_rate_masks = rtw89_ra_mask_ht_rates;
257 		if (sta->deflink.ht_cap.cap & IEEE80211_HT_CAP_RX_STBC)
258 			stbc_en = 1;
259 		if (sta->deflink.ht_cap.cap & IEEE80211_HT_CAP_LDPC_CODING)
260 			ldpc_en = 1;
261 	}
262 
263 	switch (rtwdev->hal.current_band_type) {
264 	case RTW89_BAND_2G:
265 		ra_mask |= sta->deflink.supp_rates[NL80211_BAND_2GHZ];
266 		if (sta->deflink.supp_rates[NL80211_BAND_2GHZ] <= 0xf)
267 			mode |= RTW89_RA_MODE_CCK;
268 		else
269 			mode |= RTW89_RA_MODE_CCK | RTW89_RA_MODE_OFDM;
270 		break;
271 	case RTW89_BAND_5G:
272 		ra_mask |= (u64)sta->deflink.supp_rates[NL80211_BAND_5GHZ] << 4;
273 		mode |= RTW89_RA_MODE_OFDM;
274 		break;
275 	case RTW89_BAND_6G:
276 		ra_mask |= (u64)sta->deflink.supp_rates[NL80211_BAND_6GHZ] << 4;
277 		mode |= RTW89_RA_MODE_OFDM;
278 		break;
279 	default:
280 		rtw89_err(rtwdev, "Unknown band type\n");
281 		break;
282 	}
283 
284 	ra_mask_bak = ra_mask;
285 
286 	if (mode >= RTW89_RA_MODE_HT) {
287 		u64 mask = 0;
288 		for (i = 0; i < rtwdev->hal.tx_nss; i++)
289 			mask |= high_rate_masks[i];
290 		if (mode & RTW89_RA_MODE_OFDM)
291 			mask |= RA_MASK_SUBOFDM_RATES;
292 		if (mode & RTW89_RA_MODE_CCK)
293 			mask |= RA_MASK_SUBCCK_RATES;
294 		ra_mask &= mask;
295 	} else if (mode & RTW89_RA_MODE_OFDM) {
296 		ra_mask &= (RA_MASK_OFDM_RATES | RA_MASK_SUBCCK_RATES);
297 	}
298 
299 	if (mode != RTW89_RA_MODE_CCK)
300 		ra_mask &= rtw89_phy_ra_mask_rssi(rtwdev, rssi, 0);
301 
302 	ra_mask = rtw89_phy_ra_mask_recover(ra_mask, ra_mask_bak);
303 	ra_mask &= rtw89_phy_ra_mask_cfg(rtwdev, rtwsta);
304 
305 	switch (sta->deflink.bandwidth) {
306 	case IEEE80211_STA_RX_BW_160:
307 		bw_mode = RTW89_CHANNEL_WIDTH_160;
308 		sgi = sta->deflink.vht_cap.vht_supported &&
309 		      (sta->deflink.vht_cap.cap & IEEE80211_VHT_CAP_SHORT_GI_160);
310 		break;
311 	case IEEE80211_STA_RX_BW_80:
312 		bw_mode = RTW89_CHANNEL_WIDTH_80;
313 		sgi = sta->deflink.vht_cap.vht_supported &&
314 		      (sta->deflink.vht_cap.cap & IEEE80211_VHT_CAP_SHORT_GI_80);
315 		break;
316 	case IEEE80211_STA_RX_BW_40:
317 		bw_mode = RTW89_CHANNEL_WIDTH_40;
318 		sgi = sta->deflink.ht_cap.ht_supported &&
319 		      (sta->deflink.ht_cap.cap & IEEE80211_HT_CAP_SGI_40);
320 		break;
321 	default:
322 		bw_mode = RTW89_CHANNEL_WIDTH_20;
323 		sgi = sta->deflink.ht_cap.ht_supported &&
324 		      (sta->deflink.ht_cap.cap & IEEE80211_HT_CAP_SGI_20);
325 		break;
326 	}
327 
328 	if (sta->deflink.he_cap.he_cap_elem.phy_cap_info[3] &
329 	    IEEE80211_HE_PHY_CAP3_DCM_MAX_CONST_RX_16_QAM)
330 		ra->dcm_cap = 1;
331 
332 	if (rate_pattern->enable) {
333 		ra_mask = rtw89_phy_ra_mask_cfg(rtwdev, rtwsta);
334 		ra_mask &= rate_pattern->ra_mask;
335 		mode = rate_pattern->ra_mode;
336 	}
337 
338 	ra->bw_cap = bw_mode;
339 	ra->mode_ctrl = mode;
340 	ra->macid = rtwsta->mac_id;
341 	ra->stbc_cap = stbc_en;
342 	ra->ldpc_cap = ldpc_en;
343 	ra->ss_num = min(sta->deflink.rx_nss, rtwdev->hal.tx_nss) - 1;
344 	ra->en_sgi = sgi;
345 	ra->ra_mask = ra_mask;
346 
347 	if (!csi)
348 		return;
349 
350 	ra->fixed_csi_rate_en = false;
351 	ra->ra_csi_rate_en = true;
352 	ra->cr_tbl_sel = false;
353 	ra->band_num = rtwvif->phy_idx;
354 	ra->csi_bw = bw_mode;
355 	ra->csi_gi_ltf = RTW89_GILTF_LGI_4XHE32;
356 	ra->csi_mcs_ss_idx = 5;
357 	ra->csi_mode = csi_mode;
358 }
359 
360 void rtw89_phy_ra_updata_sta(struct rtw89_dev *rtwdev, struct ieee80211_sta *sta)
361 {
362 	struct rtw89_sta *rtwsta = (struct rtw89_sta *)sta->drv_priv;
363 	struct rtw89_ra_info *ra = &rtwsta->ra;
364 
365 	rtw89_phy_ra_sta_update(rtwdev, sta, false);
366 	ra->upd_mask = 1;
367 	rtw89_debug(rtwdev, RTW89_DBG_RA,
368 		    "ra updat: macid = %d, bw = %d, nss = %d, gi = %d %d",
369 		    ra->macid,
370 		    ra->bw_cap,
371 		    ra->ss_num,
372 		    ra->en_sgi,
373 		    ra->giltf);
374 
375 	rtw89_fw_h2c_ra(rtwdev, ra, false);
376 }
377 
378 static bool __check_rate_pattern(struct rtw89_phy_rate_pattern *next,
379 				 u16 rate_base, u64 ra_mask, u8 ra_mode,
380 				 u32 rate_ctrl, u32 ctrl_skip, bool force)
381 {
382 	u8 n, c;
383 
384 	if (rate_ctrl == ctrl_skip)
385 		return true;
386 
387 	n = hweight32(rate_ctrl);
388 	if (n == 0)
389 		return true;
390 
391 	if (force && n != 1)
392 		return false;
393 
394 	if (next->enable)
395 		return false;
396 
397 	c = __fls(rate_ctrl);
398 	next->rate = rate_base + c;
399 	next->ra_mode = ra_mode;
400 	next->ra_mask = ra_mask;
401 	next->enable = true;
402 
403 	return true;
404 }
405 
406 void rtw89_phy_rate_pattern_vif(struct rtw89_dev *rtwdev,
407 				struct ieee80211_vif *vif,
408 				const struct cfg80211_bitrate_mask *mask)
409 {
410 	struct ieee80211_supported_band *sband;
411 	struct rtw89_vif *rtwvif = (struct rtw89_vif *)vif->drv_priv;
412 	struct rtw89_phy_rate_pattern next_pattern = {0};
413 	static const u16 hw_rate_he[] = {RTW89_HW_RATE_HE_NSS1_MCS0,
414 					 RTW89_HW_RATE_HE_NSS2_MCS0,
415 					 RTW89_HW_RATE_HE_NSS3_MCS0,
416 					 RTW89_HW_RATE_HE_NSS4_MCS0};
417 	static const u16 hw_rate_vht[] = {RTW89_HW_RATE_VHT_NSS1_MCS0,
418 					  RTW89_HW_RATE_VHT_NSS2_MCS0,
419 					  RTW89_HW_RATE_VHT_NSS3_MCS0,
420 					  RTW89_HW_RATE_VHT_NSS4_MCS0};
421 	static const u16 hw_rate_ht[] = {RTW89_HW_RATE_MCS0,
422 					 RTW89_HW_RATE_MCS8,
423 					 RTW89_HW_RATE_MCS16,
424 					 RTW89_HW_RATE_MCS24};
425 	u8 band = rtwdev->hal.current_band_type;
426 	u8 tx_nss = rtwdev->hal.tx_nss;
427 	u8 i;
428 
429 	for (i = 0; i < tx_nss; i++)
430 		if (!__check_rate_pattern(&next_pattern, hw_rate_he[i],
431 					  RA_MASK_HE_RATES, RTW89_RA_MODE_HE,
432 					  mask->control[band].he_mcs[i],
433 					  0, true))
434 			goto out;
435 
436 	for (i = 0; i < tx_nss; i++)
437 		if (!__check_rate_pattern(&next_pattern, hw_rate_vht[i],
438 					  RA_MASK_VHT_RATES, RTW89_RA_MODE_VHT,
439 					  mask->control[band].vht_mcs[i],
440 					  0, true))
441 			goto out;
442 
443 	for (i = 0; i < tx_nss; i++)
444 		if (!__check_rate_pattern(&next_pattern, hw_rate_ht[i],
445 					  RA_MASK_HT_RATES, RTW89_RA_MODE_HT,
446 					  mask->control[band].ht_mcs[i],
447 					  0, true))
448 			goto out;
449 
450 	/* lagacy cannot be empty for nl80211_parse_tx_bitrate_mask, and
451 	 * require at least one basic rate for ieee80211_set_bitrate_mask,
452 	 * so the decision just depends on if all bitrates are set or not.
453 	 */
454 	sband = rtwdev->hw->wiphy->bands[band];
455 	if (band == RTW89_BAND_2G) {
456 		if (!__check_rate_pattern(&next_pattern, RTW89_HW_RATE_CCK1,
457 					  RA_MASK_CCK_RATES | RA_MASK_OFDM_RATES,
458 					  RTW89_RA_MODE_CCK | RTW89_RA_MODE_OFDM,
459 					  mask->control[band].legacy,
460 					  BIT(sband->n_bitrates) - 1, false))
461 			goto out;
462 	} else {
463 		if (!__check_rate_pattern(&next_pattern, RTW89_HW_RATE_OFDM6,
464 					  RA_MASK_OFDM_RATES, RTW89_RA_MODE_OFDM,
465 					  mask->control[band].legacy,
466 					  BIT(sband->n_bitrates) - 1, false))
467 			goto out;
468 	}
469 
470 	if (!next_pattern.enable)
471 		goto out;
472 
473 	rtwvif->rate_pattern = next_pattern;
474 	rtw89_debug(rtwdev, RTW89_DBG_RA,
475 		    "configure pattern: rate 0x%x, mask 0x%llx, mode 0x%x\n",
476 		    next_pattern.rate,
477 		    next_pattern.ra_mask,
478 		    next_pattern.ra_mode);
479 	return;
480 
481 out:
482 	rtwvif->rate_pattern.enable = false;
483 	rtw89_debug(rtwdev, RTW89_DBG_RA, "unset rate pattern\n");
484 }
485 
486 static void rtw89_phy_ra_updata_sta_iter(void *data, struct ieee80211_sta *sta)
487 {
488 	struct rtw89_dev *rtwdev = (struct rtw89_dev *)data;
489 
490 	rtw89_phy_ra_updata_sta(rtwdev, sta);
491 }
492 
493 void rtw89_phy_ra_update(struct rtw89_dev *rtwdev)
494 {
495 	ieee80211_iterate_stations_atomic(rtwdev->hw,
496 					  rtw89_phy_ra_updata_sta_iter,
497 					  rtwdev);
498 }
499 
500 void rtw89_phy_ra_assoc(struct rtw89_dev *rtwdev, struct ieee80211_sta *sta)
501 {
502 	struct rtw89_sta *rtwsta = (struct rtw89_sta *)sta->drv_priv;
503 	struct rtw89_ra_info *ra = &rtwsta->ra;
504 	u8 rssi = ewma_rssi_read(&rtwsta->avg_rssi) >> RSSI_FACTOR;
505 	bool csi = rtw89_sta_has_beamformer_cap(sta);
506 
507 	rtw89_phy_ra_sta_update(rtwdev, sta, csi);
508 
509 	if (rssi > 40)
510 		ra->init_rate_lv = 1;
511 	else if (rssi > 20)
512 		ra->init_rate_lv = 2;
513 	else if (rssi > 1)
514 		ra->init_rate_lv = 3;
515 	else
516 		ra->init_rate_lv = 0;
517 	ra->upd_all = 1;
518 	rtw89_debug(rtwdev, RTW89_DBG_RA,
519 		    "ra assoc: macid = %d, mode = %d, bw = %d, nss = %d, lv = %d",
520 		    ra->macid,
521 		    ra->mode_ctrl,
522 		    ra->bw_cap,
523 		    ra->ss_num,
524 		    ra->init_rate_lv);
525 	rtw89_debug(rtwdev, RTW89_DBG_RA,
526 		    "ra assoc: dcm = %d, er = %d, ldpc = %d, stbc = %d, gi = %d %d",
527 		    ra->dcm_cap,
528 		    ra->er_cap,
529 		    ra->ldpc_cap,
530 		    ra->stbc_cap,
531 		    ra->en_sgi,
532 		    ra->giltf);
533 
534 	rtw89_fw_h2c_ra(rtwdev, ra, csi);
535 }
536 
537 u8 rtw89_phy_get_txsc(struct rtw89_dev *rtwdev,
538 		      struct rtw89_channel_params *param,
539 		      enum rtw89_bandwidth dbw)
540 {
541 	enum rtw89_bandwidth cbw = param->bandwidth;
542 	u8 pri_ch = param->primary_chan;
543 	u8 central_ch = param->center_chan;
544 	u8 txsc_idx = 0;
545 	u8 tmp = 0;
546 
547 	if (cbw == dbw || cbw == RTW89_CHANNEL_WIDTH_20)
548 		return txsc_idx;
549 
550 	switch (cbw) {
551 	case RTW89_CHANNEL_WIDTH_40:
552 		txsc_idx = pri_ch > central_ch ? 1 : 2;
553 		break;
554 	case RTW89_CHANNEL_WIDTH_80:
555 		if (dbw == RTW89_CHANNEL_WIDTH_20) {
556 			if (pri_ch > central_ch)
557 				txsc_idx = (pri_ch - central_ch) >> 1;
558 			else
559 				txsc_idx = ((central_ch - pri_ch) >> 1) + 1;
560 		} else {
561 			txsc_idx = pri_ch > central_ch ? 9 : 10;
562 		}
563 		break;
564 	case RTW89_CHANNEL_WIDTH_160:
565 		if (pri_ch > central_ch)
566 			tmp = (pri_ch - central_ch) >> 1;
567 		else
568 			tmp = ((central_ch - pri_ch) >> 1) + 1;
569 
570 		if (dbw == RTW89_CHANNEL_WIDTH_20) {
571 			txsc_idx = tmp;
572 		} else if (dbw == RTW89_CHANNEL_WIDTH_40) {
573 			if (tmp == 1 || tmp == 3)
574 				txsc_idx = 9;
575 			else if (tmp == 5 || tmp == 7)
576 				txsc_idx = 11;
577 			else if (tmp == 2 || tmp == 4)
578 				txsc_idx = 10;
579 			else if (tmp == 6 || tmp == 8)
580 				txsc_idx = 12;
581 			else
582 				return 0xff;
583 		} else {
584 			txsc_idx = pri_ch > central_ch ? 13 : 14;
585 		}
586 		break;
587 	case RTW89_CHANNEL_WIDTH_80_80:
588 		if (dbw == RTW89_CHANNEL_WIDTH_20) {
589 			if (pri_ch > central_ch)
590 				txsc_idx = (10 - (pri_ch - central_ch)) >> 1;
591 			else
592 				txsc_idx = ((central_ch - pri_ch) >> 1) + 5;
593 		} else if (dbw == RTW89_CHANNEL_WIDTH_40) {
594 			txsc_idx = pri_ch > central_ch ? 10 : 12;
595 		} else {
596 			txsc_idx = 14;
597 		}
598 		break;
599 	default:
600 		break;
601 	}
602 
603 	return txsc_idx;
604 }
605 EXPORT_SYMBOL(rtw89_phy_get_txsc);
606 
607 static bool rtw89_phy_check_swsi_busy(struct rtw89_dev *rtwdev)
608 {
609 	return !!rtw89_phy_read32_mask(rtwdev, R_SWSI_V1, B_SWSI_W_BUSY_V1) ||
610 	       !!rtw89_phy_read32_mask(rtwdev, R_SWSI_V1, B_SWSI_R_BUSY_V1);
611 }
612 
613 u32 rtw89_phy_read_rf(struct rtw89_dev *rtwdev, enum rtw89_rf_path rf_path,
614 		      u32 addr, u32 mask)
615 {
616 	const struct rtw89_chip_info *chip = rtwdev->chip;
617 	const u32 *base_addr = chip->rf_base_addr;
618 	u32 val, direct_addr;
619 
620 	if (rf_path >= rtwdev->chip->rf_path_num) {
621 		rtw89_err(rtwdev, "unsupported rf path (%d)\n", rf_path);
622 		return INV_RF_DATA;
623 	}
624 
625 	addr &= 0xff;
626 	direct_addr = base_addr[rf_path] + (addr << 2);
627 	mask &= RFREG_MASK;
628 
629 	val = rtw89_phy_read32_mask(rtwdev, direct_addr, mask);
630 
631 	return val;
632 }
633 EXPORT_SYMBOL(rtw89_phy_read_rf);
634 
635 static u32 rtw89_phy_read_rf_a(struct rtw89_dev *rtwdev,
636 			       enum rtw89_rf_path rf_path, u32 addr, u32 mask)
637 {
638 	bool busy;
639 	bool done;
640 	u32 val;
641 	int ret;
642 
643 	ret = read_poll_timeout_atomic(rtw89_phy_check_swsi_busy, busy, !busy,
644 				       1, 30, false, rtwdev);
645 	if (ret) {
646 		rtw89_err(rtwdev, "read rf busy swsi\n");
647 		return INV_RF_DATA;
648 	}
649 
650 	mask &= RFREG_MASK;
651 
652 	val = FIELD_PREP(B_SWSI_READ_ADDR_PATH_V1, rf_path) |
653 	      FIELD_PREP(B_SWSI_READ_ADDR_ADDR_V1, addr);
654 	rtw89_phy_write32_mask(rtwdev, R_SWSI_READ_ADDR_V1, B_SWSI_READ_ADDR_V1, val);
655 	udelay(2);
656 
657 	ret = read_poll_timeout_atomic(rtw89_phy_read32_mask, done, done, 1,
658 				       30, false, rtwdev, R_SWSI_V1,
659 				       B_SWSI_R_DATA_DONE_V1);
660 	if (ret) {
661 		rtw89_err(rtwdev, "read swsi busy\n");
662 		return INV_RF_DATA;
663 	}
664 
665 	return rtw89_phy_read32_mask(rtwdev, R_SWSI_V1, mask);
666 }
667 
668 u32 rtw89_phy_read_rf_v1(struct rtw89_dev *rtwdev, enum rtw89_rf_path rf_path,
669 			 u32 addr, u32 mask)
670 {
671 	bool ad_sel = FIELD_GET(RTW89_RF_ADDR_ADSEL_MASK, addr);
672 
673 	if (rf_path >= rtwdev->chip->rf_path_num) {
674 		rtw89_err(rtwdev, "unsupported rf path (%d)\n", rf_path);
675 		return INV_RF_DATA;
676 	}
677 
678 	if (ad_sel)
679 		return rtw89_phy_read_rf(rtwdev, rf_path, addr, mask);
680 	else
681 		return rtw89_phy_read_rf_a(rtwdev, rf_path, addr, mask);
682 }
683 EXPORT_SYMBOL(rtw89_phy_read_rf_v1);
684 
685 bool rtw89_phy_write_rf(struct rtw89_dev *rtwdev, enum rtw89_rf_path rf_path,
686 			u32 addr, u32 mask, u32 data)
687 {
688 	const struct rtw89_chip_info *chip = rtwdev->chip;
689 	const u32 *base_addr = chip->rf_base_addr;
690 	u32 direct_addr;
691 
692 	if (rf_path >= rtwdev->chip->rf_path_num) {
693 		rtw89_err(rtwdev, "unsupported rf path (%d)\n", rf_path);
694 		return false;
695 	}
696 
697 	addr &= 0xff;
698 	direct_addr = base_addr[rf_path] + (addr << 2);
699 	mask &= RFREG_MASK;
700 
701 	rtw89_phy_write32_mask(rtwdev, direct_addr, mask, data);
702 
703 	/* delay to ensure writing properly */
704 	udelay(1);
705 
706 	return true;
707 }
708 EXPORT_SYMBOL(rtw89_phy_write_rf);
709 
710 static bool rtw89_phy_write_rf_a(struct rtw89_dev *rtwdev,
711 				 enum rtw89_rf_path rf_path, u32 addr, u32 mask,
712 				 u32 data)
713 {
714 	u8 bit_shift;
715 	u32 val;
716 	bool busy, b_msk_en = false;
717 	int ret;
718 
719 	ret = read_poll_timeout_atomic(rtw89_phy_check_swsi_busy, busy, !busy,
720 				       1, 30, false, rtwdev);
721 	if (ret) {
722 		rtw89_err(rtwdev, "write rf busy swsi\n");
723 		return false;
724 	}
725 
726 	data &= RFREG_MASK;
727 	mask &= RFREG_MASK;
728 
729 	if (mask != RFREG_MASK) {
730 		b_msk_en = true;
731 		rtw89_phy_write32_mask(rtwdev, R_SWSI_BIT_MASK_V1, RFREG_MASK,
732 				       mask);
733 		bit_shift = __ffs(mask);
734 		data = (data << bit_shift) & RFREG_MASK;
735 	}
736 
737 	val = FIELD_PREP(B_SWSI_DATA_BIT_MASK_EN_V1, b_msk_en) |
738 	      FIELD_PREP(B_SWSI_DATA_PATH_V1, rf_path) |
739 	      FIELD_PREP(B_SWSI_DATA_ADDR_V1, addr) |
740 	      FIELD_PREP(B_SWSI_DATA_VAL_V1, data);
741 
742 	rtw89_phy_write32_mask(rtwdev, R_SWSI_DATA_V1, MASKDWORD, val);
743 
744 	return true;
745 }
746 
747 bool rtw89_phy_write_rf_v1(struct rtw89_dev *rtwdev, enum rtw89_rf_path rf_path,
748 			   u32 addr, u32 mask, u32 data)
749 {
750 	bool ad_sel = FIELD_GET(RTW89_RF_ADDR_ADSEL_MASK, addr);
751 
752 	if (rf_path >= rtwdev->chip->rf_path_num) {
753 		rtw89_err(rtwdev, "unsupported rf path (%d)\n", rf_path);
754 		return false;
755 	}
756 
757 	if (ad_sel)
758 		return rtw89_phy_write_rf(rtwdev, rf_path, addr, mask, data);
759 	else
760 		return rtw89_phy_write_rf_a(rtwdev, rf_path, addr, mask, data);
761 }
762 EXPORT_SYMBOL(rtw89_phy_write_rf_v1);
763 
764 static void rtw89_phy_bb_reset(struct rtw89_dev *rtwdev,
765 			       enum rtw89_phy_idx phy_idx)
766 {
767 	const struct rtw89_chip_info *chip = rtwdev->chip;
768 
769 	chip->ops->bb_reset(rtwdev, phy_idx);
770 }
771 
772 static void rtw89_phy_config_bb_reg(struct rtw89_dev *rtwdev,
773 				    const struct rtw89_reg2_def *reg,
774 				    enum rtw89_rf_path rf_path,
775 				    void *extra_data)
776 {
777 	if (reg->addr == 0xfe)
778 		mdelay(50);
779 	else if (reg->addr == 0xfd)
780 		mdelay(5);
781 	else if (reg->addr == 0xfc)
782 		mdelay(1);
783 	else if (reg->addr == 0xfb)
784 		udelay(50);
785 	else if (reg->addr == 0xfa)
786 		udelay(5);
787 	else if (reg->addr == 0xf9)
788 		udelay(1);
789 	else
790 		rtw89_phy_write32(rtwdev, reg->addr, reg->data);
791 }
792 
793 union rtw89_phy_bb_gain_arg {
794 	u32 addr;
795 	struct {
796 		union {
797 			u8 type;
798 			struct {
799 				u8 rxsc_start:4;
800 				u8 bw:4;
801 			};
802 		};
803 		u8 path;
804 		u8 gain_band;
805 		u8 cfg_type;
806 	};
807 } __packed;
808 
809 static void
810 rtw89_phy_cfg_bb_gain_error(struct rtw89_dev *rtwdev,
811 			    union rtw89_phy_bb_gain_arg arg, u32 data)
812 {
813 	struct rtw89_phy_bb_gain_info *gain = &rtwdev->bb_gain;
814 	u8 type = arg.type;
815 	u8 path = arg.path;
816 	u8 gband = arg.gain_band;
817 	int i;
818 
819 	switch (type) {
820 	case 0:
821 		for (i = 0; i < 4; i++, data >>= 8)
822 			gain->lna_gain[gband][path][i] = data & 0xff;
823 		break;
824 	case 1:
825 		for (i = 4; i < 7; i++, data >>= 8)
826 			gain->lna_gain[gband][path][i] = data & 0xff;
827 		break;
828 	case 2:
829 		for (i = 0; i < 2; i++, data >>= 8)
830 			gain->tia_gain[gband][path][i] = data & 0xff;
831 		break;
832 	default:
833 		rtw89_warn(rtwdev,
834 			   "bb gain error {0x%x:0x%x} with unknown type: %d\n",
835 			   arg.addr, data, type);
836 		break;
837 	}
838 }
839 
840 enum rtw89_phy_bb_rxsc_start_idx {
841 	RTW89_BB_RXSC_START_IDX_FULL = 0,
842 	RTW89_BB_RXSC_START_IDX_20 = 1,
843 	RTW89_BB_RXSC_START_IDX_20_1 = 5,
844 	RTW89_BB_RXSC_START_IDX_40 = 9,
845 	RTW89_BB_RXSC_START_IDX_80 = 13,
846 };
847 
848 static void
849 rtw89_phy_cfg_bb_rpl_ofst(struct rtw89_dev *rtwdev,
850 			  union rtw89_phy_bb_gain_arg arg, u32 data)
851 {
852 	struct rtw89_phy_bb_gain_info *gain = &rtwdev->bb_gain;
853 	u8 rxsc_start = arg.rxsc_start;
854 	u8 bw = arg.bw;
855 	u8 path = arg.path;
856 	u8 gband = arg.gain_band;
857 	u8 rxsc;
858 	s8 ofst;
859 	int i;
860 
861 	switch (bw) {
862 	case RTW89_CHANNEL_WIDTH_20:
863 		gain->rpl_ofst_20[gband][path] = (s8)data;
864 		break;
865 	case RTW89_CHANNEL_WIDTH_40:
866 		if (rxsc_start == RTW89_BB_RXSC_START_IDX_FULL) {
867 			gain->rpl_ofst_40[gband][path][0] = (s8)data;
868 		} else if (rxsc_start == RTW89_BB_RXSC_START_IDX_20) {
869 			for (i = 0; i < 2; i++, data >>= 8) {
870 				rxsc = RTW89_BB_RXSC_START_IDX_20 + i;
871 				ofst = (s8)(data & 0xff);
872 				gain->rpl_ofst_40[gband][path][rxsc] = ofst;
873 			}
874 		}
875 		break;
876 	case RTW89_CHANNEL_WIDTH_80:
877 		if (rxsc_start == RTW89_BB_RXSC_START_IDX_FULL) {
878 			gain->rpl_ofst_80[gband][path][0] = (s8)data;
879 		} else if (rxsc_start == RTW89_BB_RXSC_START_IDX_20) {
880 			for (i = 0; i < 4; i++, data >>= 8) {
881 				rxsc = RTW89_BB_RXSC_START_IDX_20 + i;
882 				ofst = (s8)(data & 0xff);
883 				gain->rpl_ofst_80[gband][path][rxsc] = ofst;
884 			}
885 		} else if (rxsc_start == RTW89_BB_RXSC_START_IDX_40) {
886 			for (i = 0; i < 2; i++, data >>= 8) {
887 				rxsc = RTW89_BB_RXSC_START_IDX_40 + i;
888 				ofst = (s8)(data & 0xff);
889 				gain->rpl_ofst_80[gband][path][rxsc] = ofst;
890 			}
891 		}
892 		break;
893 	case RTW89_CHANNEL_WIDTH_160:
894 		if (rxsc_start == RTW89_BB_RXSC_START_IDX_FULL) {
895 			gain->rpl_ofst_160[gband][path][0] = (s8)data;
896 		} else if (rxsc_start == RTW89_BB_RXSC_START_IDX_20) {
897 			for (i = 0; i < 4; i++, data >>= 8) {
898 				rxsc = RTW89_BB_RXSC_START_IDX_20 + i;
899 				ofst = (s8)(data & 0xff);
900 				gain->rpl_ofst_160[gband][path][rxsc] = ofst;
901 			}
902 		} else if (rxsc_start == RTW89_BB_RXSC_START_IDX_20_1) {
903 			for (i = 0; i < 4; i++, data >>= 8) {
904 				rxsc = RTW89_BB_RXSC_START_IDX_20_1 + i;
905 				ofst = (s8)(data & 0xff);
906 				gain->rpl_ofst_160[gband][path][rxsc] = ofst;
907 			}
908 		} else if (rxsc_start == RTW89_BB_RXSC_START_IDX_40) {
909 			for (i = 0; i < 4; i++, data >>= 8) {
910 				rxsc = RTW89_BB_RXSC_START_IDX_40 + i;
911 				ofst = (s8)(data & 0xff);
912 				gain->rpl_ofst_160[gband][path][rxsc] = ofst;
913 			}
914 		} else if (rxsc_start == RTW89_BB_RXSC_START_IDX_80) {
915 			for (i = 0; i < 2; i++, data >>= 8) {
916 				rxsc = RTW89_BB_RXSC_START_IDX_80 + i;
917 				ofst = (s8)(data & 0xff);
918 				gain->rpl_ofst_160[gband][path][rxsc] = ofst;
919 			}
920 		}
921 		break;
922 	default:
923 		rtw89_warn(rtwdev,
924 			   "bb rpl ofst {0x%x:0x%x} with unknown bw: %d\n",
925 			   arg.addr, data, bw);
926 		break;
927 	}
928 }
929 
930 static void
931 rtw89_phy_cfg_bb_gain_bypass(struct rtw89_dev *rtwdev,
932 			     union rtw89_phy_bb_gain_arg arg, u32 data)
933 {
934 	struct rtw89_phy_bb_gain_info *gain = &rtwdev->bb_gain;
935 	u8 type = arg.type;
936 	u8 path = arg.path;
937 	u8 gband = arg.gain_band;
938 	int i;
939 
940 	switch (type) {
941 	case 0:
942 		for (i = 0; i < 4; i++, data >>= 8)
943 			gain->lna_gain_bypass[gband][path][i] = data & 0xff;
944 		break;
945 	case 1:
946 		for (i = 4; i < 7; i++, data >>= 8)
947 			gain->lna_gain_bypass[gband][path][i] = data & 0xff;
948 		break;
949 	default:
950 		rtw89_warn(rtwdev,
951 			   "bb gain bypass {0x%x:0x%x} with unknown type: %d\n",
952 			   arg.addr, data, type);
953 		break;
954 	}
955 }
956 
957 static void
958 rtw89_phy_cfg_bb_gain_op1db(struct rtw89_dev *rtwdev,
959 			    union rtw89_phy_bb_gain_arg arg, u32 data)
960 {
961 	struct rtw89_phy_bb_gain_info *gain = &rtwdev->bb_gain;
962 	u8 type = arg.type;
963 	u8 path = arg.path;
964 	u8 gband = arg.gain_band;
965 	int i;
966 
967 	switch (type) {
968 	case 0:
969 		for (i = 0; i < 4; i++, data >>= 8)
970 			gain->lna_op1db[gband][path][i] = data & 0xff;
971 		break;
972 	case 1:
973 		for (i = 4; i < 7; i++, data >>= 8)
974 			gain->lna_op1db[gband][path][i] = data & 0xff;
975 		break;
976 	case 2:
977 		for (i = 0; i < 4; i++, data >>= 8)
978 			gain->tia_lna_op1db[gband][path][i] = data & 0xff;
979 		break;
980 	case 3:
981 		for (i = 4; i < 8; i++, data >>= 8)
982 			gain->tia_lna_op1db[gband][path][i] = data & 0xff;
983 		break;
984 	default:
985 		rtw89_warn(rtwdev,
986 			   "bb gain op1db {0x%x:0x%x} with unknown type: %d\n",
987 			   arg.addr, data, type);
988 		break;
989 	}
990 }
991 
992 static void rtw89_phy_config_bb_gain(struct rtw89_dev *rtwdev,
993 				     const struct rtw89_reg2_def *reg,
994 				     enum rtw89_rf_path rf_path,
995 				     void *extra_data)
996 {
997 	const struct rtw89_chip_info *chip = rtwdev->chip;
998 	union rtw89_phy_bb_gain_arg arg = { .addr = reg->addr };
999 
1000 	if (arg.gain_band >= RTW89_BB_GAIN_BAND_NR)
1001 		return;
1002 
1003 	if (arg.path >= chip->rf_path_num)
1004 		return;
1005 
1006 	if (arg.addr >= 0xf9 && arg.addr <= 0xfe) {
1007 		rtw89_warn(rtwdev, "bb gain table with flow ctrl\n");
1008 		return;
1009 	}
1010 
1011 	switch (arg.cfg_type) {
1012 	case 0:
1013 		rtw89_phy_cfg_bb_gain_error(rtwdev, arg, reg->data);
1014 		break;
1015 	case 1:
1016 		rtw89_phy_cfg_bb_rpl_ofst(rtwdev, arg, reg->data);
1017 		break;
1018 	case 2:
1019 		rtw89_phy_cfg_bb_gain_bypass(rtwdev, arg, reg->data);
1020 		break;
1021 	case 3:
1022 		rtw89_phy_cfg_bb_gain_op1db(rtwdev, arg, reg->data);
1023 		break;
1024 	default:
1025 		rtw89_warn(rtwdev,
1026 			   "bb gain {0x%x:0x%x} with unknown cfg type: %d\n",
1027 			   arg.addr, reg->data, arg.cfg_type);
1028 		break;
1029 	}
1030 }
1031 
1032 static void
1033 rtw89_phy_cofig_rf_reg_store(struct rtw89_dev *rtwdev,
1034 			     const struct rtw89_reg2_def *reg,
1035 			     enum rtw89_rf_path rf_path,
1036 			     struct rtw89_fw_h2c_rf_reg_info *info)
1037 {
1038 	u16 idx = info->curr_idx % RTW89_H2C_RF_PAGE_SIZE;
1039 	u8 page = info->curr_idx / RTW89_H2C_RF_PAGE_SIZE;
1040 
1041 	if (page >= RTW89_H2C_RF_PAGE_NUM) {
1042 		rtw89_warn(rtwdev, "RF parameters exceed size. path=%d, idx=%d",
1043 			   rf_path, info->curr_idx);
1044 		return;
1045 	}
1046 
1047 	info->rtw89_phy_config_rf_h2c[page][idx] =
1048 		cpu_to_le32((reg->addr << 20) | reg->data);
1049 	info->curr_idx++;
1050 }
1051 
1052 static int rtw89_phy_config_rf_reg_fw(struct rtw89_dev *rtwdev,
1053 				      struct rtw89_fw_h2c_rf_reg_info *info)
1054 {
1055 	u16 remain = info->curr_idx;
1056 	u16 len = 0;
1057 	u8 i;
1058 	int ret = 0;
1059 
1060 	if (remain > RTW89_H2C_RF_PAGE_NUM * RTW89_H2C_RF_PAGE_SIZE) {
1061 		rtw89_warn(rtwdev,
1062 			   "rf reg h2c total len %d larger than %d\n",
1063 			   remain, RTW89_H2C_RF_PAGE_NUM * RTW89_H2C_RF_PAGE_SIZE);
1064 		ret = -EINVAL;
1065 		goto out;
1066 	}
1067 
1068 	for (i = 0; i < RTW89_H2C_RF_PAGE_NUM && remain; i++, remain -= len) {
1069 		len = remain > RTW89_H2C_RF_PAGE_SIZE ? RTW89_H2C_RF_PAGE_SIZE : remain;
1070 		ret = rtw89_fw_h2c_rf_reg(rtwdev, info, len * 4, i);
1071 		if (ret)
1072 			goto out;
1073 	}
1074 out:
1075 	info->curr_idx = 0;
1076 
1077 	return ret;
1078 }
1079 
1080 static void rtw89_phy_config_rf_reg(struct rtw89_dev *rtwdev,
1081 				    const struct rtw89_reg2_def *reg,
1082 				    enum rtw89_rf_path rf_path,
1083 				    void *extra_data)
1084 {
1085 	if (reg->addr == 0xfe) {
1086 		mdelay(50);
1087 	} else if (reg->addr == 0xfd) {
1088 		mdelay(5);
1089 	} else if (reg->addr == 0xfc) {
1090 		mdelay(1);
1091 	} else if (reg->addr == 0xfb) {
1092 		udelay(50);
1093 	} else if (reg->addr == 0xfa) {
1094 		udelay(5);
1095 	} else if (reg->addr == 0xf9) {
1096 		udelay(1);
1097 	} else {
1098 		rtw89_write_rf(rtwdev, rf_path, reg->addr, 0xfffff, reg->data);
1099 		rtw89_phy_cofig_rf_reg_store(rtwdev, reg, rf_path,
1100 					     (struct rtw89_fw_h2c_rf_reg_info *)extra_data);
1101 	}
1102 }
1103 
1104 void rtw89_phy_config_rf_reg_v1(struct rtw89_dev *rtwdev,
1105 				const struct rtw89_reg2_def *reg,
1106 				enum rtw89_rf_path rf_path,
1107 				void *extra_data)
1108 {
1109 	rtw89_write_rf(rtwdev, rf_path, reg->addr, RFREG_MASK, reg->data);
1110 
1111 	if (reg->addr < 0x100)
1112 		return;
1113 
1114 	rtw89_phy_cofig_rf_reg_store(rtwdev, reg, rf_path,
1115 				     (struct rtw89_fw_h2c_rf_reg_info *)extra_data);
1116 }
1117 EXPORT_SYMBOL(rtw89_phy_config_rf_reg_v1);
1118 
1119 static int rtw89_phy_sel_headline(struct rtw89_dev *rtwdev,
1120 				  const struct rtw89_phy_table *table,
1121 				  u32 *headline_size, u32 *headline_idx,
1122 				  u8 rfe, u8 cv)
1123 {
1124 	const struct rtw89_reg2_def *reg;
1125 	u32 headline;
1126 	u32 compare, target;
1127 	u8 rfe_para, cv_para;
1128 	u8 cv_max = 0;
1129 	bool case_matched = false;
1130 	u32 i;
1131 
1132 	for (i = 0; i < table->n_regs; i++) {
1133 		reg = &table->regs[i];
1134 		headline = get_phy_headline(reg->addr);
1135 		if (headline != PHY_HEADLINE_VALID)
1136 			break;
1137 	}
1138 	*headline_size = i;
1139 	if (*headline_size == 0)
1140 		return 0;
1141 
1142 	/* case 1: RFE match, CV match */
1143 	compare = get_phy_compare(rfe, cv);
1144 	for (i = 0; i < *headline_size; i++) {
1145 		reg = &table->regs[i];
1146 		target = get_phy_target(reg->addr);
1147 		if (target == compare) {
1148 			*headline_idx = i;
1149 			return 0;
1150 		}
1151 	}
1152 
1153 	/* case 2: RFE match, CV don't care */
1154 	compare = get_phy_compare(rfe, PHY_COND_DONT_CARE);
1155 	for (i = 0; i < *headline_size; i++) {
1156 		reg = &table->regs[i];
1157 		target = get_phy_target(reg->addr);
1158 		if (target == compare) {
1159 			*headline_idx = i;
1160 			return 0;
1161 		}
1162 	}
1163 
1164 	/* case 3: RFE match, CV max in table */
1165 	for (i = 0; i < *headline_size; i++) {
1166 		reg = &table->regs[i];
1167 		rfe_para = get_phy_cond_rfe(reg->addr);
1168 		cv_para = get_phy_cond_cv(reg->addr);
1169 		if (rfe_para == rfe) {
1170 			if (cv_para >= cv_max) {
1171 				cv_max = cv_para;
1172 				*headline_idx = i;
1173 				case_matched = true;
1174 			}
1175 		}
1176 	}
1177 
1178 	if (case_matched)
1179 		return 0;
1180 
1181 	/* case 4: RFE don't care, CV max in table */
1182 	for (i = 0; i < *headline_size; i++) {
1183 		reg = &table->regs[i];
1184 		rfe_para = get_phy_cond_rfe(reg->addr);
1185 		cv_para = get_phy_cond_cv(reg->addr);
1186 		if (rfe_para == PHY_COND_DONT_CARE) {
1187 			if (cv_para >= cv_max) {
1188 				cv_max = cv_para;
1189 				*headline_idx = i;
1190 				case_matched = true;
1191 			}
1192 		}
1193 	}
1194 
1195 	if (case_matched)
1196 		return 0;
1197 
1198 	return -EINVAL;
1199 }
1200 
1201 static void rtw89_phy_init_reg(struct rtw89_dev *rtwdev,
1202 			       const struct rtw89_phy_table *table,
1203 			       void (*config)(struct rtw89_dev *rtwdev,
1204 					      const struct rtw89_reg2_def *reg,
1205 					      enum rtw89_rf_path rf_path,
1206 					      void *data),
1207 			       void *extra_data)
1208 {
1209 	const struct rtw89_reg2_def *reg;
1210 	enum rtw89_rf_path rf_path = table->rf_path;
1211 	u8 rfe = rtwdev->efuse.rfe_type;
1212 	u8 cv = rtwdev->hal.cv;
1213 	u32 i;
1214 	u32 headline_size = 0, headline_idx = 0;
1215 	u32 target = 0, cfg_target;
1216 	u8 cond;
1217 	bool is_matched = true;
1218 	bool target_found = false;
1219 	int ret;
1220 
1221 	ret = rtw89_phy_sel_headline(rtwdev, table, &headline_size,
1222 				     &headline_idx, rfe, cv);
1223 	if (ret) {
1224 		rtw89_err(rtwdev, "invalid PHY package: %d/%d\n", rfe, cv);
1225 		return;
1226 	}
1227 
1228 	cfg_target = get_phy_target(table->regs[headline_idx].addr);
1229 	for (i = headline_size; i < table->n_regs; i++) {
1230 		reg = &table->regs[i];
1231 		cond = get_phy_cond(reg->addr);
1232 		switch (cond) {
1233 		case PHY_COND_BRANCH_IF:
1234 		case PHY_COND_BRANCH_ELIF:
1235 			target = get_phy_target(reg->addr);
1236 			break;
1237 		case PHY_COND_BRANCH_ELSE:
1238 			is_matched = false;
1239 			if (!target_found) {
1240 				rtw89_warn(rtwdev, "failed to load CR %x/%x\n",
1241 					   reg->addr, reg->data);
1242 				return;
1243 			}
1244 			break;
1245 		case PHY_COND_BRANCH_END:
1246 			is_matched = true;
1247 			target_found = false;
1248 			break;
1249 		case PHY_COND_CHECK:
1250 			if (target_found) {
1251 				is_matched = false;
1252 				break;
1253 			}
1254 
1255 			if (target == cfg_target) {
1256 				is_matched = true;
1257 				target_found = true;
1258 			} else {
1259 				is_matched = false;
1260 				target_found = false;
1261 			}
1262 			break;
1263 		default:
1264 			if (is_matched)
1265 				config(rtwdev, reg, rf_path, extra_data);
1266 			break;
1267 		}
1268 	}
1269 }
1270 
1271 void rtw89_phy_init_bb_reg(struct rtw89_dev *rtwdev)
1272 {
1273 	const struct rtw89_chip_info *chip = rtwdev->chip;
1274 	const struct rtw89_phy_table *bb_table = chip->bb_table;
1275 	const struct rtw89_phy_table *bb_gain_table = chip->bb_gain_table;
1276 
1277 	rtw89_phy_init_reg(rtwdev, bb_table, rtw89_phy_config_bb_reg, NULL);
1278 	rtw89_chip_init_txpwr_unit(rtwdev, RTW89_PHY_0);
1279 	if (bb_gain_table)
1280 		rtw89_phy_init_reg(rtwdev, bb_gain_table,
1281 				   rtw89_phy_config_bb_gain, NULL);
1282 	rtw89_phy_bb_reset(rtwdev, RTW89_PHY_0);
1283 }
1284 
1285 static u32 rtw89_phy_nctl_poll(struct rtw89_dev *rtwdev)
1286 {
1287 	rtw89_phy_write32(rtwdev, 0x8080, 0x4);
1288 	udelay(1);
1289 	return rtw89_phy_read32(rtwdev, 0x8080);
1290 }
1291 
1292 void rtw89_phy_init_rf_reg(struct rtw89_dev *rtwdev)
1293 {
1294 	void (*config)(struct rtw89_dev *rtwdev, const struct rtw89_reg2_def *reg,
1295 		       enum rtw89_rf_path rf_path, void *data);
1296 	const struct rtw89_chip_info *chip = rtwdev->chip;
1297 	const struct rtw89_phy_table *rf_table;
1298 	struct rtw89_fw_h2c_rf_reg_info *rf_reg_info;
1299 	u8 path;
1300 
1301 	rf_reg_info = kzalloc(sizeof(*rf_reg_info), GFP_KERNEL);
1302 	if (!rf_reg_info)
1303 		return;
1304 
1305 	for (path = RF_PATH_A; path < chip->rf_path_num; path++) {
1306 		rf_table = chip->rf_table[path];
1307 		rf_reg_info->rf_path = rf_table->rf_path;
1308 		config = rf_table->config ? rf_table->config : rtw89_phy_config_rf_reg;
1309 		rtw89_phy_init_reg(rtwdev, rf_table, config, (void *)rf_reg_info);
1310 		if (rtw89_phy_config_rf_reg_fw(rtwdev, rf_reg_info))
1311 			rtw89_warn(rtwdev, "rf path %d reg h2c config failed\n",
1312 				   rf_reg_info->rf_path);
1313 	}
1314 	kfree(rf_reg_info);
1315 }
1316 
1317 static void rtw89_phy_init_rf_nctl(struct rtw89_dev *rtwdev)
1318 {
1319 	const struct rtw89_chip_info *chip = rtwdev->chip;
1320 	const struct rtw89_phy_table *nctl_table;
1321 	u32 val;
1322 	int ret;
1323 
1324 	/* IQK/DPK clock & reset */
1325 	rtw89_phy_write32_set(rtwdev, 0x0c60, 0x3);
1326 	rtw89_phy_write32_set(rtwdev, 0x0c6c, 0x1);
1327 	rtw89_phy_write32_set(rtwdev, 0x58ac, 0x8000000);
1328 	rtw89_phy_write32_set(rtwdev, 0x78ac, 0x8000000);
1329 
1330 	/* check 0x8080 */
1331 	rtw89_phy_write32(rtwdev, 0x8000, 0x8);
1332 
1333 	ret = read_poll_timeout(rtw89_phy_nctl_poll, val, val == 0x4, 10,
1334 				1000, false, rtwdev);
1335 	if (ret)
1336 		rtw89_err(rtwdev, "failed to poll nctl block\n");
1337 
1338 	nctl_table = chip->nctl_table;
1339 	rtw89_phy_init_reg(rtwdev, nctl_table, rtw89_phy_config_bb_reg, NULL);
1340 }
1341 
1342 static u32 rtw89_phy0_phy1_offset(struct rtw89_dev *rtwdev, u32 addr)
1343 {
1344 	u32 phy_page = addr >> 8;
1345 	u32 ofst = 0;
1346 
1347 	switch (phy_page) {
1348 	case 0x6:
1349 	case 0x7:
1350 	case 0x8:
1351 	case 0x9:
1352 	case 0xa:
1353 	case 0xb:
1354 	case 0xc:
1355 	case 0xd:
1356 	case 0x19:
1357 	case 0x1a:
1358 	case 0x1b:
1359 		ofst = 0x2000;
1360 		break;
1361 	default:
1362 		/* warning case */
1363 		ofst = 0;
1364 		break;
1365 	}
1366 
1367 	if (phy_page >= 0x40 && phy_page <= 0x4f)
1368 		ofst = 0x2000;
1369 
1370 	return ofst;
1371 }
1372 
1373 void rtw89_phy_write32_idx(struct rtw89_dev *rtwdev, u32 addr, u32 mask,
1374 			   u32 data, enum rtw89_phy_idx phy_idx)
1375 {
1376 	if (rtwdev->dbcc_en && phy_idx == RTW89_PHY_1)
1377 		addr += rtw89_phy0_phy1_offset(rtwdev, addr);
1378 	rtw89_phy_write32_mask(rtwdev, addr, mask, data);
1379 }
1380 EXPORT_SYMBOL(rtw89_phy_write32_idx);
1381 
1382 void rtw89_phy_set_phy_regs(struct rtw89_dev *rtwdev, u32 addr, u32 mask,
1383 			    u32 val)
1384 {
1385 	rtw89_phy_write32_idx(rtwdev, addr, mask, val, RTW89_PHY_0);
1386 
1387 	if (!rtwdev->dbcc_en)
1388 		return;
1389 
1390 	rtw89_phy_write32_idx(rtwdev, addr, mask, val, RTW89_PHY_1);
1391 }
1392 
1393 void rtw89_phy_write_reg3_tbl(struct rtw89_dev *rtwdev,
1394 			      const struct rtw89_phy_reg3_tbl *tbl)
1395 {
1396 	const struct rtw89_reg3_def *reg3;
1397 	int i;
1398 
1399 	for (i = 0; i < tbl->size; i++) {
1400 		reg3 = &tbl->reg3[i];
1401 		rtw89_phy_write32_mask(rtwdev, reg3->addr, reg3->mask, reg3->data);
1402 	}
1403 }
1404 EXPORT_SYMBOL(rtw89_phy_write_reg3_tbl);
1405 
1406 const u8 rtw89_rs_idx_max[] = {
1407 	[RTW89_RS_CCK] = RTW89_RATE_CCK_MAX,
1408 	[RTW89_RS_OFDM] = RTW89_RATE_OFDM_MAX,
1409 	[RTW89_RS_MCS] = RTW89_RATE_MCS_MAX,
1410 	[RTW89_RS_HEDCM] = RTW89_RATE_HEDCM_MAX,
1411 	[RTW89_RS_OFFSET] = RTW89_RATE_OFFSET_MAX,
1412 };
1413 EXPORT_SYMBOL(rtw89_rs_idx_max);
1414 
1415 const u8 rtw89_rs_nss_max[] = {
1416 	[RTW89_RS_CCK] = 1,
1417 	[RTW89_RS_OFDM] = 1,
1418 	[RTW89_RS_MCS] = RTW89_NSS_MAX,
1419 	[RTW89_RS_HEDCM] = RTW89_NSS_HEDCM_MAX,
1420 	[RTW89_RS_OFFSET] = 1,
1421 };
1422 EXPORT_SYMBOL(rtw89_rs_nss_max);
1423 
1424 static const u8 _byr_of_rs[] = {
1425 	[RTW89_RS_CCK] = offsetof(struct rtw89_txpwr_byrate, cck),
1426 	[RTW89_RS_OFDM] = offsetof(struct rtw89_txpwr_byrate, ofdm),
1427 	[RTW89_RS_MCS] = offsetof(struct rtw89_txpwr_byrate, mcs),
1428 	[RTW89_RS_HEDCM] = offsetof(struct rtw89_txpwr_byrate, hedcm),
1429 	[RTW89_RS_OFFSET] = offsetof(struct rtw89_txpwr_byrate, offset),
1430 };
1431 
1432 #define _byr_seek(rs, raw) ((s8 *)(raw) + _byr_of_rs[rs])
1433 #define _byr_idx(rs, nss, idx) ((nss) * rtw89_rs_idx_max[rs] + (idx))
1434 #define _byr_chk(rs, nss, idx) \
1435 	((nss) < rtw89_rs_nss_max[rs] && (idx) < rtw89_rs_idx_max[rs])
1436 
1437 void rtw89_phy_load_txpwr_byrate(struct rtw89_dev *rtwdev,
1438 				 const struct rtw89_txpwr_table *tbl)
1439 {
1440 	const struct rtw89_txpwr_byrate_cfg *cfg = tbl->data;
1441 	const struct rtw89_txpwr_byrate_cfg *end = cfg + tbl->size;
1442 	s8 *byr;
1443 	u32 data;
1444 	u8 i, idx;
1445 
1446 	for (; cfg < end; cfg++) {
1447 		byr = _byr_seek(cfg->rs, &rtwdev->byr[cfg->band]);
1448 		data = cfg->data;
1449 
1450 		for (i = 0; i < cfg->len; i++, data >>= 8) {
1451 			idx = _byr_idx(cfg->rs, cfg->nss, (cfg->shf + i));
1452 			byr[idx] = (s8)(data & 0xff);
1453 		}
1454 	}
1455 }
1456 EXPORT_SYMBOL(rtw89_phy_load_txpwr_byrate);
1457 
1458 #define _phy_txpwr_rf_to_mac(rtwdev, txpwr_rf)				\
1459 ({									\
1460 	const struct rtw89_chip_info *__c = (rtwdev)->chip;		\
1461 	(txpwr_rf) >> (__c->txpwr_factor_rf - __c->txpwr_factor_mac);	\
1462 })
1463 
1464 s8 rtw89_phy_read_txpwr_byrate(struct rtw89_dev *rtwdev,
1465 			       const struct rtw89_rate_desc *rate_desc)
1466 {
1467 	enum rtw89_band band = rtwdev->hal.current_band_type;
1468 	s8 *byr;
1469 	u8 idx;
1470 
1471 	if (rate_desc->rs == RTW89_RS_CCK)
1472 		band = RTW89_BAND_2G;
1473 
1474 	if (!_byr_chk(rate_desc->rs, rate_desc->nss, rate_desc->idx)) {
1475 		rtw89_debug(rtwdev, RTW89_DBG_TXPWR,
1476 			    "[TXPWR] unknown byrate desc rs=%d nss=%d idx=%d\n",
1477 			    rate_desc->rs, rate_desc->nss, rate_desc->idx);
1478 
1479 		return 0;
1480 	}
1481 
1482 	byr = _byr_seek(rate_desc->rs, &rtwdev->byr[band]);
1483 	idx = _byr_idx(rate_desc->rs, rate_desc->nss, rate_desc->idx);
1484 
1485 	return _phy_txpwr_rf_to_mac(rtwdev, byr[idx]);
1486 }
1487 EXPORT_SYMBOL(rtw89_phy_read_txpwr_byrate);
1488 
1489 static u8 rtw89_channel_6g_to_idx(struct rtw89_dev *rtwdev, u8 channel_6g)
1490 {
1491 	switch (channel_6g) {
1492 	case 1 ... 29:
1493 		return (channel_6g - 1) / 2;
1494 	case 33 ... 61:
1495 		return (channel_6g - 3) / 2;
1496 	case 65 ... 93:
1497 		return (channel_6g - 5) / 2;
1498 	case 97 ... 125:
1499 		return (channel_6g - 7) / 2;
1500 	case 129 ... 157:
1501 		return (channel_6g - 9) / 2;
1502 	case 161 ... 189:
1503 		return (channel_6g - 11) / 2;
1504 	case 193 ... 221:
1505 		return (channel_6g - 13) / 2;
1506 	case 225 ... 253:
1507 		return (channel_6g - 15) / 2;
1508 	default:
1509 		rtw89_warn(rtwdev, "unknown 6g channel: %d\n", channel_6g);
1510 		return 0;
1511 	}
1512 }
1513 
1514 static u8 rtw89_channel_to_idx(struct rtw89_dev *rtwdev, u8 band, u8 channel)
1515 {
1516 	if (band == RTW89_BAND_6G)
1517 		return rtw89_channel_6g_to_idx(rtwdev, channel);
1518 
1519 	switch (channel) {
1520 	case 1 ... 14:
1521 		return channel - 1;
1522 	case 36 ... 64:
1523 		return (channel - 36) / 2;
1524 	case 100 ... 144:
1525 		return ((channel - 100) / 2) + 15;
1526 	case 149 ... 177:
1527 		return ((channel - 149) / 2) + 38;
1528 	default:
1529 		rtw89_warn(rtwdev, "unknown channel: %d\n", channel);
1530 		return 0;
1531 	}
1532 }
1533 
1534 s8 rtw89_phy_read_txpwr_limit(struct rtw89_dev *rtwdev,
1535 			      u8 bw, u8 ntx, u8 rs, u8 bf, u8 ch)
1536 {
1537 	const struct rtw89_chip_info *chip = rtwdev->chip;
1538 	u8 band = rtwdev->hal.current_band_type;
1539 	u8 ch_idx = rtw89_channel_to_idx(rtwdev, band, ch);
1540 	u8 regd = rtw89_regd_get(rtwdev, band);
1541 	s8 lmt = 0, sar;
1542 
1543 	switch (band) {
1544 	case RTW89_BAND_2G:
1545 		lmt = (*chip->txpwr_lmt_2g)[bw][ntx][rs][bf][regd][ch_idx];
1546 		if (!lmt)
1547 			lmt = (*chip->txpwr_lmt_2g)[bw][ntx][rs][bf]
1548 						   [RTW89_WW][ch_idx];
1549 		break;
1550 	case RTW89_BAND_5G:
1551 		lmt = (*chip->txpwr_lmt_5g)[bw][ntx][rs][bf][regd][ch_idx];
1552 		if (!lmt)
1553 			lmt = (*chip->txpwr_lmt_5g)[bw][ntx][rs][bf]
1554 						   [RTW89_WW][ch_idx];
1555 		break;
1556 	case RTW89_BAND_6G:
1557 		lmt = (*chip->txpwr_lmt_6g)[bw][ntx][rs][bf][regd][ch_idx];
1558 		if (!lmt)
1559 			lmt = (*chip->txpwr_lmt_6g)[bw][ntx][rs][bf]
1560 						   [RTW89_WW][ch_idx];
1561 		break;
1562 	default:
1563 		rtw89_warn(rtwdev, "unknown band type: %d\n", band);
1564 		return 0;
1565 	}
1566 
1567 	lmt = _phy_txpwr_rf_to_mac(rtwdev, lmt);
1568 	sar = rtw89_query_sar(rtwdev);
1569 
1570 	return min(lmt, sar);
1571 }
1572 EXPORT_SYMBOL(rtw89_phy_read_txpwr_limit);
1573 
1574 #define __fill_txpwr_limit_nonbf_bf(ptr, bw, ntx, rs, ch)		\
1575 	do {								\
1576 		u8 __i;							\
1577 		for (__i = 0; __i < RTW89_BF_NUM; __i++)		\
1578 			ptr[__i] = rtw89_phy_read_txpwr_limit(rtwdev,	\
1579 							      bw, ntx,	\
1580 							      rs, __i,	\
1581 							      (ch));	\
1582 	} while (0)
1583 
1584 static void rtw89_phy_fill_txpwr_limit_20m(struct rtw89_dev *rtwdev,
1585 					   struct rtw89_txpwr_limit *lmt,
1586 					   u8 ntx, u8 ch)
1587 {
1588 	__fill_txpwr_limit_nonbf_bf(lmt->cck_20m, RTW89_CHANNEL_WIDTH_20,
1589 				    ntx, RTW89_RS_CCK, ch);
1590 	__fill_txpwr_limit_nonbf_bf(lmt->cck_40m, RTW89_CHANNEL_WIDTH_40,
1591 				    ntx, RTW89_RS_CCK, ch);
1592 	__fill_txpwr_limit_nonbf_bf(lmt->ofdm, RTW89_CHANNEL_WIDTH_20,
1593 				    ntx, RTW89_RS_OFDM, ch);
1594 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[0], RTW89_CHANNEL_WIDTH_20,
1595 				    ntx, RTW89_RS_MCS, ch);
1596 }
1597 
1598 static void rtw89_phy_fill_txpwr_limit_40m(struct rtw89_dev *rtwdev,
1599 					   struct rtw89_txpwr_limit *lmt,
1600 					   u8 ntx, u8 ch, u8 pri_ch)
1601 {
1602 	__fill_txpwr_limit_nonbf_bf(lmt->cck_20m, RTW89_CHANNEL_WIDTH_20,
1603 				    ntx, RTW89_RS_CCK, ch - 2);
1604 	__fill_txpwr_limit_nonbf_bf(lmt->cck_40m, RTW89_CHANNEL_WIDTH_40,
1605 				    ntx, RTW89_RS_CCK, ch);
1606 	__fill_txpwr_limit_nonbf_bf(lmt->ofdm, RTW89_CHANNEL_WIDTH_20,
1607 				    ntx, RTW89_RS_OFDM, pri_ch);
1608 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[0], RTW89_CHANNEL_WIDTH_20,
1609 				    ntx, RTW89_RS_MCS, ch - 2);
1610 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[1], RTW89_CHANNEL_WIDTH_20,
1611 				    ntx, RTW89_RS_MCS, ch + 2);
1612 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_40m[0], RTW89_CHANNEL_WIDTH_40,
1613 				    ntx, RTW89_RS_MCS, ch);
1614 }
1615 
1616 static void rtw89_phy_fill_txpwr_limit_80m(struct rtw89_dev *rtwdev,
1617 					   struct rtw89_txpwr_limit *lmt,
1618 					   u8 ntx, u8 ch, u8 pri_ch)
1619 {
1620 	s8 val_0p5_n[RTW89_BF_NUM];
1621 	s8 val_0p5_p[RTW89_BF_NUM];
1622 	u8 i;
1623 
1624 	__fill_txpwr_limit_nonbf_bf(lmt->ofdm, RTW89_CHANNEL_WIDTH_20,
1625 				    ntx, RTW89_RS_OFDM, pri_ch);
1626 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[0], RTW89_CHANNEL_WIDTH_20,
1627 				    ntx, RTW89_RS_MCS, ch - 6);
1628 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[1], RTW89_CHANNEL_WIDTH_20,
1629 				    ntx, RTW89_RS_MCS, ch - 2);
1630 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[2], RTW89_CHANNEL_WIDTH_20,
1631 				    ntx, RTW89_RS_MCS, ch + 2);
1632 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[3], RTW89_CHANNEL_WIDTH_20,
1633 				    ntx, RTW89_RS_MCS, ch + 6);
1634 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_40m[0], RTW89_CHANNEL_WIDTH_40,
1635 				    ntx, RTW89_RS_MCS, ch - 4);
1636 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_40m[1], RTW89_CHANNEL_WIDTH_40,
1637 				    ntx, RTW89_RS_MCS, ch + 4);
1638 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_80m[0], RTW89_CHANNEL_WIDTH_80,
1639 				    ntx, RTW89_RS_MCS, ch);
1640 
1641 	__fill_txpwr_limit_nonbf_bf(val_0p5_n, RTW89_CHANNEL_WIDTH_40,
1642 				    ntx, RTW89_RS_MCS, ch - 4);
1643 	__fill_txpwr_limit_nonbf_bf(val_0p5_p, RTW89_CHANNEL_WIDTH_40,
1644 				    ntx, RTW89_RS_MCS, ch + 4);
1645 
1646 	for (i = 0; i < RTW89_BF_NUM; i++)
1647 		lmt->mcs_40m_0p5[i] = min_t(s8, val_0p5_n[i], val_0p5_p[i]);
1648 }
1649 
1650 static void rtw89_phy_fill_txpwr_limit_160m(struct rtw89_dev *rtwdev,
1651 					    struct rtw89_txpwr_limit *lmt,
1652 					    u8 ntx, u8 ch, u8 pri_ch)
1653 {
1654 	s8 val_0p5_n[RTW89_BF_NUM];
1655 	s8 val_0p5_p[RTW89_BF_NUM];
1656 	s8 val_2p5_n[RTW89_BF_NUM];
1657 	s8 val_2p5_p[RTW89_BF_NUM];
1658 	u8 i;
1659 
1660 	/* fill ofdm section */
1661 	__fill_txpwr_limit_nonbf_bf(lmt->ofdm, RTW89_CHANNEL_WIDTH_20,
1662 				    ntx, RTW89_RS_OFDM, pri_ch);
1663 
1664 	/* fill mcs 20m section */
1665 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[0], RTW89_CHANNEL_WIDTH_20,
1666 				    ntx, RTW89_RS_MCS, ch - 14);
1667 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[1], RTW89_CHANNEL_WIDTH_20,
1668 				    ntx, RTW89_RS_MCS, ch - 10);
1669 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[2], RTW89_CHANNEL_WIDTH_20,
1670 				    ntx, RTW89_RS_MCS, ch - 6);
1671 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[3], RTW89_CHANNEL_WIDTH_20,
1672 				    ntx, RTW89_RS_MCS, ch - 2);
1673 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[4], RTW89_CHANNEL_WIDTH_20,
1674 				    ntx, RTW89_RS_MCS, ch + 2);
1675 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[5], RTW89_CHANNEL_WIDTH_20,
1676 				    ntx, RTW89_RS_MCS, ch + 6);
1677 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[6], RTW89_CHANNEL_WIDTH_20,
1678 				    ntx, RTW89_RS_MCS, ch + 10);
1679 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[7], RTW89_CHANNEL_WIDTH_20,
1680 				    ntx, RTW89_RS_MCS, ch + 14);
1681 
1682 	/* fill mcs 40m section */
1683 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_40m[0], RTW89_CHANNEL_WIDTH_40,
1684 				    ntx, RTW89_RS_MCS, ch - 12);
1685 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_40m[1], RTW89_CHANNEL_WIDTH_40,
1686 				    ntx, RTW89_RS_MCS, ch - 4);
1687 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_40m[2], RTW89_CHANNEL_WIDTH_40,
1688 				    ntx, RTW89_RS_MCS, ch + 4);
1689 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_40m[3], RTW89_CHANNEL_WIDTH_40,
1690 				    ntx, RTW89_RS_MCS, ch + 12);
1691 
1692 	/* fill mcs 80m section */
1693 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_80m[0], RTW89_CHANNEL_WIDTH_80,
1694 				    ntx, RTW89_RS_MCS, ch - 8);
1695 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_80m[1], RTW89_CHANNEL_WIDTH_80,
1696 				    ntx, RTW89_RS_MCS, ch + 8);
1697 
1698 	/* fill mcs 160m section */
1699 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_160m, RTW89_CHANNEL_WIDTH_160,
1700 				    ntx, RTW89_RS_MCS, ch);
1701 
1702 	/* fill mcs 40m 0p5 section */
1703 	__fill_txpwr_limit_nonbf_bf(val_0p5_n, RTW89_CHANNEL_WIDTH_40,
1704 				    ntx, RTW89_RS_MCS, ch - 4);
1705 	__fill_txpwr_limit_nonbf_bf(val_0p5_p, RTW89_CHANNEL_WIDTH_40,
1706 				    ntx, RTW89_RS_MCS, ch + 4);
1707 
1708 	for (i = 0; i < RTW89_BF_NUM; i++)
1709 		lmt->mcs_40m_0p5[i] = min_t(s8, val_0p5_n[i], val_0p5_p[i]);
1710 
1711 	/* fill mcs 40m 2p5 section */
1712 	__fill_txpwr_limit_nonbf_bf(val_2p5_n, RTW89_CHANNEL_WIDTH_40,
1713 				    ntx, RTW89_RS_MCS, ch - 8);
1714 	__fill_txpwr_limit_nonbf_bf(val_2p5_p, RTW89_CHANNEL_WIDTH_40,
1715 				    ntx, RTW89_RS_MCS, ch + 8);
1716 
1717 	for (i = 0; i < RTW89_BF_NUM; i++)
1718 		lmt->mcs_40m_2p5[i] = min_t(s8, val_2p5_n[i], val_2p5_p[i]);
1719 }
1720 
1721 void rtw89_phy_fill_txpwr_limit(struct rtw89_dev *rtwdev,
1722 				struct rtw89_txpwr_limit *lmt,
1723 				u8 ntx)
1724 {
1725 	u8 pri_ch = rtwdev->hal.current_primary_channel;
1726 	u8 ch = rtwdev->hal.current_channel;
1727 	u8 bw = rtwdev->hal.current_band_width;
1728 
1729 	memset(lmt, 0, sizeof(*lmt));
1730 
1731 	switch (bw) {
1732 	case RTW89_CHANNEL_WIDTH_20:
1733 		rtw89_phy_fill_txpwr_limit_20m(rtwdev, lmt, ntx, ch);
1734 		break;
1735 	case RTW89_CHANNEL_WIDTH_40:
1736 		rtw89_phy_fill_txpwr_limit_40m(rtwdev, lmt, ntx, ch, pri_ch);
1737 		break;
1738 	case RTW89_CHANNEL_WIDTH_80:
1739 		rtw89_phy_fill_txpwr_limit_80m(rtwdev, lmt, ntx, ch, pri_ch);
1740 		break;
1741 	case RTW89_CHANNEL_WIDTH_160:
1742 		rtw89_phy_fill_txpwr_limit_160m(rtwdev, lmt, ntx, ch, pri_ch);
1743 		break;
1744 	}
1745 }
1746 EXPORT_SYMBOL(rtw89_phy_fill_txpwr_limit);
1747 
1748 static s8 rtw89_phy_read_txpwr_limit_ru(struct rtw89_dev *rtwdev,
1749 					u8 ru, u8 ntx, u8 ch)
1750 {
1751 	const struct rtw89_chip_info *chip = rtwdev->chip;
1752 	u8 band = rtwdev->hal.current_band_type;
1753 	u8 ch_idx = rtw89_channel_to_idx(rtwdev, band, ch);
1754 	u8 regd = rtw89_regd_get(rtwdev, band);
1755 	s8 lmt_ru = 0, sar;
1756 
1757 	switch (band) {
1758 	case RTW89_BAND_2G:
1759 		lmt_ru = (*chip->txpwr_lmt_ru_2g)[ru][ntx][regd][ch_idx];
1760 		if (!lmt_ru)
1761 			lmt_ru = (*chip->txpwr_lmt_ru_2g)[ru][ntx]
1762 							 [RTW89_WW][ch_idx];
1763 		break;
1764 	case RTW89_BAND_5G:
1765 		lmt_ru = (*chip->txpwr_lmt_ru_5g)[ru][ntx][regd][ch_idx];
1766 		if (!lmt_ru)
1767 			lmt_ru = (*chip->txpwr_lmt_ru_5g)[ru][ntx]
1768 							 [RTW89_WW][ch_idx];
1769 		break;
1770 	case RTW89_BAND_6G:
1771 		lmt_ru = (*chip->txpwr_lmt_ru_6g)[ru][ntx][regd][ch_idx];
1772 		if (!lmt_ru)
1773 			lmt_ru = (*chip->txpwr_lmt_ru_6g)[ru][ntx]
1774 							 [RTW89_WW][ch_idx];
1775 		break;
1776 	default:
1777 		rtw89_warn(rtwdev, "unknown band type: %d\n", band);
1778 		return 0;
1779 	}
1780 
1781 	lmt_ru = _phy_txpwr_rf_to_mac(rtwdev, lmt_ru);
1782 	sar = rtw89_query_sar(rtwdev);
1783 
1784 	return min(lmt_ru, sar);
1785 }
1786 
1787 static void
1788 rtw89_phy_fill_txpwr_limit_ru_20m(struct rtw89_dev *rtwdev,
1789 				  struct rtw89_txpwr_limit_ru *lmt_ru,
1790 				  u8 ntx, u8 ch)
1791 {
1792 	lmt_ru->ru26[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU26,
1793 							ntx, ch);
1794 	lmt_ru->ru52[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU52,
1795 							ntx, ch);
1796 	lmt_ru->ru106[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU106,
1797 							 ntx, ch);
1798 }
1799 
1800 static void
1801 rtw89_phy_fill_txpwr_limit_ru_40m(struct rtw89_dev *rtwdev,
1802 				  struct rtw89_txpwr_limit_ru *lmt_ru,
1803 				  u8 ntx, u8 ch)
1804 {
1805 	lmt_ru->ru26[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU26,
1806 							ntx, ch - 2);
1807 	lmt_ru->ru26[1] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU26,
1808 							ntx, ch + 2);
1809 	lmt_ru->ru52[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU52,
1810 							ntx, ch - 2);
1811 	lmt_ru->ru52[1] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU52,
1812 							ntx, ch + 2);
1813 	lmt_ru->ru106[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU106,
1814 							 ntx, ch - 2);
1815 	lmt_ru->ru106[1] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU106,
1816 							 ntx, ch + 2);
1817 }
1818 
1819 static void
1820 rtw89_phy_fill_txpwr_limit_ru_80m(struct rtw89_dev *rtwdev,
1821 				  struct rtw89_txpwr_limit_ru *lmt_ru,
1822 				  u8 ntx, u8 ch)
1823 {
1824 	lmt_ru->ru26[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU26,
1825 							ntx, ch - 6);
1826 	lmt_ru->ru26[1] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU26,
1827 							ntx, ch - 2);
1828 	lmt_ru->ru26[2] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU26,
1829 							ntx, ch + 2);
1830 	lmt_ru->ru26[3] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU26,
1831 							ntx, ch + 6);
1832 	lmt_ru->ru52[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU52,
1833 							ntx, ch - 6);
1834 	lmt_ru->ru52[1] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU52,
1835 							ntx, ch - 2);
1836 	lmt_ru->ru52[2] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU52,
1837 							ntx, ch + 2);
1838 	lmt_ru->ru52[3] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU52,
1839 							ntx, ch + 6);
1840 	lmt_ru->ru106[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU106,
1841 							 ntx, ch - 6);
1842 	lmt_ru->ru106[1] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU106,
1843 							 ntx, ch - 2);
1844 	lmt_ru->ru106[2] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU106,
1845 							 ntx, ch + 2);
1846 	lmt_ru->ru106[3] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU106,
1847 							 ntx, ch + 6);
1848 }
1849 
1850 static void
1851 rtw89_phy_fill_txpwr_limit_ru_160m(struct rtw89_dev *rtwdev,
1852 				   struct rtw89_txpwr_limit_ru *lmt_ru,
1853 				   u8 ntx, u8 ch)
1854 {
1855 	static const int ofst[] = { -14, -10, -6, -2, 2, 6, 10, 14 };
1856 	int i;
1857 
1858 	static_assert(ARRAY_SIZE(ofst) == RTW89_RU_SEC_NUM);
1859 	for (i = 0; i < RTW89_RU_SEC_NUM; i++) {
1860 		lmt_ru->ru26[i] = rtw89_phy_read_txpwr_limit_ru(rtwdev,
1861 								RTW89_RU26,
1862 								ntx,
1863 								ch + ofst[i]);
1864 		lmt_ru->ru52[i] = rtw89_phy_read_txpwr_limit_ru(rtwdev,
1865 								RTW89_RU52,
1866 								ntx,
1867 								ch + ofst[i]);
1868 		lmt_ru->ru106[i] = rtw89_phy_read_txpwr_limit_ru(rtwdev,
1869 								 RTW89_RU106,
1870 								 ntx,
1871 								 ch + ofst[i]);
1872 	}
1873 }
1874 
1875 void rtw89_phy_fill_txpwr_limit_ru(struct rtw89_dev *rtwdev,
1876 				   struct rtw89_txpwr_limit_ru *lmt_ru,
1877 				   u8 ntx)
1878 {
1879 	u8 ch = rtwdev->hal.current_channel;
1880 	u8 bw = rtwdev->hal.current_band_width;
1881 
1882 	memset(lmt_ru, 0, sizeof(*lmt_ru));
1883 
1884 	switch (bw) {
1885 	case RTW89_CHANNEL_WIDTH_20:
1886 		rtw89_phy_fill_txpwr_limit_ru_20m(rtwdev, lmt_ru, ntx, ch);
1887 		break;
1888 	case RTW89_CHANNEL_WIDTH_40:
1889 		rtw89_phy_fill_txpwr_limit_ru_40m(rtwdev, lmt_ru, ntx, ch);
1890 		break;
1891 	case RTW89_CHANNEL_WIDTH_80:
1892 		rtw89_phy_fill_txpwr_limit_ru_80m(rtwdev, lmt_ru, ntx, ch);
1893 		break;
1894 	case RTW89_CHANNEL_WIDTH_160:
1895 		rtw89_phy_fill_txpwr_limit_ru_160m(rtwdev, lmt_ru, ntx, ch);
1896 		break;
1897 	}
1898 }
1899 EXPORT_SYMBOL(rtw89_phy_fill_txpwr_limit_ru);
1900 
1901 struct rtw89_phy_iter_ra_data {
1902 	struct rtw89_dev *rtwdev;
1903 	struct sk_buff *c2h;
1904 };
1905 
1906 static void rtw89_phy_c2h_ra_rpt_iter(void *data, struct ieee80211_sta *sta)
1907 {
1908 	struct rtw89_phy_iter_ra_data *ra_data = (struct rtw89_phy_iter_ra_data *)data;
1909 	struct rtw89_dev *rtwdev = ra_data->rtwdev;
1910 	struct rtw89_sta *rtwsta = (struct rtw89_sta *)sta->drv_priv;
1911 	struct rtw89_ra_report *ra_report = &rtwsta->ra_report;
1912 	struct sk_buff *c2h = ra_data->c2h;
1913 	u8 mode, rate, bw, giltf, mac_id;
1914 
1915 	mac_id = RTW89_GET_PHY_C2H_RA_RPT_MACID(c2h->data);
1916 	if (mac_id != rtwsta->mac_id)
1917 		return;
1918 
1919 	memset(ra_report, 0, sizeof(*ra_report));
1920 
1921 	rate = RTW89_GET_PHY_C2H_RA_RPT_MCSNSS(c2h->data);
1922 	bw = RTW89_GET_PHY_C2H_RA_RPT_BW(c2h->data);
1923 	giltf = RTW89_GET_PHY_C2H_RA_RPT_GILTF(c2h->data);
1924 	mode = RTW89_GET_PHY_C2H_RA_RPT_MD_SEL(c2h->data);
1925 
1926 	switch (mode) {
1927 	case RTW89_RA_RPT_MODE_LEGACY:
1928 		ra_report->txrate.legacy = rtw89_ra_report_to_bitrate(rtwdev, rate);
1929 		break;
1930 	case RTW89_RA_RPT_MODE_HT:
1931 		ra_report->txrate.flags |= RATE_INFO_FLAGS_MCS;
1932 		if (RTW89_CHK_FW_FEATURE(OLD_HT_RA_FORMAT, &rtwdev->fw))
1933 			rate = RTW89_MK_HT_RATE(FIELD_GET(RTW89_RA_RATE_MASK_NSS, rate),
1934 						FIELD_GET(RTW89_RA_RATE_MASK_MCS, rate));
1935 		else
1936 			rate = FIELD_GET(RTW89_RA_RATE_MASK_HT_MCS, rate);
1937 		ra_report->txrate.mcs = rate;
1938 		if (giltf)
1939 			ra_report->txrate.flags |= RATE_INFO_FLAGS_SHORT_GI;
1940 		break;
1941 	case RTW89_RA_RPT_MODE_VHT:
1942 		ra_report->txrate.flags |= RATE_INFO_FLAGS_VHT_MCS;
1943 		ra_report->txrate.mcs = FIELD_GET(RTW89_RA_RATE_MASK_MCS, rate);
1944 		ra_report->txrate.nss = FIELD_GET(RTW89_RA_RATE_MASK_NSS, rate) + 1;
1945 		if (giltf)
1946 			ra_report->txrate.flags |= RATE_INFO_FLAGS_SHORT_GI;
1947 		break;
1948 	case RTW89_RA_RPT_MODE_HE:
1949 		ra_report->txrate.flags |= RATE_INFO_FLAGS_HE_MCS;
1950 		ra_report->txrate.mcs = FIELD_GET(RTW89_RA_RATE_MASK_MCS, rate);
1951 		ra_report->txrate.nss = FIELD_GET(RTW89_RA_RATE_MASK_NSS, rate) + 1;
1952 		if (giltf == RTW89_GILTF_2XHE08 || giltf == RTW89_GILTF_1XHE08)
1953 			ra_report->txrate.he_gi = NL80211_RATE_INFO_HE_GI_0_8;
1954 		else if (giltf == RTW89_GILTF_2XHE16 || giltf == RTW89_GILTF_1XHE16)
1955 			ra_report->txrate.he_gi = NL80211_RATE_INFO_HE_GI_1_6;
1956 		else
1957 			ra_report->txrate.he_gi = NL80211_RATE_INFO_HE_GI_3_2;
1958 		break;
1959 	}
1960 
1961 	ra_report->txrate.bw = rtw89_hw_to_rate_info_bw(bw);
1962 	ra_report->bit_rate = cfg80211_calculate_bitrate(&ra_report->txrate);
1963 	ra_report->hw_rate = FIELD_PREP(RTW89_HW_RATE_MASK_MOD, mode) |
1964 			     FIELD_PREP(RTW89_HW_RATE_MASK_VAL, rate);
1965 	sta->max_rc_amsdu_len = get_max_amsdu_len(rtwdev, ra_report);
1966 	rtwsta->max_agg_wait = sta->max_rc_amsdu_len / 1500 - 1;
1967 }
1968 
1969 static void
1970 rtw89_phy_c2h_ra_rpt(struct rtw89_dev *rtwdev, struct sk_buff *c2h, u32 len)
1971 {
1972 	struct rtw89_phy_iter_ra_data ra_data;
1973 
1974 	ra_data.rtwdev = rtwdev;
1975 	ra_data.c2h = c2h;
1976 	ieee80211_iterate_stations_atomic(rtwdev->hw,
1977 					  rtw89_phy_c2h_ra_rpt_iter,
1978 					  &ra_data);
1979 }
1980 
1981 static
1982 void (* const rtw89_phy_c2h_ra_handler[])(struct rtw89_dev *rtwdev,
1983 					  struct sk_buff *c2h, u32 len) = {
1984 	[RTW89_PHY_C2H_FUNC_STS_RPT] = rtw89_phy_c2h_ra_rpt,
1985 	[RTW89_PHY_C2H_FUNC_MU_GPTBL_RPT] = NULL,
1986 	[RTW89_PHY_C2H_FUNC_TXSTS] = NULL,
1987 };
1988 
1989 void rtw89_phy_c2h_handle(struct rtw89_dev *rtwdev, struct sk_buff *skb,
1990 			  u32 len, u8 class, u8 func)
1991 {
1992 	void (*handler)(struct rtw89_dev *rtwdev,
1993 			struct sk_buff *c2h, u32 len) = NULL;
1994 
1995 	switch (class) {
1996 	case RTW89_PHY_C2H_CLASS_RA:
1997 		if (func < RTW89_PHY_C2H_FUNC_RA_MAX)
1998 			handler = rtw89_phy_c2h_ra_handler[func];
1999 		break;
2000 	default:
2001 		rtw89_info(rtwdev, "c2h class %d not support\n", class);
2002 		return;
2003 	}
2004 	if (!handler) {
2005 		rtw89_info(rtwdev, "c2h class %d func %d not support\n", class,
2006 			   func);
2007 		return;
2008 	}
2009 	handler(rtwdev, skb, len);
2010 }
2011 
2012 static u8 rtw89_phy_cfo_get_xcap_reg(struct rtw89_dev *rtwdev, bool sc_xo)
2013 {
2014 	u32 reg_mask;
2015 
2016 	if (sc_xo)
2017 		reg_mask = B_AX_XTAL_SC_XO_MASK;
2018 	else
2019 		reg_mask = B_AX_XTAL_SC_XI_MASK;
2020 
2021 	return (u8)rtw89_read32_mask(rtwdev, R_AX_XTAL_ON_CTRL0, reg_mask);
2022 }
2023 
2024 static void rtw89_phy_cfo_set_xcap_reg(struct rtw89_dev *rtwdev, bool sc_xo,
2025 				       u8 val)
2026 {
2027 	u32 reg_mask;
2028 
2029 	if (sc_xo)
2030 		reg_mask = B_AX_XTAL_SC_XO_MASK;
2031 	else
2032 		reg_mask = B_AX_XTAL_SC_XI_MASK;
2033 
2034 	rtw89_write32_mask(rtwdev, R_AX_XTAL_ON_CTRL0, reg_mask, val);
2035 }
2036 
2037 static void rtw89_phy_cfo_set_crystal_cap(struct rtw89_dev *rtwdev,
2038 					  u8 crystal_cap, bool force)
2039 {
2040 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2041 	const struct rtw89_chip_info *chip = rtwdev->chip;
2042 	u8 sc_xi_val, sc_xo_val;
2043 
2044 	if (!force && cfo->crystal_cap == crystal_cap)
2045 		return;
2046 	crystal_cap = clamp_t(u8, crystal_cap, 0, 127);
2047 	if (chip->chip_id == RTL8852A) {
2048 		rtw89_phy_cfo_set_xcap_reg(rtwdev, true, crystal_cap);
2049 		rtw89_phy_cfo_set_xcap_reg(rtwdev, false, crystal_cap);
2050 		sc_xo_val = rtw89_phy_cfo_get_xcap_reg(rtwdev, true);
2051 		sc_xi_val = rtw89_phy_cfo_get_xcap_reg(rtwdev, false);
2052 	} else {
2053 		rtw89_mac_write_xtal_si(rtwdev, XTAL_SI_XTAL_SC_XO,
2054 					crystal_cap, XTAL_SC_XO_MASK);
2055 		rtw89_mac_write_xtal_si(rtwdev, XTAL_SI_XTAL_SC_XI,
2056 					crystal_cap, XTAL_SC_XI_MASK);
2057 		rtw89_mac_read_xtal_si(rtwdev, XTAL_SI_XTAL_SC_XO, &sc_xo_val);
2058 		rtw89_mac_read_xtal_si(rtwdev, XTAL_SI_XTAL_SC_XI, &sc_xi_val);
2059 	}
2060 	cfo->crystal_cap = sc_xi_val;
2061 	cfo->x_cap_ofst = (s8)((int)cfo->crystal_cap - cfo->def_x_cap);
2062 
2063 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Set sc_xi=0x%x\n", sc_xi_val);
2064 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Set sc_xo=0x%x\n", sc_xo_val);
2065 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Get xcap_ofst=%d\n",
2066 		    cfo->x_cap_ofst);
2067 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Set xcap OK\n");
2068 }
2069 
2070 static void rtw89_phy_cfo_reset(struct rtw89_dev *rtwdev)
2071 {
2072 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2073 	u8 cap;
2074 
2075 	cfo->def_x_cap = cfo->crystal_cap_default & B_AX_XTAL_SC_MASK;
2076 	cfo->is_adjust = false;
2077 	if (cfo->crystal_cap == cfo->def_x_cap)
2078 		return;
2079 	cap = cfo->crystal_cap;
2080 	cap += (cap > cfo->def_x_cap ? -1 : 1);
2081 	rtw89_phy_cfo_set_crystal_cap(rtwdev, cap, false);
2082 	rtw89_debug(rtwdev, RTW89_DBG_CFO,
2083 		    "(0x%x) approach to dflt_val=(0x%x)\n", cfo->crystal_cap,
2084 		    cfo->def_x_cap);
2085 }
2086 
2087 static void rtw89_dcfo_comp(struct rtw89_dev *rtwdev, s32 curr_cfo)
2088 {
2089 	const struct rtw89_reg_def *dcfo_comp = rtwdev->chip->dcfo_comp;
2090 	bool is_linked = rtwdev->total_sta_assoc > 0;
2091 	s32 cfo_avg_312;
2092 	s32 dcfo_comp_val;
2093 	u8 dcfo_comp_sft = rtwdev->chip->dcfo_comp_sft;
2094 	int sign;
2095 
2096 	if (!is_linked) {
2097 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "DCFO: is_linked=%d\n",
2098 			    is_linked);
2099 		return;
2100 	}
2101 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "DCFO: curr_cfo=%d\n", curr_cfo);
2102 	if (curr_cfo == 0)
2103 		return;
2104 	dcfo_comp_val = rtw89_phy_read32_mask(rtwdev, R_DCFO, B_DCFO);
2105 	sign = curr_cfo > 0 ? 1 : -1;
2106 	cfo_avg_312 = (curr_cfo << dcfo_comp_sft) / 5 + sign * dcfo_comp_val;
2107 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "DCFO: avg_cfo=%d\n", cfo_avg_312);
2108 	if (rtwdev->chip->chip_id == RTL8852A && rtwdev->hal.cv == CHIP_CBV)
2109 		cfo_avg_312 = -cfo_avg_312;
2110 	rtw89_phy_set_phy_regs(rtwdev, dcfo_comp->addr, dcfo_comp->mask,
2111 			       cfo_avg_312);
2112 }
2113 
2114 static void rtw89_dcfo_comp_init(struct rtw89_dev *rtwdev)
2115 {
2116 	rtw89_phy_set_phy_regs(rtwdev, R_DCFO_OPT, B_DCFO_OPT_EN, 1);
2117 	rtw89_phy_set_phy_regs(rtwdev, R_DCFO_WEIGHT, B_DCFO_WEIGHT_MSK, 8);
2118 	rtw89_write32_clr(rtwdev, R_AX_PWR_UL_CTRL2, B_AX_PWR_UL_CFO_MASK);
2119 }
2120 
2121 static void rtw89_phy_cfo_init(struct rtw89_dev *rtwdev)
2122 {
2123 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2124 	struct rtw89_efuse *efuse = &rtwdev->efuse;
2125 
2126 	cfo->crystal_cap_default = efuse->xtal_cap & B_AX_XTAL_SC_MASK;
2127 	cfo->crystal_cap = cfo->crystal_cap_default;
2128 	cfo->def_x_cap = cfo->crystal_cap;
2129 	cfo->x_cap_ub = min_t(int, cfo->def_x_cap + CFO_BOUND, 0x7f);
2130 	cfo->x_cap_lb = max_t(int, cfo->def_x_cap - CFO_BOUND, 0x1);
2131 	cfo->is_adjust = false;
2132 	cfo->divergence_lock_en = false;
2133 	cfo->x_cap_ofst = 0;
2134 	cfo->lock_cnt = 0;
2135 	cfo->rtw89_multi_cfo_mode = RTW89_TP_BASED_AVG_MODE;
2136 	cfo->apply_compensation = false;
2137 	cfo->residual_cfo_acc = 0;
2138 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Default xcap=%0x\n",
2139 		    cfo->crystal_cap_default);
2140 	rtw89_phy_cfo_set_crystal_cap(rtwdev, cfo->crystal_cap_default, true);
2141 	rtw89_phy_set_phy_regs(rtwdev, R_DCFO, B_DCFO, 1);
2142 	rtw89_dcfo_comp_init(rtwdev);
2143 	cfo->cfo_timer_ms = 2000;
2144 	cfo->cfo_trig_by_timer_en = false;
2145 	cfo->phy_cfo_trk_cnt = 0;
2146 	cfo->phy_cfo_status = RTW89_PHY_DCFO_STATE_NORMAL;
2147 }
2148 
2149 static void rtw89_phy_cfo_crystal_cap_adjust(struct rtw89_dev *rtwdev,
2150 					     s32 curr_cfo)
2151 {
2152 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2153 	s8 crystal_cap = cfo->crystal_cap;
2154 	s32 cfo_abs = abs(curr_cfo);
2155 	int sign;
2156 
2157 	if (!cfo->is_adjust) {
2158 		if (cfo_abs > CFO_TRK_ENABLE_TH)
2159 			cfo->is_adjust = true;
2160 	} else {
2161 		if (cfo_abs < CFO_TRK_STOP_TH)
2162 			cfo->is_adjust = false;
2163 	}
2164 	if (!cfo->is_adjust) {
2165 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "Stop CFO tracking\n");
2166 		return;
2167 	}
2168 	sign = curr_cfo > 0 ? 1 : -1;
2169 	if (cfo_abs > CFO_TRK_STOP_TH_4)
2170 		crystal_cap += 7 * sign;
2171 	else if (cfo_abs > CFO_TRK_STOP_TH_3)
2172 		crystal_cap += 5 * sign;
2173 	else if (cfo_abs > CFO_TRK_STOP_TH_2)
2174 		crystal_cap += 3 * sign;
2175 	else if (cfo_abs > CFO_TRK_STOP_TH_1)
2176 		crystal_cap += 1 * sign;
2177 	else
2178 		return;
2179 	rtw89_phy_cfo_set_crystal_cap(rtwdev, (u8)crystal_cap, false);
2180 	rtw89_debug(rtwdev, RTW89_DBG_CFO,
2181 		    "X_cap{Curr,Default}={0x%x,0x%x}\n",
2182 		    cfo->crystal_cap, cfo->def_x_cap);
2183 }
2184 
2185 static s32 rtw89_phy_average_cfo_calc(struct rtw89_dev *rtwdev)
2186 {
2187 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2188 	s32 cfo_khz_all = 0;
2189 	s32 cfo_cnt_all = 0;
2190 	s32 cfo_all_avg = 0;
2191 	u8 i;
2192 
2193 	if (rtwdev->total_sta_assoc != 1)
2194 		return 0;
2195 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "one_entry_only\n");
2196 	for (i = 0; i < CFO_TRACK_MAX_USER; i++) {
2197 		if (cfo->cfo_cnt[i] == 0)
2198 			continue;
2199 		cfo_khz_all += cfo->cfo_tail[i];
2200 		cfo_cnt_all += cfo->cfo_cnt[i];
2201 		cfo_all_avg = phy_div(cfo_khz_all, cfo_cnt_all);
2202 		cfo->pre_cfo_avg[i] = cfo->cfo_avg[i];
2203 	}
2204 	rtw89_debug(rtwdev, RTW89_DBG_CFO,
2205 		    "CFO track for macid = %d\n", i);
2206 	rtw89_debug(rtwdev, RTW89_DBG_CFO,
2207 		    "Total cfo=%dK, pkt_cnt=%d, avg_cfo=%dK\n",
2208 		    cfo_khz_all, cfo_cnt_all, cfo_all_avg);
2209 	return cfo_all_avg;
2210 }
2211 
2212 static s32 rtw89_phy_multi_sta_cfo_calc(struct rtw89_dev *rtwdev)
2213 {
2214 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2215 	struct rtw89_traffic_stats *stats = &rtwdev->stats;
2216 	s32 target_cfo = 0;
2217 	s32 cfo_khz_all = 0;
2218 	s32 cfo_khz_all_tp_wgt = 0;
2219 	s32 cfo_avg = 0;
2220 	s32 max_cfo_lb = BIT(31);
2221 	s32 min_cfo_ub = GENMASK(30, 0);
2222 	u16 cfo_cnt_all = 0;
2223 	u8 active_entry_cnt = 0;
2224 	u8 sta_cnt = 0;
2225 	u32 tp_all = 0;
2226 	u8 i;
2227 	u8 cfo_tol = 0;
2228 
2229 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Multi entry cfo_trk\n");
2230 	if (cfo->rtw89_multi_cfo_mode == RTW89_PKT_BASED_AVG_MODE) {
2231 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "Pkt based avg mode\n");
2232 		for (i = 0; i < CFO_TRACK_MAX_USER; i++) {
2233 			if (cfo->cfo_cnt[i] == 0)
2234 				continue;
2235 			cfo_khz_all += cfo->cfo_tail[i];
2236 			cfo_cnt_all += cfo->cfo_cnt[i];
2237 			cfo_avg = phy_div(cfo_khz_all, (s32)cfo_cnt_all);
2238 			rtw89_debug(rtwdev, RTW89_DBG_CFO,
2239 				    "Msta cfo=%d, pkt_cnt=%d, avg_cfo=%d\n",
2240 				    cfo_khz_all, cfo_cnt_all, cfo_avg);
2241 			target_cfo = cfo_avg;
2242 		}
2243 	} else if (cfo->rtw89_multi_cfo_mode == RTW89_ENTRY_BASED_AVG_MODE) {
2244 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "Entry based avg mode\n");
2245 		for (i = 0; i < CFO_TRACK_MAX_USER; i++) {
2246 			if (cfo->cfo_cnt[i] == 0)
2247 				continue;
2248 			cfo->cfo_avg[i] = phy_div(cfo->cfo_tail[i],
2249 						  (s32)cfo->cfo_cnt[i]);
2250 			cfo_khz_all += cfo->cfo_avg[i];
2251 			rtw89_debug(rtwdev, RTW89_DBG_CFO,
2252 				    "Macid=%d, cfo_avg=%d\n", i,
2253 				    cfo->cfo_avg[i]);
2254 		}
2255 		sta_cnt = rtwdev->total_sta_assoc;
2256 		cfo_avg = phy_div(cfo_khz_all, (s32)sta_cnt);
2257 		rtw89_debug(rtwdev, RTW89_DBG_CFO,
2258 			    "Msta cfo_acc=%d, ent_cnt=%d, avg_cfo=%d\n",
2259 			    cfo_khz_all, sta_cnt, cfo_avg);
2260 		target_cfo = cfo_avg;
2261 	} else if (cfo->rtw89_multi_cfo_mode == RTW89_TP_BASED_AVG_MODE) {
2262 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "TP based avg mode\n");
2263 		cfo_tol = cfo->sta_cfo_tolerance;
2264 		for (i = 0; i < CFO_TRACK_MAX_USER; i++) {
2265 			sta_cnt++;
2266 			if (cfo->cfo_cnt[i] != 0) {
2267 				cfo->cfo_avg[i] = phy_div(cfo->cfo_tail[i],
2268 							  (s32)cfo->cfo_cnt[i]);
2269 				active_entry_cnt++;
2270 			} else {
2271 				cfo->cfo_avg[i] = cfo->pre_cfo_avg[i];
2272 			}
2273 			max_cfo_lb = max(cfo->cfo_avg[i] - cfo_tol, max_cfo_lb);
2274 			min_cfo_ub = min(cfo->cfo_avg[i] + cfo_tol, min_cfo_ub);
2275 			cfo_khz_all += cfo->cfo_avg[i];
2276 			/* need tp for each entry */
2277 			rtw89_debug(rtwdev, RTW89_DBG_CFO,
2278 				    "[%d] cfo_avg=%d, tp=tbd\n",
2279 				    i, cfo->cfo_avg[i]);
2280 			if (sta_cnt >= rtwdev->total_sta_assoc)
2281 				break;
2282 		}
2283 		tp_all = stats->rx_throughput; /* need tp for each entry */
2284 		cfo_avg =  phy_div(cfo_khz_all_tp_wgt, (s32)tp_all);
2285 
2286 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "Assoc sta cnt=%d\n",
2287 			    sta_cnt);
2288 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "Active sta cnt=%d\n",
2289 			    active_entry_cnt);
2290 		rtw89_debug(rtwdev, RTW89_DBG_CFO,
2291 			    "Msta cfo with tp_wgt=%d, avg_cfo=%d\n",
2292 			    cfo_khz_all_tp_wgt, cfo_avg);
2293 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "cfo_lb=%d,cfo_ub=%d\n",
2294 			    max_cfo_lb, min_cfo_ub);
2295 		if (max_cfo_lb <= min_cfo_ub) {
2296 			rtw89_debug(rtwdev, RTW89_DBG_CFO,
2297 				    "cfo win_size=%d\n",
2298 				    min_cfo_ub - max_cfo_lb);
2299 			target_cfo = clamp(cfo_avg, max_cfo_lb, min_cfo_ub);
2300 		} else {
2301 			rtw89_debug(rtwdev, RTW89_DBG_CFO,
2302 				    "No intersection of cfo tolerance windows\n");
2303 			target_cfo = phy_div(cfo_khz_all, (s32)sta_cnt);
2304 		}
2305 		for (i = 0; i < CFO_TRACK_MAX_USER; i++)
2306 			cfo->pre_cfo_avg[i] = cfo->cfo_avg[i];
2307 	}
2308 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Target cfo=%d\n", target_cfo);
2309 	return target_cfo;
2310 }
2311 
2312 static void rtw89_phy_cfo_statistics_reset(struct rtw89_dev *rtwdev)
2313 {
2314 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2315 
2316 	memset(&cfo->cfo_tail, 0, sizeof(cfo->cfo_tail));
2317 	memset(&cfo->cfo_cnt, 0, sizeof(cfo->cfo_cnt));
2318 	cfo->packet_count = 0;
2319 	cfo->packet_count_pre = 0;
2320 	cfo->cfo_avg_pre = 0;
2321 }
2322 
2323 static void rtw89_phy_cfo_dm(struct rtw89_dev *rtwdev)
2324 {
2325 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2326 	s32 new_cfo = 0;
2327 	bool x_cap_update = false;
2328 	u8 pre_x_cap = cfo->crystal_cap;
2329 
2330 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "CFO:total_sta_assoc=%d\n",
2331 		    rtwdev->total_sta_assoc);
2332 	if (rtwdev->total_sta_assoc == 0) {
2333 		rtw89_phy_cfo_reset(rtwdev);
2334 		return;
2335 	}
2336 	if (cfo->packet_count == 0) {
2337 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "Pkt cnt = 0\n");
2338 		return;
2339 	}
2340 	if (cfo->packet_count == cfo->packet_count_pre) {
2341 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "Pkt cnt doesn't change\n");
2342 		return;
2343 	}
2344 	if (rtwdev->total_sta_assoc == 1)
2345 		new_cfo = rtw89_phy_average_cfo_calc(rtwdev);
2346 	else
2347 		new_cfo = rtw89_phy_multi_sta_cfo_calc(rtwdev);
2348 	if (new_cfo == 0) {
2349 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "curr_cfo=0\n");
2350 		return;
2351 	}
2352 	if (cfo->divergence_lock_en) {
2353 		cfo->lock_cnt++;
2354 		if (cfo->lock_cnt > CFO_PERIOD_CNT) {
2355 			cfo->divergence_lock_en = false;
2356 			cfo->lock_cnt = 0;
2357 		} else {
2358 			rtw89_phy_cfo_reset(rtwdev);
2359 		}
2360 		return;
2361 	}
2362 	if (cfo->crystal_cap >= cfo->x_cap_ub ||
2363 	    cfo->crystal_cap <= cfo->x_cap_lb) {
2364 		cfo->divergence_lock_en = true;
2365 		rtw89_phy_cfo_reset(rtwdev);
2366 		return;
2367 	}
2368 
2369 	rtw89_phy_cfo_crystal_cap_adjust(rtwdev, new_cfo);
2370 	cfo->cfo_avg_pre = new_cfo;
2371 	x_cap_update =  cfo->crystal_cap != pre_x_cap;
2372 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Xcap_up=%d\n", x_cap_update);
2373 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Xcap: D:%x C:%x->%x, ofst=%d\n",
2374 		    cfo->def_x_cap, pre_x_cap, cfo->crystal_cap,
2375 		    cfo->x_cap_ofst);
2376 	if (x_cap_update) {
2377 		if (new_cfo > 0)
2378 			new_cfo -= CFO_SW_COMP_FINE_TUNE;
2379 		else
2380 			new_cfo += CFO_SW_COMP_FINE_TUNE;
2381 	}
2382 	rtw89_dcfo_comp(rtwdev, new_cfo);
2383 	rtw89_phy_cfo_statistics_reset(rtwdev);
2384 }
2385 
2386 void rtw89_phy_cfo_track_work(struct work_struct *work)
2387 {
2388 	struct rtw89_dev *rtwdev = container_of(work, struct rtw89_dev,
2389 						cfo_track_work.work);
2390 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2391 
2392 	mutex_lock(&rtwdev->mutex);
2393 	if (!cfo->cfo_trig_by_timer_en)
2394 		goto out;
2395 	rtw89_leave_ps_mode(rtwdev);
2396 	rtw89_phy_cfo_dm(rtwdev);
2397 	ieee80211_queue_delayed_work(rtwdev->hw, &rtwdev->cfo_track_work,
2398 				     msecs_to_jiffies(cfo->cfo_timer_ms));
2399 out:
2400 	mutex_unlock(&rtwdev->mutex);
2401 }
2402 
2403 static void rtw89_phy_cfo_start_work(struct rtw89_dev *rtwdev)
2404 {
2405 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2406 
2407 	ieee80211_queue_delayed_work(rtwdev->hw, &rtwdev->cfo_track_work,
2408 				     msecs_to_jiffies(cfo->cfo_timer_ms));
2409 }
2410 
2411 void rtw89_phy_cfo_track(struct rtw89_dev *rtwdev)
2412 {
2413 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2414 	struct rtw89_traffic_stats *stats = &rtwdev->stats;
2415 
2416 	switch (cfo->phy_cfo_status) {
2417 	case RTW89_PHY_DCFO_STATE_NORMAL:
2418 		if (stats->tx_throughput >= CFO_TP_UPPER) {
2419 			cfo->phy_cfo_status = RTW89_PHY_DCFO_STATE_ENHANCE;
2420 			cfo->cfo_trig_by_timer_en = true;
2421 			cfo->cfo_timer_ms = CFO_COMP_PERIOD;
2422 			rtw89_phy_cfo_start_work(rtwdev);
2423 		}
2424 		break;
2425 	case RTW89_PHY_DCFO_STATE_ENHANCE:
2426 		if (cfo->phy_cfo_trk_cnt >= CFO_PERIOD_CNT) {
2427 			cfo->phy_cfo_trk_cnt = 0;
2428 			cfo->cfo_trig_by_timer_en = false;
2429 		}
2430 		if (cfo->cfo_trig_by_timer_en == 1)
2431 			cfo->phy_cfo_trk_cnt++;
2432 		if (stats->tx_throughput <= CFO_TP_LOWER) {
2433 			cfo->phy_cfo_status = RTW89_PHY_DCFO_STATE_NORMAL;
2434 			cfo->phy_cfo_trk_cnt = 0;
2435 			cfo->cfo_trig_by_timer_en = false;
2436 		}
2437 		break;
2438 	default:
2439 		cfo->phy_cfo_status = RTW89_PHY_DCFO_STATE_NORMAL;
2440 		cfo->phy_cfo_trk_cnt = 0;
2441 		break;
2442 	}
2443 	rtw89_debug(rtwdev, RTW89_DBG_CFO,
2444 		    "[CFO]WatchDog tp=%d,state=%d,timer_en=%d,trk_cnt=%d,thermal=%ld\n",
2445 		    stats->tx_throughput, cfo->phy_cfo_status,
2446 		    cfo->cfo_trig_by_timer_en, cfo->phy_cfo_trk_cnt,
2447 		    ewma_thermal_read(&rtwdev->phystat.avg_thermal[0]));
2448 	if (cfo->cfo_trig_by_timer_en)
2449 		return;
2450 	rtw89_phy_cfo_dm(rtwdev);
2451 }
2452 
2453 void rtw89_phy_cfo_parse(struct rtw89_dev *rtwdev, s16 cfo_val,
2454 			 struct rtw89_rx_phy_ppdu *phy_ppdu)
2455 {
2456 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2457 	u8 macid = phy_ppdu->mac_id;
2458 
2459 	cfo->cfo_tail[macid] += cfo_val;
2460 	cfo->cfo_cnt[macid]++;
2461 	cfo->packet_count++;
2462 }
2463 
2464 static void rtw89_phy_stat_thermal_update(struct rtw89_dev *rtwdev)
2465 {
2466 	struct rtw89_phy_stat *phystat = &rtwdev->phystat;
2467 	int i;
2468 	u8 th;
2469 
2470 	for (i = 0; i < rtwdev->chip->rf_path_num; i++) {
2471 		th = rtw89_chip_get_thermal(rtwdev, i);
2472 		if (th)
2473 			ewma_thermal_add(&phystat->avg_thermal[i], th);
2474 
2475 		rtw89_debug(rtwdev, RTW89_DBG_RFK_TRACK,
2476 			    "path(%d) thermal cur=%u avg=%ld", i, th,
2477 			    ewma_thermal_read(&phystat->avg_thermal[i]));
2478 	}
2479 }
2480 
2481 struct rtw89_phy_iter_rssi_data {
2482 	struct rtw89_dev *rtwdev;
2483 	struct rtw89_phy_ch_info *ch_info;
2484 	bool rssi_changed;
2485 };
2486 
2487 static void rtw89_phy_stat_rssi_update_iter(void *data,
2488 					    struct ieee80211_sta *sta)
2489 {
2490 	struct rtw89_sta *rtwsta = (struct rtw89_sta *)sta->drv_priv;
2491 	struct rtw89_phy_iter_rssi_data *rssi_data =
2492 					(struct rtw89_phy_iter_rssi_data *)data;
2493 	struct rtw89_phy_ch_info *ch_info = rssi_data->ch_info;
2494 	unsigned long rssi_curr;
2495 
2496 	rssi_curr = ewma_rssi_read(&rtwsta->avg_rssi);
2497 
2498 	if (rssi_curr < ch_info->rssi_min) {
2499 		ch_info->rssi_min = rssi_curr;
2500 		ch_info->rssi_min_macid = rtwsta->mac_id;
2501 	}
2502 
2503 	if (rtwsta->prev_rssi == 0) {
2504 		rtwsta->prev_rssi = rssi_curr;
2505 	} else if (abs((int)rtwsta->prev_rssi - (int)rssi_curr) > (3 << RSSI_FACTOR)) {
2506 		rtwsta->prev_rssi = rssi_curr;
2507 		rssi_data->rssi_changed = true;
2508 	}
2509 }
2510 
2511 static void rtw89_phy_stat_rssi_update(struct rtw89_dev *rtwdev)
2512 {
2513 	struct rtw89_phy_iter_rssi_data rssi_data = {0};
2514 
2515 	rssi_data.rtwdev = rtwdev;
2516 	rssi_data.ch_info = &rtwdev->ch_info;
2517 	rssi_data.ch_info->rssi_min = U8_MAX;
2518 	ieee80211_iterate_stations_atomic(rtwdev->hw,
2519 					  rtw89_phy_stat_rssi_update_iter,
2520 					  &rssi_data);
2521 	if (rssi_data.rssi_changed)
2522 		rtw89_btc_ntfy_wl_sta(rtwdev);
2523 }
2524 
2525 static void rtw89_phy_stat_init(struct rtw89_dev *rtwdev)
2526 {
2527 	struct rtw89_phy_stat *phystat = &rtwdev->phystat;
2528 	int i;
2529 
2530 	for (i = 0; i < rtwdev->chip->rf_path_num; i++)
2531 		ewma_thermal_init(&phystat->avg_thermal[i]);
2532 
2533 	rtw89_phy_stat_thermal_update(rtwdev);
2534 
2535 	memset(&phystat->cur_pkt_stat, 0, sizeof(phystat->cur_pkt_stat));
2536 	memset(&phystat->last_pkt_stat, 0, sizeof(phystat->last_pkt_stat));
2537 }
2538 
2539 void rtw89_phy_stat_track(struct rtw89_dev *rtwdev)
2540 {
2541 	struct rtw89_phy_stat *phystat = &rtwdev->phystat;
2542 
2543 	rtw89_phy_stat_thermal_update(rtwdev);
2544 	rtw89_phy_stat_rssi_update(rtwdev);
2545 
2546 	phystat->last_pkt_stat = phystat->cur_pkt_stat;
2547 	memset(&phystat->cur_pkt_stat, 0, sizeof(phystat->cur_pkt_stat));
2548 }
2549 
2550 static u16 rtw89_phy_ccx_us_to_idx(struct rtw89_dev *rtwdev, u32 time_us)
2551 {
2552 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2553 
2554 	return time_us >> (ilog2(CCX_US_BASE_RATIO) + env->ccx_unit_idx);
2555 }
2556 
2557 static u32 rtw89_phy_ccx_idx_to_us(struct rtw89_dev *rtwdev, u16 idx)
2558 {
2559 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2560 
2561 	return idx << (ilog2(CCX_US_BASE_RATIO) + env->ccx_unit_idx);
2562 }
2563 
2564 static void rtw89_phy_ccx_top_setting_init(struct rtw89_dev *rtwdev)
2565 {
2566 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2567 
2568 	env->ccx_manual_ctrl = false;
2569 	env->ccx_ongoing = false;
2570 	env->ccx_rac_lv = RTW89_RAC_RELEASE;
2571 	env->ccx_rpt_stamp = 0;
2572 	env->ccx_period = 0;
2573 	env->ccx_unit_idx = RTW89_CCX_32_US;
2574 	env->ccx_trigger_time = 0;
2575 	env->ccx_edcca_opt_bw_idx = RTW89_CCX_EDCCA_BW20_0;
2576 
2577 	rtw89_phy_set_phy_regs(rtwdev, R_CCX, B_CCX_EN_MSK, 1);
2578 	rtw89_phy_set_phy_regs(rtwdev, R_CCX, B_CCX_TRIG_OPT_MSK, 1);
2579 	rtw89_phy_set_phy_regs(rtwdev, R_CCX, B_MEASUREMENT_TRIG_MSK, 1);
2580 	rtw89_phy_set_phy_regs(rtwdev, R_CCX, B_CCX_EDCCA_OPT_MSK,
2581 			       RTW89_CCX_EDCCA_BW20_0);
2582 }
2583 
2584 static u16 rtw89_phy_ccx_get_report(struct rtw89_dev *rtwdev, u16 report,
2585 				    u16 score)
2586 {
2587 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2588 	u32 numer = 0;
2589 	u16 ret = 0;
2590 
2591 	numer = report * score + (env->ccx_period >> 1);
2592 	if (env->ccx_period)
2593 		ret = numer / env->ccx_period;
2594 
2595 	return ret >= score ? score - 1 : ret;
2596 }
2597 
2598 static void rtw89_phy_ccx_ms_to_period_unit(struct rtw89_dev *rtwdev,
2599 					    u16 time_ms, u32 *period,
2600 					    u32 *unit_idx)
2601 {
2602 	u32 idx;
2603 	u8 quotient;
2604 
2605 	if (time_ms >= CCX_MAX_PERIOD)
2606 		time_ms = CCX_MAX_PERIOD;
2607 
2608 	quotient = CCX_MAX_PERIOD_UNIT * time_ms / CCX_MAX_PERIOD;
2609 
2610 	if (quotient < 4)
2611 		idx = RTW89_CCX_4_US;
2612 	else if (quotient < 8)
2613 		idx = RTW89_CCX_8_US;
2614 	else if (quotient < 16)
2615 		idx = RTW89_CCX_16_US;
2616 	else
2617 		idx = RTW89_CCX_32_US;
2618 
2619 	*unit_idx = idx;
2620 	*period = (time_ms * MS_TO_4US_RATIO) >> idx;
2621 
2622 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2623 		    "[Trigger Time] period:%d, unit_idx:%d\n",
2624 		    *period, *unit_idx);
2625 }
2626 
2627 static void rtw89_phy_ccx_racing_release(struct rtw89_dev *rtwdev)
2628 {
2629 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2630 
2631 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2632 		    "lv:(%d)->(0)\n", env->ccx_rac_lv);
2633 
2634 	env->ccx_ongoing = false;
2635 	env->ccx_rac_lv = RTW89_RAC_RELEASE;
2636 	env->ifs_clm_app = RTW89_IFS_CLM_BACKGROUND;
2637 }
2638 
2639 static bool rtw89_phy_ifs_clm_th_update_check(struct rtw89_dev *rtwdev,
2640 					      struct rtw89_ccx_para_info *para)
2641 {
2642 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2643 	bool is_update = env->ifs_clm_app != para->ifs_clm_app;
2644 	u8 i = 0;
2645 	u16 *ifs_th_l = env->ifs_clm_th_l;
2646 	u16 *ifs_th_h = env->ifs_clm_th_h;
2647 	u32 ifs_th0_us = 0, ifs_th_times = 0;
2648 	u32 ifs_th_h_us[RTW89_IFS_CLM_NUM] = {0};
2649 
2650 	if (!is_update)
2651 		goto ifs_update_finished;
2652 
2653 	switch (para->ifs_clm_app) {
2654 	case RTW89_IFS_CLM_INIT:
2655 	case RTW89_IFS_CLM_BACKGROUND:
2656 	case RTW89_IFS_CLM_ACS:
2657 	case RTW89_IFS_CLM_DBG:
2658 	case RTW89_IFS_CLM_DIG:
2659 	case RTW89_IFS_CLM_TDMA_DIG:
2660 		ifs_th0_us = IFS_CLM_TH0_UPPER;
2661 		ifs_th_times = IFS_CLM_TH_MUL;
2662 		break;
2663 	case RTW89_IFS_CLM_DBG_MANUAL:
2664 		ifs_th0_us = para->ifs_clm_manual_th0;
2665 		ifs_th_times = para->ifs_clm_manual_th_times;
2666 		break;
2667 	default:
2668 		break;
2669 	}
2670 
2671 	/* Set sampling threshold for 4 different regions, unit in idx_cnt.
2672 	 * low[i] = high[i-1] + 1
2673 	 * high[i] = high[i-1] * ifs_th_times
2674 	 */
2675 	ifs_th_l[IFS_CLM_TH_START_IDX] = 0;
2676 	ifs_th_h_us[IFS_CLM_TH_START_IDX] = ifs_th0_us;
2677 	ifs_th_h[IFS_CLM_TH_START_IDX] = rtw89_phy_ccx_us_to_idx(rtwdev,
2678 								 ifs_th0_us);
2679 	for (i = 1; i < RTW89_IFS_CLM_NUM; i++) {
2680 		ifs_th_l[i] = ifs_th_h[i - 1] + 1;
2681 		ifs_th_h_us[i] = ifs_th_h_us[i - 1] * ifs_th_times;
2682 		ifs_th_h[i] = rtw89_phy_ccx_us_to_idx(rtwdev, ifs_th_h_us[i]);
2683 	}
2684 
2685 ifs_update_finished:
2686 	if (!is_update)
2687 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2688 			    "No need to update IFS_TH\n");
2689 
2690 	return is_update;
2691 }
2692 
2693 static void rtw89_phy_ifs_clm_set_th_reg(struct rtw89_dev *rtwdev)
2694 {
2695 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2696 	u8 i = 0;
2697 
2698 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T1, B_IFS_T1_TH_LOW_MSK,
2699 			       env->ifs_clm_th_l[0]);
2700 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T2, B_IFS_T2_TH_LOW_MSK,
2701 			       env->ifs_clm_th_l[1]);
2702 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T3, B_IFS_T3_TH_LOW_MSK,
2703 			       env->ifs_clm_th_l[2]);
2704 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T4, B_IFS_T4_TH_LOW_MSK,
2705 			       env->ifs_clm_th_l[3]);
2706 
2707 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T1, B_IFS_T1_TH_HIGH_MSK,
2708 			       env->ifs_clm_th_h[0]);
2709 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T2, B_IFS_T2_TH_HIGH_MSK,
2710 			       env->ifs_clm_th_h[1]);
2711 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T3, B_IFS_T3_TH_HIGH_MSK,
2712 			       env->ifs_clm_th_h[2]);
2713 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T4, B_IFS_T4_TH_HIGH_MSK,
2714 			       env->ifs_clm_th_h[3]);
2715 
2716 	for (i = 0; i < RTW89_IFS_CLM_NUM; i++)
2717 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2718 			    "Update IFS_T%d_th{low, high} : {%d, %d}\n",
2719 			    i + 1, env->ifs_clm_th_l[i], env->ifs_clm_th_h[i]);
2720 }
2721 
2722 static void rtw89_phy_ifs_clm_setting_init(struct rtw89_dev *rtwdev)
2723 {
2724 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2725 	struct rtw89_ccx_para_info para = {0};
2726 
2727 	env->ifs_clm_app = RTW89_IFS_CLM_BACKGROUND;
2728 	env->ifs_clm_mntr_time = 0;
2729 
2730 	para.ifs_clm_app = RTW89_IFS_CLM_INIT;
2731 	if (rtw89_phy_ifs_clm_th_update_check(rtwdev, &para))
2732 		rtw89_phy_ifs_clm_set_th_reg(rtwdev);
2733 
2734 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_COUNTER, B_IFS_COLLECT_EN,
2735 			       true);
2736 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T1, B_IFS_T1_EN_MSK, true);
2737 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T2, B_IFS_T2_EN_MSK, true);
2738 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T3, B_IFS_T3_EN_MSK, true);
2739 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T4, B_IFS_T4_EN_MSK, true);
2740 }
2741 
2742 static int rtw89_phy_ccx_racing_ctrl(struct rtw89_dev *rtwdev,
2743 				     enum rtw89_env_racing_lv level)
2744 {
2745 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2746 	int ret = 0;
2747 
2748 	if (level >= RTW89_RAC_MAX_NUM) {
2749 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2750 			    "[WARNING] Wrong LV=%d\n", level);
2751 		return -EINVAL;
2752 	}
2753 
2754 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2755 		    "ccx_ongoing=%d, level:(%d)->(%d)\n", env->ccx_ongoing,
2756 		    env->ccx_rac_lv, level);
2757 
2758 	if (env->ccx_ongoing) {
2759 		if (level <= env->ccx_rac_lv)
2760 			ret = -EINVAL;
2761 		else
2762 			env->ccx_ongoing = false;
2763 	}
2764 
2765 	if (ret == 0)
2766 		env->ccx_rac_lv = level;
2767 
2768 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK, "ccx racing success=%d\n",
2769 		    !ret);
2770 
2771 	return ret;
2772 }
2773 
2774 static void rtw89_phy_ccx_trigger(struct rtw89_dev *rtwdev)
2775 {
2776 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2777 
2778 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_COUNTER, B_IFS_COUNTER_CLR_MSK, 0);
2779 	rtw89_phy_set_phy_regs(rtwdev, R_CCX, B_MEASUREMENT_TRIG_MSK, 0);
2780 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_COUNTER, B_IFS_COUNTER_CLR_MSK, 1);
2781 	rtw89_phy_set_phy_regs(rtwdev, R_CCX, B_MEASUREMENT_TRIG_MSK, 1);
2782 
2783 	env->ccx_rpt_stamp++;
2784 	env->ccx_ongoing = true;
2785 }
2786 
2787 static void rtw89_phy_ifs_clm_get_utility(struct rtw89_dev *rtwdev)
2788 {
2789 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2790 	u8 i = 0;
2791 	u32 res = 0;
2792 
2793 	env->ifs_clm_tx_ratio =
2794 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_tx, PERCENT);
2795 	env->ifs_clm_edcca_excl_cca_ratio =
2796 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_edcca_excl_cca,
2797 					 PERCENT);
2798 	env->ifs_clm_cck_fa_ratio =
2799 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_cckfa, PERCENT);
2800 	env->ifs_clm_ofdm_fa_ratio =
2801 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_ofdmfa, PERCENT);
2802 	env->ifs_clm_cck_cca_excl_fa_ratio =
2803 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_cckcca_excl_fa,
2804 					 PERCENT);
2805 	env->ifs_clm_ofdm_cca_excl_fa_ratio =
2806 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_ofdmcca_excl_fa,
2807 					 PERCENT);
2808 	env->ifs_clm_cck_fa_permil =
2809 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_cckfa, PERMIL);
2810 	env->ifs_clm_ofdm_fa_permil =
2811 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_ofdmfa, PERMIL);
2812 
2813 	for (i = 0; i < RTW89_IFS_CLM_NUM; i++) {
2814 		if (env->ifs_clm_his[i] > ENV_MNTR_IFSCLM_HIS_MAX) {
2815 			env->ifs_clm_ifs_avg[i] = ENV_MNTR_FAIL_DWORD;
2816 		} else {
2817 			env->ifs_clm_ifs_avg[i] =
2818 				rtw89_phy_ccx_idx_to_us(rtwdev,
2819 							env->ifs_clm_avg[i]);
2820 		}
2821 
2822 		res = rtw89_phy_ccx_idx_to_us(rtwdev, env->ifs_clm_cca[i]);
2823 		res += env->ifs_clm_his[i] >> 1;
2824 		if (env->ifs_clm_his[i])
2825 			res /= env->ifs_clm_his[i];
2826 		else
2827 			res = 0;
2828 		env->ifs_clm_cca_avg[i] = res;
2829 	}
2830 
2831 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2832 		    "IFS-CLM ratio {Tx, EDCCA_exclu_cca} = {%d, %d}\n",
2833 		    env->ifs_clm_tx_ratio, env->ifs_clm_edcca_excl_cca_ratio);
2834 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2835 		    "IFS-CLM FA ratio {CCK, OFDM} = {%d, %d}\n",
2836 		    env->ifs_clm_cck_fa_ratio, env->ifs_clm_ofdm_fa_ratio);
2837 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2838 		    "IFS-CLM FA permil {CCK, OFDM} = {%d, %d}\n",
2839 		    env->ifs_clm_cck_fa_permil, env->ifs_clm_ofdm_fa_permil);
2840 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2841 		    "IFS-CLM CCA_exclu_FA ratio {CCK, OFDM} = {%d, %d}\n",
2842 		    env->ifs_clm_cck_cca_excl_fa_ratio,
2843 		    env->ifs_clm_ofdm_cca_excl_fa_ratio);
2844 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2845 		    "Time:[his, ifs_avg(us), cca_avg(us)]\n");
2846 	for (i = 0; i < RTW89_IFS_CLM_NUM; i++)
2847 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK, "T%d:[%d, %d, %d]\n",
2848 			    i + 1, env->ifs_clm_his[i], env->ifs_clm_ifs_avg[i],
2849 			    env->ifs_clm_cca_avg[i]);
2850 }
2851 
2852 static bool rtw89_phy_ifs_clm_get_result(struct rtw89_dev *rtwdev)
2853 {
2854 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2855 	u8 i = 0;
2856 
2857 	if (rtw89_phy_read32_mask(rtwdev, R_IFSCNT, B_IFSCNT_DONE_MSK) == 0) {
2858 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2859 			    "Get IFS_CLM report Fail\n");
2860 		return false;
2861 	}
2862 
2863 	env->ifs_clm_tx =
2864 		rtw89_phy_read32_mask(rtwdev, R_IFS_CLM_TX_CNT,
2865 				      B_IFS_CLM_TX_CNT_MSK);
2866 	env->ifs_clm_edcca_excl_cca =
2867 		rtw89_phy_read32_mask(rtwdev, R_IFS_CLM_TX_CNT,
2868 				      B_IFS_CLM_EDCCA_EXCLUDE_CCA_FA_MSK);
2869 	env->ifs_clm_cckcca_excl_fa =
2870 		rtw89_phy_read32_mask(rtwdev, R_IFS_CLM_CCA,
2871 				      B_IFS_CLM_CCKCCA_EXCLUDE_FA_MSK);
2872 	env->ifs_clm_ofdmcca_excl_fa =
2873 		rtw89_phy_read32_mask(rtwdev, R_IFS_CLM_CCA,
2874 				      B_IFS_CLM_OFDMCCA_EXCLUDE_FA_MSK);
2875 	env->ifs_clm_cckfa =
2876 		rtw89_phy_read32_mask(rtwdev, R_IFS_CLM_FA,
2877 				      B_IFS_CLM_CCK_FA_MSK);
2878 	env->ifs_clm_ofdmfa =
2879 		rtw89_phy_read32_mask(rtwdev, R_IFS_CLM_FA,
2880 				      B_IFS_CLM_OFDM_FA_MSK);
2881 
2882 	env->ifs_clm_his[0] =
2883 		rtw89_phy_read32_mask(rtwdev, R_IFS_HIS, B_IFS_T1_HIS_MSK);
2884 	env->ifs_clm_his[1] =
2885 		rtw89_phy_read32_mask(rtwdev, R_IFS_HIS, B_IFS_T2_HIS_MSK);
2886 	env->ifs_clm_his[2] =
2887 		rtw89_phy_read32_mask(rtwdev, R_IFS_HIS, B_IFS_T3_HIS_MSK);
2888 	env->ifs_clm_his[3] =
2889 		rtw89_phy_read32_mask(rtwdev, R_IFS_HIS, B_IFS_T4_HIS_MSK);
2890 
2891 	env->ifs_clm_avg[0] =
2892 		rtw89_phy_read32_mask(rtwdev, R_IFS_AVG_L, B_IFS_T1_AVG_MSK);
2893 	env->ifs_clm_avg[1] =
2894 		rtw89_phy_read32_mask(rtwdev, R_IFS_AVG_L, B_IFS_T2_AVG_MSK);
2895 	env->ifs_clm_avg[2] =
2896 		rtw89_phy_read32_mask(rtwdev, R_IFS_AVG_H, B_IFS_T3_AVG_MSK);
2897 	env->ifs_clm_avg[3] =
2898 		rtw89_phy_read32_mask(rtwdev, R_IFS_AVG_H, B_IFS_T4_AVG_MSK);
2899 
2900 	env->ifs_clm_cca[0] =
2901 		rtw89_phy_read32_mask(rtwdev, R_IFS_CCA_L, B_IFS_T1_CCA_MSK);
2902 	env->ifs_clm_cca[1] =
2903 		rtw89_phy_read32_mask(rtwdev, R_IFS_CCA_L, B_IFS_T2_CCA_MSK);
2904 	env->ifs_clm_cca[2] =
2905 		rtw89_phy_read32_mask(rtwdev, R_IFS_CCA_H, B_IFS_T3_CCA_MSK);
2906 	env->ifs_clm_cca[3] =
2907 		rtw89_phy_read32_mask(rtwdev, R_IFS_CCA_H, B_IFS_T4_CCA_MSK);
2908 
2909 	env->ifs_clm_total_ifs =
2910 		rtw89_phy_read32_mask(rtwdev, R_IFSCNT, B_IFSCNT_TOTAL_CNT_MSK);
2911 
2912 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK, "IFS-CLM total_ifs = %d\n",
2913 		    env->ifs_clm_total_ifs);
2914 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2915 		    "{Tx, EDCCA_exclu_cca} = {%d, %d}\n",
2916 		    env->ifs_clm_tx, env->ifs_clm_edcca_excl_cca);
2917 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2918 		    "IFS-CLM FA{CCK, OFDM} = {%d, %d}\n",
2919 		    env->ifs_clm_cckfa, env->ifs_clm_ofdmfa);
2920 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2921 		    "IFS-CLM CCA_exclu_FA{CCK, OFDM} = {%d, %d}\n",
2922 		    env->ifs_clm_cckcca_excl_fa, env->ifs_clm_ofdmcca_excl_fa);
2923 
2924 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK, "Time:[his, avg, cca]\n");
2925 	for (i = 0; i < RTW89_IFS_CLM_NUM; i++)
2926 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2927 			    "T%d:[%d, %d, %d]\n", i + 1, env->ifs_clm_his[i],
2928 			    env->ifs_clm_avg[i], env->ifs_clm_cca[i]);
2929 
2930 	rtw89_phy_ifs_clm_get_utility(rtwdev);
2931 
2932 	return true;
2933 }
2934 
2935 static int rtw89_phy_ifs_clm_set(struct rtw89_dev *rtwdev,
2936 				 struct rtw89_ccx_para_info *para)
2937 {
2938 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2939 	u32 period = 0;
2940 	u32 unit_idx = 0;
2941 
2942 	if (para->mntr_time == 0) {
2943 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2944 			    "[WARN] MNTR_TIME is 0\n");
2945 		return -EINVAL;
2946 	}
2947 
2948 	if (rtw89_phy_ccx_racing_ctrl(rtwdev, para->rac_lv))
2949 		return -EINVAL;
2950 
2951 	if (para->mntr_time != env->ifs_clm_mntr_time) {
2952 		rtw89_phy_ccx_ms_to_period_unit(rtwdev, para->mntr_time,
2953 						&period, &unit_idx);
2954 		rtw89_phy_set_phy_regs(rtwdev, R_IFS_COUNTER,
2955 				       B_IFS_CLM_PERIOD_MSK, period);
2956 		rtw89_phy_set_phy_regs(rtwdev, R_IFS_COUNTER,
2957 				       B_IFS_CLM_COUNTER_UNIT_MSK, unit_idx);
2958 
2959 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2960 			    "Update IFS-CLM time ((%d)) -> ((%d))\n",
2961 			    env->ifs_clm_mntr_time, para->mntr_time);
2962 
2963 		env->ifs_clm_mntr_time = para->mntr_time;
2964 		env->ccx_period = (u16)period;
2965 		env->ccx_unit_idx = (u8)unit_idx;
2966 	}
2967 
2968 	if (rtw89_phy_ifs_clm_th_update_check(rtwdev, para)) {
2969 		env->ifs_clm_app = para->ifs_clm_app;
2970 		rtw89_phy_ifs_clm_set_th_reg(rtwdev);
2971 	}
2972 
2973 	return 0;
2974 }
2975 
2976 void rtw89_phy_env_monitor_track(struct rtw89_dev *rtwdev)
2977 {
2978 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2979 	struct rtw89_ccx_para_info para = {0};
2980 	u8 chk_result = RTW89_PHY_ENV_MON_CCX_FAIL;
2981 
2982 	env->ccx_watchdog_result = RTW89_PHY_ENV_MON_CCX_FAIL;
2983 	if (env->ccx_manual_ctrl) {
2984 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2985 			    "CCX in manual ctrl\n");
2986 		return;
2987 	}
2988 
2989 	/* only ifs_clm for now */
2990 	if (rtw89_phy_ifs_clm_get_result(rtwdev))
2991 		env->ccx_watchdog_result |= RTW89_PHY_ENV_MON_IFS_CLM;
2992 
2993 	rtw89_phy_ccx_racing_release(rtwdev);
2994 	para.mntr_time = 1900;
2995 	para.rac_lv = RTW89_RAC_LV_1;
2996 	para.ifs_clm_app = RTW89_IFS_CLM_BACKGROUND;
2997 
2998 	if (rtw89_phy_ifs_clm_set(rtwdev, &para) == 0)
2999 		chk_result |= RTW89_PHY_ENV_MON_IFS_CLM;
3000 	if (chk_result)
3001 		rtw89_phy_ccx_trigger(rtwdev);
3002 
3003 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3004 		    "get_result=0x%x, chk_result:0x%x\n",
3005 		    env->ccx_watchdog_result, chk_result);
3006 }
3007 
3008 static bool rtw89_physts_ie_page_valid(enum rtw89_phy_status_bitmap *ie_page)
3009 {
3010 	if (*ie_page > RTW89_PHYSTS_BITMAP_NUM ||
3011 	    *ie_page == RTW89_RSVD_9)
3012 		return false;
3013 	else if (*ie_page > RTW89_RSVD_9)
3014 		*ie_page -= 1;
3015 
3016 	return true;
3017 }
3018 
3019 static u32 rtw89_phy_get_ie_bitmap_addr(enum rtw89_phy_status_bitmap ie_page)
3020 {
3021 	static const u8 ie_page_shift = 2;
3022 
3023 	return R_PHY_STS_BITMAP_ADDR_START + (ie_page << ie_page_shift);
3024 }
3025 
3026 static u32 rtw89_physts_get_ie_bitmap(struct rtw89_dev *rtwdev,
3027 				      enum rtw89_phy_status_bitmap ie_page)
3028 {
3029 	u32 addr;
3030 
3031 	if (!rtw89_physts_ie_page_valid(&ie_page))
3032 		return 0;
3033 
3034 	addr = rtw89_phy_get_ie_bitmap_addr(ie_page);
3035 
3036 	return rtw89_phy_read32(rtwdev, addr);
3037 }
3038 
3039 static void rtw89_physts_set_ie_bitmap(struct rtw89_dev *rtwdev,
3040 				       enum rtw89_phy_status_bitmap ie_page,
3041 				       u32 val)
3042 {
3043 	const struct rtw89_chip_info *chip = rtwdev->chip;
3044 	u32 addr;
3045 
3046 	if (!rtw89_physts_ie_page_valid(&ie_page))
3047 		return;
3048 
3049 	if (chip->chip_id == RTL8852A)
3050 		val &= B_PHY_STS_BITMAP_MSK_52A;
3051 
3052 	addr = rtw89_phy_get_ie_bitmap_addr(ie_page);
3053 	rtw89_phy_write32(rtwdev, addr, val);
3054 }
3055 
3056 static void rtw89_physts_enable_ie_bitmap(struct rtw89_dev *rtwdev,
3057 					  enum rtw89_phy_status_bitmap bitmap,
3058 					  enum rtw89_phy_status_ie_type ie,
3059 					  bool enable)
3060 {
3061 	u32 val = rtw89_physts_get_ie_bitmap(rtwdev, bitmap);
3062 
3063 	if (enable)
3064 		val |= BIT(ie);
3065 	else
3066 		val &= ~BIT(ie);
3067 
3068 	rtw89_physts_set_ie_bitmap(rtwdev, bitmap, val);
3069 }
3070 
3071 static void rtw89_physts_enable_fail_report(struct rtw89_dev *rtwdev,
3072 					    bool enable,
3073 					    enum rtw89_phy_idx phy_idx)
3074 {
3075 	if (enable) {
3076 		rtw89_phy_write32_clr(rtwdev, R_PLCP_HISTOGRAM,
3077 				      B_STS_DIS_TRIG_BY_FAIL);
3078 		rtw89_phy_write32_clr(rtwdev, R_PLCP_HISTOGRAM,
3079 				      B_STS_DIS_TRIG_BY_BRK);
3080 	} else {
3081 		rtw89_phy_write32_set(rtwdev, R_PLCP_HISTOGRAM,
3082 				      B_STS_DIS_TRIG_BY_FAIL);
3083 		rtw89_phy_write32_set(rtwdev, R_PLCP_HISTOGRAM,
3084 				      B_STS_DIS_TRIG_BY_BRK);
3085 	}
3086 }
3087 
3088 static void rtw89_physts_parsing_init(struct rtw89_dev *rtwdev)
3089 {
3090 	const struct rtw89_chip_info *chip = rtwdev->chip;
3091 	u8 i;
3092 
3093 	if (chip->chip_id == RTL8852A && rtwdev->hal.cv == CHIP_CBV)
3094 		rtw89_physts_enable_fail_report(rtwdev, false, RTW89_PHY_0);
3095 
3096 	for (i = 0; i < RTW89_PHYSTS_BITMAP_NUM; i++) {
3097 		if (i >= RTW89_CCK_PKT)
3098 			rtw89_physts_enable_ie_bitmap(rtwdev, i,
3099 						      RTW89_PHYSTS_IE09_FTR_0,
3100 						      true);
3101 		if ((i >= RTW89_CCK_BRK && i <= RTW89_VHT_MU) ||
3102 		    (i >= RTW89_RSVD_9 && i <= RTW89_CCK_PKT))
3103 			continue;
3104 		rtw89_physts_enable_ie_bitmap(rtwdev, i,
3105 					      RTW89_PHYSTS_IE24_OFDM_TD_PATH_A,
3106 					      true);
3107 	}
3108 	rtw89_physts_enable_ie_bitmap(rtwdev, RTW89_VHT_PKT,
3109 				      RTW89_PHYSTS_IE13_DL_MU_DEF, true);
3110 	rtw89_physts_enable_ie_bitmap(rtwdev, RTW89_HE_PKT,
3111 				      RTW89_PHYSTS_IE13_DL_MU_DEF, true);
3112 
3113 	/* force IE01 for channel index, only channel field is valid */
3114 	rtw89_physts_enable_ie_bitmap(rtwdev, RTW89_CCK_PKT,
3115 				      RTW89_PHYSTS_IE01_CMN_OFDM, true);
3116 }
3117 
3118 static void rtw89_phy_dig_read_gain_table(struct rtw89_dev *rtwdev, int type)
3119 {
3120 	const struct rtw89_chip_info *chip = rtwdev->chip;
3121 	struct rtw89_dig_info *dig = &rtwdev->dig;
3122 	const struct rtw89_phy_dig_gain_cfg *cfg;
3123 	const char *msg;
3124 	u8 i;
3125 	s8 gain_base;
3126 	s8 *gain_arr;
3127 	u32 tmp;
3128 
3129 	switch (type) {
3130 	case RTW89_DIG_GAIN_LNA_G:
3131 		gain_arr = dig->lna_gain_g;
3132 		gain_base = LNA0_GAIN;
3133 		cfg = chip->dig_table->cfg_lna_g;
3134 		msg = "lna_gain_g";
3135 		break;
3136 	case RTW89_DIG_GAIN_TIA_G:
3137 		gain_arr = dig->tia_gain_g;
3138 		gain_base = TIA0_GAIN_G;
3139 		cfg = chip->dig_table->cfg_tia_g;
3140 		msg = "tia_gain_g";
3141 		break;
3142 	case RTW89_DIG_GAIN_LNA_A:
3143 		gain_arr = dig->lna_gain_a;
3144 		gain_base = LNA0_GAIN;
3145 		cfg = chip->dig_table->cfg_lna_a;
3146 		msg = "lna_gain_a";
3147 		break;
3148 	case RTW89_DIG_GAIN_TIA_A:
3149 		gain_arr = dig->tia_gain_a;
3150 		gain_base = TIA0_GAIN_A;
3151 		cfg = chip->dig_table->cfg_tia_a;
3152 		msg = "tia_gain_a";
3153 		break;
3154 	default:
3155 		return;
3156 	}
3157 
3158 	for (i = 0; i < cfg->size; i++) {
3159 		tmp = rtw89_phy_read32_mask(rtwdev, cfg->table[i].addr,
3160 					    cfg->table[i].mask);
3161 		tmp >>= DIG_GAIN_SHIFT;
3162 		gain_arr[i] = sign_extend32(tmp, U4_MAX_BIT) + gain_base;
3163 		gain_base += DIG_GAIN;
3164 
3165 		rtw89_debug(rtwdev, RTW89_DBG_DIG, "%s[%d]=%d\n",
3166 			    msg, i, gain_arr[i]);
3167 	}
3168 }
3169 
3170 static void rtw89_phy_dig_update_gain_para(struct rtw89_dev *rtwdev)
3171 {
3172 	struct rtw89_dig_info *dig = &rtwdev->dig;
3173 	u32 tmp;
3174 	u8 i;
3175 
3176 	if (!rtwdev->hal.support_igi)
3177 		return;
3178 
3179 	tmp = rtw89_phy_read32_mask(rtwdev, R_PATH0_IB_PKPW,
3180 				    B_PATH0_IB_PKPW_MSK);
3181 	dig->ib_pkpwr = sign_extend32(tmp >> DIG_GAIN_SHIFT, U8_MAX_BIT);
3182 	dig->ib_pbk = rtw89_phy_read32_mask(rtwdev, R_PATH0_IB_PBK,
3183 					    B_PATH0_IB_PBK_MSK);
3184 	rtw89_debug(rtwdev, RTW89_DBG_DIG, "ib_pkpwr=%d, ib_pbk=%d\n",
3185 		    dig->ib_pkpwr, dig->ib_pbk);
3186 
3187 	for (i = RTW89_DIG_GAIN_LNA_G; i < RTW89_DIG_GAIN_MAX; i++)
3188 		rtw89_phy_dig_read_gain_table(rtwdev, i);
3189 }
3190 
3191 static const u8 rssi_nolink = 22;
3192 static const u8 igi_rssi_th[IGI_RSSI_TH_NUM] = {68, 84, 90, 98, 104};
3193 static const u16 fa_th_2g[FA_TH_NUM] = {22, 44, 66, 88};
3194 static const u16 fa_th_5g[FA_TH_NUM] = {4, 8, 12, 16};
3195 static const u16 fa_th_nolink[FA_TH_NUM] = {196, 352, 440, 528};
3196 
3197 static void rtw89_phy_dig_update_rssi_info(struct rtw89_dev *rtwdev)
3198 {
3199 	struct rtw89_phy_ch_info *ch_info = &rtwdev->ch_info;
3200 	struct rtw89_dig_info *dig = &rtwdev->dig;
3201 	bool is_linked = rtwdev->total_sta_assoc > 0;
3202 
3203 	if (is_linked) {
3204 		dig->igi_rssi = ch_info->rssi_min >> 1;
3205 	} else {
3206 		rtw89_debug(rtwdev, RTW89_DBG_DIG, "RSSI update : NO Link\n");
3207 		dig->igi_rssi = rssi_nolink;
3208 	}
3209 }
3210 
3211 static void rtw89_phy_dig_update_para(struct rtw89_dev *rtwdev)
3212 {
3213 	struct rtw89_dig_info *dig = &rtwdev->dig;
3214 	bool is_linked = rtwdev->total_sta_assoc > 0;
3215 	const u16 *fa_th_src = NULL;
3216 
3217 	switch (rtwdev->hal.current_band_type) {
3218 	case RTW89_BAND_2G:
3219 		dig->lna_gain = dig->lna_gain_g;
3220 		dig->tia_gain = dig->tia_gain_g;
3221 		fa_th_src = is_linked ? fa_th_2g : fa_th_nolink;
3222 		dig->force_gaincode_idx_en = false;
3223 		dig->dyn_pd_th_en = true;
3224 		break;
3225 	case RTW89_BAND_5G:
3226 	default:
3227 		dig->lna_gain = dig->lna_gain_a;
3228 		dig->tia_gain = dig->tia_gain_a;
3229 		fa_th_src = is_linked ? fa_th_5g : fa_th_nolink;
3230 		dig->force_gaincode_idx_en = true;
3231 		dig->dyn_pd_th_en = true;
3232 		break;
3233 	}
3234 	memcpy(dig->fa_th, fa_th_src, sizeof(dig->fa_th));
3235 	memcpy(dig->igi_rssi_th, igi_rssi_th, sizeof(dig->igi_rssi_th));
3236 }
3237 
3238 static const u8 pd_low_th_offset = 20, dynamic_igi_min = 0x20;
3239 static const u8 igi_max_performance_mode = 0x5a;
3240 static const u8 dynamic_pd_threshold_max;
3241 
3242 static void rtw89_phy_dig_para_reset(struct rtw89_dev *rtwdev)
3243 {
3244 	struct rtw89_dig_info *dig = &rtwdev->dig;
3245 
3246 	dig->cur_gaincode.lna_idx = LNA_IDX_MAX;
3247 	dig->cur_gaincode.tia_idx = TIA_IDX_MAX;
3248 	dig->cur_gaincode.rxb_idx = RXB_IDX_MAX;
3249 	dig->force_gaincode.lna_idx = LNA_IDX_MAX;
3250 	dig->force_gaincode.tia_idx = TIA_IDX_MAX;
3251 	dig->force_gaincode.rxb_idx = RXB_IDX_MAX;
3252 
3253 	dig->dyn_igi_max = igi_max_performance_mode;
3254 	dig->dyn_igi_min = dynamic_igi_min;
3255 	dig->dyn_pd_th_max = dynamic_pd_threshold_max;
3256 	dig->pd_low_th_ofst = pd_low_th_offset;
3257 	dig->is_linked_pre = false;
3258 }
3259 
3260 static void rtw89_phy_dig_init(struct rtw89_dev *rtwdev)
3261 {
3262 	rtw89_phy_dig_update_gain_para(rtwdev);
3263 	rtw89_phy_dig_reset(rtwdev);
3264 }
3265 
3266 static u8 rtw89_phy_dig_lna_idx_by_rssi(struct rtw89_dev *rtwdev, u8 rssi)
3267 {
3268 	struct rtw89_dig_info *dig = &rtwdev->dig;
3269 	u8 lna_idx;
3270 
3271 	if (rssi < dig->igi_rssi_th[0])
3272 		lna_idx = RTW89_DIG_GAIN_LNA_IDX6;
3273 	else if (rssi < dig->igi_rssi_th[1])
3274 		lna_idx = RTW89_DIG_GAIN_LNA_IDX5;
3275 	else if (rssi < dig->igi_rssi_th[2])
3276 		lna_idx = RTW89_DIG_GAIN_LNA_IDX4;
3277 	else if (rssi < dig->igi_rssi_th[3])
3278 		lna_idx = RTW89_DIG_GAIN_LNA_IDX3;
3279 	else if (rssi < dig->igi_rssi_th[4])
3280 		lna_idx = RTW89_DIG_GAIN_LNA_IDX2;
3281 	else
3282 		lna_idx = RTW89_DIG_GAIN_LNA_IDX1;
3283 
3284 	return lna_idx;
3285 }
3286 
3287 static u8 rtw89_phy_dig_tia_idx_by_rssi(struct rtw89_dev *rtwdev, u8 rssi)
3288 {
3289 	struct rtw89_dig_info *dig = &rtwdev->dig;
3290 	u8 tia_idx;
3291 
3292 	if (rssi < dig->igi_rssi_th[0])
3293 		tia_idx = RTW89_DIG_GAIN_TIA_IDX1;
3294 	else
3295 		tia_idx = RTW89_DIG_GAIN_TIA_IDX0;
3296 
3297 	return tia_idx;
3298 }
3299 
3300 #define IB_PBK_BASE 110
3301 #define WB_RSSI_BASE 10
3302 static u8 rtw89_phy_dig_rxb_idx_by_rssi(struct rtw89_dev *rtwdev, u8 rssi,
3303 					struct rtw89_agc_gaincode_set *set)
3304 {
3305 	struct rtw89_dig_info *dig = &rtwdev->dig;
3306 	s8 lna_gain = dig->lna_gain[set->lna_idx];
3307 	s8 tia_gain = dig->tia_gain[set->tia_idx];
3308 	s32 wb_rssi = rssi + lna_gain + tia_gain;
3309 	s32 rxb_idx_tmp = IB_PBK_BASE + WB_RSSI_BASE;
3310 	u8 rxb_idx;
3311 
3312 	rxb_idx_tmp += dig->ib_pkpwr - dig->ib_pbk - wb_rssi;
3313 	rxb_idx = clamp_t(s32, rxb_idx_tmp, RXB_IDX_MIN, RXB_IDX_MAX);
3314 
3315 	rtw89_debug(rtwdev, RTW89_DBG_DIG, "wb_rssi=%03d, rxb_idx_tmp=%03d\n",
3316 		    wb_rssi, rxb_idx_tmp);
3317 
3318 	return rxb_idx;
3319 }
3320 
3321 static void rtw89_phy_dig_gaincode_by_rssi(struct rtw89_dev *rtwdev, u8 rssi,
3322 					   struct rtw89_agc_gaincode_set *set)
3323 {
3324 	set->lna_idx = rtw89_phy_dig_lna_idx_by_rssi(rtwdev, rssi);
3325 	set->tia_idx = rtw89_phy_dig_tia_idx_by_rssi(rtwdev, rssi);
3326 	set->rxb_idx = rtw89_phy_dig_rxb_idx_by_rssi(rtwdev, rssi, set);
3327 
3328 	rtw89_debug(rtwdev, RTW89_DBG_DIG,
3329 		    "final_rssi=%03d, (lna,tia,rab)=(%d,%d,%02d)\n",
3330 		    rssi, set->lna_idx, set->tia_idx, set->rxb_idx);
3331 }
3332 
3333 #define IGI_OFFSET_MAX 25
3334 #define IGI_OFFSET_MUL 2
3335 static void rtw89_phy_dig_igi_offset_by_env(struct rtw89_dev *rtwdev)
3336 {
3337 	struct rtw89_dig_info *dig = &rtwdev->dig;
3338 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
3339 	enum rtw89_dig_noisy_level noisy_lv;
3340 	u8 igi_offset = dig->fa_rssi_ofst;
3341 	u16 fa_ratio = 0;
3342 
3343 	fa_ratio = env->ifs_clm_cck_fa_permil + env->ifs_clm_ofdm_fa_permil;
3344 
3345 	if (fa_ratio < dig->fa_th[0])
3346 		noisy_lv = RTW89_DIG_NOISY_LEVEL0;
3347 	else if (fa_ratio < dig->fa_th[1])
3348 		noisy_lv = RTW89_DIG_NOISY_LEVEL1;
3349 	else if (fa_ratio < dig->fa_th[2])
3350 		noisy_lv = RTW89_DIG_NOISY_LEVEL2;
3351 	else if (fa_ratio < dig->fa_th[3])
3352 		noisy_lv = RTW89_DIG_NOISY_LEVEL3;
3353 	else
3354 		noisy_lv = RTW89_DIG_NOISY_LEVEL_MAX;
3355 
3356 	if (noisy_lv == RTW89_DIG_NOISY_LEVEL0 && igi_offset < 2)
3357 		igi_offset = 0;
3358 	else
3359 		igi_offset += noisy_lv * IGI_OFFSET_MUL;
3360 
3361 	igi_offset = min_t(u8, igi_offset, IGI_OFFSET_MAX);
3362 	dig->fa_rssi_ofst = igi_offset;
3363 
3364 	rtw89_debug(rtwdev, RTW89_DBG_DIG,
3365 		    "fa_th: [+6 (%d) +4 (%d) +2 (%d) 0 (%d) -2 ]\n",
3366 		    dig->fa_th[3], dig->fa_th[2], dig->fa_th[1], dig->fa_th[0]);
3367 
3368 	rtw89_debug(rtwdev, RTW89_DBG_DIG,
3369 		    "fa(CCK,OFDM,ALL)=(%d,%d,%d)%%, noisy_lv=%d, ofst=%d\n",
3370 		    env->ifs_clm_cck_fa_permil, env->ifs_clm_ofdm_fa_permil,
3371 		    env->ifs_clm_cck_fa_permil + env->ifs_clm_ofdm_fa_permil,
3372 		    noisy_lv, igi_offset);
3373 }
3374 
3375 static void rtw89_phy_dig_set_lna_idx(struct rtw89_dev *rtwdev, u8 lna_idx)
3376 {
3377 	rtw89_phy_write32_mask(rtwdev, R_PATH0_LNA_INIT,
3378 			       B_PATH0_LNA_INIT_IDX_MSK, lna_idx);
3379 	rtw89_phy_write32_mask(rtwdev, R_PATH1_LNA_INIT,
3380 			       B_PATH1_LNA_INIT_IDX_MSK, lna_idx);
3381 }
3382 
3383 static void rtw89_phy_dig_set_tia_idx(struct rtw89_dev *rtwdev, u8 tia_idx)
3384 {
3385 	rtw89_phy_write32_mask(rtwdev, R_PATH0_TIA_INIT,
3386 			       B_PATH0_TIA_INIT_IDX_MSK, tia_idx);
3387 	rtw89_phy_write32_mask(rtwdev, R_PATH1_TIA_INIT,
3388 			       B_PATH1_TIA_INIT_IDX_MSK, tia_idx);
3389 }
3390 
3391 static void rtw89_phy_dig_set_rxb_idx(struct rtw89_dev *rtwdev, u8 rxb_idx)
3392 {
3393 	rtw89_phy_write32_mask(rtwdev, R_PATH0_RXB_INIT,
3394 			       B_PATH0_RXB_INIT_IDX_MSK, rxb_idx);
3395 	rtw89_phy_write32_mask(rtwdev, R_PATH1_RXB_INIT,
3396 			       B_PATH1_RXB_INIT_IDX_MSK, rxb_idx);
3397 }
3398 
3399 static void rtw89_phy_dig_set_igi_cr(struct rtw89_dev *rtwdev,
3400 				     const struct rtw89_agc_gaincode_set set)
3401 {
3402 	rtw89_phy_dig_set_lna_idx(rtwdev, set.lna_idx);
3403 	rtw89_phy_dig_set_tia_idx(rtwdev, set.tia_idx);
3404 	rtw89_phy_dig_set_rxb_idx(rtwdev, set.rxb_idx);
3405 
3406 	rtw89_debug(rtwdev, RTW89_DBG_DIG, "Set (lna,tia,rxb)=((%d,%d,%02d))\n",
3407 		    set.lna_idx, set.tia_idx, set.rxb_idx);
3408 }
3409 
3410 static const struct rtw89_reg_def sdagc_config[4] = {
3411 	{R_PATH0_P20_FOLLOW_BY_PAGCUGC, B_PATH0_P20_FOLLOW_BY_PAGCUGC_EN_MSK},
3412 	{R_PATH0_S20_FOLLOW_BY_PAGCUGC, B_PATH0_S20_FOLLOW_BY_PAGCUGC_EN_MSK},
3413 	{R_PATH1_P20_FOLLOW_BY_PAGCUGC, B_PATH1_P20_FOLLOW_BY_PAGCUGC_EN_MSK},
3414 	{R_PATH1_S20_FOLLOW_BY_PAGCUGC, B_PATH1_S20_FOLLOW_BY_PAGCUGC_EN_MSK},
3415 };
3416 
3417 static void rtw89_phy_dig_sdagc_follow_pagc_config(struct rtw89_dev *rtwdev,
3418 						   bool enable)
3419 {
3420 	u8 i = 0;
3421 
3422 	for (i = 0; i < ARRAY_SIZE(sdagc_config); i++)
3423 		rtw89_phy_write32_mask(rtwdev, sdagc_config[i].addr,
3424 				       sdagc_config[i].mask, enable);
3425 
3426 	rtw89_debug(rtwdev, RTW89_DBG_DIG, "sdagc_follow_pagc=%d\n", enable);
3427 }
3428 
3429 static void rtw89_phy_dig_config_igi(struct rtw89_dev *rtwdev)
3430 {
3431 	struct rtw89_dig_info *dig = &rtwdev->dig;
3432 
3433 	if (!rtwdev->hal.support_igi)
3434 		return;
3435 
3436 	if (dig->force_gaincode_idx_en) {
3437 		rtw89_phy_dig_set_igi_cr(rtwdev, dig->force_gaincode);
3438 		rtw89_debug(rtwdev, RTW89_DBG_DIG,
3439 			    "Force gaincode index enabled.\n");
3440 	} else {
3441 		rtw89_phy_dig_gaincode_by_rssi(rtwdev, dig->igi_fa_rssi,
3442 					       &dig->cur_gaincode);
3443 		rtw89_phy_dig_set_igi_cr(rtwdev, dig->cur_gaincode);
3444 	}
3445 }
3446 
3447 static void rtw89_phy_dig_dyn_pd_th(struct rtw89_dev *rtwdev, u8 rssi,
3448 				    bool enable)
3449 {
3450 	enum rtw89_bandwidth cbw = rtwdev->hal.current_band_width;
3451 	struct rtw89_dig_info *dig = &rtwdev->dig;
3452 	u8 final_rssi = 0, under_region = dig->pd_low_th_ofst;
3453 	u8 ofdm_cca_th;
3454 	s8 cck_cca_th;
3455 	u32 pd_val = 0;
3456 
3457 	under_region += PD_TH_SB_FLTR_CMP_VAL;
3458 
3459 	switch (cbw) {
3460 	case RTW89_CHANNEL_WIDTH_40:
3461 		under_region += PD_TH_BW40_CMP_VAL;
3462 		break;
3463 	case RTW89_CHANNEL_WIDTH_80:
3464 		under_region += PD_TH_BW80_CMP_VAL;
3465 		break;
3466 	case RTW89_CHANNEL_WIDTH_160:
3467 		under_region += PD_TH_BW160_CMP_VAL;
3468 		break;
3469 	case RTW89_CHANNEL_WIDTH_20:
3470 		fallthrough;
3471 	default:
3472 		under_region += PD_TH_BW20_CMP_VAL;
3473 		break;
3474 	}
3475 
3476 	dig->dyn_pd_th_max = dig->igi_rssi;
3477 
3478 	final_rssi = min_t(u8, rssi, dig->igi_rssi);
3479 	ofdm_cca_th = clamp_t(u8, final_rssi, PD_TH_MIN_RSSI + under_region,
3480 			      PD_TH_MAX_RSSI + under_region);
3481 
3482 	if (enable) {
3483 		pd_val = (ofdm_cca_th - under_region - PD_TH_MIN_RSSI) >> 1;
3484 		rtw89_debug(rtwdev, RTW89_DBG_DIG,
3485 			    "igi=%d, ofdm_ccaTH=%d, backoff=%d, PD_low=%d\n",
3486 			    final_rssi, ofdm_cca_th, under_region, pd_val);
3487 	} else {
3488 		rtw89_debug(rtwdev, RTW89_DBG_DIG,
3489 			    "Dynamic PD th disabled, Set PD_low_bd=0\n");
3490 	}
3491 
3492 	rtw89_phy_write32_mask(rtwdev, R_SEG0R_PD, B_SEG0R_PD_LOWER_BOUND_MSK,
3493 			       pd_val);
3494 	rtw89_phy_write32_mask(rtwdev, R_SEG0R_PD,
3495 			       B_SEG0R_PD_SPATIAL_REUSE_EN_MSK, enable);
3496 
3497 	if (!rtwdev->hal.support_cckpd)
3498 		return;
3499 
3500 	cck_cca_th = max_t(s8, final_rssi - under_region, CCKPD_TH_MIN_RSSI);
3501 	pd_val = (u32)(cck_cca_th - IGI_RSSI_MAX);
3502 
3503 	rtw89_debug(rtwdev, RTW89_DBG_DIG,
3504 		    "igi=%d, cck_ccaTH=%d, backoff=%d, cck_PD_low=((%d))dB\n",
3505 		    final_rssi, cck_cca_th, under_region, pd_val);
3506 
3507 	rtw89_phy_write32_mask(rtwdev, R_BMODE_PDTH_EN_V1,
3508 			       B_BMODE_PDTH_LIMIT_EN_MSK_V1, enable);
3509 	rtw89_phy_write32_mask(rtwdev, R_BMODE_PDTH_V1,
3510 			       B_BMODE_PDTH_LOWER_BOUND_MSK_V1, pd_val);
3511 }
3512 
3513 void rtw89_phy_dig_reset(struct rtw89_dev *rtwdev)
3514 {
3515 	struct rtw89_dig_info *dig = &rtwdev->dig;
3516 
3517 	dig->bypass_dig = false;
3518 	rtw89_phy_dig_para_reset(rtwdev);
3519 	rtw89_phy_dig_set_igi_cr(rtwdev, dig->force_gaincode);
3520 	rtw89_phy_dig_dyn_pd_th(rtwdev, rssi_nolink, false);
3521 	rtw89_phy_dig_sdagc_follow_pagc_config(rtwdev, false);
3522 	rtw89_phy_dig_update_para(rtwdev);
3523 }
3524 
3525 #define IGI_RSSI_MIN 10
3526 void rtw89_phy_dig(struct rtw89_dev *rtwdev)
3527 {
3528 	struct rtw89_dig_info *dig = &rtwdev->dig;
3529 	bool is_linked = rtwdev->total_sta_assoc > 0;
3530 
3531 	if (unlikely(dig->bypass_dig)) {
3532 		dig->bypass_dig = false;
3533 		return;
3534 	}
3535 
3536 	if (!dig->is_linked_pre && is_linked) {
3537 		rtw89_debug(rtwdev, RTW89_DBG_DIG, "First connected\n");
3538 		rtw89_phy_dig_update_para(rtwdev);
3539 	} else if (dig->is_linked_pre && !is_linked) {
3540 		rtw89_debug(rtwdev, RTW89_DBG_DIG, "First disconnected\n");
3541 		rtw89_phy_dig_update_para(rtwdev);
3542 	}
3543 	dig->is_linked_pre = is_linked;
3544 
3545 	rtw89_phy_dig_igi_offset_by_env(rtwdev);
3546 	rtw89_phy_dig_update_rssi_info(rtwdev);
3547 
3548 	dig->dyn_igi_min = (dig->igi_rssi > IGI_RSSI_MIN) ?
3549 			    dig->igi_rssi - IGI_RSSI_MIN : 0;
3550 	dig->dyn_igi_max = dig->dyn_igi_min + IGI_OFFSET_MAX;
3551 	dig->igi_fa_rssi = dig->dyn_igi_min + dig->fa_rssi_ofst;
3552 
3553 	dig->igi_fa_rssi = clamp(dig->igi_fa_rssi, dig->dyn_igi_min,
3554 				 dig->dyn_igi_max);
3555 
3556 	rtw89_debug(rtwdev, RTW89_DBG_DIG,
3557 		    "rssi=%03d, dyn(max,min)=(%d,%d), final_rssi=%d\n",
3558 		    dig->igi_rssi, dig->dyn_igi_max, dig->dyn_igi_min,
3559 		    dig->igi_fa_rssi);
3560 
3561 	rtw89_phy_dig_config_igi(rtwdev);
3562 
3563 	rtw89_phy_dig_dyn_pd_th(rtwdev, dig->igi_fa_rssi, dig->dyn_pd_th_en);
3564 
3565 	if (dig->dyn_pd_th_en && dig->igi_fa_rssi > dig->dyn_pd_th_max)
3566 		rtw89_phy_dig_sdagc_follow_pagc_config(rtwdev, true);
3567 	else
3568 		rtw89_phy_dig_sdagc_follow_pagc_config(rtwdev, false);
3569 }
3570 
3571 static void rtw89_phy_env_monitor_init(struct rtw89_dev *rtwdev)
3572 {
3573 	rtw89_phy_ccx_top_setting_init(rtwdev);
3574 	rtw89_phy_ifs_clm_setting_init(rtwdev);
3575 }
3576 
3577 void rtw89_phy_dm_init(struct rtw89_dev *rtwdev)
3578 {
3579 	const struct rtw89_chip_info *chip = rtwdev->chip;
3580 
3581 	rtw89_phy_stat_init(rtwdev);
3582 
3583 	rtw89_chip_bb_sethw(rtwdev);
3584 
3585 	rtw89_phy_env_monitor_init(rtwdev);
3586 	rtw89_physts_parsing_init(rtwdev);
3587 	rtw89_phy_dig_init(rtwdev);
3588 	rtw89_phy_cfo_init(rtwdev);
3589 
3590 	rtw89_phy_init_rf_nctl(rtwdev);
3591 	rtw89_chip_rfk_init(rtwdev);
3592 	rtw89_load_txpwr_table(rtwdev, chip->byr_table);
3593 	rtw89_chip_set_txpwr_ctrl(rtwdev);
3594 	rtw89_chip_power_trim(rtwdev);
3595 	rtw89_chip_cfg_txrx_path(rtwdev);
3596 }
3597 
3598 void rtw89_phy_set_bss_color(struct rtw89_dev *rtwdev, struct ieee80211_vif *vif)
3599 {
3600 	enum rtw89_phy_idx phy_idx = RTW89_PHY_0;
3601 	u8 bss_color;
3602 
3603 	if (!vif->bss_conf.he_support || !vif->bss_conf.assoc)
3604 		return;
3605 
3606 	bss_color = vif->bss_conf.he_bss_color.color;
3607 
3608 	rtw89_phy_write32_idx(rtwdev, R_BSS_CLR_MAP, B_BSS_CLR_MAP_VLD0, 0x1,
3609 			      phy_idx);
3610 	rtw89_phy_write32_idx(rtwdev, R_BSS_CLR_MAP, B_BSS_CLR_MAP_TGT, bss_color,
3611 			      phy_idx);
3612 	rtw89_phy_write32_idx(rtwdev, R_BSS_CLR_MAP, B_BSS_CLR_MAP_STAID,
3613 			      vif->bss_conf.aid, phy_idx);
3614 }
3615 
3616 static void
3617 _rfk_write_rf(struct rtw89_dev *rtwdev, const struct rtw89_reg5_def *def)
3618 {
3619 	rtw89_write_rf(rtwdev, def->path, def->addr, def->mask, def->data);
3620 }
3621 
3622 static void
3623 _rfk_write32_mask(struct rtw89_dev *rtwdev, const struct rtw89_reg5_def *def)
3624 {
3625 	rtw89_phy_write32_mask(rtwdev, def->addr, def->mask, def->data);
3626 }
3627 
3628 static void
3629 _rfk_write32_set(struct rtw89_dev *rtwdev, const struct rtw89_reg5_def *def)
3630 {
3631 	rtw89_phy_write32_set(rtwdev, def->addr, def->mask);
3632 }
3633 
3634 static void
3635 _rfk_write32_clr(struct rtw89_dev *rtwdev, const struct rtw89_reg5_def *def)
3636 {
3637 	rtw89_phy_write32_clr(rtwdev, def->addr, def->mask);
3638 }
3639 
3640 static void
3641 _rfk_delay(struct rtw89_dev *rtwdev, const struct rtw89_reg5_def *def)
3642 {
3643 	udelay(def->data);
3644 }
3645 
3646 static void
3647 (*_rfk_handler[])(struct rtw89_dev *rtwdev, const struct rtw89_reg5_def *def) = {
3648 	[RTW89_RFK_F_WRF] = _rfk_write_rf,
3649 	[RTW89_RFK_F_WM] = _rfk_write32_mask,
3650 	[RTW89_RFK_F_WS] = _rfk_write32_set,
3651 	[RTW89_RFK_F_WC] = _rfk_write32_clr,
3652 	[RTW89_RFK_F_DELAY] = _rfk_delay,
3653 };
3654 
3655 static_assert(ARRAY_SIZE(_rfk_handler) == RTW89_RFK_F_NUM);
3656 
3657 void
3658 rtw89_rfk_parser(struct rtw89_dev *rtwdev, const struct rtw89_rfk_tbl *tbl)
3659 {
3660 	const struct rtw89_reg5_def *p = tbl->defs;
3661 	const struct rtw89_reg5_def *end = tbl->defs + tbl->size;
3662 
3663 	for (; p < end; p++)
3664 		_rfk_handler[p->flag](rtwdev, p);
3665 }
3666 EXPORT_SYMBOL(rtw89_rfk_parser);
3667 
3668 #define RTW89_TSSI_FAST_MODE_NUM 4
3669 
3670 static const struct rtw89_reg_def rtw89_tssi_fastmode_regs_flat[RTW89_TSSI_FAST_MODE_NUM] = {
3671 	{0xD934, 0xff0000},
3672 	{0xD934, 0xff000000},
3673 	{0xD938, 0xff},
3674 	{0xD934, 0xff00},
3675 };
3676 
3677 static const struct rtw89_reg_def rtw89_tssi_fastmode_regs_level[RTW89_TSSI_FAST_MODE_NUM] = {
3678 	{0xD930, 0xff0000},
3679 	{0xD930, 0xff000000},
3680 	{0xD934, 0xff},
3681 	{0xD930, 0xff00},
3682 };
3683 
3684 static
3685 void rtw89_phy_tssi_ctrl_set_fast_mode_cfg(struct rtw89_dev *rtwdev,
3686 					   enum rtw89_mac_idx mac_idx,
3687 					   enum rtw89_tssi_bandedge_cfg bandedge_cfg,
3688 					   u32 val)
3689 {
3690 	const struct rtw89_reg_def *regs;
3691 	u32 reg;
3692 	int i;
3693 
3694 	if (bandedge_cfg == RTW89_TSSI_BANDEDGE_FLAT)
3695 		regs = rtw89_tssi_fastmode_regs_flat;
3696 	else
3697 		regs = rtw89_tssi_fastmode_regs_level;
3698 
3699 	for (i = 0; i < RTW89_TSSI_FAST_MODE_NUM; i++) {
3700 		reg = rtw89_mac_reg_by_idx(regs[i].addr, mac_idx);
3701 		rtw89_write32_mask(rtwdev, reg, regs[i].mask, val);
3702 	}
3703 }
3704 
3705 static const struct rtw89_reg_def rtw89_tssi_bandedge_regs_flat[RTW89_TSSI_SBW_NUM] = {
3706 	{0xD91C, 0xff000000},
3707 	{0xD920, 0xff},
3708 	{0xD920, 0xff00},
3709 	{0xD920, 0xff0000},
3710 	{0xD920, 0xff000000},
3711 	{0xD924, 0xff},
3712 	{0xD924, 0xff00},
3713 	{0xD914, 0xff000000},
3714 	{0xD918, 0xff},
3715 	{0xD918, 0xff00},
3716 	{0xD918, 0xff0000},
3717 	{0xD918, 0xff000000},
3718 	{0xD91C, 0xff},
3719 	{0xD91C, 0xff00},
3720 	{0xD91C, 0xff0000},
3721 };
3722 
3723 static const struct rtw89_reg_def rtw89_tssi_bandedge_regs_level[RTW89_TSSI_SBW_NUM] = {
3724 	{0xD910, 0xff},
3725 	{0xD910, 0xff00},
3726 	{0xD910, 0xff0000},
3727 	{0xD910, 0xff000000},
3728 	{0xD914, 0xff},
3729 	{0xD914, 0xff00},
3730 	{0xD914, 0xff0000},
3731 	{0xD908, 0xff},
3732 	{0xD908, 0xff00},
3733 	{0xD908, 0xff0000},
3734 	{0xD908, 0xff000000},
3735 	{0xD90C, 0xff},
3736 	{0xD90C, 0xff00},
3737 	{0xD90C, 0xff0000},
3738 	{0xD90C, 0xff000000},
3739 };
3740 
3741 void rtw89_phy_tssi_ctrl_set_bandedge_cfg(struct rtw89_dev *rtwdev,
3742 					  enum rtw89_mac_idx mac_idx,
3743 					  enum rtw89_tssi_bandedge_cfg bandedge_cfg)
3744 {
3745 	const struct rtw89_chip_info *chip = rtwdev->chip;
3746 	const struct rtw89_reg_def *regs;
3747 	const u32 *data;
3748 	u32 reg;
3749 	int i;
3750 
3751 	if (bandedge_cfg >= RTW89_TSSI_CFG_NUM)
3752 		return;
3753 
3754 	if (bandedge_cfg == RTW89_TSSI_BANDEDGE_FLAT)
3755 		regs = rtw89_tssi_bandedge_regs_flat;
3756 	else
3757 		regs = rtw89_tssi_bandedge_regs_level;
3758 
3759 	data = chip->tssi_dbw_table->data[bandedge_cfg];
3760 
3761 	for (i = 0; i < RTW89_TSSI_SBW_NUM; i++) {
3762 		reg = rtw89_mac_reg_by_idx(regs[i].addr, mac_idx);
3763 		rtw89_write32_mask(rtwdev, reg, regs[i].mask, data[i]);
3764 	}
3765 
3766 	reg = rtw89_mac_reg_by_idx(R_AX_BANDEDGE_CFG, mac_idx);
3767 	rtw89_write32_mask(rtwdev, reg, B_AX_BANDEDGE_CFG_IDX_MASK, bandedge_cfg);
3768 
3769 	rtw89_phy_tssi_ctrl_set_fast_mode_cfg(rtwdev, mac_idx, bandedge_cfg,
3770 					      data[RTW89_TSSI_SBW20]);
3771 }
3772 EXPORT_SYMBOL(rtw89_phy_tssi_ctrl_set_bandedge_cfg);
3773