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