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