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