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