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