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