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