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