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