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