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