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