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