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