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