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