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