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