1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Universal Flash Storage Host controller driver Core
4 * Copyright (C) 2011-2013 Samsung India Software Operations
5 * Copyright (c) 2013-2016, The Linux Foundation. All rights reserved.
8 * Santosh Yaraganavi <santosh.sy@samsung.com>
9 * Vinayak Holikatti <h.vinayak@samsung.com>
12 #include <linux/async.h>
13 #include <linux/devfreq.h>
14 #include <linux/nls.h>
16 #include <linux/bitfield.h>
17 #include <linux/blk-pm.h>
18 #include <linux/blkdev.h>
19 #include <linux/clk.h>
20 #include <linux/delay.h>
21 #include <linux/interrupt.h>
22 #include <linux/module.h>
23 #include <linux/regulator/consumer.h>
24 #include <linux/sched/clock.h>
25 #include <scsi/scsi_cmnd.h>
26 #include <scsi/scsi_dbg.h>
27 #include <scsi/scsi_driver.h>
28 #include <scsi/scsi_eh.h>
29 #include "ufshcd-priv.h"
30 #include <ufs/ufs_quirks.h>
31 #include <ufs/unipro.h>
32 #include "ufs-sysfs.h"
33 #include "ufs-debugfs.h"
34 #include "ufs-fault-injection.h"
36 #include "ufshcd-crypto.h"
38 #include <asm/unaligned.h>
40 #define CREATE_TRACE_POINTS
41 #include <trace/events/ufs.h>
43 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
46 /* UIC command timeout, unit: ms */
47 #define UIC_CMD_TIMEOUT 500
49 /* NOP OUT retries waiting for NOP IN response */
50 #define NOP_OUT_RETRIES 10
51 /* Timeout after 50 msecs if NOP OUT hangs without response */
52 #define NOP_OUT_TIMEOUT 50 /* msecs */
54 /* Query request retries */
55 #define QUERY_REQ_RETRIES 3
56 /* Query request timeout */
57 #define QUERY_REQ_TIMEOUT 1500 /* 1.5 seconds */
59 /* Task management command timeout */
60 #define TM_CMD_TIMEOUT 100 /* msecs */
62 /* maximum number of retries for a general UIC command */
63 #define UFS_UIC_COMMAND_RETRIES 3
65 /* maximum number of link-startup retries */
66 #define DME_LINKSTARTUP_RETRIES 3
68 /* maximum number of reset retries before giving up */
69 #define MAX_HOST_RESET_RETRIES 5
71 /* Maximum number of error handler retries before giving up */
72 #define MAX_ERR_HANDLER_RETRIES 5
74 /* Expose the flag value from utp_upiu_query.value */
75 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
77 /* Interrupt aggregation default timeout, unit: 40us */
78 #define INT_AGGR_DEF_TO 0x02
80 /* default delay of autosuspend: 2000 ms */
81 #define RPM_AUTOSUSPEND_DELAY_MS 2000
83 /* Default delay of RPM device flush delayed work */
84 #define RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS 5000
86 /* Default value of wait time before gating device ref clock */
87 #define UFSHCD_REF_CLK_GATING_WAIT_US 0xFF /* microsecs */
89 /* Polling time to wait for fDeviceInit */
90 #define FDEVICEINIT_COMPL_TIMEOUT 1500 /* millisecs */
92 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
96 _ret = ufshcd_enable_vreg(_dev, _vreg); \
98 _ret = ufshcd_disable_vreg(_dev, _vreg); \
102 #define ufshcd_hex_dump(prefix_str, buf, len) do { \
103 size_t __len = (len); \
104 print_hex_dump(KERN_ERR, prefix_str, \
105 __len > 4 ? DUMP_PREFIX_OFFSET : DUMP_PREFIX_NONE,\
106 16, 4, buf, __len, false); \
109 int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len,
115 if (offset % 4 != 0 || len % 4 != 0) /* keep readl happy */
118 regs = kzalloc(len, GFP_ATOMIC);
122 for (pos = 0; pos < len; pos += 4) {
124 pos >= REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER &&
125 pos <= REG_UIC_ERROR_CODE_DME)
127 regs[pos / 4] = ufshcd_readl(hba, offset + pos);
130 ufshcd_hex_dump(prefix, regs, len);
135 EXPORT_SYMBOL_GPL(ufshcd_dump_regs);
138 UFSHCD_MAX_CHANNEL = 0,
140 UFSHCD_NUM_RESERVED = 1,
141 UFSHCD_CMD_PER_LUN = 32 - UFSHCD_NUM_RESERVED,
142 UFSHCD_CAN_QUEUE = 32 - UFSHCD_NUM_RESERVED,
145 static const char *const ufshcd_state_name[] = {
146 [UFSHCD_STATE_RESET] = "reset",
147 [UFSHCD_STATE_OPERATIONAL] = "operational",
148 [UFSHCD_STATE_ERROR] = "error",
149 [UFSHCD_STATE_EH_SCHEDULED_FATAL] = "eh_fatal",
150 [UFSHCD_STATE_EH_SCHEDULED_NON_FATAL] = "eh_non_fatal",
153 /* UFSHCD error handling flags */
155 UFSHCD_EH_IN_PROGRESS = (1 << 0),
158 /* UFSHCD UIC layer error flags */
160 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
161 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
162 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
163 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
164 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
165 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
166 UFSHCD_UIC_PA_GENERIC_ERROR = (1 << 6), /* Generic PA error */
169 #define ufshcd_set_eh_in_progress(h) \
170 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
171 #define ufshcd_eh_in_progress(h) \
172 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
173 #define ufshcd_clear_eh_in_progress(h) \
174 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
176 const struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
177 [UFS_PM_LVL_0] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
178 [UFS_PM_LVL_1] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
179 [UFS_PM_LVL_2] = {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
180 [UFS_PM_LVL_3] = {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
181 [UFS_PM_LVL_4] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
182 [UFS_PM_LVL_5] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
184 * For DeepSleep, the link is first put in hibern8 and then off.
185 * Leaving the link in hibern8 is not supported.
187 [UFS_PM_LVL_6] = {UFS_DEEPSLEEP_PWR_MODE, UIC_LINK_OFF_STATE},
190 static inline enum ufs_dev_pwr_mode
191 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
193 return ufs_pm_lvl_states[lvl].dev_state;
196 static inline enum uic_link_state
197 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
199 return ufs_pm_lvl_states[lvl].link_state;
202 static inline enum ufs_pm_level
203 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
204 enum uic_link_state link_state)
206 enum ufs_pm_level lvl;
208 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
209 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
210 (ufs_pm_lvl_states[lvl].link_state == link_state))
214 /* if no match found, return the level 0 */
218 static const struct ufs_dev_quirk ufs_fixups[] = {
219 /* UFS cards deviations table */
220 { .wmanufacturerid = UFS_VENDOR_MICRON,
221 .model = UFS_ANY_MODEL,
222 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
223 UFS_DEVICE_QUIRK_SWAP_L2P_ENTRY_FOR_HPB_READ },
224 { .wmanufacturerid = UFS_VENDOR_SAMSUNG,
225 .model = UFS_ANY_MODEL,
226 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
227 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE |
228 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS },
229 { .wmanufacturerid = UFS_VENDOR_SKHYNIX,
230 .model = UFS_ANY_MODEL,
231 .quirk = UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME },
232 { .wmanufacturerid = UFS_VENDOR_SKHYNIX,
233 .model = "hB8aL1" /*H28U62301AMR*/,
234 .quirk = UFS_DEVICE_QUIRK_HOST_VS_DEBUGSAVECONFIGTIME },
235 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
236 .model = UFS_ANY_MODEL,
237 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM },
238 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
239 .model = "THGLF2G9C8KBADG",
240 .quirk = UFS_DEVICE_QUIRK_PA_TACTIVATE },
241 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
242 .model = "THGLF2G9D8KBADG",
243 .quirk = UFS_DEVICE_QUIRK_PA_TACTIVATE },
247 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba);
248 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
249 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
250 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
251 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
252 static void ufshcd_hba_exit(struct ufs_hba *hba);
253 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params);
254 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
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 int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on);
265 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on);
266 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
267 struct ufs_vreg *vreg);
268 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag);
269 static void ufshcd_wb_toggle_buf_flush_during_h8(struct ufs_hba *hba,
271 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba);
272 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba);
274 static inline void ufshcd_enable_irq(struct ufs_hba *hba)
276 if (!hba->is_irq_enabled) {
277 enable_irq(hba->irq);
278 hba->is_irq_enabled = true;
282 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
284 if (hba->is_irq_enabled) {
285 disable_irq(hba->irq);
286 hba->is_irq_enabled = false;
290 static void ufshcd_configure_wb(struct ufs_hba *hba)
292 if (!ufshcd_is_wb_allowed(hba))
295 ufshcd_wb_toggle(hba, true);
297 ufshcd_wb_toggle_buf_flush_during_h8(hba, true);
299 if (ufshcd_is_wb_buf_flush_allowed(hba))
300 ufshcd_wb_toggle_buf_flush(hba, true);
303 static void ufshcd_scsi_unblock_requests(struct ufs_hba *hba)
305 if (atomic_dec_and_test(&hba->scsi_block_reqs_cnt))
306 scsi_unblock_requests(hba->host);
309 static void ufshcd_scsi_block_requests(struct ufs_hba *hba)
311 if (atomic_inc_return(&hba->scsi_block_reqs_cnt) == 1)
312 scsi_block_requests(hba->host);
315 static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba, unsigned int tag,
316 enum ufs_trace_str_t str_t)
318 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
319 struct utp_upiu_header *header;
321 if (!trace_ufshcd_upiu_enabled())
324 if (str_t == UFS_CMD_SEND)
325 header = &rq->header;
327 header = &hba->lrb[tag].ucd_rsp_ptr->header;
329 trace_ufshcd_upiu(dev_name(hba->dev), str_t, header, &rq->sc.cdb,
333 static void ufshcd_add_query_upiu_trace(struct ufs_hba *hba,
334 enum ufs_trace_str_t str_t,
335 struct utp_upiu_req *rq_rsp)
337 if (!trace_ufshcd_upiu_enabled())
340 trace_ufshcd_upiu(dev_name(hba->dev), str_t, &rq_rsp->header,
341 &rq_rsp->qr, UFS_TSF_OSF);
344 static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag,
345 enum ufs_trace_str_t str_t)
347 struct utp_task_req_desc *descp = &hba->utmrdl_base_addr[tag];
349 if (!trace_ufshcd_upiu_enabled())
352 if (str_t == UFS_TM_SEND)
353 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
354 &descp->upiu_req.req_header,
355 &descp->upiu_req.input_param1,
358 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
359 &descp->upiu_rsp.rsp_header,
360 &descp->upiu_rsp.output_param1,
364 static void ufshcd_add_uic_command_trace(struct ufs_hba *hba,
365 const struct uic_command *ucmd,
366 enum ufs_trace_str_t str_t)
370 if (!trace_ufshcd_uic_command_enabled())
373 if (str_t == UFS_CMD_SEND)
376 cmd = ufshcd_readl(hba, REG_UIC_COMMAND);
378 trace_ufshcd_uic_command(dev_name(hba->dev), str_t, cmd,
379 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_1),
380 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2),
381 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3));
384 static void ufshcd_add_command_trace(struct ufs_hba *hba, unsigned int tag,
385 enum ufs_trace_str_t str_t)
388 u8 opcode = 0, group_id = 0;
390 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
391 struct scsi_cmnd *cmd = lrbp->cmd;
392 struct request *rq = scsi_cmd_to_rq(cmd);
393 int transfer_len = -1;
398 /* trace UPIU also */
399 ufshcd_add_cmd_upiu_trace(hba, tag, str_t);
400 if (!trace_ufshcd_command_enabled())
403 opcode = cmd->cmnd[0];
405 if (opcode == READ_10 || opcode == WRITE_10) {
407 * Currently we only fully trace read(10) and write(10) commands
410 be32_to_cpu(lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
411 lba = scsi_get_lba(cmd);
412 if (opcode == WRITE_10)
413 group_id = lrbp->cmd->cmnd[6];
414 } else if (opcode == UNMAP) {
416 * The number of Bytes to be unmapped beginning with the lba.
418 transfer_len = blk_rq_bytes(rq);
419 lba = scsi_get_lba(cmd);
422 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
423 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
424 trace_ufshcd_command(dev_name(hba->dev), str_t, tag,
425 doorbell, transfer_len, intr, lba, opcode, group_id);
428 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
430 struct ufs_clk_info *clki;
431 struct list_head *head = &hba->clk_list_head;
433 if (list_empty(head))
436 list_for_each_entry(clki, head, list) {
437 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
439 dev_err(hba->dev, "clk: %s, rate: %u\n",
440 clki->name, clki->curr_freq);
444 static void ufshcd_print_evt(struct ufs_hba *hba, u32 id,
445 const char *err_name)
449 const struct ufs_event_hist *e;
451 if (id >= UFS_EVT_CNT)
454 e = &hba->ufs_stats.event[id];
456 for (i = 0; i < UFS_EVENT_HIST_LENGTH; i++) {
457 int p = (i + e->pos) % UFS_EVENT_HIST_LENGTH;
459 if (e->tstamp[p] == 0)
461 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, p,
462 e->val[p], div_u64(e->tstamp[p], 1000));
467 dev_err(hba->dev, "No record of %s\n", err_name);
469 dev_err(hba->dev, "%s: total cnt=%llu\n", err_name, e->cnt);
472 static void ufshcd_print_evt_hist(struct ufs_hba *hba)
474 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
476 ufshcd_print_evt(hba, UFS_EVT_PA_ERR, "pa_err");
477 ufshcd_print_evt(hba, UFS_EVT_DL_ERR, "dl_err");
478 ufshcd_print_evt(hba, UFS_EVT_NL_ERR, "nl_err");
479 ufshcd_print_evt(hba, UFS_EVT_TL_ERR, "tl_err");
480 ufshcd_print_evt(hba, UFS_EVT_DME_ERR, "dme_err");
481 ufshcd_print_evt(hba, UFS_EVT_AUTO_HIBERN8_ERR,
483 ufshcd_print_evt(hba, UFS_EVT_FATAL_ERR, "fatal_err");
484 ufshcd_print_evt(hba, UFS_EVT_LINK_STARTUP_FAIL,
485 "link_startup_fail");
486 ufshcd_print_evt(hba, UFS_EVT_RESUME_ERR, "resume_fail");
487 ufshcd_print_evt(hba, UFS_EVT_SUSPEND_ERR,
489 ufshcd_print_evt(hba, UFS_EVT_DEV_RESET, "dev_reset");
490 ufshcd_print_evt(hba, UFS_EVT_HOST_RESET, "host_reset");
491 ufshcd_print_evt(hba, UFS_EVT_ABORT, "task_abort");
493 ufshcd_vops_dbg_register_dump(hba);
497 void ufshcd_print_trs(struct ufs_hba *hba, unsigned long bitmap, bool pr_prdt)
499 const struct ufshcd_lrb *lrbp;
503 for_each_set_bit(tag, &bitmap, hba->nutrs) {
504 lrbp = &hba->lrb[tag];
506 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
507 tag, div_u64(lrbp->issue_time_stamp_local_clock, 1000));
508 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n",
509 tag, div_u64(lrbp->compl_time_stamp_local_clock, 1000));
511 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
512 tag, (u64)lrbp->utrd_dma_addr);
514 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
515 sizeof(struct utp_transfer_req_desc));
516 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
517 (u64)lrbp->ucd_req_dma_addr);
518 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
519 sizeof(struct utp_upiu_req));
520 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
521 (u64)lrbp->ucd_rsp_dma_addr);
522 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
523 sizeof(struct utp_upiu_rsp));
525 prdt_length = le16_to_cpu(
526 lrbp->utr_descriptor_ptr->prd_table_length);
527 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
528 prdt_length /= sizeof(struct ufshcd_sg_entry);
531 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
533 (u64)lrbp->ucd_prdt_dma_addr);
536 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
537 sizeof(struct ufshcd_sg_entry) * prdt_length);
541 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
545 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
546 struct utp_task_req_desc *tmrdp = &hba->utmrdl_base_addr[tag];
548 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
549 ufshcd_hex_dump("", tmrdp, sizeof(*tmrdp));
553 static void ufshcd_print_host_state(struct ufs_hba *hba)
555 const struct scsi_device *sdev_ufs = hba->ufs_device_wlun;
557 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
558 dev_err(hba->dev, "outstanding reqs=0x%lx tasks=0x%lx\n",
559 hba->outstanding_reqs, hba->outstanding_tasks);
560 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
561 hba->saved_err, hba->saved_uic_err);
562 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
563 hba->curr_dev_pwr_mode, hba->uic_link_state);
564 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
565 hba->pm_op_in_progress, hba->is_sys_suspended);
566 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
567 hba->auto_bkops_enabled, hba->host->host_self_blocked);
568 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
570 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt=%d\n",
571 div_u64(hba->ufs_stats.last_hibern8_exit_tstamp, 1000),
572 hba->ufs_stats.hibern8_exit_cnt);
573 dev_err(hba->dev, "last intr at %lld us, last intr status=0x%x\n",
574 div_u64(hba->ufs_stats.last_intr_ts, 1000),
575 hba->ufs_stats.last_intr_status);
576 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
577 hba->eh_flags, hba->req_abort_count);
578 dev_err(hba->dev, "hba->ufs_version=0x%x, Host capabilities=0x%x, caps=0x%x\n",
579 hba->ufs_version, hba->capabilities, hba->caps);
580 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
583 dev_err(hba->dev, "UFS dev info: %.8s %.16s rev %.4s\n",
584 sdev_ufs->vendor, sdev_ufs->model, sdev_ufs->rev);
586 ufshcd_print_clk_freqs(hba);
590 * ufshcd_print_pwr_info - print power params as saved in hba
592 * @hba: per-adapter instance
594 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
596 static const char * const names[] = {
607 * Using dev_dbg to avoid messages during runtime PM to avoid
608 * never-ending cycles of messages written back to storage by user space
609 * causing runtime resume, causing more messages and so on.
611 dev_dbg(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
613 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
614 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
615 names[hba->pwr_info.pwr_rx],
616 names[hba->pwr_info.pwr_tx],
617 hba->pwr_info.hs_rate);
620 static void ufshcd_device_reset(struct ufs_hba *hba)
624 err = ufshcd_vops_device_reset(hba);
627 ufshcd_set_ufs_dev_active(hba);
628 if (ufshcd_is_wb_allowed(hba)) {
629 hba->dev_info.wb_enabled = false;
630 hba->dev_info.wb_buf_flush_enabled = false;
633 if (err != -EOPNOTSUPP)
634 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, err);
637 void ufshcd_delay_us(unsigned long us, unsigned long tolerance)
645 usleep_range(us, us + tolerance);
647 EXPORT_SYMBOL_GPL(ufshcd_delay_us);
650 * ufshcd_wait_for_register - wait for register value to change
651 * @hba: per-adapter interface
652 * @reg: mmio register offset
653 * @mask: mask to apply to the read register value
654 * @val: value to wait for
655 * @interval_us: polling interval in microseconds
656 * @timeout_ms: timeout in milliseconds
659 * -ETIMEDOUT on error, zero on success.
661 static int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
662 u32 val, unsigned long interval_us,
663 unsigned long timeout_ms)
666 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
668 /* ignore bits that we don't intend to wait on */
671 while ((ufshcd_readl(hba, reg) & mask) != val) {
672 usleep_range(interval_us, interval_us + 50);
673 if (time_after(jiffies, timeout)) {
674 if ((ufshcd_readl(hba, reg) & mask) != val)
684 * ufshcd_get_intr_mask - Get the interrupt bit mask
685 * @hba: Pointer to adapter instance
687 * Returns interrupt bit mask per version
689 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
691 if (hba->ufs_version == ufshci_version(1, 0))
692 return INTERRUPT_MASK_ALL_VER_10;
693 if (hba->ufs_version <= ufshci_version(2, 0))
694 return INTERRUPT_MASK_ALL_VER_11;
696 return INTERRUPT_MASK_ALL_VER_21;
700 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
701 * @hba: Pointer to adapter instance
703 * Returns UFSHCI version supported by the controller
705 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
709 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
710 ufshci_ver = ufshcd_vops_get_ufs_hci_version(hba);
712 ufshci_ver = ufshcd_readl(hba, REG_UFS_VERSION);
715 * UFSHCI v1.x uses a different version scheme, in order
716 * to allow the use of comparisons with the ufshci_version
717 * function, we convert it to the same scheme as ufs 2.0+.
719 if (ufshci_ver & 0x00010000)
720 return ufshci_version(1, ufshci_ver & 0x00000100);
726 * ufshcd_is_device_present - Check if any device connected to
727 * the host controller
728 * @hba: pointer to adapter instance
730 * Returns true if device present, false if no device detected
732 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
734 return ufshcd_readl(hba, REG_CONTROLLER_STATUS) & DEVICE_PRESENT;
738 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
739 * @lrbp: pointer to local command reference block
741 * This function is used to get the OCS field from UTRD
742 * Returns the OCS field in the UTRD
744 static enum utp_ocs ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
746 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
750 * ufshcd_utrl_clear() - Clear requests from the controller request list.
751 * @hba: per adapter instance
752 * @mask: mask with one bit set for each request to be cleared
754 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 mask)
756 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
759 * From the UFSHCI specification: "UTP Transfer Request List CLear
760 * Register (UTRLCLR): This field is bit significant. Each bit
761 * corresponds to a slot in the UTP Transfer Request List, where bit 0
762 * corresponds to request slot 0. A bit in this field is set to ‘0’
763 * by host software to indicate to the host controller that a transfer
764 * request slot is cleared. The host controller
765 * shall free up any resources associated to the request slot
766 * immediately, and shall set the associated bit in UTRLDBR to ‘0’. The
767 * host software indicates no change to request slots by setting the
768 * associated bits in this field to ‘1’. Bits in this field shall only
769 * be set ‘1’ or ‘0’ by host software when UTRLRSR is set to ‘1’."
771 ufshcd_writel(hba, ~mask, REG_UTP_TRANSFER_REQ_LIST_CLEAR);
775 * ufshcd_utmrl_clear - Clear a bit in UTRMLCLR register
776 * @hba: per adapter instance
777 * @pos: position of the bit to be cleared
779 static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos)
781 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
782 ufshcd_writel(hba, (1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
784 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
788 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
789 * @reg: Register value of host controller status
791 * Returns integer, 0 on Success and positive value if failed
793 static inline int ufshcd_get_lists_status(u32 reg)
795 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
799 * ufshcd_get_uic_cmd_result - Get the UIC command result
800 * @hba: Pointer to adapter instance
802 * This function gets the result of UIC command completion
803 * Returns 0 on success, non zero value on error
805 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
807 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
808 MASK_UIC_COMMAND_RESULT;
812 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
813 * @hba: Pointer to adapter instance
815 * This function gets UIC command argument3
816 * Returns 0 on success, non zero value on error
818 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
820 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
824 * ufshcd_get_req_rsp - returns the TR response transaction type
825 * @ucd_rsp_ptr: pointer to response UPIU
828 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
830 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
834 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
835 * @ucd_rsp_ptr: pointer to response UPIU
837 * This function gets the response status and scsi_status from response UPIU
838 * Returns the response result code.
841 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
843 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
847 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
849 * @ucd_rsp_ptr: pointer to response UPIU
851 * Return the data segment length.
853 static inline unsigned int
854 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
856 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
857 MASK_RSP_UPIU_DATA_SEG_LEN;
861 * ufshcd_is_exception_event - Check if the device raised an exception event
862 * @ucd_rsp_ptr: pointer to response UPIU
864 * The function checks if the device raised an exception event indicated in
865 * the Device Information field of response UPIU.
867 * Returns true if exception is raised, false otherwise.
869 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
871 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
872 MASK_RSP_EXCEPTION_EVENT;
876 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
877 * @hba: per adapter instance
880 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
882 ufshcd_writel(hba, INT_AGGR_ENABLE |
883 INT_AGGR_COUNTER_AND_TIMER_RESET,
884 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
888 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
889 * @hba: per adapter instance
890 * @cnt: Interrupt aggregation counter threshold
891 * @tmout: Interrupt aggregation timeout value
894 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
896 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
897 INT_AGGR_COUNTER_THLD_VAL(cnt) |
898 INT_AGGR_TIMEOUT_VAL(tmout),
899 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
903 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
904 * @hba: per adapter instance
906 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
908 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
912 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
913 * When run-stop registers are set to 1, it indicates the
914 * host controller that it can process the requests
915 * @hba: per adapter instance
917 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
919 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
920 REG_UTP_TASK_REQ_LIST_RUN_STOP);
921 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
922 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
926 * ufshcd_hba_start - Start controller initialization sequence
927 * @hba: per adapter instance
929 static inline void ufshcd_hba_start(struct ufs_hba *hba)
931 u32 val = CONTROLLER_ENABLE;
933 if (ufshcd_crypto_enable(hba))
934 val |= CRYPTO_GENERAL_ENABLE;
936 ufshcd_writel(hba, val, REG_CONTROLLER_ENABLE);
940 * ufshcd_is_hba_active - Get controller state
941 * @hba: per adapter instance
943 * Returns true if and only if the controller is active.
945 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
947 return ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE;
950 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
952 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
953 if (hba->ufs_version <= ufshci_version(1, 1))
954 return UFS_UNIPRO_VER_1_41;
956 return UFS_UNIPRO_VER_1_6;
958 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
960 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
963 * If both host and device support UniPro ver1.6 or later, PA layer
964 * parameters tuning happens during link startup itself.
966 * We can manually tune PA layer parameters if either host or device
967 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
968 * logic simple, we will only do manual tuning if local unipro version
969 * doesn't support ver1.6 or later.
971 return ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6;
975 * ufshcd_set_clk_freq - set UFS controller clock frequencies
976 * @hba: per adapter instance
977 * @scale_up: If True, set max possible frequency othewise set low frequency
979 * Returns 0 if successful
980 * Returns < 0 for any other errors
982 static int ufshcd_set_clk_freq(struct ufs_hba *hba, bool scale_up)
985 struct ufs_clk_info *clki;
986 struct list_head *head = &hba->clk_list_head;
988 if (list_empty(head))
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)
997 ret = clk_set_rate(clki->clk, clki->max_freq);
999 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
1000 __func__, clki->name,
1001 clki->max_freq, ret);
1004 trace_ufshcd_clk_scaling(dev_name(hba->dev),
1005 "scaled up", clki->name,
1009 clki->curr_freq = clki->max_freq;
1011 } else if (!scale_up && clki->min_freq) {
1012 if (clki->curr_freq == clki->min_freq)
1015 ret = clk_set_rate(clki->clk, clki->min_freq);
1017 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
1018 __func__, clki->name,
1019 clki->min_freq, ret);
1022 trace_ufshcd_clk_scaling(dev_name(hba->dev),
1023 "scaled down", clki->name,
1026 clki->curr_freq = clki->min_freq;
1029 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
1030 clki->name, clk_get_rate(clki->clk));
1038 * ufshcd_scale_clks - scale up or scale down UFS controller clocks
1039 * @hba: per adapter instance
1040 * @scale_up: True if scaling up and false if scaling down
1042 * Returns 0 if successful
1043 * Returns < 0 for any other errors
1045 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
1048 ktime_t start = ktime_get();
1050 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
1054 ret = ufshcd_set_clk_freq(hba, scale_up);
1058 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1060 ufshcd_set_clk_freq(hba, !scale_up);
1063 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1064 (scale_up ? "up" : "down"),
1065 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1070 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
1071 * @hba: per adapter instance
1072 * @scale_up: True if scaling up and false if scaling down
1074 * Returns true if scaling is required, false otherwise.
1076 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
1079 struct ufs_clk_info *clki;
1080 struct list_head *head = &hba->clk_list_head;
1082 if (list_empty(head))
1085 list_for_each_entry(clki, head, list) {
1086 if (!IS_ERR_OR_NULL(clki->clk)) {
1087 if (scale_up && clki->max_freq) {
1088 if (clki->curr_freq == clki->max_freq)
1091 } else if (!scale_up && clki->min_freq) {
1092 if (clki->curr_freq == clki->min_freq)
1103 * Determine the number of pending commands by counting the bits in the SCSI
1104 * device budget maps. This approach has been selected because a bit is set in
1105 * the budget map before scsi_host_queue_ready() checks the host_self_blocked
1106 * flag. The host_self_blocked flag can be modified by calling
1107 * scsi_block_requests() or scsi_unblock_requests().
1109 static u32 ufshcd_pending_cmds(struct ufs_hba *hba)
1111 const struct scsi_device *sdev;
1114 lockdep_assert_held(hba->host->host_lock);
1115 __shost_for_each_device(sdev, hba->host)
1116 pending += sbitmap_weight(&sdev->budget_map);
1121 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
1122 u64 wait_timeout_us)
1124 unsigned long flags;
1128 bool timeout = false, do_last_check = false;
1131 ufshcd_hold(hba, false);
1132 spin_lock_irqsave(hba->host->host_lock, flags);
1134 * Wait for all the outstanding tasks/transfer requests.
1135 * Verify by checking the doorbell registers are clear.
1137 start = ktime_get();
1139 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
1144 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1145 tr_pending = ufshcd_pending_cmds(hba);
1146 if (!tm_doorbell && !tr_pending) {
1149 } else if (do_last_check) {
1153 spin_unlock_irqrestore(hba->host->host_lock, flags);
1155 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1159 * We might have scheduled out for long time so make
1160 * sure to check if doorbells are cleared by this time
1163 do_last_check = true;
1165 spin_lock_irqsave(hba->host->host_lock, flags);
1166 } while (tm_doorbell || tr_pending);
1170 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1171 __func__, tm_doorbell, tr_pending);
1175 spin_unlock_irqrestore(hba->host->host_lock, flags);
1176 ufshcd_release(hba);
1181 * ufshcd_scale_gear - scale up/down UFS gear
1182 * @hba: per adapter instance
1183 * @scale_up: True for scaling up gear and false for scaling down
1185 * Returns 0 for success,
1186 * Returns -EBUSY if scaling can't happen at this time
1187 * Returns non-zero for any other errors
1189 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1192 struct ufs_pa_layer_attr new_pwr_info;
1195 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info.info,
1196 sizeof(struct ufs_pa_layer_attr));
1198 memcpy(&new_pwr_info, &hba->pwr_info,
1199 sizeof(struct ufs_pa_layer_attr));
1201 if (hba->pwr_info.gear_tx > hba->clk_scaling.min_gear ||
1202 hba->pwr_info.gear_rx > hba->clk_scaling.min_gear) {
1203 /* save the current power mode */
1204 memcpy(&hba->clk_scaling.saved_pwr_info.info,
1206 sizeof(struct ufs_pa_layer_attr));
1208 /* scale down gear */
1209 new_pwr_info.gear_tx = hba->clk_scaling.min_gear;
1210 new_pwr_info.gear_rx = hba->clk_scaling.min_gear;
1214 /* check if the power mode needs to be changed or not? */
1215 ret = ufshcd_config_pwr_mode(hba, &new_pwr_info);
1217 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1219 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1220 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1225 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba)
1227 #define DOORBELL_CLR_TOUT_US (1000 * 1000) /* 1 sec */
1230 * make sure that there are no outstanding requests when
1231 * clock scaling is in progress
1233 ufshcd_scsi_block_requests(hba);
1234 down_write(&hba->clk_scaling_lock);
1236 if (!hba->clk_scaling.is_allowed ||
1237 ufshcd_wait_for_doorbell_clr(hba, DOORBELL_CLR_TOUT_US)) {
1239 up_write(&hba->clk_scaling_lock);
1240 ufshcd_scsi_unblock_requests(hba);
1244 /* let's not get into low power until clock scaling is completed */
1245 ufshcd_hold(hba, false);
1251 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba, bool writelock)
1254 up_write(&hba->clk_scaling_lock);
1256 up_read(&hba->clk_scaling_lock);
1257 ufshcd_scsi_unblock_requests(hba);
1258 ufshcd_release(hba);
1262 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1263 * @hba: per adapter instance
1264 * @scale_up: True for scaling up and false for scalin down
1266 * Returns 0 for success,
1267 * Returns -EBUSY if scaling can't happen at this time
1268 * Returns non-zero for any other errors
1270 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1273 bool is_writelock = true;
1275 ret = ufshcd_clock_scaling_prepare(hba);
1279 /* scale down the gear before scaling down clocks */
1281 ret = ufshcd_scale_gear(hba, false);
1286 ret = ufshcd_scale_clks(hba, scale_up);
1289 ufshcd_scale_gear(hba, true);
1293 /* scale up the gear after scaling up clocks */
1295 ret = ufshcd_scale_gear(hba, true);
1297 ufshcd_scale_clks(hba, false);
1302 /* Enable Write Booster if we have scaled up else disable it */
1303 if (ufshcd_enable_wb_if_scaling_up(hba)) {
1304 downgrade_write(&hba->clk_scaling_lock);
1305 is_writelock = false;
1306 ufshcd_wb_toggle(hba, scale_up);
1310 ufshcd_clock_scaling_unprepare(hba, is_writelock);
1314 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1316 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1317 clk_scaling.suspend_work);
1318 unsigned long irq_flags;
1320 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1321 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1322 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1325 hba->clk_scaling.is_suspended = true;
1326 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1328 __ufshcd_suspend_clkscaling(hba);
1331 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1333 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1334 clk_scaling.resume_work);
1335 unsigned long irq_flags;
1337 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1338 if (!hba->clk_scaling.is_suspended) {
1339 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1342 hba->clk_scaling.is_suspended = false;
1343 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1345 devfreq_resume_device(hba->devfreq);
1348 static int ufshcd_devfreq_target(struct device *dev,
1349 unsigned long *freq, u32 flags)
1352 struct ufs_hba *hba = dev_get_drvdata(dev);
1354 bool scale_up, sched_clk_scaling_suspend_work = false;
1355 struct list_head *clk_list = &hba->clk_list_head;
1356 struct ufs_clk_info *clki;
1357 unsigned long irq_flags;
1359 if (!ufshcd_is_clkscaling_supported(hba))
1362 clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info, list);
1363 /* Override with the closest supported frequency */
1364 *freq = (unsigned long) clk_round_rate(clki->clk, *freq);
1365 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1366 if (ufshcd_eh_in_progress(hba)) {
1367 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1371 if (!hba->clk_scaling.active_reqs)
1372 sched_clk_scaling_suspend_work = true;
1374 if (list_empty(clk_list)) {
1375 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1379 /* Decide based on the rounded-off frequency and update */
1380 scale_up = *freq == clki->max_freq;
1382 *freq = clki->min_freq;
1383 /* Update the frequency */
1384 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1385 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1387 goto out; /* no state change required */
1389 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1391 start = ktime_get();
1392 ret = ufshcd_devfreq_scale(hba, scale_up);
1394 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1395 (scale_up ? "up" : "down"),
1396 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1399 if (sched_clk_scaling_suspend_work)
1400 queue_work(hba->clk_scaling.workq,
1401 &hba->clk_scaling.suspend_work);
1406 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1407 struct devfreq_dev_status *stat)
1409 struct ufs_hba *hba = dev_get_drvdata(dev);
1410 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1411 unsigned long flags;
1412 struct list_head *clk_list = &hba->clk_list_head;
1413 struct ufs_clk_info *clki;
1416 if (!ufshcd_is_clkscaling_supported(hba))
1419 memset(stat, 0, sizeof(*stat));
1421 spin_lock_irqsave(hba->host->host_lock, flags);
1422 curr_t = ktime_get();
1423 if (!scaling->window_start_t)
1426 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1428 * If current frequency is 0, then the ondemand governor considers
1429 * there's no initial frequency set. And it always requests to set
1430 * to max. frequency.
1432 stat->current_frequency = clki->curr_freq;
1433 if (scaling->is_busy_started)
1434 scaling->tot_busy_t += ktime_us_delta(curr_t,
1435 scaling->busy_start_t);
1437 stat->total_time = ktime_us_delta(curr_t, scaling->window_start_t);
1438 stat->busy_time = scaling->tot_busy_t;
1440 scaling->window_start_t = curr_t;
1441 scaling->tot_busy_t = 0;
1443 if (hba->outstanding_reqs) {
1444 scaling->busy_start_t = curr_t;
1445 scaling->is_busy_started = true;
1447 scaling->busy_start_t = 0;
1448 scaling->is_busy_started = false;
1450 spin_unlock_irqrestore(hba->host->host_lock, flags);
1454 static int ufshcd_devfreq_init(struct ufs_hba *hba)
1456 struct list_head *clk_list = &hba->clk_list_head;
1457 struct ufs_clk_info *clki;
1458 struct devfreq *devfreq;
1461 /* Skip devfreq if we don't have any clocks in the list */
1462 if (list_empty(clk_list))
1465 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1466 dev_pm_opp_add(hba->dev, clki->min_freq, 0);
1467 dev_pm_opp_add(hba->dev, clki->max_freq, 0);
1469 ufshcd_vops_config_scaling_param(hba, &hba->vps->devfreq_profile,
1470 &hba->vps->ondemand_data);
1471 devfreq = devfreq_add_device(hba->dev,
1472 &hba->vps->devfreq_profile,
1473 DEVFREQ_GOV_SIMPLE_ONDEMAND,
1474 &hba->vps->ondemand_data);
1475 if (IS_ERR(devfreq)) {
1476 ret = PTR_ERR(devfreq);
1477 dev_err(hba->dev, "Unable to register with devfreq %d\n", ret);
1479 dev_pm_opp_remove(hba->dev, clki->min_freq);
1480 dev_pm_opp_remove(hba->dev, clki->max_freq);
1484 hba->devfreq = devfreq;
1489 static void ufshcd_devfreq_remove(struct ufs_hba *hba)
1491 struct list_head *clk_list = &hba->clk_list_head;
1492 struct ufs_clk_info *clki;
1497 devfreq_remove_device(hba->devfreq);
1498 hba->devfreq = NULL;
1500 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1501 dev_pm_opp_remove(hba->dev, clki->min_freq);
1502 dev_pm_opp_remove(hba->dev, clki->max_freq);
1505 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1507 unsigned long flags;
1509 devfreq_suspend_device(hba->devfreq);
1510 spin_lock_irqsave(hba->host->host_lock, flags);
1511 hba->clk_scaling.window_start_t = 0;
1512 spin_unlock_irqrestore(hba->host->host_lock, flags);
1515 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1517 unsigned long flags;
1518 bool suspend = false;
1520 cancel_work_sync(&hba->clk_scaling.suspend_work);
1521 cancel_work_sync(&hba->clk_scaling.resume_work);
1523 spin_lock_irqsave(hba->host->host_lock, flags);
1524 if (!hba->clk_scaling.is_suspended) {
1526 hba->clk_scaling.is_suspended = true;
1528 spin_unlock_irqrestore(hba->host->host_lock, flags);
1531 __ufshcd_suspend_clkscaling(hba);
1534 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1536 unsigned long flags;
1537 bool resume = false;
1539 spin_lock_irqsave(hba->host->host_lock, flags);
1540 if (hba->clk_scaling.is_suspended) {
1542 hba->clk_scaling.is_suspended = false;
1544 spin_unlock_irqrestore(hba->host->host_lock, flags);
1547 devfreq_resume_device(hba->devfreq);
1550 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1551 struct device_attribute *attr, char *buf)
1553 struct ufs_hba *hba = dev_get_drvdata(dev);
1555 return sysfs_emit(buf, "%d\n", hba->clk_scaling.is_enabled);
1558 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1559 struct device_attribute *attr, const char *buf, size_t count)
1561 struct ufs_hba *hba = dev_get_drvdata(dev);
1565 if (kstrtou32(buf, 0, &value))
1568 down(&hba->host_sem);
1569 if (!ufshcd_is_user_access_allowed(hba)) {
1575 if (value == hba->clk_scaling.is_enabled)
1578 ufshcd_rpm_get_sync(hba);
1579 ufshcd_hold(hba, false);
1581 hba->clk_scaling.is_enabled = value;
1584 ufshcd_resume_clkscaling(hba);
1586 ufshcd_suspend_clkscaling(hba);
1587 err = ufshcd_devfreq_scale(hba, true);
1589 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1593 ufshcd_release(hba);
1594 ufshcd_rpm_put_sync(hba);
1597 return err ? err : count;
1600 static void ufshcd_init_clk_scaling_sysfs(struct ufs_hba *hba)
1602 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1603 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1604 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1605 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1606 hba->clk_scaling.enable_attr.attr.mode = 0644;
1607 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1608 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1611 static void ufshcd_remove_clk_scaling_sysfs(struct ufs_hba *hba)
1613 if (hba->clk_scaling.enable_attr.attr.name)
1614 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
1617 static void ufshcd_init_clk_scaling(struct ufs_hba *hba)
1619 char wq_name[sizeof("ufs_clkscaling_00")];
1621 if (!ufshcd_is_clkscaling_supported(hba))
1624 if (!hba->clk_scaling.min_gear)
1625 hba->clk_scaling.min_gear = UFS_HS_G1;
1627 INIT_WORK(&hba->clk_scaling.suspend_work,
1628 ufshcd_clk_scaling_suspend_work);
1629 INIT_WORK(&hba->clk_scaling.resume_work,
1630 ufshcd_clk_scaling_resume_work);
1632 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
1633 hba->host->host_no);
1634 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
1636 hba->clk_scaling.is_initialized = true;
1639 static void ufshcd_exit_clk_scaling(struct ufs_hba *hba)
1641 if (!hba->clk_scaling.is_initialized)
1644 ufshcd_remove_clk_scaling_sysfs(hba);
1645 destroy_workqueue(hba->clk_scaling.workq);
1646 ufshcd_devfreq_remove(hba);
1647 hba->clk_scaling.is_initialized = false;
1650 static void ufshcd_ungate_work(struct work_struct *work)
1653 unsigned long flags;
1654 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1655 clk_gating.ungate_work);
1657 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1659 spin_lock_irqsave(hba->host->host_lock, flags);
1660 if (hba->clk_gating.state == CLKS_ON) {
1661 spin_unlock_irqrestore(hba->host->host_lock, flags);
1665 spin_unlock_irqrestore(hba->host->host_lock, flags);
1666 ufshcd_hba_vreg_set_hpm(hba);
1667 ufshcd_setup_clocks(hba, true);
1669 ufshcd_enable_irq(hba);
1671 /* Exit from hibern8 */
1672 if (ufshcd_can_hibern8_during_gating(hba)) {
1673 /* Prevent gating in this path */
1674 hba->clk_gating.is_suspended = true;
1675 if (ufshcd_is_link_hibern8(hba)) {
1676 ret = ufshcd_uic_hibern8_exit(hba);
1678 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1681 ufshcd_set_link_active(hba);
1683 hba->clk_gating.is_suspended = false;
1686 ufshcd_scsi_unblock_requests(hba);
1690 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1691 * Also, exit from hibern8 mode and set the link as active.
1692 * @hba: per adapter instance
1693 * @async: This indicates whether caller should ungate clocks asynchronously.
1695 int ufshcd_hold(struct ufs_hba *hba, bool async)
1699 unsigned long flags;
1701 if (!ufshcd_is_clkgating_allowed(hba) ||
1702 !hba->clk_gating.is_initialized)
1704 spin_lock_irqsave(hba->host->host_lock, flags);
1705 hba->clk_gating.active_reqs++;
1708 switch (hba->clk_gating.state) {
1711 * Wait for the ungate work to complete if in progress.
1712 * Though the clocks may be in ON state, the link could
1713 * still be in hibner8 state if hibern8 is allowed
1714 * during clock gating.
1715 * Make sure we exit hibern8 state also in addition to
1718 if (ufshcd_can_hibern8_during_gating(hba) &&
1719 ufshcd_is_link_hibern8(hba)) {
1722 hba->clk_gating.active_reqs--;
1725 spin_unlock_irqrestore(hba->host->host_lock, flags);
1726 flush_result = flush_work(&hba->clk_gating.ungate_work);
1727 if (hba->clk_gating.is_suspended && !flush_result)
1729 spin_lock_irqsave(hba->host->host_lock, flags);
1734 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1735 hba->clk_gating.state = CLKS_ON;
1736 trace_ufshcd_clk_gating(dev_name(hba->dev),
1737 hba->clk_gating.state);
1741 * If we are here, it means gating work is either done or
1742 * currently running. Hence, fall through to cancel gating
1743 * work and to enable clocks.
1747 hba->clk_gating.state = REQ_CLKS_ON;
1748 trace_ufshcd_clk_gating(dev_name(hba->dev),
1749 hba->clk_gating.state);
1750 if (queue_work(hba->clk_gating.clk_gating_workq,
1751 &hba->clk_gating.ungate_work))
1752 ufshcd_scsi_block_requests(hba);
1754 * fall through to check if we should wait for this
1755 * work to be done or not.
1761 hba->clk_gating.active_reqs--;
1765 spin_unlock_irqrestore(hba->host->host_lock, flags);
1766 flush_work(&hba->clk_gating.ungate_work);
1767 /* Make sure state is CLKS_ON before returning */
1768 spin_lock_irqsave(hba->host->host_lock, flags);
1771 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1772 __func__, hba->clk_gating.state);
1775 spin_unlock_irqrestore(hba->host->host_lock, flags);
1779 EXPORT_SYMBOL_GPL(ufshcd_hold);
1781 static void ufshcd_gate_work(struct work_struct *work)
1783 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1784 clk_gating.gate_work.work);
1785 unsigned long flags;
1788 spin_lock_irqsave(hba->host->host_lock, flags);
1790 * In case you are here to cancel this work the gating state
1791 * would be marked as REQ_CLKS_ON. In this case save time by
1792 * skipping the gating work and exit after changing the clock
1795 if (hba->clk_gating.is_suspended ||
1796 (hba->clk_gating.state != REQ_CLKS_OFF)) {
1797 hba->clk_gating.state = CLKS_ON;
1798 trace_ufshcd_clk_gating(dev_name(hba->dev),
1799 hba->clk_gating.state);
1803 if (hba->clk_gating.active_reqs
1804 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1805 || hba->outstanding_reqs || hba->outstanding_tasks
1806 || hba->active_uic_cmd || hba->uic_async_done)
1809 spin_unlock_irqrestore(hba->host->host_lock, flags);
1811 /* put the link into hibern8 mode before turning off clocks */
1812 if (ufshcd_can_hibern8_during_gating(hba)) {
1813 ret = ufshcd_uic_hibern8_enter(hba);
1815 hba->clk_gating.state = CLKS_ON;
1816 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
1818 trace_ufshcd_clk_gating(dev_name(hba->dev),
1819 hba->clk_gating.state);
1822 ufshcd_set_link_hibern8(hba);
1825 ufshcd_disable_irq(hba);
1827 ufshcd_setup_clocks(hba, false);
1829 /* Put the host controller in low power mode if possible */
1830 ufshcd_hba_vreg_set_lpm(hba);
1832 * In case you are here to cancel this work the gating state
1833 * would be marked as REQ_CLKS_ON. In this case keep the state
1834 * as REQ_CLKS_ON which would anyway imply that clocks are off
1835 * and a request to turn them on is pending. By doing this way,
1836 * we keep the state machine in tact and this would ultimately
1837 * prevent from doing cancel work multiple times when there are
1838 * new requests arriving before the current cancel work is done.
1840 spin_lock_irqsave(hba->host->host_lock, flags);
1841 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1842 hba->clk_gating.state = CLKS_OFF;
1843 trace_ufshcd_clk_gating(dev_name(hba->dev),
1844 hba->clk_gating.state);
1847 spin_unlock_irqrestore(hba->host->host_lock, flags);
1852 /* host lock must be held before calling this variant */
1853 static void __ufshcd_release(struct ufs_hba *hba)
1855 if (!ufshcd_is_clkgating_allowed(hba))
1858 hba->clk_gating.active_reqs--;
1860 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended ||
1861 hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL ||
1862 hba->outstanding_tasks || !hba->clk_gating.is_initialized ||
1863 hba->active_uic_cmd || hba->uic_async_done ||
1864 hba->clk_gating.state == CLKS_OFF)
1867 hba->clk_gating.state = REQ_CLKS_OFF;
1868 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1869 queue_delayed_work(hba->clk_gating.clk_gating_workq,
1870 &hba->clk_gating.gate_work,
1871 msecs_to_jiffies(hba->clk_gating.delay_ms));
1874 void ufshcd_release(struct ufs_hba *hba)
1876 unsigned long flags;
1878 spin_lock_irqsave(hba->host->host_lock, flags);
1879 __ufshcd_release(hba);
1880 spin_unlock_irqrestore(hba->host->host_lock, flags);
1882 EXPORT_SYMBOL_GPL(ufshcd_release);
1884 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1885 struct device_attribute *attr, char *buf)
1887 struct ufs_hba *hba = dev_get_drvdata(dev);
1889 return sysfs_emit(buf, "%lu\n", hba->clk_gating.delay_ms);
1892 void ufshcd_clkgate_delay_set(struct device *dev, unsigned long value)
1894 struct ufs_hba *hba = dev_get_drvdata(dev);
1895 unsigned long flags;
1897 spin_lock_irqsave(hba->host->host_lock, flags);
1898 hba->clk_gating.delay_ms = value;
1899 spin_unlock_irqrestore(hba->host->host_lock, flags);
1901 EXPORT_SYMBOL_GPL(ufshcd_clkgate_delay_set);
1903 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1904 struct device_attribute *attr, const char *buf, size_t count)
1906 unsigned long value;
1908 if (kstrtoul(buf, 0, &value))
1911 ufshcd_clkgate_delay_set(dev, value);
1915 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1916 struct device_attribute *attr, char *buf)
1918 struct ufs_hba *hba = dev_get_drvdata(dev);
1920 return sysfs_emit(buf, "%d\n", hba->clk_gating.is_enabled);
1923 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1924 struct device_attribute *attr, const char *buf, size_t count)
1926 struct ufs_hba *hba = dev_get_drvdata(dev);
1927 unsigned long flags;
1930 if (kstrtou32(buf, 0, &value))
1935 spin_lock_irqsave(hba->host->host_lock, flags);
1936 if (value == hba->clk_gating.is_enabled)
1940 __ufshcd_release(hba);
1942 hba->clk_gating.active_reqs++;
1944 hba->clk_gating.is_enabled = value;
1946 spin_unlock_irqrestore(hba->host->host_lock, flags);
1950 static void ufshcd_init_clk_gating_sysfs(struct ufs_hba *hba)
1952 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1953 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1954 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1955 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1956 hba->clk_gating.delay_attr.attr.mode = 0644;
1957 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1958 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1960 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
1961 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
1962 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
1963 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
1964 hba->clk_gating.enable_attr.attr.mode = 0644;
1965 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
1966 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1969 static void ufshcd_remove_clk_gating_sysfs(struct ufs_hba *hba)
1971 if (hba->clk_gating.delay_attr.attr.name)
1972 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1973 if (hba->clk_gating.enable_attr.attr.name)
1974 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1977 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1979 char wq_name[sizeof("ufs_clk_gating_00")];
1981 if (!ufshcd_is_clkgating_allowed(hba))
1984 hba->clk_gating.state = CLKS_ON;
1986 hba->clk_gating.delay_ms = 150;
1987 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
1988 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
1990 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d",
1991 hba->host->host_no);
1992 hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(wq_name,
1993 WQ_MEM_RECLAIM | WQ_HIGHPRI);
1995 ufshcd_init_clk_gating_sysfs(hba);
1997 hba->clk_gating.is_enabled = true;
1998 hba->clk_gating.is_initialized = true;
2001 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
2003 if (!hba->clk_gating.is_initialized)
2006 ufshcd_remove_clk_gating_sysfs(hba);
2008 /* Ungate the clock if necessary. */
2009 ufshcd_hold(hba, false);
2010 hba->clk_gating.is_initialized = false;
2011 ufshcd_release(hba);
2013 destroy_workqueue(hba->clk_gating.clk_gating_workq);
2016 /* Must be called with host lock acquired */
2017 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
2019 bool queue_resume_work = false;
2020 ktime_t curr_t = ktime_get();
2021 unsigned long flags;
2023 if (!ufshcd_is_clkscaling_supported(hba))
2026 spin_lock_irqsave(hba->host->host_lock, flags);
2027 if (!hba->clk_scaling.active_reqs++)
2028 queue_resume_work = true;
2030 if (!hba->clk_scaling.is_enabled || hba->pm_op_in_progress) {
2031 spin_unlock_irqrestore(hba->host->host_lock, flags);
2035 if (queue_resume_work)
2036 queue_work(hba->clk_scaling.workq,
2037 &hba->clk_scaling.resume_work);
2039 if (!hba->clk_scaling.window_start_t) {
2040 hba->clk_scaling.window_start_t = curr_t;
2041 hba->clk_scaling.tot_busy_t = 0;
2042 hba->clk_scaling.is_busy_started = false;
2045 if (!hba->clk_scaling.is_busy_started) {
2046 hba->clk_scaling.busy_start_t = curr_t;
2047 hba->clk_scaling.is_busy_started = true;
2049 spin_unlock_irqrestore(hba->host->host_lock, flags);
2052 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
2054 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
2055 unsigned long flags;
2057 if (!ufshcd_is_clkscaling_supported(hba))
2060 spin_lock_irqsave(hba->host->host_lock, flags);
2061 hba->clk_scaling.active_reqs--;
2062 if (!hba->outstanding_reqs && scaling->is_busy_started) {
2063 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
2064 scaling->busy_start_t));
2065 scaling->busy_start_t = 0;
2066 scaling->is_busy_started = false;
2068 spin_unlock_irqrestore(hba->host->host_lock, flags);
2071 static inline int ufshcd_monitor_opcode2dir(u8 opcode)
2073 if (opcode == READ_6 || opcode == READ_10 || opcode == READ_16)
2075 else if (opcode == WRITE_6 || opcode == WRITE_10 || opcode == WRITE_16)
2081 static inline bool ufshcd_should_inform_monitor(struct ufs_hba *hba,
2082 struct ufshcd_lrb *lrbp)
2084 const struct ufs_hba_monitor *m = &hba->monitor;
2086 return (m->enabled && lrbp && lrbp->cmd &&
2087 (!m->chunk_size || m->chunk_size == lrbp->cmd->sdb.length) &&
2088 ktime_before(hba->monitor.enabled_ts, lrbp->issue_time_stamp));
2091 static void ufshcd_start_monitor(struct ufs_hba *hba,
2092 const struct ufshcd_lrb *lrbp)
2094 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2095 unsigned long flags;
2097 spin_lock_irqsave(hba->host->host_lock, flags);
2098 if (dir >= 0 && hba->monitor.nr_queued[dir]++ == 0)
2099 hba->monitor.busy_start_ts[dir] = ktime_get();
2100 spin_unlock_irqrestore(hba->host->host_lock, flags);
2103 static void ufshcd_update_monitor(struct ufs_hba *hba, const struct ufshcd_lrb *lrbp)
2105 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2106 unsigned long flags;
2108 spin_lock_irqsave(hba->host->host_lock, flags);
2109 if (dir >= 0 && hba->monitor.nr_queued[dir] > 0) {
2110 const struct request *req = scsi_cmd_to_rq(lrbp->cmd);
2111 struct ufs_hba_monitor *m = &hba->monitor;
2112 ktime_t now, inc, lat;
2114 now = lrbp->compl_time_stamp;
2115 inc = ktime_sub(now, m->busy_start_ts[dir]);
2116 m->total_busy[dir] = ktime_add(m->total_busy[dir], inc);
2117 m->nr_sec_rw[dir] += blk_rq_sectors(req);
2119 /* Update latencies */
2121 lat = ktime_sub(now, lrbp->issue_time_stamp);
2122 m->lat_sum[dir] += lat;
2123 if (m->lat_max[dir] < lat || !m->lat_max[dir])
2124 m->lat_max[dir] = lat;
2125 if (m->lat_min[dir] > lat || !m->lat_min[dir])
2126 m->lat_min[dir] = lat;
2128 m->nr_queued[dir]--;
2129 /* Push forward the busy start of monitor */
2130 m->busy_start_ts[dir] = now;
2132 spin_unlock_irqrestore(hba->host->host_lock, flags);
2136 * ufshcd_send_command - Send SCSI or device management commands
2137 * @hba: per adapter instance
2138 * @task_tag: Task tag of the command
2141 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
2143 struct ufshcd_lrb *lrbp = &hba->lrb[task_tag];
2144 unsigned long flags;
2146 lrbp->issue_time_stamp = ktime_get();
2147 lrbp->issue_time_stamp_local_clock = local_clock();
2148 lrbp->compl_time_stamp = ktime_set(0, 0);
2149 lrbp->compl_time_stamp_local_clock = 0;
2150 ufshcd_add_command_trace(hba, task_tag, UFS_CMD_SEND);
2151 ufshcd_clk_scaling_start_busy(hba);
2152 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
2153 ufshcd_start_monitor(hba, lrbp);
2155 spin_lock_irqsave(&hba->outstanding_lock, flags);
2156 if (hba->vops && hba->vops->setup_xfer_req)
2157 hba->vops->setup_xfer_req(hba, task_tag, !!lrbp->cmd);
2158 __set_bit(task_tag, &hba->outstanding_reqs);
2159 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
2160 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
2164 * ufshcd_copy_sense_data - Copy sense data in case of check condition
2165 * @lrbp: pointer to local reference block
2167 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
2169 u8 *const sense_buffer = lrbp->cmd->sense_buffer;
2173 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
2176 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
2177 len_to_copy = min_t(int, UFS_SENSE_SIZE, len);
2179 memcpy(sense_buffer, lrbp->ucd_rsp_ptr->sr.sense_data,
2185 * ufshcd_copy_query_response() - Copy the Query Response and the data
2187 * @hba: per adapter instance
2188 * @lrbp: pointer to local reference block
2191 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2193 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2195 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
2197 /* Get the descriptor */
2198 if (hba->dev_cmd.query.descriptor &&
2199 lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
2200 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
2201 GENERAL_UPIU_REQUEST_SIZE;
2205 /* data segment length */
2206 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
2207 MASK_QUERY_DATA_SEG_LEN;
2208 buf_len = be16_to_cpu(
2209 hba->dev_cmd.query.request.upiu_req.length);
2210 if (likely(buf_len >= resp_len)) {
2211 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
2214 "%s: rsp size %d is bigger than buffer size %d",
2215 __func__, resp_len, buf_len);
2224 * ufshcd_hba_capabilities - Read controller capabilities
2225 * @hba: per adapter instance
2227 * Return: 0 on success, negative on error.
2229 static inline int ufshcd_hba_capabilities(struct ufs_hba *hba)
2233 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
2234 if (hba->quirks & UFSHCD_QUIRK_BROKEN_64BIT_ADDRESS)
2235 hba->capabilities &= ~MASK_64_ADDRESSING_SUPPORT;
2237 /* nutrs and nutmrs are 0 based values */
2238 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
2240 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
2241 hba->reserved_slot = hba->nutrs - 1;
2243 /* Read crypto capabilities */
2244 err = ufshcd_hba_init_crypto_capabilities(hba);
2246 dev_err(hba->dev, "crypto setup failed\n");
2252 * ufshcd_ready_for_uic_cmd - Check if controller is ready
2253 * to accept UIC commands
2254 * @hba: per adapter instance
2255 * Return true on success, else false
2257 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
2259 return ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY;
2263 * ufshcd_get_upmcrs - Get the power mode change request status
2264 * @hba: Pointer to adapter instance
2266 * This function gets the UPMCRS field of HCS register
2267 * Returns value of UPMCRS field
2269 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
2271 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
2275 * ufshcd_dispatch_uic_cmd - Dispatch an UIC command to the Unipro layer
2276 * @hba: per adapter instance
2277 * @uic_cmd: UIC command
2280 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2282 lockdep_assert_held(&hba->uic_cmd_mutex);
2284 WARN_ON(hba->active_uic_cmd);
2286 hba->active_uic_cmd = uic_cmd;
2289 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2290 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2291 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2293 ufshcd_add_uic_command_trace(hba, uic_cmd, UFS_CMD_SEND);
2296 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2301 * ufshcd_wait_for_uic_cmd - Wait for completion of an UIC command
2302 * @hba: per adapter instance
2303 * @uic_cmd: UIC command
2305 * Returns 0 only if success.
2308 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2311 unsigned long flags;
2313 lockdep_assert_held(&hba->uic_cmd_mutex);
2315 if (wait_for_completion_timeout(&uic_cmd->done,
2316 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
2317 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2321 "uic cmd 0x%x with arg3 0x%x completion timeout\n",
2322 uic_cmd->command, uic_cmd->argument3);
2324 if (!uic_cmd->cmd_active) {
2325 dev_err(hba->dev, "%s: UIC cmd has been completed, return the result\n",
2327 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2331 spin_lock_irqsave(hba->host->host_lock, flags);
2332 hba->active_uic_cmd = NULL;
2333 spin_unlock_irqrestore(hba->host->host_lock, flags);
2339 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2340 * @hba: per adapter instance
2341 * @uic_cmd: UIC command
2342 * @completion: initialize the completion only if this is set to true
2344 * Returns 0 only if success.
2347 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
2350 lockdep_assert_held(&hba->uic_cmd_mutex);
2351 lockdep_assert_held(hba->host->host_lock);
2353 if (!ufshcd_ready_for_uic_cmd(hba)) {
2355 "Controller not ready to accept UIC commands\n");
2360 init_completion(&uic_cmd->done);
2362 uic_cmd->cmd_active = 1;
2363 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2369 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2370 * @hba: per adapter instance
2371 * @uic_cmd: UIC command
2373 * Returns 0 only if success.
2375 int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2378 unsigned long flags;
2380 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UIC_CMD)
2383 ufshcd_hold(hba, false);
2384 mutex_lock(&hba->uic_cmd_mutex);
2385 ufshcd_add_delay_before_dme_cmd(hba);
2387 spin_lock_irqsave(hba->host->host_lock, flags);
2388 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
2389 spin_unlock_irqrestore(hba->host->host_lock, flags);
2391 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2393 mutex_unlock(&hba->uic_cmd_mutex);
2395 ufshcd_release(hba);
2400 * ufshcd_map_sg - Map scatter-gather list to prdt
2401 * @hba: per adapter instance
2402 * @lrbp: pointer to local reference block
2404 * Returns 0 in case of success, non-zero value in case of failure
2406 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2408 struct ufshcd_sg_entry *prd_table;
2409 struct scatterlist *sg;
2410 struct scsi_cmnd *cmd;
2415 sg_segments = scsi_dma_map(cmd);
2416 if (sg_segments < 0)
2421 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2422 lrbp->utr_descriptor_ptr->prd_table_length =
2423 cpu_to_le16((sg_segments *
2424 sizeof(struct ufshcd_sg_entry)));
2426 lrbp->utr_descriptor_ptr->prd_table_length =
2427 cpu_to_le16(sg_segments);
2429 prd_table = lrbp->ucd_prdt_ptr;
2431 scsi_for_each_sg(cmd, sg, sg_segments, i) {
2432 const unsigned int len = sg_dma_len(sg);
2435 * From the UFSHCI spec: "Data Byte Count (DBC): A '0'
2436 * based value that indicates the length, in bytes, of
2437 * the data block. A maximum of length of 256KB may
2438 * exist for any entry. Bits 1:0 of this field shall be
2439 * 11b to indicate Dword granularity. A value of '3'
2440 * indicates 4 bytes, '7' indicates 8 bytes, etc."
2442 WARN_ONCE(len > 256 * 1024, "len = %#x\n", len);
2443 prd_table[i].size = cpu_to_le32(len - 1);
2444 prd_table[i].addr = cpu_to_le64(sg->dma_address);
2445 prd_table[i].reserved = 0;
2448 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2455 * ufshcd_enable_intr - enable interrupts
2456 * @hba: per adapter instance
2457 * @intrs: interrupt bits
2459 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2461 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2463 if (hba->ufs_version == ufshci_version(1, 0)) {
2465 rw = set & INTERRUPT_MASK_RW_VER_10;
2466 set = rw | ((set ^ intrs) & intrs);
2471 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2475 * ufshcd_disable_intr - disable interrupts
2476 * @hba: per adapter instance
2477 * @intrs: interrupt bits
2479 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2481 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2483 if (hba->ufs_version == ufshci_version(1, 0)) {
2485 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2486 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2487 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2493 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2497 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
2498 * descriptor according to request
2499 * @lrbp: pointer to local reference block
2500 * @upiu_flags: flags required in the header
2501 * @cmd_dir: requests data direction
2503 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
2504 u8 *upiu_flags, enum dma_data_direction cmd_dir)
2506 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2512 if (cmd_dir == DMA_FROM_DEVICE) {
2513 data_direction = UTP_DEVICE_TO_HOST;
2514 *upiu_flags = UPIU_CMD_FLAGS_READ;
2515 } else if (cmd_dir == DMA_TO_DEVICE) {
2516 data_direction = UTP_HOST_TO_DEVICE;
2517 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2519 data_direction = UTP_NO_DATA_TRANSFER;
2520 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2523 dword_0 = data_direction | (lrbp->command_type
2524 << UPIU_COMMAND_TYPE_OFFSET);
2526 dword_0 |= UTP_REQ_DESC_INT_CMD;
2528 /* Prepare crypto related dwords */
2529 ufshcd_prepare_req_desc_hdr_crypto(lrbp, &dword_0, &dword_1, &dword_3);
2531 /* Transfer request descriptor header fields */
2532 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2533 req_desc->header.dword_1 = cpu_to_le32(dword_1);
2535 * assigning invalid value for command status. Controller
2536 * updates OCS on command completion, with the command
2539 req_desc->header.dword_2 =
2540 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2541 req_desc->header.dword_3 = cpu_to_le32(dword_3);
2543 req_desc->prd_table_length = 0;
2547 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2549 * @lrbp: local reference block pointer
2550 * @upiu_flags: flags
2553 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u8 upiu_flags)
2555 struct scsi_cmnd *cmd = lrbp->cmd;
2556 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2557 unsigned short cdb_len;
2559 /* command descriptor fields */
2560 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2561 UPIU_TRANSACTION_COMMAND, upiu_flags,
2562 lrbp->lun, lrbp->task_tag);
2563 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2564 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2566 /* Total EHS length and Data segment length will be zero */
2567 ucd_req_ptr->header.dword_2 = 0;
2569 ucd_req_ptr->sc.exp_data_transfer_len = cpu_to_be32(cmd->sdb.length);
2571 cdb_len = min_t(unsigned short, cmd->cmd_len, UFS_CDB_SIZE);
2572 memset(ucd_req_ptr->sc.cdb, 0, UFS_CDB_SIZE);
2573 memcpy(ucd_req_ptr->sc.cdb, cmd->cmnd, cdb_len);
2575 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2579 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
2582 * @lrbp: local reference block pointer
2583 * @upiu_flags: flags
2585 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2586 struct ufshcd_lrb *lrbp, u8 upiu_flags)
2588 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2589 struct ufs_query *query = &hba->dev_cmd.query;
2590 u16 len = be16_to_cpu(query->request.upiu_req.length);
2592 /* Query request header */
2593 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2594 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2595 lrbp->lun, lrbp->task_tag);
2596 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2597 0, query->request.query_func, 0, 0);
2599 /* Data segment length only need for WRITE_DESC */
2600 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2601 ucd_req_ptr->header.dword_2 =
2602 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2604 ucd_req_ptr->header.dword_2 = 0;
2606 /* Copy the Query Request buffer as is */
2607 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2610 /* Copy the Descriptor */
2611 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2612 memcpy(ucd_req_ptr + 1, query->descriptor, len);
2614 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2617 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2619 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2621 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2623 /* command descriptor fields */
2624 ucd_req_ptr->header.dword_0 =
2626 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2627 /* clear rest of the fields of basic header */
2628 ucd_req_ptr->header.dword_1 = 0;
2629 ucd_req_ptr->header.dword_2 = 0;
2631 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2635 * ufshcd_compose_devman_upiu - UFS Protocol Information Unit(UPIU)
2636 * for Device Management Purposes
2637 * @hba: per adapter instance
2638 * @lrbp: pointer to local reference block
2640 static int ufshcd_compose_devman_upiu(struct ufs_hba *hba,
2641 struct ufshcd_lrb *lrbp)
2646 if (hba->ufs_version <= ufshci_version(1, 1))
2647 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2649 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2651 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
2652 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2653 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2654 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2655 ufshcd_prepare_utp_nop_upiu(lrbp);
2663 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2665 * @hba: per adapter instance
2666 * @lrbp: pointer to local reference block
2668 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2673 if (hba->ufs_version <= ufshci_version(1, 1))
2674 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2676 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2678 if (likely(lrbp->cmd)) {
2679 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
2680 lrbp->cmd->sc_data_direction);
2681 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2690 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2691 * @upiu_wlun_id: UPIU W-LUN id
2693 * Returns SCSI W-LUN id
2695 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2697 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2700 static inline bool is_device_wlun(struct scsi_device *sdev)
2703 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN);
2707 * Associate the UFS controller queue with the default and poll HCTX types.
2708 * Initialize the mq_map[] arrays.
2710 static void ufshcd_map_queues(struct Scsi_Host *shost)
2714 for (i = 0; i < shost->nr_maps; i++) {
2715 struct blk_mq_queue_map *map = &shost->tag_set.map[i];
2718 case HCTX_TYPE_DEFAULT:
2719 case HCTX_TYPE_POLL:
2722 case HCTX_TYPE_READ:
2728 map->queue_offset = 0;
2729 blk_mq_map_queues(map);
2733 static void ufshcd_init_lrb(struct ufs_hba *hba, struct ufshcd_lrb *lrb, int i)
2735 struct utp_transfer_cmd_desc *cmd_descp = hba->ucdl_base_addr;
2736 struct utp_transfer_req_desc *utrdlp = hba->utrdl_base_addr;
2737 dma_addr_t cmd_desc_element_addr = hba->ucdl_dma_addr +
2738 i * sizeof(struct utp_transfer_cmd_desc);
2739 u16 response_offset = offsetof(struct utp_transfer_cmd_desc,
2741 u16 prdt_offset = offsetof(struct utp_transfer_cmd_desc, prd_table);
2743 lrb->utr_descriptor_ptr = utrdlp + i;
2744 lrb->utrd_dma_addr = hba->utrdl_dma_addr +
2745 i * sizeof(struct utp_transfer_req_desc);
2746 lrb->ucd_req_ptr = (struct utp_upiu_req *)(cmd_descp + i);
2747 lrb->ucd_req_dma_addr = cmd_desc_element_addr;
2748 lrb->ucd_rsp_ptr = (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
2749 lrb->ucd_rsp_dma_addr = cmd_desc_element_addr + response_offset;
2750 lrb->ucd_prdt_ptr = cmd_descp[i].prd_table;
2751 lrb->ucd_prdt_dma_addr = cmd_desc_element_addr + prdt_offset;
2755 * ufshcd_queuecommand - main entry point for SCSI requests
2756 * @host: SCSI host pointer
2757 * @cmd: command from SCSI Midlayer
2759 * Returns 0 for success, non-zero in case of failure
2761 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2763 struct ufs_hba *hba = shost_priv(host);
2764 int tag = scsi_cmd_to_rq(cmd)->tag;
2765 struct ufshcd_lrb *lrbp;
2768 WARN_ONCE(tag < 0 || tag >= hba->nutrs, "Invalid tag %d\n", tag);
2771 * Allows the UFS error handler to wait for prior ufshcd_queuecommand()
2776 switch (hba->ufshcd_state) {
2777 case UFSHCD_STATE_OPERATIONAL:
2779 case UFSHCD_STATE_EH_SCHEDULED_NON_FATAL:
2781 * SCSI error handler can call ->queuecommand() while UFS error
2782 * handler is in progress. Error interrupts could change the
2783 * state from UFSHCD_STATE_RESET to
2784 * UFSHCD_STATE_EH_SCHEDULED_NON_FATAL. Prevent requests
2785 * being issued in that case.
2787 if (ufshcd_eh_in_progress(hba)) {
2788 err = SCSI_MLQUEUE_HOST_BUSY;
2792 case UFSHCD_STATE_EH_SCHEDULED_FATAL:
2794 * pm_runtime_get_sync() is used at error handling preparation
2795 * stage. If a scsi cmd, e.g. the SSU cmd, is sent from hba's
2796 * PM ops, it can never be finished if we let SCSI layer keep
2797 * retrying it, which gets err handler stuck forever. Neither
2798 * can we let the scsi cmd pass through, because UFS is in bad
2799 * state, the scsi cmd may eventually time out, which will get
2800 * err handler blocked for too long. So, just fail the scsi cmd
2801 * sent from PM ops, err handler can recover PM error anyways.
2803 if (hba->pm_op_in_progress) {
2804 hba->force_reset = true;
2805 set_host_byte(cmd, DID_BAD_TARGET);
2810 case UFSHCD_STATE_RESET:
2811 err = SCSI_MLQUEUE_HOST_BUSY;
2813 case UFSHCD_STATE_ERROR:
2814 set_host_byte(cmd, DID_ERROR);
2819 hba->req_abort_count = 0;
2821 err = ufshcd_hold(hba, true);
2823 err = SCSI_MLQUEUE_HOST_BUSY;
2826 WARN_ON(ufshcd_is_clkgating_allowed(hba) &&
2827 (hba->clk_gating.state != CLKS_ON));
2829 lrbp = &hba->lrb[tag];
2832 lrbp->task_tag = tag;
2833 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2834 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba);
2836 ufshcd_prepare_lrbp_crypto(scsi_cmd_to_rq(cmd), lrbp);
2838 lrbp->req_abort_skip = false;
2840 ufshpb_prep(hba, lrbp);
2842 ufshcd_comp_scsi_upiu(hba, lrbp);
2844 err = ufshcd_map_sg(hba, lrbp);
2847 ufshcd_release(hba);
2851 ufshcd_send_command(hba, tag);
2856 if (ufs_trigger_eh()) {
2857 unsigned long flags;
2859 spin_lock_irqsave(hba->host->host_lock, flags);
2860 ufshcd_schedule_eh_work(hba);
2861 spin_unlock_irqrestore(hba->host->host_lock, flags);
2867 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2868 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2871 lrbp->task_tag = tag;
2872 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2873 lrbp->intr_cmd = true; /* No interrupt aggregation */
2874 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
2875 hba->dev_cmd.type = cmd_type;
2877 return ufshcd_compose_devman_upiu(hba, lrbp);
2881 * Clear all the requests from the controller for which a bit has been set in
2882 * @mask and wait until the controller confirms that these requests have been
2885 static int ufshcd_clear_cmds(struct ufs_hba *hba, u32 mask)
2887 unsigned long flags;
2889 /* clear outstanding transaction before retry */
2890 spin_lock_irqsave(hba->host->host_lock, flags);
2891 ufshcd_utrl_clear(hba, mask);
2892 spin_unlock_irqrestore(hba->host->host_lock, flags);
2895 * wait for h/w to clear corresponding bit in door-bell.
2896 * max. wait is 1 sec.
2898 return ufshcd_wait_for_register(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL,
2899 mask, ~mask, 1000, 1000);
2903 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2905 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2907 /* Get the UPIU response */
2908 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
2909 UPIU_RSP_CODE_OFFSET;
2910 return query_res->response;
2914 * ufshcd_dev_cmd_completion() - handles device management command responses
2915 * @hba: per adapter instance
2916 * @lrbp: pointer to local reference block
2919 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2924 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
2925 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2928 case UPIU_TRANSACTION_NOP_IN:
2929 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
2931 dev_err(hba->dev, "%s: unexpected response %x\n",
2935 case UPIU_TRANSACTION_QUERY_RSP:
2936 err = ufshcd_check_query_response(hba, lrbp);
2938 err = ufshcd_copy_query_response(hba, lrbp);
2940 case UPIU_TRANSACTION_REJECT_UPIU:
2941 /* TODO: handle Reject UPIU Response */
2943 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
2948 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
2956 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
2957 struct ufshcd_lrb *lrbp, int max_timeout)
2959 unsigned long time_left = msecs_to_jiffies(max_timeout);
2960 unsigned long flags;
2965 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
2968 if (likely(time_left)) {
2970 * The completion handler called complete() and the caller of
2971 * this function still owns the @lrbp tag so the code below does
2972 * not trigger any race conditions.
2974 hba->dev_cmd.complete = NULL;
2975 err = ufshcd_get_tr_ocs(lrbp);
2977 err = ufshcd_dev_cmd_completion(hba, lrbp);
2980 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
2981 __func__, lrbp->task_tag);
2982 if (ufshcd_clear_cmds(hba, 1U << lrbp->task_tag) == 0) {
2983 /* successfully cleared the command, retry if needed */
2986 * Since clearing the command succeeded we also need to
2987 * clear the task tag bit from the outstanding_reqs
2990 spin_lock_irqsave(&hba->outstanding_lock, flags);
2991 pending = test_bit(lrbp->task_tag,
2992 &hba->outstanding_reqs);
2994 hba->dev_cmd.complete = NULL;
2995 __clear_bit(lrbp->task_tag,
2996 &hba->outstanding_reqs);
2998 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
3002 * The completion handler ran while we tried to
3003 * clear the command.
3009 dev_err(hba->dev, "%s: failed to clear tag %d\n",
3010 __func__, lrbp->task_tag);
3018 * ufshcd_exec_dev_cmd - API for sending device management requests
3020 * @cmd_type: specifies the type (NOP, Query...)
3021 * @timeout: timeout in milliseconds
3023 * NOTE: Since there is only one available tag for device management commands,
3024 * it is expected you hold the hba->dev_cmd.lock mutex.
3026 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
3027 enum dev_cmd_type cmd_type, int timeout)
3029 DECLARE_COMPLETION_ONSTACK(wait);
3030 const u32 tag = hba->reserved_slot;
3031 struct ufshcd_lrb *lrbp;
3034 /* Protects use of hba->reserved_slot. */
3035 lockdep_assert_held(&hba->dev_cmd.lock);
3037 down_read(&hba->clk_scaling_lock);
3039 lrbp = &hba->lrb[tag];
3041 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
3045 hba->dev_cmd.complete = &wait;
3047 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
3049 ufshcd_send_command(hba, tag);
3050 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
3051 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
3052 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
3055 up_read(&hba->clk_scaling_lock);
3060 * ufshcd_init_query() - init the query response and request parameters
3061 * @hba: per-adapter instance
3062 * @request: address of the request pointer to be initialized
3063 * @response: address of the response pointer to be initialized
3064 * @opcode: operation to perform
3065 * @idn: flag idn to access
3066 * @index: LU number to access
3067 * @selector: query/flag/descriptor further identification
3069 static inline void ufshcd_init_query(struct ufs_hba *hba,
3070 struct ufs_query_req **request, struct ufs_query_res **response,
3071 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
3073 *request = &hba->dev_cmd.query.request;
3074 *response = &hba->dev_cmd.query.response;
3075 memset(*request, 0, sizeof(struct ufs_query_req));
3076 memset(*response, 0, sizeof(struct ufs_query_res));
3077 (*request)->upiu_req.opcode = opcode;
3078 (*request)->upiu_req.idn = idn;
3079 (*request)->upiu_req.index = index;
3080 (*request)->upiu_req.selector = selector;
3083 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
3084 enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res)
3089 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
3090 ret = ufshcd_query_flag(hba, opcode, idn, index, flag_res);
3093 "%s: failed with error %d, retries %d\n",
3094 __func__, ret, retries);
3101 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retries\n",
3102 __func__, opcode, idn, ret, retries);
3107 * ufshcd_query_flag() - API function for sending flag query requests
3108 * @hba: per-adapter instance
3109 * @opcode: flag query to perform
3110 * @idn: flag idn to access
3111 * @index: flag index to access
3112 * @flag_res: the flag value after the query request completes
3114 * Returns 0 for success, non-zero in case of failure
3116 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
3117 enum flag_idn idn, u8 index, bool *flag_res)
3119 struct ufs_query_req *request = NULL;
3120 struct ufs_query_res *response = NULL;
3121 int err, selector = 0;
3122 int timeout = QUERY_REQ_TIMEOUT;
3126 ufshcd_hold(hba, false);
3127 mutex_lock(&hba->dev_cmd.lock);
3128 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3132 case UPIU_QUERY_OPCODE_SET_FLAG:
3133 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
3134 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
3135 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3137 case UPIU_QUERY_OPCODE_READ_FLAG:
3138 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3140 /* No dummy reads */
3141 dev_err(hba->dev, "%s: Invalid argument for read request\n",
3149 "%s: Expected query flag opcode but got = %d\n",
3155 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
3159 "%s: Sending flag query for idn %d failed, err = %d\n",
3160 __func__, idn, err);
3165 *flag_res = (be32_to_cpu(response->upiu_res.value) &
3166 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
3169 mutex_unlock(&hba->dev_cmd.lock);
3170 ufshcd_release(hba);
3175 * ufshcd_query_attr - API function for sending attribute requests
3176 * @hba: per-adapter instance
3177 * @opcode: attribute opcode
3178 * @idn: attribute idn to access
3179 * @index: index field
3180 * @selector: selector field
3181 * @attr_val: the attribute value after the query request completes
3183 * Returns 0 for success, non-zero in case of failure
3185 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
3186 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
3188 struct ufs_query_req *request = NULL;
3189 struct ufs_query_res *response = NULL;
3195 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
3200 ufshcd_hold(hba, false);
3202 mutex_lock(&hba->dev_cmd.lock);
3203 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3207 case UPIU_QUERY_OPCODE_WRITE_ATTR:
3208 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3209 request->upiu_req.value = cpu_to_be32(*attr_val);
3211 case UPIU_QUERY_OPCODE_READ_ATTR:
3212 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3215 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
3221 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3224 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3225 __func__, opcode, idn, index, err);
3229 *attr_val = be32_to_cpu(response->upiu_res.value);
3232 mutex_unlock(&hba->dev_cmd.lock);
3233 ufshcd_release(hba);
3238 * ufshcd_query_attr_retry() - API function for sending query
3239 * attribute with retries
3240 * @hba: per-adapter instance
3241 * @opcode: attribute opcode
3242 * @idn: attribute idn to access
3243 * @index: index field
3244 * @selector: selector field
3245 * @attr_val: the attribute value after the query request
3248 * Returns 0 for success, non-zero in case of failure
3250 int ufshcd_query_attr_retry(struct ufs_hba *hba,
3251 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
3257 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3258 ret = ufshcd_query_attr(hba, opcode, idn, index,
3259 selector, attr_val);
3261 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
3262 __func__, ret, retries);
3269 "%s: query attribute, idn %d, failed with error %d after %d retries\n",
3270 __func__, idn, ret, QUERY_REQ_RETRIES);
3274 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
3275 enum query_opcode opcode, enum desc_idn idn, u8 index,
3276 u8 selector, u8 *desc_buf, int *buf_len)
3278 struct ufs_query_req *request = NULL;
3279 struct ufs_query_res *response = NULL;
3285 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
3290 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
3291 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
3292 __func__, *buf_len);
3296 ufshcd_hold(hba, false);
3298 mutex_lock(&hba->dev_cmd.lock);
3299 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3301 hba->dev_cmd.query.descriptor = desc_buf;
3302 request->upiu_req.length = cpu_to_be16(*buf_len);
3305 case UPIU_QUERY_OPCODE_WRITE_DESC:
3306 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3308 case UPIU_QUERY_OPCODE_READ_DESC:
3309 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3313 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
3319 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3322 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3323 __func__, opcode, idn, index, err);
3327 *buf_len = be16_to_cpu(response->upiu_res.length);
3330 hba->dev_cmd.query.descriptor = NULL;
3331 mutex_unlock(&hba->dev_cmd.lock);
3332 ufshcd_release(hba);
3337 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3338 * @hba: per-adapter instance
3339 * @opcode: attribute opcode
3340 * @idn: attribute idn to access
3341 * @index: index field
3342 * @selector: selector field
3343 * @desc_buf: the buffer that contains the descriptor
3344 * @buf_len: length parameter passed to the device
3346 * Returns 0 for success, non-zero in case of failure.
3347 * The buf_len parameter will contain, on return, the length parameter
3348 * received on the response.
3350 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3351 enum query_opcode opcode,
3352 enum desc_idn idn, u8 index,
3354 u8 *desc_buf, int *buf_len)
3359 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3360 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3361 selector, desc_buf, buf_len);
3362 if (!err || err == -EINVAL)
3370 * ufshcd_map_desc_id_to_length - map descriptor IDN to its length
3371 * @hba: Pointer to adapter instance
3372 * @desc_id: descriptor idn value
3373 * @desc_len: mapped desc length (out)
3375 void ufshcd_map_desc_id_to_length(struct ufs_hba *hba, enum desc_idn desc_id,
3378 if (desc_id >= QUERY_DESC_IDN_MAX || desc_id == QUERY_DESC_IDN_RFU_0 ||
3379 desc_id == QUERY_DESC_IDN_RFU_1)
3382 *desc_len = hba->desc_size[desc_id];
3384 EXPORT_SYMBOL(ufshcd_map_desc_id_to_length);
3386 static void ufshcd_update_desc_length(struct ufs_hba *hba,
3387 enum desc_idn desc_id, int desc_index,
3388 unsigned char desc_len)
3390 if (hba->desc_size[desc_id] == QUERY_DESC_MAX_SIZE &&
3391 desc_id != QUERY_DESC_IDN_STRING && desc_index != UFS_RPMB_UNIT)
3392 /* For UFS 3.1, the normal unit descriptor is 10 bytes larger
3393 * than the RPMB unit, however, both descriptors share the same
3394 * desc_idn, to cover both unit descriptors with one length, we
3395 * choose the normal unit descriptor length by desc_index.
3397 hba->desc_size[desc_id] = desc_len;
3401 * ufshcd_read_desc_param - read the specified descriptor parameter
3402 * @hba: Pointer to adapter instance
3403 * @desc_id: descriptor idn value
3404 * @desc_index: descriptor index
3405 * @param_offset: offset of the parameter to read
3406 * @param_read_buf: pointer to buffer where parameter would be read
3407 * @param_size: sizeof(param_read_buf)
3409 * Return 0 in case of success, non-zero otherwise
3411 int ufshcd_read_desc_param(struct ufs_hba *hba,
3412 enum desc_idn desc_id,
3421 bool is_kmalloc = true;
3424 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3427 /* Get the length of descriptor */
3428 ufshcd_map_desc_id_to_length(hba, desc_id, &buff_len);
3430 dev_err(hba->dev, "%s: Failed to get desc length\n", __func__);
3434 if (param_offset >= buff_len) {
3435 dev_err(hba->dev, "%s: Invalid offset 0x%x in descriptor IDN 0x%x, length 0x%x\n",
3436 __func__, param_offset, desc_id, buff_len);
3440 /* Check whether we need temp memory */
3441 if (param_offset != 0 || param_size < buff_len) {
3442 desc_buf = kzalloc(buff_len, GFP_KERNEL);
3446 desc_buf = param_read_buf;
3450 /* Request for full descriptor */
3451 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3452 desc_id, desc_index, 0,
3453 desc_buf, &buff_len);
3456 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d\n",
3457 __func__, desc_id, desc_index, param_offset, ret);
3462 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3463 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header\n",
3464 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3469 /* Update descriptor length */
3470 buff_len = desc_buf[QUERY_DESC_LENGTH_OFFSET];
3471 ufshcd_update_desc_length(hba, desc_id, desc_index, buff_len);
3474 /* Make sure we don't copy more data than available */
3475 if (param_offset >= buff_len)
3478 memcpy(param_read_buf, &desc_buf[param_offset],
3479 min_t(u32, param_size, buff_len - param_offset));
3488 * struct uc_string_id - unicode string
3490 * @len: size of this descriptor inclusive
3491 * @type: descriptor type
3492 * @uc: unicode string character
3494 struct uc_string_id {
3500 /* replace non-printable or non-ASCII characters with spaces */
3501 static inline char ufshcd_remove_non_printable(u8 ch)
3503 return (ch >= 0x20 && ch <= 0x7e) ? ch : ' ';
3507 * ufshcd_read_string_desc - read string descriptor
3508 * @hba: pointer to adapter instance
3509 * @desc_index: descriptor index
3510 * @buf: pointer to buffer where descriptor would be read,
3511 * the caller should free the memory.
3512 * @ascii: if true convert from unicode to ascii characters
3513 * null terminated string.
3516 * * string size on success.
3517 * * -ENOMEM: on allocation failure
3518 * * -EINVAL: on a wrong parameter
3520 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index,
3521 u8 **buf, bool ascii)
3523 struct uc_string_id *uc_str;
3530 uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
3534 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_STRING, desc_index, 0,
3535 (u8 *)uc_str, QUERY_DESC_MAX_SIZE);
3537 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n",
3538 QUERY_REQ_RETRIES, ret);
3543 if (uc_str->len <= QUERY_DESC_HDR_SIZE) {
3544 dev_dbg(hba->dev, "String Desc is of zero length\n");
3553 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3554 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3555 str = kzalloc(ascii_len, GFP_KERNEL);
3562 * the descriptor contains string in UTF16 format
3563 * we need to convert to utf-8 so it can be displayed
3565 ret = utf16s_to_utf8s(uc_str->uc,
3566 uc_str->len - QUERY_DESC_HDR_SIZE,
3567 UTF16_BIG_ENDIAN, str, ascii_len);
3569 /* replace non-printable or non-ASCII characters with spaces */
3570 for (i = 0; i < ret; i++)
3571 str[i] = ufshcd_remove_non_printable(str[i]);
3576 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL);
3590 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3591 * @hba: Pointer to adapter instance
3593 * @param_offset: offset of the parameter to read
3594 * @param_read_buf: pointer to buffer where parameter would be read
3595 * @param_size: sizeof(param_read_buf)
3597 * Return 0 in case of success, non-zero otherwise
3599 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3601 enum unit_desc_param param_offset,
3606 * Unit descriptors are only available for general purpose LUs (LUN id
3607 * from 0 to 7) and RPMB Well known LU.
3609 if (!ufs_is_valid_unit_desc_lun(&hba->dev_info, lun, param_offset))
3612 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3613 param_offset, param_read_buf, param_size);
3616 static int ufshcd_get_ref_clk_gating_wait(struct ufs_hba *hba)
3619 u32 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3621 if (hba->dev_info.wspecversion >= 0x300) {
3622 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3623 QUERY_ATTR_IDN_REF_CLK_GATING_WAIT_TIME, 0, 0,
3626 dev_err(hba->dev, "Failed reading bRefClkGatingWait. err = %d, use default %uus\n",
3629 if (gating_wait == 0) {
3630 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3631 dev_err(hba->dev, "Undefined ref clk gating wait time, use default %uus\n",
3635 hba->dev_info.clk_gating_wait_us = gating_wait;
3642 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3643 * @hba: per adapter instance
3645 * 1. Allocate DMA memory for Command Descriptor array
3646 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3647 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3648 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3650 * 4. Allocate memory for local reference block(lrb).
3652 * Returns 0 for success, non-zero in case of failure
3654 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3656 size_t utmrdl_size, utrdl_size, ucdl_size;
3658 /* Allocate memory for UTP command descriptors */
3659 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3660 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3662 &hba->ucdl_dma_addr,
3666 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3667 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3668 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3669 * be aligned to 128 bytes as well
3671 if (!hba->ucdl_base_addr ||
3672 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3674 "Command Descriptor Memory allocation failed\n");
3679 * Allocate memory for UTP Transfer descriptors
3680 * UFSHCI requires 1024 byte alignment of UTRD
3682 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3683 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3685 &hba->utrdl_dma_addr,
3687 if (!hba->utrdl_base_addr ||
3688 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3690 "Transfer Descriptor Memory allocation failed\n");
3695 * Allocate memory for UTP Task Management descriptors
3696 * UFSHCI requires 1024 byte alignment of UTMRD
3698 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3699 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3701 &hba->utmrdl_dma_addr,
3703 if (!hba->utmrdl_base_addr ||
3704 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3706 "Task Management Descriptor Memory allocation failed\n");
3710 /* Allocate memory for local reference block */
3711 hba->lrb = devm_kcalloc(hba->dev,
3712 hba->nutrs, sizeof(struct ufshcd_lrb),
3715 dev_err(hba->dev, "LRB Memory allocation failed\n");
3724 * ufshcd_host_memory_configure - configure local reference block with
3726 * @hba: per adapter instance
3728 * Configure Host memory space
3729 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3731 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3733 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3734 * into local reference block.
3736 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3738 struct utp_transfer_req_desc *utrdlp;
3739 dma_addr_t cmd_desc_dma_addr;
3740 dma_addr_t cmd_desc_element_addr;
3741 u16 response_offset;
3746 utrdlp = hba->utrdl_base_addr;
3749 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3751 offsetof(struct utp_transfer_cmd_desc, prd_table);
3753 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
3754 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3756 for (i = 0; i < hba->nutrs; i++) {
3757 /* Configure UTRD with command descriptor base address */
3758 cmd_desc_element_addr =
3759 (cmd_desc_dma_addr + (cmd_desc_size * i));
3760 utrdlp[i].command_desc_base_addr_lo =
3761 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3762 utrdlp[i].command_desc_base_addr_hi =
3763 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3765 /* Response upiu and prdt offset should be in double words */
3766 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3767 utrdlp[i].response_upiu_offset =
3768 cpu_to_le16(response_offset);
3769 utrdlp[i].prd_table_offset =
3770 cpu_to_le16(prdt_offset);
3771 utrdlp[i].response_upiu_length =
3772 cpu_to_le16(ALIGNED_UPIU_SIZE);
3774 utrdlp[i].response_upiu_offset =
3775 cpu_to_le16(response_offset >> 2);
3776 utrdlp[i].prd_table_offset =
3777 cpu_to_le16(prdt_offset >> 2);
3778 utrdlp[i].response_upiu_length =
3779 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3782 ufshcd_init_lrb(hba, &hba->lrb[i], i);
3787 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3788 * @hba: per adapter instance
3790 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3791 * in order to initialize the Unipro link startup procedure.
3792 * Once the Unipro links are up, the device connected to the controller
3795 * Returns 0 on success, non-zero value on failure
3797 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3799 struct uic_command uic_cmd = {0};
3802 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3804 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3807 "dme-link-startup: error code %d\n", ret);
3811 * ufshcd_dme_reset - UIC command for DME_RESET
3812 * @hba: per adapter instance
3814 * DME_RESET command is issued in order to reset UniPro stack.
3815 * This function now deals with cold reset.
3817 * Returns 0 on success, non-zero value on failure
3819 static int ufshcd_dme_reset(struct ufs_hba *hba)
3821 struct uic_command uic_cmd = {0};
3824 uic_cmd.command = UIC_CMD_DME_RESET;
3826 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3829 "dme-reset: error code %d\n", ret);
3834 int ufshcd_dme_configure_adapt(struct ufs_hba *hba,
3840 if (agreed_gear < UFS_HS_G4)
3841 adapt_val = PA_NO_ADAPT;
3843 ret = ufshcd_dme_set(hba,
3844 UIC_ARG_MIB(PA_TXHSADAPTTYPE),
3848 EXPORT_SYMBOL_GPL(ufshcd_dme_configure_adapt);
3851 * ufshcd_dme_enable - UIC command for DME_ENABLE
3852 * @hba: per adapter instance
3854 * DME_ENABLE command is issued in order to enable UniPro stack.
3856 * Returns 0 on success, non-zero value on failure
3858 static int ufshcd_dme_enable(struct ufs_hba *hba)
3860 struct uic_command uic_cmd = {0};
3863 uic_cmd.command = UIC_CMD_DME_ENABLE;
3865 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3868 "dme-enable: error code %d\n", ret);
3873 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3875 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3876 unsigned long min_sleep_time_us;
3878 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3882 * last_dme_cmd_tstamp will be 0 only for 1st call to
3885 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3886 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3888 unsigned long delta =
3889 (unsigned long) ktime_to_us(
3890 ktime_sub(ktime_get(),
3891 hba->last_dme_cmd_tstamp));
3893 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3895 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3897 return; /* no more delay required */
3900 /* allow sleep for extra 50us if needed */
3901 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3905 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3906 * @hba: per adapter instance
3907 * @attr_sel: uic command argument1
3908 * @attr_set: attribute set type as uic command argument2
3909 * @mib_val: setting value as uic command argument3
3910 * @peer: indicate whether peer or local
3912 * Returns 0 on success, non-zero value on failure
3914 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3915 u8 attr_set, u32 mib_val, u8 peer)
3917 struct uic_command uic_cmd = {0};
3918 static const char *const action[] = {
3922 const char *set = action[!!peer];
3924 int retries = UFS_UIC_COMMAND_RETRIES;
3926 uic_cmd.command = peer ?
3927 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3928 uic_cmd.argument1 = attr_sel;
3929 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3930 uic_cmd.argument3 = mib_val;
3933 /* for peer attributes we retry upon failure */
3934 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3936 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
3937 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
3938 } while (ret && peer && --retries);
3941 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
3942 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
3943 UFS_UIC_COMMAND_RETRIES - retries);
3947 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
3950 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
3951 * @hba: per adapter instance
3952 * @attr_sel: uic command argument1
3953 * @mib_val: the value of the attribute as returned by the UIC command
3954 * @peer: indicate whether peer or local
3956 * Returns 0 on success, non-zero value on failure
3958 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
3959 u32 *mib_val, u8 peer)
3961 struct uic_command uic_cmd = {0};
3962 static const char *const action[] = {
3966 const char *get = action[!!peer];
3968 int retries = UFS_UIC_COMMAND_RETRIES;
3969 struct ufs_pa_layer_attr orig_pwr_info;
3970 struct ufs_pa_layer_attr temp_pwr_info;
3971 bool pwr_mode_change = false;
3973 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
3974 orig_pwr_info = hba->pwr_info;
3975 temp_pwr_info = orig_pwr_info;
3977 if (orig_pwr_info.pwr_tx == FAST_MODE ||
3978 orig_pwr_info.pwr_rx == FAST_MODE) {
3979 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
3980 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
3981 pwr_mode_change = true;
3982 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
3983 orig_pwr_info.pwr_rx == SLOW_MODE) {
3984 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
3985 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
3986 pwr_mode_change = true;
3988 if (pwr_mode_change) {
3989 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
3995 uic_cmd.command = peer ?
3996 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
3997 uic_cmd.argument1 = attr_sel;
4000 /* for peer attributes we retry upon failure */
4001 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
4003 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
4004 get, UIC_GET_ATTR_ID(attr_sel), ret);
4005 } while (ret && peer && --retries);
4008 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
4009 get, UIC_GET_ATTR_ID(attr_sel),
4010 UFS_UIC_COMMAND_RETRIES - retries);
4012 if (mib_val && !ret)
4013 *mib_val = uic_cmd.argument3;
4015 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
4017 ufshcd_change_power_mode(hba, &orig_pwr_info);
4021 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
4024 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
4025 * state) and waits for it to take effect.
4027 * @hba: per adapter instance
4028 * @cmd: UIC command to execute
4030 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
4031 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
4032 * and device UniPro link and hence it's final completion would be indicated by
4033 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
4034 * addition to normal UIC command completion Status (UCCS). This function only
4035 * returns after the relevant status bits indicate the completion.
4037 * Returns 0 on success, non-zero value on failure
4039 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
4041 DECLARE_COMPLETION_ONSTACK(uic_async_done);
4042 unsigned long flags;
4045 bool reenable_intr = false;
4047 mutex_lock(&hba->uic_cmd_mutex);
4048 ufshcd_add_delay_before_dme_cmd(hba);
4050 spin_lock_irqsave(hba->host->host_lock, flags);
4051 if (ufshcd_is_link_broken(hba)) {
4055 hba->uic_async_done = &uic_async_done;
4056 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
4057 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
4059 * Make sure UIC command completion interrupt is disabled before
4060 * issuing UIC command.
4063 reenable_intr = true;
4065 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
4066 spin_unlock_irqrestore(hba->host->host_lock, flags);
4069 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
4070 cmd->command, cmd->argument3, ret);
4074 if (!wait_for_completion_timeout(hba->uic_async_done,
4075 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
4077 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
4078 cmd->command, cmd->argument3);
4080 if (!cmd->cmd_active) {
4081 dev_err(hba->dev, "%s: Power Mode Change operation has been completed, go check UPMCRS\n",
4091 status = ufshcd_get_upmcrs(hba);
4092 if (status != PWR_LOCAL) {
4094 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
4095 cmd->command, status);
4096 ret = (status != PWR_OK) ? status : -1;
4100 ufshcd_print_host_state(hba);
4101 ufshcd_print_pwr_info(hba);
4102 ufshcd_print_evt_hist(hba);
4105 spin_lock_irqsave(hba->host->host_lock, flags);
4106 hba->active_uic_cmd = NULL;
4107 hba->uic_async_done = NULL;
4109 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
4111 ufshcd_set_link_broken(hba);
4112 ufshcd_schedule_eh_work(hba);
4115 spin_unlock_irqrestore(hba->host->host_lock, flags);
4116 mutex_unlock(&hba->uic_cmd_mutex);
4122 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
4123 * using DME_SET primitives.
4124 * @hba: per adapter instance
4125 * @mode: powr mode value
4127 * Returns 0 on success, non-zero value on failure
4129 int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
4131 struct uic_command uic_cmd = {0};
4134 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
4135 ret = ufshcd_dme_set(hba,
4136 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
4138 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
4144 uic_cmd.command = UIC_CMD_DME_SET;
4145 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
4146 uic_cmd.argument3 = mode;
4147 ufshcd_hold(hba, false);
4148 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4149 ufshcd_release(hba);
4154 EXPORT_SYMBOL_GPL(ufshcd_uic_change_pwr_mode);
4156 int ufshcd_link_recovery(struct ufs_hba *hba)
4159 unsigned long flags;
4161 spin_lock_irqsave(hba->host->host_lock, flags);
4162 hba->ufshcd_state = UFSHCD_STATE_RESET;
4163 ufshcd_set_eh_in_progress(hba);
4164 spin_unlock_irqrestore(hba->host->host_lock, flags);
4166 /* Reset the attached device */
4167 ufshcd_device_reset(hba);
4169 ret = ufshcd_host_reset_and_restore(hba);
4171 spin_lock_irqsave(hba->host->host_lock, flags);
4173 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4174 ufshcd_clear_eh_in_progress(hba);
4175 spin_unlock_irqrestore(hba->host->host_lock, flags);
4178 dev_err(hba->dev, "%s: link recovery failed, err %d",
4183 EXPORT_SYMBOL_GPL(ufshcd_link_recovery);
4185 int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
4188 struct uic_command uic_cmd = {0};
4189 ktime_t start = ktime_get();
4191 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
4193 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
4194 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4195 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
4196 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4199 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
4202 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
4207 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_enter);
4209 int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
4211 struct uic_command uic_cmd = {0};
4213 ktime_t start = ktime_get();
4215 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
4217 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
4218 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4219 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
4220 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4223 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
4226 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
4228 hba->ufs_stats.last_hibern8_exit_tstamp = local_clock();
4229 hba->ufs_stats.hibern8_exit_cnt++;
4234 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_exit);
4236 void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit)
4238 unsigned long flags;
4239 bool update = false;
4241 if (!ufshcd_is_auto_hibern8_supported(hba))
4244 spin_lock_irqsave(hba->host->host_lock, flags);
4245 if (hba->ahit != ahit) {
4249 spin_unlock_irqrestore(hba->host->host_lock, flags);
4252 !pm_runtime_suspended(&hba->ufs_device_wlun->sdev_gendev)) {
4253 ufshcd_rpm_get_sync(hba);
4254 ufshcd_hold(hba, false);
4255 ufshcd_auto_hibern8_enable(hba);
4256 ufshcd_release(hba);
4257 ufshcd_rpm_put_sync(hba);
4260 EXPORT_SYMBOL_GPL(ufshcd_auto_hibern8_update);
4262 void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
4264 if (!ufshcd_is_auto_hibern8_supported(hba))
4267 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
4271 * ufshcd_init_pwr_info - setting the POR (power on reset)
4272 * values in hba power info
4273 * @hba: per-adapter instance
4275 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
4277 hba->pwr_info.gear_rx = UFS_PWM_G1;
4278 hba->pwr_info.gear_tx = UFS_PWM_G1;
4279 hba->pwr_info.lane_rx = 1;
4280 hba->pwr_info.lane_tx = 1;
4281 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
4282 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
4283 hba->pwr_info.hs_rate = 0;
4287 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
4288 * @hba: per-adapter instance
4290 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
4292 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
4294 if (hba->max_pwr_info.is_valid)
4297 if (hba->quirks & UFSHCD_QUIRK_HIBERN_FASTAUTO) {
4298 pwr_info->pwr_tx = FASTAUTO_MODE;
4299 pwr_info->pwr_rx = FASTAUTO_MODE;
4301 pwr_info->pwr_tx = FAST_MODE;
4302 pwr_info->pwr_rx = FAST_MODE;
4304 pwr_info->hs_rate = PA_HS_MODE_B;
4306 /* Get the connected lane count */
4307 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
4308 &pwr_info->lane_rx);
4309 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4310 &pwr_info->lane_tx);
4312 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
4313 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4321 * First, get the maximum gears of HS speed.
4322 * If a zero value, it means there is no HSGEAR capability.
4323 * Then, get the maximum gears of PWM speed.
4325 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4326 if (!pwr_info->gear_rx) {
4327 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4328 &pwr_info->gear_rx);
4329 if (!pwr_info->gear_rx) {
4330 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4331 __func__, pwr_info->gear_rx);
4334 pwr_info->pwr_rx = SLOW_MODE;
4337 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4338 &pwr_info->gear_tx);
4339 if (!pwr_info->gear_tx) {
4340 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4341 &pwr_info->gear_tx);
4342 if (!pwr_info->gear_tx) {
4343 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4344 __func__, pwr_info->gear_tx);
4347 pwr_info->pwr_tx = SLOW_MODE;
4350 hba->max_pwr_info.is_valid = true;
4354 static int ufshcd_change_power_mode(struct ufs_hba *hba,
4355 struct ufs_pa_layer_attr *pwr_mode)
4359 /* if already configured to the requested pwr_mode */
4360 if (!hba->force_pmc &&
4361 pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4362 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4363 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4364 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4365 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4366 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4367 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4368 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4373 * Configure attributes for power mode change with below.
4374 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4375 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4378 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4379 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4381 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4382 pwr_mode->pwr_rx == FAST_MODE)
4383 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), true);
4385 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), false);
4387 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4388 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4390 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4391 pwr_mode->pwr_tx == FAST_MODE)
4392 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), true);
4394 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), false);
4396 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4397 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4398 pwr_mode->pwr_rx == FAST_MODE ||
4399 pwr_mode->pwr_tx == FAST_MODE)
4400 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4403 if (!(hba->quirks & UFSHCD_QUIRK_SKIP_DEF_UNIPRO_TIMEOUT_SETTING)) {
4404 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0),
4405 DL_FC0ProtectionTimeOutVal_Default);
4406 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1),
4407 DL_TC0ReplayTimeOutVal_Default);
4408 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2),
4409 DL_AFC0ReqTimeOutVal_Default);
4410 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA3),
4411 DL_FC1ProtectionTimeOutVal_Default);
4412 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA4),
4413 DL_TC1ReplayTimeOutVal_Default);
4414 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA5),
4415 DL_AFC1ReqTimeOutVal_Default);
4417 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal),
4418 DL_FC0ProtectionTimeOutVal_Default);
4419 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal),
4420 DL_TC0ReplayTimeOutVal_Default);
4421 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal),
4422 DL_AFC0ReqTimeOutVal_Default);
4425 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4426 | pwr_mode->pwr_tx);
4430 "%s: power mode change failed %d\n", __func__, ret);
4432 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4435 memcpy(&hba->pwr_info, pwr_mode,
4436 sizeof(struct ufs_pa_layer_attr));
4443 * ufshcd_config_pwr_mode - configure a new power mode
4444 * @hba: per-adapter instance
4445 * @desired_pwr_mode: desired power configuration
4447 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4448 struct ufs_pa_layer_attr *desired_pwr_mode)
4450 struct ufs_pa_layer_attr final_params = { 0 };
4453 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4454 desired_pwr_mode, &final_params);
4457 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4459 ret = ufshcd_change_power_mode(hba, &final_params);
4463 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4466 * ufshcd_complete_dev_init() - checks device readiness
4467 * @hba: per-adapter instance
4469 * Set fDeviceInit flag and poll until device toggles it.
4471 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4474 bool flag_res = true;
4477 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4478 QUERY_FLAG_IDN_FDEVICEINIT, 0, NULL);
4481 "%s setting fDeviceInit flag failed with error %d\n",
4486 /* Poll fDeviceInit flag to be cleared */
4487 timeout = ktime_add_ms(ktime_get(), FDEVICEINIT_COMPL_TIMEOUT);
4489 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4490 QUERY_FLAG_IDN_FDEVICEINIT, 0, &flag_res);
4493 usleep_range(500, 1000);
4494 } while (ktime_before(ktime_get(), timeout));
4498 "%s reading fDeviceInit flag failed with error %d\n",
4500 } else if (flag_res) {
4502 "%s fDeviceInit was not cleared by the device\n",
4511 * ufshcd_make_hba_operational - Make UFS controller operational
4512 * @hba: per adapter instance
4514 * To bring UFS host controller to operational state,
4515 * 1. Enable required interrupts
4516 * 2. Configure interrupt aggregation
4517 * 3. Program UTRL and UTMRL base address
4518 * 4. Configure run-stop-registers
4520 * Returns 0 on success, non-zero value on failure
4522 int ufshcd_make_hba_operational(struct ufs_hba *hba)
4527 /* Enable required interrupts */
4528 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4530 /* Configure interrupt aggregation */
4531 if (ufshcd_is_intr_aggr_allowed(hba))
4532 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4534 ufshcd_disable_intr_aggr(hba);
4536 /* Configure UTRL and UTMRL base address registers */
4537 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4538 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4539 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4540 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4541 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4542 REG_UTP_TASK_REQ_LIST_BASE_L);
4543 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4544 REG_UTP_TASK_REQ_LIST_BASE_H);
4547 * Make sure base address and interrupt setup are updated before
4548 * enabling the run/stop registers below.
4553 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4555 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4556 if (!(ufshcd_get_lists_status(reg))) {
4557 ufshcd_enable_run_stop_reg(hba);
4560 "Host controller not ready to process requests");
4566 EXPORT_SYMBOL_GPL(ufshcd_make_hba_operational);
4569 * ufshcd_hba_stop - Send controller to reset state
4570 * @hba: per adapter instance
4572 void ufshcd_hba_stop(struct ufs_hba *hba)
4574 unsigned long flags;
4578 * Obtain the host lock to prevent that the controller is disabled
4579 * while the UFS interrupt handler is active on another CPU.
4581 spin_lock_irqsave(hba->host->host_lock, flags);
4582 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4583 spin_unlock_irqrestore(hba->host->host_lock, flags);
4585 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4586 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4589 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4591 EXPORT_SYMBOL_GPL(ufshcd_hba_stop);
4594 * ufshcd_hba_execute_hce - initialize the controller
4595 * @hba: per adapter instance
4597 * The controller resets itself and controller firmware initialization
4598 * sequence kicks off. When controller is ready it will set
4599 * the Host Controller Enable bit to 1.
4601 * Returns 0 on success, non-zero value on failure
4603 static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
4605 int retry_outer = 3;
4609 if (ufshcd_is_hba_active(hba))
4610 /* change controller state to "reset state" */
4611 ufshcd_hba_stop(hba);
4613 /* UniPro link is disabled at this point */
4614 ufshcd_set_link_off(hba);
4616 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4618 /* start controller initialization sequence */
4619 ufshcd_hba_start(hba);
4622 * To initialize a UFS host controller HCE bit must be set to 1.
4623 * During initialization the HCE bit value changes from 1->0->1.
4624 * When the host controller completes initialization sequence
4625 * it sets the value of HCE bit to 1. The same HCE bit is read back
4626 * to check if the controller has completed initialization sequence.
4627 * So without this delay the value HCE = 1, set in the previous
4628 * instruction might be read back.
4629 * This delay can be changed based on the controller.
4631 ufshcd_delay_us(hba->vps->hba_enable_delay_us, 100);
4633 /* wait for the host controller to complete initialization */
4635 while (!ufshcd_is_hba_active(hba)) {
4640 "Controller enable failed\n");
4647 usleep_range(1000, 1100);
4650 /* enable UIC related interrupts */
4651 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4653 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4658 int ufshcd_hba_enable(struct ufs_hba *hba)
4662 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
4663 ufshcd_set_link_off(hba);
4664 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4666 /* enable UIC related interrupts */
4667 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4668 ret = ufshcd_dme_reset(hba);
4670 ret = ufshcd_dme_enable(hba);
4672 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4675 "Host controller enable failed with non-hce\n");
4678 ret = ufshcd_hba_execute_hce(hba);
4683 EXPORT_SYMBOL_GPL(ufshcd_hba_enable);
4685 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4687 int tx_lanes = 0, i, err = 0;
4690 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4693 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4695 for (i = 0; i < tx_lanes; i++) {
4697 err = ufshcd_dme_set(hba,
4698 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4699 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4702 err = ufshcd_dme_peer_set(hba,
4703 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4704 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4707 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4708 __func__, peer, i, err);
4716 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4718 return ufshcd_disable_tx_lcc(hba, true);
4721 void ufshcd_update_evt_hist(struct ufs_hba *hba, u32 id, u32 val)
4723 struct ufs_event_hist *e;
4725 if (id >= UFS_EVT_CNT)
4728 e = &hba->ufs_stats.event[id];
4729 e->val[e->pos] = val;
4730 e->tstamp[e->pos] = local_clock();
4732 e->pos = (e->pos + 1) % UFS_EVENT_HIST_LENGTH;
4734 ufshcd_vops_event_notify(hba, id, &val);
4736 EXPORT_SYMBOL_GPL(ufshcd_update_evt_hist);
4739 * ufshcd_link_startup - Initialize unipro link startup
4740 * @hba: per adapter instance
4742 * Returns 0 for success, non-zero in case of failure
4744 static int ufshcd_link_startup(struct ufs_hba *hba)
4747 int retries = DME_LINKSTARTUP_RETRIES;
4748 bool link_startup_again = false;
4751 * If UFS device isn't active then we will have to issue link startup
4752 * 2 times to make sure the device state move to active.
4754 if (!ufshcd_is_ufs_dev_active(hba))
4755 link_startup_again = true;
4759 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4761 ret = ufshcd_dme_link_startup(hba);
4763 /* check if device is detected by inter-connect layer */
4764 if (!ret && !ufshcd_is_device_present(hba)) {
4765 ufshcd_update_evt_hist(hba,
4766 UFS_EVT_LINK_STARTUP_FAIL,
4768 dev_err(hba->dev, "%s: Device not present\n", __func__);
4774 * DME link lost indication is only received when link is up,
4775 * but we can't be sure if the link is up until link startup
4776 * succeeds. So reset the local Uni-Pro and try again.
4778 if (ret && retries && ufshcd_hba_enable(hba)) {
4779 ufshcd_update_evt_hist(hba,
4780 UFS_EVT_LINK_STARTUP_FAIL,
4784 } while (ret && retries--);
4787 /* failed to get the link up... retire */
4788 ufshcd_update_evt_hist(hba,
4789 UFS_EVT_LINK_STARTUP_FAIL,
4794 if (link_startup_again) {
4795 link_startup_again = false;
4796 retries = DME_LINKSTARTUP_RETRIES;
4800 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4801 ufshcd_init_pwr_info(hba);
4802 ufshcd_print_pwr_info(hba);
4804 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4805 ret = ufshcd_disable_device_tx_lcc(hba);
4810 /* Include any host controller configuration via UIC commands */
4811 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4815 /* Clear UECPA once due to LINERESET has happened during LINK_STARTUP */
4816 ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
4817 ret = ufshcd_make_hba_operational(hba);
4820 dev_err(hba->dev, "link startup failed %d\n", ret);
4821 ufshcd_print_host_state(hba);
4822 ufshcd_print_pwr_info(hba);
4823 ufshcd_print_evt_hist(hba);
4829 * ufshcd_verify_dev_init() - Verify device initialization
4830 * @hba: per-adapter instance
4832 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4833 * device Transport Protocol (UTP) layer is ready after a reset.
4834 * If the UTP layer at the device side is not initialized, it may
4835 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4836 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4838 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4843 ufshcd_hold(hba, false);
4844 mutex_lock(&hba->dev_cmd.lock);
4845 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4846 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4847 hba->nop_out_timeout);
4849 if (!err || err == -ETIMEDOUT)
4852 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4854 mutex_unlock(&hba->dev_cmd.lock);
4855 ufshcd_release(hba);
4858 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4863 * ufshcd_set_queue_depth - set lun queue depth
4864 * @sdev: pointer to SCSI device
4866 * Read bLUQueueDepth value and activate scsi tagged command
4867 * queueing. For WLUN, queue depth is set to 1. For best-effort
4868 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
4869 * value that host can queue.
4871 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
4875 struct ufs_hba *hba;
4877 hba = shost_priv(sdev->host);
4879 lun_qdepth = hba->nutrs;
4880 ret = ufshcd_read_unit_desc_param(hba,
4881 ufshcd_scsi_to_upiu_lun(sdev->lun),
4882 UNIT_DESC_PARAM_LU_Q_DEPTH,
4884 sizeof(lun_qdepth));
4886 /* Some WLUN doesn't support unit descriptor */
4887 if (ret == -EOPNOTSUPP)
4889 else if (!lun_qdepth)
4890 /* eventually, we can figure out the real queue depth */
4891 lun_qdepth = hba->nutrs;
4893 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
4895 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
4896 __func__, lun_qdepth);
4897 scsi_change_queue_depth(sdev, lun_qdepth);
4901 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
4902 * @hba: per-adapter instance
4903 * @lun: UFS device lun id
4904 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
4906 * Returns 0 in case of success and b_lu_write_protect status would be returned
4907 * @b_lu_write_protect parameter.
4908 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
4909 * Returns -EINVAL in case of invalid parameters passed to this function.
4911 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
4913 u8 *b_lu_write_protect)
4917 if (!b_lu_write_protect)
4920 * According to UFS device spec, RPMB LU can't be write
4921 * protected so skip reading bLUWriteProtect parameter for
4922 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
4924 else if (lun >= hba->dev_info.max_lu_supported)
4927 ret = ufshcd_read_unit_desc_param(hba,
4929 UNIT_DESC_PARAM_LU_WR_PROTECT,
4931 sizeof(*b_lu_write_protect));
4936 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
4938 * @hba: per-adapter instance
4939 * @sdev: pointer to SCSI device
4942 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
4943 const struct scsi_device *sdev)
4945 if (hba->dev_info.f_power_on_wp_en &&
4946 !hba->dev_info.is_lu_power_on_wp) {
4947 u8 b_lu_write_protect;
4949 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
4950 &b_lu_write_protect) &&
4951 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
4952 hba->dev_info.is_lu_power_on_wp = true;
4957 * ufshcd_setup_links - associate link b/w device wlun and other luns
4958 * @sdev: pointer to SCSI device
4959 * @hba: pointer to ufs hba
4961 static void ufshcd_setup_links(struct ufs_hba *hba, struct scsi_device *sdev)
4963 struct device_link *link;
4966 * Device wlun is the supplier & rest of the luns are consumers.
4967 * This ensures that device wlun suspends after all other luns.
4969 if (hba->ufs_device_wlun) {
4970 link = device_link_add(&sdev->sdev_gendev,
4971 &hba->ufs_device_wlun->sdev_gendev,
4972 DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE);
4974 dev_err(&sdev->sdev_gendev, "Failed establishing link - %s\n",
4975 dev_name(&hba->ufs_device_wlun->sdev_gendev));
4979 /* Ignore REPORT_LUN wlun probing */
4980 if (hba->luns_avail == 1) {
4981 ufshcd_rpm_put(hba);
4986 * Device wlun is probed. The assumption is that WLUNs are
4987 * scanned before other LUNs.
4994 * ufshcd_slave_alloc - handle initial SCSI device configurations
4995 * @sdev: pointer to SCSI device
4999 static int ufshcd_slave_alloc(struct scsi_device *sdev)
5001 struct ufs_hba *hba;
5003 hba = shost_priv(sdev->host);
5005 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
5006 sdev->use_10_for_ms = 1;
5008 /* DBD field should be set to 1 in mode sense(10) */
5009 sdev->set_dbd_for_ms = 1;
5011 /* allow SCSI layer to restart the device in case of errors */
5012 sdev->allow_restart = 1;
5014 /* REPORT SUPPORTED OPERATION CODES is not supported */
5015 sdev->no_report_opcodes = 1;
5017 /* WRITE_SAME command is not supported */
5018 sdev->no_write_same = 1;
5020 ufshcd_set_queue_depth(sdev);
5022 ufshcd_get_lu_power_on_wp_status(hba, sdev);
5024 ufshcd_setup_links(hba, sdev);
5030 * ufshcd_change_queue_depth - change queue depth
5031 * @sdev: pointer to SCSI device
5032 * @depth: required depth to set
5034 * Change queue depth and make sure the max. limits are not crossed.
5036 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
5038 return scsi_change_queue_depth(sdev, min(depth, sdev->host->can_queue));
5041 static void ufshcd_hpb_destroy(struct ufs_hba *hba, struct scsi_device *sdev)
5043 /* skip well-known LU */
5044 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) ||
5045 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba))
5048 ufshpb_destroy_lu(hba, sdev);
5051 static void ufshcd_hpb_configure(struct ufs_hba *hba, struct scsi_device *sdev)
5053 /* skip well-known LU */
5054 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) ||
5055 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba))
5058 ufshpb_init_hpb_lu(hba, sdev);
5062 * ufshcd_slave_configure - adjust SCSI device configurations
5063 * @sdev: pointer to SCSI device
5065 static int ufshcd_slave_configure(struct scsi_device *sdev)
5067 struct ufs_hba *hba = shost_priv(sdev->host);
5068 struct request_queue *q = sdev->request_queue;
5070 ufshcd_hpb_configure(hba, sdev);
5072 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
5073 if (hba->quirks & UFSHCD_QUIRK_ALIGN_SG_WITH_PAGE_SIZE)
5074 blk_queue_update_dma_alignment(q, PAGE_SIZE - 1);
5076 * Block runtime-pm until all consumers are added.
5077 * Refer ufshcd_setup_links().
5079 if (is_device_wlun(sdev))
5080 pm_runtime_get_noresume(&sdev->sdev_gendev);
5081 else if (ufshcd_is_rpm_autosuspend_allowed(hba))
5082 sdev->rpm_autosuspend = 1;
5084 * Do not print messages during runtime PM to avoid never-ending cycles
5085 * of messages written back to storage by user space causing runtime
5086 * resume, causing more messages and so on.
5088 sdev->silence_suspend = 1;
5090 ufshcd_crypto_register(hba, q);
5096 * ufshcd_slave_destroy - remove SCSI device configurations
5097 * @sdev: pointer to SCSI device
5099 static void ufshcd_slave_destroy(struct scsi_device *sdev)
5101 struct ufs_hba *hba;
5102 unsigned long flags;
5104 hba = shost_priv(sdev->host);
5106 ufshcd_hpb_destroy(hba, sdev);
5108 /* Drop the reference as it won't be needed anymore */
5109 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
5110 spin_lock_irqsave(hba->host->host_lock, flags);
5111 hba->ufs_device_wlun = NULL;
5112 spin_unlock_irqrestore(hba->host->host_lock, flags);
5113 } else if (hba->ufs_device_wlun) {
5114 struct device *supplier = NULL;
5116 /* Ensure UFS Device WLUN exists and does not disappear */
5117 spin_lock_irqsave(hba->host->host_lock, flags);
5118 if (hba->ufs_device_wlun) {
5119 supplier = &hba->ufs_device_wlun->sdev_gendev;
5120 get_device(supplier);
5122 spin_unlock_irqrestore(hba->host->host_lock, flags);
5126 * If a LUN fails to probe (e.g. absent BOOT WLUN), the
5127 * device will not have been registered but can still
5128 * have a device link holding a reference to the device.
5130 device_link_remove(&sdev->sdev_gendev, supplier);
5131 put_device(supplier);
5137 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
5138 * @lrbp: pointer to local reference block of completed command
5139 * @scsi_status: SCSI command status
5141 * Returns value base on SCSI command status
5144 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
5148 switch (scsi_status) {
5149 case SAM_STAT_CHECK_CONDITION:
5150 ufshcd_copy_sense_data(lrbp);
5153 result |= DID_OK << 16 | scsi_status;
5155 case SAM_STAT_TASK_SET_FULL:
5157 case SAM_STAT_TASK_ABORTED:
5158 ufshcd_copy_sense_data(lrbp);
5159 result |= scsi_status;
5162 result |= DID_ERROR << 16;
5164 } /* end of switch */
5170 * ufshcd_transfer_rsp_status - Get overall status of the response
5171 * @hba: per adapter instance
5172 * @lrbp: pointer to local reference block of completed command
5174 * Returns result of the command to notify SCSI midlayer
5177 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
5183 /* overall command status of utrd */
5184 ocs = ufshcd_get_tr_ocs(lrbp);
5186 if (hba->quirks & UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR) {
5187 if (be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_1) &
5188 MASK_RSP_UPIU_RESULT)
5194 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
5195 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
5197 case UPIU_TRANSACTION_RESPONSE:
5199 * get the response UPIU result to extract
5200 * the SCSI command status
5202 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
5205 * get the result based on SCSI status response
5206 * to notify the SCSI midlayer of the command status
5208 scsi_status = result & MASK_SCSI_STATUS;
5209 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
5212 * Currently we are only supporting BKOPs exception
5213 * events hence we can ignore BKOPs exception event
5214 * during power management callbacks. BKOPs exception
5215 * event is not expected to be raised in runtime suspend
5216 * callback as it allows the urgent bkops.
5217 * During system suspend, we are anyway forcefully
5218 * disabling the bkops and if urgent bkops is needed
5219 * it will be enabled on system resume. Long term
5220 * solution could be to abort the system suspend if
5221 * UFS device needs urgent BKOPs.
5223 if (!hba->pm_op_in_progress &&
5224 !ufshcd_eh_in_progress(hba) &&
5225 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
5226 /* Flushed in suspend */
5227 schedule_work(&hba->eeh_work);
5229 if (scsi_status == SAM_STAT_GOOD)
5230 ufshpb_rsp_upiu(hba, lrbp);
5232 case UPIU_TRANSACTION_REJECT_UPIU:
5233 /* TODO: handle Reject UPIU Response */
5234 result = DID_ERROR << 16;
5236 "Reject UPIU not fully implemented\n");
5240 "Unexpected request response code = %x\n",
5242 result = DID_ERROR << 16;
5247 result |= DID_ABORT << 16;
5249 case OCS_INVALID_COMMAND_STATUS:
5250 result |= DID_REQUEUE << 16;
5252 case OCS_INVALID_CMD_TABLE_ATTR:
5253 case OCS_INVALID_PRDT_ATTR:
5254 case OCS_MISMATCH_DATA_BUF_SIZE:
5255 case OCS_MISMATCH_RESP_UPIU_SIZE:
5256 case OCS_PEER_COMM_FAILURE:
5257 case OCS_FATAL_ERROR:
5258 case OCS_DEVICE_FATAL_ERROR:
5259 case OCS_INVALID_CRYPTO_CONFIG:
5260 case OCS_GENERAL_CRYPTO_ERROR:
5262 result |= DID_ERROR << 16;
5264 "OCS error from controller = %x for tag %d\n",
5265 ocs, lrbp->task_tag);
5266 ufshcd_print_evt_hist(hba);
5267 ufshcd_print_host_state(hba);
5269 } /* end of switch */
5271 if ((host_byte(result) != DID_OK) &&
5272 (host_byte(result) != DID_REQUEUE) && !hba->silence_err_logs)
5273 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true);
5277 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
5280 if (!ufshcd_is_auto_hibern8_supported(hba) ||
5281 !ufshcd_is_auto_hibern8_enabled(hba))
5284 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
5287 if (hba->active_uic_cmd &&
5288 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
5289 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
5296 * ufshcd_uic_cmd_compl - handle completion of uic command
5297 * @hba: per adapter instance
5298 * @intr_status: interrupt status generated by the controller
5301 * IRQ_HANDLED - If interrupt is valid
5302 * IRQ_NONE - If invalid interrupt
5304 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
5306 irqreturn_t retval = IRQ_NONE;
5308 spin_lock(hba->host->host_lock);
5309 if (ufshcd_is_auto_hibern8_error(hba, intr_status))
5310 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
5312 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
5313 hba->active_uic_cmd->argument2 |=
5314 ufshcd_get_uic_cmd_result(hba);
5315 hba->active_uic_cmd->argument3 =
5316 ufshcd_get_dme_attr_val(hba);
5317 if (!hba->uic_async_done)
5318 hba->active_uic_cmd->cmd_active = 0;
5319 complete(&hba->active_uic_cmd->done);
5320 retval = IRQ_HANDLED;
5323 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done) {
5324 hba->active_uic_cmd->cmd_active = 0;
5325 complete(hba->uic_async_done);
5326 retval = IRQ_HANDLED;
5329 if (retval == IRQ_HANDLED)
5330 ufshcd_add_uic_command_trace(hba, hba->active_uic_cmd,
5332 spin_unlock(hba->host->host_lock);
5336 /* Release the resources allocated for processing a SCSI command. */
5337 static void ufshcd_release_scsi_cmd(struct ufs_hba *hba,
5338 struct ufshcd_lrb *lrbp)
5340 struct scsi_cmnd *cmd = lrbp->cmd;
5342 scsi_dma_unmap(cmd);
5343 lrbp->cmd = NULL; /* Mark the command as completed. */
5344 ufshcd_release(hba);
5345 ufshcd_clk_scaling_update_busy(hba);
5349 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
5350 * @hba: per adapter instance
5351 * @completed_reqs: bitmask that indicates which requests to complete
5353 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
5354 unsigned long completed_reqs)
5356 struct ufshcd_lrb *lrbp;
5357 struct scsi_cmnd *cmd;
5360 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
5361 lrbp = &hba->lrb[index];
5362 lrbp->compl_time_stamp = ktime_get();
5363 lrbp->compl_time_stamp_local_clock = local_clock();
5366 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
5367 ufshcd_update_monitor(hba, lrbp);
5368 ufshcd_add_command_trace(hba, index, UFS_CMD_COMP);
5369 cmd->result = ufshcd_transfer_rsp_status(hba, lrbp);
5370 ufshcd_release_scsi_cmd(hba, lrbp);
5371 /* Do not touch lrbp after scsi done */
5373 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
5374 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
5375 if (hba->dev_cmd.complete) {
5376 ufshcd_add_command_trace(hba, index,
5378 complete(hba->dev_cmd.complete);
5379 ufshcd_clk_scaling_update_busy(hba);
5386 * Returns > 0 if one or more commands have been completed or 0 if no
5387 * requests have been completed.
5389 static int ufshcd_poll(struct Scsi_Host *shost, unsigned int queue_num)
5391 struct ufs_hba *hba = shost_priv(shost);
5392 unsigned long completed_reqs, flags;
5395 spin_lock_irqsave(&hba->outstanding_lock, flags);
5396 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5397 completed_reqs = ~tr_doorbell & hba->outstanding_reqs;
5398 WARN_ONCE(completed_reqs & ~hba->outstanding_reqs,
5399 "completed: %#lx; outstanding: %#lx\n", completed_reqs,
5400 hba->outstanding_reqs);
5401 hba->outstanding_reqs &= ~completed_reqs;
5402 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
5405 __ufshcd_transfer_req_compl(hba, completed_reqs);
5407 return completed_reqs;
5411 * ufshcd_transfer_req_compl - handle SCSI and query command completion
5412 * @hba: per adapter instance
5415 * IRQ_HANDLED - If interrupt is valid
5416 * IRQ_NONE - If invalid interrupt
5418 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba)
5420 /* Resetting interrupt aggregation counters first and reading the
5421 * DOOR_BELL afterward allows us to handle all the completed requests.
5422 * In order to prevent other interrupts starvation the DB is read once
5423 * after reset. The down side of this solution is the possibility of
5424 * false interrupt if device completes another request after resetting
5425 * aggregation and before reading the DB.
5427 if (ufshcd_is_intr_aggr_allowed(hba) &&
5428 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
5429 ufshcd_reset_intr_aggr(hba);
5431 if (ufs_fail_completion())
5435 * Ignore the ufshcd_poll() return value and return IRQ_HANDLED since we
5436 * do not want polling to trigger spurious interrupt complaints.
5438 ufshcd_poll(hba->host, 0);
5443 int __ufshcd_write_ee_control(struct ufs_hba *hba, u32 ee_ctrl_mask)
5445 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5446 QUERY_ATTR_IDN_EE_CONTROL, 0, 0,
5450 int ufshcd_write_ee_control(struct ufs_hba *hba)
5454 mutex_lock(&hba->ee_ctrl_mutex);
5455 err = __ufshcd_write_ee_control(hba, hba->ee_ctrl_mask);
5456 mutex_unlock(&hba->ee_ctrl_mutex);
5458 dev_err(hba->dev, "%s: failed to write ee control %d\n",
5463 int ufshcd_update_ee_control(struct ufs_hba *hba, u16 *mask,
5464 const u16 *other_mask, u16 set, u16 clr)
5466 u16 new_mask, ee_ctrl_mask;
5469 mutex_lock(&hba->ee_ctrl_mutex);
5470 new_mask = (*mask & ~clr) | set;
5471 ee_ctrl_mask = new_mask | *other_mask;
5472 if (ee_ctrl_mask != hba->ee_ctrl_mask)
5473 err = __ufshcd_write_ee_control(hba, ee_ctrl_mask);
5474 /* Still need to update 'mask' even if 'ee_ctrl_mask' was unchanged */
5476 hba->ee_ctrl_mask = ee_ctrl_mask;
5479 mutex_unlock(&hba->ee_ctrl_mutex);
5484 * ufshcd_disable_ee - disable exception event
5485 * @hba: per-adapter instance
5486 * @mask: exception event to disable
5488 * Disables exception event in the device so that the EVENT_ALERT
5491 * Returns zero on success, non-zero error value on failure.
5493 static inline int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
5495 return ufshcd_update_ee_drv_mask(hba, 0, mask);
5499 * ufshcd_enable_ee - enable exception event
5500 * @hba: per-adapter instance
5501 * @mask: exception event to enable
5503 * Enable corresponding exception event in the device to allow
5504 * device to alert host in critical scenarios.
5506 * Returns zero on success, non-zero error value on failure.
5508 static inline int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
5510 return ufshcd_update_ee_drv_mask(hba, mask, 0);
5514 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
5515 * @hba: per-adapter instance
5517 * Allow device to manage background operations on its own. Enabling
5518 * this might lead to inconsistent latencies during normal data transfers
5519 * as the device is allowed to manage its own way of handling background
5522 * Returns zero on success, non-zero on failure.
5524 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
5528 if (hba->auto_bkops_enabled)
5531 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5532 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5534 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
5539 hba->auto_bkops_enabled = true;
5540 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
5542 /* No need of URGENT_BKOPS exception from the device */
5543 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5545 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5552 * ufshcd_disable_auto_bkops - block device in doing background operations
5553 * @hba: per-adapter instance
5555 * Disabling background operations improves command response latency but
5556 * has drawback of device moving into critical state where the device is
5557 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5558 * host is idle so that BKOPS are managed effectively without any negative
5561 * Returns zero on success, non-zero on failure.
5563 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5567 if (!hba->auto_bkops_enabled)
5571 * If host assisted BKOPs is to be enabled, make sure
5572 * urgent bkops exception is allowed.
5574 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5576 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5581 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5582 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5584 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5586 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5590 hba->auto_bkops_enabled = false;
5591 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
5592 hba->is_urgent_bkops_lvl_checked = false;
5598 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5599 * @hba: per adapter instance
5601 * After a device reset the device may toggle the BKOPS_EN flag
5602 * to default value. The s/w tracking variables should be updated
5603 * as well. This function would change the auto-bkops state based on
5604 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5606 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5608 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5609 hba->auto_bkops_enabled = false;
5610 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5611 ufshcd_enable_auto_bkops(hba);
5613 hba->auto_bkops_enabled = true;
5614 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5615 ufshcd_disable_auto_bkops(hba);
5617 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
5618 hba->is_urgent_bkops_lvl_checked = false;
5621 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5623 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5624 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5628 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5629 * @hba: per-adapter instance
5630 * @status: bkops_status value
5632 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5633 * flag in the device to permit background operations if the device
5634 * bkops_status is greater than or equal to "status" argument passed to
5635 * this function, disable otherwise.
5637 * Returns 0 for success, non-zero in case of failure.
5639 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5640 * to know whether auto bkops is enabled or disabled after this function
5641 * returns control to it.
5643 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5644 enum bkops_status status)
5647 u32 curr_status = 0;
5649 err = ufshcd_get_bkops_status(hba, &curr_status);
5651 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5654 } else if (curr_status > BKOPS_STATUS_MAX) {
5655 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5656 __func__, curr_status);
5661 if (curr_status >= status)
5662 err = ufshcd_enable_auto_bkops(hba);
5664 err = ufshcd_disable_auto_bkops(hba);
5670 * ufshcd_urgent_bkops - handle urgent bkops exception event
5671 * @hba: per-adapter instance
5673 * Enable fBackgroundOpsEn flag in the device to permit background
5676 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5677 * and negative error value for any other failure.
5679 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5681 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5684 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5686 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5687 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5690 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5693 u32 curr_status = 0;
5695 if (hba->is_urgent_bkops_lvl_checked)
5696 goto enable_auto_bkops;
5698 err = ufshcd_get_bkops_status(hba, &curr_status);
5700 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5706 * We are seeing that some devices are raising the urgent bkops
5707 * exception events even when BKOPS status doesn't indicate performace
5708 * impacted or critical. Handle these device by determining their urgent
5709 * bkops status at runtime.
5711 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5712 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5713 __func__, curr_status);
5714 /* update the current status as the urgent bkops level */
5715 hba->urgent_bkops_lvl = curr_status;
5716 hba->is_urgent_bkops_lvl_checked = true;
5720 err = ufshcd_enable_auto_bkops(hba);
5723 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5727 static void ufshcd_temp_exception_event_handler(struct ufs_hba *hba, u16 status)
5731 if (ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5732 QUERY_ATTR_IDN_CASE_ROUGH_TEMP, 0, 0, &value))
5735 dev_info(hba->dev, "exception Tcase %d\n", value - 80);
5737 ufs_hwmon_notify_event(hba, status & MASK_EE_URGENT_TEMP);
5740 * A placeholder for the platform vendors to add whatever additional
5745 static int __ufshcd_wb_toggle(struct ufs_hba *hba, bool set, enum flag_idn idn)
5748 enum query_opcode opcode = set ? UPIU_QUERY_OPCODE_SET_FLAG :
5749 UPIU_QUERY_OPCODE_CLEAR_FLAG;
5751 index = ufshcd_wb_get_query_index(hba);
5752 return ufshcd_query_flag_retry(hba, opcode, idn, index, NULL);
5755 int ufshcd_wb_toggle(struct ufs_hba *hba, bool enable)
5759 if (!ufshcd_is_wb_allowed(hba) ||
5760 hba->dev_info.wb_enabled == enable)
5763 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_EN);
5765 dev_err(hba->dev, "%s: Write Booster %s failed %d\n",
5766 __func__, enable ? "enabling" : "disabling", ret);
5770 hba->dev_info.wb_enabled = enable;
5771 dev_dbg(hba->dev, "%s: Write Booster %s\n",
5772 __func__, enable ? "enabled" : "disabled");
5777 static void ufshcd_wb_toggle_buf_flush_during_h8(struct ufs_hba *hba,
5782 ret = __ufshcd_wb_toggle(hba, enable,
5783 QUERY_FLAG_IDN_WB_BUFF_FLUSH_DURING_HIBERN8);
5785 dev_err(hba->dev, "%s: WB-Buf Flush during H8 %s failed %d\n",
5786 __func__, enable ? "enabling" : "disabling", ret);
5789 dev_dbg(hba->dev, "%s: WB-Buf Flush during H8 %s\n",
5790 __func__, enable ? "enabled" : "disabled");
5793 int ufshcd_wb_toggle_buf_flush(struct ufs_hba *hba, bool enable)
5797 if (!ufshcd_is_wb_allowed(hba) ||
5798 hba->dev_info.wb_buf_flush_enabled == enable)
5801 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN);
5803 dev_err(hba->dev, "%s: WB-Buf Flush %s failed %d\n",
5804 __func__, enable ? "enabling" : "disabling", ret);
5808 hba->dev_info.wb_buf_flush_enabled = enable;
5809 dev_dbg(hba->dev, "%s: WB-Buf Flush %s\n",
5810 __func__, enable ? "enabled" : "disabled");
5815 static bool ufshcd_wb_presrv_usrspc_keep_vcc_on(struct ufs_hba *hba,
5822 index = ufshcd_wb_get_query_index(hba);
5823 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5824 QUERY_ATTR_IDN_CURR_WB_BUFF_SIZE,
5825 index, 0, &cur_buf);
5827 dev_err(hba->dev, "%s: dCurWriteBoosterBufferSize read failed %d\n",
5833 dev_info(hba->dev, "dCurWBBuf: %d WB disabled until free-space is available\n",
5837 /* Let it continue to flush when available buffer exceeds threshold */
5838 return avail_buf < hba->vps->wb_flush_threshold;
5841 static void ufshcd_wb_force_disable(struct ufs_hba *hba)
5843 if (ufshcd_is_wb_buf_flush_allowed(hba))
5844 ufshcd_wb_toggle_buf_flush(hba, false);
5846 ufshcd_wb_toggle_buf_flush_during_h8(hba, false);
5847 ufshcd_wb_toggle(hba, false);
5848 hba->caps &= ~UFSHCD_CAP_WB_EN;
5850 dev_info(hba->dev, "%s: WB force disabled\n", __func__);
5853 static bool ufshcd_is_wb_buf_lifetime_available(struct ufs_hba *hba)
5859 index = ufshcd_wb_get_query_index(hba);
5860 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5861 QUERY_ATTR_IDN_WB_BUFF_LIFE_TIME_EST,
5862 index, 0, &lifetime);
5865 "%s: bWriteBoosterBufferLifeTimeEst read failed %d\n",
5870 if (lifetime == UFS_WB_EXCEED_LIFETIME) {
5871 dev_err(hba->dev, "%s: WB buf lifetime is exhausted 0x%02X\n",
5872 __func__, lifetime);
5876 dev_dbg(hba->dev, "%s: WB buf lifetime is 0x%02X\n",
5877 __func__, lifetime);
5882 static bool ufshcd_wb_need_flush(struct ufs_hba *hba)
5888 if (!ufshcd_is_wb_allowed(hba))
5891 if (!ufshcd_is_wb_buf_lifetime_available(hba)) {
5892 ufshcd_wb_force_disable(hba);
5897 * The ufs device needs the vcc to be ON to flush.
5898 * With user-space reduction enabled, it's enough to enable flush
5899 * by checking only the available buffer. The threshold
5900 * defined here is > 90% full.
5901 * With user-space preserved enabled, the current-buffer
5902 * should be checked too because the wb buffer size can reduce
5903 * when disk tends to be full. This info is provided by current
5904 * buffer (dCurrentWriteBoosterBufferSize). There's no point in
5905 * keeping vcc on when current buffer is empty.
5907 index = ufshcd_wb_get_query_index(hba);
5908 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5909 QUERY_ATTR_IDN_AVAIL_WB_BUFF_SIZE,
5910 index, 0, &avail_buf);
5912 dev_warn(hba->dev, "%s: dAvailableWriteBoosterBufferSize read failed %d\n",
5917 if (!hba->dev_info.b_presrv_uspc_en)
5918 return avail_buf <= UFS_WB_BUF_REMAIN_PERCENT(10);
5920 return ufshcd_wb_presrv_usrspc_keep_vcc_on(hba, avail_buf);
5923 static void ufshcd_rpm_dev_flush_recheck_work(struct work_struct *work)
5925 struct ufs_hba *hba = container_of(to_delayed_work(work),
5927 rpm_dev_flush_recheck_work);
5929 * To prevent unnecessary VCC power drain after device finishes
5930 * WriteBooster buffer flush or Auto BKOPs, force runtime resume
5931 * after a certain delay to recheck the threshold by next runtime
5934 ufshcd_rpm_get_sync(hba);
5935 ufshcd_rpm_put_sync(hba);
5939 * ufshcd_exception_event_handler - handle exceptions raised by device
5940 * @work: pointer to work data
5942 * Read bExceptionEventStatus attribute from the device and handle the
5943 * exception event accordingly.
5945 static void ufshcd_exception_event_handler(struct work_struct *work)
5947 struct ufs_hba *hba;
5950 hba = container_of(work, struct ufs_hba, eeh_work);
5952 ufshcd_scsi_block_requests(hba);
5953 err = ufshcd_get_ee_status(hba, &status);
5955 dev_err(hba->dev, "%s: failed to get exception status %d\n",
5960 trace_ufshcd_exception_event(dev_name(hba->dev), status);
5962 if (status & hba->ee_drv_mask & MASK_EE_URGENT_BKOPS)
5963 ufshcd_bkops_exception_event_handler(hba);
5965 if (status & hba->ee_drv_mask & MASK_EE_URGENT_TEMP)
5966 ufshcd_temp_exception_event_handler(hba, status);
5968 ufs_debugfs_exception_event(hba, status);
5970 ufshcd_scsi_unblock_requests(hba);
5973 /* Complete requests that have door-bell cleared */
5974 static void ufshcd_complete_requests(struct ufs_hba *hba)
5976 ufshcd_transfer_req_compl(hba);
5977 ufshcd_tmc_handler(hba);
5981 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
5982 * to recover from the DL NAC errors or not.
5983 * @hba: per-adapter instance
5985 * Returns true if error handling is required, false otherwise
5987 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
5989 unsigned long flags;
5990 bool err_handling = true;
5992 spin_lock_irqsave(hba->host->host_lock, flags);
5994 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
5995 * device fatal error and/or DL NAC & REPLAY timeout errors.
5997 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
6000 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
6001 ((hba->saved_err & UIC_ERROR) &&
6002 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
6005 if ((hba->saved_err & UIC_ERROR) &&
6006 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
6009 * wait for 50ms to see if we can get any other errors or not.
6011 spin_unlock_irqrestore(hba->host->host_lock, flags);
6013 spin_lock_irqsave(hba->host->host_lock, flags);
6016 * now check if we have got any other severe errors other than
6019 if ((hba->saved_err & INT_FATAL_ERRORS) ||
6020 ((hba->saved_err & UIC_ERROR) &&
6021 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
6025 * As DL NAC is the only error received so far, send out NOP
6026 * command to confirm if link is still active or not.
6027 * - If we don't get any response then do error recovery.
6028 * - If we get response then clear the DL NAC error bit.
6031 spin_unlock_irqrestore(hba->host->host_lock, flags);
6032 err = ufshcd_verify_dev_init(hba);
6033 spin_lock_irqsave(hba->host->host_lock, flags);
6038 /* Link seems to be alive hence ignore the DL NAC errors */
6039 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
6040 hba->saved_err &= ~UIC_ERROR;
6041 /* clear NAC error */
6042 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6043 if (!hba->saved_uic_err)
6044 err_handling = false;
6047 spin_unlock_irqrestore(hba->host->host_lock, flags);
6048 return err_handling;
6051 /* host lock must be held before calling this func */
6052 static inline bool ufshcd_is_saved_err_fatal(struct ufs_hba *hba)
6054 return (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR) ||
6055 (hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK));
6058 void ufshcd_schedule_eh_work(struct ufs_hba *hba)
6060 lockdep_assert_held(hba->host->host_lock);
6062 /* handle fatal errors only when link is not in error state */
6063 if (hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6064 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6065 ufshcd_is_saved_err_fatal(hba))
6066 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_FATAL;
6068 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_NON_FATAL;
6069 queue_work(hba->eh_wq, &hba->eh_work);
6073 static void ufshcd_clk_scaling_allow(struct ufs_hba *hba, bool allow)
6075 down_write(&hba->clk_scaling_lock);
6076 hba->clk_scaling.is_allowed = allow;
6077 up_write(&hba->clk_scaling_lock);
6080 static void ufshcd_clk_scaling_suspend(struct ufs_hba *hba, bool suspend)
6083 if (hba->clk_scaling.is_enabled)
6084 ufshcd_suspend_clkscaling(hba);
6085 ufshcd_clk_scaling_allow(hba, false);
6087 ufshcd_clk_scaling_allow(hba, true);
6088 if (hba->clk_scaling.is_enabled)
6089 ufshcd_resume_clkscaling(hba);
6093 static void ufshcd_err_handling_prepare(struct ufs_hba *hba)
6095 ufshcd_rpm_get_sync(hba);
6096 if (pm_runtime_status_suspended(&hba->ufs_device_wlun->sdev_gendev) ||
6097 hba->is_sys_suspended) {
6098 enum ufs_pm_op pm_op;
6101 * Don't assume anything of resume, if
6102 * resume fails, irq and clocks can be OFF, and powers
6103 * can be OFF or in LPM.
6105 ufshcd_setup_hba_vreg(hba, true);
6106 ufshcd_enable_irq(hba);
6107 ufshcd_setup_vreg(hba, true);
6108 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
6109 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
6110 ufshcd_hold(hba, false);
6111 if (!ufshcd_is_clkgating_allowed(hba))
6112 ufshcd_setup_clocks(hba, true);
6113 ufshcd_release(hba);
6114 pm_op = hba->is_sys_suspended ? UFS_SYSTEM_PM : UFS_RUNTIME_PM;
6115 ufshcd_vops_resume(hba, pm_op);
6117 ufshcd_hold(hba, false);
6118 if (ufshcd_is_clkscaling_supported(hba) &&
6119 hba->clk_scaling.is_enabled)
6120 ufshcd_suspend_clkscaling(hba);
6121 ufshcd_clk_scaling_allow(hba, false);
6123 ufshcd_scsi_block_requests(hba);
6124 /* Drain ufshcd_queuecommand() */
6126 cancel_work_sync(&hba->eeh_work);
6129 static void ufshcd_err_handling_unprepare(struct ufs_hba *hba)
6131 ufshcd_scsi_unblock_requests(hba);
6132 ufshcd_release(hba);
6133 if (ufshcd_is_clkscaling_supported(hba))
6134 ufshcd_clk_scaling_suspend(hba, false);
6135 ufshcd_rpm_put(hba);
6138 static inline bool ufshcd_err_handling_should_stop(struct ufs_hba *hba)
6140 return (!hba->is_powered || hba->shutting_down ||
6141 !hba->ufs_device_wlun ||
6142 hba->ufshcd_state == UFSHCD_STATE_ERROR ||
6143 (!(hba->saved_err || hba->saved_uic_err || hba->force_reset ||
6144 ufshcd_is_link_broken(hba))));
6148 static void ufshcd_recover_pm_error(struct ufs_hba *hba)
6150 struct Scsi_Host *shost = hba->host;
6151 struct scsi_device *sdev;
6152 struct request_queue *q;
6155 hba->is_sys_suspended = false;
6157 * Set RPM status of wlun device to RPM_ACTIVE,
6158 * this also clears its runtime error.
6160 ret = pm_runtime_set_active(&hba->ufs_device_wlun->sdev_gendev);
6162 /* hba device might have a runtime error otherwise */
6164 ret = pm_runtime_set_active(hba->dev);
6166 * If wlun device had runtime error, we also need to resume those
6167 * consumer scsi devices in case any of them has failed to be
6168 * resumed due to supplier runtime resume failure. This is to unblock
6169 * blk_queue_enter in case there are bios waiting inside it.
6172 shost_for_each_device(sdev, shost) {
6173 q = sdev->request_queue;
6174 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
6175 q->rpm_status == RPM_SUSPENDING))
6176 pm_request_resume(q->dev);
6181 static inline void ufshcd_recover_pm_error(struct ufs_hba *hba)
6186 static bool ufshcd_is_pwr_mode_restore_needed(struct ufs_hba *hba)
6188 struct ufs_pa_layer_attr *pwr_info = &hba->pwr_info;
6191 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode);
6193 if (pwr_info->pwr_rx != ((mode >> PWRMODE_RX_OFFSET) & PWRMODE_MASK))
6196 if (pwr_info->pwr_tx != (mode & PWRMODE_MASK))
6203 * ufshcd_err_handler - handle UFS errors that require s/w attention
6204 * @work: pointer to work structure
6206 static void ufshcd_err_handler(struct work_struct *work)
6208 int retries = MAX_ERR_HANDLER_RETRIES;
6209 struct ufs_hba *hba;
6210 unsigned long flags;
6218 hba = container_of(work, struct ufs_hba, eh_work);
6221 "%s started; HBA state %s; powered %d; shutting down %d; saved_err = %d; saved_uic_err = %d; force_reset = %d%s\n",
6222 __func__, ufshcd_state_name[hba->ufshcd_state],
6223 hba->is_powered, hba->shutting_down, hba->saved_err,
6224 hba->saved_uic_err, hba->force_reset,
6225 ufshcd_is_link_broken(hba) ? "; link is broken" : "");
6227 down(&hba->host_sem);
6228 spin_lock_irqsave(hba->host->host_lock, flags);
6229 if (ufshcd_err_handling_should_stop(hba)) {
6230 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6231 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6232 spin_unlock_irqrestore(hba->host->host_lock, flags);
6236 ufshcd_set_eh_in_progress(hba);
6237 spin_unlock_irqrestore(hba->host->host_lock, flags);
6238 ufshcd_err_handling_prepare(hba);
6239 /* Complete requests that have door-bell cleared by h/w */
6240 ufshcd_complete_requests(hba);
6241 spin_lock_irqsave(hba->host->host_lock, flags);
6243 needs_restore = false;
6244 needs_reset = false;
6248 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6249 hba->ufshcd_state = UFSHCD_STATE_RESET;
6251 * A full reset and restore might have happened after preparation
6252 * is finished, double check whether we should stop.
6254 if (ufshcd_err_handling_should_stop(hba))
6255 goto skip_err_handling;
6257 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6260 spin_unlock_irqrestore(hba->host->host_lock, flags);
6261 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
6262 ret = ufshcd_quirk_dl_nac_errors(hba);
6263 spin_lock_irqsave(hba->host->host_lock, flags);
6264 if (!ret && ufshcd_err_handling_should_stop(hba))
6265 goto skip_err_handling;
6268 if ((hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6269 (hba->saved_uic_err &&
6270 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6271 bool pr_prdt = !!(hba->saved_err & SYSTEM_BUS_FATAL_ERROR);
6273 spin_unlock_irqrestore(hba->host->host_lock, flags);
6274 ufshcd_print_host_state(hba);
6275 ufshcd_print_pwr_info(hba);
6276 ufshcd_print_evt_hist(hba);
6277 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
6278 ufshcd_print_trs(hba, hba->outstanding_reqs, pr_prdt);
6279 spin_lock_irqsave(hba->host->host_lock, flags);
6283 * if host reset is required then skip clearing the pending
6284 * transfers forcefully because they will get cleared during
6285 * host reset and restore
6287 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6288 ufshcd_is_saved_err_fatal(hba) ||
6289 ((hba->saved_err & UIC_ERROR) &&
6290 (hba->saved_uic_err & (UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
6291 UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))) {
6297 * If LINERESET was caught, UFS might have been put to PWM mode,
6298 * check if power mode restore is needed.
6300 if (hba->saved_uic_err & UFSHCD_UIC_PA_GENERIC_ERROR) {
6301 hba->saved_uic_err &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6302 if (!hba->saved_uic_err)
6303 hba->saved_err &= ~UIC_ERROR;
6304 spin_unlock_irqrestore(hba->host->host_lock, flags);
6305 if (ufshcd_is_pwr_mode_restore_needed(hba))
6306 needs_restore = true;
6307 spin_lock_irqsave(hba->host->host_lock, flags);
6308 if (!hba->saved_err && !needs_restore)
6309 goto skip_err_handling;
6312 hba->silence_err_logs = true;
6313 /* release lock as clear command might sleep */
6314 spin_unlock_irqrestore(hba->host->host_lock, flags);
6315 /* Clear pending transfer requests */
6316 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
6317 if (ufshcd_try_to_abort_task(hba, tag)) {
6319 goto lock_skip_pending_xfer_clear;
6321 dev_err(hba->dev, "Aborted tag %d / CDB %#02x\n", tag,
6322 hba->lrb[tag].cmd ? hba->lrb[tag].cmd->cmnd[0] : -1);
6325 /* Clear pending task management requests */
6326 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
6327 if (ufshcd_clear_tm_cmd(hba, tag)) {
6329 goto lock_skip_pending_xfer_clear;
6333 lock_skip_pending_xfer_clear:
6334 /* Complete the requests that are cleared by s/w */
6335 ufshcd_complete_requests(hba);
6337 spin_lock_irqsave(hba->host->host_lock, flags);
6338 hba->silence_err_logs = false;
6339 if (err_xfer || err_tm) {
6345 * After all reqs and tasks are cleared from doorbell,
6346 * now it is safe to retore power mode.
6348 if (needs_restore) {
6349 spin_unlock_irqrestore(hba->host->host_lock, flags);
6351 * Hold the scaling lock just in case dev cmds
6352 * are sent via bsg and/or sysfs.
6354 down_write(&hba->clk_scaling_lock);
6355 hba->force_pmc = true;
6356 pmc_err = ufshcd_config_pwr_mode(hba, &(hba->pwr_info));
6359 dev_err(hba->dev, "%s: Failed to restore power mode, err = %d\n",
6362 hba->force_pmc = false;
6363 ufshcd_print_pwr_info(hba);
6364 up_write(&hba->clk_scaling_lock);
6365 spin_lock_irqsave(hba->host->host_lock, flags);
6369 /* Fatal errors need reset */
6373 hba->force_reset = false;
6374 spin_unlock_irqrestore(hba->host->host_lock, flags);
6375 err = ufshcd_reset_and_restore(hba);
6377 dev_err(hba->dev, "%s: reset and restore failed with err %d\n",
6380 ufshcd_recover_pm_error(hba);
6381 spin_lock_irqsave(hba->host->host_lock, flags);
6386 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
6387 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6388 if (hba->saved_err || hba->saved_uic_err)
6389 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
6390 __func__, hba->saved_err, hba->saved_uic_err);
6392 /* Exit in an operational state or dead */
6393 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
6394 hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6397 hba->ufshcd_state = UFSHCD_STATE_ERROR;
6399 ufshcd_clear_eh_in_progress(hba);
6400 spin_unlock_irqrestore(hba->host->host_lock, flags);
6401 ufshcd_err_handling_unprepare(hba);
6404 dev_info(hba->dev, "%s finished; HBA state %s\n", __func__,
6405 ufshcd_state_name[hba->ufshcd_state]);
6409 * ufshcd_update_uic_error - check and set fatal UIC error flags.
6410 * @hba: per-adapter instance
6413 * IRQ_HANDLED - If interrupt is valid
6414 * IRQ_NONE - If invalid interrupt
6416 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
6419 irqreturn_t retval = IRQ_NONE;
6421 /* PHY layer error */
6422 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
6423 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
6424 (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) {
6425 ufshcd_update_evt_hist(hba, UFS_EVT_PA_ERR, reg);
6427 * To know whether this error is fatal or not, DB timeout
6428 * must be checked but this error is handled separately.
6430 if (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)
6431 dev_dbg(hba->dev, "%s: UIC Lane error reported\n",
6434 /* Got a LINERESET indication. */
6435 if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) {
6436 struct uic_command *cmd = NULL;
6438 hba->uic_error |= UFSHCD_UIC_PA_GENERIC_ERROR;
6439 if (hba->uic_async_done && hba->active_uic_cmd)
6440 cmd = hba->active_uic_cmd;
6442 * Ignore the LINERESET during power mode change
6443 * operation via DME_SET command.
6445 if (cmd && (cmd->command == UIC_CMD_DME_SET))
6446 hba->uic_error &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6448 retval |= IRQ_HANDLED;
6451 /* PA_INIT_ERROR is fatal and needs UIC reset */
6452 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
6453 if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
6454 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
6455 ufshcd_update_evt_hist(hba, UFS_EVT_DL_ERR, reg);
6457 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
6458 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
6459 else if (hba->dev_quirks &
6460 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6461 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
6463 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6464 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
6465 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
6467 retval |= IRQ_HANDLED;
6470 /* UIC NL/TL/DME errors needs software retry */
6471 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
6472 if ((reg & UIC_NETWORK_LAYER_ERROR) &&
6473 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
6474 ufshcd_update_evt_hist(hba, UFS_EVT_NL_ERR, reg);
6475 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
6476 retval |= IRQ_HANDLED;
6479 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
6480 if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
6481 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
6482 ufshcd_update_evt_hist(hba, UFS_EVT_TL_ERR, reg);
6483 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
6484 retval |= IRQ_HANDLED;
6487 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
6488 if ((reg & UIC_DME_ERROR) &&
6489 (reg & UIC_DME_ERROR_CODE_MASK)) {
6490 ufshcd_update_evt_hist(hba, UFS_EVT_DME_ERR, reg);
6491 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
6492 retval |= IRQ_HANDLED;
6495 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
6496 __func__, hba->uic_error);
6501 * ufshcd_check_errors - Check for errors that need s/w attention
6502 * @hba: per-adapter instance
6503 * @intr_status: interrupt status generated by the controller
6506 * IRQ_HANDLED - If interrupt is valid
6507 * IRQ_NONE - If invalid interrupt
6509 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba, u32 intr_status)
6511 bool queue_eh_work = false;
6512 irqreturn_t retval = IRQ_NONE;
6514 spin_lock(hba->host->host_lock);
6515 hba->errors |= UFSHCD_ERROR_MASK & intr_status;
6517 if (hba->errors & INT_FATAL_ERRORS) {
6518 ufshcd_update_evt_hist(hba, UFS_EVT_FATAL_ERR,
6520 queue_eh_work = true;
6523 if (hba->errors & UIC_ERROR) {
6525 retval = ufshcd_update_uic_error(hba);
6527 queue_eh_work = true;
6530 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
6532 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
6533 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
6535 hba->errors, ufshcd_get_upmcrs(hba));
6536 ufshcd_update_evt_hist(hba, UFS_EVT_AUTO_HIBERN8_ERR,
6538 ufshcd_set_link_broken(hba);
6539 queue_eh_work = true;
6542 if (queue_eh_work) {
6544 * update the transfer error masks to sticky bits, let's do this
6545 * irrespective of current ufshcd_state.
6547 hba->saved_err |= hba->errors;
6548 hba->saved_uic_err |= hba->uic_error;
6550 /* dump controller state before resetting */
6551 if ((hba->saved_err &
6552 (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6553 (hba->saved_uic_err &&
6554 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6555 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
6556 __func__, hba->saved_err,
6557 hba->saved_uic_err);
6558 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE,
6560 ufshcd_print_pwr_info(hba);
6562 ufshcd_schedule_eh_work(hba);
6563 retval |= IRQ_HANDLED;
6566 * if (!queue_eh_work) -
6567 * Other errors are either non-fatal where host recovers
6568 * itself without s/w intervention or errors that will be
6569 * handled by the SCSI core layer.
6573 spin_unlock(hba->host->host_lock);
6578 * ufshcd_tmc_handler - handle task management function completion
6579 * @hba: per adapter instance
6582 * IRQ_HANDLED - If interrupt is valid
6583 * IRQ_NONE - If invalid interrupt
6585 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
6587 unsigned long flags, pending, issued;
6588 irqreturn_t ret = IRQ_NONE;
6591 spin_lock_irqsave(hba->host->host_lock, flags);
6592 pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
6593 issued = hba->outstanding_tasks & ~pending;
6594 for_each_set_bit(tag, &issued, hba->nutmrs) {
6595 struct request *req = hba->tmf_rqs[tag];
6596 struct completion *c = req->end_io_data;
6601 spin_unlock_irqrestore(hba->host->host_lock, flags);
6607 * ufshcd_sl_intr - Interrupt service routine
6608 * @hba: per adapter instance
6609 * @intr_status: contains interrupts generated by the controller
6612 * IRQ_HANDLED - If interrupt is valid
6613 * IRQ_NONE - If invalid interrupt
6615 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
6617 irqreturn_t retval = IRQ_NONE;
6619 if (intr_status & UFSHCD_UIC_MASK)
6620 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
6622 if (intr_status & UFSHCD_ERROR_MASK || hba->errors)
6623 retval |= ufshcd_check_errors(hba, intr_status);
6625 if (intr_status & UTP_TASK_REQ_COMPL)
6626 retval |= ufshcd_tmc_handler(hba);
6628 if (intr_status & UTP_TRANSFER_REQ_COMPL)
6629 retval |= ufshcd_transfer_req_compl(hba);
6635 * ufshcd_intr - Main interrupt service routine
6637 * @__hba: pointer to adapter instance
6640 * IRQ_HANDLED - If interrupt is valid
6641 * IRQ_NONE - If invalid interrupt
6643 static irqreturn_t ufshcd_intr(int irq, void *__hba)
6645 u32 intr_status, enabled_intr_status = 0;
6646 irqreturn_t retval = IRQ_NONE;
6647 struct ufs_hba *hba = __hba;
6648 int retries = hba->nutrs;
6650 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6651 hba->ufs_stats.last_intr_status = intr_status;
6652 hba->ufs_stats.last_intr_ts = local_clock();
6655 * There could be max of hba->nutrs reqs in flight and in worst case
6656 * if the reqs get finished 1 by 1 after the interrupt status is
6657 * read, make sure we handle them by checking the interrupt status
6658 * again in a loop until we process all of the reqs before returning.
6660 while (intr_status && retries--) {
6661 enabled_intr_status =
6662 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
6663 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
6664 if (enabled_intr_status)
6665 retval |= ufshcd_sl_intr(hba, enabled_intr_status);
6667 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6670 if (enabled_intr_status && retval == IRQ_NONE &&
6671 (!(enabled_intr_status & UTP_TRANSFER_REQ_COMPL) ||
6672 hba->outstanding_reqs) && !ufshcd_eh_in_progress(hba)) {
6673 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x (0x%08x, 0x%08x)\n",
6676 hba->ufs_stats.last_intr_status,
6677 enabled_intr_status);
6678 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
6684 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
6687 u32 mask = 1 << tag;
6688 unsigned long flags;
6690 if (!test_bit(tag, &hba->outstanding_tasks))
6693 spin_lock_irqsave(hba->host->host_lock, flags);
6694 ufshcd_utmrl_clear(hba, tag);
6695 spin_unlock_irqrestore(hba->host->host_lock, flags);
6697 /* poll for max. 1 sec to clear door bell register by h/w */
6698 err = ufshcd_wait_for_register(hba,
6699 REG_UTP_TASK_REQ_DOOR_BELL,
6700 mask, 0, 1000, 1000);
6702 dev_err(hba->dev, "Clearing task management function with tag %d %s\n",
6703 tag, err ? "succeeded" : "failed");
6709 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
6710 struct utp_task_req_desc *treq, u8 tm_function)
6712 struct request_queue *q = hba->tmf_queue;
6713 struct Scsi_Host *host = hba->host;
6714 DECLARE_COMPLETION_ONSTACK(wait);
6715 struct request *req;
6716 unsigned long flags;
6720 * blk_mq_alloc_request() is used here only to get a free tag.
6722 req = blk_mq_alloc_request(q, REQ_OP_DRV_OUT, 0);
6724 return PTR_ERR(req);
6726 req->end_io_data = &wait;
6727 ufshcd_hold(hba, false);
6729 spin_lock_irqsave(host->host_lock, flags);
6731 task_tag = req->tag;
6732 WARN_ONCE(task_tag < 0 || task_tag >= hba->nutmrs, "Invalid tag %d\n",
6734 hba->tmf_rqs[req->tag] = req;
6735 treq->upiu_req.req_header.dword_0 |= cpu_to_be32(task_tag);
6737 memcpy(hba->utmrdl_base_addr + task_tag, treq, sizeof(*treq));
6738 ufshcd_vops_setup_task_mgmt(hba, task_tag, tm_function);
6740 /* send command to the controller */
6741 __set_bit(task_tag, &hba->outstanding_tasks);
6743 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TASK_REQ_DOOR_BELL);
6744 /* Make sure that doorbell is committed immediately */
6747 spin_unlock_irqrestore(host->host_lock, flags);
6749 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_SEND);
6751 /* wait until the task management command is completed */
6752 err = wait_for_completion_io_timeout(&wait,
6753 msecs_to_jiffies(TM_CMD_TIMEOUT));
6755 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_ERR);
6756 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
6757 __func__, tm_function);
6758 if (ufshcd_clear_tm_cmd(hba, task_tag))
6759 dev_WARN(hba->dev, "%s: unable to clear tm cmd (slot %d) after timeout\n",
6760 __func__, task_tag);
6764 memcpy(treq, hba->utmrdl_base_addr + task_tag, sizeof(*treq));
6766 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_COMP);
6769 spin_lock_irqsave(hba->host->host_lock, flags);
6770 hba->tmf_rqs[req->tag] = NULL;
6771 __clear_bit(task_tag, &hba->outstanding_tasks);
6772 spin_unlock_irqrestore(hba->host->host_lock, flags);
6774 ufshcd_release(hba);
6775 blk_mq_free_request(req);
6781 * ufshcd_issue_tm_cmd - issues task management commands to controller
6782 * @hba: per adapter instance
6783 * @lun_id: LUN ID to which TM command is sent
6784 * @task_id: task ID to which the TM command is applicable
6785 * @tm_function: task management function opcode
6786 * @tm_response: task management service response return value
6788 * Returns non-zero value on error, zero on success.
6790 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
6791 u8 tm_function, u8 *tm_response)
6793 struct utp_task_req_desc treq = { { 0 }, };
6794 enum utp_ocs ocs_value;
6797 /* Configure task request descriptor */
6798 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6799 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6801 /* Configure task request UPIU */
6802 treq.upiu_req.req_header.dword_0 = cpu_to_be32(lun_id << 8) |
6803 cpu_to_be32(UPIU_TRANSACTION_TASK_REQ << 24);
6804 treq.upiu_req.req_header.dword_1 = cpu_to_be32(tm_function << 16);
6807 * The host shall provide the same value for LUN field in the basic
6808 * header and for Input Parameter.
6810 treq.upiu_req.input_param1 = cpu_to_be32(lun_id);
6811 treq.upiu_req.input_param2 = cpu_to_be32(task_id);
6813 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
6814 if (err == -ETIMEDOUT)
6817 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6818 if (ocs_value != OCS_SUCCESS)
6819 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
6820 __func__, ocs_value);
6821 else if (tm_response)
6822 *tm_response = be32_to_cpu(treq.upiu_rsp.output_param1) &
6823 MASK_TM_SERVICE_RESP;
6828 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
6829 * @hba: per-adapter instance
6830 * @req_upiu: upiu request
6831 * @rsp_upiu: upiu reply
6832 * @desc_buff: pointer to descriptor buffer, NULL if NA
6833 * @buff_len: descriptor size, 0 if NA
6834 * @cmd_type: specifies the type (NOP, Query...)
6835 * @desc_op: descriptor operation
6837 * Those type of requests uses UTP Transfer Request Descriptor - utrd.
6838 * Therefore, it "rides" the device management infrastructure: uses its tag and
6839 * tasks work queues.
6841 * Since there is only one available tag for device management commands,
6842 * the caller is expected to hold the hba->dev_cmd.lock mutex.
6844 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
6845 struct utp_upiu_req *req_upiu,
6846 struct utp_upiu_req *rsp_upiu,
6847 u8 *desc_buff, int *buff_len,
6848 enum dev_cmd_type cmd_type,
6849 enum query_opcode desc_op)
6851 DECLARE_COMPLETION_ONSTACK(wait);
6852 const u32 tag = hba->reserved_slot;
6853 struct ufshcd_lrb *lrbp;
6857 /* Protects use of hba->reserved_slot. */
6858 lockdep_assert_held(&hba->dev_cmd.lock);
6860 down_read(&hba->clk_scaling_lock);
6862 lrbp = &hba->lrb[tag];
6865 lrbp->task_tag = tag;
6867 lrbp->intr_cmd = true;
6868 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
6869 hba->dev_cmd.type = cmd_type;
6871 if (hba->ufs_version <= ufshci_version(1, 1))
6872 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
6874 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
6876 /* update the task tag in the request upiu */
6877 req_upiu->header.dword_0 |= cpu_to_be32(tag);
6879 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
6881 /* just copy the upiu request as it is */
6882 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
6883 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
6884 /* The Data Segment Area is optional depending upon the query
6885 * function value. for WRITE DESCRIPTOR, the data segment
6886 * follows right after the tsf.
6888 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
6892 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
6894 hba->dev_cmd.complete = &wait;
6896 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
6898 ufshcd_send_command(hba, tag);
6900 * ignore the returning value here - ufshcd_check_query_response is
6901 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
6902 * read the response directly ignoring all errors.
6904 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
6906 /* just copy the upiu response as it is */
6907 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
6908 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
6909 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
6910 u16 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
6911 MASK_QUERY_DATA_SEG_LEN;
6913 if (*buff_len >= resp_len) {
6914 memcpy(desc_buff, descp, resp_len);
6915 *buff_len = resp_len;
6918 "%s: rsp size %d is bigger than buffer size %d",
6919 __func__, resp_len, *buff_len);
6924 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
6925 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
6927 up_read(&hba->clk_scaling_lock);
6932 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
6933 * @hba: per-adapter instance
6934 * @req_upiu: upiu request
6935 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands
6936 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
6937 * @desc_buff: pointer to descriptor buffer, NULL if NA
6938 * @buff_len: descriptor size, 0 if NA
6939 * @desc_op: descriptor operation
6941 * Supports UTP Transfer requests (nop and query), and UTP Task
6942 * Management requests.
6943 * It is up to the caller to fill the upiu conent properly, as it will
6944 * be copied without any further input validations.
6946 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
6947 struct utp_upiu_req *req_upiu,
6948 struct utp_upiu_req *rsp_upiu,
6950 u8 *desc_buff, int *buff_len,
6951 enum query_opcode desc_op)
6954 enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
6955 struct utp_task_req_desc treq = { { 0 }, };
6956 enum utp_ocs ocs_value;
6957 u8 tm_f = be32_to_cpu(req_upiu->header.dword_1) >> 16 & MASK_TM_FUNC;
6960 case UPIU_TRANSACTION_NOP_OUT:
6961 cmd_type = DEV_CMD_TYPE_NOP;
6963 case UPIU_TRANSACTION_QUERY_REQ:
6964 ufshcd_hold(hba, false);
6965 mutex_lock(&hba->dev_cmd.lock);
6966 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
6967 desc_buff, buff_len,
6969 mutex_unlock(&hba->dev_cmd.lock);
6970 ufshcd_release(hba);
6973 case UPIU_TRANSACTION_TASK_REQ:
6974 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6975 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6977 memcpy(&treq.upiu_req, req_upiu, sizeof(*req_upiu));
6979 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
6980 if (err == -ETIMEDOUT)
6983 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6984 if (ocs_value != OCS_SUCCESS) {
6985 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
6990 memcpy(rsp_upiu, &treq.upiu_rsp, sizeof(*rsp_upiu));
7003 * ufshcd_eh_device_reset_handler() - Reset a single logical unit.
7004 * @cmd: SCSI command pointer
7006 * Returns SUCCESS/FAILED
7008 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
7010 unsigned long flags, pending_reqs = 0, not_cleared = 0;
7011 struct Scsi_Host *host;
7012 struct ufs_hba *hba;
7017 host = cmd->device->host;
7018 hba = shost_priv(host);
7020 lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
7021 err = ufshcd_issue_tm_cmd(hba, lun, 0, UFS_LOGICAL_RESET, &resp);
7022 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7028 /* clear the commands that were pending for corresponding LUN */
7029 spin_lock_irqsave(&hba->outstanding_lock, flags);
7030 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs)
7031 if (hba->lrb[pos].lun == lun)
7032 __set_bit(pos, &pending_reqs);
7033 hba->outstanding_reqs &= ~pending_reqs;
7034 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7036 if (ufshcd_clear_cmds(hba, pending_reqs) < 0) {
7037 spin_lock_irqsave(&hba->outstanding_lock, flags);
7038 not_cleared = pending_reqs &
7039 ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7040 hba->outstanding_reqs |= not_cleared;
7041 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7043 dev_err(hba->dev, "%s: failed to clear requests %#lx\n",
7044 __func__, not_cleared);
7046 __ufshcd_transfer_req_compl(hba, pending_reqs & ~not_cleared);
7049 hba->req_abort_count = 0;
7050 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, (u32)err);
7054 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7060 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
7062 struct ufshcd_lrb *lrbp;
7065 for_each_set_bit(tag, &bitmap, hba->nutrs) {
7066 lrbp = &hba->lrb[tag];
7067 lrbp->req_abort_skip = true;
7072 * ufshcd_try_to_abort_task - abort a specific task
7073 * @hba: Pointer to adapter instance
7074 * @tag: Task tag/index to be aborted
7076 * Abort the pending command in device by sending UFS_ABORT_TASK task management
7077 * command, and in host controller by clearing the door-bell register. There can
7078 * be race between controller sending the command to the device while abort is
7079 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
7080 * really issued and then try to abort it.
7082 * Returns zero on success, non-zero on failure
7084 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag)
7086 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7092 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
7093 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7094 UFS_QUERY_TASK, &resp);
7095 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
7096 /* cmd pending in the device */
7097 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
7100 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7102 * cmd not pending in the device, check if it is
7105 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
7107 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7108 if (reg & (1 << tag)) {
7109 /* sleep for max. 200us to stabilize */
7110 usleep_range(100, 200);
7113 /* command completed already */
7114 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
7119 "%s: no response from device. tag = %d, err %d\n",
7120 __func__, tag, err);
7122 err = resp; /* service response error */
7132 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7133 UFS_ABORT_TASK, &resp);
7134 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7136 err = resp; /* service response error */
7137 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
7138 __func__, tag, err);
7143 err = ufshcd_clear_cmds(hba, 1U << tag);
7145 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
7146 __func__, tag, err);
7153 * ufshcd_abort - scsi host template eh_abort_handler callback
7154 * @cmd: SCSI command pointer
7156 * Returns SUCCESS/FAILED
7158 static int ufshcd_abort(struct scsi_cmnd *cmd)
7160 struct Scsi_Host *host = cmd->device->host;
7161 struct ufs_hba *hba = shost_priv(host);
7162 int tag = scsi_cmd_to_rq(cmd)->tag;
7163 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7164 unsigned long flags;
7169 WARN_ONCE(tag < 0, "Invalid tag %d\n", tag);
7171 ufshcd_hold(hba, false);
7172 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7173 /* If command is already aborted/completed, return FAILED. */
7174 if (!(test_bit(tag, &hba->outstanding_reqs))) {
7176 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
7177 __func__, tag, hba->outstanding_reqs, reg);
7181 /* Print Transfer Request of aborted task */
7182 dev_info(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
7185 * Print detailed info about aborted request.
7186 * As more than one request might get aborted at the same time,
7187 * print full information only for the first aborted request in order
7188 * to reduce repeated printouts. For other aborted requests only print
7191 scsi_print_command(cmd);
7192 if (!hba->req_abort_count) {
7193 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, tag);
7194 ufshcd_print_evt_hist(hba);
7195 ufshcd_print_host_state(hba);
7196 ufshcd_print_pwr_info(hba);
7197 ufshcd_print_trs(hba, 1 << tag, true);
7199 ufshcd_print_trs(hba, 1 << tag, false);
7201 hba->req_abort_count++;
7203 if (!(reg & (1 << tag))) {
7205 "%s: cmd was completed, but without a notifying intr, tag = %d",
7207 __ufshcd_transfer_req_compl(hba, 1UL << tag);
7212 * Task abort to the device W-LUN is illegal. When this command
7213 * will fail, due to spec violation, scsi err handling next step
7214 * will be to send LU reset which, again, is a spec violation.
7215 * To avoid these unnecessary/illegal steps, first we clean up
7216 * the lrb taken by this cmd and re-set it in outstanding_reqs,
7217 * then queue the eh_work and bail.
7219 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN) {
7220 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, lrbp->lun);
7222 spin_lock_irqsave(host->host_lock, flags);
7223 hba->force_reset = true;
7224 ufshcd_schedule_eh_work(hba);
7225 spin_unlock_irqrestore(host->host_lock, flags);
7229 /* Skip task abort in case previous aborts failed and report failure */
7230 if (lrbp->req_abort_skip) {
7231 dev_err(hba->dev, "%s: skipping abort\n", __func__);
7232 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7236 err = ufshcd_try_to_abort_task(hba, tag);
7238 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7239 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7245 * Clear the corresponding bit from outstanding_reqs since the command
7246 * has been aborted successfully.
7248 spin_lock_irqsave(&hba->outstanding_lock, flags);
7249 outstanding = __test_and_clear_bit(tag, &hba->outstanding_reqs);
7250 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7253 ufshcd_release_scsi_cmd(hba, lrbp);
7258 /* Matches the ufshcd_hold() call at the start of this function. */
7259 ufshcd_release(hba);
7264 * ufshcd_host_reset_and_restore - reset and restore host controller
7265 * @hba: per-adapter instance
7267 * Note that host controller reset may issue DME_RESET to
7268 * local and remote (device) Uni-Pro stack and the attributes
7269 * are reset to default state.
7271 * Returns zero on success, non-zero on failure
7273 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
7278 * Stop the host controller and complete the requests
7281 ufshpb_toggle_state(hba, HPB_PRESENT, HPB_RESET);
7282 ufshcd_hba_stop(hba);
7283 hba->silence_err_logs = true;
7284 ufshcd_complete_requests(hba);
7285 hba->silence_err_logs = false;
7287 /* scale up clocks to max frequency before full reinitialization */
7288 ufshcd_scale_clks(hba, true);
7290 err = ufshcd_hba_enable(hba);
7292 /* Establish the link again and restore the device */
7294 err = ufshcd_probe_hba(hba, false);
7297 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
7298 ufshcd_update_evt_hist(hba, UFS_EVT_HOST_RESET, (u32)err);
7303 * ufshcd_reset_and_restore - reset and re-initialize host/device
7304 * @hba: per-adapter instance
7306 * Reset and recover device, host and re-establish link. This
7307 * is helpful to recover the communication in fatal error conditions.
7309 * Returns zero on success, non-zero on failure
7311 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
7314 u32 saved_uic_err = 0;
7316 unsigned long flags;
7317 int retries = MAX_HOST_RESET_RETRIES;
7319 spin_lock_irqsave(hba->host->host_lock, flags);
7322 * This is a fresh start, cache and clear saved error first,
7323 * in case new error generated during reset and restore.
7325 saved_err |= hba->saved_err;
7326 saved_uic_err |= hba->saved_uic_err;
7328 hba->saved_uic_err = 0;
7329 hba->force_reset = false;
7330 hba->ufshcd_state = UFSHCD_STATE_RESET;
7331 spin_unlock_irqrestore(hba->host->host_lock, flags);
7333 /* Reset the attached device */
7334 ufshcd_device_reset(hba);
7336 err = ufshcd_host_reset_and_restore(hba);
7338 spin_lock_irqsave(hba->host->host_lock, flags);
7341 /* Do not exit unless operational or dead */
7342 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
7343 hba->ufshcd_state != UFSHCD_STATE_ERROR &&
7344 hba->ufshcd_state != UFSHCD_STATE_EH_SCHEDULED_NON_FATAL)
7346 } while (err && --retries);
7349 * Inform scsi mid-layer that we did reset and allow to handle
7350 * Unit Attention properly.
7352 scsi_report_bus_reset(hba->host, 0);
7354 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7355 hba->saved_err |= saved_err;
7356 hba->saved_uic_err |= saved_uic_err;
7358 spin_unlock_irqrestore(hba->host->host_lock, flags);
7364 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
7365 * @cmd: SCSI command pointer
7367 * Returns SUCCESS/FAILED
7369 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
7372 unsigned long flags;
7373 struct ufs_hba *hba;
7375 hba = shost_priv(cmd->device->host);
7377 spin_lock_irqsave(hba->host->host_lock, flags);
7378 hba->force_reset = true;
7379 ufshcd_schedule_eh_work(hba);
7380 dev_err(hba->dev, "%s: reset in progress - 1\n", __func__);
7381 spin_unlock_irqrestore(hba->host->host_lock, flags);
7383 flush_work(&hba->eh_work);
7385 spin_lock_irqsave(hba->host->host_lock, flags);
7386 if (hba->ufshcd_state == UFSHCD_STATE_ERROR)
7388 spin_unlock_irqrestore(hba->host->host_lock, flags);
7394 * ufshcd_get_max_icc_level - calculate the ICC level
7395 * @sup_curr_uA: max. current supported by the regulator
7396 * @start_scan: row at the desc table to start scan from
7397 * @buff: power descriptor buffer
7399 * Returns calculated max ICC level for specific regulator
7401 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan,
7409 for (i = start_scan; i >= 0; i--) {
7410 data = get_unaligned_be16(&buff[2 * i]);
7411 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
7412 ATTR_ICC_LVL_UNIT_OFFSET;
7413 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
7415 case UFSHCD_NANO_AMP:
7416 curr_uA = curr_uA / 1000;
7418 case UFSHCD_MILI_AMP:
7419 curr_uA = curr_uA * 1000;
7422 curr_uA = curr_uA * 1000 * 1000;
7424 case UFSHCD_MICRO_AMP:
7428 if (sup_curr_uA >= curr_uA)
7433 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
7440 * ufshcd_find_max_sup_active_icc_level - calculate the max ICC level
7441 * In case regulators are not initialized we'll return 0
7442 * @hba: per-adapter instance
7443 * @desc_buf: power descriptor buffer to extract ICC levels from.
7444 * @len: length of desc_buff
7446 * Returns calculated ICC level
7448 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
7449 const u8 *desc_buf, int len)
7453 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
7454 !hba->vreg_info.vccq2) {
7456 * Using dev_dbg to avoid messages during runtime PM to avoid
7457 * never-ending cycles of messages written back to storage by
7458 * user space causing runtime resume, causing more messages and
7462 "%s: Regulator capability was not set, actvIccLevel=%d",
7463 __func__, icc_level);
7467 if (hba->vreg_info.vcc->max_uA)
7468 icc_level = ufshcd_get_max_icc_level(
7469 hba->vreg_info.vcc->max_uA,
7470 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
7471 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
7473 if (hba->vreg_info.vccq->max_uA)
7474 icc_level = ufshcd_get_max_icc_level(
7475 hba->vreg_info.vccq->max_uA,
7477 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
7479 if (hba->vreg_info.vccq2->max_uA)
7480 icc_level = ufshcd_get_max_icc_level(
7481 hba->vreg_info.vccq2->max_uA,
7483 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
7488 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba)
7491 int buff_len = hba->desc_size[QUERY_DESC_IDN_POWER];
7495 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7499 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0,
7500 desc_buf, buff_len);
7503 "%s: Failed reading power descriptor.len = %d ret = %d",
7504 __func__, buff_len, ret);
7508 icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf,
7510 dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level);
7512 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7513 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level);
7517 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
7518 __func__, icc_level, ret);
7524 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev)
7526 scsi_autopm_get_device(sdev);
7527 blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev);
7528 if (sdev->rpm_autosuspend)
7529 pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev,
7530 RPM_AUTOSUSPEND_DELAY_MS);
7531 scsi_autopm_put_device(sdev);
7535 * ufshcd_scsi_add_wlus - Adds required W-LUs
7536 * @hba: per-adapter instance
7538 * UFS device specification requires the UFS devices to support 4 well known
7540 * "REPORT_LUNS" (address: 01h)
7541 * "UFS Device" (address: 50h)
7542 * "RPMB" (address: 44h)
7543 * "BOOT" (address: 30h)
7544 * UFS device's power management needs to be controlled by "POWER CONDITION"
7545 * field of SSU (START STOP UNIT) command. But this "power condition" field
7546 * will take effect only when its sent to "UFS device" well known logical unit
7547 * hence we require the scsi_device instance to represent this logical unit in
7548 * order for the UFS host driver to send the SSU command for power management.
7550 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
7551 * Block) LU so user space process can control this LU. User space may also
7552 * want to have access to BOOT LU.
7554 * This function adds scsi device instances for each of all well known LUs
7555 * (except "REPORT LUNS" LU).
7557 * Returns zero on success (all required W-LUs are added successfully),
7558 * non-zero error value on failure (if failed to add any of the required W-LU).
7560 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
7563 struct scsi_device *sdev_boot, *sdev_rpmb;
7565 hba->ufs_device_wlun = __scsi_add_device(hba->host, 0, 0,
7566 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
7567 if (IS_ERR(hba->ufs_device_wlun)) {
7568 ret = PTR_ERR(hba->ufs_device_wlun);
7569 hba->ufs_device_wlun = NULL;
7572 scsi_device_put(hba->ufs_device_wlun);
7574 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
7575 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
7576 if (IS_ERR(sdev_rpmb)) {
7577 ret = PTR_ERR(sdev_rpmb);
7578 goto remove_ufs_device_wlun;
7580 ufshcd_blk_pm_runtime_init(sdev_rpmb);
7581 scsi_device_put(sdev_rpmb);
7583 sdev_boot = __scsi_add_device(hba->host, 0, 0,
7584 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
7585 if (IS_ERR(sdev_boot)) {
7586 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
7588 ufshcd_blk_pm_runtime_init(sdev_boot);
7589 scsi_device_put(sdev_boot);
7593 remove_ufs_device_wlun:
7594 scsi_remove_device(hba->ufs_device_wlun);
7599 static void ufshcd_wb_probe(struct ufs_hba *hba, const u8 *desc_buf)
7601 struct ufs_dev_info *dev_info = &hba->dev_info;
7603 u32 d_lu_wb_buf_alloc;
7604 u32 ext_ufs_feature;
7606 if (!ufshcd_is_wb_allowed(hba))
7610 * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or
7611 * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES
7614 if (!(dev_info->wspecversion >= 0x310 ||
7615 dev_info->wspecversion == 0x220 ||
7616 (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES)))
7619 if (hba->desc_size[QUERY_DESC_IDN_DEVICE] <
7620 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP + 4)
7623 ext_ufs_feature = get_unaligned_be32(desc_buf +
7624 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7626 if (!(ext_ufs_feature & UFS_DEV_WRITE_BOOSTER_SUP))
7630 * WB may be supported but not configured while provisioning. The spec
7631 * says, in dedicated wb buffer mode, a max of 1 lun would have wb
7632 * buffer configured.
7634 dev_info->wb_buffer_type = desc_buf[DEVICE_DESC_PARAM_WB_TYPE];
7636 dev_info->b_presrv_uspc_en =
7637 desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN];
7639 if (dev_info->wb_buffer_type == WB_BUF_MODE_SHARED) {
7640 if (!get_unaligned_be32(desc_buf +
7641 DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS))
7644 for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) {
7645 d_lu_wb_buf_alloc = 0;
7646 ufshcd_read_unit_desc_param(hba,
7648 UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS,
7649 (u8 *)&d_lu_wb_buf_alloc,
7650 sizeof(d_lu_wb_buf_alloc));
7651 if (d_lu_wb_buf_alloc) {
7652 dev_info->wb_dedicated_lu = lun;
7657 if (!d_lu_wb_buf_alloc)
7661 if (!ufshcd_is_wb_buf_lifetime_available(hba))
7667 hba->caps &= ~UFSHCD_CAP_WB_EN;
7670 static void ufshcd_temp_notif_probe(struct ufs_hba *hba, const u8 *desc_buf)
7672 struct ufs_dev_info *dev_info = &hba->dev_info;
7673 u32 ext_ufs_feature;
7676 if (!(hba->caps & UFSHCD_CAP_TEMP_NOTIF) || dev_info->wspecversion < 0x300)
7679 ext_ufs_feature = get_unaligned_be32(desc_buf + DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7681 if (ext_ufs_feature & UFS_DEV_LOW_TEMP_NOTIF)
7682 mask |= MASK_EE_TOO_LOW_TEMP;
7684 if (ext_ufs_feature & UFS_DEV_HIGH_TEMP_NOTIF)
7685 mask |= MASK_EE_TOO_HIGH_TEMP;
7688 ufshcd_enable_ee(hba, mask);
7689 ufs_hwmon_probe(hba, mask);
7693 void ufshcd_fixup_dev_quirks(struct ufs_hba *hba,
7694 const struct ufs_dev_quirk *fixups)
7696 const struct ufs_dev_quirk *f;
7697 struct ufs_dev_info *dev_info = &hba->dev_info;
7702 for (f = fixups; f->quirk; f++) {
7703 if ((f->wmanufacturerid == dev_info->wmanufacturerid ||
7704 f->wmanufacturerid == UFS_ANY_VENDOR) &&
7705 ((dev_info->model &&
7706 STR_PRFX_EQUAL(f->model, dev_info->model)) ||
7707 !strcmp(f->model, UFS_ANY_MODEL)))
7708 hba->dev_quirks |= f->quirk;
7711 EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks);
7713 static void ufs_fixup_device_setup(struct ufs_hba *hba)
7715 /* fix by general quirk table */
7716 ufshcd_fixup_dev_quirks(hba, ufs_fixups);
7718 /* allow vendors to fix quirks */
7719 ufshcd_vops_fixup_dev_quirks(hba);
7722 static int ufs_get_device_desc(struct ufs_hba *hba)
7726 u8 b_ufs_feature_sup;
7728 struct ufs_dev_info *dev_info = &hba->dev_info;
7730 desc_buf = kmalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
7736 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf,
7737 hba->desc_size[QUERY_DESC_IDN_DEVICE]);
7739 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
7745 * getting vendor (manufacturerID) and Bank Index in big endian
7748 dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
7749 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
7751 /* getting Specification Version in big endian format */
7752 dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 |
7753 desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1];
7754 b_ufs_feature_sup = desc_buf[DEVICE_DESC_PARAM_UFS_FEAT];
7756 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
7758 if (dev_info->wspecversion >= UFS_DEV_HPB_SUPPORT_VERSION &&
7759 (b_ufs_feature_sup & UFS_DEV_HPB_SUPPORT)) {
7760 bool hpb_en = false;
7762 ufshpb_get_dev_info(hba, desc_buf);
7764 if (!ufshpb_is_legacy(hba))
7765 err = ufshcd_query_flag_retry(hba,
7766 UPIU_QUERY_OPCODE_READ_FLAG,
7767 QUERY_FLAG_IDN_HPB_EN, 0,
7770 if (ufshpb_is_legacy(hba) || (!err && hpb_en))
7771 dev_info->hpb_enabled = true;
7774 err = ufshcd_read_string_desc(hba, model_index,
7775 &dev_info->model, SD_ASCII_STD);
7777 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
7782 hba->luns_avail = desc_buf[DEVICE_DESC_PARAM_NUM_LU] +
7783 desc_buf[DEVICE_DESC_PARAM_NUM_WLU];
7785 ufs_fixup_device_setup(hba);
7787 ufshcd_wb_probe(hba, desc_buf);
7789 ufshcd_temp_notif_probe(hba, desc_buf);
7792 * ufshcd_read_string_desc returns size of the string
7793 * reset the error value
7802 static void ufs_put_device_desc(struct ufs_hba *hba)
7804 struct ufs_dev_info *dev_info = &hba->dev_info;
7806 kfree(dev_info->model);
7807 dev_info->model = NULL;
7811 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
7812 * @hba: per-adapter instance
7814 * PA_TActivate parameter can be tuned manually if UniPro version is less than
7815 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
7816 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
7817 * the hibern8 exit latency.
7819 * Returns zero on success, non-zero error value on failure.
7821 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
7824 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
7826 ret = ufshcd_dme_peer_get(hba,
7828 RX_MIN_ACTIVATETIME_CAPABILITY,
7829 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7830 &peer_rx_min_activatetime);
7834 /* make sure proper unit conversion is applied */
7835 tuned_pa_tactivate =
7836 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
7837 / PA_TACTIVATE_TIME_UNIT_US);
7838 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7839 tuned_pa_tactivate);
7846 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
7847 * @hba: per-adapter instance
7849 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
7850 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
7851 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
7852 * This optimal value can help reduce the hibern8 exit latency.
7854 * Returns zero on success, non-zero error value on failure.
7856 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
7859 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
7860 u32 max_hibern8_time, tuned_pa_hibern8time;
7862 ret = ufshcd_dme_get(hba,
7863 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
7864 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
7865 &local_tx_hibern8_time_cap);
7869 ret = ufshcd_dme_peer_get(hba,
7870 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
7871 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7872 &peer_rx_hibern8_time_cap);
7876 max_hibern8_time = max(local_tx_hibern8_time_cap,
7877 peer_rx_hibern8_time_cap);
7878 /* make sure proper unit conversion is applied */
7879 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
7880 / PA_HIBERN8_TIME_UNIT_US);
7881 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
7882 tuned_pa_hibern8time);
7888 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
7889 * less than device PA_TACTIVATE time.
7890 * @hba: per-adapter instance
7892 * Some UFS devices require host PA_TACTIVATE to be lower than device
7893 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
7896 * Returns zero on success, non-zero error value on failure.
7898 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
7901 u32 granularity, peer_granularity;
7902 u32 pa_tactivate, peer_pa_tactivate;
7903 u32 pa_tactivate_us, peer_pa_tactivate_us;
7904 static const u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
7906 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7911 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7916 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
7917 (granularity > PA_GRANULARITY_MAX_VAL)) {
7918 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
7919 __func__, granularity);
7923 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
7924 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
7925 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
7926 __func__, peer_granularity);
7930 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
7934 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
7935 &peer_pa_tactivate);
7939 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
7940 peer_pa_tactivate_us = peer_pa_tactivate *
7941 gran_to_us_table[peer_granularity - 1];
7943 if (pa_tactivate_us >= peer_pa_tactivate_us) {
7944 u32 new_peer_pa_tactivate;
7946 new_peer_pa_tactivate = pa_tactivate_us /
7947 gran_to_us_table[peer_granularity - 1];
7948 new_peer_pa_tactivate++;
7949 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7950 new_peer_pa_tactivate);
7957 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
7959 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
7960 ufshcd_tune_pa_tactivate(hba);
7961 ufshcd_tune_pa_hibern8time(hba);
7964 ufshcd_vops_apply_dev_quirks(hba);
7966 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
7967 /* set 1ms timeout for PA_TACTIVATE */
7968 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
7970 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
7971 ufshcd_quirk_tune_host_pa_tactivate(hba);
7974 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
7976 hba->ufs_stats.hibern8_exit_cnt = 0;
7977 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
7978 hba->req_abort_count = 0;
7981 static int ufshcd_device_geo_params_init(struct ufs_hba *hba)
7987 buff_len = hba->desc_size[QUERY_DESC_IDN_GEOMETRY];
7988 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7994 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0,
7995 desc_buf, buff_len);
7997 dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n",
8002 if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1)
8003 hba->dev_info.max_lu_supported = 32;
8004 else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0)
8005 hba->dev_info.max_lu_supported = 8;
8007 if (hba->desc_size[QUERY_DESC_IDN_GEOMETRY] >=
8008 GEOMETRY_DESC_PARAM_HPB_MAX_ACTIVE_REGS)
8009 ufshpb_get_geo_info(hba, desc_buf);
8016 struct ufs_ref_clk {
8017 unsigned long freq_hz;
8018 enum ufs_ref_clk_freq val;
8021 static const struct ufs_ref_clk ufs_ref_clk_freqs[] = {
8022 {19200000, REF_CLK_FREQ_19_2_MHZ},
8023 {26000000, REF_CLK_FREQ_26_MHZ},
8024 {38400000, REF_CLK_FREQ_38_4_MHZ},
8025 {52000000, REF_CLK_FREQ_52_MHZ},
8026 {0, REF_CLK_FREQ_INVAL},
8029 static enum ufs_ref_clk_freq
8030 ufs_get_bref_clk_from_hz(unsigned long freq)
8034 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
8035 if (ufs_ref_clk_freqs[i].freq_hz == freq)
8036 return ufs_ref_clk_freqs[i].val;
8038 return REF_CLK_FREQ_INVAL;
8041 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
8045 freq = clk_get_rate(refclk);
8047 hba->dev_ref_clk_freq =
8048 ufs_get_bref_clk_from_hz(freq);
8050 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
8052 "invalid ref_clk setting = %ld\n", freq);
8055 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
8059 u32 freq = hba->dev_ref_clk_freq;
8061 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
8062 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
8065 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
8070 if (ref_clk == freq)
8071 goto out; /* nothing to update */
8073 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
8074 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
8077 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
8078 ufs_ref_clk_freqs[freq].freq_hz);
8082 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
8083 ufs_ref_clk_freqs[freq].freq_hz);
8089 static int ufshcd_device_params_init(struct ufs_hba *hba)
8094 /* Init device descriptor sizes */
8095 for (i = 0; i < QUERY_DESC_IDN_MAX; i++)
8096 hba->desc_size[i] = QUERY_DESC_MAX_SIZE;
8098 /* Init UFS geometry descriptor related parameters */
8099 ret = ufshcd_device_geo_params_init(hba);
8103 /* Check and apply UFS device quirks */
8104 ret = ufs_get_device_desc(hba);
8106 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
8111 ufshcd_get_ref_clk_gating_wait(hba);
8113 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
8114 QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag))
8115 hba->dev_info.f_power_on_wp_en = flag;
8117 /* Probe maximum power mode co-supported by both UFS host and device */
8118 if (ufshcd_get_max_pwr_mode(hba))
8120 "%s: Failed getting max supported power mode\n",
8127 * ufshcd_add_lus - probe and add UFS logical units
8128 * @hba: per-adapter instance
8130 static int ufshcd_add_lus(struct ufs_hba *hba)
8134 /* Add required well known logical units to scsi mid layer */
8135 ret = ufshcd_scsi_add_wlus(hba);
8139 /* Initialize devfreq after UFS device is detected */
8140 if (ufshcd_is_clkscaling_supported(hba)) {
8141 memcpy(&hba->clk_scaling.saved_pwr_info.info,
8143 sizeof(struct ufs_pa_layer_attr));
8144 hba->clk_scaling.saved_pwr_info.is_valid = true;
8145 hba->clk_scaling.is_allowed = true;
8147 ret = ufshcd_devfreq_init(hba);
8151 hba->clk_scaling.is_enabled = true;
8152 ufshcd_init_clk_scaling_sysfs(hba);
8157 scsi_scan_host(hba->host);
8158 pm_runtime_put_sync(hba->dev);
8165 * ufshcd_probe_hba - probe hba to detect device and initialize it
8166 * @hba: per-adapter instance
8167 * @init_dev_params: whether or not to call ufshcd_device_params_init().
8169 * Execute link-startup and verify device initialization
8171 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params)
8174 unsigned long flags;
8175 ktime_t start = ktime_get();
8177 hba->ufshcd_state = UFSHCD_STATE_RESET;
8179 ret = ufshcd_link_startup(hba);
8183 if (hba->quirks & UFSHCD_QUIRK_SKIP_PH_CONFIGURATION)
8186 /* Debug counters initialization */
8187 ufshcd_clear_dbg_ufs_stats(hba);
8189 /* UniPro link is active now */
8190 ufshcd_set_link_active(hba);
8192 /* Verify device initialization by sending NOP OUT UPIU */
8193 ret = ufshcd_verify_dev_init(hba);
8197 /* Initiate UFS initialization, and waiting until completion */
8198 ret = ufshcd_complete_dev_init(hba);
8203 * Initialize UFS device parameters used by driver, these
8204 * parameters are associated with UFS descriptors.
8206 if (init_dev_params) {
8207 ret = ufshcd_device_params_init(hba);
8212 ufshcd_tune_unipro_params(hba);
8214 /* UFS device is also active now */
8215 ufshcd_set_ufs_dev_active(hba);
8216 ufshcd_force_reset_auto_bkops(hba);
8218 /* Gear up to HS gear if supported */
8219 if (hba->max_pwr_info.is_valid) {
8221 * Set the right value to bRefClkFreq before attempting to
8222 * switch to HS gears.
8224 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
8225 ufshcd_set_dev_ref_clk(hba);
8226 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
8228 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
8232 ufshcd_print_pwr_info(hba);
8236 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec)
8237 * and for removable UFS card as well, hence always set the parameter.
8238 * Note: Error handler may issue the device reset hence resetting
8239 * bActiveICCLevel as well so it is always safe to set this here.
8241 ufshcd_set_active_icc_lvl(hba);
8243 /* Enable UFS Write Booster if supported */
8244 ufshcd_configure_wb(hba);
8246 if (hba->ee_usr_mask)
8247 ufshcd_write_ee_control(hba);
8248 /* Enable Auto-Hibernate if configured */
8249 ufshcd_auto_hibern8_enable(hba);
8251 ufshpb_toggle_state(hba, HPB_RESET, HPB_PRESENT);
8253 spin_lock_irqsave(hba->host->host_lock, flags);
8255 hba->ufshcd_state = UFSHCD_STATE_ERROR;
8256 else if (hba->ufshcd_state == UFSHCD_STATE_RESET)
8257 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
8258 spin_unlock_irqrestore(hba->host->host_lock, flags);
8260 trace_ufshcd_init(dev_name(hba->dev), ret,
8261 ktime_to_us(ktime_sub(ktime_get(), start)),
8262 hba->curr_dev_pwr_mode, hba->uic_link_state);
8267 * ufshcd_async_scan - asynchronous execution for probing hba
8268 * @data: data pointer to pass to this function
8269 * @cookie: cookie data
8271 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
8273 struct ufs_hba *hba = (struct ufs_hba *)data;
8276 down(&hba->host_sem);
8277 /* Initialize hba, detect and initialize UFS device */
8278 ret = ufshcd_probe_hba(hba, true);
8283 /* Probe and add UFS logical units */
8284 ret = ufshcd_add_lus(hba);
8287 * If we failed to initialize the device or the device is not
8288 * present, turn off the power/clocks etc.
8291 pm_runtime_put_sync(hba->dev);
8292 ufshcd_hba_exit(hba);
8296 static const struct attribute_group *ufshcd_driver_groups[] = {
8297 &ufs_sysfs_unit_descriptor_group,
8298 &ufs_sysfs_lun_attributes_group,
8299 #ifdef CONFIG_SCSI_UFS_HPB
8300 &ufs_sysfs_hpb_stat_group,
8301 &ufs_sysfs_hpb_param_group,
8306 static struct ufs_hba_variant_params ufs_hba_vps = {
8307 .hba_enable_delay_us = 1000,
8308 .wb_flush_threshold = UFS_WB_BUF_REMAIN_PERCENT(40),
8309 .devfreq_profile.polling_ms = 100,
8310 .devfreq_profile.target = ufshcd_devfreq_target,
8311 .devfreq_profile.get_dev_status = ufshcd_devfreq_get_dev_status,
8312 .ondemand_data.upthreshold = 70,
8313 .ondemand_data.downdifferential = 5,
8316 static struct scsi_host_template ufshcd_driver_template = {
8317 .module = THIS_MODULE,
8319 .proc_name = UFSHCD,
8320 .map_queues = ufshcd_map_queues,
8321 .queuecommand = ufshcd_queuecommand,
8322 .mq_poll = ufshcd_poll,
8323 .slave_alloc = ufshcd_slave_alloc,
8324 .slave_configure = ufshcd_slave_configure,
8325 .slave_destroy = ufshcd_slave_destroy,
8326 .change_queue_depth = ufshcd_change_queue_depth,
8327 .eh_abort_handler = ufshcd_abort,
8328 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
8329 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
8331 .sg_tablesize = SG_ALL,
8332 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
8333 .can_queue = UFSHCD_CAN_QUEUE,
8334 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX,
8335 .max_sectors = (1 << 20) / SECTOR_SIZE, /* 1 MiB */
8336 .max_host_blocked = 1,
8337 .track_queue_depth = 1,
8338 .sdev_groups = ufshcd_driver_groups,
8339 .dma_boundary = PAGE_SIZE - 1,
8340 .rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS,
8343 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
8352 * "set_load" operation shall be required on those regulators
8353 * which specifically configured current limitation. Otherwise
8354 * zero max_uA may cause unexpected behavior when regulator is
8355 * enabled or set as high power mode.
8360 ret = regulator_set_load(vreg->reg, ua);
8362 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
8363 __func__, vreg->name, ua, ret);
8369 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
8370 struct ufs_vreg *vreg)
8372 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
8375 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
8376 struct ufs_vreg *vreg)
8381 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
8384 static int ufshcd_config_vreg(struct device *dev,
8385 struct ufs_vreg *vreg, bool on)
8387 if (regulator_count_voltages(vreg->reg) <= 0)
8390 return ufshcd_config_vreg_load(dev, vreg, on ? vreg->max_uA : 0);
8393 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
8397 if (!vreg || vreg->enabled)
8400 ret = ufshcd_config_vreg(dev, vreg, true);
8402 ret = regulator_enable(vreg->reg);
8405 vreg->enabled = true;
8407 dev_err(dev, "%s: %s enable failed, err=%d\n",
8408 __func__, vreg->name, ret);
8413 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
8417 if (!vreg || !vreg->enabled || vreg->always_on)
8420 ret = regulator_disable(vreg->reg);
8423 /* ignore errors on applying disable config */
8424 ufshcd_config_vreg(dev, vreg, false);
8425 vreg->enabled = false;
8427 dev_err(dev, "%s: %s disable failed, err=%d\n",
8428 __func__, vreg->name, ret);
8434 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
8437 struct device *dev = hba->dev;
8438 struct ufs_vreg_info *info = &hba->vreg_info;
8440 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
8444 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
8448 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
8452 ufshcd_toggle_vreg(dev, info->vccq2, false);
8453 ufshcd_toggle_vreg(dev, info->vccq, false);
8454 ufshcd_toggle_vreg(dev, info->vcc, false);
8459 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
8461 struct ufs_vreg_info *info = &hba->vreg_info;
8463 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
8466 int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
8473 vreg->reg = devm_regulator_get(dev, vreg->name);
8474 if (IS_ERR(vreg->reg)) {
8475 ret = PTR_ERR(vreg->reg);
8476 dev_err(dev, "%s: %s get failed, err=%d\n",
8477 __func__, vreg->name, ret);
8482 EXPORT_SYMBOL_GPL(ufshcd_get_vreg);
8484 static int ufshcd_init_vreg(struct ufs_hba *hba)
8487 struct device *dev = hba->dev;
8488 struct ufs_vreg_info *info = &hba->vreg_info;
8490 ret = ufshcd_get_vreg(dev, info->vcc);
8494 ret = ufshcd_get_vreg(dev, info->vccq);
8496 ret = ufshcd_get_vreg(dev, info->vccq2);
8501 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
8503 struct ufs_vreg_info *info = &hba->vreg_info;
8505 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
8508 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
8511 struct ufs_clk_info *clki;
8512 struct list_head *head = &hba->clk_list_head;
8513 unsigned long flags;
8514 ktime_t start = ktime_get();
8515 bool clk_state_changed = false;
8517 if (list_empty(head))
8520 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
8524 list_for_each_entry(clki, head, list) {
8525 if (!IS_ERR_OR_NULL(clki->clk)) {
8527 * Don't disable clocks which are needed
8528 * to keep the link active.
8530 if (ufshcd_is_link_active(hba) &&
8531 clki->keep_link_active)
8534 clk_state_changed = on ^ clki->enabled;
8535 if (on && !clki->enabled) {
8536 ret = clk_prepare_enable(clki->clk);
8538 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
8539 __func__, clki->name, ret);
8542 } else if (!on && clki->enabled) {
8543 clk_disable_unprepare(clki->clk);
8546 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
8547 clki->name, on ? "en" : "dis");
8551 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
8557 list_for_each_entry(clki, head, list) {
8558 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
8559 clk_disable_unprepare(clki->clk);
8561 } else if (!ret && on) {
8562 spin_lock_irqsave(hba->host->host_lock, flags);
8563 hba->clk_gating.state = CLKS_ON;
8564 trace_ufshcd_clk_gating(dev_name(hba->dev),
8565 hba->clk_gating.state);
8566 spin_unlock_irqrestore(hba->host->host_lock, flags);
8569 if (clk_state_changed)
8570 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
8571 (on ? "on" : "off"),
8572 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
8576 static enum ufs_ref_clk_freq ufshcd_parse_ref_clk_property(struct ufs_hba *hba)
8579 int ret = device_property_read_u32(hba->dev, "ref-clk-freq", &freq);
8582 dev_dbg(hba->dev, "Cannot query 'ref-clk-freq' property = %d", ret);
8583 return REF_CLK_FREQ_INVAL;
8586 return ufs_get_bref_clk_from_hz(freq);
8589 static int ufshcd_init_clocks(struct ufs_hba *hba)
8592 struct ufs_clk_info *clki;
8593 struct device *dev = hba->dev;
8594 struct list_head *head = &hba->clk_list_head;
8596 if (list_empty(head))
8599 list_for_each_entry(clki, head, list) {
8603 clki->clk = devm_clk_get(dev, clki->name);
8604 if (IS_ERR(clki->clk)) {
8605 ret = PTR_ERR(clki->clk);
8606 dev_err(dev, "%s: %s clk get failed, %d\n",
8607 __func__, clki->name, ret);
8612 * Parse device ref clk freq as per device tree "ref_clk".
8613 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
8614 * in ufshcd_alloc_host().
8616 if (!strcmp(clki->name, "ref_clk"))
8617 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
8619 if (clki->max_freq) {
8620 ret = clk_set_rate(clki->clk, clki->max_freq);
8622 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
8623 __func__, clki->name,
8624 clki->max_freq, ret);
8627 clki->curr_freq = clki->max_freq;
8629 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
8630 clki->name, clk_get_rate(clki->clk));
8636 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
8643 err = ufshcd_vops_init(hba);
8645 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
8646 __func__, ufshcd_get_var_name(hba), err);
8651 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
8656 ufshcd_vops_exit(hba);
8659 static int ufshcd_hba_init(struct ufs_hba *hba)
8664 * Handle host controller power separately from the UFS device power
8665 * rails as it will help controlling the UFS host controller power
8666 * collapse easily which is different than UFS device power collapse.
8667 * Also, enable the host controller power before we go ahead with rest
8668 * of the initialization here.
8670 err = ufshcd_init_hba_vreg(hba);
8674 err = ufshcd_setup_hba_vreg(hba, true);
8678 err = ufshcd_init_clocks(hba);
8680 goto out_disable_hba_vreg;
8682 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
8683 hba->dev_ref_clk_freq = ufshcd_parse_ref_clk_property(hba);
8685 err = ufshcd_setup_clocks(hba, true);
8687 goto out_disable_hba_vreg;
8689 err = ufshcd_init_vreg(hba);
8691 goto out_disable_clks;
8693 err = ufshcd_setup_vreg(hba, true);
8695 goto out_disable_clks;
8697 err = ufshcd_variant_hba_init(hba);
8699 goto out_disable_vreg;
8701 ufs_debugfs_hba_init(hba);
8703 hba->is_powered = true;
8707 ufshcd_setup_vreg(hba, false);
8709 ufshcd_setup_clocks(hba, false);
8710 out_disable_hba_vreg:
8711 ufshcd_setup_hba_vreg(hba, false);
8716 static void ufshcd_hba_exit(struct ufs_hba *hba)
8718 if (hba->is_powered) {
8719 ufshcd_exit_clk_scaling(hba);
8720 ufshcd_exit_clk_gating(hba);
8722 destroy_workqueue(hba->eh_wq);
8723 ufs_debugfs_hba_exit(hba);
8724 ufshcd_variant_hba_exit(hba);
8725 ufshcd_setup_vreg(hba, false);
8726 ufshcd_setup_clocks(hba, false);
8727 ufshcd_setup_hba_vreg(hba, false);
8728 hba->is_powered = false;
8729 ufs_put_device_desc(hba);
8734 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
8736 * @hba: per adapter instance
8737 * @pwr_mode: device power mode to set
8739 * Returns 0 if requested power mode is set successfully
8740 * Returns < 0 if failed to set the requested power mode
8742 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
8743 enum ufs_dev_pwr_mode pwr_mode)
8745 unsigned char cmd[6] = { START_STOP };
8746 struct scsi_sense_hdr sshdr;
8747 struct scsi_device *sdp;
8748 unsigned long flags;
8750 unsigned long deadline;
8753 spin_lock_irqsave(hba->host->host_lock, flags);
8754 sdp = hba->ufs_device_wlun;
8756 ret = scsi_device_get(sdp);
8757 if (!ret && !scsi_device_online(sdp)) {
8759 scsi_device_put(sdp);
8764 spin_unlock_irqrestore(hba->host->host_lock, flags);
8770 * If scsi commands fail, the scsi mid-layer schedules scsi error-
8771 * handling, which would wait for host to be resumed. Since we know
8772 * we are functional while we are here, skip host resume in error
8775 hba->host->eh_noresume = 1;
8777 cmd[4] = pwr_mode << 4;
8780 * Current function would be generally called from the power management
8781 * callbacks hence set the RQF_PM flag so that it doesn't resume the
8782 * already suspended childs.
8784 deadline = jiffies + 10 * HZ;
8785 for (retries = 3; retries > 0; --retries) {
8787 remaining = deadline - jiffies;
8790 ret = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, &sshdr,
8791 remaining / HZ, 0, 0, RQF_PM, NULL);
8792 if (!scsi_status_is_check_condition(ret) ||
8793 !scsi_sense_valid(&sshdr) ||
8794 sshdr.sense_key != UNIT_ATTENTION)
8798 sdev_printk(KERN_WARNING, sdp,
8799 "START_STOP failed for power mode: %d, result %x\n",
8802 if (scsi_sense_valid(&sshdr))
8803 scsi_print_sense_hdr(sdp, NULL, &sshdr);
8809 hba->curr_dev_pwr_mode = pwr_mode;
8811 scsi_device_put(sdp);
8812 hba->host->eh_noresume = 0;
8816 static int ufshcd_link_state_transition(struct ufs_hba *hba,
8817 enum uic_link_state req_link_state,
8818 int check_for_bkops)
8822 if (req_link_state == hba->uic_link_state)
8825 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
8826 ret = ufshcd_uic_hibern8_enter(hba);
8828 ufshcd_set_link_hibern8(hba);
8830 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8836 * If autobkops is enabled, link can't be turned off because
8837 * turning off the link would also turn off the device, except in the
8838 * case of DeepSleep where the device is expected to remain powered.
8840 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
8841 (!check_for_bkops || !hba->auto_bkops_enabled)) {
8843 * Let's make sure that link is in low power mode, we are doing
8844 * this currently by putting the link in Hibern8. Otherway to
8845 * put the link in low power mode is to send the DME end point
8846 * to device and then send the DME reset command to local
8847 * unipro. But putting the link in hibern8 is much faster.
8849 * Note also that putting the link in Hibern8 is a requirement
8850 * for entering DeepSleep.
8852 ret = ufshcd_uic_hibern8_enter(hba);
8854 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8859 * Change controller state to "reset state" which
8860 * should also put the link in off/reset state
8862 ufshcd_hba_stop(hba);
8864 * TODO: Check if we need any delay to make sure that
8865 * controller is reset
8867 ufshcd_set_link_off(hba);
8874 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
8876 bool vcc_off = false;
8879 * It seems some UFS devices may keep drawing more than sleep current
8880 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
8881 * To avoid this situation, add 2ms delay before putting these UFS
8882 * rails in LPM mode.
8884 if (!ufshcd_is_link_active(hba) &&
8885 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
8886 usleep_range(2000, 2100);
8889 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
8892 * If UFS device and link is in OFF state, all power supplies (VCC,
8893 * VCCQ, VCCQ2) can be turned off if power on write protect is not
8894 * required. If UFS link is inactive (Hibern8 or OFF state) and device
8895 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
8897 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
8898 * in low power state which would save some power.
8900 * If Write Booster is enabled and the device needs to flush the WB
8901 * buffer OR if bkops status is urgent for WB, keep Vcc on.
8903 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8904 !hba->dev_info.is_lu_power_on_wp) {
8905 ufshcd_setup_vreg(hba, false);
8907 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8908 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8910 if (ufshcd_is_link_hibern8(hba) || ufshcd_is_link_off(hba)) {
8911 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8912 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
8917 * Some UFS devices require delay after VCC power rail is turned-off.
8919 if (vcc_off && hba->vreg_info.vcc &&
8920 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_AFTER_LPM)
8921 usleep_range(5000, 5100);
8925 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
8929 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8930 !hba->dev_info.is_lu_power_on_wp) {
8931 ret = ufshcd_setup_vreg(hba, true);
8932 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8933 if (!ufshcd_is_link_active(hba)) {
8934 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
8937 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
8941 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
8946 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8948 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8952 #endif /* CONFIG_PM */
8954 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
8956 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
8957 ufshcd_setup_hba_vreg(hba, false);
8960 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
8962 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
8963 ufshcd_setup_hba_vreg(hba, true);
8966 static int __ufshcd_wl_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8969 int check_for_bkops;
8970 enum ufs_pm_level pm_lvl;
8971 enum ufs_dev_pwr_mode req_dev_pwr_mode;
8972 enum uic_link_state req_link_state;
8974 hba->pm_op_in_progress = true;
8975 if (pm_op != UFS_SHUTDOWN_PM) {
8976 pm_lvl = pm_op == UFS_RUNTIME_PM ?
8977 hba->rpm_lvl : hba->spm_lvl;
8978 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
8979 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
8981 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
8982 req_link_state = UIC_LINK_OFF_STATE;
8985 ufshpb_suspend(hba);
8988 * If we can't transition into any of the low power modes
8989 * just gate the clocks.
8991 ufshcd_hold(hba, false);
8992 hba->clk_gating.is_suspended = true;
8994 if (ufshcd_is_clkscaling_supported(hba))
8995 ufshcd_clk_scaling_suspend(hba, true);
8997 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
8998 req_link_state == UIC_LINK_ACTIVE_STATE) {
9002 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
9003 (req_link_state == hba->uic_link_state))
9004 goto enable_scaling;
9006 /* UFS device & link must be active before we enter in this function */
9007 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
9009 goto enable_scaling;
9012 if (pm_op == UFS_RUNTIME_PM) {
9013 if (ufshcd_can_autobkops_during_suspend(hba)) {
9015 * The device is idle with no requests in the queue,
9016 * allow background operations if bkops status shows
9017 * that performance might be impacted.
9019 ret = ufshcd_urgent_bkops(hba);
9021 goto enable_scaling;
9023 /* make sure that auto bkops is disabled */
9024 ufshcd_disable_auto_bkops(hba);
9027 * If device needs to do BKOP or WB buffer flush during
9028 * Hibern8, keep device power mode as "active power mode"
9031 hba->dev_info.b_rpm_dev_flush_capable =
9032 hba->auto_bkops_enabled ||
9033 (((req_link_state == UIC_LINK_HIBERN8_STATE) ||
9034 ((req_link_state == UIC_LINK_ACTIVE_STATE) &&
9035 ufshcd_is_auto_hibern8_enabled(hba))) &&
9036 ufshcd_wb_need_flush(hba));
9039 flush_work(&hba->eeh_work);
9041 ret = ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
9043 goto enable_scaling;
9045 if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) {
9046 if (pm_op != UFS_RUNTIME_PM)
9047 /* ensure that bkops is disabled */
9048 ufshcd_disable_auto_bkops(hba);
9050 if (!hba->dev_info.b_rpm_dev_flush_capable) {
9051 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
9053 goto enable_scaling;
9058 * In the case of DeepSleep, the device is expected to remain powered
9059 * with the link off, so do not check for bkops.
9061 check_for_bkops = !ufshcd_is_ufs_dev_deepsleep(hba);
9062 ret = ufshcd_link_state_transition(hba, req_link_state, check_for_bkops);
9064 goto set_dev_active;
9068 * Call vendor specific suspend callback. As these callbacks may access
9069 * vendor specific host controller register space call them before the
9070 * host clocks are ON.
9072 ret = ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
9074 goto set_link_active;
9079 * Device hardware reset is required to exit DeepSleep. Also, for
9080 * DeepSleep, the link is off so host reset and restore will be done
9083 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
9084 ufshcd_device_reset(hba);
9085 WARN_ON(!ufshcd_is_link_off(hba));
9087 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
9088 ufshcd_set_link_active(hba);
9089 else if (ufshcd_is_link_off(hba))
9090 ufshcd_host_reset_and_restore(hba);
9092 /* Can also get here needing to exit DeepSleep */
9093 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
9094 ufshcd_device_reset(hba);
9095 ufshcd_host_reset_and_restore(hba);
9097 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
9098 ufshcd_disable_auto_bkops(hba);
9100 if (ufshcd_is_clkscaling_supported(hba))
9101 ufshcd_clk_scaling_suspend(hba, false);
9103 hba->dev_info.b_rpm_dev_flush_capable = false;
9105 if (hba->dev_info.b_rpm_dev_flush_capable) {
9106 schedule_delayed_work(&hba->rpm_dev_flush_recheck_work,
9107 msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS));
9111 ufshcd_update_evt_hist(hba, UFS_EVT_WL_SUSP_ERR, (u32)ret);
9112 hba->clk_gating.is_suspended = false;
9113 ufshcd_release(hba);
9116 hba->pm_op_in_progress = false;
9121 static int __ufshcd_wl_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
9124 enum uic_link_state old_link_state = hba->uic_link_state;
9126 hba->pm_op_in_progress = true;
9129 * Call vendor specific resume callback. As these callbacks may access
9130 * vendor specific host controller register space call them when the
9131 * host clocks are ON.
9133 ret = ufshcd_vops_resume(hba, pm_op);
9137 /* For DeepSleep, the only supported option is to have the link off */
9138 WARN_ON(ufshcd_is_ufs_dev_deepsleep(hba) && !ufshcd_is_link_off(hba));
9140 if (ufshcd_is_link_hibern8(hba)) {
9141 ret = ufshcd_uic_hibern8_exit(hba);
9143 ufshcd_set_link_active(hba);
9145 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
9147 goto vendor_suspend;
9149 } else if (ufshcd_is_link_off(hba)) {
9151 * A full initialization of the host and the device is
9152 * required since the link was put to off during suspend.
9153 * Note, in the case of DeepSleep, the device will exit
9154 * DeepSleep due to device reset.
9156 ret = ufshcd_reset_and_restore(hba);
9158 * ufshcd_reset_and_restore() should have already
9159 * set the link state as active
9161 if (ret || !ufshcd_is_link_active(hba))
9162 goto vendor_suspend;
9165 if (!ufshcd_is_ufs_dev_active(hba)) {
9166 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
9168 goto set_old_link_state;
9171 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
9172 ufshcd_enable_auto_bkops(hba);
9175 * If BKOPs operations are urgently needed at this moment then
9176 * keep auto-bkops enabled or else disable it.
9178 ufshcd_urgent_bkops(hba);
9180 if (hba->ee_usr_mask)
9181 ufshcd_write_ee_control(hba);
9183 if (ufshcd_is_clkscaling_supported(hba))
9184 ufshcd_clk_scaling_suspend(hba, false);
9186 if (hba->dev_info.b_rpm_dev_flush_capable) {
9187 hba->dev_info.b_rpm_dev_flush_capable = false;
9188 cancel_delayed_work(&hba->rpm_dev_flush_recheck_work);
9191 /* Enable Auto-Hibernate if configured */
9192 ufshcd_auto_hibern8_enable(hba);
9198 ufshcd_link_state_transition(hba, old_link_state, 0);
9200 ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
9201 ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
9204 ufshcd_update_evt_hist(hba, UFS_EVT_WL_RES_ERR, (u32)ret);
9205 hba->clk_gating.is_suspended = false;
9206 ufshcd_release(hba);
9207 hba->pm_op_in_progress = false;
9211 static int ufshcd_wl_runtime_suspend(struct device *dev)
9213 struct scsi_device *sdev = to_scsi_device(dev);
9214 struct ufs_hba *hba;
9216 ktime_t start = ktime_get();
9218 hba = shost_priv(sdev->host);
9220 ret = __ufshcd_wl_suspend(hba, UFS_RUNTIME_PM);
9222 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9224 trace_ufshcd_wl_runtime_suspend(dev_name(dev), ret,
9225 ktime_to_us(ktime_sub(ktime_get(), start)),
9226 hba->curr_dev_pwr_mode, hba->uic_link_state);
9231 static int ufshcd_wl_runtime_resume(struct device *dev)
9233 struct scsi_device *sdev = to_scsi_device(dev);
9234 struct ufs_hba *hba;
9236 ktime_t start = ktime_get();
9238 hba = shost_priv(sdev->host);
9240 ret = __ufshcd_wl_resume(hba, UFS_RUNTIME_PM);
9242 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9244 trace_ufshcd_wl_runtime_resume(dev_name(dev), ret,
9245 ktime_to_us(ktime_sub(ktime_get(), start)),
9246 hba->curr_dev_pwr_mode, hba->uic_link_state);
9252 #ifdef CONFIG_PM_SLEEP
9253 static int ufshcd_wl_suspend(struct device *dev)
9255 struct scsi_device *sdev = to_scsi_device(dev);
9256 struct ufs_hba *hba;
9258 ktime_t start = ktime_get();
9260 hba = shost_priv(sdev->host);
9261 down(&hba->host_sem);
9263 if (pm_runtime_suspended(dev))
9266 ret = __ufshcd_wl_suspend(hba, UFS_SYSTEM_PM);
9268 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9274 hba->is_sys_suspended = true;
9275 trace_ufshcd_wl_suspend(dev_name(dev), ret,
9276 ktime_to_us(ktime_sub(ktime_get(), start)),
9277 hba->curr_dev_pwr_mode, hba->uic_link_state);
9282 static int ufshcd_wl_resume(struct device *dev)
9284 struct scsi_device *sdev = to_scsi_device(dev);
9285 struct ufs_hba *hba;
9287 ktime_t start = ktime_get();
9289 hba = shost_priv(sdev->host);
9291 if (pm_runtime_suspended(dev))
9294 ret = __ufshcd_wl_resume(hba, UFS_SYSTEM_PM);
9296 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9298 trace_ufshcd_wl_resume(dev_name(dev), ret,
9299 ktime_to_us(ktime_sub(ktime_get(), start)),
9300 hba->curr_dev_pwr_mode, hba->uic_link_state);
9302 hba->is_sys_suspended = false;
9308 static void ufshcd_wl_shutdown(struct device *dev)
9310 struct scsi_device *sdev = to_scsi_device(dev);
9311 struct ufs_hba *hba;
9313 hba = shost_priv(sdev->host);
9315 down(&hba->host_sem);
9316 hba->shutting_down = true;
9319 /* Turn on everything while shutting down */
9320 ufshcd_rpm_get_sync(hba);
9321 scsi_device_quiesce(sdev);
9322 shost_for_each_device(sdev, hba->host) {
9323 if (sdev == hba->ufs_device_wlun)
9325 scsi_device_quiesce(sdev);
9327 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
9331 * ufshcd_suspend - helper function for suspend operations
9332 * @hba: per adapter instance
9334 * This function will put disable irqs, turn off clocks
9335 * and set vreg and hba-vreg in lpm mode.
9337 static int ufshcd_suspend(struct ufs_hba *hba)
9341 if (!hba->is_powered)
9344 * Disable the host irq as host controller as there won't be any
9345 * host controller transaction expected till resume.
9347 ufshcd_disable_irq(hba);
9348 ret = ufshcd_setup_clocks(hba, false);
9350 ufshcd_enable_irq(hba);
9353 if (ufshcd_is_clkgating_allowed(hba)) {
9354 hba->clk_gating.state = CLKS_OFF;
9355 trace_ufshcd_clk_gating(dev_name(hba->dev),
9356 hba->clk_gating.state);
9359 ufshcd_vreg_set_lpm(hba);
9360 /* Put the host controller in low power mode if possible */
9361 ufshcd_hba_vreg_set_lpm(hba);
9367 * ufshcd_resume - helper function for resume operations
9368 * @hba: per adapter instance
9370 * This function basically turns on the regulators, clocks and
9373 * Returns 0 for success and non-zero for failure
9375 static int ufshcd_resume(struct ufs_hba *hba)
9379 if (!hba->is_powered)
9382 ufshcd_hba_vreg_set_hpm(hba);
9383 ret = ufshcd_vreg_set_hpm(hba);
9387 /* Make sure clocks are enabled before accessing controller */
9388 ret = ufshcd_setup_clocks(hba, true);
9392 /* enable the host irq as host controller would be active soon */
9393 ufshcd_enable_irq(hba);
9397 ufshcd_vreg_set_lpm(hba);
9400 ufshcd_update_evt_hist(hba, UFS_EVT_RESUME_ERR, (u32)ret);
9403 #endif /* CONFIG_PM */
9405 #ifdef CONFIG_PM_SLEEP
9407 * ufshcd_system_suspend - system suspend callback
9408 * @dev: Device associated with the UFS controller.
9410 * Executed before putting the system into a sleep state in which the contents
9411 * of main memory are preserved.
9413 * Returns 0 for success and non-zero for failure
9415 int ufshcd_system_suspend(struct device *dev)
9417 struct ufs_hba *hba = dev_get_drvdata(dev);
9419 ktime_t start = ktime_get();
9421 if (pm_runtime_suspended(hba->dev))
9424 ret = ufshcd_suspend(hba);
9426 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
9427 ktime_to_us(ktime_sub(ktime_get(), start)),
9428 hba->curr_dev_pwr_mode, hba->uic_link_state);
9431 EXPORT_SYMBOL(ufshcd_system_suspend);
9434 * ufshcd_system_resume - system resume callback
9435 * @dev: Device associated with the UFS controller.
9437 * Executed after waking the system up from a sleep state in which the contents
9438 * of main memory were preserved.
9440 * Returns 0 for success and non-zero for failure
9442 int ufshcd_system_resume(struct device *dev)
9444 struct ufs_hba *hba = dev_get_drvdata(dev);
9445 ktime_t start = ktime_get();
9448 if (pm_runtime_suspended(hba->dev))
9451 ret = ufshcd_resume(hba);
9454 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
9455 ktime_to_us(ktime_sub(ktime_get(), start)),
9456 hba->curr_dev_pwr_mode, hba->uic_link_state);
9460 EXPORT_SYMBOL(ufshcd_system_resume);
9461 #endif /* CONFIG_PM_SLEEP */
9465 * ufshcd_runtime_suspend - runtime suspend callback
9466 * @dev: Device associated with the UFS controller.
9468 * Check the description of ufshcd_suspend() function for more details.
9470 * Returns 0 for success and non-zero for failure
9472 int ufshcd_runtime_suspend(struct device *dev)
9474 struct ufs_hba *hba = dev_get_drvdata(dev);
9476 ktime_t start = ktime_get();
9478 ret = ufshcd_suspend(hba);
9480 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
9481 ktime_to_us(ktime_sub(ktime_get(), start)),
9482 hba->curr_dev_pwr_mode, hba->uic_link_state);
9485 EXPORT_SYMBOL(ufshcd_runtime_suspend);
9488 * ufshcd_runtime_resume - runtime resume routine
9489 * @dev: Device associated with the UFS controller.
9491 * This function basically brings controller
9492 * to active state. Following operations are done in this function:
9494 * 1. Turn on all the controller related clocks
9495 * 2. Turn ON VCC rail
9497 int ufshcd_runtime_resume(struct device *dev)
9499 struct ufs_hba *hba = dev_get_drvdata(dev);
9501 ktime_t start = ktime_get();
9503 ret = ufshcd_resume(hba);
9505 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
9506 ktime_to_us(ktime_sub(ktime_get(), start)),
9507 hba->curr_dev_pwr_mode, hba->uic_link_state);
9510 EXPORT_SYMBOL(ufshcd_runtime_resume);
9511 #endif /* CONFIG_PM */
9514 * ufshcd_shutdown - shutdown routine
9515 * @hba: per adapter instance
9517 * This function would turn off both UFS device and UFS hba
9518 * regulators. It would also disable clocks.
9520 * Returns 0 always to allow force shutdown even in case of errors.
9522 int ufshcd_shutdown(struct ufs_hba *hba)
9524 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
9525 ufshcd_suspend(hba);
9527 hba->is_powered = false;
9528 /* allow force shutdown even in case of errors */
9531 EXPORT_SYMBOL(ufshcd_shutdown);
9534 * ufshcd_remove - de-allocate SCSI host and host memory space
9535 * data structure memory
9536 * @hba: per adapter instance
9538 void ufshcd_remove(struct ufs_hba *hba)
9540 if (hba->ufs_device_wlun)
9541 ufshcd_rpm_get_sync(hba);
9542 ufs_hwmon_remove(hba);
9543 ufs_bsg_remove(hba);
9545 ufs_sysfs_remove_nodes(hba->dev);
9546 blk_mq_destroy_queue(hba->tmf_queue);
9547 blk_mq_free_tag_set(&hba->tmf_tag_set);
9548 scsi_remove_host(hba->host);
9549 /* disable interrupts */
9550 ufshcd_disable_intr(hba, hba->intr_mask);
9551 ufshcd_hba_stop(hba);
9552 ufshcd_hba_exit(hba);
9554 EXPORT_SYMBOL_GPL(ufshcd_remove);
9557 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
9558 * @hba: pointer to Host Bus Adapter (HBA)
9560 void ufshcd_dealloc_host(struct ufs_hba *hba)
9562 scsi_host_put(hba->host);
9564 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
9567 * ufshcd_set_dma_mask - Set dma mask based on the controller
9568 * addressing capability
9569 * @hba: per adapter instance
9571 * Returns 0 for success, non-zero for failure
9573 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
9575 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
9576 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
9579 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
9583 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
9584 * @dev: pointer to device handle
9585 * @hba_handle: driver private handle
9586 * Returns 0 on success, non-zero value on failure
9588 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
9590 struct Scsi_Host *host;
9591 struct ufs_hba *hba;
9596 "Invalid memory reference for dev is NULL\n");
9601 host = scsi_host_alloc(&ufshcd_driver_template,
9602 sizeof(struct ufs_hba));
9604 dev_err(dev, "scsi_host_alloc failed\n");
9608 host->nr_maps = HCTX_TYPE_POLL + 1;
9609 hba = shost_priv(host);
9612 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
9613 hba->nop_out_timeout = NOP_OUT_TIMEOUT;
9614 INIT_LIST_HEAD(&hba->clk_list_head);
9615 spin_lock_init(&hba->outstanding_lock);
9622 EXPORT_SYMBOL(ufshcd_alloc_host);
9624 /* This function exists because blk_mq_alloc_tag_set() requires this. */
9625 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx,
9626 const struct blk_mq_queue_data *qd)
9629 return BLK_STS_NOTSUPP;
9632 static const struct blk_mq_ops ufshcd_tmf_ops = {
9633 .queue_rq = ufshcd_queue_tmf,
9637 * ufshcd_init - Driver initialization routine
9638 * @hba: per-adapter instance
9639 * @mmio_base: base register address
9640 * @irq: Interrupt line of device
9641 * Returns 0 on success, non-zero value on failure
9643 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
9646 struct Scsi_Host *host = hba->host;
9647 struct device *dev = hba->dev;
9648 char eh_wq_name[sizeof("ufs_eh_wq_00")];
9651 * dev_set_drvdata() must be called before any callbacks are registered
9652 * that use dev_get_drvdata() (frequency scaling, clock scaling, hwmon,
9655 dev_set_drvdata(dev, hba);
9659 "Invalid memory reference for mmio_base is NULL\n");
9664 hba->mmio_base = mmio_base;
9666 hba->vps = &ufs_hba_vps;
9668 err = ufshcd_hba_init(hba);
9672 /* Read capabilities registers */
9673 err = ufshcd_hba_capabilities(hba);
9677 /* Get UFS version supported by the controller */
9678 hba->ufs_version = ufshcd_get_ufs_version(hba);
9680 /* Get Interrupt bit mask per version */
9681 hba->intr_mask = ufshcd_get_intr_mask(hba);
9683 err = ufshcd_set_dma_mask(hba);
9685 dev_err(hba->dev, "set dma mask failed\n");
9689 /* Allocate memory for host memory space */
9690 err = ufshcd_memory_alloc(hba);
9692 dev_err(hba->dev, "Memory allocation failed\n");
9697 ufshcd_host_memory_configure(hba);
9699 host->can_queue = hba->nutrs - UFSHCD_NUM_RESERVED;
9700 host->cmd_per_lun = hba->nutrs - UFSHCD_NUM_RESERVED;
9701 host->max_id = UFSHCD_MAX_ID;
9702 host->max_lun = UFS_MAX_LUNS;
9703 host->max_channel = UFSHCD_MAX_CHANNEL;
9704 host->unique_id = host->host_no;
9705 host->max_cmd_len = UFS_CDB_SIZE;
9707 hba->max_pwr_info.is_valid = false;
9709 /* Initialize work queues */
9710 snprintf(eh_wq_name, sizeof(eh_wq_name), "ufs_eh_wq_%d",
9711 hba->host->host_no);
9712 hba->eh_wq = create_singlethread_workqueue(eh_wq_name);
9714 dev_err(hba->dev, "%s: failed to create eh workqueue\n",
9719 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
9720 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
9722 sema_init(&hba->host_sem, 1);
9724 /* Initialize UIC command mutex */
9725 mutex_init(&hba->uic_cmd_mutex);
9727 /* Initialize mutex for device management commands */
9728 mutex_init(&hba->dev_cmd.lock);
9730 /* Initialize mutex for exception event control */
9731 mutex_init(&hba->ee_ctrl_mutex);
9733 init_rwsem(&hba->clk_scaling_lock);
9735 ufshcd_init_clk_gating(hba);
9737 ufshcd_init_clk_scaling(hba);
9740 * In order to avoid any spurious interrupt immediately after
9741 * registering UFS controller interrupt handler, clear any pending UFS
9742 * interrupt status and disable all the UFS interrupts.
9744 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
9745 REG_INTERRUPT_STATUS);
9746 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
9748 * Make sure that UFS interrupts are disabled and any pending interrupt
9749 * status is cleared before registering UFS interrupt handler.
9753 /* IRQ registration */
9754 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
9756 dev_err(hba->dev, "request irq failed\n");
9759 hba->is_irq_enabled = true;
9762 err = scsi_add_host(host, hba->dev);
9764 dev_err(hba->dev, "scsi_add_host failed\n");
9768 hba->tmf_tag_set = (struct blk_mq_tag_set) {
9770 .queue_depth = hba->nutmrs,
9771 .ops = &ufshcd_tmf_ops,
9772 .flags = BLK_MQ_F_NO_SCHED,
9774 err = blk_mq_alloc_tag_set(&hba->tmf_tag_set);
9776 goto out_remove_scsi_host;
9777 hba->tmf_queue = blk_mq_init_queue(&hba->tmf_tag_set);
9778 if (IS_ERR(hba->tmf_queue)) {
9779 err = PTR_ERR(hba->tmf_queue);
9780 goto free_tmf_tag_set;
9782 hba->tmf_rqs = devm_kcalloc(hba->dev, hba->nutmrs,
9783 sizeof(*hba->tmf_rqs), GFP_KERNEL);
9784 if (!hba->tmf_rqs) {
9786 goto free_tmf_queue;
9789 /* Reset the attached device */
9790 ufshcd_device_reset(hba);
9792 ufshcd_init_crypto(hba);
9794 /* Host controller enable */
9795 err = ufshcd_hba_enable(hba);
9797 dev_err(hba->dev, "Host controller enable failed\n");
9798 ufshcd_print_evt_hist(hba);
9799 ufshcd_print_host_state(hba);
9800 goto free_tmf_queue;
9804 * Set the default power management level for runtime and system PM.
9805 * Default power saving mode is to keep UFS link in Hibern8 state
9806 * and UFS device in sleep state.
9808 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9810 UIC_LINK_HIBERN8_STATE);
9811 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9813 UIC_LINK_HIBERN8_STATE);
9815 INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work,
9816 ufshcd_rpm_dev_flush_recheck_work);
9818 /* Set the default auto-hiberate idle timer value to 150 ms */
9819 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
9820 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
9821 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
9824 /* Hold auto suspend until async scan completes */
9825 pm_runtime_get_sync(dev);
9826 atomic_set(&hba->scsi_block_reqs_cnt, 0);
9828 * We are assuming that device wasn't put in sleep/power-down
9829 * state exclusively during the boot stage before kernel.
9830 * This assumption helps avoid doing link startup twice during
9831 * ufshcd_probe_hba().
9833 ufshcd_set_ufs_dev_active(hba);
9835 async_schedule(ufshcd_async_scan, hba);
9836 ufs_sysfs_add_nodes(hba->dev);
9838 device_enable_async_suspend(dev);
9842 blk_mq_destroy_queue(hba->tmf_queue);
9844 blk_mq_free_tag_set(&hba->tmf_tag_set);
9845 out_remove_scsi_host:
9846 scsi_remove_host(hba->host);
9848 hba->is_irq_enabled = false;
9849 ufshcd_hba_exit(hba);
9853 EXPORT_SYMBOL_GPL(ufshcd_init);
9855 void ufshcd_resume_complete(struct device *dev)
9857 struct ufs_hba *hba = dev_get_drvdata(dev);
9859 if (hba->complete_put) {
9860 ufshcd_rpm_put(hba);
9861 hba->complete_put = false;
9864 EXPORT_SYMBOL_GPL(ufshcd_resume_complete);
9866 static bool ufshcd_rpm_ok_for_spm(struct ufs_hba *hba)
9868 struct device *dev = &hba->ufs_device_wlun->sdev_gendev;
9869 enum ufs_dev_pwr_mode dev_pwr_mode;
9870 enum uic_link_state link_state;
9871 unsigned long flags;
9874 spin_lock_irqsave(&dev->power.lock, flags);
9875 dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl);
9876 link_state = ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl);
9877 res = pm_runtime_suspended(dev) &&
9878 hba->curr_dev_pwr_mode == dev_pwr_mode &&
9879 hba->uic_link_state == link_state &&
9880 !hba->dev_info.b_rpm_dev_flush_capable;
9881 spin_unlock_irqrestore(&dev->power.lock, flags);
9886 int __ufshcd_suspend_prepare(struct device *dev, bool rpm_ok_for_spm)
9888 struct ufs_hba *hba = dev_get_drvdata(dev);
9892 * SCSI assumes that runtime-pm and system-pm for scsi drivers
9893 * are same. And it doesn't wake up the device for system-suspend
9894 * if it's runtime suspended. But ufs doesn't follow that.
9895 * Refer ufshcd_resume_complete()
9897 if (hba->ufs_device_wlun) {
9898 /* Prevent runtime suspend */
9899 ufshcd_rpm_get_noresume(hba);
9901 * Check if already runtime suspended in same state as system
9904 if (!rpm_ok_for_spm || !ufshcd_rpm_ok_for_spm(hba)) {
9905 /* RPM state is not ok for SPM, so runtime resume */
9906 ret = ufshcd_rpm_resume(hba);
9907 if (ret < 0 && ret != -EACCES) {
9908 ufshcd_rpm_put(hba);
9912 hba->complete_put = true;
9916 EXPORT_SYMBOL_GPL(__ufshcd_suspend_prepare);
9918 int ufshcd_suspend_prepare(struct device *dev)
9920 return __ufshcd_suspend_prepare(dev, true);
9922 EXPORT_SYMBOL_GPL(ufshcd_suspend_prepare);
9924 #ifdef CONFIG_PM_SLEEP
9925 static int ufshcd_wl_poweroff(struct device *dev)
9927 struct scsi_device *sdev = to_scsi_device(dev);
9928 struct ufs_hba *hba = shost_priv(sdev->host);
9930 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
9935 static int ufshcd_wl_probe(struct device *dev)
9937 struct scsi_device *sdev = to_scsi_device(dev);
9939 if (!is_device_wlun(sdev))
9942 blk_pm_runtime_init(sdev->request_queue, dev);
9943 pm_runtime_set_autosuspend_delay(dev, 0);
9944 pm_runtime_allow(dev);
9949 static int ufshcd_wl_remove(struct device *dev)
9951 pm_runtime_forbid(dev);
9955 static const struct dev_pm_ops ufshcd_wl_pm_ops = {
9956 #ifdef CONFIG_PM_SLEEP
9957 .suspend = ufshcd_wl_suspend,
9958 .resume = ufshcd_wl_resume,
9959 .freeze = ufshcd_wl_suspend,
9960 .thaw = ufshcd_wl_resume,
9961 .poweroff = ufshcd_wl_poweroff,
9962 .restore = ufshcd_wl_resume,
9964 SET_RUNTIME_PM_OPS(ufshcd_wl_runtime_suspend, ufshcd_wl_runtime_resume, NULL)
9968 * ufs_dev_wlun_template - describes ufs device wlun
9969 * ufs-device wlun - used to send pm commands
9970 * All luns are consumers of ufs-device wlun.
9972 * Currently, no sd driver is present for wluns.
9973 * Hence the no specific pm operations are performed.
9974 * With ufs design, SSU should be sent to ufs-device wlun.
9975 * Hence register a scsi driver for ufs wluns only.
9977 static struct scsi_driver ufs_dev_wlun_template = {
9979 .name = "ufs_device_wlun",
9980 .owner = THIS_MODULE,
9981 .probe = ufshcd_wl_probe,
9982 .remove = ufshcd_wl_remove,
9983 .pm = &ufshcd_wl_pm_ops,
9984 .shutdown = ufshcd_wl_shutdown,
9988 static int __init ufshcd_core_init(void)
9992 /* Verify that there are no gaps in struct utp_transfer_cmd_desc. */
9993 static_assert(sizeof(struct utp_transfer_cmd_desc) ==
9994 2 * ALIGNED_UPIU_SIZE +
9995 SG_ALL * sizeof(struct ufshcd_sg_entry));
9999 ret = scsi_register_driver(&ufs_dev_wlun_template.gendrv);
10001 ufs_debugfs_exit();
10005 static void __exit ufshcd_core_exit(void)
10007 ufs_debugfs_exit();
10008 scsi_unregister_driver(&ufs_dev_wlun_template.gendrv);
10011 module_init(ufshcd_core_init);
10012 module_exit(ufshcd_core_exit);
10014 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
10015 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
10016 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
10017 MODULE_LICENSE("GPL");