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 <scsi/scsi_driver.h>
21 #include "ufs_quirks.h"
23 #include "ufs-sysfs.h"
24 #include "ufs-debugfs.h"
25 #include "ufs-fault-injection.h"
27 #include "ufshcd-crypto.h"
29 #include <asm/unaligned.h>
31 #define CREATE_TRACE_POINTS
32 #include <trace/events/ufs.h>
34 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
37 /* UIC command timeout, unit: ms */
38 #define UIC_CMD_TIMEOUT 500
40 /* NOP OUT retries waiting for NOP IN response */
41 #define NOP_OUT_RETRIES 10
42 /* Timeout after 50 msecs if NOP OUT hangs without response */
43 #define NOP_OUT_TIMEOUT 50 /* msecs */
45 /* Query request retries */
46 #define QUERY_REQ_RETRIES 3
47 /* Query request timeout */
48 #define QUERY_REQ_TIMEOUT 1500 /* 1.5 seconds */
50 /* Task management command timeout */
51 #define TM_CMD_TIMEOUT 100 /* msecs */
53 /* maximum number of retries for a general UIC command */
54 #define UFS_UIC_COMMAND_RETRIES 3
56 /* maximum number of link-startup retries */
57 #define DME_LINKSTARTUP_RETRIES 3
59 /* Maximum retries for Hibern8 enter */
60 #define UIC_HIBERN8_ENTER_RETRIES 3
62 /* maximum number of reset retries before giving up */
63 #define MAX_HOST_RESET_RETRIES 5
65 /* Maximum number of error handler retries before giving up */
66 #define MAX_ERR_HANDLER_RETRIES 5
68 /* Expose the flag value from utp_upiu_query.value */
69 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
71 /* Interrupt aggregation default timeout, unit: 40us */
72 #define INT_AGGR_DEF_TO 0x02
74 /* default delay of autosuspend: 2000 ms */
75 #define RPM_AUTOSUSPEND_DELAY_MS 2000
77 /* Default delay of RPM device flush delayed work */
78 #define RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS 5000
80 /* Default value of wait time before gating device ref clock */
81 #define UFSHCD_REF_CLK_GATING_WAIT_US 0xFF /* microsecs */
83 /* Polling time to wait for fDeviceInit */
84 #define FDEVICEINIT_COMPL_TIMEOUT 1500 /* millisecs */
86 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
90 _ret = ufshcd_enable_vreg(_dev, _vreg); \
92 _ret = ufshcd_disable_vreg(_dev, _vreg); \
96 #define ufshcd_hex_dump(prefix_str, buf, len) do { \
97 size_t __len = (len); \
98 print_hex_dump(KERN_ERR, prefix_str, \
99 __len > 4 ? DUMP_PREFIX_OFFSET : DUMP_PREFIX_NONE,\
100 16, 4, buf, __len, false); \
103 int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len,
109 if (offset % 4 != 0 || len % 4 != 0) /* keep readl happy */
112 regs = kzalloc(len, GFP_ATOMIC);
116 for (pos = 0; pos < len; pos += 4)
117 regs[pos / 4] = ufshcd_readl(hba, offset + pos);
119 ufshcd_hex_dump(prefix, regs, len);
124 EXPORT_SYMBOL_GPL(ufshcd_dump_regs);
127 UFSHCD_MAX_CHANNEL = 0,
129 UFSHCD_NUM_RESERVED = 1,
130 UFSHCD_CMD_PER_LUN = 32 - UFSHCD_NUM_RESERVED,
131 UFSHCD_CAN_QUEUE = 32 - UFSHCD_NUM_RESERVED,
134 static const char *const ufshcd_state_name[] = {
135 [UFSHCD_STATE_RESET] = "reset",
136 [UFSHCD_STATE_OPERATIONAL] = "operational",
137 [UFSHCD_STATE_ERROR] = "error",
138 [UFSHCD_STATE_EH_SCHEDULED_FATAL] = "eh_fatal",
139 [UFSHCD_STATE_EH_SCHEDULED_NON_FATAL] = "eh_non_fatal",
142 /* UFSHCD error handling flags */
144 UFSHCD_EH_IN_PROGRESS = (1 << 0),
147 /* UFSHCD UIC layer error flags */
149 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
150 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
151 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
152 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
153 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
154 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
155 UFSHCD_UIC_PA_GENERIC_ERROR = (1 << 6), /* Generic PA error */
158 #define ufshcd_set_eh_in_progress(h) \
159 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
160 #define ufshcd_eh_in_progress(h) \
161 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
162 #define ufshcd_clear_eh_in_progress(h) \
163 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
165 struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
166 [UFS_PM_LVL_0] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
167 [UFS_PM_LVL_1] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
168 [UFS_PM_LVL_2] = {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
169 [UFS_PM_LVL_3] = {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
170 [UFS_PM_LVL_4] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
171 [UFS_PM_LVL_5] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
173 * For DeepSleep, the link is first put in hibern8 and then off.
174 * Leaving the link in hibern8 is not supported.
176 [UFS_PM_LVL_6] = {UFS_DEEPSLEEP_PWR_MODE, UIC_LINK_OFF_STATE},
179 static inline enum ufs_dev_pwr_mode
180 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
182 return ufs_pm_lvl_states[lvl].dev_state;
185 static inline enum uic_link_state
186 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
188 return ufs_pm_lvl_states[lvl].link_state;
191 static inline enum ufs_pm_level
192 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
193 enum uic_link_state link_state)
195 enum ufs_pm_level lvl;
197 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
198 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
199 (ufs_pm_lvl_states[lvl].link_state == link_state))
203 /* if no match found, return the level 0 */
207 static struct ufs_dev_fix ufs_fixups[] = {
208 /* UFS cards deviations table */
209 UFS_FIX(UFS_VENDOR_MICRON, UFS_ANY_MODEL,
210 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
211 UFS_DEVICE_QUIRK_SWAP_L2P_ENTRY_FOR_HPB_READ),
212 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
213 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
214 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE |
215 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS),
216 UFS_FIX(UFS_VENDOR_SKHYNIX, UFS_ANY_MODEL,
217 UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME),
218 UFS_FIX(UFS_VENDOR_SKHYNIX, "hB8aL1" /*H28U62301AMR*/,
219 UFS_DEVICE_QUIRK_HOST_VS_DEBUGSAVECONFIGTIME),
220 UFS_FIX(UFS_VENDOR_TOSHIBA, UFS_ANY_MODEL,
221 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
222 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9C8KBADG",
223 UFS_DEVICE_QUIRK_PA_TACTIVATE),
224 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9D8KBADG",
225 UFS_DEVICE_QUIRK_PA_TACTIVATE),
229 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba);
230 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
231 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
232 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
233 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
234 static void ufshcd_hba_exit(struct ufs_hba *hba);
235 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params);
236 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
237 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
238 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
239 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
240 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
241 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba);
242 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up);
243 static irqreturn_t ufshcd_intr(int irq, void *__hba);
244 static int ufshcd_change_power_mode(struct ufs_hba *hba,
245 struct ufs_pa_layer_attr *pwr_mode);
246 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on);
247 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on);
248 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
249 struct ufs_vreg *vreg);
250 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag);
251 static void ufshcd_wb_toggle_flush_during_h8(struct ufs_hba *hba, bool set);
252 static inline void ufshcd_wb_toggle_flush(struct ufs_hba *hba, bool enable);
253 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba);
254 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba);
256 static inline void ufshcd_enable_irq(struct ufs_hba *hba)
258 if (!hba->is_irq_enabled) {
259 enable_irq(hba->irq);
260 hba->is_irq_enabled = true;
264 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
266 if (hba->is_irq_enabled) {
267 disable_irq(hba->irq);
268 hba->is_irq_enabled = false;
272 static inline void ufshcd_wb_config(struct ufs_hba *hba)
274 if (!ufshcd_is_wb_allowed(hba))
277 ufshcd_wb_toggle(hba, true);
279 ufshcd_wb_toggle_flush_during_h8(hba, true);
280 if (!(hba->quirks & UFSHCI_QUIRK_SKIP_MANUAL_WB_FLUSH_CTRL))
281 ufshcd_wb_toggle_flush(hba, true);
284 static void ufshcd_scsi_unblock_requests(struct ufs_hba *hba)
286 if (atomic_dec_and_test(&hba->scsi_block_reqs_cnt))
287 scsi_unblock_requests(hba->host);
290 static void ufshcd_scsi_block_requests(struct ufs_hba *hba)
292 if (atomic_inc_return(&hba->scsi_block_reqs_cnt) == 1)
293 scsi_block_requests(hba->host);
296 static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba, unsigned int tag,
297 enum ufs_trace_str_t str_t)
299 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
300 struct utp_upiu_header *header;
302 if (!trace_ufshcd_upiu_enabled())
305 if (str_t == UFS_CMD_SEND)
306 header = &rq->header;
308 header = &hba->lrb[tag].ucd_rsp_ptr->header;
310 trace_ufshcd_upiu(dev_name(hba->dev), str_t, header, &rq->sc.cdb,
314 static void ufshcd_add_query_upiu_trace(struct ufs_hba *hba,
315 enum ufs_trace_str_t str_t,
316 struct utp_upiu_req *rq_rsp)
318 if (!trace_ufshcd_upiu_enabled())
321 trace_ufshcd_upiu(dev_name(hba->dev), str_t, &rq_rsp->header,
322 &rq_rsp->qr, UFS_TSF_OSF);
325 static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag,
326 enum ufs_trace_str_t str_t)
328 struct utp_task_req_desc *descp = &hba->utmrdl_base_addr[tag];
330 if (!trace_ufshcd_upiu_enabled())
333 if (str_t == UFS_TM_SEND)
334 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
335 &descp->upiu_req.req_header,
336 &descp->upiu_req.input_param1,
339 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
340 &descp->upiu_rsp.rsp_header,
341 &descp->upiu_rsp.output_param1,
345 static void ufshcd_add_uic_command_trace(struct ufs_hba *hba,
346 struct uic_command *ucmd,
347 enum ufs_trace_str_t str_t)
351 if (!trace_ufshcd_uic_command_enabled())
354 if (str_t == UFS_CMD_SEND)
357 cmd = ufshcd_readl(hba, REG_UIC_COMMAND);
359 trace_ufshcd_uic_command(dev_name(hba->dev), str_t, cmd,
360 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_1),
361 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2),
362 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3));
365 static void ufshcd_add_command_trace(struct ufs_hba *hba, unsigned int tag,
366 enum ufs_trace_str_t str_t)
369 u8 opcode = 0, group_id = 0;
371 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
372 struct scsi_cmnd *cmd = lrbp->cmd;
373 struct request *rq = scsi_cmd_to_rq(cmd);
374 int transfer_len = -1;
379 /* trace UPIU also */
380 ufshcd_add_cmd_upiu_trace(hba, tag, str_t);
381 if (!trace_ufshcd_command_enabled())
384 opcode = cmd->cmnd[0];
386 if (opcode == READ_10 || opcode == WRITE_10) {
388 * Currently we only fully trace read(10) and write(10) commands
391 be32_to_cpu(lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
392 lba = scsi_get_lba(cmd);
393 if (opcode == WRITE_10)
394 group_id = lrbp->cmd->cmnd[6];
395 } else if (opcode == UNMAP) {
397 * The number of Bytes to be unmapped beginning with the lba.
399 transfer_len = blk_rq_bytes(rq);
400 lba = scsi_get_lba(cmd);
403 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
404 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
405 trace_ufshcd_command(dev_name(hba->dev), str_t, tag,
406 doorbell, transfer_len, intr, lba, opcode, group_id);
409 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
411 struct ufs_clk_info *clki;
412 struct list_head *head = &hba->clk_list_head;
414 if (list_empty(head))
417 list_for_each_entry(clki, head, list) {
418 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
420 dev_err(hba->dev, "clk: %s, rate: %u\n",
421 clki->name, clki->curr_freq);
425 static void ufshcd_print_evt(struct ufs_hba *hba, u32 id,
430 struct ufs_event_hist *e;
432 if (id >= UFS_EVT_CNT)
435 e = &hba->ufs_stats.event[id];
437 for (i = 0; i < UFS_EVENT_HIST_LENGTH; i++) {
438 int p = (i + e->pos) % UFS_EVENT_HIST_LENGTH;
440 if (e->tstamp[p] == 0)
442 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, p,
443 e->val[p], ktime_to_us(e->tstamp[p]));
448 dev_err(hba->dev, "No record of %s\n", err_name);
450 dev_err(hba->dev, "%s: total cnt=%llu\n", err_name, e->cnt);
453 static void ufshcd_print_evt_hist(struct ufs_hba *hba)
455 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
457 ufshcd_print_evt(hba, UFS_EVT_PA_ERR, "pa_err");
458 ufshcd_print_evt(hba, UFS_EVT_DL_ERR, "dl_err");
459 ufshcd_print_evt(hba, UFS_EVT_NL_ERR, "nl_err");
460 ufshcd_print_evt(hba, UFS_EVT_TL_ERR, "tl_err");
461 ufshcd_print_evt(hba, UFS_EVT_DME_ERR, "dme_err");
462 ufshcd_print_evt(hba, UFS_EVT_AUTO_HIBERN8_ERR,
464 ufshcd_print_evt(hba, UFS_EVT_FATAL_ERR, "fatal_err");
465 ufshcd_print_evt(hba, UFS_EVT_LINK_STARTUP_FAIL,
466 "link_startup_fail");
467 ufshcd_print_evt(hba, UFS_EVT_RESUME_ERR, "resume_fail");
468 ufshcd_print_evt(hba, UFS_EVT_SUSPEND_ERR,
470 ufshcd_print_evt(hba, UFS_EVT_DEV_RESET, "dev_reset");
471 ufshcd_print_evt(hba, UFS_EVT_HOST_RESET, "host_reset");
472 ufshcd_print_evt(hba, UFS_EVT_ABORT, "task_abort");
474 ufshcd_vops_dbg_register_dump(hba);
478 void ufshcd_print_trs(struct ufs_hba *hba, unsigned long bitmap, bool pr_prdt)
480 struct ufshcd_lrb *lrbp;
484 for_each_set_bit(tag, &bitmap, hba->nutrs) {
485 lrbp = &hba->lrb[tag];
487 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
488 tag, ktime_to_us(lrbp->issue_time_stamp));
489 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n",
490 tag, ktime_to_us(lrbp->compl_time_stamp));
492 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
493 tag, (u64)lrbp->utrd_dma_addr);
495 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
496 sizeof(struct utp_transfer_req_desc));
497 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
498 (u64)lrbp->ucd_req_dma_addr);
499 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
500 sizeof(struct utp_upiu_req));
501 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
502 (u64)lrbp->ucd_rsp_dma_addr);
503 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
504 sizeof(struct utp_upiu_rsp));
506 prdt_length = le16_to_cpu(
507 lrbp->utr_descriptor_ptr->prd_table_length);
508 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
509 prdt_length /= sizeof(struct ufshcd_sg_entry);
512 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
514 (u64)lrbp->ucd_prdt_dma_addr);
517 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
518 sizeof(struct ufshcd_sg_entry) * prdt_length);
522 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
526 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
527 struct utp_task_req_desc *tmrdp = &hba->utmrdl_base_addr[tag];
529 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
530 ufshcd_hex_dump("", tmrdp, sizeof(*tmrdp));
534 static void ufshcd_print_host_state(struct ufs_hba *hba)
536 struct scsi_device *sdev_ufs = hba->sdev_ufs_device;
538 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
539 dev_err(hba->dev, "outstanding reqs=0x%lx tasks=0x%lx\n",
540 hba->outstanding_reqs, hba->outstanding_tasks);
541 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
542 hba->saved_err, hba->saved_uic_err);
543 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
544 hba->curr_dev_pwr_mode, hba->uic_link_state);
545 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
546 hba->pm_op_in_progress, hba->is_sys_suspended);
547 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
548 hba->auto_bkops_enabled, hba->host->host_self_blocked);
549 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
551 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt=%d\n",
552 ktime_to_us(hba->ufs_stats.last_hibern8_exit_tstamp),
553 hba->ufs_stats.hibern8_exit_cnt);
554 dev_err(hba->dev, "last intr at %lld us, last intr status=0x%x\n",
555 ktime_to_us(hba->ufs_stats.last_intr_ts),
556 hba->ufs_stats.last_intr_status);
557 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
558 hba->eh_flags, hba->req_abort_count);
559 dev_err(hba->dev, "hba->ufs_version=0x%x, Host capabilities=0x%x, caps=0x%x\n",
560 hba->ufs_version, hba->capabilities, hba->caps);
561 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
564 dev_err(hba->dev, "UFS dev info: %.8s %.16s rev %.4s\n",
565 sdev_ufs->vendor, sdev_ufs->model, sdev_ufs->rev);
567 ufshcd_print_clk_freqs(hba);
571 * ufshcd_print_pwr_info - print power params as saved in hba
573 * @hba: per-adapter instance
575 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
577 static const char * const names[] = {
588 * Using dev_dbg to avoid messages during runtime PM to avoid
589 * never-ending cycles of messages written back to storage by user space
590 * causing runtime resume, causing more messages and so on.
592 dev_dbg(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
594 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
595 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
596 names[hba->pwr_info.pwr_rx],
597 names[hba->pwr_info.pwr_tx],
598 hba->pwr_info.hs_rate);
601 static void ufshcd_device_reset(struct ufs_hba *hba)
605 err = ufshcd_vops_device_reset(hba);
608 ufshcd_set_ufs_dev_active(hba);
609 if (ufshcd_is_wb_allowed(hba)) {
610 hba->dev_info.wb_enabled = false;
611 hba->dev_info.wb_buf_flush_enabled = false;
614 if (err != -EOPNOTSUPP)
615 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, err);
618 void ufshcd_delay_us(unsigned long us, unsigned long tolerance)
626 usleep_range(us, us + tolerance);
628 EXPORT_SYMBOL_GPL(ufshcd_delay_us);
631 * ufshcd_wait_for_register - wait for register value to change
632 * @hba: per-adapter interface
633 * @reg: mmio register offset
634 * @mask: mask to apply to the read register value
635 * @val: value to wait for
636 * @interval_us: polling interval in microseconds
637 * @timeout_ms: timeout in milliseconds
640 * -ETIMEDOUT on error, zero on success.
642 int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
643 u32 val, unsigned long interval_us,
644 unsigned long timeout_ms)
647 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
649 /* ignore bits that we don't intend to wait on */
652 while ((ufshcd_readl(hba, reg) & mask) != val) {
653 usleep_range(interval_us, interval_us + 50);
654 if (time_after(jiffies, timeout)) {
655 if ((ufshcd_readl(hba, reg) & mask) != val)
665 * ufshcd_get_intr_mask - Get the interrupt bit mask
666 * @hba: Pointer to adapter instance
668 * Returns interrupt bit mask per version
670 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
672 if (hba->ufs_version == ufshci_version(1, 0))
673 return INTERRUPT_MASK_ALL_VER_10;
674 if (hba->ufs_version <= ufshci_version(2, 0))
675 return INTERRUPT_MASK_ALL_VER_11;
677 return INTERRUPT_MASK_ALL_VER_21;
681 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
682 * @hba: Pointer to adapter instance
684 * Returns UFSHCI version supported by the controller
686 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
690 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
691 ufshci_ver = ufshcd_vops_get_ufs_hci_version(hba);
693 ufshci_ver = ufshcd_readl(hba, REG_UFS_VERSION);
696 * UFSHCI v1.x uses a different version scheme, in order
697 * to allow the use of comparisons with the ufshci_version
698 * function, we convert it to the same scheme as ufs 2.0+.
700 if (ufshci_ver & 0x00010000)
701 return ufshci_version(1, ufshci_ver & 0x00000100);
707 * ufshcd_is_device_present - Check if any device connected to
708 * the host controller
709 * @hba: pointer to adapter instance
711 * Returns true if device present, false if no device detected
713 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
715 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
716 DEVICE_PRESENT) ? true : false;
720 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
721 * @lrbp: pointer to local command reference block
723 * This function is used to get the OCS field from UTRD
724 * Returns the OCS field in the UTRD
726 static enum utp_ocs ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
728 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
732 * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
733 * @hba: per adapter instance
734 * @pos: position of the bit to be cleared
736 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
738 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
739 ufshcd_writel(hba, (1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
741 ufshcd_writel(hba, ~(1 << pos),
742 REG_UTP_TRANSFER_REQ_LIST_CLEAR);
746 * ufshcd_utmrl_clear - Clear a bit in UTRMLCLR register
747 * @hba: per adapter instance
748 * @pos: position of the bit to be cleared
750 static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos)
752 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
753 ufshcd_writel(hba, (1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
755 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
759 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
760 * @reg: Register value of host controller status
762 * Returns integer, 0 on Success and positive value if failed
764 static inline int ufshcd_get_lists_status(u32 reg)
766 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
770 * ufshcd_get_uic_cmd_result - Get the UIC command result
771 * @hba: Pointer to adapter instance
773 * This function gets the result of UIC command completion
774 * Returns 0 on success, non zero value on error
776 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
778 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
779 MASK_UIC_COMMAND_RESULT;
783 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
784 * @hba: Pointer to adapter instance
786 * This function gets UIC command argument3
787 * Returns 0 on success, non zero value on error
789 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
791 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
795 * ufshcd_get_req_rsp - returns the TR response transaction type
796 * @ucd_rsp_ptr: pointer to response UPIU
799 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
801 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
805 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
806 * @ucd_rsp_ptr: pointer to response UPIU
808 * This function gets the response status and scsi_status from response UPIU
809 * Returns the response result code.
812 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
814 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
818 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
820 * @ucd_rsp_ptr: pointer to response UPIU
822 * Return the data segment length.
824 static inline unsigned int
825 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
827 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
828 MASK_RSP_UPIU_DATA_SEG_LEN;
832 * ufshcd_is_exception_event - Check if the device raised an exception event
833 * @ucd_rsp_ptr: pointer to response UPIU
835 * The function checks if the device raised an exception event indicated in
836 * the Device Information field of response UPIU.
838 * Returns true if exception is raised, false otherwise.
840 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
842 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
843 MASK_RSP_EXCEPTION_EVENT ? true : false;
847 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
848 * @hba: per adapter instance
851 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
853 ufshcd_writel(hba, INT_AGGR_ENABLE |
854 INT_AGGR_COUNTER_AND_TIMER_RESET,
855 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
859 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
860 * @hba: per adapter instance
861 * @cnt: Interrupt aggregation counter threshold
862 * @tmout: Interrupt aggregation timeout value
865 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
867 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
868 INT_AGGR_COUNTER_THLD_VAL(cnt) |
869 INT_AGGR_TIMEOUT_VAL(tmout),
870 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
874 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
875 * @hba: per adapter instance
877 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
879 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
883 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
884 * When run-stop registers are set to 1, it indicates the
885 * host controller that it can process the requests
886 * @hba: per adapter instance
888 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
890 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
891 REG_UTP_TASK_REQ_LIST_RUN_STOP);
892 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
893 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
897 * ufshcd_hba_start - Start controller initialization sequence
898 * @hba: per adapter instance
900 static inline void ufshcd_hba_start(struct ufs_hba *hba)
902 u32 val = CONTROLLER_ENABLE;
904 if (ufshcd_crypto_enable(hba))
905 val |= CRYPTO_GENERAL_ENABLE;
907 ufshcd_writel(hba, val, REG_CONTROLLER_ENABLE);
911 * ufshcd_is_hba_active - Get controller state
912 * @hba: per adapter instance
914 * Returns false if controller is active, true otherwise
916 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
918 return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE)
922 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
924 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
925 if (hba->ufs_version <= ufshci_version(1, 1))
926 return UFS_UNIPRO_VER_1_41;
928 return UFS_UNIPRO_VER_1_6;
930 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
932 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
935 * If both host and device support UniPro ver1.6 or later, PA layer
936 * parameters tuning happens during link startup itself.
938 * We can manually tune PA layer parameters if either host or device
939 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
940 * logic simple, we will only do manual tuning if local unipro version
941 * doesn't support ver1.6 or later.
943 if (ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6)
950 * ufshcd_set_clk_freq - set UFS controller clock frequencies
951 * @hba: per adapter instance
952 * @scale_up: If True, set max possible frequency othewise set low frequency
954 * Returns 0 if successful
955 * Returns < 0 for any other errors
957 static int ufshcd_set_clk_freq(struct ufs_hba *hba, bool scale_up)
960 struct ufs_clk_info *clki;
961 struct list_head *head = &hba->clk_list_head;
963 if (list_empty(head))
966 list_for_each_entry(clki, head, list) {
967 if (!IS_ERR_OR_NULL(clki->clk)) {
968 if (scale_up && clki->max_freq) {
969 if (clki->curr_freq == clki->max_freq)
972 ret = clk_set_rate(clki->clk, clki->max_freq);
974 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
975 __func__, clki->name,
976 clki->max_freq, ret);
979 trace_ufshcd_clk_scaling(dev_name(hba->dev),
980 "scaled up", clki->name,
984 clki->curr_freq = clki->max_freq;
986 } else if (!scale_up && clki->min_freq) {
987 if (clki->curr_freq == clki->min_freq)
990 ret = clk_set_rate(clki->clk, clki->min_freq);
992 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
993 __func__, clki->name,
994 clki->min_freq, ret);
997 trace_ufshcd_clk_scaling(dev_name(hba->dev),
998 "scaled down", clki->name,
1001 clki->curr_freq = clki->min_freq;
1004 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
1005 clki->name, clk_get_rate(clki->clk));
1013 * ufshcd_scale_clks - scale up or scale down UFS controller clocks
1014 * @hba: per adapter instance
1015 * @scale_up: True if scaling up and false if scaling down
1017 * Returns 0 if successful
1018 * Returns < 0 for any other errors
1020 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
1023 ktime_t start = ktime_get();
1025 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
1029 ret = ufshcd_set_clk_freq(hba, scale_up);
1033 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1035 ufshcd_set_clk_freq(hba, !scale_up);
1038 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1039 (scale_up ? "up" : "down"),
1040 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1045 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
1046 * @hba: per adapter instance
1047 * @scale_up: True if scaling up and false if scaling down
1049 * Returns true if scaling is required, false otherwise.
1051 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
1054 struct ufs_clk_info *clki;
1055 struct list_head *head = &hba->clk_list_head;
1057 if (list_empty(head))
1060 list_for_each_entry(clki, head, list) {
1061 if (!IS_ERR_OR_NULL(clki->clk)) {
1062 if (scale_up && clki->max_freq) {
1063 if (clki->curr_freq == clki->max_freq)
1066 } else if (!scale_up && clki->min_freq) {
1067 if (clki->curr_freq == clki->min_freq)
1078 * Determine the number of pending commands by counting the bits in the SCSI
1079 * device budget maps. This approach has been selected because a bit is set in
1080 * the budget map before scsi_host_queue_ready() checks the host_self_blocked
1081 * flag. The host_self_blocked flag can be modified by calling
1082 * scsi_block_requests() or scsi_unblock_requests().
1084 static u32 ufshcd_pending_cmds(struct ufs_hba *hba)
1086 struct scsi_device *sdev;
1089 lockdep_assert_held(hba->host->host_lock);
1090 __shost_for_each_device(sdev, hba->host)
1091 pending += sbitmap_weight(&sdev->budget_map);
1096 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
1097 u64 wait_timeout_us)
1099 unsigned long flags;
1103 bool timeout = false, do_last_check = false;
1106 ufshcd_hold(hba, false);
1107 spin_lock_irqsave(hba->host->host_lock, flags);
1109 * Wait for all the outstanding tasks/transfer requests.
1110 * Verify by checking the doorbell registers are clear.
1112 start = ktime_get();
1114 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
1119 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1120 tr_pending = ufshcd_pending_cmds(hba);
1121 if (!tm_doorbell && !tr_pending) {
1124 } else if (do_last_check) {
1128 spin_unlock_irqrestore(hba->host->host_lock, flags);
1130 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1134 * We might have scheduled out for long time so make
1135 * sure to check if doorbells are cleared by this time
1138 do_last_check = true;
1140 spin_lock_irqsave(hba->host->host_lock, flags);
1141 } while (tm_doorbell || tr_pending);
1145 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1146 __func__, tm_doorbell, tr_pending);
1150 spin_unlock_irqrestore(hba->host->host_lock, flags);
1151 ufshcd_release(hba);
1156 * ufshcd_scale_gear - scale up/down UFS gear
1157 * @hba: per adapter instance
1158 * @scale_up: True for scaling up gear and false for scaling down
1160 * Returns 0 for success,
1161 * Returns -EBUSY if scaling can't happen at this time
1162 * Returns non-zero for any other errors
1164 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1167 struct ufs_pa_layer_attr new_pwr_info;
1170 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info.info,
1171 sizeof(struct ufs_pa_layer_attr));
1173 memcpy(&new_pwr_info, &hba->pwr_info,
1174 sizeof(struct ufs_pa_layer_attr));
1176 if (hba->pwr_info.gear_tx > hba->clk_scaling.min_gear ||
1177 hba->pwr_info.gear_rx > hba->clk_scaling.min_gear) {
1178 /* save the current power mode */
1179 memcpy(&hba->clk_scaling.saved_pwr_info.info,
1181 sizeof(struct ufs_pa_layer_attr));
1183 /* scale down gear */
1184 new_pwr_info.gear_tx = hba->clk_scaling.min_gear;
1185 new_pwr_info.gear_rx = hba->clk_scaling.min_gear;
1189 /* check if the power mode needs to be changed or not? */
1190 ret = ufshcd_config_pwr_mode(hba, &new_pwr_info);
1192 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1194 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1195 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1200 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba)
1202 #define DOORBELL_CLR_TOUT_US (1000 * 1000) /* 1 sec */
1205 * make sure that there are no outstanding requests when
1206 * clock scaling is in progress
1208 ufshcd_scsi_block_requests(hba);
1209 down_write(&hba->clk_scaling_lock);
1211 if (!hba->clk_scaling.is_allowed ||
1212 ufshcd_wait_for_doorbell_clr(hba, DOORBELL_CLR_TOUT_US)) {
1214 up_write(&hba->clk_scaling_lock);
1215 ufshcd_scsi_unblock_requests(hba);
1219 /* let's not get into low power until clock scaling is completed */
1220 ufshcd_hold(hba, false);
1226 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba, bool writelock)
1229 up_write(&hba->clk_scaling_lock);
1231 up_read(&hba->clk_scaling_lock);
1232 ufshcd_scsi_unblock_requests(hba);
1233 ufshcd_release(hba);
1237 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1238 * @hba: per adapter instance
1239 * @scale_up: True for scaling up and false for scalin down
1241 * Returns 0 for success,
1242 * Returns -EBUSY if scaling can't happen at this time
1243 * Returns non-zero for any other errors
1245 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1248 bool is_writelock = true;
1250 ret = ufshcd_clock_scaling_prepare(hba);
1254 /* scale down the gear before scaling down clocks */
1256 ret = ufshcd_scale_gear(hba, false);
1261 ret = ufshcd_scale_clks(hba, scale_up);
1264 ufshcd_scale_gear(hba, true);
1268 /* scale up the gear after scaling up clocks */
1270 ret = ufshcd_scale_gear(hba, true);
1272 ufshcd_scale_clks(hba, false);
1277 /* Enable Write Booster if we have scaled up else disable it */
1278 downgrade_write(&hba->clk_scaling_lock);
1279 is_writelock = false;
1280 ufshcd_wb_toggle(hba, scale_up);
1283 ufshcd_clock_scaling_unprepare(hba, is_writelock);
1287 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1289 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1290 clk_scaling.suspend_work);
1291 unsigned long irq_flags;
1293 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1294 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1295 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1298 hba->clk_scaling.is_suspended = true;
1299 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1301 __ufshcd_suspend_clkscaling(hba);
1304 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1306 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1307 clk_scaling.resume_work);
1308 unsigned long irq_flags;
1310 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1311 if (!hba->clk_scaling.is_suspended) {
1312 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1315 hba->clk_scaling.is_suspended = false;
1316 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1318 devfreq_resume_device(hba->devfreq);
1321 static int ufshcd_devfreq_target(struct device *dev,
1322 unsigned long *freq, u32 flags)
1325 struct ufs_hba *hba = dev_get_drvdata(dev);
1327 bool scale_up, sched_clk_scaling_suspend_work = false;
1328 struct list_head *clk_list = &hba->clk_list_head;
1329 struct ufs_clk_info *clki;
1330 unsigned long irq_flags;
1332 if (!ufshcd_is_clkscaling_supported(hba))
1335 clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info, list);
1336 /* Override with the closest supported frequency */
1337 *freq = (unsigned long) clk_round_rate(clki->clk, *freq);
1338 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1339 if (ufshcd_eh_in_progress(hba)) {
1340 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1344 if (!hba->clk_scaling.active_reqs)
1345 sched_clk_scaling_suspend_work = true;
1347 if (list_empty(clk_list)) {
1348 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1352 /* Decide based on the rounded-off frequency and update */
1353 scale_up = (*freq == clki->max_freq) ? true : false;
1355 *freq = clki->min_freq;
1356 /* Update the frequency */
1357 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1358 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1360 goto out; /* no state change required */
1362 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1364 start = ktime_get();
1365 ret = ufshcd_devfreq_scale(hba, scale_up);
1367 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1368 (scale_up ? "up" : "down"),
1369 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1372 if (sched_clk_scaling_suspend_work)
1373 queue_work(hba->clk_scaling.workq,
1374 &hba->clk_scaling.suspend_work);
1379 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1380 struct devfreq_dev_status *stat)
1382 struct ufs_hba *hba = dev_get_drvdata(dev);
1383 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1384 unsigned long flags;
1385 struct list_head *clk_list = &hba->clk_list_head;
1386 struct ufs_clk_info *clki;
1389 if (!ufshcd_is_clkscaling_supported(hba))
1392 memset(stat, 0, sizeof(*stat));
1394 spin_lock_irqsave(hba->host->host_lock, flags);
1395 curr_t = ktime_get();
1396 if (!scaling->window_start_t)
1399 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1401 * If current frequency is 0, then the ondemand governor considers
1402 * there's no initial frequency set. And it always requests to set
1403 * to max. frequency.
1405 stat->current_frequency = clki->curr_freq;
1406 if (scaling->is_busy_started)
1407 scaling->tot_busy_t += ktime_us_delta(curr_t,
1408 scaling->busy_start_t);
1410 stat->total_time = ktime_us_delta(curr_t, scaling->window_start_t);
1411 stat->busy_time = scaling->tot_busy_t;
1413 scaling->window_start_t = curr_t;
1414 scaling->tot_busy_t = 0;
1416 if (hba->outstanding_reqs) {
1417 scaling->busy_start_t = curr_t;
1418 scaling->is_busy_started = true;
1420 scaling->busy_start_t = 0;
1421 scaling->is_busy_started = false;
1423 spin_unlock_irqrestore(hba->host->host_lock, flags);
1427 static int ufshcd_devfreq_init(struct ufs_hba *hba)
1429 struct list_head *clk_list = &hba->clk_list_head;
1430 struct ufs_clk_info *clki;
1431 struct devfreq *devfreq;
1434 /* Skip devfreq if we don't have any clocks in the list */
1435 if (list_empty(clk_list))
1438 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1439 dev_pm_opp_add(hba->dev, clki->min_freq, 0);
1440 dev_pm_opp_add(hba->dev, clki->max_freq, 0);
1442 ufshcd_vops_config_scaling_param(hba, &hba->vps->devfreq_profile,
1443 &hba->vps->ondemand_data);
1444 devfreq = devfreq_add_device(hba->dev,
1445 &hba->vps->devfreq_profile,
1446 DEVFREQ_GOV_SIMPLE_ONDEMAND,
1447 &hba->vps->ondemand_data);
1448 if (IS_ERR(devfreq)) {
1449 ret = PTR_ERR(devfreq);
1450 dev_err(hba->dev, "Unable to register with devfreq %d\n", ret);
1452 dev_pm_opp_remove(hba->dev, clki->min_freq);
1453 dev_pm_opp_remove(hba->dev, clki->max_freq);
1457 hba->devfreq = devfreq;
1462 static void ufshcd_devfreq_remove(struct ufs_hba *hba)
1464 struct list_head *clk_list = &hba->clk_list_head;
1465 struct ufs_clk_info *clki;
1470 devfreq_remove_device(hba->devfreq);
1471 hba->devfreq = NULL;
1473 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1474 dev_pm_opp_remove(hba->dev, clki->min_freq);
1475 dev_pm_opp_remove(hba->dev, clki->max_freq);
1478 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1480 unsigned long flags;
1482 devfreq_suspend_device(hba->devfreq);
1483 spin_lock_irqsave(hba->host->host_lock, flags);
1484 hba->clk_scaling.window_start_t = 0;
1485 spin_unlock_irqrestore(hba->host->host_lock, flags);
1488 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1490 unsigned long flags;
1491 bool suspend = false;
1493 cancel_work_sync(&hba->clk_scaling.suspend_work);
1494 cancel_work_sync(&hba->clk_scaling.resume_work);
1496 spin_lock_irqsave(hba->host->host_lock, flags);
1497 if (!hba->clk_scaling.is_suspended) {
1499 hba->clk_scaling.is_suspended = true;
1501 spin_unlock_irqrestore(hba->host->host_lock, flags);
1504 __ufshcd_suspend_clkscaling(hba);
1507 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1509 unsigned long flags;
1510 bool resume = false;
1512 spin_lock_irqsave(hba->host->host_lock, flags);
1513 if (hba->clk_scaling.is_suspended) {
1515 hba->clk_scaling.is_suspended = false;
1517 spin_unlock_irqrestore(hba->host->host_lock, flags);
1520 devfreq_resume_device(hba->devfreq);
1523 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1524 struct device_attribute *attr, char *buf)
1526 struct ufs_hba *hba = dev_get_drvdata(dev);
1528 return sysfs_emit(buf, "%d\n", hba->clk_scaling.is_enabled);
1531 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1532 struct device_attribute *attr, const char *buf, size_t count)
1534 struct ufs_hba *hba = dev_get_drvdata(dev);
1538 if (kstrtou32(buf, 0, &value))
1541 down(&hba->host_sem);
1542 if (!ufshcd_is_user_access_allowed(hba)) {
1548 if (value == hba->clk_scaling.is_enabled)
1551 ufshcd_rpm_get_sync(hba);
1552 ufshcd_hold(hba, false);
1554 hba->clk_scaling.is_enabled = value;
1557 ufshcd_resume_clkscaling(hba);
1559 ufshcd_suspend_clkscaling(hba);
1560 err = ufshcd_devfreq_scale(hba, true);
1562 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1566 ufshcd_release(hba);
1567 ufshcd_rpm_put_sync(hba);
1570 return err ? err : count;
1573 static void ufshcd_init_clk_scaling_sysfs(struct ufs_hba *hba)
1575 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1576 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1577 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1578 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1579 hba->clk_scaling.enable_attr.attr.mode = 0644;
1580 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1581 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1584 static void ufshcd_remove_clk_scaling_sysfs(struct ufs_hba *hba)
1586 if (hba->clk_scaling.enable_attr.attr.name)
1587 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
1590 static void ufshcd_init_clk_scaling(struct ufs_hba *hba)
1592 char wq_name[sizeof("ufs_clkscaling_00")];
1594 if (!ufshcd_is_clkscaling_supported(hba))
1597 if (!hba->clk_scaling.min_gear)
1598 hba->clk_scaling.min_gear = UFS_HS_G1;
1600 INIT_WORK(&hba->clk_scaling.suspend_work,
1601 ufshcd_clk_scaling_suspend_work);
1602 INIT_WORK(&hba->clk_scaling.resume_work,
1603 ufshcd_clk_scaling_resume_work);
1605 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
1606 hba->host->host_no);
1607 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
1609 hba->clk_scaling.is_initialized = true;
1612 static void ufshcd_exit_clk_scaling(struct ufs_hba *hba)
1614 if (!hba->clk_scaling.is_initialized)
1617 ufshcd_remove_clk_scaling_sysfs(hba);
1618 destroy_workqueue(hba->clk_scaling.workq);
1619 ufshcd_devfreq_remove(hba);
1620 hba->clk_scaling.is_initialized = false;
1623 static void ufshcd_ungate_work(struct work_struct *work)
1626 unsigned long flags;
1627 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1628 clk_gating.ungate_work);
1630 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1632 spin_lock_irqsave(hba->host->host_lock, flags);
1633 if (hba->clk_gating.state == CLKS_ON) {
1634 spin_unlock_irqrestore(hba->host->host_lock, flags);
1638 spin_unlock_irqrestore(hba->host->host_lock, flags);
1639 ufshcd_hba_vreg_set_hpm(hba);
1640 ufshcd_setup_clocks(hba, true);
1642 ufshcd_enable_irq(hba);
1644 /* Exit from hibern8 */
1645 if (ufshcd_can_hibern8_during_gating(hba)) {
1646 /* Prevent gating in this path */
1647 hba->clk_gating.is_suspended = true;
1648 if (ufshcd_is_link_hibern8(hba)) {
1649 ret = ufshcd_uic_hibern8_exit(hba);
1651 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1654 ufshcd_set_link_active(hba);
1656 hba->clk_gating.is_suspended = false;
1659 ufshcd_scsi_unblock_requests(hba);
1663 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1664 * Also, exit from hibern8 mode and set the link as active.
1665 * @hba: per adapter instance
1666 * @async: This indicates whether caller should ungate clocks asynchronously.
1668 int ufshcd_hold(struct ufs_hba *hba, bool async)
1672 unsigned long flags;
1674 if (!ufshcd_is_clkgating_allowed(hba) ||
1675 !hba->clk_gating.is_initialized)
1677 spin_lock_irqsave(hba->host->host_lock, flags);
1678 hba->clk_gating.active_reqs++;
1681 switch (hba->clk_gating.state) {
1684 * Wait for the ungate work to complete if in progress.
1685 * Though the clocks may be in ON state, the link could
1686 * still be in hibner8 state if hibern8 is allowed
1687 * during clock gating.
1688 * Make sure we exit hibern8 state also in addition to
1691 if (ufshcd_can_hibern8_during_gating(hba) &&
1692 ufshcd_is_link_hibern8(hba)) {
1695 hba->clk_gating.active_reqs--;
1698 spin_unlock_irqrestore(hba->host->host_lock, flags);
1699 flush_result = flush_work(&hba->clk_gating.ungate_work);
1700 if (hba->clk_gating.is_suspended && !flush_result)
1702 spin_lock_irqsave(hba->host->host_lock, flags);
1707 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1708 hba->clk_gating.state = CLKS_ON;
1709 trace_ufshcd_clk_gating(dev_name(hba->dev),
1710 hba->clk_gating.state);
1714 * If we are here, it means gating work is either done or
1715 * currently running. Hence, fall through to cancel gating
1716 * work and to enable clocks.
1720 hba->clk_gating.state = REQ_CLKS_ON;
1721 trace_ufshcd_clk_gating(dev_name(hba->dev),
1722 hba->clk_gating.state);
1723 if (queue_work(hba->clk_gating.clk_gating_workq,
1724 &hba->clk_gating.ungate_work))
1725 ufshcd_scsi_block_requests(hba);
1727 * fall through to check if we should wait for this
1728 * work to be done or not.
1734 hba->clk_gating.active_reqs--;
1738 spin_unlock_irqrestore(hba->host->host_lock, flags);
1739 flush_work(&hba->clk_gating.ungate_work);
1740 /* Make sure state is CLKS_ON before returning */
1741 spin_lock_irqsave(hba->host->host_lock, flags);
1744 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1745 __func__, hba->clk_gating.state);
1748 spin_unlock_irqrestore(hba->host->host_lock, flags);
1752 EXPORT_SYMBOL_GPL(ufshcd_hold);
1754 static void ufshcd_gate_work(struct work_struct *work)
1756 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1757 clk_gating.gate_work.work);
1758 unsigned long flags;
1761 spin_lock_irqsave(hba->host->host_lock, flags);
1763 * In case you are here to cancel this work the gating state
1764 * would be marked as REQ_CLKS_ON. In this case save time by
1765 * skipping the gating work and exit after changing the clock
1768 if (hba->clk_gating.is_suspended ||
1769 (hba->clk_gating.state != REQ_CLKS_OFF)) {
1770 hba->clk_gating.state = CLKS_ON;
1771 trace_ufshcd_clk_gating(dev_name(hba->dev),
1772 hba->clk_gating.state);
1776 if (hba->clk_gating.active_reqs
1777 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1778 || hba->outstanding_reqs || hba->outstanding_tasks
1779 || hba->active_uic_cmd || hba->uic_async_done)
1782 spin_unlock_irqrestore(hba->host->host_lock, flags);
1784 /* put the link into hibern8 mode before turning off clocks */
1785 if (ufshcd_can_hibern8_during_gating(hba)) {
1786 ret = ufshcd_uic_hibern8_enter(hba);
1788 hba->clk_gating.state = CLKS_ON;
1789 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
1791 trace_ufshcd_clk_gating(dev_name(hba->dev),
1792 hba->clk_gating.state);
1795 ufshcd_set_link_hibern8(hba);
1798 ufshcd_disable_irq(hba);
1800 ufshcd_setup_clocks(hba, false);
1802 /* Put the host controller in low power mode if possible */
1803 ufshcd_hba_vreg_set_lpm(hba);
1805 * In case you are here to cancel this work the gating state
1806 * would be marked as REQ_CLKS_ON. In this case keep the state
1807 * as REQ_CLKS_ON which would anyway imply that clocks are off
1808 * and a request to turn them on is pending. By doing this way,
1809 * we keep the state machine in tact and this would ultimately
1810 * prevent from doing cancel work multiple times when there are
1811 * new requests arriving before the current cancel work is done.
1813 spin_lock_irqsave(hba->host->host_lock, flags);
1814 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1815 hba->clk_gating.state = CLKS_OFF;
1816 trace_ufshcd_clk_gating(dev_name(hba->dev),
1817 hba->clk_gating.state);
1820 spin_unlock_irqrestore(hba->host->host_lock, flags);
1825 /* host lock must be held before calling this variant */
1826 static void __ufshcd_release(struct ufs_hba *hba)
1828 if (!ufshcd_is_clkgating_allowed(hba))
1831 hba->clk_gating.active_reqs--;
1833 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended ||
1834 hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL ||
1835 hba->outstanding_tasks || !hba->clk_gating.is_initialized ||
1836 hba->active_uic_cmd || hba->uic_async_done ||
1837 hba->clk_gating.state == CLKS_OFF)
1840 hba->clk_gating.state = REQ_CLKS_OFF;
1841 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1842 queue_delayed_work(hba->clk_gating.clk_gating_workq,
1843 &hba->clk_gating.gate_work,
1844 msecs_to_jiffies(hba->clk_gating.delay_ms));
1847 void ufshcd_release(struct ufs_hba *hba)
1849 unsigned long flags;
1851 spin_lock_irqsave(hba->host->host_lock, flags);
1852 __ufshcd_release(hba);
1853 spin_unlock_irqrestore(hba->host->host_lock, flags);
1855 EXPORT_SYMBOL_GPL(ufshcd_release);
1857 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1858 struct device_attribute *attr, char *buf)
1860 struct ufs_hba *hba = dev_get_drvdata(dev);
1862 return sysfs_emit(buf, "%lu\n", hba->clk_gating.delay_ms);
1865 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1866 struct device_attribute *attr, const char *buf, size_t count)
1868 struct ufs_hba *hba = dev_get_drvdata(dev);
1869 unsigned long flags, value;
1871 if (kstrtoul(buf, 0, &value))
1874 spin_lock_irqsave(hba->host->host_lock, flags);
1875 hba->clk_gating.delay_ms = value;
1876 spin_unlock_irqrestore(hba->host->host_lock, flags);
1880 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1881 struct device_attribute *attr, char *buf)
1883 struct ufs_hba *hba = dev_get_drvdata(dev);
1885 return sysfs_emit(buf, "%d\n", hba->clk_gating.is_enabled);
1888 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1889 struct device_attribute *attr, const char *buf, size_t count)
1891 struct ufs_hba *hba = dev_get_drvdata(dev);
1892 unsigned long flags;
1895 if (kstrtou32(buf, 0, &value))
1900 spin_lock_irqsave(hba->host->host_lock, flags);
1901 if (value == hba->clk_gating.is_enabled)
1905 __ufshcd_release(hba);
1907 hba->clk_gating.active_reqs++;
1909 hba->clk_gating.is_enabled = value;
1911 spin_unlock_irqrestore(hba->host->host_lock, flags);
1915 static void ufshcd_init_clk_gating_sysfs(struct ufs_hba *hba)
1917 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1918 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1919 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1920 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1921 hba->clk_gating.delay_attr.attr.mode = 0644;
1922 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1923 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1925 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
1926 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
1927 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
1928 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
1929 hba->clk_gating.enable_attr.attr.mode = 0644;
1930 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
1931 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1934 static void ufshcd_remove_clk_gating_sysfs(struct ufs_hba *hba)
1936 if (hba->clk_gating.delay_attr.attr.name)
1937 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1938 if (hba->clk_gating.enable_attr.attr.name)
1939 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1942 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1944 char wq_name[sizeof("ufs_clk_gating_00")];
1946 if (!ufshcd_is_clkgating_allowed(hba))
1949 hba->clk_gating.state = CLKS_ON;
1951 hba->clk_gating.delay_ms = 150;
1952 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
1953 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
1955 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d",
1956 hba->host->host_no);
1957 hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(wq_name,
1958 WQ_MEM_RECLAIM | WQ_HIGHPRI);
1960 ufshcd_init_clk_gating_sysfs(hba);
1962 hba->clk_gating.is_enabled = true;
1963 hba->clk_gating.is_initialized = true;
1966 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
1968 if (!hba->clk_gating.is_initialized)
1971 ufshcd_remove_clk_gating_sysfs(hba);
1973 /* Ungate the clock if necessary. */
1974 ufshcd_hold(hba, false);
1975 hba->clk_gating.is_initialized = false;
1976 ufshcd_release(hba);
1978 destroy_workqueue(hba->clk_gating.clk_gating_workq);
1981 /* Must be called with host lock acquired */
1982 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
1984 bool queue_resume_work = false;
1985 ktime_t curr_t = ktime_get();
1986 unsigned long flags;
1988 if (!ufshcd_is_clkscaling_supported(hba))
1991 spin_lock_irqsave(hba->host->host_lock, flags);
1992 if (!hba->clk_scaling.active_reqs++)
1993 queue_resume_work = true;
1995 if (!hba->clk_scaling.is_enabled || hba->pm_op_in_progress) {
1996 spin_unlock_irqrestore(hba->host->host_lock, flags);
2000 if (queue_resume_work)
2001 queue_work(hba->clk_scaling.workq,
2002 &hba->clk_scaling.resume_work);
2004 if (!hba->clk_scaling.window_start_t) {
2005 hba->clk_scaling.window_start_t = curr_t;
2006 hba->clk_scaling.tot_busy_t = 0;
2007 hba->clk_scaling.is_busy_started = false;
2010 if (!hba->clk_scaling.is_busy_started) {
2011 hba->clk_scaling.busy_start_t = curr_t;
2012 hba->clk_scaling.is_busy_started = true;
2014 spin_unlock_irqrestore(hba->host->host_lock, flags);
2017 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
2019 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
2020 unsigned long flags;
2022 if (!ufshcd_is_clkscaling_supported(hba))
2025 spin_lock_irqsave(hba->host->host_lock, flags);
2026 hba->clk_scaling.active_reqs--;
2027 if (!hba->outstanding_reqs && scaling->is_busy_started) {
2028 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
2029 scaling->busy_start_t));
2030 scaling->busy_start_t = 0;
2031 scaling->is_busy_started = false;
2033 spin_unlock_irqrestore(hba->host->host_lock, flags);
2036 static inline int ufshcd_monitor_opcode2dir(u8 opcode)
2038 if (opcode == READ_6 || opcode == READ_10 || opcode == READ_16)
2040 else if (opcode == WRITE_6 || opcode == WRITE_10 || opcode == WRITE_16)
2046 static inline bool ufshcd_should_inform_monitor(struct ufs_hba *hba,
2047 struct ufshcd_lrb *lrbp)
2049 struct ufs_hba_monitor *m = &hba->monitor;
2051 return (m->enabled && lrbp && lrbp->cmd &&
2052 (!m->chunk_size || m->chunk_size == lrbp->cmd->sdb.length) &&
2053 ktime_before(hba->monitor.enabled_ts, lrbp->issue_time_stamp));
2056 static void ufshcd_start_monitor(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2058 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2059 unsigned long flags;
2061 spin_lock_irqsave(hba->host->host_lock, flags);
2062 if (dir >= 0 && hba->monitor.nr_queued[dir]++ == 0)
2063 hba->monitor.busy_start_ts[dir] = ktime_get();
2064 spin_unlock_irqrestore(hba->host->host_lock, flags);
2067 static void ufshcd_update_monitor(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2069 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2070 unsigned long flags;
2072 spin_lock_irqsave(hba->host->host_lock, flags);
2073 if (dir >= 0 && hba->monitor.nr_queued[dir] > 0) {
2074 struct request *req = scsi_cmd_to_rq(lrbp->cmd);
2075 struct ufs_hba_monitor *m = &hba->monitor;
2076 ktime_t now, inc, lat;
2078 now = lrbp->compl_time_stamp;
2079 inc = ktime_sub(now, m->busy_start_ts[dir]);
2080 m->total_busy[dir] = ktime_add(m->total_busy[dir], inc);
2081 m->nr_sec_rw[dir] += blk_rq_sectors(req);
2083 /* Update latencies */
2085 lat = ktime_sub(now, lrbp->issue_time_stamp);
2086 m->lat_sum[dir] += lat;
2087 if (m->lat_max[dir] < lat || !m->lat_max[dir])
2088 m->lat_max[dir] = lat;
2089 if (m->lat_min[dir] > lat || !m->lat_min[dir])
2090 m->lat_min[dir] = lat;
2092 m->nr_queued[dir]--;
2093 /* Push forward the busy start of monitor */
2094 m->busy_start_ts[dir] = now;
2096 spin_unlock_irqrestore(hba->host->host_lock, flags);
2100 * ufshcd_send_command - Send SCSI or device management commands
2101 * @hba: per adapter instance
2102 * @task_tag: Task tag of the command
2105 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
2107 struct ufshcd_lrb *lrbp = &hba->lrb[task_tag];
2108 unsigned long flags;
2110 lrbp->issue_time_stamp = ktime_get();
2111 lrbp->compl_time_stamp = ktime_set(0, 0);
2112 ufshcd_add_command_trace(hba, task_tag, UFS_CMD_SEND);
2113 ufshcd_clk_scaling_start_busy(hba);
2114 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
2115 ufshcd_start_monitor(hba, lrbp);
2117 spin_lock_irqsave(&hba->outstanding_lock, flags);
2118 if (hba->vops && hba->vops->setup_xfer_req)
2119 hba->vops->setup_xfer_req(hba, task_tag, !!lrbp->cmd);
2120 __set_bit(task_tag, &hba->outstanding_reqs);
2121 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
2122 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
2124 /* Make sure that doorbell is committed immediately */
2129 * ufshcd_copy_sense_data - Copy sense data in case of check condition
2130 * @lrbp: pointer to local reference block
2132 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
2135 if (lrbp->sense_buffer &&
2136 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
2139 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
2140 len_to_copy = min_t(int, UFS_SENSE_SIZE, len);
2142 memcpy(lrbp->sense_buffer, lrbp->ucd_rsp_ptr->sr.sense_data,
2148 * ufshcd_copy_query_response() - Copy the Query Response and the data
2150 * @hba: per adapter instance
2151 * @lrbp: pointer to local reference block
2154 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2156 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2158 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
2160 /* Get the descriptor */
2161 if (hba->dev_cmd.query.descriptor &&
2162 lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
2163 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
2164 GENERAL_UPIU_REQUEST_SIZE;
2168 /* data segment length */
2169 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
2170 MASK_QUERY_DATA_SEG_LEN;
2171 buf_len = be16_to_cpu(
2172 hba->dev_cmd.query.request.upiu_req.length);
2173 if (likely(buf_len >= resp_len)) {
2174 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
2177 "%s: rsp size %d is bigger than buffer size %d",
2178 __func__, resp_len, buf_len);
2187 * ufshcd_hba_capabilities - Read controller capabilities
2188 * @hba: per adapter instance
2190 * Return: 0 on success, negative on error.
2192 static inline int ufshcd_hba_capabilities(struct ufs_hba *hba)
2196 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
2198 /* nutrs and nutmrs are 0 based values */
2199 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
2201 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
2202 hba->reserved_slot = hba->nutrs - 1;
2204 /* Read crypto capabilities */
2205 err = ufshcd_hba_init_crypto_capabilities(hba);
2207 dev_err(hba->dev, "crypto setup failed\n");
2213 * ufshcd_ready_for_uic_cmd - Check if controller is ready
2214 * to accept UIC commands
2215 * @hba: per adapter instance
2216 * Return true on success, else false
2218 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
2220 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
2227 * ufshcd_get_upmcrs - Get the power mode change request status
2228 * @hba: Pointer to adapter instance
2230 * This function gets the UPMCRS field of HCS register
2231 * Returns value of UPMCRS field
2233 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
2235 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
2239 * ufshcd_dispatch_uic_cmd - Dispatch an UIC command to the Unipro layer
2240 * @hba: per adapter instance
2241 * @uic_cmd: UIC command
2244 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2246 lockdep_assert_held(&hba->uic_cmd_mutex);
2248 WARN_ON(hba->active_uic_cmd);
2250 hba->active_uic_cmd = uic_cmd;
2253 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2254 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2255 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2257 ufshcd_add_uic_command_trace(hba, uic_cmd, UFS_CMD_SEND);
2260 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2265 * ufshcd_wait_for_uic_cmd - Wait for completion of an UIC command
2266 * @hba: per adapter instance
2267 * @uic_cmd: UIC command
2269 * Returns 0 only if success.
2272 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2275 unsigned long flags;
2277 lockdep_assert_held(&hba->uic_cmd_mutex);
2279 if (wait_for_completion_timeout(&uic_cmd->done,
2280 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
2281 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2285 "uic cmd 0x%x with arg3 0x%x completion timeout\n",
2286 uic_cmd->command, uic_cmd->argument3);
2288 if (!uic_cmd->cmd_active) {
2289 dev_err(hba->dev, "%s: UIC cmd has been completed, return the result\n",
2291 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2295 spin_lock_irqsave(hba->host->host_lock, flags);
2296 hba->active_uic_cmd = NULL;
2297 spin_unlock_irqrestore(hba->host->host_lock, flags);
2303 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2304 * @hba: per adapter instance
2305 * @uic_cmd: UIC command
2306 * @completion: initialize the completion only if this is set to true
2308 * Returns 0 only if success.
2311 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
2314 lockdep_assert_held(&hba->uic_cmd_mutex);
2315 lockdep_assert_held(hba->host->host_lock);
2317 if (!ufshcd_ready_for_uic_cmd(hba)) {
2319 "Controller not ready to accept UIC commands\n");
2324 init_completion(&uic_cmd->done);
2326 uic_cmd->cmd_active = 1;
2327 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2333 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2334 * @hba: per adapter instance
2335 * @uic_cmd: UIC command
2337 * Returns 0 only if success.
2339 int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2342 unsigned long flags;
2344 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UIC_CMD)
2347 ufshcd_hold(hba, false);
2348 mutex_lock(&hba->uic_cmd_mutex);
2349 ufshcd_add_delay_before_dme_cmd(hba);
2351 spin_lock_irqsave(hba->host->host_lock, flags);
2352 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
2353 spin_unlock_irqrestore(hba->host->host_lock, flags);
2355 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2357 mutex_unlock(&hba->uic_cmd_mutex);
2359 ufshcd_release(hba);
2364 * ufshcd_map_sg - Map scatter-gather list to prdt
2365 * @hba: per adapter instance
2366 * @lrbp: pointer to local reference block
2368 * Returns 0 in case of success, non-zero value in case of failure
2370 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2372 struct ufshcd_sg_entry *prd_table;
2373 struct scatterlist *sg;
2374 struct scsi_cmnd *cmd;
2379 sg_segments = scsi_dma_map(cmd);
2380 if (sg_segments < 0)
2385 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2386 lrbp->utr_descriptor_ptr->prd_table_length =
2387 cpu_to_le16((sg_segments *
2388 sizeof(struct ufshcd_sg_entry)));
2390 lrbp->utr_descriptor_ptr->prd_table_length =
2391 cpu_to_le16(sg_segments);
2393 prd_table = lrbp->ucd_prdt_ptr;
2395 scsi_for_each_sg(cmd, sg, sg_segments, i) {
2396 const unsigned int len = sg_dma_len(sg);
2399 * From the UFSHCI spec: "Data Byte Count (DBC): A '0'
2400 * based value that indicates the length, in bytes, of
2401 * the data block. A maximum of length of 256KB may
2402 * exist for any entry. Bits 1:0 of this field shall be
2403 * 11b to indicate Dword granularity. A value of '3'
2404 * indicates 4 bytes, '7' indicates 8 bytes, etc."
2406 WARN_ONCE(len > 256 * 1024, "len = %#x\n", len);
2407 prd_table[i].size = cpu_to_le32(len - 1);
2408 prd_table[i].addr = cpu_to_le64(sg->dma_address);
2409 prd_table[i].reserved = 0;
2412 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2419 * ufshcd_enable_intr - enable interrupts
2420 * @hba: per adapter instance
2421 * @intrs: interrupt bits
2423 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2425 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2427 if (hba->ufs_version == ufshci_version(1, 0)) {
2429 rw = set & INTERRUPT_MASK_RW_VER_10;
2430 set = rw | ((set ^ intrs) & intrs);
2435 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2439 * ufshcd_disable_intr - disable interrupts
2440 * @hba: per adapter instance
2441 * @intrs: interrupt bits
2443 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2445 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2447 if (hba->ufs_version == ufshci_version(1, 0)) {
2449 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2450 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2451 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2457 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2461 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
2462 * descriptor according to request
2463 * @lrbp: pointer to local reference block
2464 * @upiu_flags: flags required in the header
2465 * @cmd_dir: requests data direction
2467 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
2468 u8 *upiu_flags, enum dma_data_direction cmd_dir)
2470 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2476 if (cmd_dir == DMA_FROM_DEVICE) {
2477 data_direction = UTP_DEVICE_TO_HOST;
2478 *upiu_flags = UPIU_CMD_FLAGS_READ;
2479 } else if (cmd_dir == DMA_TO_DEVICE) {
2480 data_direction = UTP_HOST_TO_DEVICE;
2481 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2483 data_direction = UTP_NO_DATA_TRANSFER;
2484 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2487 dword_0 = data_direction | (lrbp->command_type
2488 << UPIU_COMMAND_TYPE_OFFSET);
2490 dword_0 |= UTP_REQ_DESC_INT_CMD;
2492 /* Prepare crypto related dwords */
2493 ufshcd_prepare_req_desc_hdr_crypto(lrbp, &dword_0, &dword_1, &dword_3);
2495 /* Transfer request descriptor header fields */
2496 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2497 req_desc->header.dword_1 = cpu_to_le32(dword_1);
2499 * assigning invalid value for command status. Controller
2500 * updates OCS on command completion, with the command
2503 req_desc->header.dword_2 =
2504 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2505 req_desc->header.dword_3 = cpu_to_le32(dword_3);
2507 req_desc->prd_table_length = 0;
2511 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2513 * @lrbp: local reference block pointer
2514 * @upiu_flags: flags
2517 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u8 upiu_flags)
2519 struct scsi_cmnd *cmd = lrbp->cmd;
2520 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2521 unsigned short cdb_len;
2523 /* command descriptor fields */
2524 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2525 UPIU_TRANSACTION_COMMAND, upiu_flags,
2526 lrbp->lun, lrbp->task_tag);
2527 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2528 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2530 /* Total EHS length and Data segment length will be zero */
2531 ucd_req_ptr->header.dword_2 = 0;
2533 ucd_req_ptr->sc.exp_data_transfer_len = cpu_to_be32(cmd->sdb.length);
2535 cdb_len = min_t(unsigned short, cmd->cmd_len, UFS_CDB_SIZE);
2536 memset(ucd_req_ptr->sc.cdb, 0, UFS_CDB_SIZE);
2537 memcpy(ucd_req_ptr->sc.cdb, cmd->cmnd, cdb_len);
2539 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2543 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
2546 * @lrbp: local reference block pointer
2547 * @upiu_flags: flags
2549 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2550 struct ufshcd_lrb *lrbp, u8 upiu_flags)
2552 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2553 struct ufs_query *query = &hba->dev_cmd.query;
2554 u16 len = be16_to_cpu(query->request.upiu_req.length);
2556 /* Query request header */
2557 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2558 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2559 lrbp->lun, lrbp->task_tag);
2560 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2561 0, query->request.query_func, 0, 0);
2563 /* Data segment length only need for WRITE_DESC */
2564 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2565 ucd_req_ptr->header.dword_2 =
2566 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2568 ucd_req_ptr->header.dword_2 = 0;
2570 /* Copy the Query Request buffer as is */
2571 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2574 /* Copy the Descriptor */
2575 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2576 memcpy(ucd_req_ptr + 1, query->descriptor, len);
2578 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2581 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2583 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2585 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2587 /* command descriptor fields */
2588 ucd_req_ptr->header.dword_0 =
2590 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2591 /* clear rest of the fields of basic header */
2592 ucd_req_ptr->header.dword_1 = 0;
2593 ucd_req_ptr->header.dword_2 = 0;
2595 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2599 * ufshcd_compose_devman_upiu - UFS Protocol Information Unit(UPIU)
2600 * for Device Management Purposes
2601 * @hba: per adapter instance
2602 * @lrbp: pointer to local reference block
2604 static int ufshcd_compose_devman_upiu(struct ufs_hba *hba,
2605 struct ufshcd_lrb *lrbp)
2610 if (hba->ufs_version <= ufshci_version(1, 1))
2611 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2613 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2615 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
2616 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2617 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2618 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2619 ufshcd_prepare_utp_nop_upiu(lrbp);
2627 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2629 * @hba: per adapter instance
2630 * @lrbp: pointer to local reference block
2632 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2637 if (hba->ufs_version <= ufshci_version(1, 1))
2638 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2640 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2642 if (likely(lrbp->cmd)) {
2643 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
2644 lrbp->cmd->sc_data_direction);
2645 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2654 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2655 * @upiu_wlun_id: UPIU W-LUN id
2657 * Returns SCSI W-LUN id
2659 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2661 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2664 static inline bool is_device_wlun(struct scsi_device *sdev)
2667 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN);
2671 * Associate the UFS controller queue with the default and poll HCTX types.
2672 * Initialize the mq_map[] arrays.
2674 static int ufshcd_map_queues(struct Scsi_Host *shost)
2678 for (i = 0; i < shost->nr_maps; i++) {
2679 struct blk_mq_queue_map *map = &shost->tag_set.map[i];
2682 case HCTX_TYPE_DEFAULT:
2683 case HCTX_TYPE_POLL:
2686 case HCTX_TYPE_READ:
2692 map->queue_offset = 0;
2693 ret = blk_mq_map_queues(map);
2700 static void ufshcd_init_lrb(struct ufs_hba *hba, struct ufshcd_lrb *lrb, int i)
2702 struct utp_transfer_cmd_desc *cmd_descp = hba->ucdl_base_addr;
2703 struct utp_transfer_req_desc *utrdlp = hba->utrdl_base_addr;
2704 dma_addr_t cmd_desc_element_addr = hba->ucdl_dma_addr +
2705 i * sizeof(struct utp_transfer_cmd_desc);
2706 u16 response_offset = offsetof(struct utp_transfer_cmd_desc,
2708 u16 prdt_offset = offsetof(struct utp_transfer_cmd_desc, prd_table);
2710 lrb->utr_descriptor_ptr = utrdlp + i;
2711 lrb->utrd_dma_addr = hba->utrdl_dma_addr +
2712 i * sizeof(struct utp_transfer_req_desc);
2713 lrb->ucd_req_ptr = (struct utp_upiu_req *)(cmd_descp + i);
2714 lrb->ucd_req_dma_addr = cmd_desc_element_addr;
2715 lrb->ucd_rsp_ptr = (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
2716 lrb->ucd_rsp_dma_addr = cmd_desc_element_addr + response_offset;
2717 lrb->ucd_prdt_ptr = cmd_descp[i].prd_table;
2718 lrb->ucd_prdt_dma_addr = cmd_desc_element_addr + prdt_offset;
2722 * ufshcd_queuecommand - main entry point for SCSI requests
2723 * @host: SCSI host pointer
2724 * @cmd: command from SCSI Midlayer
2726 * Returns 0 for success, non-zero in case of failure
2728 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2730 struct ufs_hba *hba = shost_priv(host);
2731 int tag = scsi_cmd_to_rq(cmd)->tag;
2732 struct ufshcd_lrb *lrbp;
2735 WARN_ONCE(tag < 0 || tag >= hba->nutrs, "Invalid tag %d\n", tag);
2738 * Allows the UFS error handler to wait for prior ufshcd_queuecommand()
2743 switch (hba->ufshcd_state) {
2744 case UFSHCD_STATE_OPERATIONAL:
2746 case UFSHCD_STATE_EH_SCHEDULED_NON_FATAL:
2748 * SCSI error handler can call ->queuecommand() while UFS error
2749 * handler is in progress. Error interrupts could change the
2750 * state from UFSHCD_STATE_RESET to
2751 * UFSHCD_STATE_EH_SCHEDULED_NON_FATAL. Prevent requests
2752 * being issued in that case.
2754 if (ufshcd_eh_in_progress(hba)) {
2755 err = SCSI_MLQUEUE_HOST_BUSY;
2759 case UFSHCD_STATE_EH_SCHEDULED_FATAL:
2761 * pm_runtime_get_sync() is used at error handling preparation
2762 * stage. If a scsi cmd, e.g. the SSU cmd, is sent from hba's
2763 * PM ops, it can never be finished if we let SCSI layer keep
2764 * retrying it, which gets err handler stuck forever. Neither
2765 * can we let the scsi cmd pass through, because UFS is in bad
2766 * state, the scsi cmd may eventually time out, which will get
2767 * err handler blocked for too long. So, just fail the scsi cmd
2768 * sent from PM ops, err handler can recover PM error anyways.
2770 if (hba->pm_op_in_progress) {
2771 hba->force_reset = true;
2772 set_host_byte(cmd, DID_BAD_TARGET);
2777 case UFSHCD_STATE_RESET:
2778 err = SCSI_MLQUEUE_HOST_BUSY;
2780 case UFSHCD_STATE_ERROR:
2781 set_host_byte(cmd, DID_ERROR);
2786 hba->req_abort_count = 0;
2788 err = ufshcd_hold(hba, true);
2790 err = SCSI_MLQUEUE_HOST_BUSY;
2793 WARN_ON(ufshcd_is_clkgating_allowed(hba) &&
2794 (hba->clk_gating.state != CLKS_ON));
2796 lrbp = &hba->lrb[tag];
2799 lrbp->sense_bufflen = UFS_SENSE_SIZE;
2800 lrbp->sense_buffer = cmd->sense_buffer;
2801 lrbp->task_tag = tag;
2802 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2803 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
2805 ufshcd_prepare_lrbp_crypto(scsi_cmd_to_rq(cmd), lrbp);
2807 lrbp->req_abort_skip = false;
2809 ufshpb_prep(hba, lrbp);
2811 ufshcd_comp_scsi_upiu(hba, lrbp);
2813 err = ufshcd_map_sg(hba, lrbp);
2816 ufshcd_release(hba);
2820 ufshcd_send_command(hba, tag);
2825 if (ufs_trigger_eh()) {
2826 unsigned long flags;
2828 spin_lock_irqsave(hba->host->host_lock, flags);
2829 ufshcd_schedule_eh_work(hba);
2830 spin_unlock_irqrestore(hba->host->host_lock, flags);
2836 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2837 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2840 lrbp->sense_bufflen = 0;
2841 lrbp->sense_buffer = NULL;
2842 lrbp->task_tag = tag;
2843 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2844 lrbp->intr_cmd = true; /* No interrupt aggregation */
2845 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
2846 hba->dev_cmd.type = cmd_type;
2848 return ufshcd_compose_devman_upiu(hba, lrbp);
2852 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
2855 unsigned long flags;
2856 u32 mask = 1 << tag;
2858 /* clear outstanding transaction before retry */
2859 spin_lock_irqsave(hba->host->host_lock, flags);
2860 ufshcd_utrl_clear(hba, tag);
2861 spin_unlock_irqrestore(hba->host->host_lock, flags);
2864 * wait for h/w to clear corresponding bit in door-bell.
2865 * max. wait is 1 sec.
2867 err = ufshcd_wait_for_register(hba,
2868 REG_UTP_TRANSFER_REQ_DOOR_BELL,
2869 mask, ~mask, 1000, 1000);
2875 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2877 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2879 /* Get the UPIU response */
2880 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
2881 UPIU_RSP_CODE_OFFSET;
2882 return query_res->response;
2886 * ufshcd_dev_cmd_completion() - handles device management command responses
2887 * @hba: per adapter instance
2888 * @lrbp: pointer to local reference block
2891 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2896 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
2897 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2900 case UPIU_TRANSACTION_NOP_IN:
2901 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
2903 dev_err(hba->dev, "%s: unexpected response %x\n",
2907 case UPIU_TRANSACTION_QUERY_RSP:
2908 err = ufshcd_check_query_response(hba, lrbp);
2910 err = ufshcd_copy_query_response(hba, lrbp);
2912 case UPIU_TRANSACTION_REJECT_UPIU:
2913 /* TODO: handle Reject UPIU Response */
2915 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
2920 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
2928 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
2929 struct ufshcd_lrb *lrbp, int max_timeout)
2932 unsigned long time_left;
2933 unsigned long flags;
2935 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
2936 msecs_to_jiffies(max_timeout));
2938 spin_lock_irqsave(hba->host->host_lock, flags);
2939 hba->dev_cmd.complete = NULL;
2940 if (likely(time_left)) {
2941 err = ufshcd_get_tr_ocs(lrbp);
2943 err = ufshcd_dev_cmd_completion(hba, lrbp);
2945 spin_unlock_irqrestore(hba->host->host_lock, flags);
2949 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
2950 __func__, lrbp->task_tag);
2951 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
2952 /* successfully cleared the command, retry if needed */
2955 * in case of an error, after clearing the doorbell,
2956 * we also need to clear the outstanding_request
2959 spin_lock_irqsave(&hba->outstanding_lock, flags);
2960 __clear_bit(lrbp->task_tag, &hba->outstanding_reqs);
2961 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
2968 * ufshcd_exec_dev_cmd - API for sending device management requests
2970 * @cmd_type: specifies the type (NOP, Query...)
2971 * @timeout: timeout in milliseconds
2973 * NOTE: Since there is only one available tag for device management commands,
2974 * it is expected you hold the hba->dev_cmd.lock mutex.
2976 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
2977 enum dev_cmd_type cmd_type, int timeout)
2979 DECLARE_COMPLETION_ONSTACK(wait);
2980 const u32 tag = hba->reserved_slot;
2981 struct ufshcd_lrb *lrbp;
2984 /* Protects use of hba->reserved_slot. */
2985 lockdep_assert_held(&hba->dev_cmd.lock);
2987 down_read(&hba->clk_scaling_lock);
2989 lrbp = &hba->lrb[tag];
2991 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
2995 hba->dev_cmd.complete = &wait;
2997 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
2999 ufshcd_send_command(hba, tag);
3000 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
3001 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
3002 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
3005 up_read(&hba->clk_scaling_lock);
3010 * ufshcd_init_query() - init the query response and request parameters
3011 * @hba: per-adapter instance
3012 * @request: address of the request pointer to be initialized
3013 * @response: address of the response pointer to be initialized
3014 * @opcode: operation to perform
3015 * @idn: flag idn to access
3016 * @index: LU number to access
3017 * @selector: query/flag/descriptor further identification
3019 static inline void ufshcd_init_query(struct ufs_hba *hba,
3020 struct ufs_query_req **request, struct ufs_query_res **response,
3021 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
3023 *request = &hba->dev_cmd.query.request;
3024 *response = &hba->dev_cmd.query.response;
3025 memset(*request, 0, sizeof(struct ufs_query_req));
3026 memset(*response, 0, sizeof(struct ufs_query_res));
3027 (*request)->upiu_req.opcode = opcode;
3028 (*request)->upiu_req.idn = idn;
3029 (*request)->upiu_req.index = index;
3030 (*request)->upiu_req.selector = selector;
3033 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
3034 enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res)
3039 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
3040 ret = ufshcd_query_flag(hba, opcode, idn, index, flag_res);
3043 "%s: failed with error %d, retries %d\n",
3044 __func__, ret, retries);
3051 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
3052 __func__, opcode, idn, ret, retries);
3057 * ufshcd_query_flag() - API function for sending flag query requests
3058 * @hba: per-adapter instance
3059 * @opcode: flag query to perform
3060 * @idn: flag idn to access
3061 * @index: flag index to access
3062 * @flag_res: the flag value after the query request completes
3064 * Returns 0 for success, non-zero in case of failure
3066 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
3067 enum flag_idn idn, u8 index, bool *flag_res)
3069 struct ufs_query_req *request = NULL;
3070 struct ufs_query_res *response = NULL;
3071 int err, selector = 0;
3072 int timeout = QUERY_REQ_TIMEOUT;
3076 ufshcd_hold(hba, false);
3077 mutex_lock(&hba->dev_cmd.lock);
3078 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3082 case UPIU_QUERY_OPCODE_SET_FLAG:
3083 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
3084 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
3085 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3087 case UPIU_QUERY_OPCODE_READ_FLAG:
3088 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3090 /* No dummy reads */
3091 dev_err(hba->dev, "%s: Invalid argument for read request\n",
3099 "%s: Expected query flag opcode but got = %d\n",
3105 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
3109 "%s: Sending flag query for idn %d failed, err = %d\n",
3110 __func__, idn, err);
3115 *flag_res = (be32_to_cpu(response->upiu_res.value) &
3116 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
3119 mutex_unlock(&hba->dev_cmd.lock);
3120 ufshcd_release(hba);
3125 * ufshcd_query_attr - API function for sending attribute requests
3126 * @hba: per-adapter instance
3127 * @opcode: attribute opcode
3128 * @idn: attribute idn to access
3129 * @index: index field
3130 * @selector: selector field
3131 * @attr_val: the attribute value after the query request completes
3133 * Returns 0 for success, non-zero in case of failure
3135 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
3136 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
3138 struct ufs_query_req *request = NULL;
3139 struct ufs_query_res *response = NULL;
3145 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
3150 ufshcd_hold(hba, false);
3152 mutex_lock(&hba->dev_cmd.lock);
3153 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3157 case UPIU_QUERY_OPCODE_WRITE_ATTR:
3158 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3159 request->upiu_req.value = cpu_to_be32(*attr_val);
3161 case UPIU_QUERY_OPCODE_READ_ATTR:
3162 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3165 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
3171 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3174 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3175 __func__, opcode, idn, index, err);
3179 *attr_val = be32_to_cpu(response->upiu_res.value);
3182 mutex_unlock(&hba->dev_cmd.lock);
3183 ufshcd_release(hba);
3188 * ufshcd_query_attr_retry() - API function for sending query
3189 * attribute with retries
3190 * @hba: per-adapter instance
3191 * @opcode: attribute opcode
3192 * @idn: attribute idn to access
3193 * @index: index field
3194 * @selector: selector field
3195 * @attr_val: the attribute value after the query request
3198 * Returns 0 for success, non-zero in case of failure
3200 int ufshcd_query_attr_retry(struct ufs_hba *hba,
3201 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
3207 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3208 ret = ufshcd_query_attr(hba, opcode, idn, index,
3209 selector, attr_val);
3211 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
3212 __func__, ret, retries);
3219 "%s: query attribute, idn %d, failed with error %d after %d retires\n",
3220 __func__, idn, ret, QUERY_REQ_RETRIES);
3224 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
3225 enum query_opcode opcode, enum desc_idn idn, u8 index,
3226 u8 selector, u8 *desc_buf, int *buf_len)
3228 struct ufs_query_req *request = NULL;
3229 struct ufs_query_res *response = NULL;
3235 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
3240 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
3241 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
3242 __func__, *buf_len);
3246 ufshcd_hold(hba, false);
3248 mutex_lock(&hba->dev_cmd.lock);
3249 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3251 hba->dev_cmd.query.descriptor = desc_buf;
3252 request->upiu_req.length = cpu_to_be16(*buf_len);
3255 case UPIU_QUERY_OPCODE_WRITE_DESC:
3256 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3258 case UPIU_QUERY_OPCODE_READ_DESC:
3259 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3263 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
3269 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3272 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3273 __func__, opcode, idn, index, err);
3277 *buf_len = be16_to_cpu(response->upiu_res.length);
3280 hba->dev_cmd.query.descriptor = NULL;
3281 mutex_unlock(&hba->dev_cmd.lock);
3282 ufshcd_release(hba);
3287 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3288 * @hba: per-adapter instance
3289 * @opcode: attribute opcode
3290 * @idn: attribute idn to access
3291 * @index: index field
3292 * @selector: selector field
3293 * @desc_buf: the buffer that contains the descriptor
3294 * @buf_len: length parameter passed to the device
3296 * Returns 0 for success, non-zero in case of failure.
3297 * The buf_len parameter will contain, on return, the length parameter
3298 * received on the response.
3300 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3301 enum query_opcode opcode,
3302 enum desc_idn idn, u8 index,
3304 u8 *desc_buf, int *buf_len)
3309 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3310 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3311 selector, desc_buf, buf_len);
3312 if (!err || err == -EINVAL)
3320 * ufshcd_map_desc_id_to_length - map descriptor IDN to its length
3321 * @hba: Pointer to adapter instance
3322 * @desc_id: descriptor idn value
3323 * @desc_len: mapped desc length (out)
3325 void ufshcd_map_desc_id_to_length(struct ufs_hba *hba, enum desc_idn desc_id,
3328 if (desc_id >= QUERY_DESC_IDN_MAX || desc_id == QUERY_DESC_IDN_RFU_0 ||
3329 desc_id == QUERY_DESC_IDN_RFU_1)
3332 *desc_len = hba->desc_size[desc_id];
3334 EXPORT_SYMBOL(ufshcd_map_desc_id_to_length);
3336 static void ufshcd_update_desc_length(struct ufs_hba *hba,
3337 enum desc_idn desc_id, int desc_index,
3338 unsigned char desc_len)
3340 if (hba->desc_size[desc_id] == QUERY_DESC_MAX_SIZE &&
3341 desc_id != QUERY_DESC_IDN_STRING && desc_index != UFS_RPMB_UNIT)
3342 /* For UFS 3.1, the normal unit descriptor is 10 bytes larger
3343 * than the RPMB unit, however, both descriptors share the same
3344 * desc_idn, to cover both unit descriptors with one length, we
3345 * choose the normal unit descriptor length by desc_index.
3347 hba->desc_size[desc_id] = desc_len;
3351 * ufshcd_read_desc_param - read the specified descriptor parameter
3352 * @hba: Pointer to adapter instance
3353 * @desc_id: descriptor idn value
3354 * @desc_index: descriptor index
3355 * @param_offset: offset of the parameter to read
3356 * @param_read_buf: pointer to buffer where parameter would be read
3357 * @param_size: sizeof(param_read_buf)
3359 * Return 0 in case of success, non-zero otherwise
3361 int ufshcd_read_desc_param(struct ufs_hba *hba,
3362 enum desc_idn desc_id,
3371 bool is_kmalloc = true;
3374 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3377 /* Get the length of descriptor */
3378 ufshcd_map_desc_id_to_length(hba, desc_id, &buff_len);
3380 dev_err(hba->dev, "%s: Failed to get desc length\n", __func__);
3384 if (param_offset >= buff_len) {
3385 dev_err(hba->dev, "%s: Invalid offset 0x%x in descriptor IDN 0x%x, length 0x%x\n",
3386 __func__, param_offset, desc_id, buff_len);
3390 /* Check whether we need temp memory */
3391 if (param_offset != 0 || param_size < buff_len) {
3392 desc_buf = kzalloc(buff_len, GFP_KERNEL);
3396 desc_buf = param_read_buf;
3400 /* Request for full descriptor */
3401 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3402 desc_id, desc_index, 0,
3403 desc_buf, &buff_len);
3406 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d\n",
3407 __func__, desc_id, desc_index, param_offset, ret);
3412 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3413 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header\n",
3414 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3419 /* Update descriptor length */
3420 buff_len = desc_buf[QUERY_DESC_LENGTH_OFFSET];
3421 ufshcd_update_desc_length(hba, desc_id, desc_index, buff_len);
3424 /* Make sure we don't copy more data than available */
3425 if (param_offset >= buff_len)
3428 memcpy(param_read_buf, &desc_buf[param_offset],
3429 min_t(u32, param_size, buff_len - param_offset));
3438 * struct uc_string_id - unicode string
3440 * @len: size of this descriptor inclusive
3441 * @type: descriptor type
3442 * @uc: unicode string character
3444 struct uc_string_id {
3450 /* replace non-printable or non-ASCII characters with spaces */
3451 static inline char ufshcd_remove_non_printable(u8 ch)
3453 return (ch >= 0x20 && ch <= 0x7e) ? ch : ' ';
3457 * ufshcd_read_string_desc - read string descriptor
3458 * @hba: pointer to adapter instance
3459 * @desc_index: descriptor index
3460 * @buf: pointer to buffer where descriptor would be read,
3461 * the caller should free the memory.
3462 * @ascii: if true convert from unicode to ascii characters
3463 * null terminated string.
3466 * * string size on success.
3467 * * -ENOMEM: on allocation failure
3468 * * -EINVAL: on a wrong parameter
3470 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index,
3471 u8 **buf, bool ascii)
3473 struct uc_string_id *uc_str;
3480 uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
3484 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_STRING, desc_index, 0,
3485 (u8 *)uc_str, QUERY_DESC_MAX_SIZE);
3487 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n",
3488 QUERY_REQ_RETRIES, ret);
3493 if (uc_str->len <= QUERY_DESC_HDR_SIZE) {
3494 dev_dbg(hba->dev, "String Desc is of zero length\n");
3503 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3504 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3505 str = kzalloc(ascii_len, GFP_KERNEL);
3512 * the descriptor contains string in UTF16 format
3513 * we need to convert to utf-8 so it can be displayed
3515 ret = utf16s_to_utf8s(uc_str->uc,
3516 uc_str->len - QUERY_DESC_HDR_SIZE,
3517 UTF16_BIG_ENDIAN, str, ascii_len);
3519 /* replace non-printable or non-ASCII characters with spaces */
3520 for (i = 0; i < ret; i++)
3521 str[i] = ufshcd_remove_non_printable(str[i]);
3526 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL);
3540 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3541 * @hba: Pointer to adapter instance
3543 * @param_offset: offset of the parameter to read
3544 * @param_read_buf: pointer to buffer where parameter would be read
3545 * @param_size: sizeof(param_read_buf)
3547 * Return 0 in case of success, non-zero otherwise
3549 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3551 enum unit_desc_param param_offset,
3556 * Unit descriptors are only available for general purpose LUs (LUN id
3557 * from 0 to 7) and RPMB Well known LU.
3559 if (!ufs_is_valid_unit_desc_lun(&hba->dev_info, lun, param_offset))
3562 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3563 param_offset, param_read_buf, param_size);
3566 static int ufshcd_get_ref_clk_gating_wait(struct ufs_hba *hba)
3569 u32 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3571 if (hba->dev_info.wspecversion >= 0x300) {
3572 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3573 QUERY_ATTR_IDN_REF_CLK_GATING_WAIT_TIME, 0, 0,
3576 dev_err(hba->dev, "Failed reading bRefClkGatingWait. err = %d, use default %uus\n",
3579 if (gating_wait == 0) {
3580 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3581 dev_err(hba->dev, "Undefined ref clk gating wait time, use default %uus\n",
3585 hba->dev_info.clk_gating_wait_us = gating_wait;
3592 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3593 * @hba: per adapter instance
3595 * 1. Allocate DMA memory for Command Descriptor array
3596 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3597 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3598 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3600 * 4. Allocate memory for local reference block(lrb).
3602 * Returns 0 for success, non-zero in case of failure
3604 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3606 size_t utmrdl_size, utrdl_size, ucdl_size;
3608 /* Allocate memory for UTP command descriptors */
3609 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3610 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3612 &hba->ucdl_dma_addr,
3616 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3617 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3618 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3619 * be aligned to 128 bytes as well
3621 if (!hba->ucdl_base_addr ||
3622 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3624 "Command Descriptor Memory allocation failed\n");
3629 * Allocate memory for UTP Transfer descriptors
3630 * UFSHCI requires 1024 byte alignment of UTRD
3632 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3633 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3635 &hba->utrdl_dma_addr,
3637 if (!hba->utrdl_base_addr ||
3638 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3640 "Transfer Descriptor Memory allocation failed\n");
3645 * Allocate memory for UTP Task Management descriptors
3646 * UFSHCI requires 1024 byte alignment of UTMRD
3648 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3649 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3651 &hba->utmrdl_dma_addr,
3653 if (!hba->utmrdl_base_addr ||
3654 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3656 "Task Management Descriptor Memory allocation failed\n");
3660 /* Allocate memory for local reference block */
3661 hba->lrb = devm_kcalloc(hba->dev,
3662 hba->nutrs, sizeof(struct ufshcd_lrb),
3665 dev_err(hba->dev, "LRB Memory allocation failed\n");
3674 * ufshcd_host_memory_configure - configure local reference block with
3676 * @hba: per adapter instance
3678 * Configure Host memory space
3679 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3681 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3683 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3684 * into local reference block.
3686 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3688 struct utp_transfer_req_desc *utrdlp;
3689 dma_addr_t cmd_desc_dma_addr;
3690 dma_addr_t cmd_desc_element_addr;
3691 u16 response_offset;
3696 utrdlp = hba->utrdl_base_addr;
3699 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3701 offsetof(struct utp_transfer_cmd_desc, prd_table);
3703 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
3704 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3706 for (i = 0; i < hba->nutrs; i++) {
3707 /* Configure UTRD with command descriptor base address */
3708 cmd_desc_element_addr =
3709 (cmd_desc_dma_addr + (cmd_desc_size * i));
3710 utrdlp[i].command_desc_base_addr_lo =
3711 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3712 utrdlp[i].command_desc_base_addr_hi =
3713 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3715 /* Response upiu and prdt offset should be in double words */
3716 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3717 utrdlp[i].response_upiu_offset =
3718 cpu_to_le16(response_offset);
3719 utrdlp[i].prd_table_offset =
3720 cpu_to_le16(prdt_offset);
3721 utrdlp[i].response_upiu_length =
3722 cpu_to_le16(ALIGNED_UPIU_SIZE);
3724 utrdlp[i].response_upiu_offset =
3725 cpu_to_le16(response_offset >> 2);
3726 utrdlp[i].prd_table_offset =
3727 cpu_to_le16(prdt_offset >> 2);
3728 utrdlp[i].response_upiu_length =
3729 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3732 ufshcd_init_lrb(hba, &hba->lrb[i], i);
3737 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3738 * @hba: per adapter instance
3740 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3741 * in order to initialize the Unipro link startup procedure.
3742 * Once the Unipro links are up, the device connected to the controller
3745 * Returns 0 on success, non-zero value on failure
3747 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3749 struct uic_command uic_cmd = {0};
3752 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3754 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3757 "dme-link-startup: error code %d\n", ret);
3761 * ufshcd_dme_reset - UIC command for DME_RESET
3762 * @hba: per adapter instance
3764 * DME_RESET command is issued in order to reset UniPro stack.
3765 * This function now deals with cold reset.
3767 * Returns 0 on success, non-zero value on failure
3769 static int ufshcd_dme_reset(struct ufs_hba *hba)
3771 struct uic_command uic_cmd = {0};
3774 uic_cmd.command = UIC_CMD_DME_RESET;
3776 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3779 "dme-reset: error code %d\n", ret);
3784 int ufshcd_dme_configure_adapt(struct ufs_hba *hba,
3790 if (agreed_gear != UFS_HS_G4)
3791 adapt_val = PA_NO_ADAPT;
3793 ret = ufshcd_dme_set(hba,
3794 UIC_ARG_MIB(PA_TXHSADAPTTYPE),
3798 EXPORT_SYMBOL_GPL(ufshcd_dme_configure_adapt);
3801 * ufshcd_dme_enable - UIC command for DME_ENABLE
3802 * @hba: per adapter instance
3804 * DME_ENABLE command is issued in order to enable UniPro stack.
3806 * Returns 0 on success, non-zero value on failure
3808 static int ufshcd_dme_enable(struct ufs_hba *hba)
3810 struct uic_command uic_cmd = {0};
3813 uic_cmd.command = UIC_CMD_DME_ENABLE;
3815 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3818 "dme-enable: error code %d\n", ret);
3823 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3825 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3826 unsigned long min_sleep_time_us;
3828 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3832 * last_dme_cmd_tstamp will be 0 only for 1st call to
3835 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3836 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3838 unsigned long delta =
3839 (unsigned long) ktime_to_us(
3840 ktime_sub(ktime_get(),
3841 hba->last_dme_cmd_tstamp));
3843 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3845 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3847 return; /* no more delay required */
3850 /* allow sleep for extra 50us if needed */
3851 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3855 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3856 * @hba: per adapter instance
3857 * @attr_sel: uic command argument1
3858 * @attr_set: attribute set type as uic command argument2
3859 * @mib_val: setting value as uic command argument3
3860 * @peer: indicate whether peer or local
3862 * Returns 0 on success, non-zero value on failure
3864 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3865 u8 attr_set, u32 mib_val, u8 peer)
3867 struct uic_command uic_cmd = {0};
3868 static const char *const action[] = {
3872 const char *set = action[!!peer];
3874 int retries = UFS_UIC_COMMAND_RETRIES;
3876 uic_cmd.command = peer ?
3877 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3878 uic_cmd.argument1 = attr_sel;
3879 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3880 uic_cmd.argument3 = mib_val;
3883 /* for peer attributes we retry upon failure */
3884 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3886 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
3887 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
3888 } while (ret && peer && --retries);
3891 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
3892 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
3893 UFS_UIC_COMMAND_RETRIES - retries);
3897 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
3900 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
3901 * @hba: per adapter instance
3902 * @attr_sel: uic command argument1
3903 * @mib_val: the value of the attribute as returned by the UIC command
3904 * @peer: indicate whether peer or local
3906 * Returns 0 on success, non-zero value on failure
3908 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
3909 u32 *mib_val, u8 peer)
3911 struct uic_command uic_cmd = {0};
3912 static const char *const action[] = {
3916 const char *get = action[!!peer];
3918 int retries = UFS_UIC_COMMAND_RETRIES;
3919 struct ufs_pa_layer_attr orig_pwr_info;
3920 struct ufs_pa_layer_attr temp_pwr_info;
3921 bool pwr_mode_change = false;
3923 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
3924 orig_pwr_info = hba->pwr_info;
3925 temp_pwr_info = orig_pwr_info;
3927 if (orig_pwr_info.pwr_tx == FAST_MODE ||
3928 orig_pwr_info.pwr_rx == FAST_MODE) {
3929 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
3930 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
3931 pwr_mode_change = true;
3932 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
3933 orig_pwr_info.pwr_rx == SLOW_MODE) {
3934 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
3935 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
3936 pwr_mode_change = true;
3938 if (pwr_mode_change) {
3939 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
3945 uic_cmd.command = peer ?
3946 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
3947 uic_cmd.argument1 = attr_sel;
3950 /* for peer attributes we retry upon failure */
3951 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3953 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
3954 get, UIC_GET_ATTR_ID(attr_sel), ret);
3955 } while (ret && peer && --retries);
3958 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
3959 get, UIC_GET_ATTR_ID(attr_sel),
3960 UFS_UIC_COMMAND_RETRIES - retries);
3962 if (mib_val && !ret)
3963 *mib_val = uic_cmd.argument3;
3965 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
3967 ufshcd_change_power_mode(hba, &orig_pwr_info);
3971 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
3974 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
3975 * state) and waits for it to take effect.
3977 * @hba: per adapter instance
3978 * @cmd: UIC command to execute
3980 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
3981 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
3982 * and device UniPro link and hence it's final completion would be indicated by
3983 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
3984 * addition to normal UIC command completion Status (UCCS). This function only
3985 * returns after the relevant status bits indicate the completion.
3987 * Returns 0 on success, non-zero value on failure
3989 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
3991 DECLARE_COMPLETION_ONSTACK(uic_async_done);
3992 unsigned long flags;
3995 bool reenable_intr = false;
3997 mutex_lock(&hba->uic_cmd_mutex);
3998 ufshcd_add_delay_before_dme_cmd(hba);
4000 spin_lock_irqsave(hba->host->host_lock, flags);
4001 if (ufshcd_is_link_broken(hba)) {
4005 hba->uic_async_done = &uic_async_done;
4006 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
4007 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
4009 * Make sure UIC command completion interrupt is disabled before
4010 * issuing UIC command.
4013 reenable_intr = true;
4015 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
4016 spin_unlock_irqrestore(hba->host->host_lock, flags);
4019 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
4020 cmd->command, cmd->argument3, ret);
4024 if (!wait_for_completion_timeout(hba->uic_async_done,
4025 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
4027 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
4028 cmd->command, cmd->argument3);
4030 if (!cmd->cmd_active) {
4031 dev_err(hba->dev, "%s: Power Mode Change operation has been completed, go check UPMCRS\n",
4041 status = ufshcd_get_upmcrs(hba);
4042 if (status != PWR_LOCAL) {
4044 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
4045 cmd->command, status);
4046 ret = (status != PWR_OK) ? status : -1;
4050 ufshcd_print_host_state(hba);
4051 ufshcd_print_pwr_info(hba);
4052 ufshcd_print_evt_hist(hba);
4055 spin_lock_irqsave(hba->host->host_lock, flags);
4056 hba->active_uic_cmd = NULL;
4057 hba->uic_async_done = NULL;
4059 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
4061 ufshcd_set_link_broken(hba);
4062 ufshcd_schedule_eh_work(hba);
4065 spin_unlock_irqrestore(hba->host->host_lock, flags);
4066 mutex_unlock(&hba->uic_cmd_mutex);
4072 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
4073 * using DME_SET primitives.
4074 * @hba: per adapter instance
4075 * @mode: powr mode value
4077 * Returns 0 on success, non-zero value on failure
4079 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
4081 struct uic_command uic_cmd = {0};
4084 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
4085 ret = ufshcd_dme_set(hba,
4086 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
4088 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
4094 uic_cmd.command = UIC_CMD_DME_SET;
4095 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
4096 uic_cmd.argument3 = mode;
4097 ufshcd_hold(hba, false);
4098 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4099 ufshcd_release(hba);
4105 int ufshcd_link_recovery(struct ufs_hba *hba)
4108 unsigned long flags;
4110 spin_lock_irqsave(hba->host->host_lock, flags);
4111 hba->ufshcd_state = UFSHCD_STATE_RESET;
4112 ufshcd_set_eh_in_progress(hba);
4113 spin_unlock_irqrestore(hba->host->host_lock, flags);
4115 /* Reset the attached device */
4116 ufshcd_device_reset(hba);
4118 ret = ufshcd_host_reset_and_restore(hba);
4120 spin_lock_irqsave(hba->host->host_lock, flags);
4122 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4123 ufshcd_clear_eh_in_progress(hba);
4124 spin_unlock_irqrestore(hba->host->host_lock, flags);
4127 dev_err(hba->dev, "%s: link recovery failed, err %d",
4132 EXPORT_SYMBOL_GPL(ufshcd_link_recovery);
4134 int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
4137 struct uic_command uic_cmd = {0};
4138 ktime_t start = ktime_get();
4140 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
4142 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
4143 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4144 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
4145 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4148 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
4151 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
4156 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_enter);
4158 int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
4160 struct uic_command uic_cmd = {0};
4162 ktime_t start = ktime_get();
4164 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
4166 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
4167 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4168 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
4169 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4172 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
4175 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
4177 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_get();
4178 hba->ufs_stats.hibern8_exit_cnt++;
4183 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_exit);
4185 void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit)
4187 unsigned long flags;
4188 bool update = false;
4190 if (!ufshcd_is_auto_hibern8_supported(hba))
4193 spin_lock_irqsave(hba->host->host_lock, flags);
4194 if (hba->ahit != ahit) {
4198 spin_unlock_irqrestore(hba->host->host_lock, flags);
4201 !pm_runtime_suspended(&hba->sdev_ufs_device->sdev_gendev)) {
4202 ufshcd_rpm_get_sync(hba);
4203 ufshcd_hold(hba, false);
4204 ufshcd_auto_hibern8_enable(hba);
4205 ufshcd_release(hba);
4206 ufshcd_rpm_put_sync(hba);
4209 EXPORT_SYMBOL_GPL(ufshcd_auto_hibern8_update);
4211 void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
4213 unsigned long flags;
4215 if (!ufshcd_is_auto_hibern8_supported(hba))
4218 spin_lock_irqsave(hba->host->host_lock, flags);
4219 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
4220 spin_unlock_irqrestore(hba->host->host_lock, flags);
4224 * ufshcd_init_pwr_info - setting the POR (power on reset)
4225 * values in hba power info
4226 * @hba: per-adapter instance
4228 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
4230 hba->pwr_info.gear_rx = UFS_PWM_G1;
4231 hba->pwr_info.gear_tx = UFS_PWM_G1;
4232 hba->pwr_info.lane_rx = 1;
4233 hba->pwr_info.lane_tx = 1;
4234 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
4235 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
4236 hba->pwr_info.hs_rate = 0;
4240 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
4241 * @hba: per-adapter instance
4243 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
4245 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
4247 if (hba->max_pwr_info.is_valid)
4250 pwr_info->pwr_tx = FAST_MODE;
4251 pwr_info->pwr_rx = FAST_MODE;
4252 pwr_info->hs_rate = PA_HS_MODE_B;
4254 /* Get the connected lane count */
4255 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
4256 &pwr_info->lane_rx);
4257 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4258 &pwr_info->lane_tx);
4260 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
4261 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4269 * First, get the maximum gears of HS speed.
4270 * If a zero value, it means there is no HSGEAR capability.
4271 * Then, get the maximum gears of PWM speed.
4273 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4274 if (!pwr_info->gear_rx) {
4275 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4276 &pwr_info->gear_rx);
4277 if (!pwr_info->gear_rx) {
4278 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4279 __func__, pwr_info->gear_rx);
4282 pwr_info->pwr_rx = SLOW_MODE;
4285 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4286 &pwr_info->gear_tx);
4287 if (!pwr_info->gear_tx) {
4288 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4289 &pwr_info->gear_tx);
4290 if (!pwr_info->gear_tx) {
4291 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4292 __func__, pwr_info->gear_tx);
4295 pwr_info->pwr_tx = SLOW_MODE;
4298 hba->max_pwr_info.is_valid = true;
4302 static int ufshcd_change_power_mode(struct ufs_hba *hba,
4303 struct ufs_pa_layer_attr *pwr_mode)
4307 /* if already configured to the requested pwr_mode */
4308 if (!hba->force_pmc &&
4309 pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4310 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4311 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4312 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4313 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4314 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4315 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4316 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4321 * Configure attributes for power mode change with below.
4322 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4323 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4326 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4327 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4329 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4330 pwr_mode->pwr_rx == FAST_MODE)
4331 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
4333 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
4335 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4336 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4338 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4339 pwr_mode->pwr_tx == FAST_MODE)
4340 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
4342 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
4344 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4345 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4346 pwr_mode->pwr_rx == FAST_MODE ||
4347 pwr_mode->pwr_tx == FAST_MODE)
4348 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4351 if (!(hba->quirks & UFSHCD_QUIRK_SKIP_DEF_UNIPRO_TIMEOUT_SETTING)) {
4352 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0),
4353 DL_FC0ProtectionTimeOutVal_Default);
4354 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1),
4355 DL_TC0ReplayTimeOutVal_Default);
4356 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2),
4357 DL_AFC0ReqTimeOutVal_Default);
4358 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA3),
4359 DL_FC1ProtectionTimeOutVal_Default);
4360 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA4),
4361 DL_TC1ReplayTimeOutVal_Default);
4362 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA5),
4363 DL_AFC1ReqTimeOutVal_Default);
4365 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal),
4366 DL_FC0ProtectionTimeOutVal_Default);
4367 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal),
4368 DL_TC0ReplayTimeOutVal_Default);
4369 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal),
4370 DL_AFC0ReqTimeOutVal_Default);
4373 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4374 | pwr_mode->pwr_tx);
4378 "%s: power mode change failed %d\n", __func__, ret);
4380 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4383 memcpy(&hba->pwr_info, pwr_mode,
4384 sizeof(struct ufs_pa_layer_attr));
4391 * ufshcd_config_pwr_mode - configure a new power mode
4392 * @hba: per-adapter instance
4393 * @desired_pwr_mode: desired power configuration
4395 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4396 struct ufs_pa_layer_attr *desired_pwr_mode)
4398 struct ufs_pa_layer_attr final_params = { 0 };
4401 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4402 desired_pwr_mode, &final_params);
4405 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4407 ret = ufshcd_change_power_mode(hba, &final_params);
4411 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4414 * ufshcd_complete_dev_init() - checks device readiness
4415 * @hba: per-adapter instance
4417 * Set fDeviceInit flag and poll until device toggles it.
4419 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4422 bool flag_res = true;
4425 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4426 QUERY_FLAG_IDN_FDEVICEINIT, 0, NULL);
4429 "%s setting fDeviceInit flag failed with error %d\n",
4434 /* Poll fDeviceInit flag to be cleared */
4435 timeout = ktime_add_ms(ktime_get(), FDEVICEINIT_COMPL_TIMEOUT);
4437 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4438 QUERY_FLAG_IDN_FDEVICEINIT, 0, &flag_res);
4441 usleep_range(5000, 10000);
4442 } while (ktime_before(ktime_get(), timeout));
4446 "%s reading fDeviceInit flag failed with error %d\n",
4448 } else if (flag_res) {
4450 "%s fDeviceInit was not cleared by the device\n",
4459 * ufshcd_make_hba_operational - Make UFS controller operational
4460 * @hba: per adapter instance
4462 * To bring UFS host controller to operational state,
4463 * 1. Enable required interrupts
4464 * 2. Configure interrupt aggregation
4465 * 3. Program UTRL and UTMRL base address
4466 * 4. Configure run-stop-registers
4468 * Returns 0 on success, non-zero value on failure
4470 int ufshcd_make_hba_operational(struct ufs_hba *hba)
4475 /* Enable required interrupts */
4476 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4478 /* Configure interrupt aggregation */
4479 if (ufshcd_is_intr_aggr_allowed(hba))
4480 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4482 ufshcd_disable_intr_aggr(hba);
4484 /* Configure UTRL and UTMRL base address registers */
4485 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4486 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4487 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4488 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4489 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4490 REG_UTP_TASK_REQ_LIST_BASE_L);
4491 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4492 REG_UTP_TASK_REQ_LIST_BASE_H);
4495 * Make sure base address and interrupt setup are updated before
4496 * enabling the run/stop registers below.
4501 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4503 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4504 if (!(ufshcd_get_lists_status(reg))) {
4505 ufshcd_enable_run_stop_reg(hba);
4508 "Host controller not ready to process requests");
4514 EXPORT_SYMBOL_GPL(ufshcd_make_hba_operational);
4517 * ufshcd_hba_stop - Send controller to reset state
4518 * @hba: per adapter instance
4520 void ufshcd_hba_stop(struct ufs_hba *hba)
4522 unsigned long flags;
4526 * Obtain the host lock to prevent that the controller is disabled
4527 * while the UFS interrupt handler is active on another CPU.
4529 spin_lock_irqsave(hba->host->host_lock, flags);
4530 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4531 spin_unlock_irqrestore(hba->host->host_lock, flags);
4533 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4534 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4537 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4539 EXPORT_SYMBOL_GPL(ufshcd_hba_stop);
4542 * ufshcd_hba_execute_hce - initialize the controller
4543 * @hba: per adapter instance
4545 * The controller resets itself and controller firmware initialization
4546 * sequence kicks off. When controller is ready it will set
4547 * the Host Controller Enable bit to 1.
4549 * Returns 0 on success, non-zero value on failure
4551 static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
4553 int retry_outer = 3;
4557 if (!ufshcd_is_hba_active(hba))
4558 /* change controller state to "reset state" */
4559 ufshcd_hba_stop(hba);
4561 /* UniPro link is disabled at this point */
4562 ufshcd_set_link_off(hba);
4564 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4566 /* start controller initialization sequence */
4567 ufshcd_hba_start(hba);
4570 * To initialize a UFS host controller HCE bit must be set to 1.
4571 * During initialization the HCE bit value changes from 1->0->1.
4572 * When the host controller completes initialization sequence
4573 * it sets the value of HCE bit to 1. The same HCE bit is read back
4574 * to check if the controller has completed initialization sequence.
4575 * So without this delay the value HCE = 1, set in the previous
4576 * instruction might be read back.
4577 * This delay can be changed based on the controller.
4579 ufshcd_delay_us(hba->vps->hba_enable_delay_us, 100);
4581 /* wait for the host controller to complete initialization */
4583 while (ufshcd_is_hba_active(hba)) {
4588 "Controller enable failed\n");
4595 usleep_range(1000, 1100);
4598 /* enable UIC related interrupts */
4599 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4601 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4606 int ufshcd_hba_enable(struct ufs_hba *hba)
4610 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
4611 ufshcd_set_link_off(hba);
4612 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4614 /* enable UIC related interrupts */
4615 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4616 ret = ufshcd_dme_reset(hba);
4618 ret = ufshcd_dme_enable(hba);
4620 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4623 "Host controller enable failed with non-hce\n");
4626 ret = ufshcd_hba_execute_hce(hba);
4631 EXPORT_SYMBOL_GPL(ufshcd_hba_enable);
4633 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4635 int tx_lanes = 0, i, err = 0;
4638 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4641 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4643 for (i = 0; i < tx_lanes; i++) {
4645 err = ufshcd_dme_set(hba,
4646 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4647 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4650 err = ufshcd_dme_peer_set(hba,
4651 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4652 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4655 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4656 __func__, peer, i, err);
4664 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4666 return ufshcd_disable_tx_lcc(hba, true);
4669 void ufshcd_update_evt_hist(struct ufs_hba *hba, u32 id, u32 val)
4671 struct ufs_event_hist *e;
4673 if (id >= UFS_EVT_CNT)
4676 e = &hba->ufs_stats.event[id];
4677 e->val[e->pos] = val;
4678 e->tstamp[e->pos] = ktime_get();
4680 e->pos = (e->pos + 1) % UFS_EVENT_HIST_LENGTH;
4682 ufshcd_vops_event_notify(hba, id, &val);
4684 EXPORT_SYMBOL_GPL(ufshcd_update_evt_hist);
4687 * ufshcd_link_startup - Initialize unipro link startup
4688 * @hba: per adapter instance
4690 * Returns 0 for success, non-zero in case of failure
4692 static int ufshcd_link_startup(struct ufs_hba *hba)
4695 int retries = DME_LINKSTARTUP_RETRIES;
4696 bool link_startup_again = false;
4699 * If UFS device isn't active then we will have to issue link startup
4700 * 2 times to make sure the device state move to active.
4702 if (!ufshcd_is_ufs_dev_active(hba))
4703 link_startup_again = true;
4707 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4709 ret = ufshcd_dme_link_startup(hba);
4711 /* check if device is detected by inter-connect layer */
4712 if (!ret && !ufshcd_is_device_present(hba)) {
4713 ufshcd_update_evt_hist(hba,
4714 UFS_EVT_LINK_STARTUP_FAIL,
4716 dev_err(hba->dev, "%s: Device not present\n", __func__);
4722 * DME link lost indication is only received when link is up,
4723 * but we can't be sure if the link is up until link startup
4724 * succeeds. So reset the local Uni-Pro and try again.
4726 if (ret && ufshcd_hba_enable(hba)) {
4727 ufshcd_update_evt_hist(hba,
4728 UFS_EVT_LINK_STARTUP_FAIL,
4732 } while (ret && retries--);
4735 /* failed to get the link up... retire */
4736 ufshcd_update_evt_hist(hba,
4737 UFS_EVT_LINK_STARTUP_FAIL,
4742 if (link_startup_again) {
4743 link_startup_again = false;
4744 retries = DME_LINKSTARTUP_RETRIES;
4748 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4749 ufshcd_init_pwr_info(hba);
4750 ufshcd_print_pwr_info(hba);
4752 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4753 ret = ufshcd_disable_device_tx_lcc(hba);
4758 /* Include any host controller configuration via UIC commands */
4759 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4763 /* Clear UECPA once due to LINERESET has happened during LINK_STARTUP */
4764 ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
4765 ret = ufshcd_make_hba_operational(hba);
4768 dev_err(hba->dev, "link startup failed %d\n", ret);
4769 ufshcd_print_host_state(hba);
4770 ufshcd_print_pwr_info(hba);
4771 ufshcd_print_evt_hist(hba);
4777 * ufshcd_verify_dev_init() - Verify device initialization
4778 * @hba: per-adapter instance
4780 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4781 * device Transport Protocol (UTP) layer is ready after a reset.
4782 * If the UTP layer at the device side is not initialized, it may
4783 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4784 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4786 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4791 ufshcd_hold(hba, false);
4792 mutex_lock(&hba->dev_cmd.lock);
4793 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4794 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4795 hba->nop_out_timeout);
4797 if (!err || err == -ETIMEDOUT)
4800 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4802 mutex_unlock(&hba->dev_cmd.lock);
4803 ufshcd_release(hba);
4806 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4811 * ufshcd_set_queue_depth - set lun queue depth
4812 * @sdev: pointer to SCSI device
4814 * Read bLUQueueDepth value and activate scsi tagged command
4815 * queueing. For WLUN, queue depth is set to 1. For best-effort
4816 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
4817 * value that host can queue.
4819 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
4823 struct ufs_hba *hba;
4825 hba = shost_priv(sdev->host);
4827 lun_qdepth = hba->nutrs;
4828 ret = ufshcd_read_unit_desc_param(hba,
4829 ufshcd_scsi_to_upiu_lun(sdev->lun),
4830 UNIT_DESC_PARAM_LU_Q_DEPTH,
4832 sizeof(lun_qdepth));
4834 /* Some WLUN doesn't support unit descriptor */
4835 if (ret == -EOPNOTSUPP)
4837 else if (!lun_qdepth)
4838 /* eventually, we can figure out the real queue depth */
4839 lun_qdepth = hba->nutrs;
4841 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
4843 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
4844 __func__, lun_qdepth);
4845 scsi_change_queue_depth(sdev, lun_qdepth);
4849 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
4850 * @hba: per-adapter instance
4851 * @lun: UFS device lun id
4852 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
4854 * Returns 0 in case of success and b_lu_write_protect status would be returned
4855 * @b_lu_write_protect parameter.
4856 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
4857 * Returns -EINVAL in case of invalid parameters passed to this function.
4859 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
4861 u8 *b_lu_write_protect)
4865 if (!b_lu_write_protect)
4868 * According to UFS device spec, RPMB LU can't be write
4869 * protected so skip reading bLUWriteProtect parameter for
4870 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
4872 else if (lun >= hba->dev_info.max_lu_supported)
4875 ret = ufshcd_read_unit_desc_param(hba,
4877 UNIT_DESC_PARAM_LU_WR_PROTECT,
4879 sizeof(*b_lu_write_protect));
4884 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
4886 * @hba: per-adapter instance
4887 * @sdev: pointer to SCSI device
4890 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
4891 struct scsi_device *sdev)
4893 if (hba->dev_info.f_power_on_wp_en &&
4894 !hba->dev_info.is_lu_power_on_wp) {
4895 u8 b_lu_write_protect;
4897 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
4898 &b_lu_write_protect) &&
4899 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
4900 hba->dev_info.is_lu_power_on_wp = true;
4905 * ufshcd_setup_links - associate link b/w device wlun and other luns
4906 * @sdev: pointer to SCSI device
4907 * @hba: pointer to ufs hba
4909 static void ufshcd_setup_links(struct ufs_hba *hba, struct scsi_device *sdev)
4911 struct device_link *link;
4914 * Device wlun is the supplier & rest of the luns are consumers.
4915 * This ensures that device wlun suspends after all other luns.
4917 if (hba->sdev_ufs_device) {
4918 link = device_link_add(&sdev->sdev_gendev,
4919 &hba->sdev_ufs_device->sdev_gendev,
4920 DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE);
4922 dev_err(&sdev->sdev_gendev, "Failed establishing link - %s\n",
4923 dev_name(&hba->sdev_ufs_device->sdev_gendev));
4927 /* Ignore REPORT_LUN wlun probing */
4928 if (hba->luns_avail == 1) {
4929 ufshcd_rpm_put(hba);
4934 * Device wlun is probed. The assumption is that WLUNs are
4935 * scanned before other LUNs.
4942 * ufshcd_slave_alloc - handle initial SCSI device configurations
4943 * @sdev: pointer to SCSI device
4947 static int ufshcd_slave_alloc(struct scsi_device *sdev)
4949 struct ufs_hba *hba;
4951 hba = shost_priv(sdev->host);
4953 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
4954 sdev->use_10_for_ms = 1;
4956 /* DBD field should be set to 1 in mode sense(10) */
4957 sdev->set_dbd_for_ms = 1;
4959 /* allow SCSI layer to restart the device in case of errors */
4960 sdev->allow_restart = 1;
4962 /* REPORT SUPPORTED OPERATION CODES is not supported */
4963 sdev->no_report_opcodes = 1;
4965 /* WRITE_SAME command is not supported */
4966 sdev->no_write_same = 1;
4968 ufshcd_set_queue_depth(sdev);
4970 ufshcd_get_lu_power_on_wp_status(hba, sdev);
4972 ufshcd_setup_links(hba, sdev);
4978 * ufshcd_change_queue_depth - change queue depth
4979 * @sdev: pointer to SCSI device
4980 * @depth: required depth to set
4982 * Change queue depth and make sure the max. limits are not crossed.
4984 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
4986 return scsi_change_queue_depth(sdev, min(depth, sdev->host->can_queue));
4989 static void ufshcd_hpb_destroy(struct ufs_hba *hba, struct scsi_device *sdev)
4991 /* skip well-known LU */
4992 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) ||
4993 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba))
4996 ufshpb_destroy_lu(hba, sdev);
4999 static void ufshcd_hpb_configure(struct ufs_hba *hba, struct scsi_device *sdev)
5001 /* skip well-known LU */
5002 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) ||
5003 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba))
5006 ufshpb_init_hpb_lu(hba, sdev);
5010 * ufshcd_slave_configure - adjust SCSI device configurations
5011 * @sdev: pointer to SCSI device
5013 static int ufshcd_slave_configure(struct scsi_device *sdev)
5015 struct ufs_hba *hba = shost_priv(sdev->host);
5016 struct request_queue *q = sdev->request_queue;
5018 ufshcd_hpb_configure(hba, sdev);
5020 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
5021 if (hba->quirks & UFSHCD_QUIRK_ALIGN_SG_WITH_PAGE_SIZE)
5022 blk_queue_update_dma_alignment(q, PAGE_SIZE - 1);
5024 * Block runtime-pm until all consumers are added.
5025 * Refer ufshcd_setup_links().
5027 if (is_device_wlun(sdev))
5028 pm_runtime_get_noresume(&sdev->sdev_gendev);
5029 else if (ufshcd_is_rpm_autosuspend_allowed(hba))
5030 sdev->rpm_autosuspend = 1;
5032 * Do not print messages during runtime PM to avoid never-ending cycles
5033 * of messages written back to storage by user space causing runtime
5034 * resume, causing more messages and so on.
5036 sdev->silence_suspend = 1;
5038 ufshcd_crypto_register(hba, q);
5044 * ufshcd_slave_destroy - remove SCSI device configurations
5045 * @sdev: pointer to SCSI device
5047 static void ufshcd_slave_destroy(struct scsi_device *sdev)
5049 struct ufs_hba *hba;
5050 unsigned long flags;
5052 hba = shost_priv(sdev->host);
5054 ufshcd_hpb_destroy(hba, sdev);
5056 /* Drop the reference as it won't be needed anymore */
5057 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
5058 spin_lock_irqsave(hba->host->host_lock, flags);
5059 hba->sdev_ufs_device = NULL;
5060 spin_unlock_irqrestore(hba->host->host_lock, flags);
5061 } else if (hba->sdev_ufs_device) {
5062 struct device *supplier = NULL;
5064 /* Ensure UFS Device WLUN exists and does not disappear */
5065 spin_lock_irqsave(hba->host->host_lock, flags);
5066 if (hba->sdev_ufs_device) {
5067 supplier = &hba->sdev_ufs_device->sdev_gendev;
5068 get_device(supplier);
5070 spin_unlock_irqrestore(hba->host->host_lock, flags);
5074 * If a LUN fails to probe (e.g. absent BOOT WLUN), the
5075 * device will not have been registered but can still
5076 * have a device link holding a reference to the device.
5078 device_link_remove(&sdev->sdev_gendev, supplier);
5079 put_device(supplier);
5085 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
5086 * @lrbp: pointer to local reference block of completed command
5087 * @scsi_status: SCSI command status
5089 * Returns value base on SCSI command status
5092 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
5096 switch (scsi_status) {
5097 case SAM_STAT_CHECK_CONDITION:
5098 ufshcd_copy_sense_data(lrbp);
5101 result |= DID_OK << 16 | scsi_status;
5103 case SAM_STAT_TASK_SET_FULL:
5105 case SAM_STAT_TASK_ABORTED:
5106 ufshcd_copy_sense_data(lrbp);
5107 result |= scsi_status;
5110 result |= DID_ERROR << 16;
5112 } /* end of switch */
5118 * ufshcd_transfer_rsp_status - Get overall status of the response
5119 * @hba: per adapter instance
5120 * @lrbp: pointer to local reference block of completed command
5122 * Returns result of the command to notify SCSI midlayer
5125 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
5131 /* overall command status of utrd */
5132 ocs = ufshcd_get_tr_ocs(lrbp);
5134 if (hba->quirks & UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR) {
5135 if (be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_1) &
5136 MASK_RSP_UPIU_RESULT)
5142 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
5143 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
5145 case UPIU_TRANSACTION_RESPONSE:
5147 * get the response UPIU result to extract
5148 * the SCSI command status
5150 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
5153 * get the result based on SCSI status response
5154 * to notify the SCSI midlayer of the command status
5156 scsi_status = result & MASK_SCSI_STATUS;
5157 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
5160 * Currently we are only supporting BKOPs exception
5161 * events hence we can ignore BKOPs exception event
5162 * during power management callbacks. BKOPs exception
5163 * event is not expected to be raised in runtime suspend
5164 * callback as it allows the urgent bkops.
5165 * During system suspend, we are anyway forcefully
5166 * disabling the bkops and if urgent bkops is needed
5167 * it will be enabled on system resume. Long term
5168 * solution could be to abort the system suspend if
5169 * UFS device needs urgent BKOPs.
5171 if (!hba->pm_op_in_progress &&
5172 !ufshcd_eh_in_progress(hba) &&
5173 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
5174 /* Flushed in suspend */
5175 schedule_work(&hba->eeh_work);
5177 if (scsi_status == SAM_STAT_GOOD)
5178 ufshpb_rsp_upiu(hba, lrbp);
5180 case UPIU_TRANSACTION_REJECT_UPIU:
5181 /* TODO: handle Reject UPIU Response */
5182 result = DID_ERROR << 16;
5184 "Reject UPIU not fully implemented\n");
5188 "Unexpected request response code = %x\n",
5190 result = DID_ERROR << 16;
5195 result |= DID_ABORT << 16;
5197 case OCS_INVALID_COMMAND_STATUS:
5198 result |= DID_REQUEUE << 16;
5200 case OCS_INVALID_CMD_TABLE_ATTR:
5201 case OCS_INVALID_PRDT_ATTR:
5202 case OCS_MISMATCH_DATA_BUF_SIZE:
5203 case OCS_MISMATCH_RESP_UPIU_SIZE:
5204 case OCS_PEER_COMM_FAILURE:
5205 case OCS_FATAL_ERROR:
5206 case OCS_DEVICE_FATAL_ERROR:
5207 case OCS_INVALID_CRYPTO_CONFIG:
5208 case OCS_GENERAL_CRYPTO_ERROR:
5210 result |= DID_ERROR << 16;
5212 "OCS error from controller = %x for tag %d\n",
5213 ocs, lrbp->task_tag);
5214 ufshcd_print_evt_hist(hba);
5215 ufshcd_print_host_state(hba);
5217 } /* end of switch */
5219 if ((host_byte(result) != DID_OK) &&
5220 (host_byte(result) != DID_REQUEUE) && !hba->silence_err_logs)
5221 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true);
5225 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
5228 if (!ufshcd_is_auto_hibern8_supported(hba) ||
5229 !ufshcd_is_auto_hibern8_enabled(hba))
5232 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
5235 if (hba->active_uic_cmd &&
5236 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
5237 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
5244 * ufshcd_uic_cmd_compl - handle completion of uic command
5245 * @hba: per adapter instance
5246 * @intr_status: interrupt status generated by the controller
5249 * IRQ_HANDLED - If interrupt is valid
5250 * IRQ_NONE - If invalid interrupt
5252 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
5254 irqreturn_t retval = IRQ_NONE;
5256 spin_lock(hba->host->host_lock);
5257 if (ufshcd_is_auto_hibern8_error(hba, intr_status))
5258 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
5260 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
5261 hba->active_uic_cmd->argument2 |=
5262 ufshcd_get_uic_cmd_result(hba);
5263 hba->active_uic_cmd->argument3 =
5264 ufshcd_get_dme_attr_val(hba);
5265 if (!hba->uic_async_done)
5266 hba->active_uic_cmd->cmd_active = 0;
5267 complete(&hba->active_uic_cmd->done);
5268 retval = IRQ_HANDLED;
5271 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done) {
5272 hba->active_uic_cmd->cmd_active = 0;
5273 complete(hba->uic_async_done);
5274 retval = IRQ_HANDLED;
5277 if (retval == IRQ_HANDLED)
5278 ufshcd_add_uic_command_trace(hba, hba->active_uic_cmd,
5280 spin_unlock(hba->host->host_lock);
5284 /* Release the resources allocated for processing a SCSI command. */
5285 static void ufshcd_release_scsi_cmd(struct ufs_hba *hba,
5286 struct ufshcd_lrb *lrbp)
5288 struct scsi_cmnd *cmd = lrbp->cmd;
5290 scsi_dma_unmap(cmd);
5291 lrbp->cmd = NULL; /* Mark the command as completed. */
5292 ufshcd_release(hba);
5293 ufshcd_clk_scaling_update_busy(hba);
5297 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
5298 * @hba: per adapter instance
5299 * @completed_reqs: bitmask that indicates which requests to complete
5301 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
5302 unsigned long completed_reqs)
5304 struct ufshcd_lrb *lrbp;
5305 struct scsi_cmnd *cmd;
5308 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
5309 lrbp = &hba->lrb[index];
5310 lrbp->compl_time_stamp = ktime_get();
5313 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
5314 ufshcd_update_monitor(hba, lrbp);
5315 ufshcd_add_command_trace(hba, index, UFS_CMD_COMP);
5316 cmd->result = ufshcd_transfer_rsp_status(hba, lrbp);
5317 ufshcd_release_scsi_cmd(hba, lrbp);
5318 /* Do not touch lrbp after scsi done */
5320 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
5321 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
5322 if (hba->dev_cmd.complete) {
5323 ufshcd_add_command_trace(hba, index,
5325 complete(hba->dev_cmd.complete);
5326 ufshcd_clk_scaling_update_busy(hba);
5333 * Returns > 0 if one or more commands have been completed or 0 if no
5334 * requests have been completed.
5336 static int ufshcd_poll(struct Scsi_Host *shost, unsigned int queue_num)
5338 struct ufs_hba *hba = shost_priv(shost);
5339 unsigned long completed_reqs, flags;
5342 spin_lock_irqsave(&hba->outstanding_lock, flags);
5343 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5344 completed_reqs = ~tr_doorbell & hba->outstanding_reqs;
5345 WARN_ONCE(completed_reqs & ~hba->outstanding_reqs,
5346 "completed: %#lx; outstanding: %#lx\n", completed_reqs,
5347 hba->outstanding_reqs);
5348 hba->outstanding_reqs &= ~completed_reqs;
5349 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
5352 __ufshcd_transfer_req_compl(hba, completed_reqs);
5354 return completed_reqs;
5358 * ufshcd_transfer_req_compl - handle SCSI and query command completion
5359 * @hba: per adapter instance
5362 * IRQ_HANDLED - If interrupt is valid
5363 * IRQ_NONE - If invalid interrupt
5365 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba)
5367 /* Resetting interrupt aggregation counters first and reading the
5368 * DOOR_BELL afterward allows us to handle all the completed requests.
5369 * In order to prevent other interrupts starvation the DB is read once
5370 * after reset. The down side of this solution is the possibility of
5371 * false interrupt if device completes another request after resetting
5372 * aggregation and before reading the DB.
5374 if (ufshcd_is_intr_aggr_allowed(hba) &&
5375 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
5376 ufshcd_reset_intr_aggr(hba);
5378 if (ufs_fail_completion())
5382 * Ignore the ufshcd_poll() return value and return IRQ_HANDLED since we
5383 * do not want polling to trigger spurious interrupt complaints.
5385 ufshcd_poll(hba->host, 0);
5390 int __ufshcd_write_ee_control(struct ufs_hba *hba, u32 ee_ctrl_mask)
5392 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5393 QUERY_ATTR_IDN_EE_CONTROL, 0, 0,
5397 int ufshcd_write_ee_control(struct ufs_hba *hba)
5401 mutex_lock(&hba->ee_ctrl_mutex);
5402 err = __ufshcd_write_ee_control(hba, hba->ee_ctrl_mask);
5403 mutex_unlock(&hba->ee_ctrl_mutex);
5405 dev_err(hba->dev, "%s: failed to write ee control %d\n",
5410 int ufshcd_update_ee_control(struct ufs_hba *hba, u16 *mask, u16 *other_mask,
5413 u16 new_mask, ee_ctrl_mask;
5416 mutex_lock(&hba->ee_ctrl_mutex);
5417 new_mask = (*mask & ~clr) | set;
5418 ee_ctrl_mask = new_mask | *other_mask;
5419 if (ee_ctrl_mask != hba->ee_ctrl_mask)
5420 err = __ufshcd_write_ee_control(hba, ee_ctrl_mask);
5421 /* Still need to update 'mask' even if 'ee_ctrl_mask' was unchanged */
5423 hba->ee_ctrl_mask = ee_ctrl_mask;
5426 mutex_unlock(&hba->ee_ctrl_mutex);
5431 * ufshcd_disable_ee - disable exception event
5432 * @hba: per-adapter instance
5433 * @mask: exception event to disable
5435 * Disables exception event in the device so that the EVENT_ALERT
5438 * Returns zero on success, non-zero error value on failure.
5440 static inline int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
5442 return ufshcd_update_ee_drv_mask(hba, 0, mask);
5446 * ufshcd_enable_ee - enable exception event
5447 * @hba: per-adapter instance
5448 * @mask: exception event to enable
5450 * Enable corresponding exception event in the device to allow
5451 * device to alert host in critical scenarios.
5453 * Returns zero on success, non-zero error value on failure.
5455 static inline int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
5457 return ufshcd_update_ee_drv_mask(hba, mask, 0);
5461 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
5462 * @hba: per-adapter instance
5464 * Allow device to manage background operations on its own. Enabling
5465 * this might lead to inconsistent latencies during normal data transfers
5466 * as the device is allowed to manage its own way of handling background
5469 * Returns zero on success, non-zero on failure.
5471 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
5475 if (hba->auto_bkops_enabled)
5478 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5479 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5481 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
5486 hba->auto_bkops_enabled = true;
5487 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
5489 /* No need of URGENT_BKOPS exception from the device */
5490 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5492 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5499 * ufshcd_disable_auto_bkops - block device in doing background operations
5500 * @hba: per-adapter instance
5502 * Disabling background operations improves command response latency but
5503 * has drawback of device moving into critical state where the device is
5504 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5505 * host is idle so that BKOPS are managed effectively without any negative
5508 * Returns zero on success, non-zero on failure.
5510 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5514 if (!hba->auto_bkops_enabled)
5518 * If host assisted BKOPs is to be enabled, make sure
5519 * urgent bkops exception is allowed.
5521 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5523 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5528 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5529 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5531 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5533 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5537 hba->auto_bkops_enabled = false;
5538 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
5539 hba->is_urgent_bkops_lvl_checked = false;
5545 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5546 * @hba: per adapter instance
5548 * After a device reset the device may toggle the BKOPS_EN flag
5549 * to default value. The s/w tracking variables should be updated
5550 * as well. This function would change the auto-bkops state based on
5551 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5553 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5555 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5556 hba->auto_bkops_enabled = false;
5557 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5558 ufshcd_enable_auto_bkops(hba);
5560 hba->auto_bkops_enabled = true;
5561 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5562 ufshcd_disable_auto_bkops(hba);
5564 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
5565 hba->is_urgent_bkops_lvl_checked = false;
5568 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5570 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5571 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5575 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5576 * @hba: per-adapter instance
5577 * @status: bkops_status value
5579 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5580 * flag in the device to permit background operations if the device
5581 * bkops_status is greater than or equal to "status" argument passed to
5582 * this function, disable otherwise.
5584 * Returns 0 for success, non-zero in case of failure.
5586 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5587 * to know whether auto bkops is enabled or disabled after this function
5588 * returns control to it.
5590 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5591 enum bkops_status status)
5594 u32 curr_status = 0;
5596 err = ufshcd_get_bkops_status(hba, &curr_status);
5598 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5601 } else if (curr_status > BKOPS_STATUS_MAX) {
5602 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5603 __func__, curr_status);
5608 if (curr_status >= status)
5609 err = ufshcd_enable_auto_bkops(hba);
5611 err = ufshcd_disable_auto_bkops(hba);
5617 * ufshcd_urgent_bkops - handle urgent bkops exception event
5618 * @hba: per-adapter instance
5620 * Enable fBackgroundOpsEn flag in the device to permit background
5623 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5624 * and negative error value for any other failure.
5626 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5628 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5631 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5633 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5634 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5637 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5640 u32 curr_status = 0;
5642 if (hba->is_urgent_bkops_lvl_checked)
5643 goto enable_auto_bkops;
5645 err = ufshcd_get_bkops_status(hba, &curr_status);
5647 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5653 * We are seeing that some devices are raising the urgent bkops
5654 * exception events even when BKOPS status doesn't indicate performace
5655 * impacted or critical. Handle these device by determining their urgent
5656 * bkops status at runtime.
5658 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5659 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5660 __func__, curr_status);
5661 /* update the current status as the urgent bkops level */
5662 hba->urgent_bkops_lvl = curr_status;
5663 hba->is_urgent_bkops_lvl_checked = true;
5667 err = ufshcd_enable_auto_bkops(hba);
5670 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5674 static void ufshcd_temp_exception_event_handler(struct ufs_hba *hba, u16 status)
5678 if (ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5679 QUERY_ATTR_IDN_CASE_ROUGH_TEMP, 0, 0, &value))
5682 dev_info(hba->dev, "exception Tcase %d\n", value - 80);
5684 ufs_hwmon_notify_event(hba, status & MASK_EE_URGENT_TEMP);
5687 * A placeholder for the platform vendors to add whatever additional
5692 static int __ufshcd_wb_toggle(struct ufs_hba *hba, bool set, enum flag_idn idn)
5695 enum query_opcode opcode = set ? UPIU_QUERY_OPCODE_SET_FLAG :
5696 UPIU_QUERY_OPCODE_CLEAR_FLAG;
5698 index = ufshcd_wb_get_query_index(hba);
5699 return ufshcd_query_flag_retry(hba, opcode, idn, index, NULL);
5702 int ufshcd_wb_toggle(struct ufs_hba *hba, bool enable)
5706 if (!ufshcd_is_wb_allowed(hba))
5709 if (!(enable ^ hba->dev_info.wb_enabled))
5712 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_EN);
5714 dev_err(hba->dev, "%s Write Booster %s failed %d\n",
5715 __func__, enable ? "enable" : "disable", ret);
5719 hba->dev_info.wb_enabled = enable;
5720 dev_info(hba->dev, "%s Write Booster %s\n",
5721 __func__, enable ? "enabled" : "disabled");
5726 static void ufshcd_wb_toggle_flush_during_h8(struct ufs_hba *hba, bool set)
5730 ret = __ufshcd_wb_toggle(hba, set,
5731 QUERY_FLAG_IDN_WB_BUFF_FLUSH_DURING_HIBERN8);
5733 dev_err(hba->dev, "%s: WB-Buf Flush during H8 %s failed: %d\n",
5734 __func__, set ? "enable" : "disable", ret);
5737 dev_dbg(hba->dev, "%s WB-Buf Flush during H8 %s\n",
5738 __func__, set ? "enabled" : "disabled");
5741 static inline void ufshcd_wb_toggle_flush(struct ufs_hba *hba, bool enable)
5745 if (!ufshcd_is_wb_allowed(hba) ||
5746 hba->dev_info.wb_buf_flush_enabled == enable)
5749 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN);
5751 dev_err(hba->dev, "%s WB-Buf Flush %s failed %d\n", __func__,
5752 enable ? "enable" : "disable", ret);
5756 hba->dev_info.wb_buf_flush_enabled = enable;
5758 dev_dbg(hba->dev, "%s WB-Buf Flush %s\n",
5759 __func__, enable ? "enabled" : "disabled");
5762 static bool ufshcd_wb_presrv_usrspc_keep_vcc_on(struct ufs_hba *hba,
5769 index = ufshcd_wb_get_query_index(hba);
5770 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5771 QUERY_ATTR_IDN_CURR_WB_BUFF_SIZE,
5772 index, 0, &cur_buf);
5774 dev_err(hba->dev, "%s dCurWriteBoosterBufferSize read failed %d\n",
5780 dev_info(hba->dev, "dCurWBBuf: %d WB disabled until free-space is available\n",
5784 /* Let it continue to flush when available buffer exceeds threshold */
5785 if (avail_buf < hba->vps->wb_flush_threshold)
5791 static void ufshcd_wb_force_disable(struct ufs_hba *hba)
5793 if (!(hba->quirks & UFSHCI_QUIRK_SKIP_MANUAL_WB_FLUSH_CTRL))
5794 ufshcd_wb_toggle_flush(hba, false);
5796 ufshcd_wb_toggle_flush_during_h8(hba, false);
5797 ufshcd_wb_toggle(hba, false);
5798 hba->caps &= ~UFSHCD_CAP_WB_EN;
5800 dev_info(hba->dev, "%s: WB force disabled\n", __func__);
5803 static bool ufshcd_is_wb_buf_lifetime_available(struct ufs_hba *hba)
5809 index = ufshcd_wb_get_query_index(hba);
5810 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5811 QUERY_ATTR_IDN_WB_BUFF_LIFE_TIME_EST,
5812 index, 0, &lifetime);
5815 "%s: bWriteBoosterBufferLifeTimeEst read failed %d\n",
5820 if (lifetime == UFS_WB_EXCEED_LIFETIME) {
5821 dev_err(hba->dev, "%s: WB buf lifetime is exhausted 0x%02X\n",
5822 __func__, lifetime);
5826 dev_dbg(hba->dev, "%s: WB buf lifetime is 0x%02X\n",
5827 __func__, lifetime);
5832 static bool ufshcd_wb_need_flush(struct ufs_hba *hba)
5838 if (!ufshcd_is_wb_allowed(hba))
5841 if (!ufshcd_is_wb_buf_lifetime_available(hba)) {
5842 ufshcd_wb_force_disable(hba);
5847 * The ufs device needs the vcc to be ON to flush.
5848 * With user-space reduction enabled, it's enough to enable flush
5849 * by checking only the available buffer. The threshold
5850 * defined here is > 90% full.
5851 * With user-space preserved enabled, the current-buffer
5852 * should be checked too because the wb buffer size can reduce
5853 * when disk tends to be full. This info is provided by current
5854 * buffer (dCurrentWriteBoosterBufferSize). There's no point in
5855 * keeping vcc on when current buffer is empty.
5857 index = ufshcd_wb_get_query_index(hba);
5858 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5859 QUERY_ATTR_IDN_AVAIL_WB_BUFF_SIZE,
5860 index, 0, &avail_buf);
5862 dev_warn(hba->dev, "%s dAvailableWriteBoosterBufferSize read failed %d\n",
5867 if (!hba->dev_info.b_presrv_uspc_en) {
5868 if (avail_buf <= UFS_WB_BUF_REMAIN_PERCENT(10))
5873 return ufshcd_wb_presrv_usrspc_keep_vcc_on(hba, avail_buf);
5876 static void ufshcd_rpm_dev_flush_recheck_work(struct work_struct *work)
5878 struct ufs_hba *hba = container_of(to_delayed_work(work),
5880 rpm_dev_flush_recheck_work);
5882 * To prevent unnecessary VCC power drain after device finishes
5883 * WriteBooster buffer flush or Auto BKOPs, force runtime resume
5884 * after a certain delay to recheck the threshold by next runtime
5887 ufshcd_rpm_get_sync(hba);
5888 ufshcd_rpm_put_sync(hba);
5892 * ufshcd_exception_event_handler - handle exceptions raised by device
5893 * @work: pointer to work data
5895 * Read bExceptionEventStatus attribute from the device and handle the
5896 * exception event accordingly.
5898 static void ufshcd_exception_event_handler(struct work_struct *work)
5900 struct ufs_hba *hba;
5903 hba = container_of(work, struct ufs_hba, eeh_work);
5905 ufshcd_scsi_block_requests(hba);
5906 err = ufshcd_get_ee_status(hba, &status);
5908 dev_err(hba->dev, "%s: failed to get exception status %d\n",
5913 trace_ufshcd_exception_event(dev_name(hba->dev), status);
5915 if (status & hba->ee_drv_mask & MASK_EE_URGENT_BKOPS)
5916 ufshcd_bkops_exception_event_handler(hba);
5918 if (status & hba->ee_drv_mask & MASK_EE_URGENT_TEMP)
5919 ufshcd_temp_exception_event_handler(hba, status);
5921 ufs_debugfs_exception_event(hba, status);
5923 ufshcd_scsi_unblock_requests(hba);
5926 /* Complete requests that have door-bell cleared */
5927 static void ufshcd_complete_requests(struct ufs_hba *hba)
5929 ufshcd_transfer_req_compl(hba);
5930 ufshcd_tmc_handler(hba);
5934 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
5935 * to recover from the DL NAC errors or not.
5936 * @hba: per-adapter instance
5938 * Returns true if error handling is required, false otherwise
5940 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
5942 unsigned long flags;
5943 bool err_handling = true;
5945 spin_lock_irqsave(hba->host->host_lock, flags);
5947 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
5948 * device fatal error and/or DL NAC & REPLAY timeout errors.
5950 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
5953 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
5954 ((hba->saved_err & UIC_ERROR) &&
5955 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
5958 if ((hba->saved_err & UIC_ERROR) &&
5959 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
5962 * wait for 50ms to see if we can get any other errors or not.
5964 spin_unlock_irqrestore(hba->host->host_lock, flags);
5966 spin_lock_irqsave(hba->host->host_lock, flags);
5969 * now check if we have got any other severe errors other than
5972 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5973 ((hba->saved_err & UIC_ERROR) &&
5974 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
5978 * As DL NAC is the only error received so far, send out NOP
5979 * command to confirm if link is still active or not.
5980 * - If we don't get any response then do error recovery.
5981 * - If we get response then clear the DL NAC error bit.
5984 spin_unlock_irqrestore(hba->host->host_lock, flags);
5985 err = ufshcd_verify_dev_init(hba);
5986 spin_lock_irqsave(hba->host->host_lock, flags);
5991 /* Link seems to be alive hence ignore the DL NAC errors */
5992 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
5993 hba->saved_err &= ~UIC_ERROR;
5994 /* clear NAC error */
5995 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5996 if (!hba->saved_uic_err)
5997 err_handling = false;
6000 spin_unlock_irqrestore(hba->host->host_lock, flags);
6001 return err_handling;
6004 /* host lock must be held before calling this func */
6005 static inline bool ufshcd_is_saved_err_fatal(struct ufs_hba *hba)
6007 return (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR) ||
6008 (hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK));
6011 void ufshcd_schedule_eh_work(struct ufs_hba *hba)
6013 lockdep_assert_held(hba->host->host_lock);
6015 /* handle fatal errors only when link is not in error state */
6016 if (hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6017 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6018 ufshcd_is_saved_err_fatal(hba))
6019 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_FATAL;
6021 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_NON_FATAL;
6022 queue_work(hba->eh_wq, &hba->eh_work);
6026 static void ufshcd_clk_scaling_allow(struct ufs_hba *hba, bool allow)
6028 down_write(&hba->clk_scaling_lock);
6029 hba->clk_scaling.is_allowed = allow;
6030 up_write(&hba->clk_scaling_lock);
6033 static void ufshcd_clk_scaling_suspend(struct ufs_hba *hba, bool suspend)
6036 if (hba->clk_scaling.is_enabled)
6037 ufshcd_suspend_clkscaling(hba);
6038 ufshcd_clk_scaling_allow(hba, false);
6040 ufshcd_clk_scaling_allow(hba, true);
6041 if (hba->clk_scaling.is_enabled)
6042 ufshcd_resume_clkscaling(hba);
6046 static void ufshcd_err_handling_prepare(struct ufs_hba *hba)
6048 ufshcd_rpm_get_sync(hba);
6049 if (pm_runtime_status_suspended(&hba->sdev_ufs_device->sdev_gendev) ||
6050 hba->is_sys_suspended) {
6051 enum ufs_pm_op pm_op;
6054 * Don't assume anything of resume, if
6055 * resume fails, irq and clocks can be OFF, and powers
6056 * can be OFF or in LPM.
6058 ufshcd_setup_hba_vreg(hba, true);
6059 ufshcd_enable_irq(hba);
6060 ufshcd_setup_vreg(hba, true);
6061 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
6062 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
6063 ufshcd_hold(hba, false);
6064 if (!ufshcd_is_clkgating_allowed(hba))
6065 ufshcd_setup_clocks(hba, true);
6066 ufshcd_release(hba);
6067 pm_op = hba->is_sys_suspended ? UFS_SYSTEM_PM : UFS_RUNTIME_PM;
6068 ufshcd_vops_resume(hba, pm_op);
6070 ufshcd_hold(hba, false);
6071 if (ufshcd_is_clkscaling_supported(hba) &&
6072 hba->clk_scaling.is_enabled)
6073 ufshcd_suspend_clkscaling(hba);
6074 ufshcd_clk_scaling_allow(hba, false);
6076 ufshcd_scsi_block_requests(hba);
6077 /* Drain ufshcd_queuecommand() */
6079 cancel_work_sync(&hba->eeh_work);
6082 static void ufshcd_err_handling_unprepare(struct ufs_hba *hba)
6084 ufshcd_scsi_unblock_requests(hba);
6085 ufshcd_release(hba);
6086 if (ufshcd_is_clkscaling_supported(hba))
6087 ufshcd_clk_scaling_suspend(hba, false);
6088 ufshcd_rpm_put(hba);
6091 static inline bool ufshcd_err_handling_should_stop(struct ufs_hba *hba)
6093 return (!hba->is_powered || hba->shutting_down ||
6094 !hba->sdev_ufs_device ||
6095 hba->ufshcd_state == UFSHCD_STATE_ERROR ||
6096 (!(hba->saved_err || hba->saved_uic_err || hba->force_reset ||
6097 ufshcd_is_link_broken(hba))));
6101 static void ufshcd_recover_pm_error(struct ufs_hba *hba)
6103 struct Scsi_Host *shost = hba->host;
6104 struct scsi_device *sdev;
6105 struct request_queue *q;
6108 hba->is_sys_suspended = false;
6110 * Set RPM status of wlun device to RPM_ACTIVE,
6111 * this also clears its runtime error.
6113 ret = pm_runtime_set_active(&hba->sdev_ufs_device->sdev_gendev);
6115 /* hba device might have a runtime error otherwise */
6117 ret = pm_runtime_set_active(hba->dev);
6119 * If wlun device had runtime error, we also need to resume those
6120 * consumer scsi devices in case any of them has failed to be
6121 * resumed due to supplier runtime resume failure. This is to unblock
6122 * blk_queue_enter in case there are bios waiting inside it.
6125 shost_for_each_device(sdev, shost) {
6126 q = sdev->request_queue;
6127 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
6128 q->rpm_status == RPM_SUSPENDING))
6129 pm_request_resume(q->dev);
6134 static inline void ufshcd_recover_pm_error(struct ufs_hba *hba)
6139 static bool ufshcd_is_pwr_mode_restore_needed(struct ufs_hba *hba)
6141 struct ufs_pa_layer_attr *pwr_info = &hba->pwr_info;
6144 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode);
6146 if (pwr_info->pwr_rx != ((mode >> PWRMODE_RX_OFFSET) & PWRMODE_MASK))
6149 if (pwr_info->pwr_tx != (mode & PWRMODE_MASK))
6156 * ufshcd_err_handler - handle UFS errors that require s/w attention
6157 * @work: pointer to work structure
6159 static void ufshcd_err_handler(struct work_struct *work)
6161 int retries = MAX_ERR_HANDLER_RETRIES;
6162 struct ufs_hba *hba;
6163 unsigned long flags;
6171 hba = container_of(work, struct ufs_hba, eh_work);
6174 "%s started; HBA state %s; powered %d; shutting down %d; saved_err = %d; saved_uic_err = %d; force_reset = %d%s\n",
6175 __func__, ufshcd_state_name[hba->ufshcd_state],
6176 hba->is_powered, hba->shutting_down, hba->saved_err,
6177 hba->saved_uic_err, hba->force_reset,
6178 ufshcd_is_link_broken(hba) ? "; link is broken" : "");
6180 down(&hba->host_sem);
6181 spin_lock_irqsave(hba->host->host_lock, flags);
6182 if (ufshcd_err_handling_should_stop(hba)) {
6183 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6184 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6185 spin_unlock_irqrestore(hba->host->host_lock, flags);
6189 ufshcd_set_eh_in_progress(hba);
6190 spin_unlock_irqrestore(hba->host->host_lock, flags);
6191 ufshcd_err_handling_prepare(hba);
6192 /* Complete requests that have door-bell cleared by h/w */
6193 ufshcd_complete_requests(hba);
6194 spin_lock_irqsave(hba->host->host_lock, flags);
6196 needs_restore = false;
6197 needs_reset = false;
6201 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6202 hba->ufshcd_state = UFSHCD_STATE_RESET;
6204 * A full reset and restore might have happened after preparation
6205 * is finished, double check whether we should stop.
6207 if (ufshcd_err_handling_should_stop(hba))
6208 goto skip_err_handling;
6210 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6213 spin_unlock_irqrestore(hba->host->host_lock, flags);
6214 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
6215 ret = ufshcd_quirk_dl_nac_errors(hba);
6216 spin_lock_irqsave(hba->host->host_lock, flags);
6217 if (!ret && ufshcd_err_handling_should_stop(hba))
6218 goto skip_err_handling;
6221 if ((hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6222 (hba->saved_uic_err &&
6223 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6224 bool pr_prdt = !!(hba->saved_err & SYSTEM_BUS_FATAL_ERROR);
6226 spin_unlock_irqrestore(hba->host->host_lock, flags);
6227 ufshcd_print_host_state(hba);
6228 ufshcd_print_pwr_info(hba);
6229 ufshcd_print_evt_hist(hba);
6230 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
6231 ufshcd_print_trs(hba, hba->outstanding_reqs, pr_prdt);
6232 spin_lock_irqsave(hba->host->host_lock, flags);
6236 * if host reset is required then skip clearing the pending
6237 * transfers forcefully because they will get cleared during
6238 * host reset and restore
6240 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6241 ufshcd_is_saved_err_fatal(hba) ||
6242 ((hba->saved_err & UIC_ERROR) &&
6243 (hba->saved_uic_err & (UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
6244 UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))) {
6250 * If LINERESET was caught, UFS might have been put to PWM mode,
6251 * check if power mode restore is needed.
6253 if (hba->saved_uic_err & UFSHCD_UIC_PA_GENERIC_ERROR) {
6254 hba->saved_uic_err &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6255 if (!hba->saved_uic_err)
6256 hba->saved_err &= ~UIC_ERROR;
6257 spin_unlock_irqrestore(hba->host->host_lock, flags);
6258 if (ufshcd_is_pwr_mode_restore_needed(hba))
6259 needs_restore = true;
6260 spin_lock_irqsave(hba->host->host_lock, flags);
6261 if (!hba->saved_err && !needs_restore)
6262 goto skip_err_handling;
6265 hba->silence_err_logs = true;
6266 /* release lock as clear command might sleep */
6267 spin_unlock_irqrestore(hba->host->host_lock, flags);
6268 /* Clear pending transfer requests */
6269 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
6270 if (ufshcd_try_to_abort_task(hba, tag)) {
6272 goto lock_skip_pending_xfer_clear;
6274 dev_err(hba->dev, "Aborted tag %d / CDB %#02x\n", tag,
6275 hba->lrb[tag].cmd ? hba->lrb[tag].cmd->cmnd[0] : -1);
6278 /* Clear pending task management requests */
6279 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
6280 if (ufshcd_clear_tm_cmd(hba, tag)) {
6282 goto lock_skip_pending_xfer_clear;
6286 lock_skip_pending_xfer_clear:
6287 /* Complete the requests that are cleared by s/w */
6288 ufshcd_complete_requests(hba);
6290 spin_lock_irqsave(hba->host->host_lock, flags);
6291 hba->silence_err_logs = false;
6292 if (err_xfer || err_tm) {
6298 * After all reqs and tasks are cleared from doorbell,
6299 * now it is safe to retore power mode.
6301 if (needs_restore) {
6302 spin_unlock_irqrestore(hba->host->host_lock, flags);
6304 * Hold the scaling lock just in case dev cmds
6305 * are sent via bsg and/or sysfs.
6307 down_write(&hba->clk_scaling_lock);
6308 hba->force_pmc = true;
6309 pmc_err = ufshcd_config_pwr_mode(hba, &(hba->pwr_info));
6312 dev_err(hba->dev, "%s: Failed to restore power mode, err = %d\n",
6315 hba->force_pmc = false;
6316 ufshcd_print_pwr_info(hba);
6317 up_write(&hba->clk_scaling_lock);
6318 spin_lock_irqsave(hba->host->host_lock, flags);
6322 /* Fatal errors need reset */
6326 hba->force_reset = false;
6327 spin_unlock_irqrestore(hba->host->host_lock, flags);
6328 err = ufshcd_reset_and_restore(hba);
6330 dev_err(hba->dev, "%s: reset and restore failed with err %d\n",
6333 ufshcd_recover_pm_error(hba);
6334 spin_lock_irqsave(hba->host->host_lock, flags);
6339 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
6340 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6341 if (hba->saved_err || hba->saved_uic_err)
6342 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
6343 __func__, hba->saved_err, hba->saved_uic_err);
6345 /* Exit in an operational state or dead */
6346 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
6347 hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6350 hba->ufshcd_state = UFSHCD_STATE_ERROR;
6352 ufshcd_clear_eh_in_progress(hba);
6353 spin_unlock_irqrestore(hba->host->host_lock, flags);
6354 ufshcd_err_handling_unprepare(hba);
6357 dev_info(hba->dev, "%s finished; HBA state %s\n", __func__,
6358 ufshcd_state_name[hba->ufshcd_state]);
6362 * ufshcd_update_uic_error - check and set fatal UIC error flags.
6363 * @hba: per-adapter instance
6366 * IRQ_HANDLED - If interrupt is valid
6367 * IRQ_NONE - If invalid interrupt
6369 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
6372 irqreturn_t retval = IRQ_NONE;
6374 /* PHY layer error */
6375 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
6376 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
6377 (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) {
6378 ufshcd_update_evt_hist(hba, UFS_EVT_PA_ERR, reg);
6380 * To know whether this error is fatal or not, DB timeout
6381 * must be checked but this error is handled separately.
6383 if (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)
6384 dev_dbg(hba->dev, "%s: UIC Lane error reported\n",
6387 /* Got a LINERESET indication. */
6388 if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) {
6389 struct uic_command *cmd = NULL;
6391 hba->uic_error |= UFSHCD_UIC_PA_GENERIC_ERROR;
6392 if (hba->uic_async_done && hba->active_uic_cmd)
6393 cmd = hba->active_uic_cmd;
6395 * Ignore the LINERESET during power mode change
6396 * operation via DME_SET command.
6398 if (cmd && (cmd->command == UIC_CMD_DME_SET))
6399 hba->uic_error &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6401 retval |= IRQ_HANDLED;
6404 /* PA_INIT_ERROR is fatal and needs UIC reset */
6405 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
6406 if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
6407 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
6408 ufshcd_update_evt_hist(hba, UFS_EVT_DL_ERR, reg);
6410 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
6411 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
6412 else if (hba->dev_quirks &
6413 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6414 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
6416 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6417 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
6418 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
6420 retval |= IRQ_HANDLED;
6423 /* UIC NL/TL/DME errors needs software retry */
6424 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
6425 if ((reg & UIC_NETWORK_LAYER_ERROR) &&
6426 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
6427 ufshcd_update_evt_hist(hba, UFS_EVT_NL_ERR, reg);
6428 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
6429 retval |= IRQ_HANDLED;
6432 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
6433 if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
6434 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
6435 ufshcd_update_evt_hist(hba, UFS_EVT_TL_ERR, reg);
6436 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
6437 retval |= IRQ_HANDLED;
6440 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
6441 if ((reg & UIC_DME_ERROR) &&
6442 (reg & UIC_DME_ERROR_CODE_MASK)) {
6443 ufshcd_update_evt_hist(hba, UFS_EVT_DME_ERR, reg);
6444 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
6445 retval |= IRQ_HANDLED;
6448 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
6449 __func__, hba->uic_error);
6454 * ufshcd_check_errors - Check for errors that need s/w attention
6455 * @hba: per-adapter instance
6456 * @intr_status: interrupt status generated by the controller
6459 * IRQ_HANDLED - If interrupt is valid
6460 * IRQ_NONE - If invalid interrupt
6462 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba, u32 intr_status)
6464 bool queue_eh_work = false;
6465 irqreturn_t retval = IRQ_NONE;
6467 spin_lock(hba->host->host_lock);
6468 hba->errors |= UFSHCD_ERROR_MASK & intr_status;
6470 if (hba->errors & INT_FATAL_ERRORS) {
6471 ufshcd_update_evt_hist(hba, UFS_EVT_FATAL_ERR,
6473 queue_eh_work = true;
6476 if (hba->errors & UIC_ERROR) {
6478 retval = ufshcd_update_uic_error(hba);
6480 queue_eh_work = true;
6483 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
6485 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
6486 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
6488 hba->errors, ufshcd_get_upmcrs(hba));
6489 ufshcd_update_evt_hist(hba, UFS_EVT_AUTO_HIBERN8_ERR,
6491 ufshcd_set_link_broken(hba);
6492 queue_eh_work = true;
6495 if (queue_eh_work) {
6497 * update the transfer error masks to sticky bits, let's do this
6498 * irrespective of current ufshcd_state.
6500 hba->saved_err |= hba->errors;
6501 hba->saved_uic_err |= hba->uic_error;
6503 /* dump controller state before resetting */
6504 if ((hba->saved_err &
6505 (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6506 (hba->saved_uic_err &&
6507 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6508 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
6509 __func__, hba->saved_err,
6510 hba->saved_uic_err);
6511 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE,
6513 ufshcd_print_pwr_info(hba);
6515 ufshcd_schedule_eh_work(hba);
6516 retval |= IRQ_HANDLED;
6519 * if (!queue_eh_work) -
6520 * Other errors are either non-fatal where host recovers
6521 * itself without s/w intervention or errors that will be
6522 * handled by the SCSI core layer.
6526 spin_unlock(hba->host->host_lock);
6531 * ufshcd_tmc_handler - handle task management function completion
6532 * @hba: per adapter instance
6535 * IRQ_HANDLED - If interrupt is valid
6536 * IRQ_NONE - If invalid interrupt
6538 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
6540 unsigned long flags, pending, issued;
6541 irqreturn_t ret = IRQ_NONE;
6544 spin_lock_irqsave(hba->host->host_lock, flags);
6545 pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
6546 issued = hba->outstanding_tasks & ~pending;
6547 for_each_set_bit(tag, &issued, hba->nutmrs) {
6548 struct request *req = hba->tmf_rqs[tag];
6549 struct completion *c = req->end_io_data;
6554 spin_unlock_irqrestore(hba->host->host_lock, flags);
6560 * ufshcd_sl_intr - Interrupt service routine
6561 * @hba: per adapter instance
6562 * @intr_status: contains interrupts generated by the controller
6565 * IRQ_HANDLED - If interrupt is valid
6566 * IRQ_NONE - If invalid interrupt
6568 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
6570 irqreturn_t retval = IRQ_NONE;
6572 if (intr_status & UFSHCD_UIC_MASK)
6573 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
6575 if (intr_status & UFSHCD_ERROR_MASK || hba->errors)
6576 retval |= ufshcd_check_errors(hba, intr_status);
6578 if (intr_status & UTP_TASK_REQ_COMPL)
6579 retval |= ufshcd_tmc_handler(hba);
6581 if (intr_status & UTP_TRANSFER_REQ_COMPL)
6582 retval |= ufshcd_transfer_req_compl(hba);
6588 * ufshcd_intr - Main interrupt service routine
6590 * @__hba: pointer to adapter instance
6593 * IRQ_HANDLED - If interrupt is valid
6594 * IRQ_NONE - If invalid interrupt
6596 static irqreturn_t ufshcd_intr(int irq, void *__hba)
6598 u32 intr_status, enabled_intr_status = 0;
6599 irqreturn_t retval = IRQ_NONE;
6600 struct ufs_hba *hba = __hba;
6601 int retries = hba->nutrs;
6603 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6604 hba->ufs_stats.last_intr_status = intr_status;
6605 hba->ufs_stats.last_intr_ts = ktime_get();
6608 * There could be max of hba->nutrs reqs in flight and in worst case
6609 * if the reqs get finished 1 by 1 after the interrupt status is
6610 * read, make sure we handle them by checking the interrupt status
6611 * again in a loop until we process all of the reqs before returning.
6613 while (intr_status && retries--) {
6614 enabled_intr_status =
6615 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
6616 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
6617 if (enabled_intr_status)
6618 retval |= ufshcd_sl_intr(hba, enabled_intr_status);
6620 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6623 if (enabled_intr_status && retval == IRQ_NONE &&
6624 (!(enabled_intr_status & UTP_TRANSFER_REQ_COMPL) ||
6625 hba->outstanding_reqs) && !ufshcd_eh_in_progress(hba)) {
6626 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x (0x%08x, 0x%08x)\n",
6629 hba->ufs_stats.last_intr_status,
6630 enabled_intr_status);
6631 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
6637 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
6640 u32 mask = 1 << tag;
6641 unsigned long flags;
6643 if (!test_bit(tag, &hba->outstanding_tasks))
6646 spin_lock_irqsave(hba->host->host_lock, flags);
6647 ufshcd_utmrl_clear(hba, tag);
6648 spin_unlock_irqrestore(hba->host->host_lock, flags);
6650 /* poll for max. 1 sec to clear door bell register by h/w */
6651 err = ufshcd_wait_for_register(hba,
6652 REG_UTP_TASK_REQ_DOOR_BELL,
6653 mask, 0, 1000, 1000);
6655 dev_err(hba->dev, "Clearing task management function with tag %d %s\n",
6656 tag, err ? "succeeded" : "failed");
6662 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
6663 struct utp_task_req_desc *treq, u8 tm_function)
6665 struct request_queue *q = hba->tmf_queue;
6666 struct Scsi_Host *host = hba->host;
6667 DECLARE_COMPLETION_ONSTACK(wait);
6668 struct request *req;
6669 unsigned long flags;
6673 * blk_mq_alloc_request() is used here only to get a free tag.
6675 req = blk_mq_alloc_request(q, REQ_OP_DRV_OUT, 0);
6677 return PTR_ERR(req);
6679 req->end_io_data = &wait;
6680 ufshcd_hold(hba, false);
6682 spin_lock_irqsave(host->host_lock, flags);
6684 task_tag = req->tag;
6685 WARN_ONCE(task_tag < 0 || task_tag >= hba->nutmrs, "Invalid tag %d\n",
6687 hba->tmf_rqs[req->tag] = req;
6688 treq->upiu_req.req_header.dword_0 |= cpu_to_be32(task_tag);
6690 memcpy(hba->utmrdl_base_addr + task_tag, treq, sizeof(*treq));
6691 ufshcd_vops_setup_task_mgmt(hba, task_tag, tm_function);
6693 /* send command to the controller */
6694 __set_bit(task_tag, &hba->outstanding_tasks);
6696 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TASK_REQ_DOOR_BELL);
6697 /* Make sure that doorbell is committed immediately */
6700 spin_unlock_irqrestore(host->host_lock, flags);
6702 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_SEND);
6704 /* wait until the task management command is completed */
6705 err = wait_for_completion_io_timeout(&wait,
6706 msecs_to_jiffies(TM_CMD_TIMEOUT));
6708 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_ERR);
6709 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
6710 __func__, tm_function);
6711 if (ufshcd_clear_tm_cmd(hba, task_tag))
6712 dev_WARN(hba->dev, "%s: unable to clear tm cmd (slot %d) after timeout\n",
6713 __func__, task_tag);
6717 memcpy(treq, hba->utmrdl_base_addr + task_tag, sizeof(*treq));
6719 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_COMP);
6722 spin_lock_irqsave(hba->host->host_lock, flags);
6723 hba->tmf_rqs[req->tag] = NULL;
6724 __clear_bit(task_tag, &hba->outstanding_tasks);
6725 spin_unlock_irqrestore(hba->host->host_lock, flags);
6727 ufshcd_release(hba);
6728 blk_mq_free_request(req);
6734 * ufshcd_issue_tm_cmd - issues task management commands to controller
6735 * @hba: per adapter instance
6736 * @lun_id: LUN ID to which TM command is sent
6737 * @task_id: task ID to which the TM command is applicable
6738 * @tm_function: task management function opcode
6739 * @tm_response: task management service response return value
6741 * Returns non-zero value on error, zero on success.
6743 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
6744 u8 tm_function, u8 *tm_response)
6746 struct utp_task_req_desc treq = { { 0 }, };
6747 enum utp_ocs ocs_value;
6750 /* Configure task request descriptor */
6751 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6752 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6754 /* Configure task request UPIU */
6755 treq.upiu_req.req_header.dword_0 = cpu_to_be32(lun_id << 8) |
6756 cpu_to_be32(UPIU_TRANSACTION_TASK_REQ << 24);
6757 treq.upiu_req.req_header.dword_1 = cpu_to_be32(tm_function << 16);
6760 * The host shall provide the same value for LUN field in the basic
6761 * header and for Input Parameter.
6763 treq.upiu_req.input_param1 = cpu_to_be32(lun_id);
6764 treq.upiu_req.input_param2 = cpu_to_be32(task_id);
6766 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
6767 if (err == -ETIMEDOUT)
6770 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6771 if (ocs_value != OCS_SUCCESS)
6772 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
6773 __func__, ocs_value);
6774 else if (tm_response)
6775 *tm_response = be32_to_cpu(treq.upiu_rsp.output_param1) &
6776 MASK_TM_SERVICE_RESP;
6781 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
6782 * @hba: per-adapter instance
6783 * @req_upiu: upiu request
6784 * @rsp_upiu: upiu reply
6785 * @desc_buff: pointer to descriptor buffer, NULL if NA
6786 * @buff_len: descriptor size, 0 if NA
6787 * @cmd_type: specifies the type (NOP, Query...)
6788 * @desc_op: descriptor operation
6790 * Those type of requests uses UTP Transfer Request Descriptor - utrd.
6791 * Therefore, it "rides" the device management infrastructure: uses its tag and
6792 * tasks work queues.
6794 * Since there is only one available tag for device management commands,
6795 * the caller is expected to hold the hba->dev_cmd.lock mutex.
6797 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
6798 struct utp_upiu_req *req_upiu,
6799 struct utp_upiu_req *rsp_upiu,
6800 u8 *desc_buff, int *buff_len,
6801 enum dev_cmd_type cmd_type,
6802 enum query_opcode desc_op)
6804 DECLARE_COMPLETION_ONSTACK(wait);
6805 const u32 tag = hba->reserved_slot;
6806 struct ufshcd_lrb *lrbp;
6810 /* Protects use of hba->reserved_slot. */
6811 lockdep_assert_held(&hba->dev_cmd.lock);
6813 down_read(&hba->clk_scaling_lock);
6815 lrbp = &hba->lrb[tag];
6818 lrbp->sense_bufflen = 0;
6819 lrbp->sense_buffer = NULL;
6820 lrbp->task_tag = tag;
6822 lrbp->intr_cmd = true;
6823 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
6824 hba->dev_cmd.type = cmd_type;
6826 if (hba->ufs_version <= ufshci_version(1, 1))
6827 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
6829 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
6831 /* update the task tag in the request upiu */
6832 req_upiu->header.dword_0 |= cpu_to_be32(tag);
6834 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
6836 /* just copy the upiu request as it is */
6837 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
6838 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
6839 /* The Data Segment Area is optional depending upon the query
6840 * function value. for WRITE DESCRIPTOR, the data segment
6841 * follows right after the tsf.
6843 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
6847 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
6849 hba->dev_cmd.complete = &wait;
6851 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
6853 ufshcd_send_command(hba, tag);
6855 * ignore the returning value here - ufshcd_check_query_response is
6856 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
6857 * read the response directly ignoring all errors.
6859 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
6861 /* just copy the upiu response as it is */
6862 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
6863 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
6864 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
6865 u16 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
6866 MASK_QUERY_DATA_SEG_LEN;
6868 if (*buff_len >= resp_len) {
6869 memcpy(desc_buff, descp, resp_len);
6870 *buff_len = resp_len;
6873 "%s: rsp size %d is bigger than buffer size %d",
6874 __func__, resp_len, *buff_len);
6879 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
6880 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
6882 up_read(&hba->clk_scaling_lock);
6887 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
6888 * @hba: per-adapter instance
6889 * @req_upiu: upiu request
6890 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands
6891 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
6892 * @desc_buff: pointer to descriptor buffer, NULL if NA
6893 * @buff_len: descriptor size, 0 if NA
6894 * @desc_op: descriptor operation
6896 * Supports UTP Transfer requests (nop and query), and UTP Task
6897 * Management requests.
6898 * It is up to the caller to fill the upiu conent properly, as it will
6899 * be copied without any further input validations.
6901 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
6902 struct utp_upiu_req *req_upiu,
6903 struct utp_upiu_req *rsp_upiu,
6905 u8 *desc_buff, int *buff_len,
6906 enum query_opcode desc_op)
6909 enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
6910 struct utp_task_req_desc treq = { { 0 }, };
6911 enum utp_ocs ocs_value;
6912 u8 tm_f = be32_to_cpu(req_upiu->header.dword_1) >> 16 & MASK_TM_FUNC;
6915 case UPIU_TRANSACTION_NOP_OUT:
6916 cmd_type = DEV_CMD_TYPE_NOP;
6918 case UPIU_TRANSACTION_QUERY_REQ:
6919 ufshcd_hold(hba, false);
6920 mutex_lock(&hba->dev_cmd.lock);
6921 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
6922 desc_buff, buff_len,
6924 mutex_unlock(&hba->dev_cmd.lock);
6925 ufshcd_release(hba);
6928 case UPIU_TRANSACTION_TASK_REQ:
6929 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6930 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6932 memcpy(&treq.upiu_req, req_upiu, sizeof(*req_upiu));
6934 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
6935 if (err == -ETIMEDOUT)
6938 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6939 if (ocs_value != OCS_SUCCESS) {
6940 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
6945 memcpy(rsp_upiu, &treq.upiu_rsp, sizeof(*rsp_upiu));
6958 * ufshcd_eh_device_reset_handler - device reset handler registered to
6960 * @cmd: SCSI command pointer
6962 * Returns SUCCESS/FAILED
6964 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
6966 struct Scsi_Host *host;
6967 struct ufs_hba *hba;
6972 host = cmd->device->host;
6973 hba = shost_priv(host);
6975 lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
6976 err = ufshcd_issue_tm_cmd(hba, lun, 0, UFS_LOGICAL_RESET, &resp);
6977 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6983 /* clear the commands that were pending for corresponding LUN */
6984 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
6985 if (hba->lrb[pos].lun == lun) {
6986 err = ufshcd_clear_cmd(hba, pos);
6989 __ufshcd_transfer_req_compl(hba, 1U << pos);
6994 hba->req_abort_count = 0;
6995 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, (u32)err);
6999 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7005 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
7007 struct ufshcd_lrb *lrbp;
7010 for_each_set_bit(tag, &bitmap, hba->nutrs) {
7011 lrbp = &hba->lrb[tag];
7012 lrbp->req_abort_skip = true;
7017 * ufshcd_try_to_abort_task - abort a specific task
7018 * @hba: Pointer to adapter instance
7019 * @tag: Task tag/index to be aborted
7021 * Abort the pending command in device by sending UFS_ABORT_TASK task management
7022 * command, and in host controller by clearing the door-bell register. There can
7023 * be race between controller sending the command to the device while abort is
7024 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
7025 * really issued and then try to abort it.
7027 * Returns zero on success, non-zero on failure
7029 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag)
7031 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7037 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
7038 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7039 UFS_QUERY_TASK, &resp);
7040 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
7041 /* cmd pending in the device */
7042 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
7045 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7047 * cmd not pending in the device, check if it is
7050 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
7052 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7053 if (reg & (1 << tag)) {
7054 /* sleep for max. 200us to stabilize */
7055 usleep_range(100, 200);
7058 /* command completed already */
7059 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
7064 "%s: no response from device. tag = %d, err %d\n",
7065 __func__, tag, err);
7067 err = resp; /* service response error */
7077 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7078 UFS_ABORT_TASK, &resp);
7079 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7081 err = resp; /* service response error */
7082 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
7083 __func__, tag, err);
7088 err = ufshcd_clear_cmd(hba, tag);
7090 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
7091 __func__, tag, err);
7098 * ufshcd_abort - scsi host template eh_abort_handler callback
7099 * @cmd: SCSI command pointer
7101 * Returns SUCCESS/FAILED
7103 static int ufshcd_abort(struct scsi_cmnd *cmd)
7105 struct Scsi_Host *host = cmd->device->host;
7106 struct ufs_hba *hba = shost_priv(host);
7107 int tag = scsi_cmd_to_rq(cmd)->tag;
7108 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7109 unsigned long flags;
7114 WARN_ONCE(tag < 0, "Invalid tag %d\n", tag);
7116 ufshcd_hold(hba, false);
7117 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7118 /* If command is already aborted/completed, return FAILED. */
7119 if (!(test_bit(tag, &hba->outstanding_reqs))) {
7121 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
7122 __func__, tag, hba->outstanding_reqs, reg);
7126 /* Print Transfer Request of aborted task */
7127 dev_info(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
7130 * Print detailed info about aborted request.
7131 * As more than one request might get aborted at the same time,
7132 * print full information only for the first aborted request in order
7133 * to reduce repeated printouts. For other aborted requests only print
7136 scsi_print_command(cmd);
7137 if (!hba->req_abort_count) {
7138 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, tag);
7139 ufshcd_print_evt_hist(hba);
7140 ufshcd_print_host_state(hba);
7141 ufshcd_print_pwr_info(hba);
7142 ufshcd_print_trs(hba, 1 << tag, true);
7144 ufshcd_print_trs(hba, 1 << tag, false);
7146 hba->req_abort_count++;
7148 if (!(reg & (1 << tag))) {
7150 "%s: cmd was completed, but without a notifying intr, tag = %d",
7152 __ufshcd_transfer_req_compl(hba, 1UL << tag);
7157 * Task abort to the device W-LUN is illegal. When this command
7158 * will fail, due to spec violation, scsi err handling next step
7159 * will be to send LU reset which, again, is a spec violation.
7160 * To avoid these unnecessary/illegal steps, first we clean up
7161 * the lrb taken by this cmd and re-set it in outstanding_reqs,
7162 * then queue the eh_work and bail.
7164 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN) {
7165 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, lrbp->lun);
7167 spin_lock_irqsave(host->host_lock, flags);
7168 hba->force_reset = true;
7169 ufshcd_schedule_eh_work(hba);
7170 spin_unlock_irqrestore(host->host_lock, flags);
7174 /* Skip task abort in case previous aborts failed and report failure */
7175 if (lrbp->req_abort_skip) {
7176 dev_err(hba->dev, "%s: skipping abort\n", __func__);
7177 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7181 err = ufshcd_try_to_abort_task(hba, tag);
7183 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7184 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7190 * Clear the corresponding bit from outstanding_reqs since the command
7191 * has been aborted successfully.
7193 spin_lock_irqsave(&hba->outstanding_lock, flags);
7194 outstanding = __test_and_clear_bit(tag, &hba->outstanding_reqs);
7195 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7198 ufshcd_release_scsi_cmd(hba, lrbp);
7203 /* Matches the ufshcd_hold() call at the start of this function. */
7204 ufshcd_release(hba);
7209 * ufshcd_host_reset_and_restore - reset and restore host controller
7210 * @hba: per-adapter instance
7212 * Note that host controller reset may issue DME_RESET to
7213 * local and remote (device) Uni-Pro stack and the attributes
7214 * are reset to default state.
7216 * Returns zero on success, non-zero on failure
7218 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
7223 * Stop the host controller and complete the requests
7226 ufshpb_reset_host(hba);
7227 ufshcd_hba_stop(hba);
7228 hba->silence_err_logs = true;
7229 ufshcd_complete_requests(hba);
7230 hba->silence_err_logs = false;
7232 /* scale up clocks to max frequency before full reinitialization */
7233 ufshcd_set_clk_freq(hba, true);
7235 err = ufshcd_hba_enable(hba);
7237 /* Establish the link again and restore the device */
7239 err = ufshcd_probe_hba(hba, false);
7242 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
7243 ufshcd_update_evt_hist(hba, UFS_EVT_HOST_RESET, (u32)err);
7248 * ufshcd_reset_and_restore - reset and re-initialize host/device
7249 * @hba: per-adapter instance
7251 * Reset and recover device, host and re-establish link. This
7252 * is helpful to recover the communication in fatal error conditions.
7254 * Returns zero on success, non-zero on failure
7256 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
7259 u32 saved_uic_err = 0;
7261 unsigned long flags;
7262 int retries = MAX_HOST_RESET_RETRIES;
7264 spin_lock_irqsave(hba->host->host_lock, flags);
7267 * This is a fresh start, cache and clear saved error first,
7268 * in case new error generated during reset and restore.
7270 saved_err |= hba->saved_err;
7271 saved_uic_err |= hba->saved_uic_err;
7273 hba->saved_uic_err = 0;
7274 hba->force_reset = false;
7275 hba->ufshcd_state = UFSHCD_STATE_RESET;
7276 spin_unlock_irqrestore(hba->host->host_lock, flags);
7278 /* Reset the attached device */
7279 ufshcd_device_reset(hba);
7281 err = ufshcd_host_reset_and_restore(hba);
7283 spin_lock_irqsave(hba->host->host_lock, flags);
7286 /* Do not exit unless operational or dead */
7287 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
7288 hba->ufshcd_state != UFSHCD_STATE_ERROR &&
7289 hba->ufshcd_state != UFSHCD_STATE_EH_SCHEDULED_NON_FATAL)
7291 } while (err && --retries);
7294 * Inform scsi mid-layer that we did reset and allow to handle
7295 * Unit Attention properly.
7297 scsi_report_bus_reset(hba->host, 0);
7299 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7300 hba->saved_err |= saved_err;
7301 hba->saved_uic_err |= saved_uic_err;
7303 spin_unlock_irqrestore(hba->host->host_lock, flags);
7309 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
7310 * @cmd: SCSI command pointer
7312 * Returns SUCCESS/FAILED
7314 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
7317 unsigned long flags;
7318 struct ufs_hba *hba;
7320 hba = shost_priv(cmd->device->host);
7322 spin_lock_irqsave(hba->host->host_lock, flags);
7323 hba->force_reset = true;
7324 ufshcd_schedule_eh_work(hba);
7325 dev_err(hba->dev, "%s: reset in progress - 1\n", __func__);
7326 spin_unlock_irqrestore(hba->host->host_lock, flags);
7328 flush_work(&hba->eh_work);
7330 spin_lock_irqsave(hba->host->host_lock, flags);
7331 if (hba->ufshcd_state == UFSHCD_STATE_ERROR)
7333 spin_unlock_irqrestore(hba->host->host_lock, flags);
7339 * ufshcd_get_max_icc_level - calculate the ICC level
7340 * @sup_curr_uA: max. current supported by the regulator
7341 * @start_scan: row at the desc table to start scan from
7342 * @buff: power descriptor buffer
7344 * Returns calculated max ICC level for specific regulator
7346 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
7353 for (i = start_scan; i >= 0; i--) {
7354 data = be16_to_cpup((__be16 *)&buff[2 * i]);
7355 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
7356 ATTR_ICC_LVL_UNIT_OFFSET;
7357 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
7359 case UFSHCD_NANO_AMP:
7360 curr_uA = curr_uA / 1000;
7362 case UFSHCD_MILI_AMP:
7363 curr_uA = curr_uA * 1000;
7366 curr_uA = curr_uA * 1000 * 1000;
7368 case UFSHCD_MICRO_AMP:
7372 if (sup_curr_uA >= curr_uA)
7377 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
7384 * ufshcd_find_max_sup_active_icc_level - calculate the max ICC level
7385 * In case regulators are not initialized we'll return 0
7386 * @hba: per-adapter instance
7387 * @desc_buf: power descriptor buffer to extract ICC levels from.
7388 * @len: length of desc_buff
7390 * Returns calculated ICC level
7392 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
7393 u8 *desc_buf, int len)
7397 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
7398 !hba->vreg_info.vccq2) {
7400 * Using dev_dbg to avoid messages during runtime PM to avoid
7401 * never-ending cycles of messages written back to storage by
7402 * user space causing runtime resume, causing more messages and
7406 "%s: Regulator capability was not set, actvIccLevel=%d",
7407 __func__, icc_level);
7411 if (hba->vreg_info.vcc->max_uA)
7412 icc_level = ufshcd_get_max_icc_level(
7413 hba->vreg_info.vcc->max_uA,
7414 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
7415 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
7417 if (hba->vreg_info.vccq->max_uA)
7418 icc_level = ufshcd_get_max_icc_level(
7419 hba->vreg_info.vccq->max_uA,
7421 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
7423 if (hba->vreg_info.vccq2->max_uA)
7424 icc_level = ufshcd_get_max_icc_level(
7425 hba->vreg_info.vccq2->max_uA,
7427 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
7432 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba)
7435 int buff_len = hba->desc_size[QUERY_DESC_IDN_POWER];
7439 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7443 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0,
7444 desc_buf, buff_len);
7447 "%s: Failed reading power descriptor.len = %d ret = %d",
7448 __func__, buff_len, ret);
7452 icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf,
7454 dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level);
7456 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7457 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level);
7461 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
7462 __func__, icc_level, ret);
7468 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev)
7470 scsi_autopm_get_device(sdev);
7471 blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev);
7472 if (sdev->rpm_autosuspend)
7473 pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev,
7474 RPM_AUTOSUSPEND_DELAY_MS);
7475 scsi_autopm_put_device(sdev);
7479 * ufshcd_scsi_add_wlus - Adds required W-LUs
7480 * @hba: per-adapter instance
7482 * UFS device specification requires the UFS devices to support 4 well known
7484 * "REPORT_LUNS" (address: 01h)
7485 * "UFS Device" (address: 50h)
7486 * "RPMB" (address: 44h)
7487 * "BOOT" (address: 30h)
7488 * UFS device's power management needs to be controlled by "POWER CONDITION"
7489 * field of SSU (START STOP UNIT) command. But this "power condition" field
7490 * will take effect only when its sent to "UFS device" well known logical unit
7491 * hence we require the scsi_device instance to represent this logical unit in
7492 * order for the UFS host driver to send the SSU command for power management.
7494 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
7495 * Block) LU so user space process can control this LU. User space may also
7496 * want to have access to BOOT LU.
7498 * This function adds scsi device instances for each of all well known LUs
7499 * (except "REPORT LUNS" LU).
7501 * Returns zero on success (all required W-LUs are added successfully),
7502 * non-zero error value on failure (if failed to add any of the required W-LU).
7504 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
7507 struct scsi_device *sdev_boot, *sdev_rpmb;
7509 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
7510 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
7511 if (IS_ERR(hba->sdev_ufs_device)) {
7512 ret = PTR_ERR(hba->sdev_ufs_device);
7513 hba->sdev_ufs_device = NULL;
7516 scsi_device_put(hba->sdev_ufs_device);
7518 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
7519 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
7520 if (IS_ERR(sdev_rpmb)) {
7521 ret = PTR_ERR(sdev_rpmb);
7522 goto remove_sdev_ufs_device;
7524 ufshcd_blk_pm_runtime_init(sdev_rpmb);
7525 scsi_device_put(sdev_rpmb);
7527 sdev_boot = __scsi_add_device(hba->host, 0, 0,
7528 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
7529 if (IS_ERR(sdev_boot)) {
7530 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
7532 ufshcd_blk_pm_runtime_init(sdev_boot);
7533 scsi_device_put(sdev_boot);
7537 remove_sdev_ufs_device:
7538 scsi_remove_device(hba->sdev_ufs_device);
7543 static void ufshcd_wb_probe(struct ufs_hba *hba, u8 *desc_buf)
7545 struct ufs_dev_info *dev_info = &hba->dev_info;
7547 u32 d_lu_wb_buf_alloc;
7548 u32 ext_ufs_feature;
7550 if (!ufshcd_is_wb_allowed(hba))
7554 * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or
7555 * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES
7558 if (!(dev_info->wspecversion >= 0x310 ||
7559 dev_info->wspecversion == 0x220 ||
7560 (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES)))
7563 if (hba->desc_size[QUERY_DESC_IDN_DEVICE] <
7564 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP + 4)
7567 ext_ufs_feature = get_unaligned_be32(desc_buf +
7568 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7570 if (!(ext_ufs_feature & UFS_DEV_WRITE_BOOSTER_SUP))
7574 * WB may be supported but not configured while provisioning. The spec
7575 * says, in dedicated wb buffer mode, a max of 1 lun would have wb
7576 * buffer configured.
7578 dev_info->wb_buffer_type = desc_buf[DEVICE_DESC_PARAM_WB_TYPE];
7580 dev_info->b_presrv_uspc_en =
7581 desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN];
7583 if (dev_info->wb_buffer_type == WB_BUF_MODE_SHARED) {
7584 if (!get_unaligned_be32(desc_buf +
7585 DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS))
7588 for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) {
7589 d_lu_wb_buf_alloc = 0;
7590 ufshcd_read_unit_desc_param(hba,
7592 UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS,
7593 (u8 *)&d_lu_wb_buf_alloc,
7594 sizeof(d_lu_wb_buf_alloc));
7595 if (d_lu_wb_buf_alloc) {
7596 dev_info->wb_dedicated_lu = lun;
7601 if (!d_lu_wb_buf_alloc)
7605 if (!ufshcd_is_wb_buf_lifetime_available(hba))
7611 hba->caps &= ~UFSHCD_CAP_WB_EN;
7614 static void ufshcd_temp_notif_probe(struct ufs_hba *hba, u8 *desc_buf)
7616 struct ufs_dev_info *dev_info = &hba->dev_info;
7617 u32 ext_ufs_feature;
7620 if (!(hba->caps & UFSHCD_CAP_TEMP_NOTIF) || dev_info->wspecversion < 0x300)
7623 ext_ufs_feature = get_unaligned_be32(desc_buf + DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7625 if (ext_ufs_feature & UFS_DEV_LOW_TEMP_NOTIF)
7626 mask |= MASK_EE_TOO_LOW_TEMP;
7628 if (ext_ufs_feature & UFS_DEV_HIGH_TEMP_NOTIF)
7629 mask |= MASK_EE_TOO_HIGH_TEMP;
7632 ufshcd_enable_ee(hba, mask);
7633 ufs_hwmon_probe(hba, mask);
7637 void ufshcd_fixup_dev_quirks(struct ufs_hba *hba, struct ufs_dev_fix *fixups)
7639 struct ufs_dev_fix *f;
7640 struct ufs_dev_info *dev_info = &hba->dev_info;
7645 for (f = fixups; f->quirk; f++) {
7646 if ((f->wmanufacturerid == dev_info->wmanufacturerid ||
7647 f->wmanufacturerid == UFS_ANY_VENDOR) &&
7648 ((dev_info->model &&
7649 STR_PRFX_EQUAL(f->model, dev_info->model)) ||
7650 !strcmp(f->model, UFS_ANY_MODEL)))
7651 hba->dev_quirks |= f->quirk;
7654 EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks);
7656 static void ufs_fixup_device_setup(struct ufs_hba *hba)
7658 /* fix by general quirk table */
7659 ufshcd_fixup_dev_quirks(hba, ufs_fixups);
7661 /* allow vendors to fix quirks */
7662 ufshcd_vops_fixup_dev_quirks(hba);
7665 static int ufs_get_device_desc(struct ufs_hba *hba)
7669 u8 b_ufs_feature_sup;
7671 struct ufs_dev_info *dev_info = &hba->dev_info;
7673 desc_buf = kmalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
7679 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf,
7680 hba->desc_size[QUERY_DESC_IDN_DEVICE]);
7682 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
7688 * getting vendor (manufacturerID) and Bank Index in big endian
7691 dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
7692 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
7694 /* getting Specification Version in big endian format */
7695 dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 |
7696 desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1];
7697 b_ufs_feature_sup = desc_buf[DEVICE_DESC_PARAM_UFS_FEAT];
7699 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
7701 if (dev_info->wspecversion >= UFS_DEV_HPB_SUPPORT_VERSION &&
7702 (b_ufs_feature_sup & UFS_DEV_HPB_SUPPORT)) {
7703 bool hpb_en = false;
7705 ufshpb_get_dev_info(hba, desc_buf);
7707 if (!ufshpb_is_legacy(hba))
7708 err = ufshcd_query_flag_retry(hba,
7709 UPIU_QUERY_OPCODE_READ_FLAG,
7710 QUERY_FLAG_IDN_HPB_EN, 0,
7713 if (ufshpb_is_legacy(hba) || (!err && hpb_en))
7714 dev_info->hpb_enabled = true;
7717 err = ufshcd_read_string_desc(hba, model_index,
7718 &dev_info->model, SD_ASCII_STD);
7720 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
7725 hba->luns_avail = desc_buf[DEVICE_DESC_PARAM_NUM_LU] +
7726 desc_buf[DEVICE_DESC_PARAM_NUM_WLU];
7728 ufs_fixup_device_setup(hba);
7730 ufshcd_wb_probe(hba, desc_buf);
7732 ufshcd_temp_notif_probe(hba, desc_buf);
7735 * ufshcd_read_string_desc returns size of the string
7736 * reset the error value
7745 static void ufs_put_device_desc(struct ufs_hba *hba)
7747 struct ufs_dev_info *dev_info = &hba->dev_info;
7749 kfree(dev_info->model);
7750 dev_info->model = NULL;
7754 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
7755 * @hba: per-adapter instance
7757 * PA_TActivate parameter can be tuned manually if UniPro version is less than
7758 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
7759 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
7760 * the hibern8 exit latency.
7762 * Returns zero on success, non-zero error value on failure.
7764 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
7767 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
7769 ret = ufshcd_dme_peer_get(hba,
7771 RX_MIN_ACTIVATETIME_CAPABILITY,
7772 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7773 &peer_rx_min_activatetime);
7777 /* make sure proper unit conversion is applied */
7778 tuned_pa_tactivate =
7779 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
7780 / PA_TACTIVATE_TIME_UNIT_US);
7781 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7782 tuned_pa_tactivate);
7789 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
7790 * @hba: per-adapter instance
7792 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
7793 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
7794 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
7795 * This optimal value can help reduce the hibern8 exit latency.
7797 * Returns zero on success, non-zero error value on failure.
7799 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
7802 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
7803 u32 max_hibern8_time, tuned_pa_hibern8time;
7805 ret = ufshcd_dme_get(hba,
7806 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
7807 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
7808 &local_tx_hibern8_time_cap);
7812 ret = ufshcd_dme_peer_get(hba,
7813 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
7814 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7815 &peer_rx_hibern8_time_cap);
7819 max_hibern8_time = max(local_tx_hibern8_time_cap,
7820 peer_rx_hibern8_time_cap);
7821 /* make sure proper unit conversion is applied */
7822 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
7823 / PA_HIBERN8_TIME_UNIT_US);
7824 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
7825 tuned_pa_hibern8time);
7831 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
7832 * less than device PA_TACTIVATE time.
7833 * @hba: per-adapter instance
7835 * Some UFS devices require host PA_TACTIVATE to be lower than device
7836 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
7839 * Returns zero on success, non-zero error value on failure.
7841 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
7844 u32 granularity, peer_granularity;
7845 u32 pa_tactivate, peer_pa_tactivate;
7846 u32 pa_tactivate_us, peer_pa_tactivate_us;
7847 u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
7849 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7854 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7859 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
7860 (granularity > PA_GRANULARITY_MAX_VAL)) {
7861 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
7862 __func__, granularity);
7866 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
7867 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
7868 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
7869 __func__, peer_granularity);
7873 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
7877 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
7878 &peer_pa_tactivate);
7882 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
7883 peer_pa_tactivate_us = peer_pa_tactivate *
7884 gran_to_us_table[peer_granularity - 1];
7886 if (pa_tactivate_us >= peer_pa_tactivate_us) {
7887 u32 new_peer_pa_tactivate;
7889 new_peer_pa_tactivate = pa_tactivate_us /
7890 gran_to_us_table[peer_granularity - 1];
7891 new_peer_pa_tactivate++;
7892 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7893 new_peer_pa_tactivate);
7900 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
7902 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
7903 ufshcd_tune_pa_tactivate(hba);
7904 ufshcd_tune_pa_hibern8time(hba);
7907 ufshcd_vops_apply_dev_quirks(hba);
7909 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
7910 /* set 1ms timeout for PA_TACTIVATE */
7911 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
7913 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
7914 ufshcd_quirk_tune_host_pa_tactivate(hba);
7917 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
7919 hba->ufs_stats.hibern8_exit_cnt = 0;
7920 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
7921 hba->req_abort_count = 0;
7924 static int ufshcd_device_geo_params_init(struct ufs_hba *hba)
7930 buff_len = hba->desc_size[QUERY_DESC_IDN_GEOMETRY];
7931 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7937 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0,
7938 desc_buf, buff_len);
7940 dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n",
7945 if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1)
7946 hba->dev_info.max_lu_supported = 32;
7947 else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0)
7948 hba->dev_info.max_lu_supported = 8;
7950 if (hba->desc_size[QUERY_DESC_IDN_GEOMETRY] >=
7951 GEOMETRY_DESC_PARAM_HPB_MAX_ACTIVE_REGS)
7952 ufshpb_get_geo_info(hba, desc_buf);
7959 static struct ufs_ref_clk ufs_ref_clk_freqs[] = {
7960 {19200000, REF_CLK_FREQ_19_2_MHZ},
7961 {26000000, REF_CLK_FREQ_26_MHZ},
7962 {38400000, REF_CLK_FREQ_38_4_MHZ},
7963 {52000000, REF_CLK_FREQ_52_MHZ},
7964 {0, REF_CLK_FREQ_INVAL},
7967 static enum ufs_ref_clk_freq
7968 ufs_get_bref_clk_from_hz(unsigned long freq)
7972 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
7973 if (ufs_ref_clk_freqs[i].freq_hz == freq)
7974 return ufs_ref_clk_freqs[i].val;
7976 return REF_CLK_FREQ_INVAL;
7979 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
7983 freq = clk_get_rate(refclk);
7985 hba->dev_ref_clk_freq =
7986 ufs_get_bref_clk_from_hz(freq);
7988 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
7990 "invalid ref_clk setting = %ld\n", freq);
7993 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
7997 u32 freq = hba->dev_ref_clk_freq;
7999 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
8000 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
8003 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
8008 if (ref_clk == freq)
8009 goto out; /* nothing to update */
8011 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
8012 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
8015 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
8016 ufs_ref_clk_freqs[freq].freq_hz);
8020 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
8021 ufs_ref_clk_freqs[freq].freq_hz);
8027 static int ufshcd_device_params_init(struct ufs_hba *hba)
8032 /* Init device descriptor sizes */
8033 for (i = 0; i < QUERY_DESC_IDN_MAX; i++)
8034 hba->desc_size[i] = QUERY_DESC_MAX_SIZE;
8036 /* Init UFS geometry descriptor related parameters */
8037 ret = ufshcd_device_geo_params_init(hba);
8041 /* Check and apply UFS device quirks */
8042 ret = ufs_get_device_desc(hba);
8044 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
8049 ufshcd_get_ref_clk_gating_wait(hba);
8051 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
8052 QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag))
8053 hba->dev_info.f_power_on_wp_en = flag;
8055 /* Probe maximum power mode co-supported by both UFS host and device */
8056 if (ufshcd_get_max_pwr_mode(hba))
8058 "%s: Failed getting max supported power mode\n",
8065 * ufshcd_add_lus - probe and add UFS logical units
8066 * @hba: per-adapter instance
8068 static int ufshcd_add_lus(struct ufs_hba *hba)
8072 /* Add required well known logical units to scsi mid layer */
8073 ret = ufshcd_scsi_add_wlus(hba);
8077 /* Initialize devfreq after UFS device is detected */
8078 if (ufshcd_is_clkscaling_supported(hba)) {
8079 memcpy(&hba->clk_scaling.saved_pwr_info.info,
8081 sizeof(struct ufs_pa_layer_attr));
8082 hba->clk_scaling.saved_pwr_info.is_valid = true;
8083 hba->clk_scaling.is_allowed = true;
8085 ret = ufshcd_devfreq_init(hba);
8089 hba->clk_scaling.is_enabled = true;
8090 ufshcd_init_clk_scaling_sysfs(hba);
8095 scsi_scan_host(hba->host);
8096 pm_runtime_put_sync(hba->dev);
8103 * ufshcd_probe_hba - probe hba to detect device and initialize it
8104 * @hba: per-adapter instance
8105 * @init_dev_params: whether or not to call ufshcd_device_params_init().
8107 * Execute link-startup and verify device initialization
8109 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params)
8112 unsigned long flags;
8113 ktime_t start = ktime_get();
8115 hba->ufshcd_state = UFSHCD_STATE_RESET;
8117 ret = ufshcd_link_startup(hba);
8121 if (hba->quirks & UFSHCD_QUIRK_SKIP_PH_CONFIGURATION)
8124 /* Debug counters initialization */
8125 ufshcd_clear_dbg_ufs_stats(hba);
8127 /* UniPro link is active now */
8128 ufshcd_set_link_active(hba);
8130 /* Verify device initialization by sending NOP OUT UPIU */
8131 ret = ufshcd_verify_dev_init(hba);
8135 /* Initiate UFS initialization, and waiting until completion */
8136 ret = ufshcd_complete_dev_init(hba);
8141 * Initialize UFS device parameters used by driver, these
8142 * parameters are associated with UFS descriptors.
8144 if (init_dev_params) {
8145 ret = ufshcd_device_params_init(hba);
8150 ufshcd_tune_unipro_params(hba);
8152 /* UFS device is also active now */
8153 ufshcd_set_ufs_dev_active(hba);
8154 ufshcd_force_reset_auto_bkops(hba);
8156 /* Gear up to HS gear if supported */
8157 if (hba->max_pwr_info.is_valid) {
8159 * Set the right value to bRefClkFreq before attempting to
8160 * switch to HS gears.
8162 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
8163 ufshcd_set_dev_ref_clk(hba);
8164 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
8166 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
8170 ufshcd_print_pwr_info(hba);
8174 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec)
8175 * and for removable UFS card as well, hence always set the parameter.
8176 * Note: Error handler may issue the device reset hence resetting
8177 * bActiveICCLevel as well so it is always safe to set this here.
8179 ufshcd_set_active_icc_lvl(hba);
8181 ufshcd_wb_config(hba);
8182 if (hba->ee_usr_mask)
8183 ufshcd_write_ee_control(hba);
8184 /* Enable Auto-Hibernate if configured */
8185 ufshcd_auto_hibern8_enable(hba);
8189 spin_lock_irqsave(hba->host->host_lock, flags);
8191 hba->ufshcd_state = UFSHCD_STATE_ERROR;
8192 else if (hba->ufshcd_state == UFSHCD_STATE_RESET)
8193 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
8194 spin_unlock_irqrestore(hba->host->host_lock, flags);
8196 trace_ufshcd_init(dev_name(hba->dev), ret,
8197 ktime_to_us(ktime_sub(ktime_get(), start)),
8198 hba->curr_dev_pwr_mode, hba->uic_link_state);
8203 * ufshcd_async_scan - asynchronous execution for probing hba
8204 * @data: data pointer to pass to this function
8205 * @cookie: cookie data
8207 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
8209 struct ufs_hba *hba = (struct ufs_hba *)data;
8212 down(&hba->host_sem);
8213 /* Initialize hba, detect and initialize UFS device */
8214 ret = ufshcd_probe_hba(hba, true);
8219 /* Probe and add UFS logical units */
8220 ret = ufshcd_add_lus(hba);
8223 * If we failed to initialize the device or the device is not
8224 * present, turn off the power/clocks etc.
8227 pm_runtime_put_sync(hba->dev);
8228 ufshcd_hba_exit(hba);
8232 static const struct attribute_group *ufshcd_driver_groups[] = {
8233 &ufs_sysfs_unit_descriptor_group,
8234 &ufs_sysfs_lun_attributes_group,
8235 #ifdef CONFIG_SCSI_UFS_HPB
8236 &ufs_sysfs_hpb_stat_group,
8237 &ufs_sysfs_hpb_param_group,
8242 static struct ufs_hba_variant_params ufs_hba_vps = {
8243 .hba_enable_delay_us = 1000,
8244 .wb_flush_threshold = UFS_WB_BUF_REMAIN_PERCENT(40),
8245 .devfreq_profile.polling_ms = 100,
8246 .devfreq_profile.target = ufshcd_devfreq_target,
8247 .devfreq_profile.get_dev_status = ufshcd_devfreq_get_dev_status,
8248 .ondemand_data.upthreshold = 70,
8249 .ondemand_data.downdifferential = 5,
8252 static struct scsi_host_template ufshcd_driver_template = {
8253 .module = THIS_MODULE,
8255 .proc_name = UFSHCD,
8256 .map_queues = ufshcd_map_queues,
8257 .queuecommand = ufshcd_queuecommand,
8258 .mq_poll = ufshcd_poll,
8259 .slave_alloc = ufshcd_slave_alloc,
8260 .slave_configure = ufshcd_slave_configure,
8261 .slave_destroy = ufshcd_slave_destroy,
8262 .change_queue_depth = ufshcd_change_queue_depth,
8263 .eh_abort_handler = ufshcd_abort,
8264 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
8265 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
8267 .sg_tablesize = SG_ALL,
8268 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
8269 .can_queue = UFSHCD_CAN_QUEUE,
8270 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX,
8271 .max_host_blocked = 1,
8272 .track_queue_depth = 1,
8273 .sdev_groups = ufshcd_driver_groups,
8274 .dma_boundary = PAGE_SIZE - 1,
8275 .rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS,
8278 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
8287 * "set_load" operation shall be required on those regulators
8288 * which specifically configured current limitation. Otherwise
8289 * zero max_uA may cause unexpected behavior when regulator is
8290 * enabled or set as high power mode.
8295 ret = regulator_set_load(vreg->reg, ua);
8297 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
8298 __func__, vreg->name, ua, ret);
8304 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
8305 struct ufs_vreg *vreg)
8307 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
8310 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
8311 struct ufs_vreg *vreg)
8316 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
8319 static int ufshcd_config_vreg(struct device *dev,
8320 struct ufs_vreg *vreg, bool on)
8323 struct regulator *reg;
8325 int min_uV, uA_load;
8332 if (regulator_count_voltages(reg) > 0) {
8333 uA_load = on ? vreg->max_uA : 0;
8334 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
8338 if (vreg->min_uV && vreg->max_uV) {
8339 min_uV = on ? vreg->min_uV : 0;
8340 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
8343 "%s: %s set voltage failed, err=%d\n",
8344 __func__, name, ret);
8351 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
8355 if (!vreg || vreg->enabled)
8358 ret = ufshcd_config_vreg(dev, vreg, true);
8360 ret = regulator_enable(vreg->reg);
8363 vreg->enabled = true;
8365 dev_err(dev, "%s: %s enable failed, err=%d\n",
8366 __func__, vreg->name, ret);
8371 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
8375 if (!vreg || !vreg->enabled || vreg->always_on)
8378 ret = regulator_disable(vreg->reg);
8381 /* ignore errors on applying disable config */
8382 ufshcd_config_vreg(dev, vreg, false);
8383 vreg->enabled = false;
8385 dev_err(dev, "%s: %s disable failed, err=%d\n",
8386 __func__, vreg->name, ret);
8392 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
8395 struct device *dev = hba->dev;
8396 struct ufs_vreg_info *info = &hba->vreg_info;
8398 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
8402 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
8406 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
8410 ufshcd_toggle_vreg(dev, info->vccq2, false);
8411 ufshcd_toggle_vreg(dev, info->vccq, false);
8412 ufshcd_toggle_vreg(dev, info->vcc, false);
8417 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
8419 struct ufs_vreg_info *info = &hba->vreg_info;
8421 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
8424 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
8431 vreg->reg = devm_regulator_get(dev, vreg->name);
8432 if (IS_ERR(vreg->reg)) {
8433 ret = PTR_ERR(vreg->reg);
8434 dev_err(dev, "%s: %s get failed, err=%d\n",
8435 __func__, vreg->name, ret);
8441 static int ufshcd_init_vreg(struct ufs_hba *hba)
8444 struct device *dev = hba->dev;
8445 struct ufs_vreg_info *info = &hba->vreg_info;
8447 ret = ufshcd_get_vreg(dev, info->vcc);
8451 ret = ufshcd_get_vreg(dev, info->vccq);
8453 ret = ufshcd_get_vreg(dev, info->vccq2);
8458 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
8460 struct ufs_vreg_info *info = &hba->vreg_info;
8463 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
8468 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
8471 struct ufs_clk_info *clki;
8472 struct list_head *head = &hba->clk_list_head;
8473 unsigned long flags;
8474 ktime_t start = ktime_get();
8475 bool clk_state_changed = false;
8477 if (list_empty(head))
8480 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
8484 list_for_each_entry(clki, head, list) {
8485 if (!IS_ERR_OR_NULL(clki->clk)) {
8487 * Don't disable clocks which are needed
8488 * to keep the link active.
8490 if (ufshcd_is_link_active(hba) &&
8491 clki->keep_link_active)
8494 clk_state_changed = on ^ clki->enabled;
8495 if (on && !clki->enabled) {
8496 ret = clk_prepare_enable(clki->clk);
8498 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
8499 __func__, clki->name, ret);
8502 } else if (!on && clki->enabled) {
8503 clk_disable_unprepare(clki->clk);
8506 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
8507 clki->name, on ? "en" : "dis");
8511 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
8517 list_for_each_entry(clki, head, list) {
8518 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
8519 clk_disable_unprepare(clki->clk);
8521 } else if (!ret && on) {
8522 spin_lock_irqsave(hba->host->host_lock, flags);
8523 hba->clk_gating.state = CLKS_ON;
8524 trace_ufshcd_clk_gating(dev_name(hba->dev),
8525 hba->clk_gating.state);
8526 spin_unlock_irqrestore(hba->host->host_lock, flags);
8529 if (clk_state_changed)
8530 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
8531 (on ? "on" : "off"),
8532 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
8536 static int ufshcd_init_clocks(struct ufs_hba *hba)
8539 struct ufs_clk_info *clki;
8540 struct device *dev = hba->dev;
8541 struct list_head *head = &hba->clk_list_head;
8543 if (list_empty(head))
8546 list_for_each_entry(clki, head, list) {
8550 clki->clk = devm_clk_get(dev, clki->name);
8551 if (IS_ERR(clki->clk)) {
8552 ret = PTR_ERR(clki->clk);
8553 dev_err(dev, "%s: %s clk get failed, %d\n",
8554 __func__, clki->name, ret);
8559 * Parse device ref clk freq as per device tree "ref_clk".
8560 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
8561 * in ufshcd_alloc_host().
8563 if (!strcmp(clki->name, "ref_clk"))
8564 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
8566 if (clki->max_freq) {
8567 ret = clk_set_rate(clki->clk, clki->max_freq);
8569 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
8570 __func__, clki->name,
8571 clki->max_freq, ret);
8574 clki->curr_freq = clki->max_freq;
8576 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
8577 clki->name, clk_get_rate(clki->clk));
8583 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
8590 err = ufshcd_vops_init(hba);
8592 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
8593 __func__, ufshcd_get_var_name(hba), err);
8598 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
8603 ufshcd_vops_exit(hba);
8606 static int ufshcd_hba_init(struct ufs_hba *hba)
8611 * Handle host controller power separately from the UFS device power
8612 * rails as it will help controlling the UFS host controller power
8613 * collapse easily which is different than UFS device power collapse.
8614 * Also, enable the host controller power before we go ahead with rest
8615 * of the initialization here.
8617 err = ufshcd_init_hba_vreg(hba);
8621 err = ufshcd_setup_hba_vreg(hba, true);
8625 err = ufshcd_init_clocks(hba);
8627 goto out_disable_hba_vreg;
8629 err = ufshcd_setup_clocks(hba, true);
8631 goto out_disable_hba_vreg;
8633 err = ufshcd_init_vreg(hba);
8635 goto out_disable_clks;
8637 err = ufshcd_setup_vreg(hba, true);
8639 goto out_disable_clks;
8641 err = ufshcd_variant_hba_init(hba);
8643 goto out_disable_vreg;
8645 ufs_debugfs_hba_init(hba);
8647 hba->is_powered = true;
8651 ufshcd_setup_vreg(hba, false);
8653 ufshcd_setup_clocks(hba, false);
8654 out_disable_hba_vreg:
8655 ufshcd_setup_hba_vreg(hba, false);
8660 static void ufshcd_hba_exit(struct ufs_hba *hba)
8662 if (hba->is_powered) {
8663 ufshcd_exit_clk_scaling(hba);
8664 ufshcd_exit_clk_gating(hba);
8666 destroy_workqueue(hba->eh_wq);
8667 ufs_debugfs_hba_exit(hba);
8668 ufshcd_variant_hba_exit(hba);
8669 ufshcd_setup_vreg(hba, false);
8670 ufshcd_setup_clocks(hba, false);
8671 ufshcd_setup_hba_vreg(hba, false);
8672 hba->is_powered = false;
8673 ufs_put_device_desc(hba);
8678 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
8680 * @hba: per adapter instance
8681 * @pwr_mode: device power mode to set
8683 * Returns 0 if requested power mode is set successfully
8684 * Returns < 0 if failed to set the requested power mode
8686 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
8687 enum ufs_dev_pwr_mode pwr_mode)
8689 unsigned char cmd[6] = { START_STOP };
8690 struct scsi_sense_hdr sshdr;
8691 struct scsi_device *sdp;
8692 unsigned long flags;
8695 spin_lock_irqsave(hba->host->host_lock, flags);
8696 sdp = hba->sdev_ufs_device;
8698 ret = scsi_device_get(sdp);
8699 if (!ret && !scsi_device_online(sdp)) {
8701 scsi_device_put(sdp);
8706 spin_unlock_irqrestore(hba->host->host_lock, flags);
8712 * If scsi commands fail, the scsi mid-layer schedules scsi error-
8713 * handling, which would wait for host to be resumed. Since we know
8714 * we are functional while we are here, skip host resume in error
8717 hba->host->eh_noresume = 1;
8719 cmd[4] = pwr_mode << 4;
8722 * Current function would be generally called from the power management
8723 * callbacks hence set the RQF_PM flag so that it doesn't resume the
8724 * already suspended childs.
8726 for (retries = 3; retries > 0; --retries) {
8727 ret = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, &sshdr,
8728 START_STOP_TIMEOUT, 0, 0, RQF_PM, NULL);
8729 if (!scsi_status_is_check_condition(ret) ||
8730 !scsi_sense_valid(&sshdr) ||
8731 sshdr.sense_key != UNIT_ATTENTION)
8735 sdev_printk(KERN_WARNING, sdp,
8736 "START_STOP failed for power mode: %d, result %x\n",
8739 if (scsi_sense_valid(&sshdr))
8740 scsi_print_sense_hdr(sdp, NULL, &sshdr);
8746 hba->curr_dev_pwr_mode = pwr_mode;
8748 scsi_device_put(sdp);
8749 hba->host->eh_noresume = 0;
8753 static int ufshcd_link_state_transition(struct ufs_hba *hba,
8754 enum uic_link_state req_link_state,
8755 int check_for_bkops)
8759 if (req_link_state == hba->uic_link_state)
8762 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
8763 ret = ufshcd_uic_hibern8_enter(hba);
8765 ufshcd_set_link_hibern8(hba);
8767 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8773 * If autobkops is enabled, link can't be turned off because
8774 * turning off the link would also turn off the device, except in the
8775 * case of DeepSleep where the device is expected to remain powered.
8777 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
8778 (!check_for_bkops || !hba->auto_bkops_enabled)) {
8780 * Let's make sure that link is in low power mode, we are doing
8781 * this currently by putting the link in Hibern8. Otherway to
8782 * put the link in low power mode is to send the DME end point
8783 * to device and then send the DME reset command to local
8784 * unipro. But putting the link in hibern8 is much faster.
8786 * Note also that putting the link in Hibern8 is a requirement
8787 * for entering DeepSleep.
8789 ret = ufshcd_uic_hibern8_enter(hba);
8791 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8796 * Change controller state to "reset state" which
8797 * should also put the link in off/reset state
8799 ufshcd_hba_stop(hba);
8801 * TODO: Check if we need any delay to make sure that
8802 * controller is reset
8804 ufshcd_set_link_off(hba);
8811 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
8813 bool vcc_off = false;
8816 * It seems some UFS devices may keep drawing more than sleep current
8817 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
8818 * To avoid this situation, add 2ms delay before putting these UFS
8819 * rails in LPM mode.
8821 if (!ufshcd_is_link_active(hba) &&
8822 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
8823 usleep_range(2000, 2100);
8826 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
8829 * If UFS device and link is in OFF state, all power supplies (VCC,
8830 * VCCQ, VCCQ2) can be turned off if power on write protect is not
8831 * required. If UFS link is inactive (Hibern8 or OFF state) and device
8832 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
8834 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
8835 * in low power state which would save some power.
8837 * If Write Booster is enabled and the device needs to flush the WB
8838 * buffer OR if bkops status is urgent for WB, keep Vcc on.
8840 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8841 !hba->dev_info.is_lu_power_on_wp) {
8842 ufshcd_setup_vreg(hba, false);
8844 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8845 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8847 if (ufshcd_is_link_hibern8(hba) || ufshcd_is_link_off(hba)) {
8848 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8849 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
8854 * Some UFS devices require delay after VCC power rail is turned-off.
8856 if (vcc_off && hba->vreg_info.vcc &&
8857 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_AFTER_LPM)
8858 usleep_range(5000, 5100);
8862 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
8866 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8867 !hba->dev_info.is_lu_power_on_wp) {
8868 ret = ufshcd_setup_vreg(hba, true);
8869 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8870 if (!ufshcd_is_link_active(hba)) {
8871 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
8874 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
8878 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
8883 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8885 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8889 #endif /* CONFIG_PM */
8891 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
8893 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
8894 ufshcd_setup_hba_vreg(hba, false);
8897 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
8899 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
8900 ufshcd_setup_hba_vreg(hba, true);
8903 static int __ufshcd_wl_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8906 int check_for_bkops;
8907 enum ufs_pm_level pm_lvl;
8908 enum ufs_dev_pwr_mode req_dev_pwr_mode;
8909 enum uic_link_state req_link_state;
8911 hba->pm_op_in_progress = true;
8912 if (pm_op != UFS_SHUTDOWN_PM) {
8913 pm_lvl = pm_op == UFS_RUNTIME_PM ?
8914 hba->rpm_lvl : hba->spm_lvl;
8915 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
8916 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
8918 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
8919 req_link_state = UIC_LINK_OFF_STATE;
8922 ufshpb_suspend(hba);
8925 * If we can't transition into any of the low power modes
8926 * just gate the clocks.
8928 ufshcd_hold(hba, false);
8929 hba->clk_gating.is_suspended = true;
8931 if (ufshcd_is_clkscaling_supported(hba))
8932 ufshcd_clk_scaling_suspend(hba, true);
8934 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
8935 req_link_state == UIC_LINK_ACTIVE_STATE) {
8939 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
8940 (req_link_state == hba->uic_link_state))
8941 goto enable_scaling;
8943 /* UFS device & link must be active before we enter in this function */
8944 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
8946 goto enable_scaling;
8949 if (pm_op == UFS_RUNTIME_PM) {
8950 if (ufshcd_can_autobkops_during_suspend(hba)) {
8952 * The device is idle with no requests in the queue,
8953 * allow background operations if bkops status shows
8954 * that performance might be impacted.
8956 ret = ufshcd_urgent_bkops(hba);
8958 goto enable_scaling;
8960 /* make sure that auto bkops is disabled */
8961 ufshcd_disable_auto_bkops(hba);
8964 * If device needs to do BKOP or WB buffer flush during
8965 * Hibern8, keep device power mode as "active power mode"
8968 hba->dev_info.b_rpm_dev_flush_capable =
8969 hba->auto_bkops_enabled ||
8970 (((req_link_state == UIC_LINK_HIBERN8_STATE) ||
8971 ((req_link_state == UIC_LINK_ACTIVE_STATE) &&
8972 ufshcd_is_auto_hibern8_enabled(hba))) &&
8973 ufshcd_wb_need_flush(hba));
8976 flush_work(&hba->eeh_work);
8978 ret = ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
8980 goto enable_scaling;
8982 if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) {
8983 if (pm_op != UFS_RUNTIME_PM)
8984 /* ensure that bkops is disabled */
8985 ufshcd_disable_auto_bkops(hba);
8987 if (!hba->dev_info.b_rpm_dev_flush_capable) {
8988 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
8990 goto enable_scaling;
8995 * In the case of DeepSleep, the device is expected to remain powered
8996 * with the link off, so do not check for bkops.
8998 check_for_bkops = !ufshcd_is_ufs_dev_deepsleep(hba);
8999 ret = ufshcd_link_state_transition(hba, req_link_state, check_for_bkops);
9001 goto set_dev_active;
9005 * Call vendor specific suspend callback. As these callbacks may access
9006 * vendor specific host controller register space call them before the
9007 * host clocks are ON.
9009 ret = ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
9011 goto set_link_active;
9016 * Device hardware reset is required to exit DeepSleep. Also, for
9017 * DeepSleep, the link is off so host reset and restore will be done
9020 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
9021 ufshcd_device_reset(hba);
9022 WARN_ON(!ufshcd_is_link_off(hba));
9024 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
9025 ufshcd_set_link_active(hba);
9026 else if (ufshcd_is_link_off(hba))
9027 ufshcd_host_reset_and_restore(hba);
9029 /* Can also get here needing to exit DeepSleep */
9030 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
9031 ufshcd_device_reset(hba);
9032 ufshcd_host_reset_and_restore(hba);
9034 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
9035 ufshcd_disable_auto_bkops(hba);
9037 if (ufshcd_is_clkscaling_supported(hba))
9038 ufshcd_clk_scaling_suspend(hba, false);
9040 hba->dev_info.b_rpm_dev_flush_capable = false;
9042 if (hba->dev_info.b_rpm_dev_flush_capable) {
9043 schedule_delayed_work(&hba->rpm_dev_flush_recheck_work,
9044 msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS));
9048 ufshcd_update_evt_hist(hba, UFS_EVT_WL_SUSP_ERR, (u32)ret);
9049 hba->clk_gating.is_suspended = false;
9050 ufshcd_release(hba);
9053 hba->pm_op_in_progress = false;
9058 static int __ufshcd_wl_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
9061 enum uic_link_state old_link_state = hba->uic_link_state;
9063 hba->pm_op_in_progress = true;
9066 * Call vendor specific resume callback. As these callbacks may access
9067 * vendor specific host controller register space call them when the
9068 * host clocks are ON.
9070 ret = ufshcd_vops_resume(hba, pm_op);
9074 /* For DeepSleep, the only supported option is to have the link off */
9075 WARN_ON(ufshcd_is_ufs_dev_deepsleep(hba) && !ufshcd_is_link_off(hba));
9077 if (ufshcd_is_link_hibern8(hba)) {
9078 ret = ufshcd_uic_hibern8_exit(hba);
9080 ufshcd_set_link_active(hba);
9082 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
9084 goto vendor_suspend;
9086 } else if (ufshcd_is_link_off(hba)) {
9088 * A full initialization of the host and the device is
9089 * required since the link was put to off during suspend.
9090 * Note, in the case of DeepSleep, the device will exit
9091 * DeepSleep due to device reset.
9093 ret = ufshcd_reset_and_restore(hba);
9095 * ufshcd_reset_and_restore() should have already
9096 * set the link state as active
9098 if (ret || !ufshcd_is_link_active(hba))
9099 goto vendor_suspend;
9102 if (!ufshcd_is_ufs_dev_active(hba)) {
9103 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
9105 goto set_old_link_state;
9108 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
9109 ufshcd_enable_auto_bkops(hba);
9112 * If BKOPs operations are urgently needed at this moment then
9113 * keep auto-bkops enabled or else disable it.
9115 ufshcd_urgent_bkops(hba);
9117 if (hba->ee_usr_mask)
9118 ufshcd_write_ee_control(hba);
9120 if (ufshcd_is_clkscaling_supported(hba))
9121 ufshcd_clk_scaling_suspend(hba, false);
9123 if (hba->dev_info.b_rpm_dev_flush_capable) {
9124 hba->dev_info.b_rpm_dev_flush_capable = false;
9125 cancel_delayed_work(&hba->rpm_dev_flush_recheck_work);
9128 /* Enable Auto-Hibernate if configured */
9129 ufshcd_auto_hibern8_enable(hba);
9135 ufshcd_link_state_transition(hba, old_link_state, 0);
9137 ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
9138 ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
9141 ufshcd_update_evt_hist(hba, UFS_EVT_WL_RES_ERR, (u32)ret);
9142 hba->clk_gating.is_suspended = false;
9143 ufshcd_release(hba);
9144 hba->pm_op_in_progress = false;
9148 static int ufshcd_wl_runtime_suspend(struct device *dev)
9150 struct scsi_device *sdev = to_scsi_device(dev);
9151 struct ufs_hba *hba;
9153 ktime_t start = ktime_get();
9155 hba = shost_priv(sdev->host);
9157 ret = __ufshcd_wl_suspend(hba, UFS_RUNTIME_PM);
9159 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9161 trace_ufshcd_wl_runtime_suspend(dev_name(dev), ret,
9162 ktime_to_us(ktime_sub(ktime_get(), start)),
9163 hba->curr_dev_pwr_mode, hba->uic_link_state);
9168 static int ufshcd_wl_runtime_resume(struct device *dev)
9170 struct scsi_device *sdev = to_scsi_device(dev);
9171 struct ufs_hba *hba;
9173 ktime_t start = ktime_get();
9175 hba = shost_priv(sdev->host);
9177 ret = __ufshcd_wl_resume(hba, UFS_RUNTIME_PM);
9179 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9181 trace_ufshcd_wl_runtime_resume(dev_name(dev), ret,
9182 ktime_to_us(ktime_sub(ktime_get(), start)),
9183 hba->curr_dev_pwr_mode, hba->uic_link_state);
9189 #ifdef CONFIG_PM_SLEEP
9190 static int ufshcd_wl_suspend(struct device *dev)
9192 struct scsi_device *sdev = to_scsi_device(dev);
9193 struct ufs_hba *hba;
9195 ktime_t start = ktime_get();
9197 hba = shost_priv(sdev->host);
9198 down(&hba->host_sem);
9200 if (pm_runtime_suspended(dev))
9203 ret = __ufshcd_wl_suspend(hba, UFS_SYSTEM_PM);
9205 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9211 hba->is_sys_suspended = true;
9212 trace_ufshcd_wl_suspend(dev_name(dev), ret,
9213 ktime_to_us(ktime_sub(ktime_get(), start)),
9214 hba->curr_dev_pwr_mode, hba->uic_link_state);
9219 static int ufshcd_wl_resume(struct device *dev)
9221 struct scsi_device *sdev = to_scsi_device(dev);
9222 struct ufs_hba *hba;
9224 ktime_t start = ktime_get();
9226 hba = shost_priv(sdev->host);
9228 if (pm_runtime_suspended(dev))
9231 ret = __ufshcd_wl_resume(hba, UFS_SYSTEM_PM);
9233 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9235 trace_ufshcd_wl_resume(dev_name(dev), ret,
9236 ktime_to_us(ktime_sub(ktime_get(), start)),
9237 hba->curr_dev_pwr_mode, hba->uic_link_state);
9239 hba->is_sys_suspended = false;
9245 static void ufshcd_wl_shutdown(struct device *dev)
9247 struct scsi_device *sdev = to_scsi_device(dev);
9248 struct ufs_hba *hba;
9250 hba = shost_priv(sdev->host);
9252 down(&hba->host_sem);
9253 hba->shutting_down = true;
9256 /* Turn on everything while shutting down */
9257 ufshcd_rpm_get_sync(hba);
9258 scsi_device_quiesce(sdev);
9259 shost_for_each_device(sdev, hba->host) {
9260 if (sdev == hba->sdev_ufs_device)
9262 scsi_device_quiesce(sdev);
9264 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
9268 * ufshcd_suspend - helper function for suspend operations
9269 * @hba: per adapter instance
9271 * This function will put disable irqs, turn off clocks
9272 * and set vreg and hba-vreg in lpm mode.
9274 static int ufshcd_suspend(struct ufs_hba *hba)
9278 if (!hba->is_powered)
9281 * Disable the host irq as host controller as there won't be any
9282 * host controller transaction expected till resume.
9284 ufshcd_disable_irq(hba);
9285 ret = ufshcd_setup_clocks(hba, false);
9287 ufshcd_enable_irq(hba);
9290 if (ufshcd_is_clkgating_allowed(hba)) {
9291 hba->clk_gating.state = CLKS_OFF;
9292 trace_ufshcd_clk_gating(dev_name(hba->dev),
9293 hba->clk_gating.state);
9296 ufshcd_vreg_set_lpm(hba);
9297 /* Put the host controller in low power mode if possible */
9298 ufshcd_hba_vreg_set_lpm(hba);
9304 * ufshcd_resume - helper function for resume operations
9305 * @hba: per adapter instance
9307 * This function basically turns on the regulators, clocks and
9310 * Returns 0 for success and non-zero for failure
9312 static int ufshcd_resume(struct ufs_hba *hba)
9316 if (!hba->is_powered)
9319 ufshcd_hba_vreg_set_hpm(hba);
9320 ret = ufshcd_vreg_set_hpm(hba);
9324 /* Make sure clocks are enabled before accessing controller */
9325 ret = ufshcd_setup_clocks(hba, true);
9329 /* enable the host irq as host controller would be active soon */
9330 ufshcd_enable_irq(hba);
9334 ufshcd_vreg_set_lpm(hba);
9337 ufshcd_update_evt_hist(hba, UFS_EVT_RESUME_ERR, (u32)ret);
9340 #endif /* CONFIG_PM */
9342 #ifdef CONFIG_PM_SLEEP
9344 * ufshcd_system_suspend - system suspend callback
9345 * @dev: Device associated with the UFS controller.
9347 * Executed before putting the system into a sleep state in which the contents
9348 * of main memory are preserved.
9350 * Returns 0 for success and non-zero for failure
9352 int ufshcd_system_suspend(struct device *dev)
9354 struct ufs_hba *hba = dev_get_drvdata(dev);
9356 ktime_t start = ktime_get();
9358 if (pm_runtime_suspended(hba->dev))
9361 ret = ufshcd_suspend(hba);
9363 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
9364 ktime_to_us(ktime_sub(ktime_get(), start)),
9365 hba->curr_dev_pwr_mode, hba->uic_link_state);
9368 EXPORT_SYMBOL(ufshcd_system_suspend);
9371 * ufshcd_system_resume - system resume callback
9372 * @dev: Device associated with the UFS controller.
9374 * Executed after waking the system up from a sleep state in which the contents
9375 * of main memory were preserved.
9377 * Returns 0 for success and non-zero for failure
9379 int ufshcd_system_resume(struct device *dev)
9381 struct ufs_hba *hba = dev_get_drvdata(dev);
9382 ktime_t start = ktime_get();
9385 if (pm_runtime_suspended(hba->dev))
9388 ret = ufshcd_resume(hba);
9391 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
9392 ktime_to_us(ktime_sub(ktime_get(), start)),
9393 hba->curr_dev_pwr_mode, hba->uic_link_state);
9397 EXPORT_SYMBOL(ufshcd_system_resume);
9398 #endif /* CONFIG_PM_SLEEP */
9402 * ufshcd_runtime_suspend - runtime suspend callback
9403 * @dev: Device associated with the UFS controller.
9405 * Check the description of ufshcd_suspend() function for more details.
9407 * Returns 0 for success and non-zero for failure
9409 int ufshcd_runtime_suspend(struct device *dev)
9411 struct ufs_hba *hba = dev_get_drvdata(dev);
9413 ktime_t start = ktime_get();
9415 ret = ufshcd_suspend(hba);
9417 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
9418 ktime_to_us(ktime_sub(ktime_get(), start)),
9419 hba->curr_dev_pwr_mode, hba->uic_link_state);
9422 EXPORT_SYMBOL(ufshcd_runtime_suspend);
9425 * ufshcd_runtime_resume - runtime resume routine
9426 * @dev: Device associated with the UFS controller.
9428 * This function basically brings controller
9429 * to active state. Following operations are done in this function:
9431 * 1. Turn on all the controller related clocks
9432 * 2. Turn ON VCC rail
9434 int ufshcd_runtime_resume(struct device *dev)
9436 struct ufs_hba *hba = dev_get_drvdata(dev);
9438 ktime_t start = ktime_get();
9440 ret = ufshcd_resume(hba);
9442 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
9443 ktime_to_us(ktime_sub(ktime_get(), start)),
9444 hba->curr_dev_pwr_mode, hba->uic_link_state);
9447 EXPORT_SYMBOL(ufshcd_runtime_resume);
9448 #endif /* CONFIG_PM */
9451 * ufshcd_shutdown - shutdown routine
9452 * @hba: per adapter instance
9454 * This function would turn off both UFS device and UFS hba
9455 * regulators. It would also disable clocks.
9457 * Returns 0 always to allow force shutdown even in case of errors.
9459 int ufshcd_shutdown(struct ufs_hba *hba)
9461 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
9464 pm_runtime_get_sync(hba->dev);
9466 ufshcd_suspend(hba);
9468 hba->is_powered = false;
9469 /* allow force shutdown even in case of errors */
9472 EXPORT_SYMBOL(ufshcd_shutdown);
9475 * ufshcd_remove - de-allocate SCSI host and host memory space
9476 * data structure memory
9477 * @hba: per adapter instance
9479 void ufshcd_remove(struct ufs_hba *hba)
9481 if (hba->sdev_ufs_device)
9482 ufshcd_rpm_get_sync(hba);
9483 ufs_hwmon_remove(hba);
9484 ufs_bsg_remove(hba);
9486 ufs_sysfs_remove_nodes(hba->dev);
9487 blk_cleanup_queue(hba->tmf_queue);
9488 blk_mq_free_tag_set(&hba->tmf_tag_set);
9489 scsi_remove_host(hba->host);
9490 /* disable interrupts */
9491 ufshcd_disable_intr(hba, hba->intr_mask);
9492 ufshcd_hba_stop(hba);
9493 ufshcd_hba_exit(hba);
9495 EXPORT_SYMBOL_GPL(ufshcd_remove);
9498 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
9499 * @hba: pointer to Host Bus Adapter (HBA)
9501 void ufshcd_dealloc_host(struct ufs_hba *hba)
9503 scsi_host_put(hba->host);
9505 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
9508 * ufshcd_set_dma_mask - Set dma mask based on the controller
9509 * addressing capability
9510 * @hba: per adapter instance
9512 * Returns 0 for success, non-zero for failure
9514 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
9516 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
9517 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
9520 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
9524 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
9525 * @dev: pointer to device handle
9526 * @hba_handle: driver private handle
9527 * Returns 0 on success, non-zero value on failure
9529 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
9531 struct Scsi_Host *host;
9532 struct ufs_hba *hba;
9537 "Invalid memory reference for dev is NULL\n");
9542 host = scsi_host_alloc(&ufshcd_driver_template,
9543 sizeof(struct ufs_hba));
9545 dev_err(dev, "scsi_host_alloc failed\n");
9549 host->nr_maps = HCTX_TYPE_POLL + 1;
9550 hba = shost_priv(host);
9553 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
9554 hba->nop_out_timeout = NOP_OUT_TIMEOUT;
9555 INIT_LIST_HEAD(&hba->clk_list_head);
9556 spin_lock_init(&hba->outstanding_lock);
9563 EXPORT_SYMBOL(ufshcd_alloc_host);
9565 /* This function exists because blk_mq_alloc_tag_set() requires this. */
9566 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx,
9567 const struct blk_mq_queue_data *qd)
9570 return BLK_STS_NOTSUPP;
9573 static const struct blk_mq_ops ufshcd_tmf_ops = {
9574 .queue_rq = ufshcd_queue_tmf,
9578 * ufshcd_init - Driver initialization routine
9579 * @hba: per-adapter instance
9580 * @mmio_base: base register address
9581 * @irq: Interrupt line of device
9582 * Returns 0 on success, non-zero value on failure
9584 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
9587 struct Scsi_Host *host = hba->host;
9588 struct device *dev = hba->dev;
9589 char eh_wq_name[sizeof("ufs_eh_wq_00")];
9592 * dev_set_drvdata() must be called before any callbacks are registered
9593 * that use dev_get_drvdata() (frequency scaling, clock scaling, hwmon,
9596 dev_set_drvdata(dev, hba);
9600 "Invalid memory reference for mmio_base is NULL\n");
9605 hba->mmio_base = mmio_base;
9607 hba->vps = &ufs_hba_vps;
9609 err = ufshcd_hba_init(hba);
9613 /* Read capabilities registers */
9614 err = ufshcd_hba_capabilities(hba);
9618 /* Get UFS version supported by the controller */
9619 hba->ufs_version = ufshcd_get_ufs_version(hba);
9621 /* Get Interrupt bit mask per version */
9622 hba->intr_mask = ufshcd_get_intr_mask(hba);
9624 err = ufshcd_set_dma_mask(hba);
9626 dev_err(hba->dev, "set dma mask failed\n");
9630 /* Allocate memory for host memory space */
9631 err = ufshcd_memory_alloc(hba);
9633 dev_err(hba->dev, "Memory allocation failed\n");
9638 ufshcd_host_memory_configure(hba);
9640 host->can_queue = hba->nutrs - UFSHCD_NUM_RESERVED;
9641 host->cmd_per_lun = hba->nutrs - UFSHCD_NUM_RESERVED;
9642 host->max_id = UFSHCD_MAX_ID;
9643 host->max_lun = UFS_MAX_LUNS;
9644 host->max_channel = UFSHCD_MAX_CHANNEL;
9645 host->unique_id = host->host_no;
9646 host->max_cmd_len = UFS_CDB_SIZE;
9648 hba->max_pwr_info.is_valid = false;
9650 /* Initialize work queues */
9651 snprintf(eh_wq_name, sizeof(eh_wq_name), "ufs_eh_wq_%d",
9652 hba->host->host_no);
9653 hba->eh_wq = create_singlethread_workqueue(eh_wq_name);
9655 dev_err(hba->dev, "%s: failed to create eh workqueue\n",
9660 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
9661 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
9663 sema_init(&hba->host_sem, 1);
9665 /* Initialize UIC command mutex */
9666 mutex_init(&hba->uic_cmd_mutex);
9668 /* Initialize mutex for device management commands */
9669 mutex_init(&hba->dev_cmd.lock);
9671 /* Initialize mutex for exception event control */
9672 mutex_init(&hba->ee_ctrl_mutex);
9674 init_rwsem(&hba->clk_scaling_lock);
9676 ufshcd_init_clk_gating(hba);
9678 ufshcd_init_clk_scaling(hba);
9681 * In order to avoid any spurious interrupt immediately after
9682 * registering UFS controller interrupt handler, clear any pending UFS
9683 * interrupt status and disable all the UFS interrupts.
9685 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
9686 REG_INTERRUPT_STATUS);
9687 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
9689 * Make sure that UFS interrupts are disabled and any pending interrupt
9690 * status is cleared before registering UFS interrupt handler.
9694 /* IRQ registration */
9695 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
9697 dev_err(hba->dev, "request irq failed\n");
9700 hba->is_irq_enabled = true;
9703 err = scsi_add_host(host, hba->dev);
9705 dev_err(hba->dev, "scsi_add_host failed\n");
9709 hba->tmf_tag_set = (struct blk_mq_tag_set) {
9711 .queue_depth = hba->nutmrs,
9712 .ops = &ufshcd_tmf_ops,
9713 .flags = BLK_MQ_F_NO_SCHED,
9715 err = blk_mq_alloc_tag_set(&hba->tmf_tag_set);
9717 goto out_remove_scsi_host;
9718 hba->tmf_queue = blk_mq_init_queue(&hba->tmf_tag_set);
9719 if (IS_ERR(hba->tmf_queue)) {
9720 err = PTR_ERR(hba->tmf_queue);
9721 goto free_tmf_tag_set;
9723 hba->tmf_rqs = devm_kcalloc(hba->dev, hba->nutmrs,
9724 sizeof(*hba->tmf_rqs), GFP_KERNEL);
9725 if (!hba->tmf_rqs) {
9727 goto free_tmf_queue;
9730 /* Reset the attached device */
9731 ufshcd_device_reset(hba);
9733 ufshcd_init_crypto(hba);
9735 /* Host controller enable */
9736 err = ufshcd_hba_enable(hba);
9738 dev_err(hba->dev, "Host controller enable failed\n");
9739 ufshcd_print_evt_hist(hba);
9740 ufshcd_print_host_state(hba);
9741 goto free_tmf_queue;
9745 * Set the default power management level for runtime and system PM.
9746 * Default power saving mode is to keep UFS link in Hibern8 state
9747 * and UFS device in sleep state.
9749 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9751 UIC_LINK_HIBERN8_STATE);
9752 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9754 UIC_LINK_HIBERN8_STATE);
9756 INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work,
9757 ufshcd_rpm_dev_flush_recheck_work);
9759 /* Set the default auto-hiberate idle timer value to 150 ms */
9760 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
9761 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
9762 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
9765 /* Hold auto suspend until async scan completes */
9766 pm_runtime_get_sync(dev);
9767 atomic_set(&hba->scsi_block_reqs_cnt, 0);
9769 * We are assuming that device wasn't put in sleep/power-down
9770 * state exclusively during the boot stage before kernel.
9771 * This assumption helps avoid doing link startup twice during
9772 * ufshcd_probe_hba().
9774 ufshcd_set_ufs_dev_active(hba);
9776 async_schedule(ufshcd_async_scan, hba);
9777 ufs_sysfs_add_nodes(hba->dev);
9779 device_enable_async_suspend(dev);
9783 blk_cleanup_queue(hba->tmf_queue);
9785 blk_mq_free_tag_set(&hba->tmf_tag_set);
9786 out_remove_scsi_host:
9787 scsi_remove_host(hba->host);
9789 hba->is_irq_enabled = false;
9790 ufshcd_hba_exit(hba);
9794 EXPORT_SYMBOL_GPL(ufshcd_init);
9796 void ufshcd_resume_complete(struct device *dev)
9798 struct ufs_hba *hba = dev_get_drvdata(dev);
9800 if (hba->complete_put) {
9801 ufshcd_rpm_put(hba);
9802 hba->complete_put = false;
9805 EXPORT_SYMBOL_GPL(ufshcd_resume_complete);
9807 static bool ufshcd_rpm_ok_for_spm(struct ufs_hba *hba)
9809 struct device *dev = &hba->sdev_ufs_device->sdev_gendev;
9810 enum ufs_dev_pwr_mode dev_pwr_mode;
9811 enum uic_link_state link_state;
9812 unsigned long flags;
9815 spin_lock_irqsave(&dev->power.lock, flags);
9816 dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl);
9817 link_state = ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl);
9818 res = pm_runtime_suspended(dev) &&
9819 hba->curr_dev_pwr_mode == dev_pwr_mode &&
9820 hba->uic_link_state == link_state &&
9821 !hba->dev_info.b_rpm_dev_flush_capable;
9822 spin_unlock_irqrestore(&dev->power.lock, flags);
9827 int __ufshcd_suspend_prepare(struct device *dev, bool rpm_ok_for_spm)
9829 struct ufs_hba *hba = dev_get_drvdata(dev);
9833 * SCSI assumes that runtime-pm and system-pm for scsi drivers
9834 * are same. And it doesn't wake up the device for system-suspend
9835 * if it's runtime suspended. But ufs doesn't follow that.
9836 * Refer ufshcd_resume_complete()
9838 if (hba->sdev_ufs_device) {
9839 /* Prevent runtime suspend */
9840 ufshcd_rpm_get_noresume(hba);
9842 * Check if already runtime suspended in same state as system
9845 if (!rpm_ok_for_spm || !ufshcd_rpm_ok_for_spm(hba)) {
9846 /* RPM state is not ok for SPM, so runtime resume */
9847 ret = ufshcd_rpm_resume(hba);
9848 if (ret < 0 && ret != -EACCES) {
9849 ufshcd_rpm_put(hba);
9853 hba->complete_put = true;
9857 EXPORT_SYMBOL_GPL(__ufshcd_suspend_prepare);
9859 int ufshcd_suspend_prepare(struct device *dev)
9861 return __ufshcd_suspend_prepare(dev, true);
9863 EXPORT_SYMBOL_GPL(ufshcd_suspend_prepare);
9865 #ifdef CONFIG_PM_SLEEP
9866 static int ufshcd_wl_poweroff(struct device *dev)
9868 struct scsi_device *sdev = to_scsi_device(dev);
9869 struct ufs_hba *hba = shost_priv(sdev->host);
9871 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
9876 static int ufshcd_wl_probe(struct device *dev)
9878 struct scsi_device *sdev = to_scsi_device(dev);
9880 if (!is_device_wlun(sdev))
9883 blk_pm_runtime_init(sdev->request_queue, dev);
9884 pm_runtime_set_autosuspend_delay(dev, 0);
9885 pm_runtime_allow(dev);
9890 static int ufshcd_wl_remove(struct device *dev)
9892 pm_runtime_forbid(dev);
9896 static const struct dev_pm_ops ufshcd_wl_pm_ops = {
9897 #ifdef CONFIG_PM_SLEEP
9898 .suspend = ufshcd_wl_suspend,
9899 .resume = ufshcd_wl_resume,
9900 .freeze = ufshcd_wl_suspend,
9901 .thaw = ufshcd_wl_resume,
9902 .poweroff = ufshcd_wl_poweroff,
9903 .restore = ufshcd_wl_resume,
9905 SET_RUNTIME_PM_OPS(ufshcd_wl_runtime_suspend, ufshcd_wl_runtime_resume, NULL)
9909 * ufs_dev_wlun_template - describes ufs device wlun
9910 * ufs-device wlun - used to send pm commands
9911 * All luns are consumers of ufs-device wlun.
9913 * Currently, no sd driver is present for wluns.
9914 * Hence the no specific pm operations are performed.
9915 * With ufs design, SSU should be sent to ufs-device wlun.
9916 * Hence register a scsi driver for ufs wluns only.
9918 static struct scsi_driver ufs_dev_wlun_template = {
9920 .name = "ufs_device_wlun",
9921 .owner = THIS_MODULE,
9922 .probe = ufshcd_wl_probe,
9923 .remove = ufshcd_wl_remove,
9924 .pm = &ufshcd_wl_pm_ops,
9925 .shutdown = ufshcd_wl_shutdown,
9929 static int __init ufshcd_core_init(void)
9933 /* Verify that there are no gaps in struct utp_transfer_cmd_desc. */
9934 static_assert(sizeof(struct utp_transfer_cmd_desc) ==
9935 2 * ALIGNED_UPIU_SIZE +
9936 SG_ALL * sizeof(struct ufshcd_sg_entry));
9940 ret = scsi_register_driver(&ufs_dev_wlun_template.gendrv);
9946 static void __exit ufshcd_core_exit(void)
9949 scsi_unregister_driver(&ufs_dev_wlun_template.gendrv);
9952 module_init(ufshcd_core_init);
9953 module_exit(ufshcd_core_exit);
9955 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
9956 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
9957 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
9958 MODULE_LICENSE("GPL");
9959 MODULE_VERSION(UFSHCD_DRIVER_VERSION);