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