interconnect: qcom: Fix Kconfig indentation
[linux/fpc-iii.git] / drivers / scsi / ufs / ufshcd.c
blobb5966faf3e984190f7af8f60daebcc32cbccf5dc
1 /*
2 * Universal Flash Storage Host controller driver Core
4 * This code is based on drivers/scsi/ufs/ufshcd.c
5 * Copyright (C) 2011-2013 Samsung India Software Operations
6 * Copyright (c) 2013-2016, The Linux Foundation. All rights reserved.
8 * Authors:
9 * Santosh Yaraganavi <santosh.sy@samsung.com>
10 * Vinayak Holikatti <h.vinayak@samsung.com>
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.
16 * See the COPYING file in the top-level directory or visit
17 * <http://www.gnu.org/licenses/gpl-2.0.html>
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.
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.
36 * The Linux Foundation chooses to take subject only to the GPLv2
37 * license terms, and distributes only under these terms.
40 #include <linux/async.h>
41 #include <linux/devfreq.h>
42 #include <linux/nls.h>
43 #include <linux/of.h>
44 #include <linux/bitfield.h>
45 #include "ufshcd.h"
46 #include "ufs_quirks.h"
47 #include "unipro.h"
48 #include "ufs-sysfs.h"
49 #include "ufs_bsg.h"
51 #define CREATE_TRACE_POINTS
52 #include <trace/events/ufs.h>
54 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
55 UTP_TASK_REQ_COMPL |\
56 UFSHCD_ERROR_MASK)
57 /* UIC command timeout, unit: ms */
58 #define UIC_CMD_TIMEOUT 500
60 /* NOP OUT retries waiting for NOP IN response */
61 #define NOP_OUT_RETRIES 10
62 /* Timeout after 30 msecs if NOP OUT hangs without response */
63 #define NOP_OUT_TIMEOUT 30 /* msecs */
65 /* Query request retries */
66 #define QUERY_REQ_RETRIES 3
67 /* Query request timeout */
68 #define QUERY_REQ_TIMEOUT 1500 /* 1.5 seconds */
70 /* Task management command timeout */
71 #define TM_CMD_TIMEOUT 100 /* msecs */
73 /* maximum number of retries for a general UIC command */
74 #define UFS_UIC_COMMAND_RETRIES 3
76 /* maximum number of link-startup retries */
77 #define DME_LINKSTARTUP_RETRIES 3
79 /* Maximum retries for Hibern8 enter */
80 #define UIC_HIBERN8_ENTER_RETRIES 3
82 /* maximum number of reset retries before giving up */
83 #define MAX_HOST_RESET_RETRIES 5
85 /* Expose the flag value from utp_upiu_query.value */
86 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
88 /* Interrupt aggregation default timeout, unit: 40us */
89 #define INT_AGGR_DEF_TO 0x02
91 /* default delay of autosuspend: 2000 ms */
92 #define RPM_AUTOSUSPEND_DELAY_MS 2000
94 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
95 ({ \
96 int _ret; \
97 if (_on) \
98 _ret = ufshcd_enable_vreg(_dev, _vreg); \
99 else \
100 _ret = ufshcd_disable_vreg(_dev, _vreg); \
101 _ret; \
104 #define ufshcd_hex_dump(prefix_str, buf, len) do { \
105 size_t __len = (len); \
106 print_hex_dump(KERN_ERR, prefix_str, \
107 __len > 4 ? DUMP_PREFIX_OFFSET : DUMP_PREFIX_NONE,\
108 16, 4, buf, __len, false); \
109 } while (0)
111 int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len,
112 const char *prefix)
114 u32 *regs;
115 size_t pos;
117 if (offset % 4 != 0 || len % 4 != 0) /* keep readl happy */
118 return -EINVAL;
120 regs = kzalloc(len, GFP_ATOMIC);
121 if (!regs)
122 return -ENOMEM;
124 for (pos = 0; pos < len; pos += 4)
125 regs[pos / 4] = ufshcd_readl(hba, offset + pos);
127 ufshcd_hex_dump(prefix, regs, len);
128 kfree(regs);
130 return 0;
132 EXPORT_SYMBOL_GPL(ufshcd_dump_regs);
134 enum {
135 UFSHCD_MAX_CHANNEL = 0,
136 UFSHCD_MAX_ID = 1,
137 UFSHCD_CMD_PER_LUN = 32,
138 UFSHCD_CAN_QUEUE = 32,
141 /* UFSHCD states */
142 enum {
143 UFSHCD_STATE_RESET,
144 UFSHCD_STATE_ERROR,
145 UFSHCD_STATE_OPERATIONAL,
146 UFSHCD_STATE_EH_SCHEDULED,
149 /* UFSHCD error handling flags */
150 enum {
151 UFSHCD_EH_IN_PROGRESS = (1 << 0),
154 /* UFSHCD UIC layer error flags */
155 enum {
156 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
157 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
158 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
159 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
160 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
161 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
164 #define ufshcd_set_eh_in_progress(h) \
165 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
166 #define ufshcd_eh_in_progress(h) \
167 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
168 #define ufshcd_clear_eh_in_progress(h) \
169 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
171 #define ufshcd_set_ufs_dev_active(h) \
172 ((h)->curr_dev_pwr_mode = UFS_ACTIVE_PWR_MODE)
173 #define ufshcd_set_ufs_dev_sleep(h) \
174 ((h)->curr_dev_pwr_mode = UFS_SLEEP_PWR_MODE)
175 #define ufshcd_set_ufs_dev_poweroff(h) \
176 ((h)->curr_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE)
177 #define ufshcd_is_ufs_dev_active(h) \
178 ((h)->curr_dev_pwr_mode == UFS_ACTIVE_PWR_MODE)
179 #define ufshcd_is_ufs_dev_sleep(h) \
180 ((h)->curr_dev_pwr_mode == UFS_SLEEP_PWR_MODE)
181 #define ufshcd_is_ufs_dev_poweroff(h) \
182 ((h)->curr_dev_pwr_mode == UFS_POWERDOWN_PWR_MODE)
184 struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
185 {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
186 {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
187 {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
188 {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
189 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
190 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
193 static inline enum ufs_dev_pwr_mode
194 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
196 return ufs_pm_lvl_states[lvl].dev_state;
199 static inline enum uic_link_state
200 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
202 return ufs_pm_lvl_states[lvl].link_state;
205 static inline enum ufs_pm_level
206 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
207 enum uic_link_state link_state)
209 enum ufs_pm_level lvl;
211 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
212 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
213 (ufs_pm_lvl_states[lvl].link_state == link_state))
214 return lvl;
217 /* if no match found, return the level 0 */
218 return UFS_PM_LVL_0;
221 static struct ufs_dev_fix ufs_fixups[] = {
222 /* UFS cards deviations table */
223 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
224 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
225 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
226 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS),
227 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
228 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE),
229 UFS_FIX(UFS_VENDOR_TOSHIBA, UFS_ANY_MODEL,
230 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
231 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9C8KBADG",
232 UFS_DEVICE_QUIRK_PA_TACTIVATE),
233 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9D8KBADG",
234 UFS_DEVICE_QUIRK_PA_TACTIVATE),
235 UFS_FIX(UFS_VENDOR_SKHYNIX, UFS_ANY_MODEL,
236 UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME),
237 UFS_FIX(UFS_VENDOR_SKHYNIX, "hB8aL1" /*H28U62301AMR*/,
238 UFS_DEVICE_QUIRK_HOST_VS_DEBUGSAVECONFIGTIME),
240 END_FIX
243 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba);
244 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
245 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
246 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
247 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
248 static void ufshcd_hba_exit(struct ufs_hba *hba);
249 static int ufshcd_probe_hba(struct ufs_hba *hba);
250 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
251 bool skip_ref_clk);
252 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
253 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba);
254 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba);
255 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
256 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
257 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
258 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
259 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba);
260 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up);
261 static irqreturn_t ufshcd_intr(int irq, void *__hba);
262 static int ufshcd_change_power_mode(struct ufs_hba *hba,
263 struct ufs_pa_layer_attr *pwr_mode);
264 static inline bool ufshcd_valid_tag(struct ufs_hba *hba, int tag)
266 return tag >= 0 && tag < hba->nutrs;
269 static inline int ufshcd_enable_irq(struct ufs_hba *hba)
271 int ret = 0;
273 if (!hba->is_irq_enabled) {
274 ret = request_irq(hba->irq, ufshcd_intr, IRQF_SHARED, UFSHCD,
275 hba);
276 if (ret)
277 dev_err(hba->dev, "%s: request_irq failed, ret=%d\n",
278 __func__, ret);
279 hba->is_irq_enabled = true;
282 return ret;
285 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
287 if (hba->is_irq_enabled) {
288 free_irq(hba->irq, hba);
289 hba->is_irq_enabled = false;
293 static void ufshcd_scsi_unblock_requests(struct ufs_hba *hba)
295 if (atomic_dec_and_test(&hba->scsi_block_reqs_cnt))
296 scsi_unblock_requests(hba->host);
299 static void ufshcd_scsi_block_requests(struct ufs_hba *hba)
301 if (atomic_inc_return(&hba->scsi_block_reqs_cnt) == 1)
302 scsi_block_requests(hba->host);
305 static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba, unsigned int tag,
306 const char *str)
308 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
310 trace_ufshcd_upiu(dev_name(hba->dev), str, &rq->header, &rq->sc.cdb);
313 static void ufshcd_add_query_upiu_trace(struct ufs_hba *hba, unsigned int tag,
314 const char *str)
316 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
318 trace_ufshcd_upiu(dev_name(hba->dev), str, &rq->header, &rq->qr);
321 static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag,
322 const char *str)
324 int off = (int)tag - hba->nutrs;
325 struct utp_task_req_desc *descp = &hba->utmrdl_base_addr[off];
327 trace_ufshcd_upiu(dev_name(hba->dev), str, &descp->req_header,
328 &descp->input_param1);
331 static void ufshcd_add_command_trace(struct ufs_hba *hba,
332 unsigned int tag, const char *str)
334 sector_t lba = -1;
335 u8 opcode = 0;
336 u32 intr, doorbell;
337 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
338 int transfer_len = -1;
340 if (!trace_ufshcd_command_enabled()) {
341 /* trace UPIU W/O tracing command */
342 if (lrbp->cmd)
343 ufshcd_add_cmd_upiu_trace(hba, tag, str);
344 return;
347 if (lrbp->cmd) { /* data phase exists */
348 /* trace UPIU also */
349 ufshcd_add_cmd_upiu_trace(hba, tag, str);
350 opcode = (u8)(*lrbp->cmd->cmnd);
351 if ((opcode == READ_10) || (opcode == WRITE_10)) {
353 * Currently we only fully trace read(10) and write(10)
354 * commands
356 if (lrbp->cmd->request && lrbp->cmd->request->bio)
357 lba =
358 lrbp->cmd->request->bio->bi_iter.bi_sector;
359 transfer_len = be32_to_cpu(
360 lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
364 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
365 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
366 trace_ufshcd_command(dev_name(hba->dev), str, tag,
367 doorbell, transfer_len, intr, lba, opcode);
370 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
372 struct ufs_clk_info *clki;
373 struct list_head *head = &hba->clk_list_head;
375 if (list_empty(head))
376 return;
378 list_for_each_entry(clki, head, list) {
379 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
380 clki->max_freq)
381 dev_err(hba->dev, "clk: %s, rate: %u\n",
382 clki->name, clki->curr_freq);
386 static void ufshcd_print_err_hist(struct ufs_hba *hba,
387 struct ufs_err_reg_hist *err_hist,
388 char *err_name)
390 int i;
391 bool found = false;
393 for (i = 0; i < UFS_ERR_REG_HIST_LENGTH; i++) {
394 int p = (i + err_hist->pos) % UFS_ERR_REG_HIST_LENGTH;
396 if (err_hist->reg[p] == 0)
397 continue;
398 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, p,
399 err_hist->reg[p], ktime_to_us(err_hist->tstamp[p]));
400 found = true;
403 if (!found)
404 dev_err(hba->dev, "No record of %s errors\n", err_name);
407 static void ufshcd_print_host_regs(struct ufs_hba *hba)
409 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
410 dev_err(hba->dev, "hba->ufs_version = 0x%x, hba->capabilities = 0x%x\n",
411 hba->ufs_version, hba->capabilities);
412 dev_err(hba->dev,
413 "hba->outstanding_reqs = 0x%x, hba->outstanding_tasks = 0x%x\n",
414 (u32)hba->outstanding_reqs, (u32)hba->outstanding_tasks);
415 dev_err(hba->dev,
416 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt = %d\n",
417 ktime_to_us(hba->ufs_stats.last_hibern8_exit_tstamp),
418 hba->ufs_stats.hibern8_exit_cnt);
420 ufshcd_print_err_hist(hba, &hba->ufs_stats.pa_err, "pa_err");
421 ufshcd_print_err_hist(hba, &hba->ufs_stats.dl_err, "dl_err");
422 ufshcd_print_err_hist(hba, &hba->ufs_stats.nl_err, "nl_err");
423 ufshcd_print_err_hist(hba, &hba->ufs_stats.tl_err, "tl_err");
424 ufshcd_print_err_hist(hba, &hba->ufs_stats.dme_err, "dme_err");
425 ufshcd_print_err_hist(hba, &hba->ufs_stats.auto_hibern8_err,
426 "auto_hibern8_err");
427 ufshcd_print_err_hist(hba, &hba->ufs_stats.fatal_err, "fatal_err");
428 ufshcd_print_err_hist(hba, &hba->ufs_stats.link_startup_err,
429 "link_startup_fail");
430 ufshcd_print_err_hist(hba, &hba->ufs_stats.resume_err, "resume_fail");
431 ufshcd_print_err_hist(hba, &hba->ufs_stats.suspend_err,
432 "suspend_fail");
433 ufshcd_print_err_hist(hba, &hba->ufs_stats.dev_reset, "dev_reset");
434 ufshcd_print_err_hist(hba, &hba->ufs_stats.host_reset, "host_reset");
435 ufshcd_print_err_hist(hba, &hba->ufs_stats.task_abort, "task_abort");
437 ufshcd_print_clk_freqs(hba);
439 if (hba->vops && hba->vops->dbg_register_dump)
440 hba->vops->dbg_register_dump(hba);
443 static
444 void ufshcd_print_trs(struct ufs_hba *hba, unsigned long bitmap, bool pr_prdt)
446 struct ufshcd_lrb *lrbp;
447 int prdt_length;
448 int tag;
450 for_each_set_bit(tag, &bitmap, hba->nutrs) {
451 lrbp = &hba->lrb[tag];
453 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
454 tag, ktime_to_us(lrbp->issue_time_stamp));
455 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n",
456 tag, ktime_to_us(lrbp->compl_time_stamp));
457 dev_err(hba->dev,
458 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
459 tag, (u64)lrbp->utrd_dma_addr);
461 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
462 sizeof(struct utp_transfer_req_desc));
463 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
464 (u64)lrbp->ucd_req_dma_addr);
465 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
466 sizeof(struct utp_upiu_req));
467 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
468 (u64)lrbp->ucd_rsp_dma_addr);
469 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
470 sizeof(struct utp_upiu_rsp));
472 prdt_length = le16_to_cpu(
473 lrbp->utr_descriptor_ptr->prd_table_length);
474 dev_err(hba->dev,
475 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
476 tag, prdt_length,
477 (u64)lrbp->ucd_prdt_dma_addr);
479 if (pr_prdt)
480 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
481 sizeof(struct ufshcd_sg_entry) * prdt_length);
485 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
487 int tag;
489 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
490 struct utp_task_req_desc *tmrdp = &hba->utmrdl_base_addr[tag];
492 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
493 ufshcd_hex_dump("", tmrdp, sizeof(*tmrdp));
497 static void ufshcd_print_host_state(struct ufs_hba *hba)
499 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
500 dev_err(hba->dev, "lrb in use=0x%lx, outstanding reqs=0x%lx tasks=0x%lx\n",
501 hba->lrb_in_use, hba->outstanding_reqs, hba->outstanding_tasks);
502 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
503 hba->saved_err, hba->saved_uic_err);
504 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
505 hba->curr_dev_pwr_mode, hba->uic_link_state);
506 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
507 hba->pm_op_in_progress, hba->is_sys_suspended);
508 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
509 hba->auto_bkops_enabled, hba->host->host_self_blocked);
510 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
511 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
512 hba->eh_flags, hba->req_abort_count);
513 dev_err(hba->dev, "Host capabilities=0x%x, caps=0x%x\n",
514 hba->capabilities, hba->caps);
515 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
516 hba->dev_quirks);
520 * ufshcd_print_pwr_info - print power params as saved in hba
521 * power info
522 * @hba: per-adapter instance
524 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
526 static const char * const names[] = {
527 "INVALID MODE",
528 "FAST MODE",
529 "SLOW_MODE",
530 "INVALID MODE",
531 "FASTAUTO_MODE",
532 "SLOWAUTO_MODE",
533 "INVALID MODE",
536 dev_err(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
537 __func__,
538 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
539 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
540 names[hba->pwr_info.pwr_rx],
541 names[hba->pwr_info.pwr_tx],
542 hba->pwr_info.hs_rate);
546 * ufshcd_wait_for_register - wait for register value to change
547 * @hba - per-adapter interface
548 * @reg - mmio register offset
549 * @mask - mask to apply to read register value
550 * @val - wait condition
551 * @interval_us - polling interval in microsecs
552 * @timeout_ms - timeout in millisecs
553 * @can_sleep - perform sleep or just spin
555 * Returns -ETIMEDOUT on error, zero on success
557 int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
558 u32 val, unsigned long interval_us,
559 unsigned long timeout_ms, bool can_sleep)
561 int err = 0;
562 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
564 /* ignore bits that we don't intend to wait on */
565 val = val & mask;
567 while ((ufshcd_readl(hba, reg) & mask) != val) {
568 if (can_sleep)
569 usleep_range(interval_us, interval_us + 50);
570 else
571 udelay(interval_us);
572 if (time_after(jiffies, timeout)) {
573 if ((ufshcd_readl(hba, reg) & mask) != val)
574 err = -ETIMEDOUT;
575 break;
579 return err;
583 * ufshcd_get_intr_mask - Get the interrupt bit mask
584 * @hba: Pointer to adapter instance
586 * Returns interrupt bit mask per version
588 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
590 u32 intr_mask = 0;
592 switch (hba->ufs_version) {
593 case UFSHCI_VERSION_10:
594 intr_mask = INTERRUPT_MASK_ALL_VER_10;
595 break;
596 case UFSHCI_VERSION_11:
597 case UFSHCI_VERSION_20:
598 intr_mask = INTERRUPT_MASK_ALL_VER_11;
599 break;
600 case UFSHCI_VERSION_21:
601 default:
602 intr_mask = INTERRUPT_MASK_ALL_VER_21;
603 break;
606 return intr_mask;
610 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
611 * @hba: Pointer to adapter instance
613 * Returns UFSHCI version supported by the controller
615 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
617 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
618 return ufshcd_vops_get_ufs_hci_version(hba);
620 return ufshcd_readl(hba, REG_UFS_VERSION);
624 * ufshcd_is_device_present - Check if any device connected to
625 * the host controller
626 * @hba: pointer to adapter instance
628 * Returns true if device present, false if no device detected
630 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
632 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
633 DEVICE_PRESENT) ? true : false;
637 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
638 * @lrbp: pointer to local command reference block
640 * This function is used to get the OCS field from UTRD
641 * Returns the OCS field in the UTRD
643 static inline int ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
645 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
649 * ufshcd_get_tm_free_slot - get a free slot for task management request
650 * @hba: per adapter instance
651 * @free_slot: pointer to variable with available slot value
653 * Get a free tag and lock it until ufshcd_put_tm_slot() is called.
654 * Returns 0 if free slot is not available, else return 1 with tag value
655 * in @free_slot.
657 static bool ufshcd_get_tm_free_slot(struct ufs_hba *hba, int *free_slot)
659 int tag;
660 bool ret = false;
662 if (!free_slot)
663 goto out;
665 do {
666 tag = find_first_zero_bit(&hba->tm_slots_in_use, hba->nutmrs);
667 if (tag >= hba->nutmrs)
668 goto out;
669 } while (test_and_set_bit_lock(tag, &hba->tm_slots_in_use));
671 *free_slot = tag;
672 ret = true;
673 out:
674 return ret;
677 static inline void ufshcd_put_tm_slot(struct ufs_hba *hba, int slot)
679 clear_bit_unlock(slot, &hba->tm_slots_in_use);
683 * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
684 * @hba: per adapter instance
685 * @pos: position of the bit to be cleared
687 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
689 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
690 ufshcd_writel(hba, (1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
691 else
692 ufshcd_writel(hba, ~(1 << pos),
693 REG_UTP_TRANSFER_REQ_LIST_CLEAR);
697 * ufshcd_utmrl_clear - Clear a bit in UTRMLCLR register
698 * @hba: per adapter instance
699 * @pos: position of the bit to be cleared
701 static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos)
703 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
704 ufshcd_writel(hba, (1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
705 else
706 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
710 * ufshcd_outstanding_req_clear - Clear a bit in outstanding request field
711 * @hba: per adapter instance
712 * @tag: position of the bit to be cleared
714 static inline void ufshcd_outstanding_req_clear(struct ufs_hba *hba, int tag)
716 __clear_bit(tag, &hba->outstanding_reqs);
720 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
721 * @reg: Register value of host controller status
723 * Returns integer, 0 on Success and positive value if failed
725 static inline int ufshcd_get_lists_status(u32 reg)
727 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
731 * ufshcd_get_uic_cmd_result - Get the UIC command result
732 * @hba: Pointer to adapter instance
734 * This function gets the result of UIC command completion
735 * Returns 0 on success, non zero value on error
737 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
739 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
740 MASK_UIC_COMMAND_RESULT;
744 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
745 * @hba: Pointer to adapter instance
747 * This function gets UIC command argument3
748 * Returns 0 on success, non zero value on error
750 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
752 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
756 * ufshcd_get_req_rsp - returns the TR response transaction type
757 * @ucd_rsp_ptr: pointer to response UPIU
759 static inline int
760 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
762 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
766 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
767 * @ucd_rsp_ptr: pointer to response UPIU
769 * This function gets the response status and scsi_status from response UPIU
770 * Returns the response result code.
772 static inline int
773 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
775 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
779 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
780 * from response UPIU
781 * @ucd_rsp_ptr: pointer to response UPIU
783 * Return the data segment length.
785 static inline unsigned int
786 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
788 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
789 MASK_RSP_UPIU_DATA_SEG_LEN;
793 * ufshcd_is_exception_event - Check if the device raised an exception event
794 * @ucd_rsp_ptr: pointer to response UPIU
796 * The function checks if the device raised an exception event indicated in
797 * the Device Information field of response UPIU.
799 * Returns true if exception is raised, false otherwise.
801 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
803 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
804 MASK_RSP_EXCEPTION_EVENT ? true : false;
808 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
809 * @hba: per adapter instance
811 static inline void
812 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
814 ufshcd_writel(hba, INT_AGGR_ENABLE |
815 INT_AGGR_COUNTER_AND_TIMER_RESET,
816 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
820 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
821 * @hba: per adapter instance
822 * @cnt: Interrupt aggregation counter threshold
823 * @tmout: Interrupt aggregation timeout value
825 static inline void
826 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
828 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
829 INT_AGGR_COUNTER_THLD_VAL(cnt) |
830 INT_AGGR_TIMEOUT_VAL(tmout),
831 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
835 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
836 * @hba: per adapter instance
838 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
840 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
844 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
845 * When run-stop registers are set to 1, it indicates the
846 * host controller that it can process the requests
847 * @hba: per adapter instance
849 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
851 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
852 REG_UTP_TASK_REQ_LIST_RUN_STOP);
853 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
854 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
858 * ufshcd_hba_start - Start controller initialization sequence
859 * @hba: per adapter instance
861 static inline void ufshcd_hba_start(struct ufs_hba *hba)
863 ufshcd_writel(hba, CONTROLLER_ENABLE, REG_CONTROLLER_ENABLE);
867 * ufshcd_is_hba_active - Get controller state
868 * @hba: per adapter instance
870 * Returns false if controller is active, true otherwise
872 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
874 return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE)
875 ? false : true;
878 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
880 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
881 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
882 (hba->ufs_version == UFSHCI_VERSION_11))
883 return UFS_UNIPRO_VER_1_41;
884 else
885 return UFS_UNIPRO_VER_1_6;
887 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
889 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
892 * If both host and device support UniPro ver1.6 or later, PA layer
893 * parameters tuning happens during link startup itself.
895 * We can manually tune PA layer parameters if either host or device
896 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
897 * logic simple, we will only do manual tuning if local unipro version
898 * doesn't support ver1.6 or later.
900 if (ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6)
901 return true;
902 else
903 return false;
906 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
908 int ret = 0;
909 struct ufs_clk_info *clki;
910 struct list_head *head = &hba->clk_list_head;
911 ktime_t start = ktime_get();
912 bool clk_state_changed = false;
914 if (list_empty(head))
915 goto out;
917 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
918 if (ret)
919 return ret;
921 list_for_each_entry(clki, head, list) {
922 if (!IS_ERR_OR_NULL(clki->clk)) {
923 if (scale_up && clki->max_freq) {
924 if (clki->curr_freq == clki->max_freq)
925 continue;
927 clk_state_changed = true;
928 ret = clk_set_rate(clki->clk, clki->max_freq);
929 if (ret) {
930 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
931 __func__, clki->name,
932 clki->max_freq, ret);
933 break;
935 trace_ufshcd_clk_scaling(dev_name(hba->dev),
936 "scaled up", clki->name,
937 clki->curr_freq,
938 clki->max_freq);
940 clki->curr_freq = clki->max_freq;
942 } else if (!scale_up && clki->min_freq) {
943 if (clki->curr_freq == clki->min_freq)
944 continue;
946 clk_state_changed = true;
947 ret = clk_set_rate(clki->clk, clki->min_freq);
948 if (ret) {
949 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
950 __func__, clki->name,
951 clki->min_freq, ret);
952 break;
954 trace_ufshcd_clk_scaling(dev_name(hba->dev),
955 "scaled down", clki->name,
956 clki->curr_freq,
957 clki->min_freq);
958 clki->curr_freq = clki->min_freq;
961 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
962 clki->name, clk_get_rate(clki->clk));
965 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
967 out:
968 if (clk_state_changed)
969 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
970 (scale_up ? "up" : "down"),
971 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
972 return ret;
976 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
977 * @hba: per adapter instance
978 * @scale_up: True if scaling up and false if scaling down
980 * Returns true if scaling is required, false otherwise.
982 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
983 bool scale_up)
985 struct ufs_clk_info *clki;
986 struct list_head *head = &hba->clk_list_head;
988 if (list_empty(head))
989 return false;
991 list_for_each_entry(clki, head, list) {
992 if (!IS_ERR_OR_NULL(clki->clk)) {
993 if (scale_up && clki->max_freq) {
994 if (clki->curr_freq == clki->max_freq)
995 continue;
996 return true;
997 } else if (!scale_up && clki->min_freq) {
998 if (clki->curr_freq == clki->min_freq)
999 continue;
1000 return true;
1005 return false;
1008 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
1009 u64 wait_timeout_us)
1011 unsigned long flags;
1012 int ret = 0;
1013 u32 tm_doorbell;
1014 u32 tr_doorbell;
1015 bool timeout = false, do_last_check = false;
1016 ktime_t start;
1018 ufshcd_hold(hba, false);
1019 spin_lock_irqsave(hba->host->host_lock, flags);
1021 * Wait for all the outstanding tasks/transfer requests.
1022 * Verify by checking the doorbell registers are clear.
1024 start = ktime_get();
1025 do {
1026 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
1027 ret = -EBUSY;
1028 goto out;
1031 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1032 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1033 if (!tm_doorbell && !tr_doorbell) {
1034 timeout = false;
1035 break;
1036 } else if (do_last_check) {
1037 break;
1040 spin_unlock_irqrestore(hba->host->host_lock, flags);
1041 schedule();
1042 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1043 wait_timeout_us) {
1044 timeout = true;
1046 * We might have scheduled out for long time so make
1047 * sure to check if doorbells are cleared by this time
1048 * or not.
1050 do_last_check = true;
1052 spin_lock_irqsave(hba->host->host_lock, flags);
1053 } while (tm_doorbell || tr_doorbell);
1055 if (timeout) {
1056 dev_err(hba->dev,
1057 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1058 __func__, tm_doorbell, tr_doorbell);
1059 ret = -EBUSY;
1061 out:
1062 spin_unlock_irqrestore(hba->host->host_lock, flags);
1063 ufshcd_release(hba);
1064 return ret;
1068 * ufshcd_scale_gear - scale up/down UFS gear
1069 * @hba: per adapter instance
1070 * @scale_up: True for scaling up gear and false for scaling down
1072 * Returns 0 for success,
1073 * Returns -EBUSY if scaling can't happen at this time
1074 * Returns non-zero for any other errors
1076 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1078 #define UFS_MIN_GEAR_TO_SCALE_DOWN UFS_HS_G1
1079 int ret = 0;
1080 struct ufs_pa_layer_attr new_pwr_info;
1082 if (scale_up) {
1083 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info.info,
1084 sizeof(struct ufs_pa_layer_attr));
1085 } else {
1086 memcpy(&new_pwr_info, &hba->pwr_info,
1087 sizeof(struct ufs_pa_layer_attr));
1089 if (hba->pwr_info.gear_tx > UFS_MIN_GEAR_TO_SCALE_DOWN
1090 || hba->pwr_info.gear_rx > UFS_MIN_GEAR_TO_SCALE_DOWN) {
1091 /* save the current power mode */
1092 memcpy(&hba->clk_scaling.saved_pwr_info.info,
1093 &hba->pwr_info,
1094 sizeof(struct ufs_pa_layer_attr));
1096 /* scale down gear */
1097 new_pwr_info.gear_tx = UFS_MIN_GEAR_TO_SCALE_DOWN;
1098 new_pwr_info.gear_rx = UFS_MIN_GEAR_TO_SCALE_DOWN;
1102 /* check if the power mode needs to be changed or not? */
1103 ret = ufshcd_change_power_mode(hba, &new_pwr_info);
1105 if (ret)
1106 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1107 __func__, ret,
1108 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1109 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1111 return ret;
1114 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba)
1116 #define DOORBELL_CLR_TOUT_US (1000 * 1000) /* 1 sec */
1117 int ret = 0;
1119 * make sure that there are no outstanding requests when
1120 * clock scaling is in progress
1122 ufshcd_scsi_block_requests(hba);
1123 down_write(&hba->clk_scaling_lock);
1124 if (ufshcd_wait_for_doorbell_clr(hba, DOORBELL_CLR_TOUT_US)) {
1125 ret = -EBUSY;
1126 up_write(&hba->clk_scaling_lock);
1127 ufshcd_scsi_unblock_requests(hba);
1130 return ret;
1133 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba)
1135 up_write(&hba->clk_scaling_lock);
1136 ufshcd_scsi_unblock_requests(hba);
1140 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1141 * @hba: per adapter instance
1142 * @scale_up: True for scaling up and false for scalin down
1144 * Returns 0 for success,
1145 * Returns -EBUSY if scaling can't happen at this time
1146 * Returns non-zero for any other errors
1148 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1150 int ret = 0;
1152 /* let's not get into low power until clock scaling is completed */
1153 ufshcd_hold(hba, false);
1155 ret = ufshcd_clock_scaling_prepare(hba);
1156 if (ret)
1157 return ret;
1159 /* scale down the gear before scaling down clocks */
1160 if (!scale_up) {
1161 ret = ufshcd_scale_gear(hba, false);
1162 if (ret)
1163 goto out;
1166 ret = ufshcd_scale_clks(hba, scale_up);
1167 if (ret) {
1168 if (!scale_up)
1169 ufshcd_scale_gear(hba, true);
1170 goto out;
1173 /* scale up the gear after scaling up clocks */
1174 if (scale_up) {
1175 ret = ufshcd_scale_gear(hba, true);
1176 if (ret) {
1177 ufshcd_scale_clks(hba, false);
1178 goto out;
1182 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1184 out:
1185 ufshcd_clock_scaling_unprepare(hba);
1186 ufshcd_release(hba);
1187 return ret;
1190 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1192 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1193 clk_scaling.suspend_work);
1194 unsigned long irq_flags;
1196 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1197 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1198 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1199 return;
1201 hba->clk_scaling.is_suspended = true;
1202 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1204 __ufshcd_suspend_clkscaling(hba);
1207 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1209 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1210 clk_scaling.resume_work);
1211 unsigned long irq_flags;
1213 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1214 if (!hba->clk_scaling.is_suspended) {
1215 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1216 return;
1218 hba->clk_scaling.is_suspended = false;
1219 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1221 devfreq_resume_device(hba->devfreq);
1224 static int ufshcd_devfreq_target(struct device *dev,
1225 unsigned long *freq, u32 flags)
1227 int ret = 0;
1228 struct ufs_hba *hba = dev_get_drvdata(dev);
1229 ktime_t start;
1230 bool scale_up, sched_clk_scaling_suspend_work = false;
1231 struct list_head *clk_list = &hba->clk_list_head;
1232 struct ufs_clk_info *clki;
1233 unsigned long irq_flags;
1235 if (!ufshcd_is_clkscaling_supported(hba))
1236 return -EINVAL;
1238 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1239 if (ufshcd_eh_in_progress(hba)) {
1240 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1241 return 0;
1244 if (!hba->clk_scaling.active_reqs)
1245 sched_clk_scaling_suspend_work = true;
1247 if (list_empty(clk_list)) {
1248 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1249 goto out;
1252 clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info, list);
1253 scale_up = (*freq == clki->max_freq) ? true : false;
1254 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1255 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1256 ret = 0;
1257 goto out; /* no state change required */
1259 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1261 start = ktime_get();
1262 ret = ufshcd_devfreq_scale(hba, scale_up);
1264 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1265 (scale_up ? "up" : "down"),
1266 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1268 out:
1269 if (sched_clk_scaling_suspend_work)
1270 queue_work(hba->clk_scaling.workq,
1271 &hba->clk_scaling.suspend_work);
1273 return ret;
1277 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1278 struct devfreq_dev_status *stat)
1280 struct ufs_hba *hba = dev_get_drvdata(dev);
1281 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1282 unsigned long flags;
1284 if (!ufshcd_is_clkscaling_supported(hba))
1285 return -EINVAL;
1287 memset(stat, 0, sizeof(*stat));
1289 spin_lock_irqsave(hba->host->host_lock, flags);
1290 if (!scaling->window_start_t)
1291 goto start_window;
1293 if (scaling->is_busy_started)
1294 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
1295 scaling->busy_start_t));
1297 stat->total_time = jiffies_to_usecs((long)jiffies -
1298 (long)scaling->window_start_t);
1299 stat->busy_time = scaling->tot_busy_t;
1300 start_window:
1301 scaling->window_start_t = jiffies;
1302 scaling->tot_busy_t = 0;
1304 if (hba->outstanding_reqs) {
1305 scaling->busy_start_t = ktime_get();
1306 scaling->is_busy_started = true;
1307 } else {
1308 scaling->busy_start_t = 0;
1309 scaling->is_busy_started = false;
1311 spin_unlock_irqrestore(hba->host->host_lock, flags);
1312 return 0;
1315 static struct devfreq_dev_profile ufs_devfreq_profile = {
1316 .polling_ms = 100,
1317 .target = ufshcd_devfreq_target,
1318 .get_dev_status = ufshcd_devfreq_get_dev_status,
1321 static int ufshcd_devfreq_init(struct ufs_hba *hba)
1323 struct list_head *clk_list = &hba->clk_list_head;
1324 struct ufs_clk_info *clki;
1325 struct devfreq *devfreq;
1326 int ret;
1328 /* Skip devfreq if we don't have any clocks in the list */
1329 if (list_empty(clk_list))
1330 return 0;
1332 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1333 dev_pm_opp_add(hba->dev, clki->min_freq, 0);
1334 dev_pm_opp_add(hba->dev, clki->max_freq, 0);
1336 devfreq = devfreq_add_device(hba->dev,
1337 &ufs_devfreq_profile,
1338 DEVFREQ_GOV_SIMPLE_ONDEMAND,
1339 NULL);
1340 if (IS_ERR(devfreq)) {
1341 ret = PTR_ERR(devfreq);
1342 dev_err(hba->dev, "Unable to register with devfreq %d\n", ret);
1344 dev_pm_opp_remove(hba->dev, clki->min_freq);
1345 dev_pm_opp_remove(hba->dev, clki->max_freq);
1346 return ret;
1349 hba->devfreq = devfreq;
1351 return 0;
1354 static void ufshcd_devfreq_remove(struct ufs_hba *hba)
1356 struct list_head *clk_list = &hba->clk_list_head;
1357 struct ufs_clk_info *clki;
1359 if (!hba->devfreq)
1360 return;
1362 devfreq_remove_device(hba->devfreq);
1363 hba->devfreq = NULL;
1365 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1366 dev_pm_opp_remove(hba->dev, clki->min_freq);
1367 dev_pm_opp_remove(hba->dev, clki->max_freq);
1370 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1372 unsigned long flags;
1374 devfreq_suspend_device(hba->devfreq);
1375 spin_lock_irqsave(hba->host->host_lock, flags);
1376 hba->clk_scaling.window_start_t = 0;
1377 spin_unlock_irqrestore(hba->host->host_lock, flags);
1380 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1382 unsigned long flags;
1383 bool suspend = false;
1385 if (!ufshcd_is_clkscaling_supported(hba))
1386 return;
1388 spin_lock_irqsave(hba->host->host_lock, flags);
1389 if (!hba->clk_scaling.is_suspended) {
1390 suspend = true;
1391 hba->clk_scaling.is_suspended = true;
1393 spin_unlock_irqrestore(hba->host->host_lock, flags);
1395 if (suspend)
1396 __ufshcd_suspend_clkscaling(hba);
1399 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1401 unsigned long flags;
1402 bool resume = false;
1404 if (!ufshcd_is_clkscaling_supported(hba))
1405 return;
1407 spin_lock_irqsave(hba->host->host_lock, flags);
1408 if (hba->clk_scaling.is_suspended) {
1409 resume = true;
1410 hba->clk_scaling.is_suspended = false;
1412 spin_unlock_irqrestore(hba->host->host_lock, flags);
1414 if (resume)
1415 devfreq_resume_device(hba->devfreq);
1418 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1419 struct device_attribute *attr, char *buf)
1421 struct ufs_hba *hba = dev_get_drvdata(dev);
1423 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_scaling.is_allowed);
1426 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1427 struct device_attribute *attr, const char *buf, size_t count)
1429 struct ufs_hba *hba = dev_get_drvdata(dev);
1430 u32 value;
1431 int err;
1433 if (kstrtou32(buf, 0, &value))
1434 return -EINVAL;
1436 value = !!value;
1437 if (value == hba->clk_scaling.is_allowed)
1438 goto out;
1440 pm_runtime_get_sync(hba->dev);
1441 ufshcd_hold(hba, false);
1443 cancel_work_sync(&hba->clk_scaling.suspend_work);
1444 cancel_work_sync(&hba->clk_scaling.resume_work);
1446 hba->clk_scaling.is_allowed = value;
1448 if (value) {
1449 ufshcd_resume_clkscaling(hba);
1450 } else {
1451 ufshcd_suspend_clkscaling(hba);
1452 err = ufshcd_devfreq_scale(hba, true);
1453 if (err)
1454 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1455 __func__, err);
1458 ufshcd_release(hba);
1459 pm_runtime_put_sync(hba->dev);
1460 out:
1461 return count;
1464 static void ufshcd_clkscaling_init_sysfs(struct ufs_hba *hba)
1466 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1467 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1468 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1469 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1470 hba->clk_scaling.enable_attr.attr.mode = 0644;
1471 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1472 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1475 static void ufshcd_ungate_work(struct work_struct *work)
1477 int ret;
1478 unsigned long flags;
1479 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1480 clk_gating.ungate_work);
1482 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1484 spin_lock_irqsave(hba->host->host_lock, flags);
1485 if (hba->clk_gating.state == CLKS_ON) {
1486 spin_unlock_irqrestore(hba->host->host_lock, flags);
1487 goto unblock_reqs;
1490 spin_unlock_irqrestore(hba->host->host_lock, flags);
1491 ufshcd_setup_clocks(hba, true);
1493 /* Exit from hibern8 */
1494 if (ufshcd_can_hibern8_during_gating(hba)) {
1495 /* Prevent gating in this path */
1496 hba->clk_gating.is_suspended = true;
1497 if (ufshcd_is_link_hibern8(hba)) {
1498 ret = ufshcd_uic_hibern8_exit(hba);
1499 if (ret)
1500 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1501 __func__, ret);
1502 else
1503 ufshcd_set_link_active(hba);
1505 hba->clk_gating.is_suspended = false;
1507 unblock_reqs:
1508 ufshcd_scsi_unblock_requests(hba);
1512 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1513 * Also, exit from hibern8 mode and set the link as active.
1514 * @hba: per adapter instance
1515 * @async: This indicates whether caller should ungate clocks asynchronously.
1517 int ufshcd_hold(struct ufs_hba *hba, bool async)
1519 int rc = 0;
1520 unsigned long flags;
1522 if (!ufshcd_is_clkgating_allowed(hba))
1523 goto out;
1524 spin_lock_irqsave(hba->host->host_lock, flags);
1525 hba->clk_gating.active_reqs++;
1527 if (ufshcd_eh_in_progress(hba)) {
1528 spin_unlock_irqrestore(hba->host->host_lock, flags);
1529 return 0;
1532 start:
1533 switch (hba->clk_gating.state) {
1534 case CLKS_ON:
1536 * Wait for the ungate work to complete if in progress.
1537 * Though the clocks may be in ON state, the link could
1538 * still be in hibner8 state if hibern8 is allowed
1539 * during clock gating.
1540 * Make sure we exit hibern8 state also in addition to
1541 * clocks being ON.
1543 if (ufshcd_can_hibern8_during_gating(hba) &&
1544 ufshcd_is_link_hibern8(hba)) {
1545 spin_unlock_irqrestore(hba->host->host_lock, flags);
1546 flush_work(&hba->clk_gating.ungate_work);
1547 spin_lock_irqsave(hba->host->host_lock, flags);
1548 goto start;
1550 break;
1551 case REQ_CLKS_OFF:
1552 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1553 hba->clk_gating.state = CLKS_ON;
1554 trace_ufshcd_clk_gating(dev_name(hba->dev),
1555 hba->clk_gating.state);
1556 break;
1559 * If we are here, it means gating work is either done or
1560 * currently running. Hence, fall through to cancel gating
1561 * work and to enable clocks.
1563 /* fallthrough */
1564 case CLKS_OFF:
1565 ufshcd_scsi_block_requests(hba);
1566 hba->clk_gating.state = REQ_CLKS_ON;
1567 trace_ufshcd_clk_gating(dev_name(hba->dev),
1568 hba->clk_gating.state);
1569 queue_work(hba->clk_gating.clk_gating_workq,
1570 &hba->clk_gating.ungate_work);
1572 * fall through to check if we should wait for this
1573 * work to be done or not.
1575 /* fallthrough */
1576 case REQ_CLKS_ON:
1577 if (async) {
1578 rc = -EAGAIN;
1579 hba->clk_gating.active_reqs--;
1580 break;
1583 spin_unlock_irqrestore(hba->host->host_lock, flags);
1584 flush_work(&hba->clk_gating.ungate_work);
1585 /* Make sure state is CLKS_ON before returning */
1586 spin_lock_irqsave(hba->host->host_lock, flags);
1587 goto start;
1588 default:
1589 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1590 __func__, hba->clk_gating.state);
1591 break;
1593 spin_unlock_irqrestore(hba->host->host_lock, flags);
1594 out:
1595 return rc;
1597 EXPORT_SYMBOL_GPL(ufshcd_hold);
1599 static void ufshcd_gate_work(struct work_struct *work)
1601 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1602 clk_gating.gate_work.work);
1603 unsigned long flags;
1605 spin_lock_irqsave(hba->host->host_lock, flags);
1607 * In case you are here to cancel this work the gating state
1608 * would be marked as REQ_CLKS_ON. In this case save time by
1609 * skipping the gating work and exit after changing the clock
1610 * state to CLKS_ON.
1612 if (hba->clk_gating.is_suspended ||
1613 (hba->clk_gating.state != REQ_CLKS_OFF)) {
1614 hba->clk_gating.state = CLKS_ON;
1615 trace_ufshcd_clk_gating(dev_name(hba->dev),
1616 hba->clk_gating.state);
1617 goto rel_lock;
1620 if (hba->clk_gating.active_reqs
1621 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1622 || hba->lrb_in_use || hba->outstanding_tasks
1623 || hba->active_uic_cmd || hba->uic_async_done)
1624 goto rel_lock;
1626 spin_unlock_irqrestore(hba->host->host_lock, flags);
1628 /* put the link into hibern8 mode before turning off clocks */
1629 if (ufshcd_can_hibern8_during_gating(hba)) {
1630 if (ufshcd_uic_hibern8_enter(hba)) {
1631 hba->clk_gating.state = CLKS_ON;
1632 trace_ufshcd_clk_gating(dev_name(hba->dev),
1633 hba->clk_gating.state);
1634 goto out;
1636 ufshcd_set_link_hibern8(hba);
1639 if (!ufshcd_is_link_active(hba))
1640 ufshcd_setup_clocks(hba, false);
1641 else
1642 /* If link is active, device ref_clk can't be switched off */
1643 __ufshcd_setup_clocks(hba, false, true);
1646 * In case you are here to cancel this work the gating state
1647 * would be marked as REQ_CLKS_ON. In this case keep the state
1648 * as REQ_CLKS_ON which would anyway imply that clocks are off
1649 * and a request to turn them on is pending. By doing this way,
1650 * we keep the state machine in tact and this would ultimately
1651 * prevent from doing cancel work multiple times when there are
1652 * new requests arriving before the current cancel work is done.
1654 spin_lock_irqsave(hba->host->host_lock, flags);
1655 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1656 hba->clk_gating.state = CLKS_OFF;
1657 trace_ufshcd_clk_gating(dev_name(hba->dev),
1658 hba->clk_gating.state);
1660 rel_lock:
1661 spin_unlock_irqrestore(hba->host->host_lock, flags);
1662 out:
1663 return;
1666 /* host lock must be held before calling this variant */
1667 static void __ufshcd_release(struct ufs_hba *hba)
1669 if (!ufshcd_is_clkgating_allowed(hba))
1670 return;
1672 hba->clk_gating.active_reqs--;
1674 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended
1675 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1676 || hba->lrb_in_use || hba->outstanding_tasks
1677 || hba->active_uic_cmd || hba->uic_async_done
1678 || ufshcd_eh_in_progress(hba))
1679 return;
1681 hba->clk_gating.state = REQ_CLKS_OFF;
1682 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1683 queue_delayed_work(hba->clk_gating.clk_gating_workq,
1684 &hba->clk_gating.gate_work,
1685 msecs_to_jiffies(hba->clk_gating.delay_ms));
1688 void ufshcd_release(struct ufs_hba *hba)
1690 unsigned long flags;
1692 spin_lock_irqsave(hba->host->host_lock, flags);
1693 __ufshcd_release(hba);
1694 spin_unlock_irqrestore(hba->host->host_lock, flags);
1696 EXPORT_SYMBOL_GPL(ufshcd_release);
1698 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1699 struct device_attribute *attr, char *buf)
1701 struct ufs_hba *hba = dev_get_drvdata(dev);
1703 return snprintf(buf, PAGE_SIZE, "%lu\n", hba->clk_gating.delay_ms);
1706 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1707 struct device_attribute *attr, const char *buf, size_t count)
1709 struct ufs_hba *hba = dev_get_drvdata(dev);
1710 unsigned long flags, value;
1712 if (kstrtoul(buf, 0, &value))
1713 return -EINVAL;
1715 spin_lock_irqsave(hba->host->host_lock, flags);
1716 hba->clk_gating.delay_ms = value;
1717 spin_unlock_irqrestore(hba->host->host_lock, flags);
1718 return count;
1721 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1722 struct device_attribute *attr, char *buf)
1724 struct ufs_hba *hba = dev_get_drvdata(dev);
1726 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_gating.is_enabled);
1729 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1730 struct device_attribute *attr, const char *buf, size_t count)
1732 struct ufs_hba *hba = dev_get_drvdata(dev);
1733 unsigned long flags;
1734 u32 value;
1736 if (kstrtou32(buf, 0, &value))
1737 return -EINVAL;
1739 value = !!value;
1740 if (value == hba->clk_gating.is_enabled)
1741 goto out;
1743 if (value) {
1744 ufshcd_release(hba);
1745 } else {
1746 spin_lock_irqsave(hba->host->host_lock, flags);
1747 hba->clk_gating.active_reqs++;
1748 spin_unlock_irqrestore(hba->host->host_lock, flags);
1751 hba->clk_gating.is_enabled = value;
1752 out:
1753 return count;
1756 static void ufshcd_init_clk_scaling(struct ufs_hba *hba)
1758 char wq_name[sizeof("ufs_clkscaling_00")];
1760 if (!ufshcd_is_clkscaling_supported(hba))
1761 return;
1763 INIT_WORK(&hba->clk_scaling.suspend_work,
1764 ufshcd_clk_scaling_suspend_work);
1765 INIT_WORK(&hba->clk_scaling.resume_work,
1766 ufshcd_clk_scaling_resume_work);
1768 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
1769 hba->host->host_no);
1770 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
1772 ufshcd_clkscaling_init_sysfs(hba);
1775 static void ufshcd_exit_clk_scaling(struct ufs_hba *hba)
1777 if (!ufshcd_is_clkscaling_supported(hba))
1778 return;
1780 destroy_workqueue(hba->clk_scaling.workq);
1781 ufshcd_devfreq_remove(hba);
1784 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1786 char wq_name[sizeof("ufs_clk_gating_00")];
1788 if (!ufshcd_is_clkgating_allowed(hba))
1789 return;
1791 hba->clk_gating.delay_ms = 150;
1792 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
1793 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
1795 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d",
1796 hba->host->host_no);
1797 hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(wq_name,
1798 WQ_MEM_RECLAIM);
1800 hba->clk_gating.is_enabled = true;
1802 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1803 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1804 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1805 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1806 hba->clk_gating.delay_attr.attr.mode = 0644;
1807 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1808 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1810 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
1811 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
1812 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
1813 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
1814 hba->clk_gating.enable_attr.attr.mode = 0644;
1815 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
1816 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1819 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
1821 if (!ufshcd_is_clkgating_allowed(hba))
1822 return;
1823 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1824 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1825 cancel_work_sync(&hba->clk_gating.ungate_work);
1826 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1827 destroy_workqueue(hba->clk_gating.clk_gating_workq);
1830 /* Must be called with host lock acquired */
1831 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
1833 bool queue_resume_work = false;
1835 if (!ufshcd_is_clkscaling_supported(hba))
1836 return;
1838 if (!hba->clk_scaling.active_reqs++)
1839 queue_resume_work = true;
1841 if (!hba->clk_scaling.is_allowed || hba->pm_op_in_progress)
1842 return;
1844 if (queue_resume_work)
1845 queue_work(hba->clk_scaling.workq,
1846 &hba->clk_scaling.resume_work);
1848 if (!hba->clk_scaling.window_start_t) {
1849 hba->clk_scaling.window_start_t = jiffies;
1850 hba->clk_scaling.tot_busy_t = 0;
1851 hba->clk_scaling.is_busy_started = false;
1854 if (!hba->clk_scaling.is_busy_started) {
1855 hba->clk_scaling.busy_start_t = ktime_get();
1856 hba->clk_scaling.is_busy_started = true;
1860 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
1862 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1864 if (!ufshcd_is_clkscaling_supported(hba))
1865 return;
1867 if (!hba->outstanding_reqs && scaling->is_busy_started) {
1868 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
1869 scaling->busy_start_t));
1870 scaling->busy_start_t = 0;
1871 scaling->is_busy_started = false;
1875 * ufshcd_send_command - Send SCSI or device management commands
1876 * @hba: per adapter instance
1877 * @task_tag: Task tag of the command
1879 static inline
1880 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
1882 hba->lrb[task_tag].issue_time_stamp = ktime_get();
1883 hba->lrb[task_tag].compl_time_stamp = ktime_set(0, 0);
1884 ufshcd_clk_scaling_start_busy(hba);
1885 __set_bit(task_tag, &hba->outstanding_reqs);
1886 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1887 /* Make sure that doorbell is committed immediately */
1888 wmb();
1889 ufshcd_add_command_trace(hba, task_tag, "send");
1893 * ufshcd_copy_sense_data - Copy sense data in case of check condition
1894 * @lrbp: pointer to local reference block
1896 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
1898 int len;
1899 if (lrbp->sense_buffer &&
1900 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
1901 int len_to_copy;
1903 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
1904 len_to_copy = min_t(int, UFS_SENSE_SIZE, len);
1906 memcpy(lrbp->sense_buffer, lrbp->ucd_rsp_ptr->sr.sense_data,
1907 len_to_copy);
1912 * ufshcd_copy_query_response() - Copy the Query Response and the data
1913 * descriptor
1914 * @hba: per adapter instance
1915 * @lrbp: pointer to local reference block
1917 static
1918 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1920 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
1922 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
1924 /* Get the descriptor */
1925 if (hba->dev_cmd.query.descriptor &&
1926 lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
1927 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
1928 GENERAL_UPIU_REQUEST_SIZE;
1929 u16 resp_len;
1930 u16 buf_len;
1932 /* data segment length */
1933 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
1934 MASK_QUERY_DATA_SEG_LEN;
1935 buf_len = be16_to_cpu(
1936 hba->dev_cmd.query.request.upiu_req.length);
1937 if (likely(buf_len >= resp_len)) {
1938 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
1939 } else {
1940 dev_warn(hba->dev,
1941 "%s: rsp size %d is bigger than buffer size %d",
1942 __func__, resp_len, buf_len);
1943 return -EINVAL;
1947 return 0;
1951 * ufshcd_hba_capabilities - Read controller capabilities
1952 * @hba: per adapter instance
1954 static inline void ufshcd_hba_capabilities(struct ufs_hba *hba)
1956 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
1958 /* nutrs and nutmrs are 0 based values */
1959 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
1960 hba->nutmrs =
1961 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
1965 * ufshcd_ready_for_uic_cmd - Check if controller is ready
1966 * to accept UIC commands
1967 * @hba: per adapter instance
1968 * Return true on success, else false
1970 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
1972 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
1973 return true;
1974 else
1975 return false;
1979 * ufshcd_get_upmcrs - Get the power mode change request status
1980 * @hba: Pointer to adapter instance
1982 * This function gets the UPMCRS field of HCS register
1983 * Returns value of UPMCRS field
1985 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
1987 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
1991 * ufshcd_dispatch_uic_cmd - Dispatch UIC commands to unipro layers
1992 * @hba: per adapter instance
1993 * @uic_cmd: UIC command
1995 * Mutex must be held.
1997 static inline void
1998 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2000 WARN_ON(hba->active_uic_cmd);
2002 hba->active_uic_cmd = uic_cmd;
2004 /* Write Args */
2005 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2006 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2007 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2009 /* Write UIC Cmd */
2010 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2011 REG_UIC_COMMAND);
2015 * ufshcd_wait_for_uic_cmd - Wait complectioin of UIC command
2016 * @hba: per adapter instance
2017 * @uic_cmd: UIC command
2019 * Must be called with mutex held.
2020 * Returns 0 only if success.
2022 static int
2023 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2025 int ret;
2026 unsigned long flags;
2028 if (wait_for_completion_timeout(&uic_cmd->done,
2029 msecs_to_jiffies(UIC_CMD_TIMEOUT)))
2030 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2031 else
2032 ret = -ETIMEDOUT;
2034 spin_lock_irqsave(hba->host->host_lock, flags);
2035 hba->active_uic_cmd = NULL;
2036 spin_unlock_irqrestore(hba->host->host_lock, flags);
2038 return ret;
2042 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2043 * @hba: per adapter instance
2044 * @uic_cmd: UIC command
2045 * @completion: initialize the completion only if this is set to true
2047 * Identical to ufshcd_send_uic_cmd() expect mutex. Must be called
2048 * with mutex held and host_lock locked.
2049 * Returns 0 only if success.
2051 static int
2052 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
2053 bool completion)
2055 if (!ufshcd_ready_for_uic_cmd(hba)) {
2056 dev_err(hba->dev,
2057 "Controller not ready to accept UIC commands\n");
2058 return -EIO;
2061 if (completion)
2062 init_completion(&uic_cmd->done);
2064 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2066 return 0;
2070 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2071 * @hba: per adapter instance
2072 * @uic_cmd: UIC command
2074 * Returns 0 only if success.
2076 int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2078 int ret;
2079 unsigned long flags;
2081 ufshcd_hold(hba, false);
2082 mutex_lock(&hba->uic_cmd_mutex);
2083 ufshcd_add_delay_before_dme_cmd(hba);
2085 spin_lock_irqsave(hba->host->host_lock, flags);
2086 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
2087 spin_unlock_irqrestore(hba->host->host_lock, flags);
2088 if (!ret)
2089 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2091 mutex_unlock(&hba->uic_cmd_mutex);
2093 ufshcd_release(hba);
2094 return ret;
2098 * ufshcd_map_sg - Map scatter-gather list to prdt
2099 * @hba: per adapter instance
2100 * @lrbp: pointer to local reference block
2102 * Returns 0 in case of success, non-zero value in case of failure
2104 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2106 struct ufshcd_sg_entry *prd_table;
2107 struct scatterlist *sg;
2108 struct scsi_cmnd *cmd;
2109 int sg_segments;
2110 int i;
2112 cmd = lrbp->cmd;
2113 sg_segments = scsi_dma_map(cmd);
2114 if (sg_segments < 0)
2115 return sg_segments;
2117 if (sg_segments) {
2118 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2119 lrbp->utr_descriptor_ptr->prd_table_length =
2120 cpu_to_le16((u16)(sg_segments *
2121 sizeof(struct ufshcd_sg_entry)));
2122 else
2123 lrbp->utr_descriptor_ptr->prd_table_length =
2124 cpu_to_le16((u16) (sg_segments));
2126 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
2128 scsi_for_each_sg(cmd, sg, sg_segments, i) {
2129 prd_table[i].size =
2130 cpu_to_le32(((u32) sg_dma_len(sg))-1);
2131 prd_table[i].base_addr =
2132 cpu_to_le32(lower_32_bits(sg->dma_address));
2133 prd_table[i].upper_addr =
2134 cpu_to_le32(upper_32_bits(sg->dma_address));
2135 prd_table[i].reserved = 0;
2137 } else {
2138 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2141 return 0;
2145 * ufshcd_enable_intr - enable interrupts
2146 * @hba: per adapter instance
2147 * @intrs: interrupt bits
2149 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2151 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2153 if (hba->ufs_version == UFSHCI_VERSION_10) {
2154 u32 rw;
2155 rw = set & INTERRUPT_MASK_RW_VER_10;
2156 set = rw | ((set ^ intrs) & intrs);
2157 } else {
2158 set |= intrs;
2161 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2165 * ufshcd_disable_intr - disable interrupts
2166 * @hba: per adapter instance
2167 * @intrs: interrupt bits
2169 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2171 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2173 if (hba->ufs_version == UFSHCI_VERSION_10) {
2174 u32 rw;
2175 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2176 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2177 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2179 } else {
2180 set &= ~intrs;
2183 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2187 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
2188 * descriptor according to request
2189 * @lrbp: pointer to local reference block
2190 * @upiu_flags: flags required in the header
2191 * @cmd_dir: requests data direction
2193 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
2194 u32 *upiu_flags, enum dma_data_direction cmd_dir)
2196 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2197 u32 data_direction;
2198 u32 dword_0;
2200 if (cmd_dir == DMA_FROM_DEVICE) {
2201 data_direction = UTP_DEVICE_TO_HOST;
2202 *upiu_flags = UPIU_CMD_FLAGS_READ;
2203 } else if (cmd_dir == DMA_TO_DEVICE) {
2204 data_direction = UTP_HOST_TO_DEVICE;
2205 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2206 } else {
2207 data_direction = UTP_NO_DATA_TRANSFER;
2208 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2211 dword_0 = data_direction | (lrbp->command_type
2212 << UPIU_COMMAND_TYPE_OFFSET);
2213 if (lrbp->intr_cmd)
2214 dword_0 |= UTP_REQ_DESC_INT_CMD;
2216 /* Transfer request descriptor header fields */
2217 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2218 /* dword_1 is reserved, hence it is set to 0 */
2219 req_desc->header.dword_1 = 0;
2221 * assigning invalid value for command status. Controller
2222 * updates OCS on command completion, with the command
2223 * status
2225 req_desc->header.dword_2 =
2226 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2227 /* dword_3 is reserved, hence it is set to 0 */
2228 req_desc->header.dword_3 = 0;
2230 req_desc->prd_table_length = 0;
2234 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2235 * for scsi commands
2236 * @lrbp: local reference block pointer
2237 * @upiu_flags: flags
2239 static
2240 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u32 upiu_flags)
2242 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2243 unsigned short cdb_len;
2245 /* command descriptor fields */
2246 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2247 UPIU_TRANSACTION_COMMAND, upiu_flags,
2248 lrbp->lun, lrbp->task_tag);
2249 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2250 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2252 /* Total EHS length and Data segment length will be zero */
2253 ucd_req_ptr->header.dword_2 = 0;
2255 ucd_req_ptr->sc.exp_data_transfer_len =
2256 cpu_to_be32(lrbp->cmd->sdb.length);
2258 cdb_len = min_t(unsigned short, lrbp->cmd->cmd_len, UFS_CDB_SIZE);
2259 memset(ucd_req_ptr->sc.cdb, 0, UFS_CDB_SIZE);
2260 memcpy(ucd_req_ptr->sc.cdb, lrbp->cmd->cmnd, cdb_len);
2262 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2266 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
2267 * for query requsts
2268 * @hba: UFS hba
2269 * @lrbp: local reference block pointer
2270 * @upiu_flags: flags
2272 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2273 struct ufshcd_lrb *lrbp, u32 upiu_flags)
2275 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2276 struct ufs_query *query = &hba->dev_cmd.query;
2277 u16 len = be16_to_cpu(query->request.upiu_req.length);
2279 /* Query request header */
2280 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2281 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2282 lrbp->lun, lrbp->task_tag);
2283 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2284 0, query->request.query_func, 0, 0);
2286 /* Data segment length only need for WRITE_DESC */
2287 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2288 ucd_req_ptr->header.dword_2 =
2289 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2290 else
2291 ucd_req_ptr->header.dword_2 = 0;
2293 /* Copy the Query Request buffer as is */
2294 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2295 QUERY_OSF_SIZE);
2297 /* Copy the Descriptor */
2298 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2299 memcpy(ucd_req_ptr + 1, query->descriptor, len);
2301 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2304 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2306 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2308 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2310 /* command descriptor fields */
2311 ucd_req_ptr->header.dword_0 =
2312 UPIU_HEADER_DWORD(
2313 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2314 /* clear rest of the fields of basic header */
2315 ucd_req_ptr->header.dword_1 = 0;
2316 ucd_req_ptr->header.dword_2 = 0;
2318 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2322 * ufshcd_comp_devman_upiu - UFS Protocol Information Unit(UPIU)
2323 * for Device Management Purposes
2324 * @hba: per adapter instance
2325 * @lrbp: pointer to local reference block
2327 static int ufshcd_comp_devman_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2329 u32 upiu_flags;
2330 int ret = 0;
2332 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
2333 (hba->ufs_version == UFSHCI_VERSION_11))
2334 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2335 else
2336 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2338 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
2339 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2340 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2341 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2342 ufshcd_prepare_utp_nop_upiu(lrbp);
2343 else
2344 ret = -EINVAL;
2346 return ret;
2350 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2351 * for SCSI Purposes
2352 * @hba: per adapter instance
2353 * @lrbp: pointer to local reference block
2355 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2357 u32 upiu_flags;
2358 int ret = 0;
2360 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
2361 (hba->ufs_version == UFSHCI_VERSION_11))
2362 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2363 else
2364 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2366 if (likely(lrbp->cmd)) {
2367 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
2368 lrbp->cmd->sc_data_direction);
2369 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2370 } else {
2371 ret = -EINVAL;
2374 return ret;
2378 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2379 * @upiu_wlun_id: UPIU W-LUN id
2381 * Returns SCSI W-LUN id
2383 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2385 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2389 * ufshcd_queuecommand - main entry point for SCSI requests
2390 * @host: SCSI host pointer
2391 * @cmd: command from SCSI Midlayer
2393 * Returns 0 for success, non-zero in case of failure
2395 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2397 struct ufshcd_lrb *lrbp;
2398 struct ufs_hba *hba;
2399 unsigned long flags;
2400 int tag;
2401 int err = 0;
2403 hba = shost_priv(host);
2405 tag = cmd->request->tag;
2406 if (!ufshcd_valid_tag(hba, tag)) {
2407 dev_err(hba->dev,
2408 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
2409 __func__, tag, cmd, cmd->request);
2410 BUG();
2413 if (!down_read_trylock(&hba->clk_scaling_lock))
2414 return SCSI_MLQUEUE_HOST_BUSY;
2416 spin_lock_irqsave(hba->host->host_lock, flags);
2417 switch (hba->ufshcd_state) {
2418 case UFSHCD_STATE_OPERATIONAL:
2419 break;
2420 case UFSHCD_STATE_EH_SCHEDULED:
2421 case UFSHCD_STATE_RESET:
2422 err = SCSI_MLQUEUE_HOST_BUSY;
2423 goto out_unlock;
2424 case UFSHCD_STATE_ERROR:
2425 set_host_byte(cmd, DID_ERROR);
2426 cmd->scsi_done(cmd);
2427 goto out_unlock;
2428 default:
2429 dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
2430 __func__, hba->ufshcd_state);
2431 set_host_byte(cmd, DID_BAD_TARGET);
2432 cmd->scsi_done(cmd);
2433 goto out_unlock;
2436 /* if error handling is in progress, don't issue commands */
2437 if (ufshcd_eh_in_progress(hba)) {
2438 set_host_byte(cmd, DID_ERROR);
2439 cmd->scsi_done(cmd);
2440 goto out_unlock;
2442 spin_unlock_irqrestore(hba->host->host_lock, flags);
2444 hba->req_abort_count = 0;
2446 /* acquire the tag to make sure device cmds don't use it */
2447 if (test_and_set_bit_lock(tag, &hba->lrb_in_use)) {
2449 * Dev manage command in progress, requeue the command.
2450 * Requeuing the command helps in cases where the request *may*
2451 * find different tag instead of waiting for dev manage command
2452 * completion.
2454 err = SCSI_MLQUEUE_HOST_BUSY;
2455 goto out;
2458 err = ufshcd_hold(hba, true);
2459 if (err) {
2460 err = SCSI_MLQUEUE_HOST_BUSY;
2461 clear_bit_unlock(tag, &hba->lrb_in_use);
2462 goto out;
2464 WARN_ON(hba->clk_gating.state != CLKS_ON);
2466 lrbp = &hba->lrb[tag];
2468 WARN_ON(lrbp->cmd);
2469 lrbp->cmd = cmd;
2470 lrbp->sense_bufflen = UFS_SENSE_SIZE;
2471 lrbp->sense_buffer = cmd->sense_buffer;
2472 lrbp->task_tag = tag;
2473 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2474 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
2475 lrbp->req_abort_skip = false;
2477 ufshcd_comp_scsi_upiu(hba, lrbp);
2479 err = ufshcd_map_sg(hba, lrbp);
2480 if (err) {
2481 lrbp->cmd = NULL;
2482 clear_bit_unlock(tag, &hba->lrb_in_use);
2483 goto out;
2485 /* Make sure descriptors are ready before ringing the doorbell */
2486 wmb();
2488 /* issue command to the controller */
2489 spin_lock_irqsave(hba->host->host_lock, flags);
2490 ufshcd_vops_setup_xfer_req(hba, tag, (lrbp->cmd ? true : false));
2491 ufshcd_send_command(hba, tag);
2492 out_unlock:
2493 spin_unlock_irqrestore(hba->host->host_lock, flags);
2494 out:
2495 up_read(&hba->clk_scaling_lock);
2496 return err;
2499 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2500 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2502 lrbp->cmd = NULL;
2503 lrbp->sense_bufflen = 0;
2504 lrbp->sense_buffer = NULL;
2505 lrbp->task_tag = tag;
2506 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2507 lrbp->intr_cmd = true; /* No interrupt aggregation */
2508 hba->dev_cmd.type = cmd_type;
2510 return ufshcd_comp_devman_upiu(hba, lrbp);
2513 static int
2514 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
2516 int err = 0;
2517 unsigned long flags;
2518 u32 mask = 1 << tag;
2520 /* clear outstanding transaction before retry */
2521 spin_lock_irqsave(hba->host->host_lock, flags);
2522 ufshcd_utrl_clear(hba, tag);
2523 spin_unlock_irqrestore(hba->host->host_lock, flags);
2526 * wait for for h/w to clear corresponding bit in door-bell.
2527 * max. wait is 1 sec.
2529 err = ufshcd_wait_for_register(hba,
2530 REG_UTP_TRANSFER_REQ_DOOR_BELL,
2531 mask, ~mask, 1000, 1000, true);
2533 return err;
2536 static int
2537 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2539 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2541 /* Get the UPIU response */
2542 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
2543 UPIU_RSP_CODE_OFFSET;
2544 return query_res->response;
2548 * ufshcd_dev_cmd_completion() - handles device management command responses
2549 * @hba: per adapter instance
2550 * @lrbp: pointer to local reference block
2552 static int
2553 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2555 int resp;
2556 int err = 0;
2558 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
2559 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2561 switch (resp) {
2562 case UPIU_TRANSACTION_NOP_IN:
2563 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
2564 err = -EINVAL;
2565 dev_err(hba->dev, "%s: unexpected response %x\n",
2566 __func__, resp);
2568 break;
2569 case UPIU_TRANSACTION_QUERY_RSP:
2570 err = ufshcd_check_query_response(hba, lrbp);
2571 if (!err)
2572 err = ufshcd_copy_query_response(hba, lrbp);
2573 break;
2574 case UPIU_TRANSACTION_REJECT_UPIU:
2575 /* TODO: handle Reject UPIU Response */
2576 err = -EPERM;
2577 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
2578 __func__);
2579 break;
2580 default:
2581 err = -EINVAL;
2582 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
2583 __func__, resp);
2584 break;
2587 return err;
2590 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
2591 struct ufshcd_lrb *lrbp, int max_timeout)
2593 int err = 0;
2594 unsigned long time_left;
2595 unsigned long flags;
2597 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
2598 msecs_to_jiffies(max_timeout));
2600 /* Make sure descriptors are ready before ringing the doorbell */
2601 wmb();
2602 spin_lock_irqsave(hba->host->host_lock, flags);
2603 hba->dev_cmd.complete = NULL;
2604 if (likely(time_left)) {
2605 err = ufshcd_get_tr_ocs(lrbp);
2606 if (!err)
2607 err = ufshcd_dev_cmd_completion(hba, lrbp);
2609 spin_unlock_irqrestore(hba->host->host_lock, flags);
2611 if (!time_left) {
2612 err = -ETIMEDOUT;
2613 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
2614 __func__, lrbp->task_tag);
2615 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
2616 /* successfully cleared the command, retry if needed */
2617 err = -EAGAIN;
2619 * in case of an error, after clearing the doorbell,
2620 * we also need to clear the outstanding_request
2621 * field in hba
2623 ufshcd_outstanding_req_clear(hba, lrbp->task_tag);
2626 return err;
2630 * ufshcd_get_dev_cmd_tag - Get device management command tag
2631 * @hba: per-adapter instance
2632 * @tag_out: pointer to variable with available slot value
2634 * Get a free slot and lock it until device management command
2635 * completes.
2637 * Returns false if free slot is unavailable for locking, else
2638 * return true with tag value in @tag.
2640 static bool ufshcd_get_dev_cmd_tag(struct ufs_hba *hba, int *tag_out)
2642 int tag;
2643 bool ret = false;
2644 unsigned long tmp;
2646 if (!tag_out)
2647 goto out;
2649 do {
2650 tmp = ~hba->lrb_in_use;
2651 tag = find_last_bit(&tmp, hba->nutrs);
2652 if (tag >= hba->nutrs)
2653 goto out;
2654 } while (test_and_set_bit_lock(tag, &hba->lrb_in_use));
2656 *tag_out = tag;
2657 ret = true;
2658 out:
2659 return ret;
2662 static inline void ufshcd_put_dev_cmd_tag(struct ufs_hba *hba, int tag)
2664 clear_bit_unlock(tag, &hba->lrb_in_use);
2668 * ufshcd_exec_dev_cmd - API for sending device management requests
2669 * @hba: UFS hba
2670 * @cmd_type: specifies the type (NOP, Query...)
2671 * @timeout: time in seconds
2673 * NOTE: Since there is only one available tag for device management commands,
2674 * it is expected you hold the hba->dev_cmd.lock mutex.
2676 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
2677 enum dev_cmd_type cmd_type, int timeout)
2679 struct ufshcd_lrb *lrbp;
2680 int err;
2681 int tag;
2682 struct completion wait;
2683 unsigned long flags;
2685 down_read(&hba->clk_scaling_lock);
2688 * Get free slot, sleep if slots are unavailable.
2689 * Even though we use wait_event() which sleeps indefinitely,
2690 * the maximum wait time is bounded by SCSI request timeout.
2692 wait_event(hba->dev_cmd.tag_wq, ufshcd_get_dev_cmd_tag(hba, &tag));
2694 init_completion(&wait);
2695 lrbp = &hba->lrb[tag];
2696 WARN_ON(lrbp->cmd);
2697 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
2698 if (unlikely(err))
2699 goto out_put_tag;
2701 hba->dev_cmd.complete = &wait;
2703 ufshcd_add_query_upiu_trace(hba, tag, "query_send");
2704 /* Make sure descriptors are ready before ringing the doorbell */
2705 wmb();
2706 spin_lock_irqsave(hba->host->host_lock, flags);
2707 ufshcd_vops_setup_xfer_req(hba, tag, (lrbp->cmd ? true : false));
2708 ufshcd_send_command(hba, tag);
2709 spin_unlock_irqrestore(hba->host->host_lock, flags);
2711 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
2713 ufshcd_add_query_upiu_trace(hba, tag,
2714 err ? "query_complete_err" : "query_complete");
2716 out_put_tag:
2717 ufshcd_put_dev_cmd_tag(hba, tag);
2718 wake_up(&hba->dev_cmd.tag_wq);
2719 up_read(&hba->clk_scaling_lock);
2720 return err;
2724 * ufshcd_init_query() - init the query response and request parameters
2725 * @hba: per-adapter instance
2726 * @request: address of the request pointer to be initialized
2727 * @response: address of the response pointer to be initialized
2728 * @opcode: operation to perform
2729 * @idn: flag idn to access
2730 * @index: LU number to access
2731 * @selector: query/flag/descriptor further identification
2733 static inline void ufshcd_init_query(struct ufs_hba *hba,
2734 struct ufs_query_req **request, struct ufs_query_res **response,
2735 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
2737 *request = &hba->dev_cmd.query.request;
2738 *response = &hba->dev_cmd.query.response;
2739 memset(*request, 0, sizeof(struct ufs_query_req));
2740 memset(*response, 0, sizeof(struct ufs_query_res));
2741 (*request)->upiu_req.opcode = opcode;
2742 (*request)->upiu_req.idn = idn;
2743 (*request)->upiu_req.index = index;
2744 (*request)->upiu_req.selector = selector;
2747 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
2748 enum query_opcode opcode, enum flag_idn idn, bool *flag_res)
2750 int ret;
2751 int retries;
2753 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
2754 ret = ufshcd_query_flag(hba, opcode, idn, flag_res);
2755 if (ret)
2756 dev_dbg(hba->dev,
2757 "%s: failed with error %d, retries %d\n",
2758 __func__, ret, retries);
2759 else
2760 break;
2763 if (ret)
2764 dev_err(hba->dev,
2765 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
2766 __func__, opcode, idn, ret, retries);
2767 return ret;
2771 * ufshcd_query_flag() - API function for sending flag query requests
2772 * @hba: per-adapter instance
2773 * @opcode: flag query to perform
2774 * @idn: flag idn to access
2775 * @flag_res: the flag value after the query request completes
2777 * Returns 0 for success, non-zero in case of failure
2779 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
2780 enum flag_idn idn, bool *flag_res)
2782 struct ufs_query_req *request = NULL;
2783 struct ufs_query_res *response = NULL;
2784 int err, index = 0, selector = 0;
2785 int timeout = QUERY_REQ_TIMEOUT;
2787 BUG_ON(!hba);
2789 ufshcd_hold(hba, false);
2790 mutex_lock(&hba->dev_cmd.lock);
2791 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2792 selector);
2794 switch (opcode) {
2795 case UPIU_QUERY_OPCODE_SET_FLAG:
2796 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
2797 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
2798 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2799 break;
2800 case UPIU_QUERY_OPCODE_READ_FLAG:
2801 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2802 if (!flag_res) {
2803 /* No dummy reads */
2804 dev_err(hba->dev, "%s: Invalid argument for read request\n",
2805 __func__);
2806 err = -EINVAL;
2807 goto out_unlock;
2809 break;
2810 default:
2811 dev_err(hba->dev,
2812 "%s: Expected query flag opcode but got = %d\n",
2813 __func__, opcode);
2814 err = -EINVAL;
2815 goto out_unlock;
2818 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
2820 if (err) {
2821 dev_err(hba->dev,
2822 "%s: Sending flag query for idn %d failed, err = %d\n",
2823 __func__, idn, err);
2824 goto out_unlock;
2827 if (flag_res)
2828 *flag_res = (be32_to_cpu(response->upiu_res.value) &
2829 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
2831 out_unlock:
2832 mutex_unlock(&hba->dev_cmd.lock);
2833 ufshcd_release(hba);
2834 return err;
2838 * ufshcd_query_attr - API function for sending attribute requests
2839 * @hba: per-adapter instance
2840 * @opcode: attribute opcode
2841 * @idn: attribute idn to access
2842 * @index: index field
2843 * @selector: selector field
2844 * @attr_val: the attribute value after the query request completes
2846 * Returns 0 for success, non-zero in case of failure
2848 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
2849 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
2851 struct ufs_query_req *request = NULL;
2852 struct ufs_query_res *response = NULL;
2853 int err;
2855 BUG_ON(!hba);
2857 ufshcd_hold(hba, false);
2858 if (!attr_val) {
2859 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
2860 __func__, opcode);
2861 err = -EINVAL;
2862 goto out;
2865 mutex_lock(&hba->dev_cmd.lock);
2866 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2867 selector);
2869 switch (opcode) {
2870 case UPIU_QUERY_OPCODE_WRITE_ATTR:
2871 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2872 request->upiu_req.value = cpu_to_be32(*attr_val);
2873 break;
2874 case UPIU_QUERY_OPCODE_READ_ATTR:
2875 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2876 break;
2877 default:
2878 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
2879 __func__, opcode);
2880 err = -EINVAL;
2881 goto out_unlock;
2884 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
2886 if (err) {
2887 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
2888 __func__, opcode, idn, index, err);
2889 goto out_unlock;
2892 *attr_val = be32_to_cpu(response->upiu_res.value);
2894 out_unlock:
2895 mutex_unlock(&hba->dev_cmd.lock);
2896 out:
2897 ufshcd_release(hba);
2898 return err;
2902 * ufshcd_query_attr_retry() - API function for sending query
2903 * attribute with retries
2904 * @hba: per-adapter instance
2905 * @opcode: attribute opcode
2906 * @idn: attribute idn to access
2907 * @index: index field
2908 * @selector: selector field
2909 * @attr_val: the attribute value after the query request
2910 * completes
2912 * Returns 0 for success, non-zero in case of failure
2914 static int ufshcd_query_attr_retry(struct ufs_hba *hba,
2915 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
2916 u32 *attr_val)
2918 int ret = 0;
2919 u32 retries;
2921 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
2922 ret = ufshcd_query_attr(hba, opcode, idn, index,
2923 selector, attr_val);
2924 if (ret)
2925 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
2926 __func__, ret, retries);
2927 else
2928 break;
2931 if (ret)
2932 dev_err(hba->dev,
2933 "%s: query attribute, idn %d, failed with error %d after %d retires\n",
2934 __func__, idn, ret, QUERY_REQ_RETRIES);
2935 return ret;
2938 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
2939 enum query_opcode opcode, enum desc_idn idn, u8 index,
2940 u8 selector, u8 *desc_buf, int *buf_len)
2942 struct ufs_query_req *request = NULL;
2943 struct ufs_query_res *response = NULL;
2944 int err;
2946 BUG_ON(!hba);
2948 ufshcd_hold(hba, false);
2949 if (!desc_buf) {
2950 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
2951 __func__, opcode);
2952 err = -EINVAL;
2953 goto out;
2956 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
2957 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
2958 __func__, *buf_len);
2959 err = -EINVAL;
2960 goto out;
2963 mutex_lock(&hba->dev_cmd.lock);
2964 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2965 selector);
2966 hba->dev_cmd.query.descriptor = desc_buf;
2967 request->upiu_req.length = cpu_to_be16(*buf_len);
2969 switch (opcode) {
2970 case UPIU_QUERY_OPCODE_WRITE_DESC:
2971 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2972 break;
2973 case UPIU_QUERY_OPCODE_READ_DESC:
2974 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2975 break;
2976 default:
2977 dev_err(hba->dev,
2978 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
2979 __func__, opcode);
2980 err = -EINVAL;
2981 goto out_unlock;
2984 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
2986 if (err) {
2987 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
2988 __func__, opcode, idn, index, err);
2989 goto out_unlock;
2992 *buf_len = be16_to_cpu(response->upiu_res.length);
2994 out_unlock:
2995 hba->dev_cmd.query.descriptor = NULL;
2996 mutex_unlock(&hba->dev_cmd.lock);
2997 out:
2998 ufshcd_release(hba);
2999 return err;
3003 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3004 * @hba: per-adapter instance
3005 * @opcode: attribute opcode
3006 * @idn: attribute idn to access
3007 * @index: index field
3008 * @selector: selector field
3009 * @desc_buf: the buffer that contains the descriptor
3010 * @buf_len: length parameter passed to the device
3012 * Returns 0 for success, non-zero in case of failure.
3013 * The buf_len parameter will contain, on return, the length parameter
3014 * received on the response.
3016 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3017 enum query_opcode opcode,
3018 enum desc_idn idn, u8 index,
3019 u8 selector,
3020 u8 *desc_buf, int *buf_len)
3022 int err;
3023 int retries;
3025 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3026 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3027 selector, desc_buf, buf_len);
3028 if (!err || err == -EINVAL)
3029 break;
3032 return err;
3036 * ufshcd_read_desc_length - read the specified descriptor length from header
3037 * @hba: Pointer to adapter instance
3038 * @desc_id: descriptor idn value
3039 * @desc_index: descriptor index
3040 * @desc_length: pointer to variable to read the length of descriptor
3042 * Return 0 in case of success, non-zero otherwise
3044 static int ufshcd_read_desc_length(struct ufs_hba *hba,
3045 enum desc_idn desc_id,
3046 int desc_index,
3047 int *desc_length)
3049 int ret;
3050 u8 header[QUERY_DESC_HDR_SIZE];
3051 int header_len = QUERY_DESC_HDR_SIZE;
3053 if (desc_id >= QUERY_DESC_IDN_MAX)
3054 return -EINVAL;
3056 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3057 desc_id, desc_index, 0, header,
3058 &header_len);
3060 if (ret) {
3061 dev_err(hba->dev, "%s: Failed to get descriptor header id %d",
3062 __func__, desc_id);
3063 return ret;
3064 } else if (desc_id != header[QUERY_DESC_DESC_TYPE_OFFSET]) {
3065 dev_warn(hba->dev, "%s: descriptor header id %d and desc_id %d mismatch",
3066 __func__, header[QUERY_DESC_DESC_TYPE_OFFSET],
3067 desc_id);
3068 ret = -EINVAL;
3071 *desc_length = header[QUERY_DESC_LENGTH_OFFSET];
3072 return ret;
3077 * ufshcd_map_desc_id_to_length - map descriptor IDN to its length
3078 * @hba: Pointer to adapter instance
3079 * @desc_id: descriptor idn value
3080 * @desc_len: mapped desc length (out)
3082 * Return 0 in case of success, non-zero otherwise
3084 int ufshcd_map_desc_id_to_length(struct ufs_hba *hba,
3085 enum desc_idn desc_id, int *desc_len)
3087 switch (desc_id) {
3088 case QUERY_DESC_IDN_DEVICE:
3089 *desc_len = hba->desc_size.dev_desc;
3090 break;
3091 case QUERY_DESC_IDN_POWER:
3092 *desc_len = hba->desc_size.pwr_desc;
3093 break;
3094 case QUERY_DESC_IDN_GEOMETRY:
3095 *desc_len = hba->desc_size.geom_desc;
3096 break;
3097 case QUERY_DESC_IDN_CONFIGURATION:
3098 *desc_len = hba->desc_size.conf_desc;
3099 break;
3100 case QUERY_DESC_IDN_UNIT:
3101 *desc_len = hba->desc_size.unit_desc;
3102 break;
3103 case QUERY_DESC_IDN_INTERCONNECT:
3104 *desc_len = hba->desc_size.interc_desc;
3105 break;
3106 case QUERY_DESC_IDN_STRING:
3107 *desc_len = QUERY_DESC_MAX_SIZE;
3108 break;
3109 case QUERY_DESC_IDN_HEALTH:
3110 *desc_len = hba->desc_size.hlth_desc;
3111 break;
3112 case QUERY_DESC_IDN_RFU_0:
3113 case QUERY_DESC_IDN_RFU_1:
3114 *desc_len = 0;
3115 break;
3116 default:
3117 *desc_len = 0;
3118 return -EINVAL;
3120 return 0;
3122 EXPORT_SYMBOL(ufshcd_map_desc_id_to_length);
3125 * ufshcd_read_desc_param - read the specified descriptor parameter
3126 * @hba: Pointer to adapter instance
3127 * @desc_id: descriptor idn value
3128 * @desc_index: descriptor index
3129 * @param_offset: offset of the parameter to read
3130 * @param_read_buf: pointer to buffer where parameter would be read
3131 * @param_size: sizeof(param_read_buf)
3133 * Return 0 in case of success, non-zero otherwise
3135 int ufshcd_read_desc_param(struct ufs_hba *hba,
3136 enum desc_idn desc_id,
3137 int desc_index,
3138 u8 param_offset,
3139 u8 *param_read_buf,
3140 u8 param_size)
3142 int ret;
3143 u8 *desc_buf;
3144 int buff_len;
3145 bool is_kmalloc = true;
3147 /* Safety check */
3148 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3149 return -EINVAL;
3151 /* Get the max length of descriptor from structure filled up at probe
3152 * time.
3154 ret = ufshcd_map_desc_id_to_length(hba, desc_id, &buff_len);
3156 /* Sanity checks */
3157 if (ret || !buff_len) {
3158 dev_err(hba->dev, "%s: Failed to get full descriptor length",
3159 __func__);
3160 return ret;
3163 /* Check whether we need temp memory */
3164 if (param_offset != 0 || param_size < buff_len) {
3165 desc_buf = kmalloc(buff_len, GFP_KERNEL);
3166 if (!desc_buf)
3167 return -ENOMEM;
3168 } else {
3169 desc_buf = param_read_buf;
3170 is_kmalloc = false;
3173 /* Request for full descriptor */
3174 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3175 desc_id, desc_index, 0,
3176 desc_buf, &buff_len);
3178 if (ret) {
3179 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d",
3180 __func__, desc_id, desc_index, param_offset, ret);
3181 goto out;
3184 /* Sanity check */
3185 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3186 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header",
3187 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3188 ret = -EINVAL;
3189 goto out;
3192 /* Check wherher we will not copy more data, than available */
3193 if (is_kmalloc && param_size > buff_len)
3194 param_size = buff_len;
3196 if (is_kmalloc)
3197 memcpy(param_read_buf, &desc_buf[param_offset], param_size);
3198 out:
3199 if (is_kmalloc)
3200 kfree(desc_buf);
3201 return ret;
3204 static inline int ufshcd_read_desc(struct ufs_hba *hba,
3205 enum desc_idn desc_id,
3206 int desc_index,
3207 void *buf,
3208 u32 size)
3210 return ufshcd_read_desc_param(hba, desc_id, desc_index, 0, buf, size);
3213 static inline int ufshcd_read_power_desc(struct ufs_hba *hba,
3214 u8 *buf,
3215 u32 size)
3217 return ufshcd_read_desc(hba, QUERY_DESC_IDN_POWER, 0, buf, size);
3220 static int ufshcd_read_device_desc(struct ufs_hba *hba, u8 *buf, u32 size)
3222 return ufshcd_read_desc(hba, QUERY_DESC_IDN_DEVICE, 0, buf, size);
3226 * struct uc_string_id - unicode string
3228 * @len: size of this descriptor inclusive
3229 * @type: descriptor type
3230 * @uc: unicode string character
3232 struct uc_string_id {
3233 u8 len;
3234 u8 type;
3235 wchar_t uc[0];
3236 } __packed;
3238 /* replace non-printable or non-ASCII characters with spaces */
3239 static inline char ufshcd_remove_non_printable(u8 ch)
3241 return (ch >= 0x20 && ch <= 0x7e) ? ch : ' ';
3245 * ufshcd_read_string_desc - read string descriptor
3246 * @hba: pointer to adapter instance
3247 * @desc_index: descriptor index
3248 * @buf: pointer to buffer where descriptor would be read,
3249 * the caller should free the memory.
3250 * @ascii: if true convert from unicode to ascii characters
3251 * null terminated string.
3253 * Return:
3254 * * string size on success.
3255 * * -ENOMEM: on allocation failure
3256 * * -EINVAL: on a wrong parameter
3258 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index,
3259 u8 **buf, bool ascii)
3261 struct uc_string_id *uc_str;
3262 u8 *str;
3263 int ret;
3265 if (!buf)
3266 return -EINVAL;
3268 uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
3269 if (!uc_str)
3270 return -ENOMEM;
3272 ret = ufshcd_read_desc(hba, QUERY_DESC_IDN_STRING,
3273 desc_index, uc_str,
3274 QUERY_DESC_MAX_SIZE);
3275 if (ret < 0) {
3276 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n",
3277 QUERY_REQ_RETRIES, ret);
3278 str = NULL;
3279 goto out;
3282 if (uc_str->len <= QUERY_DESC_HDR_SIZE) {
3283 dev_dbg(hba->dev, "String Desc is of zero length\n");
3284 str = NULL;
3285 ret = 0;
3286 goto out;
3289 if (ascii) {
3290 ssize_t ascii_len;
3291 int i;
3292 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3293 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3294 str = kzalloc(ascii_len, GFP_KERNEL);
3295 if (!str) {
3296 ret = -ENOMEM;
3297 goto out;
3301 * the descriptor contains string in UTF16 format
3302 * we need to convert to utf-8 so it can be displayed
3304 ret = utf16s_to_utf8s(uc_str->uc,
3305 uc_str->len - QUERY_DESC_HDR_SIZE,
3306 UTF16_BIG_ENDIAN, str, ascii_len);
3308 /* replace non-printable or non-ASCII characters with spaces */
3309 for (i = 0; i < ret; i++)
3310 str[i] = ufshcd_remove_non_printable(str[i]);
3312 str[ret++] = '\0';
3314 } else {
3315 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL);
3316 if (!str) {
3317 ret = -ENOMEM;
3318 goto out;
3320 ret = uc_str->len;
3322 out:
3323 *buf = str;
3324 kfree(uc_str);
3325 return ret;
3329 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3330 * @hba: Pointer to adapter instance
3331 * @lun: lun id
3332 * @param_offset: offset of the parameter to read
3333 * @param_read_buf: pointer to buffer where parameter would be read
3334 * @param_size: sizeof(param_read_buf)
3336 * Return 0 in case of success, non-zero otherwise
3338 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3339 int lun,
3340 enum unit_desc_param param_offset,
3341 u8 *param_read_buf,
3342 u32 param_size)
3345 * Unit descriptors are only available for general purpose LUs (LUN id
3346 * from 0 to 7) and RPMB Well known LU.
3348 if (!ufs_is_valid_unit_desc_lun(lun))
3349 return -EOPNOTSUPP;
3351 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3352 param_offset, param_read_buf, param_size);
3356 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3357 * @hba: per adapter instance
3359 * 1. Allocate DMA memory for Command Descriptor array
3360 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3361 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3362 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3363 * (UTMRDL)
3364 * 4. Allocate memory for local reference block(lrb).
3366 * Returns 0 for success, non-zero in case of failure
3368 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3370 size_t utmrdl_size, utrdl_size, ucdl_size;
3372 /* Allocate memory for UTP command descriptors */
3373 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3374 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3375 ucdl_size,
3376 &hba->ucdl_dma_addr,
3377 GFP_KERNEL);
3380 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3381 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3382 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3383 * be aligned to 128 bytes as well
3385 if (!hba->ucdl_base_addr ||
3386 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3387 dev_err(hba->dev,
3388 "Command Descriptor Memory allocation failed\n");
3389 goto out;
3393 * Allocate memory for UTP Transfer descriptors
3394 * UFSHCI requires 1024 byte alignment of UTRD
3396 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3397 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3398 utrdl_size,
3399 &hba->utrdl_dma_addr,
3400 GFP_KERNEL);
3401 if (!hba->utrdl_base_addr ||
3402 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3403 dev_err(hba->dev,
3404 "Transfer Descriptor Memory allocation failed\n");
3405 goto out;
3409 * Allocate memory for UTP Task Management descriptors
3410 * UFSHCI requires 1024 byte alignment of UTMRD
3412 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3413 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3414 utmrdl_size,
3415 &hba->utmrdl_dma_addr,
3416 GFP_KERNEL);
3417 if (!hba->utmrdl_base_addr ||
3418 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3419 dev_err(hba->dev,
3420 "Task Management Descriptor Memory allocation failed\n");
3421 goto out;
3424 /* Allocate memory for local reference block */
3425 hba->lrb = devm_kcalloc(hba->dev,
3426 hba->nutrs, sizeof(struct ufshcd_lrb),
3427 GFP_KERNEL);
3428 if (!hba->lrb) {
3429 dev_err(hba->dev, "LRB Memory allocation failed\n");
3430 goto out;
3432 return 0;
3433 out:
3434 return -ENOMEM;
3438 * ufshcd_host_memory_configure - configure local reference block with
3439 * memory offsets
3440 * @hba: per adapter instance
3442 * Configure Host memory space
3443 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3444 * address.
3445 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3446 * and PRDT offset.
3447 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3448 * into local reference block.
3450 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3452 struct utp_transfer_cmd_desc *cmd_descp;
3453 struct utp_transfer_req_desc *utrdlp;
3454 dma_addr_t cmd_desc_dma_addr;
3455 dma_addr_t cmd_desc_element_addr;
3456 u16 response_offset;
3457 u16 prdt_offset;
3458 int cmd_desc_size;
3459 int i;
3461 utrdlp = hba->utrdl_base_addr;
3462 cmd_descp = hba->ucdl_base_addr;
3464 response_offset =
3465 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3466 prdt_offset =
3467 offsetof(struct utp_transfer_cmd_desc, prd_table);
3469 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
3470 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3472 for (i = 0; i < hba->nutrs; i++) {
3473 /* Configure UTRD with command descriptor base address */
3474 cmd_desc_element_addr =
3475 (cmd_desc_dma_addr + (cmd_desc_size * i));
3476 utrdlp[i].command_desc_base_addr_lo =
3477 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3478 utrdlp[i].command_desc_base_addr_hi =
3479 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3481 /* Response upiu and prdt offset should be in double words */
3482 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3483 utrdlp[i].response_upiu_offset =
3484 cpu_to_le16(response_offset);
3485 utrdlp[i].prd_table_offset =
3486 cpu_to_le16(prdt_offset);
3487 utrdlp[i].response_upiu_length =
3488 cpu_to_le16(ALIGNED_UPIU_SIZE);
3489 } else {
3490 utrdlp[i].response_upiu_offset =
3491 cpu_to_le16((response_offset >> 2));
3492 utrdlp[i].prd_table_offset =
3493 cpu_to_le16((prdt_offset >> 2));
3494 utrdlp[i].response_upiu_length =
3495 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3498 hba->lrb[i].utr_descriptor_ptr = (utrdlp + i);
3499 hba->lrb[i].utrd_dma_addr = hba->utrdl_dma_addr +
3500 (i * sizeof(struct utp_transfer_req_desc));
3501 hba->lrb[i].ucd_req_ptr =
3502 (struct utp_upiu_req *)(cmd_descp + i);
3503 hba->lrb[i].ucd_req_dma_addr = cmd_desc_element_addr;
3504 hba->lrb[i].ucd_rsp_ptr =
3505 (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
3506 hba->lrb[i].ucd_rsp_dma_addr = cmd_desc_element_addr +
3507 response_offset;
3508 hba->lrb[i].ucd_prdt_ptr =
3509 (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
3510 hba->lrb[i].ucd_prdt_dma_addr = cmd_desc_element_addr +
3511 prdt_offset;
3516 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3517 * @hba: per adapter instance
3519 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3520 * in order to initialize the Unipro link startup procedure.
3521 * Once the Unipro links are up, the device connected to the controller
3522 * is detected.
3524 * Returns 0 on success, non-zero value on failure
3526 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3528 struct uic_command uic_cmd = {0};
3529 int ret;
3531 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3533 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3534 if (ret)
3535 dev_dbg(hba->dev,
3536 "dme-link-startup: error code %d\n", ret);
3537 return ret;
3540 * ufshcd_dme_reset - UIC command for DME_RESET
3541 * @hba: per adapter instance
3543 * DME_RESET command is issued in order to reset UniPro stack.
3544 * This function now deal with cold reset.
3546 * Returns 0 on success, non-zero value on failure
3548 static int ufshcd_dme_reset(struct ufs_hba *hba)
3550 struct uic_command uic_cmd = {0};
3551 int ret;
3553 uic_cmd.command = UIC_CMD_DME_RESET;
3555 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3556 if (ret)
3557 dev_err(hba->dev,
3558 "dme-reset: error code %d\n", ret);
3560 return ret;
3564 * ufshcd_dme_enable - UIC command for DME_ENABLE
3565 * @hba: per adapter instance
3567 * DME_ENABLE command is issued in order to enable UniPro stack.
3569 * Returns 0 on success, non-zero value on failure
3571 static int ufshcd_dme_enable(struct ufs_hba *hba)
3573 struct uic_command uic_cmd = {0};
3574 int ret;
3576 uic_cmd.command = UIC_CMD_DME_ENABLE;
3578 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3579 if (ret)
3580 dev_err(hba->dev,
3581 "dme-reset: error code %d\n", ret);
3583 return ret;
3586 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3588 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3589 unsigned long min_sleep_time_us;
3591 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3592 return;
3595 * last_dme_cmd_tstamp will be 0 only for 1st call to
3596 * this function
3598 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3599 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3600 } else {
3601 unsigned long delta =
3602 (unsigned long) ktime_to_us(
3603 ktime_sub(ktime_get(),
3604 hba->last_dme_cmd_tstamp));
3606 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3607 min_sleep_time_us =
3608 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3609 else
3610 return; /* no more delay required */
3613 /* allow sleep for extra 50us if needed */
3614 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3618 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3619 * @hba: per adapter instance
3620 * @attr_sel: uic command argument1
3621 * @attr_set: attribute set type as uic command argument2
3622 * @mib_val: setting value as uic command argument3
3623 * @peer: indicate whether peer or local
3625 * Returns 0 on success, non-zero value on failure
3627 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3628 u8 attr_set, u32 mib_val, u8 peer)
3630 struct uic_command uic_cmd = {0};
3631 static const char *const action[] = {
3632 "dme-set",
3633 "dme-peer-set"
3635 const char *set = action[!!peer];
3636 int ret;
3637 int retries = UFS_UIC_COMMAND_RETRIES;
3639 uic_cmd.command = peer ?
3640 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3641 uic_cmd.argument1 = attr_sel;
3642 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3643 uic_cmd.argument3 = mib_val;
3645 do {
3646 /* for peer attributes we retry upon failure */
3647 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3648 if (ret)
3649 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
3650 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
3651 } while (ret && peer && --retries);
3653 if (ret)
3654 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
3655 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
3656 UFS_UIC_COMMAND_RETRIES - retries);
3658 return ret;
3660 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
3663 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
3664 * @hba: per adapter instance
3665 * @attr_sel: uic command argument1
3666 * @mib_val: the value of the attribute as returned by the UIC command
3667 * @peer: indicate whether peer or local
3669 * Returns 0 on success, non-zero value on failure
3671 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
3672 u32 *mib_val, u8 peer)
3674 struct uic_command uic_cmd = {0};
3675 static const char *const action[] = {
3676 "dme-get",
3677 "dme-peer-get"
3679 const char *get = action[!!peer];
3680 int ret;
3681 int retries = UFS_UIC_COMMAND_RETRIES;
3682 struct ufs_pa_layer_attr orig_pwr_info;
3683 struct ufs_pa_layer_attr temp_pwr_info;
3684 bool pwr_mode_change = false;
3686 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
3687 orig_pwr_info = hba->pwr_info;
3688 temp_pwr_info = orig_pwr_info;
3690 if (orig_pwr_info.pwr_tx == FAST_MODE ||
3691 orig_pwr_info.pwr_rx == FAST_MODE) {
3692 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
3693 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
3694 pwr_mode_change = true;
3695 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
3696 orig_pwr_info.pwr_rx == SLOW_MODE) {
3697 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
3698 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
3699 pwr_mode_change = true;
3701 if (pwr_mode_change) {
3702 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
3703 if (ret)
3704 goto out;
3708 uic_cmd.command = peer ?
3709 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
3710 uic_cmd.argument1 = attr_sel;
3712 do {
3713 /* for peer attributes we retry upon failure */
3714 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3715 if (ret)
3716 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
3717 get, UIC_GET_ATTR_ID(attr_sel), ret);
3718 } while (ret && peer && --retries);
3720 if (ret)
3721 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
3722 get, UIC_GET_ATTR_ID(attr_sel),
3723 UFS_UIC_COMMAND_RETRIES - retries);
3725 if (mib_val && !ret)
3726 *mib_val = uic_cmd.argument3;
3728 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
3729 && pwr_mode_change)
3730 ufshcd_change_power_mode(hba, &orig_pwr_info);
3731 out:
3732 return ret;
3734 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
3737 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
3738 * state) and waits for it to take effect.
3740 * @hba: per adapter instance
3741 * @cmd: UIC command to execute
3743 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
3744 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
3745 * and device UniPro link and hence it's final completion would be indicated by
3746 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
3747 * addition to normal UIC command completion Status (UCCS). This function only
3748 * returns after the relevant status bits indicate the completion.
3750 * Returns 0 on success, non-zero value on failure
3752 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
3754 struct completion uic_async_done;
3755 unsigned long flags;
3756 u8 status;
3757 int ret;
3758 bool reenable_intr = false;
3760 mutex_lock(&hba->uic_cmd_mutex);
3761 init_completion(&uic_async_done);
3762 ufshcd_add_delay_before_dme_cmd(hba);
3764 spin_lock_irqsave(hba->host->host_lock, flags);
3765 hba->uic_async_done = &uic_async_done;
3766 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
3767 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
3769 * Make sure UIC command completion interrupt is disabled before
3770 * issuing UIC command.
3772 wmb();
3773 reenable_intr = true;
3775 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
3776 spin_unlock_irqrestore(hba->host->host_lock, flags);
3777 if (ret) {
3778 dev_err(hba->dev,
3779 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
3780 cmd->command, cmd->argument3, ret);
3781 goto out;
3784 if (!wait_for_completion_timeout(hba->uic_async_done,
3785 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
3786 dev_err(hba->dev,
3787 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
3788 cmd->command, cmd->argument3);
3789 ret = -ETIMEDOUT;
3790 goto out;
3793 status = ufshcd_get_upmcrs(hba);
3794 if (status != PWR_LOCAL) {
3795 dev_err(hba->dev,
3796 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
3797 cmd->command, status);
3798 ret = (status != PWR_OK) ? status : -1;
3800 out:
3801 if (ret) {
3802 ufshcd_print_host_state(hba);
3803 ufshcd_print_pwr_info(hba);
3804 ufshcd_print_host_regs(hba);
3807 spin_lock_irqsave(hba->host->host_lock, flags);
3808 hba->active_uic_cmd = NULL;
3809 hba->uic_async_done = NULL;
3810 if (reenable_intr)
3811 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
3812 spin_unlock_irqrestore(hba->host->host_lock, flags);
3813 mutex_unlock(&hba->uic_cmd_mutex);
3815 return ret;
3819 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
3820 * using DME_SET primitives.
3821 * @hba: per adapter instance
3822 * @mode: powr mode value
3824 * Returns 0 on success, non-zero value on failure
3826 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
3828 struct uic_command uic_cmd = {0};
3829 int ret;
3831 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
3832 ret = ufshcd_dme_set(hba,
3833 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
3834 if (ret) {
3835 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
3836 __func__, ret);
3837 goto out;
3841 uic_cmd.command = UIC_CMD_DME_SET;
3842 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
3843 uic_cmd.argument3 = mode;
3844 ufshcd_hold(hba, false);
3845 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3846 ufshcd_release(hba);
3848 out:
3849 return ret;
3852 static int ufshcd_link_recovery(struct ufs_hba *hba)
3854 int ret;
3855 unsigned long flags;
3857 spin_lock_irqsave(hba->host->host_lock, flags);
3858 hba->ufshcd_state = UFSHCD_STATE_RESET;
3859 ufshcd_set_eh_in_progress(hba);
3860 spin_unlock_irqrestore(hba->host->host_lock, flags);
3862 /* Reset the attached device */
3863 ufshcd_vops_device_reset(hba);
3865 ret = ufshcd_host_reset_and_restore(hba);
3867 spin_lock_irqsave(hba->host->host_lock, flags);
3868 if (ret)
3869 hba->ufshcd_state = UFSHCD_STATE_ERROR;
3870 ufshcd_clear_eh_in_progress(hba);
3871 spin_unlock_irqrestore(hba->host->host_lock, flags);
3873 if (ret)
3874 dev_err(hba->dev, "%s: link recovery failed, err %d",
3875 __func__, ret);
3877 return ret;
3880 static int __ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
3882 int ret;
3883 struct uic_command uic_cmd = {0};
3884 ktime_t start = ktime_get();
3886 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
3888 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
3889 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3890 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
3891 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
3893 if (ret) {
3894 int err;
3896 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
3897 __func__, ret);
3900 * If link recovery fails then return error code returned from
3901 * ufshcd_link_recovery().
3902 * If link recovery succeeds then return -EAGAIN to attempt
3903 * hibern8 enter retry again.
3905 err = ufshcd_link_recovery(hba);
3906 if (err) {
3907 dev_err(hba->dev, "%s: link recovery failed", __func__);
3908 ret = err;
3909 } else {
3910 ret = -EAGAIN;
3912 } else
3913 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
3914 POST_CHANGE);
3916 return ret;
3919 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
3921 int ret = 0, retries;
3923 for (retries = UIC_HIBERN8_ENTER_RETRIES; retries > 0; retries--) {
3924 ret = __ufshcd_uic_hibern8_enter(hba);
3925 if (!ret)
3926 goto out;
3928 out:
3929 return ret;
3932 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
3934 struct uic_command uic_cmd = {0};
3935 int ret;
3936 ktime_t start = ktime_get();
3938 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
3940 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
3941 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3942 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
3943 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
3945 if (ret) {
3946 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
3947 __func__, ret);
3948 ret = ufshcd_link_recovery(hba);
3949 } else {
3950 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
3951 POST_CHANGE);
3952 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_get();
3953 hba->ufs_stats.hibern8_exit_cnt++;
3956 return ret;
3959 void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
3961 unsigned long flags;
3963 if (!ufshcd_is_auto_hibern8_supported(hba) || !hba->ahit)
3964 return;
3966 spin_lock_irqsave(hba->host->host_lock, flags);
3967 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
3968 spin_unlock_irqrestore(hba->host->host_lock, flags);
3972 * ufshcd_init_pwr_info - setting the POR (power on reset)
3973 * values in hba power info
3974 * @hba: per-adapter instance
3976 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
3978 hba->pwr_info.gear_rx = UFS_PWM_G1;
3979 hba->pwr_info.gear_tx = UFS_PWM_G1;
3980 hba->pwr_info.lane_rx = 1;
3981 hba->pwr_info.lane_tx = 1;
3982 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
3983 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
3984 hba->pwr_info.hs_rate = 0;
3988 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
3989 * @hba: per-adapter instance
3991 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
3993 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
3995 if (hba->max_pwr_info.is_valid)
3996 return 0;
3998 pwr_info->pwr_tx = FAST_MODE;
3999 pwr_info->pwr_rx = FAST_MODE;
4000 pwr_info->hs_rate = PA_HS_MODE_B;
4002 /* Get the connected lane count */
4003 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
4004 &pwr_info->lane_rx);
4005 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4006 &pwr_info->lane_tx);
4008 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
4009 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4010 __func__,
4011 pwr_info->lane_rx,
4012 pwr_info->lane_tx);
4013 return -EINVAL;
4017 * First, get the maximum gears of HS speed.
4018 * If a zero value, it means there is no HSGEAR capability.
4019 * Then, get the maximum gears of PWM speed.
4021 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4022 if (!pwr_info->gear_rx) {
4023 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4024 &pwr_info->gear_rx);
4025 if (!pwr_info->gear_rx) {
4026 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4027 __func__, pwr_info->gear_rx);
4028 return -EINVAL;
4030 pwr_info->pwr_rx = SLOW_MODE;
4033 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4034 &pwr_info->gear_tx);
4035 if (!pwr_info->gear_tx) {
4036 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4037 &pwr_info->gear_tx);
4038 if (!pwr_info->gear_tx) {
4039 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4040 __func__, pwr_info->gear_tx);
4041 return -EINVAL;
4043 pwr_info->pwr_tx = SLOW_MODE;
4046 hba->max_pwr_info.is_valid = true;
4047 return 0;
4050 static int ufshcd_change_power_mode(struct ufs_hba *hba,
4051 struct ufs_pa_layer_attr *pwr_mode)
4053 int ret;
4055 /* if already configured to the requested pwr_mode */
4056 if (pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4057 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4058 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4059 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4060 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4061 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4062 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4063 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4064 return 0;
4068 * Configure attributes for power mode change with below.
4069 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4070 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4071 * - PA_HSSERIES
4073 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4074 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4075 pwr_mode->lane_rx);
4076 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4077 pwr_mode->pwr_rx == FAST_MODE)
4078 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
4079 else
4080 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
4082 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4083 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4084 pwr_mode->lane_tx);
4085 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4086 pwr_mode->pwr_tx == FAST_MODE)
4087 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
4088 else
4089 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
4091 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4092 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4093 pwr_mode->pwr_rx == FAST_MODE ||
4094 pwr_mode->pwr_tx == FAST_MODE)
4095 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4096 pwr_mode->hs_rate);
4098 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4099 | pwr_mode->pwr_tx);
4101 if (ret) {
4102 dev_err(hba->dev,
4103 "%s: power mode change failed %d\n", __func__, ret);
4104 } else {
4105 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4106 pwr_mode);
4108 memcpy(&hba->pwr_info, pwr_mode,
4109 sizeof(struct ufs_pa_layer_attr));
4112 return ret;
4116 * ufshcd_config_pwr_mode - configure a new power mode
4117 * @hba: per-adapter instance
4118 * @desired_pwr_mode: desired power configuration
4120 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4121 struct ufs_pa_layer_attr *desired_pwr_mode)
4123 struct ufs_pa_layer_attr final_params = { 0 };
4124 int ret;
4126 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4127 desired_pwr_mode, &final_params);
4129 if (ret)
4130 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4132 ret = ufshcd_change_power_mode(hba, &final_params);
4133 if (!ret)
4134 ufshcd_print_pwr_info(hba);
4136 return ret;
4138 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4141 * ufshcd_complete_dev_init() - checks device readiness
4142 * @hba: per-adapter instance
4144 * Set fDeviceInit flag and poll until device toggles it.
4146 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4148 int i;
4149 int err;
4150 bool flag_res = 1;
4152 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4153 QUERY_FLAG_IDN_FDEVICEINIT, NULL);
4154 if (err) {
4155 dev_err(hba->dev,
4156 "%s setting fDeviceInit flag failed with error %d\n",
4157 __func__, err);
4158 goto out;
4161 /* poll for max. 1000 iterations for fDeviceInit flag to clear */
4162 for (i = 0; i < 1000 && !err && flag_res; i++)
4163 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4164 QUERY_FLAG_IDN_FDEVICEINIT, &flag_res);
4166 if (err)
4167 dev_err(hba->dev,
4168 "%s reading fDeviceInit flag failed with error %d\n",
4169 __func__, err);
4170 else if (flag_res)
4171 dev_err(hba->dev,
4172 "%s fDeviceInit was not cleared by the device\n",
4173 __func__);
4175 out:
4176 return err;
4180 * ufshcd_make_hba_operational - Make UFS controller operational
4181 * @hba: per adapter instance
4183 * To bring UFS host controller to operational state,
4184 * 1. Enable required interrupts
4185 * 2. Configure interrupt aggregation
4186 * 3. Program UTRL and UTMRL base address
4187 * 4. Configure run-stop-registers
4189 * Returns 0 on success, non-zero value on failure
4191 static int ufshcd_make_hba_operational(struct ufs_hba *hba)
4193 int err = 0;
4194 u32 reg;
4196 /* Enable required interrupts */
4197 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4199 /* Configure interrupt aggregation */
4200 if (ufshcd_is_intr_aggr_allowed(hba))
4201 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4202 else
4203 ufshcd_disable_intr_aggr(hba);
4205 /* Configure UTRL and UTMRL base address registers */
4206 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4207 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4208 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4209 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4210 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4211 REG_UTP_TASK_REQ_LIST_BASE_L);
4212 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4213 REG_UTP_TASK_REQ_LIST_BASE_H);
4216 * Make sure base address and interrupt setup are updated before
4217 * enabling the run/stop registers below.
4219 wmb();
4222 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4224 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4225 if (!(ufshcd_get_lists_status(reg))) {
4226 ufshcd_enable_run_stop_reg(hba);
4227 } else {
4228 dev_err(hba->dev,
4229 "Host controller not ready to process requests");
4230 err = -EIO;
4231 goto out;
4234 out:
4235 return err;
4239 * ufshcd_hba_stop - Send controller to reset state
4240 * @hba: per adapter instance
4241 * @can_sleep: perform sleep or just spin
4243 static inline void ufshcd_hba_stop(struct ufs_hba *hba, bool can_sleep)
4245 int err;
4247 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4248 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4249 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4250 10, 1, can_sleep);
4251 if (err)
4252 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4256 * ufshcd_hba_execute_hce - initialize the controller
4257 * @hba: per adapter instance
4259 * The controller resets itself and controller firmware initialization
4260 * sequence kicks off. When controller is ready it will set
4261 * the Host Controller Enable bit to 1.
4263 * Returns 0 on success, non-zero value on failure
4265 static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
4267 int retry;
4269 if (!ufshcd_is_hba_active(hba))
4270 /* change controller state to "reset state" */
4271 ufshcd_hba_stop(hba, true);
4273 /* UniPro link is disabled at this point */
4274 ufshcd_set_link_off(hba);
4276 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4278 /* start controller initialization sequence */
4279 ufshcd_hba_start(hba);
4282 * To initialize a UFS host controller HCE bit must be set to 1.
4283 * During initialization the HCE bit value changes from 1->0->1.
4284 * When the host controller completes initialization sequence
4285 * it sets the value of HCE bit to 1. The same HCE bit is read back
4286 * to check if the controller has completed initialization sequence.
4287 * So without this delay the value HCE = 1, set in the previous
4288 * instruction might be read back.
4289 * This delay can be changed based on the controller.
4291 usleep_range(1000, 1100);
4293 /* wait for the host controller to complete initialization */
4294 retry = 10;
4295 while (ufshcd_is_hba_active(hba)) {
4296 if (retry) {
4297 retry--;
4298 } else {
4299 dev_err(hba->dev,
4300 "Controller enable failed\n");
4301 return -EIO;
4303 usleep_range(5000, 5100);
4306 /* enable UIC related interrupts */
4307 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4309 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4311 return 0;
4314 static int ufshcd_hba_enable(struct ufs_hba *hba)
4316 int ret;
4318 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
4319 ufshcd_set_link_off(hba);
4320 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4322 /* enable UIC related interrupts */
4323 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4324 ret = ufshcd_dme_reset(hba);
4325 if (!ret) {
4326 ret = ufshcd_dme_enable(hba);
4327 if (!ret)
4328 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4329 if (ret)
4330 dev_err(hba->dev,
4331 "Host controller enable failed with non-hce\n");
4333 } else {
4334 ret = ufshcd_hba_execute_hce(hba);
4337 return ret;
4339 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4341 int tx_lanes, i, err = 0;
4343 if (!peer)
4344 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4345 &tx_lanes);
4346 else
4347 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4348 &tx_lanes);
4349 for (i = 0; i < tx_lanes; i++) {
4350 if (!peer)
4351 err = ufshcd_dme_set(hba,
4352 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4353 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4355 else
4356 err = ufshcd_dme_peer_set(hba,
4357 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4358 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4360 if (err) {
4361 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4362 __func__, peer, i, err);
4363 break;
4367 return err;
4370 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4372 return ufshcd_disable_tx_lcc(hba, true);
4375 static void ufshcd_update_reg_hist(struct ufs_err_reg_hist *reg_hist,
4376 u32 reg)
4378 reg_hist->reg[reg_hist->pos] = reg;
4379 reg_hist->tstamp[reg_hist->pos] = ktime_get();
4380 reg_hist->pos = (reg_hist->pos + 1) % UFS_ERR_REG_HIST_LENGTH;
4384 * ufshcd_link_startup - Initialize unipro link startup
4385 * @hba: per adapter instance
4387 * Returns 0 for success, non-zero in case of failure
4389 static int ufshcd_link_startup(struct ufs_hba *hba)
4391 int ret;
4392 int retries = DME_LINKSTARTUP_RETRIES;
4393 bool link_startup_again = false;
4396 * If UFS device isn't active then we will have to issue link startup
4397 * 2 times to make sure the device state move to active.
4399 if (!ufshcd_is_ufs_dev_active(hba))
4400 link_startup_again = true;
4402 link_startup:
4403 do {
4404 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4406 ret = ufshcd_dme_link_startup(hba);
4408 /* check if device is detected by inter-connect layer */
4409 if (!ret && !ufshcd_is_device_present(hba)) {
4410 ufshcd_update_reg_hist(&hba->ufs_stats.link_startup_err,
4412 dev_err(hba->dev, "%s: Device not present\n", __func__);
4413 ret = -ENXIO;
4414 goto out;
4418 * DME link lost indication is only received when link is up,
4419 * but we can't be sure if the link is up until link startup
4420 * succeeds. So reset the local Uni-Pro and try again.
4422 if (ret && ufshcd_hba_enable(hba)) {
4423 ufshcd_update_reg_hist(&hba->ufs_stats.link_startup_err,
4424 (u32)ret);
4425 goto out;
4427 } while (ret && retries--);
4429 if (ret) {
4430 /* failed to get the link up... retire */
4431 ufshcd_update_reg_hist(&hba->ufs_stats.link_startup_err,
4432 (u32)ret);
4433 goto out;
4436 if (link_startup_again) {
4437 link_startup_again = false;
4438 retries = DME_LINKSTARTUP_RETRIES;
4439 goto link_startup;
4442 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4443 ufshcd_init_pwr_info(hba);
4444 ufshcd_print_pwr_info(hba);
4446 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4447 ret = ufshcd_disable_device_tx_lcc(hba);
4448 if (ret)
4449 goto out;
4452 /* Include any host controller configuration via UIC commands */
4453 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4454 if (ret)
4455 goto out;
4457 ret = ufshcd_make_hba_operational(hba);
4458 out:
4459 if (ret) {
4460 dev_err(hba->dev, "link startup failed %d\n", ret);
4461 ufshcd_print_host_state(hba);
4462 ufshcd_print_pwr_info(hba);
4463 ufshcd_print_host_regs(hba);
4465 return ret;
4469 * ufshcd_verify_dev_init() - Verify device initialization
4470 * @hba: per-adapter instance
4472 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4473 * device Transport Protocol (UTP) layer is ready after a reset.
4474 * If the UTP layer at the device side is not initialized, it may
4475 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4476 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4478 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4480 int err = 0;
4481 int retries;
4483 ufshcd_hold(hba, false);
4484 mutex_lock(&hba->dev_cmd.lock);
4485 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4486 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4487 NOP_OUT_TIMEOUT);
4489 if (!err || err == -ETIMEDOUT)
4490 break;
4492 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4494 mutex_unlock(&hba->dev_cmd.lock);
4495 ufshcd_release(hba);
4497 if (err)
4498 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4499 return err;
4503 * ufshcd_set_queue_depth - set lun queue depth
4504 * @sdev: pointer to SCSI device
4506 * Read bLUQueueDepth value and activate scsi tagged command
4507 * queueing. For WLUN, queue depth is set to 1. For best-effort
4508 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
4509 * value that host can queue.
4511 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
4513 int ret = 0;
4514 u8 lun_qdepth;
4515 struct ufs_hba *hba;
4517 hba = shost_priv(sdev->host);
4519 lun_qdepth = hba->nutrs;
4520 ret = ufshcd_read_unit_desc_param(hba,
4521 ufshcd_scsi_to_upiu_lun(sdev->lun),
4522 UNIT_DESC_PARAM_LU_Q_DEPTH,
4523 &lun_qdepth,
4524 sizeof(lun_qdepth));
4526 /* Some WLUN doesn't support unit descriptor */
4527 if (ret == -EOPNOTSUPP)
4528 lun_qdepth = 1;
4529 else if (!lun_qdepth)
4530 /* eventually, we can figure out the real queue depth */
4531 lun_qdepth = hba->nutrs;
4532 else
4533 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
4535 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
4536 __func__, lun_qdepth);
4537 scsi_change_queue_depth(sdev, lun_qdepth);
4541 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
4542 * @hba: per-adapter instance
4543 * @lun: UFS device lun id
4544 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
4546 * Returns 0 in case of success and b_lu_write_protect status would be returned
4547 * @b_lu_write_protect parameter.
4548 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
4549 * Returns -EINVAL in case of invalid parameters passed to this function.
4551 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
4552 u8 lun,
4553 u8 *b_lu_write_protect)
4555 int ret;
4557 if (!b_lu_write_protect)
4558 ret = -EINVAL;
4560 * According to UFS device spec, RPMB LU can't be write
4561 * protected so skip reading bLUWriteProtect parameter for
4562 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
4564 else if (lun >= UFS_UPIU_MAX_GENERAL_LUN)
4565 ret = -ENOTSUPP;
4566 else
4567 ret = ufshcd_read_unit_desc_param(hba,
4568 lun,
4569 UNIT_DESC_PARAM_LU_WR_PROTECT,
4570 b_lu_write_protect,
4571 sizeof(*b_lu_write_protect));
4572 return ret;
4576 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
4577 * status
4578 * @hba: per-adapter instance
4579 * @sdev: pointer to SCSI device
4582 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
4583 struct scsi_device *sdev)
4585 if (hba->dev_info.f_power_on_wp_en &&
4586 !hba->dev_info.is_lu_power_on_wp) {
4587 u8 b_lu_write_protect;
4589 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
4590 &b_lu_write_protect) &&
4591 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
4592 hba->dev_info.is_lu_power_on_wp = true;
4597 * ufshcd_slave_alloc - handle initial SCSI device configurations
4598 * @sdev: pointer to SCSI device
4600 * Returns success
4602 static int ufshcd_slave_alloc(struct scsi_device *sdev)
4604 struct ufs_hba *hba;
4606 hba = shost_priv(sdev->host);
4608 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
4609 sdev->use_10_for_ms = 1;
4611 /* allow SCSI layer to restart the device in case of errors */
4612 sdev->allow_restart = 1;
4614 /* REPORT SUPPORTED OPERATION CODES is not supported */
4615 sdev->no_report_opcodes = 1;
4617 /* WRITE_SAME command is not supported */
4618 sdev->no_write_same = 1;
4620 ufshcd_set_queue_depth(sdev);
4622 ufshcd_get_lu_power_on_wp_status(hba, sdev);
4624 return 0;
4628 * ufshcd_change_queue_depth - change queue depth
4629 * @sdev: pointer to SCSI device
4630 * @depth: required depth to set
4632 * Change queue depth and make sure the max. limits are not crossed.
4634 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
4636 struct ufs_hba *hba = shost_priv(sdev->host);
4638 if (depth > hba->nutrs)
4639 depth = hba->nutrs;
4640 return scsi_change_queue_depth(sdev, depth);
4644 * ufshcd_slave_configure - adjust SCSI device configurations
4645 * @sdev: pointer to SCSI device
4647 static int ufshcd_slave_configure(struct scsi_device *sdev)
4649 struct ufs_hba *hba = shost_priv(sdev->host);
4650 struct request_queue *q = sdev->request_queue;
4652 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
4654 if (ufshcd_is_rpm_autosuspend_allowed(hba))
4655 sdev->rpm_autosuspend = 1;
4657 return 0;
4661 * ufshcd_slave_destroy - remove SCSI device configurations
4662 * @sdev: pointer to SCSI device
4664 static void ufshcd_slave_destroy(struct scsi_device *sdev)
4666 struct ufs_hba *hba;
4668 hba = shost_priv(sdev->host);
4669 /* Drop the reference as it won't be needed anymore */
4670 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
4671 unsigned long flags;
4673 spin_lock_irqsave(hba->host->host_lock, flags);
4674 hba->sdev_ufs_device = NULL;
4675 spin_unlock_irqrestore(hba->host->host_lock, flags);
4680 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
4681 * @lrbp: pointer to local reference block of completed command
4682 * @scsi_status: SCSI command status
4684 * Returns value base on SCSI command status
4686 static inline int
4687 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
4689 int result = 0;
4691 switch (scsi_status) {
4692 case SAM_STAT_CHECK_CONDITION:
4693 ufshcd_copy_sense_data(lrbp);
4694 /* fallthrough */
4695 case SAM_STAT_GOOD:
4696 result |= DID_OK << 16 |
4697 COMMAND_COMPLETE << 8 |
4698 scsi_status;
4699 break;
4700 case SAM_STAT_TASK_SET_FULL:
4701 case SAM_STAT_BUSY:
4702 case SAM_STAT_TASK_ABORTED:
4703 ufshcd_copy_sense_data(lrbp);
4704 result |= scsi_status;
4705 break;
4706 default:
4707 result |= DID_ERROR << 16;
4708 break;
4709 } /* end of switch */
4711 return result;
4715 * ufshcd_transfer_rsp_status - Get overall status of the response
4716 * @hba: per adapter instance
4717 * @lrbp: pointer to local reference block of completed command
4719 * Returns result of the command to notify SCSI midlayer
4721 static inline int
4722 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
4724 int result = 0;
4725 int scsi_status;
4726 int ocs;
4728 /* overall command status of utrd */
4729 ocs = ufshcd_get_tr_ocs(lrbp);
4731 switch (ocs) {
4732 case OCS_SUCCESS:
4733 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
4734 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
4735 switch (result) {
4736 case UPIU_TRANSACTION_RESPONSE:
4738 * get the response UPIU result to extract
4739 * the SCSI command status
4741 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
4744 * get the result based on SCSI status response
4745 * to notify the SCSI midlayer of the command status
4747 scsi_status = result & MASK_SCSI_STATUS;
4748 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
4751 * Currently we are only supporting BKOPs exception
4752 * events hence we can ignore BKOPs exception event
4753 * during power management callbacks. BKOPs exception
4754 * event is not expected to be raised in runtime suspend
4755 * callback as it allows the urgent bkops.
4756 * During system suspend, we are anyway forcefully
4757 * disabling the bkops and if urgent bkops is needed
4758 * it will be enabled on system resume. Long term
4759 * solution could be to abort the system suspend if
4760 * UFS device needs urgent BKOPs.
4762 if (!hba->pm_op_in_progress &&
4763 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
4764 schedule_work(&hba->eeh_work);
4765 break;
4766 case UPIU_TRANSACTION_REJECT_UPIU:
4767 /* TODO: handle Reject UPIU Response */
4768 result = DID_ERROR << 16;
4769 dev_err(hba->dev,
4770 "Reject UPIU not fully implemented\n");
4771 break;
4772 default:
4773 dev_err(hba->dev,
4774 "Unexpected request response code = %x\n",
4775 result);
4776 result = DID_ERROR << 16;
4777 break;
4779 break;
4780 case OCS_ABORTED:
4781 result |= DID_ABORT << 16;
4782 break;
4783 case OCS_INVALID_COMMAND_STATUS:
4784 result |= DID_REQUEUE << 16;
4785 break;
4786 case OCS_INVALID_CMD_TABLE_ATTR:
4787 case OCS_INVALID_PRDT_ATTR:
4788 case OCS_MISMATCH_DATA_BUF_SIZE:
4789 case OCS_MISMATCH_RESP_UPIU_SIZE:
4790 case OCS_PEER_COMM_FAILURE:
4791 case OCS_FATAL_ERROR:
4792 default:
4793 result |= DID_ERROR << 16;
4794 dev_err(hba->dev,
4795 "OCS error from controller = %x for tag %d\n",
4796 ocs, lrbp->task_tag);
4797 ufshcd_print_host_regs(hba);
4798 ufshcd_print_host_state(hba);
4799 break;
4800 } /* end of switch */
4802 if (host_byte(result) != DID_OK)
4803 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true);
4804 return result;
4808 * ufshcd_uic_cmd_compl - handle completion of uic command
4809 * @hba: per adapter instance
4810 * @intr_status: interrupt status generated by the controller
4812 * Returns
4813 * IRQ_HANDLED - If interrupt is valid
4814 * IRQ_NONE - If invalid interrupt
4816 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
4818 irqreturn_t retval = IRQ_NONE;
4820 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
4821 hba->active_uic_cmd->argument2 |=
4822 ufshcd_get_uic_cmd_result(hba);
4823 hba->active_uic_cmd->argument3 =
4824 ufshcd_get_dme_attr_val(hba);
4825 complete(&hba->active_uic_cmd->done);
4826 retval = IRQ_HANDLED;
4829 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done) {
4830 complete(hba->uic_async_done);
4831 retval = IRQ_HANDLED;
4833 return retval;
4837 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
4838 * @hba: per adapter instance
4839 * @completed_reqs: requests to complete
4841 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
4842 unsigned long completed_reqs)
4844 struct ufshcd_lrb *lrbp;
4845 struct scsi_cmnd *cmd;
4846 int result;
4847 int index;
4849 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
4850 lrbp = &hba->lrb[index];
4851 cmd = lrbp->cmd;
4852 if (cmd) {
4853 ufshcd_add_command_trace(hba, index, "complete");
4854 result = ufshcd_transfer_rsp_status(hba, lrbp);
4855 scsi_dma_unmap(cmd);
4856 cmd->result = result;
4857 /* Mark completed command as NULL in LRB */
4858 lrbp->cmd = NULL;
4859 clear_bit_unlock(index, &hba->lrb_in_use);
4860 /* Do not touch lrbp after scsi done */
4861 cmd->scsi_done(cmd);
4862 __ufshcd_release(hba);
4863 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
4864 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
4865 if (hba->dev_cmd.complete) {
4866 ufshcd_add_command_trace(hba, index,
4867 "dev_complete");
4868 complete(hba->dev_cmd.complete);
4871 if (ufshcd_is_clkscaling_supported(hba))
4872 hba->clk_scaling.active_reqs--;
4874 lrbp->compl_time_stamp = ktime_get();
4877 /* clear corresponding bits of completed commands */
4878 hba->outstanding_reqs ^= completed_reqs;
4880 ufshcd_clk_scaling_update_busy(hba);
4882 /* we might have free'd some tags above */
4883 wake_up(&hba->dev_cmd.tag_wq);
4887 * ufshcd_transfer_req_compl - handle SCSI and query command completion
4888 * @hba: per adapter instance
4890 * Returns
4891 * IRQ_HANDLED - If interrupt is valid
4892 * IRQ_NONE - If invalid interrupt
4894 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba)
4896 unsigned long completed_reqs;
4897 u32 tr_doorbell;
4899 /* Resetting interrupt aggregation counters first and reading the
4900 * DOOR_BELL afterward allows us to handle all the completed requests.
4901 * In order to prevent other interrupts starvation the DB is read once
4902 * after reset. The down side of this solution is the possibility of
4903 * false interrupt if device completes another request after resetting
4904 * aggregation and before reading the DB.
4906 if (ufshcd_is_intr_aggr_allowed(hba) &&
4907 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
4908 ufshcd_reset_intr_aggr(hba);
4910 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
4911 completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
4913 if (completed_reqs) {
4914 __ufshcd_transfer_req_compl(hba, completed_reqs);
4915 return IRQ_HANDLED;
4916 } else {
4917 return IRQ_NONE;
4922 * ufshcd_disable_ee - disable exception event
4923 * @hba: per-adapter instance
4924 * @mask: exception event to disable
4926 * Disables exception event in the device so that the EVENT_ALERT
4927 * bit is not set.
4929 * Returns zero on success, non-zero error value on failure.
4931 static int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
4933 int err = 0;
4934 u32 val;
4936 if (!(hba->ee_ctrl_mask & mask))
4937 goto out;
4939 val = hba->ee_ctrl_mask & ~mask;
4940 val &= MASK_EE_STATUS;
4941 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
4942 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
4943 if (!err)
4944 hba->ee_ctrl_mask &= ~mask;
4945 out:
4946 return err;
4950 * ufshcd_enable_ee - enable exception event
4951 * @hba: per-adapter instance
4952 * @mask: exception event to enable
4954 * Enable corresponding exception event in the device to allow
4955 * device to alert host in critical scenarios.
4957 * Returns zero on success, non-zero error value on failure.
4959 static int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
4961 int err = 0;
4962 u32 val;
4964 if (hba->ee_ctrl_mask & mask)
4965 goto out;
4967 val = hba->ee_ctrl_mask | mask;
4968 val &= MASK_EE_STATUS;
4969 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
4970 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
4971 if (!err)
4972 hba->ee_ctrl_mask |= mask;
4973 out:
4974 return err;
4978 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
4979 * @hba: per-adapter instance
4981 * Allow device to manage background operations on its own. Enabling
4982 * this might lead to inconsistent latencies during normal data transfers
4983 * as the device is allowed to manage its own way of handling background
4984 * operations.
4986 * Returns zero on success, non-zero on failure.
4988 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
4990 int err = 0;
4992 if (hba->auto_bkops_enabled)
4993 goto out;
4995 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4996 QUERY_FLAG_IDN_BKOPS_EN, NULL);
4997 if (err) {
4998 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
4999 __func__, err);
5000 goto out;
5003 hba->auto_bkops_enabled = true;
5004 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
5006 /* No need of URGENT_BKOPS exception from the device */
5007 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5008 if (err)
5009 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5010 __func__, err);
5011 out:
5012 return err;
5016 * ufshcd_disable_auto_bkops - block device in doing background operations
5017 * @hba: per-adapter instance
5019 * Disabling background operations improves command response latency but
5020 * has drawback of device moving into critical state where the device is
5021 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5022 * host is idle so that BKOPS are managed effectively without any negative
5023 * impacts.
5025 * Returns zero on success, non-zero on failure.
5027 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5029 int err = 0;
5031 if (!hba->auto_bkops_enabled)
5032 goto out;
5035 * If host assisted BKOPs is to be enabled, make sure
5036 * urgent bkops exception is allowed.
5038 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5039 if (err) {
5040 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5041 __func__, err);
5042 goto out;
5045 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5046 QUERY_FLAG_IDN_BKOPS_EN, NULL);
5047 if (err) {
5048 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5049 __func__, err);
5050 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5051 goto out;
5054 hba->auto_bkops_enabled = false;
5055 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
5056 out:
5057 return err;
5061 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5062 * @hba: per adapter instance
5064 * After a device reset the device may toggle the BKOPS_EN flag
5065 * to default value. The s/w tracking variables should be updated
5066 * as well. This function would change the auto-bkops state based on
5067 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5069 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5071 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5072 hba->auto_bkops_enabled = false;
5073 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5074 ufshcd_enable_auto_bkops(hba);
5075 } else {
5076 hba->auto_bkops_enabled = true;
5077 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5078 ufshcd_disable_auto_bkops(hba);
5082 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5084 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5085 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5089 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5090 * @hba: per-adapter instance
5091 * @status: bkops_status value
5093 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5094 * flag in the device to permit background operations if the device
5095 * bkops_status is greater than or equal to "status" argument passed to
5096 * this function, disable otherwise.
5098 * Returns 0 for success, non-zero in case of failure.
5100 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5101 * to know whether auto bkops is enabled or disabled after this function
5102 * returns control to it.
5104 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5105 enum bkops_status status)
5107 int err;
5108 u32 curr_status = 0;
5110 err = ufshcd_get_bkops_status(hba, &curr_status);
5111 if (err) {
5112 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5113 __func__, err);
5114 goto out;
5115 } else if (curr_status > BKOPS_STATUS_MAX) {
5116 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5117 __func__, curr_status);
5118 err = -EINVAL;
5119 goto out;
5122 if (curr_status >= status)
5123 err = ufshcd_enable_auto_bkops(hba);
5124 else
5125 err = ufshcd_disable_auto_bkops(hba);
5126 out:
5127 return err;
5131 * ufshcd_urgent_bkops - handle urgent bkops exception event
5132 * @hba: per-adapter instance
5134 * Enable fBackgroundOpsEn flag in the device to permit background
5135 * operations.
5137 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5138 * and negative error value for any other failure.
5140 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5142 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5145 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5147 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5148 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5151 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5153 int err;
5154 u32 curr_status = 0;
5156 if (hba->is_urgent_bkops_lvl_checked)
5157 goto enable_auto_bkops;
5159 err = ufshcd_get_bkops_status(hba, &curr_status);
5160 if (err) {
5161 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5162 __func__, err);
5163 goto out;
5167 * We are seeing that some devices are raising the urgent bkops
5168 * exception events even when BKOPS status doesn't indicate performace
5169 * impacted or critical. Handle these device by determining their urgent
5170 * bkops status at runtime.
5172 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5173 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5174 __func__, curr_status);
5175 /* update the current status as the urgent bkops level */
5176 hba->urgent_bkops_lvl = curr_status;
5177 hba->is_urgent_bkops_lvl_checked = true;
5180 enable_auto_bkops:
5181 err = ufshcd_enable_auto_bkops(hba);
5182 out:
5183 if (err < 0)
5184 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5185 __func__, err);
5189 * ufshcd_exception_event_handler - handle exceptions raised by device
5190 * @work: pointer to work data
5192 * Read bExceptionEventStatus attribute from the device and handle the
5193 * exception event accordingly.
5195 static void ufshcd_exception_event_handler(struct work_struct *work)
5197 struct ufs_hba *hba;
5198 int err;
5199 u32 status = 0;
5200 hba = container_of(work, struct ufs_hba, eeh_work);
5202 pm_runtime_get_sync(hba->dev);
5203 scsi_block_requests(hba->host);
5204 err = ufshcd_get_ee_status(hba, &status);
5205 if (err) {
5206 dev_err(hba->dev, "%s: failed to get exception status %d\n",
5207 __func__, err);
5208 goto out;
5211 status &= hba->ee_ctrl_mask;
5213 if (status & MASK_EE_URGENT_BKOPS)
5214 ufshcd_bkops_exception_event_handler(hba);
5216 out:
5217 scsi_unblock_requests(hba->host);
5218 pm_runtime_put_sync(hba->dev);
5219 return;
5222 /* Complete requests that have door-bell cleared */
5223 static void ufshcd_complete_requests(struct ufs_hba *hba)
5225 ufshcd_transfer_req_compl(hba);
5226 ufshcd_tmc_handler(hba);
5230 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
5231 * to recover from the DL NAC errors or not.
5232 * @hba: per-adapter instance
5234 * Returns true if error handling is required, false otherwise
5236 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
5238 unsigned long flags;
5239 bool err_handling = true;
5241 spin_lock_irqsave(hba->host->host_lock, flags);
5243 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
5244 * device fatal error and/or DL NAC & REPLAY timeout errors.
5246 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
5247 goto out;
5249 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
5250 ((hba->saved_err & UIC_ERROR) &&
5251 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
5252 goto out;
5254 if ((hba->saved_err & UIC_ERROR) &&
5255 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
5256 int err;
5258 * wait for 50ms to see if we can get any other errors or not.
5260 spin_unlock_irqrestore(hba->host->host_lock, flags);
5261 msleep(50);
5262 spin_lock_irqsave(hba->host->host_lock, flags);
5265 * now check if we have got any other severe errors other than
5266 * DL NAC error?
5268 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5269 ((hba->saved_err & UIC_ERROR) &&
5270 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
5271 goto out;
5274 * As DL NAC is the only error received so far, send out NOP
5275 * command to confirm if link is still active or not.
5276 * - If we don't get any response then do error recovery.
5277 * - If we get response then clear the DL NAC error bit.
5280 spin_unlock_irqrestore(hba->host->host_lock, flags);
5281 err = ufshcd_verify_dev_init(hba);
5282 spin_lock_irqsave(hba->host->host_lock, flags);
5284 if (err)
5285 goto out;
5287 /* Link seems to be alive hence ignore the DL NAC errors */
5288 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
5289 hba->saved_err &= ~UIC_ERROR;
5290 /* clear NAC error */
5291 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5292 if (!hba->saved_uic_err) {
5293 err_handling = false;
5294 goto out;
5297 out:
5298 spin_unlock_irqrestore(hba->host->host_lock, flags);
5299 return err_handling;
5303 * ufshcd_err_handler - handle UFS errors that require s/w attention
5304 * @work: pointer to work structure
5306 static void ufshcd_err_handler(struct work_struct *work)
5308 struct ufs_hba *hba;
5309 unsigned long flags;
5310 u32 err_xfer = 0;
5311 u32 err_tm = 0;
5312 int err = 0;
5313 int tag;
5314 bool needs_reset = false;
5316 hba = container_of(work, struct ufs_hba, eh_work);
5318 pm_runtime_get_sync(hba->dev);
5319 ufshcd_hold(hba, false);
5321 spin_lock_irqsave(hba->host->host_lock, flags);
5322 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
5323 goto out;
5325 hba->ufshcd_state = UFSHCD_STATE_RESET;
5326 ufshcd_set_eh_in_progress(hba);
5328 /* Complete requests that have door-bell cleared by h/w */
5329 ufshcd_complete_requests(hba);
5331 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5332 bool ret;
5334 spin_unlock_irqrestore(hba->host->host_lock, flags);
5335 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
5336 ret = ufshcd_quirk_dl_nac_errors(hba);
5337 spin_lock_irqsave(hba->host->host_lock, flags);
5338 if (!ret)
5339 goto skip_err_handling;
5341 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5342 (hba->saved_err & UFSHCD_UIC_HIBERN8_MASK) ||
5343 ((hba->saved_err & UIC_ERROR) &&
5344 (hba->saved_uic_err & (UFSHCD_UIC_DL_PA_INIT_ERROR |
5345 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
5346 UFSHCD_UIC_DL_TCx_REPLAY_ERROR))))
5347 needs_reset = true;
5350 * if host reset is required then skip clearing the pending
5351 * transfers forcefully because they will automatically get
5352 * cleared after link startup.
5354 if (needs_reset)
5355 goto skip_pending_xfer_clear;
5357 /* release lock as clear command might sleep */
5358 spin_unlock_irqrestore(hba->host->host_lock, flags);
5359 /* Clear pending transfer requests */
5360 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
5361 if (ufshcd_clear_cmd(hba, tag)) {
5362 err_xfer = true;
5363 goto lock_skip_pending_xfer_clear;
5367 /* Clear pending task management requests */
5368 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
5369 if (ufshcd_clear_tm_cmd(hba, tag)) {
5370 err_tm = true;
5371 goto lock_skip_pending_xfer_clear;
5375 lock_skip_pending_xfer_clear:
5376 spin_lock_irqsave(hba->host->host_lock, flags);
5378 /* Complete the requests that are cleared by s/w */
5379 ufshcd_complete_requests(hba);
5381 if (err_xfer || err_tm)
5382 needs_reset = true;
5384 skip_pending_xfer_clear:
5385 /* Fatal errors need reset */
5386 if (needs_reset) {
5387 unsigned long max_doorbells = (1UL << hba->nutrs) - 1;
5390 * ufshcd_reset_and_restore() does the link reinitialization
5391 * which will need atleast one empty doorbell slot to send the
5392 * device management commands (NOP and query commands).
5393 * If there is no slot empty at this moment then free up last
5394 * slot forcefully.
5396 if (hba->outstanding_reqs == max_doorbells)
5397 __ufshcd_transfer_req_compl(hba,
5398 (1UL << (hba->nutrs - 1)));
5400 spin_unlock_irqrestore(hba->host->host_lock, flags);
5401 err = ufshcd_reset_and_restore(hba);
5402 spin_lock_irqsave(hba->host->host_lock, flags);
5403 if (err) {
5404 dev_err(hba->dev, "%s: reset and restore failed\n",
5405 __func__);
5406 hba->ufshcd_state = UFSHCD_STATE_ERROR;
5409 * Inform scsi mid-layer that we did reset and allow to handle
5410 * Unit Attention properly.
5412 scsi_report_bus_reset(hba->host, 0);
5413 hba->saved_err = 0;
5414 hba->saved_uic_err = 0;
5417 skip_err_handling:
5418 if (!needs_reset) {
5419 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
5420 if (hba->saved_err || hba->saved_uic_err)
5421 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
5422 __func__, hba->saved_err, hba->saved_uic_err);
5425 ufshcd_clear_eh_in_progress(hba);
5427 out:
5428 spin_unlock_irqrestore(hba->host->host_lock, flags);
5429 ufshcd_scsi_unblock_requests(hba);
5430 ufshcd_release(hba);
5431 pm_runtime_put_sync(hba->dev);
5435 * ufshcd_update_uic_error - check and set fatal UIC error flags.
5436 * @hba: per-adapter instance
5438 * Returns
5439 * IRQ_HANDLED - If interrupt is valid
5440 * IRQ_NONE - If invalid interrupt
5442 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
5444 u32 reg;
5445 irqreturn_t retval = IRQ_NONE;
5447 /* PHY layer lane error */
5448 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
5449 /* Ignore LINERESET indication, as this is not an error */
5450 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
5451 (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)) {
5453 * To know whether this error is fatal or not, DB timeout
5454 * must be checked but this error is handled separately.
5456 dev_dbg(hba->dev, "%s: UIC Lane error reported\n", __func__);
5457 ufshcd_update_reg_hist(&hba->ufs_stats.pa_err, reg);
5458 retval |= IRQ_HANDLED;
5461 /* PA_INIT_ERROR is fatal and needs UIC reset */
5462 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
5463 if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
5464 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
5465 ufshcd_update_reg_hist(&hba->ufs_stats.dl_err, reg);
5467 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
5468 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
5469 else if (hba->dev_quirks &
5470 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5471 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
5472 hba->uic_error |=
5473 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5474 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
5475 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
5477 retval |= IRQ_HANDLED;
5480 /* UIC NL/TL/DME errors needs software retry */
5481 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
5482 if ((reg & UIC_NETWORK_LAYER_ERROR) &&
5483 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
5484 ufshcd_update_reg_hist(&hba->ufs_stats.nl_err, reg);
5485 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
5486 retval |= IRQ_HANDLED;
5489 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
5490 if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
5491 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
5492 ufshcd_update_reg_hist(&hba->ufs_stats.tl_err, reg);
5493 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
5494 retval |= IRQ_HANDLED;
5497 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
5498 if ((reg & UIC_DME_ERROR) &&
5499 (reg & UIC_DME_ERROR_CODE_MASK)) {
5500 ufshcd_update_reg_hist(&hba->ufs_stats.dme_err, reg);
5501 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
5502 retval |= IRQ_HANDLED;
5505 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
5506 __func__, hba->uic_error);
5507 return retval;
5510 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
5511 u32 intr_mask)
5513 if (!ufshcd_is_auto_hibern8_supported(hba))
5514 return false;
5516 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
5517 return false;
5519 if (hba->active_uic_cmd &&
5520 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
5521 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
5522 return false;
5524 return true;
5528 * ufshcd_check_errors - Check for errors that need s/w attention
5529 * @hba: per-adapter instance
5531 * Returns
5532 * IRQ_HANDLED - If interrupt is valid
5533 * IRQ_NONE - If invalid interrupt
5535 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba)
5537 bool queue_eh_work = false;
5538 irqreturn_t retval = IRQ_NONE;
5540 if (hba->errors & INT_FATAL_ERRORS) {
5541 ufshcd_update_reg_hist(&hba->ufs_stats.fatal_err, hba->errors);
5542 queue_eh_work = true;
5545 if (hba->errors & UIC_ERROR) {
5546 hba->uic_error = 0;
5547 retval = ufshcd_update_uic_error(hba);
5548 if (hba->uic_error)
5549 queue_eh_work = true;
5552 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
5553 dev_err(hba->dev,
5554 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
5555 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
5556 "Enter" : "Exit",
5557 hba->errors, ufshcd_get_upmcrs(hba));
5558 ufshcd_update_reg_hist(&hba->ufs_stats.auto_hibern8_err,
5559 hba->errors);
5560 queue_eh_work = true;
5563 if (queue_eh_work) {
5565 * update the transfer error masks to sticky bits, let's do this
5566 * irrespective of current ufshcd_state.
5568 hba->saved_err |= hba->errors;
5569 hba->saved_uic_err |= hba->uic_error;
5571 /* handle fatal errors only when link is functional */
5572 if (hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL) {
5573 /* block commands from scsi mid-layer */
5574 ufshcd_scsi_block_requests(hba);
5576 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED;
5578 /* dump controller state before resetting */
5579 if (hba->saved_err & (INT_FATAL_ERRORS | UIC_ERROR)) {
5580 bool pr_prdt = !!(hba->saved_err &
5581 SYSTEM_BUS_FATAL_ERROR);
5583 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
5584 __func__, hba->saved_err,
5585 hba->saved_uic_err);
5587 ufshcd_print_host_regs(hba);
5588 ufshcd_print_pwr_info(hba);
5589 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
5590 ufshcd_print_trs(hba, hba->outstanding_reqs,
5591 pr_prdt);
5593 schedule_work(&hba->eh_work);
5595 retval |= IRQ_HANDLED;
5598 * if (!queue_eh_work) -
5599 * Other errors are either non-fatal where host recovers
5600 * itself without s/w intervention or errors that will be
5601 * handled by the SCSI core layer.
5603 return retval;
5607 * ufshcd_tmc_handler - handle task management function completion
5608 * @hba: per adapter instance
5610 * Returns
5611 * IRQ_HANDLED - If interrupt is valid
5612 * IRQ_NONE - If invalid interrupt
5614 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
5616 u32 tm_doorbell;
5618 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
5619 hba->tm_condition = tm_doorbell ^ hba->outstanding_tasks;
5620 if (hba->tm_condition) {
5621 wake_up(&hba->tm_wq);
5622 return IRQ_HANDLED;
5623 } else {
5624 return IRQ_NONE;
5629 * ufshcd_sl_intr - Interrupt service routine
5630 * @hba: per adapter instance
5631 * @intr_status: contains interrupts generated by the controller
5633 * Returns
5634 * IRQ_HANDLED - If interrupt is valid
5635 * IRQ_NONE - If invalid interrupt
5637 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
5639 irqreturn_t retval = IRQ_NONE;
5641 hba->errors = UFSHCD_ERROR_MASK & intr_status;
5643 if (ufshcd_is_auto_hibern8_error(hba, intr_status))
5644 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
5646 if (hba->errors)
5647 retval |= ufshcd_check_errors(hba);
5649 if (intr_status & UFSHCD_UIC_MASK)
5650 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
5652 if (intr_status & UTP_TASK_REQ_COMPL)
5653 retval |= ufshcd_tmc_handler(hba);
5655 if (intr_status & UTP_TRANSFER_REQ_COMPL)
5656 retval |= ufshcd_transfer_req_compl(hba);
5658 return retval;
5662 * ufshcd_intr - Main interrupt service routine
5663 * @irq: irq number
5664 * @__hba: pointer to adapter instance
5666 * Returns
5667 * IRQ_HANDLED - If interrupt is valid
5668 * IRQ_NONE - If invalid interrupt
5670 static irqreturn_t ufshcd_intr(int irq, void *__hba)
5672 u32 intr_status, enabled_intr_status;
5673 irqreturn_t retval = IRQ_NONE;
5674 struct ufs_hba *hba = __hba;
5675 int retries = hba->nutrs;
5677 spin_lock(hba->host->host_lock);
5678 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
5681 * There could be max of hba->nutrs reqs in flight and in worst case
5682 * if the reqs get finished 1 by 1 after the interrupt status is
5683 * read, make sure we handle them by checking the interrupt status
5684 * again in a loop until we process all of the reqs before returning.
5686 do {
5687 enabled_intr_status =
5688 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
5689 if (intr_status)
5690 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
5691 if (enabled_intr_status)
5692 retval |= ufshcd_sl_intr(hba, enabled_intr_status);
5694 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
5695 } while (intr_status && --retries);
5697 if (retval == IRQ_NONE) {
5698 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x\n",
5699 __func__, intr_status);
5700 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
5703 spin_unlock(hba->host->host_lock);
5704 return retval;
5707 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
5709 int err = 0;
5710 u32 mask = 1 << tag;
5711 unsigned long flags;
5713 if (!test_bit(tag, &hba->outstanding_tasks))
5714 goto out;
5716 spin_lock_irqsave(hba->host->host_lock, flags);
5717 ufshcd_utmrl_clear(hba, tag);
5718 spin_unlock_irqrestore(hba->host->host_lock, flags);
5720 /* poll for max. 1 sec to clear door bell register by h/w */
5721 err = ufshcd_wait_for_register(hba,
5722 REG_UTP_TASK_REQ_DOOR_BELL,
5723 mask, 0, 1000, 1000, true);
5724 out:
5725 return err;
5728 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
5729 struct utp_task_req_desc *treq, u8 tm_function)
5731 struct Scsi_Host *host = hba->host;
5732 unsigned long flags;
5733 int free_slot, task_tag, err;
5736 * Get free slot, sleep if slots are unavailable.
5737 * Even though we use wait_event() which sleeps indefinitely,
5738 * the maximum wait time is bounded by %TM_CMD_TIMEOUT.
5740 wait_event(hba->tm_tag_wq, ufshcd_get_tm_free_slot(hba, &free_slot));
5741 ufshcd_hold(hba, false);
5743 spin_lock_irqsave(host->host_lock, flags);
5744 task_tag = hba->nutrs + free_slot;
5746 treq->req_header.dword_0 |= cpu_to_be32(task_tag);
5748 memcpy(hba->utmrdl_base_addr + free_slot, treq, sizeof(*treq));
5749 ufshcd_vops_setup_task_mgmt(hba, free_slot, tm_function);
5751 /* send command to the controller */
5752 __set_bit(free_slot, &hba->outstanding_tasks);
5754 /* Make sure descriptors are ready before ringing the task doorbell */
5755 wmb();
5757 ufshcd_writel(hba, 1 << free_slot, REG_UTP_TASK_REQ_DOOR_BELL);
5758 /* Make sure that doorbell is committed immediately */
5759 wmb();
5761 spin_unlock_irqrestore(host->host_lock, flags);
5763 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_send");
5765 /* wait until the task management command is completed */
5766 err = wait_event_timeout(hba->tm_wq,
5767 test_bit(free_slot, &hba->tm_condition),
5768 msecs_to_jiffies(TM_CMD_TIMEOUT));
5769 if (!err) {
5770 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_complete_err");
5771 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
5772 __func__, tm_function);
5773 if (ufshcd_clear_tm_cmd(hba, free_slot))
5774 dev_WARN(hba->dev, "%s: unable clear tm cmd (slot %d) after timeout\n",
5775 __func__, free_slot);
5776 err = -ETIMEDOUT;
5777 } else {
5778 err = 0;
5779 memcpy(treq, hba->utmrdl_base_addr + free_slot, sizeof(*treq));
5781 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_complete");
5784 spin_lock_irqsave(hba->host->host_lock, flags);
5785 __clear_bit(free_slot, &hba->outstanding_tasks);
5786 spin_unlock_irqrestore(hba->host->host_lock, flags);
5788 clear_bit(free_slot, &hba->tm_condition);
5789 ufshcd_put_tm_slot(hba, free_slot);
5790 wake_up(&hba->tm_tag_wq);
5792 ufshcd_release(hba);
5793 return err;
5797 * ufshcd_issue_tm_cmd - issues task management commands to controller
5798 * @hba: per adapter instance
5799 * @lun_id: LUN ID to which TM command is sent
5800 * @task_id: task ID to which the TM command is applicable
5801 * @tm_function: task management function opcode
5802 * @tm_response: task management service response return value
5804 * Returns non-zero value on error, zero on success.
5806 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
5807 u8 tm_function, u8 *tm_response)
5809 struct utp_task_req_desc treq = { { 0 }, };
5810 int ocs_value, err;
5812 /* Configure task request descriptor */
5813 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
5814 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
5816 /* Configure task request UPIU */
5817 treq.req_header.dword_0 = cpu_to_be32(lun_id << 8) |
5818 cpu_to_be32(UPIU_TRANSACTION_TASK_REQ << 24);
5819 treq.req_header.dword_1 = cpu_to_be32(tm_function << 16);
5822 * The host shall provide the same value for LUN field in the basic
5823 * header and for Input Parameter.
5825 treq.input_param1 = cpu_to_be32(lun_id);
5826 treq.input_param2 = cpu_to_be32(task_id);
5828 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
5829 if (err == -ETIMEDOUT)
5830 return err;
5832 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
5833 if (ocs_value != OCS_SUCCESS)
5834 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
5835 __func__, ocs_value);
5836 else if (tm_response)
5837 *tm_response = be32_to_cpu(treq.output_param1) &
5838 MASK_TM_SERVICE_RESP;
5839 return err;
5843 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
5844 * @hba: per-adapter instance
5845 * @req_upiu: upiu request
5846 * @rsp_upiu: upiu reply
5847 * @desc_buff: pointer to descriptor buffer, NULL if NA
5848 * @buff_len: descriptor size, 0 if NA
5849 * @cmd_type: specifies the type (NOP, Query...)
5850 * @desc_op: descriptor operation
5852 * Those type of requests uses UTP Transfer Request Descriptor - utrd.
5853 * Therefore, it "rides" the device management infrastructure: uses its tag and
5854 * tasks work queues.
5856 * Since there is only one available tag for device management commands,
5857 * the caller is expected to hold the hba->dev_cmd.lock mutex.
5859 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
5860 struct utp_upiu_req *req_upiu,
5861 struct utp_upiu_req *rsp_upiu,
5862 u8 *desc_buff, int *buff_len,
5863 enum dev_cmd_type cmd_type,
5864 enum query_opcode desc_op)
5866 struct ufshcd_lrb *lrbp;
5867 int err = 0;
5868 int tag;
5869 struct completion wait;
5870 unsigned long flags;
5871 u32 upiu_flags;
5873 down_read(&hba->clk_scaling_lock);
5875 wait_event(hba->dev_cmd.tag_wq, ufshcd_get_dev_cmd_tag(hba, &tag));
5877 init_completion(&wait);
5878 lrbp = &hba->lrb[tag];
5879 WARN_ON(lrbp->cmd);
5881 lrbp->cmd = NULL;
5882 lrbp->sense_bufflen = 0;
5883 lrbp->sense_buffer = NULL;
5884 lrbp->task_tag = tag;
5885 lrbp->lun = 0;
5886 lrbp->intr_cmd = true;
5887 hba->dev_cmd.type = cmd_type;
5889 switch (hba->ufs_version) {
5890 case UFSHCI_VERSION_10:
5891 case UFSHCI_VERSION_11:
5892 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
5893 break;
5894 default:
5895 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
5896 break;
5899 /* update the task tag in the request upiu */
5900 req_upiu->header.dword_0 |= cpu_to_be32(tag);
5902 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
5904 /* just copy the upiu request as it is */
5905 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
5906 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
5907 /* The Data Segment Area is optional depending upon the query
5908 * function value. for WRITE DESCRIPTOR, the data segment
5909 * follows right after the tsf.
5911 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
5912 *buff_len = 0;
5915 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
5917 hba->dev_cmd.complete = &wait;
5919 /* Make sure descriptors are ready before ringing the doorbell */
5920 wmb();
5921 spin_lock_irqsave(hba->host->host_lock, flags);
5922 ufshcd_send_command(hba, tag);
5923 spin_unlock_irqrestore(hba->host->host_lock, flags);
5926 * ignore the returning value here - ufshcd_check_query_response is
5927 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
5928 * read the response directly ignoring all errors.
5930 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
5932 /* just copy the upiu response as it is */
5933 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
5934 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
5935 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
5936 u16 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
5937 MASK_QUERY_DATA_SEG_LEN;
5939 if (*buff_len >= resp_len) {
5940 memcpy(desc_buff, descp, resp_len);
5941 *buff_len = resp_len;
5942 } else {
5943 dev_warn(hba->dev,
5944 "%s: rsp size %d is bigger than buffer size %d",
5945 __func__, resp_len, *buff_len);
5946 *buff_len = 0;
5947 err = -EINVAL;
5951 ufshcd_put_dev_cmd_tag(hba, tag);
5952 wake_up(&hba->dev_cmd.tag_wq);
5953 up_read(&hba->clk_scaling_lock);
5954 return err;
5958 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
5959 * @hba: per-adapter instance
5960 * @req_upiu: upiu request
5961 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands
5962 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
5963 * @desc_buff: pointer to descriptor buffer, NULL if NA
5964 * @buff_len: descriptor size, 0 if NA
5965 * @desc_op: descriptor operation
5967 * Supports UTP Transfer requests (nop and query), and UTP Task
5968 * Management requests.
5969 * It is up to the caller to fill the upiu conent properly, as it will
5970 * be copied without any further input validations.
5972 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
5973 struct utp_upiu_req *req_upiu,
5974 struct utp_upiu_req *rsp_upiu,
5975 int msgcode,
5976 u8 *desc_buff, int *buff_len,
5977 enum query_opcode desc_op)
5979 int err;
5980 enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
5981 struct utp_task_req_desc treq = { { 0 }, };
5982 int ocs_value;
5983 u8 tm_f = be32_to_cpu(req_upiu->header.dword_1) >> 16 & MASK_TM_FUNC;
5985 switch (msgcode) {
5986 case UPIU_TRANSACTION_NOP_OUT:
5987 cmd_type = DEV_CMD_TYPE_NOP;
5988 /* fall through */
5989 case UPIU_TRANSACTION_QUERY_REQ:
5990 ufshcd_hold(hba, false);
5991 mutex_lock(&hba->dev_cmd.lock);
5992 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
5993 desc_buff, buff_len,
5994 cmd_type, desc_op);
5995 mutex_unlock(&hba->dev_cmd.lock);
5996 ufshcd_release(hba);
5998 break;
5999 case UPIU_TRANSACTION_TASK_REQ:
6000 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6001 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6003 memcpy(&treq.req_header, req_upiu, sizeof(*req_upiu));
6005 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
6006 if (err == -ETIMEDOUT)
6007 break;
6009 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6010 if (ocs_value != OCS_SUCCESS) {
6011 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
6012 ocs_value);
6013 break;
6016 memcpy(rsp_upiu, &treq.rsp_header, sizeof(*rsp_upiu));
6018 break;
6019 default:
6020 err = -EINVAL;
6022 break;
6025 return err;
6029 * ufshcd_eh_device_reset_handler - device reset handler registered to
6030 * scsi layer.
6031 * @cmd: SCSI command pointer
6033 * Returns SUCCESS/FAILED
6035 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
6037 struct Scsi_Host *host;
6038 struct ufs_hba *hba;
6039 unsigned int tag;
6040 u32 pos;
6041 int err;
6042 u8 resp = 0xF;
6043 struct ufshcd_lrb *lrbp;
6044 unsigned long flags;
6046 host = cmd->device->host;
6047 hba = shost_priv(host);
6048 tag = cmd->request->tag;
6050 lrbp = &hba->lrb[tag];
6051 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, 0, UFS_LOGICAL_RESET, &resp);
6052 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6053 if (!err)
6054 err = resp;
6055 goto out;
6058 /* clear the commands that were pending for corresponding LUN */
6059 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
6060 if (hba->lrb[pos].lun == lrbp->lun) {
6061 err = ufshcd_clear_cmd(hba, pos);
6062 if (err)
6063 break;
6066 spin_lock_irqsave(host->host_lock, flags);
6067 ufshcd_transfer_req_compl(hba);
6068 spin_unlock_irqrestore(host->host_lock, flags);
6070 out:
6071 hba->req_abort_count = 0;
6072 ufshcd_update_reg_hist(&hba->ufs_stats.dev_reset, (u32)err);
6073 if (!err) {
6074 err = SUCCESS;
6075 } else {
6076 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6077 err = FAILED;
6079 return err;
6082 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
6084 struct ufshcd_lrb *lrbp;
6085 int tag;
6087 for_each_set_bit(tag, &bitmap, hba->nutrs) {
6088 lrbp = &hba->lrb[tag];
6089 lrbp->req_abort_skip = true;
6094 * ufshcd_abort - abort a specific command
6095 * @cmd: SCSI command pointer
6097 * Abort the pending command in device by sending UFS_ABORT_TASK task management
6098 * command, and in host controller by clearing the door-bell register. There can
6099 * be race between controller sending the command to the device while abort is
6100 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
6101 * really issued and then try to abort it.
6103 * Returns SUCCESS/FAILED
6105 static int ufshcd_abort(struct scsi_cmnd *cmd)
6107 struct Scsi_Host *host;
6108 struct ufs_hba *hba;
6109 unsigned long flags;
6110 unsigned int tag;
6111 int err = 0;
6112 int poll_cnt;
6113 u8 resp = 0xF;
6114 struct ufshcd_lrb *lrbp;
6115 u32 reg;
6117 host = cmd->device->host;
6118 hba = shost_priv(host);
6119 tag = cmd->request->tag;
6120 lrbp = &hba->lrb[tag];
6121 if (!ufshcd_valid_tag(hba, tag)) {
6122 dev_err(hba->dev,
6123 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
6124 __func__, tag, cmd, cmd->request);
6125 BUG();
6129 * Task abort to the device W-LUN is illegal. When this command
6130 * will fail, due to spec violation, scsi err handling next step
6131 * will be to send LU reset which, again, is a spec violation.
6132 * To avoid these unnecessary/illegal step we skip to the last error
6133 * handling stage: reset and restore.
6135 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN)
6136 return ufshcd_eh_host_reset_handler(cmd);
6138 ufshcd_hold(hba, false);
6139 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6140 /* If command is already aborted/completed, return SUCCESS */
6141 if (!(test_bit(tag, &hba->outstanding_reqs))) {
6142 dev_err(hba->dev,
6143 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
6144 __func__, tag, hba->outstanding_reqs, reg);
6145 goto out;
6148 if (!(reg & (1 << tag))) {
6149 dev_err(hba->dev,
6150 "%s: cmd was completed, but without a notifying intr, tag = %d",
6151 __func__, tag);
6154 /* Print Transfer Request of aborted task */
6155 dev_err(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
6158 * Print detailed info about aborted request.
6159 * As more than one request might get aborted at the same time,
6160 * print full information only for the first aborted request in order
6161 * to reduce repeated printouts. For other aborted requests only print
6162 * basic details.
6164 scsi_print_command(hba->lrb[tag].cmd);
6165 if (!hba->req_abort_count) {
6166 ufshcd_update_reg_hist(&hba->ufs_stats.task_abort, 0);
6167 ufshcd_print_host_regs(hba);
6168 ufshcd_print_host_state(hba);
6169 ufshcd_print_pwr_info(hba);
6170 ufshcd_print_trs(hba, 1 << tag, true);
6171 } else {
6172 ufshcd_print_trs(hba, 1 << tag, false);
6174 hba->req_abort_count++;
6176 /* Skip task abort in case previous aborts failed and report failure */
6177 if (lrbp->req_abort_skip) {
6178 err = -EIO;
6179 goto out;
6182 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
6183 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6184 UFS_QUERY_TASK, &resp);
6185 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
6186 /* cmd pending in the device */
6187 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
6188 __func__, tag);
6189 break;
6190 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6192 * cmd not pending in the device, check if it is
6193 * in transition.
6195 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
6196 __func__, tag);
6197 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6198 if (reg & (1 << tag)) {
6199 /* sleep for max. 200us to stabilize */
6200 usleep_range(100, 200);
6201 continue;
6203 /* command completed already */
6204 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
6205 __func__, tag);
6206 goto out;
6207 } else {
6208 dev_err(hba->dev,
6209 "%s: no response from device. tag = %d, err %d\n",
6210 __func__, tag, err);
6211 if (!err)
6212 err = resp; /* service response error */
6213 goto out;
6217 if (!poll_cnt) {
6218 err = -EBUSY;
6219 goto out;
6222 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6223 UFS_ABORT_TASK, &resp);
6224 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6225 if (!err) {
6226 err = resp; /* service response error */
6227 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
6228 __func__, tag, err);
6230 goto out;
6233 err = ufshcd_clear_cmd(hba, tag);
6234 if (err) {
6235 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
6236 __func__, tag, err);
6237 goto out;
6240 scsi_dma_unmap(cmd);
6242 spin_lock_irqsave(host->host_lock, flags);
6243 ufshcd_outstanding_req_clear(hba, tag);
6244 hba->lrb[tag].cmd = NULL;
6245 spin_unlock_irqrestore(host->host_lock, flags);
6247 clear_bit_unlock(tag, &hba->lrb_in_use);
6248 wake_up(&hba->dev_cmd.tag_wq);
6250 out:
6251 if (!err) {
6252 err = SUCCESS;
6253 } else {
6254 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6255 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
6256 err = FAILED;
6260 * This ufshcd_release() corresponds to the original scsi cmd that got
6261 * aborted here (as we won't get any IRQ for it).
6263 ufshcd_release(hba);
6264 return err;
6268 * ufshcd_host_reset_and_restore - reset and restore host controller
6269 * @hba: per-adapter instance
6271 * Note that host controller reset may issue DME_RESET to
6272 * local and remote (device) Uni-Pro stack and the attributes
6273 * are reset to default state.
6275 * Returns zero on success, non-zero on failure
6277 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
6279 int err;
6280 unsigned long flags;
6282 /* Reset the host controller */
6283 spin_lock_irqsave(hba->host->host_lock, flags);
6284 ufshcd_hba_stop(hba, false);
6285 spin_unlock_irqrestore(hba->host->host_lock, flags);
6287 /* scale up clocks to max frequency before full reinitialization */
6288 ufshcd_scale_clks(hba, true);
6290 err = ufshcd_hba_enable(hba);
6291 if (err)
6292 goto out;
6294 /* Establish the link again and restore the device */
6295 err = ufshcd_probe_hba(hba);
6297 if (!err && (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL))
6298 err = -EIO;
6299 out:
6300 if (err)
6301 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
6302 ufshcd_update_reg_hist(&hba->ufs_stats.host_reset, (u32)err);
6303 return err;
6307 * ufshcd_reset_and_restore - reset and re-initialize host/device
6308 * @hba: per-adapter instance
6310 * Reset and recover device, host and re-establish link. This
6311 * is helpful to recover the communication in fatal error conditions.
6313 * Returns zero on success, non-zero on failure
6315 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
6317 int err = 0;
6318 unsigned long flags;
6319 int retries = MAX_HOST_RESET_RETRIES;
6321 do {
6322 /* Reset the attached device */
6323 ufshcd_vops_device_reset(hba);
6325 err = ufshcd_host_reset_and_restore(hba);
6326 } while (err && --retries);
6329 * After reset the door-bell might be cleared, complete
6330 * outstanding requests in s/w here.
6332 spin_lock_irqsave(hba->host->host_lock, flags);
6333 ufshcd_transfer_req_compl(hba);
6334 ufshcd_tmc_handler(hba);
6335 spin_unlock_irqrestore(hba->host->host_lock, flags);
6337 return err;
6341 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
6342 * @cmd: SCSI command pointer
6344 * Returns SUCCESS/FAILED
6346 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
6348 int err;
6349 unsigned long flags;
6350 struct ufs_hba *hba;
6352 hba = shost_priv(cmd->device->host);
6354 ufshcd_hold(hba, false);
6356 * Check if there is any race with fatal error handling.
6357 * If so, wait for it to complete. Even though fatal error
6358 * handling does reset and restore in some cases, don't assume
6359 * anything out of it. We are just avoiding race here.
6361 do {
6362 spin_lock_irqsave(hba->host->host_lock, flags);
6363 if (!(work_pending(&hba->eh_work) ||
6364 hba->ufshcd_state == UFSHCD_STATE_RESET ||
6365 hba->ufshcd_state == UFSHCD_STATE_EH_SCHEDULED))
6366 break;
6367 spin_unlock_irqrestore(hba->host->host_lock, flags);
6368 dev_dbg(hba->dev, "%s: reset in progress\n", __func__);
6369 flush_work(&hba->eh_work);
6370 } while (1);
6372 hba->ufshcd_state = UFSHCD_STATE_RESET;
6373 ufshcd_set_eh_in_progress(hba);
6374 spin_unlock_irqrestore(hba->host->host_lock, flags);
6376 err = ufshcd_reset_and_restore(hba);
6378 spin_lock_irqsave(hba->host->host_lock, flags);
6379 if (!err) {
6380 err = SUCCESS;
6381 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6382 } else {
6383 err = FAILED;
6384 hba->ufshcd_state = UFSHCD_STATE_ERROR;
6386 ufshcd_clear_eh_in_progress(hba);
6387 spin_unlock_irqrestore(hba->host->host_lock, flags);
6389 ufshcd_release(hba);
6390 return err;
6394 * ufshcd_get_max_icc_level - calculate the ICC level
6395 * @sup_curr_uA: max. current supported by the regulator
6396 * @start_scan: row at the desc table to start scan from
6397 * @buff: power descriptor buffer
6399 * Returns calculated max ICC level for specific regulator
6401 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
6403 int i;
6404 int curr_uA;
6405 u16 data;
6406 u16 unit;
6408 for (i = start_scan; i >= 0; i--) {
6409 data = be16_to_cpup((__be16 *)&buff[2 * i]);
6410 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
6411 ATTR_ICC_LVL_UNIT_OFFSET;
6412 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
6413 switch (unit) {
6414 case UFSHCD_NANO_AMP:
6415 curr_uA = curr_uA / 1000;
6416 break;
6417 case UFSHCD_MILI_AMP:
6418 curr_uA = curr_uA * 1000;
6419 break;
6420 case UFSHCD_AMP:
6421 curr_uA = curr_uA * 1000 * 1000;
6422 break;
6423 case UFSHCD_MICRO_AMP:
6424 default:
6425 break;
6427 if (sup_curr_uA >= curr_uA)
6428 break;
6430 if (i < 0) {
6431 i = 0;
6432 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
6435 return (u32)i;
6439 * ufshcd_calc_icc_level - calculate the max ICC level
6440 * In case regulators are not initialized we'll return 0
6441 * @hba: per-adapter instance
6442 * @desc_buf: power descriptor buffer to extract ICC levels from.
6443 * @len: length of desc_buff
6445 * Returns calculated ICC level
6447 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
6448 u8 *desc_buf, int len)
6450 u32 icc_level = 0;
6452 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
6453 !hba->vreg_info.vccq2) {
6454 dev_err(hba->dev,
6455 "%s: Regulator capability was not set, actvIccLevel=%d",
6456 __func__, icc_level);
6457 goto out;
6460 if (hba->vreg_info.vcc && hba->vreg_info.vcc->max_uA)
6461 icc_level = ufshcd_get_max_icc_level(
6462 hba->vreg_info.vcc->max_uA,
6463 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
6464 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
6466 if (hba->vreg_info.vccq && hba->vreg_info.vccq->max_uA)
6467 icc_level = ufshcd_get_max_icc_level(
6468 hba->vreg_info.vccq->max_uA,
6469 icc_level,
6470 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
6472 if (hba->vreg_info.vccq2 && hba->vreg_info.vccq2->max_uA)
6473 icc_level = ufshcd_get_max_icc_level(
6474 hba->vreg_info.vccq2->max_uA,
6475 icc_level,
6476 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
6477 out:
6478 return icc_level;
6481 static void ufshcd_init_icc_levels(struct ufs_hba *hba)
6483 int ret;
6484 int buff_len = hba->desc_size.pwr_desc;
6485 u8 *desc_buf;
6487 desc_buf = kmalloc(buff_len, GFP_KERNEL);
6488 if (!desc_buf)
6489 return;
6491 ret = ufshcd_read_power_desc(hba, desc_buf, buff_len);
6492 if (ret) {
6493 dev_err(hba->dev,
6494 "%s: Failed reading power descriptor.len = %d ret = %d",
6495 __func__, buff_len, ret);
6496 goto out;
6499 hba->init_prefetch_data.icc_level =
6500 ufshcd_find_max_sup_active_icc_level(hba,
6501 desc_buf, buff_len);
6502 dev_dbg(hba->dev, "%s: setting icc_level 0x%x",
6503 __func__, hba->init_prefetch_data.icc_level);
6505 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
6506 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0,
6507 &hba->init_prefetch_data.icc_level);
6509 if (ret)
6510 dev_err(hba->dev,
6511 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
6512 __func__, hba->init_prefetch_data.icc_level , ret);
6514 out:
6515 kfree(desc_buf);
6519 * ufshcd_scsi_add_wlus - Adds required W-LUs
6520 * @hba: per-adapter instance
6522 * UFS device specification requires the UFS devices to support 4 well known
6523 * logical units:
6524 * "REPORT_LUNS" (address: 01h)
6525 * "UFS Device" (address: 50h)
6526 * "RPMB" (address: 44h)
6527 * "BOOT" (address: 30h)
6528 * UFS device's power management needs to be controlled by "POWER CONDITION"
6529 * field of SSU (START STOP UNIT) command. But this "power condition" field
6530 * will take effect only when its sent to "UFS device" well known logical unit
6531 * hence we require the scsi_device instance to represent this logical unit in
6532 * order for the UFS host driver to send the SSU command for power management.
6534 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
6535 * Block) LU so user space process can control this LU. User space may also
6536 * want to have access to BOOT LU.
6538 * This function adds scsi device instances for each of all well known LUs
6539 * (except "REPORT LUNS" LU).
6541 * Returns zero on success (all required W-LUs are added successfully),
6542 * non-zero error value on failure (if failed to add any of the required W-LU).
6544 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
6546 int ret = 0;
6547 struct scsi_device *sdev_rpmb;
6548 struct scsi_device *sdev_boot;
6550 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
6551 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
6552 if (IS_ERR(hba->sdev_ufs_device)) {
6553 ret = PTR_ERR(hba->sdev_ufs_device);
6554 hba->sdev_ufs_device = NULL;
6555 goto out;
6557 scsi_device_put(hba->sdev_ufs_device);
6559 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
6560 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
6561 if (IS_ERR(sdev_rpmb)) {
6562 ret = PTR_ERR(sdev_rpmb);
6563 goto remove_sdev_ufs_device;
6565 scsi_device_put(sdev_rpmb);
6567 sdev_boot = __scsi_add_device(hba->host, 0, 0,
6568 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
6569 if (IS_ERR(sdev_boot))
6570 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
6571 else
6572 scsi_device_put(sdev_boot);
6573 goto out;
6575 remove_sdev_ufs_device:
6576 scsi_remove_device(hba->sdev_ufs_device);
6577 out:
6578 return ret;
6581 static int ufs_get_device_desc(struct ufs_hba *hba,
6582 struct ufs_dev_desc *dev_desc)
6584 int err;
6585 size_t buff_len;
6586 u8 model_index;
6587 u8 *desc_buf;
6589 if (!dev_desc)
6590 return -EINVAL;
6592 buff_len = max_t(size_t, hba->desc_size.dev_desc,
6593 QUERY_DESC_MAX_SIZE + 1);
6594 desc_buf = kmalloc(buff_len, GFP_KERNEL);
6595 if (!desc_buf) {
6596 err = -ENOMEM;
6597 goto out;
6600 err = ufshcd_read_device_desc(hba, desc_buf, hba->desc_size.dev_desc);
6601 if (err) {
6602 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
6603 __func__, err);
6604 goto out;
6608 * getting vendor (manufacturerID) and Bank Index in big endian
6609 * format
6611 dev_desc->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
6612 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
6614 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
6615 err = ufshcd_read_string_desc(hba, model_index,
6616 &dev_desc->model, SD_ASCII_STD);
6617 if (err < 0) {
6618 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
6619 __func__, err);
6620 goto out;
6624 * ufshcd_read_string_desc returns size of the string
6625 * reset the error value
6627 err = 0;
6629 out:
6630 kfree(desc_buf);
6631 return err;
6634 static void ufs_put_device_desc(struct ufs_dev_desc *dev_desc)
6636 kfree(dev_desc->model);
6637 dev_desc->model = NULL;
6640 static void ufs_fixup_device_setup(struct ufs_hba *hba,
6641 struct ufs_dev_desc *dev_desc)
6643 struct ufs_dev_fix *f;
6645 for (f = ufs_fixups; f->quirk; f++) {
6646 if ((f->card.wmanufacturerid == dev_desc->wmanufacturerid ||
6647 f->card.wmanufacturerid == UFS_ANY_VENDOR) &&
6648 ((dev_desc->model &&
6649 STR_PRFX_EQUAL(f->card.model, dev_desc->model)) ||
6650 !strcmp(f->card.model, UFS_ANY_MODEL)))
6651 hba->dev_quirks |= f->quirk;
6656 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
6657 * @hba: per-adapter instance
6659 * PA_TActivate parameter can be tuned manually if UniPro version is less than
6660 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
6661 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
6662 * the hibern8 exit latency.
6664 * Returns zero on success, non-zero error value on failure.
6666 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
6668 int ret = 0;
6669 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
6671 ret = ufshcd_dme_peer_get(hba,
6672 UIC_ARG_MIB_SEL(
6673 RX_MIN_ACTIVATETIME_CAPABILITY,
6674 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
6675 &peer_rx_min_activatetime);
6676 if (ret)
6677 goto out;
6679 /* make sure proper unit conversion is applied */
6680 tuned_pa_tactivate =
6681 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
6682 / PA_TACTIVATE_TIME_UNIT_US);
6683 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
6684 tuned_pa_tactivate);
6686 out:
6687 return ret;
6691 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
6692 * @hba: per-adapter instance
6694 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
6695 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
6696 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
6697 * This optimal value can help reduce the hibern8 exit latency.
6699 * Returns zero on success, non-zero error value on failure.
6701 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
6703 int ret = 0;
6704 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
6705 u32 max_hibern8_time, tuned_pa_hibern8time;
6707 ret = ufshcd_dme_get(hba,
6708 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
6709 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
6710 &local_tx_hibern8_time_cap);
6711 if (ret)
6712 goto out;
6714 ret = ufshcd_dme_peer_get(hba,
6715 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
6716 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
6717 &peer_rx_hibern8_time_cap);
6718 if (ret)
6719 goto out;
6721 max_hibern8_time = max(local_tx_hibern8_time_cap,
6722 peer_rx_hibern8_time_cap);
6723 /* make sure proper unit conversion is applied */
6724 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
6725 / PA_HIBERN8_TIME_UNIT_US);
6726 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
6727 tuned_pa_hibern8time);
6728 out:
6729 return ret;
6733 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
6734 * less than device PA_TACTIVATE time.
6735 * @hba: per-adapter instance
6737 * Some UFS devices require host PA_TACTIVATE to be lower than device
6738 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
6739 * for such devices.
6741 * Returns zero on success, non-zero error value on failure.
6743 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
6745 int ret = 0;
6746 u32 granularity, peer_granularity;
6747 u32 pa_tactivate, peer_pa_tactivate;
6748 u32 pa_tactivate_us, peer_pa_tactivate_us;
6749 u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
6751 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
6752 &granularity);
6753 if (ret)
6754 goto out;
6756 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
6757 &peer_granularity);
6758 if (ret)
6759 goto out;
6761 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
6762 (granularity > PA_GRANULARITY_MAX_VAL)) {
6763 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
6764 __func__, granularity);
6765 return -EINVAL;
6768 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
6769 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
6770 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
6771 __func__, peer_granularity);
6772 return -EINVAL;
6775 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
6776 if (ret)
6777 goto out;
6779 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
6780 &peer_pa_tactivate);
6781 if (ret)
6782 goto out;
6784 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
6785 peer_pa_tactivate_us = peer_pa_tactivate *
6786 gran_to_us_table[peer_granularity - 1];
6788 if (pa_tactivate_us > peer_pa_tactivate_us) {
6789 u32 new_peer_pa_tactivate;
6791 new_peer_pa_tactivate = pa_tactivate_us /
6792 gran_to_us_table[peer_granularity - 1];
6793 new_peer_pa_tactivate++;
6794 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
6795 new_peer_pa_tactivate);
6798 out:
6799 return ret;
6802 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
6804 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
6805 ufshcd_tune_pa_tactivate(hba);
6806 ufshcd_tune_pa_hibern8time(hba);
6809 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
6810 /* set 1ms timeout for PA_TACTIVATE */
6811 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
6813 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
6814 ufshcd_quirk_tune_host_pa_tactivate(hba);
6816 ufshcd_vops_apply_dev_quirks(hba);
6819 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
6821 hba->ufs_stats.hibern8_exit_cnt = 0;
6822 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
6823 hba->req_abort_count = 0;
6826 static void ufshcd_init_desc_sizes(struct ufs_hba *hba)
6828 int err;
6830 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_DEVICE, 0,
6831 &hba->desc_size.dev_desc);
6832 if (err)
6833 hba->desc_size.dev_desc = QUERY_DESC_DEVICE_DEF_SIZE;
6835 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_POWER, 0,
6836 &hba->desc_size.pwr_desc);
6837 if (err)
6838 hba->desc_size.pwr_desc = QUERY_DESC_POWER_DEF_SIZE;
6840 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_INTERCONNECT, 0,
6841 &hba->desc_size.interc_desc);
6842 if (err)
6843 hba->desc_size.interc_desc = QUERY_DESC_INTERCONNECT_DEF_SIZE;
6845 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_CONFIGURATION, 0,
6846 &hba->desc_size.conf_desc);
6847 if (err)
6848 hba->desc_size.conf_desc = QUERY_DESC_CONFIGURATION_DEF_SIZE;
6850 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_UNIT, 0,
6851 &hba->desc_size.unit_desc);
6852 if (err)
6853 hba->desc_size.unit_desc = QUERY_DESC_UNIT_DEF_SIZE;
6855 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_GEOMETRY, 0,
6856 &hba->desc_size.geom_desc);
6857 if (err)
6858 hba->desc_size.geom_desc = QUERY_DESC_GEOMETRY_DEF_SIZE;
6860 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_HEALTH, 0,
6861 &hba->desc_size.hlth_desc);
6862 if (err)
6863 hba->desc_size.hlth_desc = QUERY_DESC_HEALTH_DEF_SIZE;
6866 static struct ufs_ref_clk ufs_ref_clk_freqs[] = {
6867 {19200000, REF_CLK_FREQ_19_2_MHZ},
6868 {26000000, REF_CLK_FREQ_26_MHZ},
6869 {38400000, REF_CLK_FREQ_38_4_MHZ},
6870 {52000000, REF_CLK_FREQ_52_MHZ},
6871 {0, REF_CLK_FREQ_INVAL},
6874 static enum ufs_ref_clk_freq
6875 ufs_get_bref_clk_from_hz(unsigned long freq)
6877 int i;
6879 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
6880 if (ufs_ref_clk_freqs[i].freq_hz == freq)
6881 return ufs_ref_clk_freqs[i].val;
6883 return REF_CLK_FREQ_INVAL;
6886 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
6888 unsigned long freq;
6890 freq = clk_get_rate(refclk);
6892 hba->dev_ref_clk_freq =
6893 ufs_get_bref_clk_from_hz(freq);
6895 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
6896 dev_err(hba->dev,
6897 "invalid ref_clk setting = %ld\n", freq);
6900 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
6902 int err;
6903 u32 ref_clk;
6904 u32 freq = hba->dev_ref_clk_freq;
6906 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
6907 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
6909 if (err) {
6910 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
6911 err);
6912 goto out;
6915 if (ref_clk == freq)
6916 goto out; /* nothing to update */
6918 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
6919 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
6921 if (err) {
6922 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
6923 ufs_ref_clk_freqs[freq].freq_hz);
6924 goto out;
6927 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
6928 ufs_ref_clk_freqs[freq].freq_hz);
6930 out:
6931 return err;
6935 * ufshcd_probe_hba - probe hba to detect device and initialize
6936 * @hba: per-adapter instance
6938 * Execute link-startup and verify device initialization
6940 static int ufshcd_probe_hba(struct ufs_hba *hba)
6942 struct ufs_dev_desc card = {0};
6943 int ret;
6944 ktime_t start = ktime_get();
6946 ret = ufshcd_link_startup(hba);
6947 if (ret)
6948 goto out;
6950 /* set the default level for urgent bkops */
6951 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
6952 hba->is_urgent_bkops_lvl_checked = false;
6954 /* Debug counters initialization */
6955 ufshcd_clear_dbg_ufs_stats(hba);
6957 /* UniPro link is active now */
6958 ufshcd_set_link_active(hba);
6960 ret = ufshcd_verify_dev_init(hba);
6961 if (ret)
6962 goto out;
6964 ret = ufshcd_complete_dev_init(hba);
6965 if (ret)
6966 goto out;
6968 /* Init check for device descriptor sizes */
6969 ufshcd_init_desc_sizes(hba);
6971 ret = ufs_get_device_desc(hba, &card);
6972 if (ret) {
6973 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
6974 __func__, ret);
6975 goto out;
6978 ufs_fixup_device_setup(hba, &card);
6979 ufs_put_device_desc(&card);
6981 ufshcd_tune_unipro_params(hba);
6983 /* UFS device is also active now */
6984 ufshcd_set_ufs_dev_active(hba);
6985 ufshcd_force_reset_auto_bkops(hba);
6986 hba->wlun_dev_clr_ua = true;
6988 if (ufshcd_get_max_pwr_mode(hba)) {
6989 dev_err(hba->dev,
6990 "%s: Failed getting max supported power mode\n",
6991 __func__);
6992 } else {
6994 * Set the right value to bRefClkFreq before attempting to
6995 * switch to HS gears.
6997 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
6998 ufshcd_set_dev_ref_clk(hba);
6999 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
7000 if (ret) {
7001 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
7002 __func__, ret);
7003 goto out;
7007 /* set the state as operational after switching to desired gear */
7008 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
7010 /* Enable Auto-Hibernate if configured */
7011 ufshcd_auto_hibern8_enable(hba);
7014 * If we are in error handling context or in power management callbacks
7015 * context, no need to scan the host
7017 if (!ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
7018 bool flag;
7020 /* clear any previous UFS device information */
7021 memset(&hba->dev_info, 0, sizeof(hba->dev_info));
7022 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
7023 QUERY_FLAG_IDN_PWR_ON_WPE, &flag))
7024 hba->dev_info.f_power_on_wp_en = flag;
7026 if (!hba->is_init_prefetch)
7027 ufshcd_init_icc_levels(hba);
7029 /* Add required well known logical units to scsi mid layer */
7030 if (ufshcd_scsi_add_wlus(hba))
7031 goto out;
7033 /* Initialize devfreq after UFS device is detected */
7034 if (ufshcd_is_clkscaling_supported(hba)) {
7035 memcpy(&hba->clk_scaling.saved_pwr_info.info,
7036 &hba->pwr_info,
7037 sizeof(struct ufs_pa_layer_attr));
7038 hba->clk_scaling.saved_pwr_info.is_valid = true;
7039 if (!hba->devfreq) {
7040 ret = ufshcd_devfreq_init(hba);
7041 if (ret)
7042 goto out;
7044 hba->clk_scaling.is_allowed = true;
7047 ufs_bsg_probe(hba);
7049 scsi_scan_host(hba->host);
7050 pm_runtime_put_sync(hba->dev);
7053 if (!hba->is_init_prefetch)
7054 hba->is_init_prefetch = true;
7056 out:
7058 * If we failed to initialize the device or the device is not
7059 * present, turn off the power/clocks etc.
7061 if (ret && !ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
7062 pm_runtime_put_sync(hba->dev);
7063 ufshcd_exit_clk_scaling(hba);
7064 ufshcd_hba_exit(hba);
7067 trace_ufshcd_init(dev_name(hba->dev), ret,
7068 ktime_to_us(ktime_sub(ktime_get(), start)),
7069 hba->curr_dev_pwr_mode, hba->uic_link_state);
7070 return ret;
7074 * ufshcd_async_scan - asynchronous execution for probing hba
7075 * @data: data pointer to pass to this function
7076 * @cookie: cookie data
7078 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
7080 struct ufs_hba *hba = (struct ufs_hba *)data;
7082 ufshcd_probe_hba(hba);
7085 static enum blk_eh_timer_return ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
7087 unsigned long flags;
7088 struct Scsi_Host *host;
7089 struct ufs_hba *hba;
7090 int index;
7091 bool found = false;
7093 if (!scmd || !scmd->device || !scmd->device->host)
7094 return BLK_EH_DONE;
7096 host = scmd->device->host;
7097 hba = shost_priv(host);
7098 if (!hba)
7099 return BLK_EH_DONE;
7101 spin_lock_irqsave(host->host_lock, flags);
7103 for_each_set_bit(index, &hba->outstanding_reqs, hba->nutrs) {
7104 if (hba->lrb[index].cmd == scmd) {
7105 found = true;
7106 break;
7110 spin_unlock_irqrestore(host->host_lock, flags);
7113 * Bypass SCSI error handling and reset the block layer timer if this
7114 * SCSI command was not actually dispatched to UFS driver, otherwise
7115 * let SCSI layer handle the error as usual.
7117 return found ? BLK_EH_DONE : BLK_EH_RESET_TIMER;
7120 static const struct attribute_group *ufshcd_driver_groups[] = {
7121 &ufs_sysfs_unit_descriptor_group,
7122 &ufs_sysfs_lun_attributes_group,
7123 NULL,
7126 static struct scsi_host_template ufshcd_driver_template = {
7127 .module = THIS_MODULE,
7128 .name = UFSHCD,
7129 .proc_name = UFSHCD,
7130 .queuecommand = ufshcd_queuecommand,
7131 .slave_alloc = ufshcd_slave_alloc,
7132 .slave_configure = ufshcd_slave_configure,
7133 .slave_destroy = ufshcd_slave_destroy,
7134 .change_queue_depth = ufshcd_change_queue_depth,
7135 .eh_abort_handler = ufshcd_abort,
7136 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
7137 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
7138 .eh_timed_out = ufshcd_eh_timed_out,
7139 .this_id = -1,
7140 .sg_tablesize = SG_ALL,
7141 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
7142 .can_queue = UFSHCD_CAN_QUEUE,
7143 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX,
7144 .max_host_blocked = 1,
7145 .track_queue_depth = 1,
7146 .sdev_groups = ufshcd_driver_groups,
7147 .dma_boundary = PAGE_SIZE - 1,
7148 .rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS,
7151 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
7152 int ua)
7154 int ret;
7156 if (!vreg)
7157 return 0;
7160 * "set_load" operation shall be required on those regulators
7161 * which specifically configured current limitation. Otherwise
7162 * zero max_uA may cause unexpected behavior when regulator is
7163 * enabled or set as high power mode.
7165 if (!vreg->max_uA)
7166 return 0;
7168 ret = regulator_set_load(vreg->reg, ua);
7169 if (ret < 0) {
7170 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
7171 __func__, vreg->name, ua, ret);
7174 return ret;
7177 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
7178 struct ufs_vreg *vreg)
7180 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
7183 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
7184 struct ufs_vreg *vreg)
7186 if (!vreg)
7187 return 0;
7189 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
7192 static int ufshcd_config_vreg(struct device *dev,
7193 struct ufs_vreg *vreg, bool on)
7195 int ret = 0;
7196 struct regulator *reg;
7197 const char *name;
7198 int min_uV, uA_load;
7200 BUG_ON(!vreg);
7202 reg = vreg->reg;
7203 name = vreg->name;
7205 if (regulator_count_voltages(reg) > 0) {
7206 if (vreg->min_uV && vreg->max_uV) {
7207 min_uV = on ? vreg->min_uV : 0;
7208 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
7209 if (ret) {
7210 dev_err(dev,
7211 "%s: %s set voltage failed, err=%d\n",
7212 __func__, name, ret);
7213 goto out;
7217 uA_load = on ? vreg->max_uA : 0;
7218 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
7219 if (ret)
7220 goto out;
7222 out:
7223 return ret;
7226 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
7228 int ret = 0;
7230 if (!vreg || vreg->enabled)
7231 goto out;
7233 ret = ufshcd_config_vreg(dev, vreg, true);
7234 if (!ret)
7235 ret = regulator_enable(vreg->reg);
7237 if (!ret)
7238 vreg->enabled = true;
7239 else
7240 dev_err(dev, "%s: %s enable failed, err=%d\n",
7241 __func__, vreg->name, ret);
7242 out:
7243 return ret;
7246 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
7248 int ret = 0;
7250 if (!vreg || !vreg->enabled)
7251 goto out;
7253 ret = regulator_disable(vreg->reg);
7255 if (!ret) {
7256 /* ignore errors on applying disable config */
7257 ufshcd_config_vreg(dev, vreg, false);
7258 vreg->enabled = false;
7259 } else {
7260 dev_err(dev, "%s: %s disable failed, err=%d\n",
7261 __func__, vreg->name, ret);
7263 out:
7264 return ret;
7267 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
7269 int ret = 0;
7270 struct device *dev = hba->dev;
7271 struct ufs_vreg_info *info = &hba->vreg_info;
7273 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
7274 if (ret)
7275 goto out;
7277 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
7278 if (ret)
7279 goto out;
7281 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
7282 if (ret)
7283 goto out;
7285 out:
7286 if (ret) {
7287 ufshcd_toggle_vreg(dev, info->vccq2, false);
7288 ufshcd_toggle_vreg(dev, info->vccq, false);
7289 ufshcd_toggle_vreg(dev, info->vcc, false);
7291 return ret;
7294 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
7296 struct ufs_vreg_info *info = &hba->vreg_info;
7298 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
7301 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
7303 int ret = 0;
7305 if (!vreg)
7306 goto out;
7308 vreg->reg = devm_regulator_get(dev, vreg->name);
7309 if (IS_ERR(vreg->reg)) {
7310 ret = PTR_ERR(vreg->reg);
7311 dev_err(dev, "%s: %s get failed, err=%d\n",
7312 __func__, vreg->name, ret);
7314 out:
7315 return ret;
7318 static int ufshcd_init_vreg(struct ufs_hba *hba)
7320 int ret = 0;
7321 struct device *dev = hba->dev;
7322 struct ufs_vreg_info *info = &hba->vreg_info;
7324 ret = ufshcd_get_vreg(dev, info->vcc);
7325 if (ret)
7326 goto out;
7328 ret = ufshcd_get_vreg(dev, info->vccq);
7329 if (ret)
7330 goto out;
7332 ret = ufshcd_get_vreg(dev, info->vccq2);
7333 out:
7334 return ret;
7337 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
7339 struct ufs_vreg_info *info = &hba->vreg_info;
7341 if (info)
7342 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
7344 return 0;
7347 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
7348 bool skip_ref_clk)
7350 int ret = 0;
7351 struct ufs_clk_info *clki;
7352 struct list_head *head = &hba->clk_list_head;
7353 unsigned long flags;
7354 ktime_t start = ktime_get();
7355 bool clk_state_changed = false;
7357 if (list_empty(head))
7358 goto out;
7361 * vendor specific setup_clocks ops may depend on clocks managed by
7362 * this standard driver hence call the vendor specific setup_clocks
7363 * before disabling the clocks managed here.
7365 if (!on) {
7366 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
7367 if (ret)
7368 return ret;
7371 list_for_each_entry(clki, head, list) {
7372 if (!IS_ERR_OR_NULL(clki->clk)) {
7373 if (skip_ref_clk && !strcmp(clki->name, "ref_clk"))
7374 continue;
7376 clk_state_changed = on ^ clki->enabled;
7377 if (on && !clki->enabled) {
7378 ret = clk_prepare_enable(clki->clk);
7379 if (ret) {
7380 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
7381 __func__, clki->name, ret);
7382 goto out;
7384 } else if (!on && clki->enabled) {
7385 clk_disable_unprepare(clki->clk);
7387 clki->enabled = on;
7388 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
7389 clki->name, on ? "en" : "dis");
7394 * vendor specific setup_clocks ops may depend on clocks managed by
7395 * this standard driver hence call the vendor specific setup_clocks
7396 * after enabling the clocks managed here.
7398 if (on) {
7399 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
7400 if (ret)
7401 return ret;
7404 out:
7405 if (ret) {
7406 list_for_each_entry(clki, head, list) {
7407 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
7408 clk_disable_unprepare(clki->clk);
7410 } else if (!ret && on) {
7411 spin_lock_irqsave(hba->host->host_lock, flags);
7412 hba->clk_gating.state = CLKS_ON;
7413 trace_ufshcd_clk_gating(dev_name(hba->dev),
7414 hba->clk_gating.state);
7415 spin_unlock_irqrestore(hba->host->host_lock, flags);
7418 if (clk_state_changed)
7419 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
7420 (on ? "on" : "off"),
7421 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
7422 return ret;
7425 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
7427 return __ufshcd_setup_clocks(hba, on, false);
7430 static int ufshcd_init_clocks(struct ufs_hba *hba)
7432 int ret = 0;
7433 struct ufs_clk_info *clki;
7434 struct device *dev = hba->dev;
7435 struct list_head *head = &hba->clk_list_head;
7437 if (list_empty(head))
7438 goto out;
7440 list_for_each_entry(clki, head, list) {
7441 if (!clki->name)
7442 continue;
7444 clki->clk = devm_clk_get(dev, clki->name);
7445 if (IS_ERR(clki->clk)) {
7446 ret = PTR_ERR(clki->clk);
7447 dev_err(dev, "%s: %s clk get failed, %d\n",
7448 __func__, clki->name, ret);
7449 goto out;
7453 * Parse device ref clk freq as per device tree "ref_clk".
7454 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
7455 * in ufshcd_alloc_host().
7457 if (!strcmp(clki->name, "ref_clk"))
7458 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
7460 if (clki->max_freq) {
7461 ret = clk_set_rate(clki->clk, clki->max_freq);
7462 if (ret) {
7463 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
7464 __func__, clki->name,
7465 clki->max_freq, ret);
7466 goto out;
7468 clki->curr_freq = clki->max_freq;
7470 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
7471 clki->name, clk_get_rate(clki->clk));
7473 out:
7474 return ret;
7477 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
7479 int err = 0;
7481 if (!hba->vops)
7482 goto out;
7484 err = ufshcd_vops_init(hba);
7485 if (err)
7486 goto out;
7488 err = ufshcd_vops_setup_regulators(hba, true);
7489 if (err)
7490 goto out_exit;
7492 goto out;
7494 out_exit:
7495 ufshcd_vops_exit(hba);
7496 out:
7497 if (err)
7498 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
7499 __func__, ufshcd_get_var_name(hba), err);
7500 return err;
7503 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
7505 if (!hba->vops)
7506 return;
7508 ufshcd_vops_setup_regulators(hba, false);
7510 ufshcd_vops_exit(hba);
7513 static int ufshcd_hba_init(struct ufs_hba *hba)
7515 int err;
7518 * Handle host controller power separately from the UFS device power
7519 * rails as it will help controlling the UFS host controller power
7520 * collapse easily which is different than UFS device power collapse.
7521 * Also, enable the host controller power before we go ahead with rest
7522 * of the initialization here.
7524 err = ufshcd_init_hba_vreg(hba);
7525 if (err)
7526 goto out;
7528 err = ufshcd_setup_hba_vreg(hba, true);
7529 if (err)
7530 goto out;
7532 err = ufshcd_init_clocks(hba);
7533 if (err)
7534 goto out_disable_hba_vreg;
7536 err = ufshcd_setup_clocks(hba, true);
7537 if (err)
7538 goto out_disable_hba_vreg;
7540 err = ufshcd_init_vreg(hba);
7541 if (err)
7542 goto out_disable_clks;
7544 err = ufshcd_setup_vreg(hba, true);
7545 if (err)
7546 goto out_disable_clks;
7548 err = ufshcd_variant_hba_init(hba);
7549 if (err)
7550 goto out_disable_vreg;
7552 hba->is_powered = true;
7553 goto out;
7555 out_disable_vreg:
7556 ufshcd_setup_vreg(hba, false);
7557 out_disable_clks:
7558 ufshcd_setup_clocks(hba, false);
7559 out_disable_hba_vreg:
7560 ufshcd_setup_hba_vreg(hba, false);
7561 out:
7562 return err;
7565 static void ufshcd_hba_exit(struct ufs_hba *hba)
7567 if (hba->is_powered) {
7568 ufshcd_variant_hba_exit(hba);
7569 ufshcd_setup_vreg(hba, false);
7570 ufshcd_suspend_clkscaling(hba);
7571 if (ufshcd_is_clkscaling_supported(hba))
7572 if (hba->devfreq)
7573 ufshcd_suspend_clkscaling(hba);
7574 ufshcd_setup_clocks(hba, false);
7575 ufshcd_setup_hba_vreg(hba, false);
7576 hba->is_powered = false;
7580 static int
7581 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
7583 unsigned char cmd[6] = {REQUEST_SENSE,
7587 UFS_SENSE_SIZE,
7589 char *buffer;
7590 int ret;
7592 buffer = kzalloc(UFS_SENSE_SIZE, GFP_KERNEL);
7593 if (!buffer) {
7594 ret = -ENOMEM;
7595 goto out;
7598 ret = scsi_execute(sdp, cmd, DMA_FROM_DEVICE, buffer,
7599 UFS_SENSE_SIZE, NULL, NULL,
7600 msecs_to_jiffies(1000), 3, 0, RQF_PM, NULL);
7601 if (ret)
7602 pr_err("%s: failed with err %d\n", __func__, ret);
7604 kfree(buffer);
7605 out:
7606 return ret;
7610 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
7611 * power mode
7612 * @hba: per adapter instance
7613 * @pwr_mode: device power mode to set
7615 * Returns 0 if requested power mode is set successfully
7616 * Returns non-zero if failed to set the requested power mode
7618 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
7619 enum ufs_dev_pwr_mode pwr_mode)
7621 unsigned char cmd[6] = { START_STOP };
7622 struct scsi_sense_hdr sshdr;
7623 struct scsi_device *sdp;
7624 unsigned long flags;
7625 int ret;
7627 spin_lock_irqsave(hba->host->host_lock, flags);
7628 sdp = hba->sdev_ufs_device;
7629 if (sdp) {
7630 ret = scsi_device_get(sdp);
7631 if (!ret && !scsi_device_online(sdp)) {
7632 ret = -ENODEV;
7633 scsi_device_put(sdp);
7635 } else {
7636 ret = -ENODEV;
7638 spin_unlock_irqrestore(hba->host->host_lock, flags);
7640 if (ret)
7641 return ret;
7644 * If scsi commands fail, the scsi mid-layer schedules scsi error-
7645 * handling, which would wait for host to be resumed. Since we know
7646 * we are functional while we are here, skip host resume in error
7647 * handling context.
7649 hba->host->eh_noresume = 1;
7650 if (hba->wlun_dev_clr_ua) {
7651 ret = ufshcd_send_request_sense(hba, sdp);
7652 if (ret)
7653 goto out;
7654 /* Unit attention condition is cleared now */
7655 hba->wlun_dev_clr_ua = false;
7658 cmd[4] = pwr_mode << 4;
7661 * Current function would be generally called from the power management
7662 * callbacks hence set the RQF_PM flag so that it doesn't resume the
7663 * already suspended childs.
7665 ret = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, &sshdr,
7666 START_STOP_TIMEOUT, 0, 0, RQF_PM, NULL);
7667 if (ret) {
7668 sdev_printk(KERN_WARNING, sdp,
7669 "START_STOP failed for power mode: %d, result %x\n",
7670 pwr_mode, ret);
7671 if (driver_byte(ret) == DRIVER_SENSE)
7672 scsi_print_sense_hdr(sdp, NULL, &sshdr);
7675 if (!ret)
7676 hba->curr_dev_pwr_mode = pwr_mode;
7677 out:
7678 scsi_device_put(sdp);
7679 hba->host->eh_noresume = 0;
7680 return ret;
7683 static int ufshcd_link_state_transition(struct ufs_hba *hba,
7684 enum uic_link_state req_link_state,
7685 int check_for_bkops)
7687 int ret = 0;
7689 if (req_link_state == hba->uic_link_state)
7690 return 0;
7692 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
7693 ret = ufshcd_uic_hibern8_enter(hba);
7694 if (!ret)
7695 ufshcd_set_link_hibern8(hba);
7696 else
7697 goto out;
7700 * If autobkops is enabled, link can't be turned off because
7701 * turning off the link would also turn off the device.
7703 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
7704 (!check_for_bkops || (check_for_bkops &&
7705 !hba->auto_bkops_enabled))) {
7707 * Let's make sure that link is in low power mode, we are doing
7708 * this currently by putting the link in Hibern8. Otherway to
7709 * put the link in low power mode is to send the DME end point
7710 * to device and then send the DME reset command to local
7711 * unipro. But putting the link in hibern8 is much faster.
7713 ret = ufshcd_uic_hibern8_enter(hba);
7714 if (ret)
7715 goto out;
7717 * Change controller state to "reset state" which
7718 * should also put the link in off/reset state
7720 ufshcd_hba_stop(hba, true);
7722 * TODO: Check if we need any delay to make sure that
7723 * controller is reset
7725 ufshcd_set_link_off(hba);
7728 out:
7729 return ret;
7732 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
7735 * It seems some UFS devices may keep drawing more than sleep current
7736 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
7737 * To avoid this situation, add 2ms delay before putting these UFS
7738 * rails in LPM mode.
7740 if (!ufshcd_is_link_active(hba) &&
7741 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
7742 usleep_range(2000, 2100);
7745 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
7746 * power.
7748 * If UFS device and link is in OFF state, all power supplies (VCC,
7749 * VCCQ, VCCQ2) can be turned off if power on write protect is not
7750 * required. If UFS link is inactive (Hibern8 or OFF state) and device
7751 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
7753 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
7754 * in low power state which would save some power.
7756 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
7757 !hba->dev_info.is_lu_power_on_wp) {
7758 ufshcd_setup_vreg(hba, false);
7759 } else if (!ufshcd_is_ufs_dev_active(hba)) {
7760 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
7761 if (!ufshcd_is_link_active(hba)) {
7762 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
7763 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
7768 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
7770 int ret = 0;
7772 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
7773 !hba->dev_info.is_lu_power_on_wp) {
7774 ret = ufshcd_setup_vreg(hba, true);
7775 } else if (!ufshcd_is_ufs_dev_active(hba)) {
7776 if (!ret && !ufshcd_is_link_active(hba)) {
7777 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
7778 if (ret)
7779 goto vcc_disable;
7780 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
7781 if (ret)
7782 goto vccq_lpm;
7784 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
7786 goto out;
7788 vccq_lpm:
7789 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
7790 vcc_disable:
7791 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
7792 out:
7793 return ret;
7796 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
7798 if (ufshcd_is_link_off(hba))
7799 ufshcd_setup_hba_vreg(hba, false);
7802 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
7804 if (ufshcd_is_link_off(hba))
7805 ufshcd_setup_hba_vreg(hba, true);
7809 * ufshcd_suspend - helper function for suspend operations
7810 * @hba: per adapter instance
7811 * @pm_op: desired low power operation type
7813 * This function will try to put the UFS device and link into low power
7814 * mode based on the "rpm_lvl" (Runtime PM level) or "spm_lvl"
7815 * (System PM level).
7817 * If this function is called during shutdown, it will make sure that
7818 * both UFS device and UFS link is powered off.
7820 * NOTE: UFS device & link must be active before we enter in this function.
7822 * Returns 0 for success and non-zero for failure
7824 static int ufshcd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
7826 int ret = 0;
7827 enum ufs_pm_level pm_lvl;
7828 enum ufs_dev_pwr_mode req_dev_pwr_mode;
7829 enum uic_link_state req_link_state;
7831 hba->pm_op_in_progress = 1;
7832 if (!ufshcd_is_shutdown_pm(pm_op)) {
7833 pm_lvl = ufshcd_is_runtime_pm(pm_op) ?
7834 hba->rpm_lvl : hba->spm_lvl;
7835 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
7836 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
7837 } else {
7838 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
7839 req_link_state = UIC_LINK_OFF_STATE;
7843 * If we can't transition into any of the low power modes
7844 * just gate the clocks.
7846 ufshcd_hold(hba, false);
7847 hba->clk_gating.is_suspended = true;
7849 if (hba->clk_scaling.is_allowed) {
7850 cancel_work_sync(&hba->clk_scaling.suspend_work);
7851 cancel_work_sync(&hba->clk_scaling.resume_work);
7852 ufshcd_suspend_clkscaling(hba);
7855 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
7856 req_link_state == UIC_LINK_ACTIVE_STATE) {
7857 goto disable_clks;
7860 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
7861 (req_link_state == hba->uic_link_state))
7862 goto enable_gating;
7864 /* UFS device & link must be active before we enter in this function */
7865 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
7866 ret = -EINVAL;
7867 goto enable_gating;
7870 if (ufshcd_is_runtime_pm(pm_op)) {
7871 if (ufshcd_can_autobkops_during_suspend(hba)) {
7873 * The device is idle with no requests in the queue,
7874 * allow background operations if bkops status shows
7875 * that performance might be impacted.
7877 ret = ufshcd_urgent_bkops(hba);
7878 if (ret)
7879 goto enable_gating;
7880 } else {
7881 /* make sure that auto bkops is disabled */
7882 ufshcd_disable_auto_bkops(hba);
7886 if ((req_dev_pwr_mode != hba->curr_dev_pwr_mode) &&
7887 ((ufshcd_is_runtime_pm(pm_op) && !hba->auto_bkops_enabled) ||
7888 !ufshcd_is_runtime_pm(pm_op))) {
7889 /* ensure that bkops is disabled */
7890 ufshcd_disable_auto_bkops(hba);
7891 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
7892 if (ret)
7893 goto enable_gating;
7896 ret = ufshcd_link_state_transition(hba, req_link_state, 1);
7897 if (ret)
7898 goto set_dev_active;
7900 ufshcd_vreg_set_lpm(hba);
7902 disable_clks:
7904 * Call vendor specific suspend callback. As these callbacks may access
7905 * vendor specific host controller register space call them before the
7906 * host clocks are ON.
7908 ret = ufshcd_vops_suspend(hba, pm_op);
7909 if (ret)
7910 goto set_link_active;
7912 if (!ufshcd_is_link_active(hba))
7913 ufshcd_setup_clocks(hba, false);
7914 else
7915 /* If link is active, device ref_clk can't be switched off */
7916 __ufshcd_setup_clocks(hba, false, true);
7918 hba->clk_gating.state = CLKS_OFF;
7919 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
7921 * Disable the host irq as host controller as there won't be any
7922 * host controller transaction expected till resume.
7924 ufshcd_disable_irq(hba);
7925 /* Put the host controller in low power mode if possible */
7926 ufshcd_hba_vreg_set_lpm(hba);
7927 goto out;
7929 set_link_active:
7930 if (hba->clk_scaling.is_allowed)
7931 ufshcd_resume_clkscaling(hba);
7932 ufshcd_vreg_set_hpm(hba);
7933 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
7934 ufshcd_set_link_active(hba);
7935 else if (ufshcd_is_link_off(hba))
7936 ufshcd_host_reset_and_restore(hba);
7937 set_dev_active:
7938 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
7939 ufshcd_disable_auto_bkops(hba);
7940 enable_gating:
7941 if (hba->clk_scaling.is_allowed)
7942 ufshcd_resume_clkscaling(hba);
7943 hba->clk_gating.is_suspended = false;
7944 ufshcd_release(hba);
7945 out:
7946 hba->pm_op_in_progress = 0;
7947 if (ret)
7948 ufshcd_update_reg_hist(&hba->ufs_stats.suspend_err, (u32)ret);
7949 return ret;
7953 * ufshcd_resume - helper function for resume operations
7954 * @hba: per adapter instance
7955 * @pm_op: runtime PM or system PM
7957 * This function basically brings the UFS device, UniPro link and controller
7958 * to active state.
7960 * Returns 0 for success and non-zero for failure
7962 static int ufshcd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
7964 int ret;
7965 enum uic_link_state old_link_state;
7967 hba->pm_op_in_progress = 1;
7968 old_link_state = hba->uic_link_state;
7970 ufshcd_hba_vreg_set_hpm(hba);
7971 /* Make sure clocks are enabled before accessing controller */
7972 ret = ufshcd_setup_clocks(hba, true);
7973 if (ret)
7974 goto out;
7976 /* enable the host irq as host controller would be active soon */
7977 ret = ufshcd_enable_irq(hba);
7978 if (ret)
7979 goto disable_irq_and_vops_clks;
7981 ret = ufshcd_vreg_set_hpm(hba);
7982 if (ret)
7983 goto disable_irq_and_vops_clks;
7986 * Call vendor specific resume callback. As these callbacks may access
7987 * vendor specific host controller register space call them when the
7988 * host clocks are ON.
7990 ret = ufshcd_vops_resume(hba, pm_op);
7991 if (ret)
7992 goto disable_vreg;
7994 if (ufshcd_is_link_hibern8(hba)) {
7995 ret = ufshcd_uic_hibern8_exit(hba);
7996 if (!ret)
7997 ufshcd_set_link_active(hba);
7998 else
7999 goto vendor_suspend;
8000 } else if (ufshcd_is_link_off(hba)) {
8001 ret = ufshcd_host_reset_and_restore(hba);
8003 * ufshcd_host_reset_and_restore() should have already
8004 * set the link state as active
8006 if (ret || !ufshcd_is_link_active(hba))
8007 goto vendor_suspend;
8010 if (!ufshcd_is_ufs_dev_active(hba)) {
8011 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
8012 if (ret)
8013 goto set_old_link_state;
8016 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
8017 ufshcd_enable_auto_bkops(hba);
8018 else
8020 * If BKOPs operations are urgently needed at this moment then
8021 * keep auto-bkops enabled or else disable it.
8023 ufshcd_urgent_bkops(hba);
8025 hba->clk_gating.is_suspended = false;
8027 if (hba->clk_scaling.is_allowed)
8028 ufshcd_resume_clkscaling(hba);
8030 /* Enable Auto-Hibernate if configured */
8031 ufshcd_auto_hibern8_enable(hba);
8033 /* Schedule clock gating in case of no access to UFS device yet */
8034 ufshcd_release(hba);
8036 goto out;
8038 set_old_link_state:
8039 ufshcd_link_state_transition(hba, old_link_state, 0);
8040 vendor_suspend:
8041 ufshcd_vops_suspend(hba, pm_op);
8042 disable_vreg:
8043 ufshcd_vreg_set_lpm(hba);
8044 disable_irq_and_vops_clks:
8045 ufshcd_disable_irq(hba);
8046 if (hba->clk_scaling.is_allowed)
8047 ufshcd_suspend_clkscaling(hba);
8048 ufshcd_setup_clocks(hba, false);
8049 out:
8050 hba->pm_op_in_progress = 0;
8051 if (ret)
8052 ufshcd_update_reg_hist(&hba->ufs_stats.resume_err, (u32)ret);
8053 return ret;
8057 * ufshcd_system_suspend - system suspend routine
8058 * @hba: per adapter instance
8060 * Check the description of ufshcd_suspend() function for more details.
8062 * Returns 0 for success and non-zero for failure
8064 int ufshcd_system_suspend(struct ufs_hba *hba)
8066 int ret = 0;
8067 ktime_t start = ktime_get();
8069 if (!hba || !hba->is_powered)
8070 return 0;
8072 if ((ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl) ==
8073 hba->curr_dev_pwr_mode) &&
8074 (ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl) ==
8075 hba->uic_link_state))
8076 goto out;
8078 if (pm_runtime_suspended(hba->dev)) {
8080 * UFS device and/or UFS link low power states during runtime
8081 * suspend seems to be different than what is expected during
8082 * system suspend. Hence runtime resume the devic & link and
8083 * let the system suspend low power states to take effect.
8084 * TODO: If resume takes longer time, we might have optimize
8085 * it in future by not resuming everything if possible.
8087 ret = ufshcd_runtime_resume(hba);
8088 if (ret)
8089 goto out;
8092 ret = ufshcd_suspend(hba, UFS_SYSTEM_PM);
8093 out:
8094 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
8095 ktime_to_us(ktime_sub(ktime_get(), start)),
8096 hba->curr_dev_pwr_mode, hba->uic_link_state);
8097 if (!ret)
8098 hba->is_sys_suspended = true;
8099 return ret;
8101 EXPORT_SYMBOL(ufshcd_system_suspend);
8104 * ufshcd_system_resume - system resume routine
8105 * @hba: per adapter instance
8107 * Returns 0 for success and non-zero for failure
8110 int ufshcd_system_resume(struct ufs_hba *hba)
8112 int ret = 0;
8113 ktime_t start = ktime_get();
8115 if (!hba)
8116 return -EINVAL;
8118 if (!hba->is_powered || pm_runtime_suspended(hba->dev))
8120 * Let the runtime resume take care of resuming
8121 * if runtime suspended.
8123 goto out;
8124 else
8125 ret = ufshcd_resume(hba, UFS_SYSTEM_PM);
8126 out:
8127 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
8128 ktime_to_us(ktime_sub(ktime_get(), start)),
8129 hba->curr_dev_pwr_mode, hba->uic_link_state);
8130 if (!ret)
8131 hba->is_sys_suspended = false;
8132 return ret;
8134 EXPORT_SYMBOL(ufshcd_system_resume);
8137 * ufshcd_runtime_suspend - runtime suspend routine
8138 * @hba: per adapter instance
8140 * Check the description of ufshcd_suspend() function for more details.
8142 * Returns 0 for success and non-zero for failure
8144 int ufshcd_runtime_suspend(struct ufs_hba *hba)
8146 int ret = 0;
8147 ktime_t start = ktime_get();
8149 if (!hba)
8150 return -EINVAL;
8152 if (!hba->is_powered)
8153 goto out;
8154 else
8155 ret = ufshcd_suspend(hba, UFS_RUNTIME_PM);
8156 out:
8157 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
8158 ktime_to_us(ktime_sub(ktime_get(), start)),
8159 hba->curr_dev_pwr_mode, hba->uic_link_state);
8160 return ret;
8162 EXPORT_SYMBOL(ufshcd_runtime_suspend);
8165 * ufshcd_runtime_resume - runtime resume routine
8166 * @hba: per adapter instance
8168 * This function basically brings the UFS device, UniPro link and controller
8169 * to active state. Following operations are done in this function:
8171 * 1. Turn on all the controller related clocks
8172 * 2. Bring the UniPro link out of Hibernate state
8173 * 3. If UFS device is in sleep state, turn ON VCC rail and bring the UFS device
8174 * to active state.
8175 * 4. If auto-bkops is enabled on the device, disable it.
8177 * So following would be the possible power state after this function return
8178 * successfully:
8179 * S1: UFS device in Active state with VCC rail ON
8180 * UniPro link in Active state
8181 * All the UFS/UniPro controller clocks are ON
8183 * Returns 0 for success and non-zero for failure
8185 int ufshcd_runtime_resume(struct ufs_hba *hba)
8187 int ret = 0;
8188 ktime_t start = ktime_get();
8190 if (!hba)
8191 return -EINVAL;
8193 if (!hba->is_powered)
8194 goto out;
8195 else
8196 ret = ufshcd_resume(hba, UFS_RUNTIME_PM);
8197 out:
8198 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
8199 ktime_to_us(ktime_sub(ktime_get(), start)),
8200 hba->curr_dev_pwr_mode, hba->uic_link_state);
8201 return ret;
8203 EXPORT_SYMBOL(ufshcd_runtime_resume);
8205 int ufshcd_runtime_idle(struct ufs_hba *hba)
8207 return 0;
8209 EXPORT_SYMBOL(ufshcd_runtime_idle);
8212 * ufshcd_shutdown - shutdown routine
8213 * @hba: per adapter instance
8215 * This function would power off both UFS device and UFS link.
8217 * Returns 0 always to allow force shutdown even in case of errors.
8219 int ufshcd_shutdown(struct ufs_hba *hba)
8221 int ret = 0;
8223 if (!hba->is_powered)
8224 goto out;
8226 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
8227 goto out;
8229 if (pm_runtime_suspended(hba->dev)) {
8230 ret = ufshcd_runtime_resume(hba);
8231 if (ret)
8232 goto out;
8235 ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
8236 out:
8237 if (ret)
8238 dev_err(hba->dev, "%s failed, err %d\n", __func__, ret);
8239 /* allow force shutdown even in case of errors */
8240 return 0;
8242 EXPORT_SYMBOL(ufshcd_shutdown);
8245 * ufshcd_remove - de-allocate SCSI host and host memory space
8246 * data structure memory
8247 * @hba: per adapter instance
8249 void ufshcd_remove(struct ufs_hba *hba)
8251 ufs_bsg_remove(hba);
8252 ufs_sysfs_remove_nodes(hba->dev);
8253 scsi_remove_host(hba->host);
8254 /* disable interrupts */
8255 ufshcd_disable_intr(hba, hba->intr_mask);
8256 ufshcd_hba_stop(hba, true);
8258 ufshcd_exit_clk_scaling(hba);
8259 ufshcd_exit_clk_gating(hba);
8260 if (ufshcd_is_clkscaling_supported(hba))
8261 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
8262 ufshcd_hba_exit(hba);
8264 EXPORT_SYMBOL_GPL(ufshcd_remove);
8267 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
8268 * @hba: pointer to Host Bus Adapter (HBA)
8270 void ufshcd_dealloc_host(struct ufs_hba *hba)
8272 scsi_host_put(hba->host);
8274 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
8277 * ufshcd_set_dma_mask - Set dma mask based on the controller
8278 * addressing capability
8279 * @hba: per adapter instance
8281 * Returns 0 for success, non-zero for failure
8283 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
8285 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
8286 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
8287 return 0;
8289 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
8293 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
8294 * @dev: pointer to device handle
8295 * @hba_handle: driver private handle
8296 * Returns 0 on success, non-zero value on failure
8298 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
8300 struct Scsi_Host *host;
8301 struct ufs_hba *hba;
8302 int err = 0;
8304 if (!dev) {
8305 dev_err(dev,
8306 "Invalid memory reference for dev is NULL\n");
8307 err = -ENODEV;
8308 goto out_error;
8311 host = scsi_host_alloc(&ufshcd_driver_template,
8312 sizeof(struct ufs_hba));
8313 if (!host) {
8314 dev_err(dev, "scsi_host_alloc failed\n");
8315 err = -ENOMEM;
8316 goto out_error;
8318 hba = shost_priv(host);
8319 hba->host = host;
8320 hba->dev = dev;
8321 *hba_handle = hba;
8322 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
8324 INIT_LIST_HEAD(&hba->clk_list_head);
8326 out_error:
8327 return err;
8329 EXPORT_SYMBOL(ufshcd_alloc_host);
8332 * ufshcd_init - Driver initialization routine
8333 * @hba: per-adapter instance
8334 * @mmio_base: base register address
8335 * @irq: Interrupt line of device
8336 * Returns 0 on success, non-zero value on failure
8338 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
8340 int err;
8341 struct Scsi_Host *host = hba->host;
8342 struct device *dev = hba->dev;
8344 if (!mmio_base) {
8345 dev_err(hba->dev,
8346 "Invalid memory reference for mmio_base is NULL\n");
8347 err = -ENODEV;
8348 goto out_error;
8351 hba->mmio_base = mmio_base;
8352 hba->irq = irq;
8354 err = ufshcd_hba_init(hba);
8355 if (err)
8356 goto out_error;
8358 /* Read capabilities registers */
8359 ufshcd_hba_capabilities(hba);
8361 /* Get UFS version supported by the controller */
8362 hba->ufs_version = ufshcd_get_ufs_version(hba);
8364 if ((hba->ufs_version != UFSHCI_VERSION_10) &&
8365 (hba->ufs_version != UFSHCI_VERSION_11) &&
8366 (hba->ufs_version != UFSHCI_VERSION_20) &&
8367 (hba->ufs_version != UFSHCI_VERSION_21))
8368 dev_err(hba->dev, "invalid UFS version 0x%x\n",
8369 hba->ufs_version);
8371 /* Get Interrupt bit mask per version */
8372 hba->intr_mask = ufshcd_get_intr_mask(hba);
8374 err = ufshcd_set_dma_mask(hba);
8375 if (err) {
8376 dev_err(hba->dev, "set dma mask failed\n");
8377 goto out_disable;
8380 /* Allocate memory for host memory space */
8381 err = ufshcd_memory_alloc(hba);
8382 if (err) {
8383 dev_err(hba->dev, "Memory allocation failed\n");
8384 goto out_disable;
8387 /* Configure LRB */
8388 ufshcd_host_memory_configure(hba);
8390 host->can_queue = hba->nutrs;
8391 host->cmd_per_lun = hba->nutrs;
8392 host->max_id = UFSHCD_MAX_ID;
8393 host->max_lun = UFS_MAX_LUNS;
8394 host->max_channel = UFSHCD_MAX_CHANNEL;
8395 host->unique_id = host->host_no;
8396 host->max_cmd_len = UFS_CDB_SIZE;
8398 hba->max_pwr_info.is_valid = false;
8400 /* Initailize wait queue for task management */
8401 init_waitqueue_head(&hba->tm_wq);
8402 init_waitqueue_head(&hba->tm_tag_wq);
8404 /* Initialize work queues */
8405 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
8406 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
8408 /* Initialize UIC command mutex */
8409 mutex_init(&hba->uic_cmd_mutex);
8411 /* Initialize mutex for device management commands */
8412 mutex_init(&hba->dev_cmd.lock);
8414 init_rwsem(&hba->clk_scaling_lock);
8416 /* Initialize device management tag acquire wait queue */
8417 init_waitqueue_head(&hba->dev_cmd.tag_wq);
8419 ufshcd_init_clk_gating(hba);
8421 ufshcd_init_clk_scaling(hba);
8424 * In order to avoid any spurious interrupt immediately after
8425 * registering UFS controller interrupt handler, clear any pending UFS
8426 * interrupt status and disable all the UFS interrupts.
8428 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
8429 REG_INTERRUPT_STATUS);
8430 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
8432 * Make sure that UFS interrupts are disabled and any pending interrupt
8433 * status is cleared before registering UFS interrupt handler.
8435 mb();
8437 /* IRQ registration */
8438 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
8439 if (err) {
8440 dev_err(hba->dev, "request irq failed\n");
8441 goto exit_gating;
8442 } else {
8443 hba->is_irq_enabled = true;
8446 err = scsi_add_host(host, hba->dev);
8447 if (err) {
8448 dev_err(hba->dev, "scsi_add_host failed\n");
8449 goto exit_gating;
8452 /* Reset the attached device */
8453 ufshcd_vops_device_reset(hba);
8455 /* Host controller enable */
8456 err = ufshcd_hba_enable(hba);
8457 if (err) {
8458 dev_err(hba->dev, "Host controller enable failed\n");
8459 ufshcd_print_host_regs(hba);
8460 ufshcd_print_host_state(hba);
8461 goto out_remove_scsi_host;
8465 * Set the default power management level for runtime and system PM.
8466 * Default power saving mode is to keep UFS link in Hibern8 state
8467 * and UFS device in sleep state.
8469 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
8470 UFS_SLEEP_PWR_MODE,
8471 UIC_LINK_HIBERN8_STATE);
8472 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
8473 UFS_SLEEP_PWR_MODE,
8474 UIC_LINK_HIBERN8_STATE);
8476 /* Set the default auto-hiberate idle timer value to 150 ms */
8477 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
8478 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
8479 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
8482 /* Hold auto suspend until async scan completes */
8483 pm_runtime_get_sync(dev);
8484 atomic_set(&hba->scsi_block_reqs_cnt, 0);
8486 * We are assuming that device wasn't put in sleep/power-down
8487 * state exclusively during the boot stage before kernel.
8488 * This assumption helps avoid doing link startup twice during
8489 * ufshcd_probe_hba().
8491 ufshcd_set_ufs_dev_active(hba);
8493 async_schedule(ufshcd_async_scan, hba);
8494 ufs_sysfs_add_nodes(hba->dev);
8496 return 0;
8498 out_remove_scsi_host:
8499 scsi_remove_host(hba->host);
8500 exit_gating:
8501 ufshcd_exit_clk_scaling(hba);
8502 ufshcd_exit_clk_gating(hba);
8503 out_disable:
8504 hba->is_irq_enabled = false;
8505 ufshcd_hba_exit(hba);
8506 out_error:
8507 return err;
8509 EXPORT_SYMBOL_GPL(ufshcd_init);
8511 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
8512 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
8513 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
8514 MODULE_LICENSE("GPL");
8515 MODULE_VERSION(UFSHCD_DRIVER_VERSION);