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