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