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