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