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