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 "phy.h"
8 #include "ps.h"
9 #include "reg.h"
10 #include "sar.h"
11 #include "coex.h"
12 
13 static u16 get_max_amsdu_len(struct rtw89_dev *rtwdev,
14 			     const struct rtw89_ra_report *report)
15 {
16 	const struct rate_info *txrate = &report->txrate;
17 	u32 bit_rate = report->bit_rate;
18 	u8 mcs;
19 
20 	/* lower than ofdm, do not aggregate */
21 	if (bit_rate < 550)
22 		return 1;
23 
24 	/* prevent hardware rate fallback to G mode rate */
25 	if (txrate->flags & RATE_INFO_FLAGS_MCS)
26 		mcs = txrate->mcs & 0x07;
27 	else if (txrate->flags & (RATE_INFO_FLAGS_VHT_MCS | RATE_INFO_FLAGS_HE_MCS))
28 		mcs = txrate->mcs;
29 	else
30 		mcs = 0;
31 
32 	if (mcs <= 2)
33 		return 1;
34 
35 	/* lower than 20M vht 2ss mcs8, make it small */
36 	if (bit_rate < 1800)
37 		return 1200;
38 
39 	/* lower than 40M vht 2ss mcs9, make it medium */
40 	if (bit_rate < 4000)
41 		return 2600;
42 
43 	/* not yet 80M vht 2ss mcs8/9, make it twice regular packet size */
44 	if (bit_rate < 7000)
45 		return 3500;
46 
47 	return rtwdev->chip->max_amsdu_limit;
48 }
49 
50 static u64 get_mcs_ra_mask(u16 mcs_map, u8 highest_mcs, u8 gap)
51 {
52 	u64 ra_mask = 0;
53 	u8 mcs_cap;
54 	int i, nss;
55 
56 	for (i = 0, nss = 12; i < 4; i++, mcs_map >>= 2, nss += 12) {
57 		mcs_cap = mcs_map & 0x3;
58 		switch (mcs_cap) {
59 		case 2:
60 			ra_mask |= GENMASK_ULL(highest_mcs, 0) << nss;
61 			break;
62 		case 1:
63 			ra_mask |= GENMASK_ULL(highest_mcs - gap, 0) << nss;
64 			break;
65 		case 0:
66 			ra_mask |= GENMASK_ULL(highest_mcs - gap * 2, 0) << nss;
67 			break;
68 		default:
69 			break;
70 		}
71 	}
72 
73 	return ra_mask;
74 }
75 
76 static u64 get_he_ra_mask(struct ieee80211_sta *sta)
77 {
78 	struct ieee80211_sta_he_cap cap = sta->he_cap;
79 	u16 mcs_map;
80 
81 	switch (sta->bandwidth) {
82 	case IEEE80211_STA_RX_BW_160:
83 		if (cap.he_cap_elem.phy_cap_info[0] &
84 		    IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_80PLUS80_MHZ_IN_5G)
85 			mcs_map = le16_to_cpu(cap.he_mcs_nss_supp.rx_mcs_80p80);
86 		else
87 			mcs_map = le16_to_cpu(cap.he_mcs_nss_supp.rx_mcs_160);
88 		break;
89 	default:
90 		mcs_map = le16_to_cpu(cap.he_mcs_nss_supp.rx_mcs_80);
91 	}
92 
93 	/* MCS11, MCS9, MCS7 */
94 	return get_mcs_ra_mask(mcs_map, 11, 2);
95 }
96 
97 #define RA_FLOOR_TABLE_SIZE	7
98 #define RA_FLOOR_UP_GAP		3
99 static u64 rtw89_phy_ra_mask_rssi(struct rtw89_dev *rtwdev, u8 rssi,
100 				  u8 ratr_state)
101 {
102 	u8 rssi_lv_t[RA_FLOOR_TABLE_SIZE] = {30, 44, 48, 52, 56, 60, 100};
103 	u8 rssi_lv = 0;
104 	u8 i;
105 
106 	rssi >>= 1;
107 	for (i = 0; i < RA_FLOOR_TABLE_SIZE; i++) {
108 		if (i >= ratr_state)
109 			rssi_lv_t[i] += RA_FLOOR_UP_GAP;
110 		if (rssi < rssi_lv_t[i]) {
111 			rssi_lv = i;
112 			break;
113 		}
114 	}
115 	if (rssi_lv == 0)
116 		return 0xffffffffffffffffULL;
117 	else if (rssi_lv == 1)
118 		return 0xfffffffffffffff0ULL;
119 	else if (rssi_lv == 2)
120 		return 0xffffffffffffffe0ULL;
121 	else if (rssi_lv == 3)
122 		return 0xffffffffffffffc0ULL;
123 	else if (rssi_lv == 4)
124 		return 0xffffffffffffff80ULL;
125 	else if (rssi_lv >= 5)
126 		return 0xffffffffffffff00ULL;
127 
128 	return 0xffffffffffffffffULL;
129 }
130 
131 static u64 rtw89_phy_ra_mask_cfg(struct rtw89_dev *rtwdev, struct rtw89_sta *rtwsta)
132 {
133 	struct rtw89_hal *hal = &rtwdev->hal;
134 	struct ieee80211_sta *sta = rtwsta_to_sta(rtwsta);
135 	struct cfg80211_bitrate_mask *mask = &rtwsta->mask;
136 	enum nl80211_band band;
137 	u64 cfg_mask;
138 
139 	if (!rtwsta->use_cfg_mask)
140 		return -1;
141 
142 	switch (hal->current_band_type) {
143 	case RTW89_BAND_2G:
144 		band = NL80211_BAND_2GHZ;
145 		cfg_mask = u64_encode_bits(mask->control[NL80211_BAND_2GHZ].legacy,
146 					   RA_MASK_CCK_RATES | RA_MASK_OFDM_RATES);
147 		break;
148 	case RTW89_BAND_5G:
149 		band = NL80211_BAND_5GHZ;
150 		cfg_mask = u64_encode_bits(mask->control[NL80211_BAND_5GHZ].legacy,
151 					   RA_MASK_OFDM_RATES);
152 		break;
153 	default:
154 		rtw89_warn(rtwdev, "unhandled band type %d\n", hal->current_band_type);
155 		return -1;
156 	}
157 
158 	if (sta->he_cap.has_he) {
159 		cfg_mask |= u64_encode_bits(mask->control[band].he_mcs[0],
160 					    RA_MASK_HE_1SS_RATES);
161 		cfg_mask |= u64_encode_bits(mask->control[band].he_mcs[1],
162 					    RA_MASK_HE_2SS_RATES);
163 	} else if (sta->vht_cap.vht_supported) {
164 		cfg_mask |= u64_encode_bits(mask->control[band].vht_mcs[0],
165 					    RA_MASK_VHT_1SS_RATES);
166 		cfg_mask |= u64_encode_bits(mask->control[band].vht_mcs[1],
167 					    RA_MASK_VHT_2SS_RATES);
168 	} else if (sta->ht_cap.ht_supported) {
169 		cfg_mask |= u64_encode_bits(mask->control[band].ht_mcs[0],
170 					    RA_MASK_HT_1SS_RATES);
171 		cfg_mask |= u64_encode_bits(mask->control[band].ht_mcs[1],
172 					    RA_MASK_HT_2SS_RATES);
173 	}
174 
175 	return cfg_mask;
176 }
177 
178 static const u64
179 rtw89_ra_mask_ht_rates[4] = {RA_MASK_HT_1SS_RATES, RA_MASK_HT_2SS_RATES,
180 			     RA_MASK_HT_3SS_RATES, RA_MASK_HT_4SS_RATES};
181 static const u64
182 rtw89_ra_mask_vht_rates[4] = {RA_MASK_VHT_1SS_RATES, RA_MASK_VHT_2SS_RATES,
183 			      RA_MASK_VHT_3SS_RATES, RA_MASK_VHT_4SS_RATES};
184 static const u64
185 rtw89_ra_mask_he_rates[4] = {RA_MASK_HE_1SS_RATES, RA_MASK_HE_2SS_RATES,
186 			     RA_MASK_HE_3SS_RATES, RA_MASK_HE_4SS_RATES};
187 
188 static void rtw89_phy_ra_sta_update(struct rtw89_dev *rtwdev,
189 				    struct ieee80211_sta *sta, bool csi)
190 {
191 	struct rtw89_sta *rtwsta = (struct rtw89_sta *)sta->drv_priv;
192 	struct rtw89_vif *rtwvif = rtwsta->rtwvif;
193 	struct rtw89_phy_rate_pattern *rate_pattern = &rtwvif->rate_pattern;
194 	struct rtw89_ra_info *ra = &rtwsta->ra;
195 	const u64 *high_rate_masks = rtw89_ra_mask_ht_rates;
196 	u8 rssi = ewma_rssi_read(&rtwsta->avg_rssi);
197 	u64 high_rate_mask = 0;
198 	u64 ra_mask = 0;
199 	u8 mode = 0;
200 	u8 csi_mode = RTW89_RA_RPT_MODE_LEGACY;
201 	u8 bw_mode = 0;
202 	u8 stbc_en = 0;
203 	u8 ldpc_en = 0;
204 	u8 i;
205 	bool sgi = false;
206 
207 	memset(ra, 0, sizeof(*ra));
208 	/* Set the ra mask from sta's capability */
209 	if (sta->he_cap.has_he) {
210 		mode |= RTW89_RA_MODE_HE;
211 		csi_mode = RTW89_RA_RPT_MODE_HE;
212 		ra_mask |= get_he_ra_mask(sta);
213 		high_rate_masks = rtw89_ra_mask_he_rates;
214 		if (sta->he_cap.he_cap_elem.phy_cap_info[2] &
215 		    IEEE80211_HE_PHY_CAP2_STBC_RX_UNDER_80MHZ)
216 			stbc_en = 1;
217 		if (sta->he_cap.he_cap_elem.phy_cap_info[1] &
218 		    IEEE80211_HE_PHY_CAP1_LDPC_CODING_IN_PAYLOAD)
219 			ldpc_en = 1;
220 	} else if (sta->vht_cap.vht_supported) {
221 		u16 mcs_map = le16_to_cpu(sta->vht_cap.vht_mcs.rx_mcs_map);
222 
223 		mode |= RTW89_RA_MODE_VHT;
224 		csi_mode = RTW89_RA_RPT_MODE_VHT;
225 		/* MCS9, MCS8, MCS7 */
226 		ra_mask |= get_mcs_ra_mask(mcs_map, 9, 1);
227 		high_rate_masks = rtw89_ra_mask_vht_rates;
228 		if (sta->vht_cap.cap & IEEE80211_VHT_CAP_RXSTBC_MASK)
229 			stbc_en = 1;
230 		if (sta->vht_cap.cap & IEEE80211_VHT_CAP_RXLDPC)
231 			ldpc_en = 1;
232 	} else if (sta->ht_cap.ht_supported) {
233 		mode |= RTW89_RA_MODE_HT;
234 		csi_mode = RTW89_RA_RPT_MODE_HT;
235 		ra_mask |= ((u64)sta->ht_cap.mcs.rx_mask[3] << 48) |
236 			   ((u64)sta->ht_cap.mcs.rx_mask[2] << 36) |
237 			   (sta->ht_cap.mcs.rx_mask[1] << 24) |
238 			   (sta->ht_cap.mcs.rx_mask[0] << 12);
239 		high_rate_masks = rtw89_ra_mask_ht_rates;
240 		if (sta->ht_cap.cap & IEEE80211_HT_CAP_RX_STBC)
241 			stbc_en = 1;
242 		if (sta->ht_cap.cap & IEEE80211_HT_CAP_LDPC_CODING)
243 			ldpc_en = 1;
244 	}
245 
246 	if (rtwdev->hal.current_band_type == RTW89_BAND_2G) {
247 		if (sta->supp_rates[NL80211_BAND_2GHZ] <= 0xf)
248 			mode |= RTW89_RA_MODE_CCK;
249 		else
250 			mode |= RTW89_RA_MODE_CCK | RTW89_RA_MODE_OFDM;
251 	} else {
252 		mode |= RTW89_RA_MODE_OFDM;
253 	}
254 
255 	if (mode >= RTW89_RA_MODE_HT) {
256 		for (i = 0; i < rtwdev->hal.tx_nss; i++)
257 			high_rate_mask |= high_rate_masks[i];
258 		ra_mask &= high_rate_mask;
259 		if (mode & RTW89_RA_MODE_OFDM)
260 			ra_mask |= RA_MASK_SUBOFDM_RATES;
261 		if (mode & RTW89_RA_MODE_CCK)
262 			ra_mask |= RA_MASK_SUBCCK_RATES;
263 	} else if (mode & RTW89_RA_MODE_OFDM) {
264 		if (mode & RTW89_RA_MODE_CCK)
265 			ra_mask |= RA_MASK_SUBCCK_RATES;
266 		ra_mask |= RA_MASK_OFDM_RATES;
267 	} else {
268 		ra_mask = RA_MASK_CCK_RATES;
269 	}
270 
271 	if (mode != RTW89_RA_MODE_CCK) {
272 		ra_mask &= rtw89_phy_ra_mask_rssi(rtwdev, rssi, 0);
273 		ra_mask &= rtw89_phy_ra_mask_cfg(rtwdev, rtwsta);
274 	}
275 
276 	switch (sta->bandwidth) {
277 	case IEEE80211_STA_RX_BW_80:
278 		bw_mode = RTW89_CHANNEL_WIDTH_80;
279 		sgi = sta->vht_cap.vht_supported &&
280 		      (sta->vht_cap.cap & IEEE80211_VHT_CAP_SHORT_GI_80);
281 		break;
282 	case IEEE80211_STA_RX_BW_40:
283 		bw_mode = RTW89_CHANNEL_WIDTH_40;
284 		sgi = sta->ht_cap.ht_supported &&
285 		      (sta->ht_cap.cap & IEEE80211_HT_CAP_SGI_40);
286 		break;
287 	default:
288 		bw_mode = RTW89_CHANNEL_WIDTH_20;
289 		sgi = sta->ht_cap.ht_supported &&
290 		      (sta->ht_cap.cap & IEEE80211_HT_CAP_SGI_20);
291 		break;
292 	}
293 
294 	if (sta->he_cap.he_cap_elem.phy_cap_info[3] &
295 	    IEEE80211_HE_PHY_CAP3_DCM_MAX_CONST_RX_16_QAM)
296 		ra->dcm_cap = 1;
297 
298 	if (rate_pattern->enable) {
299 		ra_mask = rtw89_phy_ra_mask_cfg(rtwdev, rtwsta);
300 		ra_mask &= rate_pattern->ra_mask;
301 		mode = rate_pattern->ra_mode;
302 	}
303 
304 	ra->bw_cap = bw_mode;
305 	ra->mode_ctrl = mode;
306 	ra->macid = rtwsta->mac_id;
307 	ra->stbc_cap = stbc_en;
308 	ra->ldpc_cap = ldpc_en;
309 	ra->ss_num = min(sta->rx_nss, rtwdev->hal.tx_nss) - 1;
310 	ra->en_sgi = sgi;
311 	ra->ra_mask = ra_mask;
312 
313 	if (!csi)
314 		return;
315 
316 	ra->fixed_csi_rate_en = false;
317 	ra->ra_csi_rate_en = true;
318 	ra->cr_tbl_sel = false;
319 	ra->band_num = rtwvif->phy_idx;
320 	ra->csi_bw = bw_mode;
321 	ra->csi_gi_ltf = RTW89_GILTF_LGI_4XHE32;
322 	ra->csi_mcs_ss_idx = 5;
323 	ra->csi_mode = csi_mode;
324 }
325 
326 void rtw89_phy_ra_updata_sta(struct rtw89_dev *rtwdev, struct ieee80211_sta *sta)
327 {
328 	struct rtw89_sta *rtwsta = (struct rtw89_sta *)sta->drv_priv;
329 	struct rtw89_ra_info *ra = &rtwsta->ra;
330 
331 	rtw89_phy_ra_sta_update(rtwdev, sta, false);
332 	ra->upd_mask = 1;
333 	rtw89_debug(rtwdev, RTW89_DBG_RA,
334 		    "ra updat: macid = %d, bw = %d, nss = %d, gi = %d %d",
335 		    ra->macid,
336 		    ra->bw_cap,
337 		    ra->ss_num,
338 		    ra->en_sgi,
339 		    ra->giltf);
340 
341 	rtw89_fw_h2c_ra(rtwdev, ra, false);
342 }
343 
344 static bool __check_rate_pattern(struct rtw89_phy_rate_pattern *next,
345 				 u16 rate_base, u64 ra_mask, u8 ra_mode,
346 				 u32 rate_ctrl, u32 ctrl_skip, bool force)
347 {
348 	u8 n, c;
349 
350 	if (rate_ctrl == ctrl_skip)
351 		return true;
352 
353 	n = hweight32(rate_ctrl);
354 	if (n == 0)
355 		return true;
356 
357 	if (force && n != 1)
358 		return false;
359 
360 	if (next->enable)
361 		return false;
362 
363 	c = __fls(rate_ctrl);
364 	next->rate = rate_base + c;
365 	next->ra_mode = ra_mode;
366 	next->ra_mask = ra_mask;
367 	next->enable = true;
368 
369 	return true;
370 }
371 
372 void rtw89_phy_rate_pattern_vif(struct rtw89_dev *rtwdev,
373 				struct ieee80211_vif *vif,
374 				const struct cfg80211_bitrate_mask *mask)
375 {
376 	struct ieee80211_supported_band *sband;
377 	struct rtw89_vif *rtwvif = (struct rtw89_vif *)vif->drv_priv;
378 	struct rtw89_phy_rate_pattern next_pattern = {0};
379 	static const u16 hw_rate_he[] = {RTW89_HW_RATE_HE_NSS1_MCS0,
380 					 RTW89_HW_RATE_HE_NSS2_MCS0,
381 					 RTW89_HW_RATE_HE_NSS3_MCS0,
382 					 RTW89_HW_RATE_HE_NSS4_MCS0};
383 	static const u16 hw_rate_vht[] = {RTW89_HW_RATE_VHT_NSS1_MCS0,
384 					  RTW89_HW_RATE_VHT_NSS2_MCS0,
385 					  RTW89_HW_RATE_VHT_NSS3_MCS0,
386 					  RTW89_HW_RATE_VHT_NSS4_MCS0};
387 	static const u16 hw_rate_ht[] = {RTW89_HW_RATE_MCS0,
388 					 RTW89_HW_RATE_MCS8,
389 					 RTW89_HW_RATE_MCS16,
390 					 RTW89_HW_RATE_MCS24};
391 	u8 band = rtwdev->hal.current_band_type;
392 	u8 tx_nss = rtwdev->hal.tx_nss;
393 	u8 i;
394 
395 	for (i = 0; i < tx_nss; i++)
396 		if (!__check_rate_pattern(&next_pattern, hw_rate_he[i],
397 					  RA_MASK_HE_RATES, RTW89_RA_MODE_HE,
398 					  mask->control[band].he_mcs[i],
399 					  0, true))
400 			goto out;
401 
402 	for (i = 0; i < tx_nss; i++)
403 		if (!__check_rate_pattern(&next_pattern, hw_rate_vht[i],
404 					  RA_MASK_VHT_RATES, RTW89_RA_MODE_VHT,
405 					  mask->control[band].vht_mcs[i],
406 					  0, true))
407 			goto out;
408 
409 	for (i = 0; i < tx_nss; i++)
410 		if (!__check_rate_pattern(&next_pattern, hw_rate_ht[i],
411 					  RA_MASK_HT_RATES, RTW89_RA_MODE_HT,
412 					  mask->control[band].ht_mcs[i],
413 					  0, true))
414 			goto out;
415 
416 	/* lagacy cannot be empty for nl80211_parse_tx_bitrate_mask, and
417 	 * require at least one basic rate for ieee80211_set_bitrate_mask,
418 	 * so the decision just depends on if all bitrates are set or not.
419 	 */
420 	sband = rtwdev->hw->wiphy->bands[band];
421 	if (band == RTW89_BAND_2G) {
422 		if (!__check_rate_pattern(&next_pattern, RTW89_HW_RATE_CCK1,
423 					  RA_MASK_CCK_RATES | RA_MASK_OFDM_RATES,
424 					  RTW89_RA_MODE_CCK | RTW89_RA_MODE_OFDM,
425 					  mask->control[band].legacy,
426 					  BIT(sband->n_bitrates) - 1, false))
427 			goto out;
428 	} else {
429 		if (!__check_rate_pattern(&next_pattern, RTW89_HW_RATE_OFDM6,
430 					  RA_MASK_OFDM_RATES, RTW89_RA_MODE_OFDM,
431 					  mask->control[band].legacy,
432 					  BIT(sband->n_bitrates) - 1, false))
433 			goto out;
434 	}
435 
436 	if (!next_pattern.enable)
437 		goto out;
438 
439 	rtwvif->rate_pattern = next_pattern;
440 	rtw89_debug(rtwdev, RTW89_DBG_RA,
441 		    "configure pattern: rate 0x%x, mask 0x%llx, mode 0x%x\n",
442 		    next_pattern.rate,
443 		    next_pattern.ra_mask,
444 		    next_pattern.ra_mode);
445 	return;
446 
447 out:
448 	rtwvif->rate_pattern.enable = false;
449 	rtw89_debug(rtwdev, RTW89_DBG_RA, "unset rate pattern\n");
450 }
451 
452 static void rtw89_phy_ra_updata_sta_iter(void *data, struct ieee80211_sta *sta)
453 {
454 	struct rtw89_dev *rtwdev = (struct rtw89_dev *)data;
455 
456 	rtw89_phy_ra_updata_sta(rtwdev, sta);
457 }
458 
459 void rtw89_phy_ra_update(struct rtw89_dev *rtwdev)
460 {
461 	ieee80211_iterate_stations_atomic(rtwdev->hw,
462 					  rtw89_phy_ra_updata_sta_iter,
463 					  rtwdev);
464 }
465 
466 void rtw89_phy_ra_assoc(struct rtw89_dev *rtwdev, struct ieee80211_sta *sta)
467 {
468 	struct rtw89_sta *rtwsta = (struct rtw89_sta *)sta->drv_priv;
469 	struct rtw89_ra_info *ra = &rtwsta->ra;
470 	u8 rssi = ewma_rssi_read(&rtwsta->avg_rssi) >> RSSI_FACTOR;
471 	bool csi = rtw89_sta_has_beamformer_cap(sta);
472 
473 	rtw89_phy_ra_sta_update(rtwdev, sta, csi);
474 
475 	if (rssi > 40)
476 		ra->init_rate_lv = 1;
477 	else if (rssi > 20)
478 		ra->init_rate_lv = 2;
479 	else if (rssi > 1)
480 		ra->init_rate_lv = 3;
481 	else
482 		ra->init_rate_lv = 0;
483 	ra->upd_all = 1;
484 	rtw89_debug(rtwdev, RTW89_DBG_RA,
485 		    "ra assoc: macid = %d, mode = %d, bw = %d, nss = %d, lv = %d",
486 		    ra->macid,
487 		    ra->mode_ctrl,
488 		    ra->bw_cap,
489 		    ra->ss_num,
490 		    ra->init_rate_lv);
491 	rtw89_debug(rtwdev, RTW89_DBG_RA,
492 		    "ra assoc: dcm = %d, er = %d, ldpc = %d, stbc = %d, gi = %d %d",
493 		    ra->dcm_cap,
494 		    ra->er_cap,
495 		    ra->ldpc_cap,
496 		    ra->stbc_cap,
497 		    ra->en_sgi,
498 		    ra->giltf);
499 
500 	rtw89_fw_h2c_ra(rtwdev, ra, csi);
501 }
502 
503 u8 rtw89_phy_get_txsc(struct rtw89_dev *rtwdev,
504 		      struct rtw89_channel_params *param,
505 		      enum rtw89_bandwidth dbw)
506 {
507 	enum rtw89_bandwidth cbw = param->bandwidth;
508 	u8 pri_ch = param->primary_chan;
509 	u8 central_ch = param->center_chan;
510 	u8 txsc_idx = 0;
511 	u8 tmp = 0;
512 
513 	if (cbw == dbw || cbw == RTW89_CHANNEL_WIDTH_20)
514 		return txsc_idx;
515 
516 	switch (cbw) {
517 	case RTW89_CHANNEL_WIDTH_40:
518 		txsc_idx = pri_ch > central_ch ? 1 : 2;
519 		break;
520 	case RTW89_CHANNEL_WIDTH_80:
521 		if (dbw == RTW89_CHANNEL_WIDTH_20) {
522 			if (pri_ch > central_ch)
523 				txsc_idx = (pri_ch - central_ch) >> 1;
524 			else
525 				txsc_idx = ((central_ch - pri_ch) >> 1) + 1;
526 		} else {
527 			txsc_idx = pri_ch > central_ch ? 9 : 10;
528 		}
529 		break;
530 	case RTW89_CHANNEL_WIDTH_160:
531 		if (pri_ch > central_ch)
532 			tmp = (pri_ch - central_ch) >> 1;
533 		else
534 			tmp = ((central_ch - pri_ch) >> 1) + 1;
535 
536 		if (dbw == RTW89_CHANNEL_WIDTH_20) {
537 			txsc_idx = tmp;
538 		} else if (dbw == RTW89_CHANNEL_WIDTH_40) {
539 			if (tmp == 1 || tmp == 3)
540 				txsc_idx = 9;
541 			else if (tmp == 5 || tmp == 7)
542 				txsc_idx = 11;
543 			else if (tmp == 2 || tmp == 4)
544 				txsc_idx = 10;
545 			else if (tmp == 6 || tmp == 8)
546 				txsc_idx = 12;
547 			else
548 				return 0xff;
549 		} else {
550 			txsc_idx = pri_ch > central_ch ? 13 : 14;
551 		}
552 		break;
553 	case RTW89_CHANNEL_WIDTH_80_80:
554 		if (dbw == RTW89_CHANNEL_WIDTH_20) {
555 			if (pri_ch > central_ch)
556 				txsc_idx = (10 - (pri_ch - central_ch)) >> 1;
557 			else
558 				txsc_idx = ((central_ch - pri_ch) >> 1) + 5;
559 		} else if (dbw == RTW89_CHANNEL_WIDTH_40) {
560 			txsc_idx = pri_ch > central_ch ? 10 : 12;
561 		} else {
562 			txsc_idx = 14;
563 		}
564 		break;
565 	default:
566 		break;
567 	}
568 
569 	return txsc_idx;
570 }
571 
572 u32 rtw89_phy_read_rf(struct rtw89_dev *rtwdev, enum rtw89_rf_path rf_path,
573 		      u32 addr, u32 mask)
574 {
575 	const struct rtw89_chip_info *chip = rtwdev->chip;
576 	const u32 *base_addr = chip->rf_base_addr;
577 	u32 val, direct_addr;
578 
579 	if (rf_path >= rtwdev->chip->rf_path_num) {
580 		rtw89_err(rtwdev, "unsupported rf path (%d)\n", rf_path);
581 		return INV_RF_DATA;
582 	}
583 
584 	addr &= 0xff;
585 	direct_addr = base_addr[rf_path] + (addr << 2);
586 	mask &= RFREG_MASK;
587 
588 	val = rtw89_phy_read32_mask(rtwdev, direct_addr, mask);
589 
590 	return val;
591 }
592 EXPORT_SYMBOL(rtw89_phy_read_rf);
593 
594 bool rtw89_phy_write_rf(struct rtw89_dev *rtwdev, enum rtw89_rf_path rf_path,
595 			u32 addr, u32 mask, u32 data)
596 {
597 	const struct rtw89_chip_info *chip = rtwdev->chip;
598 	const u32 *base_addr = chip->rf_base_addr;
599 	u32 direct_addr;
600 
601 	if (rf_path >= rtwdev->chip->rf_path_num) {
602 		rtw89_err(rtwdev, "unsupported rf path (%d)\n", rf_path);
603 		return false;
604 	}
605 
606 	addr &= 0xff;
607 	direct_addr = base_addr[rf_path] + (addr << 2);
608 	mask &= RFREG_MASK;
609 
610 	rtw89_phy_write32_mask(rtwdev, direct_addr, mask, data);
611 
612 	/* delay to ensure writing properly */
613 	udelay(1);
614 
615 	return true;
616 }
617 EXPORT_SYMBOL(rtw89_phy_write_rf);
618 
619 static void rtw89_phy_bb_reset(struct rtw89_dev *rtwdev,
620 			       enum rtw89_phy_idx phy_idx)
621 {
622 	const struct rtw89_chip_info *chip = rtwdev->chip;
623 
624 	chip->ops->bb_reset(rtwdev, phy_idx);
625 }
626 
627 static void rtw89_phy_config_bb_reg(struct rtw89_dev *rtwdev,
628 				    const struct rtw89_reg2_def *reg,
629 				    enum rtw89_rf_path rf_path,
630 				    void *extra_data)
631 {
632 	if (reg->addr == 0xfe)
633 		mdelay(50);
634 	else if (reg->addr == 0xfd)
635 		mdelay(5);
636 	else if (reg->addr == 0xfc)
637 		mdelay(1);
638 	else if (reg->addr == 0xfb)
639 		udelay(50);
640 	else if (reg->addr == 0xfa)
641 		udelay(5);
642 	else if (reg->addr == 0xf9)
643 		udelay(1);
644 	else
645 		rtw89_phy_write32(rtwdev, reg->addr, reg->data);
646 }
647 
648 static void
649 rtw89_phy_cofig_rf_reg_store(struct rtw89_dev *rtwdev,
650 			     const struct rtw89_reg2_def *reg,
651 			     enum rtw89_rf_path rf_path,
652 			     struct rtw89_fw_h2c_rf_reg_info *info)
653 {
654 	u16 idx = info->curr_idx % RTW89_H2C_RF_PAGE_SIZE;
655 	u8 page = info->curr_idx / RTW89_H2C_RF_PAGE_SIZE;
656 
657 	if (page >= RTW89_H2C_RF_PAGE_NUM) {
658 		rtw89_warn(rtwdev, "RF parameters exceed size. path=%d, idx=%d",
659 			   rf_path, info->curr_idx);
660 		return;
661 	}
662 
663 	info->rtw89_phy_config_rf_h2c[page][idx] =
664 		cpu_to_le32((reg->addr << 20) | reg->data);
665 	info->curr_idx++;
666 }
667 
668 static int rtw89_phy_config_rf_reg_fw(struct rtw89_dev *rtwdev,
669 				      struct rtw89_fw_h2c_rf_reg_info *info)
670 {
671 	u16 remain = info->curr_idx;
672 	u16 len = 0;
673 	u8 i;
674 	int ret = 0;
675 
676 	if (remain > RTW89_H2C_RF_PAGE_NUM * RTW89_H2C_RF_PAGE_SIZE) {
677 		rtw89_warn(rtwdev,
678 			   "rf reg h2c total len %d larger than %d\n",
679 			   remain, RTW89_H2C_RF_PAGE_NUM * RTW89_H2C_RF_PAGE_SIZE);
680 		ret = -EINVAL;
681 		goto out;
682 	}
683 
684 	for (i = 0; i < RTW89_H2C_RF_PAGE_NUM && remain; i++, remain -= len) {
685 		len = remain > RTW89_H2C_RF_PAGE_SIZE ? RTW89_H2C_RF_PAGE_SIZE : remain;
686 		ret = rtw89_fw_h2c_rf_reg(rtwdev, info, len * 4, i);
687 		if (ret)
688 			goto out;
689 	}
690 out:
691 	info->curr_idx = 0;
692 
693 	return ret;
694 }
695 
696 static void rtw89_phy_config_rf_reg(struct rtw89_dev *rtwdev,
697 				    const struct rtw89_reg2_def *reg,
698 				    enum rtw89_rf_path rf_path,
699 				    void *extra_data)
700 {
701 	if (reg->addr == 0xfe) {
702 		mdelay(50);
703 	} else if (reg->addr == 0xfd) {
704 		mdelay(5);
705 	} else if (reg->addr == 0xfc) {
706 		mdelay(1);
707 	} else if (reg->addr == 0xfb) {
708 		udelay(50);
709 	} else if (reg->addr == 0xfa) {
710 		udelay(5);
711 	} else if (reg->addr == 0xf9) {
712 		udelay(1);
713 	} else {
714 		rtw89_write_rf(rtwdev, rf_path, reg->addr, 0xfffff, reg->data);
715 		rtw89_phy_cofig_rf_reg_store(rtwdev, reg, rf_path,
716 					     (struct rtw89_fw_h2c_rf_reg_info *)extra_data);
717 	}
718 }
719 
720 static int rtw89_phy_sel_headline(struct rtw89_dev *rtwdev,
721 				  const struct rtw89_phy_table *table,
722 				  u32 *headline_size, u32 *headline_idx,
723 				  u8 rfe, u8 cv)
724 {
725 	const struct rtw89_reg2_def *reg;
726 	u32 headline;
727 	u32 compare, target;
728 	u8 rfe_para, cv_para;
729 	u8 cv_max = 0;
730 	bool case_matched = false;
731 	u32 i;
732 
733 	for (i = 0; i < table->n_regs; i++) {
734 		reg = &table->regs[i];
735 		headline = get_phy_headline(reg->addr);
736 		if (headline != PHY_HEADLINE_VALID)
737 			break;
738 	}
739 	*headline_size = i;
740 	if (*headline_size == 0)
741 		return 0;
742 
743 	/* case 1: RFE match, CV match */
744 	compare = get_phy_compare(rfe, cv);
745 	for (i = 0; i < *headline_size; i++) {
746 		reg = &table->regs[i];
747 		target = get_phy_target(reg->addr);
748 		if (target == compare) {
749 			*headline_idx = i;
750 			return 0;
751 		}
752 	}
753 
754 	/* case 2: RFE match, CV don't care */
755 	compare = get_phy_compare(rfe, PHY_COND_DONT_CARE);
756 	for (i = 0; i < *headline_size; i++) {
757 		reg = &table->regs[i];
758 		target = get_phy_target(reg->addr);
759 		if (target == compare) {
760 			*headline_idx = i;
761 			return 0;
762 		}
763 	}
764 
765 	/* case 3: RFE match, CV max in table */
766 	for (i = 0; i < *headline_size; i++) {
767 		reg = &table->regs[i];
768 		rfe_para = get_phy_cond_rfe(reg->addr);
769 		cv_para = get_phy_cond_cv(reg->addr);
770 		if (rfe_para == rfe) {
771 			if (cv_para >= cv_max) {
772 				cv_max = cv_para;
773 				*headline_idx = i;
774 				case_matched = true;
775 			}
776 		}
777 	}
778 
779 	if (case_matched)
780 		return 0;
781 
782 	/* case 4: RFE don't care, CV max in table */
783 	for (i = 0; i < *headline_size; i++) {
784 		reg = &table->regs[i];
785 		rfe_para = get_phy_cond_rfe(reg->addr);
786 		cv_para = get_phy_cond_cv(reg->addr);
787 		if (rfe_para == PHY_COND_DONT_CARE) {
788 			if (cv_para >= cv_max) {
789 				cv_max = cv_para;
790 				*headline_idx = i;
791 				case_matched = true;
792 			}
793 		}
794 	}
795 
796 	if (case_matched)
797 		return 0;
798 
799 	return -EINVAL;
800 }
801 
802 static void rtw89_phy_init_reg(struct rtw89_dev *rtwdev,
803 			       const struct rtw89_phy_table *table,
804 			       void (*config)(struct rtw89_dev *rtwdev,
805 					      const struct rtw89_reg2_def *reg,
806 					      enum rtw89_rf_path rf_path,
807 					      void *data),
808 			       void *extra_data)
809 {
810 	const struct rtw89_reg2_def *reg;
811 	enum rtw89_rf_path rf_path = table->rf_path;
812 	u8 rfe = rtwdev->efuse.rfe_type;
813 	u8 cv = rtwdev->hal.cv;
814 	u32 i;
815 	u32 headline_size = 0, headline_idx = 0;
816 	u32 target = 0, cfg_target;
817 	u8 cond;
818 	bool is_matched = true;
819 	bool target_found = false;
820 	int ret;
821 
822 	ret = rtw89_phy_sel_headline(rtwdev, table, &headline_size,
823 				     &headline_idx, rfe, cv);
824 	if (ret) {
825 		rtw89_err(rtwdev, "invalid PHY package: %d/%d\n", rfe, cv);
826 		return;
827 	}
828 
829 	cfg_target = get_phy_target(table->regs[headline_idx].addr);
830 	for (i = headline_size; i < table->n_regs; i++) {
831 		reg = &table->regs[i];
832 		cond = get_phy_cond(reg->addr);
833 		switch (cond) {
834 		case PHY_COND_BRANCH_IF:
835 		case PHY_COND_BRANCH_ELIF:
836 			target = get_phy_target(reg->addr);
837 			break;
838 		case PHY_COND_BRANCH_ELSE:
839 			is_matched = false;
840 			if (!target_found) {
841 				rtw89_warn(rtwdev, "failed to load CR %x/%x\n",
842 					   reg->addr, reg->data);
843 				return;
844 			}
845 			break;
846 		case PHY_COND_BRANCH_END:
847 			is_matched = true;
848 			target_found = false;
849 			break;
850 		case PHY_COND_CHECK:
851 			if (target_found) {
852 				is_matched = false;
853 				break;
854 			}
855 
856 			if (target == cfg_target) {
857 				is_matched = true;
858 				target_found = true;
859 			} else {
860 				is_matched = false;
861 				target_found = false;
862 			}
863 			break;
864 		default:
865 			if (is_matched)
866 				config(rtwdev, reg, rf_path, extra_data);
867 			break;
868 		}
869 	}
870 }
871 
872 void rtw89_phy_init_bb_reg(struct rtw89_dev *rtwdev)
873 {
874 	const struct rtw89_chip_info *chip = rtwdev->chip;
875 	const struct rtw89_phy_table *bb_table = chip->bb_table;
876 
877 	rtw89_phy_init_reg(rtwdev, bb_table, rtw89_phy_config_bb_reg, NULL);
878 	rtw89_chip_init_txpwr_unit(rtwdev, RTW89_PHY_0);
879 	rtw89_phy_bb_reset(rtwdev, RTW89_PHY_0);
880 }
881 
882 static u32 rtw89_phy_nctl_poll(struct rtw89_dev *rtwdev)
883 {
884 	rtw89_phy_write32(rtwdev, 0x8080, 0x4);
885 	udelay(1);
886 	return rtw89_phy_read32(rtwdev, 0x8080);
887 }
888 
889 void rtw89_phy_init_rf_reg(struct rtw89_dev *rtwdev)
890 {
891 	const struct rtw89_chip_info *chip = rtwdev->chip;
892 	const struct rtw89_phy_table *rf_table;
893 	struct rtw89_fw_h2c_rf_reg_info *rf_reg_info;
894 	u8 path;
895 
896 	rf_reg_info = kzalloc(sizeof(*rf_reg_info), GFP_KERNEL);
897 	if (!rf_reg_info)
898 		return;
899 
900 	for (path = RF_PATH_A; path < chip->rf_path_num; path++) {
901 		rf_reg_info->rf_path = path;
902 		rf_table = chip->rf_table[path];
903 		rtw89_phy_init_reg(rtwdev, rf_table, rtw89_phy_config_rf_reg,
904 				   (void *)rf_reg_info);
905 		if (rtw89_phy_config_rf_reg_fw(rtwdev, rf_reg_info))
906 			rtw89_warn(rtwdev, "rf path %d reg h2c config failed\n",
907 				   path);
908 	}
909 	kfree(rf_reg_info);
910 }
911 
912 static void rtw89_phy_init_rf_nctl(struct rtw89_dev *rtwdev)
913 {
914 	const struct rtw89_chip_info *chip = rtwdev->chip;
915 	const struct rtw89_phy_table *nctl_table;
916 	u32 val;
917 	int ret;
918 
919 	/* IQK/DPK clock & reset */
920 	rtw89_phy_write32_set(rtwdev, 0x0c60, 0x3);
921 	rtw89_phy_write32_set(rtwdev, 0x0c6c, 0x1);
922 	rtw89_phy_write32_set(rtwdev, 0x58ac, 0x8000000);
923 	rtw89_phy_write32_set(rtwdev, 0x78ac, 0x8000000);
924 
925 	/* check 0x8080 */
926 	rtw89_phy_write32(rtwdev, 0x8000, 0x8);
927 
928 	ret = read_poll_timeout(rtw89_phy_nctl_poll, val, val == 0x4, 10,
929 				1000, false, rtwdev);
930 	if (ret)
931 		rtw89_err(rtwdev, "failed to poll nctl block\n");
932 
933 	nctl_table = chip->nctl_table;
934 	rtw89_phy_init_reg(rtwdev, nctl_table, rtw89_phy_config_bb_reg, NULL);
935 }
936 
937 static u32 rtw89_phy0_phy1_offset(struct rtw89_dev *rtwdev, u32 addr)
938 {
939 	u32 phy_page = addr >> 8;
940 	u32 ofst = 0;
941 
942 	switch (phy_page) {
943 	case 0x6:
944 	case 0x7:
945 	case 0x8:
946 	case 0x9:
947 	case 0xa:
948 	case 0xb:
949 	case 0xc:
950 	case 0xd:
951 	case 0x19:
952 	case 0x1a:
953 	case 0x1b:
954 		ofst = 0x2000;
955 		break;
956 	default:
957 		/* warning case */
958 		ofst = 0;
959 		break;
960 	}
961 
962 	if (phy_page >= 0x40 && phy_page <= 0x4f)
963 		ofst = 0x2000;
964 
965 	return ofst;
966 }
967 
968 void rtw89_phy_write32_idx(struct rtw89_dev *rtwdev, u32 addr, u32 mask,
969 			   u32 data, enum rtw89_phy_idx phy_idx)
970 {
971 	if (rtwdev->dbcc_en && phy_idx == RTW89_PHY_1)
972 		addr += rtw89_phy0_phy1_offset(rtwdev, addr);
973 	rtw89_phy_write32_mask(rtwdev, addr, mask, data);
974 }
975 
976 void rtw89_phy_set_phy_regs(struct rtw89_dev *rtwdev, u32 addr, u32 mask,
977 			    u32 val)
978 {
979 	rtw89_phy_write32_idx(rtwdev, addr, mask, val, RTW89_PHY_0);
980 
981 	if (!rtwdev->dbcc_en)
982 		return;
983 
984 	rtw89_phy_write32_idx(rtwdev, addr, mask, val, RTW89_PHY_1);
985 }
986 
987 void rtw89_phy_write_reg3_tbl(struct rtw89_dev *rtwdev,
988 			      const struct rtw89_phy_reg3_tbl *tbl)
989 {
990 	const struct rtw89_reg3_def *reg3;
991 	int i;
992 
993 	for (i = 0; i < tbl->size; i++) {
994 		reg3 = &tbl->reg3[i];
995 		rtw89_phy_write32_mask(rtwdev, reg3->addr, reg3->mask, reg3->data);
996 	}
997 }
998 
999 const u8 rtw89_rs_idx_max[] = {
1000 	[RTW89_RS_CCK] = RTW89_RATE_CCK_MAX,
1001 	[RTW89_RS_OFDM] = RTW89_RATE_OFDM_MAX,
1002 	[RTW89_RS_MCS] = RTW89_RATE_MCS_MAX,
1003 	[RTW89_RS_HEDCM] = RTW89_RATE_HEDCM_MAX,
1004 	[RTW89_RS_OFFSET] = RTW89_RATE_OFFSET_MAX,
1005 };
1006 
1007 const u8 rtw89_rs_nss_max[] = {
1008 	[RTW89_RS_CCK] = 1,
1009 	[RTW89_RS_OFDM] = 1,
1010 	[RTW89_RS_MCS] = RTW89_NSS_MAX,
1011 	[RTW89_RS_HEDCM] = RTW89_NSS_HEDCM_MAX,
1012 	[RTW89_RS_OFFSET] = 1,
1013 };
1014 
1015 static const u8 _byr_of_rs[] = {
1016 	[RTW89_RS_CCK] = offsetof(struct rtw89_txpwr_byrate, cck),
1017 	[RTW89_RS_OFDM] = offsetof(struct rtw89_txpwr_byrate, ofdm),
1018 	[RTW89_RS_MCS] = offsetof(struct rtw89_txpwr_byrate, mcs),
1019 	[RTW89_RS_HEDCM] = offsetof(struct rtw89_txpwr_byrate, hedcm),
1020 	[RTW89_RS_OFFSET] = offsetof(struct rtw89_txpwr_byrate, offset),
1021 };
1022 
1023 #define _byr_seek(rs, raw) ((s8 *)(raw) + _byr_of_rs[rs])
1024 #define _byr_idx(rs, nss, idx) ((nss) * rtw89_rs_idx_max[rs] + (idx))
1025 #define _byr_chk(rs, nss, idx) \
1026 	((nss) < rtw89_rs_nss_max[rs] && (idx) < rtw89_rs_idx_max[rs])
1027 
1028 void rtw89_phy_load_txpwr_byrate(struct rtw89_dev *rtwdev,
1029 				 const struct rtw89_txpwr_table *tbl)
1030 {
1031 	const struct rtw89_txpwr_byrate_cfg *cfg = tbl->data;
1032 	const struct rtw89_txpwr_byrate_cfg *end = cfg + tbl->size;
1033 	s8 *byr;
1034 	u32 data;
1035 	u8 i, idx;
1036 
1037 	for (; cfg < end; cfg++) {
1038 		byr = _byr_seek(cfg->rs, &rtwdev->byr[cfg->band]);
1039 		data = cfg->data;
1040 
1041 		for (i = 0; i < cfg->len; i++, data >>= 8) {
1042 			idx = _byr_idx(cfg->rs, cfg->nss, (cfg->shf + i));
1043 			byr[idx] = (s8)(data & 0xff);
1044 		}
1045 	}
1046 }
1047 
1048 #define _phy_txpwr_rf_to_mac(rtwdev, txpwr_rf)				\
1049 ({									\
1050 	const struct rtw89_chip_info *__c = (rtwdev)->chip;		\
1051 	(txpwr_rf) >> (__c->txpwr_factor_rf - __c->txpwr_factor_mac);	\
1052 })
1053 
1054 s8 rtw89_phy_read_txpwr_byrate(struct rtw89_dev *rtwdev,
1055 			       const struct rtw89_rate_desc *rate_desc)
1056 {
1057 	enum rtw89_band band = rtwdev->hal.current_band_type;
1058 	s8 *byr;
1059 	u8 idx;
1060 
1061 	if (rate_desc->rs == RTW89_RS_CCK)
1062 		band = RTW89_BAND_2G;
1063 
1064 	if (!_byr_chk(rate_desc->rs, rate_desc->nss, rate_desc->idx)) {
1065 		rtw89_debug(rtwdev, RTW89_DBG_TXPWR,
1066 			    "[TXPWR] unknown byrate desc rs=%d nss=%d idx=%d\n",
1067 			    rate_desc->rs, rate_desc->nss, rate_desc->idx);
1068 
1069 		return 0;
1070 	}
1071 
1072 	byr = _byr_seek(rate_desc->rs, &rtwdev->byr[band]);
1073 	idx = _byr_idx(rate_desc->rs, rate_desc->nss, rate_desc->idx);
1074 
1075 	return _phy_txpwr_rf_to_mac(rtwdev, byr[idx]);
1076 }
1077 
1078 static u8 rtw89_channel_to_idx(struct rtw89_dev *rtwdev, u8 channel)
1079 {
1080 	switch (channel) {
1081 	case 1 ... 14:
1082 		return channel - 1;
1083 	case 36 ... 64:
1084 		return (channel - 36) / 2;
1085 	case 100 ... 144:
1086 		return ((channel - 100) / 2) + 15;
1087 	case 149 ... 177:
1088 		return ((channel - 149) / 2) + 38;
1089 	default:
1090 		rtw89_warn(rtwdev, "unknown channel: %d\n", channel);
1091 		return 0;
1092 	}
1093 }
1094 
1095 s8 rtw89_phy_read_txpwr_limit(struct rtw89_dev *rtwdev,
1096 			      u8 bw, u8 ntx, u8 rs, u8 bf, u8 ch)
1097 {
1098 	const struct rtw89_chip_info *chip = rtwdev->chip;
1099 	u8 ch_idx = rtw89_channel_to_idx(rtwdev, ch);
1100 	u8 band = rtwdev->hal.current_band_type;
1101 	u8 regd = rtw89_regd_get(rtwdev, band);
1102 	s8 lmt = 0, sar;
1103 
1104 	switch (band) {
1105 	case RTW89_BAND_2G:
1106 		lmt = (*chip->txpwr_lmt_2g)[bw][ntx][rs][bf][regd][ch_idx];
1107 		if (!lmt)
1108 			lmt = (*chip->txpwr_lmt_2g)[bw][ntx][rs][bf]
1109 						   [RTW89_WW][ch_idx];
1110 		break;
1111 	case RTW89_BAND_5G:
1112 		lmt = (*chip->txpwr_lmt_5g)[bw][ntx][rs][bf][regd][ch_idx];
1113 		if (!lmt)
1114 			lmt = (*chip->txpwr_lmt_5g)[bw][ntx][rs][bf]
1115 						   [RTW89_WW][ch_idx];
1116 		break;
1117 	default:
1118 		rtw89_warn(rtwdev, "unknown band type: %d\n", band);
1119 		return 0;
1120 	}
1121 
1122 	lmt = _phy_txpwr_rf_to_mac(rtwdev, lmt);
1123 	sar = rtw89_query_sar(rtwdev);
1124 
1125 	return min(lmt, sar);
1126 }
1127 
1128 #define __fill_txpwr_limit_nonbf_bf(ptr, bw, ntx, rs, ch)		\
1129 	do {								\
1130 		u8 __i;							\
1131 		for (__i = 0; __i < RTW89_BF_NUM; __i++)		\
1132 			ptr[__i] = rtw89_phy_read_txpwr_limit(rtwdev,	\
1133 							      bw, ntx,	\
1134 							      rs, __i,	\
1135 							      (ch));	\
1136 	} while (0)
1137 
1138 static void rtw89_phy_fill_txpwr_limit_20m(struct rtw89_dev *rtwdev,
1139 					   struct rtw89_txpwr_limit *lmt,
1140 					   u8 ntx, u8 ch)
1141 {
1142 	__fill_txpwr_limit_nonbf_bf(lmt->cck_20m, RTW89_CHANNEL_WIDTH_20,
1143 				    ntx, RTW89_RS_CCK, ch);
1144 	__fill_txpwr_limit_nonbf_bf(lmt->cck_40m, RTW89_CHANNEL_WIDTH_40,
1145 				    ntx, RTW89_RS_CCK, ch);
1146 	__fill_txpwr_limit_nonbf_bf(lmt->ofdm, RTW89_CHANNEL_WIDTH_20,
1147 				    ntx, RTW89_RS_OFDM, ch);
1148 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[0], RTW89_CHANNEL_WIDTH_20,
1149 				    ntx, RTW89_RS_MCS, ch);
1150 }
1151 
1152 static void rtw89_phy_fill_txpwr_limit_40m(struct rtw89_dev *rtwdev,
1153 					   struct rtw89_txpwr_limit *lmt,
1154 					   u8 ntx, u8 ch)
1155 {
1156 	__fill_txpwr_limit_nonbf_bf(lmt->cck_20m, RTW89_CHANNEL_WIDTH_20,
1157 				    ntx, RTW89_RS_CCK, ch - 2);
1158 	__fill_txpwr_limit_nonbf_bf(lmt->cck_40m, RTW89_CHANNEL_WIDTH_40,
1159 				    ntx, RTW89_RS_CCK, ch);
1160 	__fill_txpwr_limit_nonbf_bf(lmt->ofdm, RTW89_CHANNEL_WIDTH_20,
1161 				    ntx, RTW89_RS_OFDM, ch - 2);
1162 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[0], RTW89_CHANNEL_WIDTH_20,
1163 				    ntx, RTW89_RS_MCS, ch - 2);
1164 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[1], RTW89_CHANNEL_WIDTH_20,
1165 				    ntx, RTW89_RS_MCS, ch + 2);
1166 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_40m[0], RTW89_CHANNEL_WIDTH_40,
1167 				    ntx, RTW89_RS_MCS, ch);
1168 }
1169 
1170 static void rtw89_phy_fill_txpwr_limit_80m(struct rtw89_dev *rtwdev,
1171 					   struct rtw89_txpwr_limit *lmt,
1172 					   u8 ntx, u8 ch)
1173 {
1174 	s8 val_0p5_n[RTW89_BF_NUM];
1175 	s8 val_0p5_p[RTW89_BF_NUM];
1176 	u8 i;
1177 
1178 	__fill_txpwr_limit_nonbf_bf(lmt->ofdm, RTW89_CHANNEL_WIDTH_20,
1179 				    ntx, RTW89_RS_OFDM, ch - 6);
1180 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[0], RTW89_CHANNEL_WIDTH_20,
1181 				    ntx, RTW89_RS_MCS, ch - 6);
1182 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[1], RTW89_CHANNEL_WIDTH_20,
1183 				    ntx, RTW89_RS_MCS, ch - 2);
1184 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[2], RTW89_CHANNEL_WIDTH_20,
1185 				    ntx, RTW89_RS_MCS, ch + 2);
1186 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_20m[3], RTW89_CHANNEL_WIDTH_20,
1187 				    ntx, RTW89_RS_MCS, ch + 6);
1188 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_40m[0], RTW89_CHANNEL_WIDTH_40,
1189 				    ntx, RTW89_RS_MCS, ch - 4);
1190 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_40m[1], RTW89_CHANNEL_WIDTH_40,
1191 				    ntx, RTW89_RS_MCS, ch + 4);
1192 	__fill_txpwr_limit_nonbf_bf(lmt->mcs_80m[0], RTW89_CHANNEL_WIDTH_80,
1193 				    ntx, RTW89_RS_MCS, ch);
1194 
1195 	__fill_txpwr_limit_nonbf_bf(val_0p5_n, RTW89_CHANNEL_WIDTH_40,
1196 				    ntx, RTW89_RS_MCS, ch - 4);
1197 	__fill_txpwr_limit_nonbf_bf(val_0p5_p, RTW89_CHANNEL_WIDTH_40,
1198 				    ntx, RTW89_RS_MCS, ch + 4);
1199 
1200 	for (i = 0; i < RTW89_BF_NUM; i++)
1201 		lmt->mcs_40m_0p5[i] = min_t(s8, val_0p5_n[i], val_0p5_p[i]);
1202 }
1203 
1204 void rtw89_phy_fill_txpwr_limit(struct rtw89_dev *rtwdev,
1205 				struct rtw89_txpwr_limit *lmt,
1206 				u8 ntx)
1207 {
1208 	u8 ch = rtwdev->hal.current_channel;
1209 	u8 bw = rtwdev->hal.current_band_width;
1210 
1211 	memset(lmt, 0, sizeof(*lmt));
1212 
1213 	switch (bw) {
1214 	case RTW89_CHANNEL_WIDTH_20:
1215 		rtw89_phy_fill_txpwr_limit_20m(rtwdev, lmt, ntx, ch);
1216 		break;
1217 	case RTW89_CHANNEL_WIDTH_40:
1218 		rtw89_phy_fill_txpwr_limit_40m(rtwdev, lmt, ntx, ch);
1219 		break;
1220 	case RTW89_CHANNEL_WIDTH_80:
1221 		rtw89_phy_fill_txpwr_limit_80m(rtwdev, lmt, ntx, ch);
1222 		break;
1223 	}
1224 }
1225 
1226 static s8 rtw89_phy_read_txpwr_limit_ru(struct rtw89_dev *rtwdev,
1227 					u8 ru, u8 ntx, u8 ch)
1228 {
1229 	const struct rtw89_chip_info *chip = rtwdev->chip;
1230 	u8 ch_idx = rtw89_channel_to_idx(rtwdev, ch);
1231 	u8 band = rtwdev->hal.current_band_type;
1232 	u8 regd = rtw89_regd_get(rtwdev, band);
1233 	s8 lmt_ru = 0, sar;
1234 
1235 	switch (band) {
1236 	case RTW89_BAND_2G:
1237 		lmt_ru = (*chip->txpwr_lmt_ru_2g)[ru][ntx][regd][ch_idx];
1238 		if (!lmt_ru)
1239 			lmt_ru = (*chip->txpwr_lmt_ru_2g)[ru][ntx]
1240 							 [RTW89_WW][ch_idx];
1241 		break;
1242 	case RTW89_BAND_5G:
1243 		lmt_ru = (*chip->txpwr_lmt_ru_5g)[ru][ntx][regd][ch_idx];
1244 		if (!lmt_ru)
1245 			lmt_ru = (*chip->txpwr_lmt_ru_5g)[ru][ntx]
1246 							 [RTW89_WW][ch_idx];
1247 		break;
1248 	default:
1249 		rtw89_warn(rtwdev, "unknown band type: %d\n", band);
1250 		return 0;
1251 	}
1252 
1253 	lmt_ru = _phy_txpwr_rf_to_mac(rtwdev, lmt_ru);
1254 	sar = rtw89_query_sar(rtwdev);
1255 
1256 	return min(lmt_ru, sar);
1257 }
1258 
1259 static void
1260 rtw89_phy_fill_txpwr_limit_ru_20m(struct rtw89_dev *rtwdev,
1261 				  struct rtw89_txpwr_limit_ru *lmt_ru,
1262 				  u8 ntx, u8 ch)
1263 {
1264 	lmt_ru->ru26[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU26,
1265 							ntx, ch);
1266 	lmt_ru->ru52[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU52,
1267 							ntx, ch);
1268 	lmt_ru->ru106[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU106,
1269 							 ntx, ch);
1270 }
1271 
1272 static void
1273 rtw89_phy_fill_txpwr_limit_ru_40m(struct rtw89_dev *rtwdev,
1274 				  struct rtw89_txpwr_limit_ru *lmt_ru,
1275 				  u8 ntx, u8 ch)
1276 {
1277 	lmt_ru->ru26[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU26,
1278 							ntx, ch - 2);
1279 	lmt_ru->ru26[1] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU26,
1280 							ntx, ch + 2);
1281 	lmt_ru->ru52[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU52,
1282 							ntx, ch - 2);
1283 	lmt_ru->ru52[1] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU52,
1284 							ntx, ch + 2);
1285 	lmt_ru->ru106[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU106,
1286 							 ntx, ch - 2);
1287 	lmt_ru->ru106[1] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU106,
1288 							 ntx, ch + 2);
1289 }
1290 
1291 static void
1292 rtw89_phy_fill_txpwr_limit_ru_80m(struct rtw89_dev *rtwdev,
1293 				  struct rtw89_txpwr_limit_ru *lmt_ru,
1294 				  u8 ntx, u8 ch)
1295 {
1296 	lmt_ru->ru26[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU26,
1297 							ntx, ch - 6);
1298 	lmt_ru->ru26[1] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU26,
1299 							ntx, ch - 2);
1300 	lmt_ru->ru26[2] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU26,
1301 							ntx, ch + 2);
1302 	lmt_ru->ru26[3] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU26,
1303 							ntx, ch + 6);
1304 	lmt_ru->ru52[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU52,
1305 							ntx, ch - 6);
1306 	lmt_ru->ru52[1] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU52,
1307 							ntx, ch - 2);
1308 	lmt_ru->ru52[2] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU52,
1309 							ntx, ch + 2);
1310 	lmt_ru->ru52[3] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU52,
1311 							ntx, ch + 6);
1312 	lmt_ru->ru106[0] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU106,
1313 							 ntx, ch - 6);
1314 	lmt_ru->ru106[1] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU106,
1315 							 ntx, ch - 2);
1316 	lmt_ru->ru106[2] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU106,
1317 							 ntx, ch + 2);
1318 	lmt_ru->ru106[3] = rtw89_phy_read_txpwr_limit_ru(rtwdev, RTW89_RU106,
1319 							 ntx, ch + 6);
1320 }
1321 
1322 void rtw89_phy_fill_txpwr_limit_ru(struct rtw89_dev *rtwdev,
1323 				   struct rtw89_txpwr_limit_ru *lmt_ru,
1324 				   u8 ntx)
1325 {
1326 	u8 ch = rtwdev->hal.current_channel;
1327 	u8 bw = rtwdev->hal.current_band_width;
1328 
1329 	memset(lmt_ru, 0, sizeof(*lmt_ru));
1330 
1331 	switch (bw) {
1332 	case RTW89_CHANNEL_WIDTH_20:
1333 		rtw89_phy_fill_txpwr_limit_ru_20m(rtwdev, lmt_ru, ntx, ch);
1334 		break;
1335 	case RTW89_CHANNEL_WIDTH_40:
1336 		rtw89_phy_fill_txpwr_limit_ru_40m(rtwdev, lmt_ru, ntx, ch);
1337 		break;
1338 	case RTW89_CHANNEL_WIDTH_80:
1339 		rtw89_phy_fill_txpwr_limit_ru_80m(rtwdev, lmt_ru, ntx, ch);
1340 		break;
1341 	}
1342 }
1343 
1344 struct rtw89_phy_iter_ra_data {
1345 	struct rtw89_dev *rtwdev;
1346 	struct sk_buff *c2h;
1347 };
1348 
1349 static void rtw89_phy_c2h_ra_rpt_iter(void *data, struct ieee80211_sta *sta)
1350 {
1351 	struct rtw89_phy_iter_ra_data *ra_data = (struct rtw89_phy_iter_ra_data *)data;
1352 	struct rtw89_dev *rtwdev = ra_data->rtwdev;
1353 	struct rtw89_sta *rtwsta = (struct rtw89_sta *)sta->drv_priv;
1354 	struct rtw89_ra_report *ra_report = &rtwsta->ra_report;
1355 	struct sk_buff *c2h = ra_data->c2h;
1356 	u8 mode, rate, bw, giltf, mac_id;
1357 
1358 	mac_id = RTW89_GET_PHY_C2H_RA_RPT_MACID(c2h->data);
1359 	if (mac_id != rtwsta->mac_id)
1360 		return;
1361 
1362 	memset(ra_report, 0, sizeof(*ra_report));
1363 
1364 	rate = RTW89_GET_PHY_C2H_RA_RPT_MCSNSS(c2h->data);
1365 	bw = RTW89_GET_PHY_C2H_RA_RPT_BW(c2h->data);
1366 	giltf = RTW89_GET_PHY_C2H_RA_RPT_GILTF(c2h->data);
1367 	mode = RTW89_GET_PHY_C2H_RA_RPT_MD_SEL(c2h->data);
1368 
1369 	switch (mode) {
1370 	case RTW89_RA_RPT_MODE_LEGACY:
1371 		ra_report->txrate.legacy = rtw89_ra_report_to_bitrate(rtwdev, rate);
1372 		break;
1373 	case RTW89_RA_RPT_MODE_HT:
1374 		ra_report->txrate.flags |= RATE_INFO_FLAGS_MCS;
1375 		if (rtwdev->fw.old_ht_ra_format)
1376 			rate = RTW89_MK_HT_RATE(FIELD_GET(RTW89_RA_RATE_MASK_NSS, rate),
1377 						FIELD_GET(RTW89_RA_RATE_MASK_MCS, rate));
1378 		else
1379 			rate = FIELD_GET(RTW89_RA_RATE_MASK_HT_MCS, rate);
1380 		ra_report->txrate.mcs = rate;
1381 		if (giltf)
1382 			ra_report->txrate.flags |= RATE_INFO_FLAGS_SHORT_GI;
1383 		break;
1384 	case RTW89_RA_RPT_MODE_VHT:
1385 		ra_report->txrate.flags |= RATE_INFO_FLAGS_VHT_MCS;
1386 		ra_report->txrate.mcs = FIELD_GET(RTW89_RA_RATE_MASK_MCS, rate);
1387 		ra_report->txrate.nss = FIELD_GET(RTW89_RA_RATE_MASK_NSS, rate) + 1;
1388 		if (giltf)
1389 			ra_report->txrate.flags |= RATE_INFO_FLAGS_SHORT_GI;
1390 		break;
1391 	case RTW89_RA_RPT_MODE_HE:
1392 		ra_report->txrate.flags |= RATE_INFO_FLAGS_HE_MCS;
1393 		ra_report->txrate.mcs = FIELD_GET(RTW89_RA_RATE_MASK_MCS, rate);
1394 		ra_report->txrate.nss = FIELD_GET(RTW89_RA_RATE_MASK_NSS, rate) + 1;
1395 		if (giltf == RTW89_GILTF_2XHE08 || giltf == RTW89_GILTF_1XHE08)
1396 			ra_report->txrate.he_gi = NL80211_RATE_INFO_HE_GI_0_8;
1397 		else if (giltf == RTW89_GILTF_2XHE16 || giltf == RTW89_GILTF_1XHE16)
1398 			ra_report->txrate.he_gi = NL80211_RATE_INFO_HE_GI_1_6;
1399 		else
1400 			ra_report->txrate.he_gi = NL80211_RATE_INFO_HE_GI_3_2;
1401 		break;
1402 	}
1403 
1404 	if (bw == RTW89_CHANNEL_WIDTH_80)
1405 		ra_report->txrate.bw = RATE_INFO_BW_80;
1406 	else if (bw == RTW89_CHANNEL_WIDTH_40)
1407 		ra_report->txrate.bw = RATE_INFO_BW_40;
1408 	else
1409 		ra_report->txrate.bw = RATE_INFO_BW_20;
1410 
1411 	ra_report->bit_rate = cfg80211_calculate_bitrate(&ra_report->txrate);
1412 	ra_report->hw_rate = FIELD_PREP(RTW89_HW_RATE_MASK_MOD, mode) |
1413 			     FIELD_PREP(RTW89_HW_RATE_MASK_VAL, rate);
1414 	sta->max_rc_amsdu_len = get_max_amsdu_len(rtwdev, ra_report);
1415 	rtwsta->max_agg_wait = sta->max_rc_amsdu_len / 1500 - 1;
1416 }
1417 
1418 static void
1419 rtw89_phy_c2h_ra_rpt(struct rtw89_dev *rtwdev, struct sk_buff *c2h, u32 len)
1420 {
1421 	struct rtw89_phy_iter_ra_data ra_data;
1422 
1423 	ra_data.rtwdev = rtwdev;
1424 	ra_data.c2h = c2h;
1425 	ieee80211_iterate_stations_atomic(rtwdev->hw,
1426 					  rtw89_phy_c2h_ra_rpt_iter,
1427 					  &ra_data);
1428 }
1429 
1430 static
1431 void (* const rtw89_phy_c2h_ra_handler[])(struct rtw89_dev *rtwdev,
1432 					  struct sk_buff *c2h, u32 len) = {
1433 	[RTW89_PHY_C2H_FUNC_STS_RPT] = rtw89_phy_c2h_ra_rpt,
1434 	[RTW89_PHY_C2H_FUNC_MU_GPTBL_RPT] = NULL,
1435 	[RTW89_PHY_C2H_FUNC_TXSTS] = NULL,
1436 };
1437 
1438 void rtw89_phy_c2h_handle(struct rtw89_dev *rtwdev, struct sk_buff *skb,
1439 			  u32 len, u8 class, u8 func)
1440 {
1441 	void (*handler)(struct rtw89_dev *rtwdev,
1442 			struct sk_buff *c2h, u32 len) = NULL;
1443 
1444 	switch (class) {
1445 	case RTW89_PHY_C2H_CLASS_RA:
1446 		if (func < RTW89_PHY_C2H_FUNC_RA_MAX)
1447 			handler = rtw89_phy_c2h_ra_handler[func];
1448 		break;
1449 	default:
1450 		rtw89_info(rtwdev, "c2h class %d not support\n", class);
1451 		return;
1452 	}
1453 	if (!handler) {
1454 		rtw89_info(rtwdev, "c2h class %d func %d not support\n", class,
1455 			   func);
1456 		return;
1457 	}
1458 	handler(rtwdev, skb, len);
1459 }
1460 
1461 static u8 rtw89_phy_cfo_get_xcap_reg(struct rtw89_dev *rtwdev, bool sc_xo)
1462 {
1463 	u32 reg_mask;
1464 
1465 	if (sc_xo)
1466 		reg_mask = B_AX_XTAL_SC_XO_MASK;
1467 	else
1468 		reg_mask = B_AX_XTAL_SC_XI_MASK;
1469 
1470 	return (u8)rtw89_read32_mask(rtwdev, R_AX_XTAL_ON_CTRL0, reg_mask);
1471 }
1472 
1473 static void rtw89_phy_cfo_set_xcap_reg(struct rtw89_dev *rtwdev, bool sc_xo,
1474 				       u8 val)
1475 {
1476 	u32 reg_mask;
1477 
1478 	if (sc_xo)
1479 		reg_mask = B_AX_XTAL_SC_XO_MASK;
1480 	else
1481 		reg_mask = B_AX_XTAL_SC_XI_MASK;
1482 
1483 	rtw89_write32_mask(rtwdev, R_AX_XTAL_ON_CTRL0, reg_mask, val);
1484 }
1485 
1486 static void rtw89_phy_cfo_set_crystal_cap(struct rtw89_dev *rtwdev,
1487 					  u8 crystal_cap, bool force)
1488 {
1489 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
1490 	u8 sc_xi_val, sc_xo_val;
1491 
1492 	if (!force && cfo->crystal_cap == crystal_cap)
1493 		return;
1494 	crystal_cap = clamp_t(u8, crystal_cap, 0, 127);
1495 	rtw89_phy_cfo_set_xcap_reg(rtwdev, true, crystal_cap);
1496 	rtw89_phy_cfo_set_xcap_reg(rtwdev, false, crystal_cap);
1497 	sc_xo_val = rtw89_phy_cfo_get_xcap_reg(rtwdev, true);
1498 	sc_xi_val = rtw89_phy_cfo_get_xcap_reg(rtwdev, false);
1499 	cfo->crystal_cap = sc_xi_val;
1500 	cfo->x_cap_ofst = (s8)((int)cfo->crystal_cap - cfo->def_x_cap);
1501 
1502 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Set sc_xi=0x%x\n", sc_xi_val);
1503 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Set sc_xo=0x%x\n", sc_xo_val);
1504 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Get xcap_ofst=%d\n",
1505 		    cfo->x_cap_ofst);
1506 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Set xcap OK\n");
1507 }
1508 
1509 static void rtw89_phy_cfo_reset(struct rtw89_dev *rtwdev)
1510 {
1511 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
1512 	u8 cap;
1513 
1514 	cfo->def_x_cap = cfo->crystal_cap_default & B_AX_XTAL_SC_MASK;
1515 	cfo->is_adjust = false;
1516 	if (cfo->crystal_cap == cfo->def_x_cap)
1517 		return;
1518 	cap = cfo->crystal_cap;
1519 	cap += (cap > cfo->def_x_cap ? -1 : 1);
1520 	rtw89_phy_cfo_set_crystal_cap(rtwdev, cap, false);
1521 	rtw89_debug(rtwdev, RTW89_DBG_CFO,
1522 		    "(0x%x) approach to dflt_val=(0x%x)\n", cfo->crystal_cap,
1523 		    cfo->def_x_cap);
1524 }
1525 
1526 static void rtw89_dcfo_comp(struct rtw89_dev *rtwdev, s32 curr_cfo)
1527 {
1528 	bool is_linked = rtwdev->total_sta_assoc > 0;
1529 	s32 cfo_avg_312;
1530 	s32 dcfo_comp;
1531 	int sign;
1532 
1533 	if (!is_linked) {
1534 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "DCFO: is_linked=%d\n",
1535 			    is_linked);
1536 		return;
1537 	}
1538 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "DCFO: curr_cfo=%d\n", curr_cfo);
1539 	if (curr_cfo == 0)
1540 		return;
1541 	dcfo_comp = rtw89_phy_read32_mask(rtwdev, R_DCFO, B_DCFO);
1542 	sign = curr_cfo > 0 ? 1 : -1;
1543 	cfo_avg_312 = (curr_cfo << 3) / 5 + sign * dcfo_comp;
1544 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "DCFO: avg_cfo=%d\n", cfo_avg_312);
1545 	if (rtwdev->chip->chip_id == RTL8852A && rtwdev->hal.cv == CHIP_CBV)
1546 		cfo_avg_312 = -cfo_avg_312;
1547 	rtw89_phy_set_phy_regs(rtwdev, R_DCFO_COMP_S0, B_DCFO_COMP_S0_MSK,
1548 			       cfo_avg_312);
1549 }
1550 
1551 static void rtw89_dcfo_comp_init(struct rtw89_dev *rtwdev)
1552 {
1553 	rtw89_phy_set_phy_regs(rtwdev, R_DCFO_OPT, B_DCFO_OPT_EN, 1);
1554 	rtw89_phy_set_phy_regs(rtwdev, R_DCFO_WEIGHT, B_DCFO_WEIGHT_MSK, 8);
1555 	rtw89_write32_clr(rtwdev, R_AX_PWR_UL_CTRL2, B_AX_PWR_UL_CFO_MASK);
1556 }
1557 
1558 static void rtw89_phy_cfo_init(struct rtw89_dev *rtwdev)
1559 {
1560 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
1561 	struct rtw89_efuse *efuse = &rtwdev->efuse;
1562 
1563 	cfo->crystal_cap_default = efuse->xtal_cap & B_AX_XTAL_SC_MASK;
1564 	cfo->crystal_cap = cfo->crystal_cap_default;
1565 	cfo->def_x_cap = cfo->crystal_cap;
1566 	cfo->is_adjust = false;
1567 	cfo->x_cap_ofst = 0;
1568 	cfo->rtw89_multi_cfo_mode = RTW89_TP_BASED_AVG_MODE;
1569 	cfo->apply_compensation = false;
1570 	cfo->residual_cfo_acc = 0;
1571 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Default xcap=%0x\n",
1572 		    cfo->crystal_cap_default);
1573 	rtw89_phy_cfo_set_crystal_cap(rtwdev, cfo->crystal_cap_default, true);
1574 	rtw89_phy_set_phy_regs(rtwdev, R_DCFO, B_DCFO, 1);
1575 	rtw89_dcfo_comp_init(rtwdev);
1576 	cfo->cfo_timer_ms = 2000;
1577 	cfo->cfo_trig_by_timer_en = false;
1578 	cfo->phy_cfo_trk_cnt = 0;
1579 	cfo->phy_cfo_status = RTW89_PHY_DCFO_STATE_NORMAL;
1580 }
1581 
1582 static void rtw89_phy_cfo_crystal_cap_adjust(struct rtw89_dev *rtwdev,
1583 					     s32 curr_cfo)
1584 {
1585 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
1586 	s8 crystal_cap = cfo->crystal_cap;
1587 	s32 cfo_abs = abs(curr_cfo);
1588 	int sign;
1589 
1590 	if (!cfo->is_adjust) {
1591 		if (cfo_abs > CFO_TRK_ENABLE_TH)
1592 			cfo->is_adjust = true;
1593 	} else {
1594 		if (cfo_abs < CFO_TRK_STOP_TH)
1595 			cfo->is_adjust = false;
1596 	}
1597 	if (!cfo->is_adjust) {
1598 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "Stop CFO tracking\n");
1599 		return;
1600 	}
1601 	sign = curr_cfo > 0 ? 1 : -1;
1602 	if (cfo_abs > CFO_TRK_STOP_TH_4)
1603 		crystal_cap += 7 * sign;
1604 	else if (cfo_abs > CFO_TRK_STOP_TH_3)
1605 		crystal_cap += 5 * sign;
1606 	else if (cfo_abs > CFO_TRK_STOP_TH_2)
1607 		crystal_cap += 3 * sign;
1608 	else if (cfo_abs > CFO_TRK_STOP_TH_1)
1609 		crystal_cap += 1 * sign;
1610 	else
1611 		return;
1612 	rtw89_phy_cfo_set_crystal_cap(rtwdev, (u8)crystal_cap, false);
1613 	rtw89_debug(rtwdev, RTW89_DBG_CFO,
1614 		    "X_cap{Curr,Default}={0x%x,0x%x}\n",
1615 		    cfo->crystal_cap, cfo->def_x_cap);
1616 }
1617 
1618 static s32 rtw89_phy_average_cfo_calc(struct rtw89_dev *rtwdev)
1619 {
1620 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
1621 	s32 cfo_khz_all = 0;
1622 	s32 cfo_cnt_all = 0;
1623 	s32 cfo_all_avg = 0;
1624 	u8 i;
1625 
1626 	if (rtwdev->total_sta_assoc != 1)
1627 		return 0;
1628 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "one_entry_only\n");
1629 	for (i = 0; i < CFO_TRACK_MAX_USER; i++) {
1630 		if (cfo->cfo_cnt[i] == 0)
1631 			continue;
1632 		cfo_khz_all += cfo->cfo_tail[i];
1633 		cfo_cnt_all += cfo->cfo_cnt[i];
1634 		cfo_all_avg = phy_div(cfo_khz_all, cfo_cnt_all);
1635 		cfo->pre_cfo_avg[i] = cfo->cfo_avg[i];
1636 	}
1637 	rtw89_debug(rtwdev, RTW89_DBG_CFO,
1638 		    "CFO track for macid = %d\n", i);
1639 	rtw89_debug(rtwdev, RTW89_DBG_CFO,
1640 		    "Total cfo=%dK, pkt_cnt=%d, avg_cfo=%dK\n",
1641 		    cfo_khz_all, cfo_cnt_all, cfo_all_avg);
1642 	return cfo_all_avg;
1643 }
1644 
1645 static s32 rtw89_phy_multi_sta_cfo_calc(struct rtw89_dev *rtwdev)
1646 {
1647 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
1648 	struct rtw89_traffic_stats *stats = &rtwdev->stats;
1649 	s32 target_cfo = 0;
1650 	s32 cfo_khz_all = 0;
1651 	s32 cfo_khz_all_tp_wgt = 0;
1652 	s32 cfo_avg = 0;
1653 	s32 max_cfo_lb = BIT(31);
1654 	s32 min_cfo_ub = GENMASK(30, 0);
1655 	u16 cfo_cnt_all = 0;
1656 	u8 active_entry_cnt = 0;
1657 	u8 sta_cnt = 0;
1658 	u32 tp_all = 0;
1659 	u8 i;
1660 	u8 cfo_tol = 0;
1661 
1662 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Multi entry cfo_trk\n");
1663 	if (cfo->rtw89_multi_cfo_mode == RTW89_PKT_BASED_AVG_MODE) {
1664 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "Pkt based avg mode\n");
1665 		for (i = 0; i < CFO_TRACK_MAX_USER; i++) {
1666 			if (cfo->cfo_cnt[i] == 0)
1667 				continue;
1668 			cfo_khz_all += cfo->cfo_tail[i];
1669 			cfo_cnt_all += cfo->cfo_cnt[i];
1670 			cfo_avg = phy_div(cfo_khz_all, (s32)cfo_cnt_all);
1671 			rtw89_debug(rtwdev, RTW89_DBG_CFO,
1672 				    "Msta cfo=%d, pkt_cnt=%d, avg_cfo=%d\n",
1673 				    cfo_khz_all, cfo_cnt_all, cfo_avg);
1674 			target_cfo = cfo_avg;
1675 		}
1676 	} else if (cfo->rtw89_multi_cfo_mode == RTW89_ENTRY_BASED_AVG_MODE) {
1677 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "Entry based avg mode\n");
1678 		for (i = 0; i < CFO_TRACK_MAX_USER; i++) {
1679 			if (cfo->cfo_cnt[i] == 0)
1680 				continue;
1681 			cfo->cfo_avg[i] = phy_div(cfo->cfo_tail[i],
1682 						  (s32)cfo->cfo_cnt[i]);
1683 			cfo_khz_all += cfo->cfo_avg[i];
1684 			rtw89_debug(rtwdev, RTW89_DBG_CFO,
1685 				    "Macid=%d, cfo_avg=%d\n", i,
1686 				    cfo->cfo_avg[i]);
1687 		}
1688 		sta_cnt = rtwdev->total_sta_assoc;
1689 		cfo_avg = phy_div(cfo_khz_all, (s32)sta_cnt);
1690 		rtw89_debug(rtwdev, RTW89_DBG_CFO,
1691 			    "Msta cfo_acc=%d, ent_cnt=%d, avg_cfo=%d\n",
1692 			    cfo_khz_all, sta_cnt, cfo_avg);
1693 		target_cfo = cfo_avg;
1694 	} else if (cfo->rtw89_multi_cfo_mode == RTW89_TP_BASED_AVG_MODE) {
1695 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "TP based avg mode\n");
1696 		cfo_tol = cfo->sta_cfo_tolerance;
1697 		for (i = 0; i < CFO_TRACK_MAX_USER; i++) {
1698 			sta_cnt++;
1699 			if (cfo->cfo_cnt[i] != 0) {
1700 				cfo->cfo_avg[i] = phy_div(cfo->cfo_tail[i],
1701 							  (s32)cfo->cfo_cnt[i]);
1702 				active_entry_cnt++;
1703 			} else {
1704 				cfo->cfo_avg[i] = cfo->pre_cfo_avg[i];
1705 			}
1706 			max_cfo_lb = max(cfo->cfo_avg[i] - cfo_tol, max_cfo_lb);
1707 			min_cfo_ub = min(cfo->cfo_avg[i] + cfo_tol, min_cfo_ub);
1708 			cfo_khz_all += cfo->cfo_avg[i];
1709 			/* need tp for each entry */
1710 			rtw89_debug(rtwdev, RTW89_DBG_CFO,
1711 				    "[%d] cfo_avg=%d, tp=tbd\n",
1712 				    i, cfo->cfo_avg[i]);
1713 			if (sta_cnt >= rtwdev->total_sta_assoc)
1714 				break;
1715 		}
1716 		tp_all = stats->rx_throughput; /* need tp for each entry */
1717 		cfo_avg =  phy_div(cfo_khz_all_tp_wgt, (s32)tp_all);
1718 
1719 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "Assoc sta cnt=%d\n",
1720 			    sta_cnt);
1721 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "Active sta cnt=%d\n",
1722 			    active_entry_cnt);
1723 		rtw89_debug(rtwdev, RTW89_DBG_CFO,
1724 			    "Msta cfo with tp_wgt=%d, avg_cfo=%d\n",
1725 			    cfo_khz_all_tp_wgt, cfo_avg);
1726 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "cfo_lb=%d,cfo_ub=%d\n",
1727 			    max_cfo_lb, min_cfo_ub);
1728 		if (max_cfo_lb <= min_cfo_ub) {
1729 			rtw89_debug(rtwdev, RTW89_DBG_CFO,
1730 				    "cfo win_size=%d\n",
1731 				    min_cfo_ub - max_cfo_lb);
1732 			target_cfo = clamp(cfo_avg, max_cfo_lb, min_cfo_ub);
1733 		} else {
1734 			rtw89_debug(rtwdev, RTW89_DBG_CFO,
1735 				    "No intersection of cfo tolerance windows\n");
1736 			target_cfo = phy_div(cfo_khz_all, (s32)sta_cnt);
1737 		}
1738 		for (i = 0; i < CFO_TRACK_MAX_USER; i++)
1739 			cfo->pre_cfo_avg[i] = cfo->cfo_avg[i];
1740 	}
1741 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Target cfo=%d\n", target_cfo);
1742 	return target_cfo;
1743 }
1744 
1745 static void rtw89_phy_cfo_statistics_reset(struct rtw89_dev *rtwdev)
1746 {
1747 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
1748 
1749 	memset(&cfo->cfo_tail, 0, sizeof(cfo->cfo_tail));
1750 	memset(&cfo->cfo_cnt, 0, sizeof(cfo->cfo_cnt));
1751 	cfo->packet_count = 0;
1752 	cfo->packet_count_pre = 0;
1753 	cfo->cfo_avg_pre = 0;
1754 }
1755 
1756 static void rtw89_phy_cfo_dm(struct rtw89_dev *rtwdev)
1757 {
1758 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
1759 	s32 new_cfo = 0;
1760 	bool x_cap_update = false;
1761 	u8 pre_x_cap = cfo->crystal_cap;
1762 
1763 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "CFO:total_sta_assoc=%d\n",
1764 		    rtwdev->total_sta_assoc);
1765 	if (rtwdev->total_sta_assoc == 0) {
1766 		rtw89_phy_cfo_reset(rtwdev);
1767 		return;
1768 	}
1769 	if (cfo->packet_count == 0) {
1770 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "Pkt cnt = 0\n");
1771 		return;
1772 	}
1773 	if (cfo->packet_count == cfo->packet_count_pre) {
1774 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "Pkt cnt doesn't change\n");
1775 		return;
1776 	}
1777 	if (rtwdev->total_sta_assoc == 1)
1778 		new_cfo = rtw89_phy_average_cfo_calc(rtwdev);
1779 	else
1780 		new_cfo = rtw89_phy_multi_sta_cfo_calc(rtwdev);
1781 	if (new_cfo == 0) {
1782 		rtw89_debug(rtwdev, RTW89_DBG_CFO, "curr_cfo=0\n");
1783 		return;
1784 	}
1785 	rtw89_phy_cfo_crystal_cap_adjust(rtwdev, new_cfo);
1786 	cfo->cfo_avg_pre = new_cfo;
1787 	x_cap_update =  cfo->crystal_cap != pre_x_cap;
1788 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Xcap_up=%d\n", x_cap_update);
1789 	rtw89_debug(rtwdev, RTW89_DBG_CFO, "Xcap: D:%x C:%x->%x, ofst=%d\n",
1790 		    cfo->def_x_cap, pre_x_cap, cfo->crystal_cap,
1791 		    cfo->x_cap_ofst);
1792 	if (x_cap_update) {
1793 		if (new_cfo > 0)
1794 			new_cfo -= CFO_SW_COMP_FINE_TUNE;
1795 		else
1796 			new_cfo += CFO_SW_COMP_FINE_TUNE;
1797 	}
1798 	rtw89_dcfo_comp(rtwdev, new_cfo);
1799 	rtw89_phy_cfo_statistics_reset(rtwdev);
1800 }
1801 
1802 void rtw89_phy_cfo_track_work(struct work_struct *work)
1803 {
1804 	struct rtw89_dev *rtwdev = container_of(work, struct rtw89_dev,
1805 						cfo_track_work.work);
1806 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
1807 
1808 	mutex_lock(&rtwdev->mutex);
1809 	if (!cfo->cfo_trig_by_timer_en)
1810 		goto out;
1811 	rtw89_leave_ps_mode(rtwdev);
1812 	rtw89_phy_cfo_dm(rtwdev);
1813 	ieee80211_queue_delayed_work(rtwdev->hw, &rtwdev->cfo_track_work,
1814 				     msecs_to_jiffies(cfo->cfo_timer_ms));
1815 out:
1816 	mutex_unlock(&rtwdev->mutex);
1817 }
1818 
1819 static void rtw89_phy_cfo_start_work(struct rtw89_dev *rtwdev)
1820 {
1821 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
1822 
1823 	ieee80211_queue_delayed_work(rtwdev->hw, &rtwdev->cfo_track_work,
1824 				     msecs_to_jiffies(cfo->cfo_timer_ms));
1825 }
1826 
1827 void rtw89_phy_cfo_track(struct rtw89_dev *rtwdev)
1828 {
1829 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
1830 	struct rtw89_traffic_stats *stats = &rtwdev->stats;
1831 
1832 	switch (cfo->phy_cfo_status) {
1833 	case RTW89_PHY_DCFO_STATE_NORMAL:
1834 		if (stats->tx_throughput >= CFO_TP_UPPER) {
1835 			cfo->phy_cfo_status = RTW89_PHY_DCFO_STATE_ENHANCE;
1836 			cfo->cfo_trig_by_timer_en = true;
1837 			cfo->cfo_timer_ms = CFO_COMP_PERIOD;
1838 			rtw89_phy_cfo_start_work(rtwdev);
1839 		}
1840 		break;
1841 	case RTW89_PHY_DCFO_STATE_ENHANCE:
1842 		if (cfo->phy_cfo_trk_cnt >= CFO_PERIOD_CNT) {
1843 			cfo->phy_cfo_trk_cnt = 0;
1844 			cfo->cfo_trig_by_timer_en = false;
1845 		}
1846 		if (cfo->cfo_trig_by_timer_en == 1)
1847 			cfo->phy_cfo_trk_cnt++;
1848 		if (stats->tx_throughput <= CFO_TP_LOWER) {
1849 			cfo->phy_cfo_status = RTW89_PHY_DCFO_STATE_NORMAL;
1850 			cfo->phy_cfo_trk_cnt = 0;
1851 			cfo->cfo_trig_by_timer_en = false;
1852 		}
1853 		break;
1854 	default:
1855 		cfo->phy_cfo_status = RTW89_PHY_DCFO_STATE_NORMAL;
1856 		cfo->phy_cfo_trk_cnt = 0;
1857 		break;
1858 	}
1859 	rtw89_debug(rtwdev, RTW89_DBG_CFO,
1860 		    "[CFO]WatchDog tp=%d,state=%d,timer_en=%d,trk_cnt=%d,thermal=%ld\n",
1861 		    stats->tx_throughput, cfo->phy_cfo_status,
1862 		    cfo->cfo_trig_by_timer_en, cfo->phy_cfo_trk_cnt,
1863 		    ewma_thermal_read(&rtwdev->phystat.avg_thermal[0]));
1864 	if (cfo->cfo_trig_by_timer_en)
1865 		return;
1866 	rtw89_phy_cfo_dm(rtwdev);
1867 }
1868 
1869 void rtw89_phy_cfo_parse(struct rtw89_dev *rtwdev, s16 cfo_val,
1870 			 struct rtw89_rx_phy_ppdu *phy_ppdu)
1871 {
1872 	struct rtw89_cfo_tracking_info *cfo = &rtwdev->cfo_tracking;
1873 	u8 macid = phy_ppdu->mac_id;
1874 
1875 	cfo->cfo_tail[macid] += cfo_val;
1876 	cfo->cfo_cnt[macid]++;
1877 	cfo->packet_count++;
1878 }
1879 
1880 static void rtw89_phy_stat_thermal_update(struct rtw89_dev *rtwdev)
1881 {
1882 	struct rtw89_phy_stat *phystat = &rtwdev->phystat;
1883 	int i;
1884 	u8 th;
1885 
1886 	for (i = 0; i < rtwdev->chip->rf_path_num; i++) {
1887 		th = rtw89_chip_get_thermal(rtwdev, i);
1888 		if (th)
1889 			ewma_thermal_add(&phystat->avg_thermal[i], th);
1890 
1891 		rtw89_debug(rtwdev, RTW89_DBG_RFK_TRACK,
1892 			    "path(%d) thermal cur=%u avg=%ld", i, th,
1893 			    ewma_thermal_read(&phystat->avg_thermal[i]));
1894 	}
1895 }
1896 
1897 struct rtw89_phy_iter_rssi_data {
1898 	struct rtw89_dev *rtwdev;
1899 	struct rtw89_phy_ch_info *ch_info;
1900 	bool rssi_changed;
1901 };
1902 
1903 static void rtw89_phy_stat_rssi_update_iter(void *data,
1904 					    struct ieee80211_sta *sta)
1905 {
1906 	struct rtw89_sta *rtwsta = (struct rtw89_sta *)sta->drv_priv;
1907 	struct rtw89_phy_iter_rssi_data *rssi_data =
1908 					(struct rtw89_phy_iter_rssi_data *)data;
1909 	struct rtw89_phy_ch_info *ch_info = rssi_data->ch_info;
1910 	unsigned long rssi_curr;
1911 
1912 	rssi_curr = ewma_rssi_read(&rtwsta->avg_rssi);
1913 
1914 	if (rssi_curr < ch_info->rssi_min) {
1915 		ch_info->rssi_min = rssi_curr;
1916 		ch_info->rssi_min_macid = rtwsta->mac_id;
1917 	}
1918 
1919 	if (rtwsta->prev_rssi == 0) {
1920 		rtwsta->prev_rssi = rssi_curr;
1921 	} else if (abs((int)rtwsta->prev_rssi - (int)rssi_curr) > (3 << RSSI_FACTOR)) {
1922 		rtwsta->prev_rssi = rssi_curr;
1923 		rssi_data->rssi_changed = true;
1924 	}
1925 }
1926 
1927 static void rtw89_phy_stat_rssi_update(struct rtw89_dev *rtwdev)
1928 {
1929 	struct rtw89_phy_iter_rssi_data rssi_data = {0};
1930 
1931 	rssi_data.rtwdev = rtwdev;
1932 	rssi_data.ch_info = &rtwdev->ch_info;
1933 	rssi_data.ch_info->rssi_min = U8_MAX;
1934 	ieee80211_iterate_stations_atomic(rtwdev->hw,
1935 					  rtw89_phy_stat_rssi_update_iter,
1936 					  &rssi_data);
1937 	if (rssi_data.rssi_changed)
1938 		rtw89_btc_ntfy_wl_sta(rtwdev);
1939 }
1940 
1941 static void rtw89_phy_stat_init(struct rtw89_dev *rtwdev)
1942 {
1943 	struct rtw89_phy_stat *phystat = &rtwdev->phystat;
1944 	int i;
1945 
1946 	for (i = 0; i < rtwdev->chip->rf_path_num; i++)
1947 		ewma_thermal_init(&phystat->avg_thermal[i]);
1948 
1949 	rtw89_phy_stat_thermal_update(rtwdev);
1950 
1951 	memset(&phystat->cur_pkt_stat, 0, sizeof(phystat->cur_pkt_stat));
1952 	memset(&phystat->last_pkt_stat, 0, sizeof(phystat->last_pkt_stat));
1953 }
1954 
1955 void rtw89_phy_stat_track(struct rtw89_dev *rtwdev)
1956 {
1957 	struct rtw89_phy_stat *phystat = &rtwdev->phystat;
1958 
1959 	rtw89_phy_stat_thermal_update(rtwdev);
1960 	rtw89_phy_stat_rssi_update(rtwdev);
1961 
1962 	phystat->last_pkt_stat = phystat->cur_pkt_stat;
1963 	memset(&phystat->cur_pkt_stat, 0, sizeof(phystat->cur_pkt_stat));
1964 }
1965 
1966 static u16 rtw89_phy_ccx_us_to_idx(struct rtw89_dev *rtwdev, u32 time_us)
1967 {
1968 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
1969 
1970 	return time_us >> (ilog2(CCX_US_BASE_RATIO) + env->ccx_unit_idx);
1971 }
1972 
1973 static u32 rtw89_phy_ccx_idx_to_us(struct rtw89_dev *rtwdev, u16 idx)
1974 {
1975 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
1976 
1977 	return idx << (ilog2(CCX_US_BASE_RATIO) + env->ccx_unit_idx);
1978 }
1979 
1980 static void rtw89_phy_ccx_top_setting_init(struct rtw89_dev *rtwdev)
1981 {
1982 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
1983 
1984 	env->ccx_manual_ctrl = false;
1985 	env->ccx_ongoing = false;
1986 	env->ccx_rac_lv = RTW89_RAC_RELEASE;
1987 	env->ccx_rpt_stamp = 0;
1988 	env->ccx_period = 0;
1989 	env->ccx_unit_idx = RTW89_CCX_32_US;
1990 	env->ccx_trigger_time = 0;
1991 	env->ccx_edcca_opt_bw_idx = RTW89_CCX_EDCCA_BW20_0;
1992 
1993 	rtw89_phy_set_phy_regs(rtwdev, R_CCX, B_CCX_EN_MSK, 1);
1994 	rtw89_phy_set_phy_regs(rtwdev, R_CCX, B_CCX_TRIG_OPT_MSK, 1);
1995 	rtw89_phy_set_phy_regs(rtwdev, R_CCX, B_MEASUREMENT_TRIG_MSK, 1);
1996 	rtw89_phy_set_phy_regs(rtwdev, R_CCX, B_CCX_EDCCA_OPT_MSK,
1997 			       RTW89_CCX_EDCCA_BW20_0);
1998 }
1999 
2000 static u16 rtw89_phy_ccx_get_report(struct rtw89_dev *rtwdev, u16 report,
2001 				    u16 score)
2002 {
2003 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2004 	u32 numer = 0;
2005 	u16 ret = 0;
2006 
2007 	numer = report * score + (env->ccx_period >> 1);
2008 	if (env->ccx_period)
2009 		ret = numer / env->ccx_period;
2010 
2011 	return ret >= score ? score - 1 : ret;
2012 }
2013 
2014 static void rtw89_phy_ccx_ms_to_period_unit(struct rtw89_dev *rtwdev,
2015 					    u16 time_ms, u32 *period,
2016 					    u32 *unit_idx)
2017 {
2018 	u32 idx;
2019 	u8 quotient;
2020 
2021 	if (time_ms >= CCX_MAX_PERIOD)
2022 		time_ms = CCX_MAX_PERIOD;
2023 
2024 	quotient = CCX_MAX_PERIOD_UNIT * time_ms / CCX_MAX_PERIOD;
2025 
2026 	if (quotient < 4)
2027 		idx = RTW89_CCX_4_US;
2028 	else if (quotient < 8)
2029 		idx = RTW89_CCX_8_US;
2030 	else if (quotient < 16)
2031 		idx = RTW89_CCX_16_US;
2032 	else
2033 		idx = RTW89_CCX_32_US;
2034 
2035 	*unit_idx = idx;
2036 	*period = (time_ms * MS_TO_4US_RATIO) >> idx;
2037 
2038 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2039 		    "[Trigger Time] period:%d, unit_idx:%d\n",
2040 		    *period, *unit_idx);
2041 }
2042 
2043 static void rtw89_phy_ccx_racing_release(struct rtw89_dev *rtwdev)
2044 {
2045 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2046 
2047 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2048 		    "lv:(%d)->(0)\n", env->ccx_rac_lv);
2049 
2050 	env->ccx_ongoing = false;
2051 	env->ccx_rac_lv = RTW89_RAC_RELEASE;
2052 	env->ifs_clm_app = RTW89_IFS_CLM_BACKGROUND;
2053 }
2054 
2055 static bool rtw89_phy_ifs_clm_th_update_check(struct rtw89_dev *rtwdev,
2056 					      struct rtw89_ccx_para_info *para)
2057 {
2058 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2059 	bool is_update = env->ifs_clm_app != para->ifs_clm_app;
2060 	u8 i = 0;
2061 	u16 *ifs_th_l = env->ifs_clm_th_l;
2062 	u16 *ifs_th_h = env->ifs_clm_th_h;
2063 	u32 ifs_th0_us = 0, ifs_th_times = 0;
2064 	u32 ifs_th_h_us[RTW89_IFS_CLM_NUM] = {0};
2065 
2066 	if (!is_update)
2067 		goto ifs_update_finished;
2068 
2069 	switch (para->ifs_clm_app) {
2070 	case RTW89_IFS_CLM_INIT:
2071 	case RTW89_IFS_CLM_BACKGROUND:
2072 	case RTW89_IFS_CLM_ACS:
2073 	case RTW89_IFS_CLM_DBG:
2074 	case RTW89_IFS_CLM_DIG:
2075 	case RTW89_IFS_CLM_TDMA_DIG:
2076 		ifs_th0_us = IFS_CLM_TH0_UPPER;
2077 		ifs_th_times = IFS_CLM_TH_MUL;
2078 		break;
2079 	case RTW89_IFS_CLM_DBG_MANUAL:
2080 		ifs_th0_us = para->ifs_clm_manual_th0;
2081 		ifs_th_times = para->ifs_clm_manual_th_times;
2082 		break;
2083 	default:
2084 		break;
2085 	}
2086 
2087 	/* Set sampling threshold for 4 different regions, unit in idx_cnt.
2088 	 * low[i] = high[i-1] + 1
2089 	 * high[i] = high[i-1] * ifs_th_times
2090 	 */
2091 	ifs_th_l[IFS_CLM_TH_START_IDX] = 0;
2092 	ifs_th_h_us[IFS_CLM_TH_START_IDX] = ifs_th0_us;
2093 	ifs_th_h[IFS_CLM_TH_START_IDX] = rtw89_phy_ccx_us_to_idx(rtwdev,
2094 								 ifs_th0_us);
2095 	for (i = 1; i < RTW89_IFS_CLM_NUM; i++) {
2096 		ifs_th_l[i] = ifs_th_h[i - 1] + 1;
2097 		ifs_th_h_us[i] = ifs_th_h_us[i - 1] * ifs_th_times;
2098 		ifs_th_h[i] = rtw89_phy_ccx_us_to_idx(rtwdev, ifs_th_h_us[i]);
2099 	}
2100 
2101 ifs_update_finished:
2102 	if (!is_update)
2103 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2104 			    "No need to update IFS_TH\n");
2105 
2106 	return is_update;
2107 }
2108 
2109 static void rtw89_phy_ifs_clm_set_th_reg(struct rtw89_dev *rtwdev)
2110 {
2111 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2112 	u8 i = 0;
2113 
2114 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T1, B_IFS_T1_TH_LOW_MSK,
2115 			       env->ifs_clm_th_l[0]);
2116 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T2, B_IFS_T2_TH_LOW_MSK,
2117 			       env->ifs_clm_th_l[1]);
2118 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T3, B_IFS_T3_TH_LOW_MSK,
2119 			       env->ifs_clm_th_l[2]);
2120 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T4, B_IFS_T4_TH_LOW_MSK,
2121 			       env->ifs_clm_th_l[3]);
2122 
2123 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T1, B_IFS_T1_TH_HIGH_MSK,
2124 			       env->ifs_clm_th_h[0]);
2125 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T2, B_IFS_T2_TH_HIGH_MSK,
2126 			       env->ifs_clm_th_h[1]);
2127 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T3, B_IFS_T3_TH_HIGH_MSK,
2128 			       env->ifs_clm_th_h[2]);
2129 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T4, B_IFS_T4_TH_HIGH_MSK,
2130 			       env->ifs_clm_th_h[3]);
2131 
2132 	for (i = 0; i < RTW89_IFS_CLM_NUM; i++)
2133 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2134 			    "Update IFS_T%d_th{low, high} : {%d, %d}\n",
2135 			    i + 1, env->ifs_clm_th_l[i], env->ifs_clm_th_h[i]);
2136 }
2137 
2138 static void rtw89_phy_ifs_clm_setting_init(struct rtw89_dev *rtwdev)
2139 {
2140 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2141 	struct rtw89_ccx_para_info para = {0};
2142 
2143 	env->ifs_clm_app = RTW89_IFS_CLM_BACKGROUND;
2144 	env->ifs_clm_mntr_time = 0;
2145 
2146 	para.ifs_clm_app = RTW89_IFS_CLM_INIT;
2147 	if (rtw89_phy_ifs_clm_th_update_check(rtwdev, &para))
2148 		rtw89_phy_ifs_clm_set_th_reg(rtwdev);
2149 
2150 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_COUNTER, B_IFS_COLLECT_EN,
2151 			       true);
2152 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T1, B_IFS_T1_EN_MSK, true);
2153 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T2, B_IFS_T2_EN_MSK, true);
2154 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T3, B_IFS_T3_EN_MSK, true);
2155 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_T4, B_IFS_T4_EN_MSK, true);
2156 }
2157 
2158 static int rtw89_phy_ccx_racing_ctrl(struct rtw89_dev *rtwdev,
2159 				     enum rtw89_env_racing_lv level)
2160 {
2161 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2162 	int ret = 0;
2163 
2164 	if (level >= RTW89_RAC_MAX_NUM) {
2165 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2166 			    "[WARNING] Wrong LV=%d\n", level);
2167 		return -EINVAL;
2168 	}
2169 
2170 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2171 		    "ccx_ongoing=%d, level:(%d)->(%d)\n", env->ccx_ongoing,
2172 		    env->ccx_rac_lv, level);
2173 
2174 	if (env->ccx_ongoing) {
2175 		if (level <= env->ccx_rac_lv)
2176 			ret = -EINVAL;
2177 		else
2178 			env->ccx_ongoing = false;
2179 	}
2180 
2181 	if (ret == 0)
2182 		env->ccx_rac_lv = level;
2183 
2184 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK, "ccx racing success=%d\n",
2185 		    !ret);
2186 
2187 	return ret;
2188 }
2189 
2190 static void rtw89_phy_ccx_trigger(struct rtw89_dev *rtwdev)
2191 {
2192 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2193 
2194 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_COUNTER, B_IFS_COUNTER_CLR_MSK, 0);
2195 	rtw89_phy_set_phy_regs(rtwdev, R_CCX, B_MEASUREMENT_TRIG_MSK, 0);
2196 	rtw89_phy_set_phy_regs(rtwdev, R_IFS_COUNTER, B_IFS_COUNTER_CLR_MSK, 1);
2197 	rtw89_phy_set_phy_regs(rtwdev, R_CCX, B_MEASUREMENT_TRIG_MSK, 1);
2198 
2199 	env->ccx_rpt_stamp++;
2200 	env->ccx_ongoing = true;
2201 }
2202 
2203 static void rtw89_phy_ifs_clm_get_utility(struct rtw89_dev *rtwdev)
2204 {
2205 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2206 	u8 i = 0;
2207 	u32 res = 0;
2208 
2209 	env->ifs_clm_tx_ratio =
2210 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_tx, PERCENT);
2211 	env->ifs_clm_edcca_excl_cca_ratio =
2212 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_edcca_excl_cca,
2213 					 PERCENT);
2214 	env->ifs_clm_cck_fa_ratio =
2215 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_cckfa, PERCENT);
2216 	env->ifs_clm_ofdm_fa_ratio =
2217 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_ofdmfa, PERCENT);
2218 	env->ifs_clm_cck_cca_excl_fa_ratio =
2219 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_cckcca_excl_fa,
2220 					 PERCENT);
2221 	env->ifs_clm_ofdm_cca_excl_fa_ratio =
2222 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_ofdmcca_excl_fa,
2223 					 PERCENT);
2224 	env->ifs_clm_cck_fa_permil =
2225 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_cckfa, PERMIL);
2226 	env->ifs_clm_ofdm_fa_permil =
2227 		rtw89_phy_ccx_get_report(rtwdev, env->ifs_clm_ofdmfa, PERMIL);
2228 
2229 	for (i = 0; i < RTW89_IFS_CLM_NUM; i++) {
2230 		if (env->ifs_clm_his[i] > ENV_MNTR_IFSCLM_HIS_MAX) {
2231 			env->ifs_clm_ifs_avg[i] = ENV_MNTR_FAIL_DWORD;
2232 		} else {
2233 			env->ifs_clm_ifs_avg[i] =
2234 				rtw89_phy_ccx_idx_to_us(rtwdev,
2235 							env->ifs_clm_avg[i]);
2236 		}
2237 
2238 		res = rtw89_phy_ccx_idx_to_us(rtwdev, env->ifs_clm_cca[i]);
2239 		res += env->ifs_clm_his[i] >> 1;
2240 		if (env->ifs_clm_his[i])
2241 			res /= env->ifs_clm_his[i];
2242 		else
2243 			res = 0;
2244 		env->ifs_clm_cca_avg[i] = res;
2245 	}
2246 
2247 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2248 		    "IFS-CLM ratio {Tx, EDCCA_exclu_cca} = {%d, %d}\n",
2249 		    env->ifs_clm_tx_ratio, env->ifs_clm_edcca_excl_cca_ratio);
2250 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2251 		    "IFS-CLM FA ratio {CCK, OFDM} = {%d, %d}\n",
2252 		    env->ifs_clm_cck_fa_ratio, env->ifs_clm_ofdm_fa_ratio);
2253 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2254 		    "IFS-CLM FA permil {CCK, OFDM} = {%d, %d}\n",
2255 		    env->ifs_clm_cck_fa_permil, env->ifs_clm_ofdm_fa_permil);
2256 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2257 		    "IFS-CLM CCA_exclu_FA ratio {CCK, OFDM} = {%d, %d}\n",
2258 		    env->ifs_clm_cck_cca_excl_fa_ratio,
2259 		    env->ifs_clm_ofdm_cca_excl_fa_ratio);
2260 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2261 		    "Time:[his, ifs_avg(us), cca_avg(us)]\n");
2262 	for (i = 0; i < RTW89_IFS_CLM_NUM; i++)
2263 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK, "T%d:[%d, %d, %d]\n",
2264 			    i + 1, env->ifs_clm_his[i], env->ifs_clm_ifs_avg[i],
2265 			    env->ifs_clm_cca_avg[i]);
2266 }
2267 
2268 static bool rtw89_phy_ifs_clm_get_result(struct rtw89_dev *rtwdev)
2269 {
2270 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2271 	u8 i = 0;
2272 
2273 	if (rtw89_phy_read32_mask(rtwdev, R_IFSCNT, B_IFSCNT_DONE_MSK) == 0) {
2274 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2275 			    "Get IFS_CLM report Fail\n");
2276 		return false;
2277 	}
2278 
2279 	env->ifs_clm_tx =
2280 		rtw89_phy_read32_mask(rtwdev, R_IFS_CLM_TX_CNT,
2281 				      B_IFS_CLM_TX_CNT_MSK);
2282 	env->ifs_clm_edcca_excl_cca =
2283 		rtw89_phy_read32_mask(rtwdev, R_IFS_CLM_TX_CNT,
2284 				      B_IFS_CLM_EDCCA_EXCLUDE_CCA_FA_MSK);
2285 	env->ifs_clm_cckcca_excl_fa =
2286 		rtw89_phy_read32_mask(rtwdev, R_IFS_CLM_CCA,
2287 				      B_IFS_CLM_CCKCCA_EXCLUDE_FA_MSK);
2288 	env->ifs_clm_ofdmcca_excl_fa =
2289 		rtw89_phy_read32_mask(rtwdev, R_IFS_CLM_CCA,
2290 				      B_IFS_CLM_OFDMCCA_EXCLUDE_FA_MSK);
2291 	env->ifs_clm_cckfa =
2292 		rtw89_phy_read32_mask(rtwdev, R_IFS_CLM_FA,
2293 				      B_IFS_CLM_CCK_FA_MSK);
2294 	env->ifs_clm_ofdmfa =
2295 		rtw89_phy_read32_mask(rtwdev, R_IFS_CLM_FA,
2296 				      B_IFS_CLM_OFDM_FA_MSK);
2297 
2298 	env->ifs_clm_his[0] =
2299 		rtw89_phy_read32_mask(rtwdev, R_IFS_HIS, B_IFS_T1_HIS_MSK);
2300 	env->ifs_clm_his[1] =
2301 		rtw89_phy_read32_mask(rtwdev, R_IFS_HIS, B_IFS_T2_HIS_MSK);
2302 	env->ifs_clm_his[2] =
2303 		rtw89_phy_read32_mask(rtwdev, R_IFS_HIS, B_IFS_T3_HIS_MSK);
2304 	env->ifs_clm_his[3] =
2305 		rtw89_phy_read32_mask(rtwdev, R_IFS_HIS, B_IFS_T4_HIS_MSK);
2306 
2307 	env->ifs_clm_avg[0] =
2308 		rtw89_phy_read32_mask(rtwdev, R_IFS_AVG_L, B_IFS_T1_AVG_MSK);
2309 	env->ifs_clm_avg[1] =
2310 		rtw89_phy_read32_mask(rtwdev, R_IFS_AVG_L, B_IFS_T2_AVG_MSK);
2311 	env->ifs_clm_avg[2] =
2312 		rtw89_phy_read32_mask(rtwdev, R_IFS_AVG_H, B_IFS_T3_AVG_MSK);
2313 	env->ifs_clm_avg[3] =
2314 		rtw89_phy_read32_mask(rtwdev, R_IFS_AVG_H, B_IFS_T4_AVG_MSK);
2315 
2316 	env->ifs_clm_cca[0] =
2317 		rtw89_phy_read32_mask(rtwdev, R_IFS_CCA_L, B_IFS_T1_CCA_MSK);
2318 	env->ifs_clm_cca[1] =
2319 		rtw89_phy_read32_mask(rtwdev, R_IFS_CCA_L, B_IFS_T2_CCA_MSK);
2320 	env->ifs_clm_cca[2] =
2321 		rtw89_phy_read32_mask(rtwdev, R_IFS_CCA_H, B_IFS_T3_CCA_MSK);
2322 	env->ifs_clm_cca[3] =
2323 		rtw89_phy_read32_mask(rtwdev, R_IFS_CCA_H, B_IFS_T4_CCA_MSK);
2324 
2325 	env->ifs_clm_total_ifs =
2326 		rtw89_phy_read32_mask(rtwdev, R_IFSCNT, B_IFSCNT_TOTAL_CNT_MSK);
2327 
2328 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK, "IFS-CLM total_ifs = %d\n",
2329 		    env->ifs_clm_total_ifs);
2330 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2331 		    "{Tx, EDCCA_exclu_cca} = {%d, %d}\n",
2332 		    env->ifs_clm_tx, env->ifs_clm_edcca_excl_cca);
2333 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2334 		    "IFS-CLM FA{CCK, OFDM} = {%d, %d}\n",
2335 		    env->ifs_clm_cckfa, env->ifs_clm_ofdmfa);
2336 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2337 		    "IFS-CLM CCA_exclu_FA{CCK, OFDM} = {%d, %d}\n",
2338 		    env->ifs_clm_cckcca_excl_fa, env->ifs_clm_ofdmcca_excl_fa);
2339 
2340 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK, "Time:[his, avg, cca]\n");
2341 	for (i = 0; i < RTW89_IFS_CLM_NUM; i++)
2342 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2343 			    "T%d:[%d, %d, %d]\n", i + 1, env->ifs_clm_his[i],
2344 			    env->ifs_clm_avg[i], env->ifs_clm_cca[i]);
2345 
2346 	rtw89_phy_ifs_clm_get_utility(rtwdev);
2347 
2348 	return true;
2349 }
2350 
2351 static int rtw89_phy_ifs_clm_set(struct rtw89_dev *rtwdev,
2352 				 struct rtw89_ccx_para_info *para)
2353 {
2354 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2355 	u32 period = 0;
2356 	u32 unit_idx = 0;
2357 
2358 	if (para->mntr_time == 0) {
2359 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2360 			    "[WARN] MNTR_TIME is 0\n");
2361 		return -EINVAL;
2362 	}
2363 
2364 	if (rtw89_phy_ccx_racing_ctrl(rtwdev, para->rac_lv))
2365 		return -EINVAL;
2366 
2367 	if (para->mntr_time != env->ifs_clm_mntr_time) {
2368 		rtw89_phy_ccx_ms_to_period_unit(rtwdev, para->mntr_time,
2369 						&period, &unit_idx);
2370 		rtw89_phy_set_phy_regs(rtwdev, R_IFS_COUNTER,
2371 				       B_IFS_CLM_PERIOD_MSK, period);
2372 		rtw89_phy_set_phy_regs(rtwdev, R_IFS_COUNTER,
2373 				       B_IFS_CLM_COUNTER_UNIT_MSK, unit_idx);
2374 
2375 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2376 			    "Update IFS-CLM time ((%d)) -> ((%d))\n",
2377 			    env->ifs_clm_mntr_time, para->mntr_time);
2378 
2379 		env->ifs_clm_mntr_time = para->mntr_time;
2380 		env->ccx_period = (u16)period;
2381 		env->ccx_unit_idx = (u8)unit_idx;
2382 	}
2383 
2384 	if (rtw89_phy_ifs_clm_th_update_check(rtwdev, para)) {
2385 		env->ifs_clm_app = para->ifs_clm_app;
2386 		rtw89_phy_ifs_clm_set_th_reg(rtwdev);
2387 	}
2388 
2389 	return 0;
2390 }
2391 
2392 void rtw89_phy_env_monitor_track(struct rtw89_dev *rtwdev)
2393 {
2394 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2395 	struct rtw89_ccx_para_info para = {0};
2396 	u8 chk_result = RTW89_PHY_ENV_MON_CCX_FAIL;
2397 
2398 	env->ccx_watchdog_result = RTW89_PHY_ENV_MON_CCX_FAIL;
2399 	if (env->ccx_manual_ctrl) {
2400 		rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2401 			    "CCX in manual ctrl\n");
2402 		return;
2403 	}
2404 
2405 	/* only ifs_clm for now */
2406 	if (rtw89_phy_ifs_clm_get_result(rtwdev))
2407 		env->ccx_watchdog_result |= RTW89_PHY_ENV_MON_IFS_CLM;
2408 
2409 	rtw89_phy_ccx_racing_release(rtwdev);
2410 	para.mntr_time = 1900;
2411 	para.rac_lv = RTW89_RAC_LV_1;
2412 	para.ifs_clm_app = RTW89_IFS_CLM_BACKGROUND;
2413 
2414 	if (rtw89_phy_ifs_clm_set(rtwdev, &para) == 0)
2415 		chk_result |= RTW89_PHY_ENV_MON_IFS_CLM;
2416 	if (chk_result)
2417 		rtw89_phy_ccx_trigger(rtwdev);
2418 
2419 	rtw89_debug(rtwdev, RTW89_DBG_PHY_TRACK,
2420 		    "get_result=0x%x, chk_result:0x%x\n",
2421 		    env->ccx_watchdog_result, chk_result);
2422 }
2423 
2424 static bool rtw89_physts_ie_page_valid(enum rtw89_phy_status_bitmap *ie_page)
2425 {
2426 	if (*ie_page > RTW89_PHYSTS_BITMAP_NUM ||
2427 	    *ie_page == RTW89_RSVD_9)
2428 		return false;
2429 	else if (*ie_page > RTW89_RSVD_9)
2430 		*ie_page -= 1;
2431 
2432 	return true;
2433 }
2434 
2435 static u32 rtw89_phy_get_ie_bitmap_addr(enum rtw89_phy_status_bitmap ie_page)
2436 {
2437 	static const u8 ie_page_shift = 2;
2438 
2439 	return R_PHY_STS_BITMAP_ADDR_START + (ie_page << ie_page_shift);
2440 }
2441 
2442 static u32 rtw89_physts_get_ie_bitmap(struct rtw89_dev *rtwdev,
2443 				      enum rtw89_phy_status_bitmap ie_page)
2444 {
2445 	u32 addr;
2446 
2447 	if (!rtw89_physts_ie_page_valid(&ie_page))
2448 		return 0;
2449 
2450 	addr = rtw89_phy_get_ie_bitmap_addr(ie_page);
2451 
2452 	return rtw89_phy_read32(rtwdev, addr);
2453 }
2454 
2455 static void rtw89_physts_set_ie_bitmap(struct rtw89_dev *rtwdev,
2456 				       enum rtw89_phy_status_bitmap ie_page,
2457 				       u32 val)
2458 {
2459 	const struct rtw89_chip_info *chip = rtwdev->chip;
2460 	u32 addr;
2461 
2462 	if (!rtw89_physts_ie_page_valid(&ie_page))
2463 		return;
2464 
2465 	if (chip->chip_id == RTL8852A)
2466 		val &= B_PHY_STS_BITMAP_MSK_52A;
2467 
2468 	addr = rtw89_phy_get_ie_bitmap_addr(ie_page);
2469 	rtw89_phy_write32(rtwdev, addr, val);
2470 }
2471 
2472 static void rtw89_physts_enable_ie_bitmap(struct rtw89_dev *rtwdev,
2473 					  enum rtw89_phy_status_bitmap bitmap,
2474 					  enum rtw89_phy_status_ie_type ie,
2475 					  bool enable)
2476 {
2477 	u32 val = rtw89_physts_get_ie_bitmap(rtwdev, bitmap);
2478 
2479 	if (enable)
2480 		val |= BIT(ie);
2481 	else
2482 		val &= ~BIT(ie);
2483 
2484 	rtw89_physts_set_ie_bitmap(rtwdev, bitmap, val);
2485 }
2486 
2487 static void rtw89_physts_enable_fail_report(struct rtw89_dev *rtwdev,
2488 					    bool enable,
2489 					    enum rtw89_phy_idx phy_idx)
2490 {
2491 	if (enable) {
2492 		rtw89_phy_write32_clr(rtwdev, R_PLCP_HISTOGRAM,
2493 				      B_STS_DIS_TRIG_BY_FAIL);
2494 		rtw89_phy_write32_clr(rtwdev, R_PLCP_HISTOGRAM,
2495 				      B_STS_DIS_TRIG_BY_BRK);
2496 	} else {
2497 		rtw89_phy_write32_set(rtwdev, R_PLCP_HISTOGRAM,
2498 				      B_STS_DIS_TRIG_BY_FAIL);
2499 		rtw89_phy_write32_set(rtwdev, R_PLCP_HISTOGRAM,
2500 				      B_STS_DIS_TRIG_BY_BRK);
2501 	}
2502 }
2503 
2504 static void rtw89_physts_parsing_init(struct rtw89_dev *rtwdev)
2505 {
2506 	const struct rtw89_chip_info *chip = rtwdev->chip;
2507 	u8 i;
2508 
2509 	if (chip->chip_id == RTL8852A && rtwdev->hal.cv == CHIP_CBV)
2510 		rtw89_physts_enable_fail_report(rtwdev, false, RTW89_PHY_0);
2511 
2512 	for (i = 0; i < RTW89_PHYSTS_BITMAP_NUM; i++) {
2513 		if (i >= RTW89_CCK_PKT)
2514 			rtw89_physts_enable_ie_bitmap(rtwdev, i,
2515 						      RTW89_PHYSTS_IE09_FTR_0,
2516 						      true);
2517 		if ((i >= RTW89_CCK_BRK && i <= RTW89_VHT_MU) ||
2518 		    (i >= RTW89_RSVD_9 && i <= RTW89_CCK_PKT))
2519 			continue;
2520 		rtw89_physts_enable_ie_bitmap(rtwdev, i,
2521 					      RTW89_PHYSTS_IE24_OFDM_TD_PATH_A,
2522 					      true);
2523 	}
2524 	rtw89_physts_enable_ie_bitmap(rtwdev, RTW89_VHT_PKT,
2525 				      RTW89_PHYSTS_IE13_DL_MU_DEF, true);
2526 	rtw89_physts_enable_ie_bitmap(rtwdev, RTW89_HE_PKT,
2527 				      RTW89_PHYSTS_IE13_DL_MU_DEF, true);
2528 
2529 	/* force IE01 for channel index, only channel field is valid */
2530 	rtw89_physts_enable_ie_bitmap(rtwdev, RTW89_CCK_PKT,
2531 				      RTW89_PHYSTS_IE01_CMN_OFDM, true);
2532 }
2533 
2534 static void rtw89_phy_dig_read_gain_table(struct rtw89_dev *rtwdev, int type)
2535 {
2536 	const struct rtw89_chip_info *chip = rtwdev->chip;
2537 	struct rtw89_dig_info *dig = &rtwdev->dig;
2538 	const struct rtw89_phy_dig_gain_cfg *cfg;
2539 	const char *msg;
2540 	u8 i;
2541 	s8 gain_base;
2542 	s8 *gain_arr;
2543 	u32 tmp;
2544 
2545 	switch (type) {
2546 	case RTW89_DIG_GAIN_LNA_G:
2547 		gain_arr = dig->lna_gain_g;
2548 		gain_base = LNA0_GAIN;
2549 		cfg = chip->dig_table->cfg_lna_g;
2550 		msg = "lna_gain_g";
2551 		break;
2552 	case RTW89_DIG_GAIN_TIA_G:
2553 		gain_arr = dig->tia_gain_g;
2554 		gain_base = TIA0_GAIN_G;
2555 		cfg = chip->dig_table->cfg_tia_g;
2556 		msg = "tia_gain_g";
2557 		break;
2558 	case RTW89_DIG_GAIN_LNA_A:
2559 		gain_arr = dig->lna_gain_a;
2560 		gain_base = LNA0_GAIN;
2561 		cfg = chip->dig_table->cfg_lna_a;
2562 		msg = "lna_gain_a";
2563 		break;
2564 	case RTW89_DIG_GAIN_TIA_A:
2565 		gain_arr = dig->tia_gain_a;
2566 		gain_base = TIA0_GAIN_A;
2567 		cfg = chip->dig_table->cfg_tia_a;
2568 		msg = "tia_gain_a";
2569 		break;
2570 	default:
2571 		return;
2572 	}
2573 
2574 	for (i = 0; i < cfg->size; i++) {
2575 		tmp = rtw89_phy_read32_mask(rtwdev, cfg->table[i].addr,
2576 					    cfg->table[i].mask);
2577 		tmp >>= DIG_GAIN_SHIFT;
2578 		gain_arr[i] = sign_extend32(tmp, U4_MAX_BIT) + gain_base;
2579 		gain_base += DIG_GAIN;
2580 
2581 		rtw89_debug(rtwdev, RTW89_DBG_DIG, "%s[%d]=%d\n",
2582 			    msg, i, gain_arr[i]);
2583 	}
2584 }
2585 
2586 static void rtw89_phy_dig_update_gain_para(struct rtw89_dev *rtwdev)
2587 {
2588 	struct rtw89_dig_info *dig = &rtwdev->dig;
2589 	u32 tmp;
2590 	u8 i;
2591 
2592 	tmp = rtw89_phy_read32_mask(rtwdev, R_PATH0_IB_PKPW,
2593 				    B_PATH0_IB_PKPW_MSK);
2594 	dig->ib_pkpwr = sign_extend32(tmp >> DIG_GAIN_SHIFT, U8_MAX_BIT);
2595 	dig->ib_pbk = rtw89_phy_read32_mask(rtwdev, R_PATH0_IB_PBK,
2596 					    B_PATH0_IB_PBK_MSK);
2597 	rtw89_debug(rtwdev, RTW89_DBG_DIG, "ib_pkpwr=%d, ib_pbk=%d\n",
2598 		    dig->ib_pkpwr, dig->ib_pbk);
2599 
2600 	for (i = RTW89_DIG_GAIN_LNA_G; i < RTW89_DIG_GAIN_MAX; i++)
2601 		rtw89_phy_dig_read_gain_table(rtwdev, i);
2602 }
2603 
2604 static const u8 rssi_nolink = 22;
2605 static const u8 igi_rssi_th[IGI_RSSI_TH_NUM] = {68, 84, 90, 98, 104};
2606 static const u16 fa_th_2g[FA_TH_NUM] = {22, 44, 66, 88};
2607 static const u16 fa_th_5g[FA_TH_NUM] = {4, 8, 12, 16};
2608 static const u16 fa_th_nolink[FA_TH_NUM] = {196, 352, 440, 528};
2609 
2610 static void rtw89_phy_dig_update_rssi_info(struct rtw89_dev *rtwdev)
2611 {
2612 	struct rtw89_phy_ch_info *ch_info = &rtwdev->ch_info;
2613 	struct rtw89_dig_info *dig = &rtwdev->dig;
2614 	bool is_linked = rtwdev->total_sta_assoc > 0;
2615 
2616 	if (is_linked) {
2617 		dig->igi_rssi = ch_info->rssi_min >> 1;
2618 	} else {
2619 		rtw89_debug(rtwdev, RTW89_DBG_DIG, "RSSI update : NO Link\n");
2620 		dig->igi_rssi = rssi_nolink;
2621 	}
2622 }
2623 
2624 static void rtw89_phy_dig_update_para(struct rtw89_dev *rtwdev)
2625 {
2626 	struct rtw89_dig_info *dig = &rtwdev->dig;
2627 	bool is_linked = rtwdev->total_sta_assoc > 0;
2628 	const u16 *fa_th_src = NULL;
2629 
2630 	switch (rtwdev->hal.current_band_type) {
2631 	case RTW89_BAND_2G:
2632 		dig->lna_gain = dig->lna_gain_g;
2633 		dig->tia_gain = dig->tia_gain_g;
2634 		fa_th_src = is_linked ? fa_th_2g : fa_th_nolink;
2635 		dig->force_gaincode_idx_en = false;
2636 		dig->dyn_pd_th_en = true;
2637 		break;
2638 	case RTW89_BAND_5G:
2639 	default:
2640 		dig->lna_gain = dig->lna_gain_a;
2641 		dig->tia_gain = dig->tia_gain_a;
2642 		fa_th_src = is_linked ? fa_th_5g : fa_th_nolink;
2643 		dig->force_gaincode_idx_en = true;
2644 		dig->dyn_pd_th_en = true;
2645 		break;
2646 	}
2647 	memcpy(dig->fa_th, fa_th_src, sizeof(dig->fa_th));
2648 	memcpy(dig->igi_rssi_th, igi_rssi_th, sizeof(dig->igi_rssi_th));
2649 }
2650 
2651 static const u8 pd_low_th_offset = 20, dynamic_igi_min = 0x20;
2652 static const u8 igi_max_performance_mode = 0x5a;
2653 static const u8 dynamic_pd_threshold_max;
2654 
2655 static void rtw89_phy_dig_para_reset(struct rtw89_dev *rtwdev)
2656 {
2657 	struct rtw89_dig_info *dig = &rtwdev->dig;
2658 
2659 	dig->cur_gaincode.lna_idx = LNA_IDX_MAX;
2660 	dig->cur_gaincode.tia_idx = TIA_IDX_MAX;
2661 	dig->cur_gaincode.rxb_idx = RXB_IDX_MAX;
2662 	dig->force_gaincode.lna_idx = LNA_IDX_MAX;
2663 	dig->force_gaincode.tia_idx = TIA_IDX_MAX;
2664 	dig->force_gaincode.rxb_idx = RXB_IDX_MAX;
2665 
2666 	dig->dyn_igi_max = igi_max_performance_mode;
2667 	dig->dyn_igi_min = dynamic_igi_min;
2668 	dig->dyn_pd_th_max = dynamic_pd_threshold_max;
2669 	dig->pd_low_th_ofst = pd_low_th_offset;
2670 	dig->is_linked_pre = false;
2671 }
2672 
2673 static void rtw89_phy_dig_init(struct rtw89_dev *rtwdev)
2674 {
2675 	rtw89_phy_dig_update_gain_para(rtwdev);
2676 	rtw89_phy_dig_reset(rtwdev);
2677 }
2678 
2679 static u8 rtw89_phy_dig_lna_idx_by_rssi(struct rtw89_dev *rtwdev, u8 rssi)
2680 {
2681 	struct rtw89_dig_info *dig = &rtwdev->dig;
2682 	u8 lna_idx;
2683 
2684 	if (rssi < dig->igi_rssi_th[0])
2685 		lna_idx = RTW89_DIG_GAIN_LNA_IDX6;
2686 	else if (rssi < dig->igi_rssi_th[1])
2687 		lna_idx = RTW89_DIG_GAIN_LNA_IDX5;
2688 	else if (rssi < dig->igi_rssi_th[2])
2689 		lna_idx = RTW89_DIG_GAIN_LNA_IDX4;
2690 	else if (rssi < dig->igi_rssi_th[3])
2691 		lna_idx = RTW89_DIG_GAIN_LNA_IDX3;
2692 	else if (rssi < dig->igi_rssi_th[4])
2693 		lna_idx = RTW89_DIG_GAIN_LNA_IDX2;
2694 	else
2695 		lna_idx = RTW89_DIG_GAIN_LNA_IDX1;
2696 
2697 	return lna_idx;
2698 }
2699 
2700 static u8 rtw89_phy_dig_tia_idx_by_rssi(struct rtw89_dev *rtwdev, u8 rssi)
2701 {
2702 	struct rtw89_dig_info *dig = &rtwdev->dig;
2703 	u8 tia_idx;
2704 
2705 	if (rssi < dig->igi_rssi_th[0])
2706 		tia_idx = RTW89_DIG_GAIN_TIA_IDX1;
2707 	else
2708 		tia_idx = RTW89_DIG_GAIN_TIA_IDX0;
2709 
2710 	return tia_idx;
2711 }
2712 
2713 #define IB_PBK_BASE 110
2714 #define WB_RSSI_BASE 10
2715 static u8 rtw89_phy_dig_rxb_idx_by_rssi(struct rtw89_dev *rtwdev, u8 rssi,
2716 					struct rtw89_agc_gaincode_set *set)
2717 {
2718 	struct rtw89_dig_info *dig = &rtwdev->dig;
2719 	s8 lna_gain = dig->lna_gain[set->lna_idx];
2720 	s8 tia_gain = dig->tia_gain[set->tia_idx];
2721 	s32 wb_rssi = rssi + lna_gain + tia_gain;
2722 	s32 rxb_idx_tmp = IB_PBK_BASE + WB_RSSI_BASE;
2723 	u8 rxb_idx;
2724 
2725 	rxb_idx_tmp += dig->ib_pkpwr - dig->ib_pbk - wb_rssi;
2726 	rxb_idx = clamp_t(s32, rxb_idx_tmp, RXB_IDX_MIN, RXB_IDX_MAX);
2727 
2728 	rtw89_debug(rtwdev, RTW89_DBG_DIG, "wb_rssi=%03d, rxb_idx_tmp=%03d\n",
2729 		    wb_rssi, rxb_idx_tmp);
2730 
2731 	return rxb_idx;
2732 }
2733 
2734 static void rtw89_phy_dig_gaincode_by_rssi(struct rtw89_dev *rtwdev, u8 rssi,
2735 					   struct rtw89_agc_gaincode_set *set)
2736 {
2737 	set->lna_idx = rtw89_phy_dig_lna_idx_by_rssi(rtwdev, rssi);
2738 	set->tia_idx = rtw89_phy_dig_tia_idx_by_rssi(rtwdev, rssi);
2739 	set->rxb_idx = rtw89_phy_dig_rxb_idx_by_rssi(rtwdev, rssi, set);
2740 
2741 	rtw89_debug(rtwdev, RTW89_DBG_DIG,
2742 		    "final_rssi=%03d, (lna,tia,rab)=(%d,%d,%02d)\n",
2743 		    rssi, set->lna_idx, set->tia_idx, set->rxb_idx);
2744 }
2745 
2746 #define IGI_OFFSET_MAX 25
2747 #define IGI_OFFSET_MUL 2
2748 static void rtw89_phy_dig_igi_offset_by_env(struct rtw89_dev *rtwdev)
2749 {
2750 	struct rtw89_dig_info *dig = &rtwdev->dig;
2751 	struct rtw89_env_monitor_info *env = &rtwdev->env_monitor;
2752 	enum rtw89_dig_noisy_level noisy_lv;
2753 	u8 igi_offset = dig->fa_rssi_ofst;
2754 	u16 fa_ratio = 0;
2755 
2756 	fa_ratio = env->ifs_clm_cck_fa_permil + env->ifs_clm_ofdm_fa_permil;
2757 
2758 	if (fa_ratio < dig->fa_th[0])
2759 		noisy_lv = RTW89_DIG_NOISY_LEVEL0;
2760 	else if (fa_ratio < dig->fa_th[1])
2761 		noisy_lv = RTW89_DIG_NOISY_LEVEL1;
2762 	else if (fa_ratio < dig->fa_th[2])
2763 		noisy_lv = RTW89_DIG_NOISY_LEVEL2;
2764 	else if (fa_ratio < dig->fa_th[3])
2765 		noisy_lv = RTW89_DIG_NOISY_LEVEL3;
2766 	else
2767 		noisy_lv = RTW89_DIG_NOISY_LEVEL_MAX;
2768 
2769 	if (noisy_lv == RTW89_DIG_NOISY_LEVEL0 && igi_offset < 2)
2770 		igi_offset = 0;
2771 	else
2772 		igi_offset += noisy_lv * IGI_OFFSET_MUL;
2773 
2774 	igi_offset = min_t(u8, igi_offset, IGI_OFFSET_MAX);
2775 	dig->fa_rssi_ofst = igi_offset;
2776 
2777 	rtw89_debug(rtwdev, RTW89_DBG_DIG,
2778 		    "fa_th: [+6 (%d) +4 (%d) +2 (%d) 0 (%d) -2 ]\n",
2779 		    dig->fa_th[3], dig->fa_th[2], dig->fa_th[1], dig->fa_th[0]);
2780 
2781 	rtw89_debug(rtwdev, RTW89_DBG_DIG,
2782 		    "fa(CCK,OFDM,ALL)=(%d,%d,%d)%%, noisy_lv=%d, ofst=%d\n",
2783 		    env->ifs_clm_cck_fa_permil, env->ifs_clm_ofdm_fa_permil,
2784 		    env->ifs_clm_cck_fa_permil + env->ifs_clm_ofdm_fa_permil,
2785 		    noisy_lv, igi_offset);
2786 }
2787 
2788 static void rtw89_phy_dig_set_lna_idx(struct rtw89_dev *rtwdev, u8 lna_idx)
2789 {
2790 	rtw89_phy_write32_mask(rtwdev, R_PATH0_LNA_INIT,
2791 			       B_PATH0_LNA_INIT_IDX_MSK, lna_idx);
2792 	rtw89_phy_write32_mask(rtwdev, R_PATH1_LNA_INIT,
2793 			       B_PATH1_LNA_INIT_IDX_MSK, lna_idx);
2794 }
2795 
2796 static void rtw89_phy_dig_set_tia_idx(struct rtw89_dev *rtwdev, u8 tia_idx)
2797 {
2798 	rtw89_phy_write32_mask(rtwdev, R_PATH0_TIA_INIT,
2799 			       B_PATH0_TIA_INIT_IDX_MSK, tia_idx);
2800 	rtw89_phy_write32_mask(rtwdev, R_PATH1_TIA_INIT,
2801 			       B_PATH1_TIA_INIT_IDX_MSK, tia_idx);
2802 }
2803 
2804 static void rtw89_phy_dig_set_rxb_idx(struct rtw89_dev *rtwdev, u8 rxb_idx)
2805 {
2806 	rtw89_phy_write32_mask(rtwdev, R_PATH0_RXB_INIT,
2807 			       B_PATH0_RXB_INIT_IDX_MSK, rxb_idx);
2808 	rtw89_phy_write32_mask(rtwdev, R_PATH1_RXB_INIT,
2809 			       B_PATH1_RXB_INIT_IDX_MSK, rxb_idx);
2810 }
2811 
2812 static void rtw89_phy_dig_set_igi_cr(struct rtw89_dev *rtwdev,
2813 				     const struct rtw89_agc_gaincode_set set)
2814 {
2815 	rtw89_phy_dig_set_lna_idx(rtwdev, set.lna_idx);
2816 	rtw89_phy_dig_set_tia_idx(rtwdev, set.tia_idx);
2817 	rtw89_phy_dig_set_rxb_idx(rtwdev, set.rxb_idx);
2818 
2819 	rtw89_debug(rtwdev, RTW89_DBG_DIG, "Set (lna,tia,rxb)=((%d,%d,%02d))\n",
2820 		    set.lna_idx, set.tia_idx, set.rxb_idx);
2821 }
2822 
2823 static const struct rtw89_reg_def sdagc_config[4] = {
2824 	{R_PATH0_P20_FOLLOW_BY_PAGCUGC, B_PATH0_P20_FOLLOW_BY_PAGCUGC_EN_MSK},
2825 	{R_PATH0_S20_FOLLOW_BY_PAGCUGC, B_PATH0_S20_FOLLOW_BY_PAGCUGC_EN_MSK},
2826 	{R_PATH1_P20_FOLLOW_BY_PAGCUGC, B_PATH1_P20_FOLLOW_BY_PAGCUGC_EN_MSK},
2827 	{R_PATH1_S20_FOLLOW_BY_PAGCUGC, B_PATH1_S20_FOLLOW_BY_PAGCUGC_EN_MSK},
2828 };
2829 
2830 static void rtw89_phy_dig_sdagc_follow_pagc_config(struct rtw89_dev *rtwdev,
2831 						   bool enable)
2832 {
2833 	u8 i = 0;
2834 
2835 	for (i = 0; i < ARRAY_SIZE(sdagc_config); i++)
2836 		rtw89_phy_write32_mask(rtwdev, sdagc_config[i].addr,
2837 				       sdagc_config[i].mask, enable);
2838 
2839 	rtw89_debug(rtwdev, RTW89_DBG_DIG, "sdagc_follow_pagc=%d\n", enable);
2840 }
2841 
2842 static void rtw89_phy_dig_dyn_pd_th(struct rtw89_dev *rtwdev, u8 rssi,
2843 				    bool enable)
2844 {
2845 	enum rtw89_bandwidth cbw = rtwdev->hal.current_band_width;
2846 	struct rtw89_dig_info *dig = &rtwdev->dig;
2847 	u8 final_rssi = 0, under_region = dig->pd_low_th_ofst;
2848 	u32 val = 0;
2849 
2850 	under_region += PD_TH_SB_FLTR_CMP_VAL;
2851 
2852 	switch (cbw) {
2853 	case RTW89_CHANNEL_WIDTH_40:
2854 		under_region += PD_TH_BW40_CMP_VAL;
2855 		break;
2856 	case RTW89_CHANNEL_WIDTH_80:
2857 		under_region += PD_TH_BW80_CMP_VAL;
2858 		break;
2859 	case RTW89_CHANNEL_WIDTH_20:
2860 		fallthrough;
2861 	default:
2862 		under_region += PD_TH_BW20_CMP_VAL;
2863 		break;
2864 	}
2865 
2866 	dig->dyn_pd_th_max = dig->igi_rssi;
2867 
2868 	final_rssi = min_t(u8, rssi, dig->igi_rssi);
2869 	final_rssi = clamp_t(u8, final_rssi, PD_TH_MIN_RSSI + under_region,
2870 			     PD_TH_MAX_RSSI + under_region);
2871 
2872 	if (enable) {
2873 		val = (final_rssi - under_region - PD_TH_MIN_RSSI) >> 1;
2874 		rtw89_debug(rtwdev, RTW89_DBG_DIG,
2875 			    "dyn_max=%d, final_rssi=%d, total=%d, PD_low=%d\n",
2876 			    dig->igi_rssi, final_rssi, under_region, val);
2877 	} else {
2878 		rtw89_debug(rtwdev, RTW89_DBG_DIG,
2879 			    "Dynamic PD th disabled, Set PD_low_bd=0\n");
2880 	}
2881 
2882 	rtw89_phy_write32_mask(rtwdev, R_SEG0R_PD, B_SEG0R_PD_LOWER_BOUND_MSK,
2883 			       val);
2884 	rtw89_phy_write32_mask(rtwdev, R_SEG0R_PD,
2885 			       B_SEG0R_PD_SPATIAL_REUSE_EN_MSK, enable);
2886 }
2887 
2888 void rtw89_phy_dig_reset(struct rtw89_dev *rtwdev)
2889 {
2890 	struct rtw89_dig_info *dig = &rtwdev->dig;
2891 
2892 	dig->bypass_dig = false;
2893 	rtw89_phy_dig_para_reset(rtwdev);
2894 	rtw89_phy_dig_set_igi_cr(rtwdev, dig->force_gaincode);
2895 	rtw89_phy_dig_dyn_pd_th(rtwdev, rssi_nolink, false);
2896 	rtw89_phy_dig_sdagc_follow_pagc_config(rtwdev, false);
2897 	rtw89_phy_dig_update_para(rtwdev);
2898 }
2899 
2900 #define IGI_RSSI_MIN 10
2901 void rtw89_phy_dig(struct rtw89_dev *rtwdev)
2902 {
2903 	struct rtw89_dig_info *dig = &rtwdev->dig;
2904 	bool is_linked = rtwdev->total_sta_assoc > 0;
2905 
2906 	if (unlikely(dig->bypass_dig)) {
2907 		dig->bypass_dig = false;
2908 		return;
2909 	}
2910 
2911 	if (!dig->is_linked_pre && is_linked) {
2912 		rtw89_debug(rtwdev, RTW89_DBG_DIG, "First connected\n");
2913 		rtw89_phy_dig_update_para(rtwdev);
2914 	} else if (dig->is_linked_pre && !is_linked) {
2915 		rtw89_debug(rtwdev, RTW89_DBG_DIG, "First disconnected\n");
2916 		rtw89_phy_dig_update_para(rtwdev);
2917 	}
2918 	dig->is_linked_pre = is_linked;
2919 
2920 	rtw89_phy_dig_igi_offset_by_env(rtwdev);
2921 	rtw89_phy_dig_update_rssi_info(rtwdev);
2922 
2923 	dig->dyn_igi_min = (dig->igi_rssi > IGI_RSSI_MIN) ?
2924 			    dig->igi_rssi - IGI_RSSI_MIN : 0;
2925 	dig->dyn_igi_max = dig->dyn_igi_min + IGI_OFFSET_MAX;
2926 	dig->igi_fa_rssi = dig->dyn_igi_min + dig->fa_rssi_ofst;
2927 
2928 	dig->igi_fa_rssi = clamp(dig->igi_fa_rssi, dig->dyn_igi_min,
2929 				 dig->dyn_igi_max);
2930 
2931 	rtw89_debug(rtwdev, RTW89_DBG_DIG,
2932 		    "rssi=%03d, dyn(max,min)=(%d,%d), final_rssi=%d\n",
2933 		    dig->igi_rssi, dig->dyn_igi_max, dig->dyn_igi_min,
2934 		    dig->igi_fa_rssi);
2935 
2936 	if (dig->force_gaincode_idx_en) {
2937 		rtw89_phy_dig_set_igi_cr(rtwdev, dig->force_gaincode);
2938 		rtw89_debug(rtwdev, RTW89_DBG_DIG,
2939 			    "Force gaincode index enabled.\n");
2940 	} else {
2941 		rtw89_phy_dig_gaincode_by_rssi(rtwdev, dig->igi_fa_rssi,
2942 					       &dig->cur_gaincode);
2943 		rtw89_phy_dig_set_igi_cr(rtwdev, dig->cur_gaincode);
2944 	}
2945 
2946 	rtw89_phy_dig_dyn_pd_th(rtwdev, dig->igi_fa_rssi, dig->dyn_pd_th_en);
2947 
2948 	if (dig->dyn_pd_th_en && dig->igi_fa_rssi > dig->dyn_pd_th_max)
2949 		rtw89_phy_dig_sdagc_follow_pagc_config(rtwdev, true);
2950 	else
2951 		rtw89_phy_dig_sdagc_follow_pagc_config(rtwdev, false);
2952 }
2953 
2954 static void rtw89_phy_env_monitor_init(struct rtw89_dev *rtwdev)
2955 {
2956 	rtw89_phy_ccx_top_setting_init(rtwdev);
2957 	rtw89_phy_ifs_clm_setting_init(rtwdev);
2958 }
2959 
2960 void rtw89_phy_dm_init(struct rtw89_dev *rtwdev)
2961 {
2962 	const struct rtw89_chip_info *chip = rtwdev->chip;
2963 
2964 	rtw89_phy_stat_init(rtwdev);
2965 
2966 	rtw89_chip_bb_sethw(rtwdev);
2967 
2968 	rtw89_phy_env_monitor_init(rtwdev);
2969 	rtw89_physts_parsing_init(rtwdev);
2970 	rtw89_phy_dig_init(rtwdev);
2971 	rtw89_phy_cfo_init(rtwdev);
2972 
2973 	rtw89_phy_init_rf_nctl(rtwdev);
2974 	rtw89_chip_rfk_init(rtwdev);
2975 	rtw89_load_txpwr_table(rtwdev, chip->byr_table);
2976 	rtw89_chip_set_txpwr_ctrl(rtwdev);
2977 	rtw89_chip_power_trim(rtwdev);
2978 }
2979 
2980 void rtw89_phy_set_bss_color(struct rtw89_dev *rtwdev, struct ieee80211_vif *vif)
2981 {
2982 	enum rtw89_phy_idx phy_idx = RTW89_PHY_0;
2983 	u8 bss_color;
2984 
2985 	if (!vif->bss_conf.he_support || !vif->bss_conf.assoc)
2986 		return;
2987 
2988 	bss_color = vif->bss_conf.he_bss_color.color;
2989 
2990 	rtw89_phy_write32_idx(rtwdev, R_BSS_CLR_MAP, B_BSS_CLR_MAP_VLD0, 0x1,
2991 			      phy_idx);
2992 	rtw89_phy_write32_idx(rtwdev, R_BSS_CLR_MAP, B_BSS_CLR_MAP_TGT, bss_color,
2993 			      phy_idx);
2994 	rtw89_phy_write32_idx(rtwdev, R_BSS_CLR_MAP, B_BSS_CLR_MAP_STAID,
2995 			      vif->bss_conf.aid, phy_idx);
2996 }
2997