개념 설명 전체 · v6.18.37 / drivers/ufs/core/ufshcd.c

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