xref: /freebsd/sys/contrib/dev/rtw89/phy.c (revision bdcbfde31e8e9b343f113a1956384bdf30d1ed62)
1 // SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
2 /* Copyright(c) 2019-2020  Realtek Corporation
3  */
4 
5 #include "coex.h"
6 #include "debug.h"
7 #include "fw.h"
8 #include "mac.h"
9 #include "phy.h"
10 #include "ps.h"
11 #include "reg.h"
12 #include "sar.h"
13 #include "txrx.h"
14 #include "util.h"
15 
16 static u16 get_max_amsdu_len(struct rtw89_dev *rtwdev,
17 			     const struct rtw89_ra_report *report)
18 {
19 	u32 bit_rate = report->bit_rate;
20 
21 	/* lower than ofdm, do not aggregate */
22 	if (bit_rate < 550)
23 		return 1;
24 
25 	/* avoid AMSDU for legacy rate */
26 	if (report->might_fallback_legacy)
27 		return 1;
28 
29 	/* lower than 20M vht 2ss mcs8, make it small */
30 	if (bit_rate < 1800)
31 		return 1200;
32 
33 	/* lower than 40M vht 2ss mcs9, make it medium */
34 	if (bit_rate < 4000)
35 		return 2600;
36 
37 	/* not yet 80M vht 2ss mcs8/9, make it twice regular packet size */
38 	if (bit_rate < 7000)
39 		return 3500;
40 
41 	return rtwdev->chip->max_amsdu_limit;
42 }
43 
44 static u64 get_mcs_ra_mask(u16 mcs_map, u8 highest_mcs, u8 gap)
45 {
46 	u64 ra_mask = 0;
47 	u8 mcs_cap;
48 	int i, nss;
49 
50 	for (i = 0, nss = 12; i < 4; i++, mcs_map >>= 2, nss += 12) {
51 		mcs_cap = mcs_map & 0x3;
52 		switch (mcs_cap) {
53 		case 2:
54 			ra_mask |= GENMASK_ULL(highest_mcs, 0) << nss;
55 			break;
56 		case 1:
57 			ra_mask |= GENMASK_ULL(highest_mcs - gap, 0) << nss;
58 			break;
59 		case 0:
60 			ra_mask |= GENMASK_ULL(highest_mcs - gap * 2, 0) << nss;
61 			break;
62 		default:
63 			break;
64 		}
65 	}
66 
67 	return ra_mask;
68 }
69 
70 static u64 get_he_ra_mask(struct ieee80211_sta *sta)
71 {
72 	struct ieee80211_sta_he_cap cap = sta->deflink.he_cap;
73 	u16 mcs_map;
74 
75 	switch (sta->deflink.bandwidth) {
76 	case IEEE80211_STA_RX_BW_160:
77 		if (cap.he_cap_elem.phy_cap_info[0] &
78 		    IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_80PLUS80_MHZ_IN_5G)
79 			mcs_map = le16_to_cpu(cap.he_mcs_nss_supp.rx_mcs_80p80);
80 		else
81 			mcs_map = le16_to_cpu(cap.he_mcs_nss_supp.rx_mcs_160);
82 		break;
83 	default:
84 		mcs_map = le16_to_cpu(cap.he_mcs_nss_supp.rx_mcs_80);
85 	}
86 
87 	/* MCS11, MCS9, MCS7 */
88 	return get_mcs_ra_mask(mcs_map, 11, 2);
89 }
90 
91 #define RA_FLOOR_TABLE_SIZE	7
92 #define RA_FLOOR_UP_GAP		3
93 static u64 rtw89_phy_ra_mask_rssi(struct rtw89_dev *rtwdev, u8 rssi,
94 				  u8 ratr_state)
95 {
96 	u8 rssi_lv_t[RA_FLOOR_TABLE_SIZE] = {30, 44, 48, 52, 56, 60, 100};
97 	u8 rssi_lv = 0;
98 	u8 i;
99 
100 	rssi >>= 1;
101 	for (i = 0; i < RA_FLOOR_TABLE_SIZE; i++) {
102 		if (i >= ratr_state)
103 			rssi_lv_t[i] += RA_FLOOR_UP_GAP;
104 		if (rssi < rssi_lv_t[i]) {
105 			rssi_lv = i;
106 			break;
107 		}
108 	}
109 	if (rssi_lv == 0)
110 		return 0xffffffffffffffffULL;
111 	else if (rssi_lv == 1)
112 		return 0xfffffffffffffff0ULL;
113 	else if (rssi_lv == 2)
114 		return 0xffffffffffffefe0ULL;
115 	else if (rssi_lv == 3)
116 		return 0xffffffffffffcfc0ULL;
117 	else if (rssi_lv == 4)
118 		return 0xffffffffffff8f80ULL;
119 	else if (rssi_lv >= 5)
120 		return 0xffffffffffff0f00ULL;
121 
122 	return 0xffffffffffffffffULL;
123 }
124 
125 static u64 rtw89_phy_ra_mask_recover(u64 ra_mask, u64 ra_mask_bak)
126 {
127 	if ((ra_mask & ~(RA_MASK_CCK_RATES | RA_MASK_OFDM_RATES)) == 0)
128 		ra_mask |= (ra_mask_bak & ~(RA_MASK_CCK_RATES | RA_MASK_OFDM_RATES));
129 
130 	if (ra_mask == 0)
131 		ra_mask |= (ra_mask_bak & (RA_MASK_CCK_RATES | RA_MASK_OFDM_RATES));
132 
133 	return ra_mask;
134 }
135 
136 static u64 rtw89_phy_ra_mask_cfg(struct rtw89_dev *rtwdev, struct rtw89_sta *rtwsta)
137 {
138 	struct ieee80211_sta *sta = rtwsta_to_sta(rtwsta);
139 	const struct rtw89_chan *chan = rtw89_chan_get(rtwdev, RTW89_SUB_ENTITY_0);
140 	struct cfg80211_bitrate_mask *mask = &rtwsta->mask;
141 	enum nl80211_band band;
142 	u64 cfg_mask;
143 
144 	if (!rtwsta->use_cfg_mask)
145 		return -1;
146 
147 	switch (chan->band_type) {
148 	case RTW89_BAND_2G:
149 		band = NL80211_BAND_2GHZ;
150 		cfg_mask = u64_encode_bits(mask->control[NL80211_BAND_2GHZ].legacy,
151 					   RA_MASK_CCK_RATES | RA_MASK_OFDM_RATES);
152 		break;
153 	case RTW89_BAND_5G:
154 		band = NL80211_BAND_5GHZ;
155 		cfg_mask = u64_encode_bits(mask->control[NL80211_BAND_5GHZ].legacy,
156 					   RA_MASK_OFDM_RATES);
157 		break;
158 	case RTW89_BAND_6G:
159 		band = NL80211_BAND_6GHZ;
160 		cfg_mask = u64_encode_bits(mask->control[NL80211_BAND_6GHZ].legacy,
161 					   RA_MASK_OFDM_RATES);
162 		break;
163 	default:
164 		rtw89_warn(rtwdev, "unhandled band type %d\n", chan->band_type);
165 		return -1;
166 	}
167 
168 	if (sta->deflink.he_cap.has_he) {
169 		cfg_mask |= u64_encode_bits(mask->control[band].he_mcs[0],
170 					    RA_MASK_HE_1SS_RATES);
171 		cfg_mask |= u64_encode_bits(mask->control[band].he_mcs[1],
172 					    RA_MASK_HE_2SS_RATES);
173 	} else if (sta->deflink.vht_cap.vht_supported) {
174 		cfg_mask |= u64_encode_bits(mask->control[band].vht_mcs[0],
175 					    RA_MASK_VHT_1SS_RATES);
176 		cfg_mask |= u64_encode_bits(mask->control[band].vht_mcs[1],
177 					    RA_MASK_VHT_2SS_RATES);
178 	} else if (sta->deflink.ht_cap.ht_supported) {
179 		cfg_mask |= u64_encode_bits(mask->control[band].ht_mcs[0],
180 					    RA_MASK_HT_1SS_RATES);
181 		cfg_mask |= u64_encode_bits(mask->control[band].ht_mcs[1],
182 					    RA_MASK_HT_2SS_RATES);
183 	}
184 
185 	return cfg_mask;
186 }
187 
188 static const u64
189 rtw89_ra_mask_ht_rates[4] = {RA_MASK_HT_1SS_RATES, RA_MASK_HT_2SS_RATES,
190 			     RA_MASK_HT_3SS_RATES, RA_MASK_HT_4SS_RATES};
191 static const u64
192 rtw89_ra_mask_vht_rates[4] = {RA_MASK_VHT_1SS_RATES, RA_MASK_VHT_2SS_RATES,
193 			      RA_MASK_VHT_3SS_RATES, RA_MASK_VHT_4SS_RATES};
194 static const u64
195 rtw89_ra_mask_he_rates[4] = {RA_MASK_HE_1SS_RATES, RA_MASK_HE_2SS_RATES,
196 			     RA_MASK_HE_3SS_RATES, RA_MASK_HE_4SS_RATES};
197 
198 static void rtw89_phy_ra_gi_ltf(struct rtw89_dev *rtwdev,
199 				struct rtw89_sta *rtwsta,
200 				bool *fix_giltf_en, u8 *fix_giltf)
201 {
202 	const struct rtw89_chan *chan = rtw89_chan_get(rtwdev, RTW89_SUB_ENTITY_0);
203 	struct cfg80211_bitrate_mask *mask = &rtwsta->mask;
204 	u8 band = chan->band_type;
205 	enum nl80211_band nl_band = rtw89_hw_to_nl80211_band(band);
206 	u8 he_gi = mask->control[nl_band].he_gi;
207 	u8 he_ltf = mask->control[nl_band].he_ltf;
208 
209 	if (!rtwsta->use_cfg_mask)
210 		return;
211 
212 	if (he_ltf == 2 && he_gi == 2) {
213 		*fix_giltf = RTW89_GILTF_LGI_4XHE32;
214 	} else if (he_ltf == 2 && he_gi == 0) {
215 		*fix_giltf = RTW89_GILTF_SGI_4XHE08;
216 	} else if (he_ltf == 1 && he_gi == 1) {
217 		*fix_giltf = RTW89_GILTF_2XHE16;
218 	} else if (he_ltf == 1 && he_gi == 0) {
219 		*fix_giltf = RTW89_GILTF_2XHE08;
220 	} else if (he_ltf == 0 && he_gi == 1) {
221 		*fix_giltf = RTW89_GILTF_1XHE16;
222 	} else if (he_ltf == 0 && he_gi == 0) {
223 		*fix_giltf = RTW89_GILTF_1XHE08;
224 	} else {
225 		*fix_giltf_en = false;
226 		return;
227 	}
228 
229 	*fix_giltf_en = true;
230 }
231 
232 static void rtw89_phy_ra_sta_update(struct rtw89_dev *rtwdev,
233 				    struct ieee80211_sta *sta, bool csi)
234 {
235 	struct rtw89_sta *rtwsta = (struct rtw89_sta *)sta->drv_priv;
236 	struct rtw89_vif *rtwvif = rtwsta->rtwvif;
237 	struct rtw89_phy_rate_pattern *rate_pattern = &rtwvif->rate_pattern;
238 	struct rtw89_ra_info *ra = &rtwsta->ra;
239 	const struct rtw89_chan *chan = rtw89_chan_get(rtwdev, RTW89_SUB_ENTITY_0);
240 	struct ieee80211_vif *vif = rtwvif_to_vif(rtwsta->rtwvif);
241 	const u64 *high_rate_masks = rtw89_ra_mask_ht_rates;
242 	u8 rssi = ewma_rssi_read(&rtwsta->avg_rssi);
243 	u64 ra_mask = 0;
244 	u64 ra_mask_bak;
245 	u8 mode = 0;
246 	u8 csi_mode = RTW89_RA_RPT_MODE_LEGACY;
247 	u8 bw_mode = 0;
248 	u8 stbc_en = 0;
249 	u8 ldpc_en = 0;
250 	u8 fix_giltf = 0;
251 	u8 i;
252 	bool sgi = false;
253 	bool fix_giltf_en = false;
254 
255 	memset(ra, 0, sizeof(*ra));
256 	/* Set the ra mask from sta's capability */
257 	if (sta->deflink.he_cap.has_he) {
258 		mode |= RTW89_RA_MODE_HE;
259 		csi_mode = RTW89_RA_RPT_MODE_HE;
260 		ra_mask |= get_he_ra_mask(sta);
261 		high_rate_masks = rtw89_ra_mask_he_rates;
262 		if (sta->deflink.he_cap.he_cap_elem.phy_cap_info[2] &
263 		    IEEE80211_HE_PHY_CAP2_STBC_RX_UNDER_80MHZ)
264 			stbc_en = 1;
265 		if (sta->deflink.he_cap.he_cap_elem.phy_cap_info[1] &
266 		    IEEE80211_HE_PHY_CAP1_LDPC_CODING_IN_PAYLOAD)
267 			ldpc_en = 1;
268 		rtw89_phy_ra_gi_ltf(rtwdev, rtwsta, &fix_giltf_en, &fix_giltf);
269 	} else if (sta->deflink.vht_cap.vht_supported) {
270 		u16 mcs_map = le16_to_cpu(sta->deflink.vht_cap.vht_mcs.rx_mcs_map);
271 
272 		mode |= RTW89_RA_MODE_VHT;
273 		csi_mode = RTW89_RA_RPT_MODE_VHT;
274 		/* MCS9, MCS8, MCS7 */
275 		ra_mask |= get_mcs_ra_mask(mcs_map, 9, 1);
276 		high_rate_masks = rtw89_ra_mask_vht_rates;
277 		if (sta->deflink.vht_cap.cap & IEEE80211_VHT_CAP_RXSTBC_MASK)
278 			stbc_en = 1;
279 		if (sta->deflink.vht_cap.cap & IEEE80211_VHT_CAP_RXLDPC)
280 			ldpc_en = 1;
281 	} else if (sta->deflink.ht_cap.ht_supported) {
282 		mode |= RTW89_RA_MODE_HT;
283 		csi_mode = RTW89_RA_RPT_MODE_HT;
284 		ra_mask |= ((u64)sta->deflink.ht_cap.mcs.rx_mask[3] << 48) |
285 			   ((u64)sta->deflink.ht_cap.mcs.rx_mask[2] << 36) |
286 			   (sta->deflink.ht_cap.mcs.rx_mask[1] << 24) |
287 			   (sta->deflink.ht_cap.mcs.rx_mask[0] << 12);
288 		high_rate_masks = rtw89_ra_mask_ht_rates;
289 		if (sta->deflink.ht_cap.cap & IEEE80211_HT_CAP_RX_STBC)
290 			stbc_en = 1;
291 		if (sta->deflink.ht_cap.cap & IEEE80211_HT_CAP_LDPC_CODING)
292 			ldpc_en = 1;
293 	}
294 
295 	switch (chan->band_type) {
296 	case RTW89_BAND_2G:
297 		ra_mask |= sta->deflink.supp_rates[NL80211_BAND_2GHZ];
298 		if (sta->deflink.supp_rates[NL80211_BAND_2GHZ] & 0xf)
299 			mode |= RTW89_RA_MODE_CCK;
300 		if (sta->deflink.supp_rates[NL80211_BAND_2GHZ] & 0xff0)
301 			mode |= RTW89_RA_MODE_OFDM;
302 		break;
303 	case RTW89_BAND_5G:
304 		ra_mask |= (u64)sta->deflink.supp_rates[NL80211_BAND_5GHZ] << 4;
305 		mode |= RTW89_RA_MODE_OFDM;
306 		break;
307 	case RTW89_BAND_6G:
308 		ra_mask |= (u64)sta->deflink.supp_rates[NL80211_BAND_6GHZ] << 4;
309 		mode |= RTW89_RA_MODE_OFDM;
310 		break;
311 	default:
312 		rtw89_err(rtwdev, "Unknown band type\n");
313 		break;
314 	}
315 
316 	ra_mask_bak = ra_mask;
317 
318 	if (mode >= RTW89_RA_MODE_HT) {
319 		u64 mask = 0;
320 		for (i = 0; i < rtwdev->hal.tx_nss; i++)
321 			mask |= high_rate_masks[i];
322 		if (mode & RTW89_RA_MODE_OFDM)
323 			mask |= RA_MASK_SUBOFDM_RATES;
324 		if (mode & RTW89_RA_MODE_CCK)
325 			mask |= RA_MASK_SUBCCK_RATES;
326 		ra_mask &= mask;
327 	} else if (mode & RTW89_RA_MODE_OFDM) {
328 		ra_mask &= (RA_MASK_OFDM_RATES | RA_MASK_SUBCCK_RATES);
329 	}
330 
331 	if (mode != RTW89_RA_MODE_CCK)
332 		ra_mask &= rtw89_phy_ra_mask_rssi(rtwdev, rssi, 0);
333 
334 	ra_mask = rtw89_phy_ra_mask_recover(ra_mask, ra_mask_bak);
335 	ra_mask &= rtw89_phy_ra_mask_cfg(rtwdev, rtwsta);
336 
337 	switch (sta->deflink.bandwidth) {
338 	case IEEE80211_STA_RX_BW_160:
339 		bw_mode = RTW89_CHANNEL_WIDTH_160;
340 		sgi = sta->deflink.vht_cap.vht_supported &&
341 		      (sta->deflink.vht_cap.cap & IEEE80211_VHT_CAP_SHORT_GI_160);
342 		break;
343 	case IEEE80211_STA_RX_BW_80:
344 		bw_mode = RTW89_CHANNEL_WIDTH_80;
345 		sgi = sta->deflink.vht_cap.vht_supported &&
346 		      (sta->deflink.vht_cap.cap & IEEE80211_VHT_CAP_SHORT_GI_80);
347 		break;
348 	case IEEE80211_STA_RX_BW_40:
349 		bw_mode = RTW89_CHANNEL_WIDTH_40;
350 		sgi = sta->deflink.ht_cap.ht_supported &&
351 		      (sta->deflink.ht_cap.cap & IEEE80211_HT_CAP_SGI_40);
352 		break;
353 	default:
354 		bw_mode = RTW89_CHANNEL_WIDTH_20;
355 		sgi = sta->deflink.ht_cap.ht_supported &&
356 		      (sta->deflink.ht_cap.cap & IEEE80211_HT_CAP_SGI_20);
357 		break;
358 	}
359 
360 	if (sta->deflink.he_cap.he_cap_elem.phy_cap_info[3] &
361 	    IEEE80211_HE_PHY_CAP3_DCM_MAX_CONST_RX_16_QAM)
362 		ra->dcm_cap = 1;
363 
364 	if (rate_pattern->enable && !vif->p2p) {
365 		ra_mask = rtw89_phy_ra_mask_cfg(rtwdev, rtwsta);
366 		ra_mask &= rate_pattern->ra_mask;
367 		mode = rate_pattern->ra_mode;
368 	}
369 
370 	ra->bw_cap = bw_mode;
371 	ra->er_cap = rtwsta->er_cap;
372 	ra->mode_ctrl = mode;
373 	ra->macid = rtwsta->mac_id;
374 	ra->stbc_cap = stbc_en;
375 	ra->ldpc_cap = ldpc_en;
376 	ra->ss_num = min(sta->deflink.rx_nss, rtwdev->hal.tx_nss) - 1;
377 	ra->en_sgi = sgi;
378 	ra->ra_mask = ra_mask;
379 	ra->fix_giltf_en = fix_giltf_en;
380 	ra->fix_giltf = fix_giltf;
381 
382 	if (!csi)
383 		return;
384 
385 	ra->fixed_csi_rate_en = false;
386 	ra->ra_csi_rate_en = true;
387 	ra->cr_tbl_sel = false;
388 	ra->band_num = rtwvif->phy_idx;
389 	ra->csi_bw = bw_mode;
390 	ra->csi_gi_ltf = RTW89_GILTF_LGI_4XHE32;
391 	ra->csi_mcs_ss_idx = 5;
392 	ra->csi_mode = csi_mode;
393 }
394 
395 void rtw89_phy_ra_updata_sta(struct rtw89_dev *rtwdev, struct ieee80211_sta *sta,
396 			     u32 changed)
397 {
398 	struct rtw89_sta *rtwsta = (struct rtw89_sta *)sta->drv_priv;
399 	struct rtw89_ra_info *ra = &rtwsta->ra;
400 
401 	rtw89_phy_ra_sta_update(rtwdev, sta, false);
402 
403 	if (changed & IEEE80211_RC_SUPP_RATES_CHANGED)
404 		ra->upd_mask = 1;
405 	if (changed & (IEEE80211_RC_BW_CHANGED | IEEE80211_RC_NSS_CHANGED))
406 		ra->upd_bw_nss_mask = 1;
407 
408 	rtw89_debug(rtwdev, RTW89_DBG_RA,
409 		    "ra updat: macid = %d, bw = %d, nss = %d, gi = %d %d",
410 		    ra->macid,
411 		    ra->bw_cap,
412 		    ra->ss_num,
413 		    ra->en_sgi,
414 		    ra->giltf);
415 
416 	rtw89_fw_h2c_ra(rtwdev, ra, false);
417 }
418 
419 static bool __check_rate_pattern(struct rtw89_phy_rate_pattern *next,
420 				 u16 rate_base, u64 ra_mask, u8 ra_mode,
421 				 u32 rate_ctrl, u32 ctrl_skip, bool force)
422 {
423 	u8 n, c;
424 
425 	if (rate_ctrl == ctrl_skip)
426 		return true;
427 
428 	n = hweight32(rate_ctrl);
429 	if (n == 0)
430 		return true;
431 
432 	if (force && n != 1)
433 		return false;
434 
435 	if (next->enable)
436 		return false;
437 
438 	c = __fls(rate_ctrl);
439 	next->rate = rate_base + c;
440 	next->ra_mode = ra_mode;
441 	next->ra_mask = ra_mask;
442 	next->enable = true;
443 
444 	return true;
445 }
446 
447 #define RTW89_HW_RATE_BY_CHIP_GEN(rate) \
448 	{ \
449 		[RTW89_CHIP_AX] = RTW89_HW_RATE_ ## rate, \
450 		[RTW89_CHIP_BE] = RTW89_HW_RATE_V1_ ## rate, \
451 	}
452 
453 void rtw89_phy_rate_pattern_vif(struct rtw89_dev *rtwdev,
454 				struct ieee80211_vif *vif,
455 				const struct cfg80211_bitrate_mask *mask)
456 {
457 	struct ieee80211_supported_band *sband;
458 	struct rtw89_vif *rtwvif = (struct rtw89_vif *)vif->drv_priv;
459 	struct rtw89_phy_rate_pattern next_pattern = {0};
460 	const struct rtw89_chan *chan = rtw89_chan_get(rtwdev, RTW89_SUB_ENTITY_0);
461 	static const u16 hw_rate_he[][RTW89_CHIP_GEN_NUM] = {
462 		RTW89_HW_RATE_BY_CHIP_GEN(HE_NSS1_MCS0),
463 		RTW89_HW_RATE_BY_CHIP_GEN(HE_NSS2_MCS0),
464 		RTW89_HW_RATE_BY_CHIP_GEN(HE_NSS3_MCS0),
465 		RTW89_HW_RATE_BY_CHIP_GEN(HE_NSS4_MCS0),
466 	};
467 	static const u16 hw_rate_vht[][RTW89_CHIP_GEN_NUM] = {
468 		RTW89_HW_RATE_BY_CHIP_GEN(VHT_NSS1_MCS0),
469 		RTW89_HW_RATE_BY_CHIP_GEN(VHT_NSS2_MCS0),
470 		RTW89_HW_RATE_BY_CHIP_GEN(VHT_NSS3_MCS0),
471 		RTW89_HW_RATE_BY_CHIP_GEN(VHT_NSS4_MCS0),
472 	};
473 	static const u16 hw_rate_ht[][RTW89_CHIP_GEN_NUM] = {
474 		RTW89_HW_RATE_BY_CHIP_GEN(MCS0),
475 		RTW89_HW_RATE_BY_CHIP_GEN(MCS8),
476 		RTW89_HW_RATE_BY_CHIP_GEN(MCS16),
477 		RTW89_HW_RATE_BY_CHIP_GEN(MCS24),
478 	};
479 	u8 band = chan->band_type;
480 	enum nl80211_band nl_band = rtw89_hw_to_nl80211_band(band);
481 	enum rtw89_chip_gen chip_gen = rtwdev->chip->chip_gen;
482 	u8 tx_nss = rtwdev->hal.tx_nss;
483 	u8 i;
484 
485 	for (i = 0; i < tx_nss; i++)
486 		if (!__check_rate_pattern(&next_pattern, hw_rate_he[i][chip_gen],
487 					  RA_MASK_HE_RATES, RTW89_RA_MODE_HE,
488 					  mask->control[nl_band].he_mcs[i],
489 					  0, true))
490 			goto out;
491 
492 	for (i = 0; i < tx_nss; i++)
493 		if (!__check_rate_pattern(&next_pattern, hw_rate_vht[i][chip_gen],
494 					  RA_MASK_VHT_RATES, RTW89_RA_MODE_VHT,
495 					  mask->control[nl_band].vht_mcs[i],
496 					  0, true))
497 			goto out;
498 
499 	for (i = 0; i < tx_nss; i++)
500 		if (!__check_rate_pattern(&next_pattern, hw_rate_ht[i][chip_gen],
501 					  RA_MASK_HT_RATES, RTW89_RA_MODE_HT,
502 					  mask->control[nl_band].ht_mcs[i],
503 					  0, true))
504 			goto out;
505 
506 	/* lagacy cannot be empty for nl80211_parse_tx_bitrate_mask, and
507 	 * require at least one basic rate for ieee80211_set_bitrate_mask,
508 	 * so the decision just depends on if all bitrates are set or not.
509 	 */
510 	sband = rtwdev->hw->wiphy->bands[nl_band];
511 	if (band == RTW89_BAND_2G) {
512 		if (!__check_rate_pattern(&next_pattern, RTW89_HW_RATE_CCK1,
513 					  RA_MASK_CCK_RATES | RA_MASK_OFDM_RATES,
514 					  RTW89_RA_MODE_CCK | RTW89_RA_MODE_OFDM,
515 					  mask->control[nl_band].legacy,
516 					  BIT(sband->n_bitrates) - 1, false))
517 			goto out;
518 	} else {
519 		if (!__check_rate_pattern(&next_pattern, RTW89_HW_RATE_OFDM6,
520 					  RA_MASK_OFDM_RATES, RTW89_RA_MODE_OFDM,
521 					  mask->control[nl_band].legacy,
522 					  BIT(sband->n_bitrates) - 1, false))
523 			goto out;
524 	}
525 
526 	if (!next_pattern.enable)
527 		goto out;
528 
529 	rtwvif->rate_pattern = next_pattern;
530 	rtw89_debug(rtwdev, RTW89_DBG_RA,
531 #if defined(__linux__)
532 		    "configure pattern: rate 0x%x, mask 0x%llx, mode 0x%x\n",
533 #elif defined(__FreeBSD__)
534 		    "configure pattern: rate 0x%x, mask 0x%jx, mode 0x%x\n",
535 #endif
536 		    next_pattern.rate,
537 #if defined(__FreeBSD__)
538 		    (uintmax_t)
539 #endif
540 		    next_pattern.ra_mask,
541 		    next_pattern.ra_mode);
542 	return;
543 
544 out:
545 	rtwvif->rate_pattern.enable = false;
546 	rtw89_debug(rtwdev, RTW89_DBG_RA, "unset rate pattern\n");
547 }
548 
549 static void rtw89_phy_ra_updata_sta_iter(void *data, struct ieee80211_sta *sta)
550 {
551 	struct rtw89_dev *rtwdev = (struct rtw89_dev *)data;
552 
553 	rtw89_phy_ra_updata_sta(rtwdev, sta, IEEE80211_RC_SUPP_RATES_CHANGED);
554 }
555 
556 void rtw89_phy_ra_update(struct rtw89_dev *rtwdev)
557 {
558 	ieee80211_iterate_stations_atomic(rtwdev->hw,
559 					  rtw89_phy_ra_updata_sta_iter,
560 					  rtwdev);
561 }
562 
563 void rtw89_phy_ra_assoc(struct rtw89_dev *rtwdev, struct ieee80211_sta *sta)
564 {
565 	struct rtw89_sta *rtwsta = (struct rtw89_sta *)sta->drv_priv;
566 	struct rtw89_ra_info *ra = &rtwsta->ra;
567 	u8 rssi = ewma_rssi_read(&rtwsta->avg_rssi) >> RSSI_FACTOR;
568 	bool csi = rtw89_sta_has_beamformer_cap(sta);
569 
570 	rtw89_phy_ra_sta_update(rtwdev, sta, csi);
571 
572 	if (rssi > 40)
573 		ra->init_rate_lv = 1;
574 	else if (rssi > 20)
575 		ra->init_rate_lv = 2;
576 	else if (rssi > 1)
577 		ra->init_rate_lv = 3;
578 	else
579 		ra->init_rate_lv = 0;
580 	ra->upd_all = 1;
581 	rtw89_debug(rtwdev, RTW89_DBG_RA,
582 		    "ra assoc: macid = %d, mode = %d, bw = %d, nss = %d, lv = %d",
583 		    ra->macid,
584 		    ra->mode_ctrl,
585 		    ra->bw_cap,
586 		    ra->ss_num,
587 		    ra->init_rate_lv);
588 	rtw89_debug(rtwdev, RTW89_DBG_RA,
589 		    "ra assoc: dcm = %d, er = %d, ldpc = %d, stbc = %d, gi = %d %d",
590 		    ra->dcm_cap,
591 		    ra->er_cap,
592 		    ra->ldpc_cap,
593 		    ra->stbc_cap,
594 		    ra->en_sgi,
595 		    ra->giltf);
596 
597 	rtw89_fw_h2c_ra(rtwdev, ra, csi);
598 }
599 
600 u8 rtw89_phy_get_txsc(struct rtw89_dev *rtwdev,
601 		      const struct rtw89_chan *chan,
602 		      enum rtw89_bandwidth dbw)
603 {
604 	enum rtw89_bandwidth cbw = chan->band_width;
605 	u8 pri_ch = chan->primary_channel;
606 	u8 central_ch = chan->channel;
607 	u8 txsc_idx = 0;
608 	u8 tmp = 0;
609 
610 	if (cbw == dbw || cbw == RTW89_CHANNEL_WIDTH_20)
611 		return txsc_idx;
612 
613 	switch (cbw) {
614 	case RTW89_CHANNEL_WIDTH_40:
615 		txsc_idx = pri_ch > central_ch ? 1 : 2;
616 		break;
617 	case RTW89_CHANNEL_WIDTH_80:
618 		if (dbw == RTW89_CHANNEL_WIDTH_20) {
619 			if (pri_ch > central_ch)
620 				txsc_idx = (pri_ch - central_ch) >> 1;
621 			else
622 				txsc_idx = ((central_ch - pri_ch) >> 1) + 1;
623 		} else {
624 			txsc_idx = pri_ch > central_ch ? 9 : 10;
625 		}
626 		break;
627 	case RTW89_CHANNEL_WIDTH_160:
628 		if (pri_ch > central_ch)
629 			tmp = (pri_ch - central_ch) >> 1;
630 		else
631 			tmp = ((central_ch - pri_ch) >> 1) + 1;
632 
633 		if (dbw == RTW89_CHANNEL_WIDTH_20) {
634 			txsc_idx = tmp;
635 		} else if (dbw == RTW89_CHANNEL_WIDTH_40) {
636 			if (tmp == 1 || tmp == 3)
637 				txsc_idx = 9;
638 			else if (tmp == 5 || tmp == 7)
639 				txsc_idx = 11;
640 			else if (tmp == 2 || tmp == 4)
641 				txsc_idx = 10;
642 			else if (tmp == 6 || tmp == 8)
643 				txsc_idx = 12;
644 			else
645 				return 0xff;
646 		} else {
647 			txsc_idx = pri_ch > central_ch ? 13 : 14;
648 		}
649 		break;
650 	case RTW89_CHANNEL_WIDTH_80_80:
651 		if (dbw == RTW89_CHANNEL_WIDTH_20) {
652 			if (pri_ch > central_ch)
653 				txsc_idx = (10 - (pri_ch - central_ch)) >> 1;
654 			else
655 				txsc_idx = ((central_ch - pri_ch) >> 1) + 5;
656 		} else if (dbw == RTW89_CHANNEL_WIDTH_40) {
657 			txsc_idx = pri_ch > central_ch ? 10 : 12;
658 		} else {
659 			txsc_idx = 14;
660 		}
661 		break;
662 	default:
663 		break;
664 	}
665 
666 	return txsc_idx;
667 }
668 EXPORT_SYMBOL(rtw89_phy_get_txsc);
669 
670 static bool rtw89_phy_check_swsi_busy(struct rtw89_dev *rtwdev)
671 {
672 	return !!rtw89_phy_read32_mask(rtwdev, R_SWSI_V1, B_SWSI_W_BUSY_V1) ||
673 	       !!rtw89_phy_read32_mask(rtwdev, R_SWSI_V1, B_SWSI_R_BUSY_V1);
674 }
675 
676 u32 rtw89_phy_read_rf(struct rtw89_dev *rtwdev, enum rtw89_rf_path rf_path,
677 		      u32 addr, u32 mask)
678 {
679 	const struct rtw89_chip_info *chip = rtwdev->chip;
680 	const u32 *base_addr = chip->rf_base_addr;
681 	u32 val, direct_addr;
682 
683 	if (rf_path >= rtwdev->chip->rf_path_num) {
684 		rtw89_err(rtwdev, "unsupported rf path (%d)\n", rf_path);
685 		return INV_RF_DATA;
686 	}
687 
688 	addr &= 0xff;
689 	direct_addr = base_addr[rf_path] + (addr << 2);
690 	mask &= RFREG_MASK;
691 
692 	val = rtw89_phy_read32_mask(rtwdev, direct_addr, mask);
693 
694 	return val;
695 }
696 EXPORT_SYMBOL(rtw89_phy_read_rf);
697 
698 static u32 rtw89_phy_read_rf_a(struct rtw89_dev *rtwdev,
699 			       enum rtw89_rf_path rf_path, u32 addr, u32 mask)
700 {
701 	bool busy;
702 	bool done;
703 	u32 val;
704 	int ret;
705 
706 	ret = read_poll_timeout_atomic(rtw89_phy_check_swsi_busy, busy, !busy,
707 				       1, 30, false, rtwdev);
708 	if (ret) {
709 		rtw89_err(rtwdev, "read rf busy swsi\n");
710 		return INV_RF_DATA;
711 	}
712 
713 	mask &= RFREG_MASK;
714 
715 	val = FIELD_PREP(B_SWSI_READ_ADDR_PATH_V1, rf_path) |
716 	      FIELD_PREP(B_SWSI_READ_ADDR_ADDR_V1, addr);
717 	rtw89_phy_write32_mask(rtwdev, R_SWSI_READ_ADDR_V1, B_SWSI_READ_ADDR_V1, val);
718 	udelay(2);
719 
720 	ret = read_poll_timeout_atomic(rtw89_phy_read32_mask, done, done, 1,
721 				       30, false, rtwdev, R_SWSI_V1,
722 				       B_SWSI_R_DATA_DONE_V1);
723 	if (ret) {
724 		rtw89_err(rtwdev, "read swsi busy\n");
725 		return INV_RF_DATA;
726 	}
727 
728 	return rtw89_phy_read32_mask(rtwdev, R_SWSI_V1, mask);
729 }
730 
731 u32 rtw89_phy_read_rf_v1(struct rtw89_dev *rtwdev, enum rtw89_rf_path rf_path,
732 			 u32 addr, u32 mask)
733 {
734 	bool ad_sel = FIELD_GET(RTW89_RF_ADDR_ADSEL_MASK, addr);
735 
736 	if (rf_path >= rtwdev->chip->rf_path_num) {
737 		rtw89_err(rtwdev, "unsupported rf path (%d)\n", rf_path);
738 		return INV_RF_DATA;
739 	}
740 
741 	if (ad_sel)
742 		return rtw89_phy_read_rf(rtwdev, rf_path, addr, mask);
743 	else
744 		return rtw89_phy_read_rf_a(rtwdev, rf_path, addr, mask);
745 }
746 EXPORT_SYMBOL(rtw89_phy_read_rf_v1);
747 
748 bool rtw89_phy_write_rf(struct rtw89_dev *rtwdev, enum rtw89_rf_path rf_path,
749 			u32 addr, u32 mask, u32 data)
750 {
751 	const struct rtw89_chip_info *chip = rtwdev->chip;
752 	const u32 *base_addr = chip->rf_base_addr;
753 	u32 direct_addr;
754 
755 	if (rf_path >= rtwdev->chip->rf_path_num) {
756 		rtw89_err(rtwdev, "unsupported rf path (%d)\n", rf_path);
757 		return false;
758 	}
759 
760 	addr &= 0xff;
761 	direct_addr = base_addr[rf_path] + (addr << 2);
762 	mask &= RFREG_MASK;
763 
764 	rtw89_phy_write32_mask(rtwdev, direct_addr, mask, data);
765 
766 	/* delay to ensure writing properly */
767 	udelay(1);
768 
769 	return true;
770 }
771 EXPORT_SYMBOL(rtw89_phy_write_rf);
772 
773 static bool rtw89_phy_write_rf_a(struct rtw89_dev *rtwdev,
774 				 enum rtw89_rf_path rf_path, u32 addr, u32 mask,
775 				 u32 data)
776 {
777 	u8 bit_shift;
778 	u32 val;
779 	bool busy, b_msk_en = false;
780 	int ret;
781 
782 	ret = read_poll_timeout_atomic(rtw89_phy_check_swsi_busy, busy, !busy,
783 				       1, 30, false, rtwdev);
784 	if (ret) {
785 		rtw89_err(rtwdev, "write rf busy swsi\n");
786 		return false;
787 	}
788 
789 	data &= RFREG_MASK;
790 	mask &= RFREG_MASK;
791 
792 	if (mask != RFREG_MASK) {
793 		b_msk_en = true;
794 		rtw89_phy_write32_mask(rtwdev, R_SWSI_BIT_MASK_V1, RFREG_MASK,
795 				       mask);
796 		bit_shift = __ffs(mask);
797 		data = (data << bit_shift) & RFREG_MASK;
798 	}
799 
800 	val = FIELD_PREP(B_SWSI_DATA_BIT_MASK_EN_V1, b_msk_en) |
801 	      FIELD_PREP(B_SWSI_DATA_PATH_V1, rf_path) |
802 	      FIELD_PREP(B_SWSI_DATA_ADDR_V1, addr) |
803 	      FIELD_PREP(B_SWSI_DATA_VAL_V1, data);
804 
805 	rtw89_phy_write32_mask(rtwdev, R_SWSI_DATA_V1, MASKDWORD, val);
806 
807 	return true;
808 }
809 
810 bool rtw89_phy_write_rf_v1(struct rtw89_dev *rtwdev, enum rtw89_rf_path rf_path,
811 			   u32 addr, u32 mask, u32 data)
812 {
813 	bool ad_sel = FIELD_GET(RTW89_RF_ADDR_ADSEL_MASK, addr);
814 
815 	if (rf_path >= rtwdev->chip->rf_path_num) {
816 		rtw89_err(rtwdev, "unsupported rf path (%d)\n", rf_path);
817 		return false;
818 	}
819 
820 	if (ad_sel)
821 		return rtw89_phy_write_rf(rtwdev, rf_path, addr, mask, data);
822 	else
823 		return rtw89_phy_write_rf_a(rtwdev, rf_path, addr, mask, data);
824 }
825 EXPORT_SYMBOL(rtw89_phy_write_rf_v1);
826 
827 static bool rtw89_chip_rf_v1(struct rtw89_dev *rtwdev)
828 {
829 	return rtwdev->chip->ops->write_rf == rtw89_phy_write_rf_v1;
830 }
831 
832 static void rtw89_phy_bb_reset(struct rtw89_dev *rtwdev,
833 			       enum rtw89_phy_idx phy_idx)
834 {
835 	const struct rtw89_chip_info *chip = rtwdev->chip;
836 
837 	chip->ops->bb_reset(rtwdev, phy_idx);
838 }
839 
840 static void rtw89_phy_config_bb_reg(struct rtw89_dev *rtwdev,
841 				    const struct rtw89_reg2_def *reg,
842 				    enum rtw89_rf_path rf_path,
843 				    void *extra_data)
844 {
845 	if (reg->addr == 0xfe)
846 		mdelay(50);
847 	else if (reg->addr == 0xfd)
848 		mdelay(5);
849 	else if (reg->addr == 0xfc)
850 		mdelay(1);
851 	else if (reg->addr == 0xfb)
852 		udelay(50);
853 	else if (reg->addr == 0xfa)
854 		udelay(5);
855 	else if (reg->addr == 0xf9)
856 		udelay(1);
857 	else
858 		rtw89_phy_write32(rtwdev, reg->addr, reg->data);
859 }
860 
861 union rtw89_phy_bb_gain_arg {
862 	u32 addr;
863 	struct {
864 		union {
865 			u8 type;
866 			struct {
867 				u8 rxsc_start:4;
868 				u8 bw:4;
869 			};
870 		};
871 		u8 path;
872 		u8 gain_band;
873 		u8 cfg_type;
874 	};
875 } __packed;
876 
877 static void
878 rtw89_phy_cfg_bb_gain_error(struct rtw89_dev *rtwdev,
879 			    union rtw89_phy_bb_gain_arg arg, u32 data)
880 {
881 	struct rtw89_phy_bb_gain_info *gain = &rtwdev->bb_gain;
882 	u8 type = arg.type;
883 	u8 path = arg.path;
884 	u8 gband = arg.gain_band;
885 	int i;
886 
887 	switch (type) {
888 	case 0:
889 		for (i = 0; i < 4; i++, data >>= 8)
890 			gain->lna_gain[gband][path][i] = data & 0xff;
891 		break;
892 	case 1:
893 		for (i = 4; i < 7; i++, data >>= 8)
894 			gain->lna_gain[gband][path][i] = data & 0xff;
895 		break;
896 	case 2:
897 		for (i = 0; i < 2; i++, data >>= 8)
898 			gain->tia_gain[gband][path][i] = data & 0xff;
899 		break;
900 	default:
901 		rtw89_warn(rtwdev,
902 			   "bb gain error {0x%x:0x%x} with unknown type: %d\n",
903 			   arg.addr, data, type);
904 		break;
905 	}
906 }
907 
908 enum rtw89_phy_bb_rxsc_start_idx {
909 	RTW89_BB_RXSC_START_IDX_FULL = 0,
910 	RTW89_BB_RXSC_START_IDX_20 = 1,
911 	RTW89_BB_RXSC_START_IDX_20_1 = 5,
912 	RTW89_BB_RXSC_START_IDX_40 = 9,
913 	RTW89_BB_RXSC_START_IDX_80 = 13,
914 };
915 
916 static void
917 rtw89_phy_cfg_bb_rpl_ofst(struct rtw89_dev *rtwdev,
918 			  union rtw89_phy_bb_gain_arg arg, u32 data)
919 {
920 	struct rtw89_phy_bb_gain_info *gain = &rtwdev->bb_gain;
921 	u8 rxsc_start = arg.rxsc_start;
922 	u8 bw = arg.bw;
923 	u8 path = arg.path;
924 	u8 gband = arg.gain_band;
925 	u8 rxsc;
926 	s8 ofst;
927 	int i;
928 
929 	switch (bw) {
930 	case RTW89_CHANNEL_WIDTH_20:
931 		gain->rpl_ofst_20[gband][path] = (s8)data;
932 		break;
933 	case RTW89_CHANNEL_WIDTH_40:
934 		if (rxsc_start == RTW89_BB_RXSC_START_IDX_FULL) {
935 			gain->rpl_ofst_40[gband][path][0] = (s8)data;
936 		} else if (rxsc_start == RTW89_BB_RXSC_START_IDX_20) {
937 			for (i = 0; i < 2; i++, data >>= 8) {
938 				rxsc = RTW89_BB_RXSC_START_IDX_20 + i;
939 				ofst = (s8)(data & 0xff);
940 				gain->rpl_ofst_40[gband][path][rxsc] = ofst;
941 			}
942 		}
943 		break;
944 	case RTW89_CHANNEL_WIDTH_80:
945 		if (rxsc_start == RTW89_BB_RXSC_START_IDX_FULL) {
946 			gain->rpl_ofst_80[gband][path][0] = (s8)data;
947 		} else if (rxsc_start == RTW89_BB_RXSC_START_IDX_20) {
948 			for (i = 0; i < 4; i++, data >>= 8) {
949 				rxsc = RTW89_BB_RXSC_START_IDX_20 + i;
950 				ofst = (s8)(data & 0xff);
951 				gain->rpl_ofst_80[gband][path][rxsc] = ofst;
952 			}
953 		} else if (rxsc_start == RTW89_BB_RXSC_START_IDX_40) {
954 			for (i = 0; i < 2; i++, data >>= 8) {
955 				rxsc = RTW89_BB_RXSC_START_IDX_40 + i;
956 				ofst = (s8)(data & 0xff);
957 				gain->rpl_ofst_80[gband][path][rxsc] = ofst;
958 			}
959 		}
960 		break;
961 	case RTW89_CHANNEL_WIDTH_160:
962 		if (rxsc_start == RTW89_BB_RXSC_START_IDX_FULL) {
963 			gain->rpl_ofst_160[gband][path][0] = (s8)data;
964 		} else if (rxsc_start == RTW89_BB_RXSC_START_IDX_20) {
965 			for (i = 0; i < 4; i++, data >>= 8) {
966 				rxsc = RTW89_BB_RXSC_START_IDX_20 + i;
967 				ofst = (s8)(data & 0xff);
968 				gain->rpl_ofst_160[gband][path][rxsc] = ofst;
969 			}
970 		} else if (rxsc_start == RTW89_BB_RXSC_START_IDX_20_1) {
971 			for (i = 0; i < 4; i++, data >>= 8) {
972 				rxsc = RTW89_BB_RXSC_START_IDX_20_1 + i;
973 				ofst = (s8)(data & 0xff);
974 				gain->rpl_ofst_160[gband][path][rxsc] = ofst;
975 			}
976 		} else if (rxsc_start == RTW89_BB_RXSC_START_IDX_40) {
977 			for (i = 0; i < 4; i++, data >>= 8) {
978 				rxsc = RTW89_BB_RXSC_START_IDX_40 + i;
979 				ofst = (s8)(data & 0xff);
980 				gain->rpl_ofst_160[gband][path][rxsc] = ofst;
981 			}
982 		} else if (rxsc_start == RTW89_BB_RXSC_START_IDX_80) {
983 			for (i = 0; i < 2; i++, data >>= 8) {
984 				rxsc = RTW89_BB_RXSC_START_IDX_80 + i;
985 				ofst = (s8)(data & 0xff);
986 				gain->rpl_ofst_160[gband][path][rxsc] = ofst;
987 			}
988 		}
989 		break;
990 	default:
991 		rtw89_warn(rtwdev,
992 			   "bb rpl ofst {0x%x:0x%x} with unknown bw: %d\n",
993 			   arg.addr, data, bw);
994 		break;
995 	}
996 }
997 
998 static void
999 rtw89_phy_cfg_bb_gain_bypass(struct rtw89_dev *rtwdev,
1000 			     union rtw89_phy_bb_gain_arg arg, u32 data)
1001 {
1002 	struct rtw89_phy_bb_gain_info *gain = &rtwdev->bb_gain;
1003 	u8 type = arg.type;
1004 	u8 path = arg.path;
1005 	u8 gband = arg.gain_band;
1006 	int i;
1007 
1008 	switch (type) {
1009 	case 0:
1010 		for (i = 0; i < 4; i++, data >>= 8)
1011 			gain->lna_gain_bypass[gband][path][i] = data & 0xff;
1012 		break;
1013 	case 1:
1014 		for (i = 4; i < 7; i++, data >>= 8)
1015 			gain->lna_gain_bypass[gband][path][i] = data & 0xff;
1016 		break;
1017 	default:
1018 		rtw89_warn(rtwdev,
1019 			   "bb gain bypass {0x%x:0x%x} with unknown type: %d\n",
1020 			   arg.addr, data, type);
1021 		break;
1022 	}
1023 }
1024 
1025 static void
1026 rtw89_phy_cfg_bb_gain_op1db(struct rtw89_dev *rtwdev,
1027 			    union rtw89_phy_bb_gain_arg arg, u32 data)
1028 {
1029 	struct rtw89_phy_bb_gain_info *gain = &rtwdev->bb_gain;
1030 	u8 type = arg.type;
1031 	u8 path = arg.path;
1032 	u8 gband = arg.gain_band;
1033 	int i;
1034 
1035 	switch (type) {
1036 	case 0:
1037 		for (i = 0; i < 4; i++, data >>= 8)
1038 			gain->lna_op1db[gband][path][i] = data & 0xff;
1039 		break;
1040 	case 1:
1041 		for (i = 4; i < 7; i++, data >>= 8)
1042 			gain->lna_op1db[gband][path][i] = data & 0xff;
1043 		break;
1044 	case 2:
1045 		for (i = 0; i < 4; i++, data >>= 8)
1046 			gain->tia_lna_op1db[gband][path][i] = data & 0xff;
1047 		break;
1048 	case 3:
1049 		for (i = 4; i < 8; i++, data >>= 8)
1050 			gain->tia_lna_op1db[gband][path][i] = data & 0xff;
1051 		break;
1052 	default:
1053 		rtw89_warn(rtwdev,
1054 			   "bb gain op1db {0x%x:0x%x} with unknown type: %d\n",
1055 			   arg.addr, data, type);
1056 		break;
1057 	}
1058 }
1059 
1060 static void rtw89_phy_config_bb_gain(struct rtw89_dev *rtwdev,
1061 				     const struct rtw89_reg2_def *reg,
1062 				     enum rtw89_rf_path rf_path,
1063 				     void *extra_data)
1064 {
1065 	const struct rtw89_chip_info *chip = rtwdev->chip;
1066 	union rtw89_phy_bb_gain_arg arg = { .addr = reg->addr };
1067 	struct rtw89_efuse *efuse = &rtwdev->efuse;
1068 
1069 	if (arg.gain_band >= RTW89_BB_GAIN_BAND_NR)
1070 		return;
1071 
1072 	if (arg.path >= chip->rf_path_num)
1073 		return;
1074 
1075 	if (arg.addr >= 0xf9 && arg.addr <= 0xfe) {
1076 		rtw89_warn(rtwdev, "bb gain table with flow ctrl\n");
1077 		return;
1078 	}
1079 
1080 	switch (arg.cfg_type) {
1081 	case 0:
1082 		rtw89_phy_cfg_bb_gain_error(rtwdev, arg, reg->data);
1083 		break;
1084 	case 1:
1085 		rtw89_phy_cfg_bb_rpl_ofst(rtwdev, arg, reg->data);
1086 		break;
1087 	case 2:
1088 		rtw89_phy_cfg_bb_gain_bypass(rtwdev, arg, reg->data);
1089 		break;
1090 	case 3:
1091 		rtw89_phy_cfg_bb_gain_op1db(rtwdev, arg, reg->data);
1092 		break;
1093 	case 4:
1094 		/* This cfg_type is only used by rfe_type >= 50 with eFEM */
1095 		if (efuse->rfe_type < 50)
1096 			break;
1097 		fallthrough;
1098 	default:
1099 		rtw89_warn(rtwdev,
1100 			   "bb gain {0x%x:0x%x} with unknown cfg type: %d\n",
1101 			   arg.addr, reg->data, arg.cfg_type);
1102 		break;
1103 	}
1104 }
1105 
1106 static void
1107 rtw89_phy_cofig_rf_reg_store(struct rtw89_dev *rtwdev,
1108 			     const struct rtw89_reg2_def *reg,
1109 			     enum rtw89_rf_path rf_path,
1110 			     struct rtw89_fw_h2c_rf_reg_info *info)
1111 {
1112 	u16 idx = info->curr_idx % RTW89_H2C_RF_PAGE_SIZE;
1113 	u8 page = info->curr_idx / RTW89_H2C_RF_PAGE_SIZE;
1114 
1115 	if (page >= RTW89_H2C_RF_PAGE_NUM) {
1116 		rtw89_warn(rtwdev, "RF parameters exceed size. path=%d, idx=%d",
1117 			   rf_path, info->curr_idx);
1118 		return;
1119 	}
1120 
1121 	info->rtw89_phy_config_rf_h2c[page][idx] =
1122 		cpu_to_le32((reg->addr << 20) | reg->data);
1123 	info->curr_idx++;
1124 }
1125 
1126 static int rtw89_phy_config_rf_reg_fw(struct rtw89_dev *rtwdev,
1127 				      struct rtw89_fw_h2c_rf_reg_info *info)
1128 {
1129 	u16 remain = info->curr_idx;
1130 	u16 len = 0;
1131 	u8 i;
1132 	int ret = 0;
1133 
1134 	if (remain > RTW89_H2C_RF_PAGE_NUM * RTW89_H2C_RF_PAGE_SIZE) {
1135 		rtw89_warn(rtwdev,
1136 			   "rf reg h2c total len %d larger than %d\n",
1137 			   remain, RTW89_H2C_RF_PAGE_NUM * RTW89_H2C_RF_PAGE_SIZE);
1138 		ret = -EINVAL;
1139 		goto out;
1140 	}
1141 
1142 	for (i = 0; i < RTW89_H2C_RF_PAGE_NUM && remain; i++, remain -= len) {
1143 		len = remain > RTW89_H2C_RF_PAGE_SIZE ? RTW89_H2C_RF_PAGE_SIZE : remain;
1144 		ret = rtw89_fw_h2c_rf_reg(rtwdev, info, len * 4, i);
1145 		if (ret)
1146 			goto out;
1147 	}
1148 out:
1149 	info->curr_idx = 0;
1150 
1151 	return ret;
1152 }
1153 
1154 static void rtw89_phy_config_rf_reg_noio(struct rtw89_dev *rtwdev,
1155 					 const struct rtw89_reg2_def *reg,
1156 					 enum rtw89_rf_path rf_path,
1157 					 void *extra_data)
1158 {
1159 	u32 addr = reg->addr;
1160 
1161 	if (addr == 0xfe || addr == 0xfd || addr == 0xfc || addr == 0xfb ||
1162 	    addr == 0xfa || addr == 0xf9)
1163 		return;
1164 
1165 	if (rtw89_chip_rf_v1(rtwdev) && addr < 0x100)
1166 		return;
1167 
1168 	rtw89_phy_cofig_rf_reg_store(rtwdev, reg, rf_path,
1169 				     (struct rtw89_fw_h2c_rf_reg_info *)extra_data);
1170 }
1171 
1172 static void rtw89_phy_config_rf_reg(struct rtw89_dev *rtwdev,
1173 				    const struct rtw89_reg2_def *reg,
1174 				    enum rtw89_rf_path rf_path,
1175 				    void *extra_data)
1176 {
1177 	if (reg->addr == 0xfe) {
1178 		mdelay(50);
1179 	} else if (reg->addr == 0xfd) {
1180 		mdelay(5);
1181 	} else if (reg->addr == 0xfc) {
1182 		mdelay(1);
1183 	} else if (reg->addr == 0xfb) {
1184 		udelay(50);
1185 	} else if (reg->addr == 0xfa) {
1186 		udelay(5);
1187 	} else if (reg->addr == 0xf9) {
1188 		udelay(1);
1189 	} else {
1190 		rtw89_write_rf(rtwdev, rf_path, reg->addr, 0xfffff, reg->data);
1191 		rtw89_phy_cofig_rf_reg_store(rtwdev, reg, rf_path,
1192 					     (struct rtw89_fw_h2c_rf_reg_info *)extra_data);
1193 	}
1194 }
1195 
1196 void rtw89_phy_config_rf_reg_v1(struct rtw89_dev *rtwdev,
1197 				const struct rtw89_reg2_def *reg,
1198 				enum rtw89_rf_path rf_path,
1199 				void *extra_data)
1200 {
1201 	rtw89_write_rf(rtwdev, rf_path, reg->addr, RFREG_MASK, reg->data);
1202 
1203 	if (reg->addr < 0x100)
1204 		return;
1205 
1206 	rtw89_phy_cofig_rf_reg_store(rtwdev, reg, rf_path,
1207 				     (struct rtw89_fw_h2c_rf_reg_info *)extra_data);
1208 }
1209 EXPORT_SYMBOL(rtw89_phy_config_rf_reg_v1);
1210 
1211 static int rtw89_phy_sel_headline(struct rtw89_dev *rtwdev,
1212 				  const struct rtw89_phy_table *table,
1213 				  u32 *headline_size, u32 *headline_idx,
1214 				  u8 rfe, u8 cv)
1215 {
1216 	const struct rtw89_reg2_def *reg;
1217 	u32 headline;
1218 	u32 compare, target;
1219 	u8 rfe_para, cv_para;
1220 	u8 cv_max = 0;
1221 	bool case_matched = false;
1222 	u32 i;
1223 
1224 	for (i = 0; i < table->n_regs; i++) {
1225 		reg = &table->regs[i];
1226 		headline = get_phy_headline(reg->addr);
1227 		if (headline != PHY_HEADLINE_VALID)
1228 			break;
1229 	}
1230 	*headline_size = i;
1231 	if (*headline_size == 0)
1232 		return 0;
1233 
1234 	/* case 1: RFE match, CV match */
1235 	compare = get_phy_compare(rfe, cv);
1236 	for (i = 0; i < *headline_size; i++) {
1237 		reg = &table->regs[i];
1238 		target = get_phy_target(reg->addr);
1239 		if (target == compare) {
1240 			*headline_idx = i;
1241 			return 0;
1242 		}
1243 	}
1244 
1245 	/* case 2: RFE match, CV don't care */
1246 	compare = get_phy_compare(rfe, PHY_COND_DONT_CARE);
1247 	for (i = 0; i < *headline_size; i++) {
1248 		reg = &table->regs[i];
1249 		target = get_phy_target(reg->addr);
1250 		if (target == compare) {
1251 			*headline_idx = i;
1252 			return 0;
1253 		}
1254 	}
1255 
1256 	/* case 3: RFE match, CV max in table */
1257 	for (i = 0; i < *headline_size; i++) {
1258 		reg = &table->regs[i];
1259 		rfe_para = get_phy_cond_rfe(reg->addr);
1260 		cv_para = get_phy_cond_cv(reg->addr);
1261 		if (rfe_para == rfe) {
1262 			if (cv_para >= cv_max) {
1263 				cv_max = cv_para;
1264 				*headline_idx = i;
1265 				case_matched = true;
1266 			}
1267 		}
1268 	}
1269 
1270 	if (case_matched)
1271 		return 0;
1272 
1273 	/* case 4: RFE don't care, CV max in table */
1274 	for (i = 0; i < *headline_size; i++) {
1275 		reg = &table->regs[i];
1276 		rfe_para = get_phy_cond_rfe(reg->addr);
1277 		cv_para = get_phy_cond_cv(reg->addr);
1278 		if (rfe_para == PHY_COND_DONT_CARE) {
1279 			if (cv_para >= cv_max) {
1280 				cv_max = cv_para;
1281 				*headline_idx = i;
1282 				case_matched = true;
1283 			}
1284 		}
1285 	}
1286 
1287 	if (case_matched)
1288 		return 0;
1289 
1290 	return -EINVAL;
1291 }
1292 
1293 static void rtw89_phy_init_reg(struct rtw89_dev *rtwdev,
1294 			       const struct rtw89_phy_table *table,
1295 			       void (*config)(struct rtw89_dev *rtwdev,
1296 					      const struct rtw89_reg2_def *reg,
1297 					      enum rtw89_rf_path rf_path,
1298 					      void *data),
1299 			       void *extra_data)
1300 {
1301 	const struct rtw89_reg2_def *reg;
1302 	enum rtw89_rf_path rf_path = table->rf_path;
1303 	u8 rfe = rtwdev->efuse.rfe_type;
1304 	u8 cv = rtwdev->hal.cv;
1305 	u32 i;
1306 	u32 headline_size = 0, headline_idx = 0;
1307 	u32 target = 0, cfg_target;
1308 	u8 cond;
1309 	bool is_matched = true;
1310 	bool target_found = false;
1311 	int ret;
1312 
1313 	ret = rtw89_phy_sel_headline(rtwdev, table, &headline_size,
1314 				     &headline_idx, rfe, cv);
1315 	if (ret) {
1316 		rtw89_err(rtwdev, "invalid PHY package: %d/%d\n", rfe, cv);
1317 		return;
1318 	}
1319 
1320 	cfg_target = get_phy_target(table->regs[headline_idx].addr);
1321 	for (i = headline_size; i < table->n_regs; i++) {
1322 		reg = &table->regs[i];
1323 		cond = get_phy_cond(reg->addr);
1324 		switch (cond) {
1325 		case PHY_COND_BRANCH_IF:
1326 		case PHY_COND_BRANCH_ELIF:
1327 			target = get_phy_target(reg->addr);
1328 			break;
1329 		case PHY_COND_BRANCH_ELSE:
1330 			is_matched = false;
1331 			if (!target_found) {
1332 				rtw89_warn(rtwdev, "failed to load CR %x/%x\n",
1333 					   reg->addr, reg->data);
1334 				return;
1335 			}
1336 			break;
1337 		case PHY_COND_BRANCH_END:
1338 			is_matched = true;
1339 			target_found = false;
1340 			break;
1341 		case PHY_COND_CHECK:
1342 			if (target_found) {
1343 				is_matched = false;
1344 				break;
1345 			}
1346 
1347 			if (target == cfg_target) {
1348 				is_matched = true;
1349 				target_found = true;
1350 			} else {
1351 				is_matched = false;
1352 				target_found = false;
1353 			}
1354 			break;
1355 		default:
1356 			if (is_matched)
1357 				config(rtwdev, reg, rf_path, extra_data);
1358 			break;
1359 		}
1360 	}
1361 }
1362 
1363 void rtw89_phy_init_bb_reg(struct rtw89_dev *rtwdev)
1364 {
1365 	struct rtw89_fw_elm_info *elm_info = &rtwdev->fw.elm_info;
1366 	const struct rtw89_chip_info *chip = rtwdev->chip;
1367 	const struct rtw89_phy_table *bb_table;
1368 	const struct rtw89_phy_table *bb_gain_table;
1369 
1370 	bb_table = elm_info->bb_tbl ? elm_info->bb_tbl : chip->bb_table;
1371 	rtw89_phy_init_reg(rtwdev, bb_table, rtw89_phy_config_bb_reg, NULL);
1372 	rtw89_chip_init_txpwr_unit(rtwdev, RTW89_PHY_0);
1373 
1374 	bb_gain_table = elm_info->bb_gain ? elm_info->bb_gain : chip->bb_gain_table;
1375 	if (bb_gain_table)
1376 		rtw89_phy_init_reg(rtwdev, bb_gain_table,
1377 				   rtw89_phy_config_bb_gain, NULL);
1378 	rtw89_phy_bb_reset(rtwdev, RTW89_PHY_0);
1379 }
1380 
1381 static u32 rtw89_phy_nctl_poll(struct rtw89_dev *rtwdev)
1382 {
1383 	rtw89_phy_write32(rtwdev, 0x8080, 0x4);
1384 	udelay(1);
1385 	return rtw89_phy_read32(rtwdev, 0x8080);
1386 }
1387 
1388 void rtw89_phy_init_rf_reg(struct rtw89_dev *rtwdev, bool noio)
1389 {
1390 	void (*config)(struct rtw89_dev *rtwdev, const struct rtw89_reg2_def *reg,
1391 		       enum rtw89_rf_path rf_path, void *data);
1392 	struct rtw89_fw_elm_info *elm_info = &rtwdev->fw.elm_info;
1393 	const struct rtw89_chip_info *chip = rtwdev->chip;
1394 	const struct rtw89_phy_table *rf_table;
1395 	struct rtw89_fw_h2c_rf_reg_info *rf_reg_info;
1396 	u8 path;
1397 
1398 	rf_reg_info = kzalloc(sizeof(*rf_reg_info), GFP_KERNEL);
1399 	if (!rf_reg_info)
1400 		return;
1401 
1402 	for (path = RF_PATH_A; path < chip->rf_path_num; path++) {
1403 		rf_table = elm_info->rf_radio[path] ?
1404 			   elm_info->rf_radio[path] : chip->rf_table[path];
1405 		rf_reg_info->rf_path = rf_table->rf_path;
1406 		if (noio)
1407 			config = rtw89_phy_config_rf_reg_noio;
1408 		else
1409 			config = rf_table->config ? rf_table->config :
1410 				 rtw89_phy_config_rf_reg;
1411 		rtw89_phy_init_reg(rtwdev, rf_table, config, (void *)rf_reg_info);
1412 		if (rtw89_phy_config_rf_reg_fw(rtwdev, rf_reg_info))
1413 			rtw89_warn(rtwdev, "rf path %d reg h2c config failed\n",
1414 				   rf_reg_info->rf_path);
1415 	}
1416 	kfree(rf_reg_info);
1417 }
1418 
1419 static void rtw89_phy_init_rf_nctl(struct rtw89_dev *rtwdev)
1420 {
1421 	struct rtw89_fw_elm_info *elm_info = &rtwdev->fw.elm_info;
1422 	const struct rtw89_chip_info *chip = rtwdev->chip;
1423 	const struct rtw89_phy_table *nctl_table;
1424 	u32 val;
1425 	int ret;
1426 
1427 	/* IQK/DPK clock & reset */
1428 	rtw89_phy_write32_set(rtwdev, R_IOQ_IQK_DPK, 0x3);
1429 	rtw89_phy_write32_set(rtwdev, R_GNT_BT_WGT_EN, 0x1);
1430 	rtw89_phy_write32_set(rtwdev, R_P0_PATH_RST, 0x8000000);
1431 	if (chip->chip_id != RTL8851B)
1432 		rtw89_phy_write32_set(rtwdev, R_P1_PATH_RST, 0x8000000);
1433 	if (chip->chip_id == RTL8852B)
1434 		rtw89_phy_write32_set(rtwdev, R_IOQ_IQK_DPK, 0x2);
1435 
1436 	/* check 0x8080 */
1437 	rtw89_phy_write32(rtwdev, R_NCTL_CFG, 0x8);
1438 
1439 	ret = read_poll_timeout(rtw89_phy_nctl_poll, val, val == 0x4, 10,
1440 				1000, false, rtwdev);
1441 	if (ret)
1442 		rtw89_err(rtwdev, "failed to poll nctl block\n");
1443 
1444 	nctl_table = elm_info->rf_nctl ? elm_info->rf_nctl : chip->nctl_table;
1445 	rtw89_phy_init_reg(rtwdev, nctl_table, rtw89_phy_config_bb_reg, NULL);
1446 
1447 	if (chip->nctl_post_table)
1448 		rtw89_rfk_parser(rtwdev, chip->nctl_post_table);
1449 }
1450 
1451 static u32 rtw89_phy0_phy1_offset(struct rtw89_dev *rtwdev, u32 addr)
1452 {
1453 	u32 phy_page = addr >> 8;
1454 	u32 ofst = 0;
1455 
1456 	switch (phy_page) {
1457 	case 0x6:
1458 	case 0x7:
1459 	case 0x8:
1460 	case 0x9:
1461 	case 0xa:
1462 	case 0xb:
1463 	case 0xc:
1464 	case 0xd:
1465 	case 0x19:
1466 	case 0x1a:
1467 	case 0x1b:
1468 		ofst = 0x2000;
1469 		break;
1470 	default:
1471 		/* warning case */
1472 		ofst = 0;
1473 		break;
1474 	}
1475 
1476 	if (phy_page >= 0x40 && phy_page <= 0x4f)
1477 		ofst = 0x2000;
1478 
1479 	return ofst;
1480 }
1481 
1482 void rtw89_phy_write32_idx(struct rtw89_dev *rtwdev, u32 addr, u32 mask,
1483 			   u32 data, enum rtw89_phy_idx phy_idx)
1484 {
1485 	if (rtwdev->dbcc_en && phy_idx == RTW89_PHY_1)
1486 		addr += rtw89_phy0_phy1_offset(rtwdev, addr);
1487 	rtw89_phy_write32_mask(rtwdev, addr, mask, data);
1488 }
1489 EXPORT_SYMBOL(rtw89_phy_write32_idx);
1490 
1491 u32 rtw89_phy_read32_idx(struct rtw89_dev *rtwdev, u32 addr, u32 mask,
1492 			 enum rtw89_phy_idx phy_idx)
1493 {
1494 	if (rtwdev->dbcc_en && phy_idx == RTW89_PHY_1)
1495 		addr += rtw89_phy0_phy1_offset(rtwdev, addr);
1496 	return rtw89_phy_read32_mask(rtwdev, addr, mask);
1497 }
1498 EXPORT_SYMBOL(rtw89_phy_read32_idx);
1499 
1500 void rtw89_phy_set_phy_regs(struct rtw89_dev *rtwdev, u32 addr, u32 mask,
1501 			    u32 val)
1502 {
1503 	rtw89_phy_write32_idx(rtwdev, addr, mask, val, RTW89_PHY_0);
1504 
1505 	if (!rtwdev->dbcc_en)
1506 		return;
1507 
1508 	rtw89_phy_write32_idx(rtwdev, addr, mask, val, RTW89_PHY_1);
1509 }
1510 
1511 void rtw89_phy_write_reg3_tbl(struct rtw89_dev *rtwdev,
1512 			      const struct rtw89_phy_reg3_tbl *tbl)
1513 {
1514 	const struct rtw89_reg3_def *reg3;
1515 	int i;
1516 
1517 	for (i = 0; i < tbl->size; i++) {
1518 		reg3 = &tbl->reg3[i];
1519 		rtw89_phy_write32_mask(rtwdev, reg3->addr, reg3->mask, reg3->data);
1520 	}
1521 }
1522 EXPORT_SYMBOL(rtw89_phy_write_reg3_tbl);
1523 
1524 static const u8 rtw89_rs_idx_num[] = {
1525 	[RTW89_RS_CCK] = RTW89_RATE_CCK_NUM,
1526 	[RTW89_RS_OFDM] = RTW89_RATE_OFDM_NUM,
1527 	[RTW89_RS_MCS] = RTW89_RATE_MCS_NUM,
1528 	[RTW89_RS_HEDCM] = RTW89_RATE_HEDCM_NUM,
1529 	[RTW89_RS_OFFSET] = RTW89_RATE_OFFSET_NUM,
1530 };
1531 
1532 static const u8 rtw89_rs_nss_num[] = {
1533 	[RTW89_RS_CCK] = 1,
1534 	[RTW89_RS_OFDM] = 1,
1535 	[RTW89_RS_MCS] = RTW89_NSS_NUM,
1536 	[RTW89_RS_HEDCM] = RTW89_NSS_HEDCM_NUM,
1537 	[RTW89_RS_OFFSET] = 1,
1538 };
1539 
1540 static const u8 _byr_of_rs[] = {
1541 	[RTW89_RS_CCK] = offsetof(struct rtw89_txpwr_byrate, cck),
1542 	[RTW89_RS_OFDM] = offsetof(struct rtw89_txpwr_byrate, ofdm),
1543 	[RTW89_RS_MCS] = offsetof(struct rtw89_txpwr_byrate, mcs),
1544 	[RTW89_RS_HEDCM] = offsetof(struct rtw89_txpwr_byrate, hedcm),
1545 	[RTW89_RS_OFFSET] = offsetof(struct rtw89_txpwr_byrate, offset),
1546 };
1547 
1548 #define _byr_seek(rs, raw) ((s8 *)(raw) + _byr_of_rs[rs])
1549 #define _byr_idx(rs, nss, idx) ((nss) * rtw89_rs_idx_num[rs] + (idx))
1550 #define _byr_chk(rs, nss, idx) \
1551 	((nss) < rtw89_rs_nss_num[rs] && (idx) < rtw89_rs_idx_num[rs])
1552 
1553 void rtw89_phy_load_txpwr_byrate(struct rtw89_dev *rtwdev,
1554 				 const struct rtw89_txpwr_table *tbl)
1555 {
1556 	const struct rtw89_txpwr_byrate_cfg *cfg = tbl->data;
1557 	const struct rtw89_txpwr_byrate_cfg *end = cfg + tbl->size;
1558 	s8 *byr;
1559 	u32 data;
1560 	u8 i, idx;
1561 
1562 	for (; cfg < end; cfg++) {
1563 		byr = _byr_seek(cfg->rs, &rtwdev->byr[cfg->band]);
1564 		data = cfg->data;
1565 
1566 		for (i = 0; i < cfg->len; i++, data >>= 8) {
1567 			idx = _byr_idx(cfg->rs, cfg->nss, (cfg->shf + i));
1568 			byr[idx] = (s8)(data & 0xff);
1569 		}
1570 	}
1571 }
1572 EXPORT_SYMBOL(rtw89_phy_load_txpwr_byrate);
1573 
1574 #define _phy_txpwr_rf_to_mac(rtwdev, txpwr_rf)				\
1575 ({									\
1576 	const struct rtw89_chip_info *__c = (rtwdev)->chip;		\
1577 	(txpwr_rf) >> (__c->txpwr_factor_rf - __c->txpwr_factor_mac);	\
1578 })
1579 
1580 static
1581 s8 rtw89_phy_read_txpwr_byrate(struct rtw89_dev *rtwdev, u8 band,
1582 			       const struct rtw89_rate_desc *rate_desc)
1583 {
1584 	s8 *byr;
1585 	u8 idx;
1586 
1587 	if (rate_desc->rs == RTW89_RS_CCK)
1588 		band = RTW89_BAND_2G;
1589 
1590 	if (!_byr_chk(rate_desc->rs, rate_desc->nss, rate_desc->idx)) {
1591 		rtw89_debug(rtwdev, RTW89_DBG_TXPWR,
1592 			    "[TXPWR] unknown byrate desc rs=%d nss=%d idx=%d\n",
1593 			    rate_desc->rs, rate_desc->nss, rate_desc->idx);
1594 
1595 		return 0;
1596 	}
1597 
1598 	byr = _byr_seek(rate_desc->rs, &rtwdev->byr[band]);
1599 	idx = _byr_idx(rate_desc->rs, rate_desc->nss, rate_desc->idx);
1600 
1601 	return _phy_txpwr_rf_to_mac(rtwdev, byr[idx]);
1602 }
1603 
1604 static u8 rtw89_channel_6g_to_idx(struct rtw89_dev *rtwdev, u8 channel_6g)
1605 {
1606 	switch (channel_6g) {
1607 	case 1 ... 29:
1608 		return (channel_6g - 1) / 2;
1609 	case 33 ... 61:
1610 		return (channel_6g - 3) / 2;
1611 	case 65 ... 93:
1612 		return (channel_6g - 5) / 2;
1613 	case 97 ... 125:
1614 		return (channel_6g - 7) / 2;
1615 	case 129 ... 157:
1616 		return (channel_6g - 9) / 2;
1617 	case 161 ... 189:
1618 		return (channel_6g - 11) / 2;
1619 	case 193 ... 221:
1620 		return (channel_6g - 13) / 2;
1621 	case 225 ... 253:
1622 		return (channel_6g - 15) / 2;
1623 	default:
1624 		rtw89_warn(rtwdev, "unknown 6g channel: %d\n", channel_6g);
1625 		return 0;
1626 	}
1627 }
1628 
1629 static u8 rtw89_channel_to_idx(struct rtw89_dev *rtwdev, u8 band, u8 channel)
1630 {
1631 	if (band == RTW89_BAND_6G)
1632 		return rtw89_channel_6g_to_idx(rtwdev, channel);
1633 
1634 	switch (channel) {
1635 	case 1 ... 14:
1636 		return channel - 1;
1637 	case 36 ... 64:
1638 		return (channel - 36) / 2;
1639 	case 100 ... 144:
1640 		return ((channel - 100) / 2) + 15;
1641 	case 149 ... 177:
1642 		return ((channel - 149) / 2) + 38;
1643 	default:
1644 		rtw89_warn(rtwdev, "unknown channel: %d\n", channel);
1645 		return 0;
1646 	}
1647 }
1648 
1649 s8 rtw89_phy_read_txpwr_limit(struct rtw89_dev *rtwdev, u8 band,
1650 			      u8 bw, u8 ntx, u8 rs, u8 bf, u8 ch)
1651 {
1652 	const struct rtw89_rfe_parms *rfe_parms = rtwdev->rfe_parms;
1653 	const struct rtw89_txpwr_rule_2ghz *rule_2ghz = &rfe_parms->rule_2ghz;
1654 	const struct rtw89_txpwr_rule_5ghz *rule_5ghz = &rfe_parms->rule_5ghz;
1655 	const struct rtw89_txpwr_rule_6ghz *rule_6ghz = &rfe_parms->rule_6ghz;
1656 	struct rtw89_regulatory_info *regulatory = &rtwdev->regulatory;
1657 	u8 ch_idx = rtw89_channel_to_idx(rtwdev, band, ch);
1658 	u8 regd = rtw89_regd_get(rtwdev, band);
1659 	u8 reg6 = regulatory->reg_6ghz_power;
1660 	s8 lmt = 0, sar;
1661 
1662 	switch (band) {
1663 	case RTW89_BAND_2G:
1664 		lmt = (*rule_2ghz->lmt)[bw][ntx][rs][bf][regd][ch_idx];
1665 		if (lmt)
1666 			break;
1667 
1668 		lmt = (*rule_2ghz->lmt)[bw][ntx][rs][bf][RTW89_WW][ch_idx];
1669 		break;
1670 	case RTW89_BAND_5G:
1671 		lmt = (*rule_5ghz->lmt)[bw][ntx][rs][bf][regd][ch_idx];
1672 		if (lmt)
1673 			break;
1674 
1675 		lmt = (*rule_5ghz->lmt)[bw][ntx][rs][bf][RTW89_WW][ch_idx];
1676 		break;
1677 	case RTW89_BAND_6G:
1678 		lmt = (*rule_6ghz->lmt)[bw][ntx][rs][bf][regd][reg6][ch_idx];
1679 		if (lmt)
1680 			break;
1681 
1682 		lmt = (*rule_6ghz->lmt)[bw][ntx][rs][bf][RTW89_WW]
1683 				       [RTW89_REG_6GHZ_POWER_DFLT]
1684 				       [ch_idx];
1685 		break;
1686 	default:
1687 		rtw89_warn(rtwdev, "unknown band type: %d\n", band);
1688 		return 0;
1689 	}
1690 
1691 	lmt = _phy_txpwr_rf_to_mac(rtwdev, lmt);
1692 	sar = rtw89_query_sar(rtwdev);
1693 
1694 	return min(lmt, sar);
1695 }
1696 EXPORT_SYMBOL(rtw89_phy_read_txpwr_limit);
1697 
1698 #define __fill_txpwr_limit_nonbf_bf(ptr, band, bw, ntx, rs, ch)		\
1699 	do {								\
1700 		u8 __i;							\
1701 		for (__i = 0; __i < RTW89_BF_NUM; __i++)		\
1702 			ptr[__i] = rtw89_phy_read_txpwr_limit(rtwdev,	\
1703 							      band,	\
1704 							      bw, ntx,	\
1705 							      rs, __i,	\
1706 							      (ch));	\
1707 	} while (0)
1708 
1709 static void rtw89_phy_fill_txpwr_limit_20m(struct rtw89_dev *rtwdev,
1710 					   struct rtw89_txpwr_limit *lmt,
1711 					   u8 band, u8 ntx, u8 ch)
1712 {
1713 	__fill_txpwr_limit_nonbf_bf(lmt->cck_20m, band, RTW89_CHANNEL_WIDTH_20,
1714 				    ntx, RTW89_RS_CCK, ch);
1715 	__fill_txpwr_limit_nonbf_bf(lmt->cck_40m, band, RTW89_CHANNEL_WIDTH_40,
1716 				    ntx, RTW89_RS_CCK, ch);
1717 	__fill_txpwr_limit_nonbf_bf(lmt->ofdm, band, RTW89_CHANNEL_WIDTH_20,
1718 				    ntx, RTW89_RS_OFDM, ch);
1719 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[0], band,
1720 				    RTW89_CHANNEL_WIDTH_20,
1721 				    ntx, RTW89_RS_MCS, ch);
1722 }
1723 
1724 static void rtw89_phy_fill_txpwr_limit_40m(struct rtw89_dev *rtwdev,
1725 					   struct rtw89_txpwr_limit *lmt,
1726 					   u8 band, u8 ntx, u8 ch, u8 pri_ch)
1727 {
1728 	__fill_txpwr_limit_nonbf_bf(lmt->cck_20m, band, RTW89_CHANNEL_WIDTH_20,
1729 				    ntx, RTW89_RS_CCK, ch - 2);
1730 	__fill_txpwr_limit_nonbf_bf(lmt->cck_40m, band, RTW89_CHANNEL_WIDTH_40,
1731 				    ntx, RTW89_RS_CCK, ch);
1732 	__fill_txpwr_limit_nonbf_bf(lmt->ofdm, band, RTW89_CHANNEL_WIDTH_20,
1733 				    ntx, RTW89_RS_OFDM, pri_ch);
1734 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[0], band,
1735 				    RTW89_CHANNEL_WIDTH_20,
1736 				    ntx, RTW89_RS_MCS, ch - 2);
1737 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[1], band,
1738 				    RTW89_CHANNEL_WIDTH_20,
1739 				    ntx, RTW89_RS_MCS, ch + 2);
1740 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_40m[0], band,
1741 				    RTW89_CHANNEL_WIDTH_40,
1742 				    ntx, RTW89_RS_MCS, ch);
1743 }
1744 
1745 static void rtw89_phy_fill_txpwr_limit_80m(struct rtw89_dev *rtwdev,
1746 					   struct rtw89_txpwr_limit *lmt,
1747 					   u8 band, u8 ntx, u8 ch, u8 pri_ch)
1748 {
1749 	s8 val_0p5_n[RTW89_BF_NUM];
1750 	s8 val_0p5_p[RTW89_BF_NUM];
1751 	u8 i;
1752 
1753 	__fill_txpwr_limit_nonbf_bf(lmt->ofdm, band, RTW89_CHANNEL_WIDTH_20,
1754 				    ntx, RTW89_RS_OFDM, pri_ch);
1755 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[0], band,
1756 				    RTW89_CHANNEL_WIDTH_20,
1757 				    ntx, RTW89_RS_MCS, ch - 6);
1758 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[1], band,
1759 				    RTW89_CHANNEL_WIDTH_20,
1760 				    ntx, RTW89_RS_MCS, ch - 2);
1761 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[2], band,
1762 				    RTW89_CHANNEL_WIDTH_20,
1763 				    ntx, RTW89_RS_MCS, ch + 2);
1764 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[3], band,
1765 				    RTW89_CHANNEL_WIDTH_20,
1766 				    ntx, RTW89_RS_MCS, ch + 6);
1767 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_40m[0], band,
1768 				    RTW89_CHANNEL_WIDTH_40,
1769 				    ntx, RTW89_RS_MCS, ch - 4);
1770 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_40m[1], band,
1771 				    RTW89_CHANNEL_WIDTH_40,
1772 				    ntx, RTW89_RS_MCS, ch + 4);
1773 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_80m[0], band,
1774 				    RTW89_CHANNEL_WIDTH_80,
1775 				    ntx, RTW89_RS_MCS, ch);
1776 
1777 	__fill_txpwr_limit_nonbf_bf(val_0p5_n, band, RTW89_CHANNEL_WIDTH_40,
1778 				    ntx, RTW89_RS_MCS, ch - 4);
1779 	__fill_txpwr_limit_nonbf_bf(val_0p5_p, band, RTW89_CHANNEL_WIDTH_40,
1780 				    ntx, RTW89_RS_MCS, ch + 4);
1781 
1782 	for (i = 0; i < RTW89_BF_NUM; i++)
1783 		lmt->mcs_40m_0p5[i] = min_t(s8, val_0p5_n[i], val_0p5_p[i]);
1784 }
1785 
1786 static void rtw89_phy_fill_txpwr_limit_160m(struct rtw89_dev *rtwdev,
1787 					    struct rtw89_txpwr_limit *lmt,
1788 					    u8 band, u8 ntx, u8 ch, u8 pri_ch)
1789 {
1790 	s8 val_0p5_n[RTW89_BF_NUM];
1791 	s8 val_0p5_p[RTW89_BF_NUM];
1792 	s8 val_2p5_n[RTW89_BF_NUM];
1793 	s8 val_2p5_p[RTW89_BF_NUM];
1794 	u8 i;
1795 
1796 	/* fill ofdm section */
1797 	__fill_txpwr_limit_nonbf_bf(lmt->ofdm, band, RTW89_CHANNEL_WIDTH_20,
1798 				    ntx, RTW89_RS_OFDM, pri_ch);
1799 
1800 	/* fill mcs 20m section */
1801 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[0], band,
1802 				    RTW89_CHANNEL_WIDTH_20,
1803 				    ntx, RTW89_RS_MCS, ch - 14);
1804 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[1], band,
1805 				    RTW89_CHANNEL_WIDTH_20,
1806 				    ntx, RTW89_RS_MCS, ch - 10);
1807 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[2], band,
1808 				    RTW89_CHANNEL_WIDTH_20,
1809 				    ntx, RTW89_RS_MCS, ch - 6);
1810 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[3], band,
1811 				    RTW89_CHANNEL_WIDTH_20,
1812 				    ntx, RTW89_RS_MCS, ch - 2);
1813 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[4], band,
1814 				    RTW89_CHANNEL_WIDTH_20,
1815 				    ntx, RTW89_RS_MCS, ch + 2);
1816 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[5], band,
1817 				    RTW89_CHANNEL_WIDTH_20,
1818 				    ntx, RTW89_RS_MCS, ch + 6);
1819 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[6], band,
1820 				    RTW89_CHANNEL_WIDTH_20,
1821 				    ntx, RTW89_RS_MCS, ch + 10);
1822 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[7], band,
1823 				    RTW89_CHANNEL_WIDTH_20,
1824 				    ntx, RTW89_RS_MCS, ch + 14);
1825 
1826 	/* fill mcs 40m section */
1827 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_40m[0], band,
1828 				    RTW89_CHANNEL_WIDTH_40,
1829 				    ntx, RTW89_RS_MCS, ch - 12);
1830 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_40m[1], band,
1831 				    RTW89_CHANNEL_WIDTH_40,
1832 				    ntx, RTW89_RS_MCS, ch - 4);
1833 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_40m[2], band,
1834 				    RTW89_CHANNEL_WIDTH_40,
1835 				    ntx, RTW89_RS_MCS, ch + 4);
1836 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_40m[3], band,
1837 				    RTW89_CHANNEL_WIDTH_40,
1838 				    ntx, RTW89_RS_MCS, ch + 12);
1839 
1840 	/* fill mcs 80m section */
1841 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_80m[0], band,
1842 				    RTW89_CHANNEL_WIDTH_80,
1843 				    ntx, RTW89_RS_MCS, ch - 8);
1844 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_80m[1], band,
1845 				    RTW89_CHANNEL_WIDTH_80,
1846 				    ntx, RTW89_RS_MCS, ch + 8);
1847 
1848 	/* fill mcs 160m section */
1849 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_160m, band,
1850 				    RTW89_CHANNEL_WIDTH_160,
1851 				    ntx, RTW89_RS_MCS, ch);
1852 
1853 	/* fill mcs 40m 0p5 section */
1854 	__fill_txpwr_limit_nonbf_bf(val_0p5_n, band, RTW89_CHANNEL_WIDTH_40,
1855 				    ntx, RTW89_RS_MCS, ch - 4);
1856 	__fill_txpwr_limit_nonbf_bf(val_0p5_p, band, RTW89_CHANNEL_WIDTH_40,
1857 				    ntx, RTW89_RS_MCS, ch + 4);
1858 
1859 	for (i = 0; i < RTW89_BF_NUM; i++)
1860 		lmt->mcs_40m_0p5[i] = min_t(s8, val_0p5_n[i], val_0p5_p[i]);
1861 
1862 	/* fill mcs 40m 2p5 section */
1863 	__fill_txpwr_limit_nonbf_bf(val_2p5_n, band, RTW89_CHANNEL_WIDTH_40,
1864 				    ntx, RTW89_RS_MCS, ch - 8);
1865 	__fill_txpwr_limit_nonbf_bf(val_2p5_p, band, RTW89_CHANNEL_WIDTH_40,
1866 				    ntx, RTW89_RS_MCS, ch + 8);
1867 
1868 	for (i = 0; i < RTW89_BF_NUM; i++)
1869 		lmt->mcs_40m_2p5[i] = min_t(s8, val_2p5_n[i], val_2p5_p[i]);
1870 }
1871 
1872 static
1873 void rtw89_phy_fill_txpwr_limit(struct rtw89_dev *rtwdev,
1874 				const struct rtw89_chan *chan,
1875 				struct rtw89_txpwr_limit *lmt,
1876 				u8 ntx)
1877 {
1878 	u8 band = chan->band_type;
1879 	u8 pri_ch = chan->primary_channel;
1880 	u8 ch = chan->channel;
1881 	u8 bw = chan->band_width;
1882 
1883 	memset(lmt, 0, sizeof(*lmt));
1884 
1885 	switch (bw) {
1886 	case RTW89_CHANNEL_WIDTH_20:
1887 		rtw89_phy_fill_txpwr_limit_20m(rtwdev, lmt, band, ntx, ch);
1888 		break;
1889 	case RTW89_CHANNEL_WIDTH_40:
1890 		rtw89_phy_fill_txpwr_limit_40m(rtwdev, lmt, band, ntx, ch,
1891 					       pri_ch);
1892 		break;
1893 	case RTW89_CHANNEL_WIDTH_80:
1894 		rtw89_phy_fill_txpwr_limit_80m(rtwdev, lmt, band, ntx, ch,
1895 					       pri_ch);
1896 		break;
1897 	case RTW89_CHANNEL_WIDTH_160:
1898 		rtw89_phy_fill_txpwr_limit_160m(rtwdev, lmt, band, ntx, ch,
1899 						pri_ch);
1900 		break;
1901 	}
1902 }
1903 
1904 static s8 rtw89_phy_read_txpwr_limit_ru(struct rtw89_dev *rtwdev, u8 band,
1905 					u8 ru, u8 ntx, u8 ch)
1906 {
1907 	const struct rtw89_rfe_parms *rfe_parms = rtwdev->rfe_parms;
1908 	const struct rtw89_txpwr_rule_2ghz *rule_2ghz = &rfe_parms->rule_2ghz;
1909 	const struct rtw89_txpwr_rule_5ghz *rule_5ghz = &rfe_parms->rule_5ghz;
1910 	const struct rtw89_txpwr_rule_6ghz *rule_6ghz = &rfe_parms->rule_6ghz;
1911 	struct rtw89_regulatory_info *regulatory = &rtwdev->regulatory;
1912 	u8 ch_idx = rtw89_channel_to_idx(rtwdev, band, ch);
1913 	u8 regd = rtw89_regd_get(rtwdev, band);
1914 	u8 reg6 = regulatory->reg_6ghz_power;
1915 	s8 lmt_ru = 0, sar;
1916 
1917 	switch (band) {
1918 	case RTW89_BAND_2G:
1919 		lmt_ru = (*rule_2ghz->lmt_ru)[ru][ntx][regd][ch_idx];
1920 		if (lmt_ru)
1921 			break;
1922 
1923 		lmt_ru = (*rule_2ghz->lmt_ru)[ru][ntx][RTW89_WW][ch_idx];
1924 		break;
1925 	case RTW89_BAND_5G:
1926 		lmt_ru = (*rule_5ghz->lmt_ru)[ru][ntx][regd][ch_idx];
1927 		if (lmt_ru)
1928 			break;
1929 
1930 		lmt_ru = (*rule_5ghz->lmt_ru)[ru][ntx][RTW89_WW][ch_idx];
1931 		break;
1932 	case RTW89_BAND_6G:
1933 		lmt_ru = (*rule_6ghz->lmt_ru)[ru][ntx][regd][reg6][ch_idx];
1934 		if (lmt_ru)
1935 			break;
1936 
1937 		lmt_ru = (*rule_6ghz->lmt_ru)[ru][ntx][RTW89_WW]
1938 					     [RTW89_REG_6GHZ_POWER_DFLT]
1939 					     [ch_idx];
1940 		break;
1941 	default:
1942 		rtw89_warn(rtwdev, "unknown band type: %d\n", band);
1943 		return 0;
1944 	}
1945 
1946 	lmt_ru = _phy_txpwr_rf_to_mac(rtwdev, lmt_ru);
1947 	sar = rtw89_query_sar(rtwdev);
1948 
1949 	return min(lmt_ru, sar);
1950 }
1951 
1952 static void
1953 rtw89_phy_fill_txpwr_limit_ru_20m(struct rtw89_dev *rtwdev,
1954 				  struct rtw89_txpwr_limit_ru *lmt_ru,
1955 				  u8 band, u8 ntx, u8 ch)
1956 {
1957 	lmt_ru->ru26[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1958 							RTW89_RU26,
1959 							ntx, ch);
1960 	lmt_ru->ru52[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1961 							RTW89_RU52,
1962 							ntx, ch);
1963 	lmt_ru->ru106[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1964 							 RTW89_RU106,
1965 							 ntx, ch);
1966 }
1967 
1968 static void
1969 rtw89_phy_fill_txpwr_limit_ru_40m(struct rtw89_dev *rtwdev,
1970 				  struct rtw89_txpwr_limit_ru *lmt_ru,
1971 				  u8 band, u8 ntx, u8 ch)
1972 {
1973 	lmt_ru->ru26[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1974 							RTW89_RU26,
1975 							ntx, ch - 2);
1976 	lmt_ru->ru26[1] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1977 							RTW89_RU26,
1978 							ntx, ch + 2);
1979 	lmt_ru->ru52[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1980 							RTW89_RU52,
1981 							ntx, ch - 2);
1982 	lmt_ru->ru52[1] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1983 							RTW89_RU52,
1984 							ntx, ch + 2);
1985 	lmt_ru->ru106[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1986 							 RTW89_RU106,
1987 							 ntx, ch - 2);
1988 	lmt_ru->ru106[1] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1989 							 RTW89_RU106,
1990 							 ntx, ch + 2);
1991 }
1992 
1993 static void
1994 rtw89_phy_fill_txpwr_limit_ru_80m(struct rtw89_dev *rtwdev,
1995 				  struct rtw89_txpwr_limit_ru *lmt_ru,
1996 				  u8 band, u8 ntx, u8 ch)
1997 {
1998 	lmt_ru->ru26[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1999 							RTW89_RU26,
2000 							ntx, ch - 6);
2001 	lmt_ru->ru26[1] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
2002 							RTW89_RU26,
2003 							ntx, ch - 2);
2004 	lmt_ru->ru26[2] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
2005 							RTW89_RU26,
2006 							ntx, ch + 2);
2007 	lmt_ru->ru26[3] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
2008 							RTW89_RU26,
2009 							ntx, ch + 6);
2010 	lmt_ru->ru52[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
2011 							RTW89_RU52,
2012 							ntx, ch - 6);
2013 	lmt_ru->ru52[1] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
2014 							RTW89_RU52,
2015 							ntx, ch - 2);
2016 	lmt_ru->ru52[2] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
2017 							RTW89_RU52,
2018 							ntx, ch + 2);
2019 	lmt_ru->ru52[3] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
2020 							RTW89_RU52,
2021 							ntx, ch + 6);
2022 	lmt_ru->ru106[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
2023 							 RTW89_RU106,
2024 							 ntx, ch - 6);
2025 	lmt_ru->ru106[1] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
2026 							 RTW89_RU106,
2027 							 ntx, ch - 2);
2028 	lmt_ru->ru106[2] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
2029 							 RTW89_RU106,
2030 							 ntx, ch + 2);
2031 	lmt_ru->ru106[3] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
2032 							 RTW89_RU106,
2033 							 ntx, ch + 6);
2034 }
2035 
2036 static void
2037 rtw89_phy_fill_txpwr_limit_ru_160m(struct rtw89_dev *rtwdev,
2038 				   struct rtw89_txpwr_limit_ru *lmt_ru,
2039 				   u8 band, u8 ntx, u8 ch)
2040 {
2041 	static const int ofst[] = { -14, -10, -6, -2, 2, 6, 10, 14 };
2042 	int i;
2043 
2044 #if defined(__linux__)
2045 	static_assert(ARRAY_SIZE(ofst) == RTW89_RU_SEC_NUM);
2046 #elif defined(__FreeBSD__)
2047 	rtw89_static_assert(ARRAY_SIZE(ofst) == RTW89_RU_SEC_NUM);
2048 #endif
2049 	for (i = 0; i < RTW89_RU_SEC_NUM; i++) {
2050 		lmt_ru->ru26[i] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
2051 								RTW89_RU26,
2052 								ntx,
2053 								ch + ofst[i]);
2054 		lmt_ru->ru52[i] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
2055 								RTW89_RU52,
2056 								ntx,
2057 								ch + ofst[i]);
2058 		lmt_ru->ru106[i] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
2059 								 RTW89_RU106,
2060 								 ntx,
2061 								 ch + ofst[i]);
2062 	}
2063 }
2064 
2065 static
2066 void rtw89_phy_fill_txpwr_limit_ru(struct rtw89_dev *rtwdev,
2067 				   const struct rtw89_chan *chan,
2068 				   struct rtw89_txpwr_limit_ru *lmt_ru,
2069 				   u8 ntx)
2070 {
2071 	u8 band = chan->band_type;
2072 	u8 ch = chan->channel;
2073 	u8 bw = chan->band_width;
2074 
2075 	memset(lmt_ru, 0, sizeof(*lmt_ru));
2076 
2077 	switch (bw) {
2078 	case RTW89_CHANNEL_WIDTH_20:
2079 		rtw89_phy_fill_txpwr_limit_ru_20m(rtwdev, lmt_ru, band, ntx,
2080 						  ch);
2081 		break;
2082 	case RTW89_CHANNEL_WIDTH_40:
2083 		rtw89_phy_fill_txpwr_limit_ru_40m(rtwdev, lmt_ru, band, ntx,
2084 						  ch);
2085 		break;
2086 	case RTW89_CHANNEL_WIDTH_80:
2087 		rtw89_phy_fill_txpwr_limit_ru_80m(rtwdev, lmt_ru, band, ntx,
2088 						  ch);
2089 		break;
2090 	case RTW89_CHANNEL_WIDTH_160:
2091 		rtw89_phy_fill_txpwr_limit_ru_160m(rtwdev, lmt_ru, band, ntx,
2092 						   ch);
2093 		break;
2094 	}
2095 }
2096 
2097 void rtw89_phy_set_txpwr_byrate(struct rtw89_dev *rtwdev,
2098 				const struct rtw89_chan *chan,
2099 				enum rtw89_phy_idx phy_idx)
2100 {
2101 	u8 max_nss_num = rtwdev->chip->rf_path_num;
2102 	static const u8 rs[] = {
2103 		RTW89_RS_CCK,
2104 		RTW89_RS_OFDM,
2105 		RTW89_RS_MCS,
2106 		RTW89_RS_HEDCM,
2107 	};
2108 	struct rtw89_rate_desc cur;
2109 	u8 band = chan->band_type;
2110 	u8 ch = chan->channel;
2111 	u32 addr, val;
2112 	s8 v[4] = {};
2113 	u8 i;
2114 
2115 	rtw89_debug(rtwdev, RTW89_DBG_TXPWR,
2116 		    "[TXPWR] set txpwr byrate with ch=%d\n", ch);
2117 
2118 	BUILD_BUG_ON(rtw89_rs_idx_num[RTW89_RS_CCK] % 4);
2119 	BUILD_BUG_ON(rtw89_rs_idx_num[RTW89_RS_OFDM] % 4);
2120 	BUILD_BUG_ON(rtw89_rs_idx_num[RTW89_RS_MCS] % 4);
2121 	BUILD_BUG_ON(rtw89_rs_idx_num[RTW89_RS_HEDCM] % 4);
2122 
2123 	addr = R_AX_PWR_BY_RATE;
2124 	for (cur.nss = 0; cur.nss < max_nss_num; cur.nss++) {
2125 		for (i = 0; i < ARRAY_SIZE(rs); i++) {
2126 			if (cur.nss >= rtw89_rs_nss_num[rs[i]])
2127 				continue;
2128 
2129 			cur.rs = rs[i];
2130 			for (cur.idx = 0; cur.idx < rtw89_rs_idx_num[rs[i]];
2131 			     cur.idx++) {
2132 				v[cur.idx % 4] =
2133 					rtw89_phy_read_txpwr_byrate(rtwdev,
2134 								    band,
2135 								    &cur);
2136 
2137 				if ((cur.idx + 1) % 4)
2138 					continue;
2139 
2140 				val = FIELD_PREP(GENMASK(7, 0), v[0]) |
2141 				      FIELD_PREP(GENMASK(15, 8), v[1]) |
2142 				      FIELD_PREP(GENMASK(23, 16), v[2]) |
2143 				      FIELD_PREP(GENMASK(31, 24), v[3]);
2144 
2145 				rtw89_mac_txpwr_write32(rtwdev, phy_idx, addr,
2146 							val);
2147 				addr += 4;
2148 			}
2149 		}
2150 	}
2151 }
2152 EXPORT_SYMBOL(rtw89_phy_set_txpwr_byrate);
2153 
2154 void rtw89_phy_set_txpwr_offset(struct rtw89_dev *rtwdev,
2155 				const struct rtw89_chan *chan,
2156 				enum rtw89_phy_idx phy_idx)
2157 {
2158 	struct rtw89_rate_desc desc = {
2159 		.nss = RTW89_NSS_1,
2160 		.rs = RTW89_RS_OFFSET,
2161 	};
2162 	u8 band = chan->band_type;
2163 	s8 v[RTW89_RATE_OFFSET_NUM] = {};
2164 	u32 val;
2165 
2166 	rtw89_debug(rtwdev, RTW89_DBG_TXPWR, "[TXPWR] set txpwr offset\n");
2167 
2168 	for (desc.idx = 0; desc.idx < RTW89_RATE_OFFSET_NUM; desc.idx++)
2169 		v[desc.idx] = rtw89_phy_read_txpwr_byrate(rtwdev, band, &desc);
2170 
2171 	BUILD_BUG_ON(RTW89_RATE_OFFSET_NUM != 5);
2172 	val = FIELD_PREP(GENMASK(3, 0), v[0]) |
2173 	      FIELD_PREP(GENMASK(7, 4), v[1]) |
2174 	      FIELD_PREP(GENMASK(11, 8), v[2]) |
2175 	      FIELD_PREP(GENMASK(15, 12), v[3]) |
2176 	      FIELD_PREP(GENMASK(19, 16), v[4]);
2177 
2178 	rtw89_mac_txpwr_write32_mask(rtwdev, phy_idx, R_AX_PWR_RATE_OFST_CTRL,
2179 				     GENMASK(19, 0), val);
2180 }
2181 EXPORT_SYMBOL(rtw89_phy_set_txpwr_offset);
2182 
2183 void rtw89_phy_set_txpwr_limit(struct rtw89_dev *rtwdev,
2184 			       const struct rtw89_chan *chan,
2185 			       enum rtw89_phy_idx phy_idx)
2186 {
2187 	u8 max_ntx_num = rtwdev->chip->rf_path_num;
2188 	struct rtw89_txpwr_limit lmt;
2189 	u8 ch = chan->channel;
2190 	u8 bw = chan->band_width;
2191 	const s8 *ptr;
2192 	u32 addr, val;
2193 	u8 i, j;
2194 
2195 	rtw89_debug(rtwdev, RTW89_DBG_TXPWR,
2196 		    "[TXPWR] set txpwr limit with ch=%d bw=%d\n", ch, bw);
2197 
2198 	BUILD_BUG_ON(sizeof(struct rtw89_txpwr_limit) !=
2199 		     RTW89_TXPWR_LMT_PAGE_SIZE);
2200 
2201 	addr = R_AX_PWR_LMT;
2202 	for (i = 0; i < max_ntx_num; i++) {
2203 		rtw89_phy_fill_txpwr_limit(rtwdev, chan, &lmt, i);
2204 
2205 		ptr = (s8 *)&lmt;
2206 		for (j = 0; j < RTW89_TXPWR_LMT_PAGE_SIZE;
2207 		     j += 4, addr += 4, ptr += 4) {
2208 			val = FIELD_PREP(GENMASK(7, 0), ptr[0]) |
2209 			      FIELD_PREP(GENMASK(15, 8), ptr[1]) |
2210 			      FIELD_PREP(GENMASK(23, 16), ptr[2]) |
2211 			      FIELD_PREP(GENMASK(31, 24), ptr[3]);
2212 
2213 			rtw89_mac_txpwr_write32(rtwdev, phy_idx, addr, val);
2214 		}
2215 	}
2216 }
2217 EXPORT_SYMBOL(rtw89_phy_set_txpwr_limit);
2218 
2219 void rtw89_phy_set_txpwr_limit_ru(struct rtw89_dev *rtwdev,
2220 				  const struct rtw89_chan *chan,
2221 				  enum rtw89_phy_idx phy_idx)
2222 {
2223 	u8 max_ntx_num = rtwdev->chip->rf_path_num;
2224 	struct rtw89_txpwr_limit_ru lmt_ru;
2225 	u8 ch = chan->channel;
2226 	u8 bw = chan->band_width;
2227 	const s8 *ptr;
2228 	u32 addr, val;
2229 	u8 i, j;
2230 
2231 	rtw89_debug(rtwdev, RTW89_DBG_TXPWR,
2232 		    "[TXPWR] set txpwr limit ru with ch=%d bw=%d\n", ch, bw);
2233 
2234 	BUILD_BUG_ON(sizeof(struct rtw89_txpwr_limit_ru) !=
2235 		     RTW89_TXPWR_LMT_RU_PAGE_SIZE);
2236 
2237 	addr = R_AX_PWR_RU_LMT;
2238 	for (i = 0; i < max_ntx_num; i++) {
2239 		rtw89_phy_fill_txpwr_limit_ru(rtwdev, chan, &lmt_ru, i);
2240 
2241 		ptr = (s8 *)&lmt_ru;
2242 		for (j = 0; j < RTW89_TXPWR_LMT_RU_PAGE_SIZE;
2243 		     j += 4, addr += 4, ptr += 4) {
2244 			val = FIELD_PREP(GENMASK(7, 0), ptr[0]) |
2245 			      FIELD_PREP(GENMASK(15, 8), ptr[1]) |
2246 			      FIELD_PREP(GENMASK(23, 16), ptr[2]) |
2247 			      FIELD_PREP(GENMASK(31, 24), ptr[3]);
2248 
2249 			rtw89_mac_txpwr_write32(rtwdev, phy_idx, addr, val);
2250 		}
2251 	}
2252 }
2253 EXPORT_SYMBOL(rtw89_phy_set_txpwr_limit_ru);
2254 
2255 struct rtw89_phy_iter_ra_data {
2256 	struct rtw89_dev *rtwdev;
2257 	struct sk_buff *c2h;
2258 };
2259 
2260 static void rtw89_phy_c2h_ra_rpt_iter(void *data, struct ieee80211_sta *sta)
2261 {
2262 	struct rtw89_phy_iter_ra_data *ra_data = (struct rtw89_phy_iter_ra_data *)data;
2263 	struct rtw89_dev *rtwdev = ra_data->rtwdev;
2264 	struct rtw89_sta *rtwsta = (struct rtw89_sta *)sta->drv_priv;
2265 	const struct rtw89_c2h_ra_rpt *c2h =
2266 		(const struct rtw89_c2h_ra_rpt *)ra_data->c2h->data;
2267 	struct rtw89_ra_report *ra_report = &rtwsta->ra_report;
2268 	const struct rtw89_chip_info *chip = rtwdev->chip;
2269 	bool format_v1 = chip->chip_gen == RTW89_CHIP_BE;
2270 	u8 mode, rate, bw, giltf, mac_id;
2271 	u16 legacy_bitrate;
2272 	bool valid;
2273 	u8 mcs = 0;
2274 	u8 t;
2275 
2276 	mac_id = le32_get_bits(c2h->w2, RTW89_C2H_RA_RPT_W2_MACID);
2277 	if (mac_id != rtwsta->mac_id)
2278 		return;
2279 
2280 	rate = le32_get_bits(c2h->w3, RTW89_C2H_RA_RPT_W3_MCSNSS);
2281 	bw = le32_get_bits(c2h->w3, RTW89_C2H_RA_RPT_W3_BW);
2282 	giltf = le32_get_bits(c2h->w3, RTW89_C2H_RA_RPT_W3_GILTF);
2283 	mode = le32_get_bits(c2h->w3, RTW89_C2H_RA_RPT_W3_MD_SEL);
2284 
2285 	if (format_v1) {
2286 		t = le32_get_bits(c2h->w2, RTW89_C2H_RA_RPT_W2_MCSNSS_B7);
2287 		rate |= u8_encode_bits(t, BIT(7));
2288 		t = le32_get_bits(c2h->w3, RTW89_C2H_RA_RPT_W3_BW_B2);
2289 		bw |= u8_encode_bits(t, BIT(2));
2290 		t = le32_get_bits(c2h->w3, RTW89_C2H_RA_RPT_W3_MD_SEL_B2);
2291 		mode |= u8_encode_bits(t, BIT(2));
2292 	}
2293 
2294 	if (mode == RTW89_RA_RPT_MODE_LEGACY) {
2295 		valid = rtw89_ra_report_to_bitrate(rtwdev, rate, &legacy_bitrate);
2296 		if (!valid)
2297 			return;
2298 	}
2299 
2300 	memset(&ra_report->txrate, 0, sizeof(ra_report->txrate));
2301 
2302 	switch (mode) {
2303 	case RTW89_RA_RPT_MODE_LEGACY:
2304 		ra_report->txrate.legacy = legacy_bitrate;
2305 		break;
2306 	case RTW89_RA_RPT_MODE_HT:
2307 		ra_report->txrate.flags |= RATE_INFO_FLAGS_MCS;
2308 		if (RTW89_CHK_FW_FEATURE(OLD_HT_RA_FORMAT, &rtwdev->fw))
2309 			rate = RTW89_MK_HT_RATE(FIELD_GET(RTW89_RA_RATE_MASK_NSS, rate),
2310 						FIELD_GET(RTW89_RA_RATE_MASK_MCS, rate));
2311 		else
2312 			rate = FIELD_GET(RTW89_RA_RATE_MASK_HT_MCS, rate);
2313 		ra_report->txrate.mcs = rate;
2314 		if (giltf)
2315 			ra_report->txrate.flags |= RATE_INFO_FLAGS_SHORT_GI;
2316 		mcs = ra_report->txrate.mcs & 0x07;
2317 		break;
2318 	case RTW89_RA_RPT_MODE_VHT:
2319 		ra_report->txrate.flags |= RATE_INFO_FLAGS_VHT_MCS;
2320 		ra_report->txrate.mcs = format_v1 ?
2321 			u8_get_bits(rate, RTW89_RA_RATE_MASK_MCS_V1) :
2322 			u8_get_bits(rate, RTW89_RA_RATE_MASK_MCS);
2323 		ra_report->txrate.nss = format_v1 ?
2324 			u8_get_bits(rate, RTW89_RA_RATE_MASK_NSS_V1) + 1 :
2325 			u8_get_bits(rate, RTW89_RA_RATE_MASK_NSS) + 1;
2326 		if (giltf)
2327 			ra_report->txrate.flags |= RATE_INFO_FLAGS_SHORT_GI;
2328 		mcs = ra_report->txrate.mcs;
2329 		break;
2330 	case RTW89_RA_RPT_MODE_HE:
2331 		ra_report->txrate.flags |= RATE_INFO_FLAGS_HE_MCS;
2332 		ra_report->txrate.mcs = format_v1 ?
2333 			u8_get_bits(rate, RTW89_RA_RATE_MASK_MCS_V1) :
2334 			u8_get_bits(rate, RTW89_RA_RATE_MASK_MCS);
2335 		ra_report->txrate.nss  = format_v1 ?
2336 			u8_get_bits(rate, RTW89_RA_RATE_MASK_NSS_V1) + 1 :
2337 			u8_get_bits(rate, RTW89_RA_RATE_MASK_NSS) + 1;
2338 		if (giltf == RTW89_GILTF_2XHE08 || giltf == RTW89_GILTF_1XHE08)
2339 			ra_report->txrate.he_gi = NL80211_RATE_INFO_HE_GI_0_8;
2340 		else if (giltf == RTW89_GILTF_2XHE16 || giltf == RTW89_GILTF_1XHE16)
2341 			ra_report->txrate.he_gi = NL80211_RATE_INFO_HE_GI_1_6;
2342 		else
2343 			ra_report->txrate.he_gi = NL80211_RATE_INFO_HE_GI_3_2;
2344 		mcs = ra_report->txrate.mcs;
2345 		break;
2346 	}
2347 
2348 	ra_report->txrate.bw = rtw89_hw_to_rate_info_bw(bw);
2349 	ra_report->bit_rate = cfg80211_calculate_bitrate(&ra_report->txrate);
2350 	ra_report->hw_rate = format_v1 ?
2351 			     u16_encode_bits(mode, RTW89_HW_RATE_V1_MASK_MOD) |
2352 			     u16_encode_bits(rate, RTW89_HW_RATE_V1_MASK_VAL) :
2353 			     u16_encode_bits(mode, RTW89_HW_RATE_MASK_MOD) |
2354 			     u16_encode_bits(rate, RTW89_HW_RATE_MASK_VAL);
2355 	ra_report->might_fallback_legacy = mcs <= 2;
2356 	sta->deflink.agg.max_rc_amsdu_len = get_max_amsdu_len(rtwdev, ra_report);
2357 	rtwsta->max_agg_wait = sta->deflink.agg.max_rc_amsdu_len / 1500 - 1;
2358 }
2359 
2360 static void
2361 rtw89_phy_c2h_ra_rpt(struct rtw89_dev *rtwdev, struct sk_buff *c2h, u32 len)
2362 {
2363 	struct rtw89_phy_iter_ra_data ra_data;
2364 
2365 	ra_data.rtwdev = rtwdev;
2366 	ra_data.c2h = c2h;
2367 	ieee80211_iterate_stations_atomic(rtwdev->hw,
2368 					  rtw89_phy_c2h_ra_rpt_iter,
2369 					  &ra_data);
2370 }
2371 
2372 static
2373 void (* const rtw89_phy_c2h_ra_handler[])(struct rtw89_dev *rtwdev,
2374 					  struct sk_buff *c2h, u32 len) = {
2375 	[RTW89_PHY_C2H_FUNC_STS_RPT] = rtw89_phy_c2h_ra_rpt,
2376 	[RTW89_PHY_C2H_FUNC_MU_GPTBL_RPT] = NULL,
2377 	[RTW89_PHY_C2H_FUNC_TXSTS] = NULL,
2378 };
2379 
2380 void rtw89_phy_c2h_handle(struct rtw89_dev *rtwdev, struct sk_buff *skb,
2381 			  u32 len, u8 class, u8 func)
2382 {
2383 	void (*handler)(struct rtw89_dev *rtwdev,
2384 			struct sk_buff *c2h, u32 len) = NULL;
2385 
2386 	switch (class) {
2387 	case RTW89_PHY_C2H_CLASS_RA:
2388 		if (func < RTW89_PHY_C2H_FUNC_RA_MAX)
2389 			handler = rtw89_phy_c2h_ra_handler[func];
2390 		break;
2391 	case RTW89_PHY_C2H_CLASS_DM:
2392 		if (func == RTW89_PHY_C2H_DM_FUNC_LOWRT_RTY)
2393 			return;
2394 		fallthrough;
2395 	default:
2396 		rtw89_info(rtwdev, "c2h class %d not support\n", class);
2397 		return;
2398 	}
2399 	if (!handler) {
2400 		rtw89_info(rtwdev, "c2h class %d func %d not support\n", class,
2401 			   func);
2402 		return;
2403 	}
2404 	handler(rtwdev, skb, len);
2405 }
2406 
2407 static u8 rtw89_phy_cfo_get_xcap_reg(struct rtw89_dev *rtwdev, bool sc_xo)
2408 {
2409 	const struct rtw89_xtal_info *xtal = rtwdev->chip->xtal_info;
2410 	u32 reg_mask;
2411 
2412 	if (sc_xo)
2413 		reg_mask = xtal->sc_xo_mask;
2414 	else
2415 		reg_mask = xtal->sc_xi_mask;
2416 
2417 	return (u8)rtw89_read32_mask(rtwdev, xtal->xcap_reg, reg_mask);
2418 }
2419 
2420 static void rtw89_phy_cfo_set_xcap_reg(struct rtw89_dev *rtwdev, bool sc_xo,
2421 				       u8 val)
2422 {
2423 	const struct rtw89_xtal_info *xtal = rtwdev->chip->xtal_info;
2424 	u32 reg_mask;
2425 
2426 	if (sc_xo)
2427 		reg_mask = xtal->sc_xo_mask;
2428 	else
2429 		reg_mask = xtal->sc_xi_mask;
2430 
2431 	rtw89_write32_mask(rtwdev, xtal->xcap_reg, reg_mask, val);
2432 }
2433 
2434 static void rtw89_phy_cfo_set_crystal_cap(struct rtw89_dev *rtwdev,
2435 					  u8 crystal_cap, bool force)
2436 {
2437 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2438 	const struct rtw89_chip_info *chip = rtwdev->chip;
2439 	u8 sc_xi_val, sc_xo_val;
2440 
2441 	if (!force && cfo->crystal_cap == crystal_cap)
2442 		return;
2443 	crystal_cap = clamp_t(u8, crystal_cap, 0, 127);
2444 	if (chip->chip_id == RTL8852A || chip->chip_id == RTL8851B) {
2445 		rtw89_phy_cfo_set_xcap_reg(rtwdev, true, crystal_cap);
2446 		rtw89_phy_cfo_set_xcap_reg(rtwdev, false, crystal_cap);
2447 		sc_xo_val = rtw89_phy_cfo_get_xcap_reg(rtwdev, true);
2448 		sc_xi_val = rtw89_phy_cfo_get_xcap_reg(rtwdev, false);
2449 	} else {
2450 		rtw89_mac_write_xtal_si(rtwdev, XTAL_SI_XTAL_SC_XO,
2451 					crystal_cap, XTAL_SC_XO_MASK);
2452 		rtw89_mac_write_xtal_si(rtwdev, XTAL_SI_XTAL_SC_XI,
2453 					crystal_cap, XTAL_SC_XI_MASK);
2454 		rtw89_mac_read_xtal_si(rtwdev, XTAL_SI_XTAL_SC_XO, &sc_xo_val);
2455 		rtw89_mac_read_xtal_si(rtwdev, XTAL_SI_XTAL_SC_XI, &sc_xi_val);
2456 	}
2457 	cfo->crystal_cap = sc_xi_val;
2458 	cfo->x_cap_ofst = (s8)((int)cfo->crystal_cap - cfo->def_x_cap);
2459 
2460 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Set sc_xi=0x%x\n", sc_xi_val);
2461 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Set sc_xo=0x%x\n", sc_xo_val);
2462 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Get xcap_ofst=%d\n",
2463 		    cfo->x_cap_ofst);
2464 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Set xcap OK\n");
2465 }
2466 
2467 static void rtw89_phy_cfo_reset(struct rtw89_dev *rtwdev)
2468 {
2469 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2470 	u8 cap;
2471 
2472 	cfo->def_x_cap = cfo->crystal_cap_default & B_AX_XTAL_SC_MASK;
2473 	cfo->is_adjust = false;
2474 	if (cfo->crystal_cap == cfo->def_x_cap)
2475 		return;
2476 	cap = cfo->crystal_cap;
2477 	cap += (cap > cfo->def_x_cap ? -1 : 1);
2478 	rtw89_phy_cfo_set_crystal_cap(rtwdev, cap, false);
2479 	rtw89_debug(rtwdev, RTW89_DBG_CFO,
2480 		    "(0x%x) approach to dflt_val=(0x%x)\n", cfo->crystal_cap,
2481 		    cfo->def_x_cap);
2482 }
2483 
2484 static void rtw89_dcfo_comp(struct rtw89_dev *rtwdev, s32 curr_cfo)
2485 {
2486 	const struct rtw89_reg_def *dcfo_comp = rtwdev->chip->dcfo_comp;
2487 	bool is_linked = rtwdev->total_sta_assoc > 0;
2488 	s32 cfo_avg_312;
2489 	s32 dcfo_comp_val;
2490 	int sign;
2491 
2492 	if (!is_linked) {
2493 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "DCFO: is_linked=%d\n",
2494 			    is_linked);
2495 		return;
2496 	}
2497 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "DCFO: curr_cfo=%d\n", curr_cfo);
2498 	if (curr_cfo == 0)
2499 		return;
2500 	dcfo_comp_val = rtw89_phy_read32_mask(rtwdev, R_DCFO, B_DCFO);
2501 	sign = curr_cfo > 0 ? 1 : -1;
2502 	cfo_avg_312 = curr_cfo / 625 + sign * dcfo_comp_val;
2503 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "avg_cfo_312=%d step\n", cfo_avg_312);
2504 	if (rtwdev->chip->chip_id == RTL8852A && rtwdev->hal.cv == CHIP_CBV)
2505 		cfo_avg_312 = -cfo_avg_312;
2506 	rtw89_phy_set_phy_regs(rtwdev, dcfo_comp->addr, dcfo_comp->mask,
2507 			       cfo_avg_312);
2508 }
2509 
2510 static void rtw89_dcfo_comp_init(struct rtw89_dev *rtwdev)
2511 {
2512 	const struct rtw89_chip_info *chip = rtwdev->chip;
2513 
2514 	rtw89_phy_set_phy_regs(rtwdev, R_DCFO_OPT, B_DCFO_OPT_EN, 1);
2515 	rtw89_phy_set_phy_regs(rtwdev, R_DCFO_WEIGHT, B_DCFO_WEIGHT_MSK, 8);
2516 
2517 	if (chip->cfo_hw_comp)
2518 		rtw89_write32_mask(rtwdev, R_AX_PWR_UL_CTRL2,
2519 				   B_AX_PWR_UL_CFO_MASK, 0x6);
2520 	else
2521 		rtw89_write32_clr(rtwdev, R_AX_PWR_UL_CTRL2, B_AX_PWR_UL_CFO_MASK);
2522 }
2523 
2524 static void rtw89_phy_cfo_init(struct rtw89_dev *rtwdev)
2525 {
2526 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2527 	struct rtw89_efuse *efuse = &rtwdev->efuse;
2528 
2529 	cfo->crystal_cap_default = efuse->xtal_cap & B_AX_XTAL_SC_MASK;
2530 	cfo->crystal_cap = cfo->crystal_cap_default;
2531 	cfo->def_x_cap = cfo->crystal_cap;
2532 	cfo->x_cap_ub = min_t(int, cfo->def_x_cap + CFO_BOUND, 0x7f);
2533 	cfo->x_cap_lb = max_t(int, cfo->def_x_cap - CFO_BOUND, 0x1);
2534 	cfo->is_adjust = false;
2535 	cfo->divergence_lock_en = false;
2536 	cfo->x_cap_ofst = 0;
2537 	cfo->lock_cnt = 0;
2538 	cfo->rtw89_multi_cfo_mode = RTW89_TP_BASED_AVG_MODE;
2539 	cfo->apply_compensation = false;
2540 	cfo->residual_cfo_acc = 0;
2541 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Default xcap=%0x\n",
2542 		    cfo->crystal_cap_default);
2543 	rtw89_phy_cfo_set_crystal_cap(rtwdev, cfo->crystal_cap_default, true);
2544 	rtw89_phy_set_phy_regs(rtwdev, R_DCFO, B_DCFO, 1);
2545 	rtw89_dcfo_comp_init(rtwdev);
2546 	cfo->cfo_timer_ms = 2000;
2547 	cfo->cfo_trig_by_timer_en = false;
2548 	cfo->phy_cfo_trk_cnt = 0;
2549 	cfo->phy_cfo_status = RTW89_PHY_DCFO_STATE_NORMAL;
2550 	cfo->cfo_ul_ofdma_acc_mode = RTW89_CFO_UL_OFDMA_ACC_ENABLE;
2551 }
2552 
2553 static void rtw89_phy_cfo_crystal_cap_adjust(struct rtw89_dev *rtwdev,
2554 					     s32 curr_cfo)
2555 {
2556 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2557 	s8 crystal_cap = cfo->crystal_cap;
2558 	s32 cfo_abs = abs(curr_cfo);
2559 	int sign;
2560 
2561 	if (!cfo->is_adjust) {
2562 		if (cfo_abs > CFO_TRK_ENABLE_TH)
2563 			cfo->is_adjust = true;
2564 	} else {
2565 		if (cfo_abs < CFO_TRK_STOP_TH)
2566 			cfo->is_adjust = false;
2567 	}
2568 	if (!cfo->is_adjust) {
2569 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "Stop CFO tracking\n");
2570 		return;
2571 	}
2572 	sign = curr_cfo > 0 ? 1 : -1;
2573 	if (cfo_abs > CFO_TRK_STOP_TH_4)
2574 		crystal_cap += 7 * sign;
2575 	else if (cfo_abs > CFO_TRK_STOP_TH_3)
2576 		crystal_cap += 5 * sign;
2577 	else if (cfo_abs > CFO_TRK_STOP_TH_2)
2578 		crystal_cap += 3 * sign;
2579 	else if (cfo_abs > CFO_TRK_STOP_TH_1)
2580 		crystal_cap += 1 * sign;
2581 	else
2582 		return;
2583 	rtw89_phy_cfo_set_crystal_cap(rtwdev, (u8)crystal_cap, false);
2584 	rtw89_debug(rtwdev, RTW89_DBG_CFO,
2585 		    "X_cap{Curr,Default}={0x%x,0x%x}\n",
2586 		    cfo->crystal_cap, cfo->def_x_cap);
2587 }
2588 
2589 static s32 rtw89_phy_average_cfo_calc(struct rtw89_dev *rtwdev)
2590 {
2591 	const struct rtw89_chip_info *chip = rtwdev->chip;
2592 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2593 	s32 cfo_khz_all = 0;
2594 	s32 cfo_cnt_all = 0;
2595 	s32 cfo_all_avg = 0;
2596 	u8 i;
2597 
2598 	if (rtwdev->total_sta_assoc != 1)
2599 		return 0;
2600 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "one_entry_only\n");
2601 	for (i = 0; i < CFO_TRACK_MAX_USER; i++) {
2602 		if (cfo->cfo_cnt[i] == 0)
2603 			continue;
2604 		cfo_khz_all += cfo->cfo_tail[i];
2605 		cfo_cnt_all += cfo->cfo_cnt[i];
2606 		cfo_all_avg = phy_div(cfo_khz_all, cfo_cnt_all);
2607 		cfo->pre_cfo_avg[i] = cfo->cfo_avg[i];
2608 		cfo->dcfo_avg = phy_div(cfo_khz_all << chip->dcfo_comp_sft,
2609 					cfo_cnt_all);
2610 	}
2611 	rtw89_debug(rtwdev, RTW89_DBG_CFO,
2612 		    "CFO track for macid = %d\n", i);
2613 	rtw89_debug(rtwdev, RTW89_DBG_CFO,
2614 		    "Total cfo=%dK, pkt_cnt=%d, avg_cfo=%dK\n",
2615 		    cfo_khz_all, cfo_cnt_all, cfo_all_avg);
2616 	return cfo_all_avg;
2617 }
2618 
2619 static s32 rtw89_phy_multi_sta_cfo_calc(struct rtw89_dev *rtwdev)
2620 {
2621 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2622 	struct rtw89_traffic_stats *stats = &rtwdev->stats;
2623 	s32 target_cfo = 0;
2624 	s32 cfo_khz_all = 0;
2625 	s32 cfo_khz_all_tp_wgt = 0;
2626 	s32 cfo_avg = 0;
2627 	s32 max_cfo_lb = BIT(31);
2628 	s32 min_cfo_ub = GENMASK(30, 0);
2629 	u16 cfo_cnt_all = 0;
2630 	u8 active_entry_cnt = 0;
2631 	u8 sta_cnt = 0;
2632 	u32 tp_all = 0;
2633 	u8 i;
2634 	u8 cfo_tol = 0;
2635 
2636 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Multi entry cfo_trk\n");
2637 	if (cfo->rtw89_multi_cfo_mode == RTW89_PKT_BASED_AVG_MODE) {
2638 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "Pkt based avg mode\n");
2639 		for (i = 0; i < CFO_TRACK_MAX_USER; i++) {
2640 			if (cfo->cfo_cnt[i] == 0)
2641 				continue;
2642 			cfo_khz_all += cfo->cfo_tail[i];
2643 			cfo_cnt_all += cfo->cfo_cnt[i];
2644 			cfo_avg = phy_div(cfo_khz_all, (s32)cfo_cnt_all);
2645 			rtw89_debug(rtwdev, RTW89_DBG_CFO,
2646 				    "Msta cfo=%d, pkt_cnt=%d, avg_cfo=%d\n",
2647 				    cfo_khz_all, cfo_cnt_all, cfo_avg);
2648 			target_cfo = cfo_avg;
2649 		}
2650 	} else if (cfo->rtw89_multi_cfo_mode == RTW89_ENTRY_BASED_AVG_MODE) {
2651 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "Entry based avg mode\n");
2652 		for (i = 0; i < CFO_TRACK_MAX_USER; i++) {
2653 			if (cfo->cfo_cnt[i] == 0)
2654 				continue;
2655 			cfo->cfo_avg[i] = phy_div(cfo->cfo_tail[i],
2656 						  (s32)cfo->cfo_cnt[i]);
2657 			cfo_khz_all += cfo->cfo_avg[i];
2658 			rtw89_debug(rtwdev, RTW89_DBG_CFO,
2659 				    "Macid=%d, cfo_avg=%d\n", i,
2660 				    cfo->cfo_avg[i]);
2661 		}
2662 		sta_cnt = rtwdev->total_sta_assoc;
2663 		cfo_avg = phy_div(cfo_khz_all, (s32)sta_cnt);
2664 		rtw89_debug(rtwdev, RTW89_DBG_CFO,
2665 			    "Msta cfo_acc=%d, ent_cnt=%d, avg_cfo=%d\n",
2666 			    cfo_khz_all, sta_cnt, cfo_avg);
2667 		target_cfo = cfo_avg;
2668 	} else if (cfo->rtw89_multi_cfo_mode == RTW89_TP_BASED_AVG_MODE) {
2669 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "TP based avg mode\n");
2670 		cfo_tol = cfo->sta_cfo_tolerance;
2671 		for (i = 0; i < CFO_TRACK_MAX_USER; i++) {
2672 			sta_cnt++;
2673 			if (cfo->cfo_cnt[i] != 0) {
2674 				cfo->cfo_avg[i] = phy_div(cfo->cfo_tail[i],
2675 							  (s32)cfo->cfo_cnt[i]);
2676 				active_entry_cnt++;
2677 			} else {
2678 				cfo->cfo_avg[i] = cfo->pre_cfo_avg[i];
2679 			}
2680 			max_cfo_lb = max(cfo->cfo_avg[i] - cfo_tol, max_cfo_lb);
2681 			min_cfo_ub = min(cfo->cfo_avg[i] + cfo_tol, min_cfo_ub);
2682 			cfo_khz_all += cfo->cfo_avg[i];
2683 			/* need tp for each entry */
2684 			rtw89_debug(rtwdev, RTW89_DBG_CFO,
2685 				    "[%d] cfo_avg=%d, tp=tbd\n",
2686 				    i, cfo->cfo_avg[i]);
2687 			if (sta_cnt >= rtwdev->total_sta_assoc)
2688 				break;
2689 		}
2690 		tp_all = stats->rx_throughput; /* need tp for each entry */
2691 		cfo_avg =  phy_div(cfo_khz_all_tp_wgt, (s32)tp_all);
2692 
2693 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "Assoc sta cnt=%d\n",
2694 			    sta_cnt);
2695 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "Active sta cnt=%d\n",
2696 			    active_entry_cnt);
2697 		rtw89_debug(rtwdev, RTW89_DBG_CFO,
2698 			    "Msta cfo with tp_wgt=%d, avg_cfo=%d\n",
2699 			    cfo_khz_all_tp_wgt, cfo_avg);
2700 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "cfo_lb=%d,cfo_ub=%d\n",
2701 			    max_cfo_lb, min_cfo_ub);
2702 		if (max_cfo_lb <= min_cfo_ub) {
2703 			rtw89_debug(rtwdev, RTW89_DBG_CFO,
2704 				    "cfo win_size=%d\n",
2705 				    min_cfo_ub - max_cfo_lb);
2706 			target_cfo = clamp(cfo_avg, max_cfo_lb, min_cfo_ub);
2707 		} else {
2708 			rtw89_debug(rtwdev, RTW89_DBG_CFO,
2709 				    "No intersection of cfo tolerance windows\n");
2710 			target_cfo = phy_div(cfo_khz_all, (s32)sta_cnt);
2711 		}
2712 		for (i = 0; i < CFO_TRACK_MAX_USER; i++)
2713 			cfo->pre_cfo_avg[i] = cfo->cfo_avg[i];
2714 	}
2715 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Target cfo=%d\n", target_cfo);
2716 	return target_cfo;
2717 }
2718 
2719 static void rtw89_phy_cfo_statistics_reset(struct rtw89_dev *rtwdev)
2720 {
2721 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2722 
2723 	memset(&cfo->cfo_tail, 0, sizeof(cfo->cfo_tail));
2724 	memset(&cfo->cfo_cnt, 0, sizeof(cfo->cfo_cnt));
2725 	cfo->packet_count = 0;
2726 	cfo->packet_count_pre = 0;
2727 	cfo->cfo_avg_pre = 0;
2728 }
2729 
2730 static void rtw89_phy_cfo_dm(struct rtw89_dev *rtwdev)
2731 {
2732 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2733 	s32 new_cfo = 0;
2734 	bool x_cap_update = false;
2735 	u8 pre_x_cap = cfo->crystal_cap;
2736 	u8 dcfo_comp_sft = rtwdev->chip->dcfo_comp_sft;
2737 
2738 	cfo->dcfo_avg = 0;
2739 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "CFO:total_sta_assoc=%d\n",
2740 		    rtwdev->total_sta_assoc);
2741 	if (rtwdev->total_sta_assoc == 0) {
2742 		rtw89_phy_cfo_reset(rtwdev);
2743 		return;
2744 	}
2745 	if (cfo->packet_count == 0) {
2746 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "Pkt cnt = 0\n");
2747 		return;
2748 	}
2749 	if (cfo->packet_count == cfo->packet_count_pre) {
2750 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "Pkt cnt doesn't change\n");
2751 		return;
2752 	}
2753 	if (rtwdev->total_sta_assoc == 1)
2754 		new_cfo = rtw89_phy_average_cfo_calc(rtwdev);
2755 	else
2756 		new_cfo = rtw89_phy_multi_sta_cfo_calc(rtwdev);
2757 	if (new_cfo == 0) {
2758 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "curr_cfo=0\n");
2759 		return;
2760 	}
2761 	if (cfo->divergence_lock_en) {
2762 		cfo->lock_cnt++;
2763 		if (cfo->lock_cnt > CFO_PERIOD_CNT) {
2764 			cfo->divergence_lock_en = false;
2765 			cfo->lock_cnt = 0;
2766 		} else {
2767 			rtw89_phy_cfo_reset(rtwdev);
2768 		}
2769 		return;
2770 	}
2771 	if (cfo->crystal_cap >= cfo->x_cap_ub ||
2772 	    cfo->crystal_cap <= cfo->x_cap_lb) {
2773 		cfo->divergence_lock_en = true;
2774 		rtw89_phy_cfo_reset(rtwdev);
2775 		return;
2776 	}
2777 
2778 	rtw89_phy_cfo_crystal_cap_adjust(rtwdev, new_cfo);
2779 	cfo->cfo_avg_pre = new_cfo;
2780 	cfo->dcfo_avg_pre = cfo->dcfo_avg;
2781 	x_cap_update =  cfo->crystal_cap != pre_x_cap;
2782 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Xcap_up=%d\n", x_cap_update);
2783 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Xcap: D:%x C:%x->%x, ofst=%d\n",
2784 		    cfo->def_x_cap, pre_x_cap, cfo->crystal_cap,
2785 		    cfo->x_cap_ofst);
2786 	if (x_cap_update) {
2787 		if (cfo->dcfo_avg > 0)
2788 			cfo->dcfo_avg -= CFO_SW_COMP_FINE_TUNE << dcfo_comp_sft;
2789 		else
2790 			cfo->dcfo_avg += CFO_SW_COMP_FINE_TUNE << dcfo_comp_sft;
2791 	}
2792 	rtw89_dcfo_comp(rtwdev, cfo->dcfo_avg);
2793 	rtw89_phy_cfo_statistics_reset(rtwdev);
2794 }
2795 
2796 void rtw89_phy_cfo_track_work(struct work_struct *work)
2797 {
2798 	struct rtw89_dev *rtwdev = container_of(work, struct rtw89_dev,
2799 						cfo_track_work.work);
2800 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2801 
2802 	mutex_lock(&rtwdev->mutex);
2803 	if (!cfo->cfo_trig_by_timer_en)
2804 		goto out;
2805 	rtw89_leave_ps_mode(rtwdev);
2806 	rtw89_phy_cfo_dm(rtwdev);
2807 	ieee80211_queue_delayed_work(rtwdev->hw, &rtwdev->cfo_track_work,
2808 				     msecs_to_jiffies(cfo->cfo_timer_ms));
2809 out:
2810 	mutex_unlock(&rtwdev->mutex);
2811 }
2812 
2813 static void rtw89_phy_cfo_start_work(struct rtw89_dev *rtwdev)
2814 {
2815 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2816 
2817 	ieee80211_queue_delayed_work(rtwdev->hw, &rtwdev->cfo_track_work,
2818 				     msecs_to_jiffies(cfo->cfo_timer_ms));
2819 }
2820 
2821 void rtw89_phy_cfo_track(struct rtw89_dev *rtwdev)
2822 {
2823 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2824 	struct rtw89_traffic_stats *stats = &rtwdev->stats;
2825 	bool is_ul_ofdma = false, ofdma_acc_en = false;
2826 
2827 	if (stats->rx_tf_periodic > CFO_TF_CNT_TH)
2828 		is_ul_ofdma = true;
2829 	if (cfo->cfo_ul_ofdma_acc_mode == RTW89_CFO_UL_OFDMA_ACC_ENABLE &&
2830 	    is_ul_ofdma)
2831 		ofdma_acc_en = true;
2832 
2833 	switch (cfo->phy_cfo_status) {
2834 	case RTW89_PHY_DCFO_STATE_NORMAL:
2835 		if (stats->tx_throughput >= CFO_TP_UPPER) {
2836 			cfo->phy_cfo_status = RTW89_PHY_DCFO_STATE_ENHANCE;
2837 			cfo->cfo_trig_by_timer_en = true;
2838 			cfo->cfo_timer_ms = CFO_COMP_PERIOD;
2839 			rtw89_phy_cfo_start_work(rtwdev);
2840 		}
2841 		break;
2842 	case RTW89_PHY_DCFO_STATE_ENHANCE:
2843 		if (stats->tx_throughput <= CFO_TP_LOWER)
2844 			cfo->phy_cfo_status = RTW89_PHY_DCFO_STATE_NORMAL;
2845 		else if (ofdma_acc_en &&
2846 			 cfo->phy_cfo_trk_cnt >= CFO_PERIOD_CNT)
2847 			cfo->phy_cfo_status = RTW89_PHY_DCFO_STATE_HOLD;
2848 		else
2849 			cfo->phy_cfo_trk_cnt++;
2850 
2851 		if (cfo->phy_cfo_status == RTW89_PHY_DCFO_STATE_NORMAL) {
2852 			cfo->phy_cfo_trk_cnt = 0;
2853 			cfo->cfo_trig_by_timer_en = false;
2854 		}
2855 		break;
2856 	case RTW89_PHY_DCFO_STATE_HOLD:
2857 		if (stats->tx_throughput <= CFO_TP_LOWER) {
2858 			cfo->phy_cfo_status = RTW89_PHY_DCFO_STATE_NORMAL;
2859 			cfo->phy_cfo_trk_cnt = 0;
2860 			cfo->cfo_trig_by_timer_en = false;
2861 		} else {
2862 			cfo->phy_cfo_trk_cnt++;
2863 		}
2864 		break;
2865 	default:
2866 		cfo->phy_cfo_status = RTW89_PHY_DCFO_STATE_NORMAL;
2867 		cfo->phy_cfo_trk_cnt = 0;
2868 		break;
2869 	}
2870 	rtw89_debug(rtwdev, RTW89_DBG_CFO,
2871 		    "[CFO]WatchDog tp=%d,state=%d,timer_en=%d,trk_cnt=%d,thermal=%ld\n",
2872 		    stats->tx_throughput, cfo->phy_cfo_status,
2873 		    cfo->cfo_trig_by_timer_en, cfo->phy_cfo_trk_cnt,
2874 		    ewma_thermal_read(&rtwdev->phystat.avg_thermal[0]));
2875 	if (cfo->cfo_trig_by_timer_en)
2876 		return;
2877 	rtw89_phy_cfo_dm(rtwdev);
2878 }
2879 
2880 void rtw89_phy_cfo_parse(struct rtw89_dev *rtwdev, s16 cfo_val,
2881 			 struct rtw89_rx_phy_ppdu *phy_ppdu)
2882 {
2883 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2884 	u8 macid = phy_ppdu->mac_id;
2885 
2886 	if (macid >= CFO_TRACK_MAX_USER) {
2887 		rtw89_warn(rtwdev, "mac_id %d is out of range\n", macid);
2888 		return;
2889 	}
2890 
2891 	cfo->cfo_tail[macid] += cfo_val;
2892 	cfo->cfo_cnt[macid]++;
2893 	cfo->packet_count++;
2894 }
2895 
2896 void rtw89_phy_ul_tb_assoc(struct rtw89_dev *rtwdev, struct rtw89_vif *rtwvif)
2897 {
2898 	const struct rtw89_chip_info *chip = rtwdev->chip;
2899 	const struct rtw89_chan *chan = rtw89_chan_get(rtwdev, RTW89_SUB_ENTITY_0);
2900 	struct rtw89_phy_ul_tb_info *ul_tb_info = &rtwdev->ul_tb_info;
2901 
2902 	if (!chip->support_ul_tb_ctrl)
2903 		return;
2904 
2905 	rtwvif->def_tri_idx =
2906 		rtw89_phy_read32_mask(rtwdev, R_DCFO_OPT, B_TXSHAPE_TRIANGULAR_CFG);
2907 
2908 	if (chip->chip_id == RTL8852B && rtwdev->hal.cv > CHIP_CBV)
2909 		rtwvif->dyn_tb_bedge_en = false;
2910 	else if (chan->band_type >= RTW89_BAND_5G &&
2911 		 chan->band_width >= RTW89_CHANNEL_WIDTH_40)
2912 		rtwvif->dyn_tb_bedge_en = true;
2913 	else
2914 		rtwvif->dyn_tb_bedge_en = false;
2915 
2916 	rtw89_debug(rtwdev, RTW89_DBG_UL_TB,
2917 		    "[ULTB] def_if_bandedge=%d, def_tri_idx=%d\n",
2918 		    ul_tb_info->def_if_bandedge, rtwvif->def_tri_idx);
2919 	rtw89_debug(rtwdev, RTW89_DBG_UL_TB,
2920 		    "[ULTB] dyn_tb_begde_en=%d, dyn_tb_tri_en=%d\n",
2921 		    rtwvif->dyn_tb_bedge_en, ul_tb_info->dyn_tb_tri_en);
2922 }
2923 
2924 struct rtw89_phy_ul_tb_check_data {
2925 	bool valid;
2926 	bool high_tf_client;
2927 	bool low_tf_client;
2928 	bool dyn_tb_bedge_en;
2929 	u8 def_tri_idx;
2930 };
2931 
2932 static
2933 void rtw89_phy_ul_tb_ctrl_check(struct rtw89_dev *rtwdev,
2934 				struct rtw89_vif *rtwvif,
2935 				struct rtw89_phy_ul_tb_check_data *ul_tb_data)
2936 {
2937 	struct rtw89_traffic_stats *stats = &rtwdev->stats;
2938 	struct ieee80211_vif *vif = rtwvif_to_vif(rtwvif);
2939 
2940 	if (rtwvif->wifi_role != RTW89_WIFI_ROLE_STATION)
2941 		return;
2942 
2943 	if (!vif->cfg.assoc)
2944 		return;
2945 
2946 	if (stats->rx_tf_periodic > UL_TB_TF_CNT_L2H_TH)
2947 		ul_tb_data->high_tf_client = true;
2948 	else if (stats->rx_tf_periodic < UL_TB_TF_CNT_H2L_TH)
2949 		ul_tb_data->low_tf_client = true;
2950 
2951 	ul_tb_data->valid = true;
2952 	ul_tb_data->def_tri_idx = rtwvif->def_tri_idx;
2953 	ul_tb_data->dyn_tb_bedge_en = rtwvif->dyn_tb_bedge_en;
2954 }
2955 
2956 void rtw89_phy_ul_tb_ctrl_track(struct rtw89_dev *rtwdev)
2957 {
2958 	const struct rtw89_chip_info *chip = rtwdev->chip;
2959 	struct rtw89_phy_ul_tb_info *ul_tb_info = &rtwdev->ul_tb_info;
2960 	struct rtw89_phy_ul_tb_check_data ul_tb_data = {};
2961 	struct rtw89_vif *rtwvif;
2962 
2963 	if (!chip->support_ul_tb_ctrl)
2964 		return;
2965 
2966 	if (rtwdev->total_sta_assoc != 1)
2967 		return;
2968 
2969 	rtw89_for_each_rtwvif(rtwdev, rtwvif)
2970 		rtw89_phy_ul_tb_ctrl_check(rtwdev, rtwvif, &ul_tb_data);
2971 
2972 	if (!ul_tb_data.valid)
2973 		return;
2974 
2975 	if (ul_tb_data.dyn_tb_bedge_en) {
2976 		if (ul_tb_data.high_tf_client) {
2977 			rtw89_phy_write32_mask(rtwdev, R_BANDEDGE, B_BANDEDGE_EN, 0);
2978 			rtw89_debug(rtwdev, RTW89_DBG_UL_TB,
2979 				    "[ULTB] Turn off if_bandedge\n");
2980 		} else if (ul_tb_data.low_tf_client) {
2981 			rtw89_phy_write32_mask(rtwdev, R_BANDEDGE, B_BANDEDGE_EN,
2982 					       ul_tb_info->def_if_bandedge);
2983 			rtw89_debug(rtwdev, RTW89_DBG_UL_TB,
2984 				    "[ULTB] Set to default if_bandedge = %d\n",
2985 				    ul_tb_info->def_if_bandedge);
2986 		}
2987 	}
2988 
2989 	if (ul_tb_info->dyn_tb_tri_en) {
2990 		if (ul_tb_data.high_tf_client) {
2991 			rtw89_phy_write32_mask(rtwdev, R_DCFO_OPT,
2992 					       B_TXSHAPE_TRIANGULAR_CFG, 0);
2993 			rtw89_debug(rtwdev, RTW89_DBG_UL_TB,
2994 				    "[ULTB] Turn off Tx triangle\n");
2995 		} else if (ul_tb_data.low_tf_client) {
2996 			rtw89_phy_write32_mask(rtwdev, R_DCFO_OPT,
2997 					       B_TXSHAPE_TRIANGULAR_CFG,
2998 					       ul_tb_data.def_tri_idx);
2999 			rtw89_debug(rtwdev, RTW89_DBG_UL_TB,
3000 				    "[ULTB] Set to default tx_shap_idx = %d\n",
3001 				    ul_tb_data.def_tri_idx);
3002 		}
3003 	}
3004 }
3005 
3006 static void rtw89_phy_ul_tb_info_init(struct rtw89_dev *rtwdev)
3007 {
3008 	const struct rtw89_chip_info *chip = rtwdev->chip;
3009 	struct rtw89_phy_ul_tb_info *ul_tb_info = &rtwdev->ul_tb_info;
3010 
3011 	if (!chip->support_ul_tb_ctrl)
3012 		return;
3013 
3014 	ul_tb_info->dyn_tb_tri_en = true;
3015 	ul_tb_info->def_if_bandedge =
3016 		rtw89_phy_read32_mask(rtwdev, R_BANDEDGE, B_BANDEDGE_EN);
3017 }
3018 
3019 static
3020 void rtw89_phy_antdiv_sts_instance_reset(struct rtw89_antdiv_stats *antdiv_sts)
3021 {
3022 	ewma_rssi_init(&antdiv_sts->cck_rssi_avg);
3023 	ewma_rssi_init(&antdiv_sts->ofdm_rssi_avg);
3024 	ewma_rssi_init(&antdiv_sts->non_legacy_rssi_avg);
3025 	antdiv_sts->pkt_cnt_cck = 0;
3026 	antdiv_sts->pkt_cnt_ofdm = 0;
3027 	antdiv_sts->pkt_cnt_non_legacy = 0;
3028 	antdiv_sts->evm = 0;
3029 }
3030 
3031 static void rtw89_phy_antdiv_sts_instance_add(struct rtw89_dev *rtwdev,
3032 					      struct rtw89_rx_phy_ppdu *phy_ppdu,
3033 					      struct rtw89_antdiv_stats *stats)
3034 {
3035 	if (rtw89_get_data_rate_mode(rtwdev, phy_ppdu->rate) == DATA_RATE_MODE_NON_HT) {
3036 		if (phy_ppdu->rate < RTW89_HW_RATE_OFDM6) {
3037 			ewma_rssi_add(&stats->cck_rssi_avg, phy_ppdu->rssi_avg);
3038 			stats->pkt_cnt_cck++;
3039 		} else {
3040 			ewma_rssi_add(&stats->ofdm_rssi_avg, phy_ppdu->rssi_avg);
3041 			stats->pkt_cnt_ofdm++;
3042 			stats->evm += phy_ppdu->ofdm.evm_min;
3043 		}
3044 	} else {
3045 		ewma_rssi_add(&stats->non_legacy_rssi_avg, phy_ppdu->rssi_avg);
3046 		stats->pkt_cnt_non_legacy++;
3047 		stats->evm += phy_ppdu->ofdm.evm_min;
3048 	}
3049 }
3050 
3051 static u8 rtw89_phy_antdiv_sts_instance_get_rssi(struct rtw89_antdiv_stats *stats)
3052 {
3053 	if (stats->pkt_cnt_non_legacy >= stats->pkt_cnt_cck &&
3054 	    stats->pkt_cnt_non_legacy >= stats->pkt_cnt_ofdm)
3055 		return ewma_rssi_read(&stats->non_legacy_rssi_avg);
3056 	else if (stats->pkt_cnt_ofdm >= stats->pkt_cnt_cck &&
3057 		 stats->pkt_cnt_ofdm >= stats->pkt_cnt_non_legacy)
3058 		return ewma_rssi_read(&stats->ofdm_rssi_avg);
3059 	else
3060 		return ewma_rssi_read(&stats->cck_rssi_avg);
3061 }
3062 
3063 static u8 rtw89_phy_antdiv_sts_instance_get_evm(struct rtw89_antdiv_stats *stats)
3064 {
3065 	return phy_div(stats->evm, stats->pkt_cnt_non_legacy + stats->pkt_cnt_ofdm);
3066 }
3067 
3068 void rtw89_phy_antdiv_parse(struct rtw89_dev *rtwdev,
3069 			    struct rtw89_rx_phy_ppdu *phy_ppdu)
3070 {
3071 	struct rtw89_antdiv_info *antdiv = &rtwdev->antdiv;
3072 	struct rtw89_hal *hal = &rtwdev->hal;
3073 
3074 	if (!hal->ant_diversity || hal->ant_diversity_fixed)
3075 		return;
3076 
3077 	rtw89_phy_antdiv_sts_instance_add(rtwdev, phy_ppdu, &antdiv->target_stats);
3078 
3079 	if (!antdiv->get_stats)
3080 		return;
3081 
3082 	if (hal->antenna_rx == RF_A)
3083 		rtw89_phy_antdiv_sts_instance_add(rtwdev, phy_ppdu, &antdiv->main_stats);
3084 	else if (hal->antenna_rx == RF_B)
3085 		rtw89_phy_antdiv_sts_instance_add(rtwdev, phy_ppdu, &antdiv->aux_stats);
3086 }
3087 
3088 static void rtw89_phy_antdiv_reg_init(struct rtw89_dev *rtwdev)
3089 {
3090 	rtw89_phy_write32_idx(rtwdev, R_P0_TRSW, B_P0_ANT_TRAIN_EN,
3091 			      0x0, RTW89_PHY_0);
3092 	rtw89_phy_write32_idx(rtwdev, R_P0_TRSW, B_P0_TX_ANT_SEL,
3093 			      0x0, RTW89_PHY_0);
3094 
3095 	rtw89_phy_write32_idx(rtwdev, R_P0_ANT_SW, B_P0_TRSW_TX_EXTEND,
3096 			      0x0, RTW89_PHY_0);
3097 	rtw89_phy_write32_idx(rtwdev, R_P0_ANT_SW, B_P0_HW_ANTSW_DIS_BY_GNT_BT,
3098 			      0x0, RTW89_PHY_0);
3099 
3100 	rtw89_phy_write32_idx(rtwdev, R_P0_TRSW, B_P0_BT_FORCE_ANTIDX_EN,
3101 			      0x0, RTW89_PHY_0);
3102 
3103 	rtw89_phy_write32_idx(rtwdev, R_RFSW_CTRL_ANT0_BASE, B_RFSW_CTRL_ANT_MAPPING,
3104 			      0x0100, RTW89_PHY_0);
3105 
3106 	rtw89_phy_write32_idx(rtwdev, R_P0_ANTSEL, B_P0_ANTSEL_BTG_TRX,
3107 			      0x1, RTW89_PHY_0);
3108 	rtw89_phy_write32_idx(rtwdev, R_P0_ANTSEL, B_P0_ANTSEL_HW_CTRL,
3109 			      0x0, RTW89_PHY_0);
3110 	rtw89_phy_write32_idx(rtwdev, R_P0_ANTSEL, B_P0_ANTSEL_SW_2G,
3111 			      0x0, RTW89_PHY_0);
3112 	rtw89_phy_write32_idx(rtwdev, R_P0_ANTSEL, B_P0_ANTSEL_SW_5G,
3113 			      0x0, RTW89_PHY_0);
3114 }
3115 
3116 static void rtw89_phy_antdiv_sts_reset(struct rtw89_dev *rtwdev)
3117 {
3118 	struct rtw89_antdiv_info *antdiv = &rtwdev->antdiv;
3119 
3120 	rtw89_phy_antdiv_sts_instance_reset(&antdiv->target_stats);
3121 	rtw89_phy_antdiv_sts_instance_reset(&antdiv->main_stats);
3122 	rtw89_phy_antdiv_sts_instance_reset(&antdiv->aux_stats);
3123 }
3124 
3125 static void rtw89_phy_antdiv_init(struct rtw89_dev *rtwdev)
3126 {
3127 	struct rtw89_antdiv_info *antdiv = &rtwdev->antdiv;
3128 	struct rtw89_hal *hal = &rtwdev->hal;
3129 
3130 	if (!hal->ant_diversity)
3131 		return;
3132 
3133 	antdiv->get_stats = false;
3134 	antdiv->rssi_pre = 0;
3135 	rtw89_phy_antdiv_sts_reset(rtwdev);
3136 	rtw89_phy_antdiv_reg_init(rtwdev);
3137 }
3138 
3139 static void rtw89_phy_stat_thermal_update(struct rtw89_dev *rtwdev)
3140 {
3141 	struct rtw89_phy_stat *phystat = &rtwdev->phystat;
3142 	int i;
3143 	u8 th;
3144 
3145 	for (i = 0; i < rtwdev->chip->rf_path_num; i++) {
3146 		th = rtw89_chip_get_thermal(rtwdev, i);
3147 		if (th)
3148 			ewma_thermal_add(&phystat->avg_thermal[i], th);
3149 
3150 		rtw89_debug(rtwdev, RTW89_DBG_RFK_TRACK,
3151 			    "path(%d) thermal cur=%u avg=%ld", i, th,
3152 			    ewma_thermal_read(&phystat->avg_thermal[i]));
3153 	}
3154 }
3155 
3156 struct rtw89_phy_iter_rssi_data {
3157 	struct rtw89_dev *rtwdev;
3158 	struct rtw89_phy_ch_info *ch_info;
3159 	bool rssi_changed;
3160 };
3161 
3162 static void rtw89_phy_stat_rssi_update_iter(void *data,
3163 					    struct ieee80211_sta *sta)
3164 {
3165 	struct rtw89_sta *rtwsta = (struct rtw89_sta *)sta->drv_priv;
3166 	struct rtw89_phy_iter_rssi_data *rssi_data =
3167 					(struct rtw89_phy_iter_rssi_data *)data;
3168 	struct rtw89_phy_ch_info *ch_info = rssi_data->ch_info;
3169 	unsigned long rssi_curr;
3170 
3171 	rssi_curr = ewma_rssi_read(&rtwsta->avg_rssi);
3172 
3173 	if (rssi_curr < ch_info->rssi_min) {
3174 		ch_info->rssi_min = rssi_curr;
3175 		ch_info->rssi_min_macid = rtwsta->mac_id;
3176 	}
3177 
3178 	if (rtwsta->prev_rssi == 0) {
3179 		rtwsta->prev_rssi = rssi_curr;
3180 	} else if (abs((int)rtwsta->prev_rssi - (int)rssi_curr) > (3 << RSSI_FACTOR)) {
3181 		rtwsta->prev_rssi = rssi_curr;
3182 		rssi_data->rssi_changed = true;
3183 	}
3184 }
3185 
3186 static void rtw89_phy_stat_rssi_update(struct rtw89_dev *rtwdev)
3187 {
3188 	struct rtw89_phy_iter_rssi_data rssi_data = {0};
3189 
3190 	rssi_data.rtwdev = rtwdev;
3191 	rssi_data.ch_info = &rtwdev->ch_info;
3192 	rssi_data.ch_info->rssi_min = U8_MAX;
3193 	ieee80211_iterate_stations_atomic(rtwdev->hw,
3194 					  rtw89_phy_stat_rssi_update_iter,
3195 					  &rssi_data);
3196 	if (rssi_data.rssi_changed)
3197 		rtw89_btc_ntfy_wl_sta(rtwdev);
3198 }
3199 
3200 static void rtw89_phy_stat_init(struct rtw89_dev *rtwdev)
3201 {
3202 	struct rtw89_phy_stat *phystat = &rtwdev->phystat;
3203 	int i;
3204 
3205 	for (i = 0; i < rtwdev->chip->rf_path_num; i++)
3206 		ewma_thermal_init(&phystat->avg_thermal[i]);
3207 
3208 	rtw89_phy_stat_thermal_update(rtwdev);
3209 
3210 	memset(&phystat->cur_pkt_stat, 0, sizeof(phystat->cur_pkt_stat));
3211 	memset(&phystat->last_pkt_stat, 0, sizeof(phystat->last_pkt_stat));
3212 }
3213 
3214 void rtw89_phy_stat_track(struct rtw89_dev *rtwdev)
3215 {
3216 	struct rtw89_phy_stat *phystat = &rtwdev->phystat;
3217 
3218 	rtw89_phy_stat_thermal_update(rtwdev);
3219 	rtw89_phy_stat_rssi_update(rtwdev);
3220 
3221 	phystat->last_pkt_stat = phystat->cur_pkt_stat;
3222 	memset(&phystat->cur_pkt_stat, 0, sizeof(phystat->cur_pkt_stat));
3223 }
3224 
3225 static u16 rtw89_phy_ccx_us_to_idx(struct rtw89_dev *rtwdev, u32 time_us)
3226 {
3227 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
3228 
3229 	return time_us >> (ilog2(CCX_US_BASE_RATIO) + env->ccx_unit_idx);
3230 }
3231 
3232 static u32 rtw89_phy_ccx_idx_to_us(struct rtw89_dev *rtwdev, u16 idx)
3233 {
3234 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
3235 
3236 	return idx << (ilog2(CCX_US_BASE_RATIO) + env->ccx_unit_idx);
3237 }
3238 
3239 static void rtw89_phy_ccx_top_setting_init(struct rtw89_dev *rtwdev)
3240 {
3241 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
3242 
3243 	env->ccx_manual_ctrl = false;
3244 	env->ccx_ongoing = false;
3245 	env->ccx_rac_lv = RTW89_RAC_RELEASE;
3246 	env->ccx_period = 0;
3247 	env->ccx_unit_idx = RTW89_CCX_32_US;
3248 
3249 	rtw89_phy_set_phy_regs(rtwdev, R_CCX, B_CCX_EN_MSK, 1);
3250 	rtw89_phy_set_phy_regs(rtwdev, R_CCX, B_CCX_TRIG_OPT_MSK, 1);
3251 	rtw89_phy_set_phy_regs(rtwdev, R_CCX, B_MEASUREMENT_TRIG_MSK, 1);
3252 	rtw89_phy_set_phy_regs(rtwdev, R_CCX, B_CCX_EDCCA_OPT_MSK,
3253 			       RTW89_CCX_EDCCA_BW20_0);
3254 }
3255 
3256 static u16 rtw89_phy_ccx_get_report(struct rtw89_dev *rtwdev, u16 report,
3257 				    u16 score)
3258 {
3259 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
3260 	u32 numer = 0;
3261 	u16 ret = 0;
3262 
3263 	numer = report * score + (env->ccx_period >> 1);
3264 	if (env->ccx_period)
3265 		ret = numer / env->ccx_period;
3266 
3267 	return ret >= score ? score - 1 : ret;
3268 }
3269 
3270 static void rtw89_phy_ccx_ms_to_period_unit(struct rtw89_dev *rtwdev,
3271 					    u16 time_ms, u32 *period,
3272 					    u32 *unit_idx)
3273 {
3274 	u32 idx;
3275 	u8 quotient;
3276 
3277 	if (time_ms >= CCX_MAX_PERIOD)
3278 		time_ms = CCX_MAX_PERIOD;
3279 
3280 	quotient = CCX_MAX_PERIOD_UNIT * time_ms / CCX_MAX_PERIOD;
3281 
3282 	if (quotient < 4)
3283 		idx = RTW89_CCX_4_US;
3284 	else if (quotient < 8)
3285 		idx = RTW89_CCX_8_US;
3286 	else if (quotient < 16)
3287 		idx = RTW89_CCX_16_US;
3288 	else
3289 		idx = RTW89_CCX_32_US;
3290 
3291 	*unit_idx = idx;
3292 	*period = (time_ms * MS_TO_4US_RATIO) >> idx;
3293 
3294 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3295 		    "[Trigger Time] period:%d, unit_idx:%d\n",
3296 		    *period, *unit_idx);
3297 }
3298 
3299 static void rtw89_phy_ccx_racing_release(struct rtw89_dev *rtwdev)
3300 {
3301 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
3302 
3303 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3304 		    "lv:(%d)->(0)\n", env->ccx_rac_lv);
3305 
3306 	env->ccx_ongoing = false;
3307 	env->ccx_rac_lv = RTW89_RAC_RELEASE;
3308 	env->ifs_clm_app = RTW89_IFS_CLM_BACKGROUND;
3309 }
3310 
3311 static bool rtw89_phy_ifs_clm_th_update_check(struct rtw89_dev *rtwdev,
3312 					      struct rtw89_ccx_para_info *para)
3313 {
3314 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
3315 	bool is_update = env->ifs_clm_app != para->ifs_clm_app;
3316 	u8 i = 0;
3317 	u16 *ifs_th_l = env->ifs_clm_th_l;
3318 	u16 *ifs_th_h = env->ifs_clm_th_h;
3319 	u32 ifs_th0_us = 0, ifs_th_times = 0;
3320 	u32 ifs_th_h_us[RTW89_IFS_CLM_NUM] = {0};
3321 
3322 	if (!is_update)
3323 		goto ifs_update_finished;
3324 
3325 	switch (para->ifs_clm_app) {
3326 	case RTW89_IFS_CLM_INIT:
3327 	case RTW89_IFS_CLM_BACKGROUND:
3328 	case RTW89_IFS_CLM_ACS:
3329 	case RTW89_IFS_CLM_DBG:
3330 	case RTW89_IFS_CLM_DIG:
3331 	case RTW89_IFS_CLM_TDMA_DIG:
3332 		ifs_th0_us = IFS_CLM_TH0_UPPER;
3333 		ifs_th_times = IFS_CLM_TH_MUL;
3334 		break;
3335 	case RTW89_IFS_CLM_DBG_MANUAL:
3336 		ifs_th0_us = para->ifs_clm_manual_th0;
3337 		ifs_th_times = para->ifs_clm_manual_th_times;
3338 		break;
3339 	default:
3340 		break;
3341 	}
3342 
3343 	/* Set sampling threshold for 4 different regions, unit in idx_cnt.
3344 	 * low[i] = high[i-1] + 1
3345 	 * high[i] = high[i-1] * ifs_th_times
3346 	 */
3347 	ifs_th_l[IFS_CLM_TH_START_IDX] = 0;
3348 	ifs_th_h_us[IFS_CLM_TH_START_IDX] = ifs_th0_us;
3349 	ifs_th_h[IFS_CLM_TH_START_IDX] = rtw89_phy_ccx_us_to_idx(rtwdev,
3350 								 ifs_th0_us);
3351 	for (i = 1; i < RTW89_IFS_CLM_NUM; i++) {
3352 		ifs_th_l[i] = ifs_th_h[i - 1] + 1;
3353 		ifs_th_h_us[i] = ifs_th_h_us[i - 1] * ifs_th_times;
3354 		ifs_th_h[i] = rtw89_phy_ccx_us_to_idx(rtwdev, ifs_th_h_us[i]);
3355 	}
3356 
3357 ifs_update_finished:
3358 	if (!is_update)
3359 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3360 			    "No need to update IFS_TH\n");
3361 
3362 	return is_update;
3363 }
3364 
3365 static void rtw89_phy_ifs_clm_set_th_reg(struct rtw89_dev *rtwdev)
3366 {
3367 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
3368 	u8 i = 0;
3369 
3370 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T1, B_IFS_T1_TH_LOW_MSK,
3371 			       env->ifs_clm_th_l[0]);
3372 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T2, B_IFS_T2_TH_LOW_MSK,
3373 			       env->ifs_clm_th_l[1]);
3374 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T3, B_IFS_T3_TH_LOW_MSK,
3375 			       env->ifs_clm_th_l[2]);
3376 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T4, B_IFS_T4_TH_LOW_MSK,
3377 			       env->ifs_clm_th_l[3]);
3378 
3379 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T1, B_IFS_T1_TH_HIGH_MSK,
3380 			       env->ifs_clm_th_h[0]);
3381 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T2, B_IFS_T2_TH_HIGH_MSK,
3382 			       env->ifs_clm_th_h[1]);
3383 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T3, B_IFS_T3_TH_HIGH_MSK,
3384 			       env->ifs_clm_th_h[2]);
3385 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T4, B_IFS_T4_TH_HIGH_MSK,
3386 			       env->ifs_clm_th_h[3]);
3387 
3388 	for (i = 0; i < RTW89_IFS_CLM_NUM; i++)
3389 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3390 			    "Update IFS_T%d_th{low, high} : {%d, %d}\n",
3391 			    i + 1, env->ifs_clm_th_l[i], env->ifs_clm_th_h[i]);
3392 }
3393 
3394 static void rtw89_phy_ifs_clm_setting_init(struct rtw89_dev *rtwdev)
3395 {
3396 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
3397 	struct rtw89_ccx_para_info para = {0};
3398 
3399 	env->ifs_clm_app = RTW89_IFS_CLM_BACKGROUND;
3400 	env->ifs_clm_mntr_time = 0;
3401 
3402 	para.ifs_clm_app = RTW89_IFS_CLM_INIT;
3403 	if (rtw89_phy_ifs_clm_th_update_check(rtwdev, &para))
3404 		rtw89_phy_ifs_clm_set_th_reg(rtwdev);
3405 
3406 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_COUNTER, B_IFS_COLLECT_EN,
3407 			       true);
3408 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T1, B_IFS_T1_EN_MSK, true);
3409 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T2, B_IFS_T2_EN_MSK, true);
3410 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T3, B_IFS_T3_EN_MSK, true);
3411 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T4, B_IFS_T4_EN_MSK, true);
3412 }
3413 
3414 static int rtw89_phy_ccx_racing_ctrl(struct rtw89_dev *rtwdev,
3415 				     enum rtw89_env_racing_lv level)
3416 {
3417 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
3418 	int ret = 0;
3419 
3420 	if (level >= RTW89_RAC_MAX_NUM) {
3421 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3422 			    "[WARNING] Wrong LV=%d\n", level);
3423 		return -EINVAL;
3424 	}
3425 
3426 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3427 		    "ccx_ongoing=%d, level:(%d)->(%d)\n", env->ccx_ongoing,
3428 		    env->ccx_rac_lv, level);
3429 
3430 	if (env->ccx_ongoing) {
3431 		if (level <= env->ccx_rac_lv)
3432 			ret = -EINVAL;
3433 		else
3434 			env->ccx_ongoing = false;
3435 	}
3436 
3437 	if (ret == 0)
3438 		env->ccx_rac_lv = level;
3439 
3440 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK, "ccx racing success=%d\n",
3441 		    !ret);
3442 
3443 	return ret;
3444 }
3445 
3446 static void rtw89_phy_ccx_trigger(struct rtw89_dev *rtwdev)
3447 {
3448 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
3449 
3450 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_COUNTER, B_IFS_COUNTER_CLR_MSK, 0);
3451 	rtw89_phy_set_phy_regs(rtwdev, R_CCX, B_MEASUREMENT_TRIG_MSK, 0);
3452 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_COUNTER, B_IFS_COUNTER_CLR_MSK, 1);
3453 	rtw89_phy_set_phy_regs(rtwdev, R_CCX, B_MEASUREMENT_TRIG_MSK, 1);
3454 
3455 	env->ccx_ongoing = true;
3456 }
3457 
3458 static void rtw89_phy_ifs_clm_get_utility(struct rtw89_dev *rtwdev)
3459 {
3460 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
3461 	u8 i = 0;
3462 	u32 res = 0;
3463 
3464 	env->ifs_clm_tx_ratio =
3465 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_tx, PERCENT);
3466 	env->ifs_clm_edcca_excl_cca_ratio =
3467 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_edcca_excl_cca,
3468 					 PERCENT);
3469 	env->ifs_clm_cck_fa_ratio =
3470 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_cckfa, PERCENT);
3471 	env->ifs_clm_ofdm_fa_ratio =
3472 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_ofdmfa, PERCENT);
3473 	env->ifs_clm_cck_cca_excl_fa_ratio =
3474 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_cckcca_excl_fa,
3475 					 PERCENT);
3476 	env->ifs_clm_ofdm_cca_excl_fa_ratio =
3477 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_ofdmcca_excl_fa,
3478 					 PERCENT);
3479 	env->ifs_clm_cck_fa_permil =
3480 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_cckfa, PERMIL);
3481 	env->ifs_clm_ofdm_fa_permil =
3482 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_ofdmfa, PERMIL);
3483 
3484 	for (i = 0; i < RTW89_IFS_CLM_NUM; i++) {
3485 		if (env->ifs_clm_his[i] > ENV_MNTR_IFSCLM_HIS_MAX) {
3486 			env->ifs_clm_ifs_avg[i] = ENV_MNTR_FAIL_DWORD;
3487 		} else {
3488 			env->ifs_clm_ifs_avg[i] =
3489 				rtw89_phy_ccx_idx_to_us(rtwdev,
3490 							env->ifs_clm_avg[i]);
3491 		}
3492 
3493 		res = rtw89_phy_ccx_idx_to_us(rtwdev, env->ifs_clm_cca[i]);
3494 		res += env->ifs_clm_his[i] >> 1;
3495 		if (env->ifs_clm_his[i])
3496 			res /= env->ifs_clm_his[i];
3497 		else
3498 			res = 0;
3499 		env->ifs_clm_cca_avg[i] = res;
3500 	}
3501 
3502 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3503 		    "IFS-CLM ratio {Tx, EDCCA_exclu_cca} = {%d, %d}\n",
3504 		    env->ifs_clm_tx_ratio, env->ifs_clm_edcca_excl_cca_ratio);
3505 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3506 		    "IFS-CLM FA ratio {CCK, OFDM} = {%d, %d}\n",
3507 		    env->ifs_clm_cck_fa_ratio, env->ifs_clm_ofdm_fa_ratio);
3508 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3509 		    "IFS-CLM FA permil {CCK, OFDM} = {%d, %d}\n",
3510 		    env->ifs_clm_cck_fa_permil, env->ifs_clm_ofdm_fa_permil);
3511 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3512 		    "IFS-CLM CCA_exclu_FA ratio {CCK, OFDM} = {%d, %d}\n",
3513 		    env->ifs_clm_cck_cca_excl_fa_ratio,
3514 		    env->ifs_clm_ofdm_cca_excl_fa_ratio);
3515 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3516 		    "Time:[his, ifs_avg(us), cca_avg(us)]\n");
3517 	for (i = 0; i < RTW89_IFS_CLM_NUM; i++)
3518 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK, "T%d:[%d, %d, %d]\n",
3519 			    i + 1, env->ifs_clm_his[i], env->ifs_clm_ifs_avg[i],
3520 			    env->ifs_clm_cca_avg[i]);
3521 }
3522 
3523 static bool rtw89_phy_ifs_clm_get_result(struct rtw89_dev *rtwdev)
3524 {
3525 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
3526 	u8 i = 0;
3527 
3528 	if (rtw89_phy_read32_mask(rtwdev, R_IFSCNT, B_IFSCNT_DONE_MSK) == 0) {
3529 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3530 			    "Get IFS_CLM report Fail\n");
3531 		return false;
3532 	}
3533 
3534 	env->ifs_clm_tx =
3535 		rtw89_phy_read32_mask(rtwdev, R_IFS_CLM_TX_CNT,
3536 				      B_IFS_CLM_TX_CNT_MSK);
3537 	env->ifs_clm_edcca_excl_cca =
3538 		rtw89_phy_read32_mask(rtwdev, R_IFS_CLM_TX_CNT,
3539 				      B_IFS_CLM_EDCCA_EXCLUDE_CCA_FA_MSK);
3540 	env->ifs_clm_cckcca_excl_fa =
3541 		rtw89_phy_read32_mask(rtwdev, R_IFS_CLM_CCA,
3542 				      B_IFS_CLM_CCKCCA_EXCLUDE_FA_MSK);
3543 	env->ifs_clm_ofdmcca_excl_fa =
3544 		rtw89_phy_read32_mask(rtwdev, R_IFS_CLM_CCA,
3545 				      B_IFS_CLM_OFDMCCA_EXCLUDE_FA_MSK);
3546 	env->ifs_clm_cckfa =
3547 		rtw89_phy_read32_mask(rtwdev, R_IFS_CLM_FA,
3548 				      B_IFS_CLM_CCK_FA_MSK);
3549 	env->ifs_clm_ofdmfa =
3550 		rtw89_phy_read32_mask(rtwdev, R_IFS_CLM_FA,
3551 				      B_IFS_CLM_OFDM_FA_MSK);
3552 
3553 	env->ifs_clm_his[0] =
3554 		rtw89_phy_read32_mask(rtwdev, R_IFS_HIS, B_IFS_T1_HIS_MSK);
3555 	env->ifs_clm_his[1] =
3556 		rtw89_phy_read32_mask(rtwdev, R_IFS_HIS, B_IFS_T2_HIS_MSK);
3557 	env->ifs_clm_his[2] =
3558 		rtw89_phy_read32_mask(rtwdev, R_IFS_HIS, B_IFS_T3_HIS_MSK);
3559 	env->ifs_clm_his[3] =
3560 		rtw89_phy_read32_mask(rtwdev, R_IFS_HIS, B_IFS_T4_HIS_MSK);
3561 
3562 	env->ifs_clm_avg[0] =
3563 		rtw89_phy_read32_mask(rtwdev, R_IFS_AVG_L, B_IFS_T1_AVG_MSK);
3564 	env->ifs_clm_avg[1] =
3565 		rtw89_phy_read32_mask(rtwdev, R_IFS_AVG_L, B_IFS_T2_AVG_MSK);
3566 	env->ifs_clm_avg[2] =
3567 		rtw89_phy_read32_mask(rtwdev, R_IFS_AVG_H, B_IFS_T3_AVG_MSK);
3568 	env->ifs_clm_avg[3] =
3569 		rtw89_phy_read32_mask(rtwdev, R_IFS_AVG_H, B_IFS_T4_AVG_MSK);
3570 
3571 	env->ifs_clm_cca[0] =
3572 		rtw89_phy_read32_mask(rtwdev, R_IFS_CCA_L, B_IFS_T1_CCA_MSK);
3573 	env->ifs_clm_cca[1] =
3574 		rtw89_phy_read32_mask(rtwdev, R_IFS_CCA_L, B_IFS_T2_CCA_MSK);
3575 	env->ifs_clm_cca[2] =
3576 		rtw89_phy_read32_mask(rtwdev, R_IFS_CCA_H, B_IFS_T3_CCA_MSK);
3577 	env->ifs_clm_cca[3] =
3578 		rtw89_phy_read32_mask(rtwdev, R_IFS_CCA_H, B_IFS_T4_CCA_MSK);
3579 
3580 	env->ifs_clm_total_ifs =
3581 		rtw89_phy_read32_mask(rtwdev, R_IFSCNT, B_IFSCNT_TOTAL_CNT_MSK);
3582 
3583 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK, "IFS-CLM total_ifs = %d\n",
3584 		    env->ifs_clm_total_ifs);
3585 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3586 		    "{Tx, EDCCA_exclu_cca} = {%d, %d}\n",
3587 		    env->ifs_clm_tx, env->ifs_clm_edcca_excl_cca);
3588 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3589 		    "IFS-CLM FA{CCK, OFDM} = {%d, %d}\n",
3590 		    env->ifs_clm_cckfa, env->ifs_clm_ofdmfa);
3591 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3592 		    "IFS-CLM CCA_exclu_FA{CCK, OFDM} = {%d, %d}\n",
3593 		    env->ifs_clm_cckcca_excl_fa, env->ifs_clm_ofdmcca_excl_fa);
3594 
3595 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK, "Time:[his, avg, cca]\n");
3596 	for (i = 0; i < RTW89_IFS_CLM_NUM; i++)
3597 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3598 			    "T%d:[%d, %d, %d]\n", i + 1, env->ifs_clm_his[i],
3599 			    env->ifs_clm_avg[i], env->ifs_clm_cca[i]);
3600 
3601 	rtw89_phy_ifs_clm_get_utility(rtwdev);
3602 
3603 	return true;
3604 }
3605 
3606 static int rtw89_phy_ifs_clm_set(struct rtw89_dev *rtwdev,
3607 				 struct rtw89_ccx_para_info *para)
3608 {
3609 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
3610 	u32 period = 0;
3611 	u32 unit_idx = 0;
3612 
3613 	if (para->mntr_time == 0) {
3614 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3615 			    "[WARN] MNTR_TIME is 0\n");
3616 		return -EINVAL;
3617 	}
3618 
3619 	if (rtw89_phy_ccx_racing_ctrl(rtwdev, para->rac_lv))
3620 		return -EINVAL;
3621 
3622 	if (para->mntr_time != env->ifs_clm_mntr_time) {
3623 		rtw89_phy_ccx_ms_to_period_unit(rtwdev, para->mntr_time,
3624 						&period, &unit_idx);
3625 		rtw89_phy_set_phy_regs(rtwdev, R_IFS_COUNTER,
3626 				       B_IFS_CLM_PERIOD_MSK, period);
3627 		rtw89_phy_set_phy_regs(rtwdev, R_IFS_COUNTER,
3628 				       B_IFS_CLM_COUNTER_UNIT_MSK, unit_idx);
3629 
3630 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3631 			    "Update IFS-CLM time ((%d)) -> ((%d))\n",
3632 			    env->ifs_clm_mntr_time, para->mntr_time);
3633 
3634 		env->ifs_clm_mntr_time = para->mntr_time;
3635 		env->ccx_period = (u16)period;
3636 		env->ccx_unit_idx = (u8)unit_idx;
3637 	}
3638 
3639 	if (rtw89_phy_ifs_clm_th_update_check(rtwdev, para)) {
3640 		env->ifs_clm_app = para->ifs_clm_app;
3641 		rtw89_phy_ifs_clm_set_th_reg(rtwdev);
3642 	}
3643 
3644 	return 0;
3645 }
3646 
3647 void rtw89_phy_env_monitor_track(struct rtw89_dev *rtwdev)
3648 {
3649 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
3650 	struct rtw89_ccx_para_info para = {0};
3651 	u8 chk_result = RTW89_PHY_ENV_MON_CCX_FAIL;
3652 
3653 	env->ccx_watchdog_result = RTW89_PHY_ENV_MON_CCX_FAIL;
3654 	if (env->ccx_manual_ctrl) {
3655 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3656 			    "CCX in manual ctrl\n");
3657 		return;
3658 	}
3659 
3660 	/* only ifs_clm for now */
3661 	if (rtw89_phy_ifs_clm_get_result(rtwdev))
3662 		env->ccx_watchdog_result |= RTW89_PHY_ENV_MON_IFS_CLM;
3663 
3664 	rtw89_phy_ccx_racing_release(rtwdev);
3665 	para.mntr_time = 1900;
3666 	para.rac_lv = RTW89_RAC_LV_1;
3667 	para.ifs_clm_app = RTW89_IFS_CLM_BACKGROUND;
3668 
3669 	if (rtw89_phy_ifs_clm_set(rtwdev, &para) == 0)
3670 		chk_result |= RTW89_PHY_ENV_MON_IFS_CLM;
3671 	if (chk_result)
3672 		rtw89_phy_ccx_trigger(rtwdev);
3673 
3674 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3675 		    "get_result=0x%x, chk_result:0x%x\n",
3676 		    env->ccx_watchdog_result, chk_result);
3677 }
3678 
3679 static bool rtw89_physts_ie_page_valid(enum rtw89_phy_status_bitmap *ie_page)
3680 {
3681 	if (*ie_page >= RTW89_PHYSTS_BITMAP_NUM ||
3682 	    *ie_page == RTW89_RSVD_9)
3683 		return false;
3684 	else if (*ie_page > RTW89_RSVD_9)
3685 		*ie_page -= 1;
3686 
3687 	return true;
3688 }
3689 
3690 static u32 rtw89_phy_get_ie_bitmap_addr(enum rtw89_phy_status_bitmap ie_page)
3691 {
3692 	static const u8 ie_page_shift = 2;
3693 
3694 	return R_PHY_STS_BITMAP_ADDR_START + (ie_page << ie_page_shift);
3695 }
3696 
3697 static u32 rtw89_physts_get_ie_bitmap(struct rtw89_dev *rtwdev,
3698 				      enum rtw89_phy_status_bitmap ie_page)
3699 {
3700 	u32 addr;
3701 
3702 	if (!rtw89_physts_ie_page_valid(&ie_page))
3703 		return 0;
3704 
3705 	addr = rtw89_phy_get_ie_bitmap_addr(ie_page);
3706 
3707 	return rtw89_phy_read32(rtwdev, addr);
3708 }
3709 
3710 static void rtw89_physts_set_ie_bitmap(struct rtw89_dev *rtwdev,
3711 				       enum rtw89_phy_status_bitmap ie_page,
3712 				       u32 val)
3713 {
3714 	const struct rtw89_chip_info *chip = rtwdev->chip;
3715 	u32 addr;
3716 
3717 	if (!rtw89_physts_ie_page_valid(&ie_page))
3718 		return;
3719 
3720 	if (chip->chip_id == RTL8852A)
3721 		val &= B_PHY_STS_BITMAP_MSK_52A;
3722 
3723 	addr = rtw89_phy_get_ie_bitmap_addr(ie_page);
3724 	rtw89_phy_write32(rtwdev, addr, val);
3725 }
3726 
3727 static void rtw89_physts_enable_ie_bitmap(struct rtw89_dev *rtwdev,
3728 					  enum rtw89_phy_status_bitmap bitmap,
3729 					  enum rtw89_phy_status_ie_type ie,
3730 					  bool enable)
3731 {
3732 	u32 val = rtw89_physts_get_ie_bitmap(rtwdev, bitmap);
3733 
3734 	if (enable)
3735 		val |= BIT(ie);
3736 	else
3737 		val &= ~BIT(ie);
3738 
3739 	rtw89_physts_set_ie_bitmap(rtwdev, bitmap, val);
3740 }
3741 
3742 static void rtw89_physts_enable_fail_report(struct rtw89_dev *rtwdev,
3743 					    bool enable,
3744 					    enum rtw89_phy_idx phy_idx)
3745 {
3746 	if (enable) {
3747 		rtw89_phy_write32_clr(rtwdev, R_PLCP_HISTOGRAM,
3748 				      B_STS_DIS_TRIG_BY_FAIL);
3749 		rtw89_phy_write32_clr(rtwdev, R_PLCP_HISTOGRAM,
3750 				      B_STS_DIS_TRIG_BY_BRK);
3751 	} else {
3752 		rtw89_phy_write32_set(rtwdev, R_PLCP_HISTOGRAM,
3753 				      B_STS_DIS_TRIG_BY_FAIL);
3754 		rtw89_phy_write32_set(rtwdev, R_PLCP_HISTOGRAM,
3755 				      B_STS_DIS_TRIG_BY_BRK);
3756 	}
3757 }
3758 
3759 static void rtw89_physts_parsing_init(struct rtw89_dev *rtwdev)
3760 {
3761 	u8 i;
3762 
3763 	rtw89_physts_enable_fail_report(rtwdev, false, RTW89_PHY_0);
3764 
3765 	for (i = 0; i < RTW89_PHYSTS_BITMAP_NUM; i++) {
3766 		if (i >= RTW89_CCK_PKT)
3767 			rtw89_physts_enable_ie_bitmap(rtwdev, i,
3768 						      RTW89_PHYSTS_IE09_FTR_0,
3769 						      true);
3770 		if ((i >= RTW89_CCK_BRK && i <= RTW89_VHT_MU) ||
3771 		    (i >= RTW89_RSVD_9 && i <= RTW89_CCK_PKT))
3772 			continue;
3773 		rtw89_physts_enable_ie_bitmap(rtwdev, i,
3774 					      RTW89_PHYSTS_IE24_OFDM_TD_PATH_A,
3775 					      true);
3776 	}
3777 	rtw89_physts_enable_ie_bitmap(rtwdev, RTW89_VHT_PKT,
3778 				      RTW89_PHYSTS_IE13_DL_MU_DEF, true);
3779 	rtw89_physts_enable_ie_bitmap(rtwdev, RTW89_HE_PKT,
3780 				      RTW89_PHYSTS_IE13_DL_MU_DEF, true);
3781 
3782 	/* force IE01 for channel index, only channel field is valid */
3783 	rtw89_physts_enable_ie_bitmap(rtwdev, RTW89_CCK_PKT,
3784 				      RTW89_PHYSTS_IE01_CMN_OFDM, true);
3785 }
3786 
3787 static void rtw89_phy_dig_read_gain_table(struct rtw89_dev *rtwdev, int type)
3788 {
3789 	const struct rtw89_chip_info *chip = rtwdev->chip;
3790 	struct rtw89_dig_info *dig = &rtwdev->dig;
3791 	const struct rtw89_phy_dig_gain_cfg *cfg;
3792 	const char *msg;
3793 	u8 i;
3794 	s8 gain_base;
3795 	s8 *gain_arr;
3796 	u32 tmp;
3797 
3798 	switch (type) {
3799 	case RTW89_DIG_GAIN_LNA_G:
3800 		gain_arr = dig->lna_gain_g;
3801 		gain_base = LNA0_GAIN;
3802 		cfg = chip->dig_table->cfg_lna_g;
3803 		msg = "lna_gain_g";
3804 		break;
3805 	case RTW89_DIG_GAIN_TIA_G:
3806 		gain_arr = dig->tia_gain_g;
3807 		gain_base = TIA0_GAIN_G;
3808 		cfg = chip->dig_table->cfg_tia_g;
3809 		msg = "tia_gain_g";
3810 		break;
3811 	case RTW89_DIG_GAIN_LNA_A:
3812 		gain_arr = dig->lna_gain_a;
3813 		gain_base = LNA0_GAIN;
3814 		cfg = chip->dig_table->cfg_lna_a;
3815 		msg = "lna_gain_a";
3816 		break;
3817 	case RTW89_DIG_GAIN_TIA_A:
3818 		gain_arr = dig->tia_gain_a;
3819 		gain_base = TIA0_GAIN_A;
3820 		cfg = chip->dig_table->cfg_tia_a;
3821 		msg = "tia_gain_a";
3822 		break;
3823 	default:
3824 		return;
3825 	}
3826 
3827 	for (i = 0; i < cfg->size; i++) {
3828 		tmp = rtw89_phy_read32_mask(rtwdev, cfg->table[i].addr,
3829 					    cfg->table[i].mask);
3830 		tmp >>= DIG_GAIN_SHIFT;
3831 		gain_arr[i] = sign_extend32(tmp, U4_MAX_BIT) + gain_base;
3832 		gain_base += DIG_GAIN;
3833 
3834 		rtw89_debug(rtwdev, RTW89_DBG_DIG, "%s[%d]=%d\n",
3835 			    msg, i, gain_arr[i]);
3836 	}
3837 }
3838 
3839 static void rtw89_phy_dig_update_gain_para(struct rtw89_dev *rtwdev)
3840 {
3841 	struct rtw89_dig_info *dig = &rtwdev->dig;
3842 	u32 tmp;
3843 	u8 i;
3844 
3845 	if (!rtwdev->hal.support_igi)
3846 		return;
3847 
3848 	tmp = rtw89_phy_read32_mask(rtwdev, R_PATH0_IB_PKPW,
3849 				    B_PATH0_IB_PKPW_MSK);
3850 	dig->ib_pkpwr = sign_extend32(tmp >> DIG_GAIN_SHIFT, U8_MAX_BIT);
3851 	dig->ib_pbk = rtw89_phy_read32_mask(rtwdev, R_PATH0_IB_PBK,
3852 					    B_PATH0_IB_PBK_MSK);
3853 	rtw89_debug(rtwdev, RTW89_DBG_DIG, "ib_pkpwr=%d, ib_pbk=%d\n",
3854 		    dig->ib_pkpwr, dig->ib_pbk);
3855 
3856 	for (i = RTW89_DIG_GAIN_LNA_G; i < RTW89_DIG_GAIN_MAX; i++)
3857 		rtw89_phy_dig_read_gain_table(rtwdev, i);
3858 }
3859 
3860 static const u8 rssi_nolink = 22;
3861 static const u8 igi_rssi_th[IGI_RSSI_TH_NUM] = {68, 84, 90, 98, 104};
3862 static const u16 fa_th_2g[FA_TH_NUM] = {22, 44, 66, 88};
3863 static const u16 fa_th_5g[FA_TH_NUM] = {4, 8, 12, 16};
3864 static const u16 fa_th_nolink[FA_TH_NUM] = {196, 352, 440, 528};
3865 
3866 static void rtw89_phy_dig_update_rssi_info(struct rtw89_dev *rtwdev)
3867 {
3868 	struct rtw89_phy_ch_info *ch_info = &rtwdev->ch_info;
3869 	struct rtw89_dig_info *dig = &rtwdev->dig;
3870 	bool is_linked = rtwdev->total_sta_assoc > 0;
3871 
3872 	if (is_linked) {
3873 		dig->igi_rssi = ch_info->rssi_min >> 1;
3874 	} else {
3875 		rtw89_debug(rtwdev, RTW89_DBG_DIG, "RSSI update : NO Link\n");
3876 		dig->igi_rssi = rssi_nolink;
3877 	}
3878 }
3879 
3880 static void rtw89_phy_dig_update_para(struct rtw89_dev *rtwdev)
3881 {
3882 	struct rtw89_dig_info *dig = &rtwdev->dig;
3883 	const struct rtw89_chan *chan = rtw89_chan_get(rtwdev, RTW89_SUB_ENTITY_0);
3884 	bool is_linked = rtwdev->total_sta_assoc > 0;
3885 	const u16 *fa_th_src = NULL;
3886 
3887 	switch (chan->band_type) {
3888 	case RTW89_BAND_2G:
3889 		dig->lna_gain = dig->lna_gain_g;
3890 		dig->tia_gain = dig->tia_gain_g;
3891 		fa_th_src = is_linked ? fa_th_2g : fa_th_nolink;
3892 		dig->force_gaincode_idx_en = false;
3893 		dig->dyn_pd_th_en = true;
3894 		break;
3895 	case RTW89_BAND_5G:
3896 	default:
3897 		dig->lna_gain = dig->lna_gain_a;
3898 		dig->tia_gain = dig->tia_gain_a;
3899 		fa_th_src = is_linked ? fa_th_5g : fa_th_nolink;
3900 		dig->force_gaincode_idx_en = true;
3901 		dig->dyn_pd_th_en = true;
3902 		break;
3903 	}
3904 	memcpy(dig->fa_th, fa_th_src, sizeof(dig->fa_th));
3905 	memcpy(dig->igi_rssi_th, igi_rssi_th, sizeof(dig->igi_rssi_th));
3906 }
3907 
3908 static const u8 pd_low_th_offset = 20, dynamic_igi_min = 0x20;
3909 static const u8 igi_max_performance_mode = 0x5a;
3910 static const u8 dynamic_pd_threshold_max;
3911 
3912 static void rtw89_phy_dig_para_reset(struct rtw89_dev *rtwdev)
3913 {
3914 	struct rtw89_dig_info *dig = &rtwdev->dig;
3915 
3916 	dig->cur_gaincode.lna_idx = LNA_IDX_MAX;
3917 	dig->cur_gaincode.tia_idx = TIA_IDX_MAX;
3918 	dig->cur_gaincode.rxb_idx = RXB_IDX_MAX;
3919 	dig->force_gaincode.lna_idx = LNA_IDX_MAX;
3920 	dig->force_gaincode.tia_idx = TIA_IDX_MAX;
3921 	dig->force_gaincode.rxb_idx = RXB_IDX_MAX;
3922 
3923 	dig->dyn_igi_max = igi_max_performance_mode;
3924 	dig->dyn_igi_min = dynamic_igi_min;
3925 	dig->dyn_pd_th_max = dynamic_pd_threshold_max;
3926 	dig->pd_low_th_ofst = pd_low_th_offset;
3927 	dig->is_linked_pre = false;
3928 }
3929 
3930 static void rtw89_phy_dig_init(struct rtw89_dev *rtwdev)
3931 {
3932 	rtw89_phy_dig_update_gain_para(rtwdev);
3933 	rtw89_phy_dig_reset(rtwdev);
3934 }
3935 
3936 static u8 rtw89_phy_dig_lna_idx_by_rssi(struct rtw89_dev *rtwdev, u8 rssi)
3937 {
3938 	struct rtw89_dig_info *dig = &rtwdev->dig;
3939 	u8 lna_idx;
3940 
3941 	if (rssi < dig->igi_rssi_th[0])
3942 		lna_idx = RTW89_DIG_GAIN_LNA_IDX6;
3943 	else if (rssi < dig->igi_rssi_th[1])
3944 		lna_idx = RTW89_DIG_GAIN_LNA_IDX5;
3945 	else if (rssi < dig->igi_rssi_th[2])
3946 		lna_idx = RTW89_DIG_GAIN_LNA_IDX4;
3947 	else if (rssi < dig->igi_rssi_th[3])
3948 		lna_idx = RTW89_DIG_GAIN_LNA_IDX3;
3949 	else if (rssi < dig->igi_rssi_th[4])
3950 		lna_idx = RTW89_DIG_GAIN_LNA_IDX2;
3951 	else
3952 		lna_idx = RTW89_DIG_GAIN_LNA_IDX1;
3953 
3954 	return lna_idx;
3955 }
3956 
3957 static u8 rtw89_phy_dig_tia_idx_by_rssi(struct rtw89_dev *rtwdev, u8 rssi)
3958 {
3959 	struct rtw89_dig_info *dig = &rtwdev->dig;
3960 	u8 tia_idx;
3961 
3962 	if (rssi < dig->igi_rssi_th[0])
3963 		tia_idx = RTW89_DIG_GAIN_TIA_IDX1;
3964 	else
3965 		tia_idx = RTW89_DIG_GAIN_TIA_IDX0;
3966 
3967 	return tia_idx;
3968 }
3969 
3970 #define IB_PBK_BASE 110
3971 #define WB_RSSI_BASE 10
3972 static u8 rtw89_phy_dig_rxb_idx_by_rssi(struct rtw89_dev *rtwdev, u8 rssi,
3973 					struct rtw89_agc_gaincode_set *set)
3974 {
3975 	struct rtw89_dig_info *dig = &rtwdev->dig;
3976 	s8 lna_gain = dig->lna_gain[set->lna_idx];
3977 	s8 tia_gain = dig->tia_gain[set->tia_idx];
3978 	s32 wb_rssi = rssi + lna_gain + tia_gain;
3979 	s32 rxb_idx_tmp = IB_PBK_BASE + WB_RSSI_BASE;
3980 	u8 rxb_idx;
3981 
3982 	rxb_idx_tmp += dig->ib_pkpwr - dig->ib_pbk - wb_rssi;
3983 	rxb_idx = clamp_t(s32, rxb_idx_tmp, RXB_IDX_MIN, RXB_IDX_MAX);
3984 
3985 	rtw89_debug(rtwdev, RTW89_DBG_DIG, "wb_rssi=%03d, rxb_idx_tmp=%03d\n",
3986 		    wb_rssi, rxb_idx_tmp);
3987 
3988 	return rxb_idx;
3989 }
3990 
3991 static void rtw89_phy_dig_gaincode_by_rssi(struct rtw89_dev *rtwdev, u8 rssi,
3992 					   struct rtw89_agc_gaincode_set *set)
3993 {
3994 	set->lna_idx = rtw89_phy_dig_lna_idx_by_rssi(rtwdev, rssi);
3995 	set->tia_idx = rtw89_phy_dig_tia_idx_by_rssi(rtwdev, rssi);
3996 	set->rxb_idx = rtw89_phy_dig_rxb_idx_by_rssi(rtwdev, rssi, set);
3997 
3998 	rtw89_debug(rtwdev, RTW89_DBG_DIG,
3999 		    "final_rssi=%03d, (lna,tia,rab)=(%d,%d,%02d)\n",
4000 		    rssi, set->lna_idx, set->tia_idx, set->rxb_idx);
4001 }
4002 
4003 #define IGI_OFFSET_MAX 25
4004 #define IGI_OFFSET_MUL 2
4005 static void rtw89_phy_dig_igi_offset_by_env(struct rtw89_dev *rtwdev)
4006 {
4007 	struct rtw89_dig_info *dig = &rtwdev->dig;
4008 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
4009 	enum rtw89_dig_noisy_level noisy_lv;
4010 	u8 igi_offset = dig->fa_rssi_ofst;
4011 	u16 fa_ratio = 0;
4012 
4013 	fa_ratio = env->ifs_clm_cck_fa_permil + env->ifs_clm_ofdm_fa_permil;
4014 
4015 	if (fa_ratio < dig->fa_th[0])
4016 		noisy_lv = RTW89_DIG_NOISY_LEVEL0;
4017 	else if (fa_ratio < dig->fa_th[1])
4018 		noisy_lv = RTW89_DIG_NOISY_LEVEL1;
4019 	else if (fa_ratio < dig->fa_th[2])
4020 		noisy_lv = RTW89_DIG_NOISY_LEVEL2;
4021 	else if (fa_ratio < dig->fa_th[3])
4022 		noisy_lv = RTW89_DIG_NOISY_LEVEL3;
4023 	else
4024 		noisy_lv = RTW89_DIG_NOISY_LEVEL_MAX;
4025 
4026 	if (noisy_lv == RTW89_DIG_NOISY_LEVEL0 && igi_offset < 2)
4027 		igi_offset = 0;
4028 	else
4029 		igi_offset += noisy_lv * IGI_OFFSET_MUL;
4030 
4031 	igi_offset = min_t(u8, igi_offset, IGI_OFFSET_MAX);
4032 	dig->fa_rssi_ofst = igi_offset;
4033 
4034 	rtw89_debug(rtwdev, RTW89_DBG_DIG,
4035 		    "fa_th: [+6 (%d) +4 (%d) +2 (%d) 0 (%d) -2 ]\n",
4036 		    dig->fa_th[3], dig->fa_th[2], dig->fa_th[1], dig->fa_th[0]);
4037 
4038 	rtw89_debug(rtwdev, RTW89_DBG_DIG,
4039 		    "fa(CCK,OFDM,ALL)=(%d,%d,%d)%%, noisy_lv=%d, ofst=%d\n",
4040 		    env->ifs_clm_cck_fa_permil, env->ifs_clm_ofdm_fa_permil,
4041 		    env->ifs_clm_cck_fa_permil + env->ifs_clm_ofdm_fa_permil,
4042 		    noisy_lv, igi_offset);
4043 }
4044 
4045 static void rtw89_phy_dig_set_lna_idx(struct rtw89_dev *rtwdev, u8 lna_idx)
4046 {
4047 	const struct rtw89_dig_regs *dig_regs = rtwdev->chip->dig_regs;
4048 
4049 	rtw89_phy_write32_mask(rtwdev, dig_regs->p0_lna_init.addr,
4050 			       dig_regs->p0_lna_init.mask, lna_idx);
4051 	rtw89_phy_write32_mask(rtwdev, dig_regs->p1_lna_init.addr,
4052 			       dig_regs->p1_lna_init.mask, lna_idx);
4053 }
4054 
4055 static void rtw89_phy_dig_set_tia_idx(struct rtw89_dev *rtwdev, u8 tia_idx)
4056 {
4057 	const struct rtw89_dig_regs *dig_regs = rtwdev->chip->dig_regs;
4058 
4059 	rtw89_phy_write32_mask(rtwdev, dig_regs->p0_tia_init.addr,
4060 			       dig_regs->p0_tia_init.mask, tia_idx);
4061 	rtw89_phy_write32_mask(rtwdev, dig_regs->p1_tia_init.addr,
4062 			       dig_regs->p1_tia_init.mask, tia_idx);
4063 }
4064 
4065 static void rtw89_phy_dig_set_rxb_idx(struct rtw89_dev *rtwdev, u8 rxb_idx)
4066 {
4067 	const struct rtw89_dig_regs *dig_regs = rtwdev->chip->dig_regs;
4068 
4069 	rtw89_phy_write32_mask(rtwdev, dig_regs->p0_rxb_init.addr,
4070 			       dig_regs->p0_rxb_init.mask, rxb_idx);
4071 	rtw89_phy_write32_mask(rtwdev, dig_regs->p1_rxb_init.addr,
4072 			       dig_regs->p1_rxb_init.mask, rxb_idx);
4073 }
4074 
4075 static void rtw89_phy_dig_set_igi_cr(struct rtw89_dev *rtwdev,
4076 				     const struct rtw89_agc_gaincode_set set)
4077 {
4078 	rtw89_phy_dig_set_lna_idx(rtwdev, set.lna_idx);
4079 	rtw89_phy_dig_set_tia_idx(rtwdev, set.tia_idx);
4080 	rtw89_phy_dig_set_rxb_idx(rtwdev, set.rxb_idx);
4081 
4082 	rtw89_debug(rtwdev, RTW89_DBG_DIG, "Set (lna,tia,rxb)=((%d,%d,%02d))\n",
4083 		    set.lna_idx, set.tia_idx, set.rxb_idx);
4084 }
4085 
4086 static void rtw89_phy_dig_sdagc_follow_pagc_config(struct rtw89_dev *rtwdev,
4087 						   bool enable)
4088 {
4089 	const struct rtw89_dig_regs *dig_regs = rtwdev->chip->dig_regs;
4090 
4091 	rtw89_phy_write32_mask(rtwdev, dig_regs->p0_p20_pagcugc_en.addr,
4092 			       dig_regs->p0_p20_pagcugc_en.mask, enable);
4093 	rtw89_phy_write32_mask(rtwdev, dig_regs->p0_s20_pagcugc_en.addr,
4094 			       dig_regs->p0_s20_pagcugc_en.mask, enable);
4095 	rtw89_phy_write32_mask(rtwdev, dig_regs->p1_p20_pagcugc_en.addr,
4096 			       dig_regs->p1_p20_pagcugc_en.mask, enable);
4097 	rtw89_phy_write32_mask(rtwdev, dig_regs->p1_s20_pagcugc_en.addr,
4098 			       dig_regs->p1_s20_pagcugc_en.mask, enable);
4099 
4100 	rtw89_debug(rtwdev, RTW89_DBG_DIG, "sdagc_follow_pagc=%d\n", enable);
4101 }
4102 
4103 static void rtw89_phy_dig_config_igi(struct rtw89_dev *rtwdev)
4104 {
4105 	struct rtw89_dig_info *dig = &rtwdev->dig;
4106 
4107 	if (!rtwdev->hal.support_igi)
4108 		return;
4109 
4110 	if (dig->force_gaincode_idx_en) {
4111 		rtw89_phy_dig_set_igi_cr(rtwdev, dig->force_gaincode);
4112 		rtw89_debug(rtwdev, RTW89_DBG_DIG,
4113 			    "Force gaincode index enabled.\n");
4114 	} else {
4115 		rtw89_phy_dig_gaincode_by_rssi(rtwdev, dig->igi_fa_rssi,
4116 					       &dig->cur_gaincode);
4117 		rtw89_phy_dig_set_igi_cr(rtwdev, dig->cur_gaincode);
4118 	}
4119 }
4120 
4121 static void rtw89_phy_dig_dyn_pd_th(struct rtw89_dev *rtwdev, u8 rssi,
4122 				    bool enable)
4123 {
4124 	const struct rtw89_chan *chan = rtw89_chan_get(rtwdev, RTW89_SUB_ENTITY_0);
4125 	const struct rtw89_dig_regs *dig_regs = rtwdev->chip->dig_regs;
4126 	enum rtw89_bandwidth cbw = chan->band_width;
4127 	struct rtw89_dig_info *dig = &rtwdev->dig;
4128 	u8 final_rssi = 0, under_region = dig->pd_low_th_ofst;
4129 	u8 ofdm_cca_th;
4130 	s8 cck_cca_th;
4131 	u32 pd_val = 0;
4132 
4133 	under_region += PD_TH_SB_FLTR_CMP_VAL;
4134 
4135 	switch (cbw) {
4136 	case RTW89_CHANNEL_WIDTH_40:
4137 		under_region += PD_TH_BW40_CMP_VAL;
4138 		break;
4139 	case RTW89_CHANNEL_WIDTH_80:
4140 		under_region += PD_TH_BW80_CMP_VAL;
4141 		break;
4142 	case RTW89_CHANNEL_WIDTH_160:
4143 		under_region += PD_TH_BW160_CMP_VAL;
4144 		break;
4145 	case RTW89_CHANNEL_WIDTH_20:
4146 		fallthrough;
4147 	default:
4148 		under_region += PD_TH_BW20_CMP_VAL;
4149 		break;
4150 	}
4151 
4152 	dig->dyn_pd_th_max = dig->igi_rssi;
4153 
4154 	final_rssi = min_t(u8, rssi, dig->igi_rssi);
4155 	ofdm_cca_th = clamp_t(u8, final_rssi, PD_TH_MIN_RSSI + under_region,
4156 			      PD_TH_MAX_RSSI + under_region);
4157 
4158 	if (enable) {
4159 		pd_val = (ofdm_cca_th - under_region - PD_TH_MIN_RSSI) >> 1;
4160 		rtw89_debug(rtwdev, RTW89_DBG_DIG,
4161 			    "igi=%d, ofdm_ccaTH=%d, backoff=%d, PD_low=%d\n",
4162 			    final_rssi, ofdm_cca_th, under_region, pd_val);
4163 	} else {
4164 		rtw89_debug(rtwdev, RTW89_DBG_DIG,
4165 			    "Dynamic PD th disabled, Set PD_low_bd=0\n");
4166 	}
4167 
4168 	rtw89_phy_write32_mask(rtwdev, dig_regs->seg0_pd_reg,
4169 			       dig_regs->pd_lower_bound_mask, pd_val);
4170 	rtw89_phy_write32_mask(rtwdev, dig_regs->seg0_pd_reg,
4171 			       dig_regs->pd_spatial_reuse_en, enable);
4172 
4173 	if (!rtwdev->hal.support_cckpd)
4174 		return;
4175 
4176 	cck_cca_th = max_t(s8, final_rssi - under_region, CCKPD_TH_MIN_RSSI);
4177 	pd_val = (u32)(cck_cca_th - IGI_RSSI_MAX);
4178 
4179 	rtw89_debug(rtwdev, RTW89_DBG_DIG,
4180 		    "igi=%d, cck_ccaTH=%d, backoff=%d, cck_PD_low=((%d))dB\n",
4181 		    final_rssi, cck_cca_th, under_region, pd_val);
4182 
4183 	rtw89_phy_write32_mask(rtwdev, R_BMODE_PDTH_EN_V1,
4184 			       B_BMODE_PDTH_LIMIT_EN_MSK_V1, enable);
4185 	rtw89_phy_write32_mask(rtwdev, R_BMODE_PDTH_V1,
4186 			       B_BMODE_PDTH_LOWER_BOUND_MSK_V1, pd_val);
4187 }
4188 
4189 void rtw89_phy_dig_reset(struct rtw89_dev *rtwdev)
4190 {
4191 	struct rtw89_dig_info *dig = &rtwdev->dig;
4192 
4193 	dig->bypass_dig = false;
4194 	rtw89_phy_dig_para_reset(rtwdev);
4195 	rtw89_phy_dig_set_igi_cr(rtwdev, dig->force_gaincode);
4196 	rtw89_phy_dig_dyn_pd_th(rtwdev, rssi_nolink, false);
4197 	rtw89_phy_dig_sdagc_follow_pagc_config(rtwdev, false);
4198 	rtw89_phy_dig_update_para(rtwdev);
4199 }
4200 
4201 #define IGI_RSSI_MIN 10
4202 void rtw89_phy_dig(struct rtw89_dev *rtwdev)
4203 {
4204 	struct rtw89_dig_info *dig = &rtwdev->dig;
4205 	bool is_linked = rtwdev->total_sta_assoc > 0;
4206 
4207 	if (unlikely(dig->bypass_dig)) {
4208 		dig->bypass_dig = false;
4209 		return;
4210 	}
4211 
4212 	if (!dig->is_linked_pre && is_linked) {
4213 		rtw89_debug(rtwdev, RTW89_DBG_DIG, "First connected\n");
4214 		rtw89_phy_dig_update_para(rtwdev);
4215 	} else if (dig->is_linked_pre && !is_linked) {
4216 		rtw89_debug(rtwdev, RTW89_DBG_DIG, "First disconnected\n");
4217 		rtw89_phy_dig_update_para(rtwdev);
4218 	}
4219 	dig->is_linked_pre = is_linked;
4220 
4221 	rtw89_phy_dig_igi_offset_by_env(rtwdev);
4222 	rtw89_phy_dig_update_rssi_info(rtwdev);
4223 
4224 	dig->dyn_igi_min = (dig->igi_rssi > IGI_RSSI_MIN) ?
4225 			    dig->igi_rssi - IGI_RSSI_MIN : 0;
4226 	dig->dyn_igi_max = dig->dyn_igi_min + IGI_OFFSET_MAX;
4227 	dig->igi_fa_rssi = dig->dyn_igi_min + dig->fa_rssi_ofst;
4228 
4229 	dig->igi_fa_rssi = clamp(dig->igi_fa_rssi, dig->dyn_igi_min,
4230 				 dig->dyn_igi_max);
4231 
4232 	rtw89_debug(rtwdev, RTW89_DBG_DIG,
4233 		    "rssi=%03d, dyn(max,min)=(%d,%d), final_rssi=%d\n",
4234 		    dig->igi_rssi, dig->dyn_igi_max, dig->dyn_igi_min,
4235 		    dig->igi_fa_rssi);
4236 
4237 	rtw89_phy_dig_config_igi(rtwdev);
4238 
4239 	rtw89_phy_dig_dyn_pd_th(rtwdev, dig->igi_fa_rssi, dig->dyn_pd_th_en);
4240 
4241 	if (dig->dyn_pd_th_en && dig->igi_fa_rssi > dig->dyn_pd_th_max)
4242 		rtw89_phy_dig_sdagc_follow_pagc_config(rtwdev, true);
4243 	else
4244 		rtw89_phy_dig_sdagc_follow_pagc_config(rtwdev, false);
4245 }
4246 
4247 static void rtw89_phy_tx_path_div_sta_iter(void *data, struct ieee80211_sta *sta)
4248 {
4249 	struct rtw89_sta *rtwsta = (struct rtw89_sta *)sta->drv_priv;
4250 	struct rtw89_dev *rtwdev = rtwsta->rtwdev;
4251 	struct rtw89_vif *rtwvif = rtwsta->rtwvif;
4252 	struct rtw89_hal *hal = &rtwdev->hal;
4253 	bool *done = data;
4254 	u8 rssi_a, rssi_b;
4255 	u32 candidate;
4256 
4257 	if (rtwvif->wifi_role != RTW89_WIFI_ROLE_STATION || sta->tdls)
4258 		return;
4259 
4260 	if (*done)
4261 		return;
4262 
4263 	*done = true;
4264 
4265 	rssi_a = ewma_rssi_read(&rtwsta->rssi[RF_PATH_A]);
4266 	rssi_b = ewma_rssi_read(&rtwsta->rssi[RF_PATH_B]);
4267 
4268 	if (rssi_a > rssi_b + RTW89_TX_DIV_RSSI_RAW_TH)
4269 		candidate = RF_A;
4270 	else if (rssi_b > rssi_a + RTW89_TX_DIV_RSSI_RAW_TH)
4271 		candidate = RF_B;
4272 	else
4273 		return;
4274 
4275 	if (hal->antenna_tx == candidate)
4276 		return;
4277 
4278 	hal->antenna_tx = candidate;
4279 	rtw89_fw_h2c_txpath_cmac_tbl(rtwdev, rtwsta);
4280 
4281 	if (hal->antenna_tx == RF_A) {
4282 		rtw89_phy_write32_mask(rtwdev, R_P0_RFMODE, B_P0_RFMODE_MUX, 0x12);
4283 		rtw89_phy_write32_mask(rtwdev, R_P1_RFMODE, B_P1_RFMODE_MUX, 0x11);
4284 	} else if (hal->antenna_tx == RF_B) {
4285 		rtw89_phy_write32_mask(rtwdev, R_P0_RFMODE, B_P0_RFMODE_MUX, 0x11);
4286 		rtw89_phy_write32_mask(rtwdev, R_P1_RFMODE, B_P1_RFMODE_MUX, 0x12);
4287 	}
4288 }
4289 
4290 void rtw89_phy_tx_path_div_track(struct rtw89_dev *rtwdev)
4291 {
4292 	struct rtw89_hal *hal = &rtwdev->hal;
4293 	bool done = false;
4294 
4295 	if (!hal->tx_path_diversity)
4296 		return;
4297 
4298 	ieee80211_iterate_stations_atomic(rtwdev->hw,
4299 					  rtw89_phy_tx_path_div_sta_iter,
4300 					  &done);
4301 }
4302 
4303 #define ANTDIV_MAIN 0
4304 #define ANTDIV_AUX 1
4305 
4306 static void rtw89_phy_antdiv_set_ant(struct rtw89_dev *rtwdev)
4307 {
4308 	struct rtw89_hal *hal = &rtwdev->hal;
4309 	u8 default_ant, optional_ant;
4310 
4311 	if (!hal->ant_diversity || hal->antenna_tx == 0)
4312 		return;
4313 
4314 	if (hal->antenna_tx == RF_B) {
4315 		default_ant = ANTDIV_AUX;
4316 		optional_ant = ANTDIV_MAIN;
4317 	} else {
4318 		default_ant = ANTDIV_MAIN;
4319 		optional_ant = ANTDIV_AUX;
4320 	}
4321 
4322 	rtw89_phy_write32_idx(rtwdev, R_P0_ANTSEL, B_P0_ANTSEL_CGCS_CTRL,
4323 			      default_ant, RTW89_PHY_0);
4324 	rtw89_phy_write32_idx(rtwdev, R_P0_ANTSEL, B_P0_ANTSEL_RX_ORI,
4325 			      default_ant, RTW89_PHY_0);
4326 	rtw89_phy_write32_idx(rtwdev, R_P0_ANTSEL, B_P0_ANTSEL_RX_ALT,
4327 			      optional_ant, RTW89_PHY_0);
4328 	rtw89_phy_write32_idx(rtwdev, R_P0_ANTSEL, B_P0_ANTSEL_TX_ORI,
4329 			      default_ant, RTW89_PHY_0);
4330 }
4331 
4332 static void rtw89_phy_swap_hal_antenna(struct rtw89_dev *rtwdev)
4333 {
4334 	struct rtw89_hal *hal = &rtwdev->hal;
4335 
4336 	hal->antenna_rx = hal->antenna_rx == RF_A ? RF_B : RF_A;
4337 	hal->antenna_tx = hal->antenna_rx;
4338 }
4339 
4340 static void rtw89_phy_antdiv_decision_state(struct rtw89_dev *rtwdev)
4341 {
4342 	struct rtw89_antdiv_info *antdiv = &rtwdev->antdiv;
4343 	struct rtw89_hal *hal = &rtwdev->hal;
4344 	bool no_change = false;
4345 	u8 main_rssi, aux_rssi;
4346 	u8 main_evm, aux_evm;
4347 	u32 candidate;
4348 
4349 	antdiv->get_stats = false;
4350 	antdiv->training_count = 0;
4351 
4352 	main_rssi = rtw89_phy_antdiv_sts_instance_get_rssi(&antdiv->main_stats);
4353 	main_evm = rtw89_phy_antdiv_sts_instance_get_evm(&antdiv->main_stats);
4354 	aux_rssi = rtw89_phy_antdiv_sts_instance_get_rssi(&antdiv->aux_stats);
4355 	aux_evm = rtw89_phy_antdiv_sts_instance_get_evm(&antdiv->aux_stats);
4356 
4357 	if (main_evm > aux_evm + ANTDIV_EVM_DIFF_TH)
4358 		candidate = RF_A;
4359 	else if (aux_evm > main_evm + ANTDIV_EVM_DIFF_TH)
4360 		candidate = RF_B;
4361 	else if (main_rssi > aux_rssi + RTW89_TX_DIV_RSSI_RAW_TH)
4362 		candidate = RF_A;
4363 	else if (aux_rssi > main_rssi + RTW89_TX_DIV_RSSI_RAW_TH)
4364 		candidate = RF_B;
4365 	else
4366 		no_change = true;
4367 
4368 	if (no_change) {
4369 		/* swap back from training antenna to original */
4370 		rtw89_phy_swap_hal_antenna(rtwdev);
4371 		return;
4372 	}
4373 
4374 	hal->antenna_tx = candidate;
4375 	hal->antenna_rx = candidate;
4376 }
4377 
4378 static void rtw89_phy_antdiv_training_state(struct rtw89_dev *rtwdev)
4379 {
4380 	struct rtw89_antdiv_info *antdiv = &rtwdev->antdiv;
4381 	u64 state_period;
4382 
4383 	if (antdiv->training_count % 2 == 0) {
4384 		if (antdiv->training_count == 0)
4385 			rtw89_phy_antdiv_sts_reset(rtwdev);
4386 
4387 		antdiv->get_stats = true;
4388 		state_period = msecs_to_jiffies(ANTDIV_TRAINNING_INTVL);
4389 	} else {
4390 		antdiv->get_stats = false;
4391 		state_period = msecs_to_jiffies(ANTDIV_DELAY);
4392 
4393 		rtw89_phy_swap_hal_antenna(rtwdev);
4394 		rtw89_phy_antdiv_set_ant(rtwdev);
4395 	}
4396 
4397 	antdiv->training_count++;
4398 	ieee80211_queue_delayed_work(rtwdev->hw, &rtwdev->antdiv_work,
4399 				     state_period);
4400 }
4401 
4402 void rtw89_phy_antdiv_work(struct work_struct *work)
4403 {
4404 	struct rtw89_dev *rtwdev = container_of(work, struct rtw89_dev,
4405 						antdiv_work.work);
4406 	struct rtw89_antdiv_info *antdiv = &rtwdev->antdiv;
4407 
4408 	mutex_lock(&rtwdev->mutex);
4409 
4410 	if (antdiv->training_count <= ANTDIV_TRAINNING_CNT) {
4411 		rtw89_phy_antdiv_training_state(rtwdev);
4412 	} else {
4413 		rtw89_phy_antdiv_decision_state(rtwdev);
4414 		rtw89_phy_antdiv_set_ant(rtwdev);
4415 	}
4416 
4417 	mutex_unlock(&rtwdev->mutex);
4418 }
4419 
4420 void rtw89_phy_antdiv_track(struct rtw89_dev *rtwdev)
4421 {
4422 	struct rtw89_antdiv_info *antdiv = &rtwdev->antdiv;
4423 	struct rtw89_hal *hal = &rtwdev->hal;
4424 	u8 rssi, rssi_pre;
4425 
4426 	if (!hal->ant_diversity || hal->ant_diversity_fixed)
4427 		return;
4428 
4429 	rssi = rtw89_phy_antdiv_sts_instance_get_rssi(&antdiv->target_stats);
4430 	rssi_pre = antdiv->rssi_pre;
4431 	antdiv->rssi_pre = rssi;
4432 	rtw89_phy_antdiv_sts_instance_reset(&antdiv->target_stats);
4433 
4434 	if (abs((int)rssi - (int)rssi_pre) < ANTDIV_RSSI_DIFF_TH)
4435 		return;
4436 
4437 	antdiv->training_count = 0;
4438 	ieee80211_queue_delayed_work(rtwdev->hw, &rtwdev->antdiv_work, 0);
4439 }
4440 
4441 static void rtw89_phy_env_monitor_init(struct rtw89_dev *rtwdev)
4442 {
4443 	rtw89_phy_ccx_top_setting_init(rtwdev);
4444 	rtw89_phy_ifs_clm_setting_init(rtwdev);
4445 }
4446 
4447 void rtw89_phy_dm_init(struct rtw89_dev *rtwdev)
4448 {
4449 	const struct rtw89_chip_info *chip = rtwdev->chip;
4450 
4451 	rtw89_phy_stat_init(rtwdev);
4452 
4453 	rtw89_chip_bb_sethw(rtwdev);
4454 
4455 	rtw89_phy_env_monitor_init(rtwdev);
4456 	rtw89_physts_parsing_init(rtwdev);
4457 	rtw89_phy_dig_init(rtwdev);
4458 	rtw89_phy_cfo_init(rtwdev);
4459 	rtw89_phy_ul_tb_info_init(rtwdev);
4460 	rtw89_phy_antdiv_init(rtwdev);
4461 	rtw89_chip_rfe_gpio(rtwdev);
4462 	rtw89_phy_antdiv_set_ant(rtwdev);
4463 
4464 	rtw89_phy_init_rf_nctl(rtwdev);
4465 	rtw89_chip_rfk_init(rtwdev);
4466 	rtw89_load_txpwr_table(rtwdev, chip->byr_table);
4467 	rtw89_chip_set_txpwr_ctrl(rtwdev);
4468 	rtw89_chip_power_trim(rtwdev);
4469 	rtw89_chip_cfg_txrx_path(rtwdev);
4470 }
4471 
4472 void rtw89_phy_set_bss_color(struct rtw89_dev *rtwdev, struct ieee80211_vif *vif)
4473 {
4474 	const struct rtw89_chip_info *chip = rtwdev->chip;
4475 	enum rtw89_phy_idx phy_idx = RTW89_PHY_0;
4476 	u8 bss_color;
4477 
4478 	if (!vif->bss_conf.he_support || !vif->cfg.assoc)
4479 		return;
4480 
4481 	bss_color = vif->bss_conf.he_bss_color.color;
4482 
4483 	rtw89_phy_write32_idx(rtwdev, chip->bss_clr_map_reg, B_BSS_CLR_MAP_VLD0, 0x1,
4484 			      phy_idx);
4485 	rtw89_phy_write32_idx(rtwdev, chip->bss_clr_map_reg, B_BSS_CLR_MAP_TGT,
4486 			      bss_color, phy_idx);
4487 	rtw89_phy_write32_idx(rtwdev, chip->bss_clr_map_reg, B_BSS_CLR_MAP_STAID,
4488 			      vif->cfg.aid, phy_idx);
4489 }
4490 
4491 static void
4492 _rfk_write_rf(struct rtw89_dev *rtwdev, const struct rtw89_reg5_def *def)
4493 {
4494 	rtw89_write_rf(rtwdev, def->path, def->addr, def->mask, def->data);
4495 }
4496 
4497 static void
4498 _rfk_write32_mask(struct rtw89_dev *rtwdev, const struct rtw89_reg5_def *def)
4499 {
4500 	rtw89_phy_write32_mask(rtwdev, def->addr, def->mask, def->data);
4501 }
4502 
4503 static void
4504 _rfk_write32_set(struct rtw89_dev *rtwdev, const struct rtw89_reg5_def *def)
4505 {
4506 	rtw89_phy_write32_set(rtwdev, def->addr, def->mask);
4507 }
4508 
4509 static void
4510 _rfk_write32_clr(struct rtw89_dev *rtwdev, const struct rtw89_reg5_def *def)
4511 {
4512 	rtw89_phy_write32_clr(rtwdev, def->addr, def->mask);
4513 }
4514 
4515 static void
4516 _rfk_delay(struct rtw89_dev *rtwdev, const struct rtw89_reg5_def *def)
4517 {
4518 	udelay(def->data);
4519 }
4520 
4521 static void
4522 (*_rfk_handler[])(struct rtw89_dev *rtwdev, const struct rtw89_reg5_def *def) = {
4523 	[RTW89_RFK_F_WRF] = _rfk_write_rf,
4524 	[RTW89_RFK_F_WM] = _rfk_write32_mask,
4525 	[RTW89_RFK_F_WS] = _rfk_write32_set,
4526 	[RTW89_RFK_F_WC] = _rfk_write32_clr,
4527 	[RTW89_RFK_F_DELAY] = _rfk_delay,
4528 };
4529 
4530 #if defined(__linux__)
4531 static_assert(ARRAY_SIZE(_rfk_handler) == RTW89_RFK_F_NUM);
4532 #elif defined(__FreeBSD__)
4533 rtw89_static_assert(ARRAY_SIZE(_rfk_handler) == RTW89_RFK_F_NUM);
4534 #endif
4535 
4536 void
4537 rtw89_rfk_parser(struct rtw89_dev *rtwdev, const struct rtw89_rfk_tbl *tbl)
4538 {
4539 	const struct rtw89_reg5_def *p = tbl->defs;
4540 	const struct rtw89_reg5_def *end = tbl->defs + tbl->size;
4541 
4542 	for (; p < end; p++)
4543 		_rfk_handler[p->flag](rtwdev, p);
4544 }
4545 EXPORT_SYMBOL(rtw89_rfk_parser);
4546 
4547 #define RTW89_TSSI_FAST_MODE_NUM 4
4548 
4549 static const struct rtw89_reg_def rtw89_tssi_fastmode_regs_flat[RTW89_TSSI_FAST_MODE_NUM] = {
4550 	{0xD934, 0xff0000},
4551 	{0xD934, 0xff000000},
4552 	{0xD938, 0xff},
4553 	{0xD934, 0xff00},
4554 };
4555 
4556 static const struct rtw89_reg_def rtw89_tssi_fastmode_regs_level[RTW89_TSSI_FAST_MODE_NUM] = {
4557 	{0xD930, 0xff0000},
4558 	{0xD930, 0xff000000},
4559 	{0xD934, 0xff},
4560 	{0xD930, 0xff00},
4561 };
4562 
4563 static
4564 void rtw89_phy_tssi_ctrl_set_fast_mode_cfg(struct rtw89_dev *rtwdev,
4565 					   enum rtw89_mac_idx mac_idx,
4566 					   enum rtw89_tssi_bandedge_cfg bandedge_cfg,
4567 					   u32 val)
4568 {
4569 	const struct rtw89_reg_def *regs;
4570 	u32 reg;
4571 	int i;
4572 
4573 	if (bandedge_cfg == RTW89_TSSI_BANDEDGE_FLAT)
4574 		regs = rtw89_tssi_fastmode_regs_flat;
4575 	else
4576 		regs = rtw89_tssi_fastmode_regs_level;
4577 
4578 	for (i = 0; i < RTW89_TSSI_FAST_MODE_NUM; i++) {
4579 		reg = rtw89_mac_reg_by_idx(regs[i].addr, mac_idx);
4580 		rtw89_write32_mask(rtwdev, reg, regs[i].mask, val);
4581 	}
4582 }
4583 
4584 static const struct rtw89_reg_def rtw89_tssi_bandedge_regs_flat[RTW89_TSSI_SBW_NUM] = {
4585 	{0xD91C, 0xff000000},
4586 	{0xD920, 0xff},
4587 	{0xD920, 0xff00},
4588 	{0xD920, 0xff0000},
4589 	{0xD920, 0xff000000},
4590 	{0xD924, 0xff},
4591 	{0xD924, 0xff00},
4592 	{0xD914, 0xff000000},
4593 	{0xD918, 0xff},
4594 	{0xD918, 0xff00},
4595 	{0xD918, 0xff0000},
4596 	{0xD918, 0xff000000},
4597 	{0xD91C, 0xff},
4598 	{0xD91C, 0xff00},
4599 	{0xD91C, 0xff0000},
4600 };
4601 
4602 static const struct rtw89_reg_def rtw89_tssi_bandedge_regs_level[RTW89_TSSI_SBW_NUM] = {
4603 	{0xD910, 0xff},
4604 	{0xD910, 0xff00},
4605 	{0xD910, 0xff0000},
4606 	{0xD910, 0xff000000},
4607 	{0xD914, 0xff},
4608 	{0xD914, 0xff00},
4609 	{0xD914, 0xff0000},
4610 	{0xD908, 0xff},
4611 	{0xD908, 0xff00},
4612 	{0xD908, 0xff0000},
4613 	{0xD908, 0xff000000},
4614 	{0xD90C, 0xff},
4615 	{0xD90C, 0xff00},
4616 	{0xD90C, 0xff0000},
4617 	{0xD90C, 0xff000000},
4618 };
4619 
4620 void rtw89_phy_tssi_ctrl_set_bandedge_cfg(struct rtw89_dev *rtwdev,
4621 					  enum rtw89_mac_idx mac_idx,
4622 					  enum rtw89_tssi_bandedge_cfg bandedge_cfg)
4623 {
4624 	const struct rtw89_chip_info *chip = rtwdev->chip;
4625 	const struct rtw89_reg_def *regs;
4626 	const u32 *data;
4627 	u32 reg;
4628 	int i;
4629 
4630 	if (bandedge_cfg >= RTW89_TSSI_CFG_NUM)
4631 		return;
4632 
4633 	if (bandedge_cfg == RTW89_TSSI_BANDEDGE_FLAT)
4634 		regs = rtw89_tssi_bandedge_regs_flat;
4635 	else
4636 		regs = rtw89_tssi_bandedge_regs_level;
4637 
4638 	data = chip->tssi_dbw_table->data[bandedge_cfg];
4639 
4640 	for (i = 0; i < RTW89_TSSI_SBW_NUM; i++) {
4641 		reg = rtw89_mac_reg_by_idx(regs[i].addr, mac_idx);
4642 		rtw89_write32_mask(rtwdev, reg, regs[i].mask, data[i]);
4643 	}
4644 
4645 	reg = rtw89_mac_reg_by_idx(R_AX_BANDEDGE_CFG, mac_idx);
4646 	rtw89_write32_mask(rtwdev, reg, B_AX_BANDEDGE_CFG_IDX_MASK, bandedge_cfg);
4647 
4648 	rtw89_phy_tssi_ctrl_set_fast_mode_cfg(rtwdev, mac_idx, bandedge_cfg,
4649 					      data[RTW89_TSSI_SBW20]);
4650 }
4651 EXPORT_SYMBOL(rtw89_phy_tssi_ctrl_set_bandedge_cfg);
4652 
4653 static
4654 const u8 rtw89_ch_base_table[16] = {1, 0xff,
4655 				    36, 100, 132, 149, 0xff,
4656 				    1, 33, 65, 97, 129, 161, 193, 225, 0xff};
4657 #define RTW89_CH_BASE_IDX_2G		0
4658 #define RTW89_CH_BASE_IDX_5G_FIRST	2
4659 #define RTW89_CH_BASE_IDX_5G_LAST	5
4660 #define RTW89_CH_BASE_IDX_6G_FIRST	7
4661 #define RTW89_CH_BASE_IDX_6G_LAST	14
4662 
4663 #define RTW89_CH_BASE_IDX_MASK		GENMASK(7, 4)
4664 #define RTW89_CH_OFFSET_MASK		GENMASK(3, 0)
4665 
4666 u8 rtw89_encode_chan_idx(struct rtw89_dev *rtwdev, u8 central_ch, u8 band)
4667 {
4668 	u8 chan_idx;
4669 	u8 last, first;
4670 	u8 idx;
4671 
4672 	switch (band) {
4673 	case RTW89_BAND_2G:
4674 		chan_idx = FIELD_PREP(RTW89_CH_BASE_IDX_MASK, RTW89_CH_BASE_IDX_2G) |
4675 			   FIELD_PREP(RTW89_CH_OFFSET_MASK, central_ch);
4676 		return chan_idx;
4677 	case RTW89_BAND_5G:
4678 		first = RTW89_CH_BASE_IDX_5G_FIRST;
4679 		last = RTW89_CH_BASE_IDX_5G_LAST;
4680 		break;
4681 	case RTW89_BAND_6G:
4682 		first = RTW89_CH_BASE_IDX_6G_FIRST;
4683 		last = RTW89_CH_BASE_IDX_6G_LAST;
4684 		break;
4685 	default:
4686 		rtw89_warn(rtwdev, "Unsupported band %d\n", band);
4687 		return 0;
4688 	}
4689 
4690 	for (idx = last; idx >= first; idx--)
4691 		if (central_ch >= rtw89_ch_base_table[idx])
4692 			break;
4693 
4694 	if (idx < first) {
4695 		rtw89_warn(rtwdev, "Unknown band %d channel %d\n", band, central_ch);
4696 		return 0;
4697 	}
4698 
4699 	chan_idx = FIELD_PREP(RTW89_CH_BASE_IDX_MASK, idx) |
4700 		   FIELD_PREP(RTW89_CH_OFFSET_MASK,
4701 			      (central_ch - rtw89_ch_base_table[idx]) >> 1);
4702 	return chan_idx;
4703 }
4704 EXPORT_SYMBOL(rtw89_encode_chan_idx);
4705 
4706 void rtw89_decode_chan_idx(struct rtw89_dev *rtwdev, u8 chan_idx,
4707 			   u8 *ch, enum nl80211_band *band)
4708 {
4709 	u8 idx, offset;
4710 
4711 	idx = FIELD_GET(RTW89_CH_BASE_IDX_MASK, chan_idx);
4712 	offset = FIELD_GET(RTW89_CH_OFFSET_MASK, chan_idx);
4713 
4714 	if (idx == RTW89_CH_BASE_IDX_2G) {
4715 		*band = NL80211_BAND_2GHZ;
4716 		*ch = offset;
4717 		return;
4718 	}
4719 
4720 	*band = idx <= RTW89_CH_BASE_IDX_5G_LAST ? NL80211_BAND_5GHZ : NL80211_BAND_6GHZ;
4721 	*ch = rtw89_ch_base_table[idx] + (offset << 1);
4722 }
4723 EXPORT_SYMBOL(rtw89_decode_chan_idx);
4724 
4725 #define EDCCA_DEFAULT 249
4726 void rtw89_phy_config_edcca(struct rtw89_dev *rtwdev, bool scan)
4727 {
4728 	u32 reg = rtwdev->chip->edcca_lvl_reg;
4729 	struct rtw89_hal *hal = &rtwdev->hal;
4730 	u32 val;
4731 
4732 	if (scan) {
4733 		hal->edcca_bak = rtw89_phy_read32(rtwdev, reg);
4734 		val = hal->edcca_bak;
4735 		u32p_replace_bits(&val, EDCCA_DEFAULT, B_SEG0R_EDCCA_LVL_A_MSK);
4736 		u32p_replace_bits(&val, EDCCA_DEFAULT, B_SEG0R_EDCCA_LVL_P_MSK);
4737 		u32p_replace_bits(&val, EDCCA_DEFAULT, B_SEG0R_PPDU_LVL_MSK);
4738 		rtw89_phy_write32(rtwdev, reg, val);
4739 	} else {
4740 		rtw89_phy_write32(rtwdev, reg, hal->edcca_bak);
4741 	}
4742 }
4743