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