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