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