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