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