xref: /linux/drivers/ufs/host/ufs-qcom.c (revision 55b6593276c8aeeb7dff2507028166337c13a30e)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (c) 2013-2016, Linux Foundation. All rights reserved.
4  */
5 
6 #include <linux/acpi.h>
7 #include <linux/clk.h>
8 #include <linux/cleanup.h>
9 #include <linux/delay.h>
10 #include <linux/devfreq.h>
11 #include <linux/gpio/consumer.h>
12 #include <linux/interconnect.h>
13 #include <linux/module.h>
14 #include <linux/of.h>
15 #include <linux/phy/phy.h>
16 #include <linux/platform_device.h>
17 #include <linux/pm_domain.h>
18 #include <linux/reset-controller.h>
19 #include <linux/time.h>
20 #include <linux/unaligned.h>
21 #include <linux/units.h>
22 
23 #include <soc/qcom/ice.h>
24 
25 #include <ufs/ufshcd.h>
26 #include <ufs/ufshci.h>
27 #include <ufs/ufs_quirks.h>
28 #include <ufs/unipro.h>
29 #include "ufshcd-pltfrm.h"
30 #include "ufs-qcom.h"
31 
32 #define MCQ_QCFGPTR_MASK	GENMASK(7, 0)
33 #define MCQ_QCFGPTR_UNIT	0x200
34 #define MCQ_SQATTR_OFFSET(c) \
35 	((((c) >> 16) & MCQ_QCFGPTR_MASK) * MCQ_QCFGPTR_UNIT)
36 #define MCQ_QCFG_SIZE	0x40
37 
38 /* De-emphasis for gear-5 */
39 #define DEEMPHASIS_3_5_dB	0x04
40 #define NO_DEEMPHASIS		0x0
41 
42 #define UFS_ICE_SYNC_RST_SEL	BIT(3)
43 #define UFS_ICE_SYNC_RST_SW	BIT(4)
44 
45 enum {
46 	TSTBUS_UAWM,
47 	TSTBUS_UARM,
48 	TSTBUS_TXUC,
49 	TSTBUS_RXUC,
50 	TSTBUS_DFC,
51 	TSTBUS_TRLUT,
52 	TSTBUS_TMRLUT,
53 	TSTBUS_OCSC,
54 	TSTBUS_UTP_HCI,
55 	TSTBUS_COMBINED,
56 	TSTBUS_WRAPPER,
57 	TSTBUS_UNIPRO,
58 	TSTBUS_MAX,
59 };
60 
61 #define QCOM_UFS_MAX_GEAR 5
62 #define QCOM_UFS_MAX_LANE 2
63 
64 enum {
65 	MODE_MIN,
66 	MODE_PWM,
67 	MODE_HS_RA,
68 	MODE_HS_RB,
69 	MODE_MAX,
70 };
71 
72 static const struct __ufs_qcom_bw_table {
73 	u32 mem_bw;
74 	u32 cfg_bw;
75 } ufs_qcom_bw_table[MODE_MAX + 1][QCOM_UFS_MAX_GEAR + 1][QCOM_UFS_MAX_LANE + 1] = {
76 	[MODE_MIN][0][0]		   = { 0,		0 }, /* Bandwidth values in KB/s */
77 	[MODE_PWM][UFS_PWM_G1][UFS_LANE_1] = { 922,		1000 },
78 	[MODE_PWM][UFS_PWM_G2][UFS_LANE_1] = { 1844,		1000 },
79 	[MODE_PWM][UFS_PWM_G3][UFS_LANE_1] = { 3688,		1000 },
80 	[MODE_PWM][UFS_PWM_G4][UFS_LANE_1] = { 7376,		1000 },
81 	[MODE_PWM][UFS_PWM_G5][UFS_LANE_1] = { 14752,		1000 },
82 	[MODE_PWM][UFS_PWM_G1][UFS_LANE_2] = { 1844,		1000 },
83 	[MODE_PWM][UFS_PWM_G2][UFS_LANE_2] = { 3688,		1000 },
84 	[MODE_PWM][UFS_PWM_G3][UFS_LANE_2] = { 7376,		1000 },
85 	[MODE_PWM][UFS_PWM_G4][UFS_LANE_2] = { 14752,		1000 },
86 	[MODE_PWM][UFS_PWM_G5][UFS_LANE_2] = { 29504,		1000 },
87 	[MODE_HS_RA][UFS_HS_G1][UFS_LANE_1] = { 127796,		1000 },
88 	[MODE_HS_RA][UFS_HS_G2][UFS_LANE_1] = { 255591,		1000 },
89 	[MODE_HS_RA][UFS_HS_G3][UFS_LANE_1] = { 1492582,	102400 },
90 	[MODE_HS_RA][UFS_HS_G4][UFS_LANE_1] = { 2915200,	204800 },
91 	[MODE_HS_RA][UFS_HS_G5][UFS_LANE_1] = { 5836800,	409600 },
92 	[MODE_HS_RA][UFS_HS_G1][UFS_LANE_2] = { 255591,		1000 },
93 	[MODE_HS_RA][UFS_HS_G2][UFS_LANE_2] = { 511181,		1000 },
94 	[MODE_HS_RA][UFS_HS_G3][UFS_LANE_2] = { 1492582,	204800 },
95 	[MODE_HS_RA][UFS_HS_G4][UFS_LANE_2] = { 2915200,	409600 },
96 	[MODE_HS_RA][UFS_HS_G5][UFS_LANE_2] = { 5836800,	819200 },
97 	[MODE_HS_RB][UFS_HS_G1][UFS_LANE_1] = { 149422,		1000 },
98 	[MODE_HS_RB][UFS_HS_G2][UFS_LANE_1] = { 298189,		1000 },
99 	[MODE_HS_RB][UFS_HS_G3][UFS_LANE_1] = { 1492582,	102400 },
100 	[MODE_HS_RB][UFS_HS_G4][UFS_LANE_1] = { 2915200,	204800 },
101 	[MODE_HS_RB][UFS_HS_G5][UFS_LANE_1] = { 5836800,	409600 },
102 	[MODE_HS_RB][UFS_HS_G1][UFS_LANE_2] = { 298189,		1000 },
103 	[MODE_HS_RB][UFS_HS_G2][UFS_LANE_2] = { 596378,		1000 },
104 	[MODE_HS_RB][UFS_HS_G3][UFS_LANE_2] = { 1492582,	204800 },
105 	[MODE_HS_RB][UFS_HS_G4][UFS_LANE_2] = { 2915200,	409600 },
106 	[MODE_HS_RB][UFS_HS_G5][UFS_LANE_2] = { 5836800,	819200 },
107 	[MODE_MAX][0][0]		    = { 7643136,	819200 },
108 };
109 
110 static const struct {
111 	int nminor;
112 	char *prefix;
113 } testbus_info[TSTBUS_MAX] = {
114 	[TSTBUS_UAWM]     = {32, "TSTBUS_UAWM"},
115 	[TSTBUS_UARM]     = {32, "TSTBUS_UARM"},
116 	[TSTBUS_TXUC]     = {32, "TSTBUS_TXUC"},
117 	[TSTBUS_RXUC]     = {32, "TSTBUS_RXUC"},
118 	[TSTBUS_DFC]      = {32, "TSTBUS_DFC"},
119 	[TSTBUS_TRLUT]    = {32, "TSTBUS_TRLUT"},
120 	[TSTBUS_TMRLUT]   = {32, "TSTBUS_TMRLUT"},
121 	[TSTBUS_OCSC]     = {32, "TSTBUS_OCSC"},
122 	[TSTBUS_UTP_HCI]  = {32, "TSTBUS_UTP_HCI"},
123 	[TSTBUS_COMBINED] = {32, "TSTBUS_COMBINED"},
124 	[TSTBUS_WRAPPER]  = {32, "TSTBUS_WRAPPER"},
125 	[TSTBUS_UNIPRO]   = {256, "TSTBUS_UNIPRO"},
126 };
127 
128 static void ufs_qcom_get_default_testbus_cfg(struct ufs_qcom_host *host);
129 static unsigned long ufs_qcom_opp_freq_to_clk_freq(struct ufs_hba *hba,
130 						   unsigned long freq, char *name);
131 static int ufs_qcom_set_core_clk_ctrl(struct ufs_hba *hba, bool is_scale_up, unsigned long freq);
132 
133 static struct ufs_qcom_host *rcdev_to_ufs_host(struct reset_controller_dev *rcd)
134 {
135 	return container_of(rcd, struct ufs_qcom_host, rcdev);
136 }
137 
138 #ifdef CONFIG_SCSI_UFS_CRYPTO
139 /**
140  * ufs_qcom_config_ice_allocator() - ICE core allocator configuration
141  *
142  * @host: pointer to qcom specific variant structure.
143  */
144 static void ufs_qcom_config_ice_allocator(struct ufs_qcom_host *host)
145 {
146 	struct ufs_hba *hba = host->hba;
147 	static const uint8_t val[4] = { NUM_RX_R1W0, NUM_TX_R0W1, NUM_RX_R1W1, NUM_TX_R1W1 };
148 	u32 config;
149 
150 	if (!(host->caps & UFS_QCOM_CAP_ICE_CONFIG) ||
151 			!(host->hba->caps & UFSHCD_CAP_CRYPTO))
152 		return;
153 
154 	config = get_unaligned_le32(val);
155 
156 	ufshcd_writel(hba, ICE_ALLOCATOR_TYPE, REG_UFS_MEM_ICE_CONFIG);
157 	ufshcd_writel(hba, config, REG_UFS_MEM_ICE_NUM_CORE);
158 }
159 
160 static inline void ufs_qcom_ice_enable(struct ufs_qcom_host *host)
161 {
162 	if (host->hba->caps & UFSHCD_CAP_CRYPTO)
163 		qcom_ice_enable(host->ice);
164 }
165 
166 static const struct blk_crypto_ll_ops ufs_qcom_crypto_ops; /* forward decl */
167 
168 static int ufs_qcom_ice_init(struct ufs_qcom_host *host)
169 {
170 	struct ufs_hba *hba = host->hba;
171 	struct blk_crypto_profile *profile = &hba->crypto_profile;
172 	struct device *dev = hba->dev;
173 	struct qcom_ice *ice;
174 	union ufs_crypto_capabilities caps;
175 	union ufs_crypto_cap_entry cap;
176 	int err;
177 	int i;
178 
179 	ice = devm_of_qcom_ice_get(dev);
180 	if (IS_ERR(ice)) {
181 		if (ice != ERR_PTR(-EOPNOTSUPP))
182 			return PTR_ERR(ice);
183 
184 		dev_warn(dev, "Disabling inline encryption support\n");
185 		return 0;
186 	}
187 
188 	host->ice = ice;
189 
190 	/* Initialize the blk_crypto_profile */
191 
192 	caps.reg_val = cpu_to_le32(ufshcd_readl(hba, REG_UFS_CCAP));
193 
194 	/* The number of keyslots supported is (CFGC+1) */
195 	err = devm_blk_crypto_profile_init(dev, profile, caps.config_count + 1);
196 	if (err)
197 		return err;
198 
199 	profile->ll_ops = ufs_qcom_crypto_ops;
200 	profile->max_dun_bytes_supported = 8;
201 	profile->key_types_supported = qcom_ice_get_supported_key_type(ice);
202 	profile->dev = dev;
203 
204 	/*
205 	 * Currently this driver only supports AES-256-XTS.  All known versions
206 	 * of ICE support it, but to be safe make sure it is really declared in
207 	 * the crypto capability registers.  The crypto capability registers
208 	 * also give the supported data unit size(s).
209 	 */
210 	for (i = 0; i < caps.num_crypto_cap; i++) {
211 		cap.reg_val = cpu_to_le32(ufshcd_readl(hba,
212 						       REG_UFS_CRYPTOCAP +
213 						       i * sizeof(__le32)));
214 		if (cap.algorithm_id == UFS_CRYPTO_ALG_AES_XTS &&
215 		    cap.key_size == UFS_CRYPTO_KEY_SIZE_256)
216 			profile->modes_supported[BLK_ENCRYPTION_MODE_AES_256_XTS] |=
217 				cap.sdus_mask * 512;
218 	}
219 
220 	hba->caps |= UFSHCD_CAP_CRYPTO;
221 	hba->quirks |= UFSHCD_QUIRK_CUSTOM_CRYPTO_PROFILE;
222 	return 0;
223 }
224 
225 static inline int ufs_qcom_ice_resume(struct ufs_qcom_host *host)
226 {
227 	if (host->hba->caps & UFSHCD_CAP_CRYPTO)
228 		return qcom_ice_resume(host->ice);
229 
230 	return 0;
231 }
232 
233 static inline int ufs_qcom_ice_suspend(struct ufs_qcom_host *host)
234 {
235 	if (host->hba->caps & UFSHCD_CAP_CRYPTO)
236 		return qcom_ice_suspend(host->ice);
237 
238 	return 0;
239 }
240 
241 static int ufs_qcom_ice_keyslot_program(struct blk_crypto_profile *profile,
242 					const struct blk_crypto_key *key,
243 					unsigned int slot)
244 {
245 	struct ufs_hba *hba = ufs_hba_from_crypto_profile(profile);
246 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
247 	int err;
248 
249 	ufshcd_hold(hba);
250 	err = qcom_ice_program_key(host->ice, slot, key);
251 	ufshcd_release(hba);
252 	return err;
253 }
254 
255 static int ufs_qcom_ice_keyslot_evict(struct blk_crypto_profile *profile,
256 				      const struct blk_crypto_key *key,
257 				      unsigned int slot)
258 {
259 	struct ufs_hba *hba = ufs_hba_from_crypto_profile(profile);
260 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
261 	int err;
262 
263 	ufshcd_hold(hba);
264 	err = qcom_ice_evict_key(host->ice, slot);
265 	ufshcd_release(hba);
266 	return err;
267 }
268 
269 static int ufs_qcom_ice_derive_sw_secret(struct blk_crypto_profile *profile,
270 					 const u8 *eph_key, size_t eph_key_size,
271 					 u8 sw_secret[BLK_CRYPTO_SW_SECRET_SIZE])
272 {
273 	struct ufs_hba *hba = ufs_hba_from_crypto_profile(profile);
274 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
275 
276 	return qcom_ice_derive_sw_secret(host->ice, eph_key, eph_key_size,
277 					 sw_secret);
278 }
279 
280 static int ufs_qcom_ice_import_key(struct blk_crypto_profile *profile,
281 				   const u8 *raw_key, size_t raw_key_size,
282 				   u8 lt_key[BLK_CRYPTO_MAX_HW_WRAPPED_KEY_SIZE])
283 {
284 	struct ufs_hba *hba = ufs_hba_from_crypto_profile(profile);
285 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
286 
287 	return qcom_ice_import_key(host->ice, raw_key, raw_key_size, lt_key);
288 }
289 
290 static int ufs_qcom_ice_generate_key(struct blk_crypto_profile *profile,
291 				     u8 lt_key[BLK_CRYPTO_MAX_HW_WRAPPED_KEY_SIZE])
292 {
293 	struct ufs_hba *hba = ufs_hba_from_crypto_profile(profile);
294 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
295 
296 	return qcom_ice_generate_key(host->ice, lt_key);
297 }
298 
299 static int ufs_qcom_ice_prepare_key(struct blk_crypto_profile *profile,
300 				    const u8 *lt_key, size_t lt_key_size,
301 				    u8 eph_key[BLK_CRYPTO_MAX_HW_WRAPPED_KEY_SIZE])
302 {
303 	struct ufs_hba *hba = ufs_hba_from_crypto_profile(profile);
304 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
305 
306 	return qcom_ice_prepare_key(host->ice, lt_key, lt_key_size, eph_key);
307 }
308 
309 static const struct blk_crypto_ll_ops ufs_qcom_crypto_ops = {
310 	.keyslot_program	= ufs_qcom_ice_keyslot_program,
311 	.keyslot_evict		= ufs_qcom_ice_keyslot_evict,
312 	.derive_sw_secret	= ufs_qcom_ice_derive_sw_secret,
313 	.import_key		= ufs_qcom_ice_import_key,
314 	.generate_key		= ufs_qcom_ice_generate_key,
315 	.prepare_key		= ufs_qcom_ice_prepare_key,
316 };
317 
318 #else
319 
320 static inline void ufs_qcom_ice_enable(struct ufs_qcom_host *host)
321 {
322 }
323 
324 static int ufs_qcom_ice_init(struct ufs_qcom_host *host)
325 {
326 	return 0;
327 }
328 
329 static inline int ufs_qcom_ice_resume(struct ufs_qcom_host *host)
330 {
331 	return 0;
332 }
333 
334 static inline int ufs_qcom_ice_suspend(struct ufs_qcom_host *host)
335 {
336 	return 0;
337 }
338 
339 static void ufs_qcom_config_ice_allocator(struct ufs_qcom_host *host)
340 {
341 }
342 
343 #endif
344 
345 static void ufs_qcom_disable_lane_clks(struct ufs_qcom_host *host)
346 {
347 	if (!host->is_lane_clks_enabled)
348 		return;
349 
350 	clk_disable_unprepare(host->rx_lane1_sync_clk);
351 	clk_disable_unprepare(host->rx_lane0_sync_clk);
352 	clk_disable_unprepare(host->tx_lane0_sync_clk);
353 
354 	host->is_lane_clks_enabled = false;
355 }
356 
357 static int ufs_qcom_enable_lane_clks(struct ufs_qcom_host *host)
358 {
359 	int err;
360 
361 	if (host->is_lane_clks_enabled)
362 		return 0;
363 
364 	err = clk_prepare_enable(host->tx_lane0_sync_clk);
365 	if (err)
366 		goto out;
367 
368 	err = clk_prepare_enable(host->rx_lane0_sync_clk);
369 	if (err)
370 		goto out_disable_tx_lane0;
371 
372 	err = clk_prepare_enable(host->rx_lane1_sync_clk);
373 	if (err)
374 		goto out_disable_rx_lane0;
375 
376 	host->is_lane_clks_enabled = true;
377 
378 	return 0;
379 
380 out_disable_rx_lane0:
381 	clk_disable_unprepare(host->rx_lane0_sync_clk);
382 out_disable_tx_lane0:
383 	clk_disable_unprepare(host->tx_lane0_sync_clk);
384 out:
385 	return err;
386 }
387 
388 static int ufs_qcom_init_lane_clks(struct ufs_qcom_host *host)
389 {
390 	struct device *dev = host->hba->dev;
391 
392 	if (has_acpi_companion(dev))
393 		return 0;
394 
395 	host->tx_lane0_sync_clk = devm_clk_get(dev, "tx_lane0_sync_clk");
396 	if (IS_ERR(host->tx_lane0_sync_clk))
397 		return dev_err_probe(dev, PTR_ERR(host->tx_lane0_sync_clk),
398 				     "failed to get tx_lane0_sync_clk\n");
399 
400 	host->rx_lane0_sync_clk = devm_clk_get(dev, "rx_lane0_sync_clk");
401 	if (IS_ERR(host->rx_lane0_sync_clk))
402 		return dev_err_probe(dev, PTR_ERR(host->rx_lane0_sync_clk),
403 				     "failed to get rx_lane0_sync_clk\n");
404 
405 	/* In case of single lane per direction, don't read lane1 clocks */
406 	if (host->hba->lanes_per_direction > 1) {
407 		host->rx_lane1_sync_clk = devm_clk_get(dev, "rx_lane1_sync_clk");
408 		if (IS_ERR(host->rx_lane1_sync_clk))
409 			return dev_err_probe(dev, PTR_ERR(host->rx_lane1_sync_clk),
410 					     "failed to get rx_lane1_sync_clk\n");
411 	}
412 
413 	return 0;
414 }
415 
416 static int ufs_qcom_check_hibern8(struct ufs_hba *hba)
417 {
418 	int err;
419 	u32 tx_fsm_val;
420 	unsigned long timeout = jiffies + msecs_to_jiffies(HBRN8_POLL_TOUT_MS);
421 
422 	do {
423 		err = ufshcd_dme_get(hba,
424 				UIC_ARG_MIB_SEL(MPHY_TX_FSM_STATE,
425 					UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
426 				&tx_fsm_val);
427 		if (err || tx_fsm_val == TX_FSM_HIBERN8)
428 			break;
429 
430 		/* sleep for max. 200us */
431 		usleep_range(100, 200);
432 	} while (time_before(jiffies, timeout));
433 
434 	/*
435 	 * we might have scheduled out for long during polling so
436 	 * check the state again.
437 	 */
438 	if (time_after(jiffies, timeout))
439 		err = ufshcd_dme_get(hba,
440 				UIC_ARG_MIB_SEL(MPHY_TX_FSM_STATE,
441 					UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
442 				&tx_fsm_val);
443 
444 	if (err) {
445 		dev_err(hba->dev, "%s: unable to get TX_FSM_STATE, err %d\n",
446 				__func__, err);
447 	} else if (tx_fsm_val != TX_FSM_HIBERN8) {
448 		err = tx_fsm_val;
449 		dev_err(hba->dev, "%s: invalid TX_FSM_STATE = %d\n",
450 				__func__, err);
451 	}
452 
453 	return err;
454 }
455 
456 static void ufs_qcom_select_unipro_mode(struct ufs_qcom_host *host)
457 {
458 	ufshcd_rmwl(host->hba, QUNIPRO_SEL, QUNIPRO_SEL, REG_UFS_CFG1);
459 
460 	if (host->hw_ver.major >= 0x05)
461 		ufshcd_rmwl(host->hba, QUNIPRO_G4_SEL, 0, REG_UFS_CFG0);
462 }
463 
464 /*
465  * ufs_qcom_host_reset - reset host controller and PHY
466  */
467 static int ufs_qcom_host_reset(struct ufs_hba *hba)
468 {
469 	int ret;
470 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
471 	bool reenable_intr;
472 
473 	if (!host->core_reset)
474 		return 0;
475 
476 	reenable_intr = hba->is_irq_enabled;
477 	ufshcd_disable_irq(hba);
478 
479 	ret = reset_control_assert(host->core_reset);
480 	if (ret) {
481 		dev_err(hba->dev, "%s: core_reset assert failed, err = %d\n",
482 				 __func__, ret);
483 		return ret;
484 	}
485 
486 	/*
487 	 * The hardware requirement for delay between assert/deassert
488 	 * is at least 3-4 sleep clock (32.7KHz) cycles, which comes to
489 	 * ~125us (4/32768). To be on the safe side add 200us delay.
490 	 */
491 	usleep_range(200, 210);
492 
493 	ret = reset_control_deassert(host->core_reset);
494 	if (ret) {
495 		dev_err(hba->dev, "%s: core_reset deassert failed, err = %d\n",
496 				 __func__, ret);
497 		return ret;
498 	}
499 
500 	usleep_range(1000, 1100);
501 
502 	if (reenable_intr)
503 		ufshcd_enable_irq(hba);
504 
505 	return 0;
506 }
507 
508 static u32 ufs_qcom_get_hs_gear(struct ufs_hba *hba)
509 {
510 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
511 
512 	if (host->hw_ver.major >= 0x4)
513 		return UFS_QCOM_MAX_GEAR(ufshcd_readl(hba, REG_UFS_PARAM0));
514 
515 	/* Default is HS-G3 */
516 	return UFS_HS_G3;
517 }
518 
519 static int ufs_qcom_power_up_sequence(struct ufs_hba *hba)
520 {
521 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
522 	struct ufs_host_params *host_params = &host->host_params;
523 	struct phy *phy = host->generic_phy;
524 	enum phy_mode mode;
525 	int ret;
526 
527 	/*
528 	 * HW ver 5 can only support up to HS-G5 Rate-A due to HW limitations.
529 	 * If the HS-G5 PHY gear is used, update host_params->hs_rate to Rate-A,
530 	 * so that the subsequent power mode change shall stick to Rate-A.
531 	 */
532 	if (host->hw_ver.major == 0x5 && host->phy_gear == UFS_HS_G5)
533 		host_params->hs_rate = PA_HS_MODE_A;
534 
535 	mode = host_params->hs_rate == PA_HS_MODE_B ? PHY_MODE_UFS_HS_B : PHY_MODE_UFS_HS_A;
536 
537 	/* Reset UFS Host Controller and PHY */
538 	ret = ufs_qcom_host_reset(hba);
539 	if (ret)
540 		return ret;
541 
542 	if (phy->power_count)
543 		phy_power_off(phy);
544 
545 
546 	/* phy initialization - calibrate the phy */
547 	ret = phy_init(phy);
548 	if (ret) {
549 		dev_err(hba->dev, "%s: phy init failed, ret = %d\n",
550 			__func__, ret);
551 		return ret;
552 	}
553 
554 	ret = phy_set_mode_ext(phy, mode, host->phy_gear);
555 	if (ret)
556 		goto out_disable_phy;
557 
558 	/* power on phy - start serdes and phy's power and clocks */
559 	ret = phy_power_on(phy);
560 	if (ret) {
561 		dev_err(hba->dev, "%s: phy power on failed, ret = %d\n",
562 			__func__, ret);
563 		goto out_disable_phy;
564 	}
565 
566 	ret = phy_calibrate(phy);
567 	if (ret) {
568 		dev_err(hba->dev, "Failed to calibrate PHY: %d\n", ret);
569 		goto out_disable_phy;
570 	}
571 
572 	ufs_qcom_select_unipro_mode(host);
573 
574 	return 0;
575 
576 out_disable_phy:
577 	phy_exit(phy);
578 
579 	return ret;
580 }
581 
582 /*
583  * The UTP controller has a number of internal clock gating cells (CGCs).
584  * Internal hardware sub-modules within the UTP controller control the CGCs.
585  * Hardware CGCs disable the clock to inactivate UTP sub-modules not involved
586  * in a specific operation, UTP controller CGCs are by default disabled and
587  * this function enables them (after every UFS link startup) to save some power
588  * leakage.
589  */
590 static void ufs_qcom_enable_hw_clk_gating(struct ufs_hba *hba)
591 {
592 	int err;
593 
594 	/* Enable UTP internal clock gating */
595 	ufshcd_rmwl(hba, REG_UFS_CFG2_CGC_EN_ALL, REG_UFS_CFG2_CGC_EN_ALL,
596 		    REG_UFS_CFG2);
597 
598 	/* Ensure that HW clock gating is enabled before next operations */
599 	ufshcd_readl(hba, REG_UFS_CFG2);
600 
601 	/* Enable Unipro internal clock gating */
602 	err = ufshcd_dme_rmw(hba, DL_VS_CLK_CFG_MASK,
603 			     DL_VS_CLK_CFG_MASK, DL_VS_CLK_CFG);
604 	if (err)
605 		goto out;
606 
607 	err = ufshcd_dme_rmw(hba, PA_VS_CLK_CFG_REG_MASK,
608 			     PA_VS_CLK_CFG_REG_MASK, PA_VS_CLK_CFG_REG);
609 	if (err)
610 		goto out;
611 
612 	err = ufshcd_dme_rmw(hba, DME_VS_CORE_CLK_CTRL_DME_HW_CGC_EN,
613 			     DME_VS_CORE_CLK_CTRL_DME_HW_CGC_EN,
614 			     DME_VS_CORE_CLK_CTRL);
615 out:
616 	if (err)
617 		dev_err(hba->dev, "hw clk gating enabled failed\n");
618 }
619 
620 static int ufs_qcom_hce_enable_notify(struct ufs_hba *hba,
621 				      enum ufs_notify_change_status status)
622 {
623 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
624 	int err;
625 
626 	switch (status) {
627 	case PRE_CHANGE:
628 		err = ufs_qcom_power_up_sequence(hba);
629 		if (err)
630 			return err;
631 
632 		/*
633 		 * The PHY PLL output is the source of tx/rx lane symbol
634 		 * clocks, hence, enable the lane clocks only after PHY
635 		 * is initialized.
636 		 */
637 		err = ufs_qcom_enable_lane_clks(host);
638 		break;
639 	case POST_CHANGE:
640 		/* check if UFS PHY moved from DISABLED to HIBERN8 */
641 		err = ufs_qcom_check_hibern8(hba);
642 		ufs_qcom_enable_hw_clk_gating(hba);
643 		ufs_qcom_ice_enable(host);
644 		ufs_qcom_config_ice_allocator(host);
645 		break;
646 	default:
647 		dev_err(hba->dev, "%s: invalid status %d\n", __func__, status);
648 		err = -EINVAL;
649 		break;
650 	}
651 	return err;
652 }
653 
654 static int ufs_qcom_fw_managed_hce_enable_notify(struct ufs_hba *hba,
655 						 enum ufs_notify_change_status status)
656 {
657 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
658 
659 	switch (status) {
660 	case PRE_CHANGE:
661 		ufs_qcom_select_unipro_mode(host);
662 		break;
663 	case POST_CHANGE:
664 		ufs_qcom_enable_hw_clk_gating(hba);
665 		ufs_qcom_ice_enable(host);
666 		break;
667 	default:
668 		dev_err(hba->dev, "Invalid status %d\n", status);
669 		return -EINVAL;
670 	}
671 
672 	return 0;
673 }
674 
675 /**
676  * ufs_qcom_cfg_timers - Configure ufs qcom cfg timers
677  *
678  * @hba: host controller instance
679  * @is_pre_scale_up: flag to check if pre scale up condition.
680  * @freq: target opp freq
681  * Return: zero for success and non-zero in case of a failure.
682  */
683 static int ufs_qcom_cfg_timers(struct ufs_hba *hba, bool is_pre_scale_up, unsigned long freq)
684 {
685 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
686 	struct ufs_clk_info *clki;
687 	unsigned long clk_freq = 0;
688 	u32 core_clk_cycles_per_us;
689 
690 	/*
691 	 * UTP controller uses SYS1CLK_1US_REG register for Interrupt
692 	 * Aggregation logic.
693 	 * It is mandatory to write SYS1CLK_1US_REG register on UFS host
694 	 * controller V4.0.0 onwards.
695 	 */
696 	if (host->hw_ver.major < 4 && !ufshcd_is_intr_aggr_allowed(hba))
697 		return 0;
698 
699 	if (hba->use_pm_opp && freq != ULONG_MAX) {
700 		clk_freq = ufs_qcom_opp_freq_to_clk_freq(hba, freq, "core_clk");
701 		if (clk_freq)
702 			goto cfg_timers;
703 	}
704 
705 	list_for_each_entry(clki, &hba->clk_list_head, list) {
706 		if (!strcmp(clki->name, "core_clk")) {
707 			if (freq == ULONG_MAX) {
708 				clk_freq = clki->max_freq;
709 				break;
710 			}
711 
712 			if (is_pre_scale_up)
713 				clk_freq = clki->max_freq;
714 			else
715 				clk_freq = clk_get_rate(clki->clk);
716 			break;
717 		}
718 
719 	}
720 
721 cfg_timers:
722 	/* If frequency is smaller than 1MHz, set to 1MHz */
723 	if (clk_freq < DEFAULT_CLK_RATE_HZ)
724 		clk_freq = DEFAULT_CLK_RATE_HZ;
725 
726 	core_clk_cycles_per_us = clk_freq / USEC_PER_SEC;
727 	if (ufshcd_readl(hba, REG_UFS_SYS1CLK_1US) != core_clk_cycles_per_us) {
728 		ufshcd_writel(hba, core_clk_cycles_per_us, REG_UFS_SYS1CLK_1US);
729 		/*
730 		 * make sure above write gets applied before we return from
731 		 * this function.
732 		 */
733 		ufshcd_readl(hba, REG_UFS_SYS1CLK_1US);
734 	}
735 
736 	return 0;
737 }
738 
739 static void ufs_qcom_link_startup_post_change(struct ufs_hba *hba)
740 {
741 	if (ufshcd_is_auto_hibern8_supported(hba))
742 		ufshcd_rmwl(hba, UFS_HW_CLK_CTRL_EN, UFS_HW_CLK_CTRL_EN,
743 			    UFS_AH8_CFG);
744 }
745 
746 static int ufs_qcom_link_startup_notify(struct ufs_hba *hba,
747 					enum ufs_notify_change_status status)
748 {
749 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
750 	int err = 0;
751 
752 	switch (status) {
753 	case PRE_CHANGE:
754 		if (ufs_qcom_cfg_timers(hba, false, ULONG_MAX)) {
755 			dev_err(hba->dev, "%s: ufs_qcom_cfg_timers() failed\n",
756 				__func__);
757 			return -EINVAL;
758 		}
759 
760 		err = ufs_qcom_set_core_clk_ctrl(hba, true, ULONG_MAX);
761 		if (err)
762 			dev_err(hba->dev, "cfg core clk ctrl failed\n");
763 		/*
764 		 * Some UFS devices (and may be host) have issues if LCC is
765 		 * enabled. So we are setting PA_Local_TX_LCC_Enable to 0
766 		 * before link startup which will make sure that both host
767 		 * and device TX LCC are disabled once link startup is
768 		 * completed.
769 		 */
770 		err = ufshcd_disable_host_tx_lcc(hba);
771 
772 		/*
773 		 * Restore HS/LS link startup mode set by bootloader
774 		 * after UFS reset clears REG_UFS_DEBUG_SPARE_CFG.
775 		 */
776 		if (host->hw_ver.major > 0x6 ||
777 		    (host->hw_ver.major == 0x6 && host->hw_ver.minor >= 0x2))
778 			ufshcd_writel(hba, host->boot_spare_cfg,
779 				      REG_UFS_DEBUG_SPARE_CFG);
780 		break;
781 	case POST_CHANGE:
782 		ufs_qcom_link_startup_post_change(hba);
783 		break;
784 	default:
785 		break;
786 	}
787 
788 	return err;
789 }
790 
791 static void ufs_qcom_device_reset_ctrl(struct ufs_hba *hba, bool asserted)
792 {
793 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
794 
795 	/* reset gpio is optional */
796 	if (!host->device_reset)
797 		return;
798 
799 	gpiod_set_value_cansleep(host->device_reset, asserted);
800 }
801 
802 static int ufs_qcom_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op,
803 	enum ufs_notify_change_status status)
804 {
805 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
806 
807 	if (status == PRE_CHANGE)
808 		return 0;
809 
810 	if (!ufs_qcom_is_link_active(hba))
811 		ufs_qcom_disable_lane_clks(host);
812 
813 
814 	/* reset the connected UFS device during power down */
815 	if (ufs_qcom_is_link_off(hba) && host->device_reset) {
816 		ufs_qcom_device_reset_ctrl(hba, true);
817 		/*
818 		 * After sending the SSU command, asserting the rst_n
819 		 * line causes the device firmware to wake up and
820 		 * execute its reset routine.
821 		 *
822 		 * During this process, the device may draw current
823 		 * beyond the permissible limit for low-power mode (LPM).
824 		 * A 10ms delay, based on experimental observations,
825 		 * allows the UFS device to complete its hardware reset
826 		 * before transitioning the power rail to LPM.
827 		 */
828 		usleep_range(10000, 11000);
829 	}
830 
831 	return ufs_qcom_ice_suspend(host);
832 }
833 
834 static int ufs_qcom_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
835 {
836 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
837 	int err;
838 	u32 reg_val;
839 
840 	err = ufs_qcom_enable_lane_clks(host);
841 	if (err)
842 		return err;
843 
844 	if ((!ufs_qcom_is_link_active(hba)) &&
845 	    host->hw_ver.major == 5 &&
846 	    host->hw_ver.minor == 0 &&
847 	    host->hw_ver.step == 0) {
848 		ufshcd_writel(hba, UFS_ICE_SYNC_RST_SEL | UFS_ICE_SYNC_RST_SW, UFS_MEM_ICE_CFG);
849 		reg_val = ufshcd_readl(hba, UFS_MEM_ICE_CFG);
850 		reg_val &= ~(UFS_ICE_SYNC_RST_SEL | UFS_ICE_SYNC_RST_SW);
851 		/*
852 		 * HW documentation doesn't recommend any delay between the
853 		 * reset set and clear. But we are enforcing an arbitrary delay
854 		 * to give flops enough time to settle in.
855 		 */
856 		usleep_range(50, 100);
857 		ufshcd_writel(hba, reg_val, UFS_MEM_ICE_CFG);
858 		ufshcd_readl(hba, UFS_MEM_ICE_CFG);
859 	}
860 
861 	return ufs_qcom_ice_resume(host);
862 }
863 
864 static int ufs_qcom_fw_managed_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op,
865 				       enum ufs_notify_change_status status)
866 {
867 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
868 
869 	if (status == PRE_CHANGE)
870 		return 0;
871 
872 	pm_runtime_put_sync(hba->dev);
873 
874 	return ufs_qcom_ice_suspend(host);
875 }
876 
877 static int ufs_qcom_fw_managed_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
878 {
879 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
880 	int err;
881 
882 	err = pm_runtime_resume_and_get(hba->dev);
883 	if (err) {
884 		dev_err(hba->dev, "PM runtime resume failed: %d\n", err);
885 		return err;
886 	}
887 
888 	return ufs_qcom_ice_resume(host);
889 }
890 
891 static void ufs_qcom_dev_ref_clk_ctrl(struct ufs_qcom_host *host, bool enable)
892 {
893 	if (host->dev_ref_clk_ctrl_mmio &&
894 	    (enable ^ host->is_dev_ref_clk_enabled)) {
895 		u32 temp = readl_relaxed(host->dev_ref_clk_ctrl_mmio);
896 
897 		if (enable)
898 			temp |= host->dev_ref_clk_en_mask;
899 		else
900 			temp &= ~host->dev_ref_clk_en_mask;
901 
902 		/*
903 		 * If we are here to disable this clock it might be immediately
904 		 * after entering into hibern8 in which case we need to make
905 		 * sure that device ref_clk is active for specific time after
906 		 * hibern8 enter.
907 		 */
908 		if (!enable) {
909 			unsigned long gating_wait;
910 
911 			gating_wait = host->hba->dev_info.clk_gating_wait_us;
912 			if (!gating_wait) {
913 				udelay(1);
914 			} else {
915 				/*
916 				 * bRefClkGatingWaitTime defines the minimum
917 				 * time for which the reference clock is
918 				 * required by device during transition from
919 				 * HS-MODE to LS-MODE or HIBERN8 state. Give it
920 				 * more delay to be on the safe side.
921 				 */
922 				gating_wait += 10;
923 				usleep_range(gating_wait, gating_wait + 10);
924 			}
925 		}
926 
927 		writel_relaxed(temp, host->dev_ref_clk_ctrl_mmio);
928 
929 		/*
930 		 * Make sure the write to ref_clk reaches the destination and
931 		 * not stored in a Write Buffer (WB).
932 		 */
933 		readl(host->dev_ref_clk_ctrl_mmio);
934 
935 		/*
936 		 * If we call hibern8 exit after this, we need to make sure that
937 		 * device ref_clk is stable for at least 1us before the hibern8
938 		 * exit command.
939 		 */
940 		if (enable)
941 			udelay(1);
942 
943 		host->is_dev_ref_clk_enabled = enable;
944 	}
945 }
946 
947 static int ufs_qcom_icc_set_bw(struct ufs_qcom_host *host, u32 mem_bw, u32 cfg_bw)
948 {
949 	struct device *dev = host->hba->dev;
950 	int ret;
951 
952 	ret = icc_set_bw(host->icc_ddr, 0, mem_bw);
953 	if (ret < 0) {
954 		dev_err(dev, "failed to set bandwidth request: %d\n", ret);
955 		return ret;
956 	}
957 
958 	ret = icc_set_bw(host->icc_cpu, 0, cfg_bw);
959 	if (ret < 0) {
960 		dev_err(dev, "failed to set bandwidth request: %d\n", ret);
961 		return ret;
962 	}
963 
964 	return 0;
965 }
966 
967 static struct __ufs_qcom_bw_table ufs_qcom_get_bw_table(struct ufs_qcom_host *host)
968 {
969 	struct ufs_pa_layer_attr *p = &host->dev_req_params;
970 	int gear = max_t(u32, p->gear_rx, p->gear_tx);
971 	int lane = max_t(u32, p->lane_rx, p->lane_tx);
972 
973 	if (WARN_ONCE(gear > QCOM_UFS_MAX_GEAR,
974 		      "ICC scaling for UFS Gear (%d) not supported. Using Gear (%d) bandwidth\n",
975 		      gear, QCOM_UFS_MAX_GEAR))
976 		gear = QCOM_UFS_MAX_GEAR;
977 
978 	if (WARN_ONCE(lane > QCOM_UFS_MAX_LANE,
979 		      "ICC scaling for UFS Lane (%d) not supported. Using Lane (%d) bandwidth\n",
980 		      lane, QCOM_UFS_MAX_LANE))
981 		lane = QCOM_UFS_MAX_LANE;
982 
983 	if (ufshcd_is_hs_mode(p)) {
984 		if (p->hs_rate == PA_HS_MODE_B)
985 			return ufs_qcom_bw_table[MODE_HS_RB][gear][lane];
986 		else
987 			return ufs_qcom_bw_table[MODE_HS_RA][gear][lane];
988 	} else {
989 		return ufs_qcom_bw_table[MODE_PWM][gear][lane];
990 	}
991 }
992 
993 static int ufs_qcom_icc_update_bw(struct ufs_qcom_host *host)
994 {
995 	struct __ufs_qcom_bw_table bw_table;
996 
997 	bw_table = ufs_qcom_get_bw_table(host);
998 
999 	return ufs_qcom_icc_set_bw(host, bw_table.mem_bw, bw_table.cfg_bw);
1000 }
1001 
1002 static void ufs_qcom_set_tx_hs_equalizer(struct ufs_hba *hba, u32 gear, u32 tx_lanes)
1003 {
1004 	u32 equalizer_val;
1005 	int ret, i;
1006 
1007 	/* Determine the equalizer value based on the gear */
1008 	equalizer_val = (gear == 5) ? DEEMPHASIS_3_5_dB : NO_DEEMPHASIS;
1009 
1010 	for (i = 0; i < tx_lanes; i++) {
1011 		ret = ufshcd_dme_set(hba, UIC_ARG_MIB_SEL(TX_HS_EQUALIZER, i),
1012 				     equalizer_val);
1013 		if (ret)
1014 			dev_err(hba->dev, "%s: failed equalizer lane %d\n",
1015 				__func__, i);
1016 	}
1017 }
1018 
1019 static int ufs_qcom_negotiate_pwr_mode(struct ufs_hba *hba,
1020 				       const struct ufs_pa_layer_attr *dev_max_params,
1021 				       struct ufs_pa_layer_attr *dev_req_params)
1022 {
1023 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
1024 	struct ufs_host_params *host_params = &host->host_params;
1025 
1026 	return ufshcd_negotiate_pwr_params(host_params, dev_max_params, dev_req_params);
1027 }
1028 
1029 static int ufs_qcom_pwr_change_notify(struct ufs_hba *hba,
1030 				      enum ufs_notify_change_status status,
1031 				      struct ufs_pa_layer_attr *dev_req_params)
1032 {
1033 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
1034 	int ret = 0;
1035 
1036 	if (!dev_req_params) {
1037 		pr_err("%s: incoming dev_req_params is NULL\n", __func__);
1038 		return -EINVAL;
1039 	}
1040 
1041 	switch (status) {
1042 	case PRE_CHANGE:
1043 		/*
1044 		 * During UFS driver probe, always update the PHY gear to match the negotiated
1045 		 * gear, so that, if quirk UFSHCD_QUIRK_REINIT_AFTER_MAX_GEAR_SWITCH is enabled,
1046 		 * the second init can program the optimal PHY settings. This allows one to start
1047 		 * the first init with either the minimum or the maximum support gear.
1048 		 */
1049 		if (hba->ufshcd_state == UFSHCD_STATE_RESET) {
1050 			/*
1051 			 * Skip REINIT if the negotiated gear matches with the
1052 			 * initial phy_gear. Otherwise, update the phy_gear to
1053 			 * program the optimal gear setting during REINIT.
1054 			 */
1055 			if (host->phy_gear == dev_req_params->gear_tx)
1056 				hba->quirks &= ~UFSHCD_QUIRK_REINIT_AFTER_MAX_GEAR_SWITCH;
1057 			else
1058 				host->phy_gear = dev_req_params->gear_tx;
1059 		}
1060 
1061 		/* enable the device ref clock before changing to HS mode */
1062 		if (!ufshcd_is_hs_mode(&hba->pwr_info) &&
1063 			ufshcd_is_hs_mode(dev_req_params))
1064 			ufs_qcom_dev_ref_clk_ctrl(host, true);
1065 
1066 		if (host->hw_ver.major >= 0x4) {
1067 			ufshcd_dme_configure_adapt(hba,
1068 						dev_req_params->gear_tx,
1069 						PA_INITIAL_ADAPT);
1070 		}
1071 
1072 		if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TX_DEEMPHASIS_TUNING)
1073 			ufs_qcom_set_tx_hs_equalizer(hba,
1074 					dev_req_params->gear_tx, dev_req_params->lane_tx);
1075 
1076 		break;
1077 	case POST_CHANGE:
1078 		/* cache the power mode parameters to use internally */
1079 		memcpy(&host->dev_req_params,
1080 				dev_req_params, sizeof(*dev_req_params));
1081 
1082 		ufs_qcom_icc_update_bw(host);
1083 
1084 		/* disable the device ref clock if entered PWM mode */
1085 		if (ufshcd_is_hs_mode(&hba->pwr_info) &&
1086 			!ufshcd_is_hs_mode(dev_req_params))
1087 			ufs_qcom_dev_ref_clk_ctrl(host, false);
1088 		break;
1089 	default:
1090 		ret = -EINVAL;
1091 		break;
1092 	}
1093 
1094 	return ret;
1095 }
1096 
1097 static int ufs_qcom_quirk_host_pa_saveconfigtime(struct ufs_hba *hba)
1098 {
1099 	int err;
1100 	u32 pa_vs_config_reg1;
1101 
1102 	err = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_VS_CONFIG_REG1),
1103 			     &pa_vs_config_reg1);
1104 	if (err)
1105 		return err;
1106 
1107 	/* Allow extension of MSB bits of PA_SaveConfigTime attribute */
1108 	return ufshcd_dme_set(hba, UIC_ARG_MIB(PA_VS_CONFIG_REG1),
1109 			    (pa_vs_config_reg1 | (1 << 12)));
1110 }
1111 
1112 static void ufs_qcom_override_pa_tx_hsg1_sync_len(struct ufs_hba *hba)
1113 {
1114 	int err;
1115 
1116 	err = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TX_HSG1_SYNC_LENGTH),
1117 				  PA_TX_HSG1_SYNC_LENGTH_VAL);
1118 	if (err)
1119 		dev_err(hba->dev, "Failed (%d) set PA_TX_HSG1_SYNC_LENGTH\n", err);
1120 }
1121 
1122 /**
1123  * ufs_qcom_double_t_adapt_l0l1l2l3 - Create a new adapt that doubles the
1124  * adaptation duration TADAPT_L0_L1_L2_L3 derived from the old adapt.
1125  *
1126  * @old_adapt: Original ADAPT_L0_L1_L2_L3 capability
1127  *
1128  * ADAPT_length_L0_L1_L2_L3 formula from M-PHY spec:
1129  * if (ADAPT_range_L0_L1_L2_L3 == COARSE) {
1130  *   ADAPT_length_L0_L1_L2_L3 = [0, 12]
1131  *   ADAPT_L0_L1_L2_L3 = 215 x 2^ADAPT_length_L0_L1_L2_L3
1132  * } else if (ADAPT_range_L0_L1_L2_L3 == FINE) {
1133  *   ADAPT_length_L0_L1_L2_L3 = [0, 127]
1134  *   TADAPT_L0_L1_L2_L3 = 215 x (ADAPT_length_L0_L1_L2_L3 + 1)
1135  * }
1136  *
1137  * To double the adaptation duration TADAPT_L0_L1_L2_L3:
1138  * 1. If adapt range is COARSE (1'b1), new adapt = old adapt + 1.
1139  * 2. If adapt range is FINE (1'b0):
1140  *   a) If old adapt length is < 64, (new adapt + 1) = 2 * (old adapt + 1).
1141  *   b) If old adapt length is >= 64, set new adapt to 0x88 using COARSE
1142  *      range, because new adapt get from equation in a) shall exceed 127.
1143  *
1144  * Examples:
1145  * ADAPT_range_L0_L1_L2_L3 | ADAPT_length_L0_L1_L2_L3 | TADAPT_L0_L1_L2_L3 (PAM-4 UI)
1146  *		0			3			131072
1147  *		0			7			262144
1148  *		0			63			2097152
1149  *		0			64			2129920
1150  *		0			127			4194304
1151  *		1			8			8388608
1152  *		1			9			16777216
1153  *		1			10			33554432
1154  *		1			11			67108864
1155  *		1			12			134217728
1156  *
1157  * Return: new adapt.
1158  */
1159 static u32 ufs_qcom_double_t_adapt_l0l1l2l3(u32 old_adapt)
1160 {
1161 	u32 adapt_length = old_adapt & ADAPT_LENGTH_MASK;
1162 	u32 new_adapt;
1163 
1164 	if (IS_ADAPT_RANGE_COARSE(old_adapt)) {
1165 		new_adapt = (adapt_length + 1) | ADAPT_RANGE_BIT;
1166 	} else {
1167 		if (adapt_length < 64)
1168 			new_adapt = (adapt_length << 1) + 1;
1169 		else
1170 			/*
1171 			 * 0x88 is the very coarse Adapt value which is two
1172 			 * times of the largest fine Adapt value (0x7F)
1173 			 */
1174 			new_adapt = 0x88;
1175 	}
1176 
1177 	return new_adapt;
1178 }
1179 
1180 static void ufs_qcom_limit_max_gear(struct ufs_hba *hba,
1181 				    enum ufs_hs_gear_tag gear)
1182 {
1183 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
1184 	struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
1185 	struct ufs_host_params *host_params = &host->host_params;
1186 
1187 	host_params->hs_tx_gear = gear;
1188 	host_params->hs_rx_gear = gear;
1189 	pwr_info->gear_tx = gear;
1190 	pwr_info->gear_rx = gear;
1191 
1192 	dev_warn(hba->dev, "Limited max gear of host and device to HS-G%d\n", gear);
1193 }
1194 
1195 static void ufs_qcom_fixup_tx_adapt_l0l1l2l3(struct ufs_hba *hba)
1196 {
1197 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
1198 	struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
1199 	struct ufs_host_params *host_params = &host->host_params;
1200 	u32 old_adapt, new_adapt, actual_adapt;
1201 	bool limit_speed = false;
1202 	int err;
1203 
1204 	if (host->hw_ver.major != 0x7 || host->hw_ver.minor > 0x1 ||
1205 	    host_params->hs_tx_gear <= UFS_HS_G5 ||
1206 	    pwr_info->gear_tx <= UFS_HS_G5)
1207 		return;
1208 
1209 	err = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PEERRXHSG6ADAPTINITIALL0L1L2L3), &old_adapt);
1210 	if (err)
1211 		goto out;
1212 
1213 	if (old_adapt > ADAPT_L0L1L2L3_LENGTH_MAX) {
1214 		dev_err(hba->dev, "PA_PeerRxHsG6AdaptInitialL0L1L2L3 value (0x%x) exceeds MAX\n",
1215 			old_adapt);
1216 		err = -ERANGE;
1217 		goto out;
1218 	}
1219 
1220 	new_adapt = ufs_qcom_double_t_adapt_l0l1l2l3(old_adapt);
1221 	dev_dbg(hba->dev, "Original PA_PeerRxHsG6AdaptInitialL0L1L2L3 = 0x%x, new value = 0x%x\n",
1222 		old_adapt, new_adapt);
1223 
1224 	/*
1225 	 * 0x8C is the max possible value allowed by UniPro v3.0 spec, some HWs
1226 	 * can accept 0x8D but some cannot.
1227 	 */
1228 	if (new_adapt <= ADAPT_L0L1L2L3_LENGTH_MAX ||
1229 	    (new_adapt == ADAPT_L0L1L2L3_LENGTH_MAX + 1 && host->hw_ver.minor == 0x1)) {
1230 		err = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PEERRXHSG6ADAPTINITIALL0L1L2L3),
1231 				     new_adapt);
1232 		if (err)
1233 			goto out;
1234 
1235 		err = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PEERRXHSG6ADAPTINITIALL0L1L2L3),
1236 				     &actual_adapt);
1237 		if (err)
1238 			goto out;
1239 
1240 		if (actual_adapt != new_adapt) {
1241 			limit_speed = true;
1242 			dev_warn(hba->dev, "PA_PeerRxHsG6AdaptInitialL0L1L2L3 0x%x, expect 0x%x\n",
1243 				 actual_adapt, new_adapt);
1244 		}
1245 	} else {
1246 		limit_speed = true;
1247 		dev_warn(hba->dev, "New PA_PeerRxHsG6AdaptInitialL0L1L2L3 (0x%x) is too large!\n",
1248 			 new_adapt);
1249 	}
1250 
1251 	err = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PEERRXHSG6ADAPTREFRESHL0L1L2L3), &old_adapt);
1252 	if (err)
1253 		goto out;
1254 
1255 	if (old_adapt > ADAPT_L0L1L2L3_LENGTH_MAX) {
1256 		dev_err(hba->dev, "PA_PeerRxHsG6AdaptRefreshL0L1L2L3 value (0x%x) exceeds MAX\n",
1257 			old_adapt);
1258 		err = -ERANGE;
1259 		goto out;
1260 	}
1261 
1262 	new_adapt = ufs_qcom_double_t_adapt_l0l1l2l3(old_adapt);
1263 	dev_dbg(hba->dev, "Original PA_PeerRxHsG6AdaptRefreshL0L1L2L3 = 0x%x, new value = 0x%x\n",
1264 		old_adapt, new_adapt);
1265 
1266 	/*
1267 	 * 0x8C is the max possible value allowed by UniPro v3.0 spec, some HWs
1268 	 * can accept 0x8D but some cannot.
1269 	 */
1270 	if (new_adapt <= ADAPT_L0L1L2L3_LENGTH_MAX ||
1271 	    (new_adapt == ADAPT_L0L1L2L3_LENGTH_MAX + 1 && host->hw_ver.minor == 0x1)) {
1272 		err = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PEERRXHSG6ADAPTREFRESHL0L1L2L3),
1273 				     new_adapt);
1274 		if (err)
1275 			goto out;
1276 
1277 		err = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PEERRXHSG6ADAPTREFRESHL0L1L2L3),
1278 				     &actual_adapt);
1279 		if (err)
1280 			goto out;
1281 
1282 		if (actual_adapt != new_adapt) {
1283 			limit_speed = true;
1284 			dev_warn(hba->dev, "PA_PeerRxHsG6AdaptRefreshL0L1L2L3 0x%x, expect 0x%x\n",
1285 				 new_adapt, actual_adapt);
1286 		}
1287 	} else {
1288 		limit_speed = true;
1289 		dev_warn(hba->dev, "New PA_PeerRxHsG6AdaptRefreshL0L1L2L3 (0x%x) is too large!\n",
1290 			 new_adapt);
1291 	}
1292 
1293 out:
1294 	if (limit_speed || err)
1295 		ufs_qcom_limit_max_gear(hba, UFS_HS_G5);
1296 }
1297 
1298 static int ufs_qcom_apply_dev_quirks(struct ufs_hba *hba)
1299 {
1300 	int err = 0;
1301 
1302 	ufs_qcom_fixup_tx_adapt_l0l1l2l3(hba);
1303 
1304 	if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME)
1305 		err = ufs_qcom_quirk_host_pa_saveconfigtime(hba);
1306 
1307 	if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TX_HSG1_SYNC_LENGTH)
1308 		ufs_qcom_override_pa_tx_hsg1_sync_len(hba);
1309 
1310 	return err;
1311 }
1312 
1313 /* UFS device-specific quirks */
1314 static struct ufs_dev_quirk ufs_qcom_dev_fixups[] = {
1315 	{ .wmanufacturerid = UFS_VENDOR_SKHYNIX,
1316 	  .model = UFS_ANY_MODEL,
1317 	  .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM },
1318 	{ .wmanufacturerid = UFS_VENDOR_WDC,
1319 	  .model = UFS_ANY_MODEL,
1320 	  .quirk = UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE },
1321 	{ .wmanufacturerid = UFS_VENDOR_SAMSUNG,
1322 	  .model = UFS_ANY_MODEL,
1323 	  .quirk = UFS_DEVICE_QUIRK_PA_TX_HSG1_SYNC_LENGTH |
1324 		   UFS_DEVICE_QUIRK_PA_TX_DEEMPHASIS_TUNING },
1325 	{}
1326 };
1327 
1328 static void ufs_qcom_fixup_dev_quirks(struct ufs_hba *hba)
1329 {
1330 	ufshcd_fixup_dev_quirks(hba, ufs_qcom_dev_fixups);
1331 }
1332 
1333 static u32 ufs_qcom_get_ufs_hci_version(struct ufs_hba *hba)
1334 {
1335 	return ufshci_version(2, 0);
1336 }
1337 
1338 /**
1339  * ufs_qcom_advertise_quirks - advertise the known QCOM UFS controller quirks
1340  * @hba: host controller instance
1341  *
1342  * QCOM UFS host controller might have some non standard behaviours (quirks)
1343  * than what is specified by UFSHCI specification. Advertise all such
1344  * quirks to standard UFS host controller driver so standard takes them into
1345  * account.
1346  */
1347 static void ufs_qcom_advertise_quirks(struct ufs_hba *hba)
1348 {
1349 	const struct ufs_qcom_drvdata *drvdata = of_device_get_match_data(hba->dev);
1350 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
1351 
1352 	if (host->hw_ver.major == 0x2)
1353 		hba->quirks |= UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION;
1354 
1355 	if (host->hw_ver.major > 0x3)
1356 		hba->quirks |= UFSHCD_QUIRK_REINIT_AFTER_MAX_GEAR_SWITCH;
1357 
1358 	if (host->hw_ver.major == 0x7 && host->hw_ver.minor == 0x1)
1359 		hba->quirks |= UFSHCD_QUIRK_EXTENDED_TX_EQTR_ADAPT_LENGTH_L0L1L2L3;
1360 
1361 	if (drvdata && drvdata->quirks)
1362 		hba->quirks |= drvdata->quirks;
1363 }
1364 
1365 static void ufs_qcom_set_phy_gear(struct ufs_qcom_host *host)
1366 {
1367 	struct ufs_host_params *host_params = &host->host_params;
1368 	u32 dev_major;
1369 
1370 	/*
1371 	 * Default to powering up the PHY to the max gear possible, which is
1372 	 * backwards compatible with lower gears but not optimal from
1373 	 * a power usage point of view. After device negotiation, if the
1374 	 * gear is lower a reinit will be performed to program the PHY
1375 	 * to the ideal gear for this combo of controller and device.
1376 	 */
1377 	host->phy_gear = host_params->hs_tx_gear;
1378 
1379 	if (host->hw_ver.major < 0x4) {
1380 		/*
1381 		 * These controllers only have one PHY init sequence,
1382 		 * let's power up the PHY using that (the minimum supported
1383 		 * gear, UFS_HS_G2).
1384 		 */
1385 		host->phy_gear = UFS_HS_G2;
1386 	} else if (host->hw_ver.major >= 0x5) {
1387 		host->boot_spare_cfg = ufshcd_readl(host->hba, REG_UFS_DEBUG_SPARE_CFG);
1388 		dev_major = FIELD_GET(UFS_DEV_VER_MAJOR_MASK, host->boot_spare_cfg);
1389 
1390 		/*
1391 		 * Since the UFS device version is populated, let's remove the
1392 		 * REINIT quirk as the negotiated gear won't change during boot.
1393 		 * So there is no need to do reinit.
1394 		 */
1395 		if (dev_major != 0x0)
1396 			host->hba->quirks &= ~UFSHCD_QUIRK_REINIT_AFTER_MAX_GEAR_SWITCH;
1397 
1398 		/*
1399 		 * For UFS 3.1 device and older, power up the PHY using HS-G4
1400 		 * PHY gear to save power.
1401 		 */
1402 		if (dev_major > 0x0 && dev_major < 0x4)
1403 			host->phy_gear = UFS_HS_G4;
1404 	}
1405 }
1406 
1407 static void ufs_qcom_parse_gear_limits(struct ufs_hba *hba)
1408 {
1409 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
1410 	struct ufs_host_params *host_params = &host->host_params;
1411 	u32 hs_gear_old = host_params->hs_tx_gear;
1412 
1413 	ufshcd_parse_gear_limits(hba, host_params);
1414 	if (host_params->hs_tx_gear != hs_gear_old) {
1415 		host->phy_gear = host_params->hs_tx_gear;
1416 	}
1417 }
1418 
1419 static void ufs_qcom_set_host_params(struct ufs_hba *hba)
1420 {
1421 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
1422 	struct ufs_host_params *host_params = &host->host_params;
1423 
1424 	ufshcd_init_host_params(host_params);
1425 
1426 	/* This driver only supports symmetic gear setting i.e., hs_tx_gear == hs_rx_gear */
1427 	host_params->hs_tx_gear = host_params->hs_rx_gear = ufs_qcom_get_hs_gear(hba);
1428 }
1429 
1430 static void ufs_qcom_set_host_caps(struct ufs_hba *hba)
1431 {
1432 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
1433 
1434 	if (host->hw_ver.major >= 0x5)
1435 		host->caps |= UFS_QCOM_CAP_ICE_CONFIG;
1436 }
1437 
1438 static void ufs_qcom_set_caps(struct ufs_hba *hba)
1439 {
1440 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
1441 
1442 	hba->caps |= UFSHCD_CAP_CLK_GATING | UFSHCD_CAP_HIBERN8_WITH_CLK_GATING;
1443 	hba->caps |= UFSHCD_CAP_CLK_SCALING | UFSHCD_CAP_WB_WITH_CLK_SCALING;
1444 	hba->caps |= UFSHCD_CAP_AUTO_BKOPS_SUSPEND;
1445 	hba->caps |= UFSHCD_CAP_WB_EN;
1446 	hba->caps |= UFSHCD_CAP_AGGR_POWER_COLLAPSE;
1447 	hba->caps |= UFSHCD_CAP_RPM_AUTOSUSPEND;
1448 
1449 	if (host->hw_ver.major >= 0x7)
1450 		hba->caps |= UFSHCD_CAP_TX_EQUALIZATION;
1451 
1452 	ufs_qcom_set_host_caps(hba);
1453 }
1454 
1455 /**
1456  * ufs_qcom_setup_clocks - enables/disable clocks
1457  * @hba: host controller instance
1458  * @on: If true, enable clocks else disable them.
1459  * @status: PRE_CHANGE or POST_CHANGE notify
1460  *
1461  * There are certain clocks which comes from the PHY so it needs
1462  * to be managed together along with controller clocks which also
1463  * provides a better power saving. Hence keep phy_power_off/on calls
1464  * in ufs_qcom_setup_clocks, so that PHY's regulators & clks can be
1465  * turned on/off along with UFS's clocks.
1466  *
1467  * Return: 0 on success, non-zero on failure.
1468  */
1469 static int ufs_qcom_setup_clocks(struct ufs_hba *hba, bool on,
1470 				 enum ufs_notify_change_status status)
1471 {
1472 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
1473 	struct phy *phy;
1474 	int err;
1475 
1476 	/*
1477 	 * In case ufs_qcom_init() is not yet done, simply ignore.
1478 	 * This ufs_qcom_setup_clocks() shall be called from
1479 	 * ufs_qcom_init() after init is done.
1480 	 */
1481 	if (!host)
1482 		return 0;
1483 
1484 	phy = host->generic_phy;
1485 
1486 	switch (status) {
1487 	case PRE_CHANGE:
1488 		if (on) {
1489 			ufs_qcom_icc_update_bw(host);
1490 			if (ufs_qcom_is_link_hibern8(hba)) {
1491 				err = ufs_qcom_enable_lane_clks(host);
1492 				if (err) {
1493 					dev_err(hba->dev, "enable lane clks failed, ret=%d\n", err);
1494 					return err;
1495 				}
1496 			}
1497 		} else {
1498 			if (!ufs_qcom_is_link_active(hba)) {
1499 				/* disable device ref_clk */
1500 				ufs_qcom_dev_ref_clk_ctrl(host, false);
1501 			}
1502 
1503 			err = phy_power_off(phy);
1504 			if (err) {
1505 				dev_err(hba->dev, "phy power off failed, ret=%d\n", err);
1506 				return err;
1507 			}
1508 		}
1509 		break;
1510 	case POST_CHANGE:
1511 		if (on) {
1512 			err = phy_power_on(phy);
1513 			if (err) {
1514 				dev_err(hba->dev, "phy power on failed, ret = %d\n", err);
1515 				return err;
1516 			}
1517 
1518 			/* enable the device ref clock for HS mode*/
1519 			if (ufshcd_is_hs_mode(&hba->pwr_info))
1520 				ufs_qcom_dev_ref_clk_ctrl(host, true);
1521 		} else {
1522 			if (ufs_qcom_is_link_hibern8(hba))
1523 				ufs_qcom_disable_lane_clks(host);
1524 
1525 			ufs_qcom_icc_set_bw(host, ufs_qcom_bw_table[MODE_MIN][0][0].mem_bw,
1526 					    ufs_qcom_bw_table[MODE_MIN][0][0].cfg_bw);
1527 		}
1528 		break;
1529 	}
1530 
1531 	return 0;
1532 }
1533 
1534 static int
1535 ufs_qcom_reset_assert(struct reset_controller_dev *rcdev, unsigned long id)
1536 {
1537 	struct ufs_qcom_host *host = rcdev_to_ufs_host(rcdev);
1538 
1539 	ufs_qcom_assert_reset(host->hba);
1540 	/* provide 1ms delay to let the reset pulse propagate. */
1541 	usleep_range(1000, 1100);
1542 	return 0;
1543 }
1544 
1545 static int
1546 ufs_qcom_reset_deassert(struct reset_controller_dev *rcdev, unsigned long id)
1547 {
1548 	struct ufs_qcom_host *host = rcdev_to_ufs_host(rcdev);
1549 
1550 	ufs_qcom_deassert_reset(host->hba);
1551 
1552 	/*
1553 	 * after reset deassertion, phy will need all ref clocks,
1554 	 * voltage, current to settle down before starting serdes.
1555 	 */
1556 	usleep_range(1000, 1100);
1557 	return 0;
1558 }
1559 
1560 static const struct reset_control_ops ufs_qcom_reset_ops = {
1561 	.assert = ufs_qcom_reset_assert,
1562 	.deassert = ufs_qcom_reset_deassert,
1563 };
1564 
1565 static int ufs_qcom_icc_init(struct ufs_qcom_host *host)
1566 {
1567 	struct device *dev = host->hba->dev;
1568 	int ret;
1569 
1570 	host->icc_ddr = devm_of_icc_get(dev, "ufs-ddr");
1571 	if (IS_ERR(host->icc_ddr))
1572 		return dev_err_probe(dev, PTR_ERR(host->icc_ddr),
1573 				    "failed to acquire interconnect path\n");
1574 
1575 	host->icc_cpu = devm_of_icc_get(dev, "cpu-ufs");
1576 	if (IS_ERR(host->icc_cpu))
1577 		return dev_err_probe(dev, PTR_ERR(host->icc_cpu),
1578 				    "failed to acquire interconnect path\n");
1579 
1580 	/*
1581 	 * Set Maximum bandwidth vote before initializing the UFS controller and
1582 	 * device. Ideally, a minimal interconnect vote would suffice for the
1583 	 * initialization, but a max vote would allow faster initialization.
1584 	 */
1585 	ret = ufs_qcom_icc_set_bw(host, ufs_qcom_bw_table[MODE_MAX][0][0].mem_bw,
1586 				  ufs_qcom_bw_table[MODE_MAX][0][0].cfg_bw);
1587 	if (ret < 0)
1588 		return dev_err_probe(dev, ret, "failed to set bandwidth request\n");
1589 
1590 	return 0;
1591 }
1592 
1593 /**
1594  * ufs_qcom_init - bind phy with controller
1595  * @hba: host controller instance
1596  *
1597  * Binds PHY with controller and powers up PHY enabling clocks
1598  * and regulators.
1599  *
1600  * Return: -EPROBE_DEFER if binding fails, returns negative error
1601  * on phy power up failure and returns zero on success.
1602  */
1603 static int ufs_qcom_init(struct ufs_hba *hba)
1604 {
1605 	int err;
1606 	struct device *dev = hba->dev;
1607 	struct ufs_qcom_host *host;
1608 	struct ufs_clk_info *clki;
1609 	const struct ufs_qcom_drvdata *drvdata = of_device_get_match_data(hba->dev);
1610 
1611 	host = devm_kzalloc(dev, sizeof(*host), GFP_KERNEL);
1612 	if (!host)
1613 		return -ENOMEM;
1614 
1615 	/* Make a two way bind between the qcom host and the hba */
1616 	host->hba = hba;
1617 	ufshcd_set_variant(hba, host);
1618 
1619 	/* Setup the optional reset control of HCI */
1620 	host->core_reset = devm_reset_control_get_optional(hba->dev, "rst");
1621 	if (IS_ERR(host->core_reset)) {
1622 		err = dev_err_probe(dev, PTR_ERR(host->core_reset),
1623 				    "Failed to get reset control\n");
1624 		goto out_variant_clear;
1625 	}
1626 
1627 	/* Fire up the reset controller. Failure here is non-fatal. */
1628 	host->rcdev.of_node = dev->of_node;
1629 	host->rcdev.ops = &ufs_qcom_reset_ops;
1630 	host->rcdev.owner = dev->driver->owner;
1631 	host->rcdev.nr_resets = 1;
1632 	err = devm_reset_controller_register(dev, &host->rcdev);
1633 	if (err)
1634 		dev_warn(dev, "Failed to register reset controller\n");
1635 
1636 	if (!has_acpi_companion(dev)) {
1637 		host->generic_phy = devm_phy_get(dev, "ufsphy");
1638 		if (IS_ERR(host->generic_phy)) {
1639 			err = dev_err_probe(dev, PTR_ERR(host->generic_phy), "Failed to get PHY\n");
1640 			goto out_variant_clear;
1641 		}
1642 	}
1643 
1644 	err = ufs_qcom_icc_init(host);
1645 	if (err)
1646 		goto out_variant_clear;
1647 
1648 	host->device_reset = devm_gpiod_get_optional(dev, "reset",
1649 						     GPIOD_OUT_HIGH);
1650 	if (IS_ERR(host->device_reset)) {
1651 		err = dev_err_probe(dev, PTR_ERR(host->device_reset),
1652 				    "Failed to acquire device reset gpio\n");
1653 		goto out_variant_clear;
1654 	}
1655 
1656 	ufs_qcom_get_controller_revision(hba, &host->hw_ver.major,
1657 		&host->hw_ver.minor, &host->hw_ver.step);
1658 
1659 	host->dev_ref_clk_ctrl_mmio = hba->mmio_base + REG_UFS_CFG1;
1660 	host->dev_ref_clk_en_mask = BIT(26);
1661 
1662 	list_for_each_entry(clki, &hba->clk_list_head, list) {
1663 		if (!strcmp(clki->name, "core_clk_unipro"))
1664 			clki->keep_link_active = true;
1665 	}
1666 
1667 	err = ufs_qcom_init_lane_clks(host);
1668 	if (err)
1669 		goto out_variant_clear;
1670 
1671 	ufs_qcom_set_caps(hba);
1672 	ufs_qcom_advertise_quirks(hba);
1673 	ufs_qcom_set_host_params(hba);
1674 	ufs_qcom_set_phy_gear(host);
1675 	ufs_qcom_parse_gear_limits(hba);
1676 
1677 	err = ufs_qcom_ice_init(host);
1678 	if (err)
1679 		goto out_variant_clear;
1680 
1681 	ufs_qcom_setup_clocks(hba, true, POST_CHANGE);
1682 
1683 	ufs_qcom_get_default_testbus_cfg(host);
1684 	err = ufs_qcom_testbus_config(host);
1685 	if (err)
1686 		/* Failure is non-fatal */
1687 		dev_warn(dev, "%s: failed to configure the testbus %d\n",
1688 				__func__, err);
1689 
1690 	if (drvdata && drvdata->no_phy_retention)
1691 		hba->spm_lvl = UFS_PM_LVL_5;
1692 
1693 	return 0;
1694 
1695 out_variant_clear:
1696 	ufshcd_set_variant(hba, NULL);
1697 
1698 	return err;
1699 }
1700 
1701 static void ufs_qcom_exit(struct ufs_hba *hba)
1702 {
1703 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
1704 
1705 	ufs_qcom_disable_lane_clks(host);
1706 	phy_power_off(host->generic_phy);
1707 	phy_exit(host->generic_phy);
1708 }
1709 
1710 static int ufs_qcom_fw_managed_init(struct ufs_hba *hba)
1711 {
1712 	struct device *dev = hba->dev;
1713 	struct ufs_qcom_host *host;
1714 	int err;
1715 
1716 	host = devm_kzalloc(dev, sizeof(*host), GFP_KERNEL);
1717 	if (!host)
1718 		return -ENOMEM;
1719 
1720 	host->hba = hba;
1721 	ufshcd_set_variant(hba, host);
1722 
1723 	ufs_qcom_get_controller_revision(hba, &host->hw_ver.major,
1724 					 &host->hw_ver.minor, &host->hw_ver.step);
1725 
1726 	err = ufs_qcom_ice_init(host);
1727 	if (err)
1728 		goto out_variant_clear;
1729 
1730 	ufs_qcom_get_default_testbus_cfg(host);
1731 	err = ufs_qcom_testbus_config(host);
1732 	if (err)
1733 		/* Failure is non-fatal */
1734 		dev_warn(dev, "Failed to configure the testbus %d\n", err);
1735 
1736 	hba->caps |= UFSHCD_CAP_WB_EN;
1737 
1738 	ufs_qcom_advertise_quirks(hba);
1739 	host->hba->quirks &= ~UFSHCD_QUIRK_REINIT_AFTER_MAX_GEAR_SWITCH;
1740 
1741 	hba->spm_lvl = hba->rpm_lvl = hba->pm_lvl_min = UFS_PM_LVL_5;
1742 
1743 	ufs_qcom_set_host_params(hba);
1744 	ufs_qcom_parse_gear_limits(hba);
1745 
1746 	return 0;
1747 
1748 out_variant_clear:
1749 	ufshcd_set_variant(hba, NULL);
1750 	return err;
1751 }
1752 
1753 static void ufs_qcom_fw_managed_exit(struct ufs_hba *hba)
1754 {
1755 	pm_runtime_put_sync(hba->dev);
1756 }
1757 
1758 /**
1759  * ufs_qcom_set_clk_40ns_cycles - Configure 40ns clk cycles
1760  *
1761  * @hba: host controller instance
1762  * @cycles_in_1us: No of cycles in 1us to be configured
1763  *
1764  * Returns error if dme get/set configuration for 40ns fails
1765  * and returns zero on success.
1766  */
1767 static int ufs_qcom_set_clk_40ns_cycles(struct ufs_hba *hba,
1768 					u32 cycles_in_1us)
1769 {
1770 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
1771 	u32 cycles_in_40ns;
1772 	u32 reg;
1773 	int err;
1774 
1775 	/*
1776 	 * UFS host controller V4.0.0 onwards needs to program
1777 	 * PA_VS_CORE_CLK_40NS_CYCLES attribute per programmed
1778 	 * frequency of unipro core clk of UFS host controller.
1779 	 */
1780 	if (host->hw_ver.major < 4)
1781 		return 0;
1782 
1783 	/*
1784 	 * Generic formulae for cycles_in_40ns = (freq_unipro/25) is not
1785 	 * applicable for all frequencies. For ex: ceil(37.5 MHz/25) will
1786 	 * be 2 and ceil(403 MHZ/25) will be 17 whereas Hardware
1787 	 * specification expect to be 16. Hence use exact hardware spec
1788 	 * mandated value for cycles_in_40ns instead of calculating using
1789 	 * generic formulae.
1790 	 */
1791 	switch (cycles_in_1us) {
1792 	case UNIPRO_CORE_CLK_FREQ_403_MHZ:
1793 		cycles_in_40ns = 16;
1794 		break;
1795 	case UNIPRO_CORE_CLK_FREQ_300_MHZ:
1796 		cycles_in_40ns = 12;
1797 		break;
1798 	case UNIPRO_CORE_CLK_FREQ_201_5_MHZ:
1799 		cycles_in_40ns = 8;
1800 		break;
1801 	case UNIPRO_CORE_CLK_FREQ_150_MHZ:
1802 		cycles_in_40ns = 6;
1803 		break;
1804 	case UNIPRO_CORE_CLK_FREQ_100_MHZ:
1805 		cycles_in_40ns = 4;
1806 		break;
1807 	case  UNIPRO_CORE_CLK_FREQ_75_MHZ:
1808 		cycles_in_40ns = 3;
1809 		break;
1810 	case UNIPRO_CORE_CLK_FREQ_37_5_MHZ:
1811 		cycles_in_40ns = 2;
1812 		break;
1813 	default:
1814 		dev_err(hba->dev, "UNIPRO clk freq %u MHz not supported\n",
1815 				cycles_in_1us);
1816 		return -EINVAL;
1817 	}
1818 
1819 	err = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_VS_CORE_CLK_40NS_CYCLES), &reg);
1820 	if (err)
1821 		return err;
1822 
1823 	reg &= ~PA_VS_CORE_CLK_40NS_CYCLES_MASK;
1824 	reg |= cycles_in_40ns;
1825 
1826 	return ufshcd_dme_set(hba, UIC_ARG_MIB(PA_VS_CORE_CLK_40NS_CYCLES), reg);
1827 }
1828 
1829 static int ufs_qcom_set_core_clk_ctrl(struct ufs_hba *hba, bool is_scale_up, unsigned long freq)
1830 {
1831 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
1832 	struct list_head *head = &hba->clk_list_head;
1833 	struct ufs_clk_info *clki;
1834 	u32 cycles_in_1us = 0;
1835 	u32 core_clk_ctrl_reg;
1836 	unsigned long clk_freq;
1837 	int err;
1838 
1839 	if (hba->use_pm_opp && freq != ULONG_MAX) {
1840 		clk_freq = ufs_qcom_opp_freq_to_clk_freq(hba, freq, "core_clk_unipro");
1841 		if (clk_freq) {
1842 			cycles_in_1us = ceil(clk_freq, HZ_PER_MHZ);
1843 			goto set_core_clk_ctrl;
1844 		}
1845 	}
1846 
1847 	list_for_each_entry(clki, head, list) {
1848 		if (!IS_ERR_OR_NULL(clki->clk) &&
1849 		    !strcmp(clki->name, "core_clk_unipro")) {
1850 			if (!clki->max_freq) {
1851 				cycles_in_1us = 150; /* default for backwards compatibility */
1852 				break;
1853 			}
1854 
1855 			if (freq == ULONG_MAX) {
1856 				cycles_in_1us = ceil(clki->max_freq, HZ_PER_MHZ);
1857 				break;
1858 			}
1859 
1860 			if (is_scale_up)
1861 				cycles_in_1us = ceil(clki->max_freq, HZ_PER_MHZ);
1862 			else
1863 				cycles_in_1us = ceil(clk_get_rate(clki->clk), HZ_PER_MHZ);
1864 			break;
1865 		}
1866 	}
1867 
1868 set_core_clk_ctrl:
1869 	err = ufshcd_dme_get(hba,
1870 			    UIC_ARG_MIB(DME_VS_CORE_CLK_CTRL),
1871 			    &core_clk_ctrl_reg);
1872 	if (err)
1873 		return err;
1874 
1875 	/* Bit mask is different for UFS host controller V4.0.0 onwards */
1876 	if (host->hw_ver.major >= 4) {
1877 		if (!FIELD_FIT(CLK_1US_CYCLES_MASK_V4, cycles_in_1us))
1878 			return -ERANGE;
1879 		core_clk_ctrl_reg &= ~CLK_1US_CYCLES_MASK_V4;
1880 		core_clk_ctrl_reg |= FIELD_PREP(CLK_1US_CYCLES_MASK_V4, cycles_in_1us);
1881 	} else {
1882 		if (!FIELD_FIT(CLK_1US_CYCLES_MASK, cycles_in_1us))
1883 			return -ERANGE;
1884 		core_clk_ctrl_reg &= ~CLK_1US_CYCLES_MASK;
1885 		core_clk_ctrl_reg |= FIELD_PREP(CLK_1US_CYCLES_MASK, cycles_in_1us);
1886 	}
1887 
1888 	/* Clear CORE_CLK_DIV_EN */
1889 	core_clk_ctrl_reg &= ~DME_VS_CORE_CLK_CTRL_CORE_CLK_DIV_EN_BIT;
1890 
1891 	err = ufshcd_dme_set(hba,
1892 			    UIC_ARG_MIB(DME_VS_CORE_CLK_CTRL),
1893 			    core_clk_ctrl_reg);
1894 	if (err)
1895 		return err;
1896 
1897 	/* Configure unipro core clk 40ns attribute */
1898 	return ufs_qcom_set_clk_40ns_cycles(hba, cycles_in_1us);
1899 }
1900 
1901 static int ufs_qcom_clk_scale_up_pre_change(struct ufs_hba *hba, unsigned long freq)
1902 {
1903 	int ret;
1904 
1905 	ret = ufs_qcom_cfg_timers(hba, true, freq);
1906 	if (ret) {
1907 		dev_err(hba->dev, "%s ufs cfg timer failed\n", __func__);
1908 		return ret;
1909 	}
1910 	/* set unipro core clock attributes and clear clock divider */
1911 	return ufs_qcom_set_core_clk_ctrl(hba, true, freq);
1912 }
1913 
1914 static int ufs_qcom_clk_scale_up_post_change(struct ufs_hba *hba)
1915 {
1916 	return 0;
1917 }
1918 
1919 static int ufs_qcom_clk_scale_down_pre_change(struct ufs_hba *hba)
1920 {
1921 	int err;
1922 	u32 core_clk_ctrl_reg;
1923 
1924 	err = ufshcd_dme_get(hba,
1925 			    UIC_ARG_MIB(DME_VS_CORE_CLK_CTRL),
1926 			    &core_clk_ctrl_reg);
1927 
1928 	/* make sure CORE_CLK_DIV_EN is cleared */
1929 	if (!err &&
1930 	    (core_clk_ctrl_reg & DME_VS_CORE_CLK_CTRL_CORE_CLK_DIV_EN_BIT)) {
1931 		core_clk_ctrl_reg &= ~DME_VS_CORE_CLK_CTRL_CORE_CLK_DIV_EN_BIT;
1932 		err = ufshcd_dme_set(hba,
1933 				    UIC_ARG_MIB(DME_VS_CORE_CLK_CTRL),
1934 				    core_clk_ctrl_reg);
1935 	}
1936 
1937 	return err;
1938 }
1939 
1940 static int ufs_qcom_clk_scale_down_post_change(struct ufs_hba *hba, unsigned long freq)
1941 {
1942 	int ret;
1943 
1944 	ret = ufs_qcom_cfg_timers(hba, false, freq);
1945 	if (ret) {
1946 		dev_err(hba->dev, "%s: ufs_qcom_cfg_timers() failed\n",	__func__);
1947 		return ret;
1948 	}
1949 	/* set unipro core clock attributes and clear clock divider */
1950 	return ufs_qcom_set_core_clk_ctrl(hba, false, freq);
1951 }
1952 
1953 static int ufs_qcom_clk_scale_notify(struct ufs_hba *hba, bool scale_up,
1954 				     unsigned long target_freq,
1955 				     enum ufs_notify_change_status status)
1956 {
1957 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
1958 	int err;
1959 
1960 	/* check the host controller state before sending hibern8 cmd */
1961 	if (!ufshcd_is_hba_active(hba))
1962 		return 0;
1963 
1964 	if (status == PRE_CHANGE) {
1965 		err = ufshcd_uic_hibern8_enter(hba);
1966 		if (err)
1967 			return err;
1968 		if (scale_up)
1969 			err = ufs_qcom_clk_scale_up_pre_change(hba, target_freq);
1970 		else
1971 			err = ufs_qcom_clk_scale_down_pre_change(hba);
1972 
1973 		if (err) {
1974 			ufshcd_uic_hibern8_exit(hba);
1975 			return err;
1976 		}
1977 	} else {
1978 		if (scale_up)
1979 			err = ufs_qcom_clk_scale_up_post_change(hba);
1980 		else
1981 			err = ufs_qcom_clk_scale_down_post_change(hba, target_freq);
1982 
1983 
1984 		if (err) {
1985 			ufshcd_uic_hibern8_exit(hba);
1986 			return err;
1987 		}
1988 
1989 		ufs_qcom_icc_update_bw(host);
1990 		ufshcd_uic_hibern8_exit(hba);
1991 	}
1992 
1993 	return 0;
1994 }
1995 
1996 static void ufs_qcom_enable_test_bus(struct ufs_qcom_host *host)
1997 {
1998 	ufshcd_rmwl(host->hba, UFS_REG_TEST_BUS_EN,
1999 			UFS_REG_TEST_BUS_EN, REG_UFS_CFG1);
2000 	ufshcd_rmwl(host->hba, TEST_BUS_EN, TEST_BUS_EN, REG_UFS_CFG1);
2001 }
2002 
2003 static void ufs_qcom_get_default_testbus_cfg(struct ufs_qcom_host *host)
2004 {
2005 	/* provide a legal default configuration */
2006 	host->testbus.select_major = TSTBUS_UNIPRO;
2007 	host->testbus.select_minor = 37;
2008 }
2009 
2010 static bool ufs_qcom_testbus_cfg_is_ok(struct ufs_qcom_host *host)
2011 {
2012 	if (host->testbus.select_major >= TSTBUS_MAX) {
2013 		dev_err(host->hba->dev,
2014 			"%s: UFS_CFG1[TEST_BUS_SEL} may not equal 0x%05X\n",
2015 			__func__, host->testbus.select_major);
2016 		return false;
2017 	}
2018 
2019 	return true;
2020 }
2021 
2022 int ufs_qcom_testbus_config(struct ufs_qcom_host *host)
2023 {
2024 	int reg;
2025 	int offset;
2026 	u32 mask = TEST_BUS_SUB_SEL_MASK;
2027 
2028 	if (!host)
2029 		return -EINVAL;
2030 
2031 	if (!ufs_qcom_testbus_cfg_is_ok(host))
2032 		return -EPERM;
2033 
2034 	switch (host->testbus.select_major) {
2035 	case TSTBUS_UAWM:
2036 		reg = UFS_TEST_BUS_CTRL_0;
2037 		offset = 24;
2038 		break;
2039 	case TSTBUS_UARM:
2040 		reg = UFS_TEST_BUS_CTRL_0;
2041 		offset = 16;
2042 		break;
2043 	case TSTBUS_TXUC:
2044 		reg = UFS_TEST_BUS_CTRL_0;
2045 		offset = 8;
2046 		break;
2047 	case TSTBUS_RXUC:
2048 		reg = UFS_TEST_BUS_CTRL_0;
2049 		offset = 0;
2050 		break;
2051 	case TSTBUS_DFC:
2052 		reg = UFS_TEST_BUS_CTRL_1;
2053 		offset = 24;
2054 		break;
2055 	case TSTBUS_TRLUT:
2056 		reg = UFS_TEST_BUS_CTRL_1;
2057 		offset = 16;
2058 		break;
2059 	case TSTBUS_TMRLUT:
2060 		reg = UFS_TEST_BUS_CTRL_1;
2061 		offset = 8;
2062 		break;
2063 	case TSTBUS_OCSC:
2064 		reg = UFS_TEST_BUS_CTRL_1;
2065 		offset = 0;
2066 		break;
2067 	case TSTBUS_WRAPPER:
2068 		reg = UFS_TEST_BUS_CTRL_2;
2069 		offset = 16;
2070 		break;
2071 	case TSTBUS_COMBINED:
2072 		reg = UFS_TEST_BUS_CTRL_2;
2073 		offset = 8;
2074 		break;
2075 	case TSTBUS_UTP_HCI:
2076 		reg = UFS_TEST_BUS_CTRL_2;
2077 		offset = 0;
2078 		break;
2079 	case TSTBUS_UNIPRO:
2080 		reg = UFS_UNIPRO_CFG;
2081 		offset = 20;
2082 		mask = 0xFFF;
2083 		break;
2084 	/*
2085 	 * No need for a default case, since
2086 	 * ufs_qcom_testbus_cfg_is_ok() checks that the configuration
2087 	 * is legal
2088 	 */
2089 	}
2090 	mask <<= offset;
2091 	ufshcd_rmwl(host->hba, TEST_BUS_SEL,
2092 		    (u32)host->testbus.select_major << 19,
2093 		    REG_UFS_CFG1);
2094 	ufshcd_rmwl(host->hba, mask,
2095 		    (u32)host->testbus.select_minor << offset,
2096 		    reg);
2097 	ufs_qcom_enable_test_bus(host);
2098 
2099 	return 0;
2100 }
2101 
2102 static void ufs_qcom_dump_testbus(struct ufs_hba *hba)
2103 {
2104 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
2105 	int i, j, nminor = 0, testbus_len = 0;
2106 	char *prefix;
2107 
2108 	u32 *testbus __free(kfree) = kmalloc_array(256, sizeof(u32), GFP_KERNEL);
2109 	if (!testbus)
2110 		return;
2111 
2112 	for (j = 0; j < TSTBUS_MAX; j++) {
2113 		nminor = testbus_info[j].nminor;
2114 		prefix = testbus_info[j].prefix;
2115 		host->testbus.select_major = j;
2116 		testbus_len = nminor * sizeof(u32);
2117 		for (i = 0; i < nminor; i++) {
2118 			host->testbus.select_minor = i;
2119 			ufs_qcom_testbus_config(host);
2120 			testbus[i] = ufshcd_readl(hba, UFS_TEST_BUS);
2121 		}
2122 		print_hex_dump(KERN_ERR, prefix, DUMP_PREFIX_OFFSET,
2123 			       16, 4, testbus, testbus_len, false);
2124 	}
2125 }
2126 
2127 static int ufs_qcom_dump_regs(struct ufs_hba *hba, size_t offset, size_t len,
2128 			      const char *prefix, void __iomem *base)
2129 {
2130 	size_t pos;
2131 
2132 	if (offset % 4 != 0 || len % 4 != 0)
2133 		return -EINVAL;
2134 
2135 	u32 *regs __free(kfree) = kzalloc(len, GFP_ATOMIC);
2136 	if (!regs)
2137 		return -ENOMEM;
2138 
2139 	for (pos = 0; pos < len; pos += 4)
2140 		regs[pos / 4] = readl(base + offset + pos);
2141 
2142 	print_hex_dump(KERN_ERR, prefix,
2143 		       len > 4 ? DUMP_PREFIX_OFFSET : DUMP_PREFIX_NONE,
2144 		       16, 4, regs, len, false);
2145 
2146 	return 0;
2147 }
2148 
2149 static void ufs_qcom_dump_mcq_hci_regs(struct ufs_hba *hba)
2150 {
2151 	struct ufshcd_mcq_opr_info_t *opr = &hba->mcq_opr[0];
2152 	void __iomem *mcq_vs_base = hba->mcq_base + UFS_MEM_VS_BASE;
2153 
2154 	struct dump_info {
2155 		void __iomem *base;
2156 		size_t offset;
2157 		size_t len;
2158 		const char *prefix;
2159 	};
2160 
2161 	struct dump_info mcq_dumps[] = {
2162 		{hba->mcq_base, 0x0, 256 * 4, "MCQ HCI-0 "},
2163 		{hba->mcq_base, 0x400, 256 * 4, "MCQ HCI-1 "},
2164 		{mcq_vs_base, 0x0, 5 * 4, "MCQ VS-0 "},
2165 		{opr->base, 0x0, 256 * 4, "MCQ SQD-0 "},
2166 		{opr->base, 0x400, 256 * 4, "MCQ SQD-1 "},
2167 		{opr->base, 0x800, 256 * 4, "MCQ SQD-2 "},
2168 		{opr->base, 0xc00, 256 * 4, "MCQ SQD-3 "},
2169 		{opr->base, 0x1000, 256 * 4, "MCQ SQD-4 "},
2170 		{opr->base, 0x1400, 256 * 4, "MCQ SQD-5 "},
2171 		{opr->base, 0x1800, 256 * 4, "MCQ SQD-6 "},
2172 		{opr->base, 0x1c00, 256 * 4, "MCQ SQD-7 "},
2173 
2174 	};
2175 
2176 	for (int i = 0; i < ARRAY_SIZE(mcq_dumps); i++) {
2177 		ufs_qcom_dump_regs(hba, mcq_dumps[i].offset, mcq_dumps[i].len,
2178 				   mcq_dumps[i].prefix, mcq_dumps[i].base);
2179 		cond_resched();
2180 	}
2181 }
2182 
2183 static void ufs_qcom_dump_dbg_regs(struct ufs_hba *hba)
2184 {
2185 	u32 reg;
2186 	struct ufs_qcom_host *host;
2187 
2188 	host = ufshcd_get_variant(hba);
2189 
2190 	dev_err(hba->dev, "HW_H8_ENTER_CNT=%d\n", ufshcd_readl(hba, REG_UFS_HW_H8_ENTER_CNT));
2191 	dev_err(hba->dev, "HW_H8_EXIT_CNT=%d\n", ufshcd_readl(hba, REG_UFS_HW_H8_EXIT_CNT));
2192 
2193 	dev_err(hba->dev, "SW_H8_ENTER_CNT=%d\n", ufshcd_readl(hba, REG_UFS_SW_H8_ENTER_CNT));
2194 	dev_err(hba->dev, "SW_H8_EXIT_CNT=%d\n", ufshcd_readl(hba, REG_UFS_SW_H8_EXIT_CNT));
2195 
2196 	dev_err(hba->dev, "SW_AFTER_HW_H8_ENTER_CNT=%d\n",
2197 			ufshcd_readl(hba, REG_UFS_SW_AFTER_HW_H8_ENTER_CNT));
2198 
2199 	ufshcd_dump_regs(hba, REG_UFS_SYS1CLK_1US, 16 * 4,
2200 			 "HCI Vendor Specific Registers ");
2201 
2202 	reg = ufs_qcom_get_debug_reg_offset(host, UFS_UFS_DBG_RD_REG_OCSC);
2203 	ufshcd_dump_regs(hba, reg, 44 * 4, "UFS_UFS_DBG_RD_REG_OCSC ");
2204 
2205 	reg = ufshcd_readl(hba, REG_UFS_CFG1);
2206 	reg |= UTP_DBG_RAMS_EN;
2207 	ufshcd_writel(hba, reg, REG_UFS_CFG1);
2208 
2209 	reg = ufs_qcom_get_debug_reg_offset(host, UFS_UFS_DBG_RD_EDTL_RAM);
2210 	ufshcd_dump_regs(hba, reg, 32 * 4, "UFS_UFS_DBG_RD_EDTL_RAM ");
2211 
2212 	reg = ufs_qcom_get_debug_reg_offset(host, UFS_UFS_DBG_RD_DESC_RAM);
2213 	ufshcd_dump_regs(hba, reg, 128 * 4, "UFS_UFS_DBG_RD_DESC_RAM ");
2214 
2215 	reg = ufs_qcom_get_debug_reg_offset(host, UFS_UFS_DBG_RD_PRDT_RAM);
2216 	ufshcd_dump_regs(hba, reg, 64 * 4, "UFS_UFS_DBG_RD_PRDT_RAM ");
2217 
2218 	/* clear bit 17 - UTP_DBG_RAMS_EN */
2219 	ufshcd_rmwl(hba, UTP_DBG_RAMS_EN, 0, REG_UFS_CFG1);
2220 
2221 	reg = ufs_qcom_get_debug_reg_offset(host, UFS_DBG_RD_REG_UAWM);
2222 	ufshcd_dump_regs(hba, reg, 4 * 4, "UFS_DBG_RD_REG_UAWM ");
2223 
2224 	reg = ufs_qcom_get_debug_reg_offset(host, UFS_DBG_RD_REG_UARM);
2225 	ufshcd_dump_regs(hba, reg, 4 * 4, "UFS_DBG_RD_REG_UARM ");
2226 
2227 	reg = ufs_qcom_get_debug_reg_offset(host, UFS_DBG_RD_REG_TXUC);
2228 	ufshcd_dump_regs(hba, reg, 48 * 4, "UFS_DBG_RD_REG_TXUC ");
2229 
2230 	reg = ufs_qcom_get_debug_reg_offset(host, UFS_DBG_RD_REG_RXUC);
2231 	ufshcd_dump_regs(hba, reg, 27 * 4, "UFS_DBG_RD_REG_RXUC ");
2232 
2233 	reg = ufs_qcom_get_debug_reg_offset(host, UFS_DBG_RD_REG_DFC);
2234 	ufshcd_dump_regs(hba, reg, 19 * 4, "UFS_DBG_RD_REG_DFC ");
2235 
2236 	reg = ufs_qcom_get_debug_reg_offset(host, UFS_DBG_RD_REG_TRLUT);
2237 	ufshcd_dump_regs(hba, reg, 34 * 4, "UFS_DBG_RD_REG_TRLUT ");
2238 
2239 	reg = ufs_qcom_get_debug_reg_offset(host, UFS_DBG_RD_REG_TMRLUT);
2240 	ufshcd_dump_regs(hba, reg, 9 * 4, "UFS_DBG_RD_REG_TMRLUT ");
2241 
2242 	if (hba->mcq_enabled) {
2243 		reg = ufs_qcom_get_debug_reg_offset(host, UFS_RD_REG_MCQ);
2244 		ufshcd_dump_regs(hba, reg, 64 * 4, "HCI MCQ Debug Registers ");
2245 	}
2246 
2247 	/* ensure below dumps occur only in task context due to blocking calls. */
2248 	if (in_task()) {
2249 		/* Dump MCQ Host Vendor Specific Registers */
2250 		if (hba->mcq_enabled)
2251 			ufs_qcom_dump_mcq_hci_regs(hba);
2252 
2253 		/* voluntarily yield the CPU as we are dumping too much data */
2254 		ufshcd_dump_regs(hba, UFS_TEST_BUS, 4, "UFS_TEST_BUS ");
2255 		cond_resched();
2256 		ufs_qcom_dump_testbus(hba);
2257 	}
2258 }
2259 
2260 /**
2261  * ufs_qcom_device_reset() - toggle the (optional) device reset line
2262  * @hba: per-adapter instance
2263  *
2264  * Toggles the (optional) reset line to reset the attached device.
2265  */
2266 static int ufs_qcom_device_reset(struct ufs_hba *hba)
2267 {
2268 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
2269 
2270 	/* reset gpio is optional */
2271 	if (!host->device_reset)
2272 		return -EOPNOTSUPP;
2273 
2274 	/*
2275 	 * The UFS device shall detect reset pulses of 1us, sleep for 10us to
2276 	 * be on the safe side.
2277 	 */
2278 	ufs_qcom_device_reset_ctrl(hba, true);
2279 	usleep_range(10, 15);
2280 
2281 	ufs_qcom_device_reset_ctrl(hba, false);
2282 	usleep_range(10, 15);
2283 
2284 	return 0;
2285 }
2286 
2287 /**
2288  * ufs_qcom_fw_managed_device_reset - Reset UFS device under FW-managed design
2289  * @hba: pointer to UFS host bus adapter
2290  *
2291  * In the firmware-managed reset model, the power domain is powered on by genpd
2292  * before the UFS controller driver probes. For subsequent resets (such as
2293  * suspend/resume or recovery), the UFS driver must explicitly invoke PM runtime
2294  *
2295  * Return: 0 on success or a negative error code on failure.
2296  */
2297 static int ufs_qcom_fw_managed_device_reset(struct ufs_hba *hba)
2298 {
2299 	static bool is_boot = true;
2300 	int err;
2301 
2302 	/* Skip reset on cold boot; perform it on subsequent calls */
2303 	if (is_boot) {
2304 		is_boot = false;
2305 		return 0;
2306 	}
2307 
2308 	pm_runtime_put_sync(hba->dev);
2309 	err = pm_runtime_resume_and_get(hba->dev);
2310 	if (err < 0) {
2311 		dev_err(hba->dev, "PM runtime resume failed: %d\n", err);
2312 		return err;
2313 	}
2314 
2315 	return 0;
2316 }
2317 
2318 static void ufs_qcom_config_scaling_param(struct ufs_hba *hba,
2319 					struct devfreq_dev_profile *p,
2320 					struct devfreq_simple_ondemand_data *d)
2321 {
2322 	p->polling_ms = 60;
2323 	p->timer = DEVFREQ_TIMER_DELAYED;
2324 	d->upthreshold = 70;
2325 	d->downdifferential = 65;
2326 
2327 	hba->clk_scaling.suspend_on_no_request = true;
2328 }
2329 
2330 static int ufs_qcom_mcq_config_resource(struct ufs_hba *hba)
2331 {
2332 	struct platform_device *pdev = to_platform_device(hba->dev);
2333 	struct resource *res;
2334 
2335 	/* Map the MCQ configuration region */
2336 	res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "mcq");
2337 	if (!res) {
2338 		dev_err(hba->dev, "MCQ resource not found in device tree\n");
2339 		return -ENODEV;
2340 	}
2341 
2342 	hba->mcq_base = devm_ioremap_resource(hba->dev, res);
2343 	if (IS_ERR(hba->mcq_base)) {
2344 		dev_err(hba->dev, "Failed to map MCQ region: %ld\n",
2345 			PTR_ERR(hba->mcq_base));
2346 		return PTR_ERR(hba->mcq_base);
2347 	}
2348 
2349 	return 0;
2350 }
2351 
2352 static int ufs_qcom_op_runtime_config(struct ufs_hba *hba)
2353 {
2354 	struct ufshcd_mcq_opr_info_t *opr;
2355 	int i;
2356 	u32 doorbell_offsets[OPR_MAX];
2357 
2358 	/*
2359 	 * Configure doorbell address offsets in MCQ configuration registers.
2360 	 * These values are offsets relative to mmio_base (UFS_HCI_BASE).
2361 	 *
2362 	 * Memory Layout:
2363 	 * - mmio_base = UFS_HCI_BASE
2364 	 * - mcq_base  = MCQ_CONFIG_BASE = mmio_base + (UFS_QCOM_MCQCAP_QCFGPTR * 0x200)
2365 	 * - Doorbell registers are at: mmio_base + (UFS_QCOM_MCQCAP_QCFGPTR * 0x200) +
2366 	 * -				UFS_QCOM_MCQ_SQD_OFFSET
2367 	 * - Which is also: mcq_base +  UFS_QCOM_MCQ_SQD_OFFSET
2368 	 */
2369 
2370 	doorbell_offsets[OPR_SQD] = UFS_QCOM_SQD_ADDR_OFFSET;
2371 	doorbell_offsets[OPR_SQIS] = UFS_QCOM_SQIS_ADDR_OFFSET;
2372 	doorbell_offsets[OPR_CQD] = UFS_QCOM_CQD_ADDR_OFFSET;
2373 	doorbell_offsets[OPR_CQIS] = UFS_QCOM_CQIS_ADDR_OFFSET;
2374 
2375 	/*
2376 	 * Configure MCQ operation registers.
2377 	 *
2378 	 * The doorbell registers are physically located within the MCQ region:
2379 	 * - doorbell_physical_addr = mmio_base + doorbell_offset
2380 	 * - doorbell_physical_addr = mcq_base + (doorbell_offset - MCQ_CONFIG_OFFSET)
2381 	 */
2382 	for (i = 0; i < OPR_MAX; i++) {
2383 		opr = &hba->mcq_opr[i];
2384 		opr->offset = doorbell_offsets[i];  /* Offset relative to mmio_base */
2385 		opr->stride = UFS_QCOM_MCQ_STRIDE;  /* 256 bytes between queues */
2386 
2387 		/*
2388 		 * Calculate the actual doorbell base address within MCQ region:
2389 		 * base = mcq_base + (doorbell_offset - MCQ_CONFIG_OFFSET)
2390 		 */
2391 		opr->base = hba->mcq_base + (opr->offset - UFS_QCOM_MCQ_CONFIG_OFFSET);
2392 	}
2393 
2394 	return 0;
2395 }
2396 
2397 static int ufs_qcom_get_hba_mac(struct ufs_hba *hba)
2398 {
2399 	/* Qualcomm HC supports up to 64 */
2400 	return MAX_SUPP_MAC;
2401 }
2402 
2403 static int ufs_qcom_get_outstanding_cqs(struct ufs_hba *hba,
2404 					unsigned long *ocqs)
2405 {
2406 	/* Read from MCQ vendor-specific register in MCQ region */
2407 	*ocqs = readl(hba->mcq_base + UFS_MEM_CQIS_VS);
2408 
2409 	return 0;
2410 }
2411 
2412 static void ufs_qcom_write_msi_msg(struct msi_desc *desc, struct msi_msg *msg)
2413 {
2414 	struct device *dev = msi_desc_to_dev(desc);
2415 	struct ufs_hba *hba = dev_get_drvdata(dev);
2416 
2417 	ufshcd_mcq_config_esi(hba, msg);
2418 }
2419 
2420 struct ufs_qcom_irq {
2421 	unsigned int		irq;
2422 	unsigned int		idx;
2423 	struct ufs_hba		*hba;
2424 };
2425 
2426 static irqreturn_t ufs_qcom_mcq_esi_handler(int irq, void *data)
2427 {
2428 	struct ufs_qcom_irq *qi = data;
2429 	struct ufs_hba *hba = qi->hba;
2430 	struct ufs_hw_queue *hwq = &hba->uhq[qi->idx];
2431 
2432 	ufshcd_mcq_write_cqis(hba, 0x1, qi->idx);
2433 	ufshcd_mcq_poll_cqe_lock(hba, hwq);
2434 
2435 	return IRQ_HANDLED;
2436 }
2437 
2438 static int ufs_qcom_config_esi(struct ufs_hba *hba)
2439 {
2440 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
2441 	int nr_irqs, ret;
2442 
2443 	if (host->esi_enabled)
2444 		return 0;
2445 
2446 	/*
2447 	 * 1. We only handle CQs as of now.
2448 	 * 2. Poll queues do not need ESI.
2449 	 */
2450 	nr_irqs = hba->nr_hw_queues - hba->nr_queues[HCTX_TYPE_POLL];
2451 
2452 	ret = platform_device_msi_init_and_alloc_irqs(hba->dev, nr_irqs,
2453 						      ufs_qcom_write_msi_msg);
2454 	if (ret) {
2455 		dev_warn(hba->dev, "Platform MSI not supported or failed, continuing without ESI\n");
2456 		return ret; /* Continue without ESI */
2457 	}
2458 
2459 	struct ufs_qcom_irq *qi = devm_kcalloc(hba->dev, nr_irqs, sizeof(*qi), GFP_KERNEL);
2460 
2461 	if (!qi) {
2462 		platform_device_msi_free_irqs_all(hba->dev);
2463 		return -ENOMEM;
2464 	}
2465 
2466 	for (int idx = 0; idx < nr_irqs; idx++) {
2467 		qi[idx].irq = msi_get_virq(hba->dev, idx);
2468 		qi[idx].idx = idx;
2469 		qi[idx].hba = hba;
2470 
2471 		ret = devm_request_irq(hba->dev, qi[idx].irq, ufs_qcom_mcq_esi_handler,
2472 				       IRQF_SHARED, "qcom-mcq-esi", qi + idx);
2473 		if (ret) {
2474 			/* Free previously allocated IRQs */
2475 			for (int j = 0; j < idx; j++)
2476 				devm_free_irq(hba->dev, qi[j].irq, qi + j);
2477 			platform_device_msi_free_irqs_all(hba->dev);
2478 			devm_kfree(hba->dev, qi);
2479 			return ret;
2480 		}
2481 	}
2482 
2483 	if (host->hw_ver.major >= 6) {
2484 		ufshcd_rmwl(hba, ESI_VEC_MASK, FIELD_PREP(ESI_VEC_MASK, MAX_ESI_VEC - 1),
2485 			    REG_UFS_CFG3);
2486 	}
2487 	ufshcd_mcq_enable_esi(hba);
2488 	host->esi_enabled = true;
2489 	return 0;
2490 }
2491 
2492 static unsigned long ufs_qcom_opp_freq_to_clk_freq(struct ufs_hba *hba,
2493 						   unsigned long freq, char *name)
2494 {
2495 	struct ufs_clk_info *clki;
2496 	struct dev_pm_opp *opp;
2497 	unsigned long clk_freq;
2498 	int idx = 0;
2499 	bool found = false;
2500 
2501 	opp = dev_pm_opp_find_freq_exact_indexed(hba->dev, freq, 0, true);
2502 	if (IS_ERR(opp)) {
2503 		dev_err(hba->dev, "Failed to find OPP for exact frequency %lu\n", freq);
2504 		return 0;
2505 	}
2506 
2507 	list_for_each_entry(clki, &hba->clk_list_head, list) {
2508 		if (!strcmp(clki->name, name)) {
2509 			found = true;
2510 			break;
2511 		}
2512 
2513 		idx++;
2514 	}
2515 
2516 	if (!found) {
2517 		dev_err(hba->dev, "Failed to find clock '%s' in clk list\n", name);
2518 		dev_pm_opp_put(opp);
2519 		return 0;
2520 	}
2521 
2522 	clk_freq = dev_pm_opp_get_freq_indexed(opp, idx);
2523 
2524 	dev_pm_opp_put(opp);
2525 
2526 	return clk_freq;
2527 }
2528 
2529 static u32 ufs_qcom_freq_to_gear_speed(struct ufs_hba *hba, unsigned long freq)
2530 {
2531 	u32 gear = UFS_HS_DONT_CHANGE;
2532 	unsigned long unipro_freq;
2533 
2534 	if (!hba->use_pm_opp)
2535 		return gear;
2536 
2537 	unipro_freq = ufs_qcom_opp_freq_to_clk_freq(hba, freq, "core_clk_unipro");
2538 	switch (unipro_freq) {
2539 	case 403000000:
2540 		gear = UFS_HS_G5;
2541 		break;
2542 	case 300000000:
2543 		gear = UFS_HS_G4;
2544 		break;
2545 	case 201500000:
2546 		gear = UFS_HS_G3;
2547 		break;
2548 	case 150000000:
2549 	case 100000000:
2550 		gear = UFS_HS_G2;
2551 		break;
2552 	case 75000000:
2553 	case 37500000:
2554 		gear = UFS_HS_G1;
2555 		break;
2556 	default:
2557 		dev_err(hba->dev, "%s: Unsupported clock freq : %lu\n", __func__, freq);
2558 		return UFS_HS_DONT_CHANGE;
2559 	}
2560 
2561 	return min_t(u32, gear, hba->max_pwr_info.info.gear_rx);
2562 }
2563 
2564 static int ufs_qcom_host_eom_config(struct ufs_hba *hba, int lane,
2565 				    const struct ufs_eom_coord *eom_coord,
2566 				    u32 target_test_count)
2567 {
2568 	enum ufs_eom_eye_mask eye_mask = eom_coord->eye_mask;
2569 	int v_step = eom_coord->v_step;
2570 	int t_step = eom_coord->t_step;
2571 	u32 volt_step, timing_step;
2572 	int ret;
2573 
2574 	if (abs(v_step) > UFS_QCOM_EOM_VOLTAGE_STEPS_MAX) {
2575 		dev_err(hba->dev, "Invalid EOM Voltage Step: %d\n", v_step);
2576 		return -ERANGE;
2577 	}
2578 
2579 	if (abs(t_step) > UFS_QCOM_EOM_TIMING_STEPS_MAX) {
2580 		dev_err(hba->dev, "Invalid EOM Timing Step: %d\n", t_step);
2581 		return -ERANGE;
2582 	}
2583 
2584 	if (v_step < 0)
2585 		volt_step = RX_EYEMON_NEGATIVE_STEP_BIT | (u32)(-v_step);
2586 	else
2587 		volt_step = (u32)v_step;
2588 
2589 	if (t_step < 0)
2590 		timing_step = RX_EYEMON_NEGATIVE_STEP_BIT | (u32)(-t_step);
2591 	else
2592 		timing_step = (u32)t_step;
2593 
2594 	ret = ufshcd_dme_set(hba, UIC_ARG_MIB_SEL(RX_EYEMON_ENABLE,
2595 				UIC_ARG_MPHY_RX_GEN_SEL_INDEX(lane)),
2596 			     BIT(eye_mask) | RX_EYEMON_EXTENDED_VRANGE_BIT);
2597 	if (ret) {
2598 		dev_err(hba->dev, "Failed to enable Host EOM on Lane %d: %d\n",
2599 			lane, ret);
2600 		return ret;
2601 	}
2602 
2603 	ret = ufshcd_dme_set(hba, UIC_ARG_MIB_SEL(RX_EYEMON_TIMING_STEPS,
2604 				UIC_ARG_MPHY_RX_GEN_SEL_INDEX(lane)),
2605 			     timing_step);
2606 	if (ret) {
2607 		dev_err(hba->dev, "Failed to set Host EOM timing step on Lane %d: %d\n",
2608 			lane, ret);
2609 		return ret;
2610 	}
2611 
2612 	ret = ufshcd_dme_set(hba, UIC_ARG_MIB_SEL(RX_EYEMON_VOLTAGE_STEPS,
2613 				UIC_ARG_MPHY_RX_GEN_SEL_INDEX(lane)),
2614 			     volt_step);
2615 	if (ret) {
2616 		dev_err(hba->dev, "Failed to set Host EOM voltage step on Lane %d: %d\n",
2617 			lane, ret);
2618 		return ret;
2619 	}
2620 
2621 	ret = ufshcd_dme_set(hba, UIC_ARG_MIB_SEL(RX_EYEMON_TARGET_TEST_COUNT,
2622 				UIC_ARG_MPHY_RX_GEN_SEL_INDEX(lane)),
2623 			     target_test_count);
2624 	if (ret)
2625 		dev_err(hba->dev, "Failed to set Host EOM target test count on Lane %d: %d\n",
2626 			lane, ret);
2627 
2628 	return ret;
2629 }
2630 
2631 static int ufs_qcom_host_eom_may_stop(struct ufs_hba *hba, int lane,
2632 				      u32 target_test_count, u32 *err_count)
2633 {
2634 	u32 start, tested_count, error_count;
2635 	int ret;
2636 
2637 	ret = ufshcd_dme_get(hba, UIC_ARG_MIB_SEL(RX_EYEMON_START,
2638 				UIC_ARG_MPHY_RX_GEN_SEL_INDEX(lane)),
2639 			     &start);
2640 	if (ret) {
2641 		dev_err(hba->dev, "Failed to get Host EOM start status on Lane %d: %d\n",
2642 			lane, ret);
2643 		return ret;
2644 	}
2645 
2646 	if (start & 0x1)
2647 		return -EAGAIN;
2648 
2649 	ret = ufshcd_dme_get(hba, UIC_ARG_MIB_SEL(RX_EYEMON_TESTED_COUNT,
2650 				UIC_ARG_MPHY_RX_GEN_SEL_INDEX(lane)),
2651 			     &tested_count);
2652 	if (ret) {
2653 		dev_err(hba->dev, "Failed to get Host EOM tested count on Lane %d: %d\n",
2654 			lane, ret);
2655 		return ret;
2656 	}
2657 
2658 	ret = ufshcd_dme_get(hba, UIC_ARG_MIB_SEL(RX_EYEMON_ERROR_COUNT,
2659 				UIC_ARG_MPHY_RX_GEN_SEL_INDEX(lane)),
2660 			     &error_count);
2661 	if (ret) {
2662 		dev_err(hba->dev, "Failed to get Host EOM error count on Lane %d: %d\n",
2663 			lane, ret);
2664 		return ret;
2665 	}
2666 
2667 	/* EOM can stop */
2668 	if ((tested_count >= target_test_count - 3) || error_count > 0) {
2669 		*err_count = error_count;
2670 
2671 		/* Disable EOM */
2672 		ret = ufshcd_dme_set(hba, UIC_ARG_MIB_SEL(RX_EYEMON_ENABLE,
2673 					UIC_ARG_MPHY_RX_GEN_SEL_INDEX(lane)),
2674 				     0x0);
2675 		if (ret) {
2676 			dev_err(hba->dev, "Failed to disable Host EOM on Lane %d: %d\n",
2677 				lane, ret);
2678 			return ret;
2679 		}
2680 	} else {
2681 		return -EAGAIN;
2682 	}
2683 
2684 	return 0;
2685 }
2686 
2687 static int ufs_qcom_host_eom_scan(struct ufs_hba *hba, int num_lanes,
2688 				  const struct ufs_eom_coord *eom_coord,
2689 				  u32 target_test_count, u32 *err_count)
2690 {
2691 	bool eom_stopped[PA_MAXDATALANES] = { 0 };
2692 	int lane, ret;
2693 	u32 setting;
2694 
2695 	if (!err_count || !eom_coord)
2696 		return -EINVAL;
2697 
2698 	if (target_test_count < UFS_QCOM_EOM_TARGET_TEST_COUNT_MIN) {
2699 		dev_err(hba->dev, "Target test count (%u) too small for Host EOM\n",
2700 			target_test_count);
2701 		return -ERANGE;
2702 	}
2703 
2704 	for (lane = 0; lane < num_lanes; lane++) {
2705 		ret = ufs_qcom_host_eom_config(hba, lane, eom_coord,
2706 					       target_test_count);
2707 		if (ret) {
2708 			dev_err(hba->dev, "Failed to config Host RX EOM: %d\n", ret);
2709 			return ret;
2710 		}
2711 	}
2712 
2713 	/*
2714 	 * Trigger a PACP_PWR_req to kick start EOM, but not to really change
2715 	 * the Power Mode.
2716 	 */
2717 	ret = ufshcd_uic_change_pwr_mode(hba, FAST_MODE << 4 | FAST_MODE);
2718 	if (ret) {
2719 		dev_err(hba->dev, "Failed to change power mode to kick start Host EOM: %d\n",
2720 			ret);
2721 		return ret;
2722 	}
2723 
2724 more_burst:
2725 	/* Create burst on Host RX Lane. */
2726 	ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_LOCALVERINFO), &setting);
2727 
2728 	for (lane = 0; lane < num_lanes; lane++) {
2729 		if (eom_stopped[lane])
2730 			continue;
2731 
2732 		ret = ufs_qcom_host_eom_may_stop(hba, lane, target_test_count,
2733 						 &err_count[lane]);
2734 		if (!ret) {
2735 			eom_stopped[lane] = true;
2736 		} else if (ret == -EAGAIN) {
2737 			/* Need more burst to excercise EOM */
2738 			goto more_burst;
2739 		} else {
2740 			dev_err(hba->dev, "Failed to stop Host EOM: %d\n", ret);
2741 			return ret;
2742 		}
2743 
2744 		dev_dbg(hba->dev, "Host RX Lane %d EOM, v_step %d, t_step %d, error count %u\n",
2745 			lane, eom_coord->v_step, eom_coord->t_step,
2746 			err_count[lane]);
2747 	}
2748 
2749 	return 0;
2750 }
2751 
2752 static int ufs_qcom_host_sw_rx_fom(struct ufs_hba *hba, int num_lanes, u32 *fom)
2753 {
2754 	const struct ufs_eom_coord *eom_coord = sw_rx_fom_eom_coords_g6;
2755 	u32 eom_err_count[PA_MAXDATALANES] = { 0 };
2756 	u32 curr_ahit;
2757 	int lane, i, ret;
2758 
2759 	if (!fom)
2760 		return -EINVAL;
2761 
2762 	/* Stop the auto hibernate idle timer */
2763 	curr_ahit = ufshcd_readl(hba, REG_AUTO_HIBERNATE_IDLE_TIMER);
2764 	if (curr_ahit)
2765 		ufshcd_writel(hba, 0, REG_AUTO_HIBERNATE_IDLE_TIMER);
2766 
2767 	ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXHSADAPTTYPE), PA_NO_ADAPT);
2768 	if (ret) {
2769 		dev_err(hba->dev, "Failed to select NO_ADAPT before starting Host EOM: %d\n", ret);
2770 		goto out;
2771 	}
2772 
2773 	for (i = 0; i < SW_RX_FOM_EOM_COORDS; i++, eom_coord++) {
2774 		ret = ufs_qcom_host_eom_scan(hba, num_lanes, eom_coord,
2775 					     UFS_QCOM_EOM_TARGET_TEST_COUNT_G6,
2776 					     eom_err_count);
2777 		if (ret) {
2778 			dev_err(hba->dev, "Failed to run Host EOM scan: %d\n", ret);
2779 			break;
2780 		}
2781 
2782 		for (lane = 0; lane < num_lanes; lane++) {
2783 			/* Bad coordinates have no weights */
2784 			if (eom_err_count[lane])
2785 				continue;
2786 			fom[lane] += SW_RX_FOM_EOM_COORDS_WEIGHT;
2787 		}
2788 	}
2789 
2790 out:
2791 	/* Restore the auto hibernate idle timer */
2792 	if (curr_ahit)
2793 		ufshcd_writel(hba, curr_ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
2794 
2795 	return ret;
2796 }
2797 
2798 static int ufs_qcom_get_rx_fom(struct ufs_hba *hba,
2799 			       struct ufs_pa_layer_attr *pwr_mode,
2800 			       struct tx_eqtr_iter *h_iter,
2801 			       struct tx_eqtr_iter *d_iter)
2802 {
2803 	struct ufshcd_tx_eq_params *params __free(kfree) =
2804 		kzalloc_obj(*params);
2805 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
2806 	struct ufs_pa_layer_attr old_pwr_info;
2807 	u32 fom[PA_MAXDATALANES] = { 0 };
2808 	u32 gear = pwr_mode->gear_tx;
2809 	u32 rate = pwr_mode->hs_rate;
2810 	int lane, ret;
2811 
2812 	if (host->hw_ver.major != 0x7 || host->hw_ver.minor > 0x1 ||
2813 	    gear <= UFS_HS_G5 || !d_iter || !d_iter->is_updated)
2814 		return 0;
2815 
2816 	if (gear < UFS_HS_G1 || gear > UFS_HS_GEAR_MAX)
2817 		return -ERANGE;
2818 
2819 	if (!params)
2820 		return -ENOMEM;
2821 
2822 	memcpy(&old_pwr_info, &hba->pwr_info, sizeof(struct ufs_pa_layer_attr));
2823 
2824 	memcpy(params, &hba->tx_eq_params[gear - 1], sizeof(struct ufshcd_tx_eq_params));
2825 	for (lane = 0; lane < pwr_mode->lane_rx; lane++) {
2826 		params->device[lane].preshoot = d_iter->preshoot;
2827 		params->device[lane].deemphasis = d_iter->deemphasis;
2828 	}
2829 
2830 	/* Use TX EQTR settings as Device's TX Equalization settings. */
2831 	ret = ufshcd_apply_tx_eq_settings(hba, params, gear);
2832 	if (ret) {
2833 		dev_err(hba->dev, "%s: Failed to apply TX EQ settings for HS-G%u: %d\n",
2834 			__func__, gear, ret);
2835 		goto link_recover_and_restore;
2836 	}
2837 
2838 	/* Force PMC to target HS Gear to use new TX Equalization settings. */
2839 	ret = ufshcd_change_power_mode(hba, pwr_mode, UFSHCD_PMC_POLICY_FORCE);
2840 	if (ret) {
2841 		dev_err(hba->dev, "%s: Failed to change power mode to HS-G%u, Rate-%s: %d\n",
2842 			__func__, gear, ufs_hs_rate_to_str(rate), ret);
2843 		goto link_recover_and_restore;
2844 	}
2845 
2846 	ret = ufs_qcom_host_sw_rx_fom(hba, pwr_mode->lane_rx, fom);
2847 	if (ret)
2848 		dev_err(hba->dev, "Failed to get SW FOM of TX (PreShoot: %u, DeEmphasis: %u): %d\n",
2849 			d_iter->preshoot, d_iter->deemphasis, ret);
2850 
2851 link_recover_and_restore:
2852 	/* Restore Device's TX Equalization settings. */
2853 	ret = ufshcd_apply_tx_eq_settings(hba, &hba->tx_eq_params[gear - 1], gear);
2854 	if (ret) {
2855 		dev_err(hba->dev, "%s: Failed to apply TX EQ settings for HS-G%u: %d\n",
2856 			__func__, gear, ret);
2857 		return ret;
2858 	}
2859 
2860 	/* Restore Power Mode. */
2861 	ret = ufshcd_change_power_mode(hba, &old_pwr_info, UFSHCD_PMC_POLICY_FORCE);
2862 	if (ret) {
2863 		dev_err(hba->dev, "%s: Failed to restore power mode to HS-G%u: %d\n",
2864 			__func__, old_pwr_info.gear_tx, ret);
2865 		return ret;
2866 	}
2867 
2868 	for (lane = 0; lane < pwr_mode->lane_rx; lane++)
2869 		d_iter->fom[lane] = fom[lane];
2870 
2871 	return 0;
2872 }
2873 
2874 static int ufs_qcom_apply_tx_eqtr_settings(struct ufs_hba *hba,
2875 					   struct ufs_pa_layer_attr *pwr_mode,
2876 					   struct tx_eqtr_iter *h_iter,
2877 					   struct tx_eqtr_iter *d_iter)
2878 {
2879 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
2880 	u32 setting = 0;
2881 	int lane;
2882 
2883 	if (host->hw_ver.major != 0x7 || host->hw_ver.minor > 0x1)
2884 		return 0;
2885 
2886 	for (lane = 0; lane < pwr_mode->lane_tx; lane++) {
2887 		setting |= TX_HS_PRESHOOT_BITS(lane, h_iter->preshoot);
2888 		setting |= TX_HS_DEEMPHASIS_BITS(lane, h_iter->deemphasis);
2889 	}
2890 
2891 	return ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXEQG1SETTING), setting);
2892 }
2893 
2894 static int ufs_qcom_tx_eqtr_notify(struct ufs_hba *hba,
2895 				   enum ufs_notify_change_status status,
2896 				   struct ufs_pa_layer_attr *pwr_mode)
2897 {
2898 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
2899 	struct ufs_pa_layer_attr pwr_mode_hs_g1 = {
2900 		.gear_rx = UFS_HS_G1,
2901 		.gear_tx = UFS_HS_G1,
2902 		.lane_rx = pwr_mode->lane_rx,
2903 		.lane_tx = pwr_mode->lane_tx,
2904 		.pwr_rx = FAST_MODE,
2905 		.pwr_tx = FAST_MODE,
2906 		.hs_rate = pwr_mode->hs_rate,
2907 	};
2908 	u32 gear = pwr_mode->gear_tx;
2909 	u32 rate = pwr_mode->hs_rate;
2910 	int ret;
2911 
2912 	if (host->hw_ver.major != 0x7 || host->hw_ver.minor > 0x1)
2913 		return 0;
2914 
2915 	if (status == PRE_CHANGE) {
2916 		ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TXEQG1SETTING),
2917 				     &host->saved_tx_eq_g1_setting);
2918 		if (ret)
2919 			return ret;
2920 
2921 		/* PMC to target HS Gear. */
2922 		ret = ufshcd_change_power_mode(hba, pwr_mode,
2923 					       UFSHCD_PMC_POLICY_DONT_FORCE);
2924 		if (ret)
2925 			dev_err(hba->dev, "%s: Failed to PMC to target HS-G%u, Rate-%s: %d\n",
2926 				__func__, gear, ufs_hs_rate_to_str(rate), ret);
2927 	} else {
2928 		ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXEQG1SETTING),
2929 				     host->saved_tx_eq_g1_setting);
2930 		if (ret)
2931 			return ret;
2932 
2933 		/* PMC back to HS-G1. */
2934 		ret = ufshcd_change_power_mode(hba, &pwr_mode_hs_g1,
2935 					       UFSHCD_PMC_POLICY_DONT_FORCE);
2936 		if (ret)
2937 			dev_err(hba->dev, "%s: Failed to PMC to HS-G1, Rate-%s: %d\n",
2938 				__func__, ufs_hs_rate_to_str(rate), ret);
2939 	}
2940 
2941 	return ret;
2942 }
2943 
2944 /*
2945  * struct ufs_hba_qcom_vops - UFS QCOM specific variant operations
2946  *
2947  * The variant operations configure the necessary controller and PHY
2948  * handshake during initialization.
2949  */
2950 static const struct ufs_hba_variant_ops ufs_hba_qcom_vops = {
2951 	.name                   = "qcom",
2952 	.init                   = ufs_qcom_init,
2953 	.exit                   = ufs_qcom_exit,
2954 	.get_ufs_hci_version	= ufs_qcom_get_ufs_hci_version,
2955 	.clk_scale_notify	= ufs_qcom_clk_scale_notify,
2956 	.setup_clocks           = ufs_qcom_setup_clocks,
2957 	.hce_enable_notify      = ufs_qcom_hce_enable_notify,
2958 	.link_startup_notify    = ufs_qcom_link_startup_notify,
2959 	.negotiate_pwr_mode	= ufs_qcom_negotiate_pwr_mode,
2960 	.pwr_change_notify	= ufs_qcom_pwr_change_notify,
2961 	.apply_dev_quirks	= ufs_qcom_apply_dev_quirks,
2962 	.fixup_dev_quirks       = ufs_qcom_fixup_dev_quirks,
2963 	.suspend		= ufs_qcom_suspend,
2964 	.resume			= ufs_qcom_resume,
2965 	.dbg_register_dump	= ufs_qcom_dump_dbg_regs,
2966 	.device_reset		= ufs_qcom_device_reset,
2967 	.config_scaling_param = ufs_qcom_config_scaling_param,
2968 	.mcq_config_resource	= ufs_qcom_mcq_config_resource,
2969 	.get_hba_mac		= ufs_qcom_get_hba_mac,
2970 	.op_runtime_config	= ufs_qcom_op_runtime_config,
2971 	.get_outstanding_cqs	= ufs_qcom_get_outstanding_cqs,
2972 	.config_esi		= ufs_qcom_config_esi,
2973 	.freq_to_gear_speed	= ufs_qcom_freq_to_gear_speed,
2974 	.get_rx_fom		= ufs_qcom_get_rx_fom,
2975 	.apply_tx_eqtr_settings	= ufs_qcom_apply_tx_eqtr_settings,
2976 	.tx_eqtr_notify		= ufs_qcom_tx_eqtr_notify,
2977 };
2978 
2979 static const struct ufs_hba_variant_ops ufs_hba_qcom_sa8255p_vops = {
2980 	.name                   = "qcom-sa8255p",
2981 	.init                   = ufs_qcom_fw_managed_init,
2982 	.exit                   = ufs_qcom_fw_managed_exit,
2983 	.hce_enable_notify      = ufs_qcom_fw_managed_hce_enable_notify,
2984 	.pwr_change_notify      = ufs_qcom_pwr_change_notify,
2985 	.apply_dev_quirks       = ufs_qcom_apply_dev_quirks,
2986 	.fixup_dev_quirks       = ufs_qcom_fixup_dev_quirks,
2987 	.suspend                = ufs_qcom_fw_managed_suspend,
2988 	.resume                 = ufs_qcom_fw_managed_resume,
2989 	.dbg_register_dump      = ufs_qcom_dump_dbg_regs,
2990 	.device_reset           = ufs_qcom_fw_managed_device_reset,
2991 	.mcq_config_resource	= ufs_qcom_mcq_config_resource,
2992 	.get_hba_mac		= ufs_qcom_get_hba_mac,
2993 	.op_runtime_config	= ufs_qcom_op_runtime_config,
2994 	.get_outstanding_cqs	= ufs_qcom_get_outstanding_cqs,
2995 	.config_esi		= ufs_qcom_config_esi,
2996 };
2997 
2998 /**
2999  * ufs_qcom_probe - probe routine of the driver
3000  * @pdev: pointer to Platform device handle
3001  *
3002  * Return: zero for success and non-zero for failure.
3003  */
3004 static int ufs_qcom_probe(struct platform_device *pdev)
3005 {
3006 	int err;
3007 	struct device *dev = &pdev->dev;
3008 	const struct ufs_hba_variant_ops *vops;
3009 	const struct ufs_qcom_drvdata *drvdata = device_get_match_data(dev);
3010 
3011 	if (drvdata && drvdata->vops)
3012 		vops = drvdata->vops;
3013 	else
3014 		vops = &ufs_hba_qcom_vops;
3015 
3016 	/* Perform generic probe */
3017 	err = ufshcd_pltfrm_init(pdev, vops);
3018 	if (err)
3019 		return dev_err_probe(dev, err, "ufshcd_pltfrm_init() failed\n");
3020 
3021 	return 0;
3022 }
3023 
3024 /**
3025  * ufs_qcom_remove - set driver_data of the device to NULL
3026  * @pdev: pointer to platform device handle
3027  *
3028  * Always returns 0
3029  */
3030 static void ufs_qcom_remove(struct platform_device *pdev)
3031 {
3032 	struct ufs_hba *hba =  platform_get_drvdata(pdev);
3033 	struct ufs_qcom_host *host = ufshcd_get_variant(hba);
3034 
3035 	ufshcd_pltfrm_remove(pdev);
3036 	if (host->esi_enabled)
3037 		platform_device_msi_free_irqs_all(hba->dev);
3038 }
3039 
3040 static const struct ufs_qcom_drvdata ufs_qcom_sm8550_drvdata = {
3041 	.quirks = UFSHCD_QUIRK_BROKEN_LSDBS_CAP,
3042 	.no_phy_retention = true,
3043 };
3044 
3045 static const struct ufs_qcom_drvdata ufs_qcom_sa8255p_drvdata = {
3046 	.vops = &ufs_hba_qcom_sa8255p_vops
3047 };
3048 
3049 static const struct of_device_id ufs_qcom_of_match[] __maybe_unused = {
3050 	{ .compatible = "qcom,ufshc" },
3051 	{ .compatible = "qcom,sm8550-ufshc", .data = &ufs_qcom_sm8550_drvdata },
3052 	{ .compatible = "qcom,sm8650-ufshc", .data = &ufs_qcom_sm8550_drvdata },
3053 	{ .compatible = "qcom,sa8255p-ufshc", .data = &ufs_qcom_sa8255p_drvdata },
3054 	{},
3055 };
3056 MODULE_DEVICE_TABLE(of, ufs_qcom_of_match);
3057 
3058 #ifdef CONFIG_ACPI
3059 static const struct acpi_device_id ufs_qcom_acpi_match[] = {
3060 	{ "QCOM24A5" },
3061 	{ },
3062 };
3063 MODULE_DEVICE_TABLE(acpi, ufs_qcom_acpi_match);
3064 #endif
3065 
3066 static const struct dev_pm_ops ufs_qcom_pm_ops = {
3067 	SET_RUNTIME_PM_OPS(ufshcd_runtime_suspend, ufshcd_runtime_resume, NULL)
3068 	.prepare	 = ufshcd_suspend_prepare,
3069 	.complete	 = ufshcd_resume_complete,
3070 #ifdef CONFIG_PM_SLEEP
3071 	.suspend         = ufshcd_system_suspend,
3072 	.resume          = ufshcd_system_resume,
3073 	.freeze          = ufshcd_system_freeze,
3074 	.restore         = ufshcd_system_restore,
3075 	.thaw            = ufshcd_system_thaw,
3076 #endif
3077 };
3078 
3079 static struct platform_driver ufs_qcom_pltform = {
3080 	.probe	= ufs_qcom_probe,
3081 	.remove = ufs_qcom_remove,
3082 	.driver	= {
3083 		.name	= "ufshcd-qcom",
3084 		.pm	= &ufs_qcom_pm_ops,
3085 		.of_match_table = of_match_ptr(ufs_qcom_of_match),
3086 		.acpi_match_table = ACPI_PTR(ufs_qcom_acpi_match),
3087 	},
3088 };
3089 module_platform_driver(ufs_qcom_pltform);
3090 
3091 MODULE_DESCRIPTION("Qualcomm UFS host controller driver");
3092 MODULE_LICENSE("GPL v2");
3093