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