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