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