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