xref: /linux/drivers/ufs/core/ufshcd.c (revision 7db28abbea0f7dc1ec4fdfdc149db5fbd9e4c994)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Universal Flash Storage Host controller driver Core
4  * Copyright (C) 2011-2013 Samsung India Software Operations
5  * Copyright (c) 2013-2016, The Linux Foundation. All rights reserved.
6  *
7  * Authors:
8  *	Santosh Yaraganavi <santosh.sy@samsung.com>
9  *	Vinayak Holikatti <h.vinayak@samsung.com>
10  */
11 
12 #include <linux/async.h>
13 #include <linux/devfreq.h>
14 #include <linux/nls.h>
15 #include <linux/of.h>
16 #include <linux/bitfield.h>
17 #include <linux/blk-pm.h>
18 #include <linux/blkdev.h>
19 #include <linux/clk.h>
20 #include <linux/delay.h>
21 #include <linux/hex.h>
22 #include <linux/interrupt.h>
23 #include <linux/module.h>
24 #include <linux/pm_opp.h>
25 #include <linux/regulator/consumer.h>
26 #include <linux/sched/clock.h>
27 #include <linux/sizes.h>
28 #include <linux/iopoll.h>
29 #include <scsi/scsi_cmnd.h>
30 #include <scsi/scsi_dbg.h>
31 #include <scsi/scsi_driver.h>
32 #include <scsi/scsi_eh.h>
33 #include <scsi/scsi_tcq.h>
34 #include "ufshcd-priv.h"
35 #include <ufs/ufs_quirks.h>
36 #include <ufs/unipro.h>
37 #include "ufs-sysfs.h"
38 #include "ufs-debugfs.h"
39 #include "ufs-fault-injection.h"
40 #include "ufs_bsg.h"
41 #include "ufshcd-crypto.h"
42 #include <linux/unaligned.h>
43 
44 #define CREATE_TRACE_POINTS
45 #include "ufs_trace.h"
46 
47 #define UFSHCD_ENABLE_INTRS	(UTP_TRANSFER_REQ_COMPL |\
48 				 UTP_TASK_REQ_COMPL |\
49 				 UFSHCD_ERROR_MASK)
50 
51 /* UIC command timeout, unit: ms */
52 enum {
53 	UIC_CMD_TIMEOUT_DEFAULT	= 500,
54 	UIC_CMD_TIMEOUT_MAX	= 5000,
55 };
56 /* NOP OUT retries waiting for NOP IN response */
57 #define NOP_OUT_RETRIES    10
58 /* Timeout after 50 msecs if NOP OUT hangs without response */
59 #define NOP_OUT_TIMEOUT    50 /* msecs */
60 
61 /* Query request retries */
62 #define QUERY_REQ_RETRIES 3
63 /* Query request timeout */
64 enum {
65 	QUERY_REQ_TIMEOUT_MIN     = 1,
66 	QUERY_REQ_TIMEOUT_DEFAULT = 1500,
67 	QUERY_REQ_TIMEOUT_MAX     = 30000
68 };
69 
70 /* Advanced RPMB request timeout */
71 #define ADVANCED_RPMB_REQ_TIMEOUT  3000 /* 3 seconds */
72 
73 /* Task management command timeout */
74 #define TM_CMD_TIMEOUT	100 /* msecs */
75 
76 /* maximum number of retries for a general UIC command  */
77 #define UFS_UIC_COMMAND_RETRIES 3
78 
79 /* maximum number of link-startup retries */
80 #define DME_LINKSTARTUP_RETRIES 3
81 
82 /* maximum number of reset retries before giving up */
83 #define MAX_HOST_RESET_RETRIES 5
84 
85 /* Maximum number of error handler retries before giving up */
86 #define MAX_ERR_HANDLER_RETRIES 5
87 
88 /* Expose the flag value from utp_upiu_query.value */
89 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
90 
91 /* Interrupt aggregation default timeout, unit: 40us */
92 #define INT_AGGR_DEF_TO	0x02
93 
94 /* default delay of autosuspend: 2000 ms */
95 #define RPM_AUTOSUSPEND_DELAY_MS 2000
96 
97 /* Default delay of RPM device flush delayed work */
98 #define RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS 5000
99 
100 /* Default value of wait time before gating device ref clock */
101 #define UFSHCD_REF_CLK_GATING_WAIT_US 0xFF /* microsecs */
102 
103 /* Polling time to wait for fDeviceInit */
104 #define FDEVICEINIT_COMPL_TIMEOUT 1500 /* millisecs */
105 
106 /* Default RTC update every 10 seconds */
107 #define UFS_RTC_UPDATE_INTERVAL_MS (10 * MSEC_PER_SEC)
108 
109 /* bMaxNumOfRTT is equal to two after device manufacturing */
110 #define DEFAULT_MAX_NUM_RTT 2
111 
112 /* UFSHC 4.0 compliant HC support this mode. */
113 static bool use_mcq_mode = true;
114 
115 static bool is_mcq_supported(struct ufs_hba *hba)
116 {
117 	return hba->mcq_sup && use_mcq_mode;
118 }
119 
120 module_param(use_mcq_mode, bool, 0644);
121 MODULE_PARM_DESC(use_mcq_mode, "Control MCQ mode for controllers starting from UFSHCI 4.0. 1 - enable MCQ, 0 - disable MCQ. MCQ is enabled by default");
122 
123 static unsigned int uic_cmd_timeout = UIC_CMD_TIMEOUT_DEFAULT;
124 
125 static int uic_cmd_timeout_set(const char *val, const struct kernel_param *kp)
126 {
127 	return param_set_uint_minmax(val, kp, UIC_CMD_TIMEOUT_DEFAULT,
128 				     UIC_CMD_TIMEOUT_MAX);
129 }
130 
131 static const struct kernel_param_ops uic_cmd_timeout_ops = {
132 	.set = uic_cmd_timeout_set,
133 	.get = param_get_uint,
134 };
135 
136 module_param_cb(uic_cmd_timeout, &uic_cmd_timeout_ops, &uic_cmd_timeout, 0644);
137 MODULE_PARM_DESC(uic_cmd_timeout,
138 		 "UFS UIC command timeout in milliseconds. Defaults to 500ms. Supported values range from 500ms to 5 seconds inclusively");
139 
140 static unsigned int dev_cmd_timeout = QUERY_REQ_TIMEOUT_DEFAULT;
141 
142 static int dev_cmd_timeout_set(const char *val, const struct kernel_param *kp)
143 {
144 	return param_set_uint_minmax(val, kp, QUERY_REQ_TIMEOUT_MIN,
145 				     QUERY_REQ_TIMEOUT_MAX);
146 }
147 
148 static const struct kernel_param_ops dev_cmd_timeout_ops = {
149 	.set = dev_cmd_timeout_set,
150 	.get = param_get_uint,
151 };
152 
153 module_param_cb(dev_cmd_timeout, &dev_cmd_timeout_ops, &dev_cmd_timeout, 0644);
154 MODULE_PARM_DESC(dev_cmd_timeout,
155 		 "UFS Device command timeout in milliseconds. Defaults to 1.5s. Supported values range from 1ms to 30 seconds inclusively");
156 
157 #define ufshcd_toggle_vreg(_dev, _vreg, _on)				\
158 	({                                                              \
159 		int _ret;                                               \
160 		if (_on)                                                \
161 			_ret = ufshcd_enable_vreg(_dev, _vreg);         \
162 		else                                                    \
163 			_ret = ufshcd_disable_vreg(_dev, _vreg);        \
164 		_ret;                                                   \
165 	})
166 
167 #define ufshcd_hex_dump(prefix_str, buf, len) do {                       \
168 	size_t __len = (len);                                            \
169 	print_hex_dump(KERN_ERR, prefix_str,                             \
170 		       __len > 4 ? DUMP_PREFIX_OFFSET : DUMP_PREFIX_NONE,\
171 		       16, 4, buf, __len, false);                        \
172 } while (0)
173 
174 int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len,
175 		     const char *prefix)
176 {
177 	u32 *regs;
178 	size_t pos;
179 
180 	if (offset % 4 != 0 || len % 4 != 0) /* keep readl happy */
181 		return -EINVAL;
182 
183 	regs = kzalloc(len, GFP_ATOMIC);
184 	if (!regs)
185 		return -ENOMEM;
186 
187 	for (pos = 0; pos < len; pos += 4) {
188 		if (offset == 0 &&
189 		    pos >= REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER &&
190 		    pos <= REG_UIC_ERROR_CODE_DME)
191 			continue;
192 		regs[pos / 4] = ufshcd_readl(hba, offset + pos);
193 	}
194 
195 	ufshcd_hex_dump(prefix, regs, len);
196 	kfree(regs);
197 
198 	return 0;
199 }
200 EXPORT_SYMBOL_GPL(ufshcd_dump_regs);
201 
202 enum {
203 	UFSHCD_MAX_CHANNEL	= 0,
204 	UFSHCD_MAX_ID		= 1,
205 };
206 
207 static const char *const ufshcd_state_name[] = {
208 	[UFSHCD_STATE_RESET]			= "reset",
209 	[UFSHCD_STATE_OPERATIONAL]		= "operational",
210 	[UFSHCD_STATE_ERROR]			= "error",
211 	[UFSHCD_STATE_EH_SCHEDULED_FATAL]	= "eh_fatal",
212 	[UFSHCD_STATE_EH_SCHEDULED_NON_FATAL]	= "eh_non_fatal",
213 };
214 
215 /* UFSHCD error handling flags */
216 enum {
217 	UFSHCD_EH_IN_PROGRESS = (1 << 0),
218 };
219 
220 /* UFSHCD UIC layer error flags */
221 enum {
222 	UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
223 	UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
224 	UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
225 	UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
226 	UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
227 	UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
228 	UFSHCD_UIC_PA_GENERIC_ERROR = (1 << 6), /* Generic PA error */
229 };
230 
231 #define ufshcd_set_eh_in_progress(h) \
232 	((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
233 #define ufshcd_eh_in_progress(h) \
234 	((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
235 #define ufshcd_clear_eh_in_progress(h) \
236 	((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
237 
238 const struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
239 	[UFS_PM_LVL_0] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
240 	[UFS_PM_LVL_1] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
241 	[UFS_PM_LVL_2] = {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
242 	[UFS_PM_LVL_3] = {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
243 	[UFS_PM_LVL_4] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
244 	[UFS_PM_LVL_5] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
245 	/*
246 	 * For DeepSleep, the link is first put in hibern8 and then off.
247 	 * Leaving the link in hibern8 is not supported.
248 	 */
249 	[UFS_PM_LVL_6] = {UFS_DEEPSLEEP_PWR_MODE, UIC_LINK_OFF_STATE},
250 };
251 
252 static inline enum ufs_dev_pwr_mode
253 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
254 {
255 	return ufs_pm_lvl_states[lvl].dev_state;
256 }
257 
258 static inline enum uic_link_state
259 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
260 {
261 	return ufs_pm_lvl_states[lvl].link_state;
262 }
263 
264 static inline enum ufs_pm_level
265 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
266 					enum uic_link_state link_state)
267 {
268 	enum ufs_pm_level lvl;
269 
270 	for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
271 		if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
272 			(ufs_pm_lvl_states[lvl].link_state == link_state))
273 			return lvl;
274 	}
275 
276 	/* if no match found, return the level 0 */
277 	return UFS_PM_LVL_0;
278 }
279 
280 static bool ufshcd_has_pending_tasks(struct ufs_hba *hba)
281 {
282 	return hba->outstanding_tasks || hba->active_uic_cmd ||
283 	       hba->uic_async_done;
284 }
285 
286 static bool ufshcd_is_ufs_dev_busy(struct ufs_hba *hba)
287 {
288 	return (hba->scsi_host_added && scsi_host_busy(hba->host)) ||
289 		ufshcd_has_pending_tasks(hba);
290 }
291 
292 static const struct ufs_dev_quirk ufs_fixups[] = {
293 	/* UFS cards deviations table */
294 	{ .wmanufacturerid = UFS_VENDOR_MICRON,
295 	  .model = UFS_ANY_MODEL,
296 	  .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM },
297 	{ .wmanufacturerid = UFS_VENDOR_SAMSUNG,
298 	  .model = UFS_ANY_MODEL,
299 	  .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
300 		   UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE |
301 		   UFS_DEVICE_QUIRK_PA_HIBER8TIME |
302 		   UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS },
303 	{ .wmanufacturerid = UFS_VENDOR_SKHYNIX,
304 	  .model = UFS_ANY_MODEL,
305 	  .quirk = UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME },
306 	{ .wmanufacturerid = UFS_VENDOR_SKHYNIX,
307 	  .model = "hB8aL1" /*H28U62301AMR*/,
308 	  .quirk = UFS_DEVICE_QUIRK_HOST_VS_DEBUGSAVECONFIGTIME },
309 	{ .wmanufacturerid = UFS_VENDOR_TOSHIBA,
310 	  .model = UFS_ANY_MODEL,
311 	  .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM },
312 	{ .wmanufacturerid = UFS_VENDOR_TOSHIBA,
313 	  .model = "THGLF2G9C8KBADG",
314 	  .quirk = UFS_DEVICE_QUIRK_PA_TACTIVATE },
315 	{ .wmanufacturerid = UFS_VENDOR_TOSHIBA,
316 	  .model = "THGLF2G9D8KBADG",
317 	  .quirk = UFS_DEVICE_QUIRK_PA_TACTIVATE },
318 	{ .wmanufacturerid = UFS_VENDOR_TOSHIBA,
319 	  .model = "THGJFJT0E25BAIP",
320 	  .quirk = UFS_DEVICE_QUIRK_NO_TIMESTAMP_SUPPORT },
321 	{ .wmanufacturerid = UFS_VENDOR_TOSHIBA,
322 	  .model = "THGJFJT1E45BATP",
323 	  .quirk = UFS_DEVICE_QUIRK_NO_TIMESTAMP_SUPPORT },
324 	{}
325 };
326 
327 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba);
328 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
329 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
330 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
331 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
332 static void ufshcd_hba_exit(struct ufs_hba *hba);
333 static int ufshcd_device_init(struct ufs_hba *hba, bool init_dev_params);
334 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params);
335 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
336 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
337 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
338 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
339 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
340 static irqreturn_t ufshcd_intr(int irq, void *__hba);
341 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on);
342 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on);
343 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
344 					 struct ufs_vreg *vreg);
345 static void ufshcd_wb_toggle_buf_flush_during_h8(struct ufs_hba *hba,
346 						 bool enable);
347 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba);
348 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba);
349 
350 void ufshcd_enable_irq(struct ufs_hba *hba)
351 {
352 	if (!hba->is_irq_enabled) {
353 		enable_irq(hba->irq);
354 		hba->is_irq_enabled = true;
355 	}
356 }
357 EXPORT_SYMBOL_GPL(ufshcd_enable_irq);
358 
359 void ufshcd_disable_irq(struct ufs_hba *hba)
360 {
361 	if (hba->is_irq_enabled) {
362 		disable_irq(hba->irq);
363 		hba->is_irq_enabled = false;
364 	}
365 }
366 EXPORT_SYMBOL_GPL(ufshcd_disable_irq);
367 
368 /**
369  * ufshcd_enable_intr - enable interrupts
370  * @hba: per adapter instance
371  * @intrs: interrupt bits
372  */
373 void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
374 {
375 	u32 old_val = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
376 	u32 new_val = old_val | intrs;
377 
378 	if (new_val != old_val)
379 		ufshcd_writel(hba, new_val, REG_INTERRUPT_ENABLE);
380 }
381 
382 /**
383  * ufshcd_disable_intr - disable interrupts
384  * @hba: per adapter instance
385  * @intrs: interrupt bits
386  */
387 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
388 {
389 	u32 old_val = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
390 	u32 new_val = old_val & ~intrs;
391 
392 	if (new_val != old_val)
393 		ufshcd_writel(hba, new_val, REG_INTERRUPT_ENABLE);
394 }
395 
396 static void ufshcd_configure_wb(struct ufs_hba *hba)
397 {
398 	if (!ufshcd_is_wb_allowed(hba))
399 		return;
400 
401 	ufshcd_wb_toggle(hba, true);
402 
403 	ufshcd_wb_toggle_buf_flush_during_h8(hba, true);
404 
405 	if (ufshcd_is_wb_buf_flush_allowed(hba))
406 		ufshcd_wb_toggle_buf_flush(hba, true);
407 }
408 
409 static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba,
410 				      struct ufshcd_lrb *lrb,
411 				      enum ufs_trace_str_t str_t)
412 {
413 	struct utp_upiu_req *rq = lrb->ucd_req_ptr;
414 	struct utp_upiu_header *header;
415 
416 	if (!trace_ufshcd_upiu_enabled())
417 		return;
418 
419 	if (str_t == UFS_CMD_SEND)
420 		header = &rq->header;
421 	else
422 		header = &lrb->ucd_rsp_ptr->header;
423 
424 	trace_ufshcd_upiu(hba, str_t, header, &rq->sc.cdb,
425 			  UFS_TSF_CDB);
426 }
427 
428 static void ufshcd_add_query_upiu_trace(struct ufs_hba *hba,
429 					enum ufs_trace_str_t str_t,
430 					struct utp_upiu_req *rq_rsp)
431 {
432 	if (!trace_ufshcd_upiu_enabled())
433 		return;
434 
435 	trace_ufshcd_upiu(hba, str_t, &rq_rsp->header,
436 			  &rq_rsp->qr, UFS_TSF_OSF);
437 }
438 
439 static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag,
440 				     enum ufs_trace_str_t str_t)
441 {
442 	struct utp_task_req_desc *descp = &hba->utmrdl_base_addr[tag];
443 
444 	if (!trace_ufshcd_upiu_enabled())
445 		return;
446 
447 	if (str_t == UFS_TM_SEND)
448 		trace_ufshcd_upiu(hba, str_t,
449 				  &descp->upiu_req.req_header,
450 				  &descp->upiu_req.input_param1,
451 				  UFS_TSF_TM_INPUT);
452 	else
453 		trace_ufshcd_upiu(hba, str_t,
454 				  &descp->upiu_rsp.rsp_header,
455 				  &descp->upiu_rsp.output_param1,
456 				  UFS_TSF_TM_OUTPUT);
457 }
458 
459 static void ufshcd_add_uic_command_trace(struct ufs_hba *hba,
460 					 const struct uic_command *ucmd,
461 					 enum ufs_trace_str_t str_t)
462 {
463 	u32 cmd, arg1, arg2, arg3;
464 
465 	if (!trace_ufshcd_uic_command_enabled())
466 		return;
467 
468 	if (str_t == UFS_CMD_SEND) {
469 		cmd = ucmd->command;
470 		arg1 = ucmd->argument1;
471 		arg2 = ucmd->argument2;
472 		arg3 = ucmd->argument3;
473 	} else {
474 		cmd = ufshcd_readl(hba, REG_UIC_COMMAND);
475 		arg1 = ufshcd_readl(hba, REG_UIC_COMMAND_ARG_1);
476 		arg2 = ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2);
477 		arg3 = ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
478 	}
479 
480 	trace_ufshcd_uic_command(hba, str_t, cmd, arg1, arg2, arg3);
481 }
482 
483 static void ufshcd_add_command_trace(struct ufs_hba *hba, struct scsi_cmnd *cmd,
484 				     enum ufs_trace_str_t str_t)
485 {
486 	u64 lba = 0;
487 	u8 opcode = 0, group_id = 0;
488 	u32 doorbell = 0;
489 	u32 intr;
490 	u32 hwq_id = 0;
491 	struct request *rq = scsi_cmd_to_rq(cmd);
492 	unsigned int tag = rq->tag;
493 	struct ufshcd_lrb *lrbp = scsi_cmd_priv(cmd);
494 	int transfer_len = -1;
495 
496 	/* trace UPIU also */
497 	ufshcd_add_cmd_upiu_trace(hba, lrbp, str_t);
498 	if (!trace_ufshcd_command_enabled())
499 		return;
500 
501 	opcode = cmd->cmnd[0];
502 
503 	if (opcode == READ_10 || opcode == WRITE_10) {
504 		/*
505 		 * Currently we only fully trace read(10) and write(10) commands
506 		 */
507 		transfer_len =
508 		       be32_to_cpu(lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
509 		lba = scsi_get_lba(cmd);
510 		if (opcode == WRITE_10)
511 			group_id = cmd->cmnd[6];
512 	} else if (opcode == UNMAP) {
513 		/*
514 		 * The number of Bytes to be unmapped beginning with the lba.
515 		 */
516 		transfer_len = blk_rq_bytes(rq);
517 		lba = scsi_get_lba(cmd);
518 	}
519 
520 	intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
521 
522 	if (hba->mcq_enabled) {
523 		struct ufs_hw_queue *hwq = ufshcd_mcq_req_to_hwq(hba, rq);
524 		if (hwq)
525 			hwq_id = hwq->id;
526 	} else {
527 		doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
528 	}
529 	trace_ufshcd_command(cmd->device, hba, str_t, tag, doorbell, hwq_id,
530 			     transfer_len, intr, lba, opcode, group_id);
531 }
532 
533 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
534 {
535 	struct ufs_clk_info *clki;
536 	struct list_head *head = &hba->clk_list_head;
537 
538 	if (list_empty(head))
539 		return;
540 
541 	list_for_each_entry(clki, head, list) {
542 		if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
543 				clki->max_freq)
544 			dev_err(hba->dev, "clk: %s, rate: %u\n",
545 					clki->name, clki->curr_freq);
546 	}
547 }
548 
549 static void ufshcd_print_evt(struct ufs_hba *hba, u32 id,
550 			     const char *err_name)
551 {
552 	int i;
553 	bool found = false;
554 	const struct ufs_event_hist *e;
555 
556 	if (id >= UFS_EVT_CNT)
557 		return;
558 
559 	e = &hba->ufs_stats.event[id];
560 
561 	for (i = 0; i < UFS_EVENT_HIST_LENGTH; i++) {
562 		int p = (i + e->pos) % UFS_EVENT_HIST_LENGTH;
563 
564 		if (e->tstamp[p] == 0)
565 			continue;
566 		dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, p,
567 			e->val[p], div_u64(e->tstamp[p], 1000));
568 		found = true;
569 	}
570 
571 	if (!found)
572 		dev_err(hba->dev, "No record of %s\n", err_name);
573 	else
574 		dev_err(hba->dev, "%s: total cnt=%llu\n", err_name, e->cnt);
575 }
576 
577 static void ufshcd_print_evt_hist(struct ufs_hba *hba)
578 {
579 	ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
580 
581 	ufshcd_print_evt(hba, UFS_EVT_PA_ERR, "pa_err");
582 	ufshcd_print_evt(hba, UFS_EVT_DL_ERR, "dl_err");
583 	ufshcd_print_evt(hba, UFS_EVT_NL_ERR, "nl_err");
584 	ufshcd_print_evt(hba, UFS_EVT_TL_ERR, "tl_err");
585 	ufshcd_print_evt(hba, UFS_EVT_DME_ERR, "dme_err");
586 	ufshcd_print_evt(hba, UFS_EVT_AUTO_HIBERN8_ERR,
587 			 "auto_hibern8_err");
588 	ufshcd_print_evt(hba, UFS_EVT_FATAL_ERR, "fatal_err");
589 	ufshcd_print_evt(hba, UFS_EVT_LINK_STARTUP_FAIL,
590 			 "link_startup_fail");
591 	ufshcd_print_evt(hba, UFS_EVT_RESUME_ERR, "resume_fail");
592 	ufshcd_print_evt(hba, UFS_EVT_SUSPEND_ERR,
593 			 "suspend_fail");
594 	ufshcd_print_evt(hba, UFS_EVT_WL_RES_ERR, "wlun resume_fail");
595 	ufshcd_print_evt(hba, UFS_EVT_WL_SUSP_ERR,
596 			 "wlun suspend_fail");
597 	ufshcd_print_evt(hba, UFS_EVT_DEV_RESET, "dev_reset");
598 	ufshcd_print_evt(hba, UFS_EVT_HOST_RESET, "host_reset");
599 	ufshcd_print_evt(hba, UFS_EVT_ABORT, "task_abort");
600 
601 	ufshcd_vops_dbg_register_dump(hba);
602 }
603 
604 static void ufshcd_print_tr(struct ufs_hba *hba, struct scsi_cmnd *cmd,
605 			    bool pr_prdt)
606 {
607 	struct ufshcd_lrb *lrbp = scsi_cmd_priv(cmd);
608 	const int tag = scsi_cmd_to_rq(cmd)->tag;
609 	int prdt_length;
610 
611 	if (hba->monitor.enabled) {
612 		dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n", tag,
613 			div_u64(lrbp->issue_time_stamp_local_clock, 1000));
614 		dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n", tag,
615 			div_u64(lrbp->compl_time_stamp_local_clock, 1000));
616 	}
617 	dev_err(hba->dev,
618 		"UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
619 		tag, (u64)lrbp->utrd_dma_addr);
620 
621 	ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
622 			sizeof(struct utp_transfer_req_desc));
623 	dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
624 		(u64)lrbp->ucd_req_dma_addr);
625 	ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
626 			sizeof(struct utp_upiu_req));
627 	dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
628 		(u64)lrbp->ucd_rsp_dma_addr);
629 	ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
630 			sizeof(struct utp_upiu_rsp));
631 
632 	prdt_length = le16_to_cpu(
633 		lrbp->utr_descriptor_ptr->prd_table_length);
634 	if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
635 		prdt_length /= ufshcd_sg_entry_size(hba);
636 
637 	dev_err(hba->dev,
638 		"UPIU[%d] - PRDT - %d entries  phys@0x%llx\n",
639 		tag, prdt_length,
640 		(u64)lrbp->ucd_prdt_dma_addr);
641 
642 	if (pr_prdt)
643 		ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
644 			ufshcd_sg_entry_size(hba) * prdt_length);
645 }
646 
647 static bool ufshcd_print_tr_iter(struct request *req, void *priv)
648 {
649 	struct scsi_device *sdev = req->q->queuedata;
650 	struct Scsi_Host *shost = sdev->host;
651 	struct ufs_hba *hba = shost_priv(shost);
652 
653 	if (!blk_mq_is_reserved_rq(req))
654 		ufshcd_print_tr(hba, blk_mq_rq_to_pdu(req), *(bool *)priv);
655 
656 	return true;
657 }
658 
659 /**
660  * ufshcd_print_trs_all - print trs for all started requests.
661  * @hba: per-adapter instance.
662  * @pr_prdt: need to print prdt or not.
663  */
664 static void ufshcd_print_trs_all(struct ufs_hba *hba, bool pr_prdt)
665 {
666 	blk_mq_tagset_busy_iter(&hba->host->tag_set, ufshcd_print_tr_iter, &pr_prdt);
667 }
668 
669 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
670 {
671 	int tag;
672 
673 	for_each_set_bit(tag, &bitmap, hba->nutmrs) {
674 		struct utp_task_req_desc *tmrdp = &hba->utmrdl_base_addr[tag];
675 
676 		dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
677 		ufshcd_hex_dump("", tmrdp, sizeof(*tmrdp));
678 	}
679 }
680 
681 static void ufshcd_print_host_state(struct ufs_hba *hba)
682 {
683 	const struct scsi_device *sdev_ufs = hba->ufs_device_wlun;
684 
685 	dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
686 	dev_err(hba->dev, "%d outstanding reqs, tasks=0x%lx\n",
687 		hba->scsi_host_added ? scsi_host_busy(hba->host) : 0,
688 		hba->outstanding_tasks);
689 	dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
690 		hba->saved_err, hba->saved_uic_err);
691 	dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
692 		hba->curr_dev_pwr_mode, hba->uic_link_state);
693 	dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
694 		hba->pm_op_in_progress, hba->is_sys_suspended);
695 	dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
696 		hba->auto_bkops_enabled, hba->host->host_self_blocked);
697 	dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
698 	dev_err(hba->dev,
699 		"last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt=%d\n",
700 		div_u64(hba->ufs_stats.last_hibern8_exit_tstamp, 1000),
701 		hba->ufs_stats.hibern8_exit_cnt);
702 	dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
703 		hba->eh_flags, hba->req_abort_count);
704 	dev_err(hba->dev, "hba->ufs_version=0x%x, Host capabilities=0x%x, caps=0x%x\n",
705 		hba->ufs_version, hba->capabilities, hba->caps);
706 	dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
707 		hba->dev_quirks);
708 	if (sdev_ufs)
709 		dev_err(hba->dev, "UFS dev info: %.8s %.16s rev %.4s\n",
710 			sdev_ufs->vendor, sdev_ufs->model, sdev_ufs->rev);
711 
712 	ufshcd_print_clk_freqs(hba);
713 }
714 
715 /**
716  * ufshcd_print_pwr_info - print power params as saved in hba
717  * power info
718  * @hba: per-adapter instance
719  */
720 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
721 {
722 	static const char * const names[] = {
723 		"INVALID MODE",
724 		"FAST MODE",
725 		"SLOW_MODE",
726 		"INVALID MODE",
727 		"FASTAUTO_MODE",
728 		"SLOWAUTO_MODE",
729 		"INVALID MODE",
730 	};
731 
732 	/*
733 	 * Using dev_dbg to avoid messages during runtime PM to avoid
734 	 * never-ending cycles of messages written back to storage by user space
735 	 * causing runtime resume, causing more messages and so on.
736 	 */
737 	dev_dbg(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
738 		 __func__,
739 		 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
740 		 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
741 		 names[hba->pwr_info.pwr_rx],
742 		 names[hba->pwr_info.pwr_tx],
743 		 hba->pwr_info.hs_rate);
744 }
745 
746 static void ufshcd_device_reset(struct ufs_hba *hba)
747 {
748 	int err;
749 
750 	err = ufshcd_vops_device_reset(hba);
751 
752 	if (!err) {
753 		ufshcd_set_ufs_dev_active(hba);
754 		if (ufshcd_is_wb_allowed(hba)) {
755 			hba->dev_info.wb_enabled = false;
756 			hba->dev_info.wb_buf_flush_enabled = false;
757 		}
758 		if (hba->dev_info.rtc_type == UFS_RTC_RELATIVE)
759 			hba->dev_info.rtc_time_baseline = 0;
760 	}
761 	if (err != -EOPNOTSUPP)
762 		ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, err);
763 }
764 
765 void ufshcd_delay_us(unsigned long us, unsigned long tolerance)
766 {
767 	if (!us)
768 		return;
769 
770 	if (us < 10)
771 		udelay(us);
772 	else
773 		usleep_range(us, us + tolerance);
774 }
775 EXPORT_SYMBOL_GPL(ufshcd_delay_us);
776 
777 /**
778  * ufshcd_wait_for_register - wait for register value to change
779  * @hba: per-adapter interface
780  * @reg: mmio register offset
781  * @mask: mask to apply to the read register value
782  * @val: value to wait for
783  * @interval_us: polling interval in microseconds
784  * @timeout_ms: timeout in milliseconds
785  *
786  * Return: -ETIMEDOUT on error, zero on success.
787  */
788 static int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
789 				    u32 val, unsigned long interval_us,
790 				    unsigned long timeout_ms)
791 {
792 	u32 v;
793 
794 	val &= mask; /* ignore bits that we don't intend to wait on */
795 
796 	return read_poll_timeout(ufshcd_readl, v, (v & mask) == val,
797 				 interval_us, timeout_ms * 1000, false, hba, reg);
798 }
799 
800 /**
801  * ufshcd_get_intr_mask - Get the interrupt bit mask
802  * @hba: Pointer to adapter instance
803  *
804  * Return: interrupt bit mask per version
805  */
806 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
807 {
808 	if (hba->ufs_version <= ufshci_version(2, 0))
809 		return INTERRUPT_MASK_ALL_VER_11;
810 
811 	return INTERRUPT_MASK_ALL_VER_21;
812 }
813 
814 /**
815  * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
816  * @hba: Pointer to adapter instance
817  *
818  * Return: UFSHCI version supported by the controller
819  */
820 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
821 {
822 	u32 ufshci_ver;
823 
824 	if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
825 		ufshci_ver = ufshcd_vops_get_ufs_hci_version(hba);
826 	else
827 		ufshci_ver = ufshcd_readl(hba, REG_UFS_VERSION);
828 
829 	/*
830 	 * UFSHCI v1.x uses a different version scheme, in order
831 	 * to allow the use of comparisons with the ufshci_version
832 	 * function, we convert it to the same scheme as ufs 2.0+.
833 	 */
834 	if (ufshci_ver & 0x00010000)
835 		return ufshci_version(1, ufshci_ver & 0x00000100);
836 
837 	return ufshci_ver;
838 }
839 
840 /**
841  * ufshcd_is_device_present - Check if any device connected to
842  *			      the host controller
843  * @hba: pointer to adapter instance
844  *
845  * Return: true if device present, false if no device detected
846  */
847 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
848 {
849 	return ufshcd_readl(hba, REG_CONTROLLER_STATUS) & DEVICE_PRESENT;
850 }
851 
852 /**
853  * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
854  * @lrbp: pointer to local command reference block
855  * @cqe: pointer to the completion queue entry
856  *
857  * This function is used to get the OCS field from UTRD
858  *
859  * Return: the OCS field in the UTRD.
860  */
861 static enum utp_ocs ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp,
862 				      struct cq_entry *cqe)
863 {
864 	if (cqe)
865 		return cqe->overall_status & MASK_OCS;
866 
867 	return lrbp->utr_descriptor_ptr->header.ocs & MASK_OCS;
868 }
869 
870 /**
871  * ufshcd_utrl_clear() - Clear requests from the controller request list.
872  * @hba: per adapter instance
873  * @mask: mask with one bit set for each request to be cleared
874  */
875 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 mask)
876 {
877 	if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
878 		mask = ~mask;
879 	/*
880 	 * From the UFSHCI specification: "UTP Transfer Request List CLear
881 	 * Register (UTRLCLR): This field is bit significant. Each bit
882 	 * corresponds to a slot in the UTP Transfer Request List, where bit 0
883 	 * corresponds to request slot 0. A bit in this field is set to ‘0’
884 	 * by host software to indicate to the host controller that a transfer
885 	 * request slot is cleared. The host controller
886 	 * shall free up any resources associated to the request slot
887 	 * immediately, and shall set the associated bit in UTRLDBR to ‘0’. The
888 	 * host software indicates no change to request slots by setting the
889 	 * associated bits in this field to ‘1’. Bits in this field shall only
890 	 * be set ‘1’ or ‘0’ by host software when UTRLRSR is set to ‘1’."
891 	 */
892 	ufshcd_writel(hba, ~mask, REG_UTP_TRANSFER_REQ_LIST_CLEAR);
893 }
894 
895 /**
896  * ufshcd_utmrl_clear - Clear a bit in UTMRLCLR register
897  * @hba: per adapter instance
898  * @pos: position of the bit to be cleared
899  */
900 static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos)
901 {
902 	if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
903 		ufshcd_writel(hba, (1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
904 	else
905 		ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
906 }
907 
908 /**
909  * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
910  * @reg: Register value of host controller status
911  *
912  * Return: 0 on success; a positive value if failed.
913  */
914 static inline int ufshcd_get_lists_status(u32 reg)
915 {
916 	return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
917 }
918 
919 /**
920  * ufshcd_get_req_rsp - returns the TR response transaction type
921  * @ucd_rsp_ptr: pointer to response UPIU
922  *
923  * Return: UPIU type.
924  */
925 static inline enum upiu_response_transaction
926 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
927 {
928 	return ucd_rsp_ptr->header.transaction_code;
929 }
930 
931 /**
932  * ufshcd_is_exception_event - Check if the device raised an exception event
933  * @ucd_rsp_ptr: pointer to response UPIU
934  *
935  * The function checks if the device raised an exception event indicated in
936  * the Device Information field of response UPIU.
937  *
938  * Return: true if exception is raised, false otherwise.
939  */
940 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
941 {
942 	return ucd_rsp_ptr->header.device_information & 1;
943 }
944 
945 /**
946  * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
947  * @hba: per adapter instance
948  */
949 static inline void
950 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
951 {
952 	ufshcd_writel(hba, INT_AGGR_ENABLE |
953 		      INT_AGGR_COUNTER_AND_TIMER_RESET,
954 		      REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
955 }
956 
957 /**
958  * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
959  * @hba: per adapter instance
960  * @cnt: Interrupt aggregation counter threshold
961  * @tmout: Interrupt aggregation timeout value
962  */
963 static inline void
964 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
965 {
966 	ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
967 		      INT_AGGR_COUNTER_THLD_VAL(cnt) |
968 		      INT_AGGR_TIMEOUT_VAL(tmout),
969 		      REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
970 }
971 
972 /**
973  * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
974  * @hba: per adapter instance
975  */
976 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
977 {
978 	ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
979 }
980 
981 /**
982  * ufshcd_enable_run_stop_reg - Enable run-stop registers,
983  *			When run-stop registers are set to 1, it indicates the
984  *			host controller that it can process the requests
985  * @hba: per adapter instance
986  */
987 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
988 {
989 	ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
990 		      REG_UTP_TASK_REQ_LIST_RUN_STOP);
991 	ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
992 		      REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
993 }
994 
995 /**
996  * ufshcd_hba_start - Start controller initialization sequence
997  * @hba: per adapter instance
998  */
999 static inline void ufshcd_hba_start(struct ufs_hba *hba)
1000 {
1001 	u32 val = CONTROLLER_ENABLE;
1002 
1003 	if (ufshcd_crypto_enable(hba))
1004 		val |= CRYPTO_GENERAL_ENABLE;
1005 
1006 	ufshcd_writel(hba, val, REG_CONTROLLER_ENABLE);
1007 }
1008 
1009 /**
1010  * ufshcd_is_hba_active - Get controller state
1011  * @hba: per adapter instance
1012  *
1013  * Return: true if and only if the controller is active.
1014  */
1015 bool ufshcd_is_hba_active(struct ufs_hba *hba)
1016 {
1017 	return ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE;
1018 }
1019 EXPORT_SYMBOL_GPL(ufshcd_is_hba_active);
1020 
1021 /**
1022  * ufshcd_pm_qos_init - initialize PM QoS request
1023  * @hba: per adapter instance
1024  */
1025 void ufshcd_pm_qos_init(struct ufs_hba *hba)
1026 {
1027 	guard(mutex)(&hba->pm_qos_mutex);
1028 
1029 	if (hba->pm_qos_enabled)
1030 		return;
1031 
1032 	cpu_latency_qos_add_request(&hba->pm_qos_req, PM_QOS_DEFAULT_VALUE);
1033 
1034 	if (cpu_latency_qos_request_active(&hba->pm_qos_req))
1035 		hba->pm_qos_enabled = true;
1036 }
1037 
1038 /**
1039  * ufshcd_pm_qos_exit - remove request from PM QoS
1040  * @hba: per adapter instance
1041  */
1042 void ufshcd_pm_qos_exit(struct ufs_hba *hba)
1043 {
1044 	guard(mutex)(&hba->pm_qos_mutex);
1045 
1046 	if (!hba->pm_qos_enabled)
1047 		return;
1048 
1049 	cpu_latency_qos_remove_request(&hba->pm_qos_req);
1050 	hba->pm_qos_enabled = false;
1051 }
1052 
1053 /**
1054  * ufshcd_pm_qos_update - update PM QoS request
1055  * @hba: per adapter instance
1056  * @on: If True, vote for perf PM QoS mode otherwise power save mode
1057  */
1058 void ufshcd_pm_qos_update(struct ufs_hba *hba, bool on)
1059 {
1060 	guard(mutex)(&hba->pm_qos_mutex);
1061 
1062 	if (!hba->pm_qos_enabled)
1063 		return;
1064 
1065 	cpu_latency_qos_update_request(&hba->pm_qos_req, on ? 0 : PM_QOS_DEFAULT_VALUE);
1066 }
1067 EXPORT_SYMBOL_GPL(ufshcd_pm_qos_update);
1068 
1069 /**
1070  * ufshcd_set_clk_freq - set UFS controller clock frequencies
1071  * @hba: per adapter instance
1072  * @scale_up: If True, set max possible frequency othewise set low frequency
1073  *
1074  * Return: 0 if successful; < 0 upon failure.
1075  */
1076 static int ufshcd_set_clk_freq(struct ufs_hba *hba, bool scale_up)
1077 {
1078 	int ret = 0;
1079 	struct ufs_clk_info *clki;
1080 	struct list_head *head = &hba->clk_list_head;
1081 
1082 	if (list_empty(head))
1083 		goto out;
1084 
1085 	list_for_each_entry(clki, head, list) {
1086 		if (!IS_ERR_OR_NULL(clki->clk)) {
1087 			if (scale_up && clki->max_freq) {
1088 				if (clki->curr_freq == clki->max_freq)
1089 					continue;
1090 
1091 				ret = clk_set_rate(clki->clk, clki->max_freq);
1092 				if (ret) {
1093 					dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
1094 						__func__, clki->name,
1095 						clki->max_freq, ret);
1096 					break;
1097 				}
1098 				trace_ufshcd_clk_scaling(hba,
1099 						"scaled up", clki->name,
1100 						clki->curr_freq,
1101 						clki->max_freq);
1102 
1103 				clki->curr_freq = clki->max_freq;
1104 
1105 			} else if (!scale_up && clki->min_freq) {
1106 				if (clki->curr_freq == clki->min_freq)
1107 					continue;
1108 
1109 				ret = clk_set_rate(clki->clk, clki->min_freq);
1110 				if (ret) {
1111 					dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
1112 						__func__, clki->name,
1113 						clki->min_freq, ret);
1114 					break;
1115 				}
1116 				trace_ufshcd_clk_scaling(hba,
1117 						"scaled down", clki->name,
1118 						clki->curr_freq,
1119 						clki->min_freq);
1120 				clki->curr_freq = clki->min_freq;
1121 			}
1122 		}
1123 		dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
1124 				clki->name, clk_get_rate(clki->clk));
1125 	}
1126 
1127 out:
1128 	return ret;
1129 }
1130 
1131 int ufshcd_opp_config_clks(struct device *dev, struct opp_table *opp_table,
1132 			   struct dev_pm_opp *opp, void *data,
1133 			   bool scaling_down)
1134 {
1135 	struct ufs_hba *hba = dev_get_drvdata(dev);
1136 	struct list_head *head = &hba->clk_list_head;
1137 	struct ufs_clk_info *clki;
1138 	unsigned long freq;
1139 	u8 idx = 0;
1140 	int ret;
1141 
1142 	list_for_each_entry(clki, head, list) {
1143 		if (!IS_ERR_OR_NULL(clki->clk)) {
1144 			freq = dev_pm_opp_get_freq_indexed(opp, idx++);
1145 
1146 			/* Do not set rate for clocks having frequency as 0 */
1147 			if (!freq)
1148 				continue;
1149 
1150 			ret = clk_set_rate(clki->clk, freq);
1151 			if (ret) {
1152 				dev_err(dev, "%s: %s clk set rate(%ldHz) failed, %d\n",
1153 					__func__, clki->name, freq, ret);
1154 				return ret;
1155 			}
1156 
1157 			trace_ufshcd_clk_scaling(hba,
1158 				(scaling_down ? "scaled down" : "scaled up"),
1159 				clki->name, hba->clk_scaling.target_freq, freq);
1160 		}
1161 	}
1162 
1163 	return 0;
1164 }
1165 EXPORT_SYMBOL_GPL(ufshcd_opp_config_clks);
1166 
1167 static int ufshcd_opp_set_rate(struct ufs_hba *hba, unsigned long freq)
1168 {
1169 	struct dev_pm_opp *opp;
1170 	int ret;
1171 
1172 	opp = dev_pm_opp_find_freq_floor_indexed(hba->dev,
1173 						 &freq, 0);
1174 	if (IS_ERR(opp))
1175 		return PTR_ERR(opp);
1176 
1177 	ret = dev_pm_opp_set_opp(hba->dev, opp);
1178 	dev_pm_opp_put(opp);
1179 
1180 	return ret;
1181 }
1182 
1183 /**
1184  * ufshcd_scale_clks - scale up or scale down UFS controller clocks
1185  * @hba: per adapter instance
1186  * @freq: frequency to scale
1187  * @scale_up: True if scaling up and false if scaling down
1188  *
1189  * Return: 0 if successful; < 0 upon failure.
1190  */
1191 int ufshcd_scale_clks(struct ufs_hba *hba, unsigned long freq, bool scale_up)
1192 {
1193 	int ret = 0;
1194 	ktime_t start = ktime_get();
1195 
1196 	ret = ufshcd_vops_clk_scale_notify(hba, scale_up, freq, PRE_CHANGE);
1197 	if (ret)
1198 		goto out;
1199 
1200 	if (hba->use_pm_opp)
1201 		ret = ufshcd_opp_set_rate(hba, freq);
1202 	else
1203 		ret = ufshcd_set_clk_freq(hba, scale_up);
1204 	if (ret)
1205 		goto out;
1206 
1207 	ret = ufshcd_vops_clk_scale_notify(hba, scale_up, freq, POST_CHANGE);
1208 	if (ret) {
1209 		if (hba->use_pm_opp)
1210 			ufshcd_opp_set_rate(hba,
1211 					    hba->devfreq->previous_freq);
1212 		else
1213 			ufshcd_set_clk_freq(hba, !scale_up);
1214 		goto out;
1215 	}
1216 
1217 	ufshcd_pm_qos_update(hba, scale_up);
1218 
1219 out:
1220 	trace_ufshcd_profile_clk_scaling(hba,
1221 			(scale_up ? "up" : "down"),
1222 			ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1223 	return ret;
1224 }
1225 
1226 /**
1227  * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
1228  * @hba: per adapter instance
1229  * @freq: frequency to scale
1230  * @scale_up: True if scaling up and false if scaling down
1231  *
1232  * Return: true if scaling is required, false otherwise.
1233  */
1234 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
1235 					       unsigned long freq, bool scale_up)
1236 {
1237 	struct ufs_clk_info *clki;
1238 	struct list_head *head = &hba->clk_list_head;
1239 
1240 	if (list_empty(head))
1241 		return false;
1242 
1243 	if (hba->use_pm_opp)
1244 		return freq != hba->clk_scaling.target_freq;
1245 
1246 	list_for_each_entry(clki, head, list) {
1247 		if (!IS_ERR_OR_NULL(clki->clk)) {
1248 			if (scale_up && clki->max_freq) {
1249 				if (clki->curr_freq == clki->max_freq)
1250 					continue;
1251 				return true;
1252 			} else if (!scale_up && clki->min_freq) {
1253 				if (clki->curr_freq == clki->min_freq)
1254 					continue;
1255 				return true;
1256 			}
1257 		}
1258 	}
1259 
1260 	return false;
1261 }
1262 
1263 /*
1264  * Determine the number of pending commands by counting the bits in the SCSI
1265  * device budget maps. This approach has been selected because a bit is set in
1266  * the budget map before scsi_host_queue_ready() checks the host_self_blocked
1267  * flag. The host_self_blocked flag can be modified by calling
1268  * scsi_block_requests() or scsi_unblock_requests().
1269  */
1270 static u32 ufshcd_pending_cmds(struct ufs_hba *hba)
1271 {
1272 	struct scsi_device *sdev;
1273 	unsigned long flags;
1274 	u32 pending = 0;
1275 
1276 	spin_lock_irqsave(hba->host->host_lock, flags);
1277 	__shost_for_each_device(sdev, hba->host)
1278 		pending += scsi_device_busy(sdev);
1279 	spin_unlock_irqrestore(hba->host->host_lock, flags);
1280 
1281 	return pending;
1282 }
1283 
1284 /*
1285  * Wait until all pending SCSI commands and TMFs have finished or the timeout
1286  * has expired.
1287  *
1288  * Return: 0 upon success; -EBUSY upon timeout.
1289  */
1290 static int ufshcd_wait_for_pending_cmds(struct ufs_hba *hba,
1291 					u64 wait_timeout_us)
1292 {
1293 	int ret = 0;
1294 	u32 tm_doorbell;
1295 	u32 tr_pending;
1296 	bool timeout = false, do_last_check = false;
1297 	ktime_t start;
1298 
1299 	ufshcd_hold(hba);
1300 	/*
1301 	 * Wait for all the outstanding tasks/transfer requests.
1302 	 * Verify by checking the doorbell registers are clear.
1303 	 */
1304 	start = ktime_get();
1305 	do {
1306 		if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
1307 			ret = -EBUSY;
1308 			goto out;
1309 		}
1310 
1311 		tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1312 		tr_pending = ufshcd_pending_cmds(hba);
1313 		if (!tm_doorbell && !tr_pending) {
1314 			timeout = false;
1315 			break;
1316 		} else if (do_last_check) {
1317 			break;
1318 		}
1319 
1320 		io_schedule_timeout(msecs_to_jiffies(20));
1321 		if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1322 		    wait_timeout_us) {
1323 			timeout = true;
1324 			/*
1325 			 * We might have scheduled out for long time so make
1326 			 * sure to check if doorbells are cleared by this time
1327 			 * or not.
1328 			 */
1329 			do_last_check = true;
1330 		}
1331 	} while (tm_doorbell || tr_pending);
1332 
1333 	if (timeout) {
1334 		dev_err(hba->dev,
1335 			"%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1336 			__func__, tm_doorbell, tr_pending);
1337 		ret = -EBUSY;
1338 	}
1339 out:
1340 	ufshcd_release(hba);
1341 	return ret;
1342 }
1343 
1344 /**
1345  * ufshcd_pause_command_processing - Pause command processing
1346  * @hba: per-adapter instance
1347  * @timeout_us: timeout in microseconds to wait for pending commands to finish
1348  *
1349  * This function stops new command submissions and waits for existing commands
1350  * to complete.
1351  *
1352  * Return: 0 on success, %-EBUSY if commands did not finish within @timeout_us.
1353  * On failure, all acquired locks are released and the tagset is unquiesced.
1354  */
1355 int ufshcd_pause_command_processing(struct ufs_hba *hba, u64 timeout_us)
1356 {
1357 	int ret = 0;
1358 
1359 	mutex_lock(&hba->host->scan_mutex);
1360 	blk_mq_quiesce_tagset(&hba->host->tag_set);
1361 	down_write(&hba->clk_scaling_lock);
1362 
1363 	if (ufshcd_wait_for_pending_cmds(hba, timeout_us)) {
1364 		ret = -EBUSY;
1365 		up_write(&hba->clk_scaling_lock);
1366 		blk_mq_unquiesce_tagset(&hba->host->tag_set);
1367 		mutex_unlock(&hba->host->scan_mutex);
1368 	}
1369 
1370 	return ret;
1371 }
1372 
1373 /**
1374  * ufshcd_resume_command_processing - Resume command processing
1375  * @hba: per-adapter instance
1376  *
1377  * This function resumes command submissions.
1378  */
1379 void ufshcd_resume_command_processing(struct ufs_hba *hba)
1380 {
1381 	up_write(&hba->clk_scaling_lock);
1382 	blk_mq_unquiesce_tagset(&hba->host->tag_set);
1383 	mutex_unlock(&hba->host->scan_mutex);
1384 }
1385 
1386 /**
1387  * ufshcd_scale_gear - scale up/down UFS gear
1388  * @hba: per adapter instance
1389  * @target_gear: target gear to scale to
1390  * @scale_up: True for scaling up gear and false for scaling down
1391  *
1392  * Return: 0 for success; -EBUSY if scaling can't happen at this time;
1393  * non-zero for any other errors.
1394  */
1395 static int ufshcd_scale_gear(struct ufs_hba *hba, u32 target_gear, bool scale_up)
1396 {
1397 	int ret = 0;
1398 	struct ufs_pa_layer_attr new_pwr_info;
1399 
1400 	if (target_gear) {
1401 		new_pwr_info = hba->pwr_info;
1402 		new_pwr_info.gear_tx = target_gear;
1403 		new_pwr_info.gear_rx = target_gear;
1404 
1405 		goto config_pwr_mode;
1406 	}
1407 
1408 	/* Legacy gear scaling, in case vops_freq_to_gear_speed() is not implemented */
1409 	if (scale_up) {
1410 		memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info,
1411 		       sizeof(struct ufs_pa_layer_attr));
1412 	} else {
1413 		memcpy(&new_pwr_info, &hba->pwr_info,
1414 		       sizeof(struct ufs_pa_layer_attr));
1415 
1416 		if (hba->pwr_info.gear_tx > hba->clk_scaling.min_gear ||
1417 		    hba->pwr_info.gear_rx > hba->clk_scaling.min_gear) {
1418 			/* save the current power mode */
1419 			memcpy(&hba->clk_scaling.saved_pwr_info,
1420 				&hba->pwr_info,
1421 				sizeof(struct ufs_pa_layer_attr));
1422 
1423 			/* scale down gear */
1424 			new_pwr_info.gear_tx = hba->clk_scaling.min_gear;
1425 			new_pwr_info.gear_rx = hba->clk_scaling.min_gear;
1426 		}
1427 	}
1428 
1429 config_pwr_mode:
1430 	/* check if the power mode needs to be changed or not? */
1431 	ret = ufshcd_config_pwr_mode(hba, &new_pwr_info,
1432 				     UFSHCD_PMC_POLICY_DONT_FORCE);
1433 	if (ret)
1434 		dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1435 			__func__, ret,
1436 			hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1437 			new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1438 
1439 	return ret;
1440 }
1441 
1442 /*
1443  * Wait until all pending SCSI commands and TMFs have finished or the timeout
1444  * has expired.
1445  *
1446  * Return: 0 upon success; -EBUSY upon timeout.
1447  */
1448 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba, u64 timeout_us)
1449 {
1450 	int ret = 0;
1451 	/*
1452 	 * make sure that there are no outstanding requests when
1453 	 * clock scaling is in progress
1454 	 */
1455 	mutex_lock(&hba->host->scan_mutex);
1456 	blk_mq_quiesce_tagset(&hba->host->tag_set);
1457 	mutex_lock(&hba->wb_mutex);
1458 	down_write(&hba->clk_scaling_lock);
1459 
1460 	if (!hba->clk_scaling.is_allowed ||
1461 	    ufshcd_wait_for_pending_cmds(hba, timeout_us)) {
1462 		ret = -EBUSY;
1463 		up_write(&hba->clk_scaling_lock);
1464 		mutex_unlock(&hba->wb_mutex);
1465 		blk_mq_unquiesce_tagset(&hba->host->tag_set);
1466 		mutex_unlock(&hba->host->scan_mutex);
1467 		goto out;
1468 	}
1469 
1470 	/* let's not get into low power until clock scaling is completed */
1471 	ufshcd_hold(hba);
1472 
1473 out:
1474 	return ret;
1475 }
1476 
1477 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba, int err)
1478 {
1479 	up_write(&hba->clk_scaling_lock);
1480 	mutex_unlock(&hba->wb_mutex);
1481 	blk_mq_unquiesce_tagset(&hba->host->tag_set);
1482 	mutex_unlock(&hba->host->scan_mutex);
1483 
1484 	/* Enable Write Booster if current gear requires it else disable it */
1485 	if (ufshcd_enable_wb_if_scaling_up(hba) && !err)
1486 		ufshcd_wb_toggle(hba, hba->pwr_info.gear_rx >= hba->clk_scaling.wb_gear);
1487 
1488 	ufshcd_release(hba);
1489 }
1490 
1491 /**
1492  * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1493  * @hba: per adapter instance
1494  * @freq: frequency to scale
1495  * @scale_up: True for scaling up and false for scalin down
1496  *
1497  * Return: 0 for success; -EBUSY if scaling can't happen at this time; non-zero
1498  * for any other errors.
1499  */
1500 static int ufshcd_devfreq_scale(struct ufs_hba *hba, unsigned long freq,
1501 				bool scale_up)
1502 {
1503 	u32 old_gear = hba->pwr_info.gear_rx;
1504 	u32 new_gear = 0;
1505 	int ret = 0;
1506 
1507 	new_gear = ufshcd_vops_freq_to_gear_speed(hba, freq);
1508 
1509 	ret = ufshcd_clock_scaling_prepare(hba, 1 * USEC_PER_SEC);
1510 	if (ret)
1511 		return ret;
1512 
1513 	/* scale down the gear before scaling down clocks */
1514 	if (!scale_up) {
1515 		ret = ufshcd_scale_gear(hba, new_gear, false);
1516 		if (ret)
1517 			goto out_unprepare;
1518 	}
1519 
1520 	ret = ufshcd_scale_clks(hba, freq, scale_up);
1521 	if (ret) {
1522 		if (!scale_up)
1523 			ufshcd_scale_gear(hba, old_gear, true);
1524 		goto out_unprepare;
1525 	}
1526 
1527 	/* scale up the gear after scaling up clocks */
1528 	if (scale_up) {
1529 		ret = ufshcd_scale_gear(hba, new_gear, true);
1530 		if (ret) {
1531 			ufshcd_scale_clks(hba, hba->devfreq->previous_freq,
1532 					  false);
1533 			goto out_unprepare;
1534 		}
1535 	}
1536 
1537 out_unprepare:
1538 	ufshcd_clock_scaling_unprepare(hba, ret);
1539 	return ret;
1540 }
1541 
1542 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1543 {
1544 	struct ufs_hba *hba = container_of(work, struct ufs_hba,
1545 					   clk_scaling.suspend_work);
1546 
1547 	scoped_guard(spinlock_irqsave, &hba->clk_scaling.lock)
1548 	{
1549 		if (hba->clk_scaling.active_reqs ||
1550 		    hba->clk_scaling.is_suspended)
1551 			return;
1552 
1553 		hba->clk_scaling.is_suspended = true;
1554 		hba->clk_scaling.window_start_t = 0;
1555 	}
1556 
1557 	devfreq_suspend_device(hba->devfreq);
1558 }
1559 
1560 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1561 {
1562 	struct ufs_hba *hba = container_of(work, struct ufs_hba,
1563 					   clk_scaling.resume_work);
1564 
1565 	scoped_guard(spinlock_irqsave, &hba->clk_scaling.lock)
1566 	{
1567 		if (!hba->clk_scaling.is_suspended)
1568 			return;
1569 		hba->clk_scaling.is_suspended = false;
1570 	}
1571 
1572 	devfreq_resume_device(hba->devfreq);
1573 }
1574 
1575 static int ufshcd_devfreq_target(struct device *dev,
1576 				unsigned long *freq, u32 flags)
1577 {
1578 	int ret = 0;
1579 	struct ufs_hba *hba = dev_get_drvdata(dev);
1580 	ktime_t start;
1581 	bool scale_up = false, sched_clk_scaling_suspend_work = false;
1582 	struct list_head *clk_list = &hba->clk_list_head;
1583 	struct ufs_clk_info *clki;
1584 
1585 	if (!ufshcd_is_clkscaling_supported(hba))
1586 		return -EINVAL;
1587 
1588 	if (hba->use_pm_opp) {
1589 		struct dev_pm_opp *opp;
1590 
1591 		/* Get the recommended frequency from OPP framework */
1592 		opp = devfreq_recommended_opp(dev, freq, flags);
1593 		if (IS_ERR(opp))
1594 			return PTR_ERR(opp);
1595 
1596 		dev_pm_opp_put(opp);
1597 	} else {
1598 		/* Override with the closest supported frequency */
1599 		clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info,
1600 					list);
1601 		*freq =	(unsigned long) clk_round_rate(clki->clk, *freq);
1602 	}
1603 
1604 	scoped_guard(spinlock_irqsave, &hba->clk_scaling.lock)
1605 	{
1606 		if (ufshcd_eh_in_progress(hba))
1607 			return 0;
1608 
1609 		/* Skip scaling clock when clock scaling is suspended */
1610 		if (hba->clk_scaling.is_suspended) {
1611 			dev_warn(hba->dev, "clock scaling is suspended, skip");
1612 			return 0;
1613 		}
1614 
1615 		if (!hba->clk_scaling.active_reqs)
1616 			sched_clk_scaling_suspend_work = true;
1617 
1618 		if (list_empty(clk_list))
1619 			goto out;
1620 
1621 		/* Decide based on the target or rounded-off frequency and update */
1622 		if (hba->use_pm_opp)
1623 			scale_up = *freq > hba->clk_scaling.target_freq;
1624 		else
1625 			scale_up = *freq == clki->max_freq;
1626 
1627 		if (!hba->use_pm_opp && !scale_up)
1628 			*freq = clki->min_freq;
1629 
1630 		/* Update the frequency */
1631 		if (!ufshcd_is_devfreq_scaling_required(hba, *freq, scale_up)) {
1632 			ret = 0;
1633 			goto out; /* no state change required */
1634 		}
1635 	}
1636 
1637 	start = ktime_get();
1638 	ret = ufshcd_devfreq_scale(hba, *freq, scale_up);
1639 	if (!ret)
1640 		hba->clk_scaling.target_freq = *freq;
1641 
1642 	trace_ufshcd_profile_clk_scaling(hba,
1643 		(scale_up ? "up" : "down"),
1644 		ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1645 
1646 out:
1647 	if (sched_clk_scaling_suspend_work &&
1648 			(!scale_up || hba->clk_scaling.suspend_on_no_request))
1649 		queue_work(hba->clk_scaling.workq,
1650 			   &hba->clk_scaling.suspend_work);
1651 
1652 	return ret;
1653 }
1654 
1655 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1656 		struct devfreq_dev_status *stat)
1657 {
1658 	struct ufs_hba *hba = dev_get_drvdata(dev);
1659 	struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1660 	ktime_t curr_t;
1661 
1662 	if (!ufshcd_is_clkscaling_supported(hba))
1663 		return -EINVAL;
1664 
1665 	memset(stat, 0, sizeof(*stat));
1666 
1667 	guard(spinlock_irqsave)(&hba->clk_scaling.lock);
1668 
1669 	curr_t = ktime_get();
1670 	if (!scaling->window_start_t)
1671 		goto start_window;
1672 
1673 	/*
1674 	 * If current frequency is 0, then the ondemand governor considers
1675 	 * there's no initial frequency set. And it always requests to set
1676 	 * to max. frequency.
1677 	 */
1678 	if (hba->use_pm_opp) {
1679 		stat->current_frequency = hba->clk_scaling.target_freq;
1680 	} else {
1681 		struct list_head *clk_list = &hba->clk_list_head;
1682 		struct ufs_clk_info *clki;
1683 
1684 		clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1685 		stat->current_frequency = clki->curr_freq;
1686 	}
1687 
1688 	if (scaling->is_busy_started)
1689 		scaling->tot_busy_t += ktime_us_delta(curr_t,
1690 				scaling->busy_start_t);
1691 	stat->total_time = ktime_us_delta(curr_t, scaling->window_start_t);
1692 	stat->busy_time = scaling->tot_busy_t;
1693 start_window:
1694 	scaling->window_start_t = curr_t;
1695 	scaling->tot_busy_t = 0;
1696 
1697 	if (scaling->active_reqs) {
1698 		scaling->busy_start_t = curr_t;
1699 		scaling->is_busy_started = true;
1700 	} else {
1701 		scaling->busy_start_t = 0;
1702 		scaling->is_busy_started = false;
1703 	}
1704 
1705 	return 0;
1706 }
1707 
1708 static int ufshcd_devfreq_init(struct ufs_hba *hba)
1709 {
1710 	struct list_head *clk_list = &hba->clk_list_head;
1711 	struct ufs_clk_info *clki;
1712 	struct devfreq *devfreq;
1713 	int ret;
1714 
1715 	/* Skip devfreq if we don't have any clocks in the list */
1716 	if (list_empty(clk_list))
1717 		return 0;
1718 
1719 	if (!hba->use_pm_opp) {
1720 		clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1721 		dev_pm_opp_add(hba->dev, clki->min_freq, 0);
1722 		dev_pm_opp_add(hba->dev, clki->max_freq, 0);
1723 	}
1724 
1725 	ufshcd_vops_config_scaling_param(hba, &hba->vps->devfreq_profile,
1726 					 &hba->vps->ondemand_data);
1727 	devfreq = devfreq_add_device(hba->dev,
1728 			&hba->vps->devfreq_profile,
1729 			DEVFREQ_GOV_SIMPLE_ONDEMAND,
1730 			&hba->vps->ondemand_data);
1731 	if (IS_ERR(devfreq)) {
1732 		ret = PTR_ERR(devfreq);
1733 		dev_err(hba->dev, "Unable to register with devfreq %d\n", ret);
1734 
1735 		if (!hba->use_pm_opp) {
1736 			dev_pm_opp_remove(hba->dev, clki->min_freq);
1737 			dev_pm_opp_remove(hba->dev, clki->max_freq);
1738 		}
1739 		return ret;
1740 	}
1741 
1742 	hba->devfreq = devfreq;
1743 
1744 	return 0;
1745 }
1746 
1747 static void ufshcd_devfreq_remove(struct ufs_hba *hba)
1748 {
1749 	struct list_head *clk_list = &hba->clk_list_head;
1750 
1751 	if (!hba->devfreq)
1752 		return;
1753 
1754 	devfreq_remove_device(hba->devfreq);
1755 	hba->devfreq = NULL;
1756 
1757 	if (!hba->use_pm_opp) {
1758 		struct ufs_clk_info *clki;
1759 
1760 		clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1761 		dev_pm_opp_remove(hba->dev, clki->min_freq);
1762 		dev_pm_opp_remove(hba->dev, clki->max_freq);
1763 	}
1764 }
1765 
1766 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1767 {
1768 	bool suspend = false;
1769 
1770 	cancel_work_sync(&hba->clk_scaling.suspend_work);
1771 	cancel_work_sync(&hba->clk_scaling.resume_work);
1772 
1773 	scoped_guard(spinlock_irqsave, &hba->clk_scaling.lock)
1774 	{
1775 		if (!hba->clk_scaling.is_suspended) {
1776 			suspend = true;
1777 			hba->clk_scaling.is_suspended = true;
1778 			hba->clk_scaling.window_start_t = 0;
1779 		}
1780 	}
1781 
1782 	if (suspend)
1783 		devfreq_suspend_device(hba->devfreq);
1784 }
1785 
1786 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1787 {
1788 	bool resume = false;
1789 
1790 	scoped_guard(spinlock_irqsave, &hba->clk_scaling.lock)
1791 	{
1792 		if (hba->clk_scaling.is_suspended) {
1793 			resume = true;
1794 			hba->clk_scaling.is_suspended = false;
1795 		}
1796 	}
1797 
1798 	if (resume)
1799 		devfreq_resume_device(hba->devfreq);
1800 }
1801 
1802 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1803 		struct device_attribute *attr, char *buf)
1804 {
1805 	struct ufs_hba *hba = dev_get_drvdata(dev);
1806 
1807 	return sysfs_emit(buf, "%d\n", hba->clk_scaling.is_enabled);
1808 }
1809 
1810 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1811 		struct device_attribute *attr, const char *buf, size_t count)
1812 {
1813 	struct ufs_hba *hba = dev_get_drvdata(dev);
1814 	struct ufs_clk_info *clki;
1815 	unsigned long freq;
1816 	u32 value;
1817 	int err = 0;
1818 
1819 	if (kstrtou32(buf, 0, &value))
1820 		return -EINVAL;
1821 
1822 	down(&hba->host_sem);
1823 	if (!ufshcd_is_user_access_allowed(hba)) {
1824 		err = -EBUSY;
1825 		goto out;
1826 	}
1827 
1828 	value = !!value;
1829 	if (value == hba->clk_scaling.is_enabled)
1830 		goto out;
1831 
1832 	ufshcd_rpm_get_sync(hba);
1833 	ufshcd_hold(hba);
1834 
1835 	hba->clk_scaling.is_enabled = value;
1836 
1837 	if (value) {
1838 		ufshcd_resume_clkscaling(hba);
1839 		goto out_rel;
1840 	}
1841 
1842 	clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info, list);
1843 	freq = clki->max_freq;
1844 
1845 	ufshcd_suspend_clkscaling(hba);
1846 
1847 	if (!ufshcd_is_devfreq_scaling_required(hba, freq, true))
1848 		goto out_rel;
1849 
1850 	err = ufshcd_devfreq_scale(hba, freq, true);
1851 	if (err)
1852 		dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1853 				__func__, err);
1854 	else
1855 		hba->clk_scaling.target_freq = freq;
1856 
1857 out_rel:
1858 	ufshcd_release(hba);
1859 	ufshcd_rpm_put_sync(hba);
1860 out:
1861 	up(&hba->host_sem);
1862 	return err ? err : count;
1863 }
1864 
1865 static void ufshcd_init_clk_scaling_sysfs(struct ufs_hba *hba)
1866 {
1867 	hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1868 	hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1869 	sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1870 	hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1871 	hba->clk_scaling.enable_attr.attr.mode = 0644;
1872 	if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1873 		dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1874 }
1875 
1876 static void ufshcd_remove_clk_scaling_sysfs(struct ufs_hba *hba)
1877 {
1878 	if (hba->clk_scaling.enable_attr.attr.name)
1879 		device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
1880 }
1881 
1882 static void ufshcd_init_clk_scaling(struct ufs_hba *hba)
1883 {
1884 	if (!ufshcd_is_clkscaling_supported(hba))
1885 		return;
1886 
1887 	if (!hba->clk_scaling.min_gear)
1888 		hba->clk_scaling.min_gear = UFS_HS_G1;
1889 
1890 	if (!hba->clk_scaling.wb_gear)
1891 		/* Use intermediate gear speed HS_G3 as the default wb_gear */
1892 		hba->clk_scaling.wb_gear = UFS_HS_G3;
1893 
1894 	INIT_WORK(&hba->clk_scaling.suspend_work,
1895 		  ufshcd_clk_scaling_suspend_work);
1896 	INIT_WORK(&hba->clk_scaling.resume_work,
1897 		  ufshcd_clk_scaling_resume_work);
1898 
1899 	spin_lock_init(&hba->clk_scaling.lock);
1900 
1901 	hba->clk_scaling.workq = alloc_ordered_workqueue(
1902 		"ufs_clkscaling_%d", WQ_MEM_RECLAIM, hba->host->host_no);
1903 
1904 	hba->clk_scaling.is_initialized = true;
1905 }
1906 
1907 static void ufshcd_exit_clk_scaling(struct ufs_hba *hba)
1908 {
1909 	if (!hba->clk_scaling.is_initialized)
1910 		return;
1911 
1912 	ufshcd_remove_clk_scaling_sysfs(hba);
1913 	destroy_workqueue(hba->clk_scaling.workq);
1914 	ufshcd_devfreq_remove(hba);
1915 	hba->clk_scaling.is_initialized = false;
1916 }
1917 
1918 static void ufshcd_ungate_work(struct work_struct *work)
1919 {
1920 	int ret;
1921 	struct ufs_hba *hba = container_of(work, struct ufs_hba,
1922 			clk_gating.ungate_work);
1923 
1924 	cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1925 
1926 	scoped_guard(spinlock_irqsave, &hba->clk_gating.lock) {
1927 		if (hba->clk_gating.state == CLKS_ON)
1928 			return;
1929 	}
1930 
1931 	ufshcd_hba_vreg_set_hpm(hba);
1932 	ufshcd_setup_clocks(hba, true);
1933 
1934 	ufshcd_enable_irq(hba);
1935 
1936 	/* Exit from hibern8 */
1937 	if (ufshcd_can_hibern8_during_gating(hba)) {
1938 		/* Prevent gating in this path */
1939 		hba->clk_gating.is_suspended = true;
1940 		if (ufshcd_is_link_hibern8(hba)) {
1941 			ret = ufshcd_uic_hibern8_exit(hba);
1942 			if (ret)
1943 				dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1944 					__func__, ret);
1945 			else
1946 				ufshcd_set_link_active(hba);
1947 		}
1948 		hba->clk_gating.is_suspended = false;
1949 	}
1950 }
1951 
1952 /**
1953  * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1954  * Also, exit from hibern8 mode and set the link as active.
1955  * @hba: per adapter instance
1956  */
1957 void ufshcd_hold(struct ufs_hba *hba)
1958 {
1959 	bool flush_result;
1960 	unsigned long flags;
1961 
1962 	if (!ufshcd_is_clkgating_allowed(hba) ||
1963 	    !hba->clk_gating.is_initialized)
1964 		return;
1965 	spin_lock_irqsave(&hba->clk_gating.lock, flags);
1966 	hba->clk_gating.active_reqs++;
1967 
1968 start:
1969 	switch (hba->clk_gating.state) {
1970 	case CLKS_ON:
1971 		/*
1972 		 * Wait for the ungate work to complete if in progress.
1973 		 * Though the clocks may be in ON state, the link could
1974 		 * still be in hibner8 state if hibern8 is allowed
1975 		 * during clock gating.
1976 		 * Make sure we exit hibern8 state also in addition to
1977 		 * clocks being ON.
1978 		 */
1979 		if (ufshcd_can_hibern8_during_gating(hba) &&
1980 		    ufshcd_is_link_hibern8(hba)) {
1981 			spin_unlock_irqrestore(&hba->clk_gating.lock, flags);
1982 			flush_result = flush_work(&hba->clk_gating.ungate_work);
1983 			if (hba->clk_gating.is_suspended && !flush_result)
1984 				return;
1985 			spin_lock_irqsave(&hba->clk_gating.lock, flags);
1986 			goto start;
1987 		}
1988 		break;
1989 	case REQ_CLKS_OFF:
1990 		if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1991 			hba->clk_gating.state = CLKS_ON;
1992 			trace_ufshcd_clk_gating(hba,
1993 						hba->clk_gating.state);
1994 			break;
1995 		}
1996 		/*
1997 		 * If we are here, it means gating work is either done or
1998 		 * currently running. Hence, fall through to cancel gating
1999 		 * work and to enable clocks.
2000 		 */
2001 		fallthrough;
2002 	case CLKS_OFF:
2003 		hba->clk_gating.state = REQ_CLKS_ON;
2004 		trace_ufshcd_clk_gating(hba,
2005 					hba->clk_gating.state);
2006 		queue_work(hba->clk_gating.clk_gating_workq,
2007 			   &hba->clk_gating.ungate_work);
2008 		/*
2009 		 * fall through to check if we should wait for this
2010 		 * work to be done or not.
2011 		 */
2012 		fallthrough;
2013 	case REQ_CLKS_ON:
2014 		spin_unlock_irqrestore(&hba->clk_gating.lock, flags);
2015 		flush_work(&hba->clk_gating.ungate_work);
2016 		/* Make sure state is CLKS_ON before returning */
2017 		spin_lock_irqsave(&hba->clk_gating.lock, flags);
2018 		goto start;
2019 	default:
2020 		dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
2021 				__func__, hba->clk_gating.state);
2022 		break;
2023 	}
2024 	spin_unlock_irqrestore(&hba->clk_gating.lock, flags);
2025 }
2026 EXPORT_SYMBOL_GPL(ufshcd_hold);
2027 
2028 static void ufshcd_gate_work(struct work_struct *work)
2029 {
2030 	struct ufs_hba *hba = container_of(work, struct ufs_hba,
2031 			clk_gating.gate_work.work);
2032 	int ret;
2033 
2034 	scoped_guard(spinlock_irqsave, &hba->clk_gating.lock) {
2035 		/*
2036 		 * In case you are here to cancel this work the gating state
2037 		 * would be marked as REQ_CLKS_ON. In this case save time by
2038 		 * skipping the gating work and exit after changing the clock
2039 		 * state to CLKS_ON.
2040 		 */
2041 		if (hba->clk_gating.is_suspended ||
2042 		    hba->clk_gating.state != REQ_CLKS_OFF) {
2043 			hba->clk_gating.state = CLKS_ON;
2044 			trace_ufshcd_clk_gating(hba,
2045 						hba->clk_gating.state);
2046 			return;
2047 		}
2048 
2049 		if (hba->clk_gating.active_reqs)
2050 			return;
2051 	}
2052 
2053 	scoped_guard(spinlock_irqsave, hba->host->host_lock) {
2054 		if (ufshcd_is_ufs_dev_busy(hba) ||
2055 		    hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL)
2056 			return;
2057 	}
2058 
2059 	/* put the link into hibern8 mode before turning off clocks */
2060 	if (ufshcd_can_hibern8_during_gating(hba)) {
2061 		ret = ufshcd_uic_hibern8_enter(hba);
2062 		if (ret) {
2063 			hba->clk_gating.state = CLKS_ON;
2064 			dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
2065 					__func__, ret);
2066 			trace_ufshcd_clk_gating(hba,
2067 						hba->clk_gating.state);
2068 			return;
2069 		}
2070 		ufshcd_set_link_hibern8(hba);
2071 	}
2072 
2073 	ufshcd_disable_irq(hba);
2074 
2075 	ufshcd_setup_clocks(hba, false);
2076 
2077 	/* Put the host controller in low power mode if possible */
2078 	ufshcd_hba_vreg_set_lpm(hba);
2079 	/*
2080 	 * In case you are here to cancel this work the gating state
2081 	 * would be marked as REQ_CLKS_ON. In this case keep the state
2082 	 * as REQ_CLKS_ON which would anyway imply that clocks are off
2083 	 * and a request to turn them on is pending. By doing this way,
2084 	 * we keep the state machine in tact and this would ultimately
2085 	 * prevent from doing cancel work multiple times when there are
2086 	 * new requests arriving before the current cancel work is done.
2087 	 */
2088 	guard(spinlock_irqsave)(&hba->clk_gating.lock);
2089 	if (hba->clk_gating.state == REQ_CLKS_OFF) {
2090 		hba->clk_gating.state = CLKS_OFF;
2091 		trace_ufshcd_clk_gating(hba,
2092 					hba->clk_gating.state);
2093 	}
2094 }
2095 
2096 static void __ufshcd_release(struct ufs_hba *hba)
2097 {
2098 	lockdep_assert_held(&hba->clk_gating.lock);
2099 
2100 	if (!ufshcd_is_clkgating_allowed(hba))
2101 		return;
2102 
2103 	hba->clk_gating.active_reqs--;
2104 
2105 	if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended ||
2106 	    !hba->clk_gating.is_initialized ||
2107 	    hba->clk_gating.state == CLKS_OFF)
2108 		return;
2109 
2110 	scoped_guard(spinlock_irqsave, hba->host->host_lock) {
2111 		if (ufshcd_has_pending_tasks(hba) ||
2112 		    hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL)
2113 			return;
2114 	}
2115 
2116 	hba->clk_gating.state = REQ_CLKS_OFF;
2117 	trace_ufshcd_clk_gating(hba, hba->clk_gating.state);
2118 	queue_delayed_work(hba->clk_gating.clk_gating_workq,
2119 			   &hba->clk_gating.gate_work,
2120 			   msecs_to_jiffies(hba->clk_gating.delay_ms));
2121 }
2122 
2123 void ufshcd_release(struct ufs_hba *hba)
2124 {
2125 	guard(spinlock_irqsave)(&hba->clk_gating.lock);
2126 	__ufshcd_release(hba);
2127 }
2128 EXPORT_SYMBOL_GPL(ufshcd_release);
2129 
2130 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
2131 		struct device_attribute *attr, char *buf)
2132 {
2133 	struct ufs_hba *hba = dev_get_drvdata(dev);
2134 
2135 	return sysfs_emit(buf, "%lu\n", hba->clk_gating.delay_ms);
2136 }
2137 
2138 void ufshcd_clkgate_delay_set(struct device *dev, unsigned long value)
2139 {
2140 	struct ufs_hba *hba = dev_get_drvdata(dev);
2141 
2142 	guard(spinlock_irqsave)(&hba->clk_gating.lock);
2143 	hba->clk_gating.delay_ms = value;
2144 }
2145 EXPORT_SYMBOL_GPL(ufshcd_clkgate_delay_set);
2146 
2147 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
2148 		struct device_attribute *attr, const char *buf, size_t count)
2149 {
2150 	unsigned long value;
2151 
2152 	if (kstrtoul(buf, 0, &value))
2153 		return -EINVAL;
2154 
2155 	ufshcd_clkgate_delay_set(dev, value);
2156 	return count;
2157 }
2158 
2159 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
2160 		struct device_attribute *attr, char *buf)
2161 {
2162 	struct ufs_hba *hba = dev_get_drvdata(dev);
2163 
2164 	return sysfs_emit(buf, "%d\n", hba->clk_gating.is_enabled);
2165 }
2166 
2167 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
2168 		struct device_attribute *attr, const char *buf, size_t count)
2169 {
2170 	struct ufs_hba *hba = dev_get_drvdata(dev);
2171 	u32 value;
2172 
2173 	if (kstrtou32(buf, 0, &value))
2174 		return -EINVAL;
2175 
2176 	value = !!value;
2177 
2178 	guard(spinlock_irqsave)(&hba->clk_gating.lock);
2179 
2180 	if (value == hba->clk_gating.is_enabled)
2181 		return count;
2182 
2183 	if (value)
2184 		__ufshcd_release(hba);
2185 	else
2186 		hba->clk_gating.active_reqs++;
2187 
2188 	hba->clk_gating.is_enabled = value;
2189 
2190 	return count;
2191 }
2192 
2193 static void ufshcd_init_clk_gating_sysfs(struct ufs_hba *hba)
2194 {
2195 	hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
2196 	hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
2197 	sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
2198 	hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
2199 	hba->clk_gating.delay_attr.attr.mode = 0644;
2200 	if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
2201 		dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
2202 
2203 	hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
2204 	hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
2205 	sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
2206 	hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
2207 	hba->clk_gating.enable_attr.attr.mode = 0644;
2208 	if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
2209 		dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
2210 }
2211 
2212 static void ufshcd_remove_clk_gating_sysfs(struct ufs_hba *hba)
2213 {
2214 	if (hba->clk_gating.delay_attr.attr.name)
2215 		device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
2216 	if (hba->clk_gating.enable_attr.attr.name)
2217 		device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
2218 }
2219 
2220 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
2221 {
2222 	if (!ufshcd_is_clkgating_allowed(hba))
2223 		return;
2224 
2225 	hba->clk_gating.state = CLKS_ON;
2226 
2227 	hba->clk_gating.delay_ms = 150;
2228 	INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
2229 	INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
2230 
2231 	hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(
2232 		"ufs_clk_gating_%d", WQ_MEM_RECLAIM | WQ_HIGHPRI,
2233 		hba->host->host_no);
2234 
2235 	ufshcd_init_clk_gating_sysfs(hba);
2236 
2237 	hba->clk_gating.is_enabled = true;
2238 	hba->clk_gating.is_initialized = true;
2239 }
2240 
2241 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
2242 {
2243 	if (!hba->clk_gating.is_initialized)
2244 		return;
2245 
2246 	ufshcd_remove_clk_gating_sysfs(hba);
2247 
2248 	/* Ungate the clock if necessary. */
2249 	ufshcd_hold(hba);
2250 	hba->clk_gating.is_initialized = false;
2251 	ufshcd_release(hba);
2252 
2253 	destroy_workqueue(hba->clk_gating.clk_gating_workq);
2254 }
2255 
2256 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
2257 {
2258 	bool queue_resume_work = false;
2259 	ktime_t curr_t;
2260 
2261 	if (!ufshcd_is_clkscaling_supported(hba))
2262 		return;
2263 
2264 	curr_t = ktime_get();
2265 
2266 	guard(spinlock_irqsave)(&hba->clk_scaling.lock);
2267 
2268 	if (!hba->clk_scaling.active_reqs++)
2269 		queue_resume_work = true;
2270 
2271 	if (!hba->clk_scaling.is_enabled || hba->pm_op_in_progress)
2272 		return;
2273 
2274 	if (queue_resume_work)
2275 		queue_work(hba->clk_scaling.workq,
2276 			   &hba->clk_scaling.resume_work);
2277 
2278 	if (!hba->clk_scaling.window_start_t) {
2279 		hba->clk_scaling.window_start_t = curr_t;
2280 		hba->clk_scaling.tot_busy_t = 0;
2281 		hba->clk_scaling.is_busy_started = false;
2282 	}
2283 
2284 	if (!hba->clk_scaling.is_busy_started) {
2285 		hba->clk_scaling.busy_start_t = curr_t;
2286 		hba->clk_scaling.is_busy_started = true;
2287 	}
2288 }
2289 
2290 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
2291 {
2292 	struct ufs_clk_scaling *scaling = &hba->clk_scaling;
2293 
2294 	if (!ufshcd_is_clkscaling_supported(hba))
2295 		return;
2296 
2297 	guard(spinlock_irqsave)(&hba->clk_scaling.lock);
2298 
2299 	hba->clk_scaling.active_reqs--;
2300 	if (!scaling->active_reqs && scaling->is_busy_started) {
2301 		scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
2302 					scaling->busy_start_t));
2303 		scaling->busy_start_t = 0;
2304 		scaling->is_busy_started = false;
2305 	}
2306 }
2307 
2308 static inline int ufshcd_monitor_opcode2dir(u8 opcode)
2309 {
2310 	if (opcode == READ_6 || opcode == READ_10 || opcode == READ_16)
2311 		return READ;
2312 	else if (opcode == WRITE_6 || opcode == WRITE_10 || opcode == WRITE_16)
2313 		return WRITE;
2314 	else
2315 		return -EINVAL;
2316 }
2317 
2318 /* Must only be called for SCSI commands. */
2319 static inline bool ufshcd_should_inform_monitor(struct ufs_hba *hba,
2320 						struct scsi_cmnd *cmd)
2321 {
2322 	const struct ufs_hba_monitor *m = &hba->monitor;
2323 	struct ufshcd_lrb *lrbp = scsi_cmd_priv(cmd);
2324 
2325 	return m->enabled &&
2326 	       (!m->chunk_size || m->chunk_size == cmd->sdb.length) &&
2327 	       ktime_before(hba->monitor.enabled_ts, lrbp->issue_time_stamp);
2328 }
2329 
2330 static void ufshcd_start_monitor(struct ufs_hba *hba, struct scsi_cmnd *cmd)
2331 {
2332 	int dir = ufshcd_monitor_opcode2dir(cmd->cmnd[0]);
2333 	unsigned long flags;
2334 
2335 	spin_lock_irqsave(hba->host->host_lock, flags);
2336 	if (dir >= 0 && hba->monitor.nr_queued[dir]++ == 0)
2337 		hba->monitor.busy_start_ts[dir] = ktime_get();
2338 	spin_unlock_irqrestore(hba->host->host_lock, flags);
2339 }
2340 
2341 static void ufshcd_update_monitor(struct ufs_hba *hba, struct scsi_cmnd *cmd)
2342 {
2343 	struct request *req = scsi_cmd_to_rq(cmd);
2344 	const struct ufshcd_lrb *lrbp = scsi_cmd_priv(cmd);
2345 	int dir = ufshcd_monitor_opcode2dir(cmd->cmnd[0]);
2346 	unsigned long flags;
2347 
2348 	spin_lock_irqsave(hba->host->host_lock, flags);
2349 	if (dir >= 0 && hba->monitor.nr_queued[dir] > 0) {
2350 		struct ufs_hba_monitor *m = &hba->monitor;
2351 		ktime_t now, inc, lat;
2352 
2353 		now = lrbp->compl_time_stamp;
2354 		inc = ktime_sub(now, m->busy_start_ts[dir]);
2355 		m->total_busy[dir] = ktime_add(m->total_busy[dir], inc);
2356 		m->nr_sec_rw[dir] += blk_rq_sectors(req);
2357 
2358 		/* Update latencies */
2359 		m->nr_req[dir]++;
2360 		lat = ktime_sub(now, lrbp->issue_time_stamp);
2361 		m->lat_sum[dir] += lat;
2362 		if (m->lat_max[dir] < lat || !m->lat_max[dir])
2363 			m->lat_max[dir] = lat;
2364 		if (m->lat_min[dir] > lat || !m->lat_min[dir])
2365 			m->lat_min[dir] = lat;
2366 
2367 		m->nr_queued[dir]--;
2368 		/* Push forward the busy start of monitor */
2369 		m->busy_start_ts[dir] = now;
2370 	}
2371 	spin_unlock_irqrestore(hba->host->host_lock, flags);
2372 }
2373 
2374 /* Returns %true for SCSI commands and %false for device management commands. */
2375 static bool ufshcd_is_scsi_cmd(struct scsi_cmnd *cmd)
2376 {
2377 	return !blk_mq_is_reserved_rq(scsi_cmd_to_rq(cmd));
2378 }
2379 
2380 /**
2381  * ufshcd_send_command - Send SCSI or device management commands
2382  * @hba: per adapter instance
2383  * @cmd: SCSI command or device management command pointer
2384  * @hwq: pointer to hardware queue instance
2385  */
2386 static inline void ufshcd_send_command(struct ufs_hba *hba,
2387 				       struct scsi_cmnd *cmd,
2388 				       struct ufs_hw_queue *hwq)
2389 {
2390 	struct ufshcd_lrb *lrbp = scsi_cmd_priv(cmd);
2391 	const int tag = scsi_cmd_to_rq(cmd)->tag;
2392 	unsigned long flags;
2393 
2394 	if (hba->monitor.enabled) {
2395 		lrbp->issue_time_stamp = ktime_get();
2396 		lrbp->issue_time_stamp_local_clock = local_clock();
2397 		lrbp->compl_time_stamp = ktime_set(0, 0);
2398 		lrbp->compl_time_stamp_local_clock = 0;
2399 	}
2400 	if (ufshcd_is_scsi_cmd(cmd)) {
2401 		ufshcd_add_command_trace(hba, cmd, UFS_CMD_SEND);
2402 		ufshcd_clk_scaling_start_busy(hba);
2403 		if (unlikely(ufshcd_should_inform_monitor(hba, cmd)))
2404 			ufshcd_start_monitor(hba, cmd);
2405 	}
2406 
2407 	if (hba->mcq_enabled) {
2408 		int utrd_size = sizeof(struct utp_transfer_req_desc);
2409 		struct utp_transfer_req_desc *src = lrbp->utr_descriptor_ptr;
2410 		struct utp_transfer_req_desc *dest;
2411 
2412 		spin_lock(&hwq->sq_lock);
2413 		dest = hwq->sqe_base_addr + hwq->sq_tail_slot;
2414 		memcpy(dest, src, utrd_size);
2415 		ufshcd_inc_sq_tail(hwq);
2416 		spin_unlock(&hwq->sq_lock);
2417 	} else {
2418 		spin_lock_irqsave(&hba->outstanding_lock, flags);
2419 		if (hba->vops && hba->vops->setup_xfer_req)
2420 			hba->vops->setup_xfer_req(hba, tag,
2421 						  ufshcd_is_scsi_cmd(cmd));
2422 		__set_bit(tag, &hba->outstanding_reqs);
2423 		ufshcd_writel(hba, 1 << tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
2424 		spin_unlock_irqrestore(&hba->outstanding_lock, flags);
2425 	}
2426 }
2427 
2428 /**
2429  * ufshcd_copy_sense_data - Copy sense data in case of check condition
2430  * @cmd: SCSI command
2431  */
2432 static inline void ufshcd_copy_sense_data(struct scsi_cmnd *cmd)
2433 {
2434 	struct ufshcd_lrb *lrbp = scsi_cmd_priv(cmd);
2435 	u8 *const sense_buffer = cmd->sense_buffer;
2436 	u16 resp_len;
2437 	int len;
2438 
2439 	resp_len = be16_to_cpu(lrbp->ucd_rsp_ptr->header.data_segment_length);
2440 	if (sense_buffer && resp_len) {
2441 		int len_to_copy;
2442 
2443 		len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
2444 		len_to_copy = min_t(int, UFS_SENSE_SIZE, len);
2445 
2446 		memcpy(sense_buffer, lrbp->ucd_rsp_ptr->sr.sense_data,
2447 		       len_to_copy);
2448 	}
2449 }
2450 
2451 /**
2452  * ufshcd_copy_query_response() - Copy the Query Response and the data
2453  * descriptor
2454  * @hba: per adapter instance
2455  * @lrbp: pointer to local reference block
2456  *
2457  * Return: 0 upon success; < 0 upon failure.
2458  */
2459 static
2460 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2461 {
2462 	struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2463 
2464 	memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
2465 
2466 	/* Get the descriptor */
2467 	if (hba->dev_cmd.query.descriptor &&
2468 	    lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
2469 		u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
2470 				GENERAL_UPIU_REQUEST_SIZE;
2471 		u16 resp_len;
2472 		u16 buf_len;
2473 
2474 		/* data segment length */
2475 		resp_len = be16_to_cpu(lrbp->ucd_rsp_ptr->header
2476 				       .data_segment_length);
2477 		buf_len = be16_to_cpu(
2478 				hba->dev_cmd.query.request.upiu_req.length);
2479 		if (likely(buf_len >= resp_len)) {
2480 			memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
2481 		} else {
2482 			dev_warn(hba->dev,
2483 				 "%s: rsp size %d is bigger than buffer size %d",
2484 				 __func__, resp_len, buf_len);
2485 			return -EINVAL;
2486 		}
2487 	}
2488 
2489 	return 0;
2490 }
2491 
2492 /**
2493  * ufshcd_hba_capabilities - Read controller capabilities
2494  * @hba: per adapter instance
2495  *
2496  * Return: 0 on success, negative on error.
2497  */
2498 static inline int ufshcd_hba_capabilities(struct ufs_hba *hba)
2499 {
2500 	int err;
2501 
2502 	hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
2503 
2504 	/* nutrs and nutmrs are 0 based values */
2505 	hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS_SDB) + 1;
2506 	hba->nutmrs =
2507 	((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
2508 
2509 	if (hba->vops && hba->vops->get_hba_nortt)
2510 		hba->nortt = hba->vops->get_hba_nortt(hba);
2511 	else
2512 		hba->nortt = FIELD_GET(MASK_NUMBER_OUTSTANDING_RTT, hba->capabilities) + 1;
2513 
2514 	/* Read crypto capabilities */
2515 	err = ufshcd_hba_init_crypto_capabilities(hba);
2516 	if (err) {
2517 		dev_err(hba->dev, "crypto setup failed\n");
2518 		return err;
2519 	}
2520 
2521 	/*
2522 	 * The UFSHCI 3.0 specification does not define MCQ_SUPPORT and
2523 	 * LSDB_SUPPORT, but [31:29] as reserved bits with reset value 0s, which
2524 	 * means we can simply read values regardless of version.
2525 	 */
2526 	hba->mcq_sup = FIELD_GET(MASK_MCQ_SUPPORT, hba->capabilities);
2527 	/*
2528 	 * 0h: legacy single doorbell support is available
2529 	 * 1h: indicate that legacy single doorbell support has been removed
2530 	 */
2531 	if (!(hba->quirks & UFSHCD_QUIRK_BROKEN_LSDBS_CAP))
2532 		hba->lsdb_sup = !FIELD_GET(MASK_LSDB_SUPPORT, hba->capabilities);
2533 	else
2534 		hba->lsdb_sup = true;
2535 
2536 	hba->mcq_capabilities = ufshcd_readl(hba, REG_MCQCAP);
2537 
2538 	return 0;
2539 }
2540 
2541 /**
2542  * ufshcd_ready_for_uic_cmd - Check if controller is ready
2543  *                            to accept UIC commands
2544  * @hba: per adapter instance
2545  *
2546  * Return: true on success, else false.
2547  */
2548 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
2549 {
2550 	u32 val;
2551 	int ret = read_poll_timeout(ufshcd_readl, val, val & UIC_COMMAND_READY,
2552 				    500, uic_cmd_timeout * 1000, false, hba,
2553 				    REG_CONTROLLER_STATUS);
2554 	return ret == 0;
2555 }
2556 
2557 /**
2558  * ufshcd_get_upmcrs - Get the power mode change request status
2559  * @hba: Pointer to adapter instance
2560  *
2561  * This function gets the UPMCRS field of HCS register
2562  *
2563  * Return: value of UPMCRS field.
2564  */
2565 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
2566 {
2567 	return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
2568 }
2569 
2570 /**
2571  * ufshcd_dispatch_uic_cmd - Dispatch an UIC command to the Unipro layer
2572  * @hba: per adapter instance
2573  * @uic_cmd: UIC command
2574  */
2575 static inline void
2576 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2577 {
2578 	lockdep_assert_held(&hba->uic_cmd_mutex);
2579 
2580 	WARN_ON(hba->active_uic_cmd);
2581 	WARN_ON_ONCE(uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT);
2582 
2583 	hba->active_uic_cmd = uic_cmd;
2584 
2585 	/* Write Args */
2586 	ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2587 	ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2588 	ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2589 
2590 	ufshcd_add_uic_command_trace(hba, uic_cmd, UFS_CMD_SEND);
2591 
2592 	/* Write UIC Cmd */
2593 	ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2594 		      REG_UIC_COMMAND);
2595 }
2596 
2597 /**
2598  * ufshcd_wait_for_uic_cmd - Wait for completion of an UIC command
2599  * @hba: per adapter instance
2600  * @uic_cmd: UIC command
2601  *
2602  * Return: 0 only if success.
2603  */
2604 static int
2605 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2606 {
2607 	int ret;
2608 	unsigned long flags;
2609 
2610 	lockdep_assert_held(&hba->uic_cmd_mutex);
2611 
2612 	if (wait_for_completion_timeout(&uic_cmd->done,
2613 					msecs_to_jiffies(uic_cmd_timeout))) {
2614 		ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2615 	} else {
2616 		ret = -ETIMEDOUT;
2617 		dev_err(hba->dev,
2618 			"uic cmd 0x%x with arg3 0x%x completion timeout\n",
2619 			uic_cmd->command, uic_cmd->argument3);
2620 
2621 		if (!uic_cmd->cmd_active) {
2622 			dev_err(hba->dev, "%s: UIC cmd has been completed, return the result\n",
2623 				__func__);
2624 			ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2625 		}
2626 	}
2627 
2628 	spin_lock_irqsave(hba->host->host_lock, flags);
2629 	hba->active_uic_cmd = NULL;
2630 	spin_unlock_irqrestore(hba->host->host_lock, flags);
2631 
2632 	return ret;
2633 }
2634 
2635 /**
2636  * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2637  * @hba: per adapter instance
2638  * @uic_cmd: UIC command
2639  *
2640  * Return: 0 if successful; < 0 upon failure.
2641  */
2642 static int
2643 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2644 {
2645 	lockdep_assert_held(&hba->uic_cmd_mutex);
2646 
2647 	if (!ufshcd_ready_for_uic_cmd(hba)) {
2648 		dev_err(hba->dev,
2649 			"Controller not ready to accept UIC commands\n");
2650 		return -EIO;
2651 	}
2652 
2653 	init_completion(&uic_cmd->done);
2654 
2655 	uic_cmd->cmd_active = true;
2656 	ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2657 
2658 	return 0;
2659 }
2660 
2661 /**
2662  * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2663  * @hba: per adapter instance
2664  * @uic_cmd: UIC command
2665  *
2666  * Return: 0 only if success.
2667  */
2668 int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2669 {
2670 	unsigned long flags;
2671 	int ret;
2672 
2673 	if (hba->quirks & UFSHCD_QUIRK_BROKEN_UIC_CMD)
2674 		return 0;
2675 
2676 	ufshcd_hold(hba);
2677 	mutex_lock(&hba->uic_cmd_mutex);
2678 	ufshcd_add_delay_before_dme_cmd(hba);
2679 
2680 	spin_lock_irqsave(hba->host->host_lock, flags);
2681 	ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
2682 	spin_unlock_irqrestore(hba->host->host_lock, flags);
2683 
2684 	ret = __ufshcd_send_uic_cmd(hba, uic_cmd);
2685 	if (!ret)
2686 		ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2687 
2688 	mutex_unlock(&hba->uic_cmd_mutex);
2689 
2690 	ufshcd_release(hba);
2691 	return ret;
2692 }
2693 
2694 /**
2695  * ufshcd_sgl_to_prdt - SG list to PRTD (Physical Region Description Table, 4DW format)
2696  * @hba:	per-adapter instance
2697  * @lrbp:	pointer to local reference block
2698  * @sg_entries:	The number of sg lists actually used
2699  * @sg_list:	Pointer to SG list
2700  */
2701 static void ufshcd_sgl_to_prdt(struct ufs_hba *hba, struct ufshcd_lrb *lrbp, int sg_entries,
2702 			       struct scatterlist *sg_list)
2703 {
2704 	struct ufshcd_sg_entry *prd;
2705 	struct scatterlist *sg;
2706 	int i;
2707 
2708 	if (sg_entries) {
2709 
2710 		if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2711 			lrbp->utr_descriptor_ptr->prd_table_length =
2712 				cpu_to_le16(sg_entries * ufshcd_sg_entry_size(hba));
2713 		else
2714 			lrbp->utr_descriptor_ptr->prd_table_length = cpu_to_le16(sg_entries);
2715 
2716 		prd = lrbp->ucd_prdt_ptr;
2717 
2718 		for_each_sg(sg_list, sg, sg_entries, i) {
2719 			const unsigned int len = sg_dma_len(sg);
2720 
2721 			/*
2722 			 * From the UFSHCI spec: "Data Byte Count (DBC): A '0'
2723 			 * based value that indicates the length, in bytes, of
2724 			 * the data block. A maximum of length of 256KB may
2725 			 * exist for any entry. Bits 1:0 of this field shall be
2726 			 * 11b to indicate Dword granularity. A value of '3'
2727 			 * indicates 4 bytes, '7' indicates 8 bytes, etc."
2728 			 */
2729 			WARN_ONCE(len > SZ_256K, "len = %#x\n", len);
2730 			prd->size = cpu_to_le32(len - 1);
2731 			prd->addr = cpu_to_le64(sg->dma_address);
2732 			prd->reserved = 0;
2733 			prd = (void *)prd + ufshcd_sg_entry_size(hba);
2734 		}
2735 	} else {
2736 		lrbp->utr_descriptor_ptr->prd_table_length = 0;
2737 	}
2738 }
2739 
2740 /**
2741  * ufshcd_map_sg - Map scatter-gather list to prdt
2742  * @hba: per adapter instance
2743  * @cmd: SCSI command
2744  *
2745  * Return: 0 in case of success, non-zero value in case of failure.
2746  */
2747 static int ufshcd_map_sg(struct ufs_hba *hba, struct scsi_cmnd *cmd)
2748 {
2749 	struct ufshcd_lrb *lrbp = scsi_cmd_priv(cmd);
2750 	int sg_segments = scsi_dma_map(cmd);
2751 
2752 	if (sg_segments < 0)
2753 		return sg_segments;
2754 
2755 	ufshcd_sgl_to_prdt(hba, lrbp, sg_segments, scsi_sglist(cmd));
2756 
2757 	return ufshcd_crypto_fill_prdt(hba, cmd);
2758 }
2759 
2760 /**
2761  * ufshcd_prepare_req_desc_hdr - Fill UTP Transfer request descriptor header according to request
2762  * descriptor according to request
2763  * @hba: per adapter instance
2764  * @lrbp: pointer to local reference block
2765  * @upiu_flags: flags required in the header
2766  * @cmd_dir: requests data direction
2767  * @ehs_length: Total EHS Length (in 32‐bytes units of all Extra Header Segments)
2768  */
2769 static void
2770 ufshcd_prepare_req_desc_hdr(struct ufs_hba *hba, struct ufshcd_lrb *lrbp,
2771 			    u8 *upiu_flags, enum dma_data_direction cmd_dir,
2772 			    int ehs_length)
2773 {
2774 	struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2775 	struct request_desc_header *h = &req_desc->header;
2776 	enum utp_data_direction data_direction;
2777 
2778 	lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2779 
2780 	*h = (typeof(*h)){ };
2781 
2782 	if (cmd_dir == DMA_FROM_DEVICE) {
2783 		data_direction = UTP_DEVICE_TO_HOST;
2784 		*upiu_flags = UPIU_CMD_FLAGS_READ;
2785 	} else if (cmd_dir == DMA_TO_DEVICE) {
2786 		data_direction = UTP_HOST_TO_DEVICE;
2787 		*upiu_flags = UPIU_CMD_FLAGS_WRITE;
2788 	} else {
2789 		data_direction = UTP_NO_DATA_TRANSFER;
2790 		*upiu_flags = UPIU_CMD_FLAGS_NONE;
2791 	}
2792 
2793 	h->command_type = lrbp->command_type;
2794 	h->data_direction = data_direction;
2795 	h->ehs_length = ehs_length;
2796 
2797 	if (lrbp->intr_cmd)
2798 		h->interrupt = 1;
2799 
2800 	/* Prepare crypto related dwords */
2801 	ufshcd_prepare_req_desc_hdr_crypto(lrbp, h);
2802 
2803 	/*
2804 	 * assigning invalid value for command status. Controller
2805 	 * updates OCS on command completion, with the command
2806 	 * status
2807 	 */
2808 	h->ocs = OCS_INVALID_COMMAND_STATUS;
2809 
2810 	req_desc->prd_table_length = 0;
2811 }
2812 
2813 /**
2814  * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2815  * for scsi commands
2816  * @cmd: SCSI command
2817  * @upiu_flags: flags
2818  */
2819 static void ufshcd_prepare_utp_scsi_cmd_upiu(struct scsi_cmnd *cmd,
2820 					     u8 upiu_flags)
2821 {
2822 	struct ufshcd_lrb *lrbp = scsi_cmd_priv(cmd);
2823 	const int tag = scsi_cmd_to_rq(cmd)->tag;
2824 	struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2825 	unsigned short cdb_len;
2826 
2827 	ucd_req_ptr->header = (struct utp_upiu_header){
2828 		.transaction_code = UPIU_TRANSACTION_COMMAND,
2829 		.flags = upiu_flags,
2830 		.lun = lrbp->lun,
2831 		.task_tag = tag,
2832 		.command_set_type = UPIU_COMMAND_SET_TYPE_SCSI,
2833 	};
2834 
2835 	WARN_ON_ONCE(ucd_req_ptr->header.task_tag != tag);
2836 
2837 	ucd_req_ptr->sc.exp_data_transfer_len = cpu_to_be32(cmd->sdb.length);
2838 
2839 	cdb_len = min_t(unsigned short, cmd->cmd_len, UFS_CDB_SIZE);
2840 	memcpy(ucd_req_ptr->sc.cdb, cmd->cmnd, cdb_len);
2841 
2842 	memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2843 }
2844 
2845 /**
2846  * ufshcd_prepare_utp_query_req_upiu() - fill the utp_transfer_req_desc for query request
2847  * @hba: UFS hba
2848  * @cmd: SCSI command pointer
2849  * @upiu_flags: flags
2850  */
2851 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2852 				struct scsi_cmnd *cmd, u8 upiu_flags)
2853 {
2854 	struct ufshcd_lrb *lrbp = scsi_cmd_priv(cmd);
2855 	struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2856 	const int tag = scsi_cmd_to_rq(cmd)->tag;
2857 	struct ufs_query *query = &hba->dev_cmd.query;
2858 	u16 len = be16_to_cpu(query->request.upiu_req.length);
2859 
2860 	/* Query request header */
2861 	ucd_req_ptr->header = (struct utp_upiu_header){
2862 		.transaction_code = UPIU_TRANSACTION_QUERY_REQ,
2863 		.flags = upiu_flags,
2864 		.lun = lrbp->lun,
2865 		.task_tag = tag,
2866 		.query_function = query->request.query_func,
2867 		/* Data segment length only need for WRITE_DESC */
2868 		.data_segment_length =
2869 			query->request.upiu_req.opcode ==
2870 					UPIU_QUERY_OPCODE_WRITE_DESC ?
2871 				cpu_to_be16(len) :
2872 				0,
2873 	};
2874 
2875 	/* Copy the Query Request buffer as is */
2876 	memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2877 			QUERY_OSF_SIZE);
2878 
2879 	/* Copy the Descriptor */
2880 	if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2881 		memcpy(ucd_req_ptr + 1, query->descriptor, len);
2882 }
2883 
2884 static inline void ufshcd_prepare_utp_nop_upiu(struct scsi_cmnd *cmd)
2885 {
2886 	struct ufshcd_lrb *lrbp = scsi_cmd_priv(cmd);
2887 	struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2888 	const int tag = scsi_cmd_to_rq(cmd)->tag;
2889 
2890 	memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2891 
2892 	ucd_req_ptr->header = (struct utp_upiu_header){
2893 		.transaction_code = UPIU_TRANSACTION_NOP_OUT,
2894 		.task_tag = tag,
2895 	};
2896 }
2897 
2898 /**
2899  * ufshcd_compose_devman_upiu - UFS Protocol Information Unit(UPIU)
2900  *			     for Device Management Purposes
2901  * @hba: per adapter instance
2902  * @cmd: SCSI command pointer
2903  *
2904  * Return: 0 upon success; < 0 upon failure.
2905  */
2906 static int ufshcd_compose_devman_upiu(struct ufs_hba *hba,
2907 				      struct scsi_cmnd *cmd)
2908 {
2909 	struct ufshcd_lrb *lrbp = scsi_cmd_priv(cmd);
2910 	u8 upiu_flags;
2911 	int ret = 0;
2912 
2913 	ufshcd_prepare_req_desc_hdr(hba, lrbp, &upiu_flags, DMA_NONE, 0);
2914 
2915 	if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2916 		ufshcd_prepare_utp_query_req_upiu(hba, cmd, upiu_flags);
2917 	else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2918 		ufshcd_prepare_utp_nop_upiu(cmd);
2919 	else
2920 		ret = -EINVAL;
2921 
2922 	memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2923 
2924 	return ret;
2925 }
2926 
2927 /**
2928  * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2929  *			   for SCSI Purposes
2930  * @hba: per adapter instance
2931  * @cmd: SCSI command
2932  */
2933 static void ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct scsi_cmnd *cmd)
2934 {
2935 	struct ufshcd_lrb *lrbp = scsi_cmd_priv(cmd);
2936 	struct request *rq = scsi_cmd_to_rq(cmd);
2937 	unsigned int ioprio_class = IOPRIO_PRIO_CLASS(req_get_ioprio(rq));
2938 	u8 upiu_flags;
2939 
2940 	ufshcd_prepare_req_desc_hdr(hba, lrbp, &upiu_flags,
2941 				    cmd->sc_data_direction, 0);
2942 	if (ioprio_class == IOPRIO_CLASS_RT)
2943 		upiu_flags |= UPIU_CMD_FLAGS_CP;
2944 	ufshcd_prepare_utp_scsi_cmd_upiu(cmd, upiu_flags);
2945 }
2946 
2947 static void ufshcd_init_lrb(struct ufs_hba *hba, struct scsi_cmnd *cmd)
2948 {
2949 	const int i = scsi_cmd_to_rq(cmd)->tag;
2950 	struct utp_transfer_req_desc *utrdlp = hba->utrdl_base_addr;
2951 	u16 response_offset = le16_to_cpu(utrdlp[i].response_upiu_offset);
2952 	u16 prdt_offset = le16_to_cpu(utrdlp[i].prd_table_offset);
2953 	struct ufshcd_lrb *lrb = scsi_cmd_priv(cmd);
2954 	u8 *command_upiu, *response_upiu, *prd_table;
2955 	dma_addr_t cmd_desc_element_addr;
2956 
2957 	/* The reserved tag uses a dedicated UCD outside the pool. */
2958 	if (unlikely(blk_mq_is_reserved_rq(scsi_cmd_to_rq(cmd)))) {
2959 		struct utp_devman_cmd_desc *cmd_descp = hba->devman_ucd_base_addr;
2960 
2961 		cmd_desc_element_addr = hba->devman_ucd_dma_addr;
2962 		command_upiu = cmd_descp->command_upiu;
2963 		response_upiu = cmd_descp->response_upiu;
2964 		prd_table = cmd_descp->prd_table;
2965 	} else {
2966 		int slot = i - UFSHCD_NUM_RESERVED;
2967 		struct utp_transfer_cmd_desc *cmd_descp;
2968 
2969 		/* Non-reserved tags start at UFSHCD_NUM_RESERVED, so slot >= 0. */
2970 		WARN_ON_ONCE(slot < 0);
2971 		cmd_descp = (void *)hba->ucdl_base_addr + slot * ufshcd_get_ucd_size(hba);
2972 
2973 		cmd_desc_element_addr =
2974 			hba->ucdl_dma_addr + slot * ufshcd_get_ucd_size(hba);
2975 		command_upiu = cmd_descp->command_upiu;
2976 		response_upiu = cmd_descp->response_upiu;
2977 		prd_table = cmd_descp->prd_table;
2978 	}
2979 
2980 	lrb->utr_descriptor_ptr = utrdlp + i;
2981 	lrb->utrd_dma_addr =
2982 		hba->utrdl_dma_addr + i * sizeof(struct utp_transfer_req_desc);
2983 	lrb->ucd_req_ptr = (struct utp_upiu_req *)command_upiu;
2984 	lrb->ucd_req_dma_addr = cmd_desc_element_addr;
2985 	lrb->ucd_rsp_ptr = (struct utp_upiu_rsp *)response_upiu;
2986 	lrb->ucd_rsp_dma_addr = cmd_desc_element_addr + response_offset;
2987 	lrb->ucd_prdt_ptr = (struct ufshcd_sg_entry *)prd_table;
2988 	lrb->ucd_prdt_dma_addr = cmd_desc_element_addr + prdt_offset;
2989 }
2990 
2991 static void __ufshcd_setup_cmd(struct ufs_hba *hba, struct scsi_cmnd *cmd,
2992 			       u8 lun, int tag)
2993 {
2994 	struct ufshcd_lrb *lrbp = scsi_cmd_priv(cmd);
2995 
2996 	ufshcd_init_lrb(hba, cmd);
2997 
2998 	memset(lrbp->ucd_req_ptr, 0, sizeof(*lrbp->ucd_req_ptr));
2999 
3000 	lrbp->lun = lun;
3001 	ufshcd_prepare_lrbp_crypto(ufshcd_is_scsi_cmd(cmd) ?
3002 				   scsi_cmd_to_rq(cmd) : NULL, lrbp);
3003 }
3004 
3005 static void ufshcd_setup_scsi_cmd(struct ufs_hba *hba, struct scsi_cmnd *cmd,
3006 				  u8 lun, int tag)
3007 {
3008 	struct ufshcd_lrb *lrbp = scsi_cmd_priv(cmd);
3009 
3010 	__ufshcd_setup_cmd(hba, cmd, lun, tag);
3011 	lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba);
3012 	lrbp->req_abort_skip = false;
3013 
3014 	ufshcd_comp_scsi_upiu(hba, cmd);
3015 }
3016 
3017 /**
3018  * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
3019  * @upiu_wlun_id: UPIU W-LUN id
3020  *
3021  * Return: SCSI W-LUN id.
3022  */
3023 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
3024 {
3025 	return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
3026 }
3027 
3028 static inline bool is_device_wlun(struct scsi_device *sdev)
3029 {
3030 	return sdev->lun ==
3031 		ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN);
3032 }
3033 
3034 /*
3035  * Associate the UFS controller queue with the default and poll HCTX types.
3036  * Initialize the mq_map[] arrays.
3037  */
3038 static void ufshcd_map_queues(struct Scsi_Host *shost)
3039 {
3040 	struct ufs_hba *hba = shost_priv(shost);
3041 	int i, queue_offset = 0;
3042 
3043 	if (!is_mcq_supported(hba)) {
3044 		hba->nr_queues[HCTX_TYPE_DEFAULT] = 1;
3045 		hba->nr_queues[HCTX_TYPE_READ] = 0;
3046 		hba->nr_queues[HCTX_TYPE_POLL] = 1;
3047 		hba->nr_hw_queues = 1;
3048 	}
3049 
3050 	for (i = 0; i < shost->nr_maps; i++) {
3051 		struct blk_mq_queue_map *map = &shost->tag_set.map[i];
3052 
3053 		map->nr_queues = hba->nr_queues[i];
3054 		if (!map->nr_queues)
3055 			continue;
3056 		map->queue_offset = queue_offset;
3057 		if (i == HCTX_TYPE_POLL && !is_mcq_supported(hba))
3058 			map->queue_offset = 0;
3059 
3060 		blk_mq_map_queues(map);
3061 		queue_offset += map->nr_queues;
3062 	}
3063 }
3064 
3065 /*
3066  * The only purpose of this function is to make the SCSI core skip the memset()
3067  * call for the private command data.
3068  */
3069 static int ufshcd_init_cmd_priv(struct Scsi_Host *host, struct scsi_cmnd *cmd)
3070 {
3071 	return 0;
3072 }
3073 
3074 /**
3075  * ufshcd_queuecommand - main entry point for SCSI requests
3076  * @host: SCSI host pointer
3077  * @cmd: command from SCSI Midlayer
3078  *
3079  * Return: 0 for success, non-zero in case of failure.
3080  */
3081 static enum scsi_qc_status ufshcd_queuecommand(struct Scsi_Host *host,
3082 					       struct scsi_cmnd *cmd)
3083 {
3084 	struct ufs_hba *hba = shost_priv(host);
3085 	int tag = scsi_cmd_to_rq(cmd)->tag;
3086 	int err = 0;
3087 	struct ufs_hw_queue *hwq = NULL;
3088 
3089 	switch (hba->ufshcd_state) {
3090 	case UFSHCD_STATE_OPERATIONAL:
3091 		break;
3092 	case UFSHCD_STATE_EH_SCHEDULED_NON_FATAL:
3093 		/*
3094 		 * SCSI error handler can call ->queuecommand() while UFS error
3095 		 * handler is in progress. Error interrupts could change the
3096 		 * state from UFSHCD_STATE_RESET to
3097 		 * UFSHCD_STATE_EH_SCHEDULED_NON_FATAL. Prevent requests
3098 		 * being issued in that case.
3099 		 */
3100 		if (ufshcd_eh_in_progress(hba)) {
3101 			err = SCSI_MLQUEUE_HOST_BUSY;
3102 			goto out;
3103 		}
3104 		break;
3105 	case UFSHCD_STATE_EH_SCHEDULED_FATAL:
3106 		/*
3107 		 * pm_runtime_get_sync() is used at error handling preparation
3108 		 * stage. If a scsi cmd, e.g. the SSU cmd, is sent from hba's
3109 		 * PM ops, it can never be finished if we let SCSI layer keep
3110 		 * retrying it, which gets err handler stuck forever. Neither
3111 		 * can we let the scsi cmd pass through, because UFS is in bad
3112 		 * state, the scsi cmd may eventually time out, which will get
3113 		 * err handler blocked for too long. So, just fail the scsi cmd
3114 		 * sent from PM ops, err handler can recover PM error anyways.
3115 		 */
3116 		if (hba->pm_op_in_progress) {
3117 			hba->force_reset = true;
3118 			set_host_byte(cmd, DID_BAD_TARGET);
3119 			scsi_done(cmd);
3120 			goto out;
3121 		}
3122 		fallthrough;
3123 	case UFSHCD_STATE_RESET:
3124 		err = SCSI_MLQUEUE_HOST_BUSY;
3125 		goto out;
3126 	case UFSHCD_STATE_ERROR:
3127 		set_host_byte(cmd, DID_ERROR);
3128 		scsi_done(cmd);
3129 		goto out;
3130 	}
3131 
3132 	hba->req_abort_count = 0;
3133 
3134 	ufshcd_hold(hba);
3135 
3136 	ufshcd_setup_scsi_cmd(hba, cmd,
3137 			      ufshcd_scsi_to_upiu_lun(cmd->device->lun), tag);
3138 
3139 	err = ufshcd_map_sg(hba, cmd);
3140 	if (err) {
3141 		ufshcd_release(hba);
3142 		goto out;
3143 	}
3144 
3145 	if (hba->mcq_enabled)
3146 		hwq = ufshcd_mcq_req_to_hwq(hba, scsi_cmd_to_rq(cmd));
3147 
3148 	ufshcd_send_command(hba, cmd, hwq);
3149 
3150 out:
3151 	if (ufs_trigger_eh(hba)) {
3152 		unsigned long flags;
3153 
3154 		spin_lock_irqsave(hba->host->host_lock, flags);
3155 		ufshcd_schedule_eh_work(hba);
3156 		spin_unlock_irqrestore(hba->host->host_lock, flags);
3157 	}
3158 
3159 	return err;
3160 }
3161 
3162 static enum scsi_qc_status ufshcd_queue_reserved_command(struct Scsi_Host *host,
3163 							 struct scsi_cmnd *cmd)
3164 {
3165 	struct ufshcd_lrb *lrbp = scsi_cmd_priv(cmd);
3166 	struct request *rq = scsi_cmd_to_rq(cmd);
3167 	struct ufs_hba *hba = shost_priv(host);
3168 	struct ufs_hw_queue *hwq =
3169 		hba->mcq_enabled ? ufshcd_mcq_req_to_hwq(hba, rq) : NULL;
3170 
3171 	ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
3172 	ufshcd_send_command(hba, cmd, hwq);
3173 	return 0;
3174 }
3175 
3176 static void ufshcd_setup_dev_cmd(struct ufs_hba *hba, struct scsi_cmnd *cmd,
3177 				 enum dev_cmd_type cmd_type, u8 lun, int tag)
3178 {
3179 	struct ufshcd_lrb *lrbp = scsi_cmd_priv(cmd);
3180 
3181 	__ufshcd_setup_cmd(hba, cmd, lun, tag);
3182 	lrbp->intr_cmd = true; /* No interrupt aggregation */
3183 	hba->dev_cmd.type = cmd_type;
3184 	hba->dev_cmd.tag = tag;
3185 }
3186 
3187 /*
3188  * Return: 0 upon success; < 0 upon failure.
3189  */
3190 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba, struct scsi_cmnd *cmd,
3191 				  enum dev_cmd_type cmd_type, int tag)
3192 {
3193 	ufshcd_setup_dev_cmd(hba, cmd, cmd_type, 0, tag);
3194 
3195 	return ufshcd_compose_devman_upiu(hba, cmd);
3196 }
3197 
3198 /*
3199  * Check with the block layer if the command is inflight
3200  * @cmd: command to check.
3201  *
3202  * Return: true if command is inflight; false if not.
3203  */
3204 bool ufshcd_cmd_inflight(struct scsi_cmnd *cmd)
3205 {
3206 	return cmd && blk_mq_rq_state(scsi_cmd_to_rq(cmd)) == MQ_RQ_IN_FLIGHT;
3207 }
3208 
3209 /*
3210  * Clear the pending command in the controller and wait until
3211  * the controller confirms that the command has been cleared.
3212  * @hba: per adapter instance
3213  * @task_tag: The tag number of the command to be cleared.
3214  */
3215 static int ufshcd_clear_cmd(struct ufs_hba *hba, u32 task_tag)
3216 {
3217 	u32 mask;
3218 	int err;
3219 
3220 	if (hba->mcq_enabled) {
3221 		/*
3222 		 * MCQ mode. Clean up the MCQ resources similar to
3223 		 * what the ufshcd_utrl_clear() does for SDB mode.
3224 		 */
3225 		err = ufshcd_mcq_sq_cleanup(hba, task_tag);
3226 		if (err) {
3227 			dev_err(hba->dev, "%s: failed tag=%d. err=%d\n",
3228 				__func__, task_tag, err);
3229 			return err;
3230 		}
3231 		return 0;
3232 	}
3233 
3234 	mask = 1U << task_tag;
3235 
3236 	/* clear outstanding transaction before retry */
3237 	ufshcd_utrl_clear(hba, mask);
3238 
3239 	/*
3240 	 * wait for h/w to clear corresponding bit in door-bell.
3241 	 * max. wait is 1 sec.
3242 	 */
3243 	return ufshcd_wait_for_register(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL,
3244 					mask, ~mask, 1000, 1000);
3245 }
3246 
3247 /**
3248  * ufshcd_dev_cmd_completion() - handles device management command responses
3249  * @hba: per adapter instance
3250  * @lrbp: pointer to local reference block
3251  *
3252  * Return: 0 upon success; < 0 upon failure.
3253  */
3254 static int
3255 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
3256 {
3257 	enum upiu_response_transaction resp;
3258 	int err = 0;
3259 
3260 	hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
3261 	resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
3262 
3263 	switch (resp) {
3264 	case UPIU_TRANSACTION_NOP_IN:
3265 		if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
3266 			err = -EINVAL;
3267 			dev_err(hba->dev, "%s: unexpected response %x\n",
3268 					__func__, resp);
3269 		}
3270 		break;
3271 	case UPIU_TRANSACTION_QUERY_RSP: {
3272 		u8 response = lrbp->ucd_rsp_ptr->header.response;
3273 
3274 		if (response == 0) {
3275 			err = ufshcd_copy_query_response(hba, lrbp);
3276 		} else {
3277 			err = -EINVAL;
3278 			dev_err(hba->dev, "%s: unexpected response in Query RSP: %x\n",
3279 					__func__, response);
3280 		}
3281 		break;
3282 	}
3283 	case UPIU_TRANSACTION_REJECT_UPIU:
3284 		/* TODO: handle Reject UPIU Response */
3285 		err = -EPERM;
3286 		dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
3287 				__func__);
3288 		break;
3289 	case UPIU_TRANSACTION_RESPONSE:
3290 		if (hba->dev_cmd.type != DEV_CMD_TYPE_RPMB) {
3291 			err = -EINVAL;
3292 			dev_err(hba->dev, "%s: unexpected response %x\n", __func__, resp);
3293 		}
3294 		break;
3295 	default:
3296 		err = -EINVAL;
3297 		dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
3298 				__func__, resp);
3299 		break;
3300 	}
3301 
3302 	WARN_ONCE(err > 0, "Incorrect return value %d > 0\n", err);
3303 	return err;
3304 }
3305 
3306 static void ufshcd_dev_man_lock(struct ufs_hba *hba)
3307 {
3308 	ufshcd_hold(hba);
3309 	mutex_lock(&hba->dev_cmd.lock);
3310 	down_read(&hba->clk_scaling_lock);
3311 }
3312 
3313 static void ufshcd_dev_man_unlock(struct ufs_hba *hba)
3314 {
3315 	up_read(&hba->clk_scaling_lock);
3316 	mutex_unlock(&hba->dev_cmd.lock);
3317 	ufshcd_release(hba);
3318 }
3319 
3320 static struct scsi_cmnd *ufshcd_get_dev_mgmt_cmd(struct ufs_hba *hba)
3321 {
3322 	/*
3323 	 * The caller must hold this lock to guarantee that the NOWAIT
3324 	 * allocation will succeed.
3325 	 */
3326 	lockdep_assert_held(&hba->dev_cmd.lock);
3327 
3328 	return scsi_get_internal_cmd(
3329 		hba->host->pseudo_sdev, DMA_TO_DEVICE,
3330 		BLK_MQ_REQ_RESERVED | BLK_MQ_REQ_NOWAIT);
3331 }
3332 
3333 static void ufshcd_put_dev_mgmt_cmd(struct scsi_cmnd *cmd)
3334 {
3335 	scsi_put_internal_cmd(cmd);
3336 }
3337 
3338 /*
3339  * Return: 0 upon success; > 0 in case the UFS device reported an OCS error;
3340  * < 0 if another error occurred.
3341  */
3342 static int ufshcd_issue_dev_cmd(struct ufs_hba *hba, struct scsi_cmnd *cmd,
3343 				const u32 tag, int timeout)
3344 {
3345 	struct ufshcd_lrb *lrbp = scsi_cmd_priv(cmd);
3346 	struct request *rq = scsi_cmd_to_rq(cmd);
3347 	blk_status_t sts;
3348 
3349 	rq->timeout = timeout;
3350 	sts = blk_execute_rq(rq, true);
3351 	if (sts != BLK_STS_OK)
3352 		return blk_status_to_errno(sts);
3353 	return lrbp->utr_descriptor_ptr->header.ocs;
3354 }
3355 
3356 /**
3357  * ufshcd_exec_dev_cmd - API for sending device management requests
3358  * @hba: UFS hba
3359  * @cmd_type: specifies the type (NOP, Query...)
3360  * @timeout: timeout in milliseconds
3361  *
3362  * Return: 0 upon success; > 0 in case the UFS device reported an OCS error;
3363  * < 0 if another error occurred.
3364  *
3365  * NOTE: Since there is only one available tag for device management commands,
3366  * it is expected you hold the hba->dev_cmd.lock mutex.
3367  */
3368 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
3369 		enum dev_cmd_type cmd_type, int timeout)
3370 {
3371 	struct scsi_cmnd *cmd = ufshcd_get_dev_mgmt_cmd(hba);
3372 	struct ufshcd_lrb *lrbp = scsi_cmd_priv(cmd);
3373 	u32 tag;
3374 	int err;
3375 
3376 	/* Protects use of hba->dev_cmd. */
3377 	lockdep_assert_held(&hba->dev_cmd.lock);
3378 
3379 	if (WARN_ON_ONCE(!cmd))
3380 		return -ENOMEM;
3381 
3382 	tag = scsi_cmd_to_rq(cmd)->tag;
3383 
3384 	err = ufshcd_compose_dev_cmd(hba, cmd, cmd_type, tag);
3385 	if (unlikely(err))
3386 		goto out;
3387 
3388 	err = ufshcd_issue_dev_cmd(hba, cmd, tag, timeout);
3389 	if (err == 0)
3390 		err = ufshcd_dev_cmd_completion(hba, lrbp);
3391 
3392 out:
3393 	ufshcd_put_dev_mgmt_cmd(cmd);
3394 
3395 	return err;
3396 }
3397 
3398 /**
3399  * ufshcd_init_query() - init the query response and request parameters
3400  * @hba: per-adapter instance
3401  * @request: address of the request pointer to be initialized
3402  * @response: address of the response pointer to be initialized
3403  * @opcode: operation to perform
3404  * @idn: flag idn to access
3405  * @index: LU number to access
3406  * @selector: query/flag/descriptor further identification
3407  */
3408 static inline void ufshcd_init_query(struct ufs_hba *hba,
3409 		struct ufs_query_req **request, struct ufs_query_res **response,
3410 		enum query_opcode opcode, u8 idn, u8 index, u8 selector)
3411 {
3412 	*request = &hba->dev_cmd.query.request;
3413 	*response = &hba->dev_cmd.query.response;
3414 	memset(*request, 0, sizeof(struct ufs_query_req));
3415 	memset(*response, 0, sizeof(struct ufs_query_res));
3416 	(*request)->upiu_req.opcode = opcode;
3417 	(*request)->upiu_req.idn = idn;
3418 	(*request)->upiu_req.index = index;
3419 	(*request)->upiu_req.selector = selector;
3420 }
3421 
3422 /*
3423  * Return: 0 upon success; > 0 in case the UFS device reported an OCS error;
3424  * < 0 if another error occurred.
3425  */
3426 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
3427 	enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res)
3428 {
3429 	int ret;
3430 	int retries;
3431 
3432 	for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
3433 		ret = ufshcd_query_flag(hba, opcode, idn, index, flag_res);
3434 		if (ret)
3435 			dev_dbg(hba->dev,
3436 				"%s: failed with error %d, retries %d\n",
3437 				__func__, ret, retries);
3438 		else
3439 			break;
3440 	}
3441 
3442 	if (ret)
3443 		dev_err(hba->dev,
3444 			"%s: query flag, opcode %d, idn %d, failed with error %d after %d retries\n",
3445 			__func__, opcode, idn, ret, retries);
3446 	return ret;
3447 }
3448 
3449 /**
3450  * ufshcd_query_flag() - API function for sending flag query requests
3451  * @hba: per-adapter instance
3452  * @opcode: flag query to perform
3453  * @idn: flag idn to access
3454  * @index: flag index to access
3455  * @flag_res: the flag value after the query request completes
3456  *
3457  * Return: 0 upon success; > 0 in case the UFS device reported an OCS error;
3458  * < 0 if another error occurred.
3459  */
3460 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
3461 			enum flag_idn idn, u8 index, bool *flag_res)
3462 {
3463 	struct ufs_query_req *request = NULL;
3464 	struct ufs_query_res *response = NULL;
3465 	int err, selector = 0;
3466 	int timeout = dev_cmd_timeout;
3467 
3468 	BUG_ON(!hba);
3469 
3470 	ufshcd_dev_man_lock(hba);
3471 
3472 	ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3473 			selector);
3474 
3475 	switch (opcode) {
3476 	case UPIU_QUERY_OPCODE_SET_FLAG:
3477 	case UPIU_QUERY_OPCODE_CLEAR_FLAG:
3478 	case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
3479 		request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3480 		break;
3481 	case UPIU_QUERY_OPCODE_READ_FLAG:
3482 		request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3483 		if (!flag_res) {
3484 			/* No dummy reads */
3485 			dev_err(hba->dev, "%s: Invalid argument for read request\n",
3486 					__func__);
3487 			err = -EINVAL;
3488 			goto out_unlock;
3489 		}
3490 		break;
3491 	default:
3492 		dev_err(hba->dev,
3493 			"%s: Expected query flag opcode but got = %d\n",
3494 			__func__, opcode);
3495 		err = -EINVAL;
3496 		goto out_unlock;
3497 	}
3498 
3499 	err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
3500 
3501 	if (err) {
3502 		dev_err(hba->dev,
3503 			"%s: Sending flag query for idn %d failed, err = %d\n",
3504 			__func__, idn, err);
3505 		goto out_unlock;
3506 	}
3507 
3508 	if (flag_res)
3509 		*flag_res = (be32_to_cpu(response->upiu_res.value) &
3510 				MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
3511 
3512 out_unlock:
3513 	ufshcd_dev_man_unlock(hba);
3514 	return err;
3515 }
3516 
3517 /**
3518  * ufshcd_query_attr - API function for sending attribute requests
3519  * @hba: per-adapter instance
3520  * @opcode: attribute opcode
3521  * @idn: attribute idn to access
3522  * @index: index field
3523  * @selector: selector field
3524  * @attr_val: the attribute value after the query request completes
3525  *
3526  * Return: 0 upon success; > 0 in case the UFS device reported an OCS error;
3527  * < 0 if another error occurred.
3528  */
3529 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
3530 		      enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
3531 {
3532 	struct ufs_query_req *request = NULL;
3533 	struct ufs_query_res *response = NULL;
3534 	int err;
3535 
3536 	BUG_ON(!hba);
3537 
3538 	if (!attr_val) {
3539 		dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
3540 				__func__, opcode);
3541 		return -EINVAL;
3542 	}
3543 
3544 	ufshcd_dev_man_lock(hba);
3545 
3546 	ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3547 			selector);
3548 
3549 	switch (opcode) {
3550 	case UPIU_QUERY_OPCODE_WRITE_ATTR:
3551 		request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3552 		request->upiu_req.value = cpu_to_be32(*attr_val);
3553 		break;
3554 	case UPIU_QUERY_OPCODE_READ_ATTR:
3555 		request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3556 		break;
3557 	default:
3558 		dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
3559 				__func__, opcode);
3560 		err = -EINVAL;
3561 		goto out_unlock;
3562 	}
3563 
3564 	err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, dev_cmd_timeout);
3565 
3566 	if (err) {
3567 		dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3568 				__func__, opcode, idn, index, err);
3569 		goto out_unlock;
3570 	}
3571 
3572 	*attr_val = be32_to_cpu(response->upiu_res.value);
3573 
3574 out_unlock:
3575 	ufshcd_dev_man_unlock(hba);
3576 	return err;
3577 }
3578 
3579 /**
3580  * ufshcd_query_attr_retry() - API function for sending query
3581  * attribute with retries
3582  * @hba: per-adapter instance
3583  * @opcode: attribute opcode
3584  * @idn: attribute idn to access
3585  * @index: index field
3586  * @selector: selector field
3587  * @attr_val: the attribute value after the query request
3588  * completes
3589  *
3590  * Return: 0 upon success; > 0 in case the UFS device reported an OCS error;
3591  * < 0 if another error occurred.
3592  */
3593 int ufshcd_query_attr_retry(struct ufs_hba *hba,
3594 	enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
3595 	u32 *attr_val)
3596 {
3597 	int ret = 0;
3598 	u32 retries;
3599 
3600 	for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3601 		ret = ufshcd_query_attr(hba, opcode, idn, index,
3602 						selector, attr_val);
3603 		if (ret)
3604 			dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
3605 				__func__, ret, retries);
3606 		else
3607 			break;
3608 	}
3609 
3610 	if (ret)
3611 		dev_err(hba->dev,
3612 			"%s: query attribute, idn %d, failed with error %d after %d retries\n",
3613 			__func__, idn, ret, QUERY_REQ_RETRIES);
3614 	return ret;
3615 }
3616 
3617 /**
3618  * ufshcd_query_attr_qword - Function of sending query requests for quad-word attributes
3619  * @hba: per-adapter instance
3620  * @opcode: attribute opcode
3621  * @idn: attribute idn to access
3622  * @index: index field
3623  * @sel: selector field
3624  * @attr_val: the attribute value after the query request completes
3625  *
3626  * Return: 0 for success, non-zero in case of failure.
3627  */
3628 int ufshcd_query_attr_qword(struct ufs_hba *hba, enum query_opcode opcode,
3629 			    enum attr_idn idn, u8 index, u8 sel, u64 *attr_val)
3630 {
3631 	struct utp_upiu_query_v4_0 *upiu_req;
3632 	struct utp_upiu_query_v4_0 *upiu_resp;
3633 	struct ufs_query_req *request = NULL;
3634 	struct ufs_query_res *response = NULL;
3635 	int err;
3636 
3637 	if (!attr_val) {
3638 		dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
3639 			__func__, opcode);
3640 		return -EINVAL;
3641 	}
3642 
3643 	ufshcd_dev_man_lock(hba);
3644 
3645 	ufshcd_init_query(hba, &request, &response, opcode, idn, index, sel);
3646 
3647 	switch (opcode) {
3648 	case UPIU_QUERY_OPCODE_WRITE_ATTR:
3649 		request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3650 		upiu_req = (struct utp_upiu_query_v4_0 *)&request->upiu_req;
3651 		put_unaligned_be64(*attr_val, &upiu_req->osf3);
3652 		break;
3653 	case UPIU_QUERY_OPCODE_READ_ATTR:
3654 		request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3655 		break;
3656 	default:
3657 		dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
3658 			__func__, opcode);
3659 		err = -EINVAL;
3660 		goto out_unlock;
3661 	}
3662 
3663 	err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, dev_cmd_timeout);
3664 	if (err) {
3665 		dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, selector %d, err = %d\n",
3666 			__func__, opcode, idn, index, sel, err);
3667 		goto out_unlock;
3668 	}
3669 
3670 	upiu_resp = (struct utp_upiu_query_v4_0 *)response;
3671 	*attr_val = get_unaligned_be64(&upiu_resp->osf3);
3672 
3673 out_unlock:
3674 	ufshcd_dev_man_unlock(hba);
3675 	return err;
3676 }
3677 
3678 /*
3679  * Return: 0 upon success; > 0 in case the UFS device reported an OCS error;
3680  * < 0 if another error occurred.
3681  */
3682 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
3683 			enum query_opcode opcode, enum desc_idn idn, u8 index,
3684 			u8 selector, u8 *desc_buf, int *buf_len)
3685 {
3686 	struct ufs_query_req *request = NULL;
3687 	struct ufs_query_res *response = NULL;
3688 	int err;
3689 
3690 	BUG_ON(!hba);
3691 
3692 	if (!desc_buf) {
3693 		dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
3694 				__func__, opcode);
3695 		return -EINVAL;
3696 	}
3697 
3698 	if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
3699 		dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
3700 				__func__, *buf_len);
3701 		return -EINVAL;
3702 	}
3703 
3704 	ufshcd_dev_man_lock(hba);
3705 
3706 	ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3707 			selector);
3708 	hba->dev_cmd.query.descriptor = desc_buf;
3709 	request->upiu_req.length = cpu_to_be16(*buf_len);
3710 
3711 	switch (opcode) {
3712 	case UPIU_QUERY_OPCODE_WRITE_DESC:
3713 		request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3714 		break;
3715 	case UPIU_QUERY_OPCODE_READ_DESC:
3716 		request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3717 		break;
3718 	default:
3719 		dev_err(hba->dev,
3720 				"%s: Expected query descriptor opcode but got = 0x%.2x\n",
3721 				__func__, opcode);
3722 		err = -EINVAL;
3723 		goto out_unlock;
3724 	}
3725 
3726 	err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, dev_cmd_timeout);
3727 
3728 	if (err) {
3729 		dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3730 				__func__, opcode, idn, index, err);
3731 		goto out_unlock;
3732 	}
3733 
3734 	*buf_len = be16_to_cpu(response->upiu_res.length);
3735 
3736 out_unlock:
3737 	hba->dev_cmd.query.descriptor = NULL;
3738 	ufshcd_dev_man_unlock(hba);
3739 	return err;
3740 }
3741 
3742 /**
3743  * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3744  * @hba: per-adapter instance
3745  * @opcode: attribute opcode
3746  * @idn: attribute idn to access
3747  * @index: index field
3748  * @selector: selector field
3749  * @desc_buf: the buffer that contains the descriptor
3750  * @buf_len: length parameter passed to the device
3751  *
3752  * The buf_len parameter will contain, on return, the length parameter
3753  * received on the response.
3754  *
3755  * Return: 0 upon success; > 0 in case the UFS device reported an OCS error;
3756  * < 0 if another error occurred.
3757  */
3758 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3759 				  enum query_opcode opcode,
3760 				  enum desc_idn idn, u8 index,
3761 				  u8 selector,
3762 				  u8 *desc_buf, int *buf_len)
3763 {
3764 	int err;
3765 	int retries;
3766 
3767 	for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3768 		err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3769 						selector, desc_buf, buf_len);
3770 		if (!err || err == -EINVAL)
3771 			break;
3772 	}
3773 
3774 	return err;
3775 }
3776 
3777 /**
3778  * ufshcd_read_desc_param - read the specified descriptor parameter
3779  * @hba: Pointer to adapter instance
3780  * @desc_id: descriptor idn value
3781  * @desc_index: descriptor index
3782  * @param_offset: offset of the parameter to read
3783  * @param_read_buf: pointer to buffer where parameter would be read
3784  * @param_size: sizeof(param_read_buf)
3785  *
3786  * Return: 0 upon success; > 0 in case the UFS device reported an OCS error;
3787  * < 0 if another error occurred.
3788  */
3789 int ufshcd_read_desc_param(struct ufs_hba *hba,
3790 			   enum desc_idn desc_id,
3791 			   int desc_index,
3792 			   u8 param_offset,
3793 			   u8 *param_read_buf,
3794 			   u8 param_size)
3795 {
3796 	int ret;
3797 	u8 *desc_buf;
3798 	int buff_len = QUERY_DESC_MAX_SIZE;
3799 	bool is_kmalloc = true;
3800 
3801 	/* Safety check */
3802 	if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3803 		return -EINVAL;
3804 
3805 	/* Check whether we need temp memory */
3806 	if (param_offset != 0 || param_size < buff_len) {
3807 		desc_buf = kzalloc(buff_len, GFP_KERNEL);
3808 		if (!desc_buf)
3809 			return -ENOMEM;
3810 	} else {
3811 		desc_buf = param_read_buf;
3812 		is_kmalloc = false;
3813 	}
3814 
3815 	/* Request for full descriptor */
3816 	ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3817 					    desc_id, desc_index, 0,
3818 					    desc_buf, &buff_len);
3819 	if (ret) {
3820 		dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d\n",
3821 			__func__, desc_id, desc_index, param_offset, ret);
3822 		goto out;
3823 	}
3824 
3825 	/* Update descriptor length */
3826 	buff_len = desc_buf[QUERY_DESC_LENGTH_OFFSET];
3827 
3828 	if (param_offset >= buff_len) {
3829 		dev_err(hba->dev, "%s: Invalid offset 0x%x in descriptor IDN 0x%x, length 0x%x\n",
3830 			__func__, param_offset, desc_id, buff_len);
3831 		ret = -EINVAL;
3832 		goto out;
3833 	}
3834 
3835 	/* Sanity check */
3836 	if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3837 		dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header\n",
3838 			__func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3839 		ret = -EINVAL;
3840 		goto out;
3841 	}
3842 
3843 	if (is_kmalloc) {
3844 		/* Make sure we don't copy more data than available */
3845 		if (param_offset >= buff_len)
3846 			ret = -EINVAL;
3847 		else
3848 			memcpy(param_read_buf, &desc_buf[param_offset],
3849 			       min_t(u32, param_size, buff_len - param_offset));
3850 	}
3851 out:
3852 	if (is_kmalloc)
3853 		kfree(desc_buf);
3854 	return ret;
3855 }
3856 
3857 /**
3858  * struct uc_string_id - unicode string
3859  *
3860  * @len: size of this descriptor inclusive
3861  * @type: descriptor type
3862  * @uc: unicode string character
3863  */
3864 struct uc_string_id {
3865 	u8 len;
3866 	u8 type;
3867 	wchar_t uc[];
3868 } __packed;
3869 
3870 /* replace non-printable or non-ASCII characters with spaces */
3871 static inline char ufshcd_remove_non_printable(u8 ch)
3872 {
3873 	return (ch >= 0x20 && ch <= 0x7e) ? ch : ' ';
3874 }
3875 
3876 /**
3877  * ufshcd_read_string_desc - read string descriptor
3878  * @hba: pointer to adapter instance
3879  * @desc_index: descriptor index
3880  * @buf: pointer to buffer where descriptor would be read,
3881  *       the caller should free the memory.
3882  * @fmt: if %SD_ASCII_STD, convert from UTF-16 to ASCII
3883  *
3884  * Return:
3885  * *      string size on success.
3886  * *      -ENOMEM: on allocation failure
3887  * *      -EINVAL: on a wrong parameter
3888  */
3889 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index, u8 **buf, enum ufs_descr_fmt fmt)
3890 {
3891 	struct uc_string_id *uc_str;
3892 	u8 *str;
3893 	int ret, uc_len;
3894 
3895 	if (!buf)
3896 		return -EINVAL;
3897 
3898 	uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
3899 	if (!uc_str)
3900 		return -ENOMEM;
3901 
3902 	ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_STRING, desc_index, 0,
3903 				     (u8 *)uc_str, QUERY_DESC_MAX_SIZE);
3904 	if (ret < 0) {
3905 		dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n",
3906 			QUERY_REQ_RETRIES, ret);
3907 		str = NULL;
3908 		goto out;
3909 	}
3910 
3911 	if (uc_str->len <= QUERY_DESC_HDR_SIZE) {
3912 		dev_dbg(hba->dev, "String Desc is of zero length\n");
3913 		str = NULL;
3914 		ret = 0;
3915 		goto out;
3916 	}
3917 
3918 	uc_len = uc_str->len - QUERY_DESC_HDR_SIZE;
3919 	if (uc_len % sizeof(*uc_str->uc)) {
3920 		dev_err(hba->dev, "String Desc has an odd UTF-16 payload length\n");
3921 		str = NULL;
3922 		ret = -EINVAL;
3923 		goto out;
3924 	}
3925 
3926 	if (fmt == SD_ASCII_STD) {
3927 		ssize_t ascii_len;
3928 		int i;
3929 		/* Allow up to three UTF-8 bytes per UTF-16 code unit plus a NUL. */
3930 		ascii_len = uc_len / sizeof(*uc_str->uc) * 3 + 1;
3931 		str = kzalloc(ascii_len, GFP_KERNEL);
3932 		if (!str) {
3933 			ret = -ENOMEM;
3934 			goto out;
3935 		}
3936 
3937 		/*
3938 		 * the descriptor contains string in UTF16 format
3939 		 * we need to convert to utf-8 so it can be displayed
3940 		 */
3941 		ret = utf16s_to_utf8s(uc_str->uc,
3942 				      uc_len / sizeof(*uc_str->uc),
3943 				      UTF16_BIG_ENDIAN, str, ascii_len - 1);
3944 
3945 		/* replace non-printable or non-ASCII characters with spaces */
3946 		for (i = 0; i < ret; i++)
3947 			str[i] = ufshcd_remove_non_printable(str[i]);
3948 
3949 		str[ret++] = '\0';
3950 
3951 	} else {
3952 		/*
3953 		 * Keep the bLength-sized raw output for the RPMB device ID ABI.
3954 		 * The two bytes beyond the UTF-16 payload are explicitly zeroed
3955 		 * instead of being read past the descriptor buffer.
3956 		 */
3957 		str = kzalloc(uc_str->len, GFP_KERNEL);
3958 		if (!str) {
3959 			ret = -ENOMEM;
3960 			goto out;
3961 		}
3962 		memcpy(str, uc_str->uc, uc_len);
3963 		ret = uc_str->len;
3964 	}
3965 out:
3966 	*buf = str;
3967 	kfree(uc_str);
3968 	return ret;
3969 }
3970 
3971 /**
3972  * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3973  * @hba: Pointer to adapter instance
3974  * @lun: lun id
3975  * @param_offset: offset of the parameter to read
3976  * @param_read_buf: pointer to buffer where parameter would be read
3977  * @param_size: sizeof(param_read_buf)
3978  *
3979  * Return: 0 in case of success; < 0 upon failure.
3980  */
3981 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3982 					      int lun,
3983 					      enum unit_desc_param param_offset,
3984 					      u8 *param_read_buf,
3985 					      u32 param_size)
3986 {
3987 	/*
3988 	 * Unit descriptors are only available for general purpose LUs (LUN id
3989 	 * from 0 to 7) and RPMB Well known LU.
3990 	 */
3991 	if (!ufs_is_valid_unit_desc_lun(&hba->dev_info, lun))
3992 		return -EOPNOTSUPP;
3993 
3994 	return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3995 				      param_offset, param_read_buf, param_size);
3996 }
3997 
3998 static int ufshcd_get_ref_clk_gating_wait(struct ufs_hba *hba)
3999 {
4000 	int err = 0;
4001 	u32 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
4002 
4003 	if (hba->dev_info.wspecversion >= 0x300) {
4004 		err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
4005 				QUERY_ATTR_IDN_REF_CLK_GATING_WAIT_TIME, 0, 0,
4006 				&gating_wait);
4007 		if (err)
4008 			dev_err(hba->dev, "Failed reading bRefClkGatingWait. err = %d, use default %uus\n",
4009 					 err, gating_wait);
4010 
4011 		if (gating_wait == 0) {
4012 			gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
4013 			dev_err(hba->dev, "Undefined ref clk gating wait time, use default %uus\n",
4014 					 gating_wait);
4015 		}
4016 
4017 		hba->dev_info.clk_gating_wait_us = gating_wait;
4018 	}
4019 
4020 	return err;
4021 }
4022 
4023 /**
4024  * ufshcd_memory_alloc - allocate memory for host memory space data structures
4025  * @hba: per adapter instance
4026  *
4027  * 1. Allocate DMA memory for Command Descriptor array
4028  *	Each command descriptor consist of Command UPIU, Response UPIU and PRDT
4029  * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
4030  * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
4031  *	(UTMRDL)
4032  * 4. Allocate memory for local reference block(lrb).
4033  *
4034  * Return: 0 for success, non-zero in case of failure.
4035  */
4036 static int ufshcd_memory_alloc(struct ufs_hba *hba)
4037 {
4038 	size_t utmrdl_size, utrdl_size, ucdl_size;
4039 
4040 	/* The reserved tag uses the dedicated UCD below, not this pool. */
4041 	ucdl_size = ufshcd_get_ucd_size(hba) * (hba->nutrs - UFSHCD_NUM_RESERVED);
4042 	hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
4043 						  ucdl_size,
4044 						  &hba->ucdl_dma_addr,
4045 						  GFP_KERNEL);
4046 
4047 	/*
4048 	 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
4049 	 */
4050 	if (!hba->ucdl_base_addr ||
4051 	    WARN_ON(hba->ucdl_dma_addr & (128 - 1))) {
4052 		dev_err(hba->dev,
4053 			"Command Descriptor Memory allocation failed\n");
4054 		goto out;
4055 	}
4056 
4057 	/* Dedicated UCD for the reserved tag; allocate once (survives MCQ re-init). */
4058 	if (!hba->devman_ucd_base_addr) {
4059 		hba->devman_ucd_base_addr =
4060 			dmam_alloc_coherent(hba->dev,
4061 					    ufshcd_get_devman_ucd_size(hba),
4062 					    &hba->devman_ucd_dma_addr,
4063 					    GFP_KERNEL);
4064 		if (!hba->devman_ucd_base_addr ||
4065 		    WARN_ON(hba->devman_ucd_dma_addr & (128 - 1))) {
4066 			dev_err(hba->dev,
4067 				"Devman Command Descriptor Memory allocation failed\n");
4068 			goto out;
4069 		}
4070 	}
4071 
4072 	/*
4073 	 * Allocate memory for UTP Transfer descriptors
4074 	 * UFSHCI requires 1KB alignment of UTRD
4075 	 */
4076 	utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
4077 	hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
4078 						   utrdl_size,
4079 						   &hba->utrdl_dma_addr,
4080 						   GFP_KERNEL);
4081 	if (!hba->utrdl_base_addr ||
4082 	    WARN_ON(hba->utrdl_dma_addr & (SZ_1K - 1))) {
4083 		dev_err(hba->dev,
4084 			"Transfer Descriptor Memory allocation failed\n");
4085 		goto out;
4086 	}
4087 
4088 	/*
4089 	 * Skip utmrdl allocation; it may have been
4090 	 * allocated during first pass and not released during
4091 	 * MCQ memory allocation.
4092 	 * See ufshcd_release_sdb_queue() and ufshcd_config_mcq()
4093 	 */
4094 	if (hba->utmrdl_base_addr)
4095 		goto skip_utmrdl;
4096 	/*
4097 	 * Allocate memory for UTP Task Management descriptors
4098 	 * UFSHCI requires 1KB alignment of UTMRD
4099 	 */
4100 	utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
4101 	hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
4102 						    utmrdl_size,
4103 						    &hba->utmrdl_dma_addr,
4104 						    GFP_KERNEL);
4105 	if (!hba->utmrdl_base_addr ||
4106 	    WARN_ON(hba->utmrdl_dma_addr & (SZ_1K - 1))) {
4107 		dev_err(hba->dev,
4108 		"Task Management Descriptor Memory allocation failed\n");
4109 		goto out;
4110 	}
4111 
4112 skip_utmrdl:
4113 	return 0;
4114 out:
4115 	return -ENOMEM;
4116 }
4117 
4118 /**
4119  * ufshcd_host_memory_configure - configure local reference block with
4120  *				memory offsets
4121  * @hba: per adapter instance
4122  *
4123  * Configure Host memory space
4124  * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
4125  * address.
4126  * 2. Update each UTRD with Response UPIU offset, Response UPIU length
4127  * and PRDT offset.
4128  * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
4129  * into local reference block.
4130  */
4131 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
4132 {
4133 	struct utp_transfer_req_desc *utrdlp;
4134 	dma_addr_t cmd_desc_dma_addr;
4135 	dma_addr_t cmd_desc_element_addr;
4136 	u16 response_offset;
4137 	u16 prdt_offset;
4138 	u16 response_len;
4139 	int cmd_desc_size;
4140 	int i;
4141 
4142 	utrdlp = hba->utrdl_base_addr;
4143 
4144 	cmd_desc_size = ufshcd_get_ucd_size(hba);
4145 	cmd_desc_dma_addr = hba->ucdl_dma_addr;
4146 
4147 	for (i = 0; i < hba->nutrs; i++) {
4148 		/*
4149 		 * Reserved tags (low end) use the dedicated devman UCD with a
4150 		 * larger response area; other tags index the pool at i - RESERVED.
4151 		 */
4152 		if (i < UFSHCD_NUM_RESERVED) {
4153 			cmd_desc_element_addr = hba->devman_ucd_dma_addr;
4154 			response_offset = offsetof(struct utp_devman_cmd_desc,
4155 						   response_upiu);
4156 			prdt_offset = offsetof(struct utp_devman_cmd_desc,
4157 					       prd_table);
4158 			response_len = ALIGNED_DEVMAN_RSP_SIZE;
4159 		} else {
4160 			cmd_desc_element_addr = cmd_desc_dma_addr +
4161 				cmd_desc_size * (i - UFSHCD_NUM_RESERVED);
4162 			response_offset = offsetof(struct utp_transfer_cmd_desc,
4163 						   response_upiu);
4164 			prdt_offset = offsetof(struct utp_transfer_cmd_desc,
4165 					       prd_table);
4166 			response_len = ALIGNED_UPIU_SIZE;
4167 		}
4168 
4169 		/* Configure UTRD with command descriptor base address */
4170 		utrdlp[i].command_desc_base_addr =
4171 				cpu_to_le64(cmd_desc_element_addr);
4172 
4173 		/* Response upiu and prdt offset should be in double words */
4174 		if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
4175 			utrdlp[i].response_upiu_offset =
4176 				cpu_to_le16(response_offset);
4177 			utrdlp[i].prd_table_offset =
4178 				cpu_to_le16(prdt_offset);
4179 			utrdlp[i].response_upiu_length =
4180 				cpu_to_le16(response_len);
4181 		} else {
4182 			utrdlp[i].response_upiu_offset =
4183 				cpu_to_le16(response_offset >> 2);
4184 			utrdlp[i].prd_table_offset =
4185 				cpu_to_le16(prdt_offset >> 2);
4186 			utrdlp[i].response_upiu_length =
4187 				cpu_to_le16(response_len >> 2);
4188 		}
4189 	}
4190 }
4191 
4192 /**
4193  * ufshcd_dme_link_startup - Notify Unipro to perform link startup
4194  * @hba: per adapter instance
4195  *
4196  * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
4197  * in order to initialize the Unipro link startup procedure.
4198  * Once the Unipro links are up, the device connected to the controller
4199  * is detected.
4200  *
4201  * Return: 0 on success, non-zero value on failure.
4202  */
4203 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
4204 {
4205 	struct uic_command uic_cmd = {
4206 		.command = UIC_CMD_DME_LINK_STARTUP,
4207 	};
4208 	int ret;
4209 
4210 	ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
4211 	if (ret)
4212 		dev_dbg(hba->dev,
4213 			"dme-link-startup: error code %d\n", ret);
4214 	return ret;
4215 }
4216 /**
4217  * ufshcd_dme_reset - UIC command for DME_RESET
4218  * @hba: per adapter instance
4219  *
4220  * DME_RESET command is issued in order to reset UniPro stack.
4221  * This function now deals with cold reset.
4222  *
4223  * Return: 0 on success, non-zero value on failure.
4224  */
4225 int ufshcd_dme_reset(struct ufs_hba *hba)
4226 {
4227 	struct uic_command uic_cmd = {
4228 		.command = UIC_CMD_DME_RESET,
4229 	};
4230 	int ret;
4231 
4232 	ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
4233 	if (ret)
4234 		dev_err(hba->dev,
4235 			"dme-reset: error code %d\n", ret);
4236 
4237 	return ret;
4238 }
4239 EXPORT_SYMBOL_GPL(ufshcd_dme_reset);
4240 
4241 int ufshcd_dme_configure_adapt(struct ufs_hba *hba,
4242 			       int agreed_gear,
4243 			       int adapt_val)
4244 {
4245 	int ret;
4246 
4247 	if (agreed_gear < UFS_HS_G4)
4248 		adapt_val = PA_NO_ADAPT;
4249 
4250 	ret = ufshcd_dme_set(hba,
4251 			     UIC_ARG_MIB(PA_TXHSADAPTTYPE),
4252 			     adapt_val);
4253 	return ret;
4254 }
4255 EXPORT_SYMBOL_GPL(ufshcd_dme_configure_adapt);
4256 
4257 /**
4258  * ufshcd_dme_enable - UIC command for DME_ENABLE
4259  * @hba: per adapter instance
4260  *
4261  * DME_ENABLE command is issued in order to enable UniPro stack.
4262  *
4263  * Return: 0 on success, non-zero value on failure.
4264  */
4265 int ufshcd_dme_enable(struct ufs_hba *hba)
4266 {
4267 	struct uic_command uic_cmd = {
4268 		.command = UIC_CMD_DME_ENABLE,
4269 	};
4270 	int ret;
4271 
4272 	ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
4273 	if (ret)
4274 		dev_err(hba->dev,
4275 			"dme-enable: error code %d\n", ret);
4276 
4277 	return ret;
4278 }
4279 EXPORT_SYMBOL_GPL(ufshcd_dme_enable);
4280 
4281 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
4282 {
4283 	#define MIN_DELAY_BEFORE_DME_CMDS_US	1000
4284 	unsigned long min_sleep_time_us;
4285 
4286 	if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
4287 		return;
4288 
4289 	/*
4290 	 * last_dme_cmd_tstamp will be 0 only for 1st call to
4291 	 * this function
4292 	 */
4293 	if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
4294 		min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
4295 	} else {
4296 		unsigned long delta =
4297 			(unsigned long) ktime_to_us(
4298 				ktime_sub(ktime_get(),
4299 				hba->last_dme_cmd_tstamp));
4300 
4301 		if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
4302 			min_sleep_time_us =
4303 				MIN_DELAY_BEFORE_DME_CMDS_US - delta;
4304 		else
4305 			min_sleep_time_us = 0; /* no more delay required */
4306 	}
4307 
4308 	if (min_sleep_time_us > 0) {
4309 		/* allow sleep for extra 50us if needed */
4310 		usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
4311 	}
4312 
4313 	/* update the last_dme_cmd_tstamp */
4314 	hba->last_dme_cmd_tstamp = ktime_get();
4315 }
4316 
4317 /**
4318  * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
4319  * @hba: per adapter instance
4320  * @attr_sel: uic command argument1
4321  * @attr_set: attribute set type as uic command argument2
4322  * @mib_val: setting value as uic command argument3
4323  * @peer: indicate whether peer or local
4324  *
4325  * Return: 0 on success, non-zero value on failure.
4326  */
4327 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
4328 			u8 attr_set, u32 mib_val, u8 peer)
4329 {
4330 	struct uic_command uic_cmd = {
4331 		.command = peer ? UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET,
4332 		.argument1 = attr_sel,
4333 		.argument2 = UIC_ARG_ATTR_TYPE(attr_set),
4334 		.argument3 = mib_val,
4335 	};
4336 	static const char *const action[] = {
4337 		"dme-set",
4338 		"dme-peer-set"
4339 	};
4340 	const char *set = action[!!peer];
4341 	int ret;
4342 	int retries = UFS_UIC_COMMAND_RETRIES;
4343 
4344 	do {
4345 		/* for peer attributes we retry upon failure */
4346 		ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
4347 		if (ret)
4348 			dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
4349 				set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
4350 	} while (ret && peer && --retries);
4351 
4352 	if (ret)
4353 		dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
4354 			set, UIC_GET_ATTR_ID(attr_sel), mib_val,
4355 			UFS_UIC_COMMAND_RETRIES - retries);
4356 
4357 	return ret;
4358 }
4359 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
4360 
4361 /**
4362  * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
4363  * @hba: per adapter instance
4364  * @attr_sel: uic command argument1
4365  * @mib_val: the value of the attribute as returned by the UIC command
4366  * @peer: indicate whether peer or local
4367  *
4368  * Return: 0 on success, non-zero value on failure.
4369  */
4370 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
4371 			u32 *mib_val, u8 peer)
4372 {
4373 	struct uic_command uic_cmd = {
4374 		.command = peer ? UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET,
4375 		.argument1 = attr_sel,
4376 	};
4377 	static const char *const action[] = {
4378 		"dme-get",
4379 		"dme-peer-get"
4380 	};
4381 	const char *get = action[!!peer];
4382 	int ret;
4383 	int retries = UFS_UIC_COMMAND_RETRIES;
4384 	struct ufs_pa_layer_attr orig_pwr_info;
4385 	struct ufs_pa_layer_attr temp_pwr_info;
4386 	bool pwr_mode_change = false;
4387 
4388 	if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
4389 		orig_pwr_info = hba->pwr_info;
4390 		temp_pwr_info = orig_pwr_info;
4391 
4392 		if (orig_pwr_info.pwr_tx == FAST_MODE ||
4393 		    orig_pwr_info.pwr_rx == FAST_MODE) {
4394 			temp_pwr_info.pwr_tx = FASTAUTO_MODE;
4395 			temp_pwr_info.pwr_rx = FASTAUTO_MODE;
4396 			pwr_mode_change = true;
4397 		} else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
4398 		    orig_pwr_info.pwr_rx == SLOW_MODE) {
4399 			temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
4400 			temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
4401 			pwr_mode_change = true;
4402 		}
4403 		if (pwr_mode_change) {
4404 			ret = ufshcd_change_power_mode(hba, &temp_pwr_info,
4405 						       UFSHCD_PMC_POLICY_DONT_FORCE);
4406 			if (ret)
4407 				goto out;
4408 		}
4409 	}
4410 
4411 	do {
4412 		/* for peer attributes we retry upon failure */
4413 		ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
4414 		if (ret)
4415 			dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
4416 				get, UIC_GET_ATTR_ID(attr_sel), ret);
4417 	} while (ret && peer && --retries);
4418 
4419 	if (ret)
4420 		dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
4421 			get, UIC_GET_ATTR_ID(attr_sel),
4422 			UFS_UIC_COMMAND_RETRIES - retries);
4423 
4424 	if (mib_val)
4425 		*mib_val = ret == 0 ? uic_cmd.argument3 : 0;
4426 
4427 	if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
4428 	    && pwr_mode_change)
4429 		ufshcd_change_power_mode(hba, &orig_pwr_info,
4430 					 UFSHCD_PMC_POLICY_DONT_FORCE);
4431 out:
4432 	return ret;
4433 }
4434 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
4435 
4436 /**
4437  * ufshcd_dme_rmw - get modify set a DME attribute
4438  * @hba: per adapter instance
4439  * @mask: indicates which bits to clear from the value that has been read
4440  * @val: actual value to write
4441  * @attr: dme attribute
4442  */
4443 int ufshcd_dme_rmw(struct ufs_hba *hba, u32 mask,
4444 		   u32 val, u32 attr)
4445 {
4446 	u32 cfg = 0;
4447 	int err;
4448 
4449 	err = ufshcd_dme_get(hba, UIC_ARG_MIB(attr), &cfg);
4450 	if (err)
4451 		return err;
4452 
4453 	cfg &= ~mask;
4454 	cfg |= (val & mask);
4455 
4456 	return ufshcd_dme_set(hba, UIC_ARG_MIB(attr), cfg);
4457 }
4458 EXPORT_SYMBOL_GPL(ufshcd_dme_rmw);
4459 
4460 /**
4461  * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
4462  * state) and waits for it to take effect.
4463  *
4464  * @hba: per adapter instance
4465  * @cmd: UIC command to execute
4466  *
4467  * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
4468  * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
4469  * and device UniPro link and hence it's final completion would be indicated by
4470  * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
4471  * addition to normal UIC command completion Status (UCCS). This function only
4472  * returns after the relevant status bits indicate the completion.
4473  *
4474  * Return: 0 on success, non-zero value on failure.
4475  */
4476 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
4477 {
4478 	DECLARE_COMPLETION_ONSTACK(uic_async_done);
4479 	unsigned long flags;
4480 	u8 status;
4481 	int ret;
4482 
4483 	mutex_lock(&hba->uic_cmd_mutex);
4484 	ufshcd_add_delay_before_dme_cmd(hba);
4485 
4486 	spin_lock_irqsave(hba->host->host_lock, flags);
4487 	if (ufshcd_is_link_broken(hba)) {
4488 		ret = -ENOLINK;
4489 		goto out_unlock;
4490 	}
4491 	hba->uic_async_done = &uic_async_done;
4492 	ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
4493 	spin_unlock_irqrestore(hba->host->host_lock, flags);
4494 	ret = __ufshcd_send_uic_cmd(hba, cmd);
4495 	if (ret) {
4496 		dev_err(hba->dev,
4497 			"pwr ctrl cmd 0x%x with (MIBattribute 0x%x, mode 0x%x) uic error %d\n",
4498 			cmd->command, UIC_GET_ATTR_ID(cmd->argument1),
4499 			cmd->argument3, ret);
4500 		goto out;
4501 	}
4502 
4503 	if (!wait_for_completion_timeout(hba->uic_async_done,
4504 					 msecs_to_jiffies(uic_cmd_timeout))) {
4505 		dev_err(hba->dev,
4506 			"pwr ctrl cmd 0x%x with (MIBattribute 0x%x, mode 0x%x) completion timeout\n",
4507 			cmd->command, UIC_GET_ATTR_ID(cmd->argument1),
4508 			cmd->argument3);
4509 
4510 		if (!cmd->cmd_active) {
4511 			dev_err(hba->dev, "%s: Power Mode Change operation has been completed, go check UPMCRS\n",
4512 				__func__);
4513 			goto check_upmcrs;
4514 		}
4515 
4516 		ret = -ETIMEDOUT;
4517 		goto out;
4518 	}
4519 
4520 check_upmcrs:
4521 	status = ufshcd_get_upmcrs(hba);
4522 	if (status != PWR_LOCAL) {
4523 		dev_err(hba->dev,
4524 			"pwr ctrl cmd 0x%x with (MIBattribute 0x%x, mode 0x%x) failed, host upmcrs:0x%x\n",
4525 			cmd->command, UIC_GET_ATTR_ID(cmd->argument1),
4526 			cmd->argument3, status);
4527 		ret = (status != PWR_OK) ? status : -1;
4528 	}
4529 out:
4530 	if (ret) {
4531 		ufshcd_print_host_state(hba);
4532 		ufshcd_print_pwr_info(hba);
4533 		ufshcd_print_tx_eq_params(hba);
4534 		ufshcd_print_evt_hist(hba);
4535 	}
4536 
4537 	spin_lock_irqsave(hba->host->host_lock, flags);
4538 	hba->active_uic_cmd = NULL;
4539 	hba->uic_async_done = NULL;
4540 	if (ret && !hba->pm_op_in_progress) {
4541 		ufshcd_set_link_broken(hba);
4542 		ufshcd_schedule_eh_work(hba);
4543 	}
4544 out_unlock:
4545 	spin_unlock_irqrestore(hba->host->host_lock, flags);
4546 	mutex_unlock(&hba->uic_cmd_mutex);
4547 
4548 	return ret;
4549 }
4550 
4551 /**
4552  * ufshcd_uic_tx_eqtr - Perform UIC TX Equalization Training
4553  * @hba: per adapter instance
4554  * @gear: target gear for EQTR
4555  *
4556  * Returns 0 on success, negative error code otherwise
4557  */
4558 int ufshcd_uic_tx_eqtr(struct ufs_hba *hba, int gear)
4559 {
4560 	struct uic_command uic_cmd = {
4561 		.command = UIC_CMD_DME_SET,
4562 		.argument1 = UIC_ARG_MIB(PA_EQTR_GEAR),
4563 		.argument3 = gear,
4564 	};
4565 	int ret;
4566 
4567 	ufshcd_hold(hba);
4568 	ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4569 	ufshcd_release(hba);
4570 
4571 	return ret;
4572 }
4573 
4574 /**
4575  * ufshcd_send_bsg_uic_cmd - Send UIC commands requested via BSG layer and retrieve the result
4576  * @hba: per adapter instance
4577  * @uic_cmd: UIC command
4578  *
4579  * Return: 0 only if success.
4580  */
4581 int ufshcd_send_bsg_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
4582 {
4583 	int ret;
4584 
4585 	if (uic_cmd->argument1 != UIC_ARG_MIB(PA_PWRMODE) ||
4586 	    uic_cmd->command != UIC_CMD_DME_SET)
4587 		return ufshcd_send_uic_cmd(hba, uic_cmd);
4588 
4589 	if (hba->quirks & UFSHCD_QUIRK_BROKEN_UIC_CMD)
4590 		return 0;
4591 
4592 	ufshcd_hold(hba);
4593 	ret = ufshcd_uic_pwr_ctrl(hba, uic_cmd);
4594 	ufshcd_release(hba);
4595 
4596 	return ret;
4597 }
4598 
4599 /**
4600  * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
4601  *				using DME_SET primitives.
4602  * @hba: per adapter instance
4603  * @mode: powr mode value
4604  *
4605  * Return: 0 on success, non-zero value on failure.
4606  */
4607 int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
4608 {
4609 	struct uic_command uic_cmd = {
4610 		.command = UIC_CMD_DME_SET,
4611 		.argument1 = UIC_ARG_MIB(PA_PWRMODE),
4612 		.argument3 = mode,
4613 	};
4614 	int ret;
4615 
4616 	if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
4617 		ret = ufshcd_dme_set(hba,
4618 				UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
4619 		if (ret) {
4620 			dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
4621 						__func__, ret);
4622 			goto out;
4623 		}
4624 	}
4625 
4626 	ufshcd_hold(hba);
4627 	ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4628 	ufshcd_release(hba);
4629 
4630 out:
4631 	return ret;
4632 }
4633 EXPORT_SYMBOL_GPL(ufshcd_uic_change_pwr_mode);
4634 
4635 int ufshcd_link_recovery(struct ufs_hba *hba)
4636 {
4637 	int ret;
4638 	unsigned long flags;
4639 
4640 	spin_lock_irqsave(hba->host->host_lock, flags);
4641 	hba->ufshcd_state = UFSHCD_STATE_RESET;
4642 	ufshcd_set_eh_in_progress(hba);
4643 	spin_unlock_irqrestore(hba->host->host_lock, flags);
4644 
4645 	/* Reset the attached device */
4646 	ufshcd_device_reset(hba);
4647 
4648 	ret = ufshcd_host_reset_and_restore(hba);
4649 
4650 	spin_lock_irqsave(hba->host->host_lock, flags);
4651 	if (ret)
4652 		hba->ufshcd_state = UFSHCD_STATE_ERROR;
4653 	ufshcd_clear_eh_in_progress(hba);
4654 	spin_unlock_irqrestore(hba->host->host_lock, flags);
4655 
4656 	if (ret)
4657 		dev_err(hba->dev, "%s: link recovery failed, err %d",
4658 			__func__, ret);
4659 
4660 	return ret;
4661 }
4662 EXPORT_SYMBOL_GPL(ufshcd_link_recovery);
4663 
4664 int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
4665 {
4666 	struct uic_command uic_cmd = {
4667 		.command = UIC_CMD_DME_HIBER_ENTER,
4668 	};
4669 	ktime_t start = ktime_get();
4670 	int ret;
4671 
4672 	ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
4673 
4674 	ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4675 	trace_ufshcd_profile_hibern8(hba, "enter",
4676 			     ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4677 
4678 	if (ret)
4679 		dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
4680 			__func__, ret);
4681 	else
4682 		ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
4683 								POST_CHANGE);
4684 
4685 	return ret;
4686 }
4687 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_enter);
4688 
4689 int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
4690 {
4691 	struct uic_command uic_cmd = {
4692 		.command = UIC_CMD_DME_HIBER_EXIT,
4693 	};
4694 	int ret;
4695 	ktime_t start = ktime_get();
4696 
4697 	ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
4698 
4699 	ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4700 	trace_ufshcd_profile_hibern8(hba, "exit",
4701 			     ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4702 
4703 	if (ret) {
4704 		dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
4705 			__func__, ret);
4706 	} else {
4707 		ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
4708 								POST_CHANGE);
4709 		hba->ufs_stats.last_hibern8_exit_tstamp = local_clock();
4710 		hba->ufs_stats.hibern8_exit_cnt++;
4711 	}
4712 
4713 	return ret;
4714 }
4715 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_exit);
4716 
4717 static void ufshcd_configure_auto_hibern8(struct ufs_hba *hba)
4718 {
4719 	if (!ufshcd_is_auto_hibern8_supported(hba))
4720 		return;
4721 
4722 	ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
4723 }
4724 
4725 void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit)
4726 {
4727 	const u32 cur_ahit = READ_ONCE(hba->ahit);
4728 
4729 	if (!ufshcd_is_auto_hibern8_supported(hba) || cur_ahit == ahit)
4730 		return;
4731 
4732 	WRITE_ONCE(hba->ahit, ahit);
4733 	if (!pm_runtime_suspended(&hba->ufs_device_wlun->sdev_gendev)) {
4734 		ufshcd_rpm_get_sync(hba);
4735 		ufshcd_hold(hba);
4736 		ufshcd_configure_auto_hibern8(hba);
4737 		ufshcd_release(hba);
4738 		ufshcd_rpm_put_sync(hba);
4739 	}
4740 }
4741 EXPORT_SYMBOL_GPL(ufshcd_auto_hibern8_update);
4742 
4743  /**
4744  * ufshcd_init_pwr_info - setting the POR (power on reset)
4745  * values in hba power info
4746  * @hba: per-adapter instance
4747  */
4748 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
4749 {
4750 	hba->pwr_info.gear_rx = UFS_PWM_G1;
4751 	hba->pwr_info.gear_tx = UFS_PWM_G1;
4752 	hba->pwr_info.lane_rx = UFS_LANE_1;
4753 	hba->pwr_info.lane_tx = UFS_LANE_1;
4754 	hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
4755 	hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
4756 	hba->pwr_info.hs_rate = 0;
4757 }
4758 
4759 /**
4760  * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
4761  * @hba: per-adapter instance
4762  *
4763  * Return: 0 upon success; < 0 upon failure.
4764  */
4765 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
4766 {
4767 	struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
4768 
4769 	if (hba->max_pwr_info.is_valid)
4770 		return 0;
4771 
4772 	if (hba->quirks & UFSHCD_QUIRK_HIBERN_FASTAUTO) {
4773 		pwr_info->pwr_tx = FASTAUTO_MODE;
4774 		pwr_info->pwr_rx = FASTAUTO_MODE;
4775 	} else {
4776 		pwr_info->pwr_tx = FAST_MODE;
4777 		pwr_info->pwr_rx = FAST_MODE;
4778 	}
4779 	pwr_info->hs_rate = PA_HS_MODE_B;
4780 
4781 	/* Get the connected lane count */
4782 	ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
4783 			&pwr_info->lane_rx);
4784 	ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4785 			&pwr_info->lane_tx);
4786 
4787 	if (!pwr_info->lane_rx || !pwr_info->lane_tx ||
4788 	    pwr_info->lane_rx > UFS_MAX_LANES ||
4789 	    pwr_info->lane_tx > UFS_MAX_LANES) {
4790 		dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4791 				__func__,
4792 				pwr_info->lane_rx,
4793 				pwr_info->lane_tx);
4794 		return -EINVAL;
4795 	}
4796 
4797 	if (pwr_info->lane_rx != pwr_info->lane_tx) {
4798 		dev_err(hba->dev, "%s: asymmetric connected lanes. rx=%d, tx=%d\n",
4799 			__func__,
4800 				pwr_info->lane_rx,
4801 				pwr_info->lane_tx);
4802 		return -EINVAL;
4803 	}
4804 
4805 	/*
4806 	 * First, get the maximum gears of HS speed.
4807 	 * If a zero value, it means there is no HSGEAR capability.
4808 	 * Then, get the maximum gears of PWM speed.
4809 	 */
4810 	ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4811 	if (!pwr_info->gear_rx) {
4812 		ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4813 				&pwr_info->gear_rx);
4814 		if (!pwr_info->gear_rx) {
4815 			dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4816 				__func__, pwr_info->gear_rx);
4817 			return -EINVAL;
4818 		}
4819 		pwr_info->pwr_rx = SLOW_MODE;
4820 	}
4821 
4822 	ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4823 			&pwr_info->gear_tx);
4824 	if (!pwr_info->gear_tx) {
4825 		ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4826 				&pwr_info->gear_tx);
4827 		if (!pwr_info->gear_tx) {
4828 			dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4829 				__func__, pwr_info->gear_tx);
4830 			return -EINVAL;
4831 		}
4832 		pwr_info->pwr_tx = SLOW_MODE;
4833 	}
4834 
4835 	hba->max_pwr_info.is_valid = true;
4836 	return 0;
4837 }
4838 
4839 /**
4840  * ufshcd_dme_change_power_mode() - UniPro DME Power Mode change sequence
4841  * @hba: per-adapter instance
4842  * @pwr_mode: pointer to the target power mode (gear/lane) attributes
4843  * @pmc_policy: Power Mode change policy
4844  *
4845  * This function handles the low-level DME (Device Management Entity)
4846  * configuration required to transition the UFS link to a new power mode. It
4847  * performs the following steps:
4848  * 1. Checks if the requested mode matches the current state.
4849  * 2. Sets M-PHY and UniPro attributes including Gear (PA_RXGEAR/TXGEAR),
4850  *    Lanes, Termination, and HS Series (PA_HSSERIES).
4851  * 3. Configures default UniPro timeout values (DL_FC0, etc.) unless
4852  *    explicitly skipped via quirks.
4853  * 4. Triggers the actual hardware mode change via ufshcd_uic_change_pwr_mode().
4854  * 5. Updates the HBA's cached power information on success.
4855  *
4856  * Return: 0 on success, non-zero error code on failure.
4857  */
4858 static int ufshcd_dme_change_power_mode(struct ufs_hba *hba,
4859 					struct ufs_pa_layer_attr *pwr_mode,
4860 					enum ufshcd_pmc_policy pmc_policy)
4861 {
4862 	int ret;
4863 
4864 	/* if already configured to the requested pwr_mode */
4865 	if (pmc_policy == UFSHCD_PMC_POLICY_DONT_FORCE &&
4866 	    pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4867 	    pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4868 	    pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4869 	    pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4870 	    pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4871 	    pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4872 	    pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4873 		dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4874 		return 0;
4875 	}
4876 
4877 	/*
4878 	 * Configure attributes for power mode change with below.
4879 	 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4880 	 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4881 	 * - PA_HSSERIES
4882 	 */
4883 	ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4884 	ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4885 			pwr_mode->lane_rx);
4886 	if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4887 			pwr_mode->pwr_rx == FAST_MODE)
4888 		ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), true);
4889 	else
4890 		ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), false);
4891 
4892 	ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4893 	ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4894 			pwr_mode->lane_tx);
4895 	if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4896 			pwr_mode->pwr_tx == FAST_MODE)
4897 		ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), true);
4898 	else
4899 		ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), false);
4900 
4901 	if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4902 	    pwr_mode->pwr_tx == FASTAUTO_MODE ||
4903 	    pwr_mode->pwr_rx == FAST_MODE ||
4904 	    pwr_mode->pwr_tx == FAST_MODE)
4905 		ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4906 						pwr_mode->hs_rate);
4907 
4908 	if (!(hba->quirks & UFSHCD_QUIRK_SKIP_DEF_UNIPRO_TIMEOUT_SETTING)) {
4909 		ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0),
4910 				DL_FC0ProtectionTimeOutVal_Default);
4911 		ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1),
4912 				DL_TC0ReplayTimeOutVal_Default);
4913 		ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2),
4914 				DL_AFC0ReqTimeOutVal_Default);
4915 		ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA3),
4916 				DL_FC1ProtectionTimeOutVal_Default);
4917 		ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA4),
4918 				DL_TC1ReplayTimeOutVal_Default);
4919 		ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA5),
4920 				DL_AFC1ReqTimeOutVal_Default);
4921 
4922 		ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal),
4923 				DL_FC0ProtectionTimeOutVal_Default);
4924 		ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal),
4925 				DL_TC0ReplayTimeOutVal_Default);
4926 		ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal),
4927 				DL_AFC0ReqTimeOutVal_Default);
4928 	}
4929 
4930 	ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4931 			| pwr_mode->pwr_tx);
4932 
4933 	if (ret) {
4934 		dev_err(hba->dev,
4935 			"%s: power mode change failed %d\n", __func__, ret);
4936 	} else {
4937 		memcpy(&hba->pwr_info, pwr_mode,
4938 			sizeof(struct ufs_pa_layer_attr));
4939 	}
4940 
4941 	return ret;
4942 }
4943 
4944 /**
4945  * ufshcd_change_power_mode() - Change UFS Link Power Mode
4946  * @hba: per-adapter instance
4947  * @pwr_mode: pointer to the target power mode (gear/lane) attributes
4948  * @pmc_policy: Power Mode change policy
4949  *
4950  * This function handles the high-level sequence for changing the UFS link
4951  * power mode. It triggers vendor-specific pre-change notification,
4952  * executes the DME (Device Management Entity) power mode change sequence,
4953  * and, upon success, triggers vendor-specific post-change notification.
4954  *
4955  * Return: 0 on success, non-zero error code on failure.
4956  */
4957 int ufshcd_change_power_mode(struct ufs_hba *hba,
4958 			     struct ufs_pa_layer_attr *pwr_mode,
4959 			     enum ufshcd_pmc_policy pmc_policy)
4960 {
4961 	int ret;
4962 
4963 	ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE, pwr_mode);
4964 
4965 	ret = ufshcd_dme_change_power_mode(hba, pwr_mode, pmc_policy);
4966 
4967 	if (!ret)
4968 		ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, pwr_mode);
4969 
4970 	return ret;
4971 }
4972 EXPORT_SYMBOL_GPL(ufshcd_change_power_mode);
4973 
4974 /**
4975  * ufshcd_config_pwr_mode - configure a new power mode
4976  * @hba: per-adapter instance
4977  * @desired_pwr_mode: desired power configuration
4978  * @pmc_policy: Power Mode change policy
4979  *
4980  * Return: 0 upon success; < 0 upon failure.
4981  */
4982 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4983 			   struct ufs_pa_layer_attr *desired_pwr_mode,
4984 			   enum ufshcd_pmc_policy pmc_policy)
4985 {
4986 	struct ufs_pa_layer_attr final_params = { 0 };
4987 	int ret;
4988 
4989 	ret = ufshcd_vops_negotiate_pwr_mode(hba, desired_pwr_mode,
4990 					     &final_params);
4991 	if (ret) {
4992 		if (ret != -ENOTSUPP)
4993 			dev_err(hba->dev, "Failed to negotiate power mode: %d, use desired as is\n",
4994 				ret);
4995 
4996 		memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4997 	}
4998 
4999 	ret = ufshcd_config_tx_eq_settings(hba, &final_params, false);
5000 	if (ret)
5001 		dev_warn(hba->dev, "Failed to configure TX Equalization for HS-G%u, Rate-%s: %d\n",
5002 			 final_params.gear_tx,
5003 			 ufs_hs_rate_to_str(final_params.hs_rate), ret);
5004 
5005 	return ufshcd_change_power_mode(hba, &final_params, pmc_policy);
5006 }
5007 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
5008 
5009 /**
5010  * ufshcd_complete_dev_init() - checks device readiness
5011  * @hba: per-adapter instance
5012  *
5013  * Set fDeviceInit flag and poll until device toggles it.
5014  *
5015  * Return: 0 upon success; > 0 in case the UFS device reported an OCS error;
5016  * < 0 if another error occurred.
5017  */
5018 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
5019 {
5020 	int err;
5021 	bool flag_res = true;
5022 	ktime_t timeout;
5023 
5024 	err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5025 		QUERY_FLAG_IDN_FDEVICEINIT, 0, NULL);
5026 	if (err) {
5027 		dev_err(hba->dev,
5028 			"%s: setting fDeviceInit flag failed with error %d\n",
5029 			__func__, err);
5030 		goto out;
5031 	}
5032 
5033 	/* Poll fDeviceInit flag to be cleared */
5034 	timeout = ktime_add_ms(ktime_get(), FDEVICEINIT_COMPL_TIMEOUT);
5035 	do {
5036 		err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG,
5037 					QUERY_FLAG_IDN_FDEVICEINIT, 0, &flag_res);
5038 		if (!flag_res)
5039 			break;
5040 		usleep_range(500, 1000);
5041 	} while (ktime_before(ktime_get(), timeout));
5042 
5043 	if (err) {
5044 		dev_err(hba->dev,
5045 				"%s: reading fDeviceInit flag failed with error %d\n",
5046 				__func__, err);
5047 	} else if (flag_res) {
5048 		dev_err(hba->dev,
5049 				"%s: fDeviceInit was not cleared by the device\n",
5050 				__func__);
5051 		err = -EBUSY;
5052 	}
5053 out:
5054 	return err;
5055 }
5056 
5057 /**
5058  * ufshcd_make_hba_operational - Make UFS controller operational
5059  * @hba: per adapter instance
5060  *
5061  * To bring UFS host controller to operational state,
5062  * 1. Enable required interrupts
5063  * 2. Configure interrupt aggregation
5064  * 3. Program UTRL and UTMRL base address
5065  * 4. Configure run-stop-registers
5066  *
5067  * Return: 0 if successful; < 0 upon failure.
5068  */
5069 int ufshcd_make_hba_operational(struct ufs_hba *hba)
5070 {
5071 	int err = 0;
5072 	u32 reg;
5073 
5074 	/* Enable required interrupts */
5075 	ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
5076 
5077 	/* Configure interrupt aggregation */
5078 	if (ufshcd_is_intr_aggr_allowed(hba))
5079 		ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
5080 	else
5081 		ufshcd_disable_intr_aggr(hba);
5082 
5083 	/* Configure UTRL and UTMRL base address registers */
5084 	ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
5085 			REG_UTP_TRANSFER_REQ_LIST_BASE_L);
5086 	ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
5087 			REG_UTP_TRANSFER_REQ_LIST_BASE_H);
5088 	ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
5089 			REG_UTP_TASK_REQ_LIST_BASE_L);
5090 	ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
5091 			REG_UTP_TASK_REQ_LIST_BASE_H);
5092 
5093 	/*
5094 	 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
5095 	 */
5096 	reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
5097 	if (!(ufshcd_get_lists_status(reg))) {
5098 		ufshcd_enable_run_stop_reg(hba);
5099 	} else {
5100 		dev_err(hba->dev,
5101 			"Host controller not ready to process requests");
5102 		err = -EIO;
5103 	}
5104 
5105 	return err;
5106 }
5107 EXPORT_SYMBOL_GPL(ufshcd_make_hba_operational);
5108 
5109 /**
5110  * ufshcd_hba_stop - Send controller to reset state
5111  * @hba: per adapter instance
5112  */
5113 void ufshcd_hba_stop(struct ufs_hba *hba)
5114 {
5115 	int err;
5116 
5117 	ufshcd_disable_irq(hba);
5118 	ufshcd_writel(hba, CONTROLLER_DISABLE,  REG_CONTROLLER_ENABLE);
5119 	err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
5120 					CONTROLLER_ENABLE, CONTROLLER_DISABLE,
5121 					10, 1);
5122 	ufshcd_enable_irq(hba);
5123 	if (err)
5124 		dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
5125 }
5126 EXPORT_SYMBOL_GPL(ufshcd_hba_stop);
5127 
5128 /**
5129  * ufshcd_hba_execute_hce - initialize the controller
5130  * @hba: per adapter instance
5131  *
5132  * The controller resets itself and controller firmware initialization
5133  * sequence kicks off. When controller is ready it will set
5134  * the Host Controller Enable bit to 1.
5135  *
5136  * Return: 0 on success, non-zero value on failure.
5137  */
5138 static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
5139 {
5140 	int retry;
5141 
5142 	for (retry = 3; retry > 0; retry--) {
5143 		if (ufshcd_is_hba_active(hba))
5144 			/* change controller state to "reset state" */
5145 			ufshcd_hba_stop(hba);
5146 
5147 		/* UniPro link is disabled at this point */
5148 		ufshcd_set_link_off(hba);
5149 
5150 		ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
5151 
5152 		/* start controller initialization sequence */
5153 		ufshcd_hba_start(hba);
5154 
5155 		/*
5156 		 * To initialize a UFS host controller HCE bit must be set to 1.
5157 		 * During initialization the HCE bit value changes from 1->0->1.
5158 		 * When the host controller completes initialization sequence
5159 		 * it sets the value of HCE bit to 1. The same HCE bit is read back
5160 		 * to check if the controller has completed initialization sequence.
5161 		 * So without this delay the value HCE = 1, set in the previous
5162 		 * instruction might be read back.
5163 		 * This delay can be changed based on the controller.
5164 		 */
5165 		ufshcd_delay_us(hba->vps->hba_enable_delay_us, 100);
5166 
5167 		/* wait for the host controller to complete initialization */
5168 		if (!ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE, CONTROLLER_ENABLE,
5169 					      CONTROLLER_ENABLE, 1000, 50))
5170 			break;
5171 
5172 		dev_err(hba->dev, "Enabling the controller failed\n");
5173 	}
5174 
5175 	if (!retry)
5176 		return -EIO;
5177 
5178 	/* enable UIC related interrupts */
5179 	ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
5180 
5181 	ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
5182 
5183 	return 0;
5184 }
5185 
5186 int ufshcd_hba_enable(struct ufs_hba *hba)
5187 {
5188 	int ret;
5189 
5190 	if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
5191 		ufshcd_set_link_off(hba);
5192 		ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
5193 
5194 		/* enable UIC related interrupts */
5195 		ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
5196 		ret = ufshcd_dme_reset(hba);
5197 		if (ret) {
5198 			dev_err(hba->dev, "DME_RESET failed\n");
5199 			return ret;
5200 		}
5201 
5202 		ret = ufshcd_dme_enable(hba);
5203 		if (ret) {
5204 			dev_err(hba->dev, "Enabling DME failed\n");
5205 			return ret;
5206 		}
5207 
5208 		ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
5209 	} else {
5210 		ret = ufshcd_hba_execute_hce(hba);
5211 	}
5212 
5213 	return ret;
5214 }
5215 EXPORT_SYMBOL_GPL(ufshcd_hba_enable);
5216 
5217 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
5218 {
5219 	int tx_lanes, i, err = 0;
5220 
5221 	if (!peer)
5222 		ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
5223 			       &tx_lanes);
5224 	else
5225 		ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
5226 				    &tx_lanes);
5227 	for (i = 0; i < tx_lanes; i++) {
5228 		if (!peer)
5229 			err = ufshcd_dme_set(hba,
5230 				UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
5231 					UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
5232 					0);
5233 		else
5234 			err = ufshcd_dme_peer_set(hba,
5235 				UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
5236 					UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
5237 					0);
5238 		if (err) {
5239 			dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
5240 				__func__, peer, i, err);
5241 			break;
5242 		}
5243 	}
5244 
5245 	return err;
5246 }
5247 
5248 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
5249 {
5250 	return ufshcd_disable_tx_lcc(hba, true);
5251 }
5252 
5253 void ufshcd_update_evt_hist(struct ufs_hba *hba, u32 id, u32 val)
5254 {
5255 	struct ufs_event_hist *e;
5256 
5257 	if (id >= UFS_EVT_CNT)
5258 		return;
5259 
5260 	e = &hba->ufs_stats.event[id];
5261 	e->val[e->pos] = val;
5262 	e->tstamp[e->pos] = local_clock();
5263 	e->cnt += 1;
5264 	e->pos = (e->pos + 1) % UFS_EVENT_HIST_LENGTH;
5265 
5266 	ufshcd_vops_event_notify(hba, id, &val);
5267 }
5268 EXPORT_SYMBOL_GPL(ufshcd_update_evt_hist);
5269 
5270 static int ufshcd_validate_link_params(struct ufs_hba *hba)
5271 {
5272 	int ret, val;
5273 
5274 	/*
5275 	 * lanes_per_direction is only populated by the platform glue (it
5276 	 * defaults to 2 or is read from the "lanes-per-direction" devicetree
5277 	 * property). Controllers probed via ufshcd-pci leave it unset (0), in
5278 	 * which case there is no expected lane count to validate the connected
5279 	 * lanes against. Skip the check instead of failing link startup.
5280 	 */
5281 	if (!hba->lanes_per_direction)
5282 		return 0;
5283 
5284 	ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
5285 			     &val);
5286 	if (ret)
5287 		return ret;
5288 
5289 	if (val != hba->lanes_per_direction) {
5290 		dev_err(hba->dev, "Tx lane mismatch [config,reported] [%d,%d]\n",
5291 			hba->lanes_per_direction, val);
5292 		return -ENOLINK;
5293 	}
5294 
5295 	ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
5296 			     &val);
5297 	if (ret)
5298 		return ret;
5299 
5300 	if (val != hba->lanes_per_direction) {
5301 		dev_err(hba->dev, "Rx lane mismatch [config,reported] [%d,%d]\n",
5302 			hba->lanes_per_direction, val);
5303 		return -ENOLINK;
5304 	}
5305 
5306 	return 0;
5307 }
5308 
5309 /**
5310  * ufshcd_link_startup - Initialize unipro link startup
5311  * @hba: per adapter instance
5312  *
5313  * Return: 0 for success, non-zero in case of failure.
5314  */
5315 static int ufshcd_link_startup(struct ufs_hba *hba)
5316 {
5317 	int ret;
5318 	int retries = DME_LINKSTARTUP_RETRIES;
5319 	bool link_startup_again = false;
5320 
5321 	/*
5322 	 * If UFS device isn't active then we will have to issue link startup
5323 	 * 2 times to make sure the device state move to active.
5324 	 */
5325 	if (!(hba->quirks & UFSHCD_QUIRK_PERFORM_LINK_STARTUP_ONCE) &&
5326 	    !ufshcd_is_ufs_dev_active(hba))
5327 		link_startup_again = true;
5328 
5329 link_startup:
5330 	do {
5331 		ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
5332 
5333 		ret = ufshcd_dme_link_startup(hba);
5334 
5335 		/* check if device is detected by inter-connect layer */
5336 		if (!ret && !ufshcd_is_device_present(hba)) {
5337 			ufshcd_update_evt_hist(hba,
5338 					       UFS_EVT_LINK_STARTUP_FAIL,
5339 					       0);
5340 			dev_err(hba->dev, "%s: Device not present\n", __func__);
5341 			ret = -ENXIO;
5342 			goto out;
5343 		}
5344 
5345 		/*
5346 		 * DME link lost indication is only received when link is up,
5347 		 * but we can't be sure if the link is up until link startup
5348 		 * succeeds. So reset the local Uni-Pro and try again.
5349 		 */
5350 		if (ret && retries && ufshcd_hba_enable(hba)) {
5351 			ufshcd_update_evt_hist(hba,
5352 					       UFS_EVT_LINK_STARTUP_FAIL,
5353 					       (u32)ret);
5354 			goto out;
5355 		}
5356 	} while (ret && retries--);
5357 
5358 	if (ret) {
5359 		/* failed to get the link up... retire */
5360 		ufshcd_update_evt_hist(hba,
5361 				       UFS_EVT_LINK_STARTUP_FAIL,
5362 				       (u32)ret);
5363 		goto out;
5364 	}
5365 
5366 	if (link_startup_again) {
5367 		link_startup_again = false;
5368 		retries = DME_LINKSTARTUP_RETRIES;
5369 		goto link_startup;
5370 	}
5371 
5372 	/* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
5373 	ufshcd_init_pwr_info(hba);
5374 	ufshcd_print_pwr_info(hba);
5375 
5376 	if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
5377 		ret = ufshcd_disable_device_tx_lcc(hba);
5378 		if (ret)
5379 			goto out;
5380 	}
5381 
5382 	ret = ufshcd_validate_link_params(hba);
5383 	if (ret)
5384 		goto out;
5385 
5386 	/* Include any host controller configuration via UIC commands */
5387 	ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
5388 	if (ret)
5389 		goto out;
5390 
5391 	/* Clear UECPA once due to LINERESET has happened during LINK_STARTUP */
5392 	ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
5393 	ret = ufshcd_make_hba_operational(hba);
5394 out:
5395 	if (ret)
5396 		dev_err(hba->dev, "link startup failed %d\n", ret);
5397 	return ret;
5398 }
5399 
5400 /**
5401  * ufshcd_verify_dev_init() - Verify device initialization
5402  * @hba: per-adapter instance
5403  *
5404  * Send NOP OUT UPIU and wait for NOP IN response to check whether the
5405  * device Transport Protocol (UTP) layer is ready after a reset.
5406  * If the UTP layer at the device side is not initialized, it may
5407  * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
5408  * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
5409  *
5410  * Return: 0 upon success; > 0 in case the UFS device reported an OCS error;
5411  * < 0 if another error occurred.
5412  */
5413 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
5414 {
5415 	int err = 0;
5416 	int retries;
5417 
5418 	ufshcd_dev_man_lock(hba);
5419 
5420 	for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
5421 		err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
5422 					  hba->nop_out_timeout);
5423 
5424 		if (!err || err == -ETIMEDOUT)
5425 			break;
5426 
5427 		dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
5428 	}
5429 
5430 	ufshcd_dev_man_unlock(hba);
5431 
5432 	if (err)
5433 		dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
5434 	return err;
5435 }
5436 
5437 /**
5438  * ufshcd_setup_links - associate link b/w device wlun and other luns
5439  * @sdev: pointer to SCSI device
5440  * @hba: pointer to ufs hba
5441  */
5442 static void ufshcd_setup_links(struct ufs_hba *hba, struct scsi_device *sdev)
5443 {
5444 	struct device_link *link;
5445 
5446 	/*
5447 	 * Device wlun is the supplier & rest of the luns are consumers.
5448 	 * This ensures that device wlun suspends after all other luns.
5449 	 */
5450 	if (hba->ufs_device_wlun) {
5451 		link = device_link_add(&sdev->sdev_gendev,
5452 				       &hba->ufs_device_wlun->sdev_gendev,
5453 				       DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE);
5454 		if (!link) {
5455 			dev_err(&sdev->sdev_gendev, "Failed establishing link - %s\n",
5456 				dev_name(&hba->ufs_device_wlun->sdev_gendev));
5457 			return;
5458 		}
5459 		hba->luns_avail--;
5460 		/* Ignore REPORT_LUN wlun probing */
5461 		if (hba->luns_avail == 1) {
5462 			ufshcd_rpm_put(hba);
5463 			return;
5464 		}
5465 	} else {
5466 		/*
5467 		 * Device wlun is probed. The assumption is that WLUNs are
5468 		 * scanned before other LUNs.
5469 		 */
5470 		hba->luns_avail--;
5471 	}
5472 }
5473 
5474 /**
5475  * ufshcd_lu_init - Initialize the relevant parameters of the LU
5476  * @hba: per-adapter instance
5477  * @sdev: pointer to SCSI device
5478  */
5479 static void ufshcd_lu_init(struct ufs_hba *hba, struct scsi_device *sdev)
5480 {
5481 	int len = QUERY_DESC_MAX_SIZE;
5482 	u8 lun = ufshcd_scsi_to_upiu_lun(sdev->lun);
5483 	u8 lun_qdepth = hba->nutrs;
5484 	u8 *desc_buf;
5485 	int ret;
5486 
5487 	desc_buf = kzalloc(len, GFP_KERNEL);
5488 	if (!desc_buf)
5489 		goto set_qdepth;
5490 
5491 	ret = ufshcd_read_unit_desc_param(hba, lun, 0, desc_buf, len);
5492 	if (ret < 0) {
5493 		if (ret == -EOPNOTSUPP)
5494 			/* If LU doesn't support unit descriptor, its queue depth is set to 1 */
5495 			lun_qdepth = 1;
5496 		kfree(desc_buf);
5497 		goto set_qdepth;
5498 	}
5499 
5500 	if (desc_buf[UNIT_DESC_PARAM_LU_Q_DEPTH]) {
5501 		/*
5502 		 * In per-LU queueing architecture, bLUQueueDepth will not be 0, then we will
5503 		 * use the smaller between UFSHCI CAP.NUTRS and UFS LU bLUQueueDepth
5504 		 */
5505 		lun_qdepth = min_t(int, desc_buf[UNIT_DESC_PARAM_LU_Q_DEPTH], hba->nutrs);
5506 	}
5507 	/*
5508 	 * According to UFS device specification, the write protection mode is only supported by
5509 	 * normal LU, not supported by WLUN.
5510 	 */
5511 	if (hba->dev_info.f_power_on_wp_en && lun < hba->dev_info.max_lu_supported &&
5512 	    !hba->dev_info.is_lu_power_on_wp &&
5513 	    desc_buf[UNIT_DESC_PARAM_LU_WR_PROTECT] == UFS_LU_POWER_ON_WP)
5514 		hba->dev_info.is_lu_power_on_wp = true;
5515 
5516 	/* In case of RPMB LU, check if advanced RPMB mode is enabled, and get region size */
5517 	if (desc_buf[UNIT_DESC_PARAM_UNIT_INDEX] == UFS_UPIU_RPMB_WLUN) {
5518 		if (desc_buf[RPMB_UNIT_DESC_PARAM_REGION_EN] & BIT(4))
5519 			hba->dev_info.b_advanced_rpmb_en = true;
5520 		hba->dev_info.rpmb_region_size[0] = desc_buf[RPMB_UNIT_DESC_PARAM_REGION0_SIZE];
5521 		hba->dev_info.rpmb_region_size[1] = desc_buf[RPMB_UNIT_DESC_PARAM_REGION1_SIZE];
5522 		hba->dev_info.rpmb_region_size[2] = desc_buf[RPMB_UNIT_DESC_PARAM_REGION2_SIZE];
5523 		hba->dev_info.rpmb_region_size[3] = desc_buf[RPMB_UNIT_DESC_PARAM_REGION3_SIZE];
5524 
5525 		if (hba->dev_info.wspecversion <= 0x0220) {
5526 			/*
5527 			 * These older spec chips have only one RPMB region,
5528 			 * sized between 128 kB minimum and 16 MB maximum.
5529 			 * No per region size fields are provided (respective
5530 			 * REGIONX_SIZE fields always contain zeros), so get
5531 			 * it from the logical block count and size fields for
5532 			 * compatibility
5533 			 *
5534 			 * (See JESD220C-2_2 Section 14.1.4.6
5535 			 * RPMB Unit Descriptor,* offset 13h, 4 bytes)
5536 			 */
5537 			hba->dev_info.rpmb_region_size[0] =
5538 				(get_unaligned_be64(desc_buf
5539 					+ RPMB_UNIT_DESC_PARAM_LOGICAL_BLK_COUNT)
5540 				<< desc_buf[RPMB_UNIT_DESC_PARAM_LOGICAL_BLK_SIZE])
5541 				/ SZ_128K;
5542 		}
5543 	}
5544 
5545 
5546 	kfree(desc_buf);
5547 set_qdepth:
5548 	/*
5549 	 * For WLUNs that don't support unit descriptor, queue depth is set to 1. For LUs whose
5550 	 * bLUQueueDepth == 0, the queue depth is set to a maximum value that host can queue.
5551 	 */
5552 	dev_dbg(hba->dev, "Set LU %x queue depth %d\n", lun, lun_qdepth);
5553 	scsi_change_queue_depth(sdev, lun_qdepth);
5554 }
5555 
5556 /**
5557  * ufshcd_sdev_init - handle initial SCSI device configurations
5558  * @sdev: pointer to SCSI device
5559  *
5560  * Return: success.
5561  */
5562 static int ufshcd_sdev_init(struct scsi_device *sdev)
5563 {
5564 	struct ufs_hba *hba;
5565 
5566 	hba = shost_priv(sdev->host);
5567 
5568 	/* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
5569 	sdev->use_10_for_ms = 1;
5570 
5571 	/* DBD field should be set to 1 in mode sense(10) */
5572 	sdev->set_dbd_for_ms = 1;
5573 
5574 	/* allow SCSI layer to restart the device in case of errors */
5575 	sdev->allow_restart = 1;
5576 
5577 	/* REPORT SUPPORTED OPERATION CODES is not supported */
5578 	sdev->no_report_opcodes = 1;
5579 
5580 	/* WRITE_SAME command is not supported */
5581 	sdev->no_write_same = 1;
5582 
5583 	ufshcd_lu_init(hba, sdev);
5584 
5585 	ufshcd_setup_links(hba, sdev);
5586 
5587 	return 0;
5588 }
5589 
5590 /**
5591  * ufshcd_change_queue_depth - change queue depth
5592  * @sdev: pointer to SCSI device
5593  * @depth: required depth to set
5594  *
5595  * Change queue depth and make sure the max. limits are not crossed.
5596  *
5597  * Return: new queue depth.
5598  */
5599 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
5600 {
5601 	return scsi_change_queue_depth(sdev, min(depth, sdev->host->can_queue));
5602 }
5603 
5604 /**
5605  * ufshcd_sdev_configure - adjust SCSI device configurations
5606  * @sdev: pointer to SCSI device
5607  * @lim: queue limits
5608  *
5609  * Return: 0 (success).
5610  */
5611 static int ufshcd_sdev_configure(struct scsi_device *sdev,
5612 				 struct queue_limits *lim)
5613 {
5614 	struct ufs_hba *hba = shost_priv(sdev->host);
5615 	struct request_queue *q = sdev->request_queue;
5616 
5617 	lim->dma_pad_mask = PRDT_DATA_BYTE_COUNT_PAD - 1;
5618 
5619 	/*
5620 	 * Block runtime-pm until all consumers are added.
5621 	 * Refer ufshcd_setup_links().
5622 	 */
5623 	if (is_device_wlun(sdev))
5624 		pm_runtime_get_noresume(&sdev->sdev_gendev);
5625 	else if (ufshcd_is_rpm_autosuspend_allowed(hba))
5626 		sdev->rpm_autosuspend = 1;
5627 	/*
5628 	 * Do not print messages during runtime PM to avoid never-ending cycles
5629 	 * of messages written back to storage by user space causing runtime
5630 	 * resume, causing more messages and so on.
5631 	 */
5632 	sdev->silence_suspend = 1;
5633 
5634 	if (hba->vops && hba->vops->config_scsi_dev)
5635 		hba->vops->config_scsi_dev(sdev);
5636 
5637 	ufshcd_crypto_register(hba, q);
5638 
5639 	return 0;
5640 }
5641 
5642 /**
5643  * ufshcd_sdev_destroy - remove SCSI device configurations
5644  * @sdev: pointer to SCSI device
5645  */
5646 static void ufshcd_sdev_destroy(struct scsi_device *sdev)
5647 {
5648 	struct ufs_hba *hba;
5649 	unsigned long flags;
5650 
5651 	hba = shost_priv(sdev->host);
5652 
5653 	/* Drop the reference as it won't be needed anymore */
5654 	if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
5655 		spin_lock_irqsave(hba->host->host_lock, flags);
5656 		hba->ufs_device_wlun = NULL;
5657 		spin_unlock_irqrestore(hba->host->host_lock, flags);
5658 	} else if (hba->ufs_device_wlun) {
5659 		struct device *supplier = NULL;
5660 
5661 		/* Ensure UFS Device WLUN exists and does not disappear */
5662 		spin_lock_irqsave(hba->host->host_lock, flags);
5663 		if (hba->ufs_device_wlun) {
5664 			supplier = &hba->ufs_device_wlun->sdev_gendev;
5665 			get_device(supplier);
5666 		}
5667 		spin_unlock_irqrestore(hba->host->host_lock, flags);
5668 
5669 		if (supplier) {
5670 			/*
5671 			 * If a LUN fails to probe (e.g. absent BOOT WLUN), the
5672 			 * device will not have been registered but can still
5673 			 * have a device link holding a reference to the device.
5674 			 */
5675 			device_link_remove(&sdev->sdev_gendev, supplier);
5676 			put_device(supplier);
5677 		}
5678 	}
5679 }
5680 
5681 /**
5682  * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
5683  * @cmd: SCSI command
5684  * @scsi_status: SCSI command status
5685  *
5686  * Return: value base on SCSI command status.
5687  */
5688 static inline int ufshcd_scsi_cmd_status(struct scsi_cmnd *cmd, int scsi_status)
5689 {
5690 	int result = 0;
5691 
5692 	switch (scsi_status) {
5693 	case SAM_STAT_CHECK_CONDITION:
5694 		ufshcd_copy_sense_data(cmd);
5695 		fallthrough;
5696 	case SAM_STAT_GOOD:
5697 		result |= DID_OK << 16 | scsi_status;
5698 		break;
5699 	case SAM_STAT_TASK_SET_FULL:
5700 	case SAM_STAT_BUSY:
5701 	case SAM_STAT_TASK_ABORTED:
5702 		ufshcd_copy_sense_data(cmd);
5703 		result |= scsi_status;
5704 		break;
5705 	default:
5706 		result |= DID_ERROR << 16;
5707 		break;
5708 	} /* end of switch */
5709 
5710 	return result;
5711 }
5712 
5713 /**
5714  * ufshcd_transfer_rsp_status - Get overall status of the response
5715  * @hba: per adapter instance
5716  * @cmd: SCSI command
5717  * @cqe: pointer to the completion queue entry
5718  *
5719  * Return: result of the command to notify SCSI midlayer.
5720  */
5721 static inline int ufshcd_transfer_rsp_status(struct ufs_hba *hba,
5722 					     struct scsi_cmnd *cmd,
5723 					     struct cq_entry *cqe)
5724 {
5725 	struct ufshcd_lrb *lrbp = scsi_cmd_priv(cmd);
5726 	const int tag = scsi_cmd_to_rq(cmd)->tag;
5727 	int result = 0;
5728 	int scsi_status;
5729 	enum utp_ocs ocs;
5730 	u8 upiu_flags;
5731 	u32 resid;
5732 
5733 	upiu_flags = lrbp->ucd_rsp_ptr->header.flags;
5734 	resid = be32_to_cpu(lrbp->ucd_rsp_ptr->sr.residual_transfer_count);
5735 	/*
5736 	 * Test !overflow instead of underflow to support UFS devices that do
5737 	 * not set either flag.
5738 	 */
5739 	if (resid && !(upiu_flags & UPIU_RSP_FLAG_OVERFLOW))
5740 		scsi_set_resid(cmd, resid);
5741 
5742 	/* overall command status of utrd */
5743 	ocs = ufshcd_get_tr_ocs(lrbp, cqe);
5744 
5745 	if (hba->quirks & UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR) {
5746 		if (lrbp->ucd_rsp_ptr->header.response ||
5747 		    lrbp->ucd_rsp_ptr->header.status)
5748 			ocs = OCS_SUCCESS;
5749 	}
5750 
5751 	switch (ocs) {
5752 	case OCS_SUCCESS:
5753 		hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
5754 		switch (ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr)) {
5755 		case UPIU_TRANSACTION_RESPONSE:
5756 			/*
5757 			 * get the result based on SCSI status response
5758 			 * to notify the SCSI midlayer of the command status
5759 			 */
5760 			scsi_status = lrbp->ucd_rsp_ptr->header.status;
5761 			result = ufshcd_scsi_cmd_status(cmd, scsi_status);
5762 
5763 			/*
5764 			 * Currently we are only supporting BKOPs exception
5765 			 * events hence we can ignore BKOPs exception event
5766 			 * during power management callbacks. BKOPs exception
5767 			 * event is not expected to be raised in runtime suspend
5768 			 * callback as it allows the urgent bkops.
5769 			 * During system suspend, we are anyway forcefully
5770 			 * disabling the bkops and if urgent bkops is needed
5771 			 * it will be enabled on system resume. Long term
5772 			 * solution could be to abort the system suspend if
5773 			 * UFS device needs urgent BKOPs.
5774 			 */
5775 			if (!hba->pm_op_in_progress &&
5776 			    !ufshcd_eh_in_progress(hba) &&
5777 			    ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
5778 				/* Flushed in suspend */
5779 				schedule_work(&hba->eeh_work);
5780 			break;
5781 		case UPIU_TRANSACTION_REJECT_UPIU:
5782 			/* TODO: handle Reject UPIU Response */
5783 			result = DID_ERROR << 16;
5784 			dev_err(hba->dev,
5785 				"Reject UPIU not fully implemented\n");
5786 			break;
5787 		default:
5788 			dev_err(hba->dev,
5789 				"Unexpected request response code = %x\n",
5790 				ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr));
5791 			result = DID_ERROR << 16;
5792 			break;
5793 		}
5794 		break;
5795 	case OCS_ABORTED:
5796 	case OCS_INVALID_COMMAND_STATUS:
5797 		result |= DID_REQUEUE << 16;
5798 		dev_warn(hba->dev, "OCS %s from controller for tag %d\n",
5799 			 ocs == OCS_ABORTED ? "aborted" : "invalid", tag);
5800 		break;
5801 	case OCS_INVALID_CMD_TABLE_ATTR:
5802 	case OCS_INVALID_PRDT_ATTR:
5803 	case OCS_MISMATCH_DATA_BUF_SIZE:
5804 	case OCS_MISMATCH_RESP_UPIU_SIZE:
5805 	case OCS_PEER_COMM_FAILURE:
5806 	case OCS_FATAL_ERROR:
5807 	case OCS_DEVICE_FATAL_ERROR:
5808 	case OCS_INVALID_CRYPTO_CONFIG:
5809 	case OCS_GENERAL_CRYPTO_ERROR:
5810 	default:
5811 		result |= DID_ERROR << 16;
5812 		dev_err(hba->dev, "OCS error from controller = %x for tag %d\n",
5813 			ocs, tag);
5814 		ufshcd_print_evt_hist(hba);
5815 		ufshcd_print_host_state(hba);
5816 		break;
5817 	} /* end of switch */
5818 
5819 	if ((host_byte(result) != DID_OK) &&
5820 	    (host_byte(result) != DID_REQUEUE) && !hba->silence_err_logs) {
5821 		if (cqe)
5822 			ufshcd_hex_dump("UPIU CQE: ", cqe, sizeof(struct cq_entry));
5823 		ufshcd_print_tr(hba, cmd, true);
5824 	}
5825 	return result;
5826 }
5827 
5828 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
5829 					 u32 intr_mask)
5830 {
5831 	if (!ufshcd_is_auto_hibern8_supported(hba) ||
5832 	    !ufshcd_is_auto_hibern8_enabled(hba))
5833 		return false;
5834 
5835 	if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
5836 		return false;
5837 
5838 	if (hba->active_uic_cmd &&
5839 	    (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
5840 	    hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
5841 		return false;
5842 
5843 	return true;
5844 }
5845 
5846 /**
5847  * ufshcd_uic_cmd_compl - handle completion of uic command
5848  * @hba: per adapter instance
5849  * @intr_status: interrupt status generated by the controller
5850  *
5851  * Return:
5852  *  IRQ_HANDLED - If interrupt is valid
5853  *  IRQ_NONE    - If invalid interrupt
5854  */
5855 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
5856 {
5857 	irqreturn_t retval = IRQ_NONE;
5858 	struct uic_command *cmd;
5859 
5860 	guard(spinlock_irqsave)(hba->host->host_lock);
5861 	cmd = hba->active_uic_cmd;
5862 	if (!cmd) {
5863 		dev_err(hba->dev,
5864 			"No active UIC command. Maybe a timeout occurred?\n");
5865 		return retval;
5866 	}
5867 
5868 	if (ufshcd_is_auto_hibern8_error(hba, intr_status))
5869 		hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
5870 
5871 	if (intr_status & UIC_COMMAND_COMPL) {
5872 		/*
5873 		 * Store the UIC command result in the lowest byte of
5874 		 * cmd->argument2.
5875 		 */
5876 		cmd->argument2 |= ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
5877 				  MASK_UIC_COMMAND_RESULT;
5878 		/* Store the DME attribute value in cmd->argument3. */
5879 		cmd->argument3 = ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
5880 		if (!hba->uic_async_done)
5881 			cmd->cmd_active = false;
5882 		complete(&cmd->done);
5883 		retval = IRQ_HANDLED;
5884 	}
5885 
5886 	if (intr_status & UFSHCD_UIC_PWR_MASK && hba->uic_async_done) {
5887 		cmd->cmd_active = false;
5888 		complete(hba->uic_async_done);
5889 		retval = IRQ_HANDLED;
5890 	}
5891 
5892 	if (retval == IRQ_HANDLED)
5893 		ufshcd_add_uic_command_trace(hba, cmd, UFS_CMD_COMP);
5894 
5895 	return retval;
5896 }
5897 
5898 /* Release the resources allocated for processing a SCSI command. */
5899 void ufshcd_release_scsi_cmd(struct ufs_hba *hba, struct scsi_cmnd *cmd)
5900 {
5901 	scsi_dma_unmap(cmd);
5902 	ufshcd_crypto_clear_prdt(hba, cmd);
5903 	ufshcd_release(hba);
5904 	ufshcd_clk_scaling_update_busy(hba);
5905 }
5906 
5907 /**
5908  * ufshcd_compl_one_cqe - handle a completion queue entry
5909  * @hba: per adapter instance
5910  * @task_tag: the task tag of the request to be completed
5911  * @cqe: pointer to the completion queue entry
5912  */
5913 void ufshcd_compl_one_cqe(struct ufs_hba *hba, int task_tag,
5914 			  struct cq_entry *cqe)
5915 {
5916 	struct scsi_cmnd *cmd = ufshcd_tag_to_cmd(hba, task_tag);
5917 	struct ufshcd_lrb *lrbp = scsi_cmd_priv(cmd);
5918 	enum utp_ocs ocs;
5919 
5920 	if (WARN_ONCE(!cmd, "invalid completion tag %d, cqe->command_desc_base_addr = %#llx\n",
5921 		      task_tag, cqe ? le64_to_cpu(cqe->command_desc_base_addr) : 0ULL))
5922 		return;
5923 
5924 	if (hba->monitor.enabled) {
5925 		lrbp->compl_time_stamp = ktime_get();
5926 		lrbp->compl_time_stamp_local_clock = local_clock();
5927 	}
5928 	if (ufshcd_is_scsi_cmd(cmd)) {
5929 		if (unlikely(ufshcd_should_inform_monitor(hba, cmd)))
5930 			ufshcd_update_monitor(hba, cmd);
5931 		ufshcd_add_command_trace(hba, cmd, UFS_CMD_COMP);
5932 		cmd->result = ufshcd_transfer_rsp_status(hba, cmd, cqe);
5933 		ufshcd_release_scsi_cmd(hba, cmd);
5934 	} else {
5935 		if (cqe) {
5936 			ocs = cqe->overall_status & MASK_OCS;
5937 			lrbp->utr_descriptor_ptr->header.ocs = ocs;
5938 		} else {
5939 			ocs = lrbp->utr_descriptor_ptr->header.ocs;
5940 		}
5941 		ufshcd_add_query_upiu_trace(
5942 			hba,
5943 			ocs == OCS_SUCCESS ? UFS_QUERY_COMP : UFS_QUERY_ERR,
5944 			(struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
5945 		cmd->result = 0;
5946 	}
5947 	/* Do not touch lrbp after scsi_done() has been called. */
5948 	scsi_done(cmd);
5949 }
5950 
5951 /**
5952  * __ufshcd_transfer_req_compl - handle SCSI and query command completion
5953  * @hba: per adapter instance
5954  * @completed_reqs: bitmask that indicates which requests to complete
5955  */
5956 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
5957 					unsigned long completed_reqs)
5958 {
5959 	int tag;
5960 
5961 	for_each_set_bit(tag, &completed_reqs, hba->nutrs)
5962 		ufshcd_compl_one_cqe(hba, tag, NULL);
5963 }
5964 
5965 /* Any value that is not an existing queue number is fine for this constant. */
5966 enum {
5967 	UFSHCD_POLL_FROM_INTERRUPT_CONTEXT = -1
5968 };
5969 
5970 static void ufshcd_clear_polled(struct ufs_hba *hba,
5971 				unsigned long *completed_reqs)
5972 {
5973 	int tag;
5974 
5975 	for_each_set_bit(tag, completed_reqs, hba->nutrs) {
5976 		struct scsi_cmnd *cmd = scsi_host_find_tag(hba->host, tag);
5977 
5978 		if (!cmd)
5979 			continue;
5980 		if (scsi_cmd_to_rq(cmd)->cmd_flags & REQ_POLLED)
5981 			__clear_bit(tag, completed_reqs);
5982 	}
5983 }
5984 
5985 /*
5986  * Return: > 0 if one or more commands have been completed or 0 if no
5987  * requests have been completed.
5988  */
5989 static int ufshcd_poll(struct Scsi_Host *shost, unsigned int queue_num)
5990 {
5991 	struct ufs_hba *hba = shost_priv(shost);
5992 	unsigned long completed_reqs, flags;
5993 	u32 tr_doorbell;
5994 	struct ufs_hw_queue *hwq;
5995 
5996 	if (hba->mcq_enabled) {
5997 		hwq = &hba->uhq[queue_num];
5998 
5999 		return ufshcd_mcq_poll_cqe_lock(hba, hwq);
6000 	}
6001 
6002 	spin_lock_irqsave(&hba->outstanding_lock, flags);
6003 	tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6004 	completed_reqs = ~tr_doorbell & hba->outstanding_reqs;
6005 	WARN_ONCE(completed_reqs & ~hba->outstanding_reqs,
6006 		  "completed: %#lx; outstanding: %#lx\n", completed_reqs,
6007 		  hba->outstanding_reqs);
6008 	if (queue_num == UFSHCD_POLL_FROM_INTERRUPT_CONTEXT) {
6009 		/* Do not complete polled requests from interrupt context. */
6010 		ufshcd_clear_polled(hba, &completed_reqs);
6011 	}
6012 	hba->outstanding_reqs &= ~completed_reqs;
6013 	spin_unlock_irqrestore(&hba->outstanding_lock, flags);
6014 
6015 	if (completed_reqs)
6016 		__ufshcd_transfer_req_compl(hba, completed_reqs);
6017 
6018 	return completed_reqs != 0;
6019 }
6020 
6021 static bool ufshcd_mcq_force_compl_one(struct request *rq, void *priv)
6022 {
6023 	struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
6024 	struct scsi_device *sdev = rq->q->queuedata;
6025 	struct Scsi_Host *shost = sdev->host;
6026 	struct ufs_hba *hba = shost_priv(shost);
6027 	struct ufs_hw_queue *hwq = ufshcd_mcq_req_to_hwq(hba, rq);
6028 
6029 	if (blk_mq_is_reserved_rq(rq) || !hwq)
6030 		return true;
6031 
6032 	ufshcd_mcq_compl_all_cqes_lock(hba, hwq);
6033 
6034 	/*
6035 	 * For those cmds of which the cqes are not present in the cq, complete
6036 	 * them explicitly.
6037 	 */
6038 	scoped_guard(spinlock_irqsave, &hwq->cq_lock) {
6039 		if (!test_bit(SCMD_STATE_COMPLETE, &cmd->state)) {
6040 			set_host_byte(cmd, DID_REQUEUE);
6041 			ufshcd_release_scsi_cmd(hba, cmd);
6042 			scsi_done(cmd);
6043 		}
6044 	}
6045 
6046 	return true;
6047 }
6048 
6049 static bool ufshcd_mcq_compl_one(struct request *rq, void *priv)
6050 {
6051 	struct scsi_device *sdev = rq->q->queuedata;
6052 	struct Scsi_Host *shost = sdev->host;
6053 	struct ufs_hba *hba = shost_priv(shost);
6054 	struct ufs_hw_queue *hwq = ufshcd_mcq_req_to_hwq(hba, rq);
6055 
6056 	if (!blk_mq_is_reserved_rq(rq) && hwq)
6057 		ufshcd_mcq_poll_cqe_lock(hba, hwq);
6058 
6059 	return true;
6060 }
6061 
6062 /**
6063  * ufshcd_mcq_compl_pending_transfer - MCQ mode function. It is
6064  * invoked from the error handler context or ufshcd_host_reset_and_restore()
6065  * to complete the pending transfers and free the resources associated with
6066  * the scsi command.
6067  *
6068  * @hba: per adapter instance
6069  * @force_compl: This flag is set to true when invoked
6070  * from ufshcd_host_reset_and_restore() in which case it requires special
6071  * handling because the host controller has been reset by ufshcd_hba_stop().
6072  */
6073 static void ufshcd_mcq_compl_pending_transfer(struct ufs_hba *hba,
6074 					      bool force_compl)
6075 {
6076 	blk_mq_tagset_busy_iter(&hba->host->tag_set,
6077 				force_compl ? ufshcd_mcq_force_compl_one :
6078 					      ufshcd_mcq_compl_one,
6079 				NULL);
6080 }
6081 
6082 /**
6083  * ufshcd_transfer_req_compl - handle SCSI and query command completion
6084  * @hba: per adapter instance
6085  *
6086  * Return:
6087  *  IRQ_HANDLED - If interrupt is valid
6088  *  IRQ_NONE    - If invalid interrupt
6089  */
6090 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba)
6091 {
6092 	/* Resetting interrupt aggregation counters first and reading the
6093 	 * DOOR_BELL afterward allows us to handle all the completed requests.
6094 	 * In order to prevent other interrupts starvation the DB is read once
6095 	 * after reset. The down side of this solution is the possibility of
6096 	 * false interrupt if device completes another request after resetting
6097 	 * aggregation and before reading the DB.
6098 	 */
6099 	if (ufshcd_is_intr_aggr_allowed(hba) &&
6100 	    !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
6101 		ufshcd_reset_intr_aggr(hba);
6102 
6103 	if (ufs_fail_completion(hba))
6104 		return IRQ_HANDLED;
6105 
6106 	/*
6107 	 * Ignore the ufshcd_poll() return value and return IRQ_HANDLED since we
6108 	 * do not want polling to trigger spurious interrupt complaints.
6109 	 */
6110 	ufshcd_poll(hba->host, UFSHCD_POLL_FROM_INTERRUPT_CONTEXT);
6111 
6112 	return IRQ_HANDLED;
6113 }
6114 
6115 int __ufshcd_write_ee_control(struct ufs_hba *hba, u32 ee_ctrl_mask)
6116 {
6117 	return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
6118 				       QUERY_ATTR_IDN_EE_CONTROL, 0, 0,
6119 				       &ee_ctrl_mask);
6120 }
6121 
6122 int ufshcd_write_ee_control(struct ufs_hba *hba)
6123 {
6124 	int err;
6125 
6126 	mutex_lock(&hba->ee_ctrl_mutex);
6127 	err = __ufshcd_write_ee_control(hba, hba->ee_ctrl_mask);
6128 	mutex_unlock(&hba->ee_ctrl_mutex);
6129 	if (err)
6130 		dev_err(hba->dev, "%s: failed to write ee control %d\n",
6131 			__func__, err);
6132 	return err;
6133 }
6134 
6135 int ufshcd_update_ee_control(struct ufs_hba *hba, u16 *mask,
6136 			     const u16 *other_mask, u16 set, u16 clr)
6137 {
6138 	u16 new_mask, ee_ctrl_mask;
6139 	int err = 0;
6140 
6141 	mutex_lock(&hba->ee_ctrl_mutex);
6142 	new_mask = (*mask & ~clr) | set;
6143 	ee_ctrl_mask = new_mask | *other_mask;
6144 	if (ee_ctrl_mask != hba->ee_ctrl_mask)
6145 		err = __ufshcd_write_ee_control(hba, ee_ctrl_mask);
6146 	/* Still need to update 'mask' even if 'ee_ctrl_mask' was unchanged */
6147 	if (!err) {
6148 		hba->ee_ctrl_mask = ee_ctrl_mask;
6149 		*mask = new_mask;
6150 	}
6151 	mutex_unlock(&hba->ee_ctrl_mutex);
6152 	return err;
6153 }
6154 
6155 /**
6156  * ufshcd_disable_ee - disable exception event
6157  * @hba: per-adapter instance
6158  * @mask: exception event to disable
6159  *
6160  * Disables exception event in the device so that the EVENT_ALERT
6161  * bit is not set.
6162  *
6163  * Return: zero on success, non-zero error value on failure.
6164  */
6165 static inline int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
6166 {
6167 	return ufshcd_update_ee_drv_mask(hba, 0, mask);
6168 }
6169 
6170 /**
6171  * ufshcd_enable_ee - enable exception event
6172  * @hba: per-adapter instance
6173  * @mask: exception event to enable
6174  *
6175  * Enable corresponding exception event in the device to allow
6176  * device to alert host in critical scenarios.
6177  *
6178  * Return: zero on success, non-zero error value on failure.
6179  */
6180 static inline int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
6181 {
6182 	return ufshcd_update_ee_drv_mask(hba, mask, 0);
6183 }
6184 
6185 /**
6186  * ufshcd_enable_auto_bkops - Allow device managed BKOPS
6187  * @hba: per-adapter instance
6188  *
6189  * Allow device to manage background operations on its own. Enabling
6190  * this might lead to inconsistent latencies during normal data transfers
6191  * as the device is allowed to manage its own way of handling background
6192  * operations.
6193  *
6194  * Return: 0 upon success; > 0 in case the UFS device reported an OCS error;
6195  * < 0 if another error occurred.
6196  */
6197 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
6198 {
6199 	int err = 0;
6200 
6201 	if (hba->auto_bkops_enabled)
6202 		goto out;
6203 
6204 	err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
6205 			QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
6206 	if (err) {
6207 		dev_err(hba->dev, "%s: failed to enable bkops %d\n",
6208 				__func__, err);
6209 		goto out;
6210 	}
6211 
6212 	hba->auto_bkops_enabled = true;
6213 	trace_ufshcd_auto_bkops_state(hba, "Enabled");
6214 
6215 	/* No need of URGENT_BKOPS exception from the device */
6216 	err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
6217 	if (err)
6218 		dev_err(hba->dev, "%s: failed to disable exception event %d\n",
6219 				__func__, err);
6220 out:
6221 	return err;
6222 }
6223 
6224 /**
6225  * ufshcd_disable_auto_bkops - block device in doing background operations
6226  * @hba: per-adapter instance
6227  *
6228  * Disabling background operations improves command response latency but
6229  * has drawback of device moving into critical state where the device is
6230  * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
6231  * host is idle so that BKOPS are managed effectively without any negative
6232  * impacts.
6233  *
6234  * Return: 0 upon success; > 0 in case the UFS device reported an OCS error;
6235  * < 0 if another error occurred.
6236  */
6237 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
6238 {
6239 	int err = 0;
6240 
6241 	if (!hba->auto_bkops_enabled)
6242 		goto out;
6243 
6244 	/*
6245 	 * If host assisted BKOPs is to be enabled, make sure
6246 	 * urgent bkops exception is allowed.
6247 	 */
6248 	err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
6249 	if (err) {
6250 		dev_err(hba->dev, "%s: failed to enable exception event %d\n",
6251 				__func__, err);
6252 		goto out;
6253 	}
6254 
6255 	err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
6256 			QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
6257 	if (err) {
6258 		dev_err(hba->dev, "%s: failed to disable bkops %d\n",
6259 				__func__, err);
6260 		ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
6261 		goto out;
6262 	}
6263 
6264 	hba->auto_bkops_enabled = false;
6265 	trace_ufshcd_auto_bkops_state(hba, "Disabled");
6266 	hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
6267 	hba->is_urgent_bkops_lvl_checked = false;
6268 out:
6269 	return err;
6270 }
6271 
6272 /**
6273  * ufshcd_force_reset_auto_bkops - force reset auto bkops state
6274  * @hba: per adapter instance
6275  *
6276  * After a device reset the device may toggle the BKOPS_EN flag
6277  * to default value. The s/w tracking variables should be updated
6278  * as well. This function would change the auto-bkops state based on
6279  * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
6280  */
6281 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
6282 {
6283 	if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
6284 		hba->auto_bkops_enabled = false;
6285 		hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
6286 		ufshcd_enable_auto_bkops(hba);
6287 	} else {
6288 		hba->auto_bkops_enabled = true;
6289 		hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
6290 		ufshcd_disable_auto_bkops(hba);
6291 	}
6292 	hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
6293 	hba->is_urgent_bkops_lvl_checked = false;
6294 }
6295 
6296 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
6297 {
6298 	return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
6299 			QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
6300 }
6301 
6302 /**
6303  * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
6304  * @hba: per-adapter instance
6305  *
6306  * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
6307  * flag in the device to permit background operations if the device
6308  * bkops_status is greater than or equal to the "hba->urgent_bkops_lvl",
6309  * disable otherwise.
6310  *
6311  * Return: 0 for success, non-zero in case of failure.
6312  *
6313  * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
6314  * to know whether auto bkops is enabled or disabled after this function
6315  * returns control to it.
6316  */
6317 static int ufshcd_bkops_ctrl(struct ufs_hba *hba)
6318 {
6319 	enum bkops_status status = hba->urgent_bkops_lvl;
6320 	u32 curr_status = 0;
6321 	int err;
6322 
6323 	err = ufshcd_get_bkops_status(hba, &curr_status);
6324 	if (err) {
6325 		dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
6326 				__func__, err);
6327 		goto out;
6328 	} else if (curr_status > BKOPS_STATUS_MAX) {
6329 		dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
6330 				__func__, curr_status);
6331 		err = -EINVAL;
6332 		goto out;
6333 	}
6334 
6335 	if (curr_status >= status)
6336 		err = ufshcd_enable_auto_bkops(hba);
6337 	else
6338 		err = ufshcd_disable_auto_bkops(hba);
6339 out:
6340 	return err;
6341 }
6342 
6343 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
6344 {
6345 	return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
6346 			QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
6347 }
6348 
6349 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
6350 {
6351 	int err;
6352 	u32 curr_status = 0;
6353 
6354 	if (hba->is_urgent_bkops_lvl_checked)
6355 		goto enable_auto_bkops;
6356 
6357 	err = ufshcd_get_bkops_status(hba, &curr_status);
6358 	if (err) {
6359 		dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
6360 				__func__, err);
6361 		goto out;
6362 	}
6363 
6364 	/*
6365 	 * We are seeing that some devices are raising the urgent bkops
6366 	 * exception events even when BKOPS status doesn't indicate performace
6367 	 * impacted or critical. Handle these device by determining their urgent
6368 	 * bkops status at runtime.
6369 	 */
6370 	if ((curr_status > BKOPS_STATUS_NO_OP) && (curr_status < BKOPS_STATUS_PERF_IMPACT)) {
6371 		dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
6372 				__func__, curr_status);
6373 		/* update the current status as the urgent bkops level */
6374 		hba->urgent_bkops_lvl = curr_status;
6375 		hba->is_urgent_bkops_lvl_checked = true;
6376 	}
6377 
6378 enable_auto_bkops:
6379 	err = ufshcd_enable_auto_bkops(hba);
6380 out:
6381 	if (err < 0)
6382 		dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
6383 				__func__, err);
6384 }
6385 
6386 static int __ufshcd_wb_toggle(struct ufs_hba *hba, bool set, enum flag_idn idn)
6387 {
6388 	u8 index;
6389 	enum query_opcode opcode = set ? UPIU_QUERY_OPCODE_SET_FLAG :
6390 				   UPIU_QUERY_OPCODE_CLEAR_FLAG;
6391 
6392 	index = ufshcd_wb_get_query_index(hba);
6393 	return ufshcd_query_flag_retry(hba, opcode, idn, index, NULL);
6394 }
6395 
6396 int ufshcd_wb_toggle(struct ufs_hba *hba, bool enable)
6397 {
6398 	int ret;
6399 
6400 	if (!ufshcd_is_wb_allowed(hba) ||
6401 	    hba->dev_info.wb_enabled == enable)
6402 		return 0;
6403 
6404 	ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_EN);
6405 	if (ret) {
6406 		dev_err(hba->dev, "%s: Write Booster %s failed %d\n",
6407 			__func__, enable ? "enabling" : "disabling", ret);
6408 		return ret;
6409 	}
6410 
6411 	hba->dev_info.wb_enabled = enable;
6412 	dev_dbg(hba->dev, "%s: Write Booster %s\n",
6413 			__func__, enable ? "enabled" : "disabled");
6414 
6415 	return ret;
6416 }
6417 
6418 static void ufshcd_wb_toggle_buf_flush_during_h8(struct ufs_hba *hba,
6419 						 bool enable)
6420 {
6421 	int ret;
6422 
6423 	ret = __ufshcd_wb_toggle(hba, enable,
6424 			QUERY_FLAG_IDN_WB_BUFF_FLUSH_DURING_HIBERN8);
6425 	if (ret) {
6426 		dev_err(hba->dev, "%s: WB-Buf Flush during H8 %s failed %d\n",
6427 			__func__, enable ? "enabling" : "disabling", ret);
6428 		return;
6429 	}
6430 	dev_dbg(hba->dev, "%s: WB-Buf Flush during H8 %s\n",
6431 			__func__, enable ? "enabled" : "disabled");
6432 }
6433 
6434 int ufshcd_wb_toggle_buf_flush(struct ufs_hba *hba, bool enable)
6435 {
6436 	int ret;
6437 
6438 	if (!ufshcd_is_wb_allowed(hba) ||
6439 	    hba->dev_info.wb_buf_flush_enabled == enable)
6440 		return 0;
6441 
6442 	ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN);
6443 	if (ret) {
6444 		dev_err(hba->dev, "%s: WB-Buf Flush %s failed %d\n",
6445 			__func__, enable ? "enabling" : "disabling", ret);
6446 		return ret;
6447 	}
6448 
6449 	hba->dev_info.wb_buf_flush_enabled = enable;
6450 	dev_dbg(hba->dev, "%s: WB-Buf Flush %s\n",
6451 			__func__, enable ? "enabled" : "disabled");
6452 
6453 	return ret;
6454 }
6455 
6456 int ufshcd_wb_set_resize_en(struct ufs_hba *hba, enum wb_resize_en en_mode)
6457 {
6458 	int ret;
6459 	u8 index;
6460 
6461 	index = ufshcd_wb_get_query_index(hba);
6462 	ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
6463 				QUERY_ATTR_IDN_WB_BUF_RESIZE_EN, index, 0, &en_mode);
6464 	if (ret)
6465 		dev_err(hba->dev, "%s: Enable WB buf resize operation failed %d\n",
6466 			__func__, ret);
6467 
6468 	return ret;
6469 }
6470 
6471 static bool ufshcd_wb_curr_buff_threshold_check(struct ufs_hba *hba,
6472 						u32 avail_buf)
6473 {
6474 	u32 cur_buf;
6475 	int ret;
6476 	u8 index;
6477 
6478 	index = ufshcd_wb_get_query_index(hba);
6479 	ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
6480 					      QUERY_ATTR_IDN_CURR_WB_BUFF_SIZE,
6481 					      index, 0, &cur_buf);
6482 	if (ret) {
6483 		dev_err(hba->dev, "%s: dCurWriteBoosterBufferSize read failed %d\n",
6484 			__func__, ret);
6485 		return false;
6486 	}
6487 
6488 	if (!cur_buf) {
6489 		dev_warn_once(hba->dev, "dCurWBBuf: %d WB disabled until free-space is available\n",
6490 			      cur_buf);
6491 		return false;
6492 	}
6493 	/* Let it continue to flush when available buffer exceeds threshold */
6494 	return avail_buf < hba->vps->wb_flush_threshold;
6495 }
6496 
6497 static void ufshcd_wb_force_disable(struct ufs_hba *hba)
6498 {
6499 	if (ufshcd_is_wb_buf_flush_allowed(hba))
6500 		ufshcd_wb_toggle_buf_flush(hba, false);
6501 
6502 	ufshcd_wb_toggle_buf_flush_during_h8(hba, false);
6503 	ufshcd_wb_toggle(hba, false);
6504 	hba->caps &= ~UFSHCD_CAP_WB_EN;
6505 
6506 	dev_info(hba->dev, "%s: WB force disabled\n", __func__);
6507 }
6508 
6509 static bool ufshcd_is_wb_buf_lifetime_available(struct ufs_hba *hba)
6510 {
6511 	u32 lifetime;
6512 	int ret;
6513 	u8 index;
6514 
6515 	index = ufshcd_wb_get_query_index(hba);
6516 	ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
6517 				      QUERY_ATTR_IDN_WB_BUFF_LIFE_TIME_EST,
6518 				      index, 0, &lifetime);
6519 	if (ret) {
6520 		dev_err(hba->dev,
6521 			"%s: bWriteBoosterBufferLifeTimeEst read failed %d\n",
6522 			__func__, ret);
6523 		return false;
6524 	}
6525 
6526 	if (lifetime == UFS_WB_EXCEED_LIFETIME) {
6527 		dev_err(hba->dev, "%s: WB buf lifetime is exhausted 0x%02X\n",
6528 			__func__, lifetime);
6529 		return false;
6530 	}
6531 
6532 	dev_dbg(hba->dev, "%s: WB buf lifetime is 0x%02X\n",
6533 		__func__, lifetime);
6534 
6535 	return true;
6536 }
6537 
6538 static bool ufshcd_wb_need_flush(struct ufs_hba *hba)
6539 {
6540 	int ret;
6541 	u32 avail_buf;
6542 	u8 index;
6543 
6544 	if (!ufshcd_is_wb_allowed(hba))
6545 		return false;
6546 
6547 	if (!ufshcd_is_wb_buf_lifetime_available(hba)) {
6548 		ufshcd_wb_force_disable(hba);
6549 		return false;
6550 	}
6551 
6552 	/*
6553 	 * With user-space reduction enabled, it's enough to enable flush
6554 	 * by checking only the available buffer. The threshold
6555 	 * defined here is > 90% full.
6556 	 * With user-space preserved enabled, the current-buffer
6557 	 * should be checked too because the wb buffer size can reduce
6558 	 * when disk tends to be full. This info is provided by current
6559 	 * buffer (dCurrentWriteBoosterBufferSize).
6560 	 */
6561 	index = ufshcd_wb_get_query_index(hba);
6562 	ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
6563 				      QUERY_ATTR_IDN_AVAIL_WB_BUFF_SIZE,
6564 				      index, 0, &avail_buf);
6565 	if (ret) {
6566 		dev_warn(hba->dev, "%s: dAvailableWriteBoosterBufferSize read failed %d\n",
6567 			 __func__, ret);
6568 		return false;
6569 	}
6570 
6571 	if (!hba->dev_info.b_presrv_uspc_en)
6572 		return avail_buf <= UFS_WB_BUF_REMAIN_PERCENT(10);
6573 
6574 	return ufshcd_wb_curr_buff_threshold_check(hba, avail_buf);
6575 }
6576 
6577 static void ufshcd_rpm_dev_flush_recheck_work(struct work_struct *work)
6578 {
6579 	struct ufs_hba *hba = container_of(to_delayed_work(work),
6580 					   struct ufs_hba,
6581 					   rpm_dev_flush_recheck_work);
6582 	/*
6583 	 * To prevent unnecessary VCC power drain after device finishes
6584 	 * WriteBooster buffer flush or Auto BKOPs, force runtime resume
6585 	 * after a certain delay to recheck the threshold by next runtime
6586 	 * suspend.
6587 	 */
6588 	ufshcd_rpm_get_sync(hba);
6589 	ufshcd_rpm_put_sync(hba);
6590 }
6591 
6592 /**
6593  * ufshcd_exception_event_handler - handle exceptions raised by device
6594  * @work: pointer to work data
6595  *
6596  * Read bExceptionEventStatus attribute from the device and handle the
6597  * exception event accordingly.
6598  */
6599 static void ufshcd_exception_event_handler(struct work_struct *work)
6600 {
6601 	struct ufs_hba *hba;
6602 	int err;
6603 	u32 status = 0;
6604 	hba = container_of(work, struct ufs_hba, eeh_work);
6605 
6606 	err = ufshcd_get_ee_status(hba, &status);
6607 	if (err) {
6608 		dev_err(hba->dev, "%s: failed to get exception status %d\n",
6609 				__func__, err);
6610 		return;
6611 	}
6612 
6613 	trace_ufshcd_exception_event(hba, status);
6614 
6615 	if (status & hba->ee_drv_mask & MASK_EE_URGENT_BKOPS)
6616 		ufshcd_bkops_exception_event_handler(hba);
6617 
6618 	if (status & hba->ee_drv_mask & MASK_EE_URGENT_TEMP)
6619 		ufs_hwmon_notify_event(hba, status & MASK_EE_URGENT_TEMP);
6620 
6621 	if (status & hba->ee_drv_mask & MASK_EE_HEALTH_CRITICAL) {
6622 		hba->critical_health_count++;
6623 		sysfs_notify(&hba->dev->kobj, NULL, "critical_health");
6624 	}
6625 
6626 	if (status & hba->ee_drv_mask & MASK_EE_DEV_LVL_EXCEPTION) {
6627 		atomic_inc(&hba->dev_lvl_exception_count);
6628 		sysfs_notify(&hba->dev->kobj, NULL, "device_lvl_exception_count");
6629 	}
6630 
6631 	ufs_debugfs_exception_event(hba, status);
6632 }
6633 
6634 /* Complete requests that have door-bell cleared */
6635 static void ufshcd_complete_requests(struct ufs_hba *hba, bool force_compl)
6636 {
6637 	if (hba->mcq_enabled)
6638 		ufshcd_mcq_compl_pending_transfer(hba, force_compl);
6639 	else
6640 		ufshcd_transfer_req_compl(hba);
6641 
6642 	ufshcd_tmc_handler(hba);
6643 }
6644 
6645 /**
6646  * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
6647  *				to recover from the DL NAC errors or not.
6648  * @hba: per-adapter instance
6649  *
6650  * Return: true if error handling is required, false otherwise.
6651  */
6652 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
6653 {
6654 	unsigned long flags;
6655 	bool err_handling = true;
6656 
6657 	spin_lock_irqsave(hba->host->host_lock, flags);
6658 	/*
6659 	 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
6660 	 * device fatal error and/or DL NAC & REPLAY timeout errors.
6661 	 */
6662 	if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
6663 		goto out;
6664 
6665 	if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
6666 	    ((hba->saved_err & UIC_ERROR) &&
6667 	     (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
6668 		goto out;
6669 
6670 	if ((hba->saved_err & UIC_ERROR) &&
6671 	    (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
6672 		int err;
6673 		/*
6674 		 * wait for 50ms to see if we can get any other errors or not.
6675 		 */
6676 		spin_unlock_irqrestore(hba->host->host_lock, flags);
6677 		msleep(50);
6678 		spin_lock_irqsave(hba->host->host_lock, flags);
6679 
6680 		/*
6681 		 * now check if we have got any other severe errors other than
6682 		 * DL NAC error?
6683 		 */
6684 		if ((hba->saved_err & INT_FATAL_ERRORS) ||
6685 		    ((hba->saved_err & UIC_ERROR) &&
6686 		    (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
6687 			goto out;
6688 
6689 		/*
6690 		 * As DL NAC is the only error received so far, send out NOP
6691 		 * command to confirm if link is still active or not.
6692 		 *   - If we don't get any response then do error recovery.
6693 		 *   - If we get response then clear the DL NAC error bit.
6694 		 */
6695 
6696 		spin_unlock_irqrestore(hba->host->host_lock, flags);
6697 		err = ufshcd_verify_dev_init(hba);
6698 		spin_lock_irqsave(hba->host->host_lock, flags);
6699 
6700 		if (err)
6701 			goto out;
6702 
6703 		/* Link seems to be alive hence ignore the DL NAC errors */
6704 		if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
6705 			hba->saved_err &= ~UIC_ERROR;
6706 		/* clear NAC error */
6707 		hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6708 		if (!hba->saved_uic_err)
6709 			err_handling = false;
6710 	}
6711 out:
6712 	spin_unlock_irqrestore(hba->host->host_lock, flags);
6713 	return err_handling;
6714 }
6715 
6716 /* host lock must be held before calling this func */
6717 static inline bool ufshcd_is_saved_err_fatal(struct ufs_hba *hba)
6718 {
6719 	return (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR) ||
6720 	       (hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK));
6721 }
6722 
6723 void ufshcd_schedule_eh_work(struct ufs_hba *hba)
6724 {
6725 	lockdep_assert_held(hba->host->host_lock);
6726 
6727 	/* handle fatal errors only when link is not in error state */
6728 	if (hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6729 		if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6730 		    ufshcd_is_saved_err_fatal(hba))
6731 			hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_FATAL;
6732 		else
6733 			hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_NON_FATAL;
6734 		queue_work(hba->eh_wq, &hba->eh_work);
6735 	}
6736 }
6737 
6738 void ufshcd_force_error_recovery(struct ufs_hba *hba)
6739 {
6740 	spin_lock_irq(hba->host->host_lock);
6741 	hba->force_reset = true;
6742 	ufshcd_schedule_eh_work(hba);
6743 	spin_unlock_irq(hba->host->host_lock);
6744 }
6745 EXPORT_SYMBOL_GPL(ufshcd_force_error_recovery);
6746 
6747 static void ufshcd_clk_scaling_allow(struct ufs_hba *hba, bool allow)
6748 {
6749 	mutex_lock(&hba->wb_mutex);
6750 	down_write(&hba->clk_scaling_lock);
6751 	hba->clk_scaling.is_allowed = allow;
6752 	up_write(&hba->clk_scaling_lock);
6753 	mutex_unlock(&hba->wb_mutex);
6754 }
6755 
6756 static void ufshcd_clk_scaling_suspend(struct ufs_hba *hba, bool suspend)
6757 {
6758 	if (suspend) {
6759 		if (hba->clk_scaling.is_enabled)
6760 			ufshcd_suspend_clkscaling(hba);
6761 		ufshcd_clk_scaling_allow(hba, false);
6762 	} else {
6763 		ufshcd_clk_scaling_allow(hba, true);
6764 		if (hba->clk_scaling.is_enabled)
6765 			ufshcd_resume_clkscaling(hba);
6766 	}
6767 }
6768 
6769 static void ufshcd_err_handling_prepare(struct ufs_hba *hba)
6770 {
6771 	/*
6772 	 * A WLUN resume failure could potentially lead to the HBA being
6773 	 * runtime suspended, so take an extra reference on hba->dev.
6774 	 */
6775 	pm_runtime_get_sync(hba->dev);
6776 	ufshcd_rpm_get_sync(hba);
6777 	if (pm_runtime_status_suspended(&hba->ufs_device_wlun->sdev_gendev) ||
6778 	    hba->is_sys_suspended) {
6779 		enum ufs_pm_op pm_op;
6780 
6781 		/*
6782 		 * Don't assume anything of resume, if
6783 		 * resume fails, irq and clocks can be OFF, and powers
6784 		 * can be OFF or in LPM.
6785 		 */
6786 		ufshcd_setup_hba_vreg(hba, true);
6787 		ufshcd_enable_irq(hba);
6788 		ufshcd_setup_vreg(hba, true);
6789 		ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
6790 		ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
6791 		ufshcd_hold(hba);
6792 		if (!ufshcd_is_clkgating_allowed(hba))
6793 			ufshcd_setup_clocks(hba, true);
6794 		pm_op = hba->is_sys_suspended ? UFS_SYSTEM_PM : UFS_RUNTIME_PM;
6795 		ufshcd_vops_resume(hba, pm_op);
6796 	} else {
6797 		ufshcd_hold(hba);
6798 		if (ufshcd_is_clkscaling_supported(hba) &&
6799 		    hba->clk_scaling.is_enabled)
6800 			ufshcd_suspend_clkscaling(hba);
6801 		ufshcd_clk_scaling_allow(hba, false);
6802 	}
6803 	/* Wait for ongoing ufshcd_queuecommand() calls to finish. */
6804 	blk_mq_quiesce_tagset(&hba->host->tag_set);
6805 	cancel_work_sync(&hba->eeh_work);
6806 }
6807 
6808 static void ufshcd_err_handling_unprepare(struct ufs_hba *hba)
6809 {
6810 	blk_mq_unquiesce_tagset(&hba->host->tag_set);
6811 	ufshcd_release(hba);
6812 	if (ufshcd_is_clkscaling_supported(hba))
6813 		ufshcd_clk_scaling_suspend(hba, false);
6814 	ufshcd_rpm_put(hba);
6815 	pm_runtime_put(hba->dev);
6816 }
6817 
6818 static inline bool ufshcd_err_handling_should_stop(struct ufs_hba *hba)
6819 {
6820 	return (!hba->is_powered || hba->shutting_down ||
6821 		!hba->ufs_device_wlun ||
6822 		hba->ufshcd_state == UFSHCD_STATE_ERROR ||
6823 		(!(hba->saved_err || hba->saved_uic_err || hba->force_reset ||
6824 		   ufshcd_is_link_broken(hba))));
6825 }
6826 
6827 #ifdef CONFIG_PM
6828 static void ufshcd_recover_pm_error(struct ufs_hba *hba)
6829 {
6830 	struct scsi_target *starget = hba->ufs_device_wlun->sdev_target;
6831 	struct Scsi_Host *shost = hba->host;
6832 	struct scsi_device *sdev;
6833 	struct request_queue *q;
6834 	bool resume_sdev_queues = false;
6835 
6836 	hba->is_sys_suspended = false;
6837 
6838 	/*
6839 	 * Ensure the parent's error status is cleared before proceeding
6840 	 * to the child, as the parent must be active to activate the child.
6841 	 */
6842 	if (hba->dev->power.runtime_error) {
6843 		/* hba->dev has no functional parent thus simplily set RPM_ACTIVE */
6844 		pm_runtime_set_active(hba->dev);
6845 		resume_sdev_queues = true;
6846 	}
6847 
6848 	if (hba->ufs_device_wlun->sdev_gendev.power.runtime_error) {
6849 		/*
6850 		 * starget, parent of wlun, might be suspended if wlun resume failed.
6851 		 * Make sure parent is resumed before set child (wlun) active.
6852 		 */
6853 		pm_runtime_get_sync(&starget->dev);
6854 		pm_runtime_set_active(&hba->ufs_device_wlun->sdev_gendev);
6855 		pm_runtime_put_sync(&starget->dev);
6856 		resume_sdev_queues = true;
6857 	}
6858 
6859 	/*
6860 	 * If wlun device had runtime error, we also need to resume those
6861 	 * consumer scsi devices in case any of them has failed to be
6862 	 * resumed due to supplier runtime resume failure. This is to unblock
6863 	 * blk_queue_enter in case there are bios waiting inside it.
6864 	 */
6865 	if (resume_sdev_queues) {
6866 		shost_for_each_device(sdev, shost) {
6867 			q = sdev->request_queue;
6868 			if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
6869 				       q->rpm_status == RPM_SUSPENDING))
6870 				pm_request_resume(q->dev);
6871 		}
6872 	}
6873 }
6874 #else
6875 static inline void ufshcd_recover_pm_error(struct ufs_hba *hba)
6876 {
6877 }
6878 #endif
6879 
6880 static bool ufshcd_is_pwr_mode_restore_needed(struct ufs_hba *hba)
6881 {
6882 	struct ufs_pa_layer_attr *pwr_info = &hba->pwr_info;
6883 	u32 mode;
6884 
6885 	ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode);
6886 
6887 	if (pwr_info->pwr_rx != ((mode >> PWRMODE_RX_OFFSET) & PWRMODE_MASK))
6888 		return true;
6889 
6890 	if (pwr_info->pwr_tx != (mode & PWRMODE_MASK))
6891 		return true;
6892 
6893 	return false;
6894 }
6895 
6896 static bool ufshcd_abort_one(struct request *rq, void *priv)
6897 {
6898 	int *ret = priv;
6899 	u32 tag = rq->tag;
6900 	struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
6901 	struct scsi_device *sdev = cmd->device;
6902 	struct Scsi_Host *shost = sdev->host;
6903 	struct ufs_hba *hba = shost_priv(shost);
6904 
6905 	if (blk_mq_is_reserved_rq(rq))
6906 		return true;
6907 
6908 	*ret = ufshcd_try_to_abort_task(hba, tag);
6909 	dev_err(hba->dev, "Aborting tag %d / CDB %#02x %s\n", tag,
6910 		ufshcd_is_scsi_cmd(cmd) ? cmd->cmnd[0] : -1,
6911 		*ret ? "failed" : "succeeded");
6912 
6913 	return *ret == 0;
6914 }
6915 
6916 /**
6917  * ufshcd_abort_all - Abort all pending commands.
6918  * @hba: Host bus adapter pointer.
6919  *
6920  * Return: true if and only if the host controller needs to be reset.
6921  */
6922 static bool ufshcd_abort_all(struct ufs_hba *hba)
6923 {
6924 	int tag, ret = 0;
6925 
6926 	blk_mq_tagset_busy_iter(&hba->host->tag_set, ufshcd_abort_one, &ret);
6927 	if (ret)
6928 		goto out;
6929 
6930 	/* Clear pending task management requests */
6931 	for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
6932 		ret = ufshcd_clear_tm_cmd(hba, tag);
6933 		if (ret)
6934 			goto out;
6935 	}
6936 
6937 out:
6938 	/* Complete the requests that are cleared by s/w */
6939 	ufshcd_complete_requests(hba, false);
6940 
6941 	return ret != 0;
6942 }
6943 
6944 /**
6945  * ufshcd_err_handler - handle UFS errors that require s/w attention
6946  * @work: pointer to work structure
6947  */
6948 static void ufshcd_err_handler(struct work_struct *work)
6949 {
6950 	int retries = MAX_ERR_HANDLER_RETRIES;
6951 	struct ufs_hba *hba;
6952 	unsigned long flags;
6953 	bool needs_restore;
6954 	bool needs_reset;
6955 	int pmc_err;
6956 
6957 	hba = container_of(work, struct ufs_hba, eh_work);
6958 
6959 	dev_info(hba->dev,
6960 		 "%s started; HBA state %s; powered %d; shutting down %d; saved_err = 0x%x; saved_uic_err = 0x%x; force_reset = %d%s\n",
6961 		 __func__, ufshcd_state_name[hba->ufshcd_state],
6962 		 hba->is_powered, hba->shutting_down, hba->saved_err,
6963 		 hba->saved_uic_err, hba->force_reset,
6964 		 ufshcd_is_link_broken(hba) ? "; link is broken" : "");
6965 
6966 	if (hba->ufs_device_wlun) {
6967 		/*
6968 		 * Use ufshcd_rpm_get_noresume() here to safely perform link
6969 		 * recovery even if an error occurs during runtime suspend or
6970 		 * runtime resume. This avoids potential deadlocks that could
6971 		 * happen if we tried to resume the device while a PM operation
6972 		 * is already in progress.
6973 		 */
6974 		ufshcd_rpm_get_noresume(hba);
6975 		if (hba->pm_op_in_progress) {
6976 			ufshcd_link_recovery(hba);
6977 			ufshcd_rpm_put(hba);
6978 			return;
6979 		}
6980 		ufshcd_rpm_put(hba);
6981 	}
6982 
6983 	down(&hba->host_sem);
6984 	spin_lock_irqsave(hba->host->host_lock, flags);
6985 	if (ufshcd_err_handling_should_stop(hba)) {
6986 		if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6987 			hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6988 		spin_unlock_irqrestore(hba->host->host_lock, flags);
6989 		up(&hba->host_sem);
6990 		return;
6991 	}
6992 	spin_unlock_irqrestore(hba->host->host_lock, flags);
6993 
6994 	ufshcd_err_handling_prepare(hba);
6995 
6996 	spin_lock_irqsave(hba->host->host_lock, flags);
6997 	ufshcd_set_eh_in_progress(hba);
6998 	spin_unlock_irqrestore(hba->host->host_lock, flags);
6999 
7000 	/* Complete requests that have door-bell cleared by h/w */
7001 	ufshcd_complete_requests(hba, false);
7002 	spin_lock_irqsave(hba->host->host_lock, flags);
7003 again:
7004 	needs_restore = false;
7005 	needs_reset = false;
7006 
7007 	if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
7008 		hba->ufshcd_state = UFSHCD_STATE_RESET;
7009 	/*
7010 	 * A full reset and restore might have happened after preparation
7011 	 * is finished, double check whether we should stop.
7012 	 */
7013 	if (ufshcd_err_handling_should_stop(hba))
7014 		goto skip_err_handling;
7015 
7016 	if ((hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) &&
7017 	    !hba->force_reset) {
7018 		bool ret;
7019 
7020 		spin_unlock_irqrestore(hba->host->host_lock, flags);
7021 		/* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
7022 		ret = ufshcd_quirk_dl_nac_errors(hba);
7023 		spin_lock_irqsave(hba->host->host_lock, flags);
7024 		if (!ret && ufshcd_err_handling_should_stop(hba))
7025 			goto skip_err_handling;
7026 	}
7027 
7028 	if ((hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
7029 	    (hba->saved_uic_err &&
7030 	     (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
7031 		bool pr_prdt = !!(hba->saved_err & SYSTEM_BUS_FATAL_ERROR);
7032 
7033 		spin_unlock_irqrestore(hba->host->host_lock, flags);
7034 		ufshcd_print_host_state(hba);
7035 		ufshcd_print_pwr_info(hba);
7036 		ufshcd_print_tx_eq_params(hba);
7037 		ufshcd_print_evt_hist(hba);
7038 		ufshcd_print_tmrs(hba, hba->outstanding_tasks);
7039 		ufshcd_print_trs_all(hba, pr_prdt);
7040 		spin_lock_irqsave(hba->host->host_lock, flags);
7041 	}
7042 
7043 	/*
7044 	 * if host reset is required then skip clearing the pending
7045 	 * transfers forcefully because they will get cleared during
7046 	 * host reset and restore
7047 	 */
7048 	if (hba->force_reset || ufshcd_is_link_broken(hba) ||
7049 	    ufshcd_is_saved_err_fatal(hba) ||
7050 	    ((hba->saved_err & UIC_ERROR) &&
7051 	     (hba->saved_uic_err & (UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
7052 				    UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))) {
7053 		needs_reset = true;
7054 		goto do_reset;
7055 	}
7056 
7057 	/*
7058 	 * If LINERESET was caught, UFS might have been put to PWM mode,
7059 	 * check if power mode restore is needed.
7060 	 */
7061 	if (hba->saved_uic_err & UFSHCD_UIC_PA_GENERIC_ERROR) {
7062 		hba->saved_uic_err &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
7063 		if (!hba->saved_uic_err)
7064 			hba->saved_err &= ~UIC_ERROR;
7065 		spin_unlock_irqrestore(hba->host->host_lock, flags);
7066 		if (ufshcd_is_pwr_mode_restore_needed(hba))
7067 			needs_restore = true;
7068 		spin_lock_irqsave(hba->host->host_lock, flags);
7069 		if (!hba->saved_err && !needs_restore)
7070 			goto skip_err_handling;
7071 	}
7072 
7073 	hba->silence_err_logs = true;
7074 	/* release lock as clear command might sleep */
7075 	spin_unlock_irqrestore(hba->host->host_lock, flags);
7076 
7077 	needs_reset = ufshcd_abort_all(hba);
7078 
7079 	spin_lock_irqsave(hba->host->host_lock, flags);
7080 	hba->silence_err_logs = false;
7081 	if (needs_reset)
7082 		goto do_reset;
7083 
7084 	/*
7085 	 * After all reqs and tasks are cleared from doorbell,
7086 	 * now it is safe to retore power mode.
7087 	 */
7088 	if (needs_restore) {
7089 		spin_unlock_irqrestore(hba->host->host_lock, flags);
7090 		/*
7091 		 * Hold the scaling lock just in case dev cmds
7092 		 * are sent via bsg and/or sysfs.
7093 		 */
7094 		down_write(&hba->clk_scaling_lock);
7095 		pmc_err = ufshcd_config_pwr_mode(hba, &hba->pwr_info,
7096 						 UFSHCD_PMC_POLICY_FORCE);
7097 		if (pmc_err) {
7098 			needs_reset = true;
7099 			dev_err(hba->dev, "%s: Failed to restore power mode, err = %d\n",
7100 					__func__, pmc_err);
7101 		}
7102 		ufshcd_print_pwr_info(hba);
7103 		up_write(&hba->clk_scaling_lock);
7104 		spin_lock_irqsave(hba->host->host_lock, flags);
7105 	}
7106 
7107 do_reset:
7108 	/* Fatal errors need reset */
7109 	if (needs_reset) {
7110 		int err;
7111 
7112 		hba->force_reset = false;
7113 		spin_unlock_irqrestore(hba->host->host_lock, flags);
7114 		err = ufshcd_reset_and_restore(hba);
7115 		if (err)
7116 			dev_err(hba->dev, "%s: reset and restore failed with err %d\n",
7117 					__func__, err);
7118 		else
7119 			ufshcd_recover_pm_error(hba);
7120 		spin_lock_irqsave(hba->host->host_lock, flags);
7121 	}
7122 
7123 skip_err_handling:
7124 	if (!needs_reset) {
7125 		if (hba->ufshcd_state == UFSHCD_STATE_RESET)
7126 			hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
7127 		if (hba->saved_err || hba->saved_uic_err)
7128 			dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
7129 			    __func__, hba->saved_err, hba->saved_uic_err);
7130 	}
7131 	/* Exit in an operational state or dead */
7132 	if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
7133 	    hba->ufshcd_state != UFSHCD_STATE_ERROR) {
7134 		if (--retries)
7135 			goto again;
7136 		hba->ufshcd_state = UFSHCD_STATE_ERROR;
7137 	}
7138 	ufshcd_clear_eh_in_progress(hba);
7139 	spin_unlock_irqrestore(hba->host->host_lock, flags);
7140 	ufshcd_err_handling_unprepare(hba);
7141 	up(&hba->host_sem);
7142 
7143 	dev_info(hba->dev, "%s finished; HBA state %s\n", __func__,
7144 		 ufshcd_state_name[hba->ufshcd_state]);
7145 }
7146 
7147 /**
7148  * ufshcd_update_uic_error - check and set fatal UIC error flags.
7149  * @hba: per-adapter instance
7150  *
7151  * Return:
7152  *  IRQ_HANDLED - If interrupt is valid
7153  *  IRQ_NONE    - If invalid interrupt
7154  */
7155 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
7156 {
7157 	u32 reg;
7158 	irqreturn_t retval = IRQ_NONE;
7159 
7160 	/* PHY layer error */
7161 	reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
7162 	if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
7163 	    (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) {
7164 		ufshcd_update_evt_hist(hba, UFS_EVT_PA_ERR, reg);
7165 		/*
7166 		 * To know whether this error is fatal or not, DB timeout
7167 		 * must be checked but this error is handled separately.
7168 		 */
7169 		if (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)
7170 			dev_dbg(hba->dev, "%s: UIC Lane error reported\n",
7171 					__func__);
7172 
7173 		/* Got a LINERESET indication. */
7174 		if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) {
7175 			struct uic_command *cmd = NULL;
7176 
7177 			hba->uic_error |= UFSHCD_UIC_PA_GENERIC_ERROR;
7178 			if (hba->uic_async_done && hba->active_uic_cmd)
7179 				cmd = hba->active_uic_cmd;
7180 			/*
7181 			 * Ignore the LINERESET during power mode change
7182 			 * operation via DME_SET command.
7183 			 */
7184 			if (cmd && (cmd->command == UIC_CMD_DME_SET))
7185 				hba->uic_error &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
7186 		}
7187 		retval |= IRQ_HANDLED;
7188 	}
7189 
7190 	/* PA_INIT_ERROR is fatal and needs UIC reset */
7191 	reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
7192 	if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
7193 	    (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
7194 		ufshcd_update_evt_hist(hba, UFS_EVT_DL_ERR, reg);
7195 
7196 		if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
7197 			hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
7198 		else if (hba->dev_quirks &
7199 				UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
7200 			if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
7201 				hba->uic_error |=
7202 					UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
7203 			else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
7204 				hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
7205 		}
7206 		retval |= IRQ_HANDLED;
7207 	}
7208 
7209 	/* UIC NL/TL/DME errors needs software retry */
7210 	reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
7211 	if ((reg & UIC_NETWORK_LAYER_ERROR) &&
7212 	    (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
7213 		ufshcd_update_evt_hist(hba, UFS_EVT_NL_ERR, reg);
7214 		hba->uic_error |= UFSHCD_UIC_NL_ERROR;
7215 		retval |= IRQ_HANDLED;
7216 	}
7217 
7218 	reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
7219 	if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
7220 	    (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
7221 		ufshcd_update_evt_hist(hba, UFS_EVT_TL_ERR, reg);
7222 		hba->uic_error |= UFSHCD_UIC_TL_ERROR;
7223 		retval |= IRQ_HANDLED;
7224 	}
7225 
7226 	reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
7227 	if (reg & UIC_DME_ERROR) {
7228 		ufshcd_update_evt_hist(hba, UFS_EVT_DME_ERR, reg);
7229 
7230 		if (reg & UIC_DME_ERROR_CODE_MASK)
7231 			hba->uic_error |= UFSHCD_UIC_DME_ERROR;
7232 
7233 		if (reg & UIC_DME_QOS_MASK) {
7234 			atomic_set(&hba->dme_qos_notification,
7235 				   reg & UIC_DME_QOS_MASK);
7236 			if (hba->dme_qos_sysfs_handle)
7237 				sysfs_notify_dirent(hba->dme_qos_sysfs_handle);
7238 		}
7239 
7240 		retval |= IRQ_HANDLED;
7241 	}
7242 
7243 	dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
7244 			__func__, hba->uic_error);
7245 	return retval;
7246 }
7247 
7248 /**
7249  * ufshcd_check_errors - Check for errors that need s/w attention
7250  * @hba: per-adapter instance
7251  * @intr_status: interrupt status generated by the controller
7252  *
7253  * Return:
7254  *  IRQ_HANDLED - If interrupt is valid
7255  *  IRQ_NONE    - If invalid interrupt
7256  */
7257 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba, u32 intr_status)
7258 {
7259 	bool queue_eh_work = false;
7260 	irqreturn_t retval = IRQ_NONE;
7261 
7262 	guard(spinlock_irqsave)(hba->host->host_lock);
7263 	hba->errors |= UFSHCD_ERROR_MASK & intr_status;
7264 
7265 	if (hba->errors & INT_FATAL_ERRORS) {
7266 		ufshcd_update_evt_hist(hba, UFS_EVT_FATAL_ERR,
7267 				       hba->errors);
7268 		queue_eh_work = true;
7269 	}
7270 
7271 	if (hba->errors & UIC_ERROR) {
7272 		hba->uic_error = 0;
7273 		retval = ufshcd_update_uic_error(hba);
7274 		if (hba->uic_error)
7275 			queue_eh_work = true;
7276 	}
7277 
7278 	if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
7279 		dev_err(hba->dev,
7280 			"%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
7281 			__func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
7282 			"Enter" : "Exit",
7283 			hba->errors, ufshcd_get_upmcrs(hba));
7284 		ufshcd_update_evt_hist(hba, UFS_EVT_AUTO_HIBERN8_ERR,
7285 				       hba->errors);
7286 		ufshcd_set_link_broken(hba);
7287 		queue_eh_work = true;
7288 	}
7289 
7290 	if (queue_eh_work) {
7291 		/*
7292 		 * update the transfer error masks to sticky bits, let's do this
7293 		 * irrespective of current ufshcd_state.
7294 		 */
7295 		hba->saved_err |= hba->errors;
7296 		hba->saved_uic_err |= hba->uic_error;
7297 
7298 		/* dump controller state before resetting */
7299 		if ((hba->saved_err &
7300 		     (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
7301 		    (hba->saved_uic_err &&
7302 		     (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
7303 			dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
7304 					__func__, hba->saved_err,
7305 					hba->saved_uic_err);
7306 			ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE,
7307 					 "host_regs: ");
7308 			ufshcd_print_pwr_info(hba);
7309 			ufshcd_print_tx_eq_params(hba);
7310 		}
7311 		ufshcd_schedule_eh_work(hba);
7312 		retval |= IRQ_HANDLED;
7313 	}
7314 	/*
7315 	 * if (!queue_eh_work) -
7316 	 * Other errors are either non-fatal where host recovers
7317 	 * itself without s/w intervention or errors that will be
7318 	 * handled by the SCSI core layer.
7319 	 */
7320 	hba->errors = 0;
7321 	hba->uic_error = 0;
7322 
7323 	return retval;
7324 }
7325 
7326 /**
7327  * ufshcd_tmc_handler - handle task management function completion
7328  * @hba: per adapter instance
7329  *
7330  * Return:
7331  *  IRQ_HANDLED - If interrupt is valid
7332  *  IRQ_NONE    - If invalid interrupt
7333  */
7334 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
7335 {
7336 	unsigned long flags, pending, issued;
7337 	irqreturn_t ret = IRQ_NONE;
7338 	int tag;
7339 
7340 	spin_lock_irqsave(hba->host->host_lock, flags);
7341 	pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
7342 	issued = hba->outstanding_tasks & ~pending;
7343 	for_each_set_bit(tag, &issued, hba->nutmrs) {
7344 		struct request *req = hba->tmf_rqs[tag];
7345 		struct completion *c = req->end_io_data;
7346 
7347 		complete(c);
7348 		ret = IRQ_HANDLED;
7349 	}
7350 	spin_unlock_irqrestore(hba->host->host_lock, flags);
7351 
7352 	return ret;
7353 }
7354 
7355 /**
7356  * ufshcd_handle_mcq_cq_events - handle MCQ completion queue events
7357  * @hba: per adapter instance
7358  * @reset_iag: true, to reset MCQ IAG counter and timer of the CQ
7359  *
7360  * Return: IRQ_HANDLED if interrupt is handled.
7361  */
7362 static irqreturn_t ufshcd_handle_mcq_cq_events(struct ufs_hba *hba, bool reset_iag)
7363 {
7364 	struct ufs_hw_queue *hwq;
7365 	unsigned long outstanding_cqs;
7366 	unsigned int nr_queues;
7367 	int i, ret;
7368 	u32 events, reg;
7369 
7370 	ret = ufshcd_vops_get_outstanding_cqs(hba, &outstanding_cqs);
7371 	if (ret)
7372 		outstanding_cqs = (1ULL << hba->nr_hw_queues) - 1;
7373 
7374 	/* Exclude the poll queues */
7375 	nr_queues = hba->nr_hw_queues - hba->nr_queues[HCTX_TYPE_POLL];
7376 	for_each_set_bit(i, &outstanding_cqs, nr_queues) {
7377 		hwq = &hba->uhq[i];
7378 
7379 		events = ufshcd_mcq_read_cqis(hba, i);
7380 		if (events)
7381 			ufshcd_mcq_write_cqis(hba, events, i);
7382 
7383 		if (reset_iag) {
7384 			reg = ufshcd_mcq_read_mcqiacr(hba, i);
7385 			reg |= INT_AGGR_COUNTER_AND_TIMER_RESET;
7386 			ufshcd_mcq_write_mcqiacr(hba, reg, i);
7387 		}
7388 
7389 		if (events & UFSHCD_MCQ_CQIS_TAIL_ENT_PUSH_STS)
7390 			ufshcd_mcq_poll_cqe_lock(hba, hwq);
7391 	}
7392 
7393 	return IRQ_HANDLED;
7394 }
7395 
7396 /**
7397  * ufshcd_sl_intr - Interrupt service routine
7398  * @hba: per adapter instance
7399  * @intr_status: contains interrupts generated by the controller
7400  *
7401  * Return:
7402  *  IRQ_HANDLED - If interrupt is valid
7403  *  IRQ_NONE    - If invalid interrupt
7404  */
7405 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
7406 {
7407 	irqreturn_t retval = IRQ_NONE;
7408 
7409 	if (intr_status & UFSHCD_UIC_MASK)
7410 		retval |= ufshcd_uic_cmd_compl(hba, intr_status);
7411 
7412 	if (intr_status & UFSHCD_ERROR_MASK || hba->errors)
7413 		retval |= ufshcd_check_errors(hba, intr_status);
7414 
7415 	if (intr_status & UTP_TASK_REQ_COMPL)
7416 		retval |= ufshcd_tmc_handler(hba);
7417 
7418 	if (intr_status & UTP_TRANSFER_REQ_COMPL)
7419 		retval |= ufshcd_transfer_req_compl(hba);
7420 
7421 	if (intr_status & MCQ_CQ_EVENT_STATUS)
7422 		retval |= ufshcd_handle_mcq_cq_events(hba, false);
7423 
7424 	if (intr_status & MCQ_IAG_EVENT_STATUS)
7425 		retval |= ufshcd_handle_mcq_cq_events(hba, true);
7426 
7427 	return retval;
7428 }
7429 
7430 /**
7431  * ufshcd_intr - Main interrupt service routine
7432  * @irq: irq number
7433  * @__hba: pointer to adapter instance
7434  *
7435  * Return:
7436  *  IRQ_HANDLED - If interrupt is valid
7437  *  IRQ_NONE    - If invalid interrupt
7438  */
7439 static irqreturn_t ufshcd_intr(int irq, void *__hba)
7440 {
7441 	u32 last_intr_status, intr_status, enabled_intr_status = 0;
7442 	irqreturn_t retval = IRQ_NONE;
7443 	struct ufs_hba *hba = __hba;
7444 	int retries = hba->nutrs;
7445 
7446 	last_intr_status = intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
7447 
7448 	/*
7449 	 * There could be max of hba->nutrs reqs in flight and in worst case
7450 	 * if the reqs get finished 1 by 1 after the interrupt status is
7451 	 * read, make sure we handle them by checking the interrupt status
7452 	 * again in a loop until we process all of the reqs before returning.
7453 	 */
7454 	while (intr_status && retries--) {
7455 		enabled_intr_status =
7456 			intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
7457 		ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
7458 		if (enabled_intr_status)
7459 			retval |= ufshcd_sl_intr(hba, enabled_intr_status);
7460 
7461 		intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
7462 	}
7463 
7464 	if (enabled_intr_status && retval == IRQ_NONE &&
7465 	    (!(enabled_intr_status & UTP_TRANSFER_REQ_COMPL) ||
7466 	     hba->outstanding_reqs) && !ufshcd_eh_in_progress(hba)) {
7467 		dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x (0x%08x, 0x%08x)\n",
7468 					__func__,
7469 					intr_status,
7470 					last_intr_status,
7471 					enabled_intr_status);
7472 		ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
7473 	}
7474 
7475 	return retval;
7476 }
7477 
7478 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
7479 {
7480 	int err = 0;
7481 	u32 mask = 1 << tag;
7482 
7483 	if (!test_bit(tag, &hba->outstanding_tasks))
7484 		goto out;
7485 
7486 	ufshcd_utmrl_clear(hba, tag);
7487 
7488 	/* poll for max. 1 sec to clear door bell register by h/w */
7489 	err = ufshcd_wait_for_register(hba,
7490 			REG_UTP_TASK_REQ_DOOR_BELL,
7491 			mask, 0, 1000, 1000);
7492 
7493 	dev_err(hba->dev, "Clearing task management function with tag %d %s\n",
7494 		tag, err < 0 ? "failed" : "succeeded");
7495 
7496 out:
7497 	return err;
7498 }
7499 
7500 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
7501 		struct utp_task_req_desc *treq, u8 tm_function)
7502 {
7503 	struct request_queue *q = hba->tmf_queue;
7504 	struct Scsi_Host *host = hba->host;
7505 	DECLARE_COMPLETION_ONSTACK(wait);
7506 	struct request *req;
7507 	unsigned long flags;
7508 	int task_tag, err;
7509 
7510 	/*
7511 	 * blk_mq_alloc_request() is used here only to get a free tag.
7512 	 */
7513 	req = blk_mq_alloc_request(q, REQ_OP_DRV_OUT, 0);
7514 	if (IS_ERR(req))
7515 		return PTR_ERR(req);
7516 
7517 	req->end_io_data = &wait;
7518 	ufshcd_hold(hba);
7519 
7520 	spin_lock_irqsave(host->host_lock, flags);
7521 
7522 	task_tag = req->tag;
7523 	hba->tmf_rqs[req->tag] = req;
7524 	treq->upiu_req.req_header.task_tag = task_tag;
7525 
7526 	memcpy(hba->utmrdl_base_addr + task_tag, treq, sizeof(*treq));
7527 	ufshcd_vops_setup_task_mgmt(hba, task_tag, tm_function);
7528 
7529 	__set_bit(task_tag, &hba->outstanding_tasks);
7530 
7531 	spin_unlock_irqrestore(host->host_lock, flags);
7532 
7533 	/* send command to the controller */
7534 	ufshcd_writel(hba, 1 << task_tag, REG_UTP_TASK_REQ_DOOR_BELL);
7535 
7536 	ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_SEND);
7537 
7538 	/* wait until the task management command is completed */
7539 	err = wait_for_completion_io_timeout(&wait,
7540 			msecs_to_jiffies(TM_CMD_TIMEOUT));
7541 	if (!err) {
7542 		ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_ERR);
7543 		dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
7544 				__func__, tm_function);
7545 		if (ufshcd_clear_tm_cmd(hba, task_tag))
7546 			dev_WARN(hba->dev, "%s: unable to clear tm cmd (slot %d) after timeout\n",
7547 					__func__, task_tag);
7548 		err = -ETIMEDOUT;
7549 	} else {
7550 		err = 0;
7551 		memcpy(treq, hba->utmrdl_base_addr + task_tag, sizeof(*treq));
7552 
7553 		ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_COMP);
7554 	}
7555 
7556 	spin_lock_irqsave(hba->host->host_lock, flags);
7557 	hba->tmf_rqs[req->tag] = NULL;
7558 	__clear_bit(task_tag, &hba->outstanding_tasks);
7559 	spin_unlock_irqrestore(hba->host->host_lock, flags);
7560 
7561 	ufshcd_release(hba);
7562 	blk_mq_free_request(req);
7563 
7564 	return err;
7565 }
7566 
7567 /**
7568  * ufshcd_issue_tm_cmd - issues task management commands to controller
7569  * @hba: per adapter instance
7570  * @lun_id: LUN ID to which TM command is sent
7571  * @task_id: task ID to which the TM command is applicable
7572  * @tm_function: task management function opcode
7573  * @tm_response: task management service response return value
7574  *
7575  * Return: non-zero value on error, zero on success.
7576  */
7577 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
7578 		u8 tm_function, u8 *tm_response)
7579 {
7580 	struct utp_task_req_desc treq = { };
7581 	enum utp_ocs ocs_value;
7582 	int err;
7583 
7584 	/* Configure task request descriptor */
7585 	treq.header.interrupt = 1;
7586 	treq.header.ocs = OCS_INVALID_COMMAND_STATUS;
7587 
7588 	/* Configure task request UPIU */
7589 	treq.upiu_req.req_header.transaction_code = UPIU_TRANSACTION_TASK_REQ;
7590 	treq.upiu_req.req_header.lun = lun_id;
7591 	treq.upiu_req.req_header.tm_function = tm_function;
7592 
7593 	/*
7594 	 * The host shall provide the same value for LUN field in the basic
7595 	 * header and for Input Parameter.
7596 	 */
7597 	treq.upiu_req.input_param1 = cpu_to_be32(lun_id);
7598 	treq.upiu_req.input_param2 = cpu_to_be32(task_id);
7599 
7600 	err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
7601 	if (err == -ETIMEDOUT)
7602 		return err;
7603 
7604 	ocs_value = treq.header.ocs & MASK_OCS;
7605 	if (ocs_value != OCS_SUCCESS)
7606 		dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
7607 				__func__, ocs_value);
7608 	else if (tm_response)
7609 		*tm_response = be32_to_cpu(treq.upiu_rsp.output_param1) &
7610 				MASK_TM_SERVICE_RESP;
7611 	return err;
7612 }
7613 
7614 /**
7615  * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
7616  * @hba:	per-adapter instance
7617  * @req_upiu:	upiu request
7618  * @rsp_upiu:	upiu reply
7619  * @desc_buff:	pointer to descriptor buffer, NULL if NA
7620  * @buff_len:	descriptor size, 0 if NA
7621  * @cmd_type:	specifies the type (NOP, Query...)
7622  * @desc_op:	descriptor operation
7623  *
7624  * Those type of requests uses UTP Transfer Request Descriptor - utrd.
7625  * Therefore, it "rides" the device management infrastructure: uses its tag and
7626  * tasks work queues.
7627  *
7628  * Since there is only one available tag for device management commands,
7629  * the caller is expected to hold the hba->dev_cmd.lock mutex.
7630  *
7631  * Return: 0 upon success; < 0 upon failure.
7632  */
7633 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
7634 					struct utp_upiu_req *req_upiu,
7635 					struct utp_upiu_req *rsp_upiu,
7636 					u8 *desc_buff, int *buff_len,
7637 					enum dev_cmd_type cmd_type,
7638 					enum query_opcode desc_op)
7639 {
7640 	struct scsi_cmnd *cmd = ufshcd_get_dev_mgmt_cmd(hba);
7641 	struct ufshcd_lrb *lrbp = scsi_cmd_priv(cmd);
7642 	u32 tag;
7643 	int err = 0;
7644 	u8 upiu_flags;
7645 
7646 	/* Protects use of hba->dev_cmd. */
7647 	lockdep_assert_held(&hba->dev_cmd.lock);
7648 
7649 	if (WARN_ON_ONCE(!cmd))
7650 		return -ENOMEM;
7651 
7652 	tag = scsi_cmd_to_rq(cmd)->tag;
7653 
7654 	ufshcd_setup_dev_cmd(hba, cmd, cmd_type, 0, tag);
7655 
7656 	ufshcd_prepare_req_desc_hdr(hba, lrbp, &upiu_flags, DMA_NONE, 0);
7657 
7658 	/* update the task tag in the request upiu */
7659 	req_upiu->header.task_tag = tag;
7660 
7661 	/* just copy the upiu request as it is */
7662 	memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
7663 	if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
7664 		/* The Data Segment Area is optional depending upon the query
7665 		 * function value. for WRITE DESCRIPTOR, the data segment
7666 		 * follows right after the tsf.
7667 		 */
7668 		memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
7669 		*buff_len = 0;
7670 	}
7671 
7672 	memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
7673 
7674 	err = ufshcd_issue_dev_cmd(hba, cmd, tag, dev_cmd_timeout);
7675 	if (err)
7676 		goto put_dev_mgmt_cmd;
7677 
7678 	/* just copy the upiu response as it is */
7679 	memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
7680 	if (desc_buff && (desc_op == UPIU_QUERY_OPCODE_READ_DESC ||
7681 			  desc_op == UPIU_QUERY_OPCODE_AGGREGATED_READ)) {
7682 		u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
7683 		u16 resp_len = be16_to_cpu(lrbp->ucd_rsp_ptr->header
7684 					   .data_segment_length);
7685 
7686 		if (*buff_len >= resp_len) {
7687 			memcpy(desc_buff, descp, resp_len);
7688 			*buff_len = resp_len;
7689 		} else {
7690 			dev_warn(hba->dev,
7691 				 "%s: rsp size %d is bigger than buffer size %d",
7692 				 __func__, resp_len, *buff_len);
7693 			*buff_len = 0;
7694 			err = -EINVAL;
7695 		}
7696 	}
7697 
7698 put_dev_mgmt_cmd:
7699 	ufshcd_put_dev_mgmt_cmd(cmd);
7700 
7701 	return err;
7702 }
7703 
7704 /**
7705  * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
7706  * @hba:	per-adapter instance
7707  * @req_upiu:	upiu request
7708  * @rsp_upiu:	upiu reply - only 8 DW as we do not support scsi commands
7709  * @msgcode:	message code, one of UPIU Transaction Codes Initiator to Target
7710  * @desc_buff:	pointer to descriptor buffer, NULL if NA
7711  * @buff_len:	descriptor size, 0 if NA
7712  * @desc_op:	descriptor operation
7713  *
7714  * Supports UTP Transfer requests (nop and query), and UTP Task
7715  * Management requests.
7716  * It is up to the caller to fill the upiu conent properly, as it will
7717  * be copied without any further input validations.
7718  *
7719  * Return: 0 upon success; < 0 upon failure.
7720  */
7721 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
7722 			     struct utp_upiu_req *req_upiu,
7723 			     struct utp_upiu_req *rsp_upiu,
7724 			     enum upiu_request_transaction msgcode,
7725 			     u8 *desc_buff, int *buff_len,
7726 			     enum query_opcode desc_op)
7727 {
7728 	int err;
7729 	enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
7730 	struct utp_task_req_desc treq = { };
7731 	enum utp_ocs ocs_value;
7732 	u8 tm_f = req_upiu->header.tm_function;
7733 
7734 	switch (msgcode) {
7735 	case UPIU_TRANSACTION_NOP_OUT:
7736 		cmd_type = DEV_CMD_TYPE_NOP;
7737 		fallthrough;
7738 	case UPIU_TRANSACTION_QUERY_REQ:
7739 		ufshcd_dev_man_lock(hba);
7740 		err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
7741 						   desc_buff, buff_len,
7742 						   cmd_type, desc_op);
7743 		ufshcd_dev_man_unlock(hba);
7744 
7745 		break;
7746 	case UPIU_TRANSACTION_TASK_REQ:
7747 		treq.header.interrupt = 1;
7748 		treq.header.ocs = OCS_INVALID_COMMAND_STATUS;
7749 
7750 		memcpy(&treq.upiu_req, req_upiu, sizeof(*req_upiu));
7751 
7752 		err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
7753 		if (err == -ETIMEDOUT)
7754 			break;
7755 
7756 		ocs_value = treq.header.ocs & MASK_OCS;
7757 		if (ocs_value != OCS_SUCCESS) {
7758 			dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
7759 				ocs_value);
7760 			break;
7761 		}
7762 
7763 		memcpy(rsp_upiu, &treq.upiu_rsp, sizeof(*rsp_upiu));
7764 
7765 		break;
7766 	default:
7767 		err = -EINVAL;
7768 
7769 		break;
7770 	}
7771 
7772 	return err;
7773 }
7774 
7775 /**
7776  * ufshcd_advanced_rpmb_req_handler - handle advanced RPMB request
7777  * @hba:	per adapter instance
7778  * @req_upiu:	upiu request
7779  * @rsp_upiu:	upiu reply
7780  * @req_ehs:	EHS field which contains Advanced RPMB Request Message
7781  * @rsp_ehs:	EHS field which returns Advanced RPMB Response Message
7782  * @sg_cnt:	The number of sg lists actually used
7783  * @sg_list:	Pointer to SG list when DATA IN/OUT UPIU is required in ARPMB operation
7784  * @dir:	DMA direction
7785  *
7786  * Return: 0 upon success; > 0 in case the UFS device reported an OCS error;
7787  * < 0 if another error occurred.
7788  */
7789 int ufshcd_advanced_rpmb_req_handler(struct ufs_hba *hba, struct utp_upiu_req *req_upiu,
7790 			 struct utp_upiu_req *rsp_upiu, struct ufs_ehs *req_ehs,
7791 			 struct ufs_ehs *rsp_ehs, int sg_cnt, struct scatterlist *sg_list,
7792 			 enum dma_data_direction dir)
7793 {
7794 	struct scsi_cmnd *cmd;
7795 	struct ufshcd_lrb *lrbp;
7796 	u32 tag;
7797 	int err = 0;
7798 	int result;
7799 	u8 upiu_flags;
7800 	u8 *ehs_data;
7801 	u16 ehs_len;
7802 	int ehs = (hba->capabilities & MASK_EHSLUTRD_SUPPORTED) ? 2 : 0;
7803 
7804 	ufshcd_dev_man_lock(hba);
7805 
7806 	cmd = ufshcd_get_dev_mgmt_cmd(hba);
7807 
7808 	if (WARN_ON_ONCE(!cmd)) {
7809 		err = -ENOMEM;
7810 		goto unlock;
7811 	}
7812 
7813 	lrbp = scsi_cmd_priv(cmd);
7814 	tag = scsi_cmd_to_rq(cmd)->tag;
7815 
7816 	ufshcd_setup_dev_cmd(hba, cmd, DEV_CMD_TYPE_RPMB, UFS_UPIU_RPMB_WLUN,
7817 			     tag);
7818 
7819 	ufshcd_prepare_req_desc_hdr(hba, lrbp, &upiu_flags, DMA_NONE, ehs);
7820 
7821 	/* update the task tag */
7822 	req_upiu->header.task_tag = tag;
7823 
7824 	/* copy the UPIU(contains CDB) request as it is */
7825 	memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
7826 	/* Copy EHS, starting with byte32, immediately after the CDB package */
7827 	memcpy(lrbp->ucd_req_ptr + 1, req_ehs, sizeof(*req_ehs));
7828 
7829 	if (dir != DMA_NONE && sg_list)
7830 		ufshcd_sgl_to_prdt(hba, lrbp, sg_cnt, sg_list);
7831 
7832 	memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
7833 
7834 	err = ufshcd_issue_dev_cmd(hba, cmd, tag, ADVANCED_RPMB_REQ_TIMEOUT);
7835 	if (err)
7836 		goto put_dev_mgmt_cmd;
7837 
7838 	err = ufshcd_dev_cmd_completion(hba, lrbp);
7839 	if (!err) {
7840 		/* Just copy the upiu response as it is */
7841 		memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
7842 		/* Get the response UPIU result */
7843 		result = (lrbp->ucd_rsp_ptr->header.response << 8) |
7844 			lrbp->ucd_rsp_ptr->header.status;
7845 
7846 		ehs_len = lrbp->ucd_rsp_ptr->header.ehs_length;
7847 		/*
7848 		 * Since the bLength in EHS indicates the total size of the EHS Header and EHS Data
7849 		 * in 32 Byte units, the value of the bLength Request/Response for Advanced RPMB
7850 		 * Message is 02h
7851 		 */
7852 		if (ehs_len == 2 && rsp_ehs) {
7853 			/* EHS data starts from byte32 of the devman UCD response area. */
7854 			ehs_data = (u8 *)lrbp->ucd_rsp_ptr + EHS_OFFSET_IN_RESPONSE;
7855 			memcpy(rsp_ehs, ehs_data, ehs_len * 32);
7856 		}
7857 	}
7858 
7859 put_dev_mgmt_cmd:
7860 	ufshcd_put_dev_mgmt_cmd(cmd);
7861 
7862 unlock:
7863 	ufshcd_dev_man_unlock(hba);
7864 
7865 	return err ? : result;
7866 }
7867 
7868 static bool ufshcd_clear_lu_cmds(struct request *req, void *priv)
7869 {
7870 	struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
7871 	struct scsi_device *sdev = cmd->device;
7872 	struct Scsi_Host *shost = sdev->host;
7873 	struct ufs_hba *hba = shost_priv(shost);
7874 	const u64 lun = *(u64 *)priv;
7875 	const u32 tag = req->tag;
7876 
7877 	if (blk_mq_is_reserved_rq(req) || sdev->lun != lun)
7878 		return true;
7879 
7880 	if (ufshcd_clear_cmd(hba, tag) < 0) {
7881 		dev_err(hba->dev, "%s: failed to clear request %d\n", __func__,
7882 			tag);
7883 		return true;
7884 	}
7885 
7886 	if (hba->mcq_enabled) {
7887 		struct ufs_hw_queue *hwq = ufshcd_mcq_req_to_hwq(hba, req);
7888 
7889 		if (hwq)
7890 			ufshcd_mcq_poll_cqe_lock(hba, hwq);
7891 		return true;
7892 	}
7893 
7894 	ufshcd_compl_one_cqe(hba, tag, NULL);
7895 	return true;
7896 }
7897 
7898 /**
7899  * ufshcd_eh_device_reset_handler() - Reset a single logical unit.
7900  * @cmd: SCSI command pointer
7901  *
7902  * Return: SUCCESS or FAILED.
7903  */
7904 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
7905 {
7906 	struct Scsi_Host *host;
7907 	struct ufs_hba *hba;
7908 	int err;
7909 	u8 resp = 0xF, lun;
7910 
7911 	host = cmd->device->host;
7912 	hba = shost_priv(host);
7913 
7914 	lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
7915 	err = ufshcd_issue_tm_cmd(hba, lun, 0, UFS_LOGICAL_RESET, &resp);
7916 	if (err) {
7917 	} else if (resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7918 		err = resp;
7919 	} else {
7920 		/* clear the commands that were pending for corresponding LUN */
7921 		blk_mq_tagset_busy_iter(&hba->host->tag_set,
7922 					ufshcd_clear_lu_cmds,
7923 					&cmd->device->lun);
7924 	}
7925 
7926 	hba->req_abort_count = 0;
7927 	ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, (u32)err);
7928 	if (!err) {
7929 		err = SUCCESS;
7930 	} else {
7931 		dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7932 		err = FAILED;
7933 	}
7934 	return err;
7935 }
7936 
7937 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
7938 {
7939 	int tag;
7940 
7941 	for_each_set_bit(tag, &bitmap, hba->nutrs) {
7942 		struct scsi_cmnd *cmd = ufshcd_tag_to_cmd(hba, tag);
7943 		struct ufshcd_lrb *lrbp;
7944 
7945 		if (!cmd)
7946 			continue;
7947 
7948 		lrbp = scsi_cmd_priv(cmd);
7949 		lrbp->req_abort_skip = true;
7950 	}
7951 }
7952 
7953 /**
7954  * ufshcd_try_to_abort_task - abort a specific task
7955  * @hba: Pointer to adapter instance
7956  * @tag: Tag of the task to be aborted
7957  *
7958  * Abort the pending command in device by sending UFS_ABORT_TASK task management
7959  * command, and in host controller by clearing the door-bell register. There can
7960  * be race between controller sending the command to the device while abort is
7961  * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
7962  * really issued and then try to abort it.
7963  *
7964  * Return: zero on success, non-zero on failure.
7965  */
7966 int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag)
7967 {
7968 	struct scsi_cmnd *cmd = ufshcd_tag_to_cmd(hba, tag);
7969 	struct ufshcd_lrb *lrbp;
7970 	int err;
7971 	int poll_cnt;
7972 	u8 resp = 0xF;
7973 
7974 	if (!cmd)
7975 		return -EINVAL;
7976 
7977 	lrbp = scsi_cmd_priv(cmd);
7978 
7979 	for (poll_cnt = 100; poll_cnt; poll_cnt--) {
7980 		err = ufshcd_issue_tm_cmd(hba, lrbp->lun, tag, UFS_QUERY_TASK,
7981 					  &resp);
7982 		if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
7983 			/* cmd pending in the device */
7984 			dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
7985 				__func__, tag);
7986 			break;
7987 		} else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7988 			/*
7989 			 * cmd not pending in the device, check if it is
7990 			 * in transition.
7991 			 */
7992 			dev_info(
7993 				hba->dev,
7994 				"%s: cmd with tag %d not pending in the device.\n",
7995 				__func__, tag);
7996 			if (!ufshcd_cmd_inflight(cmd)) {
7997 				dev_info(hba->dev,
7998 					 "%s: cmd with tag=%d completed.\n",
7999 					 __func__, tag);
8000 				return 0;
8001 			}
8002 			usleep_range(100, 200);
8003 		} else {
8004 			dev_err(hba->dev,
8005 				"%s: no response from device. tag = %d, err %d\n",
8006 				__func__, tag, err);
8007 			return err ? : resp;
8008 		}
8009 	}
8010 
8011 	if (!poll_cnt)
8012 		return -EBUSY;
8013 
8014 	err = ufshcd_issue_tm_cmd(hba, lrbp->lun, tag, UFS_ABORT_TASK, &resp);
8015 	if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
8016 		if (!err) {
8017 			err = resp; /* service response error */
8018 			dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
8019 				__func__, tag, err);
8020 		}
8021 		return err;
8022 	}
8023 
8024 	err = ufshcd_clear_cmd(hba, tag);
8025 	if (err)
8026 		dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
8027 			__func__, tag, err);
8028 
8029 	return err;
8030 }
8031 
8032 /**
8033  * ufshcd_abort - scsi host template eh_abort_handler callback
8034  * @cmd: SCSI command pointer
8035  *
8036  * Return: SUCCESS or FAILED.
8037  */
8038 static int ufshcd_abort(struct scsi_cmnd *cmd)
8039 {
8040 	struct Scsi_Host *host = cmd->device->host;
8041 	struct ufs_hba *hba = shost_priv(host);
8042 	struct request *rq = scsi_cmd_to_rq(cmd);
8043 	int tag = rq->tag;
8044 	struct ufshcd_lrb *lrbp = scsi_cmd_priv(cmd);
8045 	unsigned long flags;
8046 	int err = FAILED;
8047 	bool outstanding;
8048 	u32 reg;
8049 
8050 	ufshcd_hold(hba);
8051 
8052 	if (!hba->mcq_enabled) {
8053 		reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
8054 		if (!test_bit(tag, &hba->outstanding_reqs)) {
8055 			/* If command is already aborted/completed, return FAILED. */
8056 			dev_err(hba->dev,
8057 				"%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
8058 				__func__, tag, hba->outstanding_reqs, reg);
8059 			goto release;
8060 		}
8061 	}
8062 
8063 	/* Print Transfer Request of aborted task */
8064 	dev_info(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
8065 
8066 	/*
8067 	 * Print detailed info about aborted request.
8068 	 * As more than one request might get aborted at the same time,
8069 	 * print full information only for the first aborted request in order
8070 	 * to reduce repeated printouts. For other aborted requests only print
8071 	 * basic details.
8072 	 */
8073 	if (ufshcd_is_scsi_cmd(cmd))
8074 		scsi_print_command(cmd);
8075 	if (!hba->req_abort_count) {
8076 		ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, tag);
8077 		ufshcd_print_evt_hist(hba);
8078 		ufshcd_print_host_state(hba);
8079 		ufshcd_print_pwr_info(hba);
8080 		ufshcd_print_tx_eq_params(hba);
8081 		ufshcd_print_tr(hba, cmd, true);
8082 	} else {
8083 		ufshcd_print_tr(hba, cmd, false);
8084 	}
8085 	hba->req_abort_count++;
8086 
8087 	if (!hba->mcq_enabled && !(reg & (1 << tag))) {
8088 		/* only execute this code in single doorbell mode */
8089 		dev_err(hba->dev,
8090 		"%s: cmd was completed, but without a notifying intr, tag = %d",
8091 		__func__, tag);
8092 		__ufshcd_transfer_req_compl(hba, 1UL << tag);
8093 		goto release;
8094 	}
8095 
8096 	/*
8097 	 * Task abort to the device W-LUN is illegal. When this command
8098 	 * will fail, due to spec violation, scsi err handling next step
8099 	 * will be to send LU reset which, again, is a spec violation.
8100 	 * To avoid these unnecessary/illegal steps, first we clean up
8101 	 * the lrb taken by this cmd and re-set it in outstanding_reqs,
8102 	 * then queue the eh_work and bail.
8103 	 */
8104 	if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN) {
8105 		ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, lrbp->lun);
8106 
8107 		spin_lock_irqsave(host->host_lock, flags);
8108 		hba->force_reset = true;
8109 		ufshcd_schedule_eh_work(hba);
8110 		spin_unlock_irqrestore(host->host_lock, flags);
8111 		goto release;
8112 	}
8113 
8114 	if (hba->mcq_enabled) {
8115 		/* MCQ mode. Branch off to handle abort for mcq mode */
8116 		err = ufshcd_mcq_abort(cmd);
8117 		goto release;
8118 	}
8119 
8120 	/* Skip task abort in case previous aborts failed and report failure */
8121 	if (lrbp->req_abort_skip) {
8122 		dev_err(hba->dev, "%s: skipping abort\n", __func__);
8123 		ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
8124 		goto release;
8125 	}
8126 
8127 	if (blk_mq_is_reserved_rq(rq))
8128 		err = ufshcd_clear_cmd(hba, tag);
8129 	else
8130 		err = ufshcd_try_to_abort_task(hba, tag);
8131 	if (err) {
8132 		dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
8133 		ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
8134 		err = FAILED;
8135 		goto release;
8136 	}
8137 
8138 	/*
8139 	 * Clear the corresponding bit from outstanding_reqs since the command
8140 	 * has been aborted successfully.
8141 	 */
8142 	spin_lock_irqsave(&hba->outstanding_lock, flags);
8143 	outstanding = __test_and_clear_bit(tag, &hba->outstanding_reqs);
8144 	spin_unlock_irqrestore(&hba->outstanding_lock, flags);
8145 
8146 	if (outstanding)
8147 		ufshcd_release_scsi_cmd(hba, cmd);
8148 
8149 	err = SUCCESS;
8150 
8151 release:
8152 	/* Matches the ufshcd_hold() call at the start of this function. */
8153 	ufshcd_release(hba);
8154 	return err;
8155 }
8156 
8157 /**
8158  * ufshcd_process_probe_result - Process the ufshcd_probe_hba() result.
8159  * @hba: UFS host controller instance.
8160  * @probe_start: time when the ufshcd_probe_hba() call started.
8161  * @ret: ufshcd_probe_hba() return value.
8162  */
8163 static void ufshcd_process_probe_result(struct ufs_hba *hba,
8164 					ktime_t probe_start, int ret)
8165 {
8166 	unsigned long flags;
8167 
8168 	spin_lock_irqsave(hba->host->host_lock, flags);
8169 	if (ret)
8170 		hba->ufshcd_state = UFSHCD_STATE_ERROR;
8171 	else if (hba->ufshcd_state == UFSHCD_STATE_RESET)
8172 		hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
8173 	spin_unlock_irqrestore(hba->host->host_lock, flags);
8174 
8175 	trace_ufshcd_init(hba, ret,
8176 			  ktime_to_us(ktime_sub(ktime_get(), probe_start)),
8177 			  hba->curr_dev_pwr_mode, hba->uic_link_state);
8178 }
8179 
8180 /**
8181  * ufshcd_host_reset_and_restore - reset and restore host controller
8182  * @hba: per-adapter instance
8183  *
8184  * Note that host controller reset may issue DME_RESET to
8185  * local and remote (device) Uni-Pro stack and the attributes
8186  * are reset to default state.
8187  *
8188  * Return: zero on success, non-zero on failure.
8189  */
8190 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
8191 {
8192 	int err;
8193 
8194 	/*
8195 	 * Stop the host controller and complete the requests
8196 	 * cleared by h/w
8197 	 */
8198 	ufshcd_hba_stop(hba);
8199 	hba->silence_err_logs = true;
8200 	ufshcd_complete_requests(hba, true);
8201 	hba->silence_err_logs = false;
8202 
8203 	/* scale up clocks to max frequency before full reinitialization */
8204 	if (ufshcd_is_clkscaling_supported(hba))
8205 		ufshcd_scale_clks(hba, ULONG_MAX, true);
8206 
8207 	err = ufshcd_hba_enable(hba);
8208 
8209 	/* Establish the link again and restore the device */
8210 	if (!err) {
8211 		ktime_t probe_start = ktime_get();
8212 
8213 		err = ufshcd_device_init(hba, /*init_dev_params=*/false);
8214 		if (!err)
8215 			err = ufshcd_probe_hba(hba, false);
8216 		ufshcd_process_probe_result(hba, probe_start, err);
8217 	}
8218 
8219 	if (err)
8220 		dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
8221 	ufshcd_update_evt_hist(hba, UFS_EVT_HOST_RESET, (u32)err);
8222 	return err;
8223 }
8224 
8225 /**
8226  * ufshcd_reset_and_restore - reset and re-initialize host/device
8227  * @hba: per-adapter instance
8228  *
8229  * Reset and recover device, host and re-establish link. This
8230  * is helpful to recover the communication in fatal error conditions.
8231  *
8232  * Return: zero on success, non-zero on failure.
8233  */
8234 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
8235 {
8236 	u32 saved_err = 0;
8237 	u32 saved_uic_err = 0;
8238 	int err = 0;
8239 	unsigned long flags;
8240 	int retries = MAX_HOST_RESET_RETRIES;
8241 
8242 	spin_lock_irqsave(hba->host->host_lock, flags);
8243 	do {
8244 		/*
8245 		 * This is a fresh start, cache and clear saved error first,
8246 		 * in case new error generated during reset and restore.
8247 		 */
8248 		saved_err |= hba->saved_err;
8249 		saved_uic_err |= hba->saved_uic_err;
8250 		hba->saved_err = 0;
8251 		hba->saved_uic_err = 0;
8252 		hba->force_reset = false;
8253 		hba->ufshcd_state = UFSHCD_STATE_RESET;
8254 		spin_unlock_irqrestore(hba->host->host_lock, flags);
8255 
8256 		/* Reset the attached device */
8257 		ufshcd_device_reset(hba);
8258 
8259 		err = ufshcd_host_reset_and_restore(hba);
8260 
8261 		spin_lock_irqsave(hba->host->host_lock, flags);
8262 		if (err)
8263 			continue;
8264 		/* Do not exit unless operational or dead */
8265 		if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
8266 		    hba->ufshcd_state != UFSHCD_STATE_ERROR &&
8267 		    hba->ufshcd_state != UFSHCD_STATE_EH_SCHEDULED_NON_FATAL)
8268 			err = -EAGAIN;
8269 	} while (err && --retries);
8270 
8271 	/*
8272 	 * Inform scsi mid-layer that we did reset and allow to handle
8273 	 * Unit Attention properly.
8274 	 */
8275 	scsi_report_bus_reset(hba->host, 0);
8276 	if (err) {
8277 		hba->ufshcd_state = UFSHCD_STATE_ERROR;
8278 		hba->saved_err |= saved_err;
8279 		hba->saved_uic_err |= saved_uic_err;
8280 	}
8281 	spin_unlock_irqrestore(hba->host->host_lock, flags);
8282 
8283 	return err;
8284 }
8285 
8286 /**
8287  * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
8288  * @cmd: SCSI command pointer
8289  *
8290  * Return: SUCCESS or FAILED.
8291  */
8292 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
8293 {
8294 	int err = SUCCESS;
8295 	unsigned long flags;
8296 	struct ufs_hba *hba;
8297 
8298 	hba = shost_priv(cmd->device->host);
8299 
8300 	/*
8301 	 * If runtime PM sent SSU and got a timeout, scsi_error_handler is
8302 	 * stuck in this function waiting for flush_work(&hba->eh_work). And
8303 	 * ufshcd_err_handler(eh_work) is stuck waiting for runtime PM. Do
8304 	 * ufshcd_link_recovery instead of eh_work to prevent deadlock.
8305 	 */
8306 	if (hba->pm_op_in_progress) {
8307 		if (ufshcd_link_recovery(hba))
8308 			err = FAILED;
8309 
8310 		return err;
8311 	}
8312 
8313 	spin_lock_irqsave(hba->host->host_lock, flags);
8314 	hba->force_reset = true;
8315 	ufshcd_schedule_eh_work(hba);
8316 	dev_err(hba->dev, "%s: reset in progress - 1\n", __func__);
8317 	spin_unlock_irqrestore(hba->host->host_lock, flags);
8318 
8319 	flush_work(&hba->eh_work);
8320 
8321 	spin_lock_irqsave(hba->host->host_lock, flags);
8322 	if (hba->ufshcd_state == UFSHCD_STATE_ERROR)
8323 		err = FAILED;
8324 	spin_unlock_irqrestore(hba->host->host_lock, flags);
8325 
8326 	return err;
8327 }
8328 
8329 /**
8330  * ufshcd_get_max_icc_level - calculate the ICC level
8331  * @sup_curr_uA: max. current supported by the regulator
8332  * @start_scan: row at the desc table to start scan from
8333  * @buff: power descriptor buffer
8334  *
8335  * Return: calculated max ICC level for specific regulator.
8336  */
8337 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan,
8338 				    const char *buff)
8339 {
8340 	int i;
8341 	int curr_uA;
8342 	u16 data;
8343 	u16 unit;
8344 
8345 	for (i = start_scan; i >= 0; i--) {
8346 		data = get_unaligned_be16(&buff[2 * i]);
8347 		unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
8348 						ATTR_ICC_LVL_UNIT_OFFSET;
8349 		curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
8350 		switch (unit) {
8351 		case UFSHCD_NANO_AMP:
8352 			curr_uA = curr_uA / 1000;
8353 			break;
8354 		case UFSHCD_MILI_AMP:
8355 			curr_uA = curr_uA * 1000;
8356 			break;
8357 		case UFSHCD_AMP:
8358 			curr_uA = curr_uA * 1000 * 1000;
8359 			break;
8360 		case UFSHCD_MICRO_AMP:
8361 		default:
8362 			break;
8363 		}
8364 		if (sup_curr_uA >= curr_uA)
8365 			break;
8366 	}
8367 	if (i < 0) {
8368 		i = 0;
8369 		pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
8370 	}
8371 
8372 	return (u32)i;
8373 }
8374 
8375 /**
8376  * ufshcd_find_max_sup_active_icc_level - calculate the max ICC level
8377  * In case regulators are not initialized we'll return 0
8378  * @hba: per-adapter instance
8379  * @desc_buf: power descriptor buffer to extract ICC levels from.
8380  *
8381  * Return: calculated ICC level.
8382  */
8383 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
8384 						const u8 *desc_buf)
8385 {
8386 	u32 icc_level = 0;
8387 
8388 	if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
8389 						!hba->vreg_info.vccq2) {
8390 		/*
8391 		 * Using dev_dbg to avoid messages during runtime PM to avoid
8392 		 * never-ending cycles of messages written back to storage by
8393 		 * user space causing runtime resume, causing more messages and
8394 		 * so on.
8395 		 */
8396 		dev_dbg(hba->dev,
8397 			"%s: Regulator capability was not set, actvIccLevel=%d",
8398 							__func__, icc_level);
8399 		goto out;
8400 	}
8401 
8402 	if (hba->vreg_info.vcc->max_uA)
8403 		icc_level = ufshcd_get_max_icc_level(
8404 				hba->vreg_info.vcc->max_uA,
8405 				POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
8406 				&desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
8407 
8408 	if (hba->vreg_info.vccq->max_uA)
8409 		icc_level = ufshcd_get_max_icc_level(
8410 				hba->vreg_info.vccq->max_uA,
8411 				icc_level,
8412 				&desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
8413 
8414 	if (hba->vreg_info.vccq2->max_uA)
8415 		icc_level = ufshcd_get_max_icc_level(
8416 				hba->vreg_info.vccq2->max_uA,
8417 				icc_level,
8418 				&desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
8419 out:
8420 	return icc_level;
8421 }
8422 
8423 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba)
8424 {
8425 	int ret;
8426 	u8 *desc_buf;
8427 	u32 icc_level;
8428 
8429 	desc_buf = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
8430 	if (!desc_buf)
8431 		return;
8432 
8433 	ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0,
8434 				     desc_buf, QUERY_DESC_MAX_SIZE);
8435 	if (ret) {
8436 		dev_err(hba->dev,
8437 			"%s: Failed reading power descriptor ret = %d",
8438 			__func__, ret);
8439 		goto out;
8440 	}
8441 
8442 	icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf);
8443 	dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level);
8444 
8445 	ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
8446 		QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level);
8447 
8448 	if (ret)
8449 		dev_err(hba->dev,
8450 			"%s: Failed configuring bActiveICCLevel = %d ret = %d",
8451 			__func__, icc_level, ret);
8452 
8453 out:
8454 	kfree(desc_buf);
8455 }
8456 
8457 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev)
8458 {
8459 	struct Scsi_Host *shost = sdev->host;
8460 
8461 	scsi_autopm_get_device(sdev);
8462 	blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev);
8463 	if (sdev->rpm_autosuspend)
8464 		pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev,
8465 						 shost->rpm_autosuspend_delay);
8466 	scsi_autopm_put_device(sdev);
8467 }
8468 
8469 /**
8470  * ufshcd_scsi_add_wlus - Adds required W-LUs
8471  * @hba: per-adapter instance
8472  *
8473  * UFS device specification requires the UFS devices to support 4 well known
8474  * logical units:
8475  *	"REPORT_LUNS" (address: 01h)
8476  *	"UFS Device" (address: 50h)
8477  *	"RPMB" (address: 44h)
8478  *	"BOOT" (address: 30h)
8479  * UFS device's power management needs to be controlled by "POWER CONDITION"
8480  * field of SSU (START STOP UNIT) command. But this "power condition" field
8481  * will take effect only when its sent to "UFS device" well known logical unit
8482  * hence we require the scsi_device instance to represent this logical unit in
8483  * order for the UFS host driver to send the SSU command for power management.
8484  *
8485  * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
8486  * Block) LU so user space process can control this LU. User space may also
8487  * want to have access to BOOT LU.
8488  *
8489  * This function adds scsi device instances for each of all well known LUs
8490  * (except "REPORT LUNS" LU).
8491  *
8492  * Return: zero on success (all required W-LUs are added successfully),
8493  * non-zero error value on failure (if failed to add any of the required W-LU).
8494  */
8495 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
8496 {
8497 	int ret = 0;
8498 	struct scsi_device *sdev_boot, *sdev_rpmb;
8499 
8500 	hba->ufs_device_wlun = __scsi_add_device(hba->host, 0, 0,
8501 		ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
8502 	if (IS_ERR(hba->ufs_device_wlun)) {
8503 		ret = PTR_ERR(hba->ufs_device_wlun);
8504 		hba->ufs_device_wlun = NULL;
8505 		goto out;
8506 	}
8507 	scsi_device_put(hba->ufs_device_wlun);
8508 
8509 	sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
8510 		ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
8511 	if (IS_ERR(sdev_rpmb)) {
8512 		ret = PTR_ERR(sdev_rpmb);
8513 		hba->ufs_rpmb_wlun = NULL;
8514 		dev_err(hba->dev, "%s: RPMB WLUN not found\n", __func__);
8515 		goto remove_ufs_device_wlun;
8516 	}
8517 	hba->ufs_rpmb_wlun = sdev_rpmb;
8518 	ufshcd_blk_pm_runtime_init(sdev_rpmb);
8519 	scsi_device_put(sdev_rpmb);
8520 
8521 	sdev_boot = __scsi_add_device(hba->host, 0, 0,
8522 		ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
8523 	if (IS_ERR(sdev_boot)) {
8524 		dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
8525 	} else {
8526 		ufshcd_blk_pm_runtime_init(sdev_boot);
8527 		scsi_device_put(sdev_boot);
8528 	}
8529 	goto out;
8530 
8531 remove_ufs_device_wlun:
8532 	scsi_remove_device(hba->ufs_device_wlun);
8533 out:
8534 	return ret;
8535 }
8536 
8537 static void ufshcd_wb_probe(struct ufs_hba *hba, const u8 *desc_buf)
8538 {
8539 	struct ufs_dev_info *dev_info = &hba->dev_info;
8540 	u8 lun;
8541 	u32 d_lu_wb_buf_alloc;
8542 	u32 ext_ufs_feature;
8543 
8544 	if (!ufshcd_is_wb_allowed(hba))
8545 		return;
8546 
8547 	/*
8548 	 * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or
8549 	 * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES
8550 	 * enabled
8551 	 */
8552 	if (!(dev_info->wspecversion >= 0x310 ||
8553 	      dev_info->wspecversion == 0x220 ||
8554 	     (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES)))
8555 		goto wb_disabled;
8556 
8557 	ext_ufs_feature = get_unaligned_be32(desc_buf +
8558 					DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
8559 
8560 	if (!(ext_ufs_feature & UFS_DEV_WRITE_BOOSTER_SUP))
8561 		goto wb_disabled;
8562 
8563 	/*
8564 	 * WB may be supported but not configured while provisioning. The spec
8565 	 * says, in dedicated wb buffer mode, a max of 1 lun would have wb
8566 	 * buffer configured.
8567 	 */
8568 	dev_info->wb_buffer_type = desc_buf[DEVICE_DESC_PARAM_WB_TYPE];
8569 
8570 	dev_info->ext_wb_sup =  get_unaligned_be16(desc_buf +
8571 						DEVICE_DESC_PARAM_EXT_WB_SUP);
8572 
8573 	dev_info->b_presrv_uspc_en =
8574 		desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN];
8575 
8576 	if (dev_info->wb_buffer_type == WB_BUF_MODE_SHARED) {
8577 		if (!get_unaligned_be32(desc_buf +
8578 				   DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS))
8579 			goto wb_disabled;
8580 	} else {
8581 		for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) {
8582 			d_lu_wb_buf_alloc = 0;
8583 			ufshcd_read_unit_desc_param(hba,
8584 					lun,
8585 					UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS,
8586 					(u8 *)&d_lu_wb_buf_alloc,
8587 					sizeof(d_lu_wb_buf_alloc));
8588 			if (d_lu_wb_buf_alloc) {
8589 				dev_info->wb_dedicated_lu = lun;
8590 				break;
8591 			}
8592 		}
8593 
8594 		if (!d_lu_wb_buf_alloc)
8595 			goto wb_disabled;
8596 	}
8597 
8598 	if (!ufshcd_is_wb_buf_lifetime_available(hba))
8599 		goto wb_disabled;
8600 
8601 	return;
8602 
8603 wb_disabled:
8604 	hba->caps &= ~UFSHCD_CAP_WB_EN;
8605 }
8606 
8607 static void ufshcd_temp_notif_probe(struct ufs_hba *hba, const u8 *desc_buf)
8608 {
8609 	struct ufs_dev_info *dev_info = &hba->dev_info;
8610 	u32 ext_ufs_feature;
8611 	u8 mask = 0;
8612 
8613 	if (!(hba->caps & UFSHCD_CAP_TEMP_NOTIF) || dev_info->wspecversion < 0x300)
8614 		return;
8615 
8616 	ext_ufs_feature = get_unaligned_be32(desc_buf + DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
8617 
8618 	if (ext_ufs_feature & UFS_DEV_LOW_TEMP_NOTIF)
8619 		mask |= MASK_EE_TOO_LOW_TEMP;
8620 
8621 	if (ext_ufs_feature & UFS_DEV_HIGH_TEMP_NOTIF)
8622 		mask |= MASK_EE_TOO_HIGH_TEMP;
8623 
8624 	if (mask) {
8625 		ufshcd_enable_ee(hba, mask);
8626 		ufs_hwmon_probe(hba, mask);
8627 	}
8628 }
8629 
8630 static void ufshcd_device_lvl_exception_probe(struct ufs_hba *hba, u8 *desc_buf)
8631 {
8632 	u32 ext_ufs_feature;
8633 
8634 	if (hba->dev_info.wspecversion < 0x410)
8635 		return;
8636 
8637 	ext_ufs_feature = get_unaligned_be32(desc_buf +
8638 				DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
8639 	if (!(ext_ufs_feature & UFS_DEV_LVL_EXCEPTION_SUP))
8640 		return;
8641 
8642 	atomic_set(&hba->dev_lvl_exception_count, 0);
8643 	ufshcd_enable_ee(hba, MASK_EE_DEV_LVL_EXCEPTION);
8644 }
8645 
8646 static void ufshcd_set_rtt(struct ufs_hba *hba)
8647 {
8648 	struct ufs_dev_info *dev_info = &hba->dev_info;
8649 	u32 rtt = 0;
8650 	u32 dev_rtt = 0;
8651 
8652 	/* RTT override makes sense only for UFS-4.0 and above */
8653 	if (dev_info->wspecversion < 0x400)
8654 		return;
8655 
8656 	if (ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
8657 				    QUERY_ATTR_IDN_MAX_NUM_OF_RTT, 0, 0, &dev_rtt)) {
8658 		dev_err(hba->dev, "failed reading bMaxNumOfRTT\n");
8659 		return;
8660 	}
8661 
8662 	/* do not override if it was already written */
8663 	if (dev_rtt != DEFAULT_MAX_NUM_RTT)
8664 		return;
8665 
8666 	rtt = min_t(int, dev_info->rtt_cap, hba->nortt);
8667 
8668 	if (rtt == dev_rtt)
8669 		return;
8670 
8671 	if (ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
8672 				    QUERY_ATTR_IDN_MAX_NUM_OF_RTT, 0, 0, &rtt))
8673 		dev_err(hba->dev, "failed writing bMaxNumOfRTT\n");
8674 }
8675 
8676 void ufshcd_fixup_dev_quirks(struct ufs_hba *hba,
8677 			     const struct ufs_dev_quirk *fixups)
8678 {
8679 	const struct ufs_dev_quirk *f;
8680 	struct ufs_dev_info *dev_info = &hba->dev_info;
8681 
8682 	if (!fixups)
8683 		return;
8684 
8685 	for (f = fixups; f->quirk; f++) {
8686 		if ((f->wmanufacturerid == dev_info->wmanufacturerid ||
8687 		     f->wmanufacturerid == UFS_ANY_VENDOR) &&
8688 		     ((dev_info->model &&
8689 		       STR_PRFX_EQUAL(f->model, dev_info->model)) ||
8690 		      !strcmp(f->model, UFS_ANY_MODEL)))
8691 			hba->dev_quirks |= f->quirk;
8692 	}
8693 }
8694 EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks);
8695 
8696 static void ufs_fixup_device_setup(struct ufs_hba *hba)
8697 {
8698 	/* fix by general quirk table */
8699 	ufshcd_fixup_dev_quirks(hba, ufs_fixups);
8700 
8701 	/* allow vendors to fix quirks */
8702 	ufshcd_vops_fixup_dev_quirks(hba);
8703 }
8704 
8705 static void ufshcd_update_rtc(struct ufs_hba *hba)
8706 {
8707 	struct timespec64 ts64;
8708 	int err;
8709 	u32 val;
8710 
8711 	ktime_get_real_ts64(&ts64);
8712 
8713 	if (ts64.tv_sec < hba->dev_info.rtc_time_baseline) {
8714 		dev_warn_once(hba->dev, "%s: Current time precedes previous setting!\n", __func__);
8715 		return;
8716 	}
8717 
8718 	/*
8719 	 * The Absolute RTC mode has a 136-year limit, spanning from 2010 to 2146. If a time beyond
8720 	 * 2146 is required, it is recommended to choose the relative RTC mode.
8721 	 */
8722 	val = ts64.tv_sec - hba->dev_info.rtc_time_baseline;
8723 
8724 	/* Skip update RTC if RPM state is not RPM_ACTIVE */
8725 	if (ufshcd_rpm_get_if_active(hba) <= 0)
8726 		return;
8727 
8728 	err = ufshcd_query_attr(hba, UPIU_QUERY_OPCODE_WRITE_ATTR, QUERY_ATTR_IDN_SECONDS_PASSED,
8729 				0, 0, &val);
8730 	ufshcd_rpm_put(hba);
8731 
8732 	if (err)
8733 		dev_err(hba->dev, "%s: Failed to update rtc %d\n", __func__, err);
8734 	else if (hba->dev_info.rtc_type == UFS_RTC_RELATIVE)
8735 		hba->dev_info.rtc_time_baseline = ts64.tv_sec;
8736 }
8737 
8738 static void ufshcd_rtc_work(struct work_struct *work)
8739 {
8740 	struct ufs_hba *hba;
8741 
8742 	hba = container_of(to_delayed_work(work), struct ufs_hba, ufs_rtc_update_work);
8743 
8744 	 /* Update RTC only when there are no requests in progress and UFSHCI is operational */
8745 	if (!ufshcd_is_ufs_dev_busy(hba) &&
8746 	    hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL &&
8747 	    !hba->clk_gating.active_reqs)
8748 		ufshcd_update_rtc(hba);
8749 
8750 	if (ufshcd_is_ufs_dev_active(hba) && hba->dev_info.rtc_update_period)
8751 		schedule_delayed_work(&hba->ufs_rtc_update_work,
8752 				      msecs_to_jiffies(hba->dev_info.rtc_update_period));
8753 }
8754 
8755 static void ufs_init_rtc(struct ufs_hba *hba, u8 *desc_buf)
8756 {
8757 	u16 periodic_rtc_update = get_unaligned_be16(&desc_buf[DEVICE_DESC_PARAM_FRQ_RTC]);
8758 	struct ufs_dev_info *dev_info = &hba->dev_info;
8759 
8760 	if (periodic_rtc_update & UFS_RTC_TIME_BASELINE) {
8761 		dev_info->rtc_type = UFS_RTC_ABSOLUTE;
8762 
8763 		/*
8764 		 * The concept of measuring time in Linux as the number of seconds elapsed since
8765 		 * 00:00:00 UTC on January 1, 1970, and UFS ABS RTC is elapsed from January 1st
8766 		 * 2010 00:00, here we need to adjust ABS baseline.
8767 		 */
8768 		dev_info->rtc_time_baseline = mktime64(2010, 1, 1, 0, 0, 0) -
8769 							mktime64(1970, 1, 1, 0, 0, 0);
8770 	} else {
8771 		dev_info->rtc_type = UFS_RTC_RELATIVE;
8772 		dev_info->rtc_time_baseline = 0;
8773 	}
8774 
8775 	/*
8776 	 * We ignore TIME_PERIOD defined in wPeriodicRTCUpdate because Spec does not clearly state
8777 	 * how to calculate the specific update period for each time unit. And we disable periodic
8778 	 * RTC update work, let user configure by sysfs node according to specific circumstance.
8779 	 */
8780 	dev_info->rtc_update_period = 0;
8781 }
8782 
8783 /**
8784  * ufshcd_create_device_id - Generate unique device identifier string
8785  * @hba: per-adapter instance
8786  * @desc_buf: device descriptor buffer
8787  *
8788  * Creates a unique device ID string combining manufacturer ID, spec version,
8789  * model name, serial number (as hex), device version, and manufacture date.
8790  *
8791  * Returns: Allocated device ID string on success, NULL on failure
8792  */
8793 static char *ufshcd_create_device_id(struct ufs_hba *hba, u8 *desc_buf)
8794 {
8795 	struct ufs_dev_info *dev_info = &hba->dev_info;
8796 	u16 manufacture_date;
8797 	u16 device_version;
8798 	u8 *serial_number;
8799 	char *serial_hex;
8800 	char *device_id;
8801 	u8 serial_index;
8802 	int serial_len;
8803 	int ret;
8804 
8805 	serial_index = desc_buf[DEVICE_DESC_PARAM_SN];
8806 
8807 	ret = ufshcd_read_string_desc(hba, serial_index, &serial_number, SD_RAW);
8808 	if (ret < 0) {
8809 		dev_err(hba->dev, "Failed reading Serial Number. err = %d\n", ret);
8810 		return NULL;
8811 	}
8812 
8813 	device_version = get_unaligned_be16(&desc_buf[DEVICE_DESC_PARAM_DEV_VER]);
8814 	manufacture_date = get_unaligned_be16(&desc_buf[DEVICE_DESC_PARAM_MANF_DATE]);
8815 
8816 	serial_len = ret;
8817 	/* Allocate buffer for hex string: 2 chars per byte + null terminator */
8818 	serial_hex = kzalloc(serial_len * 2 + 1, GFP_KERNEL);
8819 	if (!serial_hex) {
8820 		kfree(serial_number);
8821 		return NULL;
8822 	}
8823 
8824 	bin2hex(serial_hex, serial_number, serial_len);
8825 
8826 	/*
8827 	 * Device ID format is ABI with secure world - do not change without firmware
8828 	 * coordination.
8829 	 */
8830 	device_id = kasprintf(GFP_KERNEL, "%04X-%04X-%s-%s-%04X-%04X",
8831 			      dev_info->wmanufacturerid, dev_info->wspecversion,
8832 			      dev_info->model, serial_hex, device_version,
8833 			      manufacture_date);
8834 
8835 	kfree(serial_hex);
8836 	kfree(serial_number);
8837 
8838 	if (!device_id)
8839 		dev_warn(hba->dev, "Failed to allocate unique device ID\n");
8840 
8841 	return device_id;
8842 }
8843 
8844 static int ufs_get_device_desc(struct ufs_hba *hba)
8845 {
8846 	struct ufs_dev_info *dev_info = &hba->dev_info;
8847 	struct Scsi_Host *shost = hba->host;
8848 	int err;
8849 	u8 model_index;
8850 	u8 *desc_buf;
8851 
8852 	desc_buf = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
8853 	if (!desc_buf) {
8854 		err = -ENOMEM;
8855 		goto out;
8856 	}
8857 
8858 	err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf,
8859 				     QUERY_DESC_MAX_SIZE);
8860 	if (err) {
8861 		dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
8862 			__func__, err);
8863 		goto out;
8864 	}
8865 
8866 	/*
8867 	 * getting vendor (manufacturerID) and Bank Index in big endian
8868 	 * format
8869 	 */
8870 	dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
8871 				     desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
8872 
8873 	/* getting Specification Version in big endian format */
8874 	dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 |
8875 				      desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1];
8876 	dev_info->bqueuedepth = desc_buf[DEVICE_DESC_PARAM_Q_DPTH];
8877 
8878 	/*
8879 	 * According to the UFS standard, the UFS device queue depth
8880 	 * (bQueueDepth) must be in the range 1..255 if the shared queueing
8881 	 * architecture is supported. bQueueDepth is zero if the shared queueing
8882 	 * architecture is not supported.
8883 	 */
8884 	if (dev_info->bqueuedepth)
8885 		shost->cmd_per_lun = min(hba->nutrs, dev_info->bqueuedepth) -
8886 				     UFSHCD_NUM_RESERVED;
8887 	else
8888 		shost->cmd_per_lun = shost->can_queue;
8889 
8890 	dev_info->rtt_cap = desc_buf[DEVICE_DESC_PARAM_RTT_CAP];
8891 
8892 	dev_info->hid_sup = get_unaligned_be32(desc_buf +
8893 				DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP) &
8894 				UFS_DEV_HID_SUPPORT;
8895 
8896 	model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
8897 
8898 	err = ufshcd_read_string_desc(hba, model_index,
8899 				      &dev_info->model, SD_ASCII_STD);
8900 	if (err < 0) {
8901 		dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
8902 			__func__, err);
8903 		goto out;
8904 	}
8905 
8906 	/* Generate unique device ID */
8907 	dev_info->device_id = ufshcd_create_device_id(hba, desc_buf);
8908 
8909 	hba->luns_avail = desc_buf[DEVICE_DESC_PARAM_NUM_LU] +
8910 		desc_buf[DEVICE_DESC_PARAM_NUM_WLU];
8911 
8912 	ufs_fixup_device_setup(hba);
8913 
8914 	ufshcd_wb_probe(hba, desc_buf);
8915 
8916 	ufshcd_temp_notif_probe(hba, desc_buf);
8917 
8918 	if (dev_info->wspecversion >= 0x410) {
8919 		hba->critical_health_count = 0;
8920 		ufshcd_enable_ee(hba, MASK_EE_HEALTH_CRITICAL);
8921 	}
8922 
8923 	ufs_init_rtc(hba, desc_buf);
8924 
8925 	ufshcd_device_lvl_exception_probe(hba, desc_buf);
8926 
8927 	/*
8928 	 * ufshcd_read_string_desc returns size of the string
8929 	 * reset the error value
8930 	 */
8931 	err = 0;
8932 
8933 out:
8934 	kfree(desc_buf);
8935 	return err;
8936 }
8937 
8938 static void ufs_put_device_desc(struct ufs_hba *hba)
8939 {
8940 	struct ufs_dev_info *dev_info = &hba->dev_info;
8941 
8942 	kfree(dev_info->model);
8943 	dev_info->model = NULL;
8944 	kfree(dev_info->device_id);
8945 	dev_info->device_id = NULL;
8946 }
8947 
8948 /**
8949  * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
8950  * less than device PA_TACTIVATE time.
8951  * @hba: per-adapter instance
8952  *
8953  * Some UFS devices require host PA_TACTIVATE to be lower than device
8954  * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
8955  * for such devices.
8956  *
8957  * Return: zero on success, non-zero error value on failure.
8958  */
8959 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
8960 {
8961 	int ret = 0;
8962 	u32 granularity, peer_granularity;
8963 	u32 pa_tactivate, peer_pa_tactivate;
8964 	u32 pa_tactivate_us, peer_pa_tactivate_us;
8965 	static const u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
8966 
8967 	ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
8968 				  &granularity);
8969 	if (ret)
8970 		goto out;
8971 
8972 	ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
8973 				  &peer_granularity);
8974 	if (ret)
8975 		goto out;
8976 
8977 	if ((granularity < PA_GRANULARITY_MIN_VAL) ||
8978 	    (granularity > PA_GRANULARITY_MAX_VAL)) {
8979 		dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
8980 			__func__, granularity);
8981 		return -EINVAL;
8982 	}
8983 
8984 	if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
8985 	    (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
8986 		dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
8987 			__func__, peer_granularity);
8988 		return -EINVAL;
8989 	}
8990 
8991 	ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
8992 	if (ret)
8993 		goto out;
8994 
8995 	ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
8996 				  &peer_pa_tactivate);
8997 	if (ret)
8998 		goto out;
8999 
9000 	pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
9001 	peer_pa_tactivate_us = peer_pa_tactivate *
9002 			     gran_to_us_table[peer_granularity - 1];
9003 
9004 	if (pa_tactivate_us >= peer_pa_tactivate_us) {
9005 		u32 new_peer_pa_tactivate;
9006 
9007 		new_peer_pa_tactivate = pa_tactivate_us /
9008 				      gran_to_us_table[peer_granularity - 1];
9009 		new_peer_pa_tactivate++;
9010 		ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
9011 					  new_peer_pa_tactivate);
9012 	}
9013 
9014 out:
9015 	return ret;
9016 }
9017 
9018 /**
9019  * ufshcd_quirk_override_pa_h8time - Ensures proper adjustment of PA_HIBERN8TIME.
9020  * @hba: per-adapter instance
9021  *
9022  * Some UFS devices require specific adjustments to the PA_HIBERN8TIME parameter
9023  * to ensure proper hibernation timing. This function retrieves the current
9024  * PA_HIBERN8TIME value and increments it by 100us.
9025  */
9026 static void ufshcd_quirk_override_pa_h8time(struct ufs_hba *hba)
9027 {
9028 	u32 pa_h8time;
9029 	int ret;
9030 
9031 	ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_HIBERN8TIME), &pa_h8time);
9032 	if (ret) {
9033 		dev_err(hba->dev, "Failed to get PA_HIBERN8TIME: %d\n", ret);
9034 		return;
9035 	}
9036 
9037 	/* Increment by 1 to increase hibernation time by 100 µs */
9038 	ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME), pa_h8time + 1);
9039 	if (ret)
9040 		dev_err(hba->dev, "Failed updating PA_HIBERN8TIME: %d\n", ret);
9041 }
9042 
9043 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
9044 {
9045 	ufshcd_vops_apply_dev_quirks(hba);
9046 
9047 	if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
9048 		/* set 1ms timeout for PA_TACTIVATE */
9049 		ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
9050 
9051 	if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
9052 		ufshcd_quirk_tune_host_pa_tactivate(hba);
9053 
9054 	if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_HIBER8TIME)
9055 		ufshcd_quirk_override_pa_h8time(hba);
9056 
9057 	ufshcd_apply_valid_tx_eq_settings(hba);
9058 }
9059 
9060 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
9061 {
9062 	hba->ufs_stats.hibern8_exit_cnt = 0;
9063 	hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
9064 	hba->req_abort_count = 0;
9065 }
9066 
9067 static int ufshcd_device_geo_params_init(struct ufs_hba *hba)
9068 {
9069 	int err;
9070 	u8 *desc_buf;
9071 
9072 	desc_buf = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
9073 	if (!desc_buf) {
9074 		err = -ENOMEM;
9075 		goto out;
9076 	}
9077 
9078 	err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0,
9079 				     desc_buf, QUERY_DESC_MAX_SIZE);
9080 	if (err) {
9081 		dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n",
9082 				__func__, err);
9083 		goto out;
9084 	}
9085 
9086 	if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1)
9087 		hba->dev_info.max_lu_supported = 32;
9088 	else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0)
9089 		hba->dev_info.max_lu_supported = 8;
9090 
9091 	hba->dev_info.rpmb_io_size = desc_buf[GEOMETRY_DESC_PARAM_RPMB_RW_SIZE];
9092 
9093 out:
9094 	kfree(desc_buf);
9095 	return err;
9096 }
9097 
9098 struct ufs_ref_clk {
9099 	unsigned long freq_hz;
9100 	enum ufs_ref_clk_freq val;
9101 };
9102 
9103 static const struct ufs_ref_clk ufs_ref_clk_freqs[] = {
9104 	{19200000, REF_CLK_FREQ_19_2_MHZ},
9105 	{26000000, REF_CLK_FREQ_26_MHZ},
9106 	{38400000, REF_CLK_FREQ_38_4_MHZ},
9107 	{52000000, REF_CLK_FREQ_52_MHZ},
9108 	{0, REF_CLK_FREQ_INVAL},
9109 };
9110 
9111 static enum ufs_ref_clk_freq
9112 ufs_get_bref_clk_from_hz(unsigned long freq)
9113 {
9114 	int i;
9115 
9116 	for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
9117 		if (ufs_ref_clk_freqs[i].freq_hz == freq)
9118 			return ufs_ref_clk_freqs[i].val;
9119 
9120 	return REF_CLK_FREQ_INVAL;
9121 }
9122 
9123 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
9124 {
9125 	unsigned long freq;
9126 
9127 	freq = clk_get_rate(refclk);
9128 
9129 	hba->dev_ref_clk_freq =
9130 		ufs_get_bref_clk_from_hz(freq);
9131 
9132 	if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
9133 		dev_err(hba->dev,
9134 		"invalid ref_clk setting = %ld\n", freq);
9135 }
9136 
9137 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
9138 {
9139 	int err;
9140 	u32 ref_clk;
9141 	u32 freq = hba->dev_ref_clk_freq;
9142 
9143 	err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
9144 			QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
9145 
9146 	if (err) {
9147 		dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
9148 			err);
9149 		goto out;
9150 	}
9151 
9152 	if (ref_clk == freq)
9153 		goto out; /* nothing to update */
9154 
9155 	err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
9156 			QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
9157 
9158 	if (err) {
9159 		dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
9160 			ufs_ref_clk_freqs[freq].freq_hz);
9161 		goto out;
9162 	}
9163 
9164 	dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
9165 			ufs_ref_clk_freqs[freq].freq_hz);
9166 
9167 out:
9168 	return err;
9169 }
9170 
9171 static int ufshcd_device_params_init(struct ufs_hba *hba)
9172 {
9173 	bool flag;
9174 	int ret;
9175 
9176 	/* Init UFS geometry descriptor related parameters */
9177 	ret = ufshcd_device_geo_params_init(hba);
9178 	if (ret)
9179 		goto out;
9180 
9181 	/* Check and apply UFS device quirks */
9182 	ret = ufs_get_device_desc(hba);
9183 	if (ret) {
9184 		dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
9185 			__func__, ret);
9186 		goto out;
9187 	}
9188 
9189 	ufshcd_set_rtt(hba);
9190 
9191 	ufshcd_get_ref_clk_gating_wait(hba);
9192 
9193 	if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
9194 			QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag))
9195 		hba->dev_info.f_power_on_wp_en = flag;
9196 
9197 	/* Probe maximum power mode co-supported by both UFS host and device */
9198 	if (ufshcd_get_max_pwr_mode(hba))
9199 		dev_err(hba->dev,
9200 			"%s: Failed getting max supported power mode\n",
9201 			__func__);
9202 
9203 	ufshcd_retrieve_tx_eq_settings(hba);
9204 out:
9205 	return ret;
9206 }
9207 
9208 static void ufshcd_set_timestamp_attr(struct ufs_hba *hba)
9209 {
9210 	struct ufs_dev_info *dev_info = &hba->dev_info;
9211 	u64 ts_ns;
9212 	int err;
9213 
9214 	if (dev_info->wspecversion < 0x400 ||
9215 	    hba->dev_quirks & UFS_DEVICE_QUIRK_NO_TIMESTAMP_SUPPORT)
9216 		return;
9217 
9218 	ts_ns = ktime_get_real_ns();
9219 	err = ufshcd_query_attr_qword(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
9220 				      QUERY_ATTR_IDN_TIMESTAMP, 0, 0, &ts_ns);
9221 	if (err)
9222 		dev_err(hba->dev, "%s: failed to set timestamp %d\n",
9223 			__func__, err);
9224 }
9225 
9226 /**
9227  * ufshcd_add_lus - probe and add UFS logical units
9228  * @hba: per-adapter instance
9229  *
9230  * Return: 0 upon success; < 0 upon failure.
9231  */
9232 static int ufshcd_add_lus(struct ufs_hba *hba)
9233 {
9234 	int ret;
9235 
9236 	/* Add required well known logical units to scsi mid layer */
9237 	ret = ufshcd_scsi_add_wlus(hba);
9238 	if (ret)
9239 		goto out;
9240 
9241 	/* Initialize devfreq after UFS device is detected */
9242 	if (ufshcd_is_clkscaling_supported(hba)) {
9243 		memcpy(&hba->clk_scaling.saved_pwr_info,
9244 			&hba->pwr_info,
9245 			sizeof(struct ufs_pa_layer_attr));
9246 		hba->clk_scaling.is_allowed = true;
9247 
9248 		ret = ufshcd_devfreq_init(hba);
9249 		if (ret)
9250 			goto out;
9251 
9252 		hba->clk_scaling.is_enabled = true;
9253 		ufshcd_init_clk_scaling_sysfs(hba);
9254 	}
9255 
9256 	/*
9257 	 * The RTC update code accesses the hba->ufs_device_wlun->sdev_gendev
9258 	 * pointer and hence must only be started after the WLUN pointer has
9259 	 * been initialized by ufshcd_scsi_add_wlus().
9260 	 */
9261 	schedule_delayed_work(&hba->ufs_rtc_update_work,
9262 			      msecs_to_jiffies(UFS_RTC_UPDATE_INTERVAL_MS));
9263 
9264 	ufs_bsg_probe(hba);
9265 	scsi_scan_host(hba->host);
9266 	ufs_rpmb_probe(hba);
9267 
9268 out:
9269 	return ret;
9270 }
9271 
9272 /* SDB - Single Doorbell */
9273 static void ufshcd_release_sdb_queue(struct ufs_hba *hba, int nutrs)
9274 {
9275 	size_t ucdl_size, utrdl_size;
9276 
9277 	ucdl_size = ufshcd_get_ucd_size(hba) * (nutrs - UFSHCD_NUM_RESERVED);
9278 	dmam_free_coherent(hba->dev, ucdl_size, hba->ucdl_base_addr,
9279 			   hba->ucdl_dma_addr);
9280 
9281 	utrdl_size = sizeof(struct utp_transfer_req_desc) * nutrs;
9282 	dmam_free_coherent(hba->dev, utrdl_size, hba->utrdl_base_addr,
9283 			   hba->utrdl_dma_addr);
9284 }
9285 
9286 static int ufshcd_alloc_mcq(struct ufs_hba *hba)
9287 {
9288 	int ret;
9289 	int old_nutrs = hba->nutrs;
9290 
9291 	ret = ufshcd_get_hba_mac(hba);
9292 	if (ret < 0)
9293 		return ret;
9294 
9295 	hba->nutrs = ret;
9296 	ret = ufshcd_mcq_init(hba);
9297 	if (ret)
9298 		goto err;
9299 
9300 	/*
9301 	 * Previously allocated memory for nutrs may not be enough in MCQ mode.
9302 	 * Number of supported tags in MCQ mode may be larger than SDB mode.
9303 	 */
9304 	if (hba->nutrs != old_nutrs) {
9305 		ufshcd_release_sdb_queue(hba, old_nutrs);
9306 		ret = ufshcd_memory_alloc(hba);
9307 		if (ret)
9308 			goto err;
9309 		ufshcd_host_memory_configure(hba);
9310 	}
9311 
9312 	ret = ufshcd_mcq_memory_alloc(hba);
9313 	if (ret)
9314 		goto err;
9315 
9316 	hba->host->can_queue = hba->nutrs - UFSHCD_NUM_RESERVED;
9317 
9318 	return 0;
9319 err:
9320 	hba->nutrs = old_nutrs;
9321 	return ret;
9322 }
9323 
9324 static void ufshcd_config_mcq(struct ufs_hba *hba)
9325 {
9326 	int ret;
9327 
9328 	ret = ufshcd_mcq_vops_config_esi(hba);
9329 	hba->mcq_esi_enabled = !ret;
9330 	dev_info(hba->dev, "ESI %sconfigured\n", ret ? "is not " : "");
9331 
9332 	ufshcd_mcq_make_queues_operational(hba);
9333 	ufshcd_mcq_config_mac(hba, hba->nutrs);
9334 
9335 	dev_info(hba->dev, "MCQ configured, nr_queues=%d, io_queues=%d, read_queue=%d, poll_queues=%d, queue_depth=%d\n",
9336 		 hba->nr_hw_queues, hba->nr_queues[HCTX_TYPE_DEFAULT],
9337 		 hba->nr_queues[HCTX_TYPE_READ], hba->nr_queues[HCTX_TYPE_POLL],
9338 		 hba->nutrs);
9339 }
9340 
9341 /**
9342  * ufshcd_get_op_mode - get UFS operating mode.
9343  * @hba: per-adapter instance
9344  *
9345  * Use the PA_PWRMODE value to represent the operating mode of UFS.
9346  *
9347  */
9348 static enum ufs_op_mode ufshcd_get_op_mode(struct ufs_hba *hba)
9349 {
9350 	u32 mode;
9351 	u8 rx_mode;
9352 	u8 tx_mode;
9353 
9354 	ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode);
9355 	rx_mode = (mode >> PWRMODE_RX_OFFSET) & PWRMODE_MASK;
9356 	tx_mode = mode & PWRMODE_MASK;
9357 
9358 	if ((rx_mode == SLOW_MODE || rx_mode == SLOWAUTO_MODE) &&
9359 	    (tx_mode == SLOW_MODE || tx_mode == SLOWAUTO_MODE))
9360 		return LS_MODE;
9361 
9362 	return HS_MODE;
9363 }
9364 
9365 static int ufshcd_post_device_init(struct ufs_hba *hba)
9366 {
9367 	int ret;
9368 
9369 	ufshcd_tune_unipro_params(hba);
9370 
9371 	/* UFS device is also active now */
9372 	ufshcd_set_ufs_dev_active(hba);
9373 
9374 	/* Indicate that DME QoS Monitor has been reset */
9375 	atomic_set(&hba->dme_qos_notification, 0x1);
9376 	if (hba->dme_qos_sysfs_handle)
9377 		sysfs_notify_dirent(hba->dme_qos_sysfs_handle);
9378 
9379 	ufshcd_force_reset_auto_bkops(hba);
9380 
9381 	ufshcd_set_timestamp_attr(hba);
9382 
9383 	if (!hba->max_pwr_info.is_valid)
9384 		return 0;
9385 
9386 	/*
9387 	 * Set the right value to bRefClkFreq in LS_MODE before attempting to
9388 	 * switch to HS gears.
9389 	 */
9390 	if (ufshcd_get_op_mode(hba) == LS_MODE &&
9391 	    hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
9392 		ufshcd_set_dev_ref_clk(hba);
9393 
9394 	/* Gear up to HS gear. */
9395 	ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info,
9396 				     UFSHCD_PMC_POLICY_DONT_FORCE);
9397 	if (ret) {
9398 		dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
9399 			__func__, ret);
9400 		return ret;
9401 	}
9402 
9403 	return 0;
9404 }
9405 
9406 static int ufshcd_device_init(struct ufs_hba *hba, bool init_dev_params)
9407 {
9408 	int ret;
9409 
9410 	WARN_ON_ONCE(!hba->scsi_host_added);
9411 
9412 	hba->ufshcd_state = UFSHCD_STATE_RESET;
9413 
9414 	ret = ufshcd_link_startup(hba);
9415 	if (ret)
9416 		return ret;
9417 
9418 	if (hba->quirks & UFSHCD_QUIRK_SKIP_PH_CONFIGURATION)
9419 		return ret;
9420 
9421 	/* Debug counters initialization */
9422 	ufshcd_clear_dbg_ufs_stats(hba);
9423 
9424 	/* UniPro link is active now */
9425 	ufshcd_set_link_active(hba);
9426 
9427 	/* Reconfigure MCQ upon reset */
9428 	if (hba->mcq_enabled && !init_dev_params) {
9429 		ufshcd_config_mcq(hba);
9430 		ufshcd_mcq_enable(hba);
9431 	}
9432 
9433 	/* Verify device initialization by sending NOP OUT UPIU */
9434 	ret = ufshcd_verify_dev_init(hba);
9435 	if (ret)
9436 		return ret;
9437 
9438 	/* Initiate UFS initialization, and waiting until completion */
9439 	ret = ufshcd_complete_dev_init(hba);
9440 	if (ret)
9441 		return ret;
9442 
9443 	/*
9444 	 * Initialize UFS device parameters used by driver, these
9445 	 * parameters are associated with UFS descriptors.
9446 	 */
9447 	if (init_dev_params) {
9448 		ret = ufshcd_device_params_init(hba);
9449 		if (ret)
9450 			return ret;
9451 		if (is_mcq_supported(hba) &&
9452 		    hba->quirks & UFSHCD_QUIRK_REINIT_AFTER_MAX_GEAR_SWITCH) {
9453 			ufshcd_config_mcq(hba);
9454 			ufshcd_mcq_enable(hba);
9455 		}
9456 	}
9457 
9458 	return ufshcd_post_device_init(hba);
9459 }
9460 
9461 /**
9462  * ufshcd_probe_hba - probe hba to detect device and initialize it
9463  * @hba: per-adapter instance
9464  * @init_dev_params: whether or not to call ufshcd_device_params_init().
9465  *
9466  * Execute link-startup and verify device initialization
9467  *
9468  * Return: 0 upon success; < 0 upon failure.
9469  */
9470 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params)
9471 {
9472 	int ret;
9473 
9474 	if (!hba->pm_op_in_progress &&
9475 	    (hba->quirks & UFSHCD_QUIRK_REINIT_AFTER_MAX_GEAR_SWITCH)) {
9476 		/* Reset the device and controller before doing reinit */
9477 		ufshcd_device_reset(hba);
9478 		ufs_put_device_desc(hba);
9479 		ufshcd_hba_stop(hba);
9480 		ret = ufshcd_hba_enable(hba);
9481 		if (ret) {
9482 			dev_err(hba->dev, "Host controller enable failed\n");
9483 			ufshcd_print_evt_hist(hba);
9484 			ufshcd_print_host_state(hba);
9485 			return ret;
9486 		}
9487 
9488 		/* Reinit the device */
9489 		ret = ufshcd_device_init(hba, init_dev_params);
9490 		if (ret)
9491 			return ret;
9492 	}
9493 
9494 	ufshcd_print_pwr_info(hba);
9495 
9496 	/*
9497 	 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec)
9498 	 * and for removable UFS card as well, hence always set the parameter.
9499 	 * Note: Error handler may issue the device reset hence resetting
9500 	 * bActiveICCLevel as well so it is always safe to set this here.
9501 	 */
9502 	ufshcd_set_active_icc_lvl(hba);
9503 
9504 	/* Enable UFS Write Booster if supported */
9505 	ufshcd_configure_wb(hba);
9506 
9507 	if (hba->ee_usr_mask)
9508 		ufshcd_write_ee_control(hba);
9509 	ufshcd_configure_auto_hibern8(hba);
9510 
9511 	return 0;
9512 }
9513 
9514 /**
9515  * ufshcd_async_scan - asynchronous execution for probing hba
9516  * @data: data pointer to pass to this function
9517  * @cookie: cookie data
9518  */
9519 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
9520 {
9521 	struct ufs_hba *hba = (struct ufs_hba *)data;
9522 	ktime_t probe_start;
9523 	int ret;
9524 
9525 	down(&hba->host_sem);
9526 	/* Initialize hba, detect and initialize UFS device */
9527 	probe_start = ktime_get();
9528 	ret = ufshcd_probe_hba(hba, true);
9529 	ufshcd_process_probe_result(hba, probe_start, ret);
9530 	up(&hba->host_sem);
9531 	if (ret)
9532 		goto out;
9533 
9534 	/* Probe and add UFS logical units  */
9535 	ret = ufshcd_add_lus(hba);
9536 
9537 out:
9538 	pm_runtime_put_sync(hba->dev);
9539 
9540 	if (ret)
9541 		dev_err(hba->dev, "%s failed: %d\n", __func__, ret);
9542 }
9543 
9544 static enum scsi_timeout_action ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
9545 {
9546 	struct ufs_hba *hba = shost_priv(scmd->device->host);
9547 
9548 	if (!hba->pm_op_in_progress) {
9549 		/* Activate the error handler in the SCSI core. */
9550 		return SCSI_EH_NOT_HANDLED;
9551 	}
9552 
9553 	/*
9554 	 * Handle the timeout directly to prevent a deadlock between
9555 	 * ufshcd_set_dev_pwr_mode() and ufshcd_err_handler().
9556 	 */
9557 	ufshcd_link_recovery(hba);
9558 	dev_info(hba->dev, "%s() finished; outstanding_tasks = %#lx.\n",
9559 		 __func__, hba->outstanding_tasks);
9560 
9561 	/*
9562 	 * ufshcd_link_recovery() may already have completed @scmd, e.g. via
9563 	 * the existing MCQ force-completion path.
9564 	 */
9565 	if (!test_bit(SCMD_STATE_COMPLETE, &scmd->state)) {
9566 		if (!hba->mcq_enabled) {
9567 			unsigned long flags;
9568 			struct request *rq = scsi_cmd_to_rq(scmd);
9569 
9570 			spin_lock_irqsave(&hba->outstanding_lock, flags);
9571 			__clear_bit(rq->tag, &hba->outstanding_reqs);
9572 			spin_unlock_irqrestore(&hba->outstanding_lock, flags);
9573 		}
9574 
9575 		if (ufshcd_is_scsi_cmd(scmd)) {
9576 			set_host_byte(scmd, DID_REQUEUE);
9577 			ufshcd_release_scsi_cmd(hba, scmd);
9578 		} else {
9579 			set_host_byte(scmd, DID_TIME_OUT);
9580 		}
9581 
9582 		scsi_done(scmd);
9583 	}
9584 
9585 	return SCSI_EH_DONE;
9586 }
9587 
9588 static const struct attribute_group *ufshcd_driver_groups[] = {
9589 	&ufs_sysfs_unit_descriptor_group,
9590 	&ufs_sysfs_lun_attributes_group,
9591 	NULL,
9592 };
9593 
9594 static struct ufs_hba_variant_params ufs_hba_vps = {
9595 	.hba_enable_delay_us		= 1000,
9596 	.wb_flush_threshold		= UFS_WB_BUF_REMAIN_PERCENT(40),
9597 	.devfreq_profile.polling_ms	= 100,
9598 	.devfreq_profile.target		= ufshcd_devfreq_target,
9599 	.devfreq_profile.get_dev_status	= ufshcd_devfreq_get_dev_status,
9600 	.ondemand_data.upthreshold	= 70,
9601 	.ondemand_data.downdifferential	= 5,
9602 };
9603 
9604 static const struct scsi_host_template ufshcd_driver_template = {
9605 	.module			= THIS_MODULE,
9606 	.name			= UFSHCD,
9607 	.proc_name		= UFSHCD,
9608 	.map_queues		= ufshcd_map_queues,
9609 	.cmd_size		= sizeof(struct ufshcd_lrb),
9610 	.init_cmd_priv		= ufshcd_init_cmd_priv,
9611 	.queuecommand		= ufshcd_queuecommand,
9612 	.queue_reserved_command	= ufshcd_queue_reserved_command,
9613 	.nr_reserved_cmds	= UFSHCD_NUM_RESERVED,
9614 	.mq_poll		= ufshcd_poll,
9615 	.sdev_init		= ufshcd_sdev_init,
9616 	.sdev_configure		= ufshcd_sdev_configure,
9617 	.sdev_destroy		= ufshcd_sdev_destroy,
9618 	.change_queue_depth	= ufshcd_change_queue_depth,
9619 	.eh_abort_handler	= ufshcd_abort,
9620 	.eh_device_reset_handler = ufshcd_eh_device_reset_handler,
9621 	.eh_host_reset_handler   = ufshcd_eh_host_reset_handler,
9622 	.eh_timed_out		= ufshcd_eh_timed_out,
9623 	.this_id		= -1,
9624 	.sg_tablesize		= SG_ALL,
9625 	.max_segment_size	= PRDT_DATA_BYTE_COUNT_MAX,
9626 	.max_sectors		= SZ_1M / SECTOR_SIZE,
9627 	.max_host_blocked	= 1,
9628 	.host_tagset		= true,
9629 	.track_queue_depth	= 1,
9630 	.skip_settle_delay	= 1,
9631 	.sdev_groups		= ufshcd_driver_groups,
9632 };
9633 
9634 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
9635 				   int ua)
9636 {
9637 	int ret;
9638 
9639 	if (!vreg)
9640 		return 0;
9641 
9642 	/*
9643 	 * "set_load" operation shall be required on those regulators
9644 	 * which specifically configured current limitation. Otherwise
9645 	 * zero max_uA may cause unexpected behavior when regulator is
9646 	 * enabled or set as high power mode.
9647 	 */
9648 	if (!vreg->max_uA)
9649 		return 0;
9650 
9651 	ret = regulator_set_load(vreg->reg, ua);
9652 	if (ret < 0) {
9653 		dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
9654 				__func__, vreg->name, ua, ret);
9655 	}
9656 
9657 	return ret;
9658 }
9659 
9660 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
9661 					 struct ufs_vreg *vreg)
9662 {
9663 	return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
9664 }
9665 
9666 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
9667 					 struct ufs_vreg *vreg)
9668 {
9669 	if (!vreg)
9670 		return 0;
9671 
9672 	return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
9673 }
9674 
9675 static int ufshcd_config_vreg(struct device *dev,
9676 		struct ufs_vreg *vreg, bool on)
9677 {
9678 	if (regulator_count_voltages(vreg->reg) <= 0)
9679 		return 0;
9680 
9681 	return ufshcd_config_vreg_load(dev, vreg, on ? vreg->max_uA : 0);
9682 }
9683 
9684 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
9685 {
9686 	int ret = 0;
9687 
9688 	if (!vreg || vreg->enabled)
9689 		goto out;
9690 
9691 	ret = ufshcd_config_vreg(dev, vreg, true);
9692 	if (!ret)
9693 		ret = regulator_enable(vreg->reg);
9694 
9695 	if (!ret)
9696 		vreg->enabled = true;
9697 	else
9698 		dev_err(dev, "%s: %s enable failed, err=%d\n",
9699 				__func__, vreg->name, ret);
9700 out:
9701 	return ret;
9702 }
9703 
9704 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
9705 {
9706 	int ret = 0;
9707 
9708 	if (!vreg || !vreg->enabled || vreg->always_on)
9709 		goto out;
9710 
9711 	ret = regulator_disable(vreg->reg);
9712 
9713 	if (!ret) {
9714 		/* ignore errors on applying disable config */
9715 		ufshcd_config_vreg(dev, vreg, false);
9716 		vreg->enabled = false;
9717 	} else {
9718 		dev_err(dev, "%s: %s disable failed, err=%d\n",
9719 				__func__, vreg->name, ret);
9720 	}
9721 out:
9722 	return ret;
9723 }
9724 
9725 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
9726 {
9727 	int ret = 0;
9728 	struct device *dev = hba->dev;
9729 	struct ufs_vreg_info *info = &hba->vreg_info;
9730 
9731 	ret = ufshcd_toggle_vreg(dev, info->vcc, on);
9732 	if (ret)
9733 		goto out;
9734 
9735 	ret = ufshcd_toggle_vreg(dev, info->vccq, on);
9736 	if (ret)
9737 		goto out;
9738 
9739 	ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
9740 
9741 out:
9742 	if (ret) {
9743 		ufshcd_toggle_vreg(dev, info->vccq2, false);
9744 		ufshcd_toggle_vreg(dev, info->vccq, false);
9745 		ufshcd_toggle_vreg(dev, info->vcc, false);
9746 	}
9747 	return ret;
9748 }
9749 
9750 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
9751 {
9752 	struct ufs_vreg_info *info = &hba->vreg_info;
9753 
9754 	return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
9755 }
9756 
9757 int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
9758 {
9759 	int ret = 0;
9760 
9761 	if (!vreg)
9762 		goto out;
9763 
9764 	vreg->reg = devm_regulator_get(dev, vreg->name);
9765 	if (IS_ERR(vreg->reg)) {
9766 		ret = PTR_ERR(vreg->reg);
9767 		dev_err(dev, "%s: %s get failed, err=%d\n",
9768 				__func__, vreg->name, ret);
9769 	}
9770 out:
9771 	return ret;
9772 }
9773 EXPORT_SYMBOL_GPL(ufshcd_get_vreg);
9774 
9775 static int ufshcd_init_vreg(struct ufs_hba *hba)
9776 {
9777 	int ret = 0;
9778 	struct device *dev = hba->dev;
9779 	struct ufs_vreg_info *info = &hba->vreg_info;
9780 
9781 	ret = ufshcd_get_vreg(dev, info->vcc);
9782 	if (ret)
9783 		goto out;
9784 
9785 	ret = ufshcd_get_vreg(dev, info->vccq);
9786 	if (!ret)
9787 		ret = ufshcd_get_vreg(dev, info->vccq2);
9788 out:
9789 	return ret;
9790 }
9791 
9792 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
9793 {
9794 	struct ufs_vreg_info *info = &hba->vreg_info;
9795 
9796 	return ufshcd_get_vreg(hba->dev, info->vdd_hba);
9797 }
9798 
9799 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
9800 {
9801 	int ret = 0;
9802 	struct ufs_clk_info *clki;
9803 	struct list_head *head = &hba->clk_list_head;
9804 	ktime_t start = ktime_get();
9805 	bool clk_state_changed = false;
9806 
9807 	if (list_empty(head))
9808 		goto out;
9809 
9810 	ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
9811 	if (ret)
9812 		return ret;
9813 
9814 	list_for_each_entry(clki, head, list) {
9815 		if (!IS_ERR_OR_NULL(clki->clk)) {
9816 			/*
9817 			 * Don't disable clocks which are needed
9818 			 * to keep the link active.
9819 			 */
9820 			if (ufshcd_is_link_active(hba) &&
9821 			    clki->keep_link_active)
9822 				continue;
9823 
9824 			clk_state_changed = on ^ clki->enabled;
9825 			if (on && !clki->enabled) {
9826 				ret = clk_prepare_enable(clki->clk);
9827 				if (ret) {
9828 					dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
9829 						__func__, clki->name, ret);
9830 					goto out;
9831 				}
9832 			} else if (!on && clki->enabled) {
9833 				clk_disable_unprepare(clki->clk);
9834 			}
9835 			clki->enabled = on;
9836 			dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
9837 					clki->name, on ? "en" : "dis");
9838 		}
9839 	}
9840 
9841 	ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
9842 	if (ret)
9843 		return ret;
9844 
9845 	if (!ufshcd_is_clkscaling_supported(hba))
9846 		ufshcd_pm_qos_update(hba, on);
9847 out:
9848 	if (ret) {
9849 		list_for_each_entry(clki, head, list) {
9850 			if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
9851 				clk_disable_unprepare(clki->clk);
9852 		}
9853 	} else if (!ret && on && hba->clk_gating.is_initialized) {
9854 		scoped_guard(spinlock_irqsave, &hba->clk_gating.lock)
9855 			hba->clk_gating.state = CLKS_ON;
9856 		trace_ufshcd_clk_gating(hba,
9857 					hba->clk_gating.state);
9858 	}
9859 
9860 	if (clk_state_changed)
9861 		trace_ufshcd_profile_clk_gating(hba,
9862 			(on ? "on" : "off"),
9863 			ktime_to_us(ktime_sub(ktime_get(), start)), ret);
9864 	return ret;
9865 }
9866 
9867 static enum ufs_ref_clk_freq ufshcd_parse_ref_clk_property(struct ufs_hba *hba)
9868 {
9869 	u32 freq;
9870 	int ret = device_property_read_u32(hba->dev, "ref-clk-freq", &freq);
9871 
9872 	if (ret) {
9873 		dev_dbg(hba->dev, "Cannot query 'ref-clk-freq' property = %d", ret);
9874 		return REF_CLK_FREQ_INVAL;
9875 	}
9876 
9877 	return ufs_get_bref_clk_from_hz(freq);
9878 }
9879 
9880 static int ufshcd_init_clocks(struct ufs_hba *hba)
9881 {
9882 	int ret = 0;
9883 	struct ufs_clk_info *clki;
9884 	struct device *dev = hba->dev;
9885 	struct list_head *head = &hba->clk_list_head;
9886 
9887 	if (list_empty(head))
9888 		goto out;
9889 
9890 	list_for_each_entry(clki, head, list) {
9891 		if (!clki->name)
9892 			continue;
9893 
9894 		clki->clk = devm_clk_get(dev, clki->name);
9895 		if (IS_ERR(clki->clk)) {
9896 			ret = PTR_ERR(clki->clk);
9897 			dev_err(dev, "%s: %s clk get failed, %d\n",
9898 					__func__, clki->name, ret);
9899 			goto out;
9900 		}
9901 
9902 		/*
9903 		 * Parse device ref clk freq as per device tree "ref_clk".
9904 		 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
9905 		 * in ufshcd_alloc_host().
9906 		 */
9907 		if (!strcmp(clki->name, "ref_clk"))
9908 			ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
9909 
9910 		if (clki->max_freq) {
9911 			ret = clk_set_rate(clki->clk, clki->max_freq);
9912 			if (ret) {
9913 				dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
9914 					__func__, clki->name,
9915 					clki->max_freq, ret);
9916 				goto out;
9917 			}
9918 			clki->curr_freq = clki->max_freq;
9919 		}
9920 		dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
9921 				clki->name, clk_get_rate(clki->clk));
9922 	}
9923 
9924 	/* Set Max. frequency for all clocks */
9925 	if (hba->use_pm_opp) {
9926 		ret = ufshcd_opp_set_rate(hba, ULONG_MAX);
9927 		if (ret) {
9928 			dev_err(hba->dev, "%s: failed to set OPP: %d", __func__,
9929 				ret);
9930 			goto out;
9931 		}
9932 	}
9933 
9934 out:
9935 	return ret;
9936 }
9937 
9938 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
9939 {
9940 	int err = ufshcd_vops_init(hba);
9941 
9942 	if (err)
9943 		dev_err_probe(hba->dev, err,
9944 			      "%s: variant %s init failed with err %d\n",
9945 			      __func__, ufshcd_get_var_name(hba), err);
9946 	return err;
9947 }
9948 
9949 static int ufshcd_hba_init(struct ufs_hba *hba)
9950 {
9951 	int err;
9952 
9953 	/*
9954 	 * Handle host controller power separately from the UFS device power
9955 	 * rails as it will help controlling the UFS host controller power
9956 	 * collapse easily which is different than UFS device power collapse.
9957 	 * Also, enable the host controller power before we go ahead with rest
9958 	 * of the initialization here.
9959 	 */
9960 	err = ufshcd_init_hba_vreg(hba);
9961 	if (err)
9962 		goto out;
9963 
9964 	err = ufshcd_setup_hba_vreg(hba, true);
9965 	if (err)
9966 		goto out;
9967 
9968 	err = ufshcd_init_clocks(hba);
9969 	if (err)
9970 		goto out_disable_hba_vreg;
9971 
9972 	if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
9973 		hba->dev_ref_clk_freq = ufshcd_parse_ref_clk_property(hba);
9974 
9975 	err = ufshcd_setup_clocks(hba, true);
9976 	if (err)
9977 		goto out_disable_hba_vreg;
9978 
9979 	err = ufshcd_init_vreg(hba);
9980 	if (err)
9981 		goto out_disable_clks;
9982 
9983 	err = ufshcd_setup_vreg(hba, true);
9984 	if (err)
9985 		goto out_disable_clks;
9986 
9987 	err = ufshcd_variant_hba_init(hba);
9988 	if (err)
9989 		goto out_disable_vreg;
9990 
9991 	ufs_debugfs_hba_init(hba);
9992 	ufs_fault_inject_hba_init(hba);
9993 
9994 	hba->is_powered = true;
9995 	goto out;
9996 
9997 out_disable_vreg:
9998 	ufshcd_setup_vreg(hba, false);
9999 out_disable_clks:
10000 	ufshcd_setup_clocks(hba, false);
10001 out_disable_hba_vreg:
10002 	ufshcd_setup_hba_vreg(hba, false);
10003 out:
10004 	return err;
10005 }
10006 
10007 static void ufshcd_hba_exit(struct ufs_hba *hba)
10008 {
10009 	if (hba->is_powered) {
10010 		ufshcd_pm_qos_exit(hba);
10011 		ufshcd_exit_clk_scaling(hba);
10012 		ufshcd_exit_clk_gating(hba);
10013 		if (hba->eh_wq)
10014 			destroy_workqueue(hba->eh_wq);
10015 		ufs_debugfs_hba_exit(hba);
10016 		ufshcd_vops_exit(hba);
10017 		ufshcd_setup_vreg(hba, false);
10018 		ufshcd_setup_clocks(hba, false);
10019 		ufshcd_setup_hba_vreg(hba, false);
10020 		hba->is_powered = false;
10021 		ufs_put_device_desc(hba);
10022 	}
10023 	sysfs_put(hba->dme_qos_sysfs_handle);
10024 }
10025 
10026 static int ufshcd_execute_start_stop(struct scsi_device *sdev,
10027 				     enum ufs_dev_pwr_mode pwr_mode,
10028 				     struct scsi_sense_hdr *sshdr)
10029 {
10030 	const unsigned char cdb[6] = { START_STOP, 0, 0, 0, pwr_mode << 4, 0 };
10031 	struct scsi_failure failure_defs[] = {
10032 		{
10033 			.allowed = 2,
10034 			.result = SCMD_FAILURE_RESULT_ANY,
10035 		},
10036 	};
10037 	struct scsi_failures failures = {
10038 		.failure_definitions = failure_defs,
10039 	};
10040 	const struct scsi_exec_args args = {
10041 		.failures = &failures,
10042 		.sshdr = sshdr,
10043 		.req_flags = BLK_MQ_REQ_PM,
10044 		.scmd_flags = SCMD_FAIL_IF_RECOVERING,
10045 	};
10046 
10047 	return scsi_execute_cmd(sdev, cdb, REQ_OP_DRV_IN, /*buffer=*/NULL,
10048 			/*bufflen=*/0, /*timeout=*/10 * HZ, /*retries=*/0,
10049 			&args);
10050 }
10051 
10052 /**
10053  * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
10054  *			     power mode
10055  * @hba: per adapter instance
10056  * @pwr_mode: device power mode to set
10057  *
10058  * Return: 0 if requested power mode is set successfully;
10059  *         < 0 if failed to set the requested power mode.
10060  */
10061 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
10062 				     enum ufs_dev_pwr_mode pwr_mode)
10063 {
10064 	struct scsi_sense_hdr sshdr;
10065 	struct scsi_device *sdp;
10066 	unsigned long flags;
10067 	int ret;
10068 
10069 	spin_lock_irqsave(hba->host->host_lock, flags);
10070 	sdp = hba->ufs_device_wlun;
10071 	if (sdp && scsi_device_online(sdp))
10072 		ret = scsi_device_get(sdp);
10073 	else
10074 		ret = -ENODEV;
10075 	spin_unlock_irqrestore(hba->host->host_lock, flags);
10076 
10077 	if (ret)
10078 		return ret;
10079 
10080 	/*
10081 	 * If scsi commands fail, the scsi mid-layer schedules scsi error-
10082 	 * handling, which would wait for host to be resumed. Since we know
10083 	 * we are functional while we are here, skip host resume in error
10084 	 * handling context.
10085 	 */
10086 	WRITE_ONCE(hba->host->eh_noresume, 1);
10087 
10088 	/*
10089 	 * Current function would be generally called from the power management
10090 	 * callbacks hence set the RQF_PM flag so that it doesn't resume the
10091 	 * already suspended childs.
10092 	 */
10093 	ret = ufshcd_execute_start_stop(sdp, pwr_mode, &sshdr);
10094 	if (ret) {
10095 		sdev_printk(KERN_WARNING, sdp,
10096 			    "START_STOP failed for power mode: %d, result %x\n",
10097 			    pwr_mode, ret);
10098 		if (ret > 0) {
10099 			if (scsi_sense_valid(&sshdr))
10100 				scsi_print_sense_hdr(sdp, NULL, &sshdr);
10101 			ret = -EIO;
10102 		}
10103 	} else {
10104 		hba->curr_dev_pwr_mode = pwr_mode;
10105 	}
10106 
10107 	scsi_device_put(sdp);
10108 	WRITE_ONCE(hba->host->eh_noresume, 0);
10109 	return ret;
10110 }
10111 
10112 static int ufshcd_link_state_transition(struct ufs_hba *hba,
10113 					enum uic_link_state req_link_state,
10114 					bool check_for_bkops)
10115 {
10116 	int ret = 0;
10117 
10118 	if (req_link_state == hba->uic_link_state)
10119 		return 0;
10120 
10121 	if (req_link_state == UIC_LINK_HIBERN8_STATE) {
10122 		ret = ufshcd_uic_hibern8_enter(hba);
10123 		if (!ret) {
10124 			ufshcd_set_link_hibern8(hba);
10125 		} else {
10126 			dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
10127 					__func__, ret);
10128 			goto out;
10129 		}
10130 	}
10131 	/*
10132 	 * If autobkops is enabled, link can't be turned off because
10133 	 * turning off the link would also turn off the device, except in the
10134 	 * case of DeepSleep where the device is expected to remain powered.
10135 	 */
10136 	else if ((req_link_state == UIC_LINK_OFF_STATE) &&
10137 		 (!check_for_bkops || !hba->auto_bkops_enabled)) {
10138 		/*
10139 		 * Let's make sure that link is in low power mode, we are doing
10140 		 * this currently by putting the link in Hibern8. Otherway to
10141 		 * put the link in low power mode is to send the DME end point
10142 		 * to device and then send the DME reset command to local
10143 		 * unipro. But putting the link in hibern8 is much faster.
10144 		 *
10145 		 * Note also that putting the link in Hibern8 is a requirement
10146 		 * for entering DeepSleep.
10147 		 */
10148 		ret = ufshcd_uic_hibern8_enter(hba);
10149 		if (ret) {
10150 			dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
10151 					__func__, ret);
10152 			goto out;
10153 		}
10154 		/*
10155 		 * Change controller state to "reset state" which
10156 		 * should also put the link in off/reset state
10157 		 */
10158 		ufshcd_hba_stop(hba);
10159 		/*
10160 		 * TODO: Check if we need any delay to make sure that
10161 		 * controller is reset
10162 		 */
10163 		ufshcd_set_link_off(hba);
10164 	}
10165 
10166 out:
10167 	return ret;
10168 }
10169 
10170 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
10171 {
10172 	bool vcc_off = false;
10173 
10174 	/*
10175 	 * It seems some UFS devices may keep drawing more than sleep current
10176 	 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
10177 	 * To avoid this situation, add 2ms delay before putting these UFS
10178 	 * rails in LPM mode.
10179 	 */
10180 	if (!ufshcd_is_link_active(hba) &&
10181 	    hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
10182 		usleep_range(2000, 2100);
10183 
10184 	/*
10185 	 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
10186 	 * power.
10187 	 *
10188 	 * If UFS device and link is in OFF state, all power supplies (VCC,
10189 	 * VCCQ, VCCQ2) can be turned off if power on write protect is not
10190 	 * required. If UFS link is inactive (Hibern8 or OFF state) and device
10191 	 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
10192 	 *
10193 	 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
10194 	 * in low power state which would save some power.
10195 	 *
10196 	 * If Write Booster is enabled and the device needs to flush the WB
10197 	 * buffer OR if bkops status is urgent for WB, keep Vcc on.
10198 	 */
10199 	if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
10200 	    !hba->dev_info.is_lu_power_on_wp) {
10201 		ufshcd_setup_vreg(hba, false);
10202 		vcc_off = true;
10203 	} else if (!ufshcd_is_ufs_dev_active(hba)) {
10204 		ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
10205 		vcc_off = true;
10206 		if (ufshcd_is_link_hibern8(hba) || ufshcd_is_link_off(hba)) {
10207 			ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
10208 			ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
10209 		}
10210 	}
10211 
10212 	/*
10213 	 * All UFS devices require delay after VCC power rail is turned-off.
10214 	 */
10215 	if (vcc_off && hba->vreg_info.vcc && !hba->vreg_info.vcc->always_on)
10216 		usleep_range(hba->vcc_off_delay_us,
10217 			     hba->vcc_off_delay_us + 100);
10218 }
10219 
10220 #ifdef CONFIG_PM
10221 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
10222 {
10223 	bool vcc_on = false;
10224 	int ret = 0;
10225 
10226 	if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
10227 	    !hba->dev_info.is_lu_power_on_wp) {
10228 		ret = ufshcd_setup_vreg(hba, true);
10229 		vcc_on = true;
10230 	} else if (!ufshcd_is_ufs_dev_active(hba)) {
10231 		if (!ufshcd_is_link_active(hba)) {
10232 			ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
10233 			if (ret)
10234 				goto vcc_disable;
10235 			ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
10236 			if (ret)
10237 				goto vccq_lpm;
10238 		}
10239 		ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
10240 		vcc_on = true;
10241 	}
10242 	goto out;
10243 
10244 vccq_lpm:
10245 	ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
10246 vcc_disable:
10247 	ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
10248 out:
10249 	/*
10250 	 * On platforms with a slow VCC ramp-up, a delay is needed after
10251 	 * turning on VCC to ensure the voltage is stable before the
10252 	 * reference clock is enabled.
10253 	 */
10254 	if (hba->quirks & UFSHCD_QUIRK_VCC_ON_DELAY && !ret && vcc_on &&
10255 	    hba->vreg_info.vcc && !hba->vreg_info.vcc->always_on)
10256 		usleep_range(1000, 1100);
10257 
10258 	return ret;
10259 }
10260 #endif /* CONFIG_PM */
10261 
10262 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
10263 {
10264 	if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
10265 		ufshcd_setup_hba_vreg(hba, false);
10266 }
10267 
10268 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
10269 {
10270 	if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
10271 		ufshcd_setup_hba_vreg(hba, true);
10272 }
10273 
10274 static int __ufshcd_wl_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
10275 {
10276 	int ret = 0;
10277 	bool check_for_bkops;
10278 	enum ufs_pm_level pm_lvl;
10279 	enum ufs_dev_pwr_mode req_dev_pwr_mode;
10280 	enum uic_link_state req_link_state;
10281 
10282 	hba->pm_op_in_progress = true;
10283 	if (pm_op != UFS_SHUTDOWN_PM) {
10284 		pm_lvl = pm_op == UFS_RUNTIME_PM ?
10285 			 hba->rpm_lvl : hba->spm_lvl;
10286 		req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
10287 		req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
10288 	} else {
10289 		req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
10290 		req_link_state = UIC_LINK_OFF_STATE;
10291 	}
10292 
10293 	/*
10294 	 * If we can't transition into any of the low power modes
10295 	 * just gate the clocks.
10296 	 */
10297 	ufshcd_hold(hba);
10298 	hba->clk_gating.is_suspended = true;
10299 
10300 	if (ufshcd_is_clkscaling_supported(hba))
10301 		ufshcd_clk_scaling_suspend(hba, true);
10302 
10303 	if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
10304 			req_link_state == UIC_LINK_ACTIVE_STATE) {
10305 		ufshcd_disable_auto_bkops(hba);
10306 		flush_work(&hba->eeh_work);
10307 		cancel_delayed_work_sync(&hba->ufs_rtc_update_work);
10308 		goto vops_suspend;
10309 	}
10310 
10311 	if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
10312 	    (req_link_state == hba->uic_link_state))
10313 		goto enable_scaling;
10314 
10315 	/* UFS device & link must be active before we enter in this function */
10316 	if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
10317 		/*  Wait err handler finish or trigger err recovery */
10318 		if (!ufshcd_eh_in_progress(hba))
10319 			ufshcd_force_error_recovery(hba);
10320 		ret = -EBUSY;
10321 		goto enable_scaling;
10322 	}
10323 
10324 	if (pm_op == UFS_RUNTIME_PM) {
10325 		if (ufshcd_can_autobkops_during_suspend(hba)) {
10326 			/*
10327 			 * The device is idle with no requests in the queue,
10328 			 * allow background operations if bkops status shows
10329 			 * that performance might be impacted.
10330 			 */
10331 			ret = ufshcd_bkops_ctrl(hba);
10332 			if (ret) {
10333 				/*
10334 				 * If return err in suspend flow, IO will hang.
10335 				 * Trigger error handler and break suspend for
10336 				 * error recovery.
10337 				 */
10338 				ufshcd_force_error_recovery(hba);
10339 				ret = -EBUSY;
10340 				goto enable_scaling;
10341 			}
10342 		} else {
10343 			/* make sure that auto bkops is disabled */
10344 			ufshcd_disable_auto_bkops(hba);
10345 		}
10346 		/*
10347 		 * If device needs to do BKOP or WB buffer flush during
10348 		 * Hibern8, keep device power mode as "active power mode"
10349 		 * and VCC supply.
10350 		 */
10351 		hba->dev_info.b_rpm_dev_flush_capable =
10352 			hba->auto_bkops_enabled ||
10353 			(((req_link_state == UIC_LINK_HIBERN8_STATE) ||
10354 			((req_link_state == UIC_LINK_ACTIVE_STATE) &&
10355 			ufshcd_is_auto_hibern8_enabled(hba))) &&
10356 			ufshcd_wb_need_flush(hba));
10357 	}
10358 
10359 	flush_work(&hba->eeh_work);
10360 	cancel_delayed_work_sync(&hba->ufs_rtc_update_work);
10361 
10362 	ret = ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
10363 	if (ret)
10364 		goto enable_scaling;
10365 
10366 	if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) {
10367 		if (pm_op != UFS_RUNTIME_PM)
10368 			/* ensure that bkops is disabled */
10369 			ufshcd_disable_auto_bkops(hba);
10370 
10371 		if (!hba->dev_info.b_rpm_dev_flush_capable) {
10372 			ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
10373 			if (ret && pm_op != UFS_SHUTDOWN_PM) {
10374 				/*
10375 				 * If return err in suspend flow, IO will hang.
10376 				 * Trigger error handler and break suspend for
10377 				 * error recovery.
10378 				 */
10379 				ufshcd_force_error_recovery(hba);
10380 				ret = -EBUSY;
10381 			}
10382 			if (ret)
10383 				goto enable_scaling;
10384 		}
10385 	}
10386 
10387 	/*
10388 	 * In the case of DeepSleep, the device is expected to remain powered
10389 	 * with the link off, so do not check for bkops.
10390 	 */
10391 	check_for_bkops = !ufshcd_is_ufs_dev_deepsleep(hba);
10392 	ret = ufshcd_link_state_transition(hba, req_link_state, check_for_bkops);
10393 	if (ret && pm_op != UFS_SHUTDOWN_PM) {
10394 		/*
10395 		 * If return err in suspend flow, IO will hang.
10396 		 * Trigger error handler and break suspend for
10397 		 * error recovery.
10398 		 */
10399 		ufshcd_force_error_recovery(hba);
10400 		ret = -EBUSY;
10401 	}
10402 	if (ret)
10403 		goto set_dev_active;
10404 
10405 vops_suspend:
10406 	/*
10407 	 * Call vendor specific suspend callback. As these callbacks may access
10408 	 * vendor specific host controller register space call them before the
10409 	 * host clocks are ON.
10410 	 */
10411 	ret = ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
10412 	if (ret)
10413 		goto set_link_active;
10414 
10415 	goto out;
10416 
10417 set_link_active:
10418 	/*
10419 	 * Device hardware reset is required to exit DeepSleep. Also, for
10420 	 * DeepSleep, the link is off so host reset and restore will be done
10421 	 * further below.
10422 	 */
10423 	if (ufshcd_is_ufs_dev_deepsleep(hba)) {
10424 		ufshcd_device_reset(hba);
10425 		WARN_ON(!ufshcd_is_link_off(hba));
10426 	}
10427 	if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
10428 		ufshcd_set_link_active(hba);
10429 	else if (ufshcd_is_link_off(hba))
10430 		ufshcd_host_reset_and_restore(hba);
10431 set_dev_active:
10432 	/* Can also get here needing to exit DeepSleep */
10433 	if (ufshcd_is_ufs_dev_deepsleep(hba)) {
10434 		ufshcd_device_reset(hba);
10435 		ufshcd_host_reset_and_restore(hba);
10436 	}
10437 	if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
10438 		ufshcd_disable_auto_bkops(hba);
10439 enable_scaling:
10440 	if (ufshcd_is_clkscaling_supported(hba))
10441 		ufshcd_clk_scaling_suspend(hba, false);
10442 
10443 	hba->dev_info.b_rpm_dev_flush_capable = false;
10444 out:
10445 	if (hba->dev_info.b_rpm_dev_flush_capable) {
10446 		schedule_delayed_work(&hba->rpm_dev_flush_recheck_work,
10447 			msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS));
10448 	}
10449 
10450 	if (ret) {
10451 		ufshcd_update_evt_hist(hba, UFS_EVT_WL_SUSP_ERR, (u32)ret);
10452 		hba->clk_gating.is_suspended = false;
10453 		ufshcd_release(hba);
10454 	}
10455 	hba->pm_op_in_progress = false;
10456 	return ret;
10457 }
10458 
10459 #ifdef CONFIG_PM
10460 static int __ufshcd_wl_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
10461 {
10462 	int ret;
10463 	enum uic_link_state old_link_state = hba->uic_link_state;
10464 
10465 	hba->pm_op_in_progress = true;
10466 
10467 	/*
10468 	 * Call vendor specific resume callback. As these callbacks may access
10469 	 * vendor specific host controller register space call them when the
10470 	 * host clocks are ON.
10471 	 */
10472 	ret = ufshcd_vops_resume(hba, pm_op);
10473 	if (ret)
10474 		goto out;
10475 
10476 	/* For DeepSleep, the only supported option is to have the link off */
10477 	WARN_ON(ufshcd_is_ufs_dev_deepsleep(hba) && !ufshcd_is_link_off(hba));
10478 
10479 	if (ufshcd_is_link_hibern8(hba)) {
10480 		ret = ufshcd_uic_hibern8_exit(hba);
10481 		if (!ret) {
10482 			ufshcd_set_link_active(hba);
10483 		} else {
10484 			dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
10485 					__func__, ret);
10486 			/*
10487 			 * If the h8 exit fails during the runtime resume
10488 			 * process, it becomes stuck and cannot be recovered
10489 			 * through the error handler. To fix this, use link
10490 			 * recovery instead of the error handler.
10491 			 */
10492 			ret = ufshcd_link_recovery(hba);
10493 			if (ret)
10494 				goto vendor_suspend;
10495 		}
10496 	} else if (ufshcd_is_link_off(hba)) {
10497 		/*
10498 		 * A full initialization of the host and the device is
10499 		 * required since the link was put to off during suspend.
10500 		 * Note, in the case of DeepSleep, the device will exit
10501 		 * DeepSleep due to device reset.
10502 		 */
10503 		ret = ufshcd_reset_and_restore(hba);
10504 		/*
10505 		 * ufshcd_reset_and_restore() should have already
10506 		 * set the link state as active
10507 		 */
10508 		if (ret || !ufshcd_is_link_active(hba))
10509 			goto vendor_suspend;
10510 	}
10511 
10512 	if (!ufshcd_is_ufs_dev_active(hba)) {
10513 		ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
10514 		if (ret)
10515 			goto set_old_link_state;
10516 		ufshcd_set_timestamp_attr(hba);
10517 	}
10518 
10519 	schedule_delayed_work(&hba->ufs_rtc_update_work,
10520 			      msecs_to_jiffies(UFS_RTC_UPDATE_INTERVAL_MS));
10521 
10522 	if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
10523 		ufshcd_enable_auto_bkops(hba);
10524 	else
10525 		/*
10526 		 * If BKOPs operations are urgently needed at this moment then
10527 		 * keep auto-bkops enabled or else disable it.
10528 		 */
10529 		ufshcd_bkops_ctrl(hba);
10530 
10531 	if (hba->ee_usr_mask)
10532 		ufshcd_write_ee_control(hba);
10533 
10534 	if (ufshcd_is_clkscaling_supported(hba))
10535 		ufshcd_clk_scaling_suspend(hba, false);
10536 
10537 	if (hba->dev_info.b_rpm_dev_flush_capable) {
10538 		hba->dev_info.b_rpm_dev_flush_capable = false;
10539 		cancel_delayed_work(&hba->rpm_dev_flush_recheck_work);
10540 	}
10541 
10542 	ufshcd_configure_auto_hibern8(hba);
10543 
10544 	goto out;
10545 
10546 set_old_link_state:
10547 	ufshcd_link_state_transition(hba, old_link_state, 0);
10548 vendor_suspend:
10549 	ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
10550 	ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
10551 out:
10552 	if (ret)
10553 		ufshcd_update_evt_hist(hba, UFS_EVT_WL_RES_ERR, (u32)ret);
10554 	hba->clk_gating.is_suspended = false;
10555 	ufshcd_release(hba);
10556 	hba->pm_op_in_progress = false;
10557 	return ret;
10558 }
10559 
10560 static int ufshcd_wl_runtime_suspend(struct device *dev)
10561 {
10562 	struct scsi_device *sdev = to_scsi_device(dev);
10563 	struct ufs_hba *hba;
10564 	int ret;
10565 	ktime_t start = ktime_get();
10566 
10567 	hba = shost_priv(sdev->host);
10568 
10569 	ret = __ufshcd_wl_suspend(hba, UFS_RUNTIME_PM);
10570 	if (ret)
10571 		dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
10572 
10573 	trace_ufshcd_wl_runtime_suspend(hba, ret,
10574 		ktime_to_us(ktime_sub(ktime_get(), start)),
10575 		hba->curr_dev_pwr_mode, hba->uic_link_state);
10576 
10577 	return ret;
10578 }
10579 
10580 static int ufshcd_wl_runtime_resume(struct device *dev)
10581 {
10582 	struct scsi_device *sdev = to_scsi_device(dev);
10583 	struct ufs_hba *hba;
10584 	int ret = 0;
10585 	ktime_t start = ktime_get();
10586 
10587 	hba = shost_priv(sdev->host);
10588 
10589 	ret = __ufshcd_wl_resume(hba, UFS_RUNTIME_PM);
10590 	if (ret)
10591 		dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
10592 
10593 	trace_ufshcd_wl_runtime_resume(hba, ret,
10594 		ktime_to_us(ktime_sub(ktime_get(), start)),
10595 		hba->curr_dev_pwr_mode, hba->uic_link_state);
10596 
10597 	return ret;
10598 }
10599 #endif
10600 
10601 #ifdef CONFIG_PM_SLEEP
10602 static int ufshcd_wl_suspend(struct device *dev)
10603 {
10604 	struct scsi_device *sdev = to_scsi_device(dev);
10605 	struct ufs_hba *hba;
10606 	int ret = 0;
10607 	ktime_t start = ktime_get();
10608 
10609 	hba = shost_priv(sdev->host);
10610 	down(&hba->host_sem);
10611 
10612 	if (pm_runtime_suspended(dev))
10613 		goto out;
10614 
10615 	ret = __ufshcd_wl_suspend(hba, UFS_SYSTEM_PM);
10616 	if (ret) {
10617 		dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__,  ret);
10618 		up(&hba->host_sem);
10619 	}
10620 
10621 out:
10622 	if (!ret)
10623 		hba->is_sys_suspended = true;
10624 	trace_ufshcd_wl_suspend(hba, ret,
10625 		ktime_to_us(ktime_sub(ktime_get(), start)),
10626 		hba->curr_dev_pwr_mode, hba->uic_link_state);
10627 
10628 	return ret;
10629 }
10630 
10631 static int ufshcd_wl_resume(struct device *dev)
10632 {
10633 	struct scsi_device *sdev = to_scsi_device(dev);
10634 	struct ufs_hba *hba;
10635 	int ret = 0;
10636 	ktime_t start = ktime_get();
10637 
10638 	hba = shost_priv(sdev->host);
10639 
10640 	if (pm_runtime_suspended(dev))
10641 		goto out;
10642 
10643 	ret = __ufshcd_wl_resume(hba, UFS_SYSTEM_PM);
10644 	if (ret)
10645 		dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
10646 out:
10647 	trace_ufshcd_wl_resume(hba, ret,
10648 		ktime_to_us(ktime_sub(ktime_get(), start)),
10649 		hba->curr_dev_pwr_mode, hba->uic_link_state);
10650 	if (!ret)
10651 		hba->is_sys_suspended = false;
10652 	up(&hba->host_sem);
10653 	return ret;
10654 }
10655 #endif
10656 
10657 /**
10658  * ufshcd_suspend - helper function for suspend operations
10659  * @hba: per adapter instance
10660  *
10661  * This function will put disable irqs, turn off clocks
10662  * and set vreg and hba-vreg in lpm mode.
10663  *
10664  * Return: 0 upon success; < 0 upon failure.
10665  */
10666 static int ufshcd_suspend(struct ufs_hba *hba)
10667 {
10668 	int ret;
10669 
10670 	if (!hba->is_powered)
10671 		return 0;
10672 	/*
10673 	 * Disable the host irq as host controller as there won't be any
10674 	 * host controller transaction expected till resume.
10675 	 */
10676 	ufshcd_disable_irq(hba);
10677 	ret = ufshcd_setup_clocks(hba, false);
10678 	if (ret) {
10679 		ufshcd_enable_irq(hba);
10680 		goto out;
10681 	}
10682 	if (ufshcd_is_clkgating_allowed(hba)) {
10683 		hba->clk_gating.state = CLKS_OFF;
10684 		trace_ufshcd_clk_gating(hba,
10685 					hba->clk_gating.state);
10686 	}
10687 
10688 	ufshcd_vreg_set_lpm(hba);
10689 	/* Put the host controller in low power mode if possible */
10690 	ufshcd_hba_vreg_set_lpm(hba);
10691 	ufshcd_pm_qos_update(hba, false);
10692 out:
10693 	if (ret)
10694 		ufshcd_update_evt_hist(hba, UFS_EVT_SUSPEND_ERR, (u32)ret);
10695 	return ret;
10696 }
10697 
10698 #ifdef CONFIG_PM
10699 /**
10700  * ufshcd_resume - helper function for resume operations
10701  * @hba: per adapter instance
10702  *
10703  * This function basically turns on the regulators, clocks and
10704  * irqs of the hba.
10705  *
10706  * Return: 0 for success and non-zero for failure.
10707  */
10708 static int ufshcd_resume(struct ufs_hba *hba)
10709 {
10710 	int ret;
10711 
10712 	if (!hba->is_powered)
10713 		return 0;
10714 
10715 	ufshcd_hba_vreg_set_hpm(hba);
10716 	ret = ufshcd_vreg_set_hpm(hba);
10717 	if (ret)
10718 		goto out;
10719 
10720 	/* Make sure clocks are enabled before accessing controller */
10721 	ret = ufshcd_setup_clocks(hba, true);
10722 	if (ret)
10723 		goto disable_vreg;
10724 
10725 	/* enable the host irq as host controller would be active soon */
10726 	ufshcd_enable_irq(hba);
10727 
10728 	goto out;
10729 
10730 disable_vreg:
10731 	ufshcd_vreg_set_lpm(hba);
10732 out:
10733 	if (ret)
10734 		ufshcd_update_evt_hist(hba, UFS_EVT_RESUME_ERR, (u32)ret);
10735 	return ret;
10736 }
10737 #endif /* CONFIG_PM */
10738 
10739 #ifdef CONFIG_PM_SLEEP
10740 /**
10741  * ufshcd_system_suspend - system suspend callback
10742  * @dev: Device associated with the UFS controller.
10743  *
10744  * Executed before putting the system into a sleep state in which the contents
10745  * of main memory are preserved.
10746  *
10747  * Return: 0 for success and non-zero for failure.
10748  */
10749 int ufshcd_system_suspend(struct device *dev)
10750 {
10751 	struct ufs_hba *hba = dev_get_drvdata(dev);
10752 	int ret = 0;
10753 	ktime_t start = ktime_get();
10754 
10755 	if (pm_runtime_suspended(hba->dev))
10756 		goto out;
10757 
10758 	ret = ufshcd_suspend(hba);
10759 out:
10760 	trace_ufshcd_system_suspend(hba, ret,
10761 		ktime_to_us(ktime_sub(ktime_get(), start)),
10762 		hba->curr_dev_pwr_mode, hba->uic_link_state);
10763 	return ret;
10764 }
10765 EXPORT_SYMBOL(ufshcd_system_suspend);
10766 
10767 /**
10768  * ufshcd_system_resume - system resume callback
10769  * @dev: Device associated with the UFS controller.
10770  *
10771  * Executed after waking the system up from a sleep state in which the contents
10772  * of main memory were preserved.
10773  *
10774  * Return: 0 for success and non-zero for failure.
10775  */
10776 int ufshcd_system_resume(struct device *dev)
10777 {
10778 	struct ufs_hba *hba = dev_get_drvdata(dev);
10779 	ktime_t start = ktime_get();
10780 	int ret = 0;
10781 
10782 	if (pm_runtime_suspended(hba->dev))
10783 		goto out;
10784 
10785 	ret = ufshcd_resume(hba);
10786 
10787 out:
10788 	trace_ufshcd_system_resume(hba, ret,
10789 		ktime_to_us(ktime_sub(ktime_get(), start)),
10790 		hba->curr_dev_pwr_mode, hba->uic_link_state);
10791 
10792 	return ret;
10793 }
10794 EXPORT_SYMBOL(ufshcd_system_resume);
10795 #endif /* CONFIG_PM_SLEEP */
10796 
10797 #ifdef CONFIG_PM
10798 /**
10799  * ufshcd_runtime_suspend - runtime suspend callback
10800  * @dev: Device associated with the UFS controller.
10801  *
10802  * Check the description of ufshcd_suspend() function for more details.
10803  *
10804  * Return: 0 for success and non-zero for failure.
10805  */
10806 int ufshcd_runtime_suspend(struct device *dev)
10807 {
10808 	struct ufs_hba *hba = dev_get_drvdata(dev);
10809 	int ret;
10810 	ktime_t start = ktime_get();
10811 
10812 	ret = ufshcd_suspend(hba);
10813 
10814 	trace_ufshcd_runtime_suspend(hba, ret,
10815 		ktime_to_us(ktime_sub(ktime_get(), start)),
10816 		hba->curr_dev_pwr_mode, hba->uic_link_state);
10817 	return ret;
10818 }
10819 EXPORT_SYMBOL(ufshcd_runtime_suspend);
10820 
10821 /**
10822  * ufshcd_runtime_resume - runtime resume routine
10823  * @dev: Device associated with the UFS controller.
10824  *
10825  * This function basically brings controller
10826  * to active state. Following operations are done in this function:
10827  *
10828  * 1. Turn on all the controller related clocks
10829  * 2. Turn ON VCC rail
10830  *
10831  * Return: 0 upon success; < 0 upon failure.
10832  */
10833 int ufshcd_runtime_resume(struct device *dev)
10834 {
10835 	struct ufs_hba *hba = dev_get_drvdata(dev);
10836 	int ret;
10837 	ktime_t start = ktime_get();
10838 
10839 	ret = ufshcd_resume(hba);
10840 
10841 	trace_ufshcd_runtime_resume(hba, ret,
10842 		ktime_to_us(ktime_sub(ktime_get(), start)),
10843 		hba->curr_dev_pwr_mode, hba->uic_link_state);
10844 	return ret;
10845 }
10846 EXPORT_SYMBOL(ufshcd_runtime_resume);
10847 #endif /* CONFIG_PM */
10848 
10849 static void ufshcd_wl_shutdown(struct scsi_device *sdev)
10850 {
10851 	struct ufs_hba *hba = shost_priv(sdev->host);
10852 
10853 	down(&hba->host_sem);
10854 	hba->shutting_down = true;
10855 	up(&hba->host_sem);
10856 
10857 	/* Turn on everything while shutting down */
10858 	ufshcd_rpm_get_sync(hba);
10859 
10860 	ufshcd_store_tx_eq_settings(hba);
10861 
10862 	scsi_device_quiesce(sdev);
10863 	shost_for_each_device(sdev, hba->host) {
10864 		if (sdev == hba->ufs_device_wlun)
10865 			continue;
10866 		mutex_lock(&sdev->state_mutex);
10867 		scsi_device_set_state(sdev, SDEV_OFFLINE);
10868 		mutex_unlock(&sdev->state_mutex);
10869 	}
10870 	__ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
10871 
10872 	/*
10873 	 * Next, turn off the UFS controller and the UFS regulators. Disable
10874 	 * clocks.
10875 	 */
10876 	if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
10877 		ufshcd_suspend(hba);
10878 
10879 	hba->is_powered = false;
10880 }
10881 
10882 /**
10883  * ufshcd_remove - de-allocate SCSI host and host memory space
10884  *		data structure memory
10885  * @hba: per adapter instance
10886  */
10887 void ufshcd_remove(struct ufs_hba *hba)
10888 {
10889 	if (hba->ufs_device_wlun)
10890 		ufshcd_rpm_get_sync(hba);
10891 	ufs_hwmon_remove(hba);
10892 	ufs_bsg_remove(hba);
10893 	ufs_rpmb_remove(hba);
10894 	ufs_sysfs_remove_nodes(hba->dev);
10895 	cancel_delayed_work_sync(&hba->ufs_rtc_update_work);
10896 	blk_mq_destroy_queue(hba->tmf_queue);
10897 	blk_put_queue(hba->tmf_queue);
10898 	blk_mq_free_tag_set(&hba->tmf_tag_set);
10899 	if (hba->scsi_host_added)
10900 		scsi_remove_host(hba->host);
10901 	/* disable interrupts */
10902 	ufshcd_disable_intr(hba, hba->intr_mask);
10903 	ufshcd_hba_stop(hba);
10904 	ufshcd_hba_exit(hba);
10905 }
10906 EXPORT_SYMBOL_GPL(ufshcd_remove);
10907 
10908 #ifdef CONFIG_PM_SLEEP
10909 int ufshcd_system_freeze(struct device *dev)
10910 {
10911 
10912 	return ufshcd_system_suspend(dev);
10913 
10914 }
10915 EXPORT_SYMBOL_GPL(ufshcd_system_freeze);
10916 
10917 int ufshcd_system_restore(struct device *dev)
10918 {
10919 
10920 	struct ufs_hba *hba = dev_get_drvdata(dev);
10921 	int ret;
10922 
10923 	ret = ufshcd_system_resume(dev);
10924 	if (ret)
10925 		return ret;
10926 
10927 	/* Configure UTRL and UTMRL base address registers */
10928 	ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
10929 			REG_UTP_TRANSFER_REQ_LIST_BASE_L);
10930 	ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
10931 			REG_UTP_TRANSFER_REQ_LIST_BASE_H);
10932 	ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
10933 			REG_UTP_TASK_REQ_LIST_BASE_L);
10934 	ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
10935 			REG_UTP_TASK_REQ_LIST_BASE_H);
10936 	/*
10937 	 * Make sure that UTRL and UTMRL base address registers
10938 	 * are updated with the latest queue addresses. Only after
10939 	 * updating these addresses, we can queue the new commands.
10940 	 */
10941 	ufshcd_readl(hba, REG_UTP_TASK_REQ_LIST_BASE_H);
10942 
10943 	return 0;
10944 
10945 }
10946 EXPORT_SYMBOL_GPL(ufshcd_system_restore);
10947 
10948 int ufshcd_system_thaw(struct device *dev)
10949 {
10950 	return ufshcd_system_resume(dev);
10951 }
10952 EXPORT_SYMBOL_GPL(ufshcd_system_thaw);
10953 #endif /* CONFIG_PM_SLEEP  */
10954 
10955 /**
10956  * ufshcd_set_dma_mask - Set dma mask based on the controller
10957  *			 addressing capability
10958  * @hba: per adapter instance
10959  *
10960  * Return: 0 for success, non-zero for failure.
10961  */
10962 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
10963 {
10964 	if (hba->vops && hba->vops->set_dma_mask)
10965 		return hba->vops->set_dma_mask(hba);
10966 	if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
10967 		if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
10968 			return 0;
10969 	}
10970 	return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
10971 }
10972 
10973 /**
10974  * ufshcd_devres_release - devres cleanup handler, invoked during release of
10975  *			   hba->dev
10976  * @host: pointer to SCSI host
10977  */
10978 static void ufshcd_devres_release(void *host)
10979 {
10980 	scsi_host_put(host);
10981 }
10982 
10983 /**
10984  * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
10985  * @dev: pointer to device handle
10986  * @hba_handle: driver private handle
10987  *
10988  * Return: 0 on success, non-zero value on failure.
10989  *
10990  * NOTE: There is no corresponding ufshcd_dealloc_host() because this function
10991  * keeps track of its allocations using devres and deallocates everything on
10992  * device removal automatically.
10993  */
10994 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
10995 {
10996 	struct Scsi_Host *host;
10997 	struct ufs_hba *hba;
10998 	int err = 0;
10999 
11000 	if (!dev) {
11001 		dev_err(dev,
11002 		"Invalid memory reference for dev is NULL\n");
11003 		err = -ENODEV;
11004 		goto out_error;
11005 	}
11006 
11007 	host = scsi_host_alloc(&ufshcd_driver_template,
11008 				sizeof(struct ufs_hba));
11009 	if (!host) {
11010 		dev_err(dev, "scsi_host_alloc failed\n");
11011 		err = -ENOMEM;
11012 		goto out_error;
11013 	}
11014 
11015 	err = devm_add_action_or_reset(dev, ufshcd_devres_release,
11016 				       host);
11017 	if (err)
11018 		return err;
11019 
11020 	host->nr_maps = HCTX_TYPE_POLL + 1;
11021 	hba = shost_priv(host);
11022 	hba->host = host;
11023 	hba->dev = dev;
11024 	hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
11025 	hba->nop_out_timeout = NOP_OUT_TIMEOUT;
11026 	ufshcd_set_sg_entry_size(hba, sizeof(struct ufshcd_sg_entry));
11027 	INIT_LIST_HEAD(&hba->clk_list_head);
11028 	INIT_LIST_HEAD(&hba->rpmbs);
11029 	spin_lock_init(&hba->outstanding_lock);
11030 
11031 	*hba_handle = hba;
11032 
11033 out_error:
11034 	return err;
11035 }
11036 EXPORT_SYMBOL(ufshcd_alloc_host);
11037 
11038 /* This function exists because blk_mq_alloc_tag_set() requires this. */
11039 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx,
11040 				     const struct blk_mq_queue_data *qd)
11041 {
11042 	WARN_ON_ONCE(true);
11043 	return BLK_STS_NOTSUPP;
11044 }
11045 
11046 static const struct blk_mq_ops ufshcd_tmf_ops = {
11047 	.queue_rq = ufshcd_queue_tmf,
11048 };
11049 
11050 static int ufshcd_add_scsi_host(struct ufs_hba *hba)
11051 {
11052 	int err;
11053 
11054 	WARN_ON_ONCE(!hba->host->can_queue);
11055 	WARN_ON_ONCE(!hba->host->cmd_per_lun);
11056 
11057 	if (is_mcq_supported(hba)) {
11058 		ufshcd_mcq_enable(hba);
11059 		err = ufshcd_alloc_mcq(hba);
11060 		if (err) {
11061 			/* Continue with SDB mode */
11062 			ufshcd_mcq_disable(hba);
11063 			use_mcq_mode = false;
11064 			dev_err(hba->dev, "MCQ mode is disabled, err=%d\n",
11065 				err);
11066 		}
11067 	}
11068 	if (!is_mcq_supported(hba) && !hba->lsdb_sup) {
11069 		dev_err(hba->dev,
11070 			"%s: failed to initialize (legacy doorbell mode not supported)\n",
11071 			__func__);
11072 		return -EINVAL;
11073 	}
11074 
11075 	err = scsi_add_host(hba->host, hba->dev);
11076 	if (err) {
11077 		dev_err(hba->dev, "scsi_add_host failed\n");
11078 		return err;
11079 	}
11080 	hba->scsi_host_added = true;
11081 
11082 	hba->tmf_tag_set = (struct blk_mq_tag_set) {
11083 		.nr_hw_queues	= 1,
11084 		.queue_depth	= hba->nutmrs,
11085 		.ops		= &ufshcd_tmf_ops,
11086 	};
11087 	err = blk_mq_alloc_tag_set(&hba->tmf_tag_set);
11088 	if (err < 0)
11089 		goto remove_scsi_host;
11090 	hba->tmf_queue = blk_mq_alloc_queue(&hba->tmf_tag_set, NULL, NULL);
11091 	if (IS_ERR(hba->tmf_queue)) {
11092 		err = PTR_ERR(hba->tmf_queue);
11093 		goto free_tmf_tag_set;
11094 	}
11095 	hba->tmf_rqs = devm_kcalloc(hba->dev, hba->nutmrs,
11096 				    sizeof(*hba->tmf_rqs), GFP_KERNEL);
11097 	if (!hba->tmf_rqs) {
11098 		err = -ENOMEM;
11099 		goto free_tmf_queue;
11100 	}
11101 
11102 	return 0;
11103 
11104 free_tmf_queue:
11105 	blk_mq_destroy_queue(hba->tmf_queue);
11106 	blk_put_queue(hba->tmf_queue);
11107 
11108 free_tmf_tag_set:
11109 	blk_mq_free_tag_set(&hba->tmf_tag_set);
11110 
11111 remove_scsi_host:
11112 	if (hba->scsi_host_added)
11113 		scsi_remove_host(hba->host);
11114 
11115 	return err;
11116 }
11117 
11118 /**
11119  * ufshcd_init - Driver initialization routine
11120  * @hba: per-adapter instance
11121  * @mmio_base: base register address
11122  * @irq: Interrupt line of device
11123  *
11124  * Return: 0 on success; < 0 on failure.
11125  */
11126 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
11127 {
11128 	int err;
11129 	struct Scsi_Host *host = hba->host;
11130 	struct device *dev = hba->dev;
11131 
11132 	/*
11133 	 * dev_set_drvdata() must be called before any callbacks are registered
11134 	 * that use dev_get_drvdata() (frequency scaling, clock scaling, hwmon,
11135 	 * sysfs).
11136 	 */
11137 	dev_set_drvdata(dev, hba);
11138 
11139 	if (!mmio_base) {
11140 		dev_err(hba->dev,
11141 		"Invalid memory reference for mmio_base is NULL\n");
11142 		err = -ENODEV;
11143 		goto out_error;
11144 	}
11145 
11146 	hba->mmio_base = mmio_base;
11147 	hba->irq = irq;
11148 	hba->vps = &ufs_hba_vps;
11149 
11150 	/*
11151 	 * Initialize clk_gating.lock early since it is being used in
11152 	 * ufshcd_setup_clocks()
11153 	 */
11154 	spin_lock_init(&hba->clk_gating.lock);
11155 
11156 	/* Initialize mutex for PM QoS request synchronization */
11157 	mutex_init(&hba->pm_qos_mutex);
11158 
11159 	/*
11160 	 * Set the default power management level for runtime and system PM.
11161 	 * Host controller drivers can override them in their
11162 	 * 'ufs_hba_variant_ops::init' callback.
11163 	 *
11164 	 * Default power saving mode is to keep UFS link in Hibern8 state
11165 	 * and UFS device in sleep state.
11166 	 */
11167 	hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
11168 						UFS_SLEEP_PWR_MODE,
11169 						UIC_LINK_HIBERN8_STATE);
11170 	hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
11171 						UFS_SLEEP_PWR_MODE,
11172 						UIC_LINK_HIBERN8_STATE);
11173 
11174 	/*
11175 	 * Most ufs devices require 1ms delay after vcc is powered off before
11176 	 * it can be powered on again. Set the default to 2ms. The platform
11177 	 * drivers can override this setting as needed.
11178 	 */
11179 	hba->vcc_off_delay_us = 2000;
11180 
11181 	err = ufshcd_hba_init(hba);
11182 	if (err)
11183 		goto out_error;
11184 
11185 	/* Read capabilities registers */
11186 	err = ufshcd_hba_capabilities(hba);
11187 	if (err)
11188 		goto out_disable;
11189 
11190 	/* Get UFS version supported by the controller */
11191 	hba->ufs_version = ufshcd_get_ufs_version(hba);
11192 
11193 	/* Get Interrupt bit mask per version */
11194 	hba->intr_mask = ufshcd_get_intr_mask(hba);
11195 
11196 	err = ufshcd_set_dma_mask(hba);
11197 	if (err) {
11198 		dev_err(hba->dev, "set dma mask failed\n");
11199 		goto out_disable;
11200 	}
11201 
11202 	/* Allocate memory for host memory space */
11203 	err = ufshcd_memory_alloc(hba);
11204 	if (err) {
11205 		dev_err(hba->dev, "Memory allocation failed\n");
11206 		goto out_disable;
11207 	}
11208 
11209 	/* Configure LRB */
11210 	ufshcd_host_memory_configure(hba);
11211 
11212 	host->can_queue = hba->nutrs - UFSHCD_NUM_RESERVED;
11213 	/*
11214 	 * Set the queue depth for WLUNs. ufs_get_device_desc() will increase
11215 	 * host->cmd_per_lun to a larger value.
11216 	 */
11217 	host->cmd_per_lun = 1;
11218 	host->max_id = UFSHCD_MAX_ID;
11219 	host->max_lun = UFS_MAX_LUNS;
11220 	host->max_channel = UFSHCD_MAX_CHANNEL;
11221 	host->unique_id = host->host_no;
11222 	host->max_cmd_len = UFS_CDB_SIZE;
11223 	host->queuecommand_may_block = !!(hba->caps & UFSHCD_CAP_CLK_GATING);
11224 
11225 	/* Use default RPM delay if host not set */
11226 	if (host->rpm_autosuspend_delay == 0)
11227 		host->rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS;
11228 
11229 	hba->max_pwr_info.is_valid = false;
11230 
11231 	/* Initialize work queues */
11232 	hba->eh_wq = alloc_ordered_workqueue("ufs_eh_wq_%d", WQ_MEM_RECLAIM,
11233 					     hba->host->host_no);
11234 	if (!hba->eh_wq) {
11235 		dev_err(hba->dev, "%s: failed to create eh workqueue\n",
11236 			__func__);
11237 		err = -ENOMEM;
11238 		goto out_disable;
11239 	}
11240 	INIT_WORK(&hba->eh_work, ufshcd_err_handler);
11241 	INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
11242 
11243 	sema_init(&hba->host_sem, 1);
11244 
11245 	/* Initialize UIC command mutex */
11246 	mutex_init(&hba->uic_cmd_mutex);
11247 
11248 	/* Initialize mutex for device management commands */
11249 	mutex_init(&hba->dev_cmd.lock);
11250 
11251 	/* Initialize mutex for exception event control */
11252 	mutex_init(&hba->ee_ctrl_mutex);
11253 
11254 	mutex_init(&hba->wb_mutex);
11255 
11256 	init_rwsem(&hba->clk_scaling_lock);
11257 
11258 	ufshcd_init_clk_gating(hba);
11259 
11260 	ufshcd_init_clk_scaling(hba);
11261 
11262 	/*
11263 	 * In order to avoid any spurious interrupt immediately after
11264 	 * registering UFS controller interrupt handler, clear any pending UFS
11265 	 * interrupt status and disable all the UFS interrupts.
11266 	 */
11267 	ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
11268 		      REG_INTERRUPT_STATUS);
11269 	ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
11270 	/*
11271 	 * Make sure that UFS interrupts are disabled and any pending interrupt
11272 	 * status is cleared before registering UFS interrupt handler.
11273 	 */
11274 	ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
11275 
11276 	/* IRQ registration */
11277 	err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
11278 	if (err) {
11279 		dev_err(hba->dev, "request irq failed\n");
11280 		goto out_disable;
11281 	} else {
11282 		hba->is_irq_enabled = true;
11283 	}
11284 
11285 	/* Reset the attached device */
11286 	ufshcd_device_reset(hba);
11287 
11288 	ufshcd_init_crypto(hba);
11289 
11290 	/* Host controller enable */
11291 	err = ufshcd_hba_enable(hba);
11292 	if (err) {
11293 		dev_err(hba->dev, "Host controller enable failed\n");
11294 		ufshcd_print_evt_hist(hba);
11295 		ufshcd_print_host_state(hba);
11296 		goto out_disable;
11297 	}
11298 
11299 	INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work, ufshcd_rpm_dev_flush_recheck_work);
11300 	INIT_DELAYED_WORK(&hba->ufs_rtc_update_work, ufshcd_rtc_work);
11301 
11302 	/* Set the default auto-hiberate idle timer value to 150 ms */
11303 	if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
11304 		hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
11305 			    FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
11306 	}
11307 
11308 	err = ufshcd_add_scsi_host(hba);
11309 	if (err)
11310 		goto out_disable;
11311 
11312 	/* Hold auto suspend until async scan completes */
11313 	pm_runtime_get_sync(dev);
11314 
11315 	/*
11316 	 * We are assuming that device wasn't put in sleep/power-down
11317 	 * state exclusively during the boot stage before kernel.
11318 	 * This assumption helps avoid doing link startup twice during
11319 	 * ufshcd_probe_hba().
11320 	 */
11321 	ufshcd_set_ufs_dev_active(hba);
11322 
11323 	/* Initialize hba, detect and initialize UFS device */
11324 	ktime_t probe_start = ktime_get();
11325 
11326 	hba->ufshcd_state = UFSHCD_STATE_RESET;
11327 
11328 	err = ufshcd_link_startup(hba);
11329 	if (err)
11330 		goto out_disable;
11331 
11332 	if (hba->mcq_enabled)
11333 		ufshcd_config_mcq(hba);
11334 
11335 	if (hba->quirks & UFSHCD_QUIRK_SKIP_PH_CONFIGURATION)
11336 		goto initialized;
11337 
11338 	/* Debug counters initialization */
11339 	ufshcd_clear_dbg_ufs_stats(hba);
11340 
11341 	/* UniPro link is active now */
11342 	ufshcd_set_link_active(hba);
11343 
11344 	/* Verify device initialization by sending NOP OUT UPIU */
11345 	err = ufshcd_verify_dev_init(hba);
11346 	if (err)
11347 		goto out_disable;
11348 
11349 	/* Initiate UFS initialization, and waiting until completion */
11350 	err = ufshcd_complete_dev_init(hba);
11351 	if (err)
11352 		goto out_disable;
11353 
11354 	err = ufshcd_device_params_init(hba);
11355 	if (err)
11356 		goto out_disable;
11357 
11358 	err = ufshcd_post_device_init(hba);
11359 
11360 initialized:
11361 	ufshcd_process_probe_result(hba, probe_start, err);
11362 	if (err)
11363 		goto out_disable;
11364 
11365 	ufs_sysfs_add_nodes(hba->dev);
11366 	hba->dme_qos_sysfs_handle = sysfs_get_dirent(hba->dev->kobj.sd,
11367 						     "dme_qos_notification");
11368 	async_schedule(ufshcd_async_scan, hba);
11369 
11370 	device_enable_async_suspend(dev);
11371 	ufshcd_pm_qos_init(hba);
11372 	return 0;
11373 
11374 out_disable:
11375 	hba->is_irq_enabled = false;
11376 	ufshcd_hba_exit(hba);
11377 out_error:
11378 	return err > 0 ? -EIO : err;
11379 }
11380 EXPORT_SYMBOL_GPL(ufshcd_init);
11381 
11382 void ufshcd_resume_complete(struct device *dev)
11383 {
11384 	struct ufs_hba *hba = dev_get_drvdata(dev);
11385 
11386 	if (hba->complete_put) {
11387 		ufshcd_rpm_put(hba);
11388 		hba->complete_put = false;
11389 	}
11390 }
11391 EXPORT_SYMBOL_GPL(ufshcd_resume_complete);
11392 
11393 static bool ufshcd_rpm_ok_for_spm(struct ufs_hba *hba)
11394 {
11395 	struct device *dev = &hba->ufs_device_wlun->sdev_gendev;
11396 	enum ufs_dev_pwr_mode dev_pwr_mode;
11397 	enum uic_link_state link_state;
11398 	unsigned long flags;
11399 	bool res;
11400 
11401 	spin_lock_irqsave(&dev->power.lock, flags);
11402 	dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl);
11403 	link_state = ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl);
11404 	res = pm_runtime_suspended(dev) &&
11405 	      hba->curr_dev_pwr_mode == dev_pwr_mode &&
11406 	      hba->uic_link_state == link_state &&
11407 	      !hba->dev_info.b_rpm_dev_flush_capable;
11408 	spin_unlock_irqrestore(&dev->power.lock, flags);
11409 
11410 	return res;
11411 }
11412 
11413 int __ufshcd_suspend_prepare(struct device *dev, bool rpm_ok_for_spm)
11414 {
11415 	struct ufs_hba *hba = dev_get_drvdata(dev);
11416 	int ret;
11417 
11418 	/*
11419 	 * SCSI assumes that runtime-pm and system-pm for scsi drivers
11420 	 * are same. And it doesn't wake up the device for system-suspend
11421 	 * if it's runtime suspended. But ufs doesn't follow that.
11422 	 * Refer ufshcd_resume_complete()
11423 	 */
11424 	if (hba->ufs_device_wlun) {
11425 		/* Prevent runtime suspend */
11426 		ufshcd_rpm_get_noresume(hba);
11427 		/*
11428 		 * Check if already runtime suspended in same state as system
11429 		 * suspend would be.
11430 		 */
11431 		if (!rpm_ok_for_spm || !ufshcd_rpm_ok_for_spm(hba)) {
11432 			/* RPM state is not ok for SPM, so runtime resume */
11433 			ret = ufshcd_rpm_resume(hba);
11434 			if (ret < 0 && ret != -EACCES) {
11435 				ufshcd_rpm_put(hba);
11436 				return ret;
11437 			}
11438 		}
11439 		hba->complete_put = true;
11440 	}
11441 	return 0;
11442 }
11443 EXPORT_SYMBOL_GPL(__ufshcd_suspend_prepare);
11444 
11445 int ufshcd_suspend_prepare(struct device *dev)
11446 {
11447 	return __ufshcd_suspend_prepare(dev, true);
11448 }
11449 EXPORT_SYMBOL_GPL(ufshcd_suspend_prepare);
11450 
11451 #ifdef CONFIG_PM_SLEEP
11452 static int ufshcd_wl_poweroff(struct device *dev)
11453 {
11454 	struct scsi_device *sdev = to_scsi_device(dev);
11455 	struct ufs_hba *hba = shost_priv(sdev->host);
11456 
11457 	__ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
11458 	return 0;
11459 }
11460 #endif
11461 
11462 static int ufshcd_wl_probe(struct scsi_device *sdev)
11463 {
11464 	struct device *dev = &sdev->sdev_gendev;
11465 
11466 	if (!is_device_wlun(sdev))
11467 		return -ENODEV;
11468 
11469 	blk_pm_runtime_init(sdev->request_queue, dev);
11470 	pm_runtime_set_autosuspend_delay(dev, 0);
11471 	pm_runtime_allow(dev);
11472 
11473 	return  0;
11474 }
11475 
11476 static void ufshcd_wl_remove(struct scsi_device *sdev)
11477 {
11478 	struct device *dev = &sdev->sdev_gendev;
11479 
11480 	pm_runtime_forbid(dev);
11481 }
11482 
11483 static const struct dev_pm_ops ufshcd_wl_pm_ops = {
11484 #ifdef CONFIG_PM_SLEEP
11485 	.suspend = ufshcd_wl_suspend,
11486 	.resume = ufshcd_wl_resume,
11487 	.freeze = ufshcd_wl_suspend,
11488 	.thaw = ufshcd_wl_resume,
11489 	.poweroff = ufshcd_wl_poweroff,
11490 	.restore = ufshcd_wl_resume,
11491 #endif
11492 	SET_RUNTIME_PM_OPS(ufshcd_wl_runtime_suspend, ufshcd_wl_runtime_resume, NULL)
11493 };
11494 
11495 static void ufshcd_check_header_layout(void)
11496 {
11497 	/*
11498 	 * gcc compilers before version 10 cannot do constant-folding for
11499 	 * sub-byte bitfields. Hence skip the layout checks for gcc 9 and
11500 	 * before.
11501 	 */
11502 	if (IS_ENABLED(CONFIG_CC_IS_GCC) && CONFIG_GCC_VERSION < 100000)
11503 		return;
11504 
11505 	BUILD_BUG_ON(((u8 *)&(struct request_desc_header){
11506 				.cci = 3})[0] != 3);
11507 
11508 	BUILD_BUG_ON(((u8 *)&(struct request_desc_header){
11509 				.ehs_length = 2})[1] != 2);
11510 
11511 	BUILD_BUG_ON(((u8 *)&(struct request_desc_header){
11512 				.enable_crypto = 1})[2]
11513 		     != 0x80);
11514 
11515 	BUILD_BUG_ON((((u8 *)&(struct request_desc_header){
11516 					.command_type = 5,
11517 					.data_direction = 3,
11518 					.interrupt = 1,
11519 				})[3]) != ((5 << 4) | (3 << 1) | 1));
11520 
11521 	BUILD_BUG_ON(((__le32 *)&(struct request_desc_header){
11522 				.dunl = cpu_to_le32(0xdeadbeef)})[1] !=
11523 		cpu_to_le32(0xdeadbeef));
11524 
11525 	BUILD_BUG_ON(((u8 *)&(struct request_desc_header){
11526 				.ocs = 4})[8] != 4);
11527 
11528 	BUILD_BUG_ON(((u8 *)&(struct request_desc_header){
11529 				.cds = 5})[9] != 5);
11530 
11531 	BUILD_BUG_ON(((__le32 *)&(struct request_desc_header){
11532 				.dunu = cpu_to_le32(0xbadcafe)})[3] !=
11533 		cpu_to_le32(0xbadcafe));
11534 
11535 	BUILD_BUG_ON(((u8 *)&(struct utp_upiu_header){
11536 			     .iid = 0xf })[4] != 0xf0);
11537 
11538 	BUILD_BUG_ON(((u8 *)&(struct utp_upiu_header){
11539 			     .command_set_type = 0xf })[4] != 0xf);
11540 }
11541 
11542 /*
11543  * ufs_dev_wlun_template - describes ufs device wlun
11544  * ufs-device wlun - used to send pm commands
11545  * All luns are consumers of ufs-device wlun.
11546  *
11547  * Currently, no sd driver is present for wluns.
11548  * Hence the no specific pm operations are performed.
11549  * With ufs design, SSU should be sent to ufs-device wlun.
11550  * Hence register a scsi driver for ufs wluns only.
11551  */
11552 static struct scsi_driver ufs_dev_wlun_template = {
11553 	.probe = ufshcd_wl_probe,
11554 	.remove = ufshcd_wl_remove,
11555 	.shutdown = ufshcd_wl_shutdown,
11556 	.gendrv = {
11557 		.name = "ufs_device_wlun",
11558 		.pm = &ufshcd_wl_pm_ops,
11559 	},
11560 };
11561 
11562 static int __init ufshcd_core_init(void)
11563 {
11564 	int ret;
11565 
11566 	ufshcd_check_header_layout();
11567 
11568 	ufs_debugfs_init();
11569 
11570 	ret = scsi_register_driver(&ufs_dev_wlun_template);
11571 	if (ret)
11572 		ufs_debugfs_exit();
11573 	return ret;
11574 }
11575 
11576 static void __exit ufshcd_core_exit(void)
11577 {
11578 	ufs_debugfs_exit();
11579 	scsi_unregister_driver(&ufs_dev_wlun_template);
11580 }
11581 
11582 module_init(ufshcd_core_init);
11583 module_exit(ufshcd_core_exit);
11584 
11585 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
11586 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
11587 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
11588 MODULE_SOFTDEP("pre: governor_simpleondemand");
11589 MODULE_LICENSE("GPL");
11590