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