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