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