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