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