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