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