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