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