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