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, R_IOQ_IQK_DPK, 0x3);
1372 	rtw89_phy_write32_set(rtwdev, R_GNT_BT_WGT_EN, 0x1);
1373 	rtw89_phy_write32_set(rtwdev, R_P0_PATH_RST, 0x8000000);
1374 	rtw89_phy_write32_set(rtwdev, R_P1_PATH_RST, 0x8000000);
1375 	if (chip->chip_id == RTL8852B)
1376 		rtw89_phy_write32_set(rtwdev, R_IOQ_IQK_DPK, 0x2);
1377 
1378 	/* check 0x8080 */
1379 	rtw89_phy_write32(rtwdev, R_NCTL_CFG, 0x8);
1380 
1381 	ret = read_poll_timeout(rtw89_phy_nctl_poll, val, val == 0x4, 10,
1382 				1000, false, rtwdev);
1383 	if (ret)
1384 		rtw89_err(rtwdev, "failed to poll nctl block\n");
1385 
1386 	nctl_table = chip->nctl_table;
1387 	rtw89_phy_init_reg(rtwdev, nctl_table, rtw89_phy_config_bb_reg, NULL);
1388 }
1389 
1390 static u32 rtw89_phy0_phy1_offset(struct rtw89_dev *rtwdev, u32 addr)
1391 {
1392 	u32 phy_page = addr >> 8;
1393 	u32 ofst = 0;
1394 
1395 	switch (phy_page) {
1396 	case 0x6:
1397 	case 0x7:
1398 	case 0x8:
1399 	case 0x9:
1400 	case 0xa:
1401 	case 0xb:
1402 	case 0xc:
1403 	case 0xd:
1404 	case 0x19:
1405 	case 0x1a:
1406 	case 0x1b:
1407 		ofst = 0x2000;
1408 		break;
1409 	default:
1410 		/* warning case */
1411 		ofst = 0;
1412 		break;
1413 	}
1414 
1415 	if (phy_page >= 0x40 && phy_page <= 0x4f)
1416 		ofst = 0x2000;
1417 
1418 	return ofst;
1419 }
1420 
1421 void rtw89_phy_write32_idx(struct rtw89_dev *rtwdev, u32 addr, u32 mask,
1422 			   u32 data, enum rtw89_phy_idx phy_idx)
1423 {
1424 	if (rtwdev->dbcc_en && phy_idx == RTW89_PHY_1)
1425 		addr += rtw89_phy0_phy1_offset(rtwdev, addr);
1426 	rtw89_phy_write32_mask(rtwdev, addr, mask, data);
1427 }
1428 EXPORT_SYMBOL(rtw89_phy_write32_idx);
1429 
1430 u32 rtw89_phy_read32_idx(struct rtw89_dev *rtwdev, u32 addr, u32 mask,
1431 			 enum rtw89_phy_idx phy_idx)
1432 {
1433 	if (rtwdev->dbcc_en && phy_idx == RTW89_PHY_1)
1434 		addr += rtw89_phy0_phy1_offset(rtwdev, addr);
1435 	return rtw89_phy_read32_mask(rtwdev, addr, mask);
1436 }
1437 EXPORT_SYMBOL(rtw89_phy_read32_idx);
1438 
1439 void rtw89_phy_set_phy_regs(struct rtw89_dev *rtwdev, u32 addr, u32 mask,
1440 			    u32 val)
1441 {
1442 	rtw89_phy_write32_idx(rtwdev, addr, mask, val, RTW89_PHY_0);
1443 
1444 	if (!rtwdev->dbcc_en)
1445 		return;
1446 
1447 	rtw89_phy_write32_idx(rtwdev, addr, mask, val, RTW89_PHY_1);
1448 }
1449 
1450 void rtw89_phy_write_reg3_tbl(struct rtw89_dev *rtwdev,
1451 			      const struct rtw89_phy_reg3_tbl *tbl)
1452 {
1453 	const struct rtw89_reg3_def *reg3;
1454 	int i;
1455 
1456 	for (i = 0; i < tbl->size; i++) {
1457 		reg3 = &tbl->reg3[i];
1458 		rtw89_phy_write32_mask(rtwdev, reg3->addr, reg3->mask, reg3->data);
1459 	}
1460 }
1461 EXPORT_SYMBOL(rtw89_phy_write_reg3_tbl);
1462 
1463 static const u8 rtw89_rs_idx_max[] = {
1464 	[RTW89_RS_CCK] = RTW89_RATE_CCK_MAX,
1465 	[RTW89_RS_OFDM] = RTW89_RATE_OFDM_MAX,
1466 	[RTW89_RS_MCS] = RTW89_RATE_MCS_MAX,
1467 	[RTW89_RS_HEDCM] = RTW89_RATE_HEDCM_MAX,
1468 	[RTW89_RS_OFFSET] = RTW89_RATE_OFFSET_MAX,
1469 };
1470 
1471 static const u8 rtw89_rs_nss_max[] = {
1472 	[RTW89_RS_CCK] = 1,
1473 	[RTW89_RS_OFDM] = 1,
1474 	[RTW89_RS_MCS] = RTW89_NSS_MAX,
1475 	[RTW89_RS_HEDCM] = RTW89_NSS_HEDCM_MAX,
1476 	[RTW89_RS_OFFSET] = 1,
1477 };
1478 
1479 static const u8 _byr_of_rs[] = {
1480 	[RTW89_RS_CCK] = offsetof(struct rtw89_txpwr_byrate, cck),
1481 	[RTW89_RS_OFDM] = offsetof(struct rtw89_txpwr_byrate, ofdm),
1482 	[RTW89_RS_MCS] = offsetof(struct rtw89_txpwr_byrate, mcs),
1483 	[RTW89_RS_HEDCM] = offsetof(struct rtw89_txpwr_byrate, hedcm),
1484 	[RTW89_RS_OFFSET] = offsetof(struct rtw89_txpwr_byrate, offset),
1485 };
1486 
1487 #define _byr_seek(rs, raw) ((s8 *)(raw) + _byr_of_rs[rs])
1488 #define _byr_idx(rs, nss, idx) ((nss) * rtw89_rs_idx_max[rs] + (idx))
1489 #define _byr_chk(rs, nss, idx) \
1490 	((nss) < rtw89_rs_nss_max[rs] && (idx) < rtw89_rs_idx_max[rs])
1491 
1492 void rtw89_phy_load_txpwr_byrate(struct rtw89_dev *rtwdev,
1493 				 const struct rtw89_txpwr_table *tbl)
1494 {
1495 	const struct rtw89_txpwr_byrate_cfg *cfg = tbl->data;
1496 	const struct rtw89_txpwr_byrate_cfg *end = cfg + tbl->size;
1497 	s8 *byr;
1498 	u32 data;
1499 	u8 i, idx;
1500 
1501 	for (; cfg < end; cfg++) {
1502 		byr = _byr_seek(cfg->rs, &rtwdev->byr[cfg->band]);
1503 		data = cfg->data;
1504 
1505 		for (i = 0; i < cfg->len; i++, data >>= 8) {
1506 			idx = _byr_idx(cfg->rs, cfg->nss, (cfg->shf + i));
1507 			byr[idx] = (s8)(data & 0xff);
1508 		}
1509 	}
1510 }
1511 EXPORT_SYMBOL(rtw89_phy_load_txpwr_byrate);
1512 
1513 #define _phy_txpwr_rf_to_mac(rtwdev, txpwr_rf)				\
1514 ({									\
1515 	const struct rtw89_chip_info *__c = (rtwdev)->chip;		\
1516 	(txpwr_rf) >> (__c->txpwr_factor_rf - __c->txpwr_factor_mac);	\
1517 })
1518 
1519 static
1520 s8 rtw89_phy_read_txpwr_byrate(struct rtw89_dev *rtwdev, u8 band,
1521 			       const struct rtw89_rate_desc *rate_desc)
1522 {
1523 	s8 *byr;
1524 	u8 idx;
1525 
1526 	if (rate_desc->rs == RTW89_RS_CCK)
1527 		band = RTW89_BAND_2G;
1528 
1529 	if (!_byr_chk(rate_desc->rs, rate_desc->nss, rate_desc->idx)) {
1530 		rtw89_debug(rtwdev, RTW89_DBG_TXPWR,
1531 			    "[TXPWR] unknown byrate desc rs=%d nss=%d idx=%d\n",
1532 			    rate_desc->rs, rate_desc->nss, rate_desc->idx);
1533 
1534 		return 0;
1535 	}
1536 
1537 	byr = _byr_seek(rate_desc->rs, &rtwdev->byr[band]);
1538 	idx = _byr_idx(rate_desc->rs, rate_desc->nss, rate_desc->idx);
1539 
1540 	return _phy_txpwr_rf_to_mac(rtwdev, byr[idx]);
1541 }
1542 
1543 static u8 rtw89_channel_6g_to_idx(struct rtw89_dev *rtwdev, u8 channel_6g)
1544 {
1545 	switch (channel_6g) {
1546 	case 1 ... 29:
1547 		return (channel_6g - 1) / 2;
1548 	case 33 ... 61:
1549 		return (channel_6g - 3) / 2;
1550 	case 65 ... 93:
1551 		return (channel_6g - 5) / 2;
1552 	case 97 ... 125:
1553 		return (channel_6g - 7) / 2;
1554 	case 129 ... 157:
1555 		return (channel_6g - 9) / 2;
1556 	case 161 ... 189:
1557 		return (channel_6g - 11) / 2;
1558 	case 193 ... 221:
1559 		return (channel_6g - 13) / 2;
1560 	case 225 ... 253:
1561 		return (channel_6g - 15) / 2;
1562 	default:
1563 		rtw89_warn(rtwdev, "unknown 6g channel: %d\n", channel_6g);
1564 		return 0;
1565 	}
1566 }
1567 
1568 static u8 rtw89_channel_to_idx(struct rtw89_dev *rtwdev, u8 band, u8 channel)
1569 {
1570 	if (band == RTW89_BAND_6G)
1571 		return rtw89_channel_6g_to_idx(rtwdev, channel);
1572 
1573 	switch (channel) {
1574 	case 1 ... 14:
1575 		return channel - 1;
1576 	case 36 ... 64:
1577 		return (channel - 36) / 2;
1578 	case 100 ... 144:
1579 		return ((channel - 100) / 2) + 15;
1580 	case 149 ... 177:
1581 		return ((channel - 149) / 2) + 38;
1582 	default:
1583 		rtw89_warn(rtwdev, "unknown channel: %d\n", channel);
1584 		return 0;
1585 	}
1586 }
1587 
1588 s8 rtw89_phy_read_txpwr_limit(struct rtw89_dev *rtwdev, u8 band,
1589 			      u8 bw, u8 ntx, u8 rs, u8 bf, u8 ch)
1590 {
1591 	const struct rtw89_chip_info *chip = rtwdev->chip;
1592 	u8 ch_idx = rtw89_channel_to_idx(rtwdev, band, ch);
1593 	u8 regd = rtw89_regd_get(rtwdev, band);
1594 	s8 lmt = 0, sar;
1595 
1596 	switch (band) {
1597 	case RTW89_BAND_2G:
1598 		lmt = (*chip->txpwr_lmt_2g)[bw][ntx][rs][bf][regd][ch_idx];
1599 		if (!lmt)
1600 			lmt = (*chip->txpwr_lmt_2g)[bw][ntx][rs][bf]
1601 						   [RTW89_WW][ch_idx];
1602 		break;
1603 	case RTW89_BAND_5G:
1604 		lmt = (*chip->txpwr_lmt_5g)[bw][ntx][rs][bf][regd][ch_idx];
1605 		if (!lmt)
1606 			lmt = (*chip->txpwr_lmt_5g)[bw][ntx][rs][bf]
1607 						   [RTW89_WW][ch_idx];
1608 		break;
1609 	case RTW89_BAND_6G:
1610 		lmt = (*chip->txpwr_lmt_6g)[bw][ntx][rs][bf][regd][ch_idx];
1611 		if (!lmt)
1612 			lmt = (*chip->txpwr_lmt_6g)[bw][ntx][rs][bf]
1613 						   [RTW89_WW][ch_idx];
1614 		break;
1615 	default:
1616 		rtw89_warn(rtwdev, "unknown band type: %d\n", band);
1617 		return 0;
1618 	}
1619 
1620 	lmt = _phy_txpwr_rf_to_mac(rtwdev, lmt);
1621 	sar = rtw89_query_sar(rtwdev);
1622 
1623 	return min(lmt, sar);
1624 }
1625 EXPORT_SYMBOL(rtw89_phy_read_txpwr_limit);
1626 
1627 #define __fill_txpwr_limit_nonbf_bf(ptr, band, bw, ntx, rs, ch)		\
1628 	do {								\
1629 		u8 __i;							\
1630 		for (__i = 0; __i < RTW89_BF_NUM; __i++)		\
1631 			ptr[__i] = rtw89_phy_read_txpwr_limit(rtwdev,	\
1632 							      band,	\
1633 							      bw, ntx,	\
1634 							      rs, __i,	\
1635 							      (ch));	\
1636 	} while (0)
1637 
1638 static void rtw89_phy_fill_txpwr_limit_20m(struct rtw89_dev *rtwdev,
1639 					   struct rtw89_txpwr_limit *lmt,
1640 					   u8 band, u8 ntx, u8 ch)
1641 {
1642 	__fill_txpwr_limit_nonbf_bf(lmt->cck_20m, band, RTW89_CHANNEL_WIDTH_20,
1643 				    ntx, RTW89_RS_CCK, ch);
1644 	__fill_txpwr_limit_nonbf_bf(lmt->cck_40m, band, RTW89_CHANNEL_WIDTH_40,
1645 				    ntx, RTW89_RS_CCK, ch);
1646 	__fill_txpwr_limit_nonbf_bf(lmt->ofdm, band, RTW89_CHANNEL_WIDTH_20,
1647 				    ntx, RTW89_RS_OFDM, ch);
1648 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[0], band,
1649 				    RTW89_CHANNEL_WIDTH_20,
1650 				    ntx, RTW89_RS_MCS, ch);
1651 }
1652 
1653 static void rtw89_phy_fill_txpwr_limit_40m(struct rtw89_dev *rtwdev,
1654 					   struct rtw89_txpwr_limit *lmt,
1655 					   u8 band, u8 ntx, u8 ch, u8 pri_ch)
1656 {
1657 	__fill_txpwr_limit_nonbf_bf(lmt->cck_20m, band, RTW89_CHANNEL_WIDTH_20,
1658 				    ntx, RTW89_RS_CCK, ch - 2);
1659 	__fill_txpwr_limit_nonbf_bf(lmt->cck_40m, band, RTW89_CHANNEL_WIDTH_40,
1660 				    ntx, RTW89_RS_CCK, ch);
1661 	__fill_txpwr_limit_nonbf_bf(lmt->ofdm, band, RTW89_CHANNEL_WIDTH_20,
1662 				    ntx, RTW89_RS_OFDM, pri_ch);
1663 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[0], band,
1664 				    RTW89_CHANNEL_WIDTH_20,
1665 				    ntx, RTW89_RS_MCS, ch - 2);
1666 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[1], band,
1667 				    RTW89_CHANNEL_WIDTH_20,
1668 				    ntx, RTW89_RS_MCS, ch + 2);
1669 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_40m[0], band,
1670 				    RTW89_CHANNEL_WIDTH_40,
1671 				    ntx, RTW89_RS_MCS, ch);
1672 }
1673 
1674 static void rtw89_phy_fill_txpwr_limit_80m(struct rtw89_dev *rtwdev,
1675 					   struct rtw89_txpwr_limit *lmt,
1676 					   u8 band, u8 ntx, u8 ch, u8 pri_ch)
1677 {
1678 	s8 val_0p5_n[RTW89_BF_NUM];
1679 	s8 val_0p5_p[RTW89_BF_NUM];
1680 	u8 i;
1681 
1682 	__fill_txpwr_limit_nonbf_bf(lmt->ofdm, band, RTW89_CHANNEL_WIDTH_20,
1683 				    ntx, RTW89_RS_OFDM, pri_ch);
1684 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[0], band,
1685 				    RTW89_CHANNEL_WIDTH_20,
1686 				    ntx, RTW89_RS_MCS, ch - 6);
1687 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[1], band,
1688 				    RTW89_CHANNEL_WIDTH_20,
1689 				    ntx, RTW89_RS_MCS, ch - 2);
1690 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[2], band,
1691 				    RTW89_CHANNEL_WIDTH_20,
1692 				    ntx, RTW89_RS_MCS, ch + 2);
1693 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[3], band,
1694 				    RTW89_CHANNEL_WIDTH_20,
1695 				    ntx, RTW89_RS_MCS, ch + 6);
1696 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_40m[0], band,
1697 				    RTW89_CHANNEL_WIDTH_40,
1698 				    ntx, RTW89_RS_MCS, ch - 4);
1699 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_40m[1], band,
1700 				    RTW89_CHANNEL_WIDTH_40,
1701 				    ntx, RTW89_RS_MCS, ch + 4);
1702 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_80m[0], band,
1703 				    RTW89_CHANNEL_WIDTH_80,
1704 				    ntx, RTW89_RS_MCS, ch);
1705 
1706 	__fill_txpwr_limit_nonbf_bf(val_0p5_n, band, RTW89_CHANNEL_WIDTH_40,
1707 				    ntx, RTW89_RS_MCS, ch - 4);
1708 	__fill_txpwr_limit_nonbf_bf(val_0p5_p, band, RTW89_CHANNEL_WIDTH_40,
1709 				    ntx, RTW89_RS_MCS, ch + 4);
1710 
1711 	for (i = 0; i < RTW89_BF_NUM; i++)
1712 		lmt->mcs_40m_0p5[i] = min_t(s8, val_0p5_n[i], val_0p5_p[i]);
1713 }
1714 
1715 static void rtw89_phy_fill_txpwr_limit_160m(struct rtw89_dev *rtwdev,
1716 					    struct rtw89_txpwr_limit *lmt,
1717 					    u8 band, u8 ntx, u8 ch, u8 pri_ch)
1718 {
1719 	s8 val_0p5_n[RTW89_BF_NUM];
1720 	s8 val_0p5_p[RTW89_BF_NUM];
1721 	s8 val_2p5_n[RTW89_BF_NUM];
1722 	s8 val_2p5_p[RTW89_BF_NUM];
1723 	u8 i;
1724 
1725 	/* fill ofdm section */
1726 	__fill_txpwr_limit_nonbf_bf(lmt->ofdm, band, RTW89_CHANNEL_WIDTH_20,
1727 				    ntx, RTW89_RS_OFDM, pri_ch);
1728 
1729 	/* fill mcs 20m section */
1730 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[0], band,
1731 				    RTW89_CHANNEL_WIDTH_20,
1732 				    ntx, RTW89_RS_MCS, ch - 14);
1733 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[1], band,
1734 				    RTW89_CHANNEL_WIDTH_20,
1735 				    ntx, RTW89_RS_MCS, ch - 10);
1736 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[2], band,
1737 				    RTW89_CHANNEL_WIDTH_20,
1738 				    ntx, RTW89_RS_MCS, ch - 6);
1739 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[3], band,
1740 				    RTW89_CHANNEL_WIDTH_20,
1741 				    ntx, RTW89_RS_MCS, ch - 2);
1742 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[4], band,
1743 				    RTW89_CHANNEL_WIDTH_20,
1744 				    ntx, RTW89_RS_MCS, ch + 2);
1745 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[5], band,
1746 				    RTW89_CHANNEL_WIDTH_20,
1747 				    ntx, RTW89_RS_MCS, ch + 6);
1748 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[6], band,
1749 				    RTW89_CHANNEL_WIDTH_20,
1750 				    ntx, RTW89_RS_MCS, ch + 10);
1751 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[7], band,
1752 				    RTW89_CHANNEL_WIDTH_20,
1753 				    ntx, RTW89_RS_MCS, ch + 14);
1754 
1755 	/* fill mcs 40m section */
1756 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_40m[0], band,
1757 				    RTW89_CHANNEL_WIDTH_40,
1758 				    ntx, RTW89_RS_MCS, ch - 12);
1759 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_40m[1], band,
1760 				    RTW89_CHANNEL_WIDTH_40,
1761 				    ntx, RTW89_RS_MCS, ch - 4);
1762 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_40m[2], band,
1763 				    RTW89_CHANNEL_WIDTH_40,
1764 				    ntx, RTW89_RS_MCS, ch + 4);
1765 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_40m[3], band,
1766 				    RTW89_CHANNEL_WIDTH_40,
1767 				    ntx, RTW89_RS_MCS, ch + 12);
1768 
1769 	/* fill mcs 80m section */
1770 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_80m[0], band,
1771 				    RTW89_CHANNEL_WIDTH_80,
1772 				    ntx, RTW89_RS_MCS, ch - 8);
1773 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_80m[1], band,
1774 				    RTW89_CHANNEL_WIDTH_80,
1775 				    ntx, RTW89_RS_MCS, ch + 8);
1776 
1777 	/* fill mcs 160m section */
1778 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_160m, band,
1779 				    RTW89_CHANNEL_WIDTH_160,
1780 				    ntx, RTW89_RS_MCS, ch);
1781 
1782 	/* fill mcs 40m 0p5 section */
1783 	__fill_txpwr_limit_nonbf_bf(val_0p5_n, band, RTW89_CHANNEL_WIDTH_40,
1784 				    ntx, RTW89_RS_MCS, ch - 4);
1785 	__fill_txpwr_limit_nonbf_bf(val_0p5_p, band, RTW89_CHANNEL_WIDTH_40,
1786 				    ntx, RTW89_RS_MCS, ch + 4);
1787 
1788 	for (i = 0; i < RTW89_BF_NUM; i++)
1789 		lmt->mcs_40m_0p5[i] = min_t(s8, val_0p5_n[i], val_0p5_p[i]);
1790 
1791 	/* fill mcs 40m 2p5 section */
1792 	__fill_txpwr_limit_nonbf_bf(val_2p5_n, band, RTW89_CHANNEL_WIDTH_40,
1793 				    ntx, RTW89_RS_MCS, ch - 8);
1794 	__fill_txpwr_limit_nonbf_bf(val_2p5_p, band, RTW89_CHANNEL_WIDTH_40,
1795 				    ntx, RTW89_RS_MCS, ch + 8);
1796 
1797 	for (i = 0; i < RTW89_BF_NUM; i++)
1798 		lmt->mcs_40m_2p5[i] = min_t(s8, val_2p5_n[i], val_2p5_p[i]);
1799 }
1800 
1801 static
1802 void rtw89_phy_fill_txpwr_limit(struct rtw89_dev *rtwdev,
1803 				const struct rtw89_chan *chan,
1804 				struct rtw89_txpwr_limit *lmt,
1805 				u8 ntx)
1806 {
1807 	u8 band = chan->band_type;
1808 	u8 pri_ch = chan->primary_channel;
1809 	u8 ch = chan->channel;
1810 	u8 bw = chan->band_width;
1811 
1812 	memset(lmt, 0, sizeof(*lmt));
1813 
1814 	switch (bw) {
1815 	case RTW89_CHANNEL_WIDTH_20:
1816 		rtw89_phy_fill_txpwr_limit_20m(rtwdev, lmt, band, ntx, ch);
1817 		break;
1818 	case RTW89_CHANNEL_WIDTH_40:
1819 		rtw89_phy_fill_txpwr_limit_40m(rtwdev, lmt, band, ntx, ch,
1820 					       pri_ch);
1821 		break;
1822 	case RTW89_CHANNEL_WIDTH_80:
1823 		rtw89_phy_fill_txpwr_limit_80m(rtwdev, lmt, band, ntx, ch,
1824 					       pri_ch);
1825 		break;
1826 	case RTW89_CHANNEL_WIDTH_160:
1827 		rtw89_phy_fill_txpwr_limit_160m(rtwdev, lmt, band, ntx, ch,
1828 						pri_ch);
1829 		break;
1830 	}
1831 }
1832 
1833 static s8 rtw89_phy_read_txpwr_limit_ru(struct rtw89_dev *rtwdev, u8 band,
1834 					u8 ru, u8 ntx, u8 ch)
1835 {
1836 	const struct rtw89_chip_info *chip = rtwdev->chip;
1837 	u8 ch_idx = rtw89_channel_to_idx(rtwdev, band, ch);
1838 	u8 regd = rtw89_regd_get(rtwdev, band);
1839 	s8 lmt_ru = 0, sar;
1840 
1841 	switch (band) {
1842 	case RTW89_BAND_2G:
1843 		lmt_ru = (*chip->txpwr_lmt_ru_2g)[ru][ntx][regd][ch_idx];
1844 		if (!lmt_ru)
1845 			lmt_ru = (*chip->txpwr_lmt_ru_2g)[ru][ntx]
1846 							 [RTW89_WW][ch_idx];
1847 		break;
1848 	case RTW89_BAND_5G:
1849 		lmt_ru = (*chip->txpwr_lmt_ru_5g)[ru][ntx][regd][ch_idx];
1850 		if (!lmt_ru)
1851 			lmt_ru = (*chip->txpwr_lmt_ru_5g)[ru][ntx]
1852 							 [RTW89_WW][ch_idx];
1853 		break;
1854 	case RTW89_BAND_6G:
1855 		lmt_ru = (*chip->txpwr_lmt_ru_6g)[ru][ntx][regd][ch_idx];
1856 		if (!lmt_ru)
1857 			lmt_ru = (*chip->txpwr_lmt_ru_6g)[ru][ntx]
1858 							 [RTW89_WW][ch_idx];
1859 		break;
1860 	default:
1861 		rtw89_warn(rtwdev, "unknown band type: %d\n", band);
1862 		return 0;
1863 	}
1864 
1865 	lmt_ru = _phy_txpwr_rf_to_mac(rtwdev, lmt_ru);
1866 	sar = rtw89_query_sar(rtwdev);
1867 
1868 	return min(lmt_ru, sar);
1869 }
1870 
1871 static void
1872 rtw89_phy_fill_txpwr_limit_ru_20m(struct rtw89_dev *rtwdev,
1873 				  struct rtw89_txpwr_limit_ru *lmt_ru,
1874 				  u8 band, u8 ntx, u8 ch)
1875 {
1876 	lmt_ru->ru26[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1877 							RTW89_RU26,
1878 							ntx, ch);
1879 	lmt_ru->ru52[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1880 							RTW89_RU52,
1881 							ntx, ch);
1882 	lmt_ru->ru106[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1883 							 RTW89_RU106,
1884 							 ntx, ch);
1885 }
1886 
1887 static void
1888 rtw89_phy_fill_txpwr_limit_ru_40m(struct rtw89_dev *rtwdev,
1889 				  struct rtw89_txpwr_limit_ru *lmt_ru,
1890 				  u8 band, u8 ntx, u8 ch)
1891 {
1892 	lmt_ru->ru26[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1893 							RTW89_RU26,
1894 							ntx, ch - 2);
1895 	lmt_ru->ru26[1] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1896 							RTW89_RU26,
1897 							ntx, ch + 2);
1898 	lmt_ru->ru52[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1899 							RTW89_RU52,
1900 							ntx, ch - 2);
1901 	lmt_ru->ru52[1] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1902 							RTW89_RU52,
1903 							ntx, ch + 2);
1904 	lmt_ru->ru106[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1905 							 RTW89_RU106,
1906 							 ntx, ch - 2);
1907 	lmt_ru->ru106[1] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1908 							 RTW89_RU106,
1909 							 ntx, ch + 2);
1910 }
1911 
1912 static void
1913 rtw89_phy_fill_txpwr_limit_ru_80m(struct rtw89_dev *rtwdev,
1914 				  struct rtw89_txpwr_limit_ru *lmt_ru,
1915 				  u8 band, u8 ntx, u8 ch)
1916 {
1917 	lmt_ru->ru26[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1918 							RTW89_RU26,
1919 							ntx, ch - 6);
1920 	lmt_ru->ru26[1] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1921 							RTW89_RU26,
1922 							ntx, ch - 2);
1923 	lmt_ru->ru26[2] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1924 							RTW89_RU26,
1925 							ntx, ch + 2);
1926 	lmt_ru->ru26[3] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1927 							RTW89_RU26,
1928 							ntx, ch + 6);
1929 	lmt_ru->ru52[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1930 							RTW89_RU52,
1931 							ntx, ch - 6);
1932 	lmt_ru->ru52[1] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1933 							RTW89_RU52,
1934 							ntx, ch - 2);
1935 	lmt_ru->ru52[2] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1936 							RTW89_RU52,
1937 							ntx, ch + 2);
1938 	lmt_ru->ru52[3] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1939 							RTW89_RU52,
1940 							ntx, ch + 6);
1941 	lmt_ru->ru106[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1942 							 RTW89_RU106,
1943 							 ntx, ch - 6);
1944 	lmt_ru->ru106[1] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1945 							 RTW89_RU106,
1946 							 ntx, ch - 2);
1947 	lmt_ru->ru106[2] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1948 							 RTW89_RU106,
1949 							 ntx, ch + 2);
1950 	lmt_ru->ru106[3] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1951 							 RTW89_RU106,
1952 							 ntx, ch + 6);
1953 }
1954 
1955 static void
1956 rtw89_phy_fill_txpwr_limit_ru_160m(struct rtw89_dev *rtwdev,
1957 				   struct rtw89_txpwr_limit_ru *lmt_ru,
1958 				   u8 band, u8 ntx, u8 ch)
1959 {
1960 	static const int ofst[] = { -14, -10, -6, -2, 2, 6, 10, 14 };
1961 	int i;
1962 
1963 	static_assert(ARRAY_SIZE(ofst) == RTW89_RU_SEC_NUM);
1964 	for (i = 0; i < RTW89_RU_SEC_NUM; i++) {
1965 		lmt_ru->ru26[i] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1966 								RTW89_RU26,
1967 								ntx,
1968 								ch + ofst[i]);
1969 		lmt_ru->ru52[i] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1970 								RTW89_RU52,
1971 								ntx,
1972 								ch + ofst[i]);
1973 		lmt_ru->ru106[i] = rtw89_phy_read_txpwr_limit_ru(rtwdev, band,
1974 								 RTW89_RU106,
1975 								 ntx,
1976 								 ch + ofst[i]);
1977 	}
1978 }
1979 
1980 static
1981 void rtw89_phy_fill_txpwr_limit_ru(struct rtw89_dev *rtwdev,
1982 				   const struct rtw89_chan *chan,
1983 				   struct rtw89_txpwr_limit_ru *lmt_ru,
1984 				   u8 ntx)
1985 {
1986 	u8 band = chan->band_type;
1987 	u8 ch = chan->channel;
1988 	u8 bw = chan->band_width;
1989 
1990 	memset(lmt_ru, 0, sizeof(*lmt_ru));
1991 
1992 	switch (bw) {
1993 	case RTW89_CHANNEL_WIDTH_20:
1994 		rtw89_phy_fill_txpwr_limit_ru_20m(rtwdev, lmt_ru, band, ntx,
1995 						  ch);
1996 		break;
1997 	case RTW89_CHANNEL_WIDTH_40:
1998 		rtw89_phy_fill_txpwr_limit_ru_40m(rtwdev, lmt_ru, band, ntx,
1999 						  ch);
2000 		break;
2001 	case RTW89_CHANNEL_WIDTH_80:
2002 		rtw89_phy_fill_txpwr_limit_ru_80m(rtwdev, lmt_ru, band, ntx,
2003 						  ch);
2004 		break;
2005 	case RTW89_CHANNEL_WIDTH_160:
2006 		rtw89_phy_fill_txpwr_limit_ru_160m(rtwdev, lmt_ru, band, ntx,
2007 						   ch);
2008 		break;
2009 	}
2010 }
2011 
2012 void rtw89_phy_set_txpwr_byrate(struct rtw89_dev *rtwdev,
2013 				const struct rtw89_chan *chan,
2014 				enum rtw89_phy_idx phy_idx)
2015 {
2016 	static const u8 rs[] = {
2017 		RTW89_RS_CCK,
2018 		RTW89_RS_OFDM,
2019 		RTW89_RS_MCS,
2020 		RTW89_RS_HEDCM,
2021 	};
2022 	struct rtw89_rate_desc cur;
2023 	u8 band = chan->band_type;
2024 	u8 ch = chan->channel;
2025 	u32 addr, val;
2026 	s8 v[4] = {};
2027 	u8 i;
2028 
2029 	rtw89_debug(rtwdev, RTW89_DBG_TXPWR,
2030 		    "[TXPWR] set txpwr byrate with ch=%d\n", ch);
2031 
2032 	BUILD_BUG_ON(rtw89_rs_idx_max[RTW89_RS_CCK] % 4);
2033 	BUILD_BUG_ON(rtw89_rs_idx_max[RTW89_RS_OFDM] % 4);
2034 	BUILD_BUG_ON(rtw89_rs_idx_max[RTW89_RS_MCS] % 4);
2035 	BUILD_BUG_ON(rtw89_rs_idx_max[RTW89_RS_HEDCM] % 4);
2036 
2037 	addr = R_AX_PWR_BY_RATE;
2038 	for (cur.nss = 0; cur.nss <= RTW89_NSS_2; cur.nss++) {
2039 		for (i = 0; i < ARRAY_SIZE(rs); i++) {
2040 			if (cur.nss >= rtw89_rs_nss_max[rs[i]])
2041 				continue;
2042 
2043 			cur.rs = rs[i];
2044 			for (cur.idx = 0; cur.idx < rtw89_rs_idx_max[rs[i]];
2045 			     cur.idx++) {
2046 				v[cur.idx % 4] =
2047 					rtw89_phy_read_txpwr_byrate(rtwdev,
2048 								    band,
2049 								    &cur);
2050 
2051 				if ((cur.idx + 1) % 4)
2052 					continue;
2053 
2054 				val = FIELD_PREP(GENMASK(7, 0), v[0]) |
2055 				      FIELD_PREP(GENMASK(15, 8), v[1]) |
2056 				      FIELD_PREP(GENMASK(23, 16), v[2]) |
2057 				      FIELD_PREP(GENMASK(31, 24), v[3]);
2058 
2059 				rtw89_mac_txpwr_write32(rtwdev, phy_idx, addr,
2060 							val);
2061 				addr += 4;
2062 			}
2063 		}
2064 	}
2065 }
2066 EXPORT_SYMBOL(rtw89_phy_set_txpwr_byrate);
2067 
2068 void rtw89_phy_set_txpwr_offset(struct rtw89_dev *rtwdev,
2069 				const struct rtw89_chan *chan,
2070 				enum rtw89_phy_idx phy_idx)
2071 {
2072 	struct rtw89_rate_desc desc = {
2073 		.nss = RTW89_NSS_1,
2074 		.rs = RTW89_RS_OFFSET,
2075 	};
2076 	u8 band = chan->band_type;
2077 	s8 v[RTW89_RATE_OFFSET_MAX] = {};
2078 	u32 val;
2079 
2080 	rtw89_debug(rtwdev, RTW89_DBG_TXPWR, "[TXPWR] set txpwr offset\n");
2081 
2082 	for (desc.idx = 0; desc.idx < RTW89_RATE_OFFSET_MAX; desc.idx++)
2083 		v[desc.idx] = rtw89_phy_read_txpwr_byrate(rtwdev, band, &desc);
2084 
2085 	BUILD_BUG_ON(RTW89_RATE_OFFSET_MAX != 5);
2086 	val = FIELD_PREP(GENMASK(3, 0), v[0]) |
2087 	      FIELD_PREP(GENMASK(7, 4), v[1]) |
2088 	      FIELD_PREP(GENMASK(11, 8), v[2]) |
2089 	      FIELD_PREP(GENMASK(15, 12), v[3]) |
2090 	      FIELD_PREP(GENMASK(19, 16), v[4]);
2091 
2092 	rtw89_mac_txpwr_write32_mask(rtwdev, phy_idx, R_AX_PWR_RATE_OFST_CTRL,
2093 				     GENMASK(19, 0), val);
2094 }
2095 EXPORT_SYMBOL(rtw89_phy_set_txpwr_offset);
2096 
2097 void rtw89_phy_set_txpwr_limit(struct rtw89_dev *rtwdev,
2098 			       const struct rtw89_chan *chan,
2099 			       enum rtw89_phy_idx phy_idx)
2100 {
2101 	struct rtw89_txpwr_limit lmt;
2102 	u8 ch = chan->channel;
2103 	u8 bw = chan->band_width;
2104 	const s8 *ptr;
2105 	u32 addr, val;
2106 	u8 i, j;
2107 
2108 	rtw89_debug(rtwdev, RTW89_DBG_TXPWR,
2109 		    "[TXPWR] set txpwr limit with ch=%d bw=%d\n", ch, bw);
2110 
2111 	BUILD_BUG_ON(sizeof(struct rtw89_txpwr_limit) !=
2112 		     RTW89_TXPWR_LMT_PAGE_SIZE);
2113 
2114 	addr = R_AX_PWR_LMT;
2115 	for (i = 0; i < RTW89_NTX_NUM; i++) {
2116 		rtw89_phy_fill_txpwr_limit(rtwdev, chan, &lmt, i);
2117 
2118 		ptr = (s8 *)&lmt;
2119 		for (j = 0; j < RTW89_TXPWR_LMT_PAGE_SIZE;
2120 		     j += 4, addr += 4, ptr += 4) {
2121 			val = FIELD_PREP(GENMASK(7, 0), ptr[0]) |
2122 			      FIELD_PREP(GENMASK(15, 8), ptr[1]) |
2123 			      FIELD_PREP(GENMASK(23, 16), ptr[2]) |
2124 			      FIELD_PREP(GENMASK(31, 24), ptr[3]);
2125 
2126 			rtw89_mac_txpwr_write32(rtwdev, phy_idx, addr, val);
2127 		}
2128 	}
2129 }
2130 EXPORT_SYMBOL(rtw89_phy_set_txpwr_limit);
2131 
2132 void rtw89_phy_set_txpwr_limit_ru(struct rtw89_dev *rtwdev,
2133 				  const struct rtw89_chan *chan,
2134 				  enum rtw89_phy_idx phy_idx)
2135 {
2136 	struct rtw89_txpwr_limit_ru lmt_ru;
2137 	u8 ch = chan->channel;
2138 	u8 bw = chan->band_width;
2139 	const s8 *ptr;
2140 	u32 addr, val;
2141 	u8 i, j;
2142 
2143 	rtw89_debug(rtwdev, RTW89_DBG_TXPWR,
2144 		    "[TXPWR] set txpwr limit ru with ch=%d bw=%d\n", ch, bw);
2145 
2146 	BUILD_BUG_ON(sizeof(struct rtw89_txpwr_limit_ru) !=
2147 		     RTW89_TXPWR_LMT_RU_PAGE_SIZE);
2148 
2149 	addr = R_AX_PWR_RU_LMT;
2150 	for (i = 0; i < RTW89_NTX_NUM; i++) {
2151 		rtw89_phy_fill_txpwr_limit_ru(rtwdev, chan, &lmt_ru, i);
2152 
2153 		ptr = (s8 *)&lmt_ru;
2154 		for (j = 0; j < RTW89_TXPWR_LMT_RU_PAGE_SIZE;
2155 		     j += 4, addr += 4, ptr += 4) {
2156 			val = FIELD_PREP(GENMASK(7, 0), ptr[0]) |
2157 			      FIELD_PREP(GENMASK(15, 8), ptr[1]) |
2158 			      FIELD_PREP(GENMASK(23, 16), ptr[2]) |
2159 			      FIELD_PREP(GENMASK(31, 24), ptr[3]);
2160 
2161 			rtw89_mac_txpwr_write32(rtwdev, phy_idx, addr, val);
2162 		}
2163 	}
2164 }
2165 EXPORT_SYMBOL(rtw89_phy_set_txpwr_limit_ru);
2166 
2167 struct rtw89_phy_iter_ra_data {
2168 	struct rtw89_dev *rtwdev;
2169 	struct sk_buff *c2h;
2170 };
2171 
2172 static void rtw89_phy_c2h_ra_rpt_iter(void *data, struct ieee80211_sta *sta)
2173 {
2174 	struct rtw89_phy_iter_ra_data *ra_data = (struct rtw89_phy_iter_ra_data *)data;
2175 	struct rtw89_dev *rtwdev = ra_data->rtwdev;
2176 	struct rtw89_sta *rtwsta = (struct rtw89_sta *)sta->drv_priv;
2177 	struct rtw89_ra_report *ra_report = &rtwsta->ra_report;
2178 	struct sk_buff *c2h = ra_data->c2h;
2179 	u8 mode, rate, bw, giltf, mac_id;
2180 	u16 legacy_bitrate;
2181 	bool valid;
2182 	u8 mcs = 0;
2183 
2184 	mac_id = RTW89_GET_PHY_C2H_RA_RPT_MACID(c2h->data);
2185 	if (mac_id != rtwsta->mac_id)
2186 		return;
2187 
2188 	rate = RTW89_GET_PHY_C2H_RA_RPT_MCSNSS(c2h->data);
2189 	bw = RTW89_GET_PHY_C2H_RA_RPT_BW(c2h->data);
2190 	giltf = RTW89_GET_PHY_C2H_RA_RPT_GILTF(c2h->data);
2191 	mode = RTW89_GET_PHY_C2H_RA_RPT_MD_SEL(c2h->data);
2192 
2193 	if (mode == RTW89_RA_RPT_MODE_LEGACY) {
2194 		valid = rtw89_ra_report_to_bitrate(rtwdev, rate, &legacy_bitrate);
2195 		if (!valid)
2196 			return;
2197 	}
2198 
2199 	memset(&ra_report->txrate, 0, sizeof(ra_report->txrate));
2200 
2201 	switch (mode) {
2202 	case RTW89_RA_RPT_MODE_LEGACY:
2203 		ra_report->txrate.legacy = legacy_bitrate;
2204 		break;
2205 	case RTW89_RA_RPT_MODE_HT:
2206 		ra_report->txrate.flags |= RATE_INFO_FLAGS_MCS;
2207 		if (RTW89_CHK_FW_FEATURE(OLD_HT_RA_FORMAT, &rtwdev->fw))
2208 			rate = RTW89_MK_HT_RATE(FIELD_GET(RTW89_RA_RATE_MASK_NSS, rate),
2209 						FIELD_GET(RTW89_RA_RATE_MASK_MCS, rate));
2210 		else
2211 			rate = FIELD_GET(RTW89_RA_RATE_MASK_HT_MCS, rate);
2212 		ra_report->txrate.mcs = rate;
2213 		if (giltf)
2214 			ra_report->txrate.flags |= RATE_INFO_FLAGS_SHORT_GI;
2215 		mcs = ra_report->txrate.mcs & 0x07;
2216 		break;
2217 	case RTW89_RA_RPT_MODE_VHT:
2218 		ra_report->txrate.flags |= RATE_INFO_FLAGS_VHT_MCS;
2219 		ra_report->txrate.mcs = FIELD_GET(RTW89_RA_RATE_MASK_MCS, rate);
2220 		ra_report->txrate.nss = FIELD_GET(RTW89_RA_RATE_MASK_NSS, rate) + 1;
2221 		if (giltf)
2222 			ra_report->txrate.flags |= RATE_INFO_FLAGS_SHORT_GI;
2223 		mcs = ra_report->txrate.mcs;
2224 		break;
2225 	case RTW89_RA_RPT_MODE_HE:
2226 		ra_report->txrate.flags |= RATE_INFO_FLAGS_HE_MCS;
2227 		ra_report->txrate.mcs = FIELD_GET(RTW89_RA_RATE_MASK_MCS, rate);
2228 		ra_report->txrate.nss = FIELD_GET(RTW89_RA_RATE_MASK_NSS, rate) + 1;
2229 		if (giltf == RTW89_GILTF_2XHE08 || giltf == RTW89_GILTF_1XHE08)
2230 			ra_report->txrate.he_gi = NL80211_RATE_INFO_HE_GI_0_8;
2231 		else if (giltf == RTW89_GILTF_2XHE16 || giltf == RTW89_GILTF_1XHE16)
2232 			ra_report->txrate.he_gi = NL80211_RATE_INFO_HE_GI_1_6;
2233 		else
2234 			ra_report->txrate.he_gi = NL80211_RATE_INFO_HE_GI_3_2;
2235 		mcs = ra_report->txrate.mcs;
2236 		break;
2237 	}
2238 
2239 	ra_report->txrate.bw = rtw89_hw_to_rate_info_bw(bw);
2240 	ra_report->bit_rate = cfg80211_calculate_bitrate(&ra_report->txrate);
2241 	ra_report->hw_rate = FIELD_PREP(RTW89_HW_RATE_MASK_MOD, mode) |
2242 			     FIELD_PREP(RTW89_HW_RATE_MASK_VAL, rate);
2243 	ra_report->might_fallback_legacy = mcs <= 2;
2244 	sta->deflink.agg.max_rc_amsdu_len = get_max_amsdu_len(rtwdev, ra_report);
2245 	rtwsta->max_agg_wait = sta->deflink.agg.max_rc_amsdu_len / 1500 - 1;
2246 }
2247 
2248 static void
2249 rtw89_phy_c2h_ra_rpt(struct rtw89_dev *rtwdev, struct sk_buff *c2h, u32 len)
2250 {
2251 	struct rtw89_phy_iter_ra_data ra_data;
2252 
2253 	ra_data.rtwdev = rtwdev;
2254 	ra_data.c2h = c2h;
2255 	ieee80211_iterate_stations_atomic(rtwdev->hw,
2256 					  rtw89_phy_c2h_ra_rpt_iter,
2257 					  &ra_data);
2258 }
2259 
2260 static
2261 void (* const rtw89_phy_c2h_ra_handler[])(struct rtw89_dev *rtwdev,
2262 					  struct sk_buff *c2h, u32 len) = {
2263 	[RTW89_PHY_C2H_FUNC_STS_RPT] = rtw89_phy_c2h_ra_rpt,
2264 	[RTW89_PHY_C2H_FUNC_MU_GPTBL_RPT] = NULL,
2265 	[RTW89_PHY_C2H_FUNC_TXSTS] = NULL,
2266 };
2267 
2268 void rtw89_phy_c2h_handle(struct rtw89_dev *rtwdev, struct sk_buff *skb,
2269 			  u32 len, u8 class, u8 func)
2270 {
2271 	void (*handler)(struct rtw89_dev *rtwdev,
2272 			struct sk_buff *c2h, u32 len) = NULL;
2273 
2274 	switch (class) {
2275 	case RTW89_PHY_C2H_CLASS_RA:
2276 		if (func < RTW89_PHY_C2H_FUNC_RA_MAX)
2277 			handler = rtw89_phy_c2h_ra_handler[func];
2278 		break;
2279 	case RTW89_PHY_C2H_CLASS_DM:
2280 		if (func == RTW89_PHY_C2H_DM_FUNC_LOWRT_RTY)
2281 			return;
2282 		fallthrough;
2283 	default:
2284 		rtw89_info(rtwdev, "c2h class %d not support\n", class);
2285 		return;
2286 	}
2287 	if (!handler) {
2288 		rtw89_info(rtwdev, "c2h class %d func %d not support\n", class,
2289 			   func);
2290 		return;
2291 	}
2292 	handler(rtwdev, skb, len);
2293 }
2294 
2295 static u8 rtw89_phy_cfo_get_xcap_reg(struct rtw89_dev *rtwdev, bool sc_xo)
2296 {
2297 	u32 reg_mask;
2298 
2299 	if (sc_xo)
2300 		reg_mask = B_AX_XTAL_SC_XO_MASK;
2301 	else
2302 		reg_mask = B_AX_XTAL_SC_XI_MASK;
2303 
2304 	return (u8)rtw89_read32_mask(rtwdev, R_AX_XTAL_ON_CTRL0, reg_mask);
2305 }
2306 
2307 static void rtw89_phy_cfo_set_xcap_reg(struct rtw89_dev *rtwdev, bool sc_xo,
2308 				       u8 val)
2309 {
2310 	u32 reg_mask;
2311 
2312 	if (sc_xo)
2313 		reg_mask = B_AX_XTAL_SC_XO_MASK;
2314 	else
2315 		reg_mask = B_AX_XTAL_SC_XI_MASK;
2316 
2317 	rtw89_write32_mask(rtwdev, R_AX_XTAL_ON_CTRL0, reg_mask, val);
2318 }
2319 
2320 static void rtw89_phy_cfo_set_crystal_cap(struct rtw89_dev *rtwdev,
2321 					  u8 crystal_cap, bool force)
2322 {
2323 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2324 	const struct rtw89_chip_info *chip = rtwdev->chip;
2325 	u8 sc_xi_val, sc_xo_val;
2326 
2327 	if (!force && cfo->crystal_cap == crystal_cap)
2328 		return;
2329 	crystal_cap = clamp_t(u8, crystal_cap, 0, 127);
2330 	if (chip->chip_id == RTL8852A) {
2331 		rtw89_phy_cfo_set_xcap_reg(rtwdev, true, crystal_cap);
2332 		rtw89_phy_cfo_set_xcap_reg(rtwdev, false, crystal_cap);
2333 		sc_xo_val = rtw89_phy_cfo_get_xcap_reg(rtwdev, true);
2334 		sc_xi_val = rtw89_phy_cfo_get_xcap_reg(rtwdev, false);
2335 	} else {
2336 		rtw89_mac_write_xtal_si(rtwdev, XTAL_SI_XTAL_SC_XO,
2337 					crystal_cap, XTAL_SC_XO_MASK);
2338 		rtw89_mac_write_xtal_si(rtwdev, XTAL_SI_XTAL_SC_XI,
2339 					crystal_cap, XTAL_SC_XI_MASK);
2340 		rtw89_mac_read_xtal_si(rtwdev, XTAL_SI_XTAL_SC_XO, &sc_xo_val);
2341 		rtw89_mac_read_xtal_si(rtwdev, XTAL_SI_XTAL_SC_XI, &sc_xi_val);
2342 	}
2343 	cfo->crystal_cap = sc_xi_val;
2344 	cfo->x_cap_ofst = (s8)((int)cfo->crystal_cap - cfo->def_x_cap);
2345 
2346 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Set sc_xi=0x%x\n", sc_xi_val);
2347 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Set sc_xo=0x%x\n", sc_xo_val);
2348 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Get xcap_ofst=%d\n",
2349 		    cfo->x_cap_ofst);
2350 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Set xcap OK\n");
2351 }
2352 
2353 static void rtw89_phy_cfo_reset(struct rtw89_dev *rtwdev)
2354 {
2355 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2356 	u8 cap;
2357 
2358 	cfo->def_x_cap = cfo->crystal_cap_default & B_AX_XTAL_SC_MASK;
2359 	cfo->is_adjust = false;
2360 	if (cfo->crystal_cap == cfo->def_x_cap)
2361 		return;
2362 	cap = cfo->crystal_cap;
2363 	cap += (cap > cfo->def_x_cap ? -1 : 1);
2364 	rtw89_phy_cfo_set_crystal_cap(rtwdev, cap, false);
2365 	rtw89_debug(rtwdev, RTW89_DBG_CFO,
2366 		    "(0x%x) approach to dflt_val=(0x%x)\n", cfo->crystal_cap,
2367 		    cfo->def_x_cap);
2368 }
2369 
2370 static void rtw89_dcfo_comp(struct rtw89_dev *rtwdev, s32 curr_cfo)
2371 {
2372 	const struct rtw89_reg_def *dcfo_comp = rtwdev->chip->dcfo_comp;
2373 	bool is_linked = rtwdev->total_sta_assoc > 0;
2374 	s32 cfo_avg_312;
2375 	s32 dcfo_comp_val;
2376 	u8 dcfo_comp_sft = rtwdev->chip->dcfo_comp_sft;
2377 	int sign;
2378 
2379 	if (!is_linked) {
2380 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "DCFO: is_linked=%d\n",
2381 			    is_linked);
2382 		return;
2383 	}
2384 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "DCFO: curr_cfo=%d\n", curr_cfo);
2385 	if (curr_cfo == 0)
2386 		return;
2387 	dcfo_comp_val = rtw89_phy_read32_mask(rtwdev, R_DCFO, B_DCFO);
2388 	sign = curr_cfo > 0 ? 1 : -1;
2389 	cfo_avg_312 = (curr_cfo << dcfo_comp_sft) / 5 + sign * dcfo_comp_val;
2390 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "DCFO: avg_cfo=%d\n", cfo_avg_312);
2391 	if (rtwdev->chip->chip_id == RTL8852A && rtwdev->hal.cv == CHIP_CBV)
2392 		cfo_avg_312 = -cfo_avg_312;
2393 	rtw89_phy_set_phy_regs(rtwdev, dcfo_comp->addr, dcfo_comp->mask,
2394 			       cfo_avg_312);
2395 }
2396 
2397 static void rtw89_dcfo_comp_init(struct rtw89_dev *rtwdev)
2398 {
2399 	rtw89_phy_set_phy_regs(rtwdev, R_DCFO_OPT, B_DCFO_OPT_EN, 1);
2400 	rtw89_phy_set_phy_regs(rtwdev, R_DCFO_WEIGHT, B_DCFO_WEIGHT_MSK, 8);
2401 	rtw89_write32_clr(rtwdev, R_AX_PWR_UL_CTRL2, B_AX_PWR_UL_CFO_MASK);
2402 }
2403 
2404 static void rtw89_phy_cfo_init(struct rtw89_dev *rtwdev)
2405 {
2406 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2407 	struct rtw89_efuse *efuse = &rtwdev->efuse;
2408 
2409 	cfo->crystal_cap_default = efuse->xtal_cap & B_AX_XTAL_SC_MASK;
2410 	cfo->crystal_cap = cfo->crystal_cap_default;
2411 	cfo->def_x_cap = cfo->crystal_cap;
2412 	cfo->x_cap_ub = min_t(int, cfo->def_x_cap + CFO_BOUND, 0x7f);
2413 	cfo->x_cap_lb = max_t(int, cfo->def_x_cap - CFO_BOUND, 0x1);
2414 	cfo->is_adjust = false;
2415 	cfo->divergence_lock_en = false;
2416 	cfo->x_cap_ofst = 0;
2417 	cfo->lock_cnt = 0;
2418 	cfo->rtw89_multi_cfo_mode = RTW89_TP_BASED_AVG_MODE;
2419 	cfo->apply_compensation = false;
2420 	cfo->residual_cfo_acc = 0;
2421 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Default xcap=%0x\n",
2422 		    cfo->crystal_cap_default);
2423 	rtw89_phy_cfo_set_crystal_cap(rtwdev, cfo->crystal_cap_default, true);
2424 	rtw89_phy_set_phy_regs(rtwdev, R_DCFO, B_DCFO, 1);
2425 	rtw89_dcfo_comp_init(rtwdev);
2426 	cfo->cfo_timer_ms = 2000;
2427 	cfo->cfo_trig_by_timer_en = false;
2428 	cfo->phy_cfo_trk_cnt = 0;
2429 	cfo->phy_cfo_status = RTW89_PHY_DCFO_STATE_NORMAL;
2430 	cfo->cfo_ul_ofdma_acc_mode = RTW89_CFO_UL_OFDMA_ACC_ENABLE;
2431 }
2432 
2433 static void rtw89_phy_cfo_crystal_cap_adjust(struct rtw89_dev *rtwdev,
2434 					     s32 curr_cfo)
2435 {
2436 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2437 	s8 crystal_cap = cfo->crystal_cap;
2438 	s32 cfo_abs = abs(curr_cfo);
2439 	int sign;
2440 
2441 	if (!cfo->is_adjust) {
2442 		if (cfo_abs > CFO_TRK_ENABLE_TH)
2443 			cfo->is_adjust = true;
2444 	} else {
2445 		if (cfo_abs < CFO_TRK_STOP_TH)
2446 			cfo->is_adjust = false;
2447 	}
2448 	if (!cfo->is_adjust) {
2449 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "Stop CFO tracking\n");
2450 		return;
2451 	}
2452 	sign = curr_cfo > 0 ? 1 : -1;
2453 	if (cfo_abs > CFO_TRK_STOP_TH_4)
2454 		crystal_cap += 7 * sign;
2455 	else if (cfo_abs > CFO_TRK_STOP_TH_3)
2456 		crystal_cap += 5 * sign;
2457 	else if (cfo_abs > CFO_TRK_STOP_TH_2)
2458 		crystal_cap += 3 * sign;
2459 	else if (cfo_abs > CFO_TRK_STOP_TH_1)
2460 		crystal_cap += 1 * sign;
2461 	else
2462 		return;
2463 	rtw89_phy_cfo_set_crystal_cap(rtwdev, (u8)crystal_cap, false);
2464 	rtw89_debug(rtwdev, RTW89_DBG_CFO,
2465 		    "X_cap{Curr,Default}={0x%x,0x%x}\n",
2466 		    cfo->crystal_cap, cfo->def_x_cap);
2467 }
2468 
2469 static s32 rtw89_phy_average_cfo_calc(struct rtw89_dev *rtwdev)
2470 {
2471 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2472 	s32 cfo_khz_all = 0;
2473 	s32 cfo_cnt_all = 0;
2474 	s32 cfo_all_avg = 0;
2475 	u8 i;
2476 
2477 	if (rtwdev->total_sta_assoc != 1)
2478 		return 0;
2479 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "one_entry_only\n");
2480 	for (i = 0; i < CFO_TRACK_MAX_USER; i++) {
2481 		if (cfo->cfo_cnt[i] == 0)
2482 			continue;
2483 		cfo_khz_all += cfo->cfo_tail[i];
2484 		cfo_cnt_all += cfo->cfo_cnt[i];
2485 		cfo_all_avg = phy_div(cfo_khz_all, cfo_cnt_all);
2486 		cfo->pre_cfo_avg[i] = cfo->cfo_avg[i];
2487 	}
2488 	rtw89_debug(rtwdev, RTW89_DBG_CFO,
2489 		    "CFO track for macid = %d\n", i);
2490 	rtw89_debug(rtwdev, RTW89_DBG_CFO,
2491 		    "Total cfo=%dK, pkt_cnt=%d, avg_cfo=%dK\n",
2492 		    cfo_khz_all, cfo_cnt_all, cfo_all_avg);
2493 	return cfo_all_avg;
2494 }
2495 
2496 static s32 rtw89_phy_multi_sta_cfo_calc(struct rtw89_dev *rtwdev)
2497 {
2498 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2499 	struct rtw89_traffic_stats *stats = &rtwdev->stats;
2500 	s32 target_cfo = 0;
2501 	s32 cfo_khz_all = 0;
2502 	s32 cfo_khz_all_tp_wgt = 0;
2503 	s32 cfo_avg = 0;
2504 	s32 max_cfo_lb = BIT(31);
2505 	s32 min_cfo_ub = GENMASK(30, 0);
2506 	u16 cfo_cnt_all = 0;
2507 	u8 active_entry_cnt = 0;
2508 	u8 sta_cnt = 0;
2509 	u32 tp_all = 0;
2510 	u8 i;
2511 	u8 cfo_tol = 0;
2512 
2513 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Multi entry cfo_trk\n");
2514 	if (cfo->rtw89_multi_cfo_mode == RTW89_PKT_BASED_AVG_MODE) {
2515 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "Pkt based avg mode\n");
2516 		for (i = 0; i < CFO_TRACK_MAX_USER; i++) {
2517 			if (cfo->cfo_cnt[i] == 0)
2518 				continue;
2519 			cfo_khz_all += cfo->cfo_tail[i];
2520 			cfo_cnt_all += cfo->cfo_cnt[i];
2521 			cfo_avg = phy_div(cfo_khz_all, (s32)cfo_cnt_all);
2522 			rtw89_debug(rtwdev, RTW89_DBG_CFO,
2523 				    "Msta cfo=%d, pkt_cnt=%d, avg_cfo=%d\n",
2524 				    cfo_khz_all, cfo_cnt_all, cfo_avg);
2525 			target_cfo = cfo_avg;
2526 		}
2527 	} else if (cfo->rtw89_multi_cfo_mode == RTW89_ENTRY_BASED_AVG_MODE) {
2528 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "Entry based avg mode\n");
2529 		for (i = 0; i < CFO_TRACK_MAX_USER; i++) {
2530 			if (cfo->cfo_cnt[i] == 0)
2531 				continue;
2532 			cfo->cfo_avg[i] = phy_div(cfo->cfo_tail[i],
2533 						  (s32)cfo->cfo_cnt[i]);
2534 			cfo_khz_all += cfo->cfo_avg[i];
2535 			rtw89_debug(rtwdev, RTW89_DBG_CFO,
2536 				    "Macid=%d, cfo_avg=%d\n", i,
2537 				    cfo->cfo_avg[i]);
2538 		}
2539 		sta_cnt = rtwdev->total_sta_assoc;
2540 		cfo_avg = phy_div(cfo_khz_all, (s32)sta_cnt);
2541 		rtw89_debug(rtwdev, RTW89_DBG_CFO,
2542 			    "Msta cfo_acc=%d, ent_cnt=%d, avg_cfo=%d\n",
2543 			    cfo_khz_all, sta_cnt, cfo_avg);
2544 		target_cfo = cfo_avg;
2545 	} else if (cfo->rtw89_multi_cfo_mode == RTW89_TP_BASED_AVG_MODE) {
2546 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "TP based avg mode\n");
2547 		cfo_tol = cfo->sta_cfo_tolerance;
2548 		for (i = 0; i < CFO_TRACK_MAX_USER; i++) {
2549 			sta_cnt++;
2550 			if (cfo->cfo_cnt[i] != 0) {
2551 				cfo->cfo_avg[i] = phy_div(cfo->cfo_tail[i],
2552 							  (s32)cfo->cfo_cnt[i]);
2553 				active_entry_cnt++;
2554 			} else {
2555 				cfo->cfo_avg[i] = cfo->pre_cfo_avg[i];
2556 			}
2557 			max_cfo_lb = max(cfo->cfo_avg[i] - cfo_tol, max_cfo_lb);
2558 			min_cfo_ub = min(cfo->cfo_avg[i] + cfo_tol, min_cfo_ub);
2559 			cfo_khz_all += cfo->cfo_avg[i];
2560 			/* need tp for each entry */
2561 			rtw89_debug(rtwdev, RTW89_DBG_CFO,
2562 				    "[%d] cfo_avg=%d, tp=tbd\n",
2563 				    i, cfo->cfo_avg[i]);
2564 			if (sta_cnt >= rtwdev->total_sta_assoc)
2565 				break;
2566 		}
2567 		tp_all = stats->rx_throughput; /* need tp for each entry */
2568 		cfo_avg =  phy_div(cfo_khz_all_tp_wgt, (s32)tp_all);
2569 
2570 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "Assoc sta cnt=%d\n",
2571 			    sta_cnt);
2572 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "Active sta cnt=%d\n",
2573 			    active_entry_cnt);
2574 		rtw89_debug(rtwdev, RTW89_DBG_CFO,
2575 			    "Msta cfo with tp_wgt=%d, avg_cfo=%d\n",
2576 			    cfo_khz_all_tp_wgt, cfo_avg);
2577 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "cfo_lb=%d,cfo_ub=%d\n",
2578 			    max_cfo_lb, min_cfo_ub);
2579 		if (max_cfo_lb <= min_cfo_ub) {
2580 			rtw89_debug(rtwdev, RTW89_DBG_CFO,
2581 				    "cfo win_size=%d\n",
2582 				    min_cfo_ub - max_cfo_lb);
2583 			target_cfo = clamp(cfo_avg, max_cfo_lb, min_cfo_ub);
2584 		} else {
2585 			rtw89_debug(rtwdev, RTW89_DBG_CFO,
2586 				    "No intersection of cfo tolerance windows\n");
2587 			target_cfo = phy_div(cfo_khz_all, (s32)sta_cnt);
2588 		}
2589 		for (i = 0; i < CFO_TRACK_MAX_USER; i++)
2590 			cfo->pre_cfo_avg[i] = cfo->cfo_avg[i];
2591 	}
2592 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Target cfo=%d\n", target_cfo);
2593 	return target_cfo;
2594 }
2595 
2596 static void rtw89_phy_cfo_statistics_reset(struct rtw89_dev *rtwdev)
2597 {
2598 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2599 
2600 	memset(&cfo->cfo_tail, 0, sizeof(cfo->cfo_tail));
2601 	memset(&cfo->cfo_cnt, 0, sizeof(cfo->cfo_cnt));
2602 	cfo->packet_count = 0;
2603 	cfo->packet_count_pre = 0;
2604 	cfo->cfo_avg_pre = 0;
2605 }
2606 
2607 static void rtw89_phy_cfo_dm(struct rtw89_dev *rtwdev)
2608 {
2609 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2610 	s32 new_cfo = 0;
2611 	bool x_cap_update = false;
2612 	u8 pre_x_cap = cfo->crystal_cap;
2613 
2614 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "CFO:total_sta_assoc=%d\n",
2615 		    rtwdev->total_sta_assoc);
2616 	if (rtwdev->total_sta_assoc == 0) {
2617 		rtw89_phy_cfo_reset(rtwdev);
2618 		return;
2619 	}
2620 	if (cfo->packet_count == 0) {
2621 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "Pkt cnt = 0\n");
2622 		return;
2623 	}
2624 	if (cfo->packet_count == cfo->packet_count_pre) {
2625 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "Pkt cnt doesn't change\n");
2626 		return;
2627 	}
2628 	if (rtwdev->total_sta_assoc == 1)
2629 		new_cfo = rtw89_phy_average_cfo_calc(rtwdev);
2630 	else
2631 		new_cfo = rtw89_phy_multi_sta_cfo_calc(rtwdev);
2632 	if (new_cfo == 0) {
2633 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "curr_cfo=0\n");
2634 		return;
2635 	}
2636 	if (cfo->divergence_lock_en) {
2637 		cfo->lock_cnt++;
2638 		if (cfo->lock_cnt > CFO_PERIOD_CNT) {
2639 			cfo->divergence_lock_en = false;
2640 			cfo->lock_cnt = 0;
2641 		} else {
2642 			rtw89_phy_cfo_reset(rtwdev);
2643 		}
2644 		return;
2645 	}
2646 	if (cfo->crystal_cap >= cfo->x_cap_ub ||
2647 	    cfo->crystal_cap <= cfo->x_cap_lb) {
2648 		cfo->divergence_lock_en = true;
2649 		rtw89_phy_cfo_reset(rtwdev);
2650 		return;
2651 	}
2652 
2653 	rtw89_phy_cfo_crystal_cap_adjust(rtwdev, new_cfo);
2654 	cfo->cfo_avg_pre = new_cfo;
2655 	x_cap_update =  cfo->crystal_cap != pre_x_cap;
2656 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Xcap_up=%d\n", x_cap_update);
2657 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Xcap: D:%x C:%x->%x, ofst=%d\n",
2658 		    cfo->def_x_cap, pre_x_cap, cfo->crystal_cap,
2659 		    cfo->x_cap_ofst);
2660 	if (x_cap_update) {
2661 		if (new_cfo > 0)
2662 			new_cfo -= CFO_SW_COMP_FINE_TUNE;
2663 		else
2664 			new_cfo += CFO_SW_COMP_FINE_TUNE;
2665 	}
2666 	rtw89_dcfo_comp(rtwdev, new_cfo);
2667 	rtw89_phy_cfo_statistics_reset(rtwdev);
2668 }
2669 
2670 void rtw89_phy_cfo_track_work(struct work_struct *work)
2671 {
2672 	struct rtw89_dev *rtwdev = container_of(work, struct rtw89_dev,
2673 						cfo_track_work.work);
2674 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2675 
2676 	mutex_lock(&rtwdev->mutex);
2677 	if (!cfo->cfo_trig_by_timer_en)
2678 		goto out;
2679 	rtw89_leave_ps_mode(rtwdev);
2680 	rtw89_phy_cfo_dm(rtwdev);
2681 	ieee80211_queue_delayed_work(rtwdev->hw, &rtwdev->cfo_track_work,
2682 				     msecs_to_jiffies(cfo->cfo_timer_ms));
2683 out:
2684 	mutex_unlock(&rtwdev->mutex);
2685 }
2686 
2687 static void rtw89_phy_cfo_start_work(struct rtw89_dev *rtwdev)
2688 {
2689 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2690 
2691 	ieee80211_queue_delayed_work(rtwdev->hw, &rtwdev->cfo_track_work,
2692 				     msecs_to_jiffies(cfo->cfo_timer_ms));
2693 }
2694 
2695 void rtw89_phy_cfo_track(struct rtw89_dev *rtwdev)
2696 {
2697 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2698 	struct rtw89_traffic_stats *stats = &rtwdev->stats;
2699 	bool is_ul_ofdma = false, ofdma_acc_en = false;
2700 
2701 	if (stats->rx_tf_periodic > CFO_TF_CNT_TH)
2702 		is_ul_ofdma = true;
2703 	if (cfo->cfo_ul_ofdma_acc_mode == RTW89_CFO_UL_OFDMA_ACC_ENABLE &&
2704 	    is_ul_ofdma)
2705 		ofdma_acc_en = true;
2706 
2707 	switch (cfo->phy_cfo_status) {
2708 	case RTW89_PHY_DCFO_STATE_NORMAL:
2709 		if (stats->tx_throughput >= CFO_TP_UPPER) {
2710 			cfo->phy_cfo_status = RTW89_PHY_DCFO_STATE_ENHANCE;
2711 			cfo->cfo_trig_by_timer_en = true;
2712 			cfo->cfo_timer_ms = CFO_COMP_PERIOD;
2713 			rtw89_phy_cfo_start_work(rtwdev);
2714 		}
2715 		break;
2716 	case RTW89_PHY_DCFO_STATE_ENHANCE:
2717 		if (stats->tx_throughput <= CFO_TP_LOWER)
2718 			cfo->phy_cfo_status = RTW89_PHY_DCFO_STATE_NORMAL;
2719 		else if (ofdma_acc_en &&
2720 			 cfo->phy_cfo_trk_cnt >= CFO_PERIOD_CNT)
2721 			cfo->phy_cfo_status = RTW89_PHY_DCFO_STATE_HOLD;
2722 		else
2723 			cfo->phy_cfo_trk_cnt++;
2724 
2725 		if (cfo->phy_cfo_status == RTW89_PHY_DCFO_STATE_NORMAL) {
2726 			cfo->phy_cfo_trk_cnt = 0;
2727 			cfo->cfo_trig_by_timer_en = false;
2728 		}
2729 		break;
2730 	case RTW89_PHY_DCFO_STATE_HOLD:
2731 		if (stats->tx_throughput <= CFO_TP_LOWER) {
2732 			cfo->phy_cfo_status = RTW89_PHY_DCFO_STATE_NORMAL;
2733 			cfo->phy_cfo_trk_cnt = 0;
2734 			cfo->cfo_trig_by_timer_en = false;
2735 		} else {
2736 			cfo->phy_cfo_trk_cnt++;
2737 		}
2738 		break;
2739 	default:
2740 		cfo->phy_cfo_status = RTW89_PHY_DCFO_STATE_NORMAL;
2741 		cfo->phy_cfo_trk_cnt = 0;
2742 		break;
2743 	}
2744 	rtw89_debug(rtwdev, RTW89_DBG_CFO,
2745 		    "[CFO]WatchDog tp=%d,state=%d,timer_en=%d,trk_cnt=%d,thermal=%ld\n",
2746 		    stats->tx_throughput, cfo->phy_cfo_status,
2747 		    cfo->cfo_trig_by_timer_en, cfo->phy_cfo_trk_cnt,
2748 		    ewma_thermal_read(&rtwdev->phystat.avg_thermal[0]));
2749 	if (cfo->cfo_trig_by_timer_en)
2750 		return;
2751 	rtw89_phy_cfo_dm(rtwdev);
2752 }
2753 
2754 void rtw89_phy_cfo_parse(struct rtw89_dev *rtwdev, s16 cfo_val,
2755 			 struct rtw89_rx_phy_ppdu *phy_ppdu)
2756 {
2757 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
2758 	u8 macid = phy_ppdu->mac_id;
2759 
2760 	if (macid >= CFO_TRACK_MAX_USER) {
2761 		rtw89_warn(rtwdev, "mac_id %d is out of range\n", macid);
2762 		return;
2763 	}
2764 
2765 	cfo->cfo_tail[macid] += cfo_val;
2766 	cfo->cfo_cnt[macid]++;
2767 	cfo->packet_count++;
2768 }
2769 
2770 static void rtw89_phy_stat_thermal_update(struct rtw89_dev *rtwdev)
2771 {
2772 	struct rtw89_phy_stat *phystat = &rtwdev->phystat;
2773 	int i;
2774 	u8 th;
2775 
2776 	for (i = 0; i < rtwdev->chip->rf_path_num; i++) {
2777 		th = rtw89_chip_get_thermal(rtwdev, i);
2778 		if (th)
2779 			ewma_thermal_add(&phystat->avg_thermal[i], th);
2780 
2781 		rtw89_debug(rtwdev, RTW89_DBG_RFK_TRACK,
2782 			    "path(%d) thermal cur=%u avg=%ld", i, th,
2783 			    ewma_thermal_read(&phystat->avg_thermal[i]));
2784 	}
2785 }
2786 
2787 struct rtw89_phy_iter_rssi_data {
2788 	struct rtw89_dev *rtwdev;
2789 	struct rtw89_phy_ch_info *ch_info;
2790 	bool rssi_changed;
2791 };
2792 
2793 static void rtw89_phy_stat_rssi_update_iter(void *data,
2794 					    struct ieee80211_sta *sta)
2795 {
2796 	struct rtw89_sta *rtwsta = (struct rtw89_sta *)sta->drv_priv;
2797 	struct rtw89_phy_iter_rssi_data *rssi_data =
2798 					(struct rtw89_phy_iter_rssi_data *)data;
2799 	struct rtw89_phy_ch_info *ch_info = rssi_data->ch_info;
2800 	unsigned long rssi_curr;
2801 
2802 	rssi_curr = ewma_rssi_read(&rtwsta->avg_rssi);
2803 
2804 	if (rssi_curr < ch_info->rssi_min) {
2805 		ch_info->rssi_min = rssi_curr;
2806 		ch_info->rssi_min_macid = rtwsta->mac_id;
2807 	}
2808 
2809 	if (rtwsta->prev_rssi == 0) {
2810 		rtwsta->prev_rssi = rssi_curr;
2811 	} else if (abs((int)rtwsta->prev_rssi - (int)rssi_curr) > (3 << RSSI_FACTOR)) {
2812 		rtwsta->prev_rssi = rssi_curr;
2813 		rssi_data->rssi_changed = true;
2814 	}
2815 }
2816 
2817 static void rtw89_phy_stat_rssi_update(struct rtw89_dev *rtwdev)
2818 {
2819 	struct rtw89_phy_iter_rssi_data rssi_data = {0};
2820 
2821 	rssi_data.rtwdev = rtwdev;
2822 	rssi_data.ch_info = &rtwdev->ch_info;
2823 	rssi_data.ch_info->rssi_min = U8_MAX;
2824 	ieee80211_iterate_stations_atomic(rtwdev->hw,
2825 					  rtw89_phy_stat_rssi_update_iter,
2826 					  &rssi_data);
2827 	if (rssi_data.rssi_changed)
2828 		rtw89_btc_ntfy_wl_sta(rtwdev);
2829 }
2830 
2831 static void rtw89_phy_stat_init(struct rtw89_dev *rtwdev)
2832 {
2833 	struct rtw89_phy_stat *phystat = &rtwdev->phystat;
2834 	int i;
2835 
2836 	for (i = 0; i < rtwdev->chip->rf_path_num; i++)
2837 		ewma_thermal_init(&phystat->avg_thermal[i]);
2838 
2839 	rtw89_phy_stat_thermal_update(rtwdev);
2840 
2841 	memset(&phystat->cur_pkt_stat, 0, sizeof(phystat->cur_pkt_stat));
2842 	memset(&phystat->last_pkt_stat, 0, sizeof(phystat->last_pkt_stat));
2843 }
2844 
2845 void rtw89_phy_stat_track(struct rtw89_dev *rtwdev)
2846 {
2847 	struct rtw89_phy_stat *phystat = &rtwdev->phystat;
2848 
2849 	rtw89_phy_stat_thermal_update(rtwdev);
2850 	rtw89_phy_stat_rssi_update(rtwdev);
2851 
2852 	phystat->last_pkt_stat = phystat->cur_pkt_stat;
2853 	memset(&phystat->cur_pkt_stat, 0, sizeof(phystat->cur_pkt_stat));
2854 }
2855 
2856 static u16 rtw89_phy_ccx_us_to_idx(struct rtw89_dev *rtwdev, u32 time_us)
2857 {
2858 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2859 
2860 	return time_us >> (ilog2(CCX_US_BASE_RATIO) + env->ccx_unit_idx);
2861 }
2862 
2863 static u32 rtw89_phy_ccx_idx_to_us(struct rtw89_dev *rtwdev, u16 idx)
2864 {
2865 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2866 
2867 	return idx << (ilog2(CCX_US_BASE_RATIO) + env->ccx_unit_idx);
2868 }
2869 
2870 static void rtw89_phy_ccx_top_setting_init(struct rtw89_dev *rtwdev)
2871 {
2872 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2873 
2874 	env->ccx_manual_ctrl = false;
2875 	env->ccx_ongoing = false;
2876 	env->ccx_rac_lv = RTW89_RAC_RELEASE;
2877 	env->ccx_rpt_stamp = 0;
2878 	env->ccx_period = 0;
2879 	env->ccx_unit_idx = RTW89_CCX_32_US;
2880 	env->ccx_trigger_time = 0;
2881 	env->ccx_edcca_opt_bw_idx = RTW89_CCX_EDCCA_BW20_0;
2882 
2883 	rtw89_phy_set_phy_regs(rtwdev, R_CCX, B_CCX_EN_MSK, 1);
2884 	rtw89_phy_set_phy_regs(rtwdev, R_CCX, B_CCX_TRIG_OPT_MSK, 1);
2885 	rtw89_phy_set_phy_regs(rtwdev, R_CCX, B_MEASUREMENT_TRIG_MSK, 1);
2886 	rtw89_phy_set_phy_regs(rtwdev, R_CCX, B_CCX_EDCCA_OPT_MSK,
2887 			       RTW89_CCX_EDCCA_BW20_0);
2888 }
2889 
2890 static u16 rtw89_phy_ccx_get_report(struct rtw89_dev *rtwdev, u16 report,
2891 				    u16 score)
2892 {
2893 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2894 	u32 numer = 0;
2895 	u16 ret = 0;
2896 
2897 	numer = report * score + (env->ccx_period >> 1);
2898 	if (env->ccx_period)
2899 		ret = numer / env->ccx_period;
2900 
2901 	return ret >= score ? score - 1 : ret;
2902 }
2903 
2904 static void rtw89_phy_ccx_ms_to_period_unit(struct rtw89_dev *rtwdev,
2905 					    u16 time_ms, u32 *period,
2906 					    u32 *unit_idx)
2907 {
2908 	u32 idx;
2909 	u8 quotient;
2910 
2911 	if (time_ms >= CCX_MAX_PERIOD)
2912 		time_ms = CCX_MAX_PERIOD;
2913 
2914 	quotient = CCX_MAX_PERIOD_UNIT * time_ms / CCX_MAX_PERIOD;
2915 
2916 	if (quotient < 4)
2917 		idx = RTW89_CCX_4_US;
2918 	else if (quotient < 8)
2919 		idx = RTW89_CCX_8_US;
2920 	else if (quotient < 16)
2921 		idx = RTW89_CCX_16_US;
2922 	else
2923 		idx = RTW89_CCX_32_US;
2924 
2925 	*unit_idx = idx;
2926 	*period = (time_ms * MS_TO_4US_RATIO) >> idx;
2927 
2928 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2929 		    "[Trigger Time] period:%d, unit_idx:%d\n",
2930 		    *period, *unit_idx);
2931 }
2932 
2933 static void rtw89_phy_ccx_racing_release(struct rtw89_dev *rtwdev)
2934 {
2935 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2936 
2937 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2938 		    "lv:(%d)->(0)\n", env->ccx_rac_lv);
2939 
2940 	env->ccx_ongoing = false;
2941 	env->ccx_rac_lv = RTW89_RAC_RELEASE;
2942 	env->ifs_clm_app = RTW89_IFS_CLM_BACKGROUND;
2943 }
2944 
2945 static bool rtw89_phy_ifs_clm_th_update_check(struct rtw89_dev *rtwdev,
2946 					      struct rtw89_ccx_para_info *para)
2947 {
2948 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2949 	bool is_update = env->ifs_clm_app != para->ifs_clm_app;
2950 	u8 i = 0;
2951 	u16 *ifs_th_l = env->ifs_clm_th_l;
2952 	u16 *ifs_th_h = env->ifs_clm_th_h;
2953 	u32 ifs_th0_us = 0, ifs_th_times = 0;
2954 	u32 ifs_th_h_us[RTW89_IFS_CLM_NUM] = {0};
2955 
2956 	if (!is_update)
2957 		goto ifs_update_finished;
2958 
2959 	switch (para->ifs_clm_app) {
2960 	case RTW89_IFS_CLM_INIT:
2961 	case RTW89_IFS_CLM_BACKGROUND:
2962 	case RTW89_IFS_CLM_ACS:
2963 	case RTW89_IFS_CLM_DBG:
2964 	case RTW89_IFS_CLM_DIG:
2965 	case RTW89_IFS_CLM_TDMA_DIG:
2966 		ifs_th0_us = IFS_CLM_TH0_UPPER;
2967 		ifs_th_times = IFS_CLM_TH_MUL;
2968 		break;
2969 	case RTW89_IFS_CLM_DBG_MANUAL:
2970 		ifs_th0_us = para->ifs_clm_manual_th0;
2971 		ifs_th_times = para->ifs_clm_manual_th_times;
2972 		break;
2973 	default:
2974 		break;
2975 	}
2976 
2977 	/* Set sampling threshold for 4 different regions, unit in idx_cnt.
2978 	 * low[i] = high[i-1] + 1
2979 	 * high[i] = high[i-1] * ifs_th_times
2980 	 */
2981 	ifs_th_l[IFS_CLM_TH_START_IDX] = 0;
2982 	ifs_th_h_us[IFS_CLM_TH_START_IDX] = ifs_th0_us;
2983 	ifs_th_h[IFS_CLM_TH_START_IDX] = rtw89_phy_ccx_us_to_idx(rtwdev,
2984 								 ifs_th0_us);
2985 	for (i = 1; i < RTW89_IFS_CLM_NUM; i++) {
2986 		ifs_th_l[i] = ifs_th_h[i - 1] + 1;
2987 		ifs_th_h_us[i] = ifs_th_h_us[i - 1] * ifs_th_times;
2988 		ifs_th_h[i] = rtw89_phy_ccx_us_to_idx(rtwdev, ifs_th_h_us[i]);
2989 	}
2990 
2991 ifs_update_finished:
2992 	if (!is_update)
2993 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2994 			    "No need to update IFS_TH\n");
2995 
2996 	return is_update;
2997 }
2998 
2999 static void rtw89_phy_ifs_clm_set_th_reg(struct rtw89_dev *rtwdev)
3000 {
3001 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
3002 	u8 i = 0;
3003 
3004 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T1, B_IFS_T1_TH_LOW_MSK,
3005 			       env->ifs_clm_th_l[0]);
3006 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T2, B_IFS_T2_TH_LOW_MSK,
3007 			       env->ifs_clm_th_l[1]);
3008 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T3, B_IFS_T3_TH_LOW_MSK,
3009 			       env->ifs_clm_th_l[2]);
3010 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T4, B_IFS_T4_TH_LOW_MSK,
3011 			       env->ifs_clm_th_l[3]);
3012 
3013 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T1, B_IFS_T1_TH_HIGH_MSK,
3014 			       env->ifs_clm_th_h[0]);
3015 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T2, B_IFS_T2_TH_HIGH_MSK,
3016 			       env->ifs_clm_th_h[1]);
3017 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T3, B_IFS_T3_TH_HIGH_MSK,
3018 			       env->ifs_clm_th_h[2]);
3019 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T4, B_IFS_T4_TH_HIGH_MSK,
3020 			       env->ifs_clm_th_h[3]);
3021 
3022 	for (i = 0; i < RTW89_IFS_CLM_NUM; i++)
3023 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3024 			    "Update IFS_T%d_th{low, high} : {%d, %d}\n",
3025 			    i + 1, env->ifs_clm_th_l[i], env->ifs_clm_th_h[i]);
3026 }
3027 
3028 static void rtw89_phy_ifs_clm_setting_init(struct rtw89_dev *rtwdev)
3029 {
3030 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
3031 	struct rtw89_ccx_para_info para = {0};
3032 
3033 	env->ifs_clm_app = RTW89_IFS_CLM_BACKGROUND;
3034 	env->ifs_clm_mntr_time = 0;
3035 
3036 	para.ifs_clm_app = RTW89_IFS_CLM_INIT;
3037 	if (rtw89_phy_ifs_clm_th_update_check(rtwdev, &para))
3038 		rtw89_phy_ifs_clm_set_th_reg(rtwdev);
3039 
3040 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_COUNTER, B_IFS_COLLECT_EN,
3041 			       true);
3042 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T1, B_IFS_T1_EN_MSK, true);
3043 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T2, B_IFS_T2_EN_MSK, true);
3044 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T3, B_IFS_T3_EN_MSK, true);
3045 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T4, B_IFS_T4_EN_MSK, true);
3046 }
3047 
3048 static int rtw89_phy_ccx_racing_ctrl(struct rtw89_dev *rtwdev,
3049 				     enum rtw89_env_racing_lv level)
3050 {
3051 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
3052 	int ret = 0;
3053 
3054 	if (level >= RTW89_RAC_MAX_NUM) {
3055 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3056 			    "[WARNING] Wrong LV=%d\n", level);
3057 		return -EINVAL;
3058 	}
3059 
3060 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3061 		    "ccx_ongoing=%d, level:(%d)->(%d)\n", env->ccx_ongoing,
3062 		    env->ccx_rac_lv, level);
3063 
3064 	if (env->ccx_ongoing) {
3065 		if (level <= env->ccx_rac_lv)
3066 			ret = -EINVAL;
3067 		else
3068 			env->ccx_ongoing = false;
3069 	}
3070 
3071 	if (ret == 0)
3072 		env->ccx_rac_lv = level;
3073 
3074 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK, "ccx racing success=%d\n",
3075 		    !ret);
3076 
3077 	return ret;
3078 }
3079 
3080 static void rtw89_phy_ccx_trigger(struct rtw89_dev *rtwdev)
3081 {
3082 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
3083 
3084 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_COUNTER, B_IFS_COUNTER_CLR_MSK, 0);
3085 	rtw89_phy_set_phy_regs(rtwdev, R_CCX, B_MEASUREMENT_TRIG_MSK, 0);
3086 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_COUNTER, B_IFS_COUNTER_CLR_MSK, 1);
3087 	rtw89_phy_set_phy_regs(rtwdev, R_CCX, B_MEASUREMENT_TRIG_MSK, 1);
3088 
3089 	env->ccx_rpt_stamp++;
3090 	env->ccx_ongoing = true;
3091 }
3092 
3093 static void rtw89_phy_ifs_clm_get_utility(struct rtw89_dev *rtwdev)
3094 {
3095 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
3096 	u8 i = 0;
3097 	u32 res = 0;
3098 
3099 	env->ifs_clm_tx_ratio =
3100 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_tx, PERCENT);
3101 	env->ifs_clm_edcca_excl_cca_ratio =
3102 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_edcca_excl_cca,
3103 					 PERCENT);
3104 	env->ifs_clm_cck_fa_ratio =
3105 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_cckfa, PERCENT);
3106 	env->ifs_clm_ofdm_fa_ratio =
3107 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_ofdmfa, PERCENT);
3108 	env->ifs_clm_cck_cca_excl_fa_ratio =
3109 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_cckcca_excl_fa,
3110 					 PERCENT);
3111 	env->ifs_clm_ofdm_cca_excl_fa_ratio =
3112 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_ofdmcca_excl_fa,
3113 					 PERCENT);
3114 	env->ifs_clm_cck_fa_permil =
3115 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_cckfa, PERMIL);
3116 	env->ifs_clm_ofdm_fa_permil =
3117 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_ofdmfa, PERMIL);
3118 
3119 	for (i = 0; i < RTW89_IFS_CLM_NUM; i++) {
3120 		if (env->ifs_clm_his[i] > ENV_MNTR_IFSCLM_HIS_MAX) {
3121 			env->ifs_clm_ifs_avg[i] = ENV_MNTR_FAIL_DWORD;
3122 		} else {
3123 			env->ifs_clm_ifs_avg[i] =
3124 				rtw89_phy_ccx_idx_to_us(rtwdev,
3125 							env->ifs_clm_avg[i]);
3126 		}
3127 
3128 		res = rtw89_phy_ccx_idx_to_us(rtwdev, env->ifs_clm_cca[i]);
3129 		res += env->ifs_clm_his[i] >> 1;
3130 		if (env->ifs_clm_his[i])
3131 			res /= env->ifs_clm_his[i];
3132 		else
3133 			res = 0;
3134 		env->ifs_clm_cca_avg[i] = res;
3135 	}
3136 
3137 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3138 		    "IFS-CLM ratio {Tx, EDCCA_exclu_cca} = {%d, %d}\n",
3139 		    env->ifs_clm_tx_ratio, env->ifs_clm_edcca_excl_cca_ratio);
3140 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3141 		    "IFS-CLM FA ratio {CCK, OFDM} = {%d, %d}\n",
3142 		    env->ifs_clm_cck_fa_ratio, env->ifs_clm_ofdm_fa_ratio);
3143 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3144 		    "IFS-CLM FA permil {CCK, OFDM} = {%d, %d}\n",
3145 		    env->ifs_clm_cck_fa_permil, env->ifs_clm_ofdm_fa_permil);
3146 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3147 		    "IFS-CLM CCA_exclu_FA ratio {CCK, OFDM} = {%d, %d}\n",
3148 		    env->ifs_clm_cck_cca_excl_fa_ratio,
3149 		    env->ifs_clm_ofdm_cca_excl_fa_ratio);
3150 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3151 		    "Time:[his, ifs_avg(us), cca_avg(us)]\n");
3152 	for (i = 0; i < RTW89_IFS_CLM_NUM; i++)
3153 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK, "T%d:[%d, %d, %d]\n",
3154 			    i + 1, env->ifs_clm_his[i], env->ifs_clm_ifs_avg[i],
3155 			    env->ifs_clm_cca_avg[i]);
3156 }
3157 
3158 static bool rtw89_phy_ifs_clm_get_result(struct rtw89_dev *rtwdev)
3159 {
3160 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
3161 	u8 i = 0;
3162 
3163 	if (rtw89_phy_read32_mask(rtwdev, R_IFSCNT, B_IFSCNT_DONE_MSK) == 0) {
3164 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3165 			    "Get IFS_CLM report Fail\n");
3166 		return false;
3167 	}
3168 
3169 	env->ifs_clm_tx =
3170 		rtw89_phy_read32_mask(rtwdev, R_IFS_CLM_TX_CNT,
3171 				      B_IFS_CLM_TX_CNT_MSK);
3172 	env->ifs_clm_edcca_excl_cca =
3173 		rtw89_phy_read32_mask(rtwdev, R_IFS_CLM_TX_CNT,
3174 				      B_IFS_CLM_EDCCA_EXCLUDE_CCA_FA_MSK);
3175 	env->ifs_clm_cckcca_excl_fa =
3176 		rtw89_phy_read32_mask(rtwdev, R_IFS_CLM_CCA,
3177 				      B_IFS_CLM_CCKCCA_EXCLUDE_FA_MSK);
3178 	env->ifs_clm_ofdmcca_excl_fa =
3179 		rtw89_phy_read32_mask(rtwdev, R_IFS_CLM_CCA,
3180 				      B_IFS_CLM_OFDMCCA_EXCLUDE_FA_MSK);
3181 	env->ifs_clm_cckfa =
3182 		rtw89_phy_read32_mask(rtwdev, R_IFS_CLM_FA,
3183 				      B_IFS_CLM_CCK_FA_MSK);
3184 	env->ifs_clm_ofdmfa =
3185 		rtw89_phy_read32_mask(rtwdev, R_IFS_CLM_FA,
3186 				      B_IFS_CLM_OFDM_FA_MSK);
3187 
3188 	env->ifs_clm_his[0] =
3189 		rtw89_phy_read32_mask(rtwdev, R_IFS_HIS, B_IFS_T1_HIS_MSK);
3190 	env->ifs_clm_his[1] =
3191 		rtw89_phy_read32_mask(rtwdev, R_IFS_HIS, B_IFS_T2_HIS_MSK);
3192 	env->ifs_clm_his[2] =
3193 		rtw89_phy_read32_mask(rtwdev, R_IFS_HIS, B_IFS_T3_HIS_MSK);
3194 	env->ifs_clm_his[3] =
3195 		rtw89_phy_read32_mask(rtwdev, R_IFS_HIS, B_IFS_T4_HIS_MSK);
3196 
3197 	env->ifs_clm_avg[0] =
3198 		rtw89_phy_read32_mask(rtwdev, R_IFS_AVG_L, B_IFS_T1_AVG_MSK);
3199 	env->ifs_clm_avg[1] =
3200 		rtw89_phy_read32_mask(rtwdev, R_IFS_AVG_L, B_IFS_T2_AVG_MSK);
3201 	env->ifs_clm_avg[2] =
3202 		rtw89_phy_read32_mask(rtwdev, R_IFS_AVG_H, B_IFS_T3_AVG_MSK);
3203 	env->ifs_clm_avg[3] =
3204 		rtw89_phy_read32_mask(rtwdev, R_IFS_AVG_H, B_IFS_T4_AVG_MSK);
3205 
3206 	env->ifs_clm_cca[0] =
3207 		rtw89_phy_read32_mask(rtwdev, R_IFS_CCA_L, B_IFS_T1_CCA_MSK);
3208 	env->ifs_clm_cca[1] =
3209 		rtw89_phy_read32_mask(rtwdev, R_IFS_CCA_L, B_IFS_T2_CCA_MSK);
3210 	env->ifs_clm_cca[2] =
3211 		rtw89_phy_read32_mask(rtwdev, R_IFS_CCA_H, B_IFS_T3_CCA_MSK);
3212 	env->ifs_clm_cca[3] =
3213 		rtw89_phy_read32_mask(rtwdev, R_IFS_CCA_H, B_IFS_T4_CCA_MSK);
3214 
3215 	env->ifs_clm_total_ifs =
3216 		rtw89_phy_read32_mask(rtwdev, R_IFSCNT, B_IFSCNT_TOTAL_CNT_MSK);
3217 
3218 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK, "IFS-CLM total_ifs = %d\n",
3219 		    env->ifs_clm_total_ifs);
3220 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3221 		    "{Tx, EDCCA_exclu_cca} = {%d, %d}\n",
3222 		    env->ifs_clm_tx, env->ifs_clm_edcca_excl_cca);
3223 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3224 		    "IFS-CLM FA{CCK, OFDM} = {%d, %d}\n",
3225 		    env->ifs_clm_cckfa, env->ifs_clm_ofdmfa);
3226 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3227 		    "IFS-CLM CCA_exclu_FA{CCK, OFDM} = {%d, %d}\n",
3228 		    env->ifs_clm_cckcca_excl_fa, env->ifs_clm_ofdmcca_excl_fa);
3229 
3230 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK, "Time:[his, avg, cca]\n");
3231 	for (i = 0; i < RTW89_IFS_CLM_NUM; i++)
3232 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3233 			    "T%d:[%d, %d, %d]\n", i + 1, env->ifs_clm_his[i],
3234 			    env->ifs_clm_avg[i], env->ifs_clm_cca[i]);
3235 
3236 	rtw89_phy_ifs_clm_get_utility(rtwdev);
3237 
3238 	return true;
3239 }
3240 
3241 static int rtw89_phy_ifs_clm_set(struct rtw89_dev *rtwdev,
3242 				 struct rtw89_ccx_para_info *para)
3243 {
3244 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
3245 	u32 period = 0;
3246 	u32 unit_idx = 0;
3247 
3248 	if (para->mntr_time == 0) {
3249 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3250 			    "[WARN] MNTR_TIME is 0\n");
3251 		return -EINVAL;
3252 	}
3253 
3254 	if (rtw89_phy_ccx_racing_ctrl(rtwdev, para->rac_lv))
3255 		return -EINVAL;
3256 
3257 	if (para->mntr_time != env->ifs_clm_mntr_time) {
3258 		rtw89_phy_ccx_ms_to_period_unit(rtwdev, para->mntr_time,
3259 						&period, &unit_idx);
3260 		rtw89_phy_set_phy_regs(rtwdev, R_IFS_COUNTER,
3261 				       B_IFS_CLM_PERIOD_MSK, period);
3262 		rtw89_phy_set_phy_regs(rtwdev, R_IFS_COUNTER,
3263 				       B_IFS_CLM_COUNTER_UNIT_MSK, unit_idx);
3264 
3265 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3266 			    "Update IFS-CLM time ((%d)) -> ((%d))\n",
3267 			    env->ifs_clm_mntr_time, para->mntr_time);
3268 
3269 		env->ifs_clm_mntr_time = para->mntr_time;
3270 		env->ccx_period = (u16)period;
3271 		env->ccx_unit_idx = (u8)unit_idx;
3272 	}
3273 
3274 	if (rtw89_phy_ifs_clm_th_update_check(rtwdev, para)) {
3275 		env->ifs_clm_app = para->ifs_clm_app;
3276 		rtw89_phy_ifs_clm_set_th_reg(rtwdev);
3277 	}
3278 
3279 	return 0;
3280 }
3281 
3282 void rtw89_phy_env_monitor_track(struct rtw89_dev *rtwdev)
3283 {
3284 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
3285 	struct rtw89_ccx_para_info para = {0};
3286 	u8 chk_result = RTW89_PHY_ENV_MON_CCX_FAIL;
3287 
3288 	env->ccx_watchdog_result = RTW89_PHY_ENV_MON_CCX_FAIL;
3289 	if (env->ccx_manual_ctrl) {
3290 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3291 			    "CCX in manual ctrl\n");
3292 		return;
3293 	}
3294 
3295 	/* only ifs_clm for now */
3296 	if (rtw89_phy_ifs_clm_get_result(rtwdev))
3297 		env->ccx_watchdog_result |= RTW89_PHY_ENV_MON_IFS_CLM;
3298 
3299 	rtw89_phy_ccx_racing_release(rtwdev);
3300 	para.mntr_time = 1900;
3301 	para.rac_lv = RTW89_RAC_LV_1;
3302 	para.ifs_clm_app = RTW89_IFS_CLM_BACKGROUND;
3303 
3304 	if (rtw89_phy_ifs_clm_set(rtwdev, &para) == 0)
3305 		chk_result |= RTW89_PHY_ENV_MON_IFS_CLM;
3306 	if (chk_result)
3307 		rtw89_phy_ccx_trigger(rtwdev);
3308 
3309 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
3310 		    "get_result=0x%x, chk_result:0x%x\n",
3311 		    env->ccx_watchdog_result, chk_result);
3312 }
3313 
3314 static bool rtw89_physts_ie_page_valid(enum rtw89_phy_status_bitmap *ie_page)
3315 {
3316 	if (*ie_page > RTW89_PHYSTS_BITMAP_NUM ||
3317 	    *ie_page == RTW89_RSVD_9)
3318 		return false;
3319 	else if (*ie_page > RTW89_RSVD_9)
3320 		*ie_page -= 1;
3321 
3322 	return true;
3323 }
3324 
3325 static u32 rtw89_phy_get_ie_bitmap_addr(enum rtw89_phy_status_bitmap ie_page)
3326 {
3327 	static const u8 ie_page_shift = 2;
3328 
3329 	return R_PHY_STS_BITMAP_ADDR_START + (ie_page << ie_page_shift);
3330 }
3331 
3332 static u32 rtw89_physts_get_ie_bitmap(struct rtw89_dev *rtwdev,
3333 				      enum rtw89_phy_status_bitmap ie_page)
3334 {
3335 	u32 addr;
3336 
3337 	if (!rtw89_physts_ie_page_valid(&ie_page))
3338 		return 0;
3339 
3340 	addr = rtw89_phy_get_ie_bitmap_addr(ie_page);
3341 
3342 	return rtw89_phy_read32(rtwdev, addr);
3343 }
3344 
3345 static void rtw89_physts_set_ie_bitmap(struct rtw89_dev *rtwdev,
3346 				       enum rtw89_phy_status_bitmap ie_page,
3347 				       u32 val)
3348 {
3349 	const struct rtw89_chip_info *chip = rtwdev->chip;
3350 	u32 addr;
3351 
3352 	if (!rtw89_physts_ie_page_valid(&ie_page))
3353 		return;
3354 
3355 	if (chip->chip_id == RTL8852A)
3356 		val &= B_PHY_STS_BITMAP_MSK_52A;
3357 
3358 	addr = rtw89_phy_get_ie_bitmap_addr(ie_page);
3359 	rtw89_phy_write32(rtwdev, addr, val);
3360 }
3361 
3362 static void rtw89_physts_enable_ie_bitmap(struct rtw89_dev *rtwdev,
3363 					  enum rtw89_phy_status_bitmap bitmap,
3364 					  enum rtw89_phy_status_ie_type ie,
3365 					  bool enable)
3366 {
3367 	u32 val = rtw89_physts_get_ie_bitmap(rtwdev, bitmap);
3368 
3369 	if (enable)
3370 		val |= BIT(ie);
3371 	else
3372 		val &= ~BIT(ie);
3373 
3374 	rtw89_physts_set_ie_bitmap(rtwdev, bitmap, val);
3375 }
3376 
3377 static void rtw89_physts_enable_fail_report(struct rtw89_dev *rtwdev,
3378 					    bool enable,
3379 					    enum rtw89_phy_idx phy_idx)
3380 {
3381 	if (enable) {
3382 		rtw89_phy_write32_clr(rtwdev, R_PLCP_HISTOGRAM,
3383 				      B_STS_DIS_TRIG_BY_FAIL);
3384 		rtw89_phy_write32_clr(rtwdev, R_PLCP_HISTOGRAM,
3385 				      B_STS_DIS_TRIG_BY_BRK);
3386 	} else {
3387 		rtw89_phy_write32_set(rtwdev, R_PLCP_HISTOGRAM,
3388 				      B_STS_DIS_TRIG_BY_FAIL);
3389 		rtw89_phy_write32_set(rtwdev, R_PLCP_HISTOGRAM,
3390 				      B_STS_DIS_TRIG_BY_BRK);
3391 	}
3392 }
3393 
3394 static void rtw89_physts_parsing_init(struct rtw89_dev *rtwdev)
3395 {
3396 	u8 i;
3397 
3398 	rtw89_physts_enable_fail_report(rtwdev, false, RTW89_PHY_0);
3399 
3400 	for (i = 0; i < RTW89_PHYSTS_BITMAP_NUM; i++) {
3401 		if (i >= RTW89_CCK_PKT)
3402 			rtw89_physts_enable_ie_bitmap(rtwdev, i,
3403 						      RTW89_PHYSTS_IE09_FTR_0,
3404 						      true);
3405 		if ((i >= RTW89_CCK_BRK && i <= RTW89_VHT_MU) ||
3406 		    (i >= RTW89_RSVD_9 && i <= RTW89_CCK_PKT))
3407 			continue;
3408 		rtw89_physts_enable_ie_bitmap(rtwdev, i,
3409 					      RTW89_PHYSTS_IE24_OFDM_TD_PATH_A,
3410 					      true);
3411 	}
3412 	rtw89_physts_enable_ie_bitmap(rtwdev, RTW89_VHT_PKT,
3413 				      RTW89_PHYSTS_IE13_DL_MU_DEF, true);
3414 	rtw89_physts_enable_ie_bitmap(rtwdev, RTW89_HE_PKT,
3415 				      RTW89_PHYSTS_IE13_DL_MU_DEF, true);
3416 
3417 	/* force IE01 for channel index, only channel field is valid */
3418 	rtw89_physts_enable_ie_bitmap(rtwdev, RTW89_CCK_PKT,
3419 				      RTW89_PHYSTS_IE01_CMN_OFDM, true);
3420 }
3421 
3422 static void rtw89_phy_dig_read_gain_table(struct rtw89_dev *rtwdev, int type)
3423 {
3424 	const struct rtw89_chip_info *chip = rtwdev->chip;
3425 	struct rtw89_dig_info *dig = &rtwdev->dig;
3426 	const struct rtw89_phy_dig_gain_cfg *cfg;
3427 	const char *msg;
3428 	u8 i;
3429 	s8 gain_base;
3430 	s8 *gain_arr;
3431 	u32 tmp;
3432 
3433 	switch (type) {
3434 	case RTW89_DIG_GAIN_LNA_G:
3435 		gain_arr = dig->lna_gain_g;
3436 		gain_base = LNA0_GAIN;
3437 		cfg = chip->dig_table->cfg_lna_g;
3438 		msg = "lna_gain_g";
3439 		break;
3440 	case RTW89_DIG_GAIN_TIA_G:
3441 		gain_arr = dig->tia_gain_g;
3442 		gain_base = TIA0_GAIN_G;
3443 		cfg = chip->dig_table->cfg_tia_g;
3444 		msg = "tia_gain_g";
3445 		break;
3446 	case RTW89_DIG_GAIN_LNA_A:
3447 		gain_arr = dig->lna_gain_a;
3448 		gain_base = LNA0_GAIN;
3449 		cfg = chip->dig_table->cfg_lna_a;
3450 		msg = "lna_gain_a";
3451 		break;
3452 	case RTW89_DIG_GAIN_TIA_A:
3453 		gain_arr = dig->tia_gain_a;
3454 		gain_base = TIA0_GAIN_A;
3455 		cfg = chip->dig_table->cfg_tia_a;
3456 		msg = "tia_gain_a";
3457 		break;
3458 	default:
3459 		return;
3460 	}
3461 
3462 	for (i = 0; i < cfg->size; i++) {
3463 		tmp = rtw89_phy_read32_mask(rtwdev, cfg->table[i].addr,
3464 					    cfg->table[i].mask);
3465 		tmp >>= DIG_GAIN_SHIFT;
3466 		gain_arr[i] = sign_extend32(tmp, U4_MAX_BIT) + gain_base;
3467 		gain_base += DIG_GAIN;
3468 
3469 		rtw89_debug(rtwdev, RTW89_DBG_DIG, "%s[%d]=%d\n",
3470 			    msg, i, gain_arr[i]);
3471 	}
3472 }
3473 
3474 static void rtw89_phy_dig_update_gain_para(struct rtw89_dev *rtwdev)
3475 {
3476 	struct rtw89_dig_info *dig = &rtwdev->dig;
3477 	u32 tmp;
3478 	u8 i;
3479 
3480 	if (!rtwdev->hal.support_igi)
3481 		return;
3482 
3483 	tmp = rtw89_phy_read32_mask(rtwdev, R_PATH0_IB_PKPW,
3484 				    B_PATH0_IB_PKPW_MSK);
3485 	dig->ib_pkpwr = sign_extend32(tmp >> DIG_GAIN_SHIFT, U8_MAX_BIT);
3486 	dig->ib_pbk = rtw89_phy_read32_mask(rtwdev, R_PATH0_IB_PBK,
3487 					    B_PATH0_IB_PBK_MSK);
3488 	rtw89_debug(rtwdev, RTW89_DBG_DIG, "ib_pkpwr=%d, ib_pbk=%d\n",
3489 		    dig->ib_pkpwr, dig->ib_pbk);
3490 
3491 	for (i = RTW89_DIG_GAIN_LNA_G; i < RTW89_DIG_GAIN_MAX; i++)
3492 		rtw89_phy_dig_read_gain_table(rtwdev, i);
3493 }
3494 
3495 static const u8 rssi_nolink = 22;
3496 static const u8 igi_rssi_th[IGI_RSSI_TH_NUM] = {68, 84, 90, 98, 104};
3497 static const u16 fa_th_2g[FA_TH_NUM] = {22, 44, 66, 88};
3498 static const u16 fa_th_5g[FA_TH_NUM] = {4, 8, 12, 16};
3499 static const u16 fa_th_nolink[FA_TH_NUM] = {196, 352, 440, 528};
3500 
3501 static void rtw89_phy_dig_update_rssi_info(struct rtw89_dev *rtwdev)
3502 {
3503 	struct rtw89_phy_ch_info *ch_info = &rtwdev->ch_info;
3504 	struct rtw89_dig_info *dig = &rtwdev->dig;
3505 	bool is_linked = rtwdev->total_sta_assoc > 0;
3506 
3507 	if (is_linked) {
3508 		dig->igi_rssi = ch_info->rssi_min >> 1;
3509 	} else {
3510 		rtw89_debug(rtwdev, RTW89_DBG_DIG, "RSSI update : NO Link\n");
3511 		dig->igi_rssi = rssi_nolink;
3512 	}
3513 }
3514 
3515 static void rtw89_phy_dig_update_para(struct rtw89_dev *rtwdev)
3516 {
3517 	struct rtw89_dig_info *dig = &rtwdev->dig;
3518 	const struct rtw89_chan *chan = rtw89_chan_get(rtwdev, RTW89_SUB_ENTITY_0);
3519 	bool is_linked = rtwdev->total_sta_assoc > 0;
3520 	const u16 *fa_th_src = NULL;
3521 
3522 	switch (chan->band_type) {
3523 	case RTW89_BAND_2G:
3524 		dig->lna_gain = dig->lna_gain_g;
3525 		dig->tia_gain = dig->tia_gain_g;
3526 		fa_th_src = is_linked ? fa_th_2g : fa_th_nolink;
3527 		dig->force_gaincode_idx_en = false;
3528 		dig->dyn_pd_th_en = true;
3529 		break;
3530 	case RTW89_BAND_5G:
3531 	default:
3532 		dig->lna_gain = dig->lna_gain_a;
3533 		dig->tia_gain = dig->tia_gain_a;
3534 		fa_th_src = is_linked ? fa_th_5g : fa_th_nolink;
3535 		dig->force_gaincode_idx_en = true;
3536 		dig->dyn_pd_th_en = true;
3537 		break;
3538 	}
3539 	memcpy(dig->fa_th, fa_th_src, sizeof(dig->fa_th));
3540 	memcpy(dig->igi_rssi_th, igi_rssi_th, sizeof(dig->igi_rssi_th));
3541 }
3542 
3543 static const u8 pd_low_th_offset = 20, dynamic_igi_min = 0x20;
3544 static const u8 igi_max_performance_mode = 0x5a;
3545 static const u8 dynamic_pd_threshold_max;
3546 
3547 static void rtw89_phy_dig_para_reset(struct rtw89_dev *rtwdev)
3548 {
3549 	struct rtw89_dig_info *dig = &rtwdev->dig;
3550 
3551 	dig->cur_gaincode.lna_idx = LNA_IDX_MAX;
3552 	dig->cur_gaincode.tia_idx = TIA_IDX_MAX;
3553 	dig->cur_gaincode.rxb_idx = RXB_IDX_MAX;
3554 	dig->force_gaincode.lna_idx = LNA_IDX_MAX;
3555 	dig->force_gaincode.tia_idx = TIA_IDX_MAX;
3556 	dig->force_gaincode.rxb_idx = RXB_IDX_MAX;
3557 
3558 	dig->dyn_igi_max = igi_max_performance_mode;
3559 	dig->dyn_igi_min = dynamic_igi_min;
3560 	dig->dyn_pd_th_max = dynamic_pd_threshold_max;
3561 	dig->pd_low_th_ofst = pd_low_th_offset;
3562 	dig->is_linked_pre = false;
3563 }
3564 
3565 static void rtw89_phy_dig_init(struct rtw89_dev *rtwdev)
3566 {
3567 	rtw89_phy_dig_update_gain_para(rtwdev);
3568 	rtw89_phy_dig_reset(rtwdev);
3569 }
3570 
3571 static u8 rtw89_phy_dig_lna_idx_by_rssi(struct rtw89_dev *rtwdev, u8 rssi)
3572 {
3573 	struct rtw89_dig_info *dig = &rtwdev->dig;
3574 	u8 lna_idx;
3575 
3576 	if (rssi < dig->igi_rssi_th[0])
3577 		lna_idx = RTW89_DIG_GAIN_LNA_IDX6;
3578 	else if (rssi < dig->igi_rssi_th[1])
3579 		lna_idx = RTW89_DIG_GAIN_LNA_IDX5;
3580 	else if (rssi < dig->igi_rssi_th[2])
3581 		lna_idx = RTW89_DIG_GAIN_LNA_IDX4;
3582 	else if (rssi < dig->igi_rssi_th[3])
3583 		lna_idx = RTW89_DIG_GAIN_LNA_IDX3;
3584 	else if (rssi < dig->igi_rssi_th[4])
3585 		lna_idx = RTW89_DIG_GAIN_LNA_IDX2;
3586 	else
3587 		lna_idx = RTW89_DIG_GAIN_LNA_IDX1;
3588 
3589 	return lna_idx;
3590 }
3591 
3592 static u8 rtw89_phy_dig_tia_idx_by_rssi(struct rtw89_dev *rtwdev, u8 rssi)
3593 {
3594 	struct rtw89_dig_info *dig = &rtwdev->dig;
3595 	u8 tia_idx;
3596 
3597 	if (rssi < dig->igi_rssi_th[0])
3598 		tia_idx = RTW89_DIG_GAIN_TIA_IDX1;
3599 	else
3600 		tia_idx = RTW89_DIG_GAIN_TIA_IDX0;
3601 
3602 	return tia_idx;
3603 }
3604 
3605 #define IB_PBK_BASE 110
3606 #define WB_RSSI_BASE 10
3607 static u8 rtw89_phy_dig_rxb_idx_by_rssi(struct rtw89_dev *rtwdev, u8 rssi,
3608 					struct rtw89_agc_gaincode_set *set)
3609 {
3610 	struct rtw89_dig_info *dig = &rtwdev->dig;
3611 	s8 lna_gain = dig->lna_gain[set->lna_idx];
3612 	s8 tia_gain = dig->tia_gain[set->tia_idx];
3613 	s32 wb_rssi = rssi + lna_gain + tia_gain;
3614 	s32 rxb_idx_tmp = IB_PBK_BASE + WB_RSSI_BASE;
3615 	u8 rxb_idx;
3616 
3617 	rxb_idx_tmp += dig->ib_pkpwr - dig->ib_pbk - wb_rssi;
3618 	rxb_idx = clamp_t(s32, rxb_idx_tmp, RXB_IDX_MIN, RXB_IDX_MAX);
3619 
3620 	rtw89_debug(rtwdev, RTW89_DBG_DIG, "wb_rssi=%03d, rxb_idx_tmp=%03d\n",
3621 		    wb_rssi, rxb_idx_tmp);
3622 
3623 	return rxb_idx;
3624 }
3625 
3626 static void rtw89_phy_dig_gaincode_by_rssi(struct rtw89_dev *rtwdev, u8 rssi,
3627 					   struct rtw89_agc_gaincode_set *set)
3628 {
3629 	set->lna_idx = rtw89_phy_dig_lna_idx_by_rssi(rtwdev, rssi);
3630 	set->tia_idx = rtw89_phy_dig_tia_idx_by_rssi(rtwdev, rssi);
3631 	set->rxb_idx = rtw89_phy_dig_rxb_idx_by_rssi(rtwdev, rssi, set);
3632 
3633 	rtw89_debug(rtwdev, RTW89_DBG_DIG,
3634 		    "final_rssi=%03d, (lna,tia,rab)=(%d,%d,%02d)\n",
3635 		    rssi, set->lna_idx, set->tia_idx, set->rxb_idx);
3636 }
3637 
3638 #define IGI_OFFSET_MAX 25
3639 #define IGI_OFFSET_MUL 2
3640 static void rtw89_phy_dig_igi_offset_by_env(struct rtw89_dev *rtwdev)
3641 {
3642 	struct rtw89_dig_info *dig = &rtwdev->dig;
3643 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
3644 	enum rtw89_dig_noisy_level noisy_lv;
3645 	u8 igi_offset = dig->fa_rssi_ofst;
3646 	u16 fa_ratio = 0;
3647 
3648 	fa_ratio = env->ifs_clm_cck_fa_permil + env->ifs_clm_ofdm_fa_permil;
3649 
3650 	if (fa_ratio < dig->fa_th[0])
3651 		noisy_lv = RTW89_DIG_NOISY_LEVEL0;
3652 	else if (fa_ratio < dig->fa_th[1])
3653 		noisy_lv = RTW89_DIG_NOISY_LEVEL1;
3654 	else if (fa_ratio < dig->fa_th[2])
3655 		noisy_lv = RTW89_DIG_NOISY_LEVEL2;
3656 	else if (fa_ratio < dig->fa_th[3])
3657 		noisy_lv = RTW89_DIG_NOISY_LEVEL3;
3658 	else
3659 		noisy_lv = RTW89_DIG_NOISY_LEVEL_MAX;
3660 
3661 	if (noisy_lv == RTW89_DIG_NOISY_LEVEL0 && igi_offset < 2)
3662 		igi_offset = 0;
3663 	else
3664 		igi_offset += noisy_lv * IGI_OFFSET_MUL;
3665 
3666 	igi_offset = min_t(u8, igi_offset, IGI_OFFSET_MAX);
3667 	dig->fa_rssi_ofst = igi_offset;
3668 
3669 	rtw89_debug(rtwdev, RTW89_DBG_DIG,
3670 		    "fa_th: [+6 (%d) +4 (%d) +2 (%d) 0 (%d) -2 ]\n",
3671 		    dig->fa_th[3], dig->fa_th[2], dig->fa_th[1], dig->fa_th[0]);
3672 
3673 	rtw89_debug(rtwdev, RTW89_DBG_DIG,
3674 		    "fa(CCK,OFDM,ALL)=(%d,%d,%d)%%, noisy_lv=%d, ofst=%d\n",
3675 		    env->ifs_clm_cck_fa_permil, env->ifs_clm_ofdm_fa_permil,
3676 		    env->ifs_clm_cck_fa_permil + env->ifs_clm_ofdm_fa_permil,
3677 		    noisy_lv, igi_offset);
3678 }
3679 
3680 static void rtw89_phy_dig_set_lna_idx(struct rtw89_dev *rtwdev, u8 lna_idx)
3681 {
3682 	const struct rtw89_dig_regs *dig_regs = rtwdev->chip->dig_regs;
3683 
3684 	rtw89_phy_write32_mask(rtwdev, dig_regs->p0_lna_init.addr,
3685 			       dig_regs->p0_lna_init.mask, lna_idx);
3686 	rtw89_phy_write32_mask(rtwdev, dig_regs->p1_lna_init.addr,
3687 			       dig_regs->p1_lna_init.mask, lna_idx);
3688 }
3689 
3690 static void rtw89_phy_dig_set_tia_idx(struct rtw89_dev *rtwdev, u8 tia_idx)
3691 {
3692 	const struct rtw89_dig_regs *dig_regs = rtwdev->chip->dig_regs;
3693 
3694 	rtw89_phy_write32_mask(rtwdev, dig_regs->p0_tia_init.addr,
3695 			       dig_regs->p0_tia_init.mask, tia_idx);
3696 	rtw89_phy_write32_mask(rtwdev, dig_regs->p1_tia_init.addr,
3697 			       dig_regs->p1_tia_init.mask, tia_idx);
3698 }
3699 
3700 static void rtw89_phy_dig_set_rxb_idx(struct rtw89_dev *rtwdev, u8 rxb_idx)
3701 {
3702 	const struct rtw89_dig_regs *dig_regs = rtwdev->chip->dig_regs;
3703 
3704 	rtw89_phy_write32_mask(rtwdev, dig_regs->p0_rxb_init.addr,
3705 			       dig_regs->p0_rxb_init.mask, rxb_idx);
3706 	rtw89_phy_write32_mask(rtwdev, dig_regs->p1_rxb_init.addr,
3707 			       dig_regs->p1_rxb_init.mask, rxb_idx);
3708 }
3709 
3710 static void rtw89_phy_dig_set_igi_cr(struct rtw89_dev *rtwdev,
3711 				     const struct rtw89_agc_gaincode_set set)
3712 {
3713 	rtw89_phy_dig_set_lna_idx(rtwdev, set.lna_idx);
3714 	rtw89_phy_dig_set_tia_idx(rtwdev, set.tia_idx);
3715 	rtw89_phy_dig_set_rxb_idx(rtwdev, set.rxb_idx);
3716 
3717 	rtw89_debug(rtwdev, RTW89_DBG_DIG, "Set (lna,tia,rxb)=((%d,%d,%02d))\n",
3718 		    set.lna_idx, set.tia_idx, set.rxb_idx);
3719 }
3720 
3721 static void rtw89_phy_dig_sdagc_follow_pagc_config(struct rtw89_dev *rtwdev,
3722 						   bool enable)
3723 {
3724 	const struct rtw89_dig_regs *dig_regs = rtwdev->chip->dig_regs;
3725 
3726 	rtw89_phy_write32_mask(rtwdev, dig_regs->p0_p20_pagcugc_en.addr,
3727 			       dig_regs->p0_p20_pagcugc_en.mask, enable);
3728 	rtw89_phy_write32_mask(rtwdev, dig_regs->p0_s20_pagcugc_en.addr,
3729 			       dig_regs->p0_s20_pagcugc_en.mask, enable);
3730 	rtw89_phy_write32_mask(rtwdev, dig_regs->p1_p20_pagcugc_en.addr,
3731 			       dig_regs->p1_p20_pagcugc_en.mask, enable);
3732 	rtw89_phy_write32_mask(rtwdev, dig_regs->p1_s20_pagcugc_en.addr,
3733 			       dig_regs->p1_s20_pagcugc_en.mask, enable);
3734 
3735 	rtw89_debug(rtwdev, RTW89_DBG_DIG, "sdagc_follow_pagc=%d\n", enable);
3736 }
3737 
3738 static void rtw89_phy_dig_config_igi(struct rtw89_dev *rtwdev)
3739 {
3740 	struct rtw89_dig_info *dig = &rtwdev->dig;
3741 
3742 	if (!rtwdev->hal.support_igi)
3743 		return;
3744 
3745 	if (dig->force_gaincode_idx_en) {
3746 		rtw89_phy_dig_set_igi_cr(rtwdev, dig->force_gaincode);
3747 		rtw89_debug(rtwdev, RTW89_DBG_DIG,
3748 			    "Force gaincode index enabled.\n");
3749 	} else {
3750 		rtw89_phy_dig_gaincode_by_rssi(rtwdev, dig->igi_fa_rssi,
3751 					       &dig->cur_gaincode);
3752 		rtw89_phy_dig_set_igi_cr(rtwdev, dig->cur_gaincode);
3753 	}
3754 }
3755 
3756 static void rtw89_phy_dig_dyn_pd_th(struct rtw89_dev *rtwdev, u8 rssi,
3757 				    bool enable)
3758 {
3759 	const struct rtw89_chan *chan = rtw89_chan_get(rtwdev, RTW89_SUB_ENTITY_0);
3760 	const struct rtw89_dig_regs *dig_regs = rtwdev->chip->dig_regs;
3761 	enum rtw89_bandwidth cbw = chan->band_width;
3762 	struct rtw89_dig_info *dig = &rtwdev->dig;
3763 	u8 final_rssi = 0, under_region = dig->pd_low_th_ofst;
3764 	u8 ofdm_cca_th;
3765 	s8 cck_cca_th;
3766 	u32 pd_val = 0;
3767 
3768 	under_region += PD_TH_SB_FLTR_CMP_VAL;
3769 
3770 	switch (cbw) {
3771 	case RTW89_CHANNEL_WIDTH_40:
3772 		under_region += PD_TH_BW40_CMP_VAL;
3773 		break;
3774 	case RTW89_CHANNEL_WIDTH_80:
3775 		under_region += PD_TH_BW80_CMP_VAL;
3776 		break;
3777 	case RTW89_CHANNEL_WIDTH_160:
3778 		under_region += PD_TH_BW160_CMP_VAL;
3779 		break;
3780 	case RTW89_CHANNEL_WIDTH_20:
3781 		fallthrough;
3782 	default:
3783 		under_region += PD_TH_BW20_CMP_VAL;
3784 		break;
3785 	}
3786 
3787 	dig->dyn_pd_th_max = dig->igi_rssi;
3788 
3789 	final_rssi = min_t(u8, rssi, dig->igi_rssi);
3790 	ofdm_cca_th = clamp_t(u8, final_rssi, PD_TH_MIN_RSSI + under_region,
3791 			      PD_TH_MAX_RSSI + under_region);
3792 
3793 	if (enable) {
3794 		pd_val = (ofdm_cca_th - under_region - PD_TH_MIN_RSSI) >> 1;
3795 		rtw89_debug(rtwdev, RTW89_DBG_DIG,
3796 			    "igi=%d, ofdm_ccaTH=%d, backoff=%d, PD_low=%d\n",
3797 			    final_rssi, ofdm_cca_th, under_region, pd_val);
3798 	} else {
3799 		rtw89_debug(rtwdev, RTW89_DBG_DIG,
3800 			    "Dynamic PD th disabled, Set PD_low_bd=0\n");
3801 	}
3802 
3803 	rtw89_phy_write32_mask(rtwdev, dig_regs->seg0_pd_reg,
3804 			       dig_regs->pd_lower_bound_mask, pd_val);
3805 	rtw89_phy_write32_mask(rtwdev, dig_regs->seg0_pd_reg,
3806 			       dig_regs->pd_spatial_reuse_en, enable);
3807 
3808 	if (!rtwdev->hal.support_cckpd)
3809 		return;
3810 
3811 	cck_cca_th = max_t(s8, final_rssi - under_region, CCKPD_TH_MIN_RSSI);
3812 	pd_val = (u32)(cck_cca_th - IGI_RSSI_MAX);
3813 
3814 	rtw89_debug(rtwdev, RTW89_DBG_DIG,
3815 		    "igi=%d, cck_ccaTH=%d, backoff=%d, cck_PD_low=((%d))dB\n",
3816 		    final_rssi, cck_cca_th, under_region, pd_val);
3817 
3818 	rtw89_phy_write32_mask(rtwdev, R_BMODE_PDTH_EN_V1,
3819 			       B_BMODE_PDTH_LIMIT_EN_MSK_V1, enable);
3820 	rtw89_phy_write32_mask(rtwdev, R_BMODE_PDTH_V1,
3821 			       B_BMODE_PDTH_LOWER_BOUND_MSK_V1, pd_val);
3822 }
3823 
3824 void rtw89_phy_dig_reset(struct rtw89_dev *rtwdev)
3825 {
3826 	struct rtw89_dig_info *dig = &rtwdev->dig;
3827 
3828 	dig->bypass_dig = false;
3829 	rtw89_phy_dig_para_reset(rtwdev);
3830 	rtw89_phy_dig_set_igi_cr(rtwdev, dig->force_gaincode);
3831 	rtw89_phy_dig_dyn_pd_th(rtwdev, rssi_nolink, false);
3832 	rtw89_phy_dig_sdagc_follow_pagc_config(rtwdev, false);
3833 	rtw89_phy_dig_update_para(rtwdev);
3834 }
3835 
3836 #define IGI_RSSI_MIN 10
3837 void rtw89_phy_dig(struct rtw89_dev *rtwdev)
3838 {
3839 	struct rtw89_dig_info *dig = &rtwdev->dig;
3840 	bool is_linked = rtwdev->total_sta_assoc > 0;
3841 
3842 	if (unlikely(dig->bypass_dig)) {
3843 		dig->bypass_dig = false;
3844 		return;
3845 	}
3846 
3847 	if (!dig->is_linked_pre && is_linked) {
3848 		rtw89_debug(rtwdev, RTW89_DBG_DIG, "First connected\n");
3849 		rtw89_phy_dig_update_para(rtwdev);
3850 	} else if (dig->is_linked_pre && !is_linked) {
3851 		rtw89_debug(rtwdev, RTW89_DBG_DIG, "First disconnected\n");
3852 		rtw89_phy_dig_update_para(rtwdev);
3853 	}
3854 	dig->is_linked_pre = is_linked;
3855 
3856 	rtw89_phy_dig_igi_offset_by_env(rtwdev);
3857 	rtw89_phy_dig_update_rssi_info(rtwdev);
3858 
3859 	dig->dyn_igi_min = (dig->igi_rssi > IGI_RSSI_MIN) ?
3860 			    dig->igi_rssi - IGI_RSSI_MIN : 0;
3861 	dig->dyn_igi_max = dig->dyn_igi_min + IGI_OFFSET_MAX;
3862 	dig->igi_fa_rssi = dig->dyn_igi_min + dig->fa_rssi_ofst;
3863 
3864 	dig->igi_fa_rssi = clamp(dig->igi_fa_rssi, dig->dyn_igi_min,
3865 				 dig->dyn_igi_max);
3866 
3867 	rtw89_debug(rtwdev, RTW89_DBG_DIG,
3868 		    "rssi=%03d, dyn(max,min)=(%d,%d), final_rssi=%d\n",
3869 		    dig->igi_rssi, dig->dyn_igi_max, dig->dyn_igi_min,
3870 		    dig->igi_fa_rssi);
3871 
3872 	rtw89_phy_dig_config_igi(rtwdev);
3873 
3874 	rtw89_phy_dig_dyn_pd_th(rtwdev, dig->igi_fa_rssi, dig->dyn_pd_th_en);
3875 
3876 	if (dig->dyn_pd_th_en && dig->igi_fa_rssi > dig->dyn_pd_th_max)
3877 		rtw89_phy_dig_sdagc_follow_pagc_config(rtwdev, true);
3878 	else
3879 		rtw89_phy_dig_sdagc_follow_pagc_config(rtwdev, false);
3880 }
3881 
3882 static void rtw89_phy_tx_path_div_sta_iter(void *data, struct ieee80211_sta *sta)
3883 {
3884 	struct rtw89_sta *rtwsta = (struct rtw89_sta *)sta->drv_priv;
3885 	struct rtw89_dev *rtwdev = rtwsta->rtwdev;
3886 	struct rtw89_vif *rtwvif = rtwsta->rtwvif;
3887 	struct rtw89_hal *hal = &rtwdev->hal;
3888 	bool *done = data;
3889 	u8 rssi_a, rssi_b;
3890 	u32 candidate;
3891 
3892 	if (rtwvif->wifi_role != RTW89_WIFI_ROLE_STATION || sta->tdls)
3893 		return;
3894 
3895 	if (*done)
3896 		return;
3897 
3898 	*done = true;
3899 
3900 	rssi_a = ewma_rssi_read(&rtwsta->rssi[RF_PATH_A]);
3901 	rssi_b = ewma_rssi_read(&rtwsta->rssi[RF_PATH_B]);
3902 
3903 	if (rssi_a > rssi_b + RTW89_TX_DIV_RSSI_RAW_TH)
3904 		candidate = RF_A;
3905 	else if (rssi_b > rssi_a + RTW89_TX_DIV_RSSI_RAW_TH)
3906 		candidate = RF_B;
3907 	else
3908 		return;
3909 
3910 	if (hal->antenna_tx == candidate)
3911 		return;
3912 
3913 	hal->antenna_tx = candidate;
3914 	rtw89_fw_h2c_txpath_cmac_tbl(rtwdev, rtwsta);
3915 
3916 	if (hal->antenna_tx == RF_A) {
3917 		rtw89_phy_write32_mask(rtwdev, R_P0_RFMODE, B_P0_RFMODE_MUX, 0x12);
3918 		rtw89_phy_write32_mask(rtwdev, R_P1_RFMODE, B_P1_RFMODE_MUX, 0x11);
3919 	} else if (hal->antenna_tx == RF_B) {
3920 		rtw89_phy_write32_mask(rtwdev, R_P0_RFMODE, B_P0_RFMODE_MUX, 0x11);
3921 		rtw89_phy_write32_mask(rtwdev, R_P1_RFMODE, B_P1_RFMODE_MUX, 0x12);
3922 	}
3923 }
3924 
3925 void rtw89_phy_tx_path_div_track(struct rtw89_dev *rtwdev)
3926 {
3927 	struct rtw89_hal *hal = &rtwdev->hal;
3928 	bool done = false;
3929 
3930 	if (!hal->tx_path_diversity)
3931 		return;
3932 
3933 	ieee80211_iterate_stations_atomic(rtwdev->hw,
3934 					  rtw89_phy_tx_path_div_sta_iter,
3935 					  &done);
3936 }
3937 
3938 static void rtw89_phy_env_monitor_init(struct rtw89_dev *rtwdev)
3939 {
3940 	rtw89_phy_ccx_top_setting_init(rtwdev);
3941 	rtw89_phy_ifs_clm_setting_init(rtwdev);
3942 }
3943 
3944 void rtw89_phy_dm_init(struct rtw89_dev *rtwdev)
3945 {
3946 	const struct rtw89_chip_info *chip = rtwdev->chip;
3947 
3948 	rtw89_phy_stat_init(rtwdev);
3949 
3950 	rtw89_chip_bb_sethw(rtwdev);
3951 
3952 	rtw89_phy_env_monitor_init(rtwdev);
3953 	rtw89_physts_parsing_init(rtwdev);
3954 	rtw89_phy_dig_init(rtwdev);
3955 	rtw89_phy_cfo_init(rtwdev);
3956 
3957 	rtw89_phy_init_rf_nctl(rtwdev);
3958 	rtw89_chip_rfk_init(rtwdev);
3959 	rtw89_load_txpwr_table(rtwdev, chip->byr_table);
3960 	rtw89_chip_set_txpwr_ctrl(rtwdev);
3961 	rtw89_chip_power_trim(rtwdev);
3962 	rtw89_chip_cfg_txrx_path(rtwdev);
3963 }
3964 
3965 void rtw89_phy_set_bss_color(struct rtw89_dev *rtwdev, struct ieee80211_vif *vif)
3966 {
3967 	enum rtw89_phy_idx phy_idx = RTW89_PHY_0;
3968 	u8 bss_color;
3969 
3970 	if (!vif->bss_conf.he_support || !vif->cfg.assoc)
3971 		return;
3972 
3973 	bss_color = vif->bss_conf.he_bss_color.color;
3974 
3975 	rtw89_phy_write32_idx(rtwdev, R_BSS_CLR_MAP, B_BSS_CLR_MAP_VLD0, 0x1,
3976 			      phy_idx);
3977 	rtw89_phy_write32_idx(rtwdev, R_BSS_CLR_MAP, B_BSS_CLR_MAP_TGT, bss_color,
3978 			      phy_idx);
3979 	rtw89_phy_write32_idx(rtwdev, R_BSS_CLR_MAP, B_BSS_CLR_MAP_STAID,
3980 			      vif->cfg.aid, phy_idx);
3981 }
3982 
3983 static void
3984 _rfk_write_rf(struct rtw89_dev *rtwdev, const struct rtw89_reg5_def *def)
3985 {
3986 	rtw89_write_rf(rtwdev, def->path, def->addr, def->mask, def->data);
3987 }
3988 
3989 static void
3990 _rfk_write32_mask(struct rtw89_dev *rtwdev, const struct rtw89_reg5_def *def)
3991 {
3992 	rtw89_phy_write32_mask(rtwdev, def->addr, def->mask, def->data);
3993 }
3994 
3995 static void
3996 _rfk_write32_set(struct rtw89_dev *rtwdev, const struct rtw89_reg5_def *def)
3997 {
3998 	rtw89_phy_write32_set(rtwdev, def->addr, def->mask);
3999 }
4000 
4001 static void
4002 _rfk_write32_clr(struct rtw89_dev *rtwdev, const struct rtw89_reg5_def *def)
4003 {
4004 	rtw89_phy_write32_clr(rtwdev, def->addr, def->mask);
4005 }
4006 
4007 static void
4008 _rfk_delay(struct rtw89_dev *rtwdev, const struct rtw89_reg5_def *def)
4009 {
4010 	udelay(def->data);
4011 }
4012 
4013 static void
4014 (*_rfk_handler[])(struct rtw89_dev *rtwdev, const struct rtw89_reg5_def *def) = {
4015 	[RTW89_RFK_F_WRF] = _rfk_write_rf,
4016 	[RTW89_RFK_F_WM] = _rfk_write32_mask,
4017 	[RTW89_RFK_F_WS] = _rfk_write32_set,
4018 	[RTW89_RFK_F_WC] = _rfk_write32_clr,
4019 	[RTW89_RFK_F_DELAY] = _rfk_delay,
4020 };
4021 
4022 static_assert(ARRAY_SIZE(_rfk_handler) == RTW89_RFK_F_NUM);
4023 
4024 void
4025 rtw89_rfk_parser(struct rtw89_dev *rtwdev, const struct rtw89_rfk_tbl *tbl)
4026 {
4027 	const struct rtw89_reg5_def *p = tbl->defs;
4028 	const struct rtw89_reg5_def *end = tbl->defs + tbl->size;
4029 
4030 	for (; p < end; p++)
4031 		_rfk_handler[p->flag](rtwdev, p);
4032 }
4033 EXPORT_SYMBOL(rtw89_rfk_parser);
4034 
4035 #define RTW89_TSSI_FAST_MODE_NUM 4
4036 
4037 static const struct rtw89_reg_def rtw89_tssi_fastmode_regs_flat[RTW89_TSSI_FAST_MODE_NUM] = {
4038 	{0xD934, 0xff0000},
4039 	{0xD934, 0xff000000},
4040 	{0xD938, 0xff},
4041 	{0xD934, 0xff00},
4042 };
4043 
4044 static const struct rtw89_reg_def rtw89_tssi_fastmode_regs_level[RTW89_TSSI_FAST_MODE_NUM] = {
4045 	{0xD930, 0xff0000},
4046 	{0xD930, 0xff000000},
4047 	{0xD934, 0xff},
4048 	{0xD930, 0xff00},
4049 };
4050 
4051 static
4052 void rtw89_phy_tssi_ctrl_set_fast_mode_cfg(struct rtw89_dev *rtwdev,
4053 					   enum rtw89_mac_idx mac_idx,
4054 					   enum rtw89_tssi_bandedge_cfg bandedge_cfg,
4055 					   u32 val)
4056 {
4057 	const struct rtw89_reg_def *regs;
4058 	u32 reg;
4059 	int i;
4060 
4061 	if (bandedge_cfg == RTW89_TSSI_BANDEDGE_FLAT)
4062 		regs = rtw89_tssi_fastmode_regs_flat;
4063 	else
4064 		regs = rtw89_tssi_fastmode_regs_level;
4065 
4066 	for (i = 0; i < RTW89_TSSI_FAST_MODE_NUM; i++) {
4067 		reg = rtw89_mac_reg_by_idx(regs[i].addr, mac_idx);
4068 		rtw89_write32_mask(rtwdev, reg, regs[i].mask, val);
4069 	}
4070 }
4071 
4072 static const struct rtw89_reg_def rtw89_tssi_bandedge_regs_flat[RTW89_TSSI_SBW_NUM] = {
4073 	{0xD91C, 0xff000000},
4074 	{0xD920, 0xff},
4075 	{0xD920, 0xff00},
4076 	{0xD920, 0xff0000},
4077 	{0xD920, 0xff000000},
4078 	{0xD924, 0xff},
4079 	{0xD924, 0xff00},
4080 	{0xD914, 0xff000000},
4081 	{0xD918, 0xff},
4082 	{0xD918, 0xff00},
4083 	{0xD918, 0xff0000},
4084 	{0xD918, 0xff000000},
4085 	{0xD91C, 0xff},
4086 	{0xD91C, 0xff00},
4087 	{0xD91C, 0xff0000},
4088 };
4089 
4090 static const struct rtw89_reg_def rtw89_tssi_bandedge_regs_level[RTW89_TSSI_SBW_NUM] = {
4091 	{0xD910, 0xff},
4092 	{0xD910, 0xff00},
4093 	{0xD910, 0xff0000},
4094 	{0xD910, 0xff000000},
4095 	{0xD914, 0xff},
4096 	{0xD914, 0xff00},
4097 	{0xD914, 0xff0000},
4098 	{0xD908, 0xff},
4099 	{0xD908, 0xff00},
4100 	{0xD908, 0xff0000},
4101 	{0xD908, 0xff000000},
4102 	{0xD90C, 0xff},
4103 	{0xD90C, 0xff00},
4104 	{0xD90C, 0xff0000},
4105 	{0xD90C, 0xff000000},
4106 };
4107 
4108 void rtw89_phy_tssi_ctrl_set_bandedge_cfg(struct rtw89_dev *rtwdev,
4109 					  enum rtw89_mac_idx mac_idx,
4110 					  enum rtw89_tssi_bandedge_cfg bandedge_cfg)
4111 {
4112 	const struct rtw89_chip_info *chip = rtwdev->chip;
4113 	const struct rtw89_reg_def *regs;
4114 	const u32 *data;
4115 	u32 reg;
4116 	int i;
4117 
4118 	if (bandedge_cfg >= RTW89_TSSI_CFG_NUM)
4119 		return;
4120 
4121 	if (bandedge_cfg == RTW89_TSSI_BANDEDGE_FLAT)
4122 		regs = rtw89_tssi_bandedge_regs_flat;
4123 	else
4124 		regs = rtw89_tssi_bandedge_regs_level;
4125 
4126 	data = chip->tssi_dbw_table->data[bandedge_cfg];
4127 
4128 	for (i = 0; i < RTW89_TSSI_SBW_NUM; i++) {
4129 		reg = rtw89_mac_reg_by_idx(regs[i].addr, mac_idx);
4130 		rtw89_write32_mask(rtwdev, reg, regs[i].mask, data[i]);
4131 	}
4132 
4133 	reg = rtw89_mac_reg_by_idx(R_AX_BANDEDGE_CFG, mac_idx);
4134 	rtw89_write32_mask(rtwdev, reg, B_AX_BANDEDGE_CFG_IDX_MASK, bandedge_cfg);
4135 
4136 	rtw89_phy_tssi_ctrl_set_fast_mode_cfg(rtwdev, mac_idx, bandedge_cfg,
4137 					      data[RTW89_TSSI_SBW20]);
4138 }
4139 EXPORT_SYMBOL(rtw89_phy_tssi_ctrl_set_bandedge_cfg);
4140