xref: /openbmc/linux/drivers/ufs/core/ufshcd.c (revision 2455f0e1)
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_force_error_recovery(struct ufs_hba *hba)
6060 {
6061 	spin_lock_irq(hba->host->host_lock);
6062 	hba->force_reset = true;
6063 	ufshcd_schedule_eh_work(hba);
6064 	spin_unlock_irq(hba->host->host_lock);
6065 }
6066 
6067 static void ufshcd_clk_scaling_allow(struct ufs_hba *hba, bool allow)
6068 {
6069 	down_write(&hba->clk_scaling_lock);
6070 	hba->clk_scaling.is_allowed = allow;
6071 	up_write(&hba->clk_scaling_lock);
6072 }
6073 
6074 static void ufshcd_clk_scaling_suspend(struct ufs_hba *hba, bool suspend)
6075 {
6076 	if (suspend) {
6077 		if (hba->clk_scaling.is_enabled)
6078 			ufshcd_suspend_clkscaling(hba);
6079 		ufshcd_clk_scaling_allow(hba, false);
6080 	} else {
6081 		ufshcd_clk_scaling_allow(hba, true);
6082 		if (hba->clk_scaling.is_enabled)
6083 			ufshcd_resume_clkscaling(hba);
6084 	}
6085 }
6086 
6087 static void ufshcd_err_handling_prepare(struct ufs_hba *hba)
6088 {
6089 	ufshcd_rpm_get_sync(hba);
6090 	if (pm_runtime_status_suspended(&hba->ufs_device_wlun->sdev_gendev) ||
6091 	    hba->is_sys_suspended) {
6092 		enum ufs_pm_op pm_op;
6093 
6094 		/*
6095 		 * Don't assume anything of resume, if
6096 		 * resume fails, irq and clocks can be OFF, and powers
6097 		 * can be OFF or in LPM.
6098 		 */
6099 		ufshcd_setup_hba_vreg(hba, true);
6100 		ufshcd_enable_irq(hba);
6101 		ufshcd_setup_vreg(hba, true);
6102 		ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
6103 		ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
6104 		ufshcd_hold(hba, false);
6105 		if (!ufshcd_is_clkgating_allowed(hba))
6106 			ufshcd_setup_clocks(hba, true);
6107 		ufshcd_release(hba);
6108 		pm_op = hba->is_sys_suspended ? UFS_SYSTEM_PM : UFS_RUNTIME_PM;
6109 		ufshcd_vops_resume(hba, pm_op);
6110 	} else {
6111 		ufshcd_hold(hba, false);
6112 		if (ufshcd_is_clkscaling_supported(hba) &&
6113 		    hba->clk_scaling.is_enabled)
6114 			ufshcd_suspend_clkscaling(hba);
6115 		ufshcd_clk_scaling_allow(hba, false);
6116 	}
6117 	ufshcd_scsi_block_requests(hba);
6118 	/* Drain ufshcd_queuecommand() */
6119 	synchronize_rcu();
6120 	cancel_work_sync(&hba->eeh_work);
6121 }
6122 
6123 static void ufshcd_err_handling_unprepare(struct ufs_hba *hba)
6124 {
6125 	ufshcd_scsi_unblock_requests(hba);
6126 	ufshcd_release(hba);
6127 	if (ufshcd_is_clkscaling_supported(hba))
6128 		ufshcd_clk_scaling_suspend(hba, false);
6129 	ufshcd_rpm_put(hba);
6130 }
6131 
6132 static inline bool ufshcd_err_handling_should_stop(struct ufs_hba *hba)
6133 {
6134 	return (!hba->is_powered || hba->shutting_down ||
6135 		!hba->ufs_device_wlun ||
6136 		hba->ufshcd_state == UFSHCD_STATE_ERROR ||
6137 		(!(hba->saved_err || hba->saved_uic_err || hba->force_reset ||
6138 		   ufshcd_is_link_broken(hba))));
6139 }
6140 
6141 #ifdef CONFIG_PM
6142 static void ufshcd_recover_pm_error(struct ufs_hba *hba)
6143 {
6144 	struct Scsi_Host *shost = hba->host;
6145 	struct scsi_device *sdev;
6146 	struct request_queue *q;
6147 	int ret;
6148 
6149 	hba->is_sys_suspended = false;
6150 	/*
6151 	 * Set RPM status of wlun device to RPM_ACTIVE,
6152 	 * this also clears its runtime error.
6153 	 */
6154 	ret = pm_runtime_set_active(&hba->ufs_device_wlun->sdev_gendev);
6155 
6156 	/* hba device might have a runtime error otherwise */
6157 	if (ret)
6158 		ret = pm_runtime_set_active(hba->dev);
6159 	/*
6160 	 * If wlun device had runtime error, we also need to resume those
6161 	 * consumer scsi devices in case any of them has failed to be
6162 	 * resumed due to supplier runtime resume failure. This is to unblock
6163 	 * blk_queue_enter in case there are bios waiting inside it.
6164 	 */
6165 	if (!ret) {
6166 		shost_for_each_device(sdev, shost) {
6167 			q = sdev->request_queue;
6168 			if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
6169 				       q->rpm_status == RPM_SUSPENDING))
6170 				pm_request_resume(q->dev);
6171 		}
6172 	}
6173 }
6174 #else
6175 static inline void ufshcd_recover_pm_error(struct ufs_hba *hba)
6176 {
6177 }
6178 #endif
6179 
6180 static bool ufshcd_is_pwr_mode_restore_needed(struct ufs_hba *hba)
6181 {
6182 	struct ufs_pa_layer_attr *pwr_info = &hba->pwr_info;
6183 	u32 mode;
6184 
6185 	ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode);
6186 
6187 	if (pwr_info->pwr_rx != ((mode >> PWRMODE_RX_OFFSET) & PWRMODE_MASK))
6188 		return true;
6189 
6190 	if (pwr_info->pwr_tx != (mode & PWRMODE_MASK))
6191 		return true;
6192 
6193 	return false;
6194 }
6195 
6196 static bool ufshcd_abort_all(struct ufs_hba *hba)
6197 {
6198 	bool needs_reset = false;
6199 	int tag, ret;
6200 
6201 	/* Clear pending transfer requests */
6202 	for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
6203 		ret = ufshcd_try_to_abort_task(hba, tag);
6204 		dev_err(hba->dev, "Aborting tag %d / CDB %#02x %s\n", tag,
6205 			hba->lrb[tag].cmd ? hba->lrb[tag].cmd->cmnd[0] : -1,
6206 			ret ? "failed" : "succeeded");
6207 		if (ret) {
6208 			needs_reset = true;
6209 			goto out;
6210 		}
6211 	}
6212 
6213 	/* Clear pending task management requests */
6214 	for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
6215 		if (ufshcd_clear_tm_cmd(hba, tag)) {
6216 			needs_reset = true;
6217 			goto out;
6218 		}
6219 	}
6220 
6221 out:
6222 	/* Complete the requests that are cleared by s/w */
6223 	ufshcd_complete_requests(hba);
6224 
6225 	return needs_reset;
6226 }
6227 
6228 /**
6229  * ufshcd_err_handler - handle UFS errors that require s/w attention
6230  * @work: pointer to work structure
6231  */
6232 static void ufshcd_err_handler(struct work_struct *work)
6233 {
6234 	int retries = MAX_ERR_HANDLER_RETRIES;
6235 	struct ufs_hba *hba;
6236 	unsigned long flags;
6237 	bool needs_restore;
6238 	bool needs_reset;
6239 	int pmc_err;
6240 
6241 	hba = container_of(work, struct ufs_hba, eh_work);
6242 
6243 	dev_info(hba->dev,
6244 		 "%s started; HBA state %s; powered %d; shutting down %d; saved_err = %d; saved_uic_err = %d; force_reset = %d%s\n",
6245 		 __func__, ufshcd_state_name[hba->ufshcd_state],
6246 		 hba->is_powered, hba->shutting_down, hba->saved_err,
6247 		 hba->saved_uic_err, hba->force_reset,
6248 		 ufshcd_is_link_broken(hba) ? "; link is broken" : "");
6249 
6250 	down(&hba->host_sem);
6251 	spin_lock_irqsave(hba->host->host_lock, flags);
6252 	if (ufshcd_err_handling_should_stop(hba)) {
6253 		if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6254 			hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6255 		spin_unlock_irqrestore(hba->host->host_lock, flags);
6256 		up(&hba->host_sem);
6257 		return;
6258 	}
6259 	ufshcd_set_eh_in_progress(hba);
6260 	spin_unlock_irqrestore(hba->host->host_lock, flags);
6261 	ufshcd_err_handling_prepare(hba);
6262 	/* Complete requests that have door-bell cleared by h/w */
6263 	ufshcd_complete_requests(hba);
6264 	spin_lock_irqsave(hba->host->host_lock, flags);
6265 again:
6266 	needs_restore = false;
6267 	needs_reset = false;
6268 
6269 	if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6270 		hba->ufshcd_state = UFSHCD_STATE_RESET;
6271 	/*
6272 	 * A full reset and restore might have happened after preparation
6273 	 * is finished, double check whether we should stop.
6274 	 */
6275 	if (ufshcd_err_handling_should_stop(hba))
6276 		goto skip_err_handling;
6277 
6278 	if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6279 		bool ret;
6280 
6281 		spin_unlock_irqrestore(hba->host->host_lock, flags);
6282 		/* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
6283 		ret = ufshcd_quirk_dl_nac_errors(hba);
6284 		spin_lock_irqsave(hba->host->host_lock, flags);
6285 		if (!ret && ufshcd_err_handling_should_stop(hba))
6286 			goto skip_err_handling;
6287 	}
6288 
6289 	if ((hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6290 	    (hba->saved_uic_err &&
6291 	     (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6292 		bool pr_prdt = !!(hba->saved_err & SYSTEM_BUS_FATAL_ERROR);
6293 
6294 		spin_unlock_irqrestore(hba->host->host_lock, flags);
6295 		ufshcd_print_host_state(hba);
6296 		ufshcd_print_pwr_info(hba);
6297 		ufshcd_print_evt_hist(hba);
6298 		ufshcd_print_tmrs(hba, hba->outstanding_tasks);
6299 		ufshcd_print_trs(hba, hba->outstanding_reqs, pr_prdt);
6300 		spin_lock_irqsave(hba->host->host_lock, flags);
6301 	}
6302 
6303 	/*
6304 	 * if host reset is required then skip clearing the pending
6305 	 * transfers forcefully because they will get cleared during
6306 	 * host reset and restore
6307 	 */
6308 	if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6309 	    ufshcd_is_saved_err_fatal(hba) ||
6310 	    ((hba->saved_err & UIC_ERROR) &&
6311 	     (hba->saved_uic_err & (UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
6312 				    UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))) {
6313 		needs_reset = true;
6314 		goto do_reset;
6315 	}
6316 
6317 	/*
6318 	 * If LINERESET was caught, UFS might have been put to PWM mode,
6319 	 * check if power mode restore is needed.
6320 	 */
6321 	if (hba->saved_uic_err & UFSHCD_UIC_PA_GENERIC_ERROR) {
6322 		hba->saved_uic_err &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6323 		if (!hba->saved_uic_err)
6324 			hba->saved_err &= ~UIC_ERROR;
6325 		spin_unlock_irqrestore(hba->host->host_lock, flags);
6326 		if (ufshcd_is_pwr_mode_restore_needed(hba))
6327 			needs_restore = true;
6328 		spin_lock_irqsave(hba->host->host_lock, flags);
6329 		if (!hba->saved_err && !needs_restore)
6330 			goto skip_err_handling;
6331 	}
6332 
6333 	hba->silence_err_logs = true;
6334 	/* release lock as clear command might sleep */
6335 	spin_unlock_irqrestore(hba->host->host_lock, flags);
6336 
6337 	needs_reset = ufshcd_abort_all(hba);
6338 
6339 	spin_lock_irqsave(hba->host->host_lock, flags);
6340 	hba->silence_err_logs = false;
6341 	if (needs_reset)
6342 		goto do_reset;
6343 
6344 	/*
6345 	 * After all reqs and tasks are cleared from doorbell,
6346 	 * now it is safe to retore power mode.
6347 	 */
6348 	if (needs_restore) {
6349 		spin_unlock_irqrestore(hba->host->host_lock, flags);
6350 		/*
6351 		 * Hold the scaling lock just in case dev cmds
6352 		 * are sent via bsg and/or sysfs.
6353 		 */
6354 		down_write(&hba->clk_scaling_lock);
6355 		hba->force_pmc = true;
6356 		pmc_err = ufshcd_config_pwr_mode(hba, &(hba->pwr_info));
6357 		if (pmc_err) {
6358 			needs_reset = true;
6359 			dev_err(hba->dev, "%s: Failed to restore power mode, err = %d\n",
6360 					__func__, pmc_err);
6361 		}
6362 		hba->force_pmc = false;
6363 		ufshcd_print_pwr_info(hba);
6364 		up_write(&hba->clk_scaling_lock);
6365 		spin_lock_irqsave(hba->host->host_lock, flags);
6366 	}
6367 
6368 do_reset:
6369 	/* Fatal errors need reset */
6370 	if (needs_reset) {
6371 		int err;
6372 
6373 		hba->force_reset = false;
6374 		spin_unlock_irqrestore(hba->host->host_lock, flags);
6375 		err = ufshcd_reset_and_restore(hba);
6376 		if (err)
6377 			dev_err(hba->dev, "%s: reset and restore failed with err %d\n",
6378 					__func__, err);
6379 		else
6380 			ufshcd_recover_pm_error(hba);
6381 		spin_lock_irqsave(hba->host->host_lock, flags);
6382 	}
6383 
6384 skip_err_handling:
6385 	if (!needs_reset) {
6386 		if (hba->ufshcd_state == UFSHCD_STATE_RESET)
6387 			hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6388 		if (hba->saved_err || hba->saved_uic_err)
6389 			dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
6390 			    __func__, hba->saved_err, hba->saved_uic_err);
6391 	}
6392 	/* Exit in an operational state or dead */
6393 	if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
6394 	    hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6395 		if (--retries)
6396 			goto again;
6397 		hba->ufshcd_state = UFSHCD_STATE_ERROR;
6398 	}
6399 	ufshcd_clear_eh_in_progress(hba);
6400 	spin_unlock_irqrestore(hba->host->host_lock, flags);
6401 	ufshcd_err_handling_unprepare(hba);
6402 	up(&hba->host_sem);
6403 
6404 	dev_info(hba->dev, "%s finished; HBA state %s\n", __func__,
6405 		 ufshcd_state_name[hba->ufshcd_state]);
6406 }
6407 
6408 /**
6409  * ufshcd_update_uic_error - check and set fatal UIC error flags.
6410  * @hba: per-adapter instance
6411  *
6412  * Returns
6413  *  IRQ_HANDLED - If interrupt is valid
6414  *  IRQ_NONE    - If invalid interrupt
6415  */
6416 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
6417 {
6418 	u32 reg;
6419 	irqreturn_t retval = IRQ_NONE;
6420 
6421 	/* PHY layer error */
6422 	reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
6423 	if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
6424 	    (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) {
6425 		ufshcd_update_evt_hist(hba, UFS_EVT_PA_ERR, reg);
6426 		/*
6427 		 * To know whether this error is fatal or not, DB timeout
6428 		 * must be checked but this error is handled separately.
6429 		 */
6430 		if (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)
6431 			dev_dbg(hba->dev, "%s: UIC Lane error reported\n",
6432 					__func__);
6433 
6434 		/* Got a LINERESET indication. */
6435 		if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) {
6436 			struct uic_command *cmd = NULL;
6437 
6438 			hba->uic_error |= UFSHCD_UIC_PA_GENERIC_ERROR;
6439 			if (hba->uic_async_done && hba->active_uic_cmd)
6440 				cmd = hba->active_uic_cmd;
6441 			/*
6442 			 * Ignore the LINERESET during power mode change
6443 			 * operation via DME_SET command.
6444 			 */
6445 			if (cmd && (cmd->command == UIC_CMD_DME_SET))
6446 				hba->uic_error &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6447 		}
6448 		retval |= IRQ_HANDLED;
6449 	}
6450 
6451 	/* PA_INIT_ERROR is fatal and needs UIC reset */
6452 	reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
6453 	if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
6454 	    (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
6455 		ufshcd_update_evt_hist(hba, UFS_EVT_DL_ERR, reg);
6456 
6457 		if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
6458 			hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
6459 		else if (hba->dev_quirks &
6460 				UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6461 			if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
6462 				hba->uic_error |=
6463 					UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6464 			else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
6465 				hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
6466 		}
6467 		retval |= IRQ_HANDLED;
6468 	}
6469 
6470 	/* UIC NL/TL/DME errors needs software retry */
6471 	reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
6472 	if ((reg & UIC_NETWORK_LAYER_ERROR) &&
6473 	    (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
6474 		ufshcd_update_evt_hist(hba, UFS_EVT_NL_ERR, reg);
6475 		hba->uic_error |= UFSHCD_UIC_NL_ERROR;
6476 		retval |= IRQ_HANDLED;
6477 	}
6478 
6479 	reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
6480 	if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
6481 	    (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
6482 		ufshcd_update_evt_hist(hba, UFS_EVT_TL_ERR, reg);
6483 		hba->uic_error |= UFSHCD_UIC_TL_ERROR;
6484 		retval |= IRQ_HANDLED;
6485 	}
6486 
6487 	reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
6488 	if ((reg & UIC_DME_ERROR) &&
6489 	    (reg & UIC_DME_ERROR_CODE_MASK)) {
6490 		ufshcd_update_evt_hist(hba, UFS_EVT_DME_ERR, reg);
6491 		hba->uic_error |= UFSHCD_UIC_DME_ERROR;
6492 		retval |= IRQ_HANDLED;
6493 	}
6494 
6495 	dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
6496 			__func__, hba->uic_error);
6497 	return retval;
6498 }
6499 
6500 /**
6501  * ufshcd_check_errors - Check for errors that need s/w attention
6502  * @hba: per-adapter instance
6503  * @intr_status: interrupt status generated by the controller
6504  *
6505  * Returns
6506  *  IRQ_HANDLED - If interrupt is valid
6507  *  IRQ_NONE    - If invalid interrupt
6508  */
6509 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba, u32 intr_status)
6510 {
6511 	bool queue_eh_work = false;
6512 	irqreturn_t retval = IRQ_NONE;
6513 
6514 	spin_lock(hba->host->host_lock);
6515 	hba->errors |= UFSHCD_ERROR_MASK & intr_status;
6516 
6517 	if (hba->errors & INT_FATAL_ERRORS) {
6518 		ufshcd_update_evt_hist(hba, UFS_EVT_FATAL_ERR,
6519 				       hba->errors);
6520 		queue_eh_work = true;
6521 	}
6522 
6523 	if (hba->errors & UIC_ERROR) {
6524 		hba->uic_error = 0;
6525 		retval = ufshcd_update_uic_error(hba);
6526 		if (hba->uic_error)
6527 			queue_eh_work = true;
6528 	}
6529 
6530 	if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
6531 		dev_err(hba->dev,
6532 			"%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
6533 			__func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
6534 			"Enter" : "Exit",
6535 			hba->errors, ufshcd_get_upmcrs(hba));
6536 		ufshcd_update_evt_hist(hba, UFS_EVT_AUTO_HIBERN8_ERR,
6537 				       hba->errors);
6538 		ufshcd_set_link_broken(hba);
6539 		queue_eh_work = true;
6540 	}
6541 
6542 	if (queue_eh_work) {
6543 		/*
6544 		 * update the transfer error masks to sticky bits, let's do this
6545 		 * irrespective of current ufshcd_state.
6546 		 */
6547 		hba->saved_err |= hba->errors;
6548 		hba->saved_uic_err |= hba->uic_error;
6549 
6550 		/* dump controller state before resetting */
6551 		if ((hba->saved_err &
6552 		     (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6553 		    (hba->saved_uic_err &&
6554 		     (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6555 			dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
6556 					__func__, hba->saved_err,
6557 					hba->saved_uic_err);
6558 			ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE,
6559 					 "host_regs: ");
6560 			ufshcd_print_pwr_info(hba);
6561 		}
6562 		ufshcd_schedule_eh_work(hba);
6563 		retval |= IRQ_HANDLED;
6564 	}
6565 	/*
6566 	 * if (!queue_eh_work) -
6567 	 * Other errors are either non-fatal where host recovers
6568 	 * itself without s/w intervention or errors that will be
6569 	 * handled by the SCSI core layer.
6570 	 */
6571 	hba->errors = 0;
6572 	hba->uic_error = 0;
6573 	spin_unlock(hba->host->host_lock);
6574 	return retval;
6575 }
6576 
6577 /**
6578  * ufshcd_tmc_handler - handle task management function completion
6579  * @hba: per adapter instance
6580  *
6581  * Returns
6582  *  IRQ_HANDLED - If interrupt is valid
6583  *  IRQ_NONE    - If invalid interrupt
6584  */
6585 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
6586 {
6587 	unsigned long flags, pending, issued;
6588 	irqreturn_t ret = IRQ_NONE;
6589 	int tag;
6590 
6591 	spin_lock_irqsave(hba->host->host_lock, flags);
6592 	pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
6593 	issued = hba->outstanding_tasks & ~pending;
6594 	for_each_set_bit(tag, &issued, hba->nutmrs) {
6595 		struct request *req = hba->tmf_rqs[tag];
6596 		struct completion *c = req->end_io_data;
6597 
6598 		complete(c);
6599 		ret = IRQ_HANDLED;
6600 	}
6601 	spin_unlock_irqrestore(hba->host->host_lock, flags);
6602 
6603 	return ret;
6604 }
6605 
6606 /**
6607  * ufshcd_sl_intr - Interrupt service routine
6608  * @hba: per adapter instance
6609  * @intr_status: contains interrupts generated by the controller
6610  *
6611  * Returns
6612  *  IRQ_HANDLED - If interrupt is valid
6613  *  IRQ_NONE    - If invalid interrupt
6614  */
6615 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
6616 {
6617 	irqreturn_t retval = IRQ_NONE;
6618 
6619 	if (intr_status & UFSHCD_UIC_MASK)
6620 		retval |= ufshcd_uic_cmd_compl(hba, intr_status);
6621 
6622 	if (intr_status & UFSHCD_ERROR_MASK || hba->errors)
6623 		retval |= ufshcd_check_errors(hba, intr_status);
6624 
6625 	if (intr_status & UTP_TASK_REQ_COMPL)
6626 		retval |= ufshcd_tmc_handler(hba);
6627 
6628 	if (intr_status & UTP_TRANSFER_REQ_COMPL)
6629 		retval |= ufshcd_transfer_req_compl(hba);
6630 
6631 	return retval;
6632 }
6633 
6634 /**
6635  * ufshcd_intr - Main interrupt service routine
6636  * @irq: irq number
6637  * @__hba: pointer to adapter instance
6638  *
6639  * Returns
6640  *  IRQ_HANDLED - If interrupt is valid
6641  *  IRQ_NONE    - If invalid interrupt
6642  */
6643 static irqreturn_t ufshcd_intr(int irq, void *__hba)
6644 {
6645 	u32 intr_status, enabled_intr_status = 0;
6646 	irqreturn_t retval = IRQ_NONE;
6647 	struct ufs_hba *hba = __hba;
6648 	int retries = hba->nutrs;
6649 
6650 	intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6651 	hba->ufs_stats.last_intr_status = intr_status;
6652 	hba->ufs_stats.last_intr_ts = local_clock();
6653 
6654 	/*
6655 	 * There could be max of hba->nutrs reqs in flight and in worst case
6656 	 * if the reqs get finished 1 by 1 after the interrupt status is
6657 	 * read, make sure we handle them by checking the interrupt status
6658 	 * again in a loop until we process all of the reqs before returning.
6659 	 */
6660 	while (intr_status && retries--) {
6661 		enabled_intr_status =
6662 			intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
6663 		ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
6664 		if (enabled_intr_status)
6665 			retval |= ufshcd_sl_intr(hba, enabled_intr_status);
6666 
6667 		intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6668 	}
6669 
6670 	if (enabled_intr_status && retval == IRQ_NONE &&
6671 	    (!(enabled_intr_status & UTP_TRANSFER_REQ_COMPL) ||
6672 	     hba->outstanding_reqs) && !ufshcd_eh_in_progress(hba)) {
6673 		dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x (0x%08x, 0x%08x)\n",
6674 					__func__,
6675 					intr_status,
6676 					hba->ufs_stats.last_intr_status,
6677 					enabled_intr_status);
6678 		ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
6679 	}
6680 
6681 	return retval;
6682 }
6683 
6684 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
6685 {
6686 	int err = 0;
6687 	u32 mask = 1 << tag;
6688 	unsigned long flags;
6689 
6690 	if (!test_bit(tag, &hba->outstanding_tasks))
6691 		goto out;
6692 
6693 	spin_lock_irqsave(hba->host->host_lock, flags);
6694 	ufshcd_utmrl_clear(hba, tag);
6695 	spin_unlock_irqrestore(hba->host->host_lock, flags);
6696 
6697 	/* poll for max. 1 sec to clear door bell register by h/w */
6698 	err = ufshcd_wait_for_register(hba,
6699 			REG_UTP_TASK_REQ_DOOR_BELL,
6700 			mask, 0, 1000, 1000);
6701 
6702 	dev_err(hba->dev, "Clearing task management function with tag %d %s\n",
6703 		tag, err ? "succeeded" : "failed");
6704 
6705 out:
6706 	return err;
6707 }
6708 
6709 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
6710 		struct utp_task_req_desc *treq, u8 tm_function)
6711 {
6712 	struct request_queue *q = hba->tmf_queue;
6713 	struct Scsi_Host *host = hba->host;
6714 	DECLARE_COMPLETION_ONSTACK(wait);
6715 	struct request *req;
6716 	unsigned long flags;
6717 	int task_tag, err;
6718 
6719 	/*
6720 	 * blk_mq_alloc_request() is used here only to get a free tag.
6721 	 */
6722 	req = blk_mq_alloc_request(q, REQ_OP_DRV_OUT, 0);
6723 	if (IS_ERR(req))
6724 		return PTR_ERR(req);
6725 
6726 	req->end_io_data = &wait;
6727 	ufshcd_hold(hba, false);
6728 
6729 	spin_lock_irqsave(host->host_lock, flags);
6730 
6731 	task_tag = req->tag;
6732 	WARN_ONCE(task_tag < 0 || task_tag >= hba->nutmrs, "Invalid tag %d\n",
6733 		  task_tag);
6734 	hba->tmf_rqs[req->tag] = req;
6735 	treq->upiu_req.req_header.dword_0 |= cpu_to_be32(task_tag);
6736 
6737 	memcpy(hba->utmrdl_base_addr + task_tag, treq, sizeof(*treq));
6738 	ufshcd_vops_setup_task_mgmt(hba, task_tag, tm_function);
6739 
6740 	/* send command to the controller */
6741 	__set_bit(task_tag, &hba->outstanding_tasks);
6742 
6743 	ufshcd_writel(hba, 1 << task_tag, REG_UTP_TASK_REQ_DOOR_BELL);
6744 	/* Make sure that doorbell is committed immediately */
6745 	wmb();
6746 
6747 	spin_unlock_irqrestore(host->host_lock, flags);
6748 
6749 	ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_SEND);
6750 
6751 	/* wait until the task management command is completed */
6752 	err = wait_for_completion_io_timeout(&wait,
6753 			msecs_to_jiffies(TM_CMD_TIMEOUT));
6754 	if (!err) {
6755 		ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_ERR);
6756 		dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
6757 				__func__, tm_function);
6758 		if (ufshcd_clear_tm_cmd(hba, task_tag))
6759 			dev_WARN(hba->dev, "%s: unable to clear tm cmd (slot %d) after timeout\n",
6760 					__func__, task_tag);
6761 		err = -ETIMEDOUT;
6762 	} else {
6763 		err = 0;
6764 		memcpy(treq, hba->utmrdl_base_addr + task_tag, sizeof(*treq));
6765 
6766 		ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_COMP);
6767 	}
6768 
6769 	spin_lock_irqsave(hba->host->host_lock, flags);
6770 	hba->tmf_rqs[req->tag] = NULL;
6771 	__clear_bit(task_tag, &hba->outstanding_tasks);
6772 	spin_unlock_irqrestore(hba->host->host_lock, flags);
6773 
6774 	ufshcd_release(hba);
6775 	blk_mq_free_request(req);
6776 
6777 	return err;
6778 }
6779 
6780 /**
6781  * ufshcd_issue_tm_cmd - issues task management commands to controller
6782  * @hba: per adapter instance
6783  * @lun_id: LUN ID to which TM command is sent
6784  * @task_id: task ID to which the TM command is applicable
6785  * @tm_function: task management function opcode
6786  * @tm_response: task management service response return value
6787  *
6788  * Returns non-zero value on error, zero on success.
6789  */
6790 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
6791 		u8 tm_function, u8 *tm_response)
6792 {
6793 	struct utp_task_req_desc treq = { { 0 }, };
6794 	enum utp_ocs ocs_value;
6795 	int err;
6796 
6797 	/* Configure task request descriptor */
6798 	treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6799 	treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6800 
6801 	/* Configure task request UPIU */
6802 	treq.upiu_req.req_header.dword_0 = cpu_to_be32(lun_id << 8) |
6803 				  cpu_to_be32(UPIU_TRANSACTION_TASK_REQ << 24);
6804 	treq.upiu_req.req_header.dword_1 = cpu_to_be32(tm_function << 16);
6805 
6806 	/*
6807 	 * The host shall provide the same value for LUN field in the basic
6808 	 * header and for Input Parameter.
6809 	 */
6810 	treq.upiu_req.input_param1 = cpu_to_be32(lun_id);
6811 	treq.upiu_req.input_param2 = cpu_to_be32(task_id);
6812 
6813 	err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
6814 	if (err == -ETIMEDOUT)
6815 		return err;
6816 
6817 	ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6818 	if (ocs_value != OCS_SUCCESS)
6819 		dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
6820 				__func__, ocs_value);
6821 	else if (tm_response)
6822 		*tm_response = be32_to_cpu(treq.upiu_rsp.output_param1) &
6823 				MASK_TM_SERVICE_RESP;
6824 	return err;
6825 }
6826 
6827 /**
6828  * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
6829  * @hba:	per-adapter instance
6830  * @req_upiu:	upiu request
6831  * @rsp_upiu:	upiu reply
6832  * @desc_buff:	pointer to descriptor buffer, NULL if NA
6833  * @buff_len:	descriptor size, 0 if NA
6834  * @cmd_type:	specifies the type (NOP, Query...)
6835  * @desc_op:	descriptor operation
6836  *
6837  * Those type of requests uses UTP Transfer Request Descriptor - utrd.
6838  * Therefore, it "rides" the device management infrastructure: uses its tag and
6839  * tasks work queues.
6840  *
6841  * Since there is only one available tag for device management commands,
6842  * the caller is expected to hold the hba->dev_cmd.lock mutex.
6843  */
6844 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
6845 					struct utp_upiu_req *req_upiu,
6846 					struct utp_upiu_req *rsp_upiu,
6847 					u8 *desc_buff, int *buff_len,
6848 					enum dev_cmd_type cmd_type,
6849 					enum query_opcode desc_op)
6850 {
6851 	DECLARE_COMPLETION_ONSTACK(wait);
6852 	const u32 tag = hba->reserved_slot;
6853 	struct ufshcd_lrb *lrbp;
6854 	int err = 0;
6855 	u8 upiu_flags;
6856 
6857 	/* Protects use of hba->reserved_slot. */
6858 	lockdep_assert_held(&hba->dev_cmd.lock);
6859 
6860 	down_read(&hba->clk_scaling_lock);
6861 
6862 	lrbp = &hba->lrb[tag];
6863 	WARN_ON(lrbp->cmd);
6864 	lrbp->cmd = NULL;
6865 	lrbp->task_tag = tag;
6866 	lrbp->lun = 0;
6867 	lrbp->intr_cmd = true;
6868 	ufshcd_prepare_lrbp_crypto(NULL, lrbp);
6869 	hba->dev_cmd.type = cmd_type;
6870 
6871 	if (hba->ufs_version <= ufshci_version(1, 1))
6872 		lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
6873 	else
6874 		lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
6875 
6876 	/* update the task tag in the request upiu */
6877 	req_upiu->header.dword_0 |= cpu_to_be32(tag);
6878 
6879 	ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
6880 
6881 	/* just copy the upiu request as it is */
6882 	memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
6883 	if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
6884 		/* The Data Segment Area is optional depending upon the query
6885 		 * function value. for WRITE DESCRIPTOR, the data segment
6886 		 * follows right after the tsf.
6887 		 */
6888 		memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
6889 		*buff_len = 0;
6890 	}
6891 
6892 	memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
6893 
6894 	hba->dev_cmd.complete = &wait;
6895 
6896 	ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
6897 
6898 	ufshcd_send_command(hba, tag);
6899 	/*
6900 	 * ignore the returning value here - ufshcd_check_query_response is
6901 	 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
6902 	 * read the response directly ignoring all errors.
6903 	 */
6904 	ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
6905 
6906 	/* just copy the upiu response as it is */
6907 	memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
6908 	if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
6909 		u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
6910 		u16 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
6911 			       MASK_QUERY_DATA_SEG_LEN;
6912 
6913 		if (*buff_len >= resp_len) {
6914 			memcpy(desc_buff, descp, resp_len);
6915 			*buff_len = resp_len;
6916 		} else {
6917 			dev_warn(hba->dev,
6918 				 "%s: rsp size %d is bigger than buffer size %d",
6919 				 __func__, resp_len, *buff_len);
6920 			*buff_len = 0;
6921 			err = -EINVAL;
6922 		}
6923 	}
6924 	ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
6925 				    (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
6926 
6927 	up_read(&hba->clk_scaling_lock);
6928 	return err;
6929 }
6930 
6931 /**
6932  * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
6933  * @hba:	per-adapter instance
6934  * @req_upiu:	upiu request
6935  * @rsp_upiu:	upiu reply - only 8 DW as we do not support scsi commands
6936  * @msgcode:	message code, one of UPIU Transaction Codes Initiator to Target
6937  * @desc_buff:	pointer to descriptor buffer, NULL if NA
6938  * @buff_len:	descriptor size, 0 if NA
6939  * @desc_op:	descriptor operation
6940  *
6941  * Supports UTP Transfer requests (nop and query), and UTP Task
6942  * Management requests.
6943  * It is up to the caller to fill the upiu conent properly, as it will
6944  * be copied without any further input validations.
6945  */
6946 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
6947 			     struct utp_upiu_req *req_upiu,
6948 			     struct utp_upiu_req *rsp_upiu,
6949 			     int msgcode,
6950 			     u8 *desc_buff, int *buff_len,
6951 			     enum query_opcode desc_op)
6952 {
6953 	int err;
6954 	enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
6955 	struct utp_task_req_desc treq = { { 0 }, };
6956 	enum utp_ocs ocs_value;
6957 	u8 tm_f = be32_to_cpu(req_upiu->header.dword_1) >> 16 & MASK_TM_FUNC;
6958 
6959 	switch (msgcode) {
6960 	case UPIU_TRANSACTION_NOP_OUT:
6961 		cmd_type = DEV_CMD_TYPE_NOP;
6962 		fallthrough;
6963 	case UPIU_TRANSACTION_QUERY_REQ:
6964 		ufshcd_hold(hba, false);
6965 		mutex_lock(&hba->dev_cmd.lock);
6966 		err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
6967 						   desc_buff, buff_len,
6968 						   cmd_type, desc_op);
6969 		mutex_unlock(&hba->dev_cmd.lock);
6970 		ufshcd_release(hba);
6971 
6972 		break;
6973 	case UPIU_TRANSACTION_TASK_REQ:
6974 		treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6975 		treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6976 
6977 		memcpy(&treq.upiu_req, req_upiu, sizeof(*req_upiu));
6978 
6979 		err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
6980 		if (err == -ETIMEDOUT)
6981 			break;
6982 
6983 		ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6984 		if (ocs_value != OCS_SUCCESS) {
6985 			dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
6986 				ocs_value);
6987 			break;
6988 		}
6989 
6990 		memcpy(rsp_upiu, &treq.upiu_rsp, sizeof(*rsp_upiu));
6991 
6992 		break;
6993 	default:
6994 		err = -EINVAL;
6995 
6996 		break;
6997 	}
6998 
6999 	return err;
7000 }
7001 
7002 /**
7003  * ufshcd_eh_device_reset_handler() - Reset a single logical unit.
7004  * @cmd: SCSI command pointer
7005  *
7006  * Returns SUCCESS/FAILED
7007  */
7008 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
7009 {
7010 	unsigned long flags, pending_reqs = 0, not_cleared = 0;
7011 	struct Scsi_Host *host;
7012 	struct ufs_hba *hba;
7013 	u32 pos;
7014 	int err;
7015 	u8 resp = 0xF, lun;
7016 
7017 	host = cmd->device->host;
7018 	hba = shost_priv(host);
7019 
7020 	lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
7021 	err = ufshcd_issue_tm_cmd(hba, lun, 0, UFS_LOGICAL_RESET, &resp);
7022 	if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7023 		if (!err)
7024 			err = resp;
7025 		goto out;
7026 	}
7027 
7028 	/* clear the commands that were pending for corresponding LUN */
7029 	spin_lock_irqsave(&hba->outstanding_lock, flags);
7030 	for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs)
7031 		if (hba->lrb[pos].lun == lun)
7032 			__set_bit(pos, &pending_reqs);
7033 	hba->outstanding_reqs &= ~pending_reqs;
7034 	spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7035 
7036 	if (ufshcd_clear_cmds(hba, pending_reqs) < 0) {
7037 		spin_lock_irqsave(&hba->outstanding_lock, flags);
7038 		not_cleared = pending_reqs &
7039 			ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7040 		hba->outstanding_reqs |= not_cleared;
7041 		spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7042 
7043 		dev_err(hba->dev, "%s: failed to clear requests %#lx\n",
7044 			__func__, not_cleared);
7045 	}
7046 	__ufshcd_transfer_req_compl(hba, pending_reqs & ~not_cleared);
7047 
7048 out:
7049 	hba->req_abort_count = 0;
7050 	ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, (u32)err);
7051 	if (!err) {
7052 		err = SUCCESS;
7053 	} else {
7054 		dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7055 		err = FAILED;
7056 	}
7057 	return err;
7058 }
7059 
7060 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
7061 {
7062 	struct ufshcd_lrb *lrbp;
7063 	int tag;
7064 
7065 	for_each_set_bit(tag, &bitmap, hba->nutrs) {
7066 		lrbp = &hba->lrb[tag];
7067 		lrbp->req_abort_skip = true;
7068 	}
7069 }
7070 
7071 /**
7072  * ufshcd_try_to_abort_task - abort a specific task
7073  * @hba: Pointer to adapter instance
7074  * @tag: Task tag/index to be aborted
7075  *
7076  * Abort the pending command in device by sending UFS_ABORT_TASK task management
7077  * command, and in host controller by clearing the door-bell register. There can
7078  * be race between controller sending the command to the device while abort is
7079  * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
7080  * really issued and then try to abort it.
7081  *
7082  * Returns zero on success, non-zero on failure
7083  */
7084 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag)
7085 {
7086 	struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7087 	int err = 0;
7088 	int poll_cnt;
7089 	u8 resp = 0xF;
7090 	u32 reg;
7091 
7092 	for (poll_cnt = 100; poll_cnt; poll_cnt--) {
7093 		err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7094 				UFS_QUERY_TASK, &resp);
7095 		if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
7096 			/* cmd pending in the device */
7097 			dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
7098 				__func__, tag);
7099 			break;
7100 		} else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7101 			/*
7102 			 * cmd not pending in the device, check if it is
7103 			 * in transition.
7104 			 */
7105 			dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
7106 				__func__, tag);
7107 			reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7108 			if (reg & (1 << tag)) {
7109 				/* sleep for max. 200us to stabilize */
7110 				usleep_range(100, 200);
7111 				continue;
7112 			}
7113 			/* command completed already */
7114 			dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
7115 				__func__, tag);
7116 			goto out;
7117 		} else {
7118 			dev_err(hba->dev,
7119 				"%s: no response from device. tag = %d, err %d\n",
7120 				__func__, tag, err);
7121 			if (!err)
7122 				err = resp; /* service response error */
7123 			goto out;
7124 		}
7125 	}
7126 
7127 	if (!poll_cnt) {
7128 		err = -EBUSY;
7129 		goto out;
7130 	}
7131 
7132 	err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7133 			UFS_ABORT_TASK, &resp);
7134 	if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7135 		if (!err) {
7136 			err = resp; /* service response error */
7137 			dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
7138 				__func__, tag, err);
7139 		}
7140 		goto out;
7141 	}
7142 
7143 	err = ufshcd_clear_cmds(hba, 1U << tag);
7144 	if (err)
7145 		dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
7146 			__func__, tag, err);
7147 
7148 out:
7149 	return err;
7150 }
7151 
7152 /**
7153  * ufshcd_abort - scsi host template eh_abort_handler callback
7154  * @cmd: SCSI command pointer
7155  *
7156  * Returns SUCCESS/FAILED
7157  */
7158 static int ufshcd_abort(struct scsi_cmnd *cmd)
7159 {
7160 	struct Scsi_Host *host = cmd->device->host;
7161 	struct ufs_hba *hba = shost_priv(host);
7162 	int tag = scsi_cmd_to_rq(cmd)->tag;
7163 	struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7164 	unsigned long flags;
7165 	int err = FAILED;
7166 	bool outstanding;
7167 	u32 reg;
7168 
7169 	WARN_ONCE(tag < 0, "Invalid tag %d\n", tag);
7170 
7171 	ufshcd_hold(hba, false);
7172 	reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7173 	/* If command is already aborted/completed, return FAILED. */
7174 	if (!(test_bit(tag, &hba->outstanding_reqs))) {
7175 		dev_err(hba->dev,
7176 			"%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
7177 			__func__, tag, hba->outstanding_reqs, reg);
7178 		goto release;
7179 	}
7180 
7181 	/* Print Transfer Request of aborted task */
7182 	dev_info(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
7183 
7184 	/*
7185 	 * Print detailed info about aborted request.
7186 	 * As more than one request might get aborted at the same time,
7187 	 * print full information only for the first aborted request in order
7188 	 * to reduce repeated printouts. For other aborted requests only print
7189 	 * basic details.
7190 	 */
7191 	scsi_print_command(cmd);
7192 	if (!hba->req_abort_count) {
7193 		ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, tag);
7194 		ufshcd_print_evt_hist(hba);
7195 		ufshcd_print_host_state(hba);
7196 		ufshcd_print_pwr_info(hba);
7197 		ufshcd_print_trs(hba, 1 << tag, true);
7198 	} else {
7199 		ufshcd_print_trs(hba, 1 << tag, false);
7200 	}
7201 	hba->req_abort_count++;
7202 
7203 	if (!(reg & (1 << tag))) {
7204 		dev_err(hba->dev,
7205 		"%s: cmd was completed, but without a notifying intr, tag = %d",
7206 		__func__, tag);
7207 		__ufshcd_transfer_req_compl(hba, 1UL << tag);
7208 		goto release;
7209 	}
7210 
7211 	/*
7212 	 * Task abort to the device W-LUN is illegal. When this command
7213 	 * will fail, due to spec violation, scsi err handling next step
7214 	 * will be to send LU reset which, again, is a spec violation.
7215 	 * To avoid these unnecessary/illegal steps, first we clean up
7216 	 * the lrb taken by this cmd and re-set it in outstanding_reqs,
7217 	 * then queue the eh_work and bail.
7218 	 */
7219 	if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN) {
7220 		ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, lrbp->lun);
7221 
7222 		spin_lock_irqsave(host->host_lock, flags);
7223 		hba->force_reset = true;
7224 		ufshcd_schedule_eh_work(hba);
7225 		spin_unlock_irqrestore(host->host_lock, flags);
7226 		goto release;
7227 	}
7228 
7229 	/* Skip task abort in case previous aborts failed and report failure */
7230 	if (lrbp->req_abort_skip) {
7231 		dev_err(hba->dev, "%s: skipping abort\n", __func__);
7232 		ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7233 		goto release;
7234 	}
7235 
7236 	err = ufshcd_try_to_abort_task(hba, tag);
7237 	if (err) {
7238 		dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7239 		ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7240 		err = FAILED;
7241 		goto release;
7242 	}
7243 
7244 	/*
7245 	 * Clear the corresponding bit from outstanding_reqs since the command
7246 	 * has been aborted successfully.
7247 	 */
7248 	spin_lock_irqsave(&hba->outstanding_lock, flags);
7249 	outstanding = __test_and_clear_bit(tag, &hba->outstanding_reqs);
7250 	spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7251 
7252 	if (outstanding)
7253 		ufshcd_release_scsi_cmd(hba, lrbp);
7254 
7255 	err = SUCCESS;
7256 
7257 release:
7258 	/* Matches the ufshcd_hold() call at the start of this function. */
7259 	ufshcd_release(hba);
7260 	return err;
7261 }
7262 
7263 /**
7264  * ufshcd_host_reset_and_restore - reset and restore host controller
7265  * @hba: per-adapter instance
7266  *
7267  * Note that host controller reset may issue DME_RESET to
7268  * local and remote (device) Uni-Pro stack and the attributes
7269  * are reset to default state.
7270  *
7271  * Returns zero on success, non-zero on failure
7272  */
7273 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
7274 {
7275 	int err;
7276 
7277 	/*
7278 	 * Stop the host controller and complete the requests
7279 	 * cleared by h/w
7280 	 */
7281 	ufshpb_toggle_state(hba, HPB_PRESENT, HPB_RESET);
7282 	ufshcd_hba_stop(hba);
7283 	hba->silence_err_logs = true;
7284 	ufshcd_complete_requests(hba);
7285 	hba->silence_err_logs = false;
7286 
7287 	/* scale up clocks to max frequency before full reinitialization */
7288 	ufshcd_scale_clks(hba, true);
7289 
7290 	err = ufshcd_hba_enable(hba);
7291 
7292 	/* Establish the link again and restore the device */
7293 	if (!err)
7294 		err = ufshcd_probe_hba(hba, false);
7295 
7296 	if (err)
7297 		dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
7298 	ufshcd_update_evt_hist(hba, UFS_EVT_HOST_RESET, (u32)err);
7299 	return err;
7300 }
7301 
7302 /**
7303  * ufshcd_reset_and_restore - reset and re-initialize host/device
7304  * @hba: per-adapter instance
7305  *
7306  * Reset and recover device, host and re-establish link. This
7307  * is helpful to recover the communication in fatal error conditions.
7308  *
7309  * Returns zero on success, non-zero on failure
7310  */
7311 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
7312 {
7313 	u32 saved_err = 0;
7314 	u32 saved_uic_err = 0;
7315 	int err = 0;
7316 	unsigned long flags;
7317 	int retries = MAX_HOST_RESET_RETRIES;
7318 
7319 	spin_lock_irqsave(hba->host->host_lock, flags);
7320 	do {
7321 		/*
7322 		 * This is a fresh start, cache and clear saved error first,
7323 		 * in case new error generated during reset and restore.
7324 		 */
7325 		saved_err |= hba->saved_err;
7326 		saved_uic_err |= hba->saved_uic_err;
7327 		hba->saved_err = 0;
7328 		hba->saved_uic_err = 0;
7329 		hba->force_reset = false;
7330 		hba->ufshcd_state = UFSHCD_STATE_RESET;
7331 		spin_unlock_irqrestore(hba->host->host_lock, flags);
7332 
7333 		/* Reset the attached device */
7334 		ufshcd_device_reset(hba);
7335 
7336 		err = ufshcd_host_reset_and_restore(hba);
7337 
7338 		spin_lock_irqsave(hba->host->host_lock, flags);
7339 		if (err)
7340 			continue;
7341 		/* Do not exit unless operational or dead */
7342 		if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
7343 		    hba->ufshcd_state != UFSHCD_STATE_ERROR &&
7344 		    hba->ufshcd_state != UFSHCD_STATE_EH_SCHEDULED_NON_FATAL)
7345 			err = -EAGAIN;
7346 	} while (err && --retries);
7347 
7348 	/*
7349 	 * Inform scsi mid-layer that we did reset and allow to handle
7350 	 * Unit Attention properly.
7351 	 */
7352 	scsi_report_bus_reset(hba->host, 0);
7353 	if (err) {
7354 		hba->ufshcd_state = UFSHCD_STATE_ERROR;
7355 		hba->saved_err |= saved_err;
7356 		hba->saved_uic_err |= saved_uic_err;
7357 	}
7358 	spin_unlock_irqrestore(hba->host->host_lock, flags);
7359 
7360 	return err;
7361 }
7362 
7363 /**
7364  * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
7365  * @cmd: SCSI command pointer
7366  *
7367  * Returns SUCCESS/FAILED
7368  */
7369 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
7370 {
7371 	int err = SUCCESS;
7372 	unsigned long flags;
7373 	struct ufs_hba *hba;
7374 
7375 	hba = shost_priv(cmd->device->host);
7376 
7377 	spin_lock_irqsave(hba->host->host_lock, flags);
7378 	hba->force_reset = true;
7379 	ufshcd_schedule_eh_work(hba);
7380 	dev_err(hba->dev, "%s: reset in progress - 1\n", __func__);
7381 	spin_unlock_irqrestore(hba->host->host_lock, flags);
7382 
7383 	flush_work(&hba->eh_work);
7384 
7385 	spin_lock_irqsave(hba->host->host_lock, flags);
7386 	if (hba->ufshcd_state == UFSHCD_STATE_ERROR)
7387 		err = FAILED;
7388 	spin_unlock_irqrestore(hba->host->host_lock, flags);
7389 
7390 	return err;
7391 }
7392 
7393 /**
7394  * ufshcd_get_max_icc_level - calculate the ICC level
7395  * @sup_curr_uA: max. current supported by the regulator
7396  * @start_scan: row at the desc table to start scan from
7397  * @buff: power descriptor buffer
7398  *
7399  * Returns calculated max ICC level for specific regulator
7400  */
7401 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan,
7402 				    const char *buff)
7403 {
7404 	int i;
7405 	int curr_uA;
7406 	u16 data;
7407 	u16 unit;
7408 
7409 	for (i = start_scan; i >= 0; i--) {
7410 		data = get_unaligned_be16(&buff[2 * i]);
7411 		unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
7412 						ATTR_ICC_LVL_UNIT_OFFSET;
7413 		curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
7414 		switch (unit) {
7415 		case UFSHCD_NANO_AMP:
7416 			curr_uA = curr_uA / 1000;
7417 			break;
7418 		case UFSHCD_MILI_AMP:
7419 			curr_uA = curr_uA * 1000;
7420 			break;
7421 		case UFSHCD_AMP:
7422 			curr_uA = curr_uA * 1000 * 1000;
7423 			break;
7424 		case UFSHCD_MICRO_AMP:
7425 		default:
7426 			break;
7427 		}
7428 		if (sup_curr_uA >= curr_uA)
7429 			break;
7430 	}
7431 	if (i < 0) {
7432 		i = 0;
7433 		pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
7434 	}
7435 
7436 	return (u32)i;
7437 }
7438 
7439 /**
7440  * ufshcd_find_max_sup_active_icc_level - calculate the max ICC level
7441  * In case regulators are not initialized we'll return 0
7442  * @hba: per-adapter instance
7443  * @desc_buf: power descriptor buffer to extract ICC levels from.
7444  * @len: length of desc_buff
7445  *
7446  * Returns calculated ICC level
7447  */
7448 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
7449 						const u8 *desc_buf, int len)
7450 {
7451 	u32 icc_level = 0;
7452 
7453 	if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
7454 						!hba->vreg_info.vccq2) {
7455 		/*
7456 		 * Using dev_dbg to avoid messages during runtime PM to avoid
7457 		 * never-ending cycles of messages written back to storage by
7458 		 * user space causing runtime resume, causing more messages and
7459 		 * so on.
7460 		 */
7461 		dev_dbg(hba->dev,
7462 			"%s: Regulator capability was not set, actvIccLevel=%d",
7463 							__func__, icc_level);
7464 		goto out;
7465 	}
7466 
7467 	if (hba->vreg_info.vcc->max_uA)
7468 		icc_level = ufshcd_get_max_icc_level(
7469 				hba->vreg_info.vcc->max_uA,
7470 				POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
7471 				&desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
7472 
7473 	if (hba->vreg_info.vccq->max_uA)
7474 		icc_level = ufshcd_get_max_icc_level(
7475 				hba->vreg_info.vccq->max_uA,
7476 				icc_level,
7477 				&desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
7478 
7479 	if (hba->vreg_info.vccq2->max_uA)
7480 		icc_level = ufshcd_get_max_icc_level(
7481 				hba->vreg_info.vccq2->max_uA,
7482 				icc_level,
7483 				&desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
7484 out:
7485 	return icc_level;
7486 }
7487 
7488 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba)
7489 {
7490 	int ret;
7491 	int buff_len = hba->desc_size[QUERY_DESC_IDN_POWER];
7492 	u8 *desc_buf;
7493 	u32 icc_level;
7494 
7495 	desc_buf = kmalloc(buff_len, GFP_KERNEL);
7496 	if (!desc_buf)
7497 		return;
7498 
7499 	ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0,
7500 				     desc_buf, buff_len);
7501 	if (ret) {
7502 		dev_err(hba->dev,
7503 			"%s: Failed reading power descriptor.len = %d ret = %d",
7504 			__func__, buff_len, ret);
7505 		goto out;
7506 	}
7507 
7508 	icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf,
7509 							 buff_len);
7510 	dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level);
7511 
7512 	ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7513 		QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level);
7514 
7515 	if (ret)
7516 		dev_err(hba->dev,
7517 			"%s: Failed configuring bActiveICCLevel = %d ret = %d",
7518 			__func__, icc_level, ret);
7519 
7520 out:
7521 	kfree(desc_buf);
7522 }
7523 
7524 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev)
7525 {
7526 	scsi_autopm_get_device(sdev);
7527 	blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev);
7528 	if (sdev->rpm_autosuspend)
7529 		pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev,
7530 						 RPM_AUTOSUSPEND_DELAY_MS);
7531 	scsi_autopm_put_device(sdev);
7532 }
7533 
7534 /**
7535  * ufshcd_scsi_add_wlus - Adds required W-LUs
7536  * @hba: per-adapter instance
7537  *
7538  * UFS device specification requires the UFS devices to support 4 well known
7539  * logical units:
7540  *	"REPORT_LUNS" (address: 01h)
7541  *	"UFS Device" (address: 50h)
7542  *	"RPMB" (address: 44h)
7543  *	"BOOT" (address: 30h)
7544  * UFS device's power management needs to be controlled by "POWER CONDITION"
7545  * field of SSU (START STOP UNIT) command. But this "power condition" field
7546  * will take effect only when its sent to "UFS device" well known logical unit
7547  * hence we require the scsi_device instance to represent this logical unit in
7548  * order for the UFS host driver to send the SSU command for power management.
7549  *
7550  * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
7551  * Block) LU so user space process can control this LU. User space may also
7552  * want to have access to BOOT LU.
7553  *
7554  * This function adds scsi device instances for each of all well known LUs
7555  * (except "REPORT LUNS" LU).
7556  *
7557  * Returns zero on success (all required W-LUs are added successfully),
7558  * non-zero error value on failure (if failed to add any of the required W-LU).
7559  */
7560 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
7561 {
7562 	int ret = 0;
7563 	struct scsi_device *sdev_boot, *sdev_rpmb;
7564 
7565 	hba->ufs_device_wlun = __scsi_add_device(hba->host, 0, 0,
7566 		ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
7567 	if (IS_ERR(hba->ufs_device_wlun)) {
7568 		ret = PTR_ERR(hba->ufs_device_wlun);
7569 		hba->ufs_device_wlun = NULL;
7570 		goto out;
7571 	}
7572 	scsi_device_put(hba->ufs_device_wlun);
7573 
7574 	sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
7575 		ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
7576 	if (IS_ERR(sdev_rpmb)) {
7577 		ret = PTR_ERR(sdev_rpmb);
7578 		goto remove_ufs_device_wlun;
7579 	}
7580 	ufshcd_blk_pm_runtime_init(sdev_rpmb);
7581 	scsi_device_put(sdev_rpmb);
7582 
7583 	sdev_boot = __scsi_add_device(hba->host, 0, 0,
7584 		ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
7585 	if (IS_ERR(sdev_boot)) {
7586 		dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
7587 	} else {
7588 		ufshcd_blk_pm_runtime_init(sdev_boot);
7589 		scsi_device_put(sdev_boot);
7590 	}
7591 	goto out;
7592 
7593 remove_ufs_device_wlun:
7594 	scsi_remove_device(hba->ufs_device_wlun);
7595 out:
7596 	return ret;
7597 }
7598 
7599 static void ufshcd_wb_probe(struct ufs_hba *hba, const u8 *desc_buf)
7600 {
7601 	struct ufs_dev_info *dev_info = &hba->dev_info;
7602 	u8 lun;
7603 	u32 d_lu_wb_buf_alloc;
7604 	u32 ext_ufs_feature;
7605 
7606 	if (!ufshcd_is_wb_allowed(hba))
7607 		return;
7608 
7609 	/*
7610 	 * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or
7611 	 * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES
7612 	 * enabled
7613 	 */
7614 	if (!(dev_info->wspecversion >= 0x310 ||
7615 	      dev_info->wspecversion == 0x220 ||
7616 	     (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES)))
7617 		goto wb_disabled;
7618 
7619 	if (hba->desc_size[QUERY_DESC_IDN_DEVICE] <
7620 	    DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP + 4)
7621 		goto wb_disabled;
7622 
7623 	ext_ufs_feature = get_unaligned_be32(desc_buf +
7624 					DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7625 
7626 	if (!(ext_ufs_feature & UFS_DEV_WRITE_BOOSTER_SUP))
7627 		goto wb_disabled;
7628 
7629 	/*
7630 	 * WB may be supported but not configured while provisioning. The spec
7631 	 * says, in dedicated wb buffer mode, a max of 1 lun would have wb
7632 	 * buffer configured.
7633 	 */
7634 	dev_info->wb_buffer_type = desc_buf[DEVICE_DESC_PARAM_WB_TYPE];
7635 
7636 	dev_info->b_presrv_uspc_en =
7637 		desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN];
7638 
7639 	if (dev_info->wb_buffer_type == WB_BUF_MODE_SHARED) {
7640 		if (!get_unaligned_be32(desc_buf +
7641 				   DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS))
7642 			goto wb_disabled;
7643 	} else {
7644 		for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) {
7645 			d_lu_wb_buf_alloc = 0;
7646 			ufshcd_read_unit_desc_param(hba,
7647 					lun,
7648 					UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS,
7649 					(u8 *)&d_lu_wb_buf_alloc,
7650 					sizeof(d_lu_wb_buf_alloc));
7651 			if (d_lu_wb_buf_alloc) {
7652 				dev_info->wb_dedicated_lu = lun;
7653 				break;
7654 			}
7655 		}
7656 
7657 		if (!d_lu_wb_buf_alloc)
7658 			goto wb_disabled;
7659 	}
7660 
7661 	if (!ufshcd_is_wb_buf_lifetime_available(hba))
7662 		goto wb_disabled;
7663 
7664 	return;
7665 
7666 wb_disabled:
7667 	hba->caps &= ~UFSHCD_CAP_WB_EN;
7668 }
7669 
7670 static void ufshcd_temp_notif_probe(struct ufs_hba *hba, const u8 *desc_buf)
7671 {
7672 	struct ufs_dev_info *dev_info = &hba->dev_info;
7673 	u32 ext_ufs_feature;
7674 	u8 mask = 0;
7675 
7676 	if (!(hba->caps & UFSHCD_CAP_TEMP_NOTIF) || dev_info->wspecversion < 0x300)
7677 		return;
7678 
7679 	ext_ufs_feature = get_unaligned_be32(desc_buf + DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7680 
7681 	if (ext_ufs_feature & UFS_DEV_LOW_TEMP_NOTIF)
7682 		mask |= MASK_EE_TOO_LOW_TEMP;
7683 
7684 	if (ext_ufs_feature & UFS_DEV_HIGH_TEMP_NOTIF)
7685 		mask |= MASK_EE_TOO_HIGH_TEMP;
7686 
7687 	if (mask) {
7688 		ufshcd_enable_ee(hba, mask);
7689 		ufs_hwmon_probe(hba, mask);
7690 	}
7691 }
7692 
7693 void ufshcd_fixup_dev_quirks(struct ufs_hba *hba,
7694 			     const struct ufs_dev_quirk *fixups)
7695 {
7696 	const struct ufs_dev_quirk *f;
7697 	struct ufs_dev_info *dev_info = &hba->dev_info;
7698 
7699 	if (!fixups)
7700 		return;
7701 
7702 	for (f = fixups; f->quirk; f++) {
7703 		if ((f->wmanufacturerid == dev_info->wmanufacturerid ||
7704 		     f->wmanufacturerid == UFS_ANY_VENDOR) &&
7705 		     ((dev_info->model &&
7706 		       STR_PRFX_EQUAL(f->model, dev_info->model)) ||
7707 		      !strcmp(f->model, UFS_ANY_MODEL)))
7708 			hba->dev_quirks |= f->quirk;
7709 	}
7710 }
7711 EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks);
7712 
7713 static void ufs_fixup_device_setup(struct ufs_hba *hba)
7714 {
7715 	/* fix by general quirk table */
7716 	ufshcd_fixup_dev_quirks(hba, ufs_fixups);
7717 
7718 	/* allow vendors to fix quirks */
7719 	ufshcd_vops_fixup_dev_quirks(hba);
7720 }
7721 
7722 static int ufs_get_device_desc(struct ufs_hba *hba)
7723 {
7724 	int err;
7725 	u8 model_index;
7726 	u8 b_ufs_feature_sup;
7727 	u8 *desc_buf;
7728 	struct ufs_dev_info *dev_info = &hba->dev_info;
7729 
7730 	desc_buf = kmalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
7731 	if (!desc_buf) {
7732 		err = -ENOMEM;
7733 		goto out;
7734 	}
7735 
7736 	err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf,
7737 				     hba->desc_size[QUERY_DESC_IDN_DEVICE]);
7738 	if (err) {
7739 		dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
7740 			__func__, err);
7741 		goto out;
7742 	}
7743 
7744 	/*
7745 	 * getting vendor (manufacturerID) and Bank Index in big endian
7746 	 * format
7747 	 */
7748 	dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
7749 				     desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
7750 
7751 	/* getting Specification Version in big endian format */
7752 	dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 |
7753 				      desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1];
7754 	b_ufs_feature_sup = desc_buf[DEVICE_DESC_PARAM_UFS_FEAT];
7755 
7756 	model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
7757 
7758 	if (dev_info->wspecversion >= UFS_DEV_HPB_SUPPORT_VERSION &&
7759 	    (b_ufs_feature_sup & UFS_DEV_HPB_SUPPORT)) {
7760 		bool hpb_en = false;
7761 
7762 		ufshpb_get_dev_info(hba, desc_buf);
7763 
7764 		if (!ufshpb_is_legacy(hba))
7765 			err = ufshcd_query_flag_retry(hba,
7766 						      UPIU_QUERY_OPCODE_READ_FLAG,
7767 						      QUERY_FLAG_IDN_HPB_EN, 0,
7768 						      &hpb_en);
7769 
7770 		if (ufshpb_is_legacy(hba) || (!err && hpb_en))
7771 			dev_info->hpb_enabled = true;
7772 	}
7773 
7774 	err = ufshcd_read_string_desc(hba, model_index,
7775 				      &dev_info->model, SD_ASCII_STD);
7776 	if (err < 0) {
7777 		dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
7778 			__func__, err);
7779 		goto out;
7780 	}
7781 
7782 	hba->luns_avail = desc_buf[DEVICE_DESC_PARAM_NUM_LU] +
7783 		desc_buf[DEVICE_DESC_PARAM_NUM_WLU];
7784 
7785 	ufs_fixup_device_setup(hba);
7786 
7787 	ufshcd_wb_probe(hba, desc_buf);
7788 
7789 	ufshcd_temp_notif_probe(hba, desc_buf);
7790 
7791 	/*
7792 	 * ufshcd_read_string_desc returns size of the string
7793 	 * reset the error value
7794 	 */
7795 	err = 0;
7796 
7797 out:
7798 	kfree(desc_buf);
7799 	return err;
7800 }
7801 
7802 static void ufs_put_device_desc(struct ufs_hba *hba)
7803 {
7804 	struct ufs_dev_info *dev_info = &hba->dev_info;
7805 
7806 	kfree(dev_info->model);
7807 	dev_info->model = NULL;
7808 }
7809 
7810 /**
7811  * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
7812  * @hba: per-adapter instance
7813  *
7814  * PA_TActivate parameter can be tuned manually if UniPro version is less than
7815  * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
7816  * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
7817  * the hibern8 exit latency.
7818  *
7819  * Returns zero on success, non-zero error value on failure.
7820  */
7821 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
7822 {
7823 	int ret = 0;
7824 	u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
7825 
7826 	ret = ufshcd_dme_peer_get(hba,
7827 				  UIC_ARG_MIB_SEL(
7828 					RX_MIN_ACTIVATETIME_CAPABILITY,
7829 					UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7830 				  &peer_rx_min_activatetime);
7831 	if (ret)
7832 		goto out;
7833 
7834 	/* make sure proper unit conversion is applied */
7835 	tuned_pa_tactivate =
7836 		((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
7837 		 / PA_TACTIVATE_TIME_UNIT_US);
7838 	ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7839 			     tuned_pa_tactivate);
7840 
7841 out:
7842 	return ret;
7843 }
7844 
7845 /**
7846  * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
7847  * @hba: per-adapter instance
7848  *
7849  * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
7850  * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
7851  * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
7852  * This optimal value can help reduce the hibern8 exit latency.
7853  *
7854  * Returns zero on success, non-zero error value on failure.
7855  */
7856 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
7857 {
7858 	int ret = 0;
7859 	u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
7860 	u32 max_hibern8_time, tuned_pa_hibern8time;
7861 
7862 	ret = ufshcd_dme_get(hba,
7863 			     UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
7864 					UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
7865 				  &local_tx_hibern8_time_cap);
7866 	if (ret)
7867 		goto out;
7868 
7869 	ret = ufshcd_dme_peer_get(hba,
7870 				  UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
7871 					UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7872 				  &peer_rx_hibern8_time_cap);
7873 	if (ret)
7874 		goto out;
7875 
7876 	max_hibern8_time = max(local_tx_hibern8_time_cap,
7877 			       peer_rx_hibern8_time_cap);
7878 	/* make sure proper unit conversion is applied */
7879 	tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
7880 				/ PA_HIBERN8_TIME_UNIT_US);
7881 	ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
7882 			     tuned_pa_hibern8time);
7883 out:
7884 	return ret;
7885 }
7886 
7887 /**
7888  * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
7889  * less than device PA_TACTIVATE time.
7890  * @hba: per-adapter instance
7891  *
7892  * Some UFS devices require host PA_TACTIVATE to be lower than device
7893  * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
7894  * for such devices.
7895  *
7896  * Returns zero on success, non-zero error value on failure.
7897  */
7898 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
7899 {
7900 	int ret = 0;
7901 	u32 granularity, peer_granularity;
7902 	u32 pa_tactivate, peer_pa_tactivate;
7903 	u32 pa_tactivate_us, peer_pa_tactivate_us;
7904 	static const u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
7905 
7906 	ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7907 				  &granularity);
7908 	if (ret)
7909 		goto out;
7910 
7911 	ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7912 				  &peer_granularity);
7913 	if (ret)
7914 		goto out;
7915 
7916 	if ((granularity < PA_GRANULARITY_MIN_VAL) ||
7917 	    (granularity > PA_GRANULARITY_MAX_VAL)) {
7918 		dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
7919 			__func__, granularity);
7920 		return -EINVAL;
7921 	}
7922 
7923 	if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
7924 	    (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
7925 		dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
7926 			__func__, peer_granularity);
7927 		return -EINVAL;
7928 	}
7929 
7930 	ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
7931 	if (ret)
7932 		goto out;
7933 
7934 	ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
7935 				  &peer_pa_tactivate);
7936 	if (ret)
7937 		goto out;
7938 
7939 	pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
7940 	peer_pa_tactivate_us = peer_pa_tactivate *
7941 			     gran_to_us_table[peer_granularity - 1];
7942 
7943 	if (pa_tactivate_us >= peer_pa_tactivate_us) {
7944 		u32 new_peer_pa_tactivate;
7945 
7946 		new_peer_pa_tactivate = pa_tactivate_us /
7947 				      gran_to_us_table[peer_granularity - 1];
7948 		new_peer_pa_tactivate++;
7949 		ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7950 					  new_peer_pa_tactivate);
7951 	}
7952 
7953 out:
7954 	return ret;
7955 }
7956 
7957 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
7958 {
7959 	if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
7960 		ufshcd_tune_pa_tactivate(hba);
7961 		ufshcd_tune_pa_hibern8time(hba);
7962 	}
7963 
7964 	ufshcd_vops_apply_dev_quirks(hba);
7965 
7966 	if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
7967 		/* set 1ms timeout for PA_TACTIVATE */
7968 		ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
7969 
7970 	if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
7971 		ufshcd_quirk_tune_host_pa_tactivate(hba);
7972 }
7973 
7974 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
7975 {
7976 	hba->ufs_stats.hibern8_exit_cnt = 0;
7977 	hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
7978 	hba->req_abort_count = 0;
7979 }
7980 
7981 static int ufshcd_device_geo_params_init(struct ufs_hba *hba)
7982 {
7983 	int err;
7984 	size_t buff_len;
7985 	u8 *desc_buf;
7986 
7987 	buff_len = hba->desc_size[QUERY_DESC_IDN_GEOMETRY];
7988 	desc_buf = kmalloc(buff_len, GFP_KERNEL);
7989 	if (!desc_buf) {
7990 		err = -ENOMEM;
7991 		goto out;
7992 	}
7993 
7994 	err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0,
7995 				     desc_buf, buff_len);
7996 	if (err) {
7997 		dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n",
7998 				__func__, err);
7999 		goto out;
8000 	}
8001 
8002 	if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1)
8003 		hba->dev_info.max_lu_supported = 32;
8004 	else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0)
8005 		hba->dev_info.max_lu_supported = 8;
8006 
8007 	if (hba->desc_size[QUERY_DESC_IDN_GEOMETRY] >=
8008 		GEOMETRY_DESC_PARAM_HPB_MAX_ACTIVE_REGS)
8009 		ufshpb_get_geo_info(hba, desc_buf);
8010 
8011 out:
8012 	kfree(desc_buf);
8013 	return err;
8014 }
8015 
8016 struct ufs_ref_clk {
8017 	unsigned long freq_hz;
8018 	enum ufs_ref_clk_freq val;
8019 };
8020 
8021 static const struct ufs_ref_clk ufs_ref_clk_freqs[] = {
8022 	{19200000, REF_CLK_FREQ_19_2_MHZ},
8023 	{26000000, REF_CLK_FREQ_26_MHZ},
8024 	{38400000, REF_CLK_FREQ_38_4_MHZ},
8025 	{52000000, REF_CLK_FREQ_52_MHZ},
8026 	{0, REF_CLK_FREQ_INVAL},
8027 };
8028 
8029 static enum ufs_ref_clk_freq
8030 ufs_get_bref_clk_from_hz(unsigned long freq)
8031 {
8032 	int i;
8033 
8034 	for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
8035 		if (ufs_ref_clk_freqs[i].freq_hz == freq)
8036 			return ufs_ref_clk_freqs[i].val;
8037 
8038 	return REF_CLK_FREQ_INVAL;
8039 }
8040 
8041 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
8042 {
8043 	unsigned long freq;
8044 
8045 	freq = clk_get_rate(refclk);
8046 
8047 	hba->dev_ref_clk_freq =
8048 		ufs_get_bref_clk_from_hz(freq);
8049 
8050 	if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
8051 		dev_err(hba->dev,
8052 		"invalid ref_clk setting = %ld\n", freq);
8053 }
8054 
8055 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
8056 {
8057 	int err;
8058 	u32 ref_clk;
8059 	u32 freq = hba->dev_ref_clk_freq;
8060 
8061 	err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
8062 			QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
8063 
8064 	if (err) {
8065 		dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
8066 			err);
8067 		goto out;
8068 	}
8069 
8070 	if (ref_clk == freq)
8071 		goto out; /* nothing to update */
8072 
8073 	err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
8074 			QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
8075 
8076 	if (err) {
8077 		dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
8078 			ufs_ref_clk_freqs[freq].freq_hz);
8079 		goto out;
8080 	}
8081 
8082 	dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
8083 			ufs_ref_clk_freqs[freq].freq_hz);
8084 
8085 out:
8086 	return err;
8087 }
8088 
8089 static int ufshcd_device_params_init(struct ufs_hba *hba)
8090 {
8091 	bool flag;
8092 	int ret, i;
8093 
8094 	 /* Init device descriptor sizes */
8095 	for (i = 0; i < QUERY_DESC_IDN_MAX; i++)
8096 		hba->desc_size[i] = QUERY_DESC_MAX_SIZE;
8097 
8098 	/* Init UFS geometry descriptor related parameters */
8099 	ret = ufshcd_device_geo_params_init(hba);
8100 	if (ret)
8101 		goto out;
8102 
8103 	/* Check and apply UFS device quirks */
8104 	ret = ufs_get_device_desc(hba);
8105 	if (ret) {
8106 		dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
8107 			__func__, ret);
8108 		goto out;
8109 	}
8110 
8111 	ufshcd_get_ref_clk_gating_wait(hba);
8112 
8113 	if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
8114 			QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag))
8115 		hba->dev_info.f_power_on_wp_en = flag;
8116 
8117 	/* Probe maximum power mode co-supported by both UFS host and device */
8118 	if (ufshcd_get_max_pwr_mode(hba))
8119 		dev_err(hba->dev,
8120 			"%s: Failed getting max supported power mode\n",
8121 			__func__);
8122 out:
8123 	return ret;
8124 }
8125 
8126 /**
8127  * ufshcd_add_lus - probe and add UFS logical units
8128  * @hba: per-adapter instance
8129  */
8130 static int ufshcd_add_lus(struct ufs_hba *hba)
8131 {
8132 	int ret;
8133 
8134 	/* Add required well known logical units to scsi mid layer */
8135 	ret = ufshcd_scsi_add_wlus(hba);
8136 	if (ret)
8137 		goto out;
8138 
8139 	/* Initialize devfreq after UFS device is detected */
8140 	if (ufshcd_is_clkscaling_supported(hba)) {
8141 		memcpy(&hba->clk_scaling.saved_pwr_info.info,
8142 			&hba->pwr_info,
8143 			sizeof(struct ufs_pa_layer_attr));
8144 		hba->clk_scaling.saved_pwr_info.is_valid = true;
8145 		hba->clk_scaling.is_allowed = true;
8146 
8147 		ret = ufshcd_devfreq_init(hba);
8148 		if (ret)
8149 			goto out;
8150 
8151 		hba->clk_scaling.is_enabled = true;
8152 		ufshcd_init_clk_scaling_sysfs(hba);
8153 	}
8154 
8155 	ufs_bsg_probe(hba);
8156 	ufshpb_init(hba);
8157 	scsi_scan_host(hba->host);
8158 	pm_runtime_put_sync(hba->dev);
8159 
8160 out:
8161 	return ret;
8162 }
8163 
8164 /**
8165  * ufshcd_probe_hba - probe hba to detect device and initialize it
8166  * @hba: per-adapter instance
8167  * @init_dev_params: whether or not to call ufshcd_device_params_init().
8168  *
8169  * Execute link-startup and verify device initialization
8170  */
8171 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params)
8172 {
8173 	int ret;
8174 	unsigned long flags;
8175 	ktime_t start = ktime_get();
8176 
8177 	hba->ufshcd_state = UFSHCD_STATE_RESET;
8178 
8179 	ret = ufshcd_link_startup(hba);
8180 	if (ret)
8181 		goto out;
8182 
8183 	if (hba->quirks & UFSHCD_QUIRK_SKIP_PH_CONFIGURATION)
8184 		goto out;
8185 
8186 	/* Debug counters initialization */
8187 	ufshcd_clear_dbg_ufs_stats(hba);
8188 
8189 	/* UniPro link is active now */
8190 	ufshcd_set_link_active(hba);
8191 
8192 	/* Verify device initialization by sending NOP OUT UPIU */
8193 	ret = ufshcd_verify_dev_init(hba);
8194 	if (ret)
8195 		goto out;
8196 
8197 	/* Initiate UFS initialization, and waiting until completion */
8198 	ret = ufshcd_complete_dev_init(hba);
8199 	if (ret)
8200 		goto out;
8201 
8202 	/*
8203 	 * Initialize UFS device parameters used by driver, these
8204 	 * parameters are associated with UFS descriptors.
8205 	 */
8206 	if (init_dev_params) {
8207 		ret = ufshcd_device_params_init(hba);
8208 		if (ret)
8209 			goto out;
8210 	}
8211 
8212 	ufshcd_tune_unipro_params(hba);
8213 
8214 	/* UFS device is also active now */
8215 	ufshcd_set_ufs_dev_active(hba);
8216 	ufshcd_force_reset_auto_bkops(hba);
8217 
8218 	/* Gear up to HS gear if supported */
8219 	if (hba->max_pwr_info.is_valid) {
8220 		/*
8221 		 * Set the right value to bRefClkFreq before attempting to
8222 		 * switch to HS gears.
8223 		 */
8224 		if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
8225 			ufshcd_set_dev_ref_clk(hba);
8226 		ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
8227 		if (ret) {
8228 			dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
8229 					__func__, ret);
8230 			goto out;
8231 		}
8232 		ufshcd_print_pwr_info(hba);
8233 	}
8234 
8235 	/*
8236 	 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec)
8237 	 * and for removable UFS card as well, hence always set the parameter.
8238 	 * Note: Error handler may issue the device reset hence resetting
8239 	 * bActiveICCLevel as well so it is always safe to set this here.
8240 	 */
8241 	ufshcd_set_active_icc_lvl(hba);
8242 
8243 	/* Enable UFS Write Booster if supported */
8244 	ufshcd_configure_wb(hba);
8245 
8246 	if (hba->ee_usr_mask)
8247 		ufshcd_write_ee_control(hba);
8248 	/* Enable Auto-Hibernate if configured */
8249 	ufshcd_auto_hibern8_enable(hba);
8250 
8251 	ufshpb_toggle_state(hba, HPB_RESET, HPB_PRESENT);
8252 out:
8253 	spin_lock_irqsave(hba->host->host_lock, flags);
8254 	if (ret)
8255 		hba->ufshcd_state = UFSHCD_STATE_ERROR;
8256 	else if (hba->ufshcd_state == UFSHCD_STATE_RESET)
8257 		hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
8258 	spin_unlock_irqrestore(hba->host->host_lock, flags);
8259 
8260 	trace_ufshcd_init(dev_name(hba->dev), ret,
8261 		ktime_to_us(ktime_sub(ktime_get(), start)),
8262 		hba->curr_dev_pwr_mode, hba->uic_link_state);
8263 	return ret;
8264 }
8265 
8266 /**
8267  * ufshcd_async_scan - asynchronous execution for probing hba
8268  * @data: data pointer to pass to this function
8269  * @cookie: cookie data
8270  */
8271 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
8272 {
8273 	struct ufs_hba *hba = (struct ufs_hba *)data;
8274 	int ret;
8275 
8276 	down(&hba->host_sem);
8277 	/* Initialize hba, detect and initialize UFS device */
8278 	ret = ufshcd_probe_hba(hba, true);
8279 	up(&hba->host_sem);
8280 	if (ret)
8281 		goto out;
8282 
8283 	/* Probe and add UFS logical units  */
8284 	ret = ufshcd_add_lus(hba);
8285 out:
8286 	/*
8287 	 * If we failed to initialize the device or the device is not
8288 	 * present, turn off the power/clocks etc.
8289 	 */
8290 	if (ret) {
8291 		pm_runtime_put_sync(hba->dev);
8292 		ufshcd_hba_exit(hba);
8293 	}
8294 }
8295 
8296 static enum scsi_timeout_action ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
8297 {
8298 	struct ufs_hba *hba = shost_priv(scmd->device->host);
8299 
8300 	if (!hba->system_suspending) {
8301 		/* Activate the error handler in the SCSI core. */
8302 		return SCSI_EH_NOT_HANDLED;
8303 	}
8304 
8305 	/*
8306 	 * If we get here we know that no TMFs are outstanding and also that
8307 	 * the only pending command is a START STOP UNIT command. Handle the
8308 	 * timeout of that command directly to prevent a deadlock between
8309 	 * ufshcd_set_dev_pwr_mode() and ufshcd_err_handler().
8310 	 */
8311 	ufshcd_link_recovery(hba);
8312 	dev_info(hba->dev, "%s() finished; outstanding_tasks = %#lx.\n",
8313 		 __func__, hba->outstanding_tasks);
8314 
8315 	return hba->outstanding_reqs ? SCSI_EH_RESET_TIMER : SCSI_EH_DONE;
8316 }
8317 
8318 static const struct attribute_group *ufshcd_driver_groups[] = {
8319 	&ufs_sysfs_unit_descriptor_group,
8320 	&ufs_sysfs_lun_attributes_group,
8321 #ifdef CONFIG_SCSI_UFS_HPB
8322 	&ufs_sysfs_hpb_stat_group,
8323 	&ufs_sysfs_hpb_param_group,
8324 #endif
8325 	NULL,
8326 };
8327 
8328 static struct ufs_hba_variant_params ufs_hba_vps = {
8329 	.hba_enable_delay_us		= 1000,
8330 	.wb_flush_threshold		= UFS_WB_BUF_REMAIN_PERCENT(40),
8331 	.devfreq_profile.polling_ms	= 100,
8332 	.devfreq_profile.target		= ufshcd_devfreq_target,
8333 	.devfreq_profile.get_dev_status	= ufshcd_devfreq_get_dev_status,
8334 	.ondemand_data.upthreshold	= 70,
8335 	.ondemand_data.downdifferential	= 5,
8336 };
8337 
8338 static struct scsi_host_template ufshcd_driver_template = {
8339 	.module			= THIS_MODULE,
8340 	.name			= UFSHCD,
8341 	.proc_name		= UFSHCD,
8342 	.map_queues		= ufshcd_map_queues,
8343 	.queuecommand		= ufshcd_queuecommand,
8344 	.mq_poll		= ufshcd_poll,
8345 	.slave_alloc		= ufshcd_slave_alloc,
8346 	.slave_configure	= ufshcd_slave_configure,
8347 	.slave_destroy		= ufshcd_slave_destroy,
8348 	.change_queue_depth	= ufshcd_change_queue_depth,
8349 	.eh_abort_handler	= ufshcd_abort,
8350 	.eh_device_reset_handler = ufshcd_eh_device_reset_handler,
8351 	.eh_host_reset_handler   = ufshcd_eh_host_reset_handler,
8352 	.eh_timed_out		= ufshcd_eh_timed_out,
8353 	.this_id		= -1,
8354 	.sg_tablesize		= SG_ALL,
8355 	.cmd_per_lun		= UFSHCD_CMD_PER_LUN,
8356 	.can_queue		= UFSHCD_CAN_QUEUE,
8357 	.max_segment_size	= PRDT_DATA_BYTE_COUNT_MAX,
8358 	.max_sectors		= (1 << 20) / SECTOR_SIZE, /* 1 MiB */
8359 	.max_host_blocked	= 1,
8360 	.track_queue_depth	= 1,
8361 	.sdev_groups		= ufshcd_driver_groups,
8362 	.dma_boundary		= PAGE_SIZE - 1,
8363 	.rpm_autosuspend_delay	= RPM_AUTOSUSPEND_DELAY_MS,
8364 };
8365 
8366 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
8367 				   int ua)
8368 {
8369 	int ret;
8370 
8371 	if (!vreg)
8372 		return 0;
8373 
8374 	/*
8375 	 * "set_load" operation shall be required on those regulators
8376 	 * which specifically configured current limitation. Otherwise
8377 	 * zero max_uA may cause unexpected behavior when regulator is
8378 	 * enabled or set as high power mode.
8379 	 */
8380 	if (!vreg->max_uA)
8381 		return 0;
8382 
8383 	ret = regulator_set_load(vreg->reg, ua);
8384 	if (ret < 0) {
8385 		dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
8386 				__func__, vreg->name, ua, ret);
8387 	}
8388 
8389 	return ret;
8390 }
8391 
8392 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
8393 					 struct ufs_vreg *vreg)
8394 {
8395 	return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
8396 }
8397 
8398 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
8399 					 struct ufs_vreg *vreg)
8400 {
8401 	if (!vreg)
8402 		return 0;
8403 
8404 	return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
8405 }
8406 
8407 static int ufshcd_config_vreg(struct device *dev,
8408 		struct ufs_vreg *vreg, bool on)
8409 {
8410 	if (regulator_count_voltages(vreg->reg) <= 0)
8411 		return 0;
8412 
8413 	return ufshcd_config_vreg_load(dev, vreg, on ? vreg->max_uA : 0);
8414 }
8415 
8416 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
8417 {
8418 	int ret = 0;
8419 
8420 	if (!vreg || vreg->enabled)
8421 		goto out;
8422 
8423 	ret = ufshcd_config_vreg(dev, vreg, true);
8424 	if (!ret)
8425 		ret = regulator_enable(vreg->reg);
8426 
8427 	if (!ret)
8428 		vreg->enabled = true;
8429 	else
8430 		dev_err(dev, "%s: %s enable failed, err=%d\n",
8431 				__func__, vreg->name, ret);
8432 out:
8433 	return ret;
8434 }
8435 
8436 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
8437 {
8438 	int ret = 0;
8439 
8440 	if (!vreg || !vreg->enabled || vreg->always_on)
8441 		goto out;
8442 
8443 	ret = regulator_disable(vreg->reg);
8444 
8445 	if (!ret) {
8446 		/* ignore errors on applying disable config */
8447 		ufshcd_config_vreg(dev, vreg, false);
8448 		vreg->enabled = false;
8449 	} else {
8450 		dev_err(dev, "%s: %s disable failed, err=%d\n",
8451 				__func__, vreg->name, ret);
8452 	}
8453 out:
8454 	return ret;
8455 }
8456 
8457 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
8458 {
8459 	int ret = 0;
8460 	struct device *dev = hba->dev;
8461 	struct ufs_vreg_info *info = &hba->vreg_info;
8462 
8463 	ret = ufshcd_toggle_vreg(dev, info->vcc, on);
8464 	if (ret)
8465 		goto out;
8466 
8467 	ret = ufshcd_toggle_vreg(dev, info->vccq, on);
8468 	if (ret)
8469 		goto out;
8470 
8471 	ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
8472 
8473 out:
8474 	if (ret) {
8475 		ufshcd_toggle_vreg(dev, info->vccq2, false);
8476 		ufshcd_toggle_vreg(dev, info->vccq, false);
8477 		ufshcd_toggle_vreg(dev, info->vcc, false);
8478 	}
8479 	return ret;
8480 }
8481 
8482 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
8483 {
8484 	struct ufs_vreg_info *info = &hba->vreg_info;
8485 
8486 	return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
8487 }
8488 
8489 int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
8490 {
8491 	int ret = 0;
8492 
8493 	if (!vreg)
8494 		goto out;
8495 
8496 	vreg->reg = devm_regulator_get(dev, vreg->name);
8497 	if (IS_ERR(vreg->reg)) {
8498 		ret = PTR_ERR(vreg->reg);
8499 		dev_err(dev, "%s: %s get failed, err=%d\n",
8500 				__func__, vreg->name, ret);
8501 	}
8502 out:
8503 	return ret;
8504 }
8505 EXPORT_SYMBOL_GPL(ufshcd_get_vreg);
8506 
8507 static int ufshcd_init_vreg(struct ufs_hba *hba)
8508 {
8509 	int ret = 0;
8510 	struct device *dev = hba->dev;
8511 	struct ufs_vreg_info *info = &hba->vreg_info;
8512 
8513 	ret = ufshcd_get_vreg(dev, info->vcc);
8514 	if (ret)
8515 		goto out;
8516 
8517 	ret = ufshcd_get_vreg(dev, info->vccq);
8518 	if (!ret)
8519 		ret = ufshcd_get_vreg(dev, info->vccq2);
8520 out:
8521 	return ret;
8522 }
8523 
8524 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
8525 {
8526 	struct ufs_vreg_info *info = &hba->vreg_info;
8527 
8528 	return ufshcd_get_vreg(hba->dev, info->vdd_hba);
8529 }
8530 
8531 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
8532 {
8533 	int ret = 0;
8534 	struct ufs_clk_info *clki;
8535 	struct list_head *head = &hba->clk_list_head;
8536 	unsigned long flags;
8537 	ktime_t start = ktime_get();
8538 	bool clk_state_changed = false;
8539 
8540 	if (list_empty(head))
8541 		goto out;
8542 
8543 	ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
8544 	if (ret)
8545 		return ret;
8546 
8547 	list_for_each_entry(clki, head, list) {
8548 		if (!IS_ERR_OR_NULL(clki->clk)) {
8549 			/*
8550 			 * Don't disable clocks which are needed
8551 			 * to keep the link active.
8552 			 */
8553 			if (ufshcd_is_link_active(hba) &&
8554 			    clki->keep_link_active)
8555 				continue;
8556 
8557 			clk_state_changed = on ^ clki->enabled;
8558 			if (on && !clki->enabled) {
8559 				ret = clk_prepare_enable(clki->clk);
8560 				if (ret) {
8561 					dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
8562 						__func__, clki->name, ret);
8563 					goto out;
8564 				}
8565 			} else if (!on && clki->enabled) {
8566 				clk_disable_unprepare(clki->clk);
8567 			}
8568 			clki->enabled = on;
8569 			dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
8570 					clki->name, on ? "en" : "dis");
8571 		}
8572 	}
8573 
8574 	ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
8575 	if (ret)
8576 		return ret;
8577 
8578 out:
8579 	if (ret) {
8580 		list_for_each_entry(clki, head, list) {
8581 			if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
8582 				clk_disable_unprepare(clki->clk);
8583 		}
8584 	} else if (!ret && on) {
8585 		spin_lock_irqsave(hba->host->host_lock, flags);
8586 		hba->clk_gating.state = CLKS_ON;
8587 		trace_ufshcd_clk_gating(dev_name(hba->dev),
8588 					hba->clk_gating.state);
8589 		spin_unlock_irqrestore(hba->host->host_lock, flags);
8590 	}
8591 
8592 	if (clk_state_changed)
8593 		trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
8594 			(on ? "on" : "off"),
8595 			ktime_to_us(ktime_sub(ktime_get(), start)), ret);
8596 	return ret;
8597 }
8598 
8599 static enum ufs_ref_clk_freq ufshcd_parse_ref_clk_property(struct ufs_hba *hba)
8600 {
8601 	u32 freq;
8602 	int ret = device_property_read_u32(hba->dev, "ref-clk-freq", &freq);
8603 
8604 	if (ret) {
8605 		dev_dbg(hba->dev, "Cannot query 'ref-clk-freq' property = %d", ret);
8606 		return REF_CLK_FREQ_INVAL;
8607 	}
8608 
8609 	return ufs_get_bref_clk_from_hz(freq);
8610 }
8611 
8612 static int ufshcd_init_clocks(struct ufs_hba *hba)
8613 {
8614 	int ret = 0;
8615 	struct ufs_clk_info *clki;
8616 	struct device *dev = hba->dev;
8617 	struct list_head *head = &hba->clk_list_head;
8618 
8619 	if (list_empty(head))
8620 		goto out;
8621 
8622 	list_for_each_entry(clki, head, list) {
8623 		if (!clki->name)
8624 			continue;
8625 
8626 		clki->clk = devm_clk_get(dev, clki->name);
8627 		if (IS_ERR(clki->clk)) {
8628 			ret = PTR_ERR(clki->clk);
8629 			dev_err(dev, "%s: %s clk get failed, %d\n",
8630 					__func__, clki->name, ret);
8631 			goto out;
8632 		}
8633 
8634 		/*
8635 		 * Parse device ref clk freq as per device tree "ref_clk".
8636 		 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
8637 		 * in ufshcd_alloc_host().
8638 		 */
8639 		if (!strcmp(clki->name, "ref_clk"))
8640 			ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
8641 
8642 		if (clki->max_freq) {
8643 			ret = clk_set_rate(clki->clk, clki->max_freq);
8644 			if (ret) {
8645 				dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
8646 					__func__, clki->name,
8647 					clki->max_freq, ret);
8648 				goto out;
8649 			}
8650 			clki->curr_freq = clki->max_freq;
8651 		}
8652 		dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
8653 				clki->name, clk_get_rate(clki->clk));
8654 	}
8655 out:
8656 	return ret;
8657 }
8658 
8659 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
8660 {
8661 	int err = 0;
8662 
8663 	if (!hba->vops)
8664 		goto out;
8665 
8666 	err = ufshcd_vops_init(hba);
8667 	if (err)
8668 		dev_err(hba->dev, "%s: variant %s init failed err %d\n",
8669 			__func__, ufshcd_get_var_name(hba), err);
8670 out:
8671 	return err;
8672 }
8673 
8674 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
8675 {
8676 	if (!hba->vops)
8677 		return;
8678 
8679 	ufshcd_vops_exit(hba);
8680 }
8681 
8682 static int ufshcd_hba_init(struct ufs_hba *hba)
8683 {
8684 	int err;
8685 
8686 	/*
8687 	 * Handle host controller power separately from the UFS device power
8688 	 * rails as it will help controlling the UFS host controller power
8689 	 * collapse easily which is different than UFS device power collapse.
8690 	 * Also, enable the host controller power before we go ahead with rest
8691 	 * of the initialization here.
8692 	 */
8693 	err = ufshcd_init_hba_vreg(hba);
8694 	if (err)
8695 		goto out;
8696 
8697 	err = ufshcd_setup_hba_vreg(hba, true);
8698 	if (err)
8699 		goto out;
8700 
8701 	err = ufshcd_init_clocks(hba);
8702 	if (err)
8703 		goto out_disable_hba_vreg;
8704 
8705 	if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
8706 		hba->dev_ref_clk_freq = ufshcd_parse_ref_clk_property(hba);
8707 
8708 	err = ufshcd_setup_clocks(hba, true);
8709 	if (err)
8710 		goto out_disable_hba_vreg;
8711 
8712 	err = ufshcd_init_vreg(hba);
8713 	if (err)
8714 		goto out_disable_clks;
8715 
8716 	err = ufshcd_setup_vreg(hba, true);
8717 	if (err)
8718 		goto out_disable_clks;
8719 
8720 	err = ufshcd_variant_hba_init(hba);
8721 	if (err)
8722 		goto out_disable_vreg;
8723 
8724 	ufs_debugfs_hba_init(hba);
8725 
8726 	hba->is_powered = true;
8727 	goto out;
8728 
8729 out_disable_vreg:
8730 	ufshcd_setup_vreg(hba, false);
8731 out_disable_clks:
8732 	ufshcd_setup_clocks(hba, false);
8733 out_disable_hba_vreg:
8734 	ufshcd_setup_hba_vreg(hba, false);
8735 out:
8736 	return err;
8737 }
8738 
8739 static void ufshcd_hba_exit(struct ufs_hba *hba)
8740 {
8741 	if (hba->is_powered) {
8742 		ufshcd_exit_clk_scaling(hba);
8743 		ufshcd_exit_clk_gating(hba);
8744 		if (hba->eh_wq)
8745 			destroy_workqueue(hba->eh_wq);
8746 		ufs_debugfs_hba_exit(hba);
8747 		ufshcd_variant_hba_exit(hba);
8748 		ufshcd_setup_vreg(hba, false);
8749 		ufshcd_setup_clocks(hba, false);
8750 		ufshcd_setup_hba_vreg(hba, false);
8751 		hba->is_powered = false;
8752 		ufs_put_device_desc(hba);
8753 	}
8754 }
8755 
8756 static int ufshcd_execute_start_stop(struct scsi_device *sdev,
8757 				     enum ufs_dev_pwr_mode pwr_mode,
8758 				     struct scsi_sense_hdr *sshdr)
8759 {
8760 	unsigned char cdb[6] = { START_STOP, 0, 0, 0, pwr_mode << 4, 0 };
8761 	struct request *req;
8762 	struct scsi_cmnd *scmd;
8763 	int ret;
8764 
8765 	req = scsi_alloc_request(sdev->request_queue, REQ_OP_DRV_IN,
8766 				 BLK_MQ_REQ_PM);
8767 	if (IS_ERR(req))
8768 		return PTR_ERR(req);
8769 
8770 	scmd = blk_mq_rq_to_pdu(req);
8771 	scmd->cmd_len = COMMAND_SIZE(cdb[0]);
8772 	memcpy(scmd->cmnd, cdb, scmd->cmd_len);
8773 	scmd->allowed = 0/*retries*/;
8774 	scmd->flags |= SCMD_FAIL_IF_RECOVERING;
8775 	req->timeout = 1 * HZ;
8776 	req->rq_flags |= RQF_PM | RQF_QUIET;
8777 
8778 	blk_execute_rq(req, /*at_head=*/true);
8779 
8780 	if (sshdr)
8781 		scsi_normalize_sense(scmd->sense_buffer, scmd->sense_len,
8782 				     sshdr);
8783 	ret = scmd->result;
8784 
8785 	blk_mq_free_request(req);
8786 
8787 	return ret;
8788 }
8789 
8790 /**
8791  * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
8792  *			     power mode
8793  * @hba: per adapter instance
8794  * @pwr_mode: device power mode to set
8795  *
8796  * Returns 0 if requested power mode is set successfully
8797  * Returns < 0 if failed to set the requested power mode
8798  */
8799 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
8800 				     enum ufs_dev_pwr_mode pwr_mode)
8801 {
8802 	struct scsi_sense_hdr sshdr;
8803 	struct scsi_device *sdp;
8804 	unsigned long flags;
8805 	int ret, retries;
8806 
8807 	spin_lock_irqsave(hba->host->host_lock, flags);
8808 	sdp = hba->ufs_device_wlun;
8809 	if (sdp && scsi_device_online(sdp))
8810 		ret = scsi_device_get(sdp);
8811 	else
8812 		ret = -ENODEV;
8813 	spin_unlock_irqrestore(hba->host->host_lock, flags);
8814 
8815 	if (ret)
8816 		return ret;
8817 
8818 	/*
8819 	 * If scsi commands fail, the scsi mid-layer schedules scsi error-
8820 	 * handling, which would wait for host to be resumed. Since we know
8821 	 * we are functional while we are here, skip host resume in error
8822 	 * handling context.
8823 	 */
8824 	hba->host->eh_noresume = 1;
8825 
8826 	/*
8827 	 * Current function would be generally called from the power management
8828 	 * callbacks hence set the RQF_PM flag so that it doesn't resume the
8829 	 * already suspended childs.
8830 	 */
8831 	for (retries = 3; retries > 0; --retries) {
8832 		ret = ufshcd_execute_start_stop(sdp, pwr_mode, &sshdr);
8833 		/*
8834 		 * scsi_execute() only returns a negative value if the request
8835 		 * queue is dying.
8836 		 */
8837 		if (ret <= 0)
8838 			break;
8839 	}
8840 	if (ret) {
8841 		sdev_printk(KERN_WARNING, sdp,
8842 			    "START_STOP failed for power mode: %d, result %x\n",
8843 			    pwr_mode, ret);
8844 		if (ret > 0) {
8845 			if (scsi_sense_valid(&sshdr))
8846 				scsi_print_sense_hdr(sdp, NULL, &sshdr);
8847 			ret = -EIO;
8848 		}
8849 	} else {
8850 		hba->curr_dev_pwr_mode = pwr_mode;
8851 	}
8852 
8853 	scsi_device_put(sdp);
8854 	hba->host->eh_noresume = 0;
8855 	return ret;
8856 }
8857 
8858 static int ufshcd_link_state_transition(struct ufs_hba *hba,
8859 					enum uic_link_state req_link_state,
8860 					bool check_for_bkops)
8861 {
8862 	int ret = 0;
8863 
8864 	if (req_link_state == hba->uic_link_state)
8865 		return 0;
8866 
8867 	if (req_link_state == UIC_LINK_HIBERN8_STATE) {
8868 		ret = ufshcd_uic_hibern8_enter(hba);
8869 		if (!ret) {
8870 			ufshcd_set_link_hibern8(hba);
8871 		} else {
8872 			dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8873 					__func__, ret);
8874 			goto out;
8875 		}
8876 	}
8877 	/*
8878 	 * If autobkops is enabled, link can't be turned off because
8879 	 * turning off the link would also turn off the device, except in the
8880 	 * case of DeepSleep where the device is expected to remain powered.
8881 	 */
8882 	else if ((req_link_state == UIC_LINK_OFF_STATE) &&
8883 		 (!check_for_bkops || !hba->auto_bkops_enabled)) {
8884 		/*
8885 		 * Let's make sure that link is in low power mode, we are doing
8886 		 * this currently by putting the link in Hibern8. Otherway to
8887 		 * put the link in low power mode is to send the DME end point
8888 		 * to device and then send the DME reset command to local
8889 		 * unipro. But putting the link in hibern8 is much faster.
8890 		 *
8891 		 * Note also that putting the link in Hibern8 is a requirement
8892 		 * for entering DeepSleep.
8893 		 */
8894 		ret = ufshcd_uic_hibern8_enter(hba);
8895 		if (ret) {
8896 			dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8897 					__func__, ret);
8898 			goto out;
8899 		}
8900 		/*
8901 		 * Change controller state to "reset state" which
8902 		 * should also put the link in off/reset state
8903 		 */
8904 		ufshcd_hba_stop(hba);
8905 		/*
8906 		 * TODO: Check if we need any delay to make sure that
8907 		 * controller is reset
8908 		 */
8909 		ufshcd_set_link_off(hba);
8910 	}
8911 
8912 out:
8913 	return ret;
8914 }
8915 
8916 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
8917 {
8918 	bool vcc_off = false;
8919 
8920 	/*
8921 	 * It seems some UFS devices may keep drawing more than sleep current
8922 	 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
8923 	 * To avoid this situation, add 2ms delay before putting these UFS
8924 	 * rails in LPM mode.
8925 	 */
8926 	if (!ufshcd_is_link_active(hba) &&
8927 	    hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
8928 		usleep_range(2000, 2100);
8929 
8930 	/*
8931 	 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
8932 	 * power.
8933 	 *
8934 	 * If UFS device and link is in OFF state, all power supplies (VCC,
8935 	 * VCCQ, VCCQ2) can be turned off if power on write protect is not
8936 	 * required. If UFS link is inactive (Hibern8 or OFF state) and device
8937 	 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
8938 	 *
8939 	 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
8940 	 * in low power state which would save some power.
8941 	 *
8942 	 * If Write Booster is enabled and the device needs to flush the WB
8943 	 * buffer OR if bkops status is urgent for WB, keep Vcc on.
8944 	 */
8945 	if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8946 	    !hba->dev_info.is_lu_power_on_wp) {
8947 		ufshcd_setup_vreg(hba, false);
8948 		vcc_off = true;
8949 	} else if (!ufshcd_is_ufs_dev_active(hba)) {
8950 		ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8951 		vcc_off = true;
8952 		if (ufshcd_is_link_hibern8(hba) || ufshcd_is_link_off(hba)) {
8953 			ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8954 			ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
8955 		}
8956 	}
8957 
8958 	/*
8959 	 * Some UFS devices require delay after VCC power rail is turned-off.
8960 	 */
8961 	if (vcc_off && hba->vreg_info.vcc &&
8962 		hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_AFTER_LPM)
8963 		usleep_range(5000, 5100);
8964 }
8965 
8966 #ifdef CONFIG_PM
8967 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
8968 {
8969 	int ret = 0;
8970 
8971 	if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8972 	    !hba->dev_info.is_lu_power_on_wp) {
8973 		ret = ufshcd_setup_vreg(hba, true);
8974 	} else if (!ufshcd_is_ufs_dev_active(hba)) {
8975 		if (!ufshcd_is_link_active(hba)) {
8976 			ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
8977 			if (ret)
8978 				goto vcc_disable;
8979 			ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
8980 			if (ret)
8981 				goto vccq_lpm;
8982 		}
8983 		ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
8984 	}
8985 	goto out;
8986 
8987 vccq_lpm:
8988 	ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8989 vcc_disable:
8990 	ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8991 out:
8992 	return ret;
8993 }
8994 #endif /* CONFIG_PM */
8995 
8996 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
8997 {
8998 	if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
8999 		ufshcd_setup_hba_vreg(hba, false);
9000 }
9001 
9002 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
9003 {
9004 	if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
9005 		ufshcd_setup_hba_vreg(hba, true);
9006 }
9007 
9008 static int __ufshcd_wl_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
9009 {
9010 	int ret = 0;
9011 	bool check_for_bkops;
9012 	enum ufs_pm_level pm_lvl;
9013 	enum ufs_dev_pwr_mode req_dev_pwr_mode;
9014 	enum uic_link_state req_link_state;
9015 
9016 	hba->pm_op_in_progress = true;
9017 	if (pm_op != UFS_SHUTDOWN_PM) {
9018 		pm_lvl = pm_op == UFS_RUNTIME_PM ?
9019 			 hba->rpm_lvl : hba->spm_lvl;
9020 		req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
9021 		req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
9022 	} else {
9023 		req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
9024 		req_link_state = UIC_LINK_OFF_STATE;
9025 	}
9026 
9027 	ufshpb_suspend(hba);
9028 
9029 	/*
9030 	 * If we can't transition into any of the low power modes
9031 	 * just gate the clocks.
9032 	 */
9033 	ufshcd_hold(hba, false);
9034 	hba->clk_gating.is_suspended = true;
9035 
9036 	if (ufshcd_is_clkscaling_supported(hba))
9037 		ufshcd_clk_scaling_suspend(hba, true);
9038 
9039 	if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
9040 			req_link_state == UIC_LINK_ACTIVE_STATE) {
9041 		goto vops_suspend;
9042 	}
9043 
9044 	if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
9045 	    (req_link_state == hba->uic_link_state))
9046 		goto enable_scaling;
9047 
9048 	/* UFS device & link must be active before we enter in this function */
9049 	if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
9050 		ret = -EINVAL;
9051 		goto enable_scaling;
9052 	}
9053 
9054 	if (pm_op == UFS_RUNTIME_PM) {
9055 		if (ufshcd_can_autobkops_during_suspend(hba)) {
9056 			/*
9057 			 * The device is idle with no requests in the queue,
9058 			 * allow background operations if bkops status shows
9059 			 * that performance might be impacted.
9060 			 */
9061 			ret = ufshcd_urgent_bkops(hba);
9062 			if (ret)
9063 				goto enable_scaling;
9064 		} else {
9065 			/* make sure that auto bkops is disabled */
9066 			ufshcd_disable_auto_bkops(hba);
9067 		}
9068 		/*
9069 		 * If device needs to do BKOP or WB buffer flush during
9070 		 * Hibern8, keep device power mode as "active power mode"
9071 		 * and VCC supply.
9072 		 */
9073 		hba->dev_info.b_rpm_dev_flush_capable =
9074 			hba->auto_bkops_enabled ||
9075 			(((req_link_state == UIC_LINK_HIBERN8_STATE) ||
9076 			((req_link_state == UIC_LINK_ACTIVE_STATE) &&
9077 			ufshcd_is_auto_hibern8_enabled(hba))) &&
9078 			ufshcd_wb_need_flush(hba));
9079 	}
9080 
9081 	flush_work(&hba->eeh_work);
9082 
9083 	ret = ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
9084 	if (ret)
9085 		goto enable_scaling;
9086 
9087 	if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) {
9088 		if (pm_op != UFS_RUNTIME_PM)
9089 			/* ensure that bkops is disabled */
9090 			ufshcd_disable_auto_bkops(hba);
9091 
9092 		if (!hba->dev_info.b_rpm_dev_flush_capable) {
9093 			ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
9094 			if (ret && pm_op != UFS_SHUTDOWN_PM) {
9095 				/*
9096 				 * If return err in suspend flow, IO will hang.
9097 				 * Trigger error handler and break suspend for
9098 				 * error recovery.
9099 				 */
9100 				ufshcd_force_error_recovery(hba);
9101 				ret = -EBUSY;
9102 			}
9103 			if (ret)
9104 				goto enable_scaling;
9105 		}
9106 	}
9107 
9108 	/*
9109 	 * In the case of DeepSleep, the device is expected to remain powered
9110 	 * with the link off, so do not check for bkops.
9111 	 */
9112 	check_for_bkops = !ufshcd_is_ufs_dev_deepsleep(hba);
9113 	ret = ufshcd_link_state_transition(hba, req_link_state, check_for_bkops);
9114 	if (ret && pm_op != UFS_SHUTDOWN_PM) {
9115 		/*
9116 		 * If return err in suspend flow, IO will hang.
9117 		 * Trigger error handler and break suspend for
9118 		 * error recovery.
9119 		 */
9120 		ufshcd_force_error_recovery(hba);
9121 		ret = -EBUSY;
9122 	}
9123 	if (ret)
9124 		goto set_dev_active;
9125 
9126 vops_suspend:
9127 	/*
9128 	 * Call vendor specific suspend callback. As these callbacks may access
9129 	 * vendor specific host controller register space call them before the
9130 	 * host clocks are ON.
9131 	 */
9132 	ret = ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
9133 	if (ret)
9134 		goto set_link_active;
9135 	goto out;
9136 
9137 set_link_active:
9138 	/*
9139 	 * Device hardware reset is required to exit DeepSleep. Also, for
9140 	 * DeepSleep, the link is off so host reset and restore will be done
9141 	 * further below.
9142 	 */
9143 	if (ufshcd_is_ufs_dev_deepsleep(hba)) {
9144 		ufshcd_device_reset(hba);
9145 		WARN_ON(!ufshcd_is_link_off(hba));
9146 	}
9147 	if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
9148 		ufshcd_set_link_active(hba);
9149 	else if (ufshcd_is_link_off(hba))
9150 		ufshcd_host_reset_and_restore(hba);
9151 set_dev_active:
9152 	/* Can also get here needing to exit DeepSleep */
9153 	if (ufshcd_is_ufs_dev_deepsleep(hba)) {
9154 		ufshcd_device_reset(hba);
9155 		ufshcd_host_reset_and_restore(hba);
9156 	}
9157 	if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
9158 		ufshcd_disable_auto_bkops(hba);
9159 enable_scaling:
9160 	if (ufshcd_is_clkscaling_supported(hba))
9161 		ufshcd_clk_scaling_suspend(hba, false);
9162 
9163 	hba->dev_info.b_rpm_dev_flush_capable = false;
9164 out:
9165 	if (hba->dev_info.b_rpm_dev_flush_capable) {
9166 		schedule_delayed_work(&hba->rpm_dev_flush_recheck_work,
9167 			msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS));
9168 	}
9169 
9170 	if (ret) {
9171 		ufshcd_update_evt_hist(hba, UFS_EVT_WL_SUSP_ERR, (u32)ret);
9172 		hba->clk_gating.is_suspended = false;
9173 		ufshcd_release(hba);
9174 		ufshpb_resume(hba);
9175 	}
9176 	hba->pm_op_in_progress = false;
9177 	return ret;
9178 }
9179 
9180 #ifdef CONFIG_PM
9181 static int __ufshcd_wl_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
9182 {
9183 	int ret;
9184 	enum uic_link_state old_link_state = hba->uic_link_state;
9185 
9186 	hba->pm_op_in_progress = true;
9187 
9188 	/*
9189 	 * Call vendor specific resume callback. As these callbacks may access
9190 	 * vendor specific host controller register space call them when the
9191 	 * host clocks are ON.
9192 	 */
9193 	ret = ufshcd_vops_resume(hba, pm_op);
9194 	if (ret)
9195 		goto out;
9196 
9197 	/* For DeepSleep, the only supported option is to have the link off */
9198 	WARN_ON(ufshcd_is_ufs_dev_deepsleep(hba) && !ufshcd_is_link_off(hba));
9199 
9200 	if (ufshcd_is_link_hibern8(hba)) {
9201 		ret = ufshcd_uic_hibern8_exit(hba);
9202 		if (!ret) {
9203 			ufshcd_set_link_active(hba);
9204 		} else {
9205 			dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
9206 					__func__, ret);
9207 			goto vendor_suspend;
9208 		}
9209 	} else if (ufshcd_is_link_off(hba)) {
9210 		/*
9211 		 * A full initialization of the host and the device is
9212 		 * required since the link was put to off during suspend.
9213 		 * Note, in the case of DeepSleep, the device will exit
9214 		 * DeepSleep due to device reset.
9215 		 */
9216 		ret = ufshcd_reset_and_restore(hba);
9217 		/*
9218 		 * ufshcd_reset_and_restore() should have already
9219 		 * set the link state as active
9220 		 */
9221 		if (ret || !ufshcd_is_link_active(hba))
9222 			goto vendor_suspend;
9223 	}
9224 
9225 	if (!ufshcd_is_ufs_dev_active(hba)) {
9226 		ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
9227 		if (ret)
9228 			goto set_old_link_state;
9229 	}
9230 
9231 	if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
9232 		ufshcd_enable_auto_bkops(hba);
9233 	else
9234 		/*
9235 		 * If BKOPs operations are urgently needed at this moment then
9236 		 * keep auto-bkops enabled or else disable it.
9237 		 */
9238 		ufshcd_urgent_bkops(hba);
9239 
9240 	if (hba->ee_usr_mask)
9241 		ufshcd_write_ee_control(hba);
9242 
9243 	if (ufshcd_is_clkscaling_supported(hba))
9244 		ufshcd_clk_scaling_suspend(hba, false);
9245 
9246 	if (hba->dev_info.b_rpm_dev_flush_capable) {
9247 		hba->dev_info.b_rpm_dev_flush_capable = false;
9248 		cancel_delayed_work(&hba->rpm_dev_flush_recheck_work);
9249 	}
9250 
9251 	/* Enable Auto-Hibernate if configured */
9252 	ufshcd_auto_hibern8_enable(hba);
9253 
9254 	ufshpb_resume(hba);
9255 	goto out;
9256 
9257 set_old_link_state:
9258 	ufshcd_link_state_transition(hba, old_link_state, 0);
9259 vendor_suspend:
9260 	ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
9261 	ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
9262 out:
9263 	if (ret)
9264 		ufshcd_update_evt_hist(hba, UFS_EVT_WL_RES_ERR, (u32)ret);
9265 	hba->clk_gating.is_suspended = false;
9266 	ufshcd_release(hba);
9267 	hba->pm_op_in_progress = false;
9268 	return ret;
9269 }
9270 
9271 static int ufshcd_wl_runtime_suspend(struct device *dev)
9272 {
9273 	struct scsi_device *sdev = to_scsi_device(dev);
9274 	struct ufs_hba *hba;
9275 	int ret;
9276 	ktime_t start = ktime_get();
9277 
9278 	hba = shost_priv(sdev->host);
9279 
9280 	ret = __ufshcd_wl_suspend(hba, UFS_RUNTIME_PM);
9281 	if (ret)
9282 		dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9283 
9284 	trace_ufshcd_wl_runtime_suspend(dev_name(dev), ret,
9285 		ktime_to_us(ktime_sub(ktime_get(), start)),
9286 		hba->curr_dev_pwr_mode, hba->uic_link_state);
9287 
9288 	return ret;
9289 }
9290 
9291 static int ufshcd_wl_runtime_resume(struct device *dev)
9292 {
9293 	struct scsi_device *sdev = to_scsi_device(dev);
9294 	struct ufs_hba *hba;
9295 	int ret = 0;
9296 	ktime_t start = ktime_get();
9297 
9298 	hba = shost_priv(sdev->host);
9299 
9300 	ret = __ufshcd_wl_resume(hba, UFS_RUNTIME_PM);
9301 	if (ret)
9302 		dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9303 
9304 	trace_ufshcd_wl_runtime_resume(dev_name(dev), ret,
9305 		ktime_to_us(ktime_sub(ktime_get(), start)),
9306 		hba->curr_dev_pwr_mode, hba->uic_link_state);
9307 
9308 	return ret;
9309 }
9310 #endif
9311 
9312 #ifdef CONFIG_PM_SLEEP
9313 static int ufshcd_wl_suspend(struct device *dev)
9314 {
9315 	struct scsi_device *sdev = to_scsi_device(dev);
9316 	struct ufs_hba *hba;
9317 	int ret = 0;
9318 	ktime_t start = ktime_get();
9319 
9320 	hba = shost_priv(sdev->host);
9321 	down(&hba->host_sem);
9322 	hba->system_suspending = true;
9323 
9324 	if (pm_runtime_suspended(dev))
9325 		goto out;
9326 
9327 	ret = __ufshcd_wl_suspend(hba, UFS_SYSTEM_PM);
9328 	if (ret) {
9329 		dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__,  ret);
9330 		up(&hba->host_sem);
9331 	}
9332 
9333 out:
9334 	if (!ret)
9335 		hba->is_sys_suspended = true;
9336 	trace_ufshcd_wl_suspend(dev_name(dev), ret,
9337 		ktime_to_us(ktime_sub(ktime_get(), start)),
9338 		hba->curr_dev_pwr_mode, hba->uic_link_state);
9339 
9340 	return ret;
9341 }
9342 
9343 static int ufshcd_wl_resume(struct device *dev)
9344 {
9345 	struct scsi_device *sdev = to_scsi_device(dev);
9346 	struct ufs_hba *hba;
9347 	int ret = 0;
9348 	ktime_t start = ktime_get();
9349 
9350 	hba = shost_priv(sdev->host);
9351 
9352 	if (pm_runtime_suspended(dev))
9353 		goto out;
9354 
9355 	ret = __ufshcd_wl_resume(hba, UFS_SYSTEM_PM);
9356 	if (ret)
9357 		dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9358 out:
9359 	trace_ufshcd_wl_resume(dev_name(dev), ret,
9360 		ktime_to_us(ktime_sub(ktime_get(), start)),
9361 		hba->curr_dev_pwr_mode, hba->uic_link_state);
9362 	if (!ret)
9363 		hba->is_sys_suspended = false;
9364 	hba->system_suspending = false;
9365 	up(&hba->host_sem);
9366 	return ret;
9367 }
9368 #endif
9369 
9370 static void ufshcd_wl_shutdown(struct device *dev)
9371 {
9372 	struct scsi_device *sdev = to_scsi_device(dev);
9373 	struct ufs_hba *hba;
9374 
9375 	hba = shost_priv(sdev->host);
9376 
9377 	down(&hba->host_sem);
9378 	hba->shutting_down = true;
9379 	up(&hba->host_sem);
9380 
9381 	/* Turn on everything while shutting down */
9382 	ufshcd_rpm_get_sync(hba);
9383 	scsi_device_quiesce(sdev);
9384 	shost_for_each_device(sdev, hba->host) {
9385 		if (sdev == hba->ufs_device_wlun)
9386 			continue;
9387 		scsi_device_quiesce(sdev);
9388 	}
9389 	__ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
9390 }
9391 
9392 /**
9393  * ufshcd_suspend - helper function for suspend operations
9394  * @hba: per adapter instance
9395  *
9396  * This function will put disable irqs, turn off clocks
9397  * and set vreg and hba-vreg in lpm mode.
9398  */
9399 static int ufshcd_suspend(struct ufs_hba *hba)
9400 {
9401 	int ret;
9402 
9403 	if (!hba->is_powered)
9404 		return 0;
9405 	/*
9406 	 * Disable the host irq as host controller as there won't be any
9407 	 * host controller transaction expected till resume.
9408 	 */
9409 	ufshcd_disable_irq(hba);
9410 	ret = ufshcd_setup_clocks(hba, false);
9411 	if (ret) {
9412 		ufshcd_enable_irq(hba);
9413 		return ret;
9414 	}
9415 	if (ufshcd_is_clkgating_allowed(hba)) {
9416 		hba->clk_gating.state = CLKS_OFF;
9417 		trace_ufshcd_clk_gating(dev_name(hba->dev),
9418 					hba->clk_gating.state);
9419 	}
9420 
9421 	ufshcd_vreg_set_lpm(hba);
9422 	/* Put the host controller in low power mode if possible */
9423 	ufshcd_hba_vreg_set_lpm(hba);
9424 	return ret;
9425 }
9426 
9427 #ifdef CONFIG_PM
9428 /**
9429  * ufshcd_resume - helper function for resume operations
9430  * @hba: per adapter instance
9431  *
9432  * This function basically turns on the regulators, clocks and
9433  * irqs of the hba.
9434  *
9435  * Returns 0 for success and non-zero for failure
9436  */
9437 static int ufshcd_resume(struct ufs_hba *hba)
9438 {
9439 	int ret;
9440 
9441 	if (!hba->is_powered)
9442 		return 0;
9443 
9444 	ufshcd_hba_vreg_set_hpm(hba);
9445 	ret = ufshcd_vreg_set_hpm(hba);
9446 	if (ret)
9447 		goto out;
9448 
9449 	/* Make sure clocks are enabled before accessing controller */
9450 	ret = ufshcd_setup_clocks(hba, true);
9451 	if (ret)
9452 		goto disable_vreg;
9453 
9454 	/* enable the host irq as host controller would be active soon */
9455 	ufshcd_enable_irq(hba);
9456 	goto out;
9457 
9458 disable_vreg:
9459 	ufshcd_vreg_set_lpm(hba);
9460 out:
9461 	if (ret)
9462 		ufshcd_update_evt_hist(hba, UFS_EVT_RESUME_ERR, (u32)ret);
9463 	return ret;
9464 }
9465 #endif /* CONFIG_PM */
9466 
9467 #ifdef CONFIG_PM_SLEEP
9468 /**
9469  * ufshcd_system_suspend - system suspend callback
9470  * @dev: Device associated with the UFS controller.
9471  *
9472  * Executed before putting the system into a sleep state in which the contents
9473  * of main memory are preserved.
9474  *
9475  * Returns 0 for success and non-zero for failure
9476  */
9477 int ufshcd_system_suspend(struct device *dev)
9478 {
9479 	struct ufs_hba *hba = dev_get_drvdata(dev);
9480 	int ret = 0;
9481 	ktime_t start = ktime_get();
9482 
9483 	if (pm_runtime_suspended(hba->dev))
9484 		goto out;
9485 
9486 	ret = ufshcd_suspend(hba);
9487 out:
9488 	trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
9489 		ktime_to_us(ktime_sub(ktime_get(), start)),
9490 		hba->curr_dev_pwr_mode, hba->uic_link_state);
9491 	return ret;
9492 }
9493 EXPORT_SYMBOL(ufshcd_system_suspend);
9494 
9495 /**
9496  * ufshcd_system_resume - system resume callback
9497  * @dev: Device associated with the UFS controller.
9498  *
9499  * Executed after waking the system up from a sleep state in which the contents
9500  * of main memory were preserved.
9501  *
9502  * Returns 0 for success and non-zero for failure
9503  */
9504 int ufshcd_system_resume(struct device *dev)
9505 {
9506 	struct ufs_hba *hba = dev_get_drvdata(dev);
9507 	ktime_t start = ktime_get();
9508 	int ret = 0;
9509 
9510 	if (pm_runtime_suspended(hba->dev))
9511 		goto out;
9512 
9513 	ret = ufshcd_resume(hba);
9514 
9515 out:
9516 	trace_ufshcd_system_resume(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 
9520 	return ret;
9521 }
9522 EXPORT_SYMBOL(ufshcd_system_resume);
9523 #endif /* CONFIG_PM_SLEEP */
9524 
9525 #ifdef CONFIG_PM
9526 /**
9527  * ufshcd_runtime_suspend - runtime suspend callback
9528  * @dev: Device associated with the UFS controller.
9529  *
9530  * Check the description of ufshcd_suspend() function for more details.
9531  *
9532  * Returns 0 for success and non-zero for failure
9533  */
9534 int ufshcd_runtime_suspend(struct device *dev)
9535 {
9536 	struct ufs_hba *hba = dev_get_drvdata(dev);
9537 	int ret;
9538 	ktime_t start = ktime_get();
9539 
9540 	ret = ufshcd_suspend(hba);
9541 
9542 	trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
9543 		ktime_to_us(ktime_sub(ktime_get(), start)),
9544 		hba->curr_dev_pwr_mode, hba->uic_link_state);
9545 	return ret;
9546 }
9547 EXPORT_SYMBOL(ufshcd_runtime_suspend);
9548 
9549 /**
9550  * ufshcd_runtime_resume - runtime resume routine
9551  * @dev: Device associated with the UFS controller.
9552  *
9553  * This function basically brings controller
9554  * to active state. Following operations are done in this function:
9555  *
9556  * 1. Turn on all the controller related clocks
9557  * 2. Turn ON VCC rail
9558  */
9559 int ufshcd_runtime_resume(struct device *dev)
9560 {
9561 	struct ufs_hba *hba = dev_get_drvdata(dev);
9562 	int ret;
9563 	ktime_t start = ktime_get();
9564 
9565 	ret = ufshcd_resume(hba);
9566 
9567 	trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
9568 		ktime_to_us(ktime_sub(ktime_get(), start)),
9569 		hba->curr_dev_pwr_mode, hba->uic_link_state);
9570 	return ret;
9571 }
9572 EXPORT_SYMBOL(ufshcd_runtime_resume);
9573 #endif /* CONFIG_PM */
9574 
9575 /**
9576  * ufshcd_shutdown - shutdown routine
9577  * @hba: per adapter instance
9578  *
9579  * This function would turn off both UFS device and UFS hba
9580  * regulators. It would also disable clocks.
9581  *
9582  * Returns 0 always to allow force shutdown even in case of errors.
9583  */
9584 int ufshcd_shutdown(struct ufs_hba *hba)
9585 {
9586 	if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
9587 		ufshcd_suspend(hba);
9588 
9589 	hba->is_powered = false;
9590 	/* allow force shutdown even in case of errors */
9591 	return 0;
9592 }
9593 EXPORT_SYMBOL(ufshcd_shutdown);
9594 
9595 /**
9596  * ufshcd_remove - de-allocate SCSI host and host memory space
9597  *		data structure memory
9598  * @hba: per adapter instance
9599  */
9600 void ufshcd_remove(struct ufs_hba *hba)
9601 {
9602 	if (hba->ufs_device_wlun)
9603 		ufshcd_rpm_get_sync(hba);
9604 	ufs_hwmon_remove(hba);
9605 	ufs_bsg_remove(hba);
9606 	ufshpb_remove(hba);
9607 	ufs_sysfs_remove_nodes(hba->dev);
9608 	blk_mq_destroy_queue(hba->tmf_queue);
9609 	blk_put_queue(hba->tmf_queue);
9610 	blk_mq_free_tag_set(&hba->tmf_tag_set);
9611 	scsi_remove_host(hba->host);
9612 	/* disable interrupts */
9613 	ufshcd_disable_intr(hba, hba->intr_mask);
9614 	ufshcd_hba_stop(hba);
9615 	ufshcd_hba_exit(hba);
9616 }
9617 EXPORT_SYMBOL_GPL(ufshcd_remove);
9618 
9619 /**
9620  * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
9621  * @hba: pointer to Host Bus Adapter (HBA)
9622  */
9623 void ufshcd_dealloc_host(struct ufs_hba *hba)
9624 {
9625 	scsi_host_put(hba->host);
9626 }
9627 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
9628 
9629 /**
9630  * ufshcd_set_dma_mask - Set dma mask based on the controller
9631  *			 addressing capability
9632  * @hba: per adapter instance
9633  *
9634  * Returns 0 for success, non-zero for failure
9635  */
9636 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
9637 {
9638 	if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
9639 		if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
9640 			return 0;
9641 	}
9642 	return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
9643 }
9644 
9645 /**
9646  * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
9647  * @dev: pointer to device handle
9648  * @hba_handle: driver private handle
9649  * Returns 0 on success, non-zero value on failure
9650  */
9651 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
9652 {
9653 	struct Scsi_Host *host;
9654 	struct ufs_hba *hba;
9655 	int err = 0;
9656 
9657 	if (!dev) {
9658 		dev_err(dev,
9659 		"Invalid memory reference for dev is NULL\n");
9660 		err = -ENODEV;
9661 		goto out_error;
9662 	}
9663 
9664 	host = scsi_host_alloc(&ufshcd_driver_template,
9665 				sizeof(struct ufs_hba));
9666 	if (!host) {
9667 		dev_err(dev, "scsi_host_alloc failed\n");
9668 		err = -ENOMEM;
9669 		goto out_error;
9670 	}
9671 	host->nr_maps = HCTX_TYPE_POLL + 1;
9672 	hba = shost_priv(host);
9673 	hba->host = host;
9674 	hba->dev = dev;
9675 	hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
9676 	hba->nop_out_timeout = NOP_OUT_TIMEOUT;
9677 	INIT_LIST_HEAD(&hba->clk_list_head);
9678 	spin_lock_init(&hba->outstanding_lock);
9679 
9680 	*hba_handle = hba;
9681 
9682 out_error:
9683 	return err;
9684 }
9685 EXPORT_SYMBOL(ufshcd_alloc_host);
9686 
9687 /* This function exists because blk_mq_alloc_tag_set() requires this. */
9688 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx,
9689 				     const struct blk_mq_queue_data *qd)
9690 {
9691 	WARN_ON_ONCE(true);
9692 	return BLK_STS_NOTSUPP;
9693 }
9694 
9695 static const struct blk_mq_ops ufshcd_tmf_ops = {
9696 	.queue_rq = ufshcd_queue_tmf,
9697 };
9698 
9699 /**
9700  * ufshcd_init - Driver initialization routine
9701  * @hba: per-adapter instance
9702  * @mmio_base: base register address
9703  * @irq: Interrupt line of device
9704  * Returns 0 on success, non-zero value on failure
9705  */
9706 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
9707 {
9708 	int err;
9709 	struct Scsi_Host *host = hba->host;
9710 	struct device *dev = hba->dev;
9711 	char eh_wq_name[sizeof("ufs_eh_wq_00")];
9712 
9713 	/*
9714 	 * dev_set_drvdata() must be called before any callbacks are registered
9715 	 * that use dev_get_drvdata() (frequency scaling, clock scaling, hwmon,
9716 	 * sysfs).
9717 	 */
9718 	dev_set_drvdata(dev, hba);
9719 
9720 	if (!mmio_base) {
9721 		dev_err(hba->dev,
9722 		"Invalid memory reference for mmio_base is NULL\n");
9723 		err = -ENODEV;
9724 		goto out_error;
9725 	}
9726 
9727 	hba->mmio_base = mmio_base;
9728 	hba->irq = irq;
9729 	hba->vps = &ufs_hba_vps;
9730 
9731 	err = ufshcd_hba_init(hba);
9732 	if (err)
9733 		goto out_error;
9734 
9735 	/* Read capabilities registers */
9736 	err = ufshcd_hba_capabilities(hba);
9737 	if (err)
9738 		goto out_disable;
9739 
9740 	/* Get UFS version supported by the controller */
9741 	hba->ufs_version = ufshcd_get_ufs_version(hba);
9742 
9743 	/* Get Interrupt bit mask per version */
9744 	hba->intr_mask = ufshcd_get_intr_mask(hba);
9745 
9746 	err = ufshcd_set_dma_mask(hba);
9747 	if (err) {
9748 		dev_err(hba->dev, "set dma mask failed\n");
9749 		goto out_disable;
9750 	}
9751 
9752 	/* Allocate memory for host memory space */
9753 	err = ufshcd_memory_alloc(hba);
9754 	if (err) {
9755 		dev_err(hba->dev, "Memory allocation failed\n");
9756 		goto out_disable;
9757 	}
9758 
9759 	/* Configure LRB */
9760 	ufshcd_host_memory_configure(hba);
9761 
9762 	host->can_queue = hba->nutrs - UFSHCD_NUM_RESERVED;
9763 	host->cmd_per_lun = hba->nutrs - UFSHCD_NUM_RESERVED;
9764 	host->max_id = UFSHCD_MAX_ID;
9765 	host->max_lun = UFS_MAX_LUNS;
9766 	host->max_channel = UFSHCD_MAX_CHANNEL;
9767 	host->unique_id = host->host_no;
9768 	host->max_cmd_len = UFS_CDB_SIZE;
9769 
9770 	hba->max_pwr_info.is_valid = false;
9771 
9772 	/* Initialize work queues */
9773 	snprintf(eh_wq_name, sizeof(eh_wq_name), "ufs_eh_wq_%d",
9774 		 hba->host->host_no);
9775 	hba->eh_wq = create_singlethread_workqueue(eh_wq_name);
9776 	if (!hba->eh_wq) {
9777 		dev_err(hba->dev, "%s: failed to create eh workqueue\n",
9778 			__func__);
9779 		err = -ENOMEM;
9780 		goto out_disable;
9781 	}
9782 	INIT_WORK(&hba->eh_work, ufshcd_err_handler);
9783 	INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
9784 
9785 	sema_init(&hba->host_sem, 1);
9786 
9787 	/* Initialize UIC command mutex */
9788 	mutex_init(&hba->uic_cmd_mutex);
9789 
9790 	/* Initialize mutex for device management commands */
9791 	mutex_init(&hba->dev_cmd.lock);
9792 
9793 	/* Initialize mutex for exception event control */
9794 	mutex_init(&hba->ee_ctrl_mutex);
9795 
9796 	init_rwsem(&hba->clk_scaling_lock);
9797 
9798 	ufshcd_init_clk_gating(hba);
9799 
9800 	ufshcd_init_clk_scaling(hba);
9801 
9802 	/*
9803 	 * In order to avoid any spurious interrupt immediately after
9804 	 * registering UFS controller interrupt handler, clear any pending UFS
9805 	 * interrupt status and disable all the UFS interrupts.
9806 	 */
9807 	ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
9808 		      REG_INTERRUPT_STATUS);
9809 	ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
9810 	/*
9811 	 * Make sure that UFS interrupts are disabled and any pending interrupt
9812 	 * status is cleared before registering UFS interrupt handler.
9813 	 */
9814 	mb();
9815 
9816 	/* IRQ registration */
9817 	err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
9818 	if (err) {
9819 		dev_err(hba->dev, "request irq failed\n");
9820 		goto out_disable;
9821 	} else {
9822 		hba->is_irq_enabled = true;
9823 	}
9824 
9825 	err = scsi_add_host(host, hba->dev);
9826 	if (err) {
9827 		dev_err(hba->dev, "scsi_add_host failed\n");
9828 		goto out_disable;
9829 	}
9830 
9831 	hba->tmf_tag_set = (struct blk_mq_tag_set) {
9832 		.nr_hw_queues	= 1,
9833 		.queue_depth	= hba->nutmrs,
9834 		.ops		= &ufshcd_tmf_ops,
9835 		.flags		= BLK_MQ_F_NO_SCHED,
9836 	};
9837 	err = blk_mq_alloc_tag_set(&hba->tmf_tag_set);
9838 	if (err < 0)
9839 		goto out_remove_scsi_host;
9840 	hba->tmf_queue = blk_mq_init_queue(&hba->tmf_tag_set);
9841 	if (IS_ERR(hba->tmf_queue)) {
9842 		err = PTR_ERR(hba->tmf_queue);
9843 		goto free_tmf_tag_set;
9844 	}
9845 	hba->tmf_rqs = devm_kcalloc(hba->dev, hba->nutmrs,
9846 				    sizeof(*hba->tmf_rqs), GFP_KERNEL);
9847 	if (!hba->tmf_rqs) {
9848 		err = -ENOMEM;
9849 		goto free_tmf_queue;
9850 	}
9851 
9852 	/* Reset the attached device */
9853 	ufshcd_device_reset(hba);
9854 
9855 	ufshcd_init_crypto(hba);
9856 
9857 	/* Host controller enable */
9858 	err = ufshcd_hba_enable(hba);
9859 	if (err) {
9860 		dev_err(hba->dev, "Host controller enable failed\n");
9861 		ufshcd_print_evt_hist(hba);
9862 		ufshcd_print_host_state(hba);
9863 		goto free_tmf_queue;
9864 	}
9865 
9866 	/*
9867 	 * Set the default power management level for runtime and system PM.
9868 	 * Default power saving mode is to keep UFS link in Hibern8 state
9869 	 * and UFS device in sleep state.
9870 	 */
9871 	hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9872 						UFS_SLEEP_PWR_MODE,
9873 						UIC_LINK_HIBERN8_STATE);
9874 	hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9875 						UFS_SLEEP_PWR_MODE,
9876 						UIC_LINK_HIBERN8_STATE);
9877 
9878 	INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work,
9879 			  ufshcd_rpm_dev_flush_recheck_work);
9880 
9881 	/* Set the default auto-hiberate idle timer value to 150 ms */
9882 	if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
9883 		hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
9884 			    FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
9885 	}
9886 
9887 	/* Hold auto suspend until async scan completes */
9888 	pm_runtime_get_sync(dev);
9889 	atomic_set(&hba->scsi_block_reqs_cnt, 0);
9890 	/*
9891 	 * We are assuming that device wasn't put in sleep/power-down
9892 	 * state exclusively during the boot stage before kernel.
9893 	 * This assumption helps avoid doing link startup twice during
9894 	 * ufshcd_probe_hba().
9895 	 */
9896 	ufshcd_set_ufs_dev_active(hba);
9897 
9898 	async_schedule(ufshcd_async_scan, hba);
9899 	ufs_sysfs_add_nodes(hba->dev);
9900 
9901 	device_enable_async_suspend(dev);
9902 	return 0;
9903 
9904 free_tmf_queue:
9905 	blk_mq_destroy_queue(hba->tmf_queue);
9906 	blk_put_queue(hba->tmf_queue);
9907 free_tmf_tag_set:
9908 	blk_mq_free_tag_set(&hba->tmf_tag_set);
9909 out_remove_scsi_host:
9910 	scsi_remove_host(hba->host);
9911 out_disable:
9912 	hba->is_irq_enabled = false;
9913 	ufshcd_hba_exit(hba);
9914 out_error:
9915 	return err;
9916 }
9917 EXPORT_SYMBOL_GPL(ufshcd_init);
9918 
9919 void ufshcd_resume_complete(struct device *dev)
9920 {
9921 	struct ufs_hba *hba = dev_get_drvdata(dev);
9922 
9923 	if (hba->complete_put) {
9924 		ufshcd_rpm_put(hba);
9925 		hba->complete_put = false;
9926 	}
9927 }
9928 EXPORT_SYMBOL_GPL(ufshcd_resume_complete);
9929 
9930 static bool ufshcd_rpm_ok_for_spm(struct ufs_hba *hba)
9931 {
9932 	struct device *dev = &hba->ufs_device_wlun->sdev_gendev;
9933 	enum ufs_dev_pwr_mode dev_pwr_mode;
9934 	enum uic_link_state link_state;
9935 	unsigned long flags;
9936 	bool res;
9937 
9938 	spin_lock_irqsave(&dev->power.lock, flags);
9939 	dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl);
9940 	link_state = ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl);
9941 	res = pm_runtime_suspended(dev) &&
9942 	      hba->curr_dev_pwr_mode == dev_pwr_mode &&
9943 	      hba->uic_link_state == link_state &&
9944 	      !hba->dev_info.b_rpm_dev_flush_capable;
9945 	spin_unlock_irqrestore(&dev->power.lock, flags);
9946 
9947 	return res;
9948 }
9949 
9950 int __ufshcd_suspend_prepare(struct device *dev, bool rpm_ok_for_spm)
9951 {
9952 	struct ufs_hba *hba = dev_get_drvdata(dev);
9953 	int ret;
9954 
9955 	/*
9956 	 * SCSI assumes that runtime-pm and system-pm for scsi drivers
9957 	 * are same. And it doesn't wake up the device for system-suspend
9958 	 * if it's runtime suspended. But ufs doesn't follow that.
9959 	 * Refer ufshcd_resume_complete()
9960 	 */
9961 	if (hba->ufs_device_wlun) {
9962 		/* Prevent runtime suspend */
9963 		ufshcd_rpm_get_noresume(hba);
9964 		/*
9965 		 * Check if already runtime suspended in same state as system
9966 		 * suspend would be.
9967 		 */
9968 		if (!rpm_ok_for_spm || !ufshcd_rpm_ok_for_spm(hba)) {
9969 			/* RPM state is not ok for SPM, so runtime resume */
9970 			ret = ufshcd_rpm_resume(hba);
9971 			if (ret < 0 && ret != -EACCES) {
9972 				ufshcd_rpm_put(hba);
9973 				return ret;
9974 			}
9975 		}
9976 		hba->complete_put = true;
9977 	}
9978 	return 0;
9979 }
9980 EXPORT_SYMBOL_GPL(__ufshcd_suspend_prepare);
9981 
9982 int ufshcd_suspend_prepare(struct device *dev)
9983 {
9984 	return __ufshcd_suspend_prepare(dev, true);
9985 }
9986 EXPORT_SYMBOL_GPL(ufshcd_suspend_prepare);
9987 
9988 #ifdef CONFIG_PM_SLEEP
9989 static int ufshcd_wl_poweroff(struct device *dev)
9990 {
9991 	struct scsi_device *sdev = to_scsi_device(dev);
9992 	struct ufs_hba *hba = shost_priv(sdev->host);
9993 
9994 	__ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
9995 	return 0;
9996 }
9997 #endif
9998 
9999 static int ufshcd_wl_probe(struct device *dev)
10000 {
10001 	struct scsi_device *sdev = to_scsi_device(dev);
10002 
10003 	if (!is_device_wlun(sdev))
10004 		return -ENODEV;
10005 
10006 	blk_pm_runtime_init(sdev->request_queue, dev);
10007 	pm_runtime_set_autosuspend_delay(dev, 0);
10008 	pm_runtime_allow(dev);
10009 
10010 	return  0;
10011 }
10012 
10013 static int ufshcd_wl_remove(struct device *dev)
10014 {
10015 	pm_runtime_forbid(dev);
10016 	return 0;
10017 }
10018 
10019 static const struct dev_pm_ops ufshcd_wl_pm_ops = {
10020 #ifdef CONFIG_PM_SLEEP
10021 	.suspend = ufshcd_wl_suspend,
10022 	.resume = ufshcd_wl_resume,
10023 	.freeze = ufshcd_wl_suspend,
10024 	.thaw = ufshcd_wl_resume,
10025 	.poweroff = ufshcd_wl_poweroff,
10026 	.restore = ufshcd_wl_resume,
10027 #endif
10028 	SET_RUNTIME_PM_OPS(ufshcd_wl_runtime_suspend, ufshcd_wl_runtime_resume, NULL)
10029 };
10030 
10031 /*
10032  * ufs_dev_wlun_template - describes ufs device wlun
10033  * ufs-device wlun - used to send pm commands
10034  * All luns are consumers of ufs-device wlun.
10035  *
10036  * Currently, no sd driver is present for wluns.
10037  * Hence the no specific pm operations are performed.
10038  * With ufs design, SSU should be sent to ufs-device wlun.
10039  * Hence register a scsi driver for ufs wluns only.
10040  */
10041 static struct scsi_driver ufs_dev_wlun_template = {
10042 	.gendrv = {
10043 		.name = "ufs_device_wlun",
10044 		.owner = THIS_MODULE,
10045 		.probe = ufshcd_wl_probe,
10046 		.remove = ufshcd_wl_remove,
10047 		.pm = &ufshcd_wl_pm_ops,
10048 		.shutdown = ufshcd_wl_shutdown,
10049 	},
10050 };
10051 
10052 static int __init ufshcd_core_init(void)
10053 {
10054 	int ret;
10055 
10056 	/* Verify that there are no gaps in struct utp_transfer_cmd_desc. */
10057 	static_assert(sizeof(struct utp_transfer_cmd_desc) ==
10058 		      2 * ALIGNED_UPIU_SIZE +
10059 			      SG_ALL * sizeof(struct ufshcd_sg_entry));
10060 
10061 	ufs_debugfs_init();
10062 
10063 	ret = scsi_register_driver(&ufs_dev_wlun_template.gendrv);
10064 	if (ret)
10065 		ufs_debugfs_exit();
10066 	return ret;
10067 }
10068 
10069 static void __exit ufshcd_core_exit(void)
10070 {
10071 	ufs_debugfs_exit();
10072 	scsi_unregister_driver(&ufs_dev_wlun_template.gendrv);
10073 }
10074 
10075 module_init(ufshcd_core_init);
10076 module_exit(ufshcd_core_exit);
10077 
10078 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
10079 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
10080 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
10081 MODULE_LICENSE("GPL");
10082