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