1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Universal Flash Storage Host controller driver Core
4 * Copyright (C) 2011-2013 Samsung India Software Operations
5 * Copyright (c) 2013-2016, The Linux Foundation. All rights reserved.
8 * Santosh Yaraganavi <santosh.sy@samsung.com>
9 * Vinayak Holikatti <h.vinayak@samsung.com>
12 #include <linux/async.h>
13 #include <linux/devfreq.h>
14 #include <linux/nls.h>
16 #include <linux/bitfield.h>
17 #include <linux/blk-pm.h>
18 #include <linux/blkdev.h>
19 #include <linux/clk.h>
20 #include <linux/delay.h>
21 #include <linux/interrupt.h>
22 #include <linux/module.h>
23 #include <linux/regulator/consumer.h>
24 #include <linux/sched/clock.h>
25 #include <scsi/scsi_cmnd.h>
26 #include <scsi/scsi_dbg.h>
27 #include <scsi/scsi_driver.h>
28 #include <scsi/scsi_eh.h>
29 #include "ufshcd-priv.h"
30 #include <ufs/ufs_quirks.h>
31 #include <ufs/unipro.h>
32 #include "ufs-sysfs.h"
33 #include "ufs-debugfs.h"
34 #include "ufs-fault-injection.h"
36 #include "ufshcd-crypto.h"
38 #include <asm/unaligned.h>
40 #define CREATE_TRACE_POINTS
41 #include <trace/events/ufs.h>
43 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
46 /* UIC command timeout, unit: ms */
47 #define UIC_CMD_TIMEOUT 500
49 /* NOP OUT retries waiting for NOP IN response */
50 #define NOP_OUT_RETRIES 10
51 /* Timeout after 50 msecs if NOP OUT hangs without response */
52 #define NOP_OUT_TIMEOUT 50 /* msecs */
54 /* Query request retries */
55 #define QUERY_REQ_RETRIES 3
56 /* Query request timeout */
57 #define QUERY_REQ_TIMEOUT 1500 /* 1.5 seconds */
59 /* Task management command timeout */
60 #define TM_CMD_TIMEOUT 100 /* msecs */
62 /* maximum number of retries for a general UIC command */
63 #define UFS_UIC_COMMAND_RETRIES 3
65 /* maximum number of link-startup retries */
66 #define DME_LINKSTARTUP_RETRIES 3
68 /* maximum number of reset retries before giving up */
69 #define MAX_HOST_RESET_RETRIES 5
71 /* Maximum number of error handler retries before giving up */
72 #define MAX_ERR_HANDLER_RETRIES 5
74 /* Expose the flag value from utp_upiu_query.value */
75 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
77 /* Interrupt aggregation default timeout, unit: 40us */
78 #define INT_AGGR_DEF_TO 0x02
80 /* default delay of autosuspend: 2000 ms */
81 #define RPM_AUTOSUSPEND_DELAY_MS 2000
83 /* Default delay of RPM device flush delayed work */
84 #define RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS 5000
86 /* Default value of wait time before gating device ref clock */
87 #define UFSHCD_REF_CLK_GATING_WAIT_US 0xFF /* microsecs */
89 /* Polling time to wait for fDeviceInit */
90 #define FDEVICEINIT_COMPL_TIMEOUT 1500 /* millisecs */
92 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
96 _ret = ufshcd_enable_vreg(_dev, _vreg); \
98 _ret = ufshcd_disable_vreg(_dev, _vreg); \
102 #define ufshcd_hex_dump(prefix_str, buf, len) do { \
103 size_t __len = (len); \
104 print_hex_dump(KERN_ERR, prefix_str, \
105 __len > 4 ? DUMP_PREFIX_OFFSET : DUMP_PREFIX_NONE,\
106 16, 4, buf, __len, false); \
109 int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len,
115 if (offset % 4 != 0 || len % 4 != 0) /* keep readl happy */
118 regs = kzalloc(len, GFP_ATOMIC);
122 for (pos = 0; pos < len; pos += 4) {
124 pos >= REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER &&
125 pos <= REG_UIC_ERROR_CODE_DME)
127 regs[pos / 4] = ufshcd_readl(hba, offset + pos);
130 ufshcd_hex_dump(prefix, regs, len);
135 EXPORT_SYMBOL_GPL(ufshcd_dump_regs);
138 UFSHCD_MAX_CHANNEL = 0,
140 UFSHCD_NUM_RESERVED = 1,
141 UFSHCD_CMD_PER_LUN = 32 - UFSHCD_NUM_RESERVED,
142 UFSHCD_CAN_QUEUE = 32 - UFSHCD_NUM_RESERVED,
145 static const char *const ufshcd_state_name[] = {
146 [UFSHCD_STATE_RESET] = "reset",
147 [UFSHCD_STATE_OPERATIONAL] = "operational",
148 [UFSHCD_STATE_ERROR] = "error",
149 [UFSHCD_STATE_EH_SCHEDULED_FATAL] = "eh_fatal",
150 [UFSHCD_STATE_EH_SCHEDULED_NON_FATAL] = "eh_non_fatal",
153 /* UFSHCD error handling flags */
155 UFSHCD_EH_IN_PROGRESS = (1 << 0),
158 /* UFSHCD UIC layer error flags */
160 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
161 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
162 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
163 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
164 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
165 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
166 UFSHCD_UIC_PA_GENERIC_ERROR = (1 << 6), /* Generic PA error */
169 #define ufshcd_set_eh_in_progress(h) \
170 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
171 #define ufshcd_eh_in_progress(h) \
172 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
173 #define ufshcd_clear_eh_in_progress(h) \
174 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
176 const struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
177 [UFS_PM_LVL_0] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
178 [UFS_PM_LVL_1] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
179 [UFS_PM_LVL_2] = {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
180 [UFS_PM_LVL_3] = {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
181 [UFS_PM_LVL_4] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
182 [UFS_PM_LVL_5] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
184 * For DeepSleep, the link is first put in hibern8 and then off.
185 * Leaving the link in hibern8 is not supported.
187 [UFS_PM_LVL_6] = {UFS_DEEPSLEEP_PWR_MODE, UIC_LINK_OFF_STATE},
190 static inline enum ufs_dev_pwr_mode
191 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
193 return ufs_pm_lvl_states[lvl].dev_state;
196 static inline enum uic_link_state
197 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
199 return ufs_pm_lvl_states[lvl].link_state;
202 static inline enum ufs_pm_level
203 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
204 enum uic_link_state link_state)
206 enum ufs_pm_level lvl;
208 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
209 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
210 (ufs_pm_lvl_states[lvl].link_state == link_state))
214 /* if no match found, return the level 0 */
218 static const struct ufs_dev_quirk ufs_fixups[] = {
219 /* UFS cards deviations table */
220 { .wmanufacturerid = UFS_VENDOR_MICRON,
221 .model = UFS_ANY_MODEL,
222 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
223 UFS_DEVICE_QUIRK_SWAP_L2P_ENTRY_FOR_HPB_READ },
224 { .wmanufacturerid = UFS_VENDOR_SAMSUNG,
225 .model = UFS_ANY_MODEL,
226 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
227 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE |
228 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS },
229 { .wmanufacturerid = UFS_VENDOR_SKHYNIX,
230 .model = UFS_ANY_MODEL,
231 .quirk = UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME },
232 { .wmanufacturerid = UFS_VENDOR_SKHYNIX,
233 .model = "hB8aL1" /*H28U62301AMR*/,
234 .quirk = UFS_DEVICE_QUIRK_HOST_VS_DEBUGSAVECONFIGTIME },
235 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
236 .model = UFS_ANY_MODEL,
237 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM },
238 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
239 .model = "THGLF2G9C8KBADG",
240 .quirk = UFS_DEVICE_QUIRK_PA_TACTIVATE },
241 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
242 .model = "THGLF2G9D8KBADG",
243 .quirk = UFS_DEVICE_QUIRK_PA_TACTIVATE },
247 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba);
248 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
249 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
250 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
251 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
252 static void ufshcd_hba_exit(struct ufs_hba *hba);
253 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params);
254 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
255 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
256 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
257 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
258 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
259 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba);
260 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up);
261 static irqreturn_t ufshcd_intr(int irq, void *__hba);
262 static int ufshcd_change_power_mode(struct ufs_hba *hba,
263 struct ufs_pa_layer_attr *pwr_mode);
264 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on);
265 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on);
266 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
267 struct ufs_vreg *vreg);
268 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag);
269 static void ufshcd_wb_toggle_buf_flush_during_h8(struct ufs_hba *hba,
271 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba);
272 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba);
274 static inline void ufshcd_enable_irq(struct ufs_hba *hba)
276 if (!hba->is_irq_enabled) {
277 enable_irq(hba->irq);
278 hba->is_irq_enabled = true;
282 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
284 if (hba->is_irq_enabled) {
285 disable_irq(hba->irq);
286 hba->is_irq_enabled = false;
290 static void ufshcd_configure_wb(struct ufs_hba *hba)
292 if (!ufshcd_is_wb_allowed(hba))
295 ufshcd_wb_toggle(hba, true);
297 ufshcd_wb_toggle_buf_flush_during_h8(hba, true);
299 if (ufshcd_is_wb_buf_flush_allowed(hba))
300 ufshcd_wb_toggle_buf_flush(hba, true);
303 static void ufshcd_scsi_unblock_requests(struct ufs_hba *hba)
305 if (atomic_dec_and_test(&hba->scsi_block_reqs_cnt))
306 scsi_unblock_requests(hba->host);
309 static void ufshcd_scsi_block_requests(struct ufs_hba *hba)
311 if (atomic_inc_return(&hba->scsi_block_reqs_cnt) == 1)
312 scsi_block_requests(hba->host);
315 static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba, unsigned int tag,
316 enum ufs_trace_str_t str_t)
318 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
319 struct utp_upiu_header *header;
321 if (!trace_ufshcd_upiu_enabled())
324 if (str_t == UFS_CMD_SEND)
325 header = &rq->header;
327 header = &hba->lrb[tag].ucd_rsp_ptr->header;
329 trace_ufshcd_upiu(dev_name(hba->dev), str_t, header, &rq->sc.cdb,
333 static void ufshcd_add_query_upiu_trace(struct ufs_hba *hba,
334 enum ufs_trace_str_t str_t,
335 struct utp_upiu_req *rq_rsp)
337 if (!trace_ufshcd_upiu_enabled())
340 trace_ufshcd_upiu(dev_name(hba->dev), str_t, &rq_rsp->header,
341 &rq_rsp->qr, UFS_TSF_OSF);
344 static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag,
345 enum ufs_trace_str_t str_t)
347 struct utp_task_req_desc *descp = &hba->utmrdl_base_addr[tag];
349 if (!trace_ufshcd_upiu_enabled())
352 if (str_t == UFS_TM_SEND)
353 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
354 &descp->upiu_req.req_header,
355 &descp->upiu_req.input_param1,
358 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
359 &descp->upiu_rsp.rsp_header,
360 &descp->upiu_rsp.output_param1,
364 static void ufshcd_add_uic_command_trace(struct ufs_hba *hba,
365 const struct uic_command *ucmd,
366 enum ufs_trace_str_t str_t)
370 if (!trace_ufshcd_uic_command_enabled())
373 if (str_t == UFS_CMD_SEND)
376 cmd = ufshcd_readl(hba, REG_UIC_COMMAND);
378 trace_ufshcd_uic_command(dev_name(hba->dev), str_t, cmd,
379 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_1),
380 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2),
381 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3));
384 static void ufshcd_add_command_trace(struct ufs_hba *hba, unsigned int tag,
385 enum ufs_trace_str_t str_t)
388 u8 opcode = 0, group_id = 0;
390 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
391 struct scsi_cmnd *cmd = lrbp->cmd;
392 struct request *rq = scsi_cmd_to_rq(cmd);
393 int transfer_len = -1;
398 /* trace UPIU also */
399 ufshcd_add_cmd_upiu_trace(hba, tag, str_t);
400 if (!trace_ufshcd_command_enabled())
403 opcode = cmd->cmnd[0];
405 if (opcode == READ_10 || opcode == WRITE_10) {
407 * Currently we only fully trace read(10) and write(10) commands
410 be32_to_cpu(lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
411 lba = scsi_get_lba(cmd);
412 if (opcode == WRITE_10)
413 group_id = lrbp->cmd->cmnd[6];
414 } else if (opcode == UNMAP) {
416 * The number of Bytes to be unmapped beginning with the lba.
418 transfer_len = blk_rq_bytes(rq);
419 lba = scsi_get_lba(cmd);
422 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
423 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
424 trace_ufshcd_command(dev_name(hba->dev), str_t, tag,
425 doorbell, transfer_len, intr, lba, opcode, group_id);
428 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
430 struct ufs_clk_info *clki;
431 struct list_head *head = &hba->clk_list_head;
433 if (list_empty(head))
436 list_for_each_entry(clki, head, list) {
437 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
439 dev_err(hba->dev, "clk: %s, rate: %u\n",
440 clki->name, clki->curr_freq);
444 static void ufshcd_print_evt(struct ufs_hba *hba, u32 id,
445 const char *err_name)
449 const struct ufs_event_hist *e;
451 if (id >= UFS_EVT_CNT)
454 e = &hba->ufs_stats.event[id];
456 for (i = 0; i < UFS_EVENT_HIST_LENGTH; i++) {
457 int p = (i + e->pos) % UFS_EVENT_HIST_LENGTH;
459 if (e->tstamp[p] == 0)
461 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, p,
462 e->val[p], div_u64(e->tstamp[p], 1000));
467 dev_err(hba->dev, "No record of %s\n", err_name);
469 dev_err(hba->dev, "%s: total cnt=%llu\n", err_name, e->cnt);
472 static void ufshcd_print_evt_hist(struct ufs_hba *hba)
474 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
476 ufshcd_print_evt(hba, UFS_EVT_PA_ERR, "pa_err");
477 ufshcd_print_evt(hba, UFS_EVT_DL_ERR, "dl_err");
478 ufshcd_print_evt(hba, UFS_EVT_NL_ERR, "nl_err");
479 ufshcd_print_evt(hba, UFS_EVT_TL_ERR, "tl_err");
480 ufshcd_print_evt(hba, UFS_EVT_DME_ERR, "dme_err");
481 ufshcd_print_evt(hba, UFS_EVT_AUTO_HIBERN8_ERR,
483 ufshcd_print_evt(hba, UFS_EVT_FATAL_ERR, "fatal_err");
484 ufshcd_print_evt(hba, UFS_EVT_LINK_STARTUP_FAIL,
485 "link_startup_fail");
486 ufshcd_print_evt(hba, UFS_EVT_RESUME_ERR, "resume_fail");
487 ufshcd_print_evt(hba, UFS_EVT_SUSPEND_ERR,
489 ufshcd_print_evt(hba, UFS_EVT_WL_RES_ERR, "wlun resume_fail");
490 ufshcd_print_evt(hba, UFS_EVT_WL_SUSP_ERR,
491 "wlun suspend_fail");
492 ufshcd_print_evt(hba, UFS_EVT_DEV_RESET, "dev_reset");
493 ufshcd_print_evt(hba, UFS_EVT_HOST_RESET, "host_reset");
494 ufshcd_print_evt(hba, UFS_EVT_ABORT, "task_abort");
496 ufshcd_vops_dbg_register_dump(hba);
500 void ufshcd_print_trs(struct ufs_hba *hba, unsigned long bitmap, bool pr_prdt)
502 const struct ufshcd_lrb *lrbp;
506 for_each_set_bit(tag, &bitmap, hba->nutrs) {
507 lrbp = &hba->lrb[tag];
509 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
510 tag, div_u64(lrbp->issue_time_stamp_local_clock, 1000));
511 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n",
512 tag, div_u64(lrbp->compl_time_stamp_local_clock, 1000));
514 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
515 tag, (u64)lrbp->utrd_dma_addr);
517 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
518 sizeof(struct utp_transfer_req_desc));
519 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
520 (u64)lrbp->ucd_req_dma_addr);
521 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
522 sizeof(struct utp_upiu_req));
523 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
524 (u64)lrbp->ucd_rsp_dma_addr);
525 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
526 sizeof(struct utp_upiu_rsp));
528 prdt_length = le16_to_cpu(
529 lrbp->utr_descriptor_ptr->prd_table_length);
530 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
531 prdt_length /= sizeof(struct ufshcd_sg_entry);
534 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
536 (u64)lrbp->ucd_prdt_dma_addr);
539 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
540 sizeof(struct ufshcd_sg_entry) * prdt_length);
544 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
548 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
549 struct utp_task_req_desc *tmrdp = &hba->utmrdl_base_addr[tag];
551 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
552 ufshcd_hex_dump("", tmrdp, sizeof(*tmrdp));
556 static void ufshcd_print_host_state(struct ufs_hba *hba)
558 const struct scsi_device *sdev_ufs = hba->ufs_device_wlun;
560 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
561 dev_err(hba->dev, "outstanding reqs=0x%lx tasks=0x%lx\n",
562 hba->outstanding_reqs, hba->outstanding_tasks);
563 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
564 hba->saved_err, hba->saved_uic_err);
565 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
566 hba->curr_dev_pwr_mode, hba->uic_link_state);
567 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
568 hba->pm_op_in_progress, hba->is_sys_suspended);
569 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
570 hba->auto_bkops_enabled, hba->host->host_self_blocked);
571 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
573 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt=%d\n",
574 div_u64(hba->ufs_stats.last_hibern8_exit_tstamp, 1000),
575 hba->ufs_stats.hibern8_exit_cnt);
576 dev_err(hba->dev, "last intr at %lld us, last intr status=0x%x\n",
577 div_u64(hba->ufs_stats.last_intr_ts, 1000),
578 hba->ufs_stats.last_intr_status);
579 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
580 hba->eh_flags, hba->req_abort_count);
581 dev_err(hba->dev, "hba->ufs_version=0x%x, Host capabilities=0x%x, caps=0x%x\n",
582 hba->ufs_version, hba->capabilities, hba->caps);
583 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
586 dev_err(hba->dev, "UFS dev info: %.8s %.16s rev %.4s\n",
587 sdev_ufs->vendor, sdev_ufs->model, sdev_ufs->rev);
589 ufshcd_print_clk_freqs(hba);
593 * ufshcd_print_pwr_info - print power params as saved in hba
595 * @hba: per-adapter instance
597 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
599 static const char * const names[] = {
610 * Using dev_dbg to avoid messages during runtime PM to avoid
611 * never-ending cycles of messages written back to storage by user space
612 * causing runtime resume, causing more messages and so on.
614 dev_dbg(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
616 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
617 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
618 names[hba->pwr_info.pwr_rx],
619 names[hba->pwr_info.pwr_tx],
620 hba->pwr_info.hs_rate);
623 static void ufshcd_device_reset(struct ufs_hba *hba)
627 err = ufshcd_vops_device_reset(hba);
630 ufshcd_set_ufs_dev_active(hba);
631 if (ufshcd_is_wb_allowed(hba)) {
632 hba->dev_info.wb_enabled = false;
633 hba->dev_info.wb_buf_flush_enabled = false;
636 if (err != -EOPNOTSUPP)
637 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, err);
640 void ufshcd_delay_us(unsigned long us, unsigned long tolerance)
648 usleep_range(us, us + tolerance);
650 EXPORT_SYMBOL_GPL(ufshcd_delay_us);
653 * ufshcd_wait_for_register - wait for register value to change
654 * @hba: per-adapter interface
655 * @reg: mmio register offset
656 * @mask: mask to apply to the read register value
657 * @val: value to wait for
658 * @interval_us: polling interval in microseconds
659 * @timeout_ms: timeout in milliseconds
662 * -ETIMEDOUT on error, zero on success.
664 static int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
665 u32 val, unsigned long interval_us,
666 unsigned long timeout_ms)
669 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
671 /* ignore bits that we don't intend to wait on */
674 while ((ufshcd_readl(hba, reg) & mask) != val) {
675 usleep_range(interval_us, interval_us + 50);
676 if (time_after(jiffies, timeout)) {
677 if ((ufshcd_readl(hba, reg) & mask) != val)
687 * ufshcd_get_intr_mask - Get the interrupt bit mask
688 * @hba: Pointer to adapter instance
690 * Returns interrupt bit mask per version
692 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
694 if (hba->ufs_version == ufshci_version(1, 0))
695 return INTERRUPT_MASK_ALL_VER_10;
696 if (hba->ufs_version <= ufshci_version(2, 0))
697 return INTERRUPT_MASK_ALL_VER_11;
699 return INTERRUPT_MASK_ALL_VER_21;
703 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
704 * @hba: Pointer to adapter instance
706 * Returns UFSHCI version supported by the controller
708 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
712 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
713 ufshci_ver = ufshcd_vops_get_ufs_hci_version(hba);
715 ufshci_ver = ufshcd_readl(hba, REG_UFS_VERSION);
718 * UFSHCI v1.x uses a different version scheme, in order
719 * to allow the use of comparisons with the ufshci_version
720 * function, we convert it to the same scheme as ufs 2.0+.
722 if (ufshci_ver & 0x00010000)
723 return ufshci_version(1, ufshci_ver & 0x00000100);
729 * ufshcd_is_device_present - Check if any device connected to
730 * the host controller
731 * @hba: pointer to adapter instance
733 * Returns true if device present, false if no device detected
735 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
737 return ufshcd_readl(hba, REG_CONTROLLER_STATUS) & DEVICE_PRESENT;
741 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
742 * @lrbp: pointer to local command reference block
744 * This function is used to get the OCS field from UTRD
745 * Returns the OCS field in the UTRD
747 static enum utp_ocs ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
749 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
753 * ufshcd_utrl_clear() - Clear requests from the controller request list.
754 * @hba: per adapter instance
755 * @mask: mask with one bit set for each request to be cleared
757 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 mask)
759 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
762 * From the UFSHCI specification: "UTP Transfer Request List CLear
763 * Register (UTRLCLR): This field is bit significant. Each bit
764 * corresponds to a slot in the UTP Transfer Request List, where bit 0
765 * corresponds to request slot 0. A bit in this field is set to ‘0’
766 * by host software to indicate to the host controller that a transfer
767 * request slot is cleared. The host controller
768 * shall free up any resources associated to the request slot
769 * immediately, and shall set the associated bit in UTRLDBR to ‘0’. The
770 * host software indicates no change to request slots by setting the
771 * associated bits in this field to ‘1’. Bits in this field shall only
772 * be set ‘1’ or ‘0’ by host software when UTRLRSR is set to ‘1’."
774 ufshcd_writel(hba, ~mask, REG_UTP_TRANSFER_REQ_LIST_CLEAR);
778 * ufshcd_utmrl_clear - Clear a bit in UTMRLCLR register
779 * @hba: per adapter instance
780 * @pos: position of the bit to be cleared
782 static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos)
784 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
785 ufshcd_writel(hba, (1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
787 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
791 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
792 * @reg: Register value of host controller status
794 * Returns integer, 0 on Success and positive value if failed
796 static inline int ufshcd_get_lists_status(u32 reg)
798 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
802 * ufshcd_get_uic_cmd_result - Get the UIC command result
803 * @hba: Pointer to adapter instance
805 * This function gets the result of UIC command completion
806 * Returns 0 on success, non zero value on error
808 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
810 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
811 MASK_UIC_COMMAND_RESULT;
815 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
816 * @hba: Pointer to adapter instance
818 * This function gets UIC command argument3
819 * Returns 0 on success, non zero value on error
821 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
823 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
827 * ufshcd_get_req_rsp - returns the TR response transaction type
828 * @ucd_rsp_ptr: pointer to response UPIU
831 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
833 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
837 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
838 * @ucd_rsp_ptr: pointer to response UPIU
840 * This function gets the response status and scsi_status from response UPIU
841 * Returns the response result code.
844 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
846 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
850 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
852 * @ucd_rsp_ptr: pointer to response UPIU
854 * Return the data segment length.
856 static inline unsigned int
857 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
859 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
860 MASK_RSP_UPIU_DATA_SEG_LEN;
864 * ufshcd_is_exception_event - Check if the device raised an exception event
865 * @ucd_rsp_ptr: pointer to response UPIU
867 * The function checks if the device raised an exception event indicated in
868 * the Device Information field of response UPIU.
870 * Returns true if exception is raised, false otherwise.
872 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
874 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
875 MASK_RSP_EXCEPTION_EVENT;
879 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
880 * @hba: per adapter instance
883 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
885 ufshcd_writel(hba, INT_AGGR_ENABLE |
886 INT_AGGR_COUNTER_AND_TIMER_RESET,
887 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
891 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
892 * @hba: per adapter instance
893 * @cnt: Interrupt aggregation counter threshold
894 * @tmout: Interrupt aggregation timeout value
897 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
899 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
900 INT_AGGR_COUNTER_THLD_VAL(cnt) |
901 INT_AGGR_TIMEOUT_VAL(tmout),
902 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
906 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
907 * @hba: per adapter instance
909 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
911 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
915 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
916 * When run-stop registers are set to 1, it indicates the
917 * host controller that it can process the requests
918 * @hba: per adapter instance
920 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
922 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
923 REG_UTP_TASK_REQ_LIST_RUN_STOP);
924 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
925 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
929 * ufshcd_hba_start - Start controller initialization sequence
930 * @hba: per adapter instance
932 static inline void ufshcd_hba_start(struct ufs_hba *hba)
934 u32 val = CONTROLLER_ENABLE;
936 if (ufshcd_crypto_enable(hba))
937 val |= CRYPTO_GENERAL_ENABLE;
939 ufshcd_writel(hba, val, REG_CONTROLLER_ENABLE);
943 * ufshcd_is_hba_active - Get controller state
944 * @hba: per adapter instance
946 * Returns true if and only if the controller is active.
948 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
950 return ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE;
953 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
955 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
956 if (hba->ufs_version <= ufshci_version(1, 1))
957 return UFS_UNIPRO_VER_1_41;
959 return UFS_UNIPRO_VER_1_6;
961 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
963 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
966 * If both host and device support UniPro ver1.6 or later, PA layer
967 * parameters tuning happens during link startup itself.
969 * We can manually tune PA layer parameters if either host or device
970 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
971 * logic simple, we will only do manual tuning if local unipro version
972 * doesn't support ver1.6 or later.
974 return ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6;
978 * ufshcd_set_clk_freq - set UFS controller clock frequencies
979 * @hba: per adapter instance
980 * @scale_up: If True, set max possible frequency othewise set low frequency
982 * Returns 0 if successful
983 * Returns < 0 for any other errors
985 static int ufshcd_set_clk_freq(struct ufs_hba *hba, bool scale_up)
988 struct ufs_clk_info *clki;
989 struct list_head *head = &hba->clk_list_head;
991 if (list_empty(head))
994 list_for_each_entry(clki, head, list) {
995 if (!IS_ERR_OR_NULL(clki->clk)) {
996 if (scale_up && clki->max_freq) {
997 if (clki->curr_freq == clki->max_freq)
1000 ret = clk_set_rate(clki->clk, clki->max_freq);
1002 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
1003 __func__, clki->name,
1004 clki->max_freq, ret);
1007 trace_ufshcd_clk_scaling(dev_name(hba->dev),
1008 "scaled up", clki->name,
1012 clki->curr_freq = clki->max_freq;
1014 } else if (!scale_up && clki->min_freq) {
1015 if (clki->curr_freq == clki->min_freq)
1018 ret = clk_set_rate(clki->clk, clki->min_freq);
1020 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
1021 __func__, clki->name,
1022 clki->min_freq, ret);
1025 trace_ufshcd_clk_scaling(dev_name(hba->dev),
1026 "scaled down", clki->name,
1029 clki->curr_freq = clki->min_freq;
1032 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
1033 clki->name, clk_get_rate(clki->clk));
1041 * ufshcd_scale_clks - scale up or scale down UFS controller clocks
1042 * @hba: per adapter instance
1043 * @scale_up: True if scaling up and false if scaling down
1045 * Returns 0 if successful
1046 * Returns < 0 for any other errors
1048 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
1051 ktime_t start = ktime_get();
1053 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
1057 ret = ufshcd_set_clk_freq(hba, scale_up);
1061 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1063 ufshcd_set_clk_freq(hba, !scale_up);
1066 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1067 (scale_up ? "up" : "down"),
1068 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1073 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
1074 * @hba: per adapter instance
1075 * @scale_up: True if scaling up and false if scaling down
1077 * Returns true if scaling is required, false otherwise.
1079 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
1082 struct ufs_clk_info *clki;
1083 struct list_head *head = &hba->clk_list_head;
1085 if (list_empty(head))
1088 list_for_each_entry(clki, head, list) {
1089 if (!IS_ERR_OR_NULL(clki->clk)) {
1090 if (scale_up && clki->max_freq) {
1091 if (clki->curr_freq == clki->max_freq)
1094 } else if (!scale_up && clki->min_freq) {
1095 if (clki->curr_freq == clki->min_freq)
1106 * Determine the number of pending commands by counting the bits in the SCSI
1107 * device budget maps. This approach has been selected because a bit is set in
1108 * the budget map before scsi_host_queue_ready() checks the host_self_blocked
1109 * flag. The host_self_blocked flag can be modified by calling
1110 * scsi_block_requests() or scsi_unblock_requests().
1112 static u32 ufshcd_pending_cmds(struct ufs_hba *hba)
1114 const struct scsi_device *sdev;
1117 lockdep_assert_held(hba->host->host_lock);
1118 __shost_for_each_device(sdev, hba->host)
1119 pending += sbitmap_weight(&sdev->budget_map);
1124 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
1125 u64 wait_timeout_us)
1127 unsigned long flags;
1131 bool timeout = false, do_last_check = false;
1134 ufshcd_hold(hba, false);
1135 spin_lock_irqsave(hba->host->host_lock, flags);
1137 * Wait for all the outstanding tasks/transfer requests.
1138 * Verify by checking the doorbell registers are clear.
1140 start = ktime_get();
1142 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
1147 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1148 tr_pending = ufshcd_pending_cmds(hba);
1149 if (!tm_doorbell && !tr_pending) {
1152 } else if (do_last_check) {
1156 spin_unlock_irqrestore(hba->host->host_lock, flags);
1158 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1162 * We might have scheduled out for long time so make
1163 * sure to check if doorbells are cleared by this time
1166 do_last_check = true;
1168 spin_lock_irqsave(hba->host->host_lock, flags);
1169 } while (tm_doorbell || tr_pending);
1173 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1174 __func__, tm_doorbell, tr_pending);
1178 spin_unlock_irqrestore(hba->host->host_lock, flags);
1179 ufshcd_release(hba);
1184 * ufshcd_scale_gear - scale up/down UFS gear
1185 * @hba: per adapter instance
1186 * @scale_up: True for scaling up gear and false for scaling down
1188 * Returns 0 for success,
1189 * Returns -EBUSY if scaling can't happen at this time
1190 * Returns non-zero for any other errors
1192 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1195 struct ufs_pa_layer_attr new_pwr_info;
1198 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info.info,
1199 sizeof(struct ufs_pa_layer_attr));
1201 memcpy(&new_pwr_info, &hba->pwr_info,
1202 sizeof(struct ufs_pa_layer_attr));
1204 if (hba->pwr_info.gear_tx > hba->clk_scaling.min_gear ||
1205 hba->pwr_info.gear_rx > hba->clk_scaling.min_gear) {
1206 /* save the current power mode */
1207 memcpy(&hba->clk_scaling.saved_pwr_info.info,
1209 sizeof(struct ufs_pa_layer_attr));
1211 /* scale down gear */
1212 new_pwr_info.gear_tx = hba->clk_scaling.min_gear;
1213 new_pwr_info.gear_rx = hba->clk_scaling.min_gear;
1217 /* check if the power mode needs to be changed or not? */
1218 ret = ufshcd_config_pwr_mode(hba, &new_pwr_info);
1220 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1222 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1223 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1228 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba)
1230 #define DOORBELL_CLR_TOUT_US (1000 * 1000) /* 1 sec */
1233 * make sure that there are no outstanding requests when
1234 * clock scaling is in progress
1236 ufshcd_scsi_block_requests(hba);
1237 mutex_lock(&hba->wb_mutex);
1238 down_write(&hba->clk_scaling_lock);
1240 if (!hba->clk_scaling.is_allowed ||
1241 ufshcd_wait_for_doorbell_clr(hba, DOORBELL_CLR_TOUT_US)) {
1243 up_write(&hba->clk_scaling_lock);
1244 mutex_unlock(&hba->wb_mutex);
1245 ufshcd_scsi_unblock_requests(hba);
1249 /* let's not get into low power until clock scaling is completed */
1250 ufshcd_hold(hba, false);
1256 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba, int err, bool scale_up)
1258 up_write(&hba->clk_scaling_lock);
1260 /* Enable Write Booster if we have scaled up else disable it */
1261 if (ufshcd_enable_wb_if_scaling_up(hba) && !err)
1262 ufshcd_wb_toggle(hba, scale_up);
1264 mutex_unlock(&hba->wb_mutex);
1266 ufshcd_scsi_unblock_requests(hba);
1267 ufshcd_release(hba);
1271 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1272 * @hba: per adapter instance
1273 * @scale_up: True for scaling up and false for scalin down
1275 * Returns 0 for success,
1276 * Returns -EBUSY if scaling can't happen at this time
1277 * Returns non-zero for any other errors
1279 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1283 ret = ufshcd_clock_scaling_prepare(hba);
1287 /* scale down the gear before scaling down clocks */
1289 ret = ufshcd_scale_gear(hba, false);
1294 ret = ufshcd_scale_clks(hba, scale_up);
1297 ufshcd_scale_gear(hba, true);
1301 /* scale up the gear after scaling up clocks */
1303 ret = ufshcd_scale_gear(hba, true);
1305 ufshcd_scale_clks(hba, false);
1311 ufshcd_clock_scaling_unprepare(hba, ret, scale_up);
1315 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1317 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1318 clk_scaling.suspend_work);
1319 unsigned long irq_flags;
1321 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1322 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1323 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1326 hba->clk_scaling.is_suspended = true;
1327 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1329 __ufshcd_suspend_clkscaling(hba);
1332 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1334 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1335 clk_scaling.resume_work);
1336 unsigned long irq_flags;
1338 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1339 if (!hba->clk_scaling.is_suspended) {
1340 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1343 hba->clk_scaling.is_suspended = false;
1344 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1346 devfreq_resume_device(hba->devfreq);
1349 static int ufshcd_devfreq_target(struct device *dev,
1350 unsigned long *freq, u32 flags)
1353 struct ufs_hba *hba = dev_get_drvdata(dev);
1355 bool scale_up, sched_clk_scaling_suspend_work = false;
1356 struct list_head *clk_list = &hba->clk_list_head;
1357 struct ufs_clk_info *clki;
1358 unsigned long irq_flags;
1360 if (!ufshcd_is_clkscaling_supported(hba))
1363 clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info, list);
1364 /* Override with the closest supported frequency */
1365 *freq = (unsigned long) clk_round_rate(clki->clk, *freq);
1366 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1367 if (ufshcd_eh_in_progress(hba)) {
1368 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1372 if (!hba->clk_scaling.active_reqs)
1373 sched_clk_scaling_suspend_work = true;
1375 if (list_empty(clk_list)) {
1376 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1380 /* Decide based on the rounded-off frequency and update */
1381 scale_up = *freq == clki->max_freq;
1383 *freq = clki->min_freq;
1384 /* Update the frequency */
1385 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1386 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1388 goto out; /* no state change required */
1390 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1392 start = ktime_get();
1393 ret = ufshcd_devfreq_scale(hba, scale_up);
1395 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1396 (scale_up ? "up" : "down"),
1397 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1400 if (sched_clk_scaling_suspend_work)
1401 queue_work(hba->clk_scaling.workq,
1402 &hba->clk_scaling.suspend_work);
1407 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1408 struct devfreq_dev_status *stat)
1410 struct ufs_hba *hba = dev_get_drvdata(dev);
1411 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1412 unsigned long flags;
1413 struct list_head *clk_list = &hba->clk_list_head;
1414 struct ufs_clk_info *clki;
1417 if (!ufshcd_is_clkscaling_supported(hba))
1420 memset(stat, 0, sizeof(*stat));
1422 spin_lock_irqsave(hba->host->host_lock, flags);
1423 curr_t = ktime_get();
1424 if (!scaling->window_start_t)
1427 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1429 * If current frequency is 0, then the ondemand governor considers
1430 * there's no initial frequency set. And it always requests to set
1431 * to max. frequency.
1433 stat->current_frequency = clki->curr_freq;
1434 if (scaling->is_busy_started)
1435 scaling->tot_busy_t += ktime_us_delta(curr_t,
1436 scaling->busy_start_t);
1438 stat->total_time = ktime_us_delta(curr_t, scaling->window_start_t);
1439 stat->busy_time = scaling->tot_busy_t;
1441 scaling->window_start_t = curr_t;
1442 scaling->tot_busy_t = 0;
1444 if (hba->outstanding_reqs) {
1445 scaling->busy_start_t = curr_t;
1446 scaling->is_busy_started = true;
1448 scaling->busy_start_t = 0;
1449 scaling->is_busy_started = false;
1451 spin_unlock_irqrestore(hba->host->host_lock, flags);
1455 static int ufshcd_devfreq_init(struct ufs_hba *hba)
1457 struct list_head *clk_list = &hba->clk_list_head;
1458 struct ufs_clk_info *clki;
1459 struct devfreq *devfreq;
1462 /* Skip devfreq if we don't have any clocks in the list */
1463 if (list_empty(clk_list))
1466 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1467 dev_pm_opp_add(hba->dev, clki->min_freq, 0);
1468 dev_pm_opp_add(hba->dev, clki->max_freq, 0);
1470 ufshcd_vops_config_scaling_param(hba, &hba->vps->devfreq_profile,
1471 &hba->vps->ondemand_data);
1472 devfreq = devfreq_add_device(hba->dev,
1473 &hba->vps->devfreq_profile,
1474 DEVFREQ_GOV_SIMPLE_ONDEMAND,
1475 &hba->vps->ondemand_data);
1476 if (IS_ERR(devfreq)) {
1477 ret = PTR_ERR(devfreq);
1478 dev_err(hba->dev, "Unable to register with devfreq %d\n", ret);
1480 dev_pm_opp_remove(hba->dev, clki->min_freq);
1481 dev_pm_opp_remove(hba->dev, clki->max_freq);
1485 hba->devfreq = devfreq;
1490 static void ufshcd_devfreq_remove(struct ufs_hba *hba)
1492 struct list_head *clk_list = &hba->clk_list_head;
1493 struct ufs_clk_info *clki;
1498 devfreq_remove_device(hba->devfreq);
1499 hba->devfreq = NULL;
1501 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1502 dev_pm_opp_remove(hba->dev, clki->min_freq);
1503 dev_pm_opp_remove(hba->dev, clki->max_freq);
1506 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1508 unsigned long flags;
1510 devfreq_suspend_device(hba->devfreq);
1511 spin_lock_irqsave(hba->host->host_lock, flags);
1512 hba->clk_scaling.window_start_t = 0;
1513 spin_unlock_irqrestore(hba->host->host_lock, flags);
1516 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1518 unsigned long flags;
1519 bool suspend = false;
1521 cancel_work_sync(&hba->clk_scaling.suspend_work);
1522 cancel_work_sync(&hba->clk_scaling.resume_work);
1524 spin_lock_irqsave(hba->host->host_lock, flags);
1525 if (!hba->clk_scaling.is_suspended) {
1527 hba->clk_scaling.is_suspended = true;
1529 spin_unlock_irqrestore(hba->host->host_lock, flags);
1532 __ufshcd_suspend_clkscaling(hba);
1535 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1537 unsigned long flags;
1538 bool resume = false;
1540 spin_lock_irqsave(hba->host->host_lock, flags);
1541 if (hba->clk_scaling.is_suspended) {
1543 hba->clk_scaling.is_suspended = false;
1545 spin_unlock_irqrestore(hba->host->host_lock, flags);
1548 devfreq_resume_device(hba->devfreq);
1551 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1552 struct device_attribute *attr, char *buf)
1554 struct ufs_hba *hba = dev_get_drvdata(dev);
1556 return sysfs_emit(buf, "%d\n", hba->clk_scaling.is_enabled);
1559 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1560 struct device_attribute *attr, const char *buf, size_t count)
1562 struct ufs_hba *hba = dev_get_drvdata(dev);
1566 if (kstrtou32(buf, 0, &value))
1569 down(&hba->host_sem);
1570 if (!ufshcd_is_user_access_allowed(hba)) {
1576 if (value == hba->clk_scaling.is_enabled)
1579 ufshcd_rpm_get_sync(hba);
1580 ufshcd_hold(hba, false);
1582 hba->clk_scaling.is_enabled = value;
1585 ufshcd_resume_clkscaling(hba);
1587 ufshcd_suspend_clkscaling(hba);
1588 err = ufshcd_devfreq_scale(hba, true);
1590 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1594 ufshcd_release(hba);
1595 ufshcd_rpm_put_sync(hba);
1598 return err ? err : count;
1601 static void ufshcd_init_clk_scaling_sysfs(struct ufs_hba *hba)
1603 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1604 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1605 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1606 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1607 hba->clk_scaling.enable_attr.attr.mode = 0644;
1608 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1609 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1612 static void ufshcd_remove_clk_scaling_sysfs(struct ufs_hba *hba)
1614 if (hba->clk_scaling.enable_attr.attr.name)
1615 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
1618 static void ufshcd_init_clk_scaling(struct ufs_hba *hba)
1620 char wq_name[sizeof("ufs_clkscaling_00")];
1622 if (!ufshcd_is_clkscaling_supported(hba))
1625 if (!hba->clk_scaling.min_gear)
1626 hba->clk_scaling.min_gear = UFS_HS_G1;
1628 INIT_WORK(&hba->clk_scaling.suspend_work,
1629 ufshcd_clk_scaling_suspend_work);
1630 INIT_WORK(&hba->clk_scaling.resume_work,
1631 ufshcd_clk_scaling_resume_work);
1633 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
1634 hba->host->host_no);
1635 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
1637 hba->clk_scaling.is_initialized = true;
1640 static void ufshcd_exit_clk_scaling(struct ufs_hba *hba)
1642 if (!hba->clk_scaling.is_initialized)
1645 ufshcd_remove_clk_scaling_sysfs(hba);
1646 destroy_workqueue(hba->clk_scaling.workq);
1647 ufshcd_devfreq_remove(hba);
1648 hba->clk_scaling.is_initialized = false;
1651 static void ufshcd_ungate_work(struct work_struct *work)
1654 unsigned long flags;
1655 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1656 clk_gating.ungate_work);
1658 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1660 spin_lock_irqsave(hba->host->host_lock, flags);
1661 if (hba->clk_gating.state == CLKS_ON) {
1662 spin_unlock_irqrestore(hba->host->host_lock, flags);
1666 spin_unlock_irqrestore(hba->host->host_lock, flags);
1667 ufshcd_hba_vreg_set_hpm(hba);
1668 ufshcd_setup_clocks(hba, true);
1670 ufshcd_enable_irq(hba);
1672 /* Exit from hibern8 */
1673 if (ufshcd_can_hibern8_during_gating(hba)) {
1674 /* Prevent gating in this path */
1675 hba->clk_gating.is_suspended = true;
1676 if (ufshcd_is_link_hibern8(hba)) {
1677 ret = ufshcd_uic_hibern8_exit(hba);
1679 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1682 ufshcd_set_link_active(hba);
1684 hba->clk_gating.is_suspended = false;
1687 ufshcd_scsi_unblock_requests(hba);
1691 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1692 * Also, exit from hibern8 mode and set the link as active.
1693 * @hba: per adapter instance
1694 * @async: This indicates whether caller should ungate clocks asynchronously.
1696 int ufshcd_hold(struct ufs_hba *hba, bool async)
1700 unsigned long flags;
1702 if (!ufshcd_is_clkgating_allowed(hba) ||
1703 !hba->clk_gating.is_initialized)
1705 spin_lock_irqsave(hba->host->host_lock, flags);
1706 hba->clk_gating.active_reqs++;
1709 switch (hba->clk_gating.state) {
1712 * Wait for the ungate work to complete if in progress.
1713 * Though the clocks may be in ON state, the link could
1714 * still be in hibner8 state if hibern8 is allowed
1715 * during clock gating.
1716 * Make sure we exit hibern8 state also in addition to
1719 if (ufshcd_can_hibern8_during_gating(hba) &&
1720 ufshcd_is_link_hibern8(hba)) {
1723 hba->clk_gating.active_reqs--;
1726 spin_unlock_irqrestore(hba->host->host_lock, flags);
1727 flush_result = flush_work(&hba->clk_gating.ungate_work);
1728 if (hba->clk_gating.is_suspended && !flush_result)
1730 spin_lock_irqsave(hba->host->host_lock, flags);
1735 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1736 hba->clk_gating.state = CLKS_ON;
1737 trace_ufshcd_clk_gating(dev_name(hba->dev),
1738 hba->clk_gating.state);
1742 * If we are here, it means gating work is either done or
1743 * currently running. Hence, fall through to cancel gating
1744 * work and to enable clocks.
1748 hba->clk_gating.state = REQ_CLKS_ON;
1749 trace_ufshcd_clk_gating(dev_name(hba->dev),
1750 hba->clk_gating.state);
1751 if (queue_work(hba->clk_gating.clk_gating_workq,
1752 &hba->clk_gating.ungate_work))
1753 ufshcd_scsi_block_requests(hba);
1755 * fall through to check if we should wait for this
1756 * work to be done or not.
1762 hba->clk_gating.active_reqs--;
1766 spin_unlock_irqrestore(hba->host->host_lock, flags);
1767 flush_work(&hba->clk_gating.ungate_work);
1768 /* Make sure state is CLKS_ON before returning */
1769 spin_lock_irqsave(hba->host->host_lock, flags);
1772 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1773 __func__, hba->clk_gating.state);
1776 spin_unlock_irqrestore(hba->host->host_lock, flags);
1780 EXPORT_SYMBOL_GPL(ufshcd_hold);
1782 static void ufshcd_gate_work(struct work_struct *work)
1784 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1785 clk_gating.gate_work.work);
1786 unsigned long flags;
1789 spin_lock_irqsave(hba->host->host_lock, flags);
1791 * In case you are here to cancel this work the gating state
1792 * would be marked as REQ_CLKS_ON. In this case save time by
1793 * skipping the gating work and exit after changing the clock
1796 if (hba->clk_gating.is_suspended ||
1797 (hba->clk_gating.state != REQ_CLKS_OFF)) {
1798 hba->clk_gating.state = CLKS_ON;
1799 trace_ufshcd_clk_gating(dev_name(hba->dev),
1800 hba->clk_gating.state);
1804 if (hba->clk_gating.active_reqs
1805 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1806 || hba->outstanding_reqs || hba->outstanding_tasks
1807 || hba->active_uic_cmd || hba->uic_async_done)
1810 spin_unlock_irqrestore(hba->host->host_lock, flags);
1812 /* put the link into hibern8 mode before turning off clocks */
1813 if (ufshcd_can_hibern8_during_gating(hba)) {
1814 ret = ufshcd_uic_hibern8_enter(hba);
1816 hba->clk_gating.state = CLKS_ON;
1817 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
1819 trace_ufshcd_clk_gating(dev_name(hba->dev),
1820 hba->clk_gating.state);
1823 ufshcd_set_link_hibern8(hba);
1826 ufshcd_disable_irq(hba);
1828 ufshcd_setup_clocks(hba, false);
1830 /* Put the host controller in low power mode if possible */
1831 ufshcd_hba_vreg_set_lpm(hba);
1833 * In case you are here to cancel this work the gating state
1834 * would be marked as REQ_CLKS_ON. In this case keep the state
1835 * as REQ_CLKS_ON which would anyway imply that clocks are off
1836 * and a request to turn them on is pending. By doing this way,
1837 * we keep the state machine in tact and this would ultimately
1838 * prevent from doing cancel work multiple times when there are
1839 * new requests arriving before the current cancel work is done.
1841 spin_lock_irqsave(hba->host->host_lock, flags);
1842 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1843 hba->clk_gating.state = CLKS_OFF;
1844 trace_ufshcd_clk_gating(dev_name(hba->dev),
1845 hba->clk_gating.state);
1848 spin_unlock_irqrestore(hba->host->host_lock, flags);
1853 /* host lock must be held before calling this variant */
1854 static void __ufshcd_release(struct ufs_hba *hba)
1856 if (!ufshcd_is_clkgating_allowed(hba))
1859 hba->clk_gating.active_reqs--;
1861 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended ||
1862 hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL ||
1863 hba->outstanding_tasks || !hba->clk_gating.is_initialized ||
1864 hba->active_uic_cmd || hba->uic_async_done ||
1865 hba->clk_gating.state == CLKS_OFF)
1868 hba->clk_gating.state = REQ_CLKS_OFF;
1869 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1870 queue_delayed_work(hba->clk_gating.clk_gating_workq,
1871 &hba->clk_gating.gate_work,
1872 msecs_to_jiffies(hba->clk_gating.delay_ms));
1875 void ufshcd_release(struct ufs_hba *hba)
1877 unsigned long flags;
1879 spin_lock_irqsave(hba->host->host_lock, flags);
1880 __ufshcd_release(hba);
1881 spin_unlock_irqrestore(hba->host->host_lock, flags);
1883 EXPORT_SYMBOL_GPL(ufshcd_release);
1885 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1886 struct device_attribute *attr, char *buf)
1888 struct ufs_hba *hba = dev_get_drvdata(dev);
1890 return sysfs_emit(buf, "%lu\n", hba->clk_gating.delay_ms);
1893 void ufshcd_clkgate_delay_set(struct device *dev, unsigned long value)
1895 struct ufs_hba *hba = dev_get_drvdata(dev);
1896 unsigned long flags;
1898 spin_lock_irqsave(hba->host->host_lock, flags);
1899 hba->clk_gating.delay_ms = value;
1900 spin_unlock_irqrestore(hba->host->host_lock, flags);
1902 EXPORT_SYMBOL_GPL(ufshcd_clkgate_delay_set);
1904 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1905 struct device_attribute *attr, const char *buf, size_t count)
1907 unsigned long value;
1909 if (kstrtoul(buf, 0, &value))
1912 ufshcd_clkgate_delay_set(dev, value);
1916 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1917 struct device_attribute *attr, char *buf)
1919 struct ufs_hba *hba = dev_get_drvdata(dev);
1921 return sysfs_emit(buf, "%d\n", hba->clk_gating.is_enabled);
1924 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1925 struct device_attribute *attr, const char *buf, size_t count)
1927 struct ufs_hba *hba = dev_get_drvdata(dev);
1928 unsigned long flags;
1931 if (kstrtou32(buf, 0, &value))
1936 spin_lock_irqsave(hba->host->host_lock, flags);
1937 if (value == hba->clk_gating.is_enabled)
1941 __ufshcd_release(hba);
1943 hba->clk_gating.active_reqs++;
1945 hba->clk_gating.is_enabled = value;
1947 spin_unlock_irqrestore(hba->host->host_lock, flags);
1951 static void ufshcd_init_clk_gating_sysfs(struct ufs_hba *hba)
1953 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1954 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1955 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1956 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1957 hba->clk_gating.delay_attr.attr.mode = 0644;
1958 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1959 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1961 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
1962 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
1963 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
1964 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
1965 hba->clk_gating.enable_attr.attr.mode = 0644;
1966 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
1967 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1970 static void ufshcd_remove_clk_gating_sysfs(struct ufs_hba *hba)
1972 if (hba->clk_gating.delay_attr.attr.name)
1973 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1974 if (hba->clk_gating.enable_attr.attr.name)
1975 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1978 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1980 char wq_name[sizeof("ufs_clk_gating_00")];
1982 if (!ufshcd_is_clkgating_allowed(hba))
1985 hba->clk_gating.state = CLKS_ON;
1987 hba->clk_gating.delay_ms = 150;
1988 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
1989 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
1991 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d",
1992 hba->host->host_no);
1993 hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(wq_name,
1994 WQ_MEM_RECLAIM | WQ_HIGHPRI);
1996 ufshcd_init_clk_gating_sysfs(hba);
1998 hba->clk_gating.is_enabled = true;
1999 hba->clk_gating.is_initialized = true;
2002 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
2004 if (!hba->clk_gating.is_initialized)
2007 ufshcd_remove_clk_gating_sysfs(hba);
2009 /* Ungate the clock if necessary. */
2010 ufshcd_hold(hba, false);
2011 hba->clk_gating.is_initialized = false;
2012 ufshcd_release(hba);
2014 destroy_workqueue(hba->clk_gating.clk_gating_workq);
2017 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
2019 bool queue_resume_work = false;
2020 ktime_t curr_t = ktime_get();
2021 unsigned long flags;
2023 if (!ufshcd_is_clkscaling_supported(hba))
2026 spin_lock_irqsave(hba->host->host_lock, flags);
2027 if (!hba->clk_scaling.active_reqs++)
2028 queue_resume_work = true;
2030 if (!hba->clk_scaling.is_enabled || hba->pm_op_in_progress) {
2031 spin_unlock_irqrestore(hba->host->host_lock, flags);
2035 if (queue_resume_work)
2036 queue_work(hba->clk_scaling.workq,
2037 &hba->clk_scaling.resume_work);
2039 if (!hba->clk_scaling.window_start_t) {
2040 hba->clk_scaling.window_start_t = curr_t;
2041 hba->clk_scaling.tot_busy_t = 0;
2042 hba->clk_scaling.is_busy_started = false;
2045 if (!hba->clk_scaling.is_busy_started) {
2046 hba->clk_scaling.busy_start_t = curr_t;
2047 hba->clk_scaling.is_busy_started = true;
2049 spin_unlock_irqrestore(hba->host->host_lock, flags);
2052 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
2054 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
2055 unsigned long flags;
2057 if (!ufshcd_is_clkscaling_supported(hba))
2060 spin_lock_irqsave(hba->host->host_lock, flags);
2061 hba->clk_scaling.active_reqs--;
2062 if (!hba->outstanding_reqs && scaling->is_busy_started) {
2063 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
2064 scaling->busy_start_t));
2065 scaling->busy_start_t = 0;
2066 scaling->is_busy_started = false;
2068 spin_unlock_irqrestore(hba->host->host_lock, flags);
2071 static inline int ufshcd_monitor_opcode2dir(u8 opcode)
2073 if (opcode == READ_6 || opcode == READ_10 || opcode == READ_16)
2075 else if (opcode == WRITE_6 || opcode == WRITE_10 || opcode == WRITE_16)
2081 static inline bool ufshcd_should_inform_monitor(struct ufs_hba *hba,
2082 struct ufshcd_lrb *lrbp)
2084 const struct ufs_hba_monitor *m = &hba->monitor;
2086 return (m->enabled && lrbp && lrbp->cmd &&
2087 (!m->chunk_size || m->chunk_size == lrbp->cmd->sdb.length) &&
2088 ktime_before(hba->monitor.enabled_ts, lrbp->issue_time_stamp));
2091 static void ufshcd_start_monitor(struct ufs_hba *hba,
2092 const struct ufshcd_lrb *lrbp)
2094 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2095 unsigned long flags;
2097 spin_lock_irqsave(hba->host->host_lock, flags);
2098 if (dir >= 0 && hba->monitor.nr_queued[dir]++ == 0)
2099 hba->monitor.busy_start_ts[dir] = ktime_get();
2100 spin_unlock_irqrestore(hba->host->host_lock, flags);
2103 static void ufshcd_update_monitor(struct ufs_hba *hba, const struct ufshcd_lrb *lrbp)
2105 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2106 unsigned long flags;
2108 spin_lock_irqsave(hba->host->host_lock, flags);
2109 if (dir >= 0 && hba->monitor.nr_queued[dir] > 0) {
2110 const struct request *req = scsi_cmd_to_rq(lrbp->cmd);
2111 struct ufs_hba_monitor *m = &hba->monitor;
2112 ktime_t now, inc, lat;
2114 now = lrbp->compl_time_stamp;
2115 inc = ktime_sub(now, m->busy_start_ts[dir]);
2116 m->total_busy[dir] = ktime_add(m->total_busy[dir], inc);
2117 m->nr_sec_rw[dir] += blk_rq_sectors(req);
2119 /* Update latencies */
2121 lat = ktime_sub(now, lrbp->issue_time_stamp);
2122 m->lat_sum[dir] += lat;
2123 if (m->lat_max[dir] < lat || !m->lat_max[dir])
2124 m->lat_max[dir] = lat;
2125 if (m->lat_min[dir] > lat || !m->lat_min[dir])
2126 m->lat_min[dir] = lat;
2128 m->nr_queued[dir]--;
2129 /* Push forward the busy start of monitor */
2130 m->busy_start_ts[dir] = now;
2132 spin_unlock_irqrestore(hba->host->host_lock, flags);
2136 * ufshcd_send_command - Send SCSI or device management commands
2137 * @hba: per adapter instance
2138 * @task_tag: Task tag of the command
2141 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
2143 struct ufshcd_lrb *lrbp = &hba->lrb[task_tag];
2144 unsigned long flags;
2146 lrbp->issue_time_stamp = ktime_get();
2147 lrbp->issue_time_stamp_local_clock = local_clock();
2148 lrbp->compl_time_stamp = ktime_set(0, 0);
2149 lrbp->compl_time_stamp_local_clock = 0;
2150 ufshcd_add_command_trace(hba, task_tag, UFS_CMD_SEND);
2151 ufshcd_clk_scaling_start_busy(hba);
2152 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
2153 ufshcd_start_monitor(hba, lrbp);
2155 spin_lock_irqsave(&hba->outstanding_lock, flags);
2156 if (hba->vops && hba->vops->setup_xfer_req)
2157 hba->vops->setup_xfer_req(hba, task_tag, !!lrbp->cmd);
2158 __set_bit(task_tag, &hba->outstanding_reqs);
2159 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
2160 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
2164 * ufshcd_copy_sense_data - Copy sense data in case of check condition
2165 * @lrbp: pointer to local reference block
2167 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
2169 u8 *const sense_buffer = lrbp->cmd->sense_buffer;
2173 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
2176 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
2177 len_to_copy = min_t(int, UFS_SENSE_SIZE, len);
2179 memcpy(sense_buffer, lrbp->ucd_rsp_ptr->sr.sense_data,
2185 * ufshcd_copy_query_response() - Copy the Query Response and the data
2187 * @hba: per adapter instance
2188 * @lrbp: pointer to local reference block
2191 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2193 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2195 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
2197 /* Get the descriptor */
2198 if (hba->dev_cmd.query.descriptor &&
2199 lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
2200 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
2201 GENERAL_UPIU_REQUEST_SIZE;
2205 /* data segment length */
2206 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
2207 MASK_QUERY_DATA_SEG_LEN;
2208 buf_len = be16_to_cpu(
2209 hba->dev_cmd.query.request.upiu_req.length);
2210 if (likely(buf_len >= resp_len)) {
2211 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
2214 "%s: rsp size %d is bigger than buffer size %d",
2215 __func__, resp_len, buf_len);
2224 * ufshcd_hba_capabilities - Read controller capabilities
2225 * @hba: per adapter instance
2227 * Return: 0 on success, negative on error.
2229 static inline int ufshcd_hba_capabilities(struct ufs_hba *hba)
2233 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
2234 if (hba->quirks & UFSHCD_QUIRK_BROKEN_64BIT_ADDRESS)
2235 hba->capabilities &= ~MASK_64_ADDRESSING_SUPPORT;
2237 /* nutrs and nutmrs are 0 based values */
2238 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
2240 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
2241 hba->reserved_slot = hba->nutrs - 1;
2243 /* Read crypto capabilities */
2244 err = ufshcd_hba_init_crypto_capabilities(hba);
2246 dev_err(hba->dev, "crypto setup failed\n");
2252 * ufshcd_ready_for_uic_cmd - Check if controller is ready
2253 * to accept UIC commands
2254 * @hba: per adapter instance
2255 * Return true on success, else false
2257 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
2259 return ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY;
2263 * ufshcd_get_upmcrs - Get the power mode change request status
2264 * @hba: Pointer to adapter instance
2266 * This function gets the UPMCRS field of HCS register
2267 * Returns value of UPMCRS field
2269 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
2271 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
2275 * ufshcd_dispatch_uic_cmd - Dispatch an UIC command to the Unipro layer
2276 * @hba: per adapter instance
2277 * @uic_cmd: UIC command
2280 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2282 lockdep_assert_held(&hba->uic_cmd_mutex);
2284 WARN_ON(hba->active_uic_cmd);
2286 hba->active_uic_cmd = uic_cmd;
2289 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2290 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2291 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2293 ufshcd_add_uic_command_trace(hba, uic_cmd, UFS_CMD_SEND);
2296 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2301 * ufshcd_wait_for_uic_cmd - Wait for completion of an UIC command
2302 * @hba: per adapter instance
2303 * @uic_cmd: UIC command
2305 * Returns 0 only if success.
2308 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2311 unsigned long flags;
2313 lockdep_assert_held(&hba->uic_cmd_mutex);
2315 if (wait_for_completion_timeout(&uic_cmd->done,
2316 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
2317 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2321 "uic cmd 0x%x with arg3 0x%x completion timeout\n",
2322 uic_cmd->command, uic_cmd->argument3);
2324 if (!uic_cmd->cmd_active) {
2325 dev_err(hba->dev, "%s: UIC cmd has been completed, return the result\n",
2327 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2331 spin_lock_irqsave(hba->host->host_lock, flags);
2332 hba->active_uic_cmd = NULL;
2333 spin_unlock_irqrestore(hba->host->host_lock, flags);
2339 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2340 * @hba: per adapter instance
2341 * @uic_cmd: UIC command
2342 * @completion: initialize the completion only if this is set to true
2344 * Returns 0 only if success.
2347 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
2350 lockdep_assert_held(&hba->uic_cmd_mutex);
2351 lockdep_assert_held(hba->host->host_lock);
2353 if (!ufshcd_ready_for_uic_cmd(hba)) {
2355 "Controller not ready to accept UIC commands\n");
2360 init_completion(&uic_cmd->done);
2362 uic_cmd->cmd_active = 1;
2363 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2369 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2370 * @hba: per adapter instance
2371 * @uic_cmd: UIC command
2373 * Returns 0 only if success.
2375 int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2378 unsigned long flags;
2380 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UIC_CMD)
2383 ufshcd_hold(hba, false);
2384 mutex_lock(&hba->uic_cmd_mutex);
2385 ufshcd_add_delay_before_dme_cmd(hba);
2387 spin_lock_irqsave(hba->host->host_lock, flags);
2388 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
2389 spin_unlock_irqrestore(hba->host->host_lock, flags);
2391 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2393 mutex_unlock(&hba->uic_cmd_mutex);
2395 ufshcd_release(hba);
2400 * ufshcd_map_sg - Map scatter-gather list to prdt
2401 * @hba: per adapter instance
2402 * @lrbp: pointer to local reference block
2404 * Returns 0 in case of success, non-zero value in case of failure
2406 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2408 struct ufshcd_sg_entry *prd_table;
2409 struct scatterlist *sg;
2410 struct scsi_cmnd *cmd;
2415 sg_segments = scsi_dma_map(cmd);
2416 if (sg_segments < 0)
2421 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2422 lrbp->utr_descriptor_ptr->prd_table_length =
2423 cpu_to_le16((sg_segments *
2424 sizeof(struct ufshcd_sg_entry)));
2426 lrbp->utr_descriptor_ptr->prd_table_length =
2427 cpu_to_le16(sg_segments);
2429 prd_table = lrbp->ucd_prdt_ptr;
2431 scsi_for_each_sg(cmd, sg, sg_segments, i) {
2432 const unsigned int len = sg_dma_len(sg);
2435 * From the UFSHCI spec: "Data Byte Count (DBC): A '0'
2436 * based value that indicates the length, in bytes, of
2437 * the data block. A maximum of length of 256KB may
2438 * exist for any entry. Bits 1:0 of this field shall be
2439 * 11b to indicate Dword granularity. A value of '3'
2440 * indicates 4 bytes, '7' indicates 8 bytes, etc."
2442 WARN_ONCE(len > 256 * 1024, "len = %#x\n", len);
2443 prd_table[i].size = cpu_to_le32(len - 1);
2444 prd_table[i].addr = cpu_to_le64(sg->dma_address);
2445 prd_table[i].reserved = 0;
2448 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2455 * ufshcd_enable_intr - enable interrupts
2456 * @hba: per adapter instance
2457 * @intrs: interrupt bits
2459 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2461 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2463 if (hba->ufs_version == ufshci_version(1, 0)) {
2465 rw = set & INTERRUPT_MASK_RW_VER_10;
2466 set = rw | ((set ^ intrs) & intrs);
2471 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2475 * ufshcd_disable_intr - disable interrupts
2476 * @hba: per adapter instance
2477 * @intrs: interrupt bits
2479 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2481 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2483 if (hba->ufs_version == ufshci_version(1, 0)) {
2485 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2486 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2487 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2493 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2497 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
2498 * descriptor according to request
2499 * @lrbp: pointer to local reference block
2500 * @upiu_flags: flags required in the header
2501 * @cmd_dir: requests data direction
2503 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
2504 u8 *upiu_flags, enum dma_data_direction cmd_dir)
2506 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2512 if (cmd_dir == DMA_FROM_DEVICE) {
2513 data_direction = UTP_DEVICE_TO_HOST;
2514 *upiu_flags = UPIU_CMD_FLAGS_READ;
2515 } else if (cmd_dir == DMA_TO_DEVICE) {
2516 data_direction = UTP_HOST_TO_DEVICE;
2517 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2519 data_direction = UTP_NO_DATA_TRANSFER;
2520 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2523 dword_0 = data_direction | (lrbp->command_type
2524 << UPIU_COMMAND_TYPE_OFFSET);
2526 dword_0 |= UTP_REQ_DESC_INT_CMD;
2528 /* Prepare crypto related dwords */
2529 ufshcd_prepare_req_desc_hdr_crypto(lrbp, &dword_0, &dword_1, &dword_3);
2531 /* Transfer request descriptor header fields */
2532 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2533 req_desc->header.dword_1 = cpu_to_le32(dword_1);
2535 * assigning invalid value for command status. Controller
2536 * updates OCS on command completion, with the command
2539 req_desc->header.dword_2 =
2540 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2541 req_desc->header.dword_3 = cpu_to_le32(dword_3);
2543 req_desc->prd_table_length = 0;
2547 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2549 * @lrbp: local reference block pointer
2550 * @upiu_flags: flags
2553 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u8 upiu_flags)
2555 struct scsi_cmnd *cmd = lrbp->cmd;
2556 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2557 unsigned short cdb_len;
2559 /* command descriptor fields */
2560 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2561 UPIU_TRANSACTION_COMMAND, upiu_flags,
2562 lrbp->lun, lrbp->task_tag);
2563 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2564 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2566 /* Total EHS length and Data segment length will be zero */
2567 ucd_req_ptr->header.dword_2 = 0;
2569 ucd_req_ptr->sc.exp_data_transfer_len = cpu_to_be32(cmd->sdb.length);
2571 cdb_len = min_t(unsigned short, cmd->cmd_len, UFS_CDB_SIZE);
2572 memset(ucd_req_ptr->sc.cdb, 0, UFS_CDB_SIZE);
2573 memcpy(ucd_req_ptr->sc.cdb, cmd->cmnd, cdb_len);
2575 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2579 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
2582 * @lrbp: local reference block pointer
2583 * @upiu_flags: flags
2585 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2586 struct ufshcd_lrb *lrbp, u8 upiu_flags)
2588 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2589 struct ufs_query *query = &hba->dev_cmd.query;
2590 u16 len = be16_to_cpu(query->request.upiu_req.length);
2592 /* Query request header */
2593 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2594 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2595 lrbp->lun, lrbp->task_tag);
2596 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2597 0, query->request.query_func, 0, 0);
2599 /* Data segment length only need for WRITE_DESC */
2600 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2601 ucd_req_ptr->header.dword_2 =
2602 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2604 ucd_req_ptr->header.dword_2 = 0;
2606 /* Copy the Query Request buffer as is */
2607 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2610 /* Copy the Descriptor */
2611 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2612 memcpy(ucd_req_ptr + 1, query->descriptor, len);
2614 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2617 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2619 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2621 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2623 /* command descriptor fields */
2624 ucd_req_ptr->header.dword_0 =
2626 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2627 /* clear rest of the fields of basic header */
2628 ucd_req_ptr->header.dword_1 = 0;
2629 ucd_req_ptr->header.dword_2 = 0;
2631 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2635 * ufshcd_compose_devman_upiu - UFS Protocol Information Unit(UPIU)
2636 * for Device Management Purposes
2637 * @hba: per adapter instance
2638 * @lrbp: pointer to local reference block
2640 static int ufshcd_compose_devman_upiu(struct ufs_hba *hba,
2641 struct ufshcd_lrb *lrbp)
2646 if (hba->ufs_version <= ufshci_version(1, 1))
2647 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2649 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2651 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
2652 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2653 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2654 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2655 ufshcd_prepare_utp_nop_upiu(lrbp);
2663 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2665 * @hba: per adapter instance
2666 * @lrbp: pointer to local reference block
2668 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2673 if (hba->ufs_version <= ufshci_version(1, 1))
2674 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2676 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2678 if (likely(lrbp->cmd)) {
2679 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
2680 lrbp->cmd->sc_data_direction);
2681 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2690 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2691 * @upiu_wlun_id: UPIU W-LUN id
2693 * Returns SCSI W-LUN id
2695 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2697 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2700 static inline bool is_device_wlun(struct scsi_device *sdev)
2703 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN);
2707 * Associate the UFS controller queue with the default and poll HCTX types.
2708 * Initialize the mq_map[] arrays.
2710 static void ufshcd_map_queues(struct Scsi_Host *shost)
2714 for (i = 0; i < shost->nr_maps; i++) {
2715 struct blk_mq_queue_map *map = &shost->tag_set.map[i];
2718 case HCTX_TYPE_DEFAULT:
2719 case HCTX_TYPE_POLL:
2722 case HCTX_TYPE_READ:
2728 map->queue_offset = 0;
2729 blk_mq_map_queues(map);
2733 static void ufshcd_init_lrb(struct ufs_hba *hba, struct ufshcd_lrb *lrb, int i)
2735 struct utp_transfer_cmd_desc *cmd_descp = hba->ucdl_base_addr;
2736 struct utp_transfer_req_desc *utrdlp = hba->utrdl_base_addr;
2737 dma_addr_t cmd_desc_element_addr = hba->ucdl_dma_addr +
2738 i * sizeof(struct utp_transfer_cmd_desc);
2739 u16 response_offset = offsetof(struct utp_transfer_cmd_desc,
2741 u16 prdt_offset = offsetof(struct utp_transfer_cmd_desc, prd_table);
2743 lrb->utr_descriptor_ptr = utrdlp + i;
2744 lrb->utrd_dma_addr = hba->utrdl_dma_addr +
2745 i * sizeof(struct utp_transfer_req_desc);
2746 lrb->ucd_req_ptr = (struct utp_upiu_req *)(cmd_descp + i);
2747 lrb->ucd_req_dma_addr = cmd_desc_element_addr;
2748 lrb->ucd_rsp_ptr = (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
2749 lrb->ucd_rsp_dma_addr = cmd_desc_element_addr + response_offset;
2750 lrb->ucd_prdt_ptr = cmd_descp[i].prd_table;
2751 lrb->ucd_prdt_dma_addr = cmd_desc_element_addr + prdt_offset;
2755 * ufshcd_queuecommand - main entry point for SCSI requests
2756 * @host: SCSI host pointer
2757 * @cmd: command from SCSI Midlayer
2759 * Returns 0 for success, non-zero in case of failure
2761 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2763 struct ufs_hba *hba = shost_priv(host);
2764 int tag = scsi_cmd_to_rq(cmd)->tag;
2765 struct ufshcd_lrb *lrbp;
2768 WARN_ONCE(tag < 0 || tag >= hba->nutrs, "Invalid tag %d\n", tag);
2771 * Allows the UFS error handler to wait for prior ufshcd_queuecommand()
2776 switch (hba->ufshcd_state) {
2777 case UFSHCD_STATE_OPERATIONAL:
2779 case UFSHCD_STATE_EH_SCHEDULED_NON_FATAL:
2781 * SCSI error handler can call ->queuecommand() while UFS error
2782 * handler is in progress. Error interrupts could change the
2783 * state from UFSHCD_STATE_RESET to
2784 * UFSHCD_STATE_EH_SCHEDULED_NON_FATAL. Prevent requests
2785 * being issued in that case.
2787 if (ufshcd_eh_in_progress(hba)) {
2788 err = SCSI_MLQUEUE_HOST_BUSY;
2792 case UFSHCD_STATE_EH_SCHEDULED_FATAL:
2794 * pm_runtime_get_sync() is used at error handling preparation
2795 * stage. If a scsi cmd, e.g. the SSU cmd, is sent from hba's
2796 * PM ops, it can never be finished if we let SCSI layer keep
2797 * retrying it, which gets err handler stuck forever. Neither
2798 * can we let the scsi cmd pass through, because UFS is in bad
2799 * state, the scsi cmd may eventually time out, which will get
2800 * err handler blocked for too long. So, just fail the scsi cmd
2801 * sent from PM ops, err handler can recover PM error anyways.
2803 if (hba->pm_op_in_progress) {
2804 hba->force_reset = true;
2805 set_host_byte(cmd, DID_BAD_TARGET);
2810 case UFSHCD_STATE_RESET:
2811 err = SCSI_MLQUEUE_HOST_BUSY;
2813 case UFSHCD_STATE_ERROR:
2814 set_host_byte(cmd, DID_ERROR);
2819 hba->req_abort_count = 0;
2821 err = ufshcd_hold(hba, true);
2823 err = SCSI_MLQUEUE_HOST_BUSY;
2826 WARN_ON(ufshcd_is_clkgating_allowed(hba) &&
2827 (hba->clk_gating.state != CLKS_ON));
2829 lrbp = &hba->lrb[tag];
2832 lrbp->task_tag = tag;
2833 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2834 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba);
2836 ufshcd_prepare_lrbp_crypto(scsi_cmd_to_rq(cmd), lrbp);
2838 lrbp->req_abort_skip = false;
2840 ufshpb_prep(hba, lrbp);
2842 ufshcd_comp_scsi_upiu(hba, lrbp);
2844 err = ufshcd_map_sg(hba, lrbp);
2847 ufshcd_release(hba);
2851 ufshcd_send_command(hba, tag);
2856 if (ufs_trigger_eh()) {
2857 unsigned long flags;
2859 spin_lock_irqsave(hba->host->host_lock, flags);
2860 ufshcd_schedule_eh_work(hba);
2861 spin_unlock_irqrestore(hba->host->host_lock, flags);
2867 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2868 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2871 lrbp->task_tag = tag;
2872 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2873 lrbp->intr_cmd = true; /* No interrupt aggregation */
2874 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
2875 hba->dev_cmd.type = cmd_type;
2877 return ufshcd_compose_devman_upiu(hba, lrbp);
2881 * Clear all the requests from the controller for which a bit has been set in
2882 * @mask and wait until the controller confirms that these requests have been
2885 static int ufshcd_clear_cmds(struct ufs_hba *hba, u32 mask)
2887 unsigned long flags;
2889 /* clear outstanding transaction before retry */
2890 spin_lock_irqsave(hba->host->host_lock, flags);
2891 ufshcd_utrl_clear(hba, mask);
2892 spin_unlock_irqrestore(hba->host->host_lock, flags);
2895 * wait for h/w to clear corresponding bit in door-bell.
2896 * max. wait is 1 sec.
2898 return ufshcd_wait_for_register(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL,
2899 mask, ~mask, 1000, 1000);
2903 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2905 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2907 /* Get the UPIU response */
2908 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
2909 UPIU_RSP_CODE_OFFSET;
2910 return query_res->response;
2914 * ufshcd_dev_cmd_completion() - handles device management command responses
2915 * @hba: per adapter instance
2916 * @lrbp: pointer to local reference block
2919 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2924 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
2925 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2928 case UPIU_TRANSACTION_NOP_IN:
2929 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
2931 dev_err(hba->dev, "%s: unexpected response %x\n",
2935 case UPIU_TRANSACTION_QUERY_RSP:
2936 err = ufshcd_check_query_response(hba, lrbp);
2938 err = ufshcd_copy_query_response(hba, lrbp);
2940 case UPIU_TRANSACTION_REJECT_UPIU:
2941 /* TODO: handle Reject UPIU Response */
2943 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
2948 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
2956 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
2957 struct ufshcd_lrb *lrbp, int max_timeout)
2959 unsigned long time_left = msecs_to_jiffies(max_timeout);
2960 unsigned long flags;
2965 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
2968 if (likely(time_left)) {
2970 * The completion handler called complete() and the caller of
2971 * this function still owns the @lrbp tag so the code below does
2972 * not trigger any race conditions.
2974 hba->dev_cmd.complete = NULL;
2975 err = ufshcd_get_tr_ocs(lrbp);
2977 err = ufshcd_dev_cmd_completion(hba, lrbp);
2980 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
2981 __func__, lrbp->task_tag);
2982 if (ufshcd_clear_cmds(hba, 1U << lrbp->task_tag) == 0) {
2983 /* successfully cleared the command, retry if needed */
2986 * Since clearing the command succeeded we also need to
2987 * clear the task tag bit from the outstanding_reqs
2990 spin_lock_irqsave(&hba->outstanding_lock, flags);
2991 pending = test_bit(lrbp->task_tag,
2992 &hba->outstanding_reqs);
2994 hba->dev_cmd.complete = NULL;
2995 __clear_bit(lrbp->task_tag,
2996 &hba->outstanding_reqs);
2998 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
3002 * The completion handler ran while we tried to
3003 * clear the command.
3009 dev_err(hba->dev, "%s: failed to clear tag %d\n",
3010 __func__, lrbp->task_tag);
3018 * ufshcd_exec_dev_cmd - API for sending device management requests
3020 * @cmd_type: specifies the type (NOP, Query...)
3021 * @timeout: timeout in milliseconds
3023 * NOTE: Since there is only one available tag for device management commands,
3024 * it is expected you hold the hba->dev_cmd.lock mutex.
3026 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
3027 enum dev_cmd_type cmd_type, int timeout)
3029 DECLARE_COMPLETION_ONSTACK(wait);
3030 const u32 tag = hba->reserved_slot;
3031 struct ufshcd_lrb *lrbp;
3034 /* Protects use of hba->reserved_slot. */
3035 lockdep_assert_held(&hba->dev_cmd.lock);
3037 down_read(&hba->clk_scaling_lock);
3039 lrbp = &hba->lrb[tag];
3041 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
3045 hba->dev_cmd.complete = &wait;
3047 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
3049 ufshcd_send_command(hba, tag);
3050 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
3051 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
3052 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
3055 up_read(&hba->clk_scaling_lock);
3060 * ufshcd_init_query() - init the query response and request parameters
3061 * @hba: per-adapter instance
3062 * @request: address of the request pointer to be initialized
3063 * @response: address of the response pointer to be initialized
3064 * @opcode: operation to perform
3065 * @idn: flag idn to access
3066 * @index: LU number to access
3067 * @selector: query/flag/descriptor further identification
3069 static inline void ufshcd_init_query(struct ufs_hba *hba,
3070 struct ufs_query_req **request, struct ufs_query_res **response,
3071 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
3073 *request = &hba->dev_cmd.query.request;
3074 *response = &hba->dev_cmd.query.response;
3075 memset(*request, 0, sizeof(struct ufs_query_req));
3076 memset(*response, 0, sizeof(struct ufs_query_res));
3077 (*request)->upiu_req.opcode = opcode;
3078 (*request)->upiu_req.idn = idn;
3079 (*request)->upiu_req.index = index;
3080 (*request)->upiu_req.selector = selector;
3083 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
3084 enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res)
3089 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
3090 ret = ufshcd_query_flag(hba, opcode, idn, index, flag_res);
3093 "%s: failed with error %d, retries %d\n",
3094 __func__, ret, retries);
3101 "%s: query flag, opcode %d, idn %d, failed with error %d after %d retries\n",
3102 __func__, opcode, idn, ret, retries);
3107 * ufshcd_query_flag() - API function for sending flag query requests
3108 * @hba: per-adapter instance
3109 * @opcode: flag query to perform
3110 * @idn: flag idn to access
3111 * @index: flag index to access
3112 * @flag_res: the flag value after the query request completes
3114 * Returns 0 for success, non-zero in case of failure
3116 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
3117 enum flag_idn idn, u8 index, bool *flag_res)
3119 struct ufs_query_req *request = NULL;
3120 struct ufs_query_res *response = NULL;
3121 int err, selector = 0;
3122 int timeout = QUERY_REQ_TIMEOUT;
3126 ufshcd_hold(hba, false);
3127 mutex_lock(&hba->dev_cmd.lock);
3128 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3132 case UPIU_QUERY_OPCODE_SET_FLAG:
3133 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
3134 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
3135 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3137 case UPIU_QUERY_OPCODE_READ_FLAG:
3138 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3140 /* No dummy reads */
3141 dev_err(hba->dev, "%s: Invalid argument for read request\n",
3149 "%s: Expected query flag opcode but got = %d\n",
3155 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
3159 "%s: Sending flag query for idn %d failed, err = %d\n",
3160 __func__, idn, err);
3165 *flag_res = (be32_to_cpu(response->upiu_res.value) &
3166 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
3169 mutex_unlock(&hba->dev_cmd.lock);
3170 ufshcd_release(hba);
3175 * ufshcd_query_attr - API function for sending attribute requests
3176 * @hba: per-adapter instance
3177 * @opcode: attribute opcode
3178 * @idn: attribute idn to access
3179 * @index: index field
3180 * @selector: selector field
3181 * @attr_val: the attribute value after the query request completes
3183 * Returns 0 for success, non-zero in case of failure
3185 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
3186 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
3188 struct ufs_query_req *request = NULL;
3189 struct ufs_query_res *response = NULL;
3195 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
3200 ufshcd_hold(hba, false);
3202 mutex_lock(&hba->dev_cmd.lock);
3203 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3207 case UPIU_QUERY_OPCODE_WRITE_ATTR:
3208 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3209 request->upiu_req.value = cpu_to_be32(*attr_val);
3211 case UPIU_QUERY_OPCODE_READ_ATTR:
3212 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3215 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
3221 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3224 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3225 __func__, opcode, idn, index, err);
3229 *attr_val = be32_to_cpu(response->upiu_res.value);
3232 mutex_unlock(&hba->dev_cmd.lock);
3233 ufshcd_release(hba);
3238 * ufshcd_query_attr_retry() - API function for sending query
3239 * attribute with retries
3240 * @hba: per-adapter instance
3241 * @opcode: attribute opcode
3242 * @idn: attribute idn to access
3243 * @index: index field
3244 * @selector: selector field
3245 * @attr_val: the attribute value after the query request
3248 * Returns 0 for success, non-zero in case of failure
3250 int ufshcd_query_attr_retry(struct ufs_hba *hba,
3251 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
3257 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3258 ret = ufshcd_query_attr(hba, opcode, idn, index,
3259 selector, attr_val);
3261 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
3262 __func__, ret, retries);
3269 "%s: query attribute, idn %d, failed with error %d after %d retries\n",
3270 __func__, idn, ret, QUERY_REQ_RETRIES);
3274 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
3275 enum query_opcode opcode, enum desc_idn idn, u8 index,
3276 u8 selector, u8 *desc_buf, int *buf_len)
3278 struct ufs_query_req *request = NULL;
3279 struct ufs_query_res *response = NULL;
3285 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
3290 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
3291 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
3292 __func__, *buf_len);
3296 ufshcd_hold(hba, false);
3298 mutex_lock(&hba->dev_cmd.lock);
3299 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3301 hba->dev_cmd.query.descriptor = desc_buf;
3302 request->upiu_req.length = cpu_to_be16(*buf_len);
3305 case UPIU_QUERY_OPCODE_WRITE_DESC:
3306 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3308 case UPIU_QUERY_OPCODE_READ_DESC:
3309 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3313 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
3319 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3322 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3323 __func__, opcode, idn, index, err);
3327 *buf_len = be16_to_cpu(response->upiu_res.length);
3330 hba->dev_cmd.query.descriptor = NULL;
3331 mutex_unlock(&hba->dev_cmd.lock);
3332 ufshcd_release(hba);
3337 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3338 * @hba: per-adapter instance
3339 * @opcode: attribute opcode
3340 * @idn: attribute idn to access
3341 * @index: index field
3342 * @selector: selector field
3343 * @desc_buf: the buffer that contains the descriptor
3344 * @buf_len: length parameter passed to the device
3346 * Returns 0 for success, non-zero in case of failure.
3347 * The buf_len parameter will contain, on return, the length parameter
3348 * received on the response.
3350 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3351 enum query_opcode opcode,
3352 enum desc_idn idn, u8 index,
3354 u8 *desc_buf, int *buf_len)
3359 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3360 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3361 selector, desc_buf, buf_len);
3362 if (!err || err == -EINVAL)
3370 * ufshcd_map_desc_id_to_length - map descriptor IDN to its length
3371 * @hba: Pointer to adapter instance
3372 * @desc_id: descriptor idn value
3373 * @desc_len: mapped desc length (out)
3375 void ufshcd_map_desc_id_to_length(struct ufs_hba *hba, enum desc_idn desc_id,
3378 if (desc_id >= QUERY_DESC_IDN_MAX || desc_id == QUERY_DESC_IDN_RFU_0 ||
3379 desc_id == QUERY_DESC_IDN_RFU_1)
3382 *desc_len = hba->desc_size[desc_id];
3384 EXPORT_SYMBOL(ufshcd_map_desc_id_to_length);
3386 static void ufshcd_update_desc_length(struct ufs_hba *hba,
3387 enum desc_idn desc_id, int desc_index,
3388 unsigned char desc_len)
3390 if (hba->desc_size[desc_id] == QUERY_DESC_MAX_SIZE &&
3391 desc_id != QUERY_DESC_IDN_STRING && desc_index != UFS_RPMB_UNIT)
3392 /* For UFS 3.1, the normal unit descriptor is 10 bytes larger
3393 * than the RPMB unit, however, both descriptors share the same
3394 * desc_idn, to cover both unit descriptors with one length, we
3395 * choose the normal unit descriptor length by desc_index.
3397 hba->desc_size[desc_id] = desc_len;
3401 * ufshcd_read_desc_param - read the specified descriptor parameter
3402 * @hba: Pointer to adapter instance
3403 * @desc_id: descriptor idn value
3404 * @desc_index: descriptor index
3405 * @param_offset: offset of the parameter to read
3406 * @param_read_buf: pointer to buffer where parameter would be read
3407 * @param_size: sizeof(param_read_buf)
3409 * Return 0 in case of success, non-zero otherwise
3411 int ufshcd_read_desc_param(struct ufs_hba *hba,
3412 enum desc_idn desc_id,
3421 bool is_kmalloc = true;
3424 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3427 /* Get the length of descriptor */
3428 ufshcd_map_desc_id_to_length(hba, desc_id, &buff_len);
3430 dev_err(hba->dev, "%s: Failed to get desc length\n", __func__);
3434 if (param_offset >= buff_len) {
3435 dev_err(hba->dev, "%s: Invalid offset 0x%x in descriptor IDN 0x%x, length 0x%x\n",
3436 __func__, param_offset, desc_id, buff_len);
3440 /* Check whether we need temp memory */
3441 if (param_offset != 0 || param_size < buff_len) {
3442 desc_buf = kzalloc(buff_len, GFP_KERNEL);
3446 desc_buf = param_read_buf;
3450 /* Request for full descriptor */
3451 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3452 desc_id, desc_index, 0,
3453 desc_buf, &buff_len);
3456 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d\n",
3457 __func__, desc_id, desc_index, param_offset, ret);
3462 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3463 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header\n",
3464 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3469 /* Update descriptor length */
3470 buff_len = desc_buf[QUERY_DESC_LENGTH_OFFSET];
3471 ufshcd_update_desc_length(hba, desc_id, desc_index, buff_len);
3474 /* Make sure we don't copy more data than available */
3475 if (param_offset >= buff_len)
3478 memcpy(param_read_buf, &desc_buf[param_offset],
3479 min_t(u32, param_size, buff_len - param_offset));
3488 * struct uc_string_id - unicode string
3490 * @len: size of this descriptor inclusive
3491 * @type: descriptor type
3492 * @uc: unicode string character
3494 struct uc_string_id {
3500 /* replace non-printable or non-ASCII characters with spaces */
3501 static inline char ufshcd_remove_non_printable(u8 ch)
3503 return (ch >= 0x20 && ch <= 0x7e) ? ch : ' ';
3507 * ufshcd_read_string_desc - read string descriptor
3508 * @hba: pointer to adapter instance
3509 * @desc_index: descriptor index
3510 * @buf: pointer to buffer where descriptor would be read,
3511 * the caller should free the memory.
3512 * @ascii: if true convert from unicode to ascii characters
3513 * null terminated string.
3516 * * string size on success.
3517 * * -ENOMEM: on allocation failure
3518 * * -EINVAL: on a wrong parameter
3520 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index,
3521 u8 **buf, bool ascii)
3523 struct uc_string_id *uc_str;
3530 uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
3534 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_STRING, desc_index, 0,
3535 (u8 *)uc_str, QUERY_DESC_MAX_SIZE);
3537 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n",
3538 QUERY_REQ_RETRIES, ret);
3543 if (uc_str->len <= QUERY_DESC_HDR_SIZE) {
3544 dev_dbg(hba->dev, "String Desc is of zero length\n");
3553 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3554 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3555 str = kzalloc(ascii_len, GFP_KERNEL);
3562 * the descriptor contains string in UTF16 format
3563 * we need to convert to utf-8 so it can be displayed
3565 ret = utf16s_to_utf8s(uc_str->uc,
3566 uc_str->len - QUERY_DESC_HDR_SIZE,
3567 UTF16_BIG_ENDIAN, str, ascii_len);
3569 /* replace non-printable or non-ASCII characters with spaces */
3570 for (i = 0; i < ret; i++)
3571 str[i] = ufshcd_remove_non_printable(str[i]);
3576 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL);
3590 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3591 * @hba: Pointer to adapter instance
3593 * @param_offset: offset of the parameter to read
3594 * @param_read_buf: pointer to buffer where parameter would be read
3595 * @param_size: sizeof(param_read_buf)
3597 * Return 0 in case of success, non-zero otherwise
3599 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3601 enum unit_desc_param param_offset,
3606 * Unit descriptors are only available for general purpose LUs (LUN id
3607 * from 0 to 7) and RPMB Well known LU.
3609 if (!ufs_is_valid_unit_desc_lun(&hba->dev_info, lun))
3612 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3613 param_offset, param_read_buf, param_size);
3616 static int ufshcd_get_ref_clk_gating_wait(struct ufs_hba *hba)
3619 u32 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3621 if (hba->dev_info.wspecversion >= 0x300) {
3622 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3623 QUERY_ATTR_IDN_REF_CLK_GATING_WAIT_TIME, 0, 0,
3626 dev_err(hba->dev, "Failed reading bRefClkGatingWait. err = %d, use default %uus\n",
3629 if (gating_wait == 0) {
3630 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3631 dev_err(hba->dev, "Undefined ref clk gating wait time, use default %uus\n",
3635 hba->dev_info.clk_gating_wait_us = gating_wait;
3642 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3643 * @hba: per adapter instance
3645 * 1. Allocate DMA memory for Command Descriptor array
3646 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3647 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3648 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3650 * 4. Allocate memory for local reference block(lrb).
3652 * Returns 0 for success, non-zero in case of failure
3654 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3656 size_t utmrdl_size, utrdl_size, ucdl_size;
3658 /* Allocate memory for UTP command descriptors */
3659 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3660 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3662 &hba->ucdl_dma_addr,
3666 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3667 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3668 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3669 * be aligned to 128 bytes as well
3671 if (!hba->ucdl_base_addr ||
3672 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3674 "Command Descriptor Memory allocation failed\n");
3679 * Allocate memory for UTP Transfer descriptors
3680 * UFSHCI requires 1024 byte alignment of UTRD
3682 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3683 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3685 &hba->utrdl_dma_addr,
3687 if (!hba->utrdl_base_addr ||
3688 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3690 "Transfer Descriptor Memory allocation failed\n");
3695 * Allocate memory for UTP Task Management descriptors
3696 * UFSHCI requires 1024 byte alignment of UTMRD
3698 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3699 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3701 &hba->utmrdl_dma_addr,
3703 if (!hba->utmrdl_base_addr ||
3704 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3706 "Task Management Descriptor Memory allocation failed\n");
3710 /* Allocate memory for local reference block */
3711 hba->lrb = devm_kcalloc(hba->dev,
3712 hba->nutrs, sizeof(struct ufshcd_lrb),
3715 dev_err(hba->dev, "LRB Memory allocation failed\n");
3724 * ufshcd_host_memory_configure - configure local reference block with
3726 * @hba: per adapter instance
3728 * Configure Host memory space
3729 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3731 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3733 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3734 * into local reference block.
3736 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3738 struct utp_transfer_req_desc *utrdlp;
3739 dma_addr_t cmd_desc_dma_addr;
3740 dma_addr_t cmd_desc_element_addr;
3741 u16 response_offset;
3746 utrdlp = hba->utrdl_base_addr;
3749 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3751 offsetof(struct utp_transfer_cmd_desc, prd_table);
3753 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
3754 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3756 for (i = 0; i < hba->nutrs; i++) {
3757 /* Configure UTRD with command descriptor base address */
3758 cmd_desc_element_addr =
3759 (cmd_desc_dma_addr + (cmd_desc_size * i));
3760 utrdlp[i].command_desc_base_addr_lo =
3761 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3762 utrdlp[i].command_desc_base_addr_hi =
3763 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3765 /* Response upiu and prdt offset should be in double words */
3766 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3767 utrdlp[i].response_upiu_offset =
3768 cpu_to_le16(response_offset);
3769 utrdlp[i].prd_table_offset =
3770 cpu_to_le16(prdt_offset);
3771 utrdlp[i].response_upiu_length =
3772 cpu_to_le16(ALIGNED_UPIU_SIZE);
3774 utrdlp[i].response_upiu_offset =
3775 cpu_to_le16(response_offset >> 2);
3776 utrdlp[i].prd_table_offset =
3777 cpu_to_le16(prdt_offset >> 2);
3778 utrdlp[i].response_upiu_length =
3779 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3782 ufshcd_init_lrb(hba, &hba->lrb[i], i);
3787 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3788 * @hba: per adapter instance
3790 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3791 * in order to initialize the Unipro link startup procedure.
3792 * Once the Unipro links are up, the device connected to the controller
3795 * Returns 0 on success, non-zero value on failure
3797 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3799 struct uic_command uic_cmd = {0};
3802 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3804 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3807 "dme-link-startup: error code %d\n", ret);
3811 * ufshcd_dme_reset - UIC command for DME_RESET
3812 * @hba: per adapter instance
3814 * DME_RESET command is issued in order to reset UniPro stack.
3815 * This function now deals with cold reset.
3817 * Returns 0 on success, non-zero value on failure
3819 static int ufshcd_dme_reset(struct ufs_hba *hba)
3821 struct uic_command uic_cmd = {0};
3824 uic_cmd.command = UIC_CMD_DME_RESET;
3826 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3829 "dme-reset: error code %d\n", ret);
3834 int ufshcd_dme_configure_adapt(struct ufs_hba *hba,
3840 if (agreed_gear < UFS_HS_G4)
3841 adapt_val = PA_NO_ADAPT;
3843 ret = ufshcd_dme_set(hba,
3844 UIC_ARG_MIB(PA_TXHSADAPTTYPE),
3848 EXPORT_SYMBOL_GPL(ufshcd_dme_configure_adapt);
3851 * ufshcd_dme_enable - UIC command for DME_ENABLE
3852 * @hba: per adapter instance
3854 * DME_ENABLE command is issued in order to enable UniPro stack.
3856 * Returns 0 on success, non-zero value on failure
3858 static int ufshcd_dme_enable(struct ufs_hba *hba)
3860 struct uic_command uic_cmd = {0};
3863 uic_cmd.command = UIC_CMD_DME_ENABLE;
3865 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3868 "dme-enable: error code %d\n", ret);
3873 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3875 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3876 unsigned long min_sleep_time_us;
3878 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3882 * last_dme_cmd_tstamp will be 0 only for 1st call to
3885 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3886 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3888 unsigned long delta =
3889 (unsigned long) ktime_to_us(
3890 ktime_sub(ktime_get(),
3891 hba->last_dme_cmd_tstamp));
3893 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3895 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3897 return; /* no more delay required */
3900 /* allow sleep for extra 50us if needed */
3901 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3905 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3906 * @hba: per adapter instance
3907 * @attr_sel: uic command argument1
3908 * @attr_set: attribute set type as uic command argument2
3909 * @mib_val: setting value as uic command argument3
3910 * @peer: indicate whether peer or local
3912 * Returns 0 on success, non-zero value on failure
3914 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3915 u8 attr_set, u32 mib_val, u8 peer)
3917 struct uic_command uic_cmd = {0};
3918 static const char *const action[] = {
3922 const char *set = action[!!peer];
3924 int retries = UFS_UIC_COMMAND_RETRIES;
3926 uic_cmd.command = peer ?
3927 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3928 uic_cmd.argument1 = attr_sel;
3929 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3930 uic_cmd.argument3 = mib_val;
3933 /* for peer attributes we retry upon failure */
3934 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3936 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
3937 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
3938 } while (ret && peer && --retries);
3941 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
3942 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
3943 UFS_UIC_COMMAND_RETRIES - retries);
3947 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
3950 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
3951 * @hba: per adapter instance
3952 * @attr_sel: uic command argument1
3953 * @mib_val: the value of the attribute as returned by the UIC command
3954 * @peer: indicate whether peer or local
3956 * Returns 0 on success, non-zero value on failure
3958 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
3959 u32 *mib_val, u8 peer)
3961 struct uic_command uic_cmd = {0};
3962 static const char *const action[] = {
3966 const char *get = action[!!peer];
3968 int retries = UFS_UIC_COMMAND_RETRIES;
3969 struct ufs_pa_layer_attr orig_pwr_info;
3970 struct ufs_pa_layer_attr temp_pwr_info;
3971 bool pwr_mode_change = false;
3973 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
3974 orig_pwr_info = hba->pwr_info;
3975 temp_pwr_info = orig_pwr_info;
3977 if (orig_pwr_info.pwr_tx == FAST_MODE ||
3978 orig_pwr_info.pwr_rx == FAST_MODE) {
3979 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
3980 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
3981 pwr_mode_change = true;
3982 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
3983 orig_pwr_info.pwr_rx == SLOW_MODE) {
3984 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
3985 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
3986 pwr_mode_change = true;
3988 if (pwr_mode_change) {
3989 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
3995 uic_cmd.command = peer ?
3996 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
3997 uic_cmd.argument1 = attr_sel;
4000 /* for peer attributes we retry upon failure */
4001 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
4003 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
4004 get, UIC_GET_ATTR_ID(attr_sel), ret);
4005 } while (ret && peer && --retries);
4008 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
4009 get, UIC_GET_ATTR_ID(attr_sel),
4010 UFS_UIC_COMMAND_RETRIES - retries);
4012 if (mib_val && !ret)
4013 *mib_val = uic_cmd.argument3;
4015 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
4017 ufshcd_change_power_mode(hba, &orig_pwr_info);
4021 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
4024 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
4025 * state) and waits for it to take effect.
4027 * @hba: per adapter instance
4028 * @cmd: UIC command to execute
4030 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
4031 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
4032 * and device UniPro link and hence it's final completion would be indicated by
4033 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
4034 * addition to normal UIC command completion Status (UCCS). This function only
4035 * returns after the relevant status bits indicate the completion.
4037 * Returns 0 on success, non-zero value on failure
4039 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
4041 DECLARE_COMPLETION_ONSTACK(uic_async_done);
4042 unsigned long flags;
4045 bool reenable_intr = false;
4047 mutex_lock(&hba->uic_cmd_mutex);
4048 ufshcd_add_delay_before_dme_cmd(hba);
4050 spin_lock_irqsave(hba->host->host_lock, flags);
4051 if (ufshcd_is_link_broken(hba)) {
4055 hba->uic_async_done = &uic_async_done;
4056 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
4057 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
4059 * Make sure UIC command completion interrupt is disabled before
4060 * issuing UIC command.
4063 reenable_intr = true;
4065 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
4066 spin_unlock_irqrestore(hba->host->host_lock, flags);
4069 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
4070 cmd->command, cmd->argument3, ret);
4074 if (!wait_for_completion_timeout(hba->uic_async_done,
4075 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
4077 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
4078 cmd->command, cmd->argument3);
4080 if (!cmd->cmd_active) {
4081 dev_err(hba->dev, "%s: Power Mode Change operation has been completed, go check UPMCRS\n",
4091 status = ufshcd_get_upmcrs(hba);
4092 if (status != PWR_LOCAL) {
4094 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
4095 cmd->command, status);
4096 ret = (status != PWR_OK) ? status : -1;
4100 ufshcd_print_host_state(hba);
4101 ufshcd_print_pwr_info(hba);
4102 ufshcd_print_evt_hist(hba);
4105 spin_lock_irqsave(hba->host->host_lock, flags);
4106 hba->active_uic_cmd = NULL;
4107 hba->uic_async_done = NULL;
4109 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
4111 ufshcd_set_link_broken(hba);
4112 ufshcd_schedule_eh_work(hba);
4115 spin_unlock_irqrestore(hba->host->host_lock, flags);
4116 mutex_unlock(&hba->uic_cmd_mutex);
4122 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
4123 * using DME_SET primitives.
4124 * @hba: per adapter instance
4125 * @mode: powr mode value
4127 * Returns 0 on success, non-zero value on failure
4129 int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
4131 struct uic_command uic_cmd = {0};
4134 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
4135 ret = ufshcd_dme_set(hba,
4136 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
4138 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
4144 uic_cmd.command = UIC_CMD_DME_SET;
4145 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
4146 uic_cmd.argument3 = mode;
4147 ufshcd_hold(hba, false);
4148 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4149 ufshcd_release(hba);
4154 EXPORT_SYMBOL_GPL(ufshcd_uic_change_pwr_mode);
4156 int ufshcd_link_recovery(struct ufs_hba *hba)
4159 unsigned long flags;
4161 spin_lock_irqsave(hba->host->host_lock, flags);
4162 hba->ufshcd_state = UFSHCD_STATE_RESET;
4163 ufshcd_set_eh_in_progress(hba);
4164 spin_unlock_irqrestore(hba->host->host_lock, flags);
4166 /* Reset the attached device */
4167 ufshcd_device_reset(hba);
4169 ret = ufshcd_host_reset_and_restore(hba);
4171 spin_lock_irqsave(hba->host->host_lock, flags);
4173 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4174 ufshcd_clear_eh_in_progress(hba);
4175 spin_unlock_irqrestore(hba->host->host_lock, flags);
4178 dev_err(hba->dev, "%s: link recovery failed, err %d",
4183 EXPORT_SYMBOL_GPL(ufshcd_link_recovery);
4185 int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
4188 struct uic_command uic_cmd = {0};
4189 ktime_t start = ktime_get();
4191 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
4193 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
4194 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4195 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
4196 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4199 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
4202 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
4207 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_enter);
4209 int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
4211 struct uic_command uic_cmd = {0};
4213 ktime_t start = ktime_get();
4215 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
4217 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
4218 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4219 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
4220 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4223 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
4226 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
4228 hba->ufs_stats.last_hibern8_exit_tstamp = local_clock();
4229 hba->ufs_stats.hibern8_exit_cnt++;
4234 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_exit);
4236 void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit)
4238 unsigned long flags;
4239 bool update = false;
4241 if (!ufshcd_is_auto_hibern8_supported(hba))
4244 spin_lock_irqsave(hba->host->host_lock, flags);
4245 if (hba->ahit != ahit) {
4249 spin_unlock_irqrestore(hba->host->host_lock, flags);
4252 !pm_runtime_suspended(&hba->ufs_device_wlun->sdev_gendev)) {
4253 ufshcd_rpm_get_sync(hba);
4254 ufshcd_hold(hba, false);
4255 ufshcd_auto_hibern8_enable(hba);
4256 ufshcd_release(hba);
4257 ufshcd_rpm_put_sync(hba);
4260 EXPORT_SYMBOL_GPL(ufshcd_auto_hibern8_update);
4262 void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
4264 if (!ufshcd_is_auto_hibern8_supported(hba))
4267 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
4271 * ufshcd_init_pwr_info - setting the POR (power on reset)
4272 * values in hba power info
4273 * @hba: per-adapter instance
4275 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
4277 hba->pwr_info.gear_rx = UFS_PWM_G1;
4278 hba->pwr_info.gear_tx = UFS_PWM_G1;
4279 hba->pwr_info.lane_rx = 1;
4280 hba->pwr_info.lane_tx = 1;
4281 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
4282 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
4283 hba->pwr_info.hs_rate = 0;
4287 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
4288 * @hba: per-adapter instance
4290 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
4292 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
4294 if (hba->max_pwr_info.is_valid)
4297 if (hba->quirks & UFSHCD_QUIRK_HIBERN_FASTAUTO) {
4298 pwr_info->pwr_tx = FASTAUTO_MODE;
4299 pwr_info->pwr_rx = FASTAUTO_MODE;
4301 pwr_info->pwr_tx = FAST_MODE;
4302 pwr_info->pwr_rx = FAST_MODE;
4304 pwr_info->hs_rate = PA_HS_MODE_B;
4306 /* Get the connected lane count */
4307 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
4308 &pwr_info->lane_rx);
4309 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4310 &pwr_info->lane_tx);
4312 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
4313 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4321 * First, get the maximum gears of HS speed.
4322 * If a zero value, it means there is no HSGEAR capability.
4323 * Then, get the maximum gears of PWM speed.
4325 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4326 if (!pwr_info->gear_rx) {
4327 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4328 &pwr_info->gear_rx);
4329 if (!pwr_info->gear_rx) {
4330 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4331 __func__, pwr_info->gear_rx);
4334 pwr_info->pwr_rx = SLOW_MODE;
4337 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4338 &pwr_info->gear_tx);
4339 if (!pwr_info->gear_tx) {
4340 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4341 &pwr_info->gear_tx);
4342 if (!pwr_info->gear_tx) {
4343 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4344 __func__, pwr_info->gear_tx);
4347 pwr_info->pwr_tx = SLOW_MODE;
4350 hba->max_pwr_info.is_valid = true;
4354 static int ufshcd_change_power_mode(struct ufs_hba *hba,
4355 struct ufs_pa_layer_attr *pwr_mode)
4359 /* if already configured to the requested pwr_mode */
4360 if (!hba->force_pmc &&
4361 pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4362 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4363 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4364 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4365 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4366 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4367 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4368 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4373 * Configure attributes for power mode change with below.
4374 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4375 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4378 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4379 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4381 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4382 pwr_mode->pwr_rx == FAST_MODE)
4383 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), true);
4385 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), false);
4387 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4388 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4390 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4391 pwr_mode->pwr_tx == FAST_MODE)
4392 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), true);
4394 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), false);
4396 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4397 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4398 pwr_mode->pwr_rx == FAST_MODE ||
4399 pwr_mode->pwr_tx == FAST_MODE)
4400 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4403 if (!(hba->quirks & UFSHCD_QUIRK_SKIP_DEF_UNIPRO_TIMEOUT_SETTING)) {
4404 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0),
4405 DL_FC0ProtectionTimeOutVal_Default);
4406 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1),
4407 DL_TC0ReplayTimeOutVal_Default);
4408 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2),
4409 DL_AFC0ReqTimeOutVal_Default);
4410 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA3),
4411 DL_FC1ProtectionTimeOutVal_Default);
4412 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA4),
4413 DL_TC1ReplayTimeOutVal_Default);
4414 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA5),
4415 DL_AFC1ReqTimeOutVal_Default);
4417 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal),
4418 DL_FC0ProtectionTimeOutVal_Default);
4419 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal),
4420 DL_TC0ReplayTimeOutVal_Default);
4421 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal),
4422 DL_AFC0ReqTimeOutVal_Default);
4425 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4426 | pwr_mode->pwr_tx);
4430 "%s: power mode change failed %d\n", __func__, ret);
4432 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4435 memcpy(&hba->pwr_info, pwr_mode,
4436 sizeof(struct ufs_pa_layer_attr));
4443 * ufshcd_config_pwr_mode - configure a new power mode
4444 * @hba: per-adapter instance
4445 * @desired_pwr_mode: desired power configuration
4447 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4448 struct ufs_pa_layer_attr *desired_pwr_mode)
4450 struct ufs_pa_layer_attr final_params = { 0 };
4453 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4454 desired_pwr_mode, &final_params);
4457 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4459 ret = ufshcd_change_power_mode(hba, &final_params);
4463 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4466 * ufshcd_complete_dev_init() - checks device readiness
4467 * @hba: per-adapter instance
4469 * Set fDeviceInit flag and poll until device toggles it.
4471 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4474 bool flag_res = true;
4477 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4478 QUERY_FLAG_IDN_FDEVICEINIT, 0, NULL);
4481 "%s: setting fDeviceInit flag failed with error %d\n",
4486 /* Poll fDeviceInit flag to be cleared */
4487 timeout = ktime_add_ms(ktime_get(), FDEVICEINIT_COMPL_TIMEOUT);
4489 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4490 QUERY_FLAG_IDN_FDEVICEINIT, 0, &flag_res);
4493 usleep_range(500, 1000);
4494 } while (ktime_before(ktime_get(), timeout));
4498 "%s: reading fDeviceInit flag failed with error %d\n",
4500 } else if (flag_res) {
4502 "%s: fDeviceInit was not cleared by the device\n",
4511 * ufshcd_make_hba_operational - Make UFS controller operational
4512 * @hba: per adapter instance
4514 * To bring UFS host controller to operational state,
4515 * 1. Enable required interrupts
4516 * 2. Configure interrupt aggregation
4517 * 3. Program UTRL and UTMRL base address
4518 * 4. Configure run-stop-registers
4520 * Returns 0 on success, non-zero value on failure
4522 int ufshcd_make_hba_operational(struct ufs_hba *hba)
4527 /* Enable required interrupts */
4528 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4530 /* Configure interrupt aggregation */
4531 if (ufshcd_is_intr_aggr_allowed(hba))
4532 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4534 ufshcd_disable_intr_aggr(hba);
4536 /* Configure UTRL and UTMRL base address registers */
4537 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4538 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4539 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4540 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4541 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4542 REG_UTP_TASK_REQ_LIST_BASE_L);
4543 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4544 REG_UTP_TASK_REQ_LIST_BASE_H);
4547 * Make sure base address and interrupt setup are updated before
4548 * enabling the run/stop registers below.
4553 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4555 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4556 if (!(ufshcd_get_lists_status(reg))) {
4557 ufshcd_enable_run_stop_reg(hba);
4560 "Host controller not ready to process requests");
4566 EXPORT_SYMBOL_GPL(ufshcd_make_hba_operational);
4569 * ufshcd_hba_stop - Send controller to reset state
4570 * @hba: per adapter instance
4572 void ufshcd_hba_stop(struct ufs_hba *hba)
4574 unsigned long flags;
4578 * Obtain the host lock to prevent that the controller is disabled
4579 * while the UFS interrupt handler is active on another CPU.
4581 spin_lock_irqsave(hba->host->host_lock, flags);
4582 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4583 spin_unlock_irqrestore(hba->host->host_lock, flags);
4585 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4586 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4589 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4591 EXPORT_SYMBOL_GPL(ufshcd_hba_stop);
4594 * ufshcd_hba_execute_hce - initialize the controller
4595 * @hba: per adapter instance
4597 * The controller resets itself and controller firmware initialization
4598 * sequence kicks off. When controller is ready it will set
4599 * the Host Controller Enable bit to 1.
4601 * Returns 0 on success, non-zero value on failure
4603 static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
4605 int retry_outer = 3;
4609 if (ufshcd_is_hba_active(hba))
4610 /* change controller state to "reset state" */
4611 ufshcd_hba_stop(hba);
4613 /* UniPro link is disabled at this point */
4614 ufshcd_set_link_off(hba);
4616 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4618 /* start controller initialization sequence */
4619 ufshcd_hba_start(hba);
4622 * To initialize a UFS host controller HCE bit must be set to 1.
4623 * During initialization the HCE bit value changes from 1->0->1.
4624 * When the host controller completes initialization sequence
4625 * it sets the value of HCE bit to 1. The same HCE bit is read back
4626 * to check if the controller has completed initialization sequence.
4627 * So without this delay the value HCE = 1, set in the previous
4628 * instruction might be read back.
4629 * This delay can be changed based on the controller.
4631 ufshcd_delay_us(hba->vps->hba_enable_delay_us, 100);
4633 /* wait for the host controller to complete initialization */
4635 while (!ufshcd_is_hba_active(hba)) {
4640 "Controller enable failed\n");
4647 usleep_range(1000, 1100);
4650 /* enable UIC related interrupts */
4651 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4653 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4658 int ufshcd_hba_enable(struct ufs_hba *hba)
4662 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
4663 ufshcd_set_link_off(hba);
4664 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4666 /* enable UIC related interrupts */
4667 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4668 ret = ufshcd_dme_reset(hba);
4670 dev_err(hba->dev, "DME_RESET failed\n");
4674 ret = ufshcd_dme_enable(hba);
4676 dev_err(hba->dev, "Enabling DME failed\n");
4680 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4682 ret = ufshcd_hba_execute_hce(hba);
4687 EXPORT_SYMBOL_GPL(ufshcd_hba_enable);
4689 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4691 int tx_lanes = 0, i, err = 0;
4694 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4697 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4699 for (i = 0; i < tx_lanes; i++) {
4701 err = ufshcd_dme_set(hba,
4702 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4703 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4706 err = ufshcd_dme_peer_set(hba,
4707 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4708 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4711 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4712 __func__, peer, i, err);
4720 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4722 return ufshcd_disable_tx_lcc(hba, true);
4725 void ufshcd_update_evt_hist(struct ufs_hba *hba, u32 id, u32 val)
4727 struct ufs_event_hist *e;
4729 if (id >= UFS_EVT_CNT)
4732 e = &hba->ufs_stats.event[id];
4733 e->val[e->pos] = val;
4734 e->tstamp[e->pos] = local_clock();
4736 e->pos = (e->pos + 1) % UFS_EVENT_HIST_LENGTH;
4738 ufshcd_vops_event_notify(hba, id, &val);
4740 EXPORT_SYMBOL_GPL(ufshcd_update_evt_hist);
4743 * ufshcd_link_startup - Initialize unipro link startup
4744 * @hba: per adapter instance
4746 * Returns 0 for success, non-zero in case of failure
4748 static int ufshcd_link_startup(struct ufs_hba *hba)
4751 int retries = DME_LINKSTARTUP_RETRIES;
4752 bool link_startup_again = false;
4755 * If UFS device isn't active then we will have to issue link startup
4756 * 2 times to make sure the device state move to active.
4758 if (!ufshcd_is_ufs_dev_active(hba))
4759 link_startup_again = true;
4763 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4765 ret = ufshcd_dme_link_startup(hba);
4767 /* check if device is detected by inter-connect layer */
4768 if (!ret && !ufshcd_is_device_present(hba)) {
4769 ufshcd_update_evt_hist(hba,
4770 UFS_EVT_LINK_STARTUP_FAIL,
4772 dev_err(hba->dev, "%s: Device not present\n", __func__);
4778 * DME link lost indication is only received when link is up,
4779 * but we can't be sure if the link is up until link startup
4780 * succeeds. So reset the local Uni-Pro and try again.
4782 if (ret && retries && ufshcd_hba_enable(hba)) {
4783 ufshcd_update_evt_hist(hba,
4784 UFS_EVT_LINK_STARTUP_FAIL,
4788 } while (ret && retries--);
4791 /* failed to get the link up... retire */
4792 ufshcd_update_evt_hist(hba,
4793 UFS_EVT_LINK_STARTUP_FAIL,
4798 if (link_startup_again) {
4799 link_startup_again = false;
4800 retries = DME_LINKSTARTUP_RETRIES;
4804 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4805 ufshcd_init_pwr_info(hba);
4806 ufshcd_print_pwr_info(hba);
4808 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4809 ret = ufshcd_disable_device_tx_lcc(hba);
4814 /* Include any host controller configuration via UIC commands */
4815 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4819 /* Clear UECPA once due to LINERESET has happened during LINK_STARTUP */
4820 ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
4821 ret = ufshcd_make_hba_operational(hba);
4824 dev_err(hba->dev, "link startup failed %d\n", ret);
4825 ufshcd_print_host_state(hba);
4826 ufshcd_print_pwr_info(hba);
4827 ufshcd_print_evt_hist(hba);
4833 * ufshcd_verify_dev_init() - Verify device initialization
4834 * @hba: per-adapter instance
4836 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4837 * device Transport Protocol (UTP) layer is ready after a reset.
4838 * If the UTP layer at the device side is not initialized, it may
4839 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4840 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4842 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4847 ufshcd_hold(hba, false);
4848 mutex_lock(&hba->dev_cmd.lock);
4849 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4850 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4851 hba->nop_out_timeout);
4853 if (!err || err == -ETIMEDOUT)
4856 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4858 mutex_unlock(&hba->dev_cmd.lock);
4859 ufshcd_release(hba);
4862 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4867 * ufshcd_setup_links - associate link b/w device wlun and other luns
4868 * @sdev: pointer to SCSI device
4869 * @hba: pointer to ufs hba
4871 static void ufshcd_setup_links(struct ufs_hba *hba, struct scsi_device *sdev)
4873 struct device_link *link;
4876 * Device wlun is the supplier & rest of the luns are consumers.
4877 * This ensures that device wlun suspends after all other luns.
4879 if (hba->ufs_device_wlun) {
4880 link = device_link_add(&sdev->sdev_gendev,
4881 &hba->ufs_device_wlun->sdev_gendev,
4882 DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE);
4884 dev_err(&sdev->sdev_gendev, "Failed establishing link - %s\n",
4885 dev_name(&hba->ufs_device_wlun->sdev_gendev));
4889 /* Ignore REPORT_LUN wlun probing */
4890 if (hba->luns_avail == 1) {
4891 ufshcd_rpm_put(hba);
4896 * Device wlun is probed. The assumption is that WLUNs are
4897 * scanned before other LUNs.
4904 * ufshcd_lu_init - Initialize the relevant parameters of the LU
4905 * @hba: per-adapter instance
4906 * @sdev: pointer to SCSI device
4908 static void ufshcd_lu_init(struct ufs_hba *hba, struct scsi_device *sdev)
4910 int len = hba->desc_size[QUERY_DESC_IDN_UNIT];
4911 u8 lun = ufshcd_scsi_to_upiu_lun(sdev->lun);
4912 u8 lun_qdepth = hba->nutrs;
4916 desc_buf = kzalloc(len, GFP_KERNEL);
4920 ret = ufshcd_read_unit_desc_param(hba, lun, 0, desc_buf, len);
4922 if (ret == -EOPNOTSUPP)
4923 /* If LU doesn't support unit descriptor, its queue depth is set to 1 */
4929 if (desc_buf[UNIT_DESC_PARAM_LU_Q_DEPTH]) {
4931 * In per-LU queueing architecture, bLUQueueDepth will not be 0, then we will
4932 * use the smaller between UFSHCI CAP.NUTRS and UFS LU bLUQueueDepth
4934 lun_qdepth = min_t(int, desc_buf[UNIT_DESC_PARAM_LU_Q_DEPTH], hba->nutrs);
4937 * According to UFS device specification, the write protection mode is only supported by
4938 * normal LU, not supported by WLUN.
4940 if (hba->dev_info.f_power_on_wp_en && lun < hba->dev_info.max_lu_supported &&
4941 !hba->dev_info.is_lu_power_on_wp &&
4942 desc_buf[UNIT_DESC_PARAM_LU_WR_PROTECT] == UFS_LU_POWER_ON_WP)
4943 hba->dev_info.is_lu_power_on_wp = true;
4948 * For WLUNs that don't support unit descriptor, queue depth is set to 1. For LUs whose
4949 * bLUQueueDepth == 0, the queue depth is set to a maximum value that host can queue.
4951 dev_dbg(hba->dev, "Set LU %x queue depth %d\n", lun, lun_qdepth);
4952 scsi_change_queue_depth(sdev, lun_qdepth);
4956 * ufshcd_slave_alloc - handle initial SCSI device configurations
4957 * @sdev: pointer to SCSI device
4961 static int ufshcd_slave_alloc(struct scsi_device *sdev)
4963 struct ufs_hba *hba;
4965 hba = shost_priv(sdev->host);
4967 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
4968 sdev->use_10_for_ms = 1;
4970 /* DBD field should be set to 1 in mode sense(10) */
4971 sdev->set_dbd_for_ms = 1;
4973 /* allow SCSI layer to restart the device in case of errors */
4974 sdev->allow_restart = 1;
4976 /* REPORT SUPPORTED OPERATION CODES is not supported */
4977 sdev->no_report_opcodes = 1;
4979 /* WRITE_SAME command is not supported */
4980 sdev->no_write_same = 1;
4982 ufshcd_lu_init(hba, sdev);
4984 ufshcd_setup_links(hba, sdev);
4990 * ufshcd_change_queue_depth - change queue depth
4991 * @sdev: pointer to SCSI device
4992 * @depth: required depth to set
4994 * Change queue depth and make sure the max. limits are not crossed.
4996 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
4998 return scsi_change_queue_depth(sdev, min(depth, sdev->host->can_queue));
5001 static void ufshcd_hpb_destroy(struct ufs_hba *hba, struct scsi_device *sdev)
5003 /* skip well-known LU */
5004 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) ||
5005 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba))
5008 ufshpb_destroy_lu(hba, sdev);
5011 static void ufshcd_hpb_configure(struct ufs_hba *hba, struct scsi_device *sdev)
5013 /* skip well-known LU */
5014 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) ||
5015 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba))
5018 ufshpb_init_hpb_lu(hba, sdev);
5022 * ufshcd_slave_configure - adjust SCSI device configurations
5023 * @sdev: pointer to SCSI device
5025 static int ufshcd_slave_configure(struct scsi_device *sdev)
5027 struct ufs_hba *hba = shost_priv(sdev->host);
5028 struct request_queue *q = sdev->request_queue;
5030 ufshcd_hpb_configure(hba, sdev);
5032 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
5033 if (hba->quirks & UFSHCD_QUIRK_ALIGN_SG_WITH_PAGE_SIZE)
5034 blk_queue_update_dma_alignment(q, PAGE_SIZE - 1);
5036 * Block runtime-pm until all consumers are added.
5037 * Refer ufshcd_setup_links().
5039 if (is_device_wlun(sdev))
5040 pm_runtime_get_noresume(&sdev->sdev_gendev);
5041 else if (ufshcd_is_rpm_autosuspend_allowed(hba))
5042 sdev->rpm_autosuspend = 1;
5044 * Do not print messages during runtime PM to avoid never-ending cycles
5045 * of messages written back to storage by user space causing runtime
5046 * resume, causing more messages and so on.
5048 sdev->silence_suspend = 1;
5050 ufshcd_crypto_register(hba, q);
5056 * ufshcd_slave_destroy - remove SCSI device configurations
5057 * @sdev: pointer to SCSI device
5059 static void ufshcd_slave_destroy(struct scsi_device *sdev)
5061 struct ufs_hba *hba;
5062 unsigned long flags;
5064 hba = shost_priv(sdev->host);
5066 ufshcd_hpb_destroy(hba, sdev);
5068 /* Drop the reference as it won't be needed anymore */
5069 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
5070 spin_lock_irqsave(hba->host->host_lock, flags);
5071 hba->ufs_device_wlun = NULL;
5072 spin_unlock_irqrestore(hba->host->host_lock, flags);
5073 } else if (hba->ufs_device_wlun) {
5074 struct device *supplier = NULL;
5076 /* Ensure UFS Device WLUN exists and does not disappear */
5077 spin_lock_irqsave(hba->host->host_lock, flags);
5078 if (hba->ufs_device_wlun) {
5079 supplier = &hba->ufs_device_wlun->sdev_gendev;
5080 get_device(supplier);
5082 spin_unlock_irqrestore(hba->host->host_lock, flags);
5086 * If a LUN fails to probe (e.g. absent BOOT WLUN), the
5087 * device will not have been registered but can still
5088 * have a device link holding a reference to the device.
5090 device_link_remove(&sdev->sdev_gendev, supplier);
5091 put_device(supplier);
5097 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
5098 * @lrbp: pointer to local reference block of completed command
5099 * @scsi_status: SCSI command status
5101 * Returns value base on SCSI command status
5104 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
5108 switch (scsi_status) {
5109 case SAM_STAT_CHECK_CONDITION:
5110 ufshcd_copy_sense_data(lrbp);
5113 result |= DID_OK << 16 | scsi_status;
5115 case SAM_STAT_TASK_SET_FULL:
5117 case SAM_STAT_TASK_ABORTED:
5118 ufshcd_copy_sense_data(lrbp);
5119 result |= scsi_status;
5122 result |= DID_ERROR << 16;
5124 } /* end of switch */
5130 * ufshcd_transfer_rsp_status - Get overall status of the response
5131 * @hba: per adapter instance
5132 * @lrbp: pointer to local reference block of completed command
5134 * Returns result of the command to notify SCSI midlayer
5137 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
5143 /* overall command status of utrd */
5144 ocs = ufshcd_get_tr_ocs(lrbp);
5146 if (hba->quirks & UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR) {
5147 if (be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_1) &
5148 MASK_RSP_UPIU_RESULT)
5154 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
5155 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
5157 case UPIU_TRANSACTION_RESPONSE:
5159 * get the response UPIU result to extract
5160 * the SCSI command status
5162 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
5165 * get the result based on SCSI status response
5166 * to notify the SCSI midlayer of the command status
5168 scsi_status = result & MASK_SCSI_STATUS;
5169 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
5172 * Currently we are only supporting BKOPs exception
5173 * events hence we can ignore BKOPs exception event
5174 * during power management callbacks. BKOPs exception
5175 * event is not expected to be raised in runtime suspend
5176 * callback as it allows the urgent bkops.
5177 * During system suspend, we are anyway forcefully
5178 * disabling the bkops and if urgent bkops is needed
5179 * it will be enabled on system resume. Long term
5180 * solution could be to abort the system suspend if
5181 * UFS device needs urgent BKOPs.
5183 if (!hba->pm_op_in_progress &&
5184 !ufshcd_eh_in_progress(hba) &&
5185 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
5186 /* Flushed in suspend */
5187 schedule_work(&hba->eeh_work);
5189 if (scsi_status == SAM_STAT_GOOD)
5190 ufshpb_rsp_upiu(hba, lrbp);
5192 case UPIU_TRANSACTION_REJECT_UPIU:
5193 /* TODO: handle Reject UPIU Response */
5194 result = DID_ERROR << 16;
5196 "Reject UPIU not fully implemented\n");
5200 "Unexpected request response code = %x\n",
5202 result = DID_ERROR << 16;
5207 result |= DID_ABORT << 16;
5209 case OCS_INVALID_COMMAND_STATUS:
5210 result |= DID_REQUEUE << 16;
5212 case OCS_INVALID_CMD_TABLE_ATTR:
5213 case OCS_INVALID_PRDT_ATTR:
5214 case OCS_MISMATCH_DATA_BUF_SIZE:
5215 case OCS_MISMATCH_RESP_UPIU_SIZE:
5216 case OCS_PEER_COMM_FAILURE:
5217 case OCS_FATAL_ERROR:
5218 case OCS_DEVICE_FATAL_ERROR:
5219 case OCS_INVALID_CRYPTO_CONFIG:
5220 case OCS_GENERAL_CRYPTO_ERROR:
5222 result |= DID_ERROR << 16;
5224 "OCS error from controller = %x for tag %d\n",
5225 ocs, lrbp->task_tag);
5226 ufshcd_print_evt_hist(hba);
5227 ufshcd_print_host_state(hba);
5229 } /* end of switch */
5231 if ((host_byte(result) != DID_OK) &&
5232 (host_byte(result) != DID_REQUEUE) && !hba->silence_err_logs)
5233 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true);
5237 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
5240 if (!ufshcd_is_auto_hibern8_supported(hba) ||
5241 !ufshcd_is_auto_hibern8_enabled(hba))
5244 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
5247 if (hba->active_uic_cmd &&
5248 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
5249 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
5256 * ufshcd_uic_cmd_compl - handle completion of uic command
5257 * @hba: per adapter instance
5258 * @intr_status: interrupt status generated by the controller
5261 * IRQ_HANDLED - If interrupt is valid
5262 * IRQ_NONE - If invalid interrupt
5264 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
5266 irqreturn_t retval = IRQ_NONE;
5268 spin_lock(hba->host->host_lock);
5269 if (ufshcd_is_auto_hibern8_error(hba, intr_status))
5270 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
5272 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
5273 hba->active_uic_cmd->argument2 |=
5274 ufshcd_get_uic_cmd_result(hba);
5275 hba->active_uic_cmd->argument3 =
5276 ufshcd_get_dme_attr_val(hba);
5277 if (!hba->uic_async_done)
5278 hba->active_uic_cmd->cmd_active = 0;
5279 complete(&hba->active_uic_cmd->done);
5280 retval = IRQ_HANDLED;
5283 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done) {
5284 hba->active_uic_cmd->cmd_active = 0;
5285 complete(hba->uic_async_done);
5286 retval = IRQ_HANDLED;
5289 if (retval == IRQ_HANDLED)
5290 ufshcd_add_uic_command_trace(hba, hba->active_uic_cmd,
5292 spin_unlock(hba->host->host_lock);
5296 /* Release the resources allocated for processing a SCSI command. */
5297 static void ufshcd_release_scsi_cmd(struct ufs_hba *hba,
5298 struct ufshcd_lrb *lrbp)
5300 struct scsi_cmnd *cmd = lrbp->cmd;
5302 scsi_dma_unmap(cmd);
5303 lrbp->cmd = NULL; /* Mark the command as completed. */
5304 ufshcd_release(hba);
5305 ufshcd_clk_scaling_update_busy(hba);
5309 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
5310 * @hba: per adapter instance
5311 * @completed_reqs: bitmask that indicates which requests to complete
5313 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
5314 unsigned long completed_reqs)
5316 struct ufshcd_lrb *lrbp;
5317 struct scsi_cmnd *cmd;
5320 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
5321 lrbp = &hba->lrb[index];
5322 lrbp->compl_time_stamp = ktime_get();
5323 lrbp->compl_time_stamp_local_clock = local_clock();
5326 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
5327 ufshcd_update_monitor(hba, lrbp);
5328 ufshcd_add_command_trace(hba, index, UFS_CMD_COMP);
5329 cmd->result = ufshcd_transfer_rsp_status(hba, lrbp);
5330 ufshcd_release_scsi_cmd(hba, lrbp);
5331 /* Do not touch lrbp after scsi done */
5333 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
5334 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
5335 if (hba->dev_cmd.complete) {
5336 ufshcd_add_command_trace(hba, index,
5338 complete(hba->dev_cmd.complete);
5339 ufshcd_clk_scaling_update_busy(hba);
5345 /* Any value that is not an existing queue number is fine for this constant. */
5347 UFSHCD_POLL_FROM_INTERRUPT_CONTEXT = -1
5350 static void ufshcd_clear_polled(struct ufs_hba *hba,
5351 unsigned long *completed_reqs)
5355 for_each_set_bit(tag, completed_reqs, hba->nutrs) {
5356 struct scsi_cmnd *cmd = hba->lrb[tag].cmd;
5360 if (scsi_cmd_to_rq(cmd)->cmd_flags & REQ_POLLED)
5361 __clear_bit(tag, completed_reqs);
5366 * Returns > 0 if one or more commands have been completed or 0 if no
5367 * requests have been completed.
5369 static int ufshcd_poll(struct Scsi_Host *shost, unsigned int queue_num)
5371 struct ufs_hba *hba = shost_priv(shost);
5372 unsigned long completed_reqs, flags;
5375 spin_lock_irqsave(&hba->outstanding_lock, flags);
5376 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5377 completed_reqs = ~tr_doorbell & hba->outstanding_reqs;
5378 WARN_ONCE(completed_reqs & ~hba->outstanding_reqs,
5379 "completed: %#lx; outstanding: %#lx\n", completed_reqs,
5380 hba->outstanding_reqs);
5381 if (queue_num == UFSHCD_POLL_FROM_INTERRUPT_CONTEXT) {
5382 /* Do not complete polled requests from interrupt context. */
5383 ufshcd_clear_polled(hba, &completed_reqs);
5385 hba->outstanding_reqs &= ~completed_reqs;
5386 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
5389 __ufshcd_transfer_req_compl(hba, completed_reqs);
5391 return completed_reqs != 0;
5395 * ufshcd_transfer_req_compl - handle SCSI and query command completion
5396 * @hba: per adapter instance
5399 * IRQ_HANDLED - If interrupt is valid
5400 * IRQ_NONE - If invalid interrupt
5402 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba)
5404 /* Resetting interrupt aggregation counters first and reading the
5405 * DOOR_BELL afterward allows us to handle all the completed requests.
5406 * In order to prevent other interrupts starvation the DB is read once
5407 * after reset. The down side of this solution is the possibility of
5408 * false interrupt if device completes another request after resetting
5409 * aggregation and before reading the DB.
5411 if (ufshcd_is_intr_aggr_allowed(hba) &&
5412 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
5413 ufshcd_reset_intr_aggr(hba);
5415 if (ufs_fail_completion())
5419 * Ignore the ufshcd_poll() return value and return IRQ_HANDLED since we
5420 * do not want polling to trigger spurious interrupt complaints.
5422 ufshcd_poll(hba->host, UFSHCD_POLL_FROM_INTERRUPT_CONTEXT);
5427 int __ufshcd_write_ee_control(struct ufs_hba *hba, u32 ee_ctrl_mask)
5429 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5430 QUERY_ATTR_IDN_EE_CONTROL, 0, 0,
5434 int ufshcd_write_ee_control(struct ufs_hba *hba)
5438 mutex_lock(&hba->ee_ctrl_mutex);
5439 err = __ufshcd_write_ee_control(hba, hba->ee_ctrl_mask);
5440 mutex_unlock(&hba->ee_ctrl_mutex);
5442 dev_err(hba->dev, "%s: failed to write ee control %d\n",
5447 int ufshcd_update_ee_control(struct ufs_hba *hba, u16 *mask,
5448 const u16 *other_mask, u16 set, u16 clr)
5450 u16 new_mask, ee_ctrl_mask;
5453 mutex_lock(&hba->ee_ctrl_mutex);
5454 new_mask = (*mask & ~clr) | set;
5455 ee_ctrl_mask = new_mask | *other_mask;
5456 if (ee_ctrl_mask != hba->ee_ctrl_mask)
5457 err = __ufshcd_write_ee_control(hba, ee_ctrl_mask);
5458 /* Still need to update 'mask' even if 'ee_ctrl_mask' was unchanged */
5460 hba->ee_ctrl_mask = ee_ctrl_mask;
5463 mutex_unlock(&hba->ee_ctrl_mutex);
5468 * ufshcd_disable_ee - disable exception event
5469 * @hba: per-adapter instance
5470 * @mask: exception event to disable
5472 * Disables exception event in the device so that the EVENT_ALERT
5475 * Returns zero on success, non-zero error value on failure.
5477 static inline int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
5479 return ufshcd_update_ee_drv_mask(hba, 0, mask);
5483 * ufshcd_enable_ee - enable exception event
5484 * @hba: per-adapter instance
5485 * @mask: exception event to enable
5487 * Enable corresponding exception event in the device to allow
5488 * device to alert host in critical scenarios.
5490 * Returns zero on success, non-zero error value on failure.
5492 static inline int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
5494 return ufshcd_update_ee_drv_mask(hba, mask, 0);
5498 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
5499 * @hba: per-adapter instance
5501 * Allow device to manage background operations on its own. Enabling
5502 * this might lead to inconsistent latencies during normal data transfers
5503 * as the device is allowed to manage its own way of handling background
5506 * Returns zero on success, non-zero on failure.
5508 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
5512 if (hba->auto_bkops_enabled)
5515 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5516 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5518 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
5523 hba->auto_bkops_enabled = true;
5524 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
5526 /* No need of URGENT_BKOPS exception from the device */
5527 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5529 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5536 * ufshcd_disable_auto_bkops - block device in doing background operations
5537 * @hba: per-adapter instance
5539 * Disabling background operations improves command response latency but
5540 * has drawback of device moving into critical state where the device is
5541 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5542 * host is idle so that BKOPS are managed effectively without any negative
5545 * Returns zero on success, non-zero on failure.
5547 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5551 if (!hba->auto_bkops_enabled)
5555 * If host assisted BKOPs is to be enabled, make sure
5556 * urgent bkops exception is allowed.
5558 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5560 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5565 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5566 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5568 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5570 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5574 hba->auto_bkops_enabled = false;
5575 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
5576 hba->is_urgent_bkops_lvl_checked = false;
5582 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5583 * @hba: per adapter instance
5585 * After a device reset the device may toggle the BKOPS_EN flag
5586 * to default value. The s/w tracking variables should be updated
5587 * as well. This function would change the auto-bkops state based on
5588 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5590 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5592 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5593 hba->auto_bkops_enabled = false;
5594 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5595 ufshcd_enable_auto_bkops(hba);
5597 hba->auto_bkops_enabled = true;
5598 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5599 ufshcd_disable_auto_bkops(hba);
5601 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
5602 hba->is_urgent_bkops_lvl_checked = false;
5605 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5607 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5608 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5612 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5613 * @hba: per-adapter instance
5614 * @status: bkops_status value
5616 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5617 * flag in the device to permit background operations if the device
5618 * bkops_status is greater than or equal to "status" argument passed to
5619 * this function, disable otherwise.
5621 * Returns 0 for success, non-zero in case of failure.
5623 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5624 * to know whether auto bkops is enabled or disabled after this function
5625 * returns control to it.
5627 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5628 enum bkops_status status)
5631 u32 curr_status = 0;
5633 err = ufshcd_get_bkops_status(hba, &curr_status);
5635 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5638 } else if (curr_status > BKOPS_STATUS_MAX) {
5639 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5640 __func__, curr_status);
5645 if (curr_status >= status)
5646 err = ufshcd_enable_auto_bkops(hba);
5648 err = ufshcd_disable_auto_bkops(hba);
5654 * ufshcd_urgent_bkops - handle urgent bkops exception event
5655 * @hba: per-adapter instance
5657 * Enable fBackgroundOpsEn flag in the device to permit background
5660 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5661 * and negative error value for any other failure.
5663 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5665 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5668 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5670 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5671 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5674 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5677 u32 curr_status = 0;
5679 if (hba->is_urgent_bkops_lvl_checked)
5680 goto enable_auto_bkops;
5682 err = ufshcd_get_bkops_status(hba, &curr_status);
5684 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5690 * We are seeing that some devices are raising the urgent bkops
5691 * exception events even when BKOPS status doesn't indicate performace
5692 * impacted or critical. Handle these device by determining their urgent
5693 * bkops status at runtime.
5695 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5696 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5697 __func__, curr_status);
5698 /* update the current status as the urgent bkops level */
5699 hba->urgent_bkops_lvl = curr_status;
5700 hba->is_urgent_bkops_lvl_checked = true;
5704 err = ufshcd_enable_auto_bkops(hba);
5707 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5711 static void ufshcd_temp_exception_event_handler(struct ufs_hba *hba, u16 status)
5715 if (ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5716 QUERY_ATTR_IDN_CASE_ROUGH_TEMP, 0, 0, &value))
5719 dev_info(hba->dev, "exception Tcase %d\n", value - 80);
5721 ufs_hwmon_notify_event(hba, status & MASK_EE_URGENT_TEMP);
5724 * A placeholder for the platform vendors to add whatever additional
5729 static int __ufshcd_wb_toggle(struct ufs_hba *hba, bool set, enum flag_idn idn)
5732 enum query_opcode opcode = set ? UPIU_QUERY_OPCODE_SET_FLAG :
5733 UPIU_QUERY_OPCODE_CLEAR_FLAG;
5735 index = ufshcd_wb_get_query_index(hba);
5736 return ufshcd_query_flag_retry(hba, opcode, idn, index, NULL);
5739 int ufshcd_wb_toggle(struct ufs_hba *hba, bool enable)
5743 if (!ufshcd_is_wb_allowed(hba) ||
5744 hba->dev_info.wb_enabled == enable)
5747 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_EN);
5749 dev_err(hba->dev, "%s: Write Booster %s failed %d\n",
5750 __func__, enable ? "enabling" : "disabling", ret);
5754 hba->dev_info.wb_enabled = enable;
5755 dev_dbg(hba->dev, "%s: Write Booster %s\n",
5756 __func__, enable ? "enabled" : "disabled");
5761 static void ufshcd_wb_toggle_buf_flush_during_h8(struct ufs_hba *hba,
5766 ret = __ufshcd_wb_toggle(hba, enable,
5767 QUERY_FLAG_IDN_WB_BUFF_FLUSH_DURING_HIBERN8);
5769 dev_err(hba->dev, "%s: WB-Buf Flush during H8 %s failed %d\n",
5770 __func__, enable ? "enabling" : "disabling", ret);
5773 dev_dbg(hba->dev, "%s: WB-Buf Flush during H8 %s\n",
5774 __func__, enable ? "enabled" : "disabled");
5777 int ufshcd_wb_toggle_buf_flush(struct ufs_hba *hba, bool enable)
5781 if (!ufshcd_is_wb_allowed(hba) ||
5782 hba->dev_info.wb_buf_flush_enabled == enable)
5785 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN);
5787 dev_err(hba->dev, "%s: WB-Buf Flush %s failed %d\n",
5788 __func__, enable ? "enabling" : "disabling", ret);
5792 hba->dev_info.wb_buf_flush_enabled = enable;
5793 dev_dbg(hba->dev, "%s: WB-Buf Flush %s\n",
5794 __func__, enable ? "enabled" : "disabled");
5799 static bool ufshcd_wb_presrv_usrspc_keep_vcc_on(struct ufs_hba *hba,
5806 index = ufshcd_wb_get_query_index(hba);
5807 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5808 QUERY_ATTR_IDN_CURR_WB_BUFF_SIZE,
5809 index, 0, &cur_buf);
5811 dev_err(hba->dev, "%s: dCurWriteBoosterBufferSize read failed %d\n",
5817 dev_info(hba->dev, "dCurWBBuf: %d WB disabled until free-space is available\n",
5821 /* Let it continue to flush when available buffer exceeds threshold */
5822 return avail_buf < hba->vps->wb_flush_threshold;
5825 static void ufshcd_wb_force_disable(struct ufs_hba *hba)
5827 if (ufshcd_is_wb_buf_flush_allowed(hba))
5828 ufshcd_wb_toggle_buf_flush(hba, false);
5830 ufshcd_wb_toggle_buf_flush_during_h8(hba, false);
5831 ufshcd_wb_toggle(hba, false);
5832 hba->caps &= ~UFSHCD_CAP_WB_EN;
5834 dev_info(hba->dev, "%s: WB force disabled\n", __func__);
5837 static bool ufshcd_is_wb_buf_lifetime_available(struct ufs_hba *hba)
5843 index = ufshcd_wb_get_query_index(hba);
5844 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5845 QUERY_ATTR_IDN_WB_BUFF_LIFE_TIME_EST,
5846 index, 0, &lifetime);
5849 "%s: bWriteBoosterBufferLifeTimeEst read failed %d\n",
5854 if (lifetime == UFS_WB_EXCEED_LIFETIME) {
5855 dev_err(hba->dev, "%s: WB buf lifetime is exhausted 0x%02X\n",
5856 __func__, lifetime);
5860 dev_dbg(hba->dev, "%s: WB buf lifetime is 0x%02X\n",
5861 __func__, lifetime);
5866 static bool ufshcd_wb_need_flush(struct ufs_hba *hba)
5872 if (!ufshcd_is_wb_allowed(hba))
5875 if (!ufshcd_is_wb_buf_lifetime_available(hba)) {
5876 ufshcd_wb_force_disable(hba);
5881 * The ufs device needs the vcc to be ON to flush.
5882 * With user-space reduction enabled, it's enough to enable flush
5883 * by checking only the available buffer. The threshold
5884 * defined here is > 90% full.
5885 * With user-space preserved enabled, the current-buffer
5886 * should be checked too because the wb buffer size can reduce
5887 * when disk tends to be full. This info is provided by current
5888 * buffer (dCurrentWriteBoosterBufferSize). There's no point in
5889 * keeping vcc on when current buffer is empty.
5891 index = ufshcd_wb_get_query_index(hba);
5892 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5893 QUERY_ATTR_IDN_AVAIL_WB_BUFF_SIZE,
5894 index, 0, &avail_buf);
5896 dev_warn(hba->dev, "%s: dAvailableWriteBoosterBufferSize read failed %d\n",
5901 if (!hba->dev_info.b_presrv_uspc_en)
5902 return avail_buf <= UFS_WB_BUF_REMAIN_PERCENT(10);
5904 return ufshcd_wb_presrv_usrspc_keep_vcc_on(hba, avail_buf);
5907 static void ufshcd_rpm_dev_flush_recheck_work(struct work_struct *work)
5909 struct ufs_hba *hba = container_of(to_delayed_work(work),
5911 rpm_dev_flush_recheck_work);
5913 * To prevent unnecessary VCC power drain after device finishes
5914 * WriteBooster buffer flush or Auto BKOPs, force runtime resume
5915 * after a certain delay to recheck the threshold by next runtime
5918 ufshcd_rpm_get_sync(hba);
5919 ufshcd_rpm_put_sync(hba);
5923 * ufshcd_exception_event_handler - handle exceptions raised by device
5924 * @work: pointer to work data
5926 * Read bExceptionEventStatus attribute from the device and handle the
5927 * exception event accordingly.
5929 static void ufshcd_exception_event_handler(struct work_struct *work)
5931 struct ufs_hba *hba;
5934 hba = container_of(work, struct ufs_hba, eeh_work);
5936 ufshcd_scsi_block_requests(hba);
5937 err = ufshcd_get_ee_status(hba, &status);
5939 dev_err(hba->dev, "%s: failed to get exception status %d\n",
5944 trace_ufshcd_exception_event(dev_name(hba->dev), status);
5946 if (status & hba->ee_drv_mask & MASK_EE_URGENT_BKOPS)
5947 ufshcd_bkops_exception_event_handler(hba);
5949 if (status & hba->ee_drv_mask & MASK_EE_URGENT_TEMP)
5950 ufshcd_temp_exception_event_handler(hba, status);
5952 ufs_debugfs_exception_event(hba, status);
5954 ufshcd_scsi_unblock_requests(hba);
5957 /* Complete requests that have door-bell cleared */
5958 static void ufshcd_complete_requests(struct ufs_hba *hba)
5960 ufshcd_transfer_req_compl(hba);
5961 ufshcd_tmc_handler(hba);
5965 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
5966 * to recover from the DL NAC errors or not.
5967 * @hba: per-adapter instance
5969 * Returns true if error handling is required, false otherwise
5971 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
5973 unsigned long flags;
5974 bool err_handling = true;
5976 spin_lock_irqsave(hba->host->host_lock, flags);
5978 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
5979 * device fatal error and/or DL NAC & REPLAY timeout errors.
5981 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
5984 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
5985 ((hba->saved_err & UIC_ERROR) &&
5986 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
5989 if ((hba->saved_err & UIC_ERROR) &&
5990 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
5993 * wait for 50ms to see if we can get any other errors or not.
5995 spin_unlock_irqrestore(hba->host->host_lock, flags);
5997 spin_lock_irqsave(hba->host->host_lock, flags);
6000 * now check if we have got any other severe errors other than
6003 if ((hba->saved_err & INT_FATAL_ERRORS) ||
6004 ((hba->saved_err & UIC_ERROR) &&
6005 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
6009 * As DL NAC is the only error received so far, send out NOP
6010 * command to confirm if link is still active or not.
6011 * - If we don't get any response then do error recovery.
6012 * - If we get response then clear the DL NAC error bit.
6015 spin_unlock_irqrestore(hba->host->host_lock, flags);
6016 err = ufshcd_verify_dev_init(hba);
6017 spin_lock_irqsave(hba->host->host_lock, flags);
6022 /* Link seems to be alive hence ignore the DL NAC errors */
6023 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
6024 hba->saved_err &= ~UIC_ERROR;
6025 /* clear NAC error */
6026 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6027 if (!hba->saved_uic_err)
6028 err_handling = false;
6031 spin_unlock_irqrestore(hba->host->host_lock, flags);
6032 return err_handling;
6035 /* host lock must be held before calling this func */
6036 static inline bool ufshcd_is_saved_err_fatal(struct ufs_hba *hba)
6038 return (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR) ||
6039 (hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK));
6042 void ufshcd_schedule_eh_work(struct ufs_hba *hba)
6044 lockdep_assert_held(hba->host->host_lock);
6046 /* handle fatal errors only when link is not in error state */
6047 if (hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6048 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6049 ufshcd_is_saved_err_fatal(hba))
6050 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_FATAL;
6052 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_NON_FATAL;
6053 queue_work(hba->eh_wq, &hba->eh_work);
6057 static void ufshcd_force_error_recovery(struct ufs_hba *hba)
6059 spin_lock_irq(hba->host->host_lock);
6060 hba->force_reset = true;
6061 ufshcd_schedule_eh_work(hba);
6062 spin_unlock_irq(hba->host->host_lock);
6065 static void ufshcd_clk_scaling_allow(struct ufs_hba *hba, bool allow)
6067 mutex_lock(&hba->wb_mutex);
6068 down_write(&hba->clk_scaling_lock);
6069 hba->clk_scaling.is_allowed = allow;
6070 up_write(&hba->clk_scaling_lock);
6071 mutex_unlock(&hba->wb_mutex);
6074 static void ufshcd_clk_scaling_suspend(struct ufs_hba *hba, bool suspend)
6077 if (hba->clk_scaling.is_enabled)
6078 ufshcd_suspend_clkscaling(hba);
6079 ufshcd_clk_scaling_allow(hba, false);
6081 ufshcd_clk_scaling_allow(hba, true);
6082 if (hba->clk_scaling.is_enabled)
6083 ufshcd_resume_clkscaling(hba);
6087 static void ufshcd_err_handling_prepare(struct ufs_hba *hba)
6089 ufshcd_rpm_get_sync(hba);
6090 if (pm_runtime_status_suspended(&hba->ufs_device_wlun->sdev_gendev) ||
6091 hba->is_sys_suspended) {
6092 enum ufs_pm_op pm_op;
6095 * Don't assume anything of resume, if
6096 * resume fails, irq and clocks can be OFF, and powers
6097 * can be OFF or in LPM.
6099 ufshcd_setup_hba_vreg(hba, true);
6100 ufshcd_enable_irq(hba);
6101 ufshcd_setup_vreg(hba, true);
6102 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
6103 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
6104 ufshcd_hold(hba, false);
6105 if (!ufshcd_is_clkgating_allowed(hba))
6106 ufshcd_setup_clocks(hba, true);
6107 ufshcd_release(hba);
6108 pm_op = hba->is_sys_suspended ? UFS_SYSTEM_PM : UFS_RUNTIME_PM;
6109 ufshcd_vops_resume(hba, pm_op);
6111 ufshcd_hold(hba, false);
6112 if (ufshcd_is_clkscaling_supported(hba) &&
6113 hba->clk_scaling.is_enabled)
6114 ufshcd_suspend_clkscaling(hba);
6115 ufshcd_clk_scaling_allow(hba, false);
6117 ufshcd_scsi_block_requests(hba);
6118 /* Drain ufshcd_queuecommand() */
6120 cancel_work_sync(&hba->eeh_work);
6123 static void ufshcd_err_handling_unprepare(struct ufs_hba *hba)
6125 ufshcd_scsi_unblock_requests(hba);
6126 ufshcd_release(hba);
6127 if (ufshcd_is_clkscaling_supported(hba))
6128 ufshcd_clk_scaling_suspend(hba, false);
6129 ufshcd_rpm_put(hba);
6132 static inline bool ufshcd_err_handling_should_stop(struct ufs_hba *hba)
6134 return (!hba->is_powered || hba->shutting_down ||
6135 !hba->ufs_device_wlun ||
6136 hba->ufshcd_state == UFSHCD_STATE_ERROR ||
6137 (!(hba->saved_err || hba->saved_uic_err || hba->force_reset ||
6138 ufshcd_is_link_broken(hba))));
6142 static void ufshcd_recover_pm_error(struct ufs_hba *hba)
6144 struct Scsi_Host *shost = hba->host;
6145 struct scsi_device *sdev;
6146 struct request_queue *q;
6149 hba->is_sys_suspended = false;
6151 * Set RPM status of wlun device to RPM_ACTIVE,
6152 * this also clears its runtime error.
6154 ret = pm_runtime_set_active(&hba->ufs_device_wlun->sdev_gendev);
6156 /* hba device might have a runtime error otherwise */
6158 ret = pm_runtime_set_active(hba->dev);
6160 * If wlun device had runtime error, we also need to resume those
6161 * consumer scsi devices in case any of them has failed to be
6162 * resumed due to supplier runtime resume failure. This is to unblock
6163 * blk_queue_enter in case there are bios waiting inside it.
6166 shost_for_each_device(sdev, shost) {
6167 q = sdev->request_queue;
6168 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
6169 q->rpm_status == RPM_SUSPENDING))
6170 pm_request_resume(q->dev);
6175 static inline void ufshcd_recover_pm_error(struct ufs_hba *hba)
6180 static bool ufshcd_is_pwr_mode_restore_needed(struct ufs_hba *hba)
6182 struct ufs_pa_layer_attr *pwr_info = &hba->pwr_info;
6185 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode);
6187 if (pwr_info->pwr_rx != ((mode >> PWRMODE_RX_OFFSET) & PWRMODE_MASK))
6190 if (pwr_info->pwr_tx != (mode & PWRMODE_MASK))
6196 static bool ufshcd_abort_all(struct ufs_hba *hba)
6198 bool needs_reset = false;
6201 /* Clear pending transfer requests */
6202 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
6203 ret = ufshcd_try_to_abort_task(hba, tag);
6204 dev_err(hba->dev, "Aborting tag %d / CDB %#02x %s\n", tag,
6205 hba->lrb[tag].cmd ? hba->lrb[tag].cmd->cmnd[0] : -1,
6206 ret ? "failed" : "succeeded");
6213 /* Clear pending task management requests */
6214 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
6215 if (ufshcd_clear_tm_cmd(hba, tag)) {
6222 /* Complete the requests that are cleared by s/w */
6223 ufshcd_complete_requests(hba);
6229 * ufshcd_err_handler - handle UFS errors that require s/w attention
6230 * @work: pointer to work structure
6232 static void ufshcd_err_handler(struct work_struct *work)
6234 int retries = MAX_ERR_HANDLER_RETRIES;
6235 struct ufs_hba *hba;
6236 unsigned long flags;
6241 hba = container_of(work, struct ufs_hba, eh_work);
6244 "%s started; HBA state %s; powered %d; shutting down %d; saved_err = %d; saved_uic_err = %d; force_reset = %d%s\n",
6245 __func__, ufshcd_state_name[hba->ufshcd_state],
6246 hba->is_powered, hba->shutting_down, hba->saved_err,
6247 hba->saved_uic_err, hba->force_reset,
6248 ufshcd_is_link_broken(hba) ? "; link is broken" : "");
6250 down(&hba->host_sem);
6251 spin_lock_irqsave(hba->host->host_lock, flags);
6252 if (ufshcd_err_handling_should_stop(hba)) {
6253 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6254 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6255 spin_unlock_irqrestore(hba->host->host_lock, flags);
6259 ufshcd_set_eh_in_progress(hba);
6260 spin_unlock_irqrestore(hba->host->host_lock, flags);
6261 ufshcd_err_handling_prepare(hba);
6262 /* Complete requests that have door-bell cleared by h/w */
6263 ufshcd_complete_requests(hba);
6264 spin_lock_irqsave(hba->host->host_lock, flags);
6266 needs_restore = false;
6267 needs_reset = false;
6269 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6270 hba->ufshcd_state = UFSHCD_STATE_RESET;
6272 * A full reset and restore might have happened after preparation
6273 * is finished, double check whether we should stop.
6275 if (ufshcd_err_handling_should_stop(hba))
6276 goto skip_err_handling;
6278 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6281 spin_unlock_irqrestore(hba->host->host_lock, flags);
6282 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
6283 ret = ufshcd_quirk_dl_nac_errors(hba);
6284 spin_lock_irqsave(hba->host->host_lock, flags);
6285 if (!ret && ufshcd_err_handling_should_stop(hba))
6286 goto skip_err_handling;
6289 if ((hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6290 (hba->saved_uic_err &&
6291 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6292 bool pr_prdt = !!(hba->saved_err & SYSTEM_BUS_FATAL_ERROR);
6294 spin_unlock_irqrestore(hba->host->host_lock, flags);
6295 ufshcd_print_host_state(hba);
6296 ufshcd_print_pwr_info(hba);
6297 ufshcd_print_evt_hist(hba);
6298 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
6299 ufshcd_print_trs(hba, hba->outstanding_reqs, pr_prdt);
6300 spin_lock_irqsave(hba->host->host_lock, flags);
6304 * if host reset is required then skip clearing the pending
6305 * transfers forcefully because they will get cleared during
6306 * host reset and restore
6308 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6309 ufshcd_is_saved_err_fatal(hba) ||
6310 ((hba->saved_err & UIC_ERROR) &&
6311 (hba->saved_uic_err & (UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
6312 UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))) {
6318 * If LINERESET was caught, UFS might have been put to PWM mode,
6319 * check if power mode restore is needed.
6321 if (hba->saved_uic_err & UFSHCD_UIC_PA_GENERIC_ERROR) {
6322 hba->saved_uic_err &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6323 if (!hba->saved_uic_err)
6324 hba->saved_err &= ~UIC_ERROR;
6325 spin_unlock_irqrestore(hba->host->host_lock, flags);
6326 if (ufshcd_is_pwr_mode_restore_needed(hba))
6327 needs_restore = true;
6328 spin_lock_irqsave(hba->host->host_lock, flags);
6329 if (!hba->saved_err && !needs_restore)
6330 goto skip_err_handling;
6333 hba->silence_err_logs = true;
6334 /* release lock as clear command might sleep */
6335 spin_unlock_irqrestore(hba->host->host_lock, flags);
6337 needs_reset = ufshcd_abort_all(hba);
6339 spin_lock_irqsave(hba->host->host_lock, flags);
6340 hba->silence_err_logs = false;
6345 * After all reqs and tasks are cleared from doorbell,
6346 * now it is safe to retore power mode.
6348 if (needs_restore) {
6349 spin_unlock_irqrestore(hba->host->host_lock, flags);
6351 * Hold the scaling lock just in case dev cmds
6352 * are sent via bsg and/or sysfs.
6354 down_write(&hba->clk_scaling_lock);
6355 hba->force_pmc = true;
6356 pmc_err = ufshcd_config_pwr_mode(hba, &(hba->pwr_info));
6359 dev_err(hba->dev, "%s: Failed to restore power mode, err = %d\n",
6362 hba->force_pmc = false;
6363 ufshcd_print_pwr_info(hba);
6364 up_write(&hba->clk_scaling_lock);
6365 spin_lock_irqsave(hba->host->host_lock, flags);
6369 /* Fatal errors need reset */
6373 hba->force_reset = false;
6374 spin_unlock_irqrestore(hba->host->host_lock, flags);
6375 err = ufshcd_reset_and_restore(hba);
6377 dev_err(hba->dev, "%s: reset and restore failed with err %d\n",
6380 ufshcd_recover_pm_error(hba);
6381 spin_lock_irqsave(hba->host->host_lock, flags);
6386 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
6387 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6388 if (hba->saved_err || hba->saved_uic_err)
6389 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
6390 __func__, hba->saved_err, hba->saved_uic_err);
6392 /* Exit in an operational state or dead */
6393 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
6394 hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6397 hba->ufshcd_state = UFSHCD_STATE_ERROR;
6399 ufshcd_clear_eh_in_progress(hba);
6400 spin_unlock_irqrestore(hba->host->host_lock, flags);
6401 ufshcd_err_handling_unprepare(hba);
6404 dev_info(hba->dev, "%s finished; HBA state %s\n", __func__,
6405 ufshcd_state_name[hba->ufshcd_state]);
6409 * ufshcd_update_uic_error - check and set fatal UIC error flags.
6410 * @hba: per-adapter instance
6413 * IRQ_HANDLED - If interrupt is valid
6414 * IRQ_NONE - If invalid interrupt
6416 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
6419 irqreturn_t retval = IRQ_NONE;
6421 /* PHY layer error */
6422 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
6423 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
6424 (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) {
6425 ufshcd_update_evt_hist(hba, UFS_EVT_PA_ERR, reg);
6427 * To know whether this error is fatal or not, DB timeout
6428 * must be checked but this error is handled separately.
6430 if (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)
6431 dev_dbg(hba->dev, "%s: UIC Lane error reported\n",
6434 /* Got a LINERESET indication. */
6435 if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) {
6436 struct uic_command *cmd = NULL;
6438 hba->uic_error |= UFSHCD_UIC_PA_GENERIC_ERROR;
6439 if (hba->uic_async_done && hba->active_uic_cmd)
6440 cmd = hba->active_uic_cmd;
6442 * Ignore the LINERESET during power mode change
6443 * operation via DME_SET command.
6445 if (cmd && (cmd->command == UIC_CMD_DME_SET))
6446 hba->uic_error &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6448 retval |= IRQ_HANDLED;
6451 /* PA_INIT_ERROR is fatal and needs UIC reset */
6452 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
6453 if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
6454 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
6455 ufshcd_update_evt_hist(hba, UFS_EVT_DL_ERR, reg);
6457 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
6458 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
6459 else if (hba->dev_quirks &
6460 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6461 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
6463 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6464 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
6465 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
6467 retval |= IRQ_HANDLED;
6470 /* UIC NL/TL/DME errors needs software retry */
6471 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
6472 if ((reg & UIC_NETWORK_LAYER_ERROR) &&
6473 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
6474 ufshcd_update_evt_hist(hba, UFS_EVT_NL_ERR, reg);
6475 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
6476 retval |= IRQ_HANDLED;
6479 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
6480 if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
6481 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
6482 ufshcd_update_evt_hist(hba, UFS_EVT_TL_ERR, reg);
6483 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
6484 retval |= IRQ_HANDLED;
6487 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
6488 if ((reg & UIC_DME_ERROR) &&
6489 (reg & UIC_DME_ERROR_CODE_MASK)) {
6490 ufshcd_update_evt_hist(hba, UFS_EVT_DME_ERR, reg);
6491 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
6492 retval |= IRQ_HANDLED;
6495 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
6496 __func__, hba->uic_error);
6501 * ufshcd_check_errors - Check for errors that need s/w attention
6502 * @hba: per-adapter instance
6503 * @intr_status: interrupt status generated by the controller
6506 * IRQ_HANDLED - If interrupt is valid
6507 * IRQ_NONE - If invalid interrupt
6509 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba, u32 intr_status)
6511 bool queue_eh_work = false;
6512 irqreturn_t retval = IRQ_NONE;
6514 spin_lock(hba->host->host_lock);
6515 hba->errors |= UFSHCD_ERROR_MASK & intr_status;
6517 if (hba->errors & INT_FATAL_ERRORS) {
6518 ufshcd_update_evt_hist(hba, UFS_EVT_FATAL_ERR,
6520 queue_eh_work = true;
6523 if (hba->errors & UIC_ERROR) {
6525 retval = ufshcd_update_uic_error(hba);
6527 queue_eh_work = true;
6530 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
6532 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
6533 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
6535 hba->errors, ufshcd_get_upmcrs(hba));
6536 ufshcd_update_evt_hist(hba, UFS_EVT_AUTO_HIBERN8_ERR,
6538 ufshcd_set_link_broken(hba);
6539 queue_eh_work = true;
6542 if (queue_eh_work) {
6544 * update the transfer error masks to sticky bits, let's do this
6545 * irrespective of current ufshcd_state.
6547 hba->saved_err |= hba->errors;
6548 hba->saved_uic_err |= hba->uic_error;
6550 /* dump controller state before resetting */
6551 if ((hba->saved_err &
6552 (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6553 (hba->saved_uic_err &&
6554 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6555 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
6556 __func__, hba->saved_err,
6557 hba->saved_uic_err);
6558 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE,
6560 ufshcd_print_pwr_info(hba);
6562 ufshcd_schedule_eh_work(hba);
6563 retval |= IRQ_HANDLED;
6566 * if (!queue_eh_work) -
6567 * Other errors are either non-fatal where host recovers
6568 * itself without s/w intervention or errors that will be
6569 * handled by the SCSI core layer.
6573 spin_unlock(hba->host->host_lock);
6578 * ufshcd_tmc_handler - handle task management function completion
6579 * @hba: per adapter instance
6582 * IRQ_HANDLED - If interrupt is valid
6583 * IRQ_NONE - If invalid interrupt
6585 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
6587 unsigned long flags, pending, issued;
6588 irqreturn_t ret = IRQ_NONE;
6591 spin_lock_irqsave(hba->host->host_lock, flags);
6592 pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
6593 issued = hba->outstanding_tasks & ~pending;
6594 for_each_set_bit(tag, &issued, hba->nutmrs) {
6595 struct request *req = hba->tmf_rqs[tag];
6596 struct completion *c = req->end_io_data;
6601 spin_unlock_irqrestore(hba->host->host_lock, flags);
6607 * ufshcd_sl_intr - Interrupt service routine
6608 * @hba: per adapter instance
6609 * @intr_status: contains interrupts generated by the controller
6612 * IRQ_HANDLED - If interrupt is valid
6613 * IRQ_NONE - If invalid interrupt
6615 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
6617 irqreturn_t retval = IRQ_NONE;
6619 if (intr_status & UFSHCD_UIC_MASK)
6620 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
6622 if (intr_status & UFSHCD_ERROR_MASK || hba->errors)
6623 retval |= ufshcd_check_errors(hba, intr_status);
6625 if (intr_status & UTP_TASK_REQ_COMPL)
6626 retval |= ufshcd_tmc_handler(hba);
6628 if (intr_status & UTP_TRANSFER_REQ_COMPL)
6629 retval |= ufshcd_transfer_req_compl(hba);
6635 * ufshcd_intr - Main interrupt service routine
6637 * @__hba: pointer to adapter instance
6640 * IRQ_HANDLED - If interrupt is valid
6641 * IRQ_NONE - If invalid interrupt
6643 static irqreturn_t ufshcd_intr(int irq, void *__hba)
6645 u32 intr_status, enabled_intr_status = 0;
6646 irqreturn_t retval = IRQ_NONE;
6647 struct ufs_hba *hba = __hba;
6648 int retries = hba->nutrs;
6650 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6651 hba->ufs_stats.last_intr_status = intr_status;
6652 hba->ufs_stats.last_intr_ts = local_clock();
6655 * There could be max of hba->nutrs reqs in flight and in worst case
6656 * if the reqs get finished 1 by 1 after the interrupt status is
6657 * read, make sure we handle them by checking the interrupt status
6658 * again in a loop until we process all of the reqs before returning.
6660 while (intr_status && retries--) {
6661 enabled_intr_status =
6662 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
6663 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
6664 if (enabled_intr_status)
6665 retval |= ufshcd_sl_intr(hba, enabled_intr_status);
6667 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6670 if (enabled_intr_status && retval == IRQ_NONE &&
6671 (!(enabled_intr_status & UTP_TRANSFER_REQ_COMPL) ||
6672 hba->outstanding_reqs) && !ufshcd_eh_in_progress(hba)) {
6673 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x (0x%08x, 0x%08x)\n",
6676 hba->ufs_stats.last_intr_status,
6677 enabled_intr_status);
6678 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
6684 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
6687 u32 mask = 1 << tag;
6688 unsigned long flags;
6690 if (!test_bit(tag, &hba->outstanding_tasks))
6693 spin_lock_irqsave(hba->host->host_lock, flags);
6694 ufshcd_utmrl_clear(hba, tag);
6695 spin_unlock_irqrestore(hba->host->host_lock, flags);
6697 /* poll for max. 1 sec to clear door bell register by h/w */
6698 err = ufshcd_wait_for_register(hba,
6699 REG_UTP_TASK_REQ_DOOR_BELL,
6700 mask, 0, 1000, 1000);
6702 dev_err(hba->dev, "Clearing task management function with tag %d %s\n",
6703 tag, err ? "succeeded" : "failed");
6709 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
6710 struct utp_task_req_desc *treq, u8 tm_function)
6712 struct request_queue *q = hba->tmf_queue;
6713 struct Scsi_Host *host = hba->host;
6714 DECLARE_COMPLETION_ONSTACK(wait);
6715 struct request *req;
6716 unsigned long flags;
6720 * blk_mq_alloc_request() is used here only to get a free tag.
6722 req = blk_mq_alloc_request(q, REQ_OP_DRV_OUT, 0);
6724 return PTR_ERR(req);
6726 req->end_io_data = &wait;
6727 ufshcd_hold(hba, false);
6729 spin_lock_irqsave(host->host_lock, flags);
6731 task_tag = req->tag;
6732 WARN_ONCE(task_tag < 0 || task_tag >= hba->nutmrs, "Invalid tag %d\n",
6734 hba->tmf_rqs[req->tag] = req;
6735 treq->upiu_req.req_header.dword_0 |= cpu_to_be32(task_tag);
6737 memcpy(hba->utmrdl_base_addr + task_tag, treq, sizeof(*treq));
6738 ufshcd_vops_setup_task_mgmt(hba, task_tag, tm_function);
6740 /* send command to the controller */
6741 __set_bit(task_tag, &hba->outstanding_tasks);
6743 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TASK_REQ_DOOR_BELL);
6744 /* Make sure that doorbell is committed immediately */
6747 spin_unlock_irqrestore(host->host_lock, flags);
6749 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_SEND);
6751 /* wait until the task management command is completed */
6752 err = wait_for_completion_io_timeout(&wait,
6753 msecs_to_jiffies(TM_CMD_TIMEOUT));
6755 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_ERR);
6756 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
6757 __func__, tm_function);
6758 if (ufshcd_clear_tm_cmd(hba, task_tag))
6759 dev_WARN(hba->dev, "%s: unable to clear tm cmd (slot %d) after timeout\n",
6760 __func__, task_tag);
6764 memcpy(treq, hba->utmrdl_base_addr + task_tag, sizeof(*treq));
6766 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_COMP);
6769 spin_lock_irqsave(hba->host->host_lock, flags);
6770 hba->tmf_rqs[req->tag] = NULL;
6771 __clear_bit(task_tag, &hba->outstanding_tasks);
6772 spin_unlock_irqrestore(hba->host->host_lock, flags);
6774 ufshcd_release(hba);
6775 blk_mq_free_request(req);
6781 * ufshcd_issue_tm_cmd - issues task management commands to controller
6782 * @hba: per adapter instance
6783 * @lun_id: LUN ID to which TM command is sent
6784 * @task_id: task ID to which the TM command is applicable
6785 * @tm_function: task management function opcode
6786 * @tm_response: task management service response return value
6788 * Returns non-zero value on error, zero on success.
6790 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
6791 u8 tm_function, u8 *tm_response)
6793 struct utp_task_req_desc treq = { { 0 }, };
6794 enum utp_ocs ocs_value;
6797 /* Configure task request descriptor */
6798 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6799 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6801 /* Configure task request UPIU */
6802 treq.upiu_req.req_header.dword_0 = cpu_to_be32(lun_id << 8) |
6803 cpu_to_be32(UPIU_TRANSACTION_TASK_REQ << 24);
6804 treq.upiu_req.req_header.dword_1 = cpu_to_be32(tm_function << 16);
6807 * The host shall provide the same value for LUN field in the basic
6808 * header and for Input Parameter.
6810 treq.upiu_req.input_param1 = cpu_to_be32(lun_id);
6811 treq.upiu_req.input_param2 = cpu_to_be32(task_id);
6813 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
6814 if (err == -ETIMEDOUT)
6817 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6818 if (ocs_value != OCS_SUCCESS)
6819 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
6820 __func__, ocs_value);
6821 else if (tm_response)
6822 *tm_response = be32_to_cpu(treq.upiu_rsp.output_param1) &
6823 MASK_TM_SERVICE_RESP;
6828 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
6829 * @hba: per-adapter instance
6830 * @req_upiu: upiu request
6831 * @rsp_upiu: upiu reply
6832 * @desc_buff: pointer to descriptor buffer, NULL if NA
6833 * @buff_len: descriptor size, 0 if NA
6834 * @cmd_type: specifies the type (NOP, Query...)
6835 * @desc_op: descriptor operation
6837 * Those type of requests uses UTP Transfer Request Descriptor - utrd.
6838 * Therefore, it "rides" the device management infrastructure: uses its tag and
6839 * tasks work queues.
6841 * Since there is only one available tag for device management commands,
6842 * the caller is expected to hold the hba->dev_cmd.lock mutex.
6844 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
6845 struct utp_upiu_req *req_upiu,
6846 struct utp_upiu_req *rsp_upiu,
6847 u8 *desc_buff, int *buff_len,
6848 enum dev_cmd_type cmd_type,
6849 enum query_opcode desc_op)
6851 DECLARE_COMPLETION_ONSTACK(wait);
6852 const u32 tag = hba->reserved_slot;
6853 struct ufshcd_lrb *lrbp;
6857 /* Protects use of hba->reserved_slot. */
6858 lockdep_assert_held(&hba->dev_cmd.lock);
6860 down_read(&hba->clk_scaling_lock);
6862 lrbp = &hba->lrb[tag];
6865 lrbp->task_tag = tag;
6867 lrbp->intr_cmd = true;
6868 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
6869 hba->dev_cmd.type = cmd_type;
6871 if (hba->ufs_version <= ufshci_version(1, 1))
6872 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
6874 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
6876 /* update the task tag in the request upiu */
6877 req_upiu->header.dword_0 |= cpu_to_be32(tag);
6879 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
6881 /* just copy the upiu request as it is */
6882 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
6883 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
6884 /* The Data Segment Area is optional depending upon the query
6885 * function value. for WRITE DESCRIPTOR, the data segment
6886 * follows right after the tsf.
6888 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
6892 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
6894 hba->dev_cmd.complete = &wait;
6896 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
6898 ufshcd_send_command(hba, tag);
6900 * ignore the returning value here - ufshcd_check_query_response is
6901 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
6902 * read the response directly ignoring all errors.
6904 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
6906 /* just copy the upiu response as it is */
6907 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
6908 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
6909 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
6910 u16 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
6911 MASK_QUERY_DATA_SEG_LEN;
6913 if (*buff_len >= resp_len) {
6914 memcpy(desc_buff, descp, resp_len);
6915 *buff_len = resp_len;
6918 "%s: rsp size %d is bigger than buffer size %d",
6919 __func__, resp_len, *buff_len);
6924 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
6925 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
6927 up_read(&hba->clk_scaling_lock);
6932 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
6933 * @hba: per-adapter instance
6934 * @req_upiu: upiu request
6935 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands
6936 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
6937 * @desc_buff: pointer to descriptor buffer, NULL if NA
6938 * @buff_len: descriptor size, 0 if NA
6939 * @desc_op: descriptor operation
6941 * Supports UTP Transfer requests (nop and query), and UTP Task
6942 * Management requests.
6943 * It is up to the caller to fill the upiu conent properly, as it will
6944 * be copied without any further input validations.
6946 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
6947 struct utp_upiu_req *req_upiu,
6948 struct utp_upiu_req *rsp_upiu,
6950 u8 *desc_buff, int *buff_len,
6951 enum query_opcode desc_op)
6954 enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
6955 struct utp_task_req_desc treq = { { 0 }, };
6956 enum utp_ocs ocs_value;
6957 u8 tm_f = be32_to_cpu(req_upiu->header.dword_1) >> 16 & MASK_TM_FUNC;
6960 case UPIU_TRANSACTION_NOP_OUT:
6961 cmd_type = DEV_CMD_TYPE_NOP;
6963 case UPIU_TRANSACTION_QUERY_REQ:
6964 ufshcd_hold(hba, false);
6965 mutex_lock(&hba->dev_cmd.lock);
6966 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
6967 desc_buff, buff_len,
6969 mutex_unlock(&hba->dev_cmd.lock);
6970 ufshcd_release(hba);
6973 case UPIU_TRANSACTION_TASK_REQ:
6974 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6975 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6977 memcpy(&treq.upiu_req, req_upiu, sizeof(*req_upiu));
6979 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
6980 if (err == -ETIMEDOUT)
6983 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6984 if (ocs_value != OCS_SUCCESS) {
6985 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
6990 memcpy(rsp_upiu, &treq.upiu_rsp, sizeof(*rsp_upiu));
7003 * ufshcd_eh_device_reset_handler() - Reset a single logical unit.
7004 * @cmd: SCSI command pointer
7006 * Returns SUCCESS/FAILED
7008 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
7010 unsigned long flags, pending_reqs = 0, not_cleared = 0;
7011 struct Scsi_Host *host;
7012 struct ufs_hba *hba;
7017 host = cmd->device->host;
7018 hba = shost_priv(host);
7020 lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
7021 err = ufshcd_issue_tm_cmd(hba, lun, 0, UFS_LOGICAL_RESET, &resp);
7022 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7028 /* clear the commands that were pending for corresponding LUN */
7029 spin_lock_irqsave(&hba->outstanding_lock, flags);
7030 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs)
7031 if (hba->lrb[pos].lun == lun)
7032 __set_bit(pos, &pending_reqs);
7033 hba->outstanding_reqs &= ~pending_reqs;
7034 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7036 if (ufshcd_clear_cmds(hba, pending_reqs) < 0) {
7037 spin_lock_irqsave(&hba->outstanding_lock, flags);
7038 not_cleared = pending_reqs &
7039 ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7040 hba->outstanding_reqs |= not_cleared;
7041 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7043 dev_err(hba->dev, "%s: failed to clear requests %#lx\n",
7044 __func__, not_cleared);
7046 __ufshcd_transfer_req_compl(hba, pending_reqs & ~not_cleared);
7049 hba->req_abort_count = 0;
7050 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, (u32)err);
7054 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7060 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
7062 struct ufshcd_lrb *lrbp;
7065 for_each_set_bit(tag, &bitmap, hba->nutrs) {
7066 lrbp = &hba->lrb[tag];
7067 lrbp->req_abort_skip = true;
7072 * ufshcd_try_to_abort_task - abort a specific task
7073 * @hba: Pointer to adapter instance
7074 * @tag: Task tag/index to be aborted
7076 * Abort the pending command in device by sending UFS_ABORT_TASK task management
7077 * command, and in host controller by clearing the door-bell register. There can
7078 * be race between controller sending the command to the device while abort is
7079 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
7080 * really issued and then try to abort it.
7082 * Returns zero on success, non-zero on failure
7084 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag)
7086 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7092 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
7093 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7094 UFS_QUERY_TASK, &resp);
7095 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
7096 /* cmd pending in the device */
7097 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
7100 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7102 * cmd not pending in the device, check if it is
7105 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
7107 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7108 if (reg & (1 << tag)) {
7109 /* sleep for max. 200us to stabilize */
7110 usleep_range(100, 200);
7113 /* command completed already */
7114 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
7119 "%s: no response from device. tag = %d, err %d\n",
7120 __func__, tag, err);
7122 err = resp; /* service response error */
7132 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7133 UFS_ABORT_TASK, &resp);
7134 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7136 err = resp; /* service response error */
7137 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
7138 __func__, tag, err);
7143 err = ufshcd_clear_cmds(hba, 1U << tag);
7145 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
7146 __func__, tag, err);
7153 * ufshcd_abort - scsi host template eh_abort_handler callback
7154 * @cmd: SCSI command pointer
7156 * Returns SUCCESS/FAILED
7158 static int ufshcd_abort(struct scsi_cmnd *cmd)
7160 struct Scsi_Host *host = cmd->device->host;
7161 struct ufs_hba *hba = shost_priv(host);
7162 int tag = scsi_cmd_to_rq(cmd)->tag;
7163 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7164 unsigned long flags;
7169 WARN_ONCE(tag < 0, "Invalid tag %d\n", tag);
7171 ufshcd_hold(hba, false);
7172 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7173 /* If command is already aborted/completed, return FAILED. */
7174 if (!(test_bit(tag, &hba->outstanding_reqs))) {
7176 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
7177 __func__, tag, hba->outstanding_reqs, reg);
7181 /* Print Transfer Request of aborted task */
7182 dev_info(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
7185 * Print detailed info about aborted request.
7186 * As more than one request might get aborted at the same time,
7187 * print full information only for the first aborted request in order
7188 * to reduce repeated printouts. For other aborted requests only print
7191 scsi_print_command(cmd);
7192 if (!hba->req_abort_count) {
7193 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, tag);
7194 ufshcd_print_evt_hist(hba);
7195 ufshcd_print_host_state(hba);
7196 ufshcd_print_pwr_info(hba);
7197 ufshcd_print_trs(hba, 1 << tag, true);
7199 ufshcd_print_trs(hba, 1 << tag, false);
7201 hba->req_abort_count++;
7203 if (!(reg & (1 << tag))) {
7205 "%s: cmd was completed, but without a notifying intr, tag = %d",
7207 __ufshcd_transfer_req_compl(hba, 1UL << tag);
7212 * Task abort to the device W-LUN is illegal. When this command
7213 * will fail, due to spec violation, scsi err handling next step
7214 * will be to send LU reset which, again, is a spec violation.
7215 * To avoid these unnecessary/illegal steps, first we clean up
7216 * the lrb taken by this cmd and re-set it in outstanding_reqs,
7217 * then queue the eh_work and bail.
7219 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN) {
7220 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, lrbp->lun);
7222 spin_lock_irqsave(host->host_lock, flags);
7223 hba->force_reset = true;
7224 ufshcd_schedule_eh_work(hba);
7225 spin_unlock_irqrestore(host->host_lock, flags);
7229 /* Skip task abort in case previous aborts failed and report failure */
7230 if (lrbp->req_abort_skip) {
7231 dev_err(hba->dev, "%s: skipping abort\n", __func__);
7232 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7236 err = ufshcd_try_to_abort_task(hba, tag);
7238 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7239 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7245 * Clear the corresponding bit from outstanding_reqs since the command
7246 * has been aborted successfully.
7248 spin_lock_irqsave(&hba->outstanding_lock, flags);
7249 outstanding = __test_and_clear_bit(tag, &hba->outstanding_reqs);
7250 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7253 ufshcd_release_scsi_cmd(hba, lrbp);
7258 /* Matches the ufshcd_hold() call at the start of this function. */
7259 ufshcd_release(hba);
7264 * ufshcd_host_reset_and_restore - reset and restore host controller
7265 * @hba: per-adapter instance
7267 * Note that host controller reset may issue DME_RESET to
7268 * local and remote (device) Uni-Pro stack and the attributes
7269 * are reset to default state.
7271 * Returns zero on success, non-zero on failure
7273 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
7278 * Stop the host controller and complete the requests
7281 ufshpb_toggle_state(hba, HPB_PRESENT, HPB_RESET);
7282 ufshcd_hba_stop(hba);
7283 hba->silence_err_logs = true;
7284 ufshcd_complete_requests(hba);
7285 hba->silence_err_logs = false;
7287 /* scale up clocks to max frequency before full reinitialization */
7288 ufshcd_scale_clks(hba, true);
7290 err = ufshcd_hba_enable(hba);
7292 /* Establish the link again and restore the device */
7294 err = ufshcd_probe_hba(hba, false);
7297 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
7298 ufshcd_update_evt_hist(hba, UFS_EVT_HOST_RESET, (u32)err);
7303 * ufshcd_reset_and_restore - reset and re-initialize host/device
7304 * @hba: per-adapter instance
7306 * Reset and recover device, host and re-establish link. This
7307 * is helpful to recover the communication in fatal error conditions.
7309 * Returns zero on success, non-zero on failure
7311 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
7314 u32 saved_uic_err = 0;
7316 unsigned long flags;
7317 int retries = MAX_HOST_RESET_RETRIES;
7319 spin_lock_irqsave(hba->host->host_lock, flags);
7322 * This is a fresh start, cache and clear saved error first,
7323 * in case new error generated during reset and restore.
7325 saved_err |= hba->saved_err;
7326 saved_uic_err |= hba->saved_uic_err;
7328 hba->saved_uic_err = 0;
7329 hba->force_reset = false;
7330 hba->ufshcd_state = UFSHCD_STATE_RESET;
7331 spin_unlock_irqrestore(hba->host->host_lock, flags);
7333 /* Reset the attached device */
7334 ufshcd_device_reset(hba);
7336 err = ufshcd_host_reset_and_restore(hba);
7338 spin_lock_irqsave(hba->host->host_lock, flags);
7341 /* Do not exit unless operational or dead */
7342 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
7343 hba->ufshcd_state != UFSHCD_STATE_ERROR &&
7344 hba->ufshcd_state != UFSHCD_STATE_EH_SCHEDULED_NON_FATAL)
7346 } while (err && --retries);
7349 * Inform scsi mid-layer that we did reset and allow to handle
7350 * Unit Attention properly.
7352 scsi_report_bus_reset(hba->host, 0);
7354 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7355 hba->saved_err |= saved_err;
7356 hba->saved_uic_err |= saved_uic_err;
7358 spin_unlock_irqrestore(hba->host->host_lock, flags);
7364 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
7365 * @cmd: SCSI command pointer
7367 * Returns SUCCESS/FAILED
7369 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
7372 unsigned long flags;
7373 struct ufs_hba *hba;
7375 hba = shost_priv(cmd->device->host);
7377 spin_lock_irqsave(hba->host->host_lock, flags);
7378 hba->force_reset = true;
7379 ufshcd_schedule_eh_work(hba);
7380 dev_err(hba->dev, "%s: reset in progress - 1\n", __func__);
7381 spin_unlock_irqrestore(hba->host->host_lock, flags);
7383 flush_work(&hba->eh_work);
7385 spin_lock_irqsave(hba->host->host_lock, flags);
7386 if (hba->ufshcd_state == UFSHCD_STATE_ERROR)
7388 spin_unlock_irqrestore(hba->host->host_lock, flags);
7394 * ufshcd_get_max_icc_level - calculate the ICC level
7395 * @sup_curr_uA: max. current supported by the regulator
7396 * @start_scan: row at the desc table to start scan from
7397 * @buff: power descriptor buffer
7399 * Returns calculated max ICC level for specific regulator
7401 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan,
7409 for (i = start_scan; i >= 0; i--) {
7410 data = get_unaligned_be16(&buff[2 * i]);
7411 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
7412 ATTR_ICC_LVL_UNIT_OFFSET;
7413 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
7415 case UFSHCD_NANO_AMP:
7416 curr_uA = curr_uA / 1000;
7418 case UFSHCD_MILI_AMP:
7419 curr_uA = curr_uA * 1000;
7422 curr_uA = curr_uA * 1000 * 1000;
7424 case UFSHCD_MICRO_AMP:
7428 if (sup_curr_uA >= curr_uA)
7433 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
7440 * ufshcd_find_max_sup_active_icc_level - calculate the max ICC level
7441 * In case regulators are not initialized we'll return 0
7442 * @hba: per-adapter instance
7443 * @desc_buf: power descriptor buffer to extract ICC levels from.
7444 * @len: length of desc_buff
7446 * Returns calculated ICC level
7448 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
7449 const u8 *desc_buf, int len)
7453 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
7454 !hba->vreg_info.vccq2) {
7456 * Using dev_dbg to avoid messages during runtime PM to avoid
7457 * never-ending cycles of messages written back to storage by
7458 * user space causing runtime resume, causing more messages and
7462 "%s: Regulator capability was not set, actvIccLevel=%d",
7463 __func__, icc_level);
7467 if (hba->vreg_info.vcc->max_uA)
7468 icc_level = ufshcd_get_max_icc_level(
7469 hba->vreg_info.vcc->max_uA,
7470 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
7471 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
7473 if (hba->vreg_info.vccq->max_uA)
7474 icc_level = ufshcd_get_max_icc_level(
7475 hba->vreg_info.vccq->max_uA,
7477 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
7479 if (hba->vreg_info.vccq2->max_uA)
7480 icc_level = ufshcd_get_max_icc_level(
7481 hba->vreg_info.vccq2->max_uA,
7483 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
7488 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba)
7491 int buff_len = hba->desc_size[QUERY_DESC_IDN_POWER];
7495 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7499 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0,
7500 desc_buf, buff_len);
7503 "%s: Failed reading power descriptor.len = %d ret = %d",
7504 __func__, buff_len, ret);
7508 icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf,
7510 dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level);
7512 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7513 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level);
7517 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
7518 __func__, icc_level, ret);
7524 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev)
7526 scsi_autopm_get_device(sdev);
7527 blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev);
7528 if (sdev->rpm_autosuspend)
7529 pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev,
7530 RPM_AUTOSUSPEND_DELAY_MS);
7531 scsi_autopm_put_device(sdev);
7535 * ufshcd_scsi_add_wlus - Adds required W-LUs
7536 * @hba: per-adapter instance
7538 * UFS device specification requires the UFS devices to support 4 well known
7540 * "REPORT_LUNS" (address: 01h)
7541 * "UFS Device" (address: 50h)
7542 * "RPMB" (address: 44h)
7543 * "BOOT" (address: 30h)
7544 * UFS device's power management needs to be controlled by "POWER CONDITION"
7545 * field of SSU (START STOP UNIT) command. But this "power condition" field
7546 * will take effect only when its sent to "UFS device" well known logical unit
7547 * hence we require the scsi_device instance to represent this logical unit in
7548 * order for the UFS host driver to send the SSU command for power management.
7550 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
7551 * Block) LU so user space process can control this LU. User space may also
7552 * want to have access to BOOT LU.
7554 * This function adds scsi device instances for each of all well known LUs
7555 * (except "REPORT LUNS" LU).
7557 * Returns zero on success (all required W-LUs are added successfully),
7558 * non-zero error value on failure (if failed to add any of the required W-LU).
7560 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
7563 struct scsi_device *sdev_boot, *sdev_rpmb;
7565 hba->ufs_device_wlun = __scsi_add_device(hba->host, 0, 0,
7566 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
7567 if (IS_ERR(hba->ufs_device_wlun)) {
7568 ret = PTR_ERR(hba->ufs_device_wlun);
7569 hba->ufs_device_wlun = NULL;
7572 scsi_device_put(hba->ufs_device_wlun);
7574 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
7575 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
7576 if (IS_ERR(sdev_rpmb)) {
7577 ret = PTR_ERR(sdev_rpmb);
7578 goto remove_ufs_device_wlun;
7580 ufshcd_blk_pm_runtime_init(sdev_rpmb);
7581 scsi_device_put(sdev_rpmb);
7583 sdev_boot = __scsi_add_device(hba->host, 0, 0,
7584 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
7585 if (IS_ERR(sdev_boot)) {
7586 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
7588 ufshcd_blk_pm_runtime_init(sdev_boot);
7589 scsi_device_put(sdev_boot);
7593 remove_ufs_device_wlun:
7594 scsi_remove_device(hba->ufs_device_wlun);
7599 static void ufshcd_wb_probe(struct ufs_hba *hba, const u8 *desc_buf)
7601 struct ufs_dev_info *dev_info = &hba->dev_info;
7603 u32 d_lu_wb_buf_alloc;
7604 u32 ext_ufs_feature;
7606 if (!ufshcd_is_wb_allowed(hba))
7610 * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or
7611 * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES
7614 if (!(dev_info->wspecversion >= 0x310 ||
7615 dev_info->wspecversion == 0x220 ||
7616 (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES)))
7619 if (hba->desc_size[QUERY_DESC_IDN_DEVICE] <
7620 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP + 4)
7623 ext_ufs_feature = get_unaligned_be32(desc_buf +
7624 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7626 if (!(ext_ufs_feature & UFS_DEV_WRITE_BOOSTER_SUP))
7630 * WB may be supported but not configured while provisioning. The spec
7631 * says, in dedicated wb buffer mode, a max of 1 lun would have wb
7632 * buffer configured.
7634 dev_info->wb_buffer_type = desc_buf[DEVICE_DESC_PARAM_WB_TYPE];
7636 dev_info->b_presrv_uspc_en =
7637 desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN];
7639 if (dev_info->wb_buffer_type == WB_BUF_MODE_SHARED) {
7640 if (!get_unaligned_be32(desc_buf +
7641 DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS))
7644 for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) {
7645 d_lu_wb_buf_alloc = 0;
7646 ufshcd_read_unit_desc_param(hba,
7648 UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS,
7649 (u8 *)&d_lu_wb_buf_alloc,
7650 sizeof(d_lu_wb_buf_alloc));
7651 if (d_lu_wb_buf_alloc) {
7652 dev_info->wb_dedicated_lu = lun;
7657 if (!d_lu_wb_buf_alloc)
7661 if (!ufshcd_is_wb_buf_lifetime_available(hba))
7667 hba->caps &= ~UFSHCD_CAP_WB_EN;
7670 static void ufshcd_temp_notif_probe(struct ufs_hba *hba, const u8 *desc_buf)
7672 struct ufs_dev_info *dev_info = &hba->dev_info;
7673 u32 ext_ufs_feature;
7676 if (!(hba->caps & UFSHCD_CAP_TEMP_NOTIF) || dev_info->wspecversion < 0x300)
7679 ext_ufs_feature = get_unaligned_be32(desc_buf + DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7681 if (ext_ufs_feature & UFS_DEV_LOW_TEMP_NOTIF)
7682 mask |= MASK_EE_TOO_LOW_TEMP;
7684 if (ext_ufs_feature & UFS_DEV_HIGH_TEMP_NOTIF)
7685 mask |= MASK_EE_TOO_HIGH_TEMP;
7688 ufshcd_enable_ee(hba, mask);
7689 ufs_hwmon_probe(hba, mask);
7693 void ufshcd_fixup_dev_quirks(struct ufs_hba *hba,
7694 const struct ufs_dev_quirk *fixups)
7696 const struct ufs_dev_quirk *f;
7697 struct ufs_dev_info *dev_info = &hba->dev_info;
7702 for (f = fixups; f->quirk; f++) {
7703 if ((f->wmanufacturerid == dev_info->wmanufacturerid ||
7704 f->wmanufacturerid == UFS_ANY_VENDOR) &&
7705 ((dev_info->model &&
7706 STR_PRFX_EQUAL(f->model, dev_info->model)) ||
7707 !strcmp(f->model, UFS_ANY_MODEL)))
7708 hba->dev_quirks |= f->quirk;
7711 EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks);
7713 static void ufs_fixup_device_setup(struct ufs_hba *hba)
7715 /* fix by general quirk table */
7716 ufshcd_fixup_dev_quirks(hba, ufs_fixups);
7718 /* allow vendors to fix quirks */
7719 ufshcd_vops_fixup_dev_quirks(hba);
7722 static int ufs_get_device_desc(struct ufs_hba *hba)
7726 u8 b_ufs_feature_sup;
7728 struct ufs_dev_info *dev_info = &hba->dev_info;
7730 desc_buf = kmalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
7736 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf,
7737 hba->desc_size[QUERY_DESC_IDN_DEVICE]);
7739 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
7745 * getting vendor (manufacturerID) and Bank Index in big endian
7748 dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
7749 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
7751 /* getting Specification Version in big endian format */
7752 dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 |
7753 desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1];
7754 b_ufs_feature_sup = desc_buf[DEVICE_DESC_PARAM_UFS_FEAT];
7756 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
7758 if (dev_info->wspecversion >= UFS_DEV_HPB_SUPPORT_VERSION &&
7759 (b_ufs_feature_sup & UFS_DEV_HPB_SUPPORT)) {
7760 bool hpb_en = false;
7762 ufshpb_get_dev_info(hba, desc_buf);
7764 if (!ufshpb_is_legacy(hba))
7765 err = ufshcd_query_flag_retry(hba,
7766 UPIU_QUERY_OPCODE_READ_FLAG,
7767 QUERY_FLAG_IDN_HPB_EN, 0,
7770 if (ufshpb_is_legacy(hba) || (!err && hpb_en))
7771 dev_info->hpb_enabled = true;
7774 err = ufshcd_read_string_desc(hba, model_index,
7775 &dev_info->model, SD_ASCII_STD);
7777 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
7782 hba->luns_avail = desc_buf[DEVICE_DESC_PARAM_NUM_LU] +
7783 desc_buf[DEVICE_DESC_PARAM_NUM_WLU];
7785 ufs_fixup_device_setup(hba);
7787 ufshcd_wb_probe(hba, desc_buf);
7789 ufshcd_temp_notif_probe(hba, desc_buf);
7792 * ufshcd_read_string_desc returns size of the string
7793 * reset the error value
7802 static void ufs_put_device_desc(struct ufs_hba *hba)
7804 struct ufs_dev_info *dev_info = &hba->dev_info;
7806 kfree(dev_info->model);
7807 dev_info->model = NULL;
7811 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
7812 * @hba: per-adapter instance
7814 * PA_TActivate parameter can be tuned manually if UniPro version is less than
7815 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
7816 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
7817 * the hibern8 exit latency.
7819 * Returns zero on success, non-zero error value on failure.
7821 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
7824 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
7826 ret = ufshcd_dme_peer_get(hba,
7828 RX_MIN_ACTIVATETIME_CAPABILITY,
7829 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7830 &peer_rx_min_activatetime);
7834 /* make sure proper unit conversion is applied */
7835 tuned_pa_tactivate =
7836 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
7837 / PA_TACTIVATE_TIME_UNIT_US);
7838 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7839 tuned_pa_tactivate);
7846 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
7847 * @hba: per-adapter instance
7849 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
7850 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
7851 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
7852 * This optimal value can help reduce the hibern8 exit latency.
7854 * Returns zero on success, non-zero error value on failure.
7856 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
7859 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
7860 u32 max_hibern8_time, tuned_pa_hibern8time;
7862 ret = ufshcd_dme_get(hba,
7863 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
7864 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
7865 &local_tx_hibern8_time_cap);
7869 ret = ufshcd_dme_peer_get(hba,
7870 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
7871 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7872 &peer_rx_hibern8_time_cap);
7876 max_hibern8_time = max(local_tx_hibern8_time_cap,
7877 peer_rx_hibern8_time_cap);
7878 /* make sure proper unit conversion is applied */
7879 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
7880 / PA_HIBERN8_TIME_UNIT_US);
7881 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
7882 tuned_pa_hibern8time);
7888 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
7889 * less than device PA_TACTIVATE time.
7890 * @hba: per-adapter instance
7892 * Some UFS devices require host PA_TACTIVATE to be lower than device
7893 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
7896 * Returns zero on success, non-zero error value on failure.
7898 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
7901 u32 granularity, peer_granularity;
7902 u32 pa_tactivate, peer_pa_tactivate;
7903 u32 pa_tactivate_us, peer_pa_tactivate_us;
7904 static const u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
7906 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7911 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7916 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
7917 (granularity > PA_GRANULARITY_MAX_VAL)) {
7918 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
7919 __func__, granularity);
7923 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
7924 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
7925 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
7926 __func__, peer_granularity);
7930 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
7934 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
7935 &peer_pa_tactivate);
7939 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
7940 peer_pa_tactivate_us = peer_pa_tactivate *
7941 gran_to_us_table[peer_granularity - 1];
7943 if (pa_tactivate_us >= peer_pa_tactivate_us) {
7944 u32 new_peer_pa_tactivate;
7946 new_peer_pa_tactivate = pa_tactivate_us /
7947 gran_to_us_table[peer_granularity - 1];
7948 new_peer_pa_tactivate++;
7949 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7950 new_peer_pa_tactivate);
7957 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
7959 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
7960 ufshcd_tune_pa_tactivate(hba);
7961 ufshcd_tune_pa_hibern8time(hba);
7964 ufshcd_vops_apply_dev_quirks(hba);
7966 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
7967 /* set 1ms timeout for PA_TACTIVATE */
7968 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
7970 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
7971 ufshcd_quirk_tune_host_pa_tactivate(hba);
7974 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
7976 hba->ufs_stats.hibern8_exit_cnt = 0;
7977 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
7978 hba->req_abort_count = 0;
7981 static int ufshcd_device_geo_params_init(struct ufs_hba *hba)
7987 buff_len = hba->desc_size[QUERY_DESC_IDN_GEOMETRY];
7988 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7994 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0,
7995 desc_buf, buff_len);
7997 dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n",
8002 if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1)
8003 hba->dev_info.max_lu_supported = 32;
8004 else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0)
8005 hba->dev_info.max_lu_supported = 8;
8007 if (hba->desc_size[QUERY_DESC_IDN_GEOMETRY] >=
8008 GEOMETRY_DESC_PARAM_HPB_MAX_ACTIVE_REGS)
8009 ufshpb_get_geo_info(hba, desc_buf);
8016 struct ufs_ref_clk {
8017 unsigned long freq_hz;
8018 enum ufs_ref_clk_freq val;
8021 static const struct ufs_ref_clk ufs_ref_clk_freqs[] = {
8022 {19200000, REF_CLK_FREQ_19_2_MHZ},
8023 {26000000, REF_CLK_FREQ_26_MHZ},
8024 {38400000, REF_CLK_FREQ_38_4_MHZ},
8025 {52000000, REF_CLK_FREQ_52_MHZ},
8026 {0, REF_CLK_FREQ_INVAL},
8029 static enum ufs_ref_clk_freq
8030 ufs_get_bref_clk_from_hz(unsigned long freq)
8034 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
8035 if (ufs_ref_clk_freqs[i].freq_hz == freq)
8036 return ufs_ref_clk_freqs[i].val;
8038 return REF_CLK_FREQ_INVAL;
8041 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
8045 freq = clk_get_rate(refclk);
8047 hba->dev_ref_clk_freq =
8048 ufs_get_bref_clk_from_hz(freq);
8050 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
8052 "invalid ref_clk setting = %ld\n", freq);
8055 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
8059 u32 freq = hba->dev_ref_clk_freq;
8061 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
8062 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
8065 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
8070 if (ref_clk == freq)
8071 goto out; /* nothing to update */
8073 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
8074 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
8077 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
8078 ufs_ref_clk_freqs[freq].freq_hz);
8082 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
8083 ufs_ref_clk_freqs[freq].freq_hz);
8089 static int ufshcd_device_params_init(struct ufs_hba *hba)
8094 /* Init device descriptor sizes */
8095 for (i = 0; i < QUERY_DESC_IDN_MAX; i++)
8096 hba->desc_size[i] = QUERY_DESC_MAX_SIZE;
8098 /* Init UFS geometry descriptor related parameters */
8099 ret = ufshcd_device_geo_params_init(hba);
8103 /* Check and apply UFS device quirks */
8104 ret = ufs_get_device_desc(hba);
8106 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
8111 ufshcd_get_ref_clk_gating_wait(hba);
8113 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
8114 QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag))
8115 hba->dev_info.f_power_on_wp_en = flag;
8117 /* Probe maximum power mode co-supported by both UFS host and device */
8118 if (ufshcd_get_max_pwr_mode(hba))
8120 "%s: Failed getting max supported power mode\n",
8127 * ufshcd_add_lus - probe and add UFS logical units
8128 * @hba: per-adapter instance
8130 static int ufshcd_add_lus(struct ufs_hba *hba)
8134 /* Add required well known logical units to scsi mid layer */
8135 ret = ufshcd_scsi_add_wlus(hba);
8139 /* Initialize devfreq after UFS device is detected */
8140 if (ufshcd_is_clkscaling_supported(hba)) {
8141 memcpy(&hba->clk_scaling.saved_pwr_info.info,
8143 sizeof(struct ufs_pa_layer_attr));
8144 hba->clk_scaling.saved_pwr_info.is_valid = true;
8145 hba->clk_scaling.is_allowed = true;
8147 ret = ufshcd_devfreq_init(hba);
8151 hba->clk_scaling.is_enabled = true;
8152 ufshcd_init_clk_scaling_sysfs(hba);
8157 scsi_scan_host(hba->host);
8158 pm_runtime_put_sync(hba->dev);
8165 * ufshcd_probe_hba - probe hba to detect device and initialize it
8166 * @hba: per-adapter instance
8167 * @init_dev_params: whether or not to call ufshcd_device_params_init().
8169 * Execute link-startup and verify device initialization
8171 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params)
8174 unsigned long flags;
8175 ktime_t start = ktime_get();
8177 hba->ufshcd_state = UFSHCD_STATE_RESET;
8179 ret = ufshcd_link_startup(hba);
8183 if (hba->quirks & UFSHCD_QUIRK_SKIP_PH_CONFIGURATION)
8186 /* Debug counters initialization */
8187 ufshcd_clear_dbg_ufs_stats(hba);
8189 /* UniPro link is active now */
8190 ufshcd_set_link_active(hba);
8192 /* Verify device initialization by sending NOP OUT UPIU */
8193 ret = ufshcd_verify_dev_init(hba);
8197 /* Initiate UFS initialization, and waiting until completion */
8198 ret = ufshcd_complete_dev_init(hba);
8203 * Initialize UFS device parameters used by driver, these
8204 * parameters are associated with UFS descriptors.
8206 if (init_dev_params) {
8207 ret = ufshcd_device_params_init(hba);
8212 ufshcd_tune_unipro_params(hba);
8214 /* UFS device is also active now */
8215 ufshcd_set_ufs_dev_active(hba);
8216 ufshcd_force_reset_auto_bkops(hba);
8218 /* Gear up to HS gear if supported */
8219 if (hba->max_pwr_info.is_valid) {
8221 * Set the right value to bRefClkFreq before attempting to
8222 * switch to HS gears.
8224 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
8225 ufshcd_set_dev_ref_clk(hba);
8226 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
8228 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
8232 ufshcd_print_pwr_info(hba);
8236 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec)
8237 * and for removable UFS card as well, hence always set the parameter.
8238 * Note: Error handler may issue the device reset hence resetting
8239 * bActiveICCLevel as well so it is always safe to set this here.
8241 ufshcd_set_active_icc_lvl(hba);
8243 /* Enable UFS Write Booster if supported */
8244 ufshcd_configure_wb(hba);
8246 if (hba->ee_usr_mask)
8247 ufshcd_write_ee_control(hba);
8248 /* Enable Auto-Hibernate if configured */
8249 ufshcd_auto_hibern8_enable(hba);
8251 ufshpb_toggle_state(hba, HPB_RESET, HPB_PRESENT);
8253 spin_lock_irqsave(hba->host->host_lock, flags);
8255 hba->ufshcd_state = UFSHCD_STATE_ERROR;
8256 else if (hba->ufshcd_state == UFSHCD_STATE_RESET)
8257 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
8258 spin_unlock_irqrestore(hba->host->host_lock, flags);
8260 trace_ufshcd_init(dev_name(hba->dev), ret,
8261 ktime_to_us(ktime_sub(ktime_get(), start)),
8262 hba->curr_dev_pwr_mode, hba->uic_link_state);
8267 * ufshcd_async_scan - asynchronous execution for probing hba
8268 * @data: data pointer to pass to this function
8269 * @cookie: cookie data
8271 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
8273 struct ufs_hba *hba = (struct ufs_hba *)data;
8276 down(&hba->host_sem);
8277 /* Initialize hba, detect and initialize UFS device */
8278 ret = ufshcd_probe_hba(hba, true);
8283 /* Probe and add UFS logical units */
8284 ret = ufshcd_add_lus(hba);
8287 * If we failed to initialize the device or the device is not
8288 * present, turn off the power/clocks etc.
8291 pm_runtime_put_sync(hba->dev);
8292 ufshcd_hba_exit(hba);
8296 static enum scsi_timeout_action ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
8298 struct ufs_hba *hba = shost_priv(scmd->device->host);
8300 if (!hba->system_suspending) {
8301 /* Activate the error handler in the SCSI core. */
8302 return SCSI_EH_NOT_HANDLED;
8306 * If we get here we know that no TMFs are outstanding and also that
8307 * the only pending command is a START STOP UNIT command. Handle the
8308 * timeout of that command directly to prevent a deadlock between
8309 * ufshcd_set_dev_pwr_mode() and ufshcd_err_handler().
8311 ufshcd_link_recovery(hba);
8312 dev_info(hba->dev, "%s() finished; outstanding_tasks = %#lx.\n",
8313 __func__, hba->outstanding_tasks);
8315 return hba->outstanding_reqs ? SCSI_EH_RESET_TIMER : SCSI_EH_DONE;
8318 static const struct attribute_group *ufshcd_driver_groups[] = {
8319 &ufs_sysfs_unit_descriptor_group,
8320 &ufs_sysfs_lun_attributes_group,
8321 #ifdef CONFIG_SCSI_UFS_HPB
8322 &ufs_sysfs_hpb_stat_group,
8323 &ufs_sysfs_hpb_param_group,
8328 static struct ufs_hba_variant_params ufs_hba_vps = {
8329 .hba_enable_delay_us = 1000,
8330 .wb_flush_threshold = UFS_WB_BUF_REMAIN_PERCENT(40),
8331 .devfreq_profile.polling_ms = 100,
8332 .devfreq_profile.target = ufshcd_devfreq_target,
8333 .devfreq_profile.get_dev_status = ufshcd_devfreq_get_dev_status,
8334 .ondemand_data.upthreshold = 70,
8335 .ondemand_data.downdifferential = 5,
8338 static struct scsi_host_template ufshcd_driver_template = {
8339 .module = THIS_MODULE,
8341 .proc_name = UFSHCD,
8342 .map_queues = ufshcd_map_queues,
8343 .queuecommand = ufshcd_queuecommand,
8344 .mq_poll = ufshcd_poll,
8345 .slave_alloc = ufshcd_slave_alloc,
8346 .slave_configure = ufshcd_slave_configure,
8347 .slave_destroy = ufshcd_slave_destroy,
8348 .change_queue_depth = ufshcd_change_queue_depth,
8349 .eh_abort_handler = ufshcd_abort,
8350 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
8351 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
8352 .eh_timed_out = ufshcd_eh_timed_out,
8354 .sg_tablesize = SG_ALL,
8355 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
8356 .can_queue = UFSHCD_CAN_QUEUE,
8357 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX,
8358 .max_sectors = (1 << 20) / SECTOR_SIZE, /* 1 MiB */
8359 .max_host_blocked = 1,
8360 .track_queue_depth = 1,
8361 .sdev_groups = ufshcd_driver_groups,
8362 .dma_boundary = PAGE_SIZE - 1,
8363 .rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS,
8366 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
8375 * "set_load" operation shall be required on those regulators
8376 * which specifically configured current limitation. Otherwise
8377 * zero max_uA may cause unexpected behavior when regulator is
8378 * enabled or set as high power mode.
8383 ret = regulator_set_load(vreg->reg, ua);
8385 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
8386 __func__, vreg->name, ua, ret);
8392 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
8393 struct ufs_vreg *vreg)
8395 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
8398 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
8399 struct ufs_vreg *vreg)
8404 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
8407 static int ufshcd_config_vreg(struct device *dev,
8408 struct ufs_vreg *vreg, bool on)
8410 if (regulator_count_voltages(vreg->reg) <= 0)
8413 return ufshcd_config_vreg_load(dev, vreg, on ? vreg->max_uA : 0);
8416 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
8420 if (!vreg || vreg->enabled)
8423 ret = ufshcd_config_vreg(dev, vreg, true);
8425 ret = regulator_enable(vreg->reg);
8428 vreg->enabled = true;
8430 dev_err(dev, "%s: %s enable failed, err=%d\n",
8431 __func__, vreg->name, ret);
8436 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
8440 if (!vreg || !vreg->enabled || vreg->always_on)
8443 ret = regulator_disable(vreg->reg);
8446 /* ignore errors on applying disable config */
8447 ufshcd_config_vreg(dev, vreg, false);
8448 vreg->enabled = false;
8450 dev_err(dev, "%s: %s disable failed, err=%d\n",
8451 __func__, vreg->name, ret);
8457 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
8460 struct device *dev = hba->dev;
8461 struct ufs_vreg_info *info = &hba->vreg_info;
8463 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
8467 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
8471 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
8475 ufshcd_toggle_vreg(dev, info->vccq2, false);
8476 ufshcd_toggle_vreg(dev, info->vccq, false);
8477 ufshcd_toggle_vreg(dev, info->vcc, false);
8482 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
8484 struct ufs_vreg_info *info = &hba->vreg_info;
8486 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
8489 int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
8496 vreg->reg = devm_regulator_get(dev, vreg->name);
8497 if (IS_ERR(vreg->reg)) {
8498 ret = PTR_ERR(vreg->reg);
8499 dev_err(dev, "%s: %s get failed, err=%d\n",
8500 __func__, vreg->name, ret);
8505 EXPORT_SYMBOL_GPL(ufshcd_get_vreg);
8507 static int ufshcd_init_vreg(struct ufs_hba *hba)
8510 struct device *dev = hba->dev;
8511 struct ufs_vreg_info *info = &hba->vreg_info;
8513 ret = ufshcd_get_vreg(dev, info->vcc);
8517 ret = ufshcd_get_vreg(dev, info->vccq);
8519 ret = ufshcd_get_vreg(dev, info->vccq2);
8524 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
8526 struct ufs_vreg_info *info = &hba->vreg_info;
8528 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
8531 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
8534 struct ufs_clk_info *clki;
8535 struct list_head *head = &hba->clk_list_head;
8536 unsigned long flags;
8537 ktime_t start = ktime_get();
8538 bool clk_state_changed = false;
8540 if (list_empty(head))
8543 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
8547 list_for_each_entry(clki, head, list) {
8548 if (!IS_ERR_OR_NULL(clki->clk)) {
8550 * Don't disable clocks which are needed
8551 * to keep the link active.
8553 if (ufshcd_is_link_active(hba) &&
8554 clki->keep_link_active)
8557 clk_state_changed = on ^ clki->enabled;
8558 if (on && !clki->enabled) {
8559 ret = clk_prepare_enable(clki->clk);
8561 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
8562 __func__, clki->name, ret);
8565 } else if (!on && clki->enabled) {
8566 clk_disable_unprepare(clki->clk);
8569 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
8570 clki->name, on ? "en" : "dis");
8574 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
8580 list_for_each_entry(clki, head, list) {
8581 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
8582 clk_disable_unprepare(clki->clk);
8584 } else if (!ret && on) {
8585 spin_lock_irqsave(hba->host->host_lock, flags);
8586 hba->clk_gating.state = CLKS_ON;
8587 trace_ufshcd_clk_gating(dev_name(hba->dev),
8588 hba->clk_gating.state);
8589 spin_unlock_irqrestore(hba->host->host_lock, flags);
8592 if (clk_state_changed)
8593 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
8594 (on ? "on" : "off"),
8595 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
8599 static enum ufs_ref_clk_freq ufshcd_parse_ref_clk_property(struct ufs_hba *hba)
8602 int ret = device_property_read_u32(hba->dev, "ref-clk-freq", &freq);
8605 dev_dbg(hba->dev, "Cannot query 'ref-clk-freq' property = %d", ret);
8606 return REF_CLK_FREQ_INVAL;
8609 return ufs_get_bref_clk_from_hz(freq);
8612 static int ufshcd_init_clocks(struct ufs_hba *hba)
8615 struct ufs_clk_info *clki;
8616 struct device *dev = hba->dev;
8617 struct list_head *head = &hba->clk_list_head;
8619 if (list_empty(head))
8622 list_for_each_entry(clki, head, list) {
8626 clki->clk = devm_clk_get(dev, clki->name);
8627 if (IS_ERR(clki->clk)) {
8628 ret = PTR_ERR(clki->clk);
8629 dev_err(dev, "%s: %s clk get failed, %d\n",
8630 __func__, clki->name, ret);
8635 * Parse device ref clk freq as per device tree "ref_clk".
8636 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
8637 * in ufshcd_alloc_host().
8639 if (!strcmp(clki->name, "ref_clk"))
8640 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
8642 if (clki->max_freq) {
8643 ret = clk_set_rate(clki->clk, clki->max_freq);
8645 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
8646 __func__, clki->name,
8647 clki->max_freq, ret);
8650 clki->curr_freq = clki->max_freq;
8652 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
8653 clki->name, clk_get_rate(clki->clk));
8659 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
8666 err = ufshcd_vops_init(hba);
8668 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
8669 __func__, ufshcd_get_var_name(hba), err);
8674 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
8679 ufshcd_vops_exit(hba);
8682 static int ufshcd_hba_init(struct ufs_hba *hba)
8687 * Handle host controller power separately from the UFS device power
8688 * rails as it will help controlling the UFS host controller power
8689 * collapse easily which is different than UFS device power collapse.
8690 * Also, enable the host controller power before we go ahead with rest
8691 * of the initialization here.
8693 err = ufshcd_init_hba_vreg(hba);
8697 err = ufshcd_setup_hba_vreg(hba, true);
8701 err = ufshcd_init_clocks(hba);
8703 goto out_disable_hba_vreg;
8705 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
8706 hba->dev_ref_clk_freq = ufshcd_parse_ref_clk_property(hba);
8708 err = ufshcd_setup_clocks(hba, true);
8710 goto out_disable_hba_vreg;
8712 err = ufshcd_init_vreg(hba);
8714 goto out_disable_clks;
8716 err = ufshcd_setup_vreg(hba, true);
8718 goto out_disable_clks;
8720 err = ufshcd_variant_hba_init(hba);
8722 goto out_disable_vreg;
8724 ufs_debugfs_hba_init(hba);
8726 hba->is_powered = true;
8730 ufshcd_setup_vreg(hba, false);
8732 ufshcd_setup_clocks(hba, false);
8733 out_disable_hba_vreg:
8734 ufshcd_setup_hba_vreg(hba, false);
8739 static void ufshcd_hba_exit(struct ufs_hba *hba)
8741 if (hba->is_powered) {
8742 ufshcd_exit_clk_scaling(hba);
8743 ufshcd_exit_clk_gating(hba);
8745 destroy_workqueue(hba->eh_wq);
8746 ufs_debugfs_hba_exit(hba);
8747 ufshcd_variant_hba_exit(hba);
8748 ufshcd_setup_vreg(hba, false);
8749 ufshcd_setup_clocks(hba, false);
8750 ufshcd_setup_hba_vreg(hba, false);
8751 hba->is_powered = false;
8752 ufs_put_device_desc(hba);
8756 static int ufshcd_execute_start_stop(struct scsi_device *sdev,
8757 enum ufs_dev_pwr_mode pwr_mode,
8758 struct scsi_sense_hdr *sshdr)
8760 unsigned char cdb[6] = { START_STOP, 0, 0, 0, pwr_mode << 4, 0 };
8761 struct request *req;
8762 struct scsi_cmnd *scmd;
8765 req = scsi_alloc_request(sdev->request_queue, REQ_OP_DRV_IN,
8768 return PTR_ERR(req);
8770 scmd = blk_mq_rq_to_pdu(req);
8771 scmd->cmd_len = COMMAND_SIZE(cdb[0]);
8772 memcpy(scmd->cmnd, cdb, scmd->cmd_len);
8773 scmd->allowed = 0/*retries*/;
8774 scmd->flags |= SCMD_FAIL_IF_RECOVERING;
8775 req->timeout = 1 * HZ;
8776 req->rq_flags |= RQF_PM | RQF_QUIET;
8778 blk_execute_rq(req, /*at_head=*/true);
8781 scsi_normalize_sense(scmd->sense_buffer, scmd->sense_len,
8785 blk_mq_free_request(req);
8791 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
8793 * @hba: per adapter instance
8794 * @pwr_mode: device power mode to set
8796 * Returns 0 if requested power mode is set successfully
8797 * Returns < 0 if failed to set the requested power mode
8799 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
8800 enum ufs_dev_pwr_mode pwr_mode)
8802 struct scsi_sense_hdr sshdr;
8803 struct scsi_device *sdp;
8804 unsigned long flags;
8807 spin_lock_irqsave(hba->host->host_lock, flags);
8808 sdp = hba->ufs_device_wlun;
8809 if (sdp && scsi_device_online(sdp))
8810 ret = scsi_device_get(sdp);
8813 spin_unlock_irqrestore(hba->host->host_lock, flags);
8819 * If scsi commands fail, the scsi mid-layer schedules scsi error-
8820 * handling, which would wait for host to be resumed. Since we know
8821 * we are functional while we are here, skip host resume in error
8824 hba->host->eh_noresume = 1;
8827 * Current function would be generally called from the power management
8828 * callbacks hence set the RQF_PM flag so that it doesn't resume the
8829 * already suspended childs.
8831 for (retries = 3; retries > 0; --retries) {
8832 ret = ufshcd_execute_start_stop(sdp, pwr_mode, &sshdr);
8834 * scsi_execute() only returns a negative value if the request
8841 sdev_printk(KERN_WARNING, sdp,
8842 "START_STOP failed for power mode: %d, result %x\n",
8845 if (scsi_sense_valid(&sshdr))
8846 scsi_print_sense_hdr(sdp, NULL, &sshdr);
8850 hba->curr_dev_pwr_mode = pwr_mode;
8853 scsi_device_put(sdp);
8854 hba->host->eh_noresume = 0;
8858 static int ufshcd_link_state_transition(struct ufs_hba *hba,
8859 enum uic_link_state req_link_state,
8860 bool check_for_bkops)
8864 if (req_link_state == hba->uic_link_state)
8867 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
8868 ret = ufshcd_uic_hibern8_enter(hba);
8870 ufshcd_set_link_hibern8(hba);
8872 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8878 * If autobkops is enabled, link can't be turned off because
8879 * turning off the link would also turn off the device, except in the
8880 * case of DeepSleep where the device is expected to remain powered.
8882 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
8883 (!check_for_bkops || !hba->auto_bkops_enabled)) {
8885 * Let's make sure that link is in low power mode, we are doing
8886 * this currently by putting the link in Hibern8. Otherway to
8887 * put the link in low power mode is to send the DME end point
8888 * to device and then send the DME reset command to local
8889 * unipro. But putting the link in hibern8 is much faster.
8891 * Note also that putting the link in Hibern8 is a requirement
8892 * for entering DeepSleep.
8894 ret = ufshcd_uic_hibern8_enter(hba);
8896 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8901 * Change controller state to "reset state" which
8902 * should also put the link in off/reset state
8904 ufshcd_hba_stop(hba);
8906 * TODO: Check if we need any delay to make sure that
8907 * controller is reset
8909 ufshcd_set_link_off(hba);
8916 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
8918 bool vcc_off = false;
8921 * It seems some UFS devices may keep drawing more than sleep current
8922 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
8923 * To avoid this situation, add 2ms delay before putting these UFS
8924 * rails in LPM mode.
8926 if (!ufshcd_is_link_active(hba) &&
8927 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
8928 usleep_range(2000, 2100);
8931 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
8934 * If UFS device and link is in OFF state, all power supplies (VCC,
8935 * VCCQ, VCCQ2) can be turned off if power on write protect is not
8936 * required. If UFS link is inactive (Hibern8 or OFF state) and device
8937 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
8939 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
8940 * in low power state which would save some power.
8942 * If Write Booster is enabled and the device needs to flush the WB
8943 * buffer OR if bkops status is urgent for WB, keep Vcc on.
8945 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8946 !hba->dev_info.is_lu_power_on_wp) {
8947 ufshcd_setup_vreg(hba, false);
8949 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8950 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8952 if (ufshcd_is_link_hibern8(hba) || ufshcd_is_link_off(hba)) {
8953 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8954 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
8959 * Some UFS devices require delay after VCC power rail is turned-off.
8961 if (vcc_off && hba->vreg_info.vcc &&
8962 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_AFTER_LPM)
8963 usleep_range(5000, 5100);
8967 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
8971 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8972 !hba->dev_info.is_lu_power_on_wp) {
8973 ret = ufshcd_setup_vreg(hba, true);
8974 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8975 if (!ufshcd_is_link_active(hba)) {
8976 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
8979 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
8983 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
8988 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8990 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8994 #endif /* CONFIG_PM */
8996 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
8998 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
8999 ufshcd_setup_hba_vreg(hba, false);
9002 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
9004 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
9005 ufshcd_setup_hba_vreg(hba, true);
9008 static int __ufshcd_wl_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
9011 bool check_for_bkops;
9012 enum ufs_pm_level pm_lvl;
9013 enum ufs_dev_pwr_mode req_dev_pwr_mode;
9014 enum uic_link_state req_link_state;
9016 hba->pm_op_in_progress = true;
9017 if (pm_op != UFS_SHUTDOWN_PM) {
9018 pm_lvl = pm_op == UFS_RUNTIME_PM ?
9019 hba->rpm_lvl : hba->spm_lvl;
9020 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
9021 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
9023 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
9024 req_link_state = UIC_LINK_OFF_STATE;
9027 ufshpb_suspend(hba);
9030 * If we can't transition into any of the low power modes
9031 * just gate the clocks.
9033 ufshcd_hold(hba, false);
9034 hba->clk_gating.is_suspended = true;
9036 if (ufshcd_is_clkscaling_supported(hba))
9037 ufshcd_clk_scaling_suspend(hba, true);
9039 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
9040 req_link_state == UIC_LINK_ACTIVE_STATE) {
9044 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
9045 (req_link_state == hba->uic_link_state))
9046 goto enable_scaling;
9048 /* UFS device & link must be active before we enter in this function */
9049 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
9051 goto enable_scaling;
9054 if (pm_op == UFS_RUNTIME_PM) {
9055 if (ufshcd_can_autobkops_during_suspend(hba)) {
9057 * The device is idle with no requests in the queue,
9058 * allow background operations if bkops status shows
9059 * that performance might be impacted.
9061 ret = ufshcd_urgent_bkops(hba);
9063 goto enable_scaling;
9065 /* make sure that auto bkops is disabled */
9066 ufshcd_disable_auto_bkops(hba);
9069 * If device needs to do BKOP or WB buffer flush during
9070 * Hibern8, keep device power mode as "active power mode"
9073 hba->dev_info.b_rpm_dev_flush_capable =
9074 hba->auto_bkops_enabled ||
9075 (((req_link_state == UIC_LINK_HIBERN8_STATE) ||
9076 ((req_link_state == UIC_LINK_ACTIVE_STATE) &&
9077 ufshcd_is_auto_hibern8_enabled(hba))) &&
9078 ufshcd_wb_need_flush(hba));
9081 flush_work(&hba->eeh_work);
9083 ret = ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
9085 goto enable_scaling;
9087 if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) {
9088 if (pm_op != UFS_RUNTIME_PM)
9089 /* ensure that bkops is disabled */
9090 ufshcd_disable_auto_bkops(hba);
9092 if (!hba->dev_info.b_rpm_dev_flush_capable) {
9093 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
9094 if (ret && pm_op != UFS_SHUTDOWN_PM) {
9096 * If return err in suspend flow, IO will hang.
9097 * Trigger error handler and break suspend for
9100 ufshcd_force_error_recovery(hba);
9104 goto enable_scaling;
9109 * In the case of DeepSleep, the device is expected to remain powered
9110 * with the link off, so do not check for bkops.
9112 check_for_bkops = !ufshcd_is_ufs_dev_deepsleep(hba);
9113 ret = ufshcd_link_state_transition(hba, req_link_state, check_for_bkops);
9114 if (ret && pm_op != UFS_SHUTDOWN_PM) {
9116 * If return err in suspend flow, IO will hang.
9117 * Trigger error handler and break suspend for
9120 ufshcd_force_error_recovery(hba);
9124 goto set_dev_active;
9128 * Call vendor specific suspend callback. As these callbacks may access
9129 * vendor specific host controller register space call them before the
9130 * host clocks are ON.
9132 ret = ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
9134 goto set_link_active;
9139 * Device hardware reset is required to exit DeepSleep. Also, for
9140 * DeepSleep, the link is off so host reset and restore will be done
9143 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
9144 ufshcd_device_reset(hba);
9145 WARN_ON(!ufshcd_is_link_off(hba));
9147 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
9148 ufshcd_set_link_active(hba);
9149 else if (ufshcd_is_link_off(hba))
9150 ufshcd_host_reset_and_restore(hba);
9152 /* Can also get here needing to exit DeepSleep */
9153 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
9154 ufshcd_device_reset(hba);
9155 ufshcd_host_reset_and_restore(hba);
9157 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
9158 ufshcd_disable_auto_bkops(hba);
9160 if (ufshcd_is_clkscaling_supported(hba))
9161 ufshcd_clk_scaling_suspend(hba, false);
9163 hba->dev_info.b_rpm_dev_flush_capable = false;
9165 if (hba->dev_info.b_rpm_dev_flush_capable) {
9166 schedule_delayed_work(&hba->rpm_dev_flush_recheck_work,
9167 msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS));
9171 ufshcd_update_evt_hist(hba, UFS_EVT_WL_SUSP_ERR, (u32)ret);
9172 hba->clk_gating.is_suspended = false;
9173 ufshcd_release(hba);
9176 hba->pm_op_in_progress = false;
9181 static int __ufshcd_wl_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
9184 enum uic_link_state old_link_state = hba->uic_link_state;
9186 hba->pm_op_in_progress = true;
9189 * Call vendor specific resume callback. As these callbacks may access
9190 * vendor specific host controller register space call them when the
9191 * host clocks are ON.
9193 ret = ufshcd_vops_resume(hba, pm_op);
9197 /* For DeepSleep, the only supported option is to have the link off */
9198 WARN_ON(ufshcd_is_ufs_dev_deepsleep(hba) && !ufshcd_is_link_off(hba));
9200 if (ufshcd_is_link_hibern8(hba)) {
9201 ret = ufshcd_uic_hibern8_exit(hba);
9203 ufshcd_set_link_active(hba);
9205 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
9207 goto vendor_suspend;
9209 } else if (ufshcd_is_link_off(hba)) {
9211 * A full initialization of the host and the device is
9212 * required since the link was put to off during suspend.
9213 * Note, in the case of DeepSleep, the device will exit
9214 * DeepSleep due to device reset.
9216 ret = ufshcd_reset_and_restore(hba);
9218 * ufshcd_reset_and_restore() should have already
9219 * set the link state as active
9221 if (ret || !ufshcd_is_link_active(hba))
9222 goto vendor_suspend;
9225 if (!ufshcd_is_ufs_dev_active(hba)) {
9226 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
9228 goto set_old_link_state;
9231 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
9232 ufshcd_enable_auto_bkops(hba);
9235 * If BKOPs operations are urgently needed at this moment then
9236 * keep auto-bkops enabled or else disable it.
9238 ufshcd_urgent_bkops(hba);
9240 if (hba->ee_usr_mask)
9241 ufshcd_write_ee_control(hba);
9243 if (ufshcd_is_clkscaling_supported(hba))
9244 ufshcd_clk_scaling_suspend(hba, false);
9246 if (hba->dev_info.b_rpm_dev_flush_capable) {
9247 hba->dev_info.b_rpm_dev_flush_capable = false;
9248 cancel_delayed_work(&hba->rpm_dev_flush_recheck_work);
9251 /* Enable Auto-Hibernate if configured */
9252 ufshcd_auto_hibern8_enable(hba);
9258 ufshcd_link_state_transition(hba, old_link_state, 0);
9260 ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
9261 ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
9264 ufshcd_update_evt_hist(hba, UFS_EVT_WL_RES_ERR, (u32)ret);
9265 hba->clk_gating.is_suspended = false;
9266 ufshcd_release(hba);
9267 hba->pm_op_in_progress = false;
9271 static int ufshcd_wl_runtime_suspend(struct device *dev)
9273 struct scsi_device *sdev = to_scsi_device(dev);
9274 struct ufs_hba *hba;
9276 ktime_t start = ktime_get();
9278 hba = shost_priv(sdev->host);
9280 ret = __ufshcd_wl_suspend(hba, UFS_RUNTIME_PM);
9282 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9284 trace_ufshcd_wl_runtime_suspend(dev_name(dev), ret,
9285 ktime_to_us(ktime_sub(ktime_get(), start)),
9286 hba->curr_dev_pwr_mode, hba->uic_link_state);
9291 static int ufshcd_wl_runtime_resume(struct device *dev)
9293 struct scsi_device *sdev = to_scsi_device(dev);
9294 struct ufs_hba *hba;
9296 ktime_t start = ktime_get();
9298 hba = shost_priv(sdev->host);
9300 ret = __ufshcd_wl_resume(hba, UFS_RUNTIME_PM);
9302 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9304 trace_ufshcd_wl_runtime_resume(dev_name(dev), ret,
9305 ktime_to_us(ktime_sub(ktime_get(), start)),
9306 hba->curr_dev_pwr_mode, hba->uic_link_state);
9312 #ifdef CONFIG_PM_SLEEP
9313 static int ufshcd_wl_suspend(struct device *dev)
9315 struct scsi_device *sdev = to_scsi_device(dev);
9316 struct ufs_hba *hba;
9318 ktime_t start = ktime_get();
9320 hba = shost_priv(sdev->host);
9321 down(&hba->host_sem);
9322 hba->system_suspending = true;
9324 if (pm_runtime_suspended(dev))
9327 ret = __ufshcd_wl_suspend(hba, UFS_SYSTEM_PM);
9329 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9335 hba->is_sys_suspended = true;
9336 trace_ufshcd_wl_suspend(dev_name(dev), ret,
9337 ktime_to_us(ktime_sub(ktime_get(), start)),
9338 hba->curr_dev_pwr_mode, hba->uic_link_state);
9343 static int ufshcd_wl_resume(struct device *dev)
9345 struct scsi_device *sdev = to_scsi_device(dev);
9346 struct ufs_hba *hba;
9348 ktime_t start = ktime_get();
9350 hba = shost_priv(sdev->host);
9352 if (pm_runtime_suspended(dev))
9355 ret = __ufshcd_wl_resume(hba, UFS_SYSTEM_PM);
9357 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9359 trace_ufshcd_wl_resume(dev_name(dev), ret,
9360 ktime_to_us(ktime_sub(ktime_get(), start)),
9361 hba->curr_dev_pwr_mode, hba->uic_link_state);
9363 hba->is_sys_suspended = false;
9364 hba->system_suspending = false;
9370 static void ufshcd_wl_shutdown(struct device *dev)
9372 struct scsi_device *sdev = to_scsi_device(dev);
9373 struct ufs_hba *hba;
9375 hba = shost_priv(sdev->host);
9377 down(&hba->host_sem);
9378 hba->shutting_down = true;
9381 /* Turn on everything while shutting down */
9382 ufshcd_rpm_get_sync(hba);
9383 scsi_device_quiesce(sdev);
9384 shost_for_each_device(sdev, hba->host) {
9385 if (sdev == hba->ufs_device_wlun)
9387 scsi_device_quiesce(sdev);
9389 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
9393 * ufshcd_suspend - helper function for suspend operations
9394 * @hba: per adapter instance
9396 * This function will put disable irqs, turn off clocks
9397 * and set vreg and hba-vreg in lpm mode.
9399 static int ufshcd_suspend(struct ufs_hba *hba)
9403 if (!hba->is_powered)
9406 * Disable the host irq as host controller as there won't be any
9407 * host controller transaction expected till resume.
9409 ufshcd_disable_irq(hba);
9410 ret = ufshcd_setup_clocks(hba, false);
9412 ufshcd_enable_irq(hba);
9415 if (ufshcd_is_clkgating_allowed(hba)) {
9416 hba->clk_gating.state = CLKS_OFF;
9417 trace_ufshcd_clk_gating(dev_name(hba->dev),
9418 hba->clk_gating.state);
9421 ufshcd_vreg_set_lpm(hba);
9422 /* Put the host controller in low power mode if possible */
9423 ufshcd_hba_vreg_set_lpm(hba);
9429 * ufshcd_resume - helper function for resume operations
9430 * @hba: per adapter instance
9432 * This function basically turns on the regulators, clocks and
9435 * Returns 0 for success and non-zero for failure
9437 static int ufshcd_resume(struct ufs_hba *hba)
9441 if (!hba->is_powered)
9444 ufshcd_hba_vreg_set_hpm(hba);
9445 ret = ufshcd_vreg_set_hpm(hba);
9449 /* Make sure clocks are enabled before accessing controller */
9450 ret = ufshcd_setup_clocks(hba, true);
9454 /* enable the host irq as host controller would be active soon */
9455 ufshcd_enable_irq(hba);
9459 ufshcd_vreg_set_lpm(hba);
9462 ufshcd_update_evt_hist(hba, UFS_EVT_RESUME_ERR, (u32)ret);
9465 #endif /* CONFIG_PM */
9467 #ifdef CONFIG_PM_SLEEP
9469 * ufshcd_system_suspend - system suspend callback
9470 * @dev: Device associated with the UFS controller.
9472 * Executed before putting the system into a sleep state in which the contents
9473 * of main memory are preserved.
9475 * Returns 0 for success and non-zero for failure
9477 int ufshcd_system_suspend(struct device *dev)
9479 struct ufs_hba *hba = dev_get_drvdata(dev);
9481 ktime_t start = ktime_get();
9483 if (pm_runtime_suspended(hba->dev))
9486 ret = ufshcd_suspend(hba);
9488 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
9489 ktime_to_us(ktime_sub(ktime_get(), start)),
9490 hba->curr_dev_pwr_mode, hba->uic_link_state);
9493 EXPORT_SYMBOL(ufshcd_system_suspend);
9496 * ufshcd_system_resume - system resume callback
9497 * @dev: Device associated with the UFS controller.
9499 * Executed after waking the system up from a sleep state in which the contents
9500 * of main memory were preserved.
9502 * Returns 0 for success and non-zero for failure
9504 int ufshcd_system_resume(struct device *dev)
9506 struct ufs_hba *hba = dev_get_drvdata(dev);
9507 ktime_t start = ktime_get();
9510 if (pm_runtime_suspended(hba->dev))
9513 ret = ufshcd_resume(hba);
9516 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
9517 ktime_to_us(ktime_sub(ktime_get(), start)),
9518 hba->curr_dev_pwr_mode, hba->uic_link_state);
9522 EXPORT_SYMBOL(ufshcd_system_resume);
9523 #endif /* CONFIG_PM_SLEEP */
9527 * ufshcd_runtime_suspend - runtime suspend callback
9528 * @dev: Device associated with the UFS controller.
9530 * Check the description of ufshcd_suspend() function for more details.
9532 * Returns 0 for success and non-zero for failure
9534 int ufshcd_runtime_suspend(struct device *dev)
9536 struct ufs_hba *hba = dev_get_drvdata(dev);
9538 ktime_t start = ktime_get();
9540 ret = ufshcd_suspend(hba);
9542 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
9543 ktime_to_us(ktime_sub(ktime_get(), start)),
9544 hba->curr_dev_pwr_mode, hba->uic_link_state);
9547 EXPORT_SYMBOL(ufshcd_runtime_suspend);
9550 * ufshcd_runtime_resume - runtime resume routine
9551 * @dev: Device associated with the UFS controller.
9553 * This function basically brings controller
9554 * to active state. Following operations are done in this function:
9556 * 1. Turn on all the controller related clocks
9557 * 2. Turn ON VCC rail
9559 int ufshcd_runtime_resume(struct device *dev)
9561 struct ufs_hba *hba = dev_get_drvdata(dev);
9563 ktime_t start = ktime_get();
9565 ret = ufshcd_resume(hba);
9567 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
9568 ktime_to_us(ktime_sub(ktime_get(), start)),
9569 hba->curr_dev_pwr_mode, hba->uic_link_state);
9572 EXPORT_SYMBOL(ufshcd_runtime_resume);
9573 #endif /* CONFIG_PM */
9576 * ufshcd_shutdown - shutdown routine
9577 * @hba: per adapter instance
9579 * This function would turn off both UFS device and UFS hba
9580 * regulators. It would also disable clocks.
9582 * Returns 0 always to allow force shutdown even in case of errors.
9584 int ufshcd_shutdown(struct ufs_hba *hba)
9586 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
9587 ufshcd_suspend(hba);
9589 hba->is_powered = false;
9590 /* allow force shutdown even in case of errors */
9593 EXPORT_SYMBOL(ufshcd_shutdown);
9596 * ufshcd_remove - de-allocate SCSI host and host memory space
9597 * data structure memory
9598 * @hba: per adapter instance
9600 void ufshcd_remove(struct ufs_hba *hba)
9602 if (hba->ufs_device_wlun)
9603 ufshcd_rpm_get_sync(hba);
9604 ufs_hwmon_remove(hba);
9605 ufs_bsg_remove(hba);
9607 ufs_sysfs_remove_nodes(hba->dev);
9608 blk_mq_destroy_queue(hba->tmf_queue);
9609 blk_put_queue(hba->tmf_queue);
9610 blk_mq_free_tag_set(&hba->tmf_tag_set);
9611 scsi_remove_host(hba->host);
9612 /* disable interrupts */
9613 ufshcd_disable_intr(hba, hba->intr_mask);
9614 ufshcd_hba_stop(hba);
9615 ufshcd_hba_exit(hba);
9617 EXPORT_SYMBOL_GPL(ufshcd_remove);
9620 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
9621 * @hba: pointer to Host Bus Adapter (HBA)
9623 void ufshcd_dealloc_host(struct ufs_hba *hba)
9625 scsi_host_put(hba->host);
9627 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
9630 * ufshcd_set_dma_mask - Set dma mask based on the controller
9631 * addressing capability
9632 * @hba: per adapter instance
9634 * Returns 0 for success, non-zero for failure
9636 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
9638 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
9639 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
9642 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
9646 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
9647 * @dev: pointer to device handle
9648 * @hba_handle: driver private handle
9649 * Returns 0 on success, non-zero value on failure
9651 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
9653 struct Scsi_Host *host;
9654 struct ufs_hba *hba;
9659 "Invalid memory reference for dev is NULL\n");
9664 host = scsi_host_alloc(&ufshcd_driver_template,
9665 sizeof(struct ufs_hba));
9667 dev_err(dev, "scsi_host_alloc failed\n");
9671 host->nr_maps = HCTX_TYPE_POLL + 1;
9672 hba = shost_priv(host);
9675 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
9676 hba->nop_out_timeout = NOP_OUT_TIMEOUT;
9677 INIT_LIST_HEAD(&hba->clk_list_head);
9678 spin_lock_init(&hba->outstanding_lock);
9685 EXPORT_SYMBOL(ufshcd_alloc_host);
9687 /* This function exists because blk_mq_alloc_tag_set() requires this. */
9688 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx,
9689 const struct blk_mq_queue_data *qd)
9692 return BLK_STS_NOTSUPP;
9695 static const struct blk_mq_ops ufshcd_tmf_ops = {
9696 .queue_rq = ufshcd_queue_tmf,
9700 * ufshcd_init - Driver initialization routine
9701 * @hba: per-adapter instance
9702 * @mmio_base: base register address
9703 * @irq: Interrupt line of device
9704 * Returns 0 on success, non-zero value on failure
9706 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
9709 struct Scsi_Host *host = hba->host;
9710 struct device *dev = hba->dev;
9711 char eh_wq_name[sizeof("ufs_eh_wq_00")];
9714 * dev_set_drvdata() must be called before any callbacks are registered
9715 * that use dev_get_drvdata() (frequency scaling, clock scaling, hwmon,
9718 dev_set_drvdata(dev, hba);
9722 "Invalid memory reference for mmio_base is NULL\n");
9727 hba->mmio_base = mmio_base;
9729 hba->vps = &ufs_hba_vps;
9731 err = ufshcd_hba_init(hba);
9735 /* Read capabilities registers */
9736 err = ufshcd_hba_capabilities(hba);
9740 /* Get UFS version supported by the controller */
9741 hba->ufs_version = ufshcd_get_ufs_version(hba);
9743 /* Get Interrupt bit mask per version */
9744 hba->intr_mask = ufshcd_get_intr_mask(hba);
9746 err = ufshcd_set_dma_mask(hba);
9748 dev_err(hba->dev, "set dma mask failed\n");
9752 /* Allocate memory for host memory space */
9753 err = ufshcd_memory_alloc(hba);
9755 dev_err(hba->dev, "Memory allocation failed\n");
9760 ufshcd_host_memory_configure(hba);
9762 host->can_queue = hba->nutrs - UFSHCD_NUM_RESERVED;
9763 host->cmd_per_lun = hba->nutrs - UFSHCD_NUM_RESERVED;
9764 host->max_id = UFSHCD_MAX_ID;
9765 host->max_lun = UFS_MAX_LUNS;
9766 host->max_channel = UFSHCD_MAX_CHANNEL;
9767 host->unique_id = host->host_no;
9768 host->max_cmd_len = UFS_CDB_SIZE;
9770 hba->max_pwr_info.is_valid = false;
9772 /* Initialize work queues */
9773 snprintf(eh_wq_name, sizeof(eh_wq_name), "ufs_eh_wq_%d",
9774 hba->host->host_no);
9775 hba->eh_wq = create_singlethread_workqueue(eh_wq_name);
9777 dev_err(hba->dev, "%s: failed to create eh workqueue\n",
9782 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
9783 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
9785 sema_init(&hba->host_sem, 1);
9787 /* Initialize UIC command mutex */
9788 mutex_init(&hba->uic_cmd_mutex);
9790 /* Initialize mutex for device management commands */
9791 mutex_init(&hba->dev_cmd.lock);
9793 /* Initialize mutex for exception event control */
9794 mutex_init(&hba->ee_ctrl_mutex);
9796 mutex_init(&hba->wb_mutex);
9797 init_rwsem(&hba->clk_scaling_lock);
9799 ufshcd_init_clk_gating(hba);
9801 ufshcd_init_clk_scaling(hba);
9804 * In order to avoid any spurious interrupt immediately after
9805 * registering UFS controller interrupt handler, clear any pending UFS
9806 * interrupt status and disable all the UFS interrupts.
9808 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
9809 REG_INTERRUPT_STATUS);
9810 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
9812 * Make sure that UFS interrupts are disabled and any pending interrupt
9813 * status is cleared before registering UFS interrupt handler.
9817 /* IRQ registration */
9818 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
9820 dev_err(hba->dev, "request irq failed\n");
9823 hba->is_irq_enabled = true;
9826 err = scsi_add_host(host, hba->dev);
9828 dev_err(hba->dev, "scsi_add_host failed\n");
9832 hba->tmf_tag_set = (struct blk_mq_tag_set) {
9834 .queue_depth = hba->nutmrs,
9835 .ops = &ufshcd_tmf_ops,
9836 .flags = BLK_MQ_F_NO_SCHED,
9838 err = blk_mq_alloc_tag_set(&hba->tmf_tag_set);
9840 goto out_remove_scsi_host;
9841 hba->tmf_queue = blk_mq_init_queue(&hba->tmf_tag_set);
9842 if (IS_ERR(hba->tmf_queue)) {
9843 err = PTR_ERR(hba->tmf_queue);
9844 goto free_tmf_tag_set;
9846 hba->tmf_rqs = devm_kcalloc(hba->dev, hba->nutmrs,
9847 sizeof(*hba->tmf_rqs), GFP_KERNEL);
9848 if (!hba->tmf_rqs) {
9850 goto free_tmf_queue;
9853 /* Reset the attached device */
9854 ufshcd_device_reset(hba);
9856 ufshcd_init_crypto(hba);
9858 /* Host controller enable */
9859 err = ufshcd_hba_enable(hba);
9861 dev_err(hba->dev, "Host controller enable failed\n");
9862 ufshcd_print_evt_hist(hba);
9863 ufshcd_print_host_state(hba);
9864 goto free_tmf_queue;
9868 * Set the default power management level for runtime and system PM.
9869 * Default power saving mode is to keep UFS link in Hibern8 state
9870 * and UFS device in sleep state.
9872 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9874 UIC_LINK_HIBERN8_STATE);
9875 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9877 UIC_LINK_HIBERN8_STATE);
9879 INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work,
9880 ufshcd_rpm_dev_flush_recheck_work);
9882 /* Set the default auto-hiberate idle timer value to 150 ms */
9883 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
9884 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
9885 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
9888 /* Hold auto suspend until async scan completes */
9889 pm_runtime_get_sync(dev);
9890 atomic_set(&hba->scsi_block_reqs_cnt, 0);
9892 * We are assuming that device wasn't put in sleep/power-down
9893 * state exclusively during the boot stage before kernel.
9894 * This assumption helps avoid doing link startup twice during
9895 * ufshcd_probe_hba().
9897 ufshcd_set_ufs_dev_active(hba);
9899 async_schedule(ufshcd_async_scan, hba);
9900 ufs_sysfs_add_nodes(hba->dev);
9902 device_enable_async_suspend(dev);
9906 blk_mq_destroy_queue(hba->tmf_queue);
9907 blk_put_queue(hba->tmf_queue);
9909 blk_mq_free_tag_set(&hba->tmf_tag_set);
9910 out_remove_scsi_host:
9911 scsi_remove_host(hba->host);
9913 hba->is_irq_enabled = false;
9914 ufshcd_hba_exit(hba);
9918 EXPORT_SYMBOL_GPL(ufshcd_init);
9920 void ufshcd_resume_complete(struct device *dev)
9922 struct ufs_hba *hba = dev_get_drvdata(dev);
9924 if (hba->complete_put) {
9925 ufshcd_rpm_put(hba);
9926 hba->complete_put = false;
9929 EXPORT_SYMBOL_GPL(ufshcd_resume_complete);
9931 static bool ufshcd_rpm_ok_for_spm(struct ufs_hba *hba)
9933 struct device *dev = &hba->ufs_device_wlun->sdev_gendev;
9934 enum ufs_dev_pwr_mode dev_pwr_mode;
9935 enum uic_link_state link_state;
9936 unsigned long flags;
9939 spin_lock_irqsave(&dev->power.lock, flags);
9940 dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl);
9941 link_state = ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl);
9942 res = pm_runtime_suspended(dev) &&
9943 hba->curr_dev_pwr_mode == dev_pwr_mode &&
9944 hba->uic_link_state == link_state &&
9945 !hba->dev_info.b_rpm_dev_flush_capable;
9946 spin_unlock_irqrestore(&dev->power.lock, flags);
9951 int __ufshcd_suspend_prepare(struct device *dev, bool rpm_ok_for_spm)
9953 struct ufs_hba *hba = dev_get_drvdata(dev);
9957 * SCSI assumes that runtime-pm and system-pm for scsi drivers
9958 * are same. And it doesn't wake up the device for system-suspend
9959 * if it's runtime suspended. But ufs doesn't follow that.
9960 * Refer ufshcd_resume_complete()
9962 if (hba->ufs_device_wlun) {
9963 /* Prevent runtime suspend */
9964 ufshcd_rpm_get_noresume(hba);
9966 * Check if already runtime suspended in same state as system
9969 if (!rpm_ok_for_spm || !ufshcd_rpm_ok_for_spm(hba)) {
9970 /* RPM state is not ok for SPM, so runtime resume */
9971 ret = ufshcd_rpm_resume(hba);
9972 if (ret < 0 && ret != -EACCES) {
9973 ufshcd_rpm_put(hba);
9977 hba->complete_put = true;
9981 EXPORT_SYMBOL_GPL(__ufshcd_suspend_prepare);
9983 int ufshcd_suspend_prepare(struct device *dev)
9985 return __ufshcd_suspend_prepare(dev, true);
9987 EXPORT_SYMBOL_GPL(ufshcd_suspend_prepare);
9989 #ifdef CONFIG_PM_SLEEP
9990 static int ufshcd_wl_poweroff(struct device *dev)
9992 struct scsi_device *sdev = to_scsi_device(dev);
9993 struct ufs_hba *hba = shost_priv(sdev->host);
9995 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
10000 static int ufshcd_wl_probe(struct device *dev)
10002 struct scsi_device *sdev = to_scsi_device(dev);
10004 if (!is_device_wlun(sdev))
10007 blk_pm_runtime_init(sdev->request_queue, dev);
10008 pm_runtime_set_autosuspend_delay(dev, 0);
10009 pm_runtime_allow(dev);
10014 static int ufshcd_wl_remove(struct device *dev)
10016 pm_runtime_forbid(dev);
10020 static const struct dev_pm_ops ufshcd_wl_pm_ops = {
10021 #ifdef CONFIG_PM_SLEEP
10022 .suspend = ufshcd_wl_suspend,
10023 .resume = ufshcd_wl_resume,
10024 .freeze = ufshcd_wl_suspend,
10025 .thaw = ufshcd_wl_resume,
10026 .poweroff = ufshcd_wl_poweroff,
10027 .restore = ufshcd_wl_resume,
10029 SET_RUNTIME_PM_OPS(ufshcd_wl_runtime_suspend, ufshcd_wl_runtime_resume, NULL)
10033 * ufs_dev_wlun_template - describes ufs device wlun
10034 * ufs-device wlun - used to send pm commands
10035 * All luns are consumers of ufs-device wlun.
10037 * Currently, no sd driver is present for wluns.
10038 * Hence the no specific pm operations are performed.
10039 * With ufs design, SSU should be sent to ufs-device wlun.
10040 * Hence register a scsi driver for ufs wluns only.
10042 static struct scsi_driver ufs_dev_wlun_template = {
10044 .name = "ufs_device_wlun",
10045 .owner = THIS_MODULE,
10046 .probe = ufshcd_wl_probe,
10047 .remove = ufshcd_wl_remove,
10048 .pm = &ufshcd_wl_pm_ops,
10049 .shutdown = ufshcd_wl_shutdown,
10053 static int __init ufshcd_core_init(void)
10057 /* Verify that there are no gaps in struct utp_transfer_cmd_desc. */
10058 static_assert(sizeof(struct utp_transfer_cmd_desc) ==
10059 2 * ALIGNED_UPIU_SIZE +
10060 SG_ALL * sizeof(struct ufshcd_sg_entry));
10062 ufs_debugfs_init();
10064 ret = scsi_register_driver(&ufs_dev_wlun_template.gendrv);
10066 ufs_debugfs_exit();
10070 static void __exit ufshcd_core_exit(void)
10072 ufs_debugfs_exit();
10073 scsi_unregister_driver(&ufs_dev_wlun_template.gendrv);
10076 module_init(ufshcd_core_init);
10077 module_exit(ufshcd_core_exit);
10079 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
10080 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
10081 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
10082 MODULE_LICENSE("GPL");