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