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