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