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