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