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 |\
47 #define UFSHCD_ENABLE_MCQ_INTRS (UTP_TASK_REQ_COMPL |\
52 /* UIC command timeout, unit: ms */
53 #define UIC_CMD_TIMEOUT 500
55 /* NOP OUT retries waiting for NOP IN response */
56 #define NOP_OUT_RETRIES 10
57 /* Timeout after 50 msecs if NOP OUT hangs without response */
58 #define NOP_OUT_TIMEOUT 50 /* msecs */
60 /* Query request retries */
61 #define QUERY_REQ_RETRIES 3
62 /* Query request timeout */
63 #define QUERY_REQ_TIMEOUT 1500 /* 1.5 seconds */
65 /* Advanced RPMB request timeout */
66 #define ADVANCED_RPMB_REQ_TIMEOUT 3000 /* 3 seconds */
68 /* Task management command timeout */
69 #define TM_CMD_TIMEOUT 100 /* msecs */
71 /* maximum number of retries for a general UIC command */
72 #define UFS_UIC_COMMAND_RETRIES 3
74 /* maximum number of link-startup retries */
75 #define DME_LINKSTARTUP_RETRIES 3
77 /* maximum number of reset retries before giving up */
78 #define MAX_HOST_RESET_RETRIES 5
80 /* Maximum number of error handler retries before giving up */
81 #define MAX_ERR_HANDLER_RETRIES 5
83 /* Expose the flag value from utp_upiu_query.value */
84 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
86 /* Interrupt aggregation default timeout, unit: 40us */
87 #define INT_AGGR_DEF_TO 0x02
89 /* default delay of autosuspend: 2000 ms */
90 #define RPM_AUTOSUSPEND_DELAY_MS 2000
92 /* Default delay of RPM device flush delayed work */
93 #define RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS 5000
95 /* Default value of wait time before gating device ref clock */
96 #define UFSHCD_REF_CLK_GATING_WAIT_US 0xFF /* microsecs */
98 /* Polling time to wait for fDeviceInit */
99 #define FDEVICEINIT_COMPL_TIMEOUT 1500 /* millisecs */
101 /* UFSHC 4.0 compliant HC support this mode, refer param_set_mcq_mode() */
102 static bool use_mcq_mode = true;
104 static bool is_mcq_supported(struct ufs_hba *hba)
106 return hba->mcq_sup && use_mcq_mode;
109 static int param_set_mcq_mode(const char *val, const struct kernel_param *kp)
113 ret = param_set_bool(val, kp);
120 static const struct kernel_param_ops mcq_mode_ops = {
121 .set = param_set_mcq_mode,
122 .get = param_get_bool,
125 module_param_cb(use_mcq_mode, &mcq_mode_ops, &use_mcq_mode, 0644);
126 MODULE_PARM_DESC(use_mcq_mode, "Control MCQ mode for controllers starting from UFSHCI 4.0. 1 - enable MCQ, 0 - disable MCQ. MCQ is enabled by default");
128 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
132 _ret = ufshcd_enable_vreg(_dev, _vreg); \
134 _ret = ufshcd_disable_vreg(_dev, _vreg); \
138 #define ufshcd_hex_dump(prefix_str, buf, len) do { \
139 size_t __len = (len); \
140 print_hex_dump(KERN_ERR, prefix_str, \
141 __len > 4 ? DUMP_PREFIX_OFFSET : DUMP_PREFIX_NONE,\
142 16, 4, buf, __len, false); \
145 int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len,
151 if (offset % 4 != 0 || len % 4 != 0) /* keep readl happy */
154 regs = kzalloc(len, GFP_ATOMIC);
158 for (pos = 0; pos < len; pos += 4) {
160 pos >= REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER &&
161 pos <= REG_UIC_ERROR_CODE_DME)
163 regs[pos / 4] = ufshcd_readl(hba, offset + pos);
166 ufshcd_hex_dump(prefix, regs, len);
171 EXPORT_SYMBOL_GPL(ufshcd_dump_regs);
174 UFSHCD_MAX_CHANNEL = 0,
176 UFSHCD_CMD_PER_LUN = 32 - UFSHCD_NUM_RESERVED,
177 UFSHCD_CAN_QUEUE = 32 - UFSHCD_NUM_RESERVED,
180 static const char *const ufshcd_state_name[] = {
181 [UFSHCD_STATE_RESET] = "reset",
182 [UFSHCD_STATE_OPERATIONAL] = "operational",
183 [UFSHCD_STATE_ERROR] = "error",
184 [UFSHCD_STATE_EH_SCHEDULED_FATAL] = "eh_fatal",
185 [UFSHCD_STATE_EH_SCHEDULED_NON_FATAL] = "eh_non_fatal",
188 /* UFSHCD error handling flags */
190 UFSHCD_EH_IN_PROGRESS = (1 << 0),
193 /* UFSHCD UIC layer error flags */
195 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
196 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
197 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
198 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
199 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
200 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
201 UFSHCD_UIC_PA_GENERIC_ERROR = (1 << 6), /* Generic PA error */
204 #define ufshcd_set_eh_in_progress(h) \
205 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
206 #define ufshcd_eh_in_progress(h) \
207 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
208 #define ufshcd_clear_eh_in_progress(h) \
209 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
211 const struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
212 [UFS_PM_LVL_0] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
213 [UFS_PM_LVL_1] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
214 [UFS_PM_LVL_2] = {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
215 [UFS_PM_LVL_3] = {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
216 [UFS_PM_LVL_4] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
217 [UFS_PM_LVL_5] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
219 * For DeepSleep, the link is first put in hibern8 and then off.
220 * Leaving the link in hibern8 is not supported.
222 [UFS_PM_LVL_6] = {UFS_DEEPSLEEP_PWR_MODE, UIC_LINK_OFF_STATE},
225 static inline enum ufs_dev_pwr_mode
226 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
228 return ufs_pm_lvl_states[lvl].dev_state;
231 static inline enum uic_link_state
232 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
234 return ufs_pm_lvl_states[lvl].link_state;
237 static inline enum ufs_pm_level
238 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
239 enum uic_link_state link_state)
241 enum ufs_pm_level lvl;
243 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
244 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
245 (ufs_pm_lvl_states[lvl].link_state == link_state))
249 /* if no match found, return the level 0 */
253 static const struct ufs_dev_quirk ufs_fixups[] = {
254 /* UFS cards deviations table */
255 { .wmanufacturerid = UFS_VENDOR_MICRON,
256 .model = UFS_ANY_MODEL,
257 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
258 UFS_DEVICE_QUIRK_SWAP_L2P_ENTRY_FOR_HPB_READ },
259 { .wmanufacturerid = UFS_VENDOR_SAMSUNG,
260 .model = UFS_ANY_MODEL,
261 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
262 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE |
263 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS },
264 { .wmanufacturerid = UFS_VENDOR_SKHYNIX,
265 .model = UFS_ANY_MODEL,
266 .quirk = UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME },
267 { .wmanufacturerid = UFS_VENDOR_SKHYNIX,
268 .model = "hB8aL1" /*H28U62301AMR*/,
269 .quirk = UFS_DEVICE_QUIRK_HOST_VS_DEBUGSAVECONFIGTIME },
270 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
271 .model = UFS_ANY_MODEL,
272 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM },
273 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
274 .model = "THGLF2G9C8KBADG",
275 .quirk = UFS_DEVICE_QUIRK_PA_TACTIVATE },
276 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
277 .model = "THGLF2G9D8KBADG",
278 .quirk = UFS_DEVICE_QUIRK_PA_TACTIVATE },
282 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba);
283 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
284 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
285 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
286 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
287 static void ufshcd_hba_exit(struct ufs_hba *hba);
288 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params);
289 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
290 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
291 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
292 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
293 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
294 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba);
295 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up);
296 static irqreturn_t ufshcd_intr(int irq, void *__hba);
297 static int ufshcd_change_power_mode(struct ufs_hba *hba,
298 struct ufs_pa_layer_attr *pwr_mode);
299 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on);
300 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on);
301 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
302 struct ufs_vreg *vreg);
303 static void ufshcd_wb_toggle_buf_flush_during_h8(struct ufs_hba *hba,
305 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba);
306 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba);
308 static inline void ufshcd_enable_irq(struct ufs_hba *hba)
310 if (!hba->is_irq_enabled) {
311 enable_irq(hba->irq);
312 hba->is_irq_enabled = true;
316 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
318 if (hba->is_irq_enabled) {
319 disable_irq(hba->irq);
320 hba->is_irq_enabled = false;
324 static void ufshcd_configure_wb(struct ufs_hba *hba)
326 if (!ufshcd_is_wb_allowed(hba))
329 ufshcd_wb_toggle(hba, true);
331 ufshcd_wb_toggle_buf_flush_during_h8(hba, true);
333 if (ufshcd_is_wb_buf_flush_allowed(hba))
334 ufshcd_wb_toggle_buf_flush(hba, true);
337 static void ufshcd_scsi_unblock_requests(struct ufs_hba *hba)
339 if (atomic_dec_and_test(&hba->scsi_block_reqs_cnt))
340 scsi_unblock_requests(hba->host);
343 static void ufshcd_scsi_block_requests(struct ufs_hba *hba)
345 if (atomic_inc_return(&hba->scsi_block_reqs_cnt) == 1)
346 scsi_block_requests(hba->host);
349 static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba, unsigned int tag,
350 enum ufs_trace_str_t str_t)
352 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
353 struct utp_upiu_header *header;
355 if (!trace_ufshcd_upiu_enabled())
358 if (str_t == UFS_CMD_SEND)
359 header = &rq->header;
361 header = &hba->lrb[tag].ucd_rsp_ptr->header;
363 trace_ufshcd_upiu(dev_name(hba->dev), str_t, header, &rq->sc.cdb,
367 static void ufshcd_add_query_upiu_trace(struct ufs_hba *hba,
368 enum ufs_trace_str_t str_t,
369 struct utp_upiu_req *rq_rsp)
371 if (!trace_ufshcd_upiu_enabled())
374 trace_ufshcd_upiu(dev_name(hba->dev), str_t, &rq_rsp->header,
375 &rq_rsp->qr, UFS_TSF_OSF);
378 static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag,
379 enum ufs_trace_str_t str_t)
381 struct utp_task_req_desc *descp = &hba->utmrdl_base_addr[tag];
383 if (!trace_ufshcd_upiu_enabled())
386 if (str_t == UFS_TM_SEND)
387 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
388 &descp->upiu_req.req_header,
389 &descp->upiu_req.input_param1,
392 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
393 &descp->upiu_rsp.rsp_header,
394 &descp->upiu_rsp.output_param1,
398 static void ufshcd_add_uic_command_trace(struct ufs_hba *hba,
399 const struct uic_command *ucmd,
400 enum ufs_trace_str_t str_t)
404 if (!trace_ufshcd_uic_command_enabled())
407 if (str_t == UFS_CMD_SEND)
410 cmd = ufshcd_readl(hba, REG_UIC_COMMAND);
412 trace_ufshcd_uic_command(dev_name(hba->dev), str_t, cmd,
413 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_1),
414 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2),
415 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3));
418 static void ufshcd_add_command_trace(struct ufs_hba *hba, unsigned int tag,
419 enum ufs_trace_str_t str_t)
422 u8 opcode = 0, group_id = 0;
426 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
427 struct scsi_cmnd *cmd = lrbp->cmd;
428 struct request *rq = scsi_cmd_to_rq(cmd);
429 int transfer_len = -1;
434 /* trace UPIU also */
435 ufshcd_add_cmd_upiu_trace(hba, tag, str_t);
436 if (!trace_ufshcd_command_enabled())
439 opcode = cmd->cmnd[0];
441 if (opcode == READ_10 || opcode == WRITE_10) {
443 * Currently we only fully trace read(10) and write(10) commands
446 be32_to_cpu(lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
447 lba = scsi_get_lba(cmd);
448 if (opcode == WRITE_10)
449 group_id = lrbp->cmd->cmnd[6];
450 } else if (opcode == UNMAP) {
452 * The number of Bytes to be unmapped beginning with the lba.
454 transfer_len = blk_rq_bytes(rq);
455 lba = scsi_get_lba(cmd);
458 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
460 if (is_mcq_enabled(hba)) {
461 struct ufs_hw_queue *hwq = ufshcd_mcq_req_to_hwq(hba, rq);
465 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
467 trace_ufshcd_command(dev_name(hba->dev), str_t, tag,
468 doorbell, hwq_id, transfer_len, intr, lba, opcode, group_id);
471 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
473 struct ufs_clk_info *clki;
474 struct list_head *head = &hba->clk_list_head;
476 if (list_empty(head))
479 list_for_each_entry(clki, head, list) {
480 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
482 dev_err(hba->dev, "clk: %s, rate: %u\n",
483 clki->name, clki->curr_freq);
487 static void ufshcd_print_evt(struct ufs_hba *hba, u32 id,
488 const char *err_name)
492 const struct ufs_event_hist *e;
494 if (id >= UFS_EVT_CNT)
497 e = &hba->ufs_stats.event[id];
499 for (i = 0; i < UFS_EVENT_HIST_LENGTH; i++) {
500 int p = (i + e->pos) % UFS_EVENT_HIST_LENGTH;
502 if (e->tstamp[p] == 0)
504 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, p,
505 e->val[p], div_u64(e->tstamp[p], 1000));
510 dev_err(hba->dev, "No record of %s\n", err_name);
512 dev_err(hba->dev, "%s: total cnt=%llu\n", err_name, e->cnt);
515 static void ufshcd_print_evt_hist(struct ufs_hba *hba)
517 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
519 ufshcd_print_evt(hba, UFS_EVT_PA_ERR, "pa_err");
520 ufshcd_print_evt(hba, UFS_EVT_DL_ERR, "dl_err");
521 ufshcd_print_evt(hba, UFS_EVT_NL_ERR, "nl_err");
522 ufshcd_print_evt(hba, UFS_EVT_TL_ERR, "tl_err");
523 ufshcd_print_evt(hba, UFS_EVT_DME_ERR, "dme_err");
524 ufshcd_print_evt(hba, UFS_EVT_AUTO_HIBERN8_ERR,
526 ufshcd_print_evt(hba, UFS_EVT_FATAL_ERR, "fatal_err");
527 ufshcd_print_evt(hba, UFS_EVT_LINK_STARTUP_FAIL,
528 "link_startup_fail");
529 ufshcd_print_evt(hba, UFS_EVT_RESUME_ERR, "resume_fail");
530 ufshcd_print_evt(hba, UFS_EVT_SUSPEND_ERR,
532 ufshcd_print_evt(hba, UFS_EVT_WL_RES_ERR, "wlun resume_fail");
533 ufshcd_print_evt(hba, UFS_EVT_WL_SUSP_ERR,
534 "wlun suspend_fail");
535 ufshcd_print_evt(hba, UFS_EVT_DEV_RESET, "dev_reset");
536 ufshcd_print_evt(hba, UFS_EVT_HOST_RESET, "host_reset");
537 ufshcd_print_evt(hba, UFS_EVT_ABORT, "task_abort");
539 ufshcd_vops_dbg_register_dump(hba);
543 void ufshcd_print_tr(struct ufs_hba *hba, int tag, bool pr_prdt)
545 const struct ufshcd_lrb *lrbp;
548 lrbp = &hba->lrb[tag];
550 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
551 tag, div_u64(lrbp->issue_time_stamp_local_clock, 1000));
552 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n",
553 tag, div_u64(lrbp->compl_time_stamp_local_clock, 1000));
555 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
556 tag, (u64)lrbp->utrd_dma_addr);
558 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
559 sizeof(struct utp_transfer_req_desc));
560 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
561 (u64)lrbp->ucd_req_dma_addr);
562 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
563 sizeof(struct utp_upiu_req));
564 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
565 (u64)lrbp->ucd_rsp_dma_addr);
566 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
567 sizeof(struct utp_upiu_rsp));
569 prdt_length = le16_to_cpu(
570 lrbp->utr_descriptor_ptr->prd_table_length);
571 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
572 prdt_length /= ufshcd_sg_entry_size(hba);
575 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
577 (u64)lrbp->ucd_prdt_dma_addr);
580 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
581 ufshcd_sg_entry_size(hba) * prdt_length);
584 static bool ufshcd_print_tr_iter(struct request *req, void *priv)
586 struct scsi_device *sdev = req->q->queuedata;
587 struct Scsi_Host *shost = sdev->host;
588 struct ufs_hba *hba = shost_priv(shost);
590 ufshcd_print_tr(hba, req->tag, *(bool *)priv);
596 * ufshcd_print_trs_all - print trs for all started requests.
597 * @hba: per-adapter instance.
598 * @pr_prdt: need to print prdt or not.
600 static void ufshcd_print_trs_all(struct ufs_hba *hba, bool pr_prdt)
602 blk_mq_tagset_busy_iter(&hba->host->tag_set, ufshcd_print_tr_iter, &pr_prdt);
605 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
609 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
610 struct utp_task_req_desc *tmrdp = &hba->utmrdl_base_addr[tag];
612 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
613 ufshcd_hex_dump("", tmrdp, sizeof(*tmrdp));
617 static void ufshcd_print_host_state(struct ufs_hba *hba)
619 const struct scsi_device *sdev_ufs = hba->ufs_device_wlun;
621 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
622 dev_err(hba->dev, "outstanding reqs=0x%lx tasks=0x%lx\n",
623 hba->outstanding_reqs, hba->outstanding_tasks);
624 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
625 hba->saved_err, hba->saved_uic_err);
626 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
627 hba->curr_dev_pwr_mode, hba->uic_link_state);
628 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
629 hba->pm_op_in_progress, hba->is_sys_suspended);
630 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
631 hba->auto_bkops_enabled, hba->host->host_self_blocked);
632 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
634 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt=%d\n",
635 div_u64(hba->ufs_stats.last_hibern8_exit_tstamp, 1000),
636 hba->ufs_stats.hibern8_exit_cnt);
637 dev_err(hba->dev, "last intr at %lld us, last intr status=0x%x\n",
638 div_u64(hba->ufs_stats.last_intr_ts, 1000),
639 hba->ufs_stats.last_intr_status);
640 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
641 hba->eh_flags, hba->req_abort_count);
642 dev_err(hba->dev, "hba->ufs_version=0x%x, Host capabilities=0x%x, caps=0x%x\n",
643 hba->ufs_version, hba->capabilities, hba->caps);
644 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
647 dev_err(hba->dev, "UFS dev info: %.8s %.16s rev %.4s\n",
648 sdev_ufs->vendor, sdev_ufs->model, sdev_ufs->rev);
650 ufshcd_print_clk_freqs(hba);
654 * ufshcd_print_pwr_info - print power params as saved in hba
656 * @hba: per-adapter instance
658 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
660 static const char * const names[] = {
671 * Using dev_dbg to avoid messages during runtime PM to avoid
672 * never-ending cycles of messages written back to storage by user space
673 * causing runtime resume, causing more messages and so on.
675 dev_dbg(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
677 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
678 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
679 names[hba->pwr_info.pwr_rx],
680 names[hba->pwr_info.pwr_tx],
681 hba->pwr_info.hs_rate);
684 static void ufshcd_device_reset(struct ufs_hba *hba)
688 err = ufshcd_vops_device_reset(hba);
691 ufshcd_set_ufs_dev_active(hba);
692 if (ufshcd_is_wb_allowed(hba)) {
693 hba->dev_info.wb_enabled = false;
694 hba->dev_info.wb_buf_flush_enabled = false;
697 if (err != -EOPNOTSUPP)
698 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, err);
701 void ufshcd_delay_us(unsigned long us, unsigned long tolerance)
709 usleep_range(us, us + tolerance);
711 EXPORT_SYMBOL_GPL(ufshcd_delay_us);
714 * ufshcd_wait_for_register - wait for register value to change
715 * @hba: per-adapter interface
716 * @reg: mmio register offset
717 * @mask: mask to apply to the read register value
718 * @val: value to wait for
719 * @interval_us: polling interval in microseconds
720 * @timeout_ms: timeout in milliseconds
723 * -ETIMEDOUT on error, zero on success.
725 static int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
726 u32 val, unsigned long interval_us,
727 unsigned long timeout_ms)
730 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
732 /* ignore bits that we don't intend to wait on */
735 while ((ufshcd_readl(hba, reg) & mask) != val) {
736 usleep_range(interval_us, interval_us + 50);
737 if (time_after(jiffies, timeout)) {
738 if ((ufshcd_readl(hba, reg) & mask) != val)
748 * ufshcd_get_intr_mask - Get the interrupt bit mask
749 * @hba: Pointer to adapter instance
751 * Returns interrupt bit mask per version
753 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
755 if (hba->ufs_version == ufshci_version(1, 0))
756 return INTERRUPT_MASK_ALL_VER_10;
757 if (hba->ufs_version <= ufshci_version(2, 0))
758 return INTERRUPT_MASK_ALL_VER_11;
760 return INTERRUPT_MASK_ALL_VER_21;
764 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
765 * @hba: Pointer to adapter instance
767 * Returns UFSHCI version supported by the controller
769 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
773 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
774 ufshci_ver = ufshcd_vops_get_ufs_hci_version(hba);
776 ufshci_ver = ufshcd_readl(hba, REG_UFS_VERSION);
779 * UFSHCI v1.x uses a different version scheme, in order
780 * to allow the use of comparisons with the ufshci_version
781 * function, we convert it to the same scheme as ufs 2.0+.
783 if (ufshci_ver & 0x00010000)
784 return ufshci_version(1, ufshci_ver & 0x00000100);
790 * ufshcd_is_device_present - Check if any device connected to
791 * the host controller
792 * @hba: pointer to adapter instance
794 * Returns true if device present, false if no device detected
796 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
798 return ufshcd_readl(hba, REG_CONTROLLER_STATUS) & DEVICE_PRESENT;
802 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
803 * @lrbp: pointer to local command reference block
804 * @cqe: pointer to the completion queue entry
806 * This function is used to get the OCS field from UTRD
807 * Returns the OCS field in the UTRD
809 static enum utp_ocs ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp,
810 struct cq_entry *cqe)
813 return le32_to_cpu(cqe->status) & MASK_OCS;
815 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
819 * ufshcd_utrl_clear() - Clear requests from the controller request list.
820 * @hba: per adapter instance
821 * @mask: mask with one bit set for each request to be cleared
823 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 mask)
825 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
828 * From the UFSHCI specification: "UTP Transfer Request List CLear
829 * Register (UTRLCLR): This field is bit significant. Each bit
830 * corresponds to a slot in the UTP Transfer Request List, where bit 0
831 * corresponds to request slot 0. A bit in this field is set to ‘0’
832 * by host software to indicate to the host controller that a transfer
833 * request slot is cleared. The host controller
834 * shall free up any resources associated to the request slot
835 * immediately, and shall set the associated bit in UTRLDBR to ‘0’. The
836 * host software indicates no change to request slots by setting the
837 * associated bits in this field to ‘1’. Bits in this field shall only
838 * be set ‘1’ or ‘0’ by host software when UTRLRSR is set to ‘1’."
840 ufshcd_writel(hba, ~mask, REG_UTP_TRANSFER_REQ_LIST_CLEAR);
844 * ufshcd_utmrl_clear - Clear a bit in UTMRLCLR register
845 * @hba: per adapter instance
846 * @pos: position of the bit to be cleared
848 static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos)
850 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
851 ufshcd_writel(hba, (1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
853 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
857 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
858 * @reg: Register value of host controller status
860 * Returns integer, 0 on Success and positive value if failed
862 static inline int ufshcd_get_lists_status(u32 reg)
864 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
868 * ufshcd_get_uic_cmd_result - Get the UIC command result
869 * @hba: Pointer to adapter instance
871 * This function gets the result of UIC command completion
872 * Returns 0 on success, non zero value on error
874 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
876 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
877 MASK_UIC_COMMAND_RESULT;
881 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
882 * @hba: Pointer to adapter instance
884 * This function gets UIC command argument3
885 * Returns 0 on success, non zero value on error
887 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
889 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
893 * ufshcd_get_req_rsp - returns the TR response transaction type
894 * @ucd_rsp_ptr: pointer to response UPIU
897 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
899 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
903 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
904 * @ucd_rsp_ptr: pointer to response UPIU
906 * This function gets the response status and scsi_status from response UPIU
907 * Returns the response result code.
910 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
912 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
916 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
918 * @ucd_rsp_ptr: pointer to response UPIU
920 * Return the data segment length.
922 static inline unsigned int
923 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
925 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
926 MASK_RSP_UPIU_DATA_SEG_LEN;
930 * ufshcd_is_exception_event - Check if the device raised an exception event
931 * @ucd_rsp_ptr: pointer to response UPIU
933 * The function checks if the device raised an exception event indicated in
934 * the Device Information field of response UPIU.
936 * Returns true if exception is raised, false otherwise.
938 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
940 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
941 MASK_RSP_EXCEPTION_EVENT;
945 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
946 * @hba: per adapter instance
949 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
951 ufshcd_writel(hba, INT_AGGR_ENABLE |
952 INT_AGGR_COUNTER_AND_TIMER_RESET,
953 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
957 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
958 * @hba: per adapter instance
959 * @cnt: Interrupt aggregation counter threshold
960 * @tmout: Interrupt aggregation timeout value
963 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
965 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
966 INT_AGGR_COUNTER_THLD_VAL(cnt) |
967 INT_AGGR_TIMEOUT_VAL(tmout),
968 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
972 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
973 * @hba: per adapter instance
975 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
977 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
981 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
982 * When run-stop registers are set to 1, it indicates the
983 * host controller that it can process the requests
984 * @hba: per adapter instance
986 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
988 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
989 REG_UTP_TASK_REQ_LIST_RUN_STOP);
990 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
991 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
995 * ufshcd_hba_start - Start controller initialization sequence
996 * @hba: per adapter instance
998 static inline void ufshcd_hba_start(struct ufs_hba *hba)
1000 u32 val = CONTROLLER_ENABLE;
1002 if (ufshcd_crypto_enable(hba))
1003 val |= CRYPTO_GENERAL_ENABLE;
1005 ufshcd_writel(hba, val, REG_CONTROLLER_ENABLE);
1009 * ufshcd_is_hba_active - Get controller state
1010 * @hba: per adapter instance
1012 * Returns true if and only if the controller is active.
1014 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
1016 return ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE;
1019 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
1021 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
1022 if (hba->ufs_version <= ufshci_version(1, 1))
1023 return UFS_UNIPRO_VER_1_41;
1025 return UFS_UNIPRO_VER_1_6;
1027 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
1029 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
1032 * If both host and device support UniPro ver1.6 or later, PA layer
1033 * parameters tuning happens during link startup itself.
1035 * We can manually tune PA layer parameters if either host or device
1036 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
1037 * logic simple, we will only do manual tuning if local unipro version
1038 * doesn't support ver1.6 or later.
1040 return ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6;
1044 * ufshcd_set_clk_freq - set UFS controller clock frequencies
1045 * @hba: per adapter instance
1046 * @scale_up: If True, set max possible frequency othewise set low frequency
1048 * Returns 0 if successful
1049 * Returns < 0 for any other errors
1051 static int ufshcd_set_clk_freq(struct ufs_hba *hba, bool scale_up)
1054 struct ufs_clk_info *clki;
1055 struct list_head *head = &hba->clk_list_head;
1057 if (list_empty(head))
1060 list_for_each_entry(clki, head, list) {
1061 if (!IS_ERR_OR_NULL(clki->clk)) {
1062 if (scale_up && clki->max_freq) {
1063 if (clki->curr_freq == clki->max_freq)
1066 ret = clk_set_rate(clki->clk, clki->max_freq);
1068 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
1069 __func__, clki->name,
1070 clki->max_freq, ret);
1073 trace_ufshcd_clk_scaling(dev_name(hba->dev),
1074 "scaled up", clki->name,
1078 clki->curr_freq = clki->max_freq;
1080 } else if (!scale_up && clki->min_freq) {
1081 if (clki->curr_freq == clki->min_freq)
1084 ret = clk_set_rate(clki->clk, clki->min_freq);
1086 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
1087 __func__, clki->name,
1088 clki->min_freq, ret);
1091 trace_ufshcd_clk_scaling(dev_name(hba->dev),
1092 "scaled down", clki->name,
1095 clki->curr_freq = clki->min_freq;
1098 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
1099 clki->name, clk_get_rate(clki->clk));
1107 * ufshcd_scale_clks - scale up or scale down UFS controller clocks
1108 * @hba: per adapter instance
1109 * @scale_up: True if scaling up and false if scaling down
1111 * Returns 0 if successful
1112 * Returns < 0 for any other errors
1114 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
1117 ktime_t start = ktime_get();
1119 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
1123 ret = ufshcd_set_clk_freq(hba, scale_up);
1127 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1129 ufshcd_set_clk_freq(hba, !scale_up);
1132 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1133 (scale_up ? "up" : "down"),
1134 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1139 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
1140 * @hba: per adapter instance
1141 * @scale_up: True if scaling up and false if scaling down
1143 * Returns true if scaling is required, false otherwise.
1145 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
1148 struct ufs_clk_info *clki;
1149 struct list_head *head = &hba->clk_list_head;
1151 if (list_empty(head))
1154 list_for_each_entry(clki, head, list) {
1155 if (!IS_ERR_OR_NULL(clki->clk)) {
1156 if (scale_up && clki->max_freq) {
1157 if (clki->curr_freq == clki->max_freq)
1160 } else if (!scale_up && clki->min_freq) {
1161 if (clki->curr_freq == clki->min_freq)
1172 * Determine the number of pending commands by counting the bits in the SCSI
1173 * device budget maps. This approach has been selected because a bit is set in
1174 * the budget map before scsi_host_queue_ready() checks the host_self_blocked
1175 * flag. The host_self_blocked flag can be modified by calling
1176 * scsi_block_requests() or scsi_unblock_requests().
1178 static u32 ufshcd_pending_cmds(struct ufs_hba *hba)
1180 const struct scsi_device *sdev;
1183 lockdep_assert_held(hba->host->host_lock);
1184 __shost_for_each_device(sdev, hba->host)
1185 pending += sbitmap_weight(&sdev->budget_map);
1191 * Wait until all pending SCSI commands and TMFs have finished or the timeout
1194 * Return: 0 upon success; -EBUSY upon timeout.
1196 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
1197 u64 wait_timeout_us)
1199 unsigned long flags;
1203 bool timeout = false, do_last_check = false;
1206 ufshcd_hold(hba, false);
1207 spin_lock_irqsave(hba->host->host_lock, flags);
1209 * Wait for all the outstanding tasks/transfer requests.
1210 * Verify by checking the doorbell registers are clear.
1212 start = ktime_get();
1214 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
1219 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1220 tr_pending = ufshcd_pending_cmds(hba);
1221 if (!tm_doorbell && !tr_pending) {
1224 } else if (do_last_check) {
1228 spin_unlock_irqrestore(hba->host->host_lock, flags);
1229 io_schedule_timeout(msecs_to_jiffies(20));
1230 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1234 * We might have scheduled out for long time so make
1235 * sure to check if doorbells are cleared by this time
1238 do_last_check = true;
1240 spin_lock_irqsave(hba->host->host_lock, flags);
1241 } while (tm_doorbell || tr_pending);
1245 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1246 __func__, tm_doorbell, tr_pending);
1250 spin_unlock_irqrestore(hba->host->host_lock, flags);
1251 ufshcd_release(hba);
1256 * ufshcd_scale_gear - scale up/down UFS gear
1257 * @hba: per adapter instance
1258 * @scale_up: True for scaling up gear and false for scaling down
1260 * Returns 0 for success,
1261 * Returns -EBUSY if scaling can't happen at this time
1262 * Returns non-zero for any other errors
1264 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1267 struct ufs_pa_layer_attr new_pwr_info;
1270 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info,
1271 sizeof(struct ufs_pa_layer_attr));
1273 memcpy(&new_pwr_info, &hba->pwr_info,
1274 sizeof(struct ufs_pa_layer_attr));
1276 if (hba->pwr_info.gear_tx > hba->clk_scaling.min_gear ||
1277 hba->pwr_info.gear_rx > hba->clk_scaling.min_gear) {
1278 /* save the current power mode */
1279 memcpy(&hba->clk_scaling.saved_pwr_info,
1281 sizeof(struct ufs_pa_layer_attr));
1283 /* scale down gear */
1284 new_pwr_info.gear_tx = hba->clk_scaling.min_gear;
1285 new_pwr_info.gear_rx = hba->clk_scaling.min_gear;
1289 /* check if the power mode needs to be changed or not? */
1290 ret = ufshcd_config_pwr_mode(hba, &new_pwr_info);
1292 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1294 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1295 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1301 * Wait until all pending SCSI commands and TMFs have finished or the timeout
1304 * Return: 0 upon success; -EBUSY upon timeout.
1306 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba, u64 timeout_us)
1310 * make sure that there are no outstanding requests when
1311 * clock scaling is in progress
1313 ufshcd_scsi_block_requests(hba);
1314 mutex_lock(&hba->wb_mutex);
1315 down_write(&hba->clk_scaling_lock);
1317 if (!hba->clk_scaling.is_allowed ||
1318 ufshcd_wait_for_doorbell_clr(hba, timeout_us)) {
1320 up_write(&hba->clk_scaling_lock);
1321 mutex_unlock(&hba->wb_mutex);
1322 ufshcd_scsi_unblock_requests(hba);
1326 /* let's not get into low power until clock scaling is completed */
1327 ufshcd_hold(hba, false);
1333 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba, int err, bool scale_up)
1335 up_write(&hba->clk_scaling_lock);
1337 /* Enable Write Booster if we have scaled up else disable it */
1338 if (ufshcd_enable_wb_if_scaling_up(hba) && !err)
1339 ufshcd_wb_toggle(hba, scale_up);
1341 mutex_unlock(&hba->wb_mutex);
1343 ufshcd_scsi_unblock_requests(hba);
1344 ufshcd_release(hba);
1348 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1349 * @hba: per adapter instance
1350 * @scale_up: True for scaling up and false for scalin down
1352 * Returns 0 for success,
1353 * Returns -EBUSY if scaling can't happen at this time
1354 * Returns non-zero for any other errors
1356 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1360 ret = ufshcd_clock_scaling_prepare(hba, 1 * USEC_PER_SEC);
1364 /* scale down the gear before scaling down clocks */
1366 ret = ufshcd_scale_gear(hba, false);
1371 ret = ufshcd_scale_clks(hba, scale_up);
1374 ufshcd_scale_gear(hba, true);
1378 /* scale up the gear after scaling up clocks */
1380 ret = ufshcd_scale_gear(hba, true);
1382 ufshcd_scale_clks(hba, false);
1388 ufshcd_clock_scaling_unprepare(hba, ret, scale_up);
1392 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1394 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1395 clk_scaling.suspend_work);
1396 unsigned long irq_flags;
1398 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1399 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1400 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1403 hba->clk_scaling.is_suspended = true;
1404 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1406 __ufshcd_suspend_clkscaling(hba);
1409 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1411 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1412 clk_scaling.resume_work);
1413 unsigned long irq_flags;
1415 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1416 if (!hba->clk_scaling.is_suspended) {
1417 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1420 hba->clk_scaling.is_suspended = false;
1421 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1423 devfreq_resume_device(hba->devfreq);
1426 static int ufshcd_devfreq_target(struct device *dev,
1427 unsigned long *freq, u32 flags)
1430 struct ufs_hba *hba = dev_get_drvdata(dev);
1432 bool scale_up, sched_clk_scaling_suspend_work = false;
1433 struct list_head *clk_list = &hba->clk_list_head;
1434 struct ufs_clk_info *clki;
1435 unsigned long irq_flags;
1437 if (!ufshcd_is_clkscaling_supported(hba))
1440 clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info, list);
1441 /* Override with the closest supported frequency */
1442 *freq = (unsigned long) clk_round_rate(clki->clk, *freq);
1443 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1444 if (ufshcd_eh_in_progress(hba)) {
1445 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1449 if (!hba->clk_scaling.active_reqs)
1450 sched_clk_scaling_suspend_work = true;
1452 if (list_empty(clk_list)) {
1453 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1457 /* Decide based on the rounded-off frequency and update */
1458 scale_up = *freq == clki->max_freq;
1460 *freq = clki->min_freq;
1461 /* Update the frequency */
1462 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1463 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1465 goto out; /* no state change required */
1467 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1469 start = ktime_get();
1470 ret = ufshcd_devfreq_scale(hba, scale_up);
1472 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1473 (scale_up ? "up" : "down"),
1474 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1477 if (sched_clk_scaling_suspend_work)
1478 queue_work(hba->clk_scaling.workq,
1479 &hba->clk_scaling.suspend_work);
1484 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1485 struct devfreq_dev_status *stat)
1487 struct ufs_hba *hba = dev_get_drvdata(dev);
1488 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1489 unsigned long flags;
1490 struct list_head *clk_list = &hba->clk_list_head;
1491 struct ufs_clk_info *clki;
1494 if (!ufshcd_is_clkscaling_supported(hba))
1497 memset(stat, 0, sizeof(*stat));
1499 spin_lock_irqsave(hba->host->host_lock, flags);
1500 curr_t = ktime_get();
1501 if (!scaling->window_start_t)
1504 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1506 * If current frequency is 0, then the ondemand governor considers
1507 * there's no initial frequency set. And it always requests to set
1508 * to max. frequency.
1510 stat->current_frequency = clki->curr_freq;
1511 if (scaling->is_busy_started)
1512 scaling->tot_busy_t += ktime_us_delta(curr_t,
1513 scaling->busy_start_t);
1515 stat->total_time = ktime_us_delta(curr_t, scaling->window_start_t);
1516 stat->busy_time = scaling->tot_busy_t;
1518 scaling->window_start_t = curr_t;
1519 scaling->tot_busy_t = 0;
1521 if (scaling->active_reqs) {
1522 scaling->busy_start_t = curr_t;
1523 scaling->is_busy_started = true;
1525 scaling->busy_start_t = 0;
1526 scaling->is_busy_started = false;
1528 spin_unlock_irqrestore(hba->host->host_lock, flags);
1532 static int ufshcd_devfreq_init(struct ufs_hba *hba)
1534 struct list_head *clk_list = &hba->clk_list_head;
1535 struct ufs_clk_info *clki;
1536 struct devfreq *devfreq;
1539 /* Skip devfreq if we don't have any clocks in the list */
1540 if (list_empty(clk_list))
1543 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1544 dev_pm_opp_add(hba->dev, clki->min_freq, 0);
1545 dev_pm_opp_add(hba->dev, clki->max_freq, 0);
1547 ufshcd_vops_config_scaling_param(hba, &hba->vps->devfreq_profile,
1548 &hba->vps->ondemand_data);
1549 devfreq = devfreq_add_device(hba->dev,
1550 &hba->vps->devfreq_profile,
1551 DEVFREQ_GOV_SIMPLE_ONDEMAND,
1552 &hba->vps->ondemand_data);
1553 if (IS_ERR(devfreq)) {
1554 ret = PTR_ERR(devfreq);
1555 dev_err(hba->dev, "Unable to register with devfreq %d\n", ret);
1557 dev_pm_opp_remove(hba->dev, clki->min_freq);
1558 dev_pm_opp_remove(hba->dev, clki->max_freq);
1562 hba->devfreq = devfreq;
1567 static void ufshcd_devfreq_remove(struct ufs_hba *hba)
1569 struct list_head *clk_list = &hba->clk_list_head;
1570 struct ufs_clk_info *clki;
1575 devfreq_remove_device(hba->devfreq);
1576 hba->devfreq = NULL;
1578 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1579 dev_pm_opp_remove(hba->dev, clki->min_freq);
1580 dev_pm_opp_remove(hba->dev, clki->max_freq);
1583 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1585 unsigned long flags;
1587 devfreq_suspend_device(hba->devfreq);
1588 spin_lock_irqsave(hba->host->host_lock, flags);
1589 hba->clk_scaling.window_start_t = 0;
1590 spin_unlock_irqrestore(hba->host->host_lock, flags);
1593 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1595 unsigned long flags;
1596 bool suspend = false;
1598 cancel_work_sync(&hba->clk_scaling.suspend_work);
1599 cancel_work_sync(&hba->clk_scaling.resume_work);
1601 spin_lock_irqsave(hba->host->host_lock, flags);
1602 if (!hba->clk_scaling.is_suspended) {
1604 hba->clk_scaling.is_suspended = true;
1606 spin_unlock_irqrestore(hba->host->host_lock, flags);
1609 __ufshcd_suspend_clkscaling(hba);
1612 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1614 unsigned long flags;
1615 bool resume = false;
1617 spin_lock_irqsave(hba->host->host_lock, flags);
1618 if (hba->clk_scaling.is_suspended) {
1620 hba->clk_scaling.is_suspended = false;
1622 spin_unlock_irqrestore(hba->host->host_lock, flags);
1625 devfreq_resume_device(hba->devfreq);
1628 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1629 struct device_attribute *attr, char *buf)
1631 struct ufs_hba *hba = dev_get_drvdata(dev);
1633 return sysfs_emit(buf, "%d\n", hba->clk_scaling.is_enabled);
1636 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1637 struct device_attribute *attr, const char *buf, size_t count)
1639 struct ufs_hba *hba = dev_get_drvdata(dev);
1643 if (kstrtou32(buf, 0, &value))
1646 down(&hba->host_sem);
1647 if (!ufshcd_is_user_access_allowed(hba)) {
1653 if (value == hba->clk_scaling.is_enabled)
1656 ufshcd_rpm_get_sync(hba);
1657 ufshcd_hold(hba, false);
1659 hba->clk_scaling.is_enabled = value;
1662 ufshcd_resume_clkscaling(hba);
1664 ufshcd_suspend_clkscaling(hba);
1665 err = ufshcd_devfreq_scale(hba, true);
1667 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1671 ufshcd_release(hba);
1672 ufshcd_rpm_put_sync(hba);
1675 return err ? err : count;
1678 static void ufshcd_init_clk_scaling_sysfs(struct ufs_hba *hba)
1680 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1681 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1682 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1683 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1684 hba->clk_scaling.enable_attr.attr.mode = 0644;
1685 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1686 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1689 static void ufshcd_remove_clk_scaling_sysfs(struct ufs_hba *hba)
1691 if (hba->clk_scaling.enable_attr.attr.name)
1692 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
1695 static void ufshcd_init_clk_scaling(struct ufs_hba *hba)
1697 char wq_name[sizeof("ufs_clkscaling_00")];
1699 if (!ufshcd_is_clkscaling_supported(hba))
1702 if (!hba->clk_scaling.min_gear)
1703 hba->clk_scaling.min_gear = UFS_HS_G1;
1705 INIT_WORK(&hba->clk_scaling.suspend_work,
1706 ufshcd_clk_scaling_suspend_work);
1707 INIT_WORK(&hba->clk_scaling.resume_work,
1708 ufshcd_clk_scaling_resume_work);
1710 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
1711 hba->host->host_no);
1712 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
1714 hba->clk_scaling.is_initialized = true;
1717 static void ufshcd_exit_clk_scaling(struct ufs_hba *hba)
1719 if (!hba->clk_scaling.is_initialized)
1722 ufshcd_remove_clk_scaling_sysfs(hba);
1723 destroy_workqueue(hba->clk_scaling.workq);
1724 ufshcd_devfreq_remove(hba);
1725 hba->clk_scaling.is_initialized = false;
1728 static void ufshcd_ungate_work(struct work_struct *work)
1731 unsigned long flags;
1732 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1733 clk_gating.ungate_work);
1735 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1737 spin_lock_irqsave(hba->host->host_lock, flags);
1738 if (hba->clk_gating.state == CLKS_ON) {
1739 spin_unlock_irqrestore(hba->host->host_lock, flags);
1743 spin_unlock_irqrestore(hba->host->host_lock, flags);
1744 ufshcd_hba_vreg_set_hpm(hba);
1745 ufshcd_setup_clocks(hba, true);
1747 ufshcd_enable_irq(hba);
1749 /* Exit from hibern8 */
1750 if (ufshcd_can_hibern8_during_gating(hba)) {
1751 /* Prevent gating in this path */
1752 hba->clk_gating.is_suspended = true;
1753 if (ufshcd_is_link_hibern8(hba)) {
1754 ret = ufshcd_uic_hibern8_exit(hba);
1756 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1759 ufshcd_set_link_active(hba);
1761 hba->clk_gating.is_suspended = false;
1764 ufshcd_scsi_unblock_requests(hba);
1768 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1769 * Also, exit from hibern8 mode and set the link as active.
1770 * @hba: per adapter instance
1771 * @async: This indicates whether caller should ungate clocks asynchronously.
1773 int ufshcd_hold(struct ufs_hba *hba, bool async)
1777 unsigned long flags;
1779 if (!ufshcd_is_clkgating_allowed(hba) ||
1780 !hba->clk_gating.is_initialized)
1782 spin_lock_irqsave(hba->host->host_lock, flags);
1783 hba->clk_gating.active_reqs++;
1786 switch (hba->clk_gating.state) {
1789 * Wait for the ungate work to complete if in progress.
1790 * Though the clocks may be in ON state, the link could
1791 * still be in hibner8 state if hibern8 is allowed
1792 * during clock gating.
1793 * Make sure we exit hibern8 state also in addition to
1796 if (ufshcd_can_hibern8_during_gating(hba) &&
1797 ufshcd_is_link_hibern8(hba)) {
1800 hba->clk_gating.active_reqs--;
1803 spin_unlock_irqrestore(hba->host->host_lock, flags);
1804 flush_result = flush_work(&hba->clk_gating.ungate_work);
1805 if (hba->clk_gating.is_suspended && !flush_result)
1807 spin_lock_irqsave(hba->host->host_lock, flags);
1812 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1813 hba->clk_gating.state = CLKS_ON;
1814 trace_ufshcd_clk_gating(dev_name(hba->dev),
1815 hba->clk_gating.state);
1819 * If we are here, it means gating work is either done or
1820 * currently running. Hence, fall through to cancel gating
1821 * work and to enable clocks.
1825 hba->clk_gating.state = REQ_CLKS_ON;
1826 trace_ufshcd_clk_gating(dev_name(hba->dev),
1827 hba->clk_gating.state);
1828 if (queue_work(hba->clk_gating.clk_gating_workq,
1829 &hba->clk_gating.ungate_work))
1830 ufshcd_scsi_block_requests(hba);
1832 * fall through to check if we should wait for this
1833 * work to be done or not.
1839 hba->clk_gating.active_reqs--;
1843 spin_unlock_irqrestore(hba->host->host_lock, flags);
1844 flush_work(&hba->clk_gating.ungate_work);
1845 /* Make sure state is CLKS_ON before returning */
1846 spin_lock_irqsave(hba->host->host_lock, flags);
1849 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1850 __func__, hba->clk_gating.state);
1853 spin_unlock_irqrestore(hba->host->host_lock, flags);
1857 EXPORT_SYMBOL_GPL(ufshcd_hold);
1859 static void ufshcd_gate_work(struct work_struct *work)
1861 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1862 clk_gating.gate_work.work);
1863 unsigned long flags;
1866 spin_lock_irqsave(hba->host->host_lock, flags);
1868 * In case you are here to cancel this work the gating state
1869 * would be marked as REQ_CLKS_ON. In this case save time by
1870 * skipping the gating work and exit after changing the clock
1873 if (hba->clk_gating.is_suspended ||
1874 (hba->clk_gating.state != REQ_CLKS_OFF)) {
1875 hba->clk_gating.state = CLKS_ON;
1876 trace_ufshcd_clk_gating(dev_name(hba->dev),
1877 hba->clk_gating.state);
1881 if (hba->clk_gating.active_reqs
1882 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1883 || hba->outstanding_reqs || hba->outstanding_tasks
1884 || hba->active_uic_cmd || hba->uic_async_done)
1887 spin_unlock_irqrestore(hba->host->host_lock, flags);
1889 /* put the link into hibern8 mode before turning off clocks */
1890 if (ufshcd_can_hibern8_during_gating(hba)) {
1891 ret = ufshcd_uic_hibern8_enter(hba);
1893 hba->clk_gating.state = CLKS_ON;
1894 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
1896 trace_ufshcd_clk_gating(dev_name(hba->dev),
1897 hba->clk_gating.state);
1900 ufshcd_set_link_hibern8(hba);
1903 ufshcd_disable_irq(hba);
1905 ufshcd_setup_clocks(hba, false);
1907 /* Put the host controller in low power mode if possible */
1908 ufshcd_hba_vreg_set_lpm(hba);
1910 * In case you are here to cancel this work the gating state
1911 * would be marked as REQ_CLKS_ON. In this case keep the state
1912 * as REQ_CLKS_ON which would anyway imply that clocks are off
1913 * and a request to turn them on is pending. By doing this way,
1914 * we keep the state machine in tact and this would ultimately
1915 * prevent from doing cancel work multiple times when there are
1916 * new requests arriving before the current cancel work is done.
1918 spin_lock_irqsave(hba->host->host_lock, flags);
1919 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1920 hba->clk_gating.state = CLKS_OFF;
1921 trace_ufshcd_clk_gating(dev_name(hba->dev),
1922 hba->clk_gating.state);
1925 spin_unlock_irqrestore(hba->host->host_lock, flags);
1930 /* host lock must be held before calling this variant */
1931 static void __ufshcd_release(struct ufs_hba *hba)
1933 if (!ufshcd_is_clkgating_allowed(hba))
1936 hba->clk_gating.active_reqs--;
1938 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended ||
1939 hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL ||
1940 hba->outstanding_tasks || !hba->clk_gating.is_initialized ||
1941 hba->active_uic_cmd || hba->uic_async_done ||
1942 hba->clk_gating.state == CLKS_OFF)
1945 hba->clk_gating.state = REQ_CLKS_OFF;
1946 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1947 queue_delayed_work(hba->clk_gating.clk_gating_workq,
1948 &hba->clk_gating.gate_work,
1949 msecs_to_jiffies(hba->clk_gating.delay_ms));
1952 void ufshcd_release(struct ufs_hba *hba)
1954 unsigned long flags;
1956 spin_lock_irqsave(hba->host->host_lock, flags);
1957 __ufshcd_release(hba);
1958 spin_unlock_irqrestore(hba->host->host_lock, flags);
1960 EXPORT_SYMBOL_GPL(ufshcd_release);
1962 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1963 struct device_attribute *attr, char *buf)
1965 struct ufs_hba *hba = dev_get_drvdata(dev);
1967 return sysfs_emit(buf, "%lu\n", hba->clk_gating.delay_ms);
1970 void ufshcd_clkgate_delay_set(struct device *dev, unsigned long value)
1972 struct ufs_hba *hba = dev_get_drvdata(dev);
1973 unsigned long flags;
1975 spin_lock_irqsave(hba->host->host_lock, flags);
1976 hba->clk_gating.delay_ms = value;
1977 spin_unlock_irqrestore(hba->host->host_lock, flags);
1979 EXPORT_SYMBOL_GPL(ufshcd_clkgate_delay_set);
1981 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1982 struct device_attribute *attr, const char *buf, size_t count)
1984 unsigned long value;
1986 if (kstrtoul(buf, 0, &value))
1989 ufshcd_clkgate_delay_set(dev, value);
1993 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1994 struct device_attribute *attr, char *buf)
1996 struct ufs_hba *hba = dev_get_drvdata(dev);
1998 return sysfs_emit(buf, "%d\n", hba->clk_gating.is_enabled);
2001 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
2002 struct device_attribute *attr, const char *buf, size_t count)
2004 struct ufs_hba *hba = dev_get_drvdata(dev);
2005 unsigned long flags;
2008 if (kstrtou32(buf, 0, &value))
2013 spin_lock_irqsave(hba->host->host_lock, flags);
2014 if (value == hba->clk_gating.is_enabled)
2018 __ufshcd_release(hba);
2020 hba->clk_gating.active_reqs++;
2022 hba->clk_gating.is_enabled = value;
2024 spin_unlock_irqrestore(hba->host->host_lock, flags);
2028 static void ufshcd_init_clk_gating_sysfs(struct ufs_hba *hba)
2030 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
2031 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
2032 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
2033 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
2034 hba->clk_gating.delay_attr.attr.mode = 0644;
2035 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
2036 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
2038 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
2039 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
2040 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
2041 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
2042 hba->clk_gating.enable_attr.attr.mode = 0644;
2043 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
2044 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
2047 static void ufshcd_remove_clk_gating_sysfs(struct ufs_hba *hba)
2049 if (hba->clk_gating.delay_attr.attr.name)
2050 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
2051 if (hba->clk_gating.enable_attr.attr.name)
2052 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
2055 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
2057 char wq_name[sizeof("ufs_clk_gating_00")];
2059 if (!ufshcd_is_clkgating_allowed(hba))
2062 hba->clk_gating.state = CLKS_ON;
2064 hba->clk_gating.delay_ms = 150;
2065 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
2066 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
2068 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d",
2069 hba->host->host_no);
2070 hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(wq_name,
2071 WQ_MEM_RECLAIM | WQ_HIGHPRI);
2073 ufshcd_init_clk_gating_sysfs(hba);
2075 hba->clk_gating.is_enabled = true;
2076 hba->clk_gating.is_initialized = true;
2079 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
2081 if (!hba->clk_gating.is_initialized)
2084 ufshcd_remove_clk_gating_sysfs(hba);
2086 /* Ungate the clock if necessary. */
2087 ufshcd_hold(hba, false);
2088 hba->clk_gating.is_initialized = false;
2089 ufshcd_release(hba);
2091 destroy_workqueue(hba->clk_gating.clk_gating_workq);
2094 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
2096 bool queue_resume_work = false;
2097 ktime_t curr_t = ktime_get();
2098 unsigned long flags;
2100 if (!ufshcd_is_clkscaling_supported(hba))
2103 spin_lock_irqsave(hba->host->host_lock, flags);
2104 if (!hba->clk_scaling.active_reqs++)
2105 queue_resume_work = true;
2107 if (!hba->clk_scaling.is_enabled || hba->pm_op_in_progress) {
2108 spin_unlock_irqrestore(hba->host->host_lock, flags);
2112 if (queue_resume_work)
2113 queue_work(hba->clk_scaling.workq,
2114 &hba->clk_scaling.resume_work);
2116 if (!hba->clk_scaling.window_start_t) {
2117 hba->clk_scaling.window_start_t = curr_t;
2118 hba->clk_scaling.tot_busy_t = 0;
2119 hba->clk_scaling.is_busy_started = false;
2122 if (!hba->clk_scaling.is_busy_started) {
2123 hba->clk_scaling.busy_start_t = curr_t;
2124 hba->clk_scaling.is_busy_started = true;
2126 spin_unlock_irqrestore(hba->host->host_lock, flags);
2129 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
2131 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
2132 unsigned long flags;
2134 if (!ufshcd_is_clkscaling_supported(hba))
2137 spin_lock_irqsave(hba->host->host_lock, flags);
2138 hba->clk_scaling.active_reqs--;
2139 if (!scaling->active_reqs && scaling->is_busy_started) {
2140 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
2141 scaling->busy_start_t));
2142 scaling->busy_start_t = 0;
2143 scaling->is_busy_started = false;
2145 spin_unlock_irqrestore(hba->host->host_lock, flags);
2148 static inline int ufshcd_monitor_opcode2dir(u8 opcode)
2150 if (opcode == READ_6 || opcode == READ_10 || opcode == READ_16)
2152 else if (opcode == WRITE_6 || opcode == WRITE_10 || opcode == WRITE_16)
2158 static inline bool ufshcd_should_inform_monitor(struct ufs_hba *hba,
2159 struct ufshcd_lrb *lrbp)
2161 const struct ufs_hba_monitor *m = &hba->monitor;
2163 return (m->enabled && lrbp && lrbp->cmd &&
2164 (!m->chunk_size || m->chunk_size == lrbp->cmd->sdb.length) &&
2165 ktime_before(hba->monitor.enabled_ts, lrbp->issue_time_stamp));
2168 static void ufshcd_start_monitor(struct ufs_hba *hba,
2169 const struct ufshcd_lrb *lrbp)
2171 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2172 unsigned long flags;
2174 spin_lock_irqsave(hba->host->host_lock, flags);
2175 if (dir >= 0 && hba->monitor.nr_queued[dir]++ == 0)
2176 hba->monitor.busy_start_ts[dir] = ktime_get();
2177 spin_unlock_irqrestore(hba->host->host_lock, flags);
2180 static void ufshcd_update_monitor(struct ufs_hba *hba, const struct ufshcd_lrb *lrbp)
2182 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2183 unsigned long flags;
2185 spin_lock_irqsave(hba->host->host_lock, flags);
2186 if (dir >= 0 && hba->monitor.nr_queued[dir] > 0) {
2187 const struct request *req = scsi_cmd_to_rq(lrbp->cmd);
2188 struct ufs_hba_monitor *m = &hba->monitor;
2189 ktime_t now, inc, lat;
2191 now = lrbp->compl_time_stamp;
2192 inc = ktime_sub(now, m->busy_start_ts[dir]);
2193 m->total_busy[dir] = ktime_add(m->total_busy[dir], inc);
2194 m->nr_sec_rw[dir] += blk_rq_sectors(req);
2196 /* Update latencies */
2198 lat = ktime_sub(now, lrbp->issue_time_stamp);
2199 m->lat_sum[dir] += lat;
2200 if (m->lat_max[dir] < lat || !m->lat_max[dir])
2201 m->lat_max[dir] = lat;
2202 if (m->lat_min[dir] > lat || !m->lat_min[dir])
2203 m->lat_min[dir] = lat;
2205 m->nr_queued[dir]--;
2206 /* Push forward the busy start of monitor */
2207 m->busy_start_ts[dir] = now;
2209 spin_unlock_irqrestore(hba->host->host_lock, flags);
2213 * ufshcd_send_command - Send SCSI or device management commands
2214 * @hba: per adapter instance
2215 * @task_tag: Task tag of the command
2216 * @hwq: pointer to hardware queue instance
2219 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag,
2220 struct ufs_hw_queue *hwq)
2222 struct ufshcd_lrb *lrbp = &hba->lrb[task_tag];
2223 unsigned long flags;
2225 lrbp->issue_time_stamp = ktime_get();
2226 lrbp->issue_time_stamp_local_clock = local_clock();
2227 lrbp->compl_time_stamp = ktime_set(0, 0);
2228 lrbp->compl_time_stamp_local_clock = 0;
2229 ufshcd_add_command_trace(hba, task_tag, UFS_CMD_SEND);
2230 ufshcd_clk_scaling_start_busy(hba);
2231 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
2232 ufshcd_start_monitor(hba, lrbp);
2234 if (is_mcq_enabled(hba)) {
2235 int utrd_size = sizeof(struct utp_transfer_req_desc);
2236 struct utp_transfer_req_desc *src = lrbp->utr_descriptor_ptr;
2237 struct utp_transfer_req_desc *dest = hwq->sqe_base_addr + hwq->sq_tail_slot;
2239 spin_lock(&hwq->sq_lock);
2240 memcpy(dest, src, utrd_size);
2241 ufshcd_inc_sq_tail(hwq);
2242 spin_unlock(&hwq->sq_lock);
2244 spin_lock_irqsave(&hba->outstanding_lock, flags);
2245 if (hba->vops && hba->vops->setup_xfer_req)
2246 hba->vops->setup_xfer_req(hba, lrbp->task_tag,
2248 __set_bit(lrbp->task_tag, &hba->outstanding_reqs);
2249 ufshcd_writel(hba, 1 << lrbp->task_tag,
2250 REG_UTP_TRANSFER_REQ_DOOR_BELL);
2251 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
2256 * ufshcd_copy_sense_data - Copy sense data in case of check condition
2257 * @lrbp: pointer to local reference block
2259 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
2261 u8 *const sense_buffer = lrbp->cmd->sense_buffer;
2265 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
2268 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
2269 len_to_copy = min_t(int, UFS_SENSE_SIZE, len);
2271 memcpy(sense_buffer, lrbp->ucd_rsp_ptr->sr.sense_data,
2277 * ufshcd_copy_query_response() - Copy the Query Response and the data
2279 * @hba: per adapter instance
2280 * @lrbp: pointer to local reference block
2283 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2285 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2287 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
2289 /* Get the descriptor */
2290 if (hba->dev_cmd.query.descriptor &&
2291 lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
2292 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
2293 GENERAL_UPIU_REQUEST_SIZE;
2297 /* data segment length */
2298 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
2299 MASK_QUERY_DATA_SEG_LEN;
2300 buf_len = be16_to_cpu(
2301 hba->dev_cmd.query.request.upiu_req.length);
2302 if (likely(buf_len >= resp_len)) {
2303 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
2306 "%s: rsp size %d is bigger than buffer size %d",
2307 __func__, resp_len, buf_len);
2316 * ufshcd_hba_capabilities - Read controller capabilities
2317 * @hba: per adapter instance
2319 * Return: 0 on success, negative on error.
2321 static inline int ufshcd_hba_capabilities(struct ufs_hba *hba)
2325 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
2326 if (hba->quirks & UFSHCD_QUIRK_BROKEN_64BIT_ADDRESS)
2327 hba->capabilities &= ~MASK_64_ADDRESSING_SUPPORT;
2329 /* nutrs and nutmrs are 0 based values */
2330 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
2332 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
2333 hba->reserved_slot = hba->nutrs - 1;
2335 /* Read crypto capabilities */
2336 err = ufshcd_hba_init_crypto_capabilities(hba);
2338 dev_err(hba->dev, "crypto setup failed\n");
2340 hba->mcq_sup = FIELD_GET(MASK_MCQ_SUPPORT, hba->capabilities);
2344 hba->mcq_capabilities = ufshcd_readl(hba, REG_MCQCAP);
2345 hba->ext_iid_sup = FIELD_GET(MASK_EXT_IID_SUPPORT,
2346 hba->mcq_capabilities);
2352 * ufshcd_ready_for_uic_cmd - Check if controller is ready
2353 * to accept UIC commands
2354 * @hba: per adapter instance
2355 * Return true on success, else false
2357 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
2359 return ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY;
2363 * ufshcd_get_upmcrs - Get the power mode change request status
2364 * @hba: Pointer to adapter instance
2366 * This function gets the UPMCRS field of HCS register
2367 * Returns value of UPMCRS field
2369 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
2371 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
2375 * ufshcd_dispatch_uic_cmd - Dispatch an UIC command to the Unipro layer
2376 * @hba: per adapter instance
2377 * @uic_cmd: UIC command
2380 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2382 lockdep_assert_held(&hba->uic_cmd_mutex);
2384 WARN_ON(hba->active_uic_cmd);
2386 hba->active_uic_cmd = uic_cmd;
2389 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2390 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2391 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2393 ufshcd_add_uic_command_trace(hba, uic_cmd, UFS_CMD_SEND);
2396 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2401 * ufshcd_wait_for_uic_cmd - Wait for completion of an UIC command
2402 * @hba: per adapter instance
2403 * @uic_cmd: UIC command
2405 * Returns 0 only if success.
2408 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2411 unsigned long flags;
2413 lockdep_assert_held(&hba->uic_cmd_mutex);
2415 if (wait_for_completion_timeout(&uic_cmd->done,
2416 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
2417 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2421 "uic cmd 0x%x with arg3 0x%x completion timeout\n",
2422 uic_cmd->command, uic_cmd->argument3);
2424 if (!uic_cmd->cmd_active) {
2425 dev_err(hba->dev, "%s: UIC cmd has been completed, return the result\n",
2427 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2431 spin_lock_irqsave(hba->host->host_lock, flags);
2432 hba->active_uic_cmd = NULL;
2433 spin_unlock_irqrestore(hba->host->host_lock, flags);
2439 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2440 * @hba: per adapter instance
2441 * @uic_cmd: UIC command
2442 * @completion: initialize the completion only if this is set to true
2444 * Returns 0 only if success.
2447 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
2450 lockdep_assert_held(&hba->uic_cmd_mutex);
2451 lockdep_assert_held(hba->host->host_lock);
2453 if (!ufshcd_ready_for_uic_cmd(hba)) {
2455 "Controller not ready to accept UIC commands\n");
2460 init_completion(&uic_cmd->done);
2462 uic_cmd->cmd_active = 1;
2463 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2469 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2470 * @hba: per adapter instance
2471 * @uic_cmd: UIC command
2473 * Returns 0 only if success.
2475 int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2478 unsigned long flags;
2480 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UIC_CMD)
2483 ufshcd_hold(hba, false);
2484 mutex_lock(&hba->uic_cmd_mutex);
2485 ufshcd_add_delay_before_dme_cmd(hba);
2487 spin_lock_irqsave(hba->host->host_lock, flags);
2488 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
2489 spin_unlock_irqrestore(hba->host->host_lock, flags);
2491 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2493 mutex_unlock(&hba->uic_cmd_mutex);
2495 ufshcd_release(hba);
2500 * ufshcd_sgl_to_prdt - SG list to PRTD (Physical Region Description Table, 4DW format)
2501 * @hba: per-adapter instance
2502 * @lrbp: pointer to local reference block
2503 * @sg_entries: The number of sg lists actually used
2504 * @sg_list: Pointer to SG list
2506 static void ufshcd_sgl_to_prdt(struct ufs_hba *hba, struct ufshcd_lrb *lrbp, int sg_entries,
2507 struct scatterlist *sg_list)
2509 struct ufshcd_sg_entry *prd;
2510 struct scatterlist *sg;
2515 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2516 lrbp->utr_descriptor_ptr->prd_table_length =
2517 cpu_to_le16(sg_entries * ufshcd_sg_entry_size(hba));
2519 lrbp->utr_descriptor_ptr->prd_table_length = cpu_to_le16(sg_entries);
2521 prd = lrbp->ucd_prdt_ptr;
2523 for_each_sg(sg_list, sg, sg_entries, i) {
2524 const unsigned int len = sg_dma_len(sg);
2527 * From the UFSHCI spec: "Data Byte Count (DBC): A '0'
2528 * based value that indicates the length, in bytes, of
2529 * the data block. A maximum of length of 256KB may
2530 * exist for any entry. Bits 1:0 of this field shall be
2531 * 11b to indicate Dword granularity. A value of '3'
2532 * indicates 4 bytes, '7' indicates 8 bytes, etc."
2534 WARN_ONCE(len > 256 * 1024, "len = %#x\n", len);
2535 prd->size = cpu_to_le32(len - 1);
2536 prd->addr = cpu_to_le64(sg->dma_address);
2538 prd = (void *)prd + ufshcd_sg_entry_size(hba);
2541 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2546 * ufshcd_map_sg - Map scatter-gather list to prdt
2547 * @hba: per adapter instance
2548 * @lrbp: pointer to local reference block
2550 * Returns 0 in case of success, non-zero value in case of failure
2552 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2554 struct scsi_cmnd *cmd = lrbp->cmd;
2555 int sg_segments = scsi_dma_map(cmd);
2557 if (sg_segments < 0)
2560 ufshcd_sgl_to_prdt(hba, lrbp, sg_segments, scsi_sglist(cmd));
2566 * ufshcd_enable_intr - enable interrupts
2567 * @hba: per adapter instance
2568 * @intrs: interrupt bits
2570 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2572 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2574 if (hba->ufs_version == ufshci_version(1, 0)) {
2576 rw = set & INTERRUPT_MASK_RW_VER_10;
2577 set = rw | ((set ^ intrs) & intrs);
2582 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2586 * ufshcd_disable_intr - disable interrupts
2587 * @hba: per adapter instance
2588 * @intrs: interrupt bits
2590 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2592 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2594 if (hba->ufs_version == ufshci_version(1, 0)) {
2596 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2597 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2598 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2604 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2608 * ufshcd_prepare_req_desc_hdr - Fill UTP Transfer request descriptor header according to request
2609 * descriptor according to request
2610 * @lrbp: pointer to local reference block
2611 * @upiu_flags: flags required in the header
2612 * @cmd_dir: requests data direction
2613 * @ehs_length: Total EHS Length (in 32‐bytes units of all Extra Header Segments)
2615 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp, u8 *upiu_flags,
2616 enum dma_data_direction cmd_dir, int ehs_length)
2618 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2624 if (cmd_dir == DMA_FROM_DEVICE) {
2625 data_direction = UTP_DEVICE_TO_HOST;
2626 *upiu_flags = UPIU_CMD_FLAGS_READ;
2627 } else if (cmd_dir == DMA_TO_DEVICE) {
2628 data_direction = UTP_HOST_TO_DEVICE;
2629 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2631 data_direction = UTP_NO_DATA_TRANSFER;
2632 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2635 dword_0 = data_direction | (lrbp->command_type << UPIU_COMMAND_TYPE_OFFSET) |
2638 dword_0 |= UTP_REQ_DESC_INT_CMD;
2640 /* Prepare crypto related dwords */
2641 ufshcd_prepare_req_desc_hdr_crypto(lrbp, &dword_0, &dword_1, &dword_3);
2643 /* Transfer request descriptor header fields */
2644 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2645 req_desc->header.dword_1 = cpu_to_le32(dword_1);
2647 * assigning invalid value for command status. Controller
2648 * updates OCS on command completion, with the command
2651 req_desc->header.dword_2 =
2652 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2653 req_desc->header.dword_3 = cpu_to_le32(dword_3);
2655 req_desc->prd_table_length = 0;
2659 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2661 * @lrbp: local reference block pointer
2662 * @upiu_flags: flags
2665 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u8 upiu_flags)
2667 struct scsi_cmnd *cmd = lrbp->cmd;
2668 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2669 unsigned short cdb_len;
2671 /* command descriptor fields */
2672 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2673 UPIU_TRANSACTION_COMMAND, upiu_flags,
2674 lrbp->lun, lrbp->task_tag);
2675 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2676 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2678 /* Total EHS length and Data segment length will be zero */
2679 ucd_req_ptr->header.dword_2 = 0;
2681 ucd_req_ptr->sc.exp_data_transfer_len = cpu_to_be32(cmd->sdb.length);
2683 cdb_len = min_t(unsigned short, cmd->cmd_len, UFS_CDB_SIZE);
2684 memset(ucd_req_ptr->sc.cdb, 0, UFS_CDB_SIZE);
2685 memcpy(ucd_req_ptr->sc.cdb, cmd->cmnd, cdb_len);
2687 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2691 * ufshcd_prepare_utp_query_req_upiu() - fill the utp_transfer_req_desc for query request
2693 * @lrbp: local reference block pointer
2694 * @upiu_flags: flags
2696 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2697 struct ufshcd_lrb *lrbp, u8 upiu_flags)
2699 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2700 struct ufs_query *query = &hba->dev_cmd.query;
2701 u16 len = be16_to_cpu(query->request.upiu_req.length);
2703 /* Query request header */
2704 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2705 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2706 lrbp->lun, lrbp->task_tag);
2707 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2708 0, query->request.query_func, 0, 0);
2710 /* Data segment length only need for WRITE_DESC */
2711 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2712 ucd_req_ptr->header.dword_2 =
2713 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2715 ucd_req_ptr->header.dword_2 = 0;
2717 /* Copy the Query Request buffer as is */
2718 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2721 /* Copy the Descriptor */
2722 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2723 memcpy(ucd_req_ptr + 1, query->descriptor, len);
2725 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2728 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2730 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2732 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2734 /* command descriptor fields */
2735 ucd_req_ptr->header.dword_0 =
2737 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2738 /* clear rest of the fields of basic header */
2739 ucd_req_ptr->header.dword_1 = 0;
2740 ucd_req_ptr->header.dword_2 = 0;
2742 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2746 * ufshcd_compose_devman_upiu - UFS Protocol Information Unit(UPIU)
2747 * for Device Management Purposes
2748 * @hba: per adapter instance
2749 * @lrbp: pointer to local reference block
2751 static int ufshcd_compose_devman_upiu(struct ufs_hba *hba,
2752 struct ufshcd_lrb *lrbp)
2757 if (hba->ufs_version <= ufshci_version(1, 1))
2758 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2760 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2762 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE, 0);
2763 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2764 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2765 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2766 ufshcd_prepare_utp_nop_upiu(lrbp);
2774 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2776 * @hba: per adapter instance
2777 * @lrbp: pointer to local reference block
2779 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2784 if (hba->ufs_version <= ufshci_version(1, 1))
2785 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2787 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2789 if (likely(lrbp->cmd)) {
2790 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, lrbp->cmd->sc_data_direction, 0);
2791 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2800 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2801 * @upiu_wlun_id: UPIU W-LUN id
2803 * Returns SCSI W-LUN id
2805 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2807 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2810 static inline bool is_device_wlun(struct scsi_device *sdev)
2813 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN);
2817 * Associate the UFS controller queue with the default and poll HCTX types.
2818 * Initialize the mq_map[] arrays.
2820 static void ufshcd_map_queues(struct Scsi_Host *shost)
2822 struct ufs_hba *hba = shost_priv(shost);
2823 int i, queue_offset = 0;
2825 if (!is_mcq_supported(hba)) {
2826 hba->nr_queues[HCTX_TYPE_DEFAULT] = 1;
2827 hba->nr_queues[HCTX_TYPE_READ] = 0;
2828 hba->nr_queues[HCTX_TYPE_POLL] = 1;
2829 hba->nr_hw_queues = 1;
2832 for (i = 0; i < shost->nr_maps; i++) {
2833 struct blk_mq_queue_map *map = &shost->tag_set.map[i];
2835 map->nr_queues = hba->nr_queues[i];
2836 if (!map->nr_queues)
2838 map->queue_offset = queue_offset;
2839 if (i == HCTX_TYPE_POLL && !is_mcq_supported(hba))
2840 map->queue_offset = 0;
2842 blk_mq_map_queues(map);
2843 queue_offset += map->nr_queues;
2847 static void ufshcd_init_lrb(struct ufs_hba *hba, struct ufshcd_lrb *lrb, int i)
2849 struct utp_transfer_cmd_desc *cmd_descp = (void *)hba->ucdl_base_addr +
2850 i * sizeof_utp_transfer_cmd_desc(hba);
2851 struct utp_transfer_req_desc *utrdlp = hba->utrdl_base_addr;
2852 dma_addr_t cmd_desc_element_addr = hba->ucdl_dma_addr +
2853 i * sizeof_utp_transfer_cmd_desc(hba);
2854 u16 response_offset = offsetof(struct utp_transfer_cmd_desc,
2856 u16 prdt_offset = offsetof(struct utp_transfer_cmd_desc, prd_table);
2858 lrb->utr_descriptor_ptr = utrdlp + i;
2859 lrb->utrd_dma_addr = hba->utrdl_dma_addr +
2860 i * sizeof(struct utp_transfer_req_desc);
2861 lrb->ucd_req_ptr = (struct utp_upiu_req *)cmd_descp->command_upiu;
2862 lrb->ucd_req_dma_addr = cmd_desc_element_addr;
2863 lrb->ucd_rsp_ptr = (struct utp_upiu_rsp *)cmd_descp->response_upiu;
2864 lrb->ucd_rsp_dma_addr = cmd_desc_element_addr + response_offset;
2865 lrb->ucd_prdt_ptr = (struct ufshcd_sg_entry *)cmd_descp->prd_table;
2866 lrb->ucd_prdt_dma_addr = cmd_desc_element_addr + prdt_offset;
2870 * ufshcd_queuecommand - main entry point for SCSI requests
2871 * @host: SCSI host pointer
2872 * @cmd: command from SCSI Midlayer
2874 * Returns 0 for success, non-zero in case of failure
2876 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2878 struct ufs_hba *hba = shost_priv(host);
2879 int tag = scsi_cmd_to_rq(cmd)->tag;
2880 struct ufshcd_lrb *lrbp;
2882 struct ufs_hw_queue *hwq = NULL;
2884 WARN_ONCE(tag < 0 || tag >= hba->nutrs, "Invalid tag %d\n", tag);
2887 * Allows the UFS error handler to wait for prior ufshcd_queuecommand()
2892 switch (hba->ufshcd_state) {
2893 case UFSHCD_STATE_OPERATIONAL:
2895 case UFSHCD_STATE_EH_SCHEDULED_NON_FATAL:
2897 * SCSI error handler can call ->queuecommand() while UFS error
2898 * handler is in progress. Error interrupts could change the
2899 * state from UFSHCD_STATE_RESET to
2900 * UFSHCD_STATE_EH_SCHEDULED_NON_FATAL. Prevent requests
2901 * being issued in that case.
2903 if (ufshcd_eh_in_progress(hba)) {
2904 err = SCSI_MLQUEUE_HOST_BUSY;
2908 case UFSHCD_STATE_EH_SCHEDULED_FATAL:
2910 * pm_runtime_get_sync() is used at error handling preparation
2911 * stage. If a scsi cmd, e.g. the SSU cmd, is sent from hba's
2912 * PM ops, it can never be finished if we let SCSI layer keep
2913 * retrying it, which gets err handler stuck forever. Neither
2914 * can we let the scsi cmd pass through, because UFS is in bad
2915 * state, the scsi cmd may eventually time out, which will get
2916 * err handler blocked for too long. So, just fail the scsi cmd
2917 * sent from PM ops, err handler can recover PM error anyways.
2919 if (hba->pm_op_in_progress) {
2920 hba->force_reset = true;
2921 set_host_byte(cmd, DID_BAD_TARGET);
2926 case UFSHCD_STATE_RESET:
2927 err = SCSI_MLQUEUE_HOST_BUSY;
2929 case UFSHCD_STATE_ERROR:
2930 set_host_byte(cmd, DID_ERROR);
2935 hba->req_abort_count = 0;
2937 err = ufshcd_hold(hba, true);
2939 err = SCSI_MLQUEUE_HOST_BUSY;
2942 WARN_ON(ufshcd_is_clkgating_allowed(hba) &&
2943 (hba->clk_gating.state != CLKS_ON));
2945 lrbp = &hba->lrb[tag];
2948 lrbp->task_tag = tag;
2949 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2950 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba);
2952 ufshcd_prepare_lrbp_crypto(scsi_cmd_to_rq(cmd), lrbp);
2954 lrbp->req_abort_skip = false;
2956 ufshpb_prep(hba, lrbp);
2958 ufshcd_comp_scsi_upiu(hba, lrbp);
2960 err = ufshcd_map_sg(hba, lrbp);
2963 ufshcd_release(hba);
2967 if (is_mcq_enabled(hba))
2968 hwq = ufshcd_mcq_req_to_hwq(hba, scsi_cmd_to_rq(cmd));
2970 ufshcd_send_command(hba, tag, hwq);
2975 if (ufs_trigger_eh()) {
2976 unsigned long flags;
2978 spin_lock_irqsave(hba->host->host_lock, flags);
2979 ufshcd_schedule_eh_work(hba);
2980 spin_unlock_irqrestore(hba->host->host_lock, flags);
2986 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2987 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2990 lrbp->task_tag = tag;
2991 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2992 lrbp->intr_cmd = true; /* No interrupt aggregation */
2993 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
2994 hba->dev_cmd.type = cmd_type;
2996 return ufshcd_compose_devman_upiu(hba, lrbp);
3000 * Check with the block layer if the command is inflight
3001 * @cmd: command to check.
3003 * Returns true if command is inflight; false if not.
3005 bool ufshcd_cmd_inflight(struct scsi_cmnd *cmd)
3012 rq = scsi_cmd_to_rq(cmd);
3013 if (!blk_mq_request_started(rq))
3020 * Clear the pending command in the controller and wait until
3021 * the controller confirms that the command has been cleared.
3022 * @hba: per adapter instance
3023 * @task_tag: The tag number of the command to be cleared.
3025 static int ufshcd_clear_cmd(struct ufs_hba *hba, u32 task_tag)
3027 u32 mask = 1U << task_tag;
3028 unsigned long flags;
3031 if (is_mcq_enabled(hba)) {
3033 * MCQ mode. Clean up the MCQ resources similar to
3034 * what the ufshcd_utrl_clear() does for SDB mode.
3036 err = ufshcd_mcq_sq_cleanup(hba, task_tag);
3038 dev_err(hba->dev, "%s: failed tag=%d. err=%d\n",
3039 __func__, task_tag, err);
3045 /* clear outstanding transaction before retry */
3046 spin_lock_irqsave(hba->host->host_lock, flags);
3047 ufshcd_utrl_clear(hba, mask);
3048 spin_unlock_irqrestore(hba->host->host_lock, flags);
3051 * wait for h/w to clear corresponding bit in door-bell.
3052 * max. wait is 1 sec.
3054 return ufshcd_wait_for_register(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL,
3055 mask, ~mask, 1000, 1000);
3059 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
3061 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
3063 /* Get the UPIU response */
3064 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
3065 UPIU_RSP_CODE_OFFSET;
3066 return query_res->response;
3070 * ufshcd_dev_cmd_completion() - handles device management command responses
3071 * @hba: per adapter instance
3072 * @lrbp: pointer to local reference block
3075 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
3080 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
3081 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
3084 case UPIU_TRANSACTION_NOP_IN:
3085 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
3087 dev_err(hba->dev, "%s: unexpected response %x\n",
3091 case UPIU_TRANSACTION_QUERY_RSP:
3092 err = ufshcd_check_query_response(hba, lrbp);
3094 err = ufshcd_copy_query_response(hba, lrbp);
3096 case UPIU_TRANSACTION_REJECT_UPIU:
3097 /* TODO: handle Reject UPIU Response */
3099 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
3102 case UPIU_TRANSACTION_RESPONSE:
3103 if (hba->dev_cmd.type != DEV_CMD_TYPE_RPMB) {
3105 dev_err(hba->dev, "%s: unexpected response %x\n", __func__, resp);
3110 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
3118 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
3119 struct ufshcd_lrb *lrbp, int max_timeout)
3121 unsigned long time_left = msecs_to_jiffies(max_timeout);
3122 unsigned long flags;
3127 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
3130 if (likely(time_left)) {
3132 * The completion handler called complete() and the caller of
3133 * this function still owns the @lrbp tag so the code below does
3134 * not trigger any race conditions.
3136 hba->dev_cmd.complete = NULL;
3137 err = ufshcd_get_tr_ocs(lrbp, hba->dev_cmd.cqe);
3139 err = ufshcd_dev_cmd_completion(hba, lrbp);
3142 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
3143 __func__, lrbp->task_tag);
3144 if (ufshcd_clear_cmd(hba, lrbp->task_tag) == 0) {
3145 /* successfully cleared the command, retry if needed */
3148 * Since clearing the command succeeded we also need to
3149 * clear the task tag bit from the outstanding_reqs
3152 spin_lock_irqsave(&hba->outstanding_lock, flags);
3153 pending = test_bit(lrbp->task_tag,
3154 &hba->outstanding_reqs);
3156 hba->dev_cmd.complete = NULL;
3157 __clear_bit(lrbp->task_tag,
3158 &hba->outstanding_reqs);
3160 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
3164 * The completion handler ran while we tried to
3165 * clear the command.
3171 dev_err(hba->dev, "%s: failed to clear tag %d\n",
3172 __func__, lrbp->task_tag);
3174 spin_lock_irqsave(&hba->outstanding_lock, flags);
3175 pending = test_bit(lrbp->task_tag,
3176 &hba->outstanding_reqs);
3178 hba->dev_cmd.complete = NULL;
3179 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
3183 * The completion handler ran while we tried to
3184 * clear the command.
3196 * ufshcd_exec_dev_cmd - API for sending device management requests
3198 * @cmd_type: specifies the type (NOP, Query...)
3199 * @timeout: timeout in milliseconds
3201 * NOTE: Since there is only one available tag for device management commands,
3202 * it is expected you hold the hba->dev_cmd.lock mutex.
3204 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
3205 enum dev_cmd_type cmd_type, int timeout)
3207 DECLARE_COMPLETION_ONSTACK(wait);
3208 const u32 tag = hba->reserved_slot;
3209 struct ufshcd_lrb *lrbp;
3212 /* Protects use of hba->reserved_slot. */
3213 lockdep_assert_held(&hba->dev_cmd.lock);
3215 down_read(&hba->clk_scaling_lock);
3217 lrbp = &hba->lrb[tag];
3219 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
3223 hba->dev_cmd.complete = &wait;
3224 hba->dev_cmd.cqe = NULL;
3226 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
3228 ufshcd_send_command(hba, tag, hba->dev_cmd_queue);
3229 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
3230 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
3231 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
3234 up_read(&hba->clk_scaling_lock);
3239 * ufshcd_init_query() - init the query response and request parameters
3240 * @hba: per-adapter instance
3241 * @request: address of the request pointer to be initialized
3242 * @response: address of the response pointer to be initialized
3243 * @opcode: operation to perform
3244 * @idn: flag idn to access
3245 * @index: LU number to access
3246 * @selector: query/flag/descriptor further identification
3248 static inline void ufshcd_init_query(struct ufs_hba *hba,
3249 struct ufs_query_req **request, struct ufs_query_res **response,
3250 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
3252 *request = &hba->dev_cmd.query.request;
3253 *response = &hba->dev_cmd.query.response;
3254 memset(*request, 0, sizeof(struct ufs_query_req));
3255 memset(*response, 0, sizeof(struct ufs_query_res));
3256 (*request)->upiu_req.opcode = opcode;
3257 (*request)->upiu_req.idn = idn;
3258 (*request)->upiu_req.index = index;
3259 (*request)->upiu_req.selector = selector;
3262 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
3263 enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res)
3268 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
3269 ret = ufshcd_query_flag(hba, opcode, idn, index, flag_res);
3272 "%s: failed with error %d, retries %d\n",
3273 __func__, ret, retries);
3280 "%s: query flag, opcode %d, idn %d, failed with error %d after %d retries\n",
3281 __func__, opcode, idn, ret, retries);
3286 * ufshcd_query_flag() - API function for sending flag query requests
3287 * @hba: per-adapter instance
3288 * @opcode: flag query to perform
3289 * @idn: flag idn to access
3290 * @index: flag index to access
3291 * @flag_res: the flag value after the query request completes
3293 * Returns 0 for success, non-zero in case of failure
3295 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
3296 enum flag_idn idn, u8 index, bool *flag_res)
3298 struct ufs_query_req *request = NULL;
3299 struct ufs_query_res *response = NULL;
3300 int err, selector = 0;
3301 int timeout = QUERY_REQ_TIMEOUT;
3305 ufshcd_hold(hba, false);
3306 mutex_lock(&hba->dev_cmd.lock);
3307 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3311 case UPIU_QUERY_OPCODE_SET_FLAG:
3312 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
3313 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
3314 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3316 case UPIU_QUERY_OPCODE_READ_FLAG:
3317 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3319 /* No dummy reads */
3320 dev_err(hba->dev, "%s: Invalid argument for read request\n",
3328 "%s: Expected query flag opcode but got = %d\n",
3334 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
3338 "%s: Sending flag query for idn %d failed, err = %d\n",
3339 __func__, idn, err);
3344 *flag_res = (be32_to_cpu(response->upiu_res.value) &
3345 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
3348 mutex_unlock(&hba->dev_cmd.lock);
3349 ufshcd_release(hba);
3354 * ufshcd_query_attr - API function for sending attribute requests
3355 * @hba: per-adapter instance
3356 * @opcode: attribute opcode
3357 * @idn: attribute idn to access
3358 * @index: index field
3359 * @selector: selector field
3360 * @attr_val: the attribute value after the query request completes
3362 * Returns 0 for success, non-zero in case of failure
3364 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
3365 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
3367 struct ufs_query_req *request = NULL;
3368 struct ufs_query_res *response = NULL;
3374 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
3379 ufshcd_hold(hba, false);
3381 mutex_lock(&hba->dev_cmd.lock);
3382 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3386 case UPIU_QUERY_OPCODE_WRITE_ATTR:
3387 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3388 request->upiu_req.value = cpu_to_be32(*attr_val);
3390 case UPIU_QUERY_OPCODE_READ_ATTR:
3391 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3394 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
3400 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3403 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3404 __func__, opcode, idn, index, err);
3408 *attr_val = be32_to_cpu(response->upiu_res.value);
3411 mutex_unlock(&hba->dev_cmd.lock);
3412 ufshcd_release(hba);
3417 * ufshcd_query_attr_retry() - API function for sending query
3418 * attribute with retries
3419 * @hba: per-adapter instance
3420 * @opcode: attribute opcode
3421 * @idn: attribute idn to access
3422 * @index: index field
3423 * @selector: selector field
3424 * @attr_val: the attribute value after the query request
3427 * Returns 0 for success, non-zero in case of failure
3429 int ufshcd_query_attr_retry(struct ufs_hba *hba,
3430 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
3436 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3437 ret = ufshcd_query_attr(hba, opcode, idn, index,
3438 selector, attr_val);
3440 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
3441 __func__, ret, retries);
3448 "%s: query attribute, idn %d, failed with error %d after %d retries\n",
3449 __func__, idn, ret, QUERY_REQ_RETRIES);
3453 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
3454 enum query_opcode opcode, enum desc_idn idn, u8 index,
3455 u8 selector, u8 *desc_buf, int *buf_len)
3457 struct ufs_query_req *request = NULL;
3458 struct ufs_query_res *response = NULL;
3464 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
3469 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
3470 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
3471 __func__, *buf_len);
3475 ufshcd_hold(hba, false);
3477 mutex_lock(&hba->dev_cmd.lock);
3478 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3480 hba->dev_cmd.query.descriptor = desc_buf;
3481 request->upiu_req.length = cpu_to_be16(*buf_len);
3484 case UPIU_QUERY_OPCODE_WRITE_DESC:
3485 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3487 case UPIU_QUERY_OPCODE_READ_DESC:
3488 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3492 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
3498 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3501 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3502 __func__, opcode, idn, index, err);
3506 *buf_len = be16_to_cpu(response->upiu_res.length);
3509 hba->dev_cmd.query.descriptor = NULL;
3510 mutex_unlock(&hba->dev_cmd.lock);
3511 ufshcd_release(hba);
3516 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3517 * @hba: per-adapter instance
3518 * @opcode: attribute opcode
3519 * @idn: attribute idn to access
3520 * @index: index field
3521 * @selector: selector field
3522 * @desc_buf: the buffer that contains the descriptor
3523 * @buf_len: length parameter passed to the device
3525 * Returns 0 for success, non-zero in case of failure.
3526 * The buf_len parameter will contain, on return, the length parameter
3527 * received on the response.
3529 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3530 enum query_opcode opcode,
3531 enum desc_idn idn, u8 index,
3533 u8 *desc_buf, int *buf_len)
3538 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3539 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3540 selector, desc_buf, buf_len);
3541 if (!err || err == -EINVAL)
3549 * ufshcd_read_desc_param - read the specified descriptor parameter
3550 * @hba: Pointer to adapter instance
3551 * @desc_id: descriptor idn value
3552 * @desc_index: descriptor index
3553 * @param_offset: offset of the parameter to read
3554 * @param_read_buf: pointer to buffer where parameter would be read
3555 * @param_size: sizeof(param_read_buf)
3557 * Return 0 in case of success, non-zero otherwise
3559 int ufshcd_read_desc_param(struct ufs_hba *hba,
3560 enum desc_idn desc_id,
3568 int buff_len = QUERY_DESC_MAX_SIZE;
3569 bool is_kmalloc = true;
3572 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3575 /* Check whether we need temp memory */
3576 if (param_offset != 0 || param_size < buff_len) {
3577 desc_buf = kzalloc(buff_len, GFP_KERNEL);
3581 desc_buf = param_read_buf;
3585 /* Request for full descriptor */
3586 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3587 desc_id, desc_index, 0,
3588 desc_buf, &buff_len);
3590 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d\n",
3591 __func__, desc_id, desc_index, param_offset, ret);
3595 /* Update descriptor length */
3596 buff_len = desc_buf[QUERY_DESC_LENGTH_OFFSET];
3598 if (param_offset >= buff_len) {
3599 dev_err(hba->dev, "%s: Invalid offset 0x%x in descriptor IDN 0x%x, length 0x%x\n",
3600 __func__, param_offset, desc_id, buff_len);
3606 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3607 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header\n",
3608 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3614 /* Make sure we don't copy more data than available */
3615 if (param_offset >= buff_len)
3618 memcpy(param_read_buf, &desc_buf[param_offset],
3619 min_t(u32, param_size, buff_len - param_offset));
3628 * struct uc_string_id - unicode string
3630 * @len: size of this descriptor inclusive
3631 * @type: descriptor type
3632 * @uc: unicode string character
3634 struct uc_string_id {
3640 /* replace non-printable or non-ASCII characters with spaces */
3641 static inline char ufshcd_remove_non_printable(u8 ch)
3643 return (ch >= 0x20 && ch <= 0x7e) ? ch : ' ';
3647 * ufshcd_read_string_desc - read string descriptor
3648 * @hba: pointer to adapter instance
3649 * @desc_index: descriptor index
3650 * @buf: pointer to buffer where descriptor would be read,
3651 * the caller should free the memory.
3652 * @ascii: if true convert from unicode to ascii characters
3653 * null terminated string.
3656 * * string size on success.
3657 * * -ENOMEM: on allocation failure
3658 * * -EINVAL: on a wrong parameter
3660 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index,
3661 u8 **buf, bool ascii)
3663 struct uc_string_id *uc_str;
3670 uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
3674 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_STRING, desc_index, 0,
3675 (u8 *)uc_str, QUERY_DESC_MAX_SIZE);
3677 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n",
3678 QUERY_REQ_RETRIES, ret);
3683 if (uc_str->len <= QUERY_DESC_HDR_SIZE) {
3684 dev_dbg(hba->dev, "String Desc is of zero length\n");
3693 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3694 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3695 str = kzalloc(ascii_len, GFP_KERNEL);
3702 * the descriptor contains string in UTF16 format
3703 * we need to convert to utf-8 so it can be displayed
3705 ret = utf16s_to_utf8s(uc_str->uc,
3706 uc_str->len - QUERY_DESC_HDR_SIZE,
3707 UTF16_BIG_ENDIAN, str, ascii_len);
3709 /* replace non-printable or non-ASCII characters with spaces */
3710 for (i = 0; i < ret; i++)
3711 str[i] = ufshcd_remove_non_printable(str[i]);
3716 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL);
3730 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3731 * @hba: Pointer to adapter instance
3733 * @param_offset: offset of the parameter to read
3734 * @param_read_buf: pointer to buffer where parameter would be read
3735 * @param_size: sizeof(param_read_buf)
3737 * Return 0 in case of success, non-zero otherwise
3739 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3741 enum unit_desc_param param_offset,
3746 * Unit descriptors are only available for general purpose LUs (LUN id
3747 * from 0 to 7) and RPMB Well known LU.
3749 if (!ufs_is_valid_unit_desc_lun(&hba->dev_info, lun))
3752 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3753 param_offset, param_read_buf, param_size);
3756 static int ufshcd_get_ref_clk_gating_wait(struct ufs_hba *hba)
3759 u32 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3761 if (hba->dev_info.wspecversion >= 0x300) {
3762 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3763 QUERY_ATTR_IDN_REF_CLK_GATING_WAIT_TIME, 0, 0,
3766 dev_err(hba->dev, "Failed reading bRefClkGatingWait. err = %d, use default %uus\n",
3769 if (gating_wait == 0) {
3770 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3771 dev_err(hba->dev, "Undefined ref clk gating wait time, use default %uus\n",
3775 hba->dev_info.clk_gating_wait_us = gating_wait;
3782 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3783 * @hba: per adapter instance
3785 * 1. Allocate DMA memory for Command Descriptor array
3786 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3787 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3788 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3790 * 4. Allocate memory for local reference block(lrb).
3792 * Returns 0 for success, non-zero in case of failure
3794 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3796 size_t utmrdl_size, utrdl_size, ucdl_size;
3798 /* Allocate memory for UTP command descriptors */
3799 ucdl_size = sizeof_utp_transfer_cmd_desc(hba) * hba->nutrs;
3800 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3802 &hba->ucdl_dma_addr,
3806 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3808 if (!hba->ucdl_base_addr ||
3809 WARN_ON(hba->ucdl_dma_addr & (128 - 1))) {
3811 "Command Descriptor Memory allocation failed\n");
3816 * Allocate memory for UTP Transfer descriptors
3817 * UFSHCI requires 1024 byte alignment of UTRD
3819 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3820 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3822 &hba->utrdl_dma_addr,
3824 if (!hba->utrdl_base_addr ||
3825 WARN_ON(hba->utrdl_dma_addr & (1024 - 1))) {
3827 "Transfer Descriptor Memory allocation failed\n");
3832 * Skip utmrdl allocation; it may have been
3833 * allocated during first pass and not released during
3834 * MCQ memory allocation.
3835 * See ufshcd_release_sdb_queue() and ufshcd_config_mcq()
3837 if (hba->utmrdl_base_addr)
3840 * Allocate memory for UTP Task Management descriptors
3841 * UFSHCI requires 1024 byte alignment of UTMRD
3843 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3844 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3846 &hba->utmrdl_dma_addr,
3848 if (!hba->utmrdl_base_addr ||
3849 WARN_ON(hba->utmrdl_dma_addr & (1024 - 1))) {
3851 "Task Management Descriptor Memory allocation failed\n");
3856 /* Allocate memory for local reference block */
3857 hba->lrb = devm_kcalloc(hba->dev,
3858 hba->nutrs, sizeof(struct ufshcd_lrb),
3861 dev_err(hba->dev, "LRB Memory allocation failed\n");
3870 * ufshcd_host_memory_configure - configure local reference block with
3872 * @hba: per adapter instance
3874 * Configure Host memory space
3875 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3877 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3879 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3880 * into local reference block.
3882 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3884 struct utp_transfer_req_desc *utrdlp;
3885 dma_addr_t cmd_desc_dma_addr;
3886 dma_addr_t cmd_desc_element_addr;
3887 u16 response_offset;
3892 utrdlp = hba->utrdl_base_addr;
3895 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3897 offsetof(struct utp_transfer_cmd_desc, prd_table);
3899 cmd_desc_size = sizeof_utp_transfer_cmd_desc(hba);
3900 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3902 for (i = 0; i < hba->nutrs; i++) {
3903 /* Configure UTRD with command descriptor base address */
3904 cmd_desc_element_addr =
3905 (cmd_desc_dma_addr + (cmd_desc_size * i));
3906 utrdlp[i].command_desc_base_addr =
3907 cpu_to_le64(cmd_desc_element_addr);
3909 /* Response upiu and prdt offset should be in double words */
3910 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3911 utrdlp[i].response_upiu_offset =
3912 cpu_to_le16(response_offset);
3913 utrdlp[i].prd_table_offset =
3914 cpu_to_le16(prdt_offset);
3915 utrdlp[i].response_upiu_length =
3916 cpu_to_le16(ALIGNED_UPIU_SIZE);
3918 utrdlp[i].response_upiu_offset =
3919 cpu_to_le16(response_offset >> 2);
3920 utrdlp[i].prd_table_offset =
3921 cpu_to_le16(prdt_offset >> 2);
3922 utrdlp[i].response_upiu_length =
3923 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3926 ufshcd_init_lrb(hba, &hba->lrb[i], i);
3931 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3932 * @hba: per adapter instance
3934 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3935 * in order to initialize the Unipro link startup procedure.
3936 * Once the Unipro links are up, the device connected to the controller
3939 * Returns 0 on success, non-zero value on failure
3941 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3943 struct uic_command uic_cmd = {0};
3946 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3948 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3951 "dme-link-startup: error code %d\n", ret);
3955 * ufshcd_dme_reset - UIC command for DME_RESET
3956 * @hba: per adapter instance
3958 * DME_RESET command is issued in order to reset UniPro stack.
3959 * This function now deals with cold reset.
3961 * Returns 0 on success, non-zero value on failure
3963 static int ufshcd_dme_reset(struct ufs_hba *hba)
3965 struct uic_command uic_cmd = {0};
3968 uic_cmd.command = UIC_CMD_DME_RESET;
3970 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3973 "dme-reset: error code %d\n", ret);
3978 int ufshcd_dme_configure_adapt(struct ufs_hba *hba,
3984 if (agreed_gear < UFS_HS_G4)
3985 adapt_val = PA_NO_ADAPT;
3987 ret = ufshcd_dme_set(hba,
3988 UIC_ARG_MIB(PA_TXHSADAPTTYPE),
3992 EXPORT_SYMBOL_GPL(ufshcd_dme_configure_adapt);
3995 * ufshcd_dme_enable - UIC command for DME_ENABLE
3996 * @hba: per adapter instance
3998 * DME_ENABLE command is issued in order to enable UniPro stack.
4000 * Returns 0 on success, non-zero value on failure
4002 static int ufshcd_dme_enable(struct ufs_hba *hba)
4004 struct uic_command uic_cmd = {0};
4007 uic_cmd.command = UIC_CMD_DME_ENABLE;
4009 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
4012 "dme-enable: error code %d\n", ret);
4017 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
4019 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
4020 unsigned long min_sleep_time_us;
4022 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
4026 * last_dme_cmd_tstamp will be 0 only for 1st call to
4029 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
4030 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
4032 unsigned long delta =
4033 (unsigned long) ktime_to_us(
4034 ktime_sub(ktime_get(),
4035 hba->last_dme_cmd_tstamp));
4037 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
4039 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
4041 return; /* no more delay required */
4044 /* allow sleep for extra 50us if needed */
4045 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
4049 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
4050 * @hba: per adapter instance
4051 * @attr_sel: uic command argument1
4052 * @attr_set: attribute set type as uic command argument2
4053 * @mib_val: setting value as uic command argument3
4054 * @peer: indicate whether peer or local
4056 * Returns 0 on success, non-zero value on failure
4058 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
4059 u8 attr_set, u32 mib_val, u8 peer)
4061 struct uic_command uic_cmd = {0};
4062 static const char *const action[] = {
4066 const char *set = action[!!peer];
4068 int retries = UFS_UIC_COMMAND_RETRIES;
4070 uic_cmd.command = peer ?
4071 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
4072 uic_cmd.argument1 = attr_sel;
4073 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
4074 uic_cmd.argument3 = mib_val;
4077 /* for peer attributes we retry upon failure */
4078 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
4080 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
4081 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
4082 } while (ret && peer && --retries);
4085 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
4086 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
4087 UFS_UIC_COMMAND_RETRIES - retries);
4091 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
4094 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
4095 * @hba: per adapter instance
4096 * @attr_sel: uic command argument1
4097 * @mib_val: the value of the attribute as returned by the UIC command
4098 * @peer: indicate whether peer or local
4100 * Returns 0 on success, non-zero value on failure
4102 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
4103 u32 *mib_val, u8 peer)
4105 struct uic_command uic_cmd = {0};
4106 static const char *const action[] = {
4110 const char *get = action[!!peer];
4112 int retries = UFS_UIC_COMMAND_RETRIES;
4113 struct ufs_pa_layer_attr orig_pwr_info;
4114 struct ufs_pa_layer_attr temp_pwr_info;
4115 bool pwr_mode_change = false;
4117 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
4118 orig_pwr_info = hba->pwr_info;
4119 temp_pwr_info = orig_pwr_info;
4121 if (orig_pwr_info.pwr_tx == FAST_MODE ||
4122 orig_pwr_info.pwr_rx == FAST_MODE) {
4123 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
4124 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
4125 pwr_mode_change = true;
4126 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
4127 orig_pwr_info.pwr_rx == SLOW_MODE) {
4128 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
4129 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
4130 pwr_mode_change = true;
4132 if (pwr_mode_change) {
4133 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
4139 uic_cmd.command = peer ?
4140 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
4141 uic_cmd.argument1 = attr_sel;
4144 /* for peer attributes we retry upon failure */
4145 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
4147 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
4148 get, UIC_GET_ATTR_ID(attr_sel), ret);
4149 } while (ret && peer && --retries);
4152 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
4153 get, UIC_GET_ATTR_ID(attr_sel),
4154 UFS_UIC_COMMAND_RETRIES - retries);
4156 if (mib_val && !ret)
4157 *mib_val = uic_cmd.argument3;
4159 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
4161 ufshcd_change_power_mode(hba, &orig_pwr_info);
4165 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
4168 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
4169 * state) and waits for it to take effect.
4171 * @hba: per adapter instance
4172 * @cmd: UIC command to execute
4174 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
4175 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
4176 * and device UniPro link and hence it's final completion would be indicated by
4177 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
4178 * addition to normal UIC command completion Status (UCCS). This function only
4179 * returns after the relevant status bits indicate the completion.
4181 * Returns 0 on success, non-zero value on failure
4183 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
4185 DECLARE_COMPLETION_ONSTACK(uic_async_done);
4186 unsigned long flags;
4189 bool reenable_intr = false;
4191 mutex_lock(&hba->uic_cmd_mutex);
4192 ufshcd_add_delay_before_dme_cmd(hba);
4194 spin_lock_irqsave(hba->host->host_lock, flags);
4195 if (ufshcd_is_link_broken(hba)) {
4199 hba->uic_async_done = &uic_async_done;
4200 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
4201 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
4203 * Make sure UIC command completion interrupt is disabled before
4204 * issuing UIC command.
4207 reenable_intr = true;
4209 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
4210 spin_unlock_irqrestore(hba->host->host_lock, flags);
4213 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
4214 cmd->command, cmd->argument3, ret);
4218 if (!wait_for_completion_timeout(hba->uic_async_done,
4219 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
4221 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
4222 cmd->command, cmd->argument3);
4224 if (!cmd->cmd_active) {
4225 dev_err(hba->dev, "%s: Power Mode Change operation has been completed, go check UPMCRS\n",
4235 status = ufshcd_get_upmcrs(hba);
4236 if (status != PWR_LOCAL) {
4238 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
4239 cmd->command, status);
4240 ret = (status != PWR_OK) ? status : -1;
4244 ufshcd_print_host_state(hba);
4245 ufshcd_print_pwr_info(hba);
4246 ufshcd_print_evt_hist(hba);
4249 spin_lock_irqsave(hba->host->host_lock, flags);
4250 hba->active_uic_cmd = NULL;
4251 hba->uic_async_done = NULL;
4253 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
4255 ufshcd_set_link_broken(hba);
4256 ufshcd_schedule_eh_work(hba);
4259 spin_unlock_irqrestore(hba->host->host_lock, flags);
4260 mutex_unlock(&hba->uic_cmd_mutex);
4266 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
4267 * using DME_SET primitives.
4268 * @hba: per adapter instance
4269 * @mode: powr mode value
4271 * Returns 0 on success, non-zero value on failure
4273 int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
4275 struct uic_command uic_cmd = {0};
4278 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
4279 ret = ufshcd_dme_set(hba,
4280 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
4282 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
4288 uic_cmd.command = UIC_CMD_DME_SET;
4289 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
4290 uic_cmd.argument3 = mode;
4291 ufshcd_hold(hba, false);
4292 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4293 ufshcd_release(hba);
4298 EXPORT_SYMBOL_GPL(ufshcd_uic_change_pwr_mode);
4300 int ufshcd_link_recovery(struct ufs_hba *hba)
4303 unsigned long flags;
4305 spin_lock_irqsave(hba->host->host_lock, flags);
4306 hba->ufshcd_state = UFSHCD_STATE_RESET;
4307 ufshcd_set_eh_in_progress(hba);
4308 spin_unlock_irqrestore(hba->host->host_lock, flags);
4310 /* Reset the attached device */
4311 ufshcd_device_reset(hba);
4313 ret = ufshcd_host_reset_and_restore(hba);
4315 spin_lock_irqsave(hba->host->host_lock, flags);
4317 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4318 ufshcd_clear_eh_in_progress(hba);
4319 spin_unlock_irqrestore(hba->host->host_lock, flags);
4322 dev_err(hba->dev, "%s: link recovery failed, err %d",
4327 EXPORT_SYMBOL_GPL(ufshcd_link_recovery);
4329 int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
4332 struct uic_command uic_cmd = {0};
4333 ktime_t start = ktime_get();
4335 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
4337 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
4338 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4339 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
4340 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4343 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
4346 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
4351 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_enter);
4353 int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
4355 struct uic_command uic_cmd = {0};
4357 ktime_t start = ktime_get();
4359 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
4361 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
4362 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4363 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
4364 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4367 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
4370 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
4372 hba->ufs_stats.last_hibern8_exit_tstamp = local_clock();
4373 hba->ufs_stats.hibern8_exit_cnt++;
4378 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_exit);
4380 void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit)
4382 unsigned long flags;
4383 bool update = false;
4385 if (!ufshcd_is_auto_hibern8_supported(hba))
4388 spin_lock_irqsave(hba->host->host_lock, flags);
4389 if (hba->ahit != ahit) {
4393 spin_unlock_irqrestore(hba->host->host_lock, flags);
4396 !pm_runtime_suspended(&hba->ufs_device_wlun->sdev_gendev)) {
4397 ufshcd_rpm_get_sync(hba);
4398 ufshcd_hold(hba, false);
4399 ufshcd_auto_hibern8_enable(hba);
4400 ufshcd_release(hba);
4401 ufshcd_rpm_put_sync(hba);
4404 EXPORT_SYMBOL_GPL(ufshcd_auto_hibern8_update);
4406 void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
4408 if (!ufshcd_is_auto_hibern8_supported(hba))
4411 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
4415 * ufshcd_init_pwr_info - setting the POR (power on reset)
4416 * values in hba power info
4417 * @hba: per-adapter instance
4419 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
4421 hba->pwr_info.gear_rx = UFS_PWM_G1;
4422 hba->pwr_info.gear_tx = UFS_PWM_G1;
4423 hba->pwr_info.lane_rx = 1;
4424 hba->pwr_info.lane_tx = 1;
4425 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
4426 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
4427 hba->pwr_info.hs_rate = 0;
4431 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
4432 * @hba: per-adapter instance
4434 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
4436 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
4438 if (hba->max_pwr_info.is_valid)
4441 if (hba->quirks & UFSHCD_QUIRK_HIBERN_FASTAUTO) {
4442 pwr_info->pwr_tx = FASTAUTO_MODE;
4443 pwr_info->pwr_rx = FASTAUTO_MODE;
4445 pwr_info->pwr_tx = FAST_MODE;
4446 pwr_info->pwr_rx = FAST_MODE;
4448 pwr_info->hs_rate = PA_HS_MODE_B;
4450 /* Get the connected lane count */
4451 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
4452 &pwr_info->lane_rx);
4453 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4454 &pwr_info->lane_tx);
4456 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
4457 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4465 * First, get the maximum gears of HS speed.
4466 * If a zero value, it means there is no HSGEAR capability.
4467 * Then, get the maximum gears of PWM speed.
4469 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4470 if (!pwr_info->gear_rx) {
4471 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4472 &pwr_info->gear_rx);
4473 if (!pwr_info->gear_rx) {
4474 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4475 __func__, pwr_info->gear_rx);
4478 pwr_info->pwr_rx = SLOW_MODE;
4481 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4482 &pwr_info->gear_tx);
4483 if (!pwr_info->gear_tx) {
4484 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4485 &pwr_info->gear_tx);
4486 if (!pwr_info->gear_tx) {
4487 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4488 __func__, pwr_info->gear_tx);
4491 pwr_info->pwr_tx = SLOW_MODE;
4494 hba->max_pwr_info.is_valid = true;
4498 static int ufshcd_change_power_mode(struct ufs_hba *hba,
4499 struct ufs_pa_layer_attr *pwr_mode)
4503 /* if already configured to the requested pwr_mode */
4504 if (!hba->force_pmc &&
4505 pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4506 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4507 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4508 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4509 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4510 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4511 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4512 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4517 * Configure attributes for power mode change with below.
4518 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4519 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4522 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4523 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4525 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4526 pwr_mode->pwr_rx == FAST_MODE)
4527 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), true);
4529 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), false);
4531 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4532 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4534 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4535 pwr_mode->pwr_tx == FAST_MODE)
4536 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), true);
4538 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), false);
4540 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4541 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4542 pwr_mode->pwr_rx == FAST_MODE ||
4543 pwr_mode->pwr_tx == FAST_MODE)
4544 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4547 if (!(hba->quirks & UFSHCD_QUIRK_SKIP_DEF_UNIPRO_TIMEOUT_SETTING)) {
4548 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0),
4549 DL_FC0ProtectionTimeOutVal_Default);
4550 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1),
4551 DL_TC0ReplayTimeOutVal_Default);
4552 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2),
4553 DL_AFC0ReqTimeOutVal_Default);
4554 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA3),
4555 DL_FC1ProtectionTimeOutVal_Default);
4556 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA4),
4557 DL_TC1ReplayTimeOutVal_Default);
4558 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA5),
4559 DL_AFC1ReqTimeOutVal_Default);
4561 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal),
4562 DL_FC0ProtectionTimeOutVal_Default);
4563 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal),
4564 DL_TC0ReplayTimeOutVal_Default);
4565 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal),
4566 DL_AFC0ReqTimeOutVal_Default);
4569 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4570 | pwr_mode->pwr_tx);
4574 "%s: power mode change failed %d\n", __func__, ret);
4576 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4579 memcpy(&hba->pwr_info, pwr_mode,
4580 sizeof(struct ufs_pa_layer_attr));
4587 * ufshcd_config_pwr_mode - configure a new power mode
4588 * @hba: per-adapter instance
4589 * @desired_pwr_mode: desired power configuration
4591 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4592 struct ufs_pa_layer_attr *desired_pwr_mode)
4594 struct ufs_pa_layer_attr final_params = { 0 };
4597 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4598 desired_pwr_mode, &final_params);
4601 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4603 ret = ufshcd_change_power_mode(hba, &final_params);
4607 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4610 * ufshcd_complete_dev_init() - checks device readiness
4611 * @hba: per-adapter instance
4613 * Set fDeviceInit flag and poll until device toggles it.
4615 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4618 bool flag_res = true;
4621 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4622 QUERY_FLAG_IDN_FDEVICEINIT, 0, NULL);
4625 "%s: setting fDeviceInit flag failed with error %d\n",
4630 /* Poll fDeviceInit flag to be cleared */
4631 timeout = ktime_add_ms(ktime_get(), FDEVICEINIT_COMPL_TIMEOUT);
4633 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4634 QUERY_FLAG_IDN_FDEVICEINIT, 0, &flag_res);
4637 usleep_range(500, 1000);
4638 } while (ktime_before(ktime_get(), timeout));
4642 "%s: reading fDeviceInit flag failed with error %d\n",
4644 } else if (flag_res) {
4646 "%s: fDeviceInit was not cleared by the device\n",
4655 * ufshcd_make_hba_operational - Make UFS controller operational
4656 * @hba: per adapter instance
4658 * To bring UFS host controller to operational state,
4659 * 1. Enable required interrupts
4660 * 2. Configure interrupt aggregation
4661 * 3. Program UTRL and UTMRL base address
4662 * 4. Configure run-stop-registers
4664 * Returns 0 on success, non-zero value on failure
4666 int ufshcd_make_hba_operational(struct ufs_hba *hba)
4671 /* Enable required interrupts */
4672 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4674 /* Configure interrupt aggregation */
4675 if (ufshcd_is_intr_aggr_allowed(hba))
4676 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4678 ufshcd_disable_intr_aggr(hba);
4680 /* Configure UTRL and UTMRL base address registers */
4681 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4682 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4683 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4684 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4685 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4686 REG_UTP_TASK_REQ_LIST_BASE_L);
4687 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4688 REG_UTP_TASK_REQ_LIST_BASE_H);
4691 * Make sure base address and interrupt setup are updated before
4692 * enabling the run/stop registers below.
4697 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4699 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4700 if (!(ufshcd_get_lists_status(reg))) {
4701 ufshcd_enable_run_stop_reg(hba);
4704 "Host controller not ready to process requests");
4710 EXPORT_SYMBOL_GPL(ufshcd_make_hba_operational);
4713 * ufshcd_hba_stop - Send controller to reset state
4714 * @hba: per adapter instance
4716 void ufshcd_hba_stop(struct ufs_hba *hba)
4718 unsigned long flags;
4722 * Obtain the host lock to prevent that the controller is disabled
4723 * while the UFS interrupt handler is active on another CPU.
4725 spin_lock_irqsave(hba->host->host_lock, flags);
4726 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4727 spin_unlock_irqrestore(hba->host->host_lock, flags);
4729 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4730 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4733 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4735 EXPORT_SYMBOL_GPL(ufshcd_hba_stop);
4738 * ufshcd_hba_execute_hce - initialize the controller
4739 * @hba: per adapter instance
4741 * The controller resets itself and controller firmware initialization
4742 * sequence kicks off. When controller is ready it will set
4743 * the Host Controller Enable bit to 1.
4745 * Returns 0 on success, non-zero value on failure
4747 static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
4749 int retry_outer = 3;
4753 if (ufshcd_is_hba_active(hba))
4754 /* change controller state to "reset state" */
4755 ufshcd_hba_stop(hba);
4757 /* UniPro link is disabled at this point */
4758 ufshcd_set_link_off(hba);
4760 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4762 /* start controller initialization sequence */
4763 ufshcd_hba_start(hba);
4766 * To initialize a UFS host controller HCE bit must be set to 1.
4767 * During initialization the HCE bit value changes from 1->0->1.
4768 * When the host controller completes initialization sequence
4769 * it sets the value of HCE bit to 1. The same HCE bit is read back
4770 * to check if the controller has completed initialization sequence.
4771 * So without this delay the value HCE = 1, set in the previous
4772 * instruction might be read back.
4773 * This delay can be changed based on the controller.
4775 ufshcd_delay_us(hba->vps->hba_enable_delay_us, 100);
4777 /* wait for the host controller to complete initialization */
4779 while (!ufshcd_is_hba_active(hba)) {
4784 "Controller enable failed\n");
4791 usleep_range(1000, 1100);
4794 /* enable UIC related interrupts */
4795 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4797 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4802 int ufshcd_hba_enable(struct ufs_hba *hba)
4806 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
4807 ufshcd_set_link_off(hba);
4808 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4810 /* enable UIC related interrupts */
4811 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4812 ret = ufshcd_dme_reset(hba);
4814 dev_err(hba->dev, "DME_RESET failed\n");
4818 ret = ufshcd_dme_enable(hba);
4820 dev_err(hba->dev, "Enabling DME failed\n");
4824 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4826 ret = ufshcd_hba_execute_hce(hba);
4831 EXPORT_SYMBOL_GPL(ufshcd_hba_enable);
4833 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4835 int tx_lanes = 0, i, err = 0;
4838 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4841 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4843 for (i = 0; i < tx_lanes; i++) {
4845 err = ufshcd_dme_set(hba,
4846 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4847 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4850 err = ufshcd_dme_peer_set(hba,
4851 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4852 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4855 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4856 __func__, peer, i, err);
4864 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4866 return ufshcd_disable_tx_lcc(hba, true);
4869 void ufshcd_update_evt_hist(struct ufs_hba *hba, u32 id, u32 val)
4871 struct ufs_event_hist *e;
4873 if (id >= UFS_EVT_CNT)
4876 e = &hba->ufs_stats.event[id];
4877 e->val[e->pos] = val;
4878 e->tstamp[e->pos] = local_clock();
4880 e->pos = (e->pos + 1) % UFS_EVENT_HIST_LENGTH;
4882 ufshcd_vops_event_notify(hba, id, &val);
4884 EXPORT_SYMBOL_GPL(ufshcd_update_evt_hist);
4887 * ufshcd_link_startup - Initialize unipro link startup
4888 * @hba: per adapter instance
4890 * Returns 0 for success, non-zero in case of failure
4892 static int ufshcd_link_startup(struct ufs_hba *hba)
4895 int retries = DME_LINKSTARTUP_RETRIES;
4896 bool link_startup_again = false;
4899 * If UFS device isn't active then we will have to issue link startup
4900 * 2 times to make sure the device state move to active.
4902 if (!ufshcd_is_ufs_dev_active(hba))
4903 link_startup_again = true;
4907 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4909 ret = ufshcd_dme_link_startup(hba);
4911 /* check if device is detected by inter-connect layer */
4912 if (!ret && !ufshcd_is_device_present(hba)) {
4913 ufshcd_update_evt_hist(hba,
4914 UFS_EVT_LINK_STARTUP_FAIL,
4916 dev_err(hba->dev, "%s: Device not present\n", __func__);
4922 * DME link lost indication is only received when link is up,
4923 * but we can't be sure if the link is up until link startup
4924 * succeeds. So reset the local Uni-Pro and try again.
4926 if (ret && retries && ufshcd_hba_enable(hba)) {
4927 ufshcd_update_evt_hist(hba,
4928 UFS_EVT_LINK_STARTUP_FAIL,
4932 } while (ret && retries--);
4935 /* failed to get the link up... retire */
4936 ufshcd_update_evt_hist(hba,
4937 UFS_EVT_LINK_STARTUP_FAIL,
4942 if (link_startup_again) {
4943 link_startup_again = false;
4944 retries = DME_LINKSTARTUP_RETRIES;
4948 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4949 ufshcd_init_pwr_info(hba);
4950 ufshcd_print_pwr_info(hba);
4952 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4953 ret = ufshcd_disable_device_tx_lcc(hba);
4958 /* Include any host controller configuration via UIC commands */
4959 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4963 /* Clear UECPA once due to LINERESET has happened during LINK_STARTUP */
4964 ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
4965 ret = ufshcd_make_hba_operational(hba);
4968 dev_err(hba->dev, "link startup failed %d\n", ret);
4969 ufshcd_print_host_state(hba);
4970 ufshcd_print_pwr_info(hba);
4971 ufshcd_print_evt_hist(hba);
4977 * ufshcd_verify_dev_init() - Verify device initialization
4978 * @hba: per-adapter instance
4980 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4981 * device Transport Protocol (UTP) layer is ready after a reset.
4982 * If the UTP layer at the device side is not initialized, it may
4983 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4984 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4986 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4991 ufshcd_hold(hba, false);
4992 mutex_lock(&hba->dev_cmd.lock);
4993 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4994 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4995 hba->nop_out_timeout);
4997 if (!err || err == -ETIMEDOUT)
5000 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
5002 mutex_unlock(&hba->dev_cmd.lock);
5003 ufshcd_release(hba);
5006 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
5011 * ufshcd_setup_links - associate link b/w device wlun and other luns
5012 * @sdev: pointer to SCSI device
5013 * @hba: pointer to ufs hba
5015 static void ufshcd_setup_links(struct ufs_hba *hba, struct scsi_device *sdev)
5017 struct device_link *link;
5020 * Device wlun is the supplier & rest of the luns are consumers.
5021 * This ensures that device wlun suspends after all other luns.
5023 if (hba->ufs_device_wlun) {
5024 link = device_link_add(&sdev->sdev_gendev,
5025 &hba->ufs_device_wlun->sdev_gendev,
5026 DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE);
5028 dev_err(&sdev->sdev_gendev, "Failed establishing link - %s\n",
5029 dev_name(&hba->ufs_device_wlun->sdev_gendev));
5033 /* Ignore REPORT_LUN wlun probing */
5034 if (hba->luns_avail == 1) {
5035 ufshcd_rpm_put(hba);
5040 * Device wlun is probed. The assumption is that WLUNs are
5041 * scanned before other LUNs.
5048 * ufshcd_lu_init - Initialize the relevant parameters of the LU
5049 * @hba: per-adapter instance
5050 * @sdev: pointer to SCSI device
5052 static void ufshcd_lu_init(struct ufs_hba *hba, struct scsi_device *sdev)
5054 int len = QUERY_DESC_MAX_SIZE;
5055 u8 lun = ufshcd_scsi_to_upiu_lun(sdev->lun);
5056 u8 lun_qdepth = hba->nutrs;
5060 desc_buf = kzalloc(len, GFP_KERNEL);
5064 ret = ufshcd_read_unit_desc_param(hba, lun, 0, desc_buf, len);
5066 if (ret == -EOPNOTSUPP)
5067 /* If LU doesn't support unit descriptor, its queue depth is set to 1 */
5073 if (desc_buf[UNIT_DESC_PARAM_LU_Q_DEPTH]) {
5075 * In per-LU queueing architecture, bLUQueueDepth will not be 0, then we will
5076 * use the smaller between UFSHCI CAP.NUTRS and UFS LU bLUQueueDepth
5078 lun_qdepth = min_t(int, desc_buf[UNIT_DESC_PARAM_LU_Q_DEPTH], hba->nutrs);
5081 * According to UFS device specification, the write protection mode is only supported by
5082 * normal LU, not supported by WLUN.
5084 if (hba->dev_info.f_power_on_wp_en && lun < hba->dev_info.max_lu_supported &&
5085 !hba->dev_info.is_lu_power_on_wp &&
5086 desc_buf[UNIT_DESC_PARAM_LU_WR_PROTECT] == UFS_LU_POWER_ON_WP)
5087 hba->dev_info.is_lu_power_on_wp = true;
5089 /* In case of RPMB LU, check if advanced RPMB mode is enabled */
5090 if (desc_buf[UNIT_DESC_PARAM_UNIT_INDEX] == UFS_UPIU_RPMB_WLUN &&
5091 desc_buf[RPMB_UNIT_DESC_PARAM_REGION_EN] & BIT(4))
5092 hba->dev_info.b_advanced_rpmb_en = true;
5098 * For WLUNs that don't support unit descriptor, queue depth is set to 1. For LUs whose
5099 * bLUQueueDepth == 0, the queue depth is set to a maximum value that host can queue.
5101 dev_dbg(hba->dev, "Set LU %x queue depth %d\n", lun, lun_qdepth);
5102 scsi_change_queue_depth(sdev, lun_qdepth);
5106 * ufshcd_slave_alloc - handle initial SCSI device configurations
5107 * @sdev: pointer to SCSI device
5111 static int ufshcd_slave_alloc(struct scsi_device *sdev)
5113 struct ufs_hba *hba;
5115 hba = shost_priv(sdev->host);
5117 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
5118 sdev->use_10_for_ms = 1;
5120 /* DBD field should be set to 1 in mode sense(10) */
5121 sdev->set_dbd_for_ms = 1;
5123 /* allow SCSI layer to restart the device in case of errors */
5124 sdev->allow_restart = 1;
5126 /* REPORT SUPPORTED OPERATION CODES is not supported */
5127 sdev->no_report_opcodes = 1;
5129 /* WRITE_SAME command is not supported */
5130 sdev->no_write_same = 1;
5132 ufshcd_lu_init(hba, sdev);
5134 ufshcd_setup_links(hba, sdev);
5140 * ufshcd_change_queue_depth - change queue depth
5141 * @sdev: pointer to SCSI device
5142 * @depth: required depth to set
5144 * Change queue depth and make sure the max. limits are not crossed.
5146 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
5148 return scsi_change_queue_depth(sdev, min(depth, sdev->host->can_queue));
5151 static void ufshcd_hpb_destroy(struct ufs_hba *hba, struct scsi_device *sdev)
5153 /* skip well-known LU */
5154 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) ||
5155 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba))
5158 ufshpb_destroy_lu(hba, sdev);
5161 static void ufshcd_hpb_configure(struct ufs_hba *hba, struct scsi_device *sdev)
5163 /* skip well-known LU */
5164 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) ||
5165 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba))
5168 ufshpb_init_hpb_lu(hba, sdev);
5172 * ufshcd_slave_configure - adjust SCSI device configurations
5173 * @sdev: pointer to SCSI device
5175 static int ufshcd_slave_configure(struct scsi_device *sdev)
5177 struct ufs_hba *hba = shost_priv(sdev->host);
5178 struct request_queue *q = sdev->request_queue;
5180 ufshcd_hpb_configure(hba, sdev);
5182 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
5183 if (hba->quirks & UFSHCD_QUIRK_4KB_DMA_ALIGNMENT)
5184 blk_queue_update_dma_alignment(q, 4096 - 1);
5186 * Block runtime-pm until all consumers are added.
5187 * Refer ufshcd_setup_links().
5189 if (is_device_wlun(sdev))
5190 pm_runtime_get_noresume(&sdev->sdev_gendev);
5191 else if (ufshcd_is_rpm_autosuspend_allowed(hba))
5192 sdev->rpm_autosuspend = 1;
5194 * Do not print messages during runtime PM to avoid never-ending cycles
5195 * of messages written back to storage by user space causing runtime
5196 * resume, causing more messages and so on.
5198 sdev->silence_suspend = 1;
5200 ufshcd_crypto_register(hba, q);
5206 * ufshcd_slave_destroy - remove SCSI device configurations
5207 * @sdev: pointer to SCSI device
5209 static void ufshcd_slave_destroy(struct scsi_device *sdev)
5211 struct ufs_hba *hba;
5212 unsigned long flags;
5214 hba = shost_priv(sdev->host);
5216 ufshcd_hpb_destroy(hba, sdev);
5218 /* Drop the reference as it won't be needed anymore */
5219 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
5220 spin_lock_irqsave(hba->host->host_lock, flags);
5221 hba->ufs_device_wlun = NULL;
5222 spin_unlock_irqrestore(hba->host->host_lock, flags);
5223 } else if (hba->ufs_device_wlun) {
5224 struct device *supplier = NULL;
5226 /* Ensure UFS Device WLUN exists and does not disappear */
5227 spin_lock_irqsave(hba->host->host_lock, flags);
5228 if (hba->ufs_device_wlun) {
5229 supplier = &hba->ufs_device_wlun->sdev_gendev;
5230 get_device(supplier);
5232 spin_unlock_irqrestore(hba->host->host_lock, flags);
5236 * If a LUN fails to probe (e.g. absent BOOT WLUN), the
5237 * device will not have been registered but can still
5238 * have a device link holding a reference to the device.
5240 device_link_remove(&sdev->sdev_gendev, supplier);
5241 put_device(supplier);
5247 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
5248 * @lrbp: pointer to local reference block of completed command
5249 * @scsi_status: SCSI command status
5251 * Returns value base on SCSI command status
5254 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
5258 switch (scsi_status) {
5259 case SAM_STAT_CHECK_CONDITION:
5260 ufshcd_copy_sense_data(lrbp);
5263 result |= DID_OK << 16 | scsi_status;
5265 case SAM_STAT_TASK_SET_FULL:
5267 case SAM_STAT_TASK_ABORTED:
5268 ufshcd_copy_sense_data(lrbp);
5269 result |= scsi_status;
5272 result |= DID_ERROR << 16;
5274 } /* end of switch */
5280 * ufshcd_transfer_rsp_status - Get overall status of the response
5281 * @hba: per adapter instance
5282 * @lrbp: pointer to local reference block of completed command
5283 * @cqe: pointer to the completion queue entry
5285 * Returns result of the command to notify SCSI midlayer
5288 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp,
5289 struct cq_entry *cqe)
5295 scsi_set_resid(lrbp->cmd,
5296 be32_to_cpu(lrbp->ucd_rsp_ptr->sr.residual_transfer_count));
5298 /* overall command status of utrd */
5299 ocs = ufshcd_get_tr_ocs(lrbp, cqe);
5301 if (hba->quirks & UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR) {
5302 if (be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_1) &
5303 MASK_RSP_UPIU_RESULT)
5309 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
5310 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
5312 case UPIU_TRANSACTION_RESPONSE:
5314 * get the response UPIU result to extract
5315 * the SCSI command status
5317 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
5320 * get the result based on SCSI status response
5321 * to notify the SCSI midlayer of the command status
5323 scsi_status = result & MASK_SCSI_STATUS;
5324 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
5327 * Currently we are only supporting BKOPs exception
5328 * events hence we can ignore BKOPs exception event
5329 * during power management callbacks. BKOPs exception
5330 * event is not expected to be raised in runtime suspend
5331 * callback as it allows the urgent bkops.
5332 * During system suspend, we are anyway forcefully
5333 * disabling the bkops and if urgent bkops is needed
5334 * it will be enabled on system resume. Long term
5335 * solution could be to abort the system suspend if
5336 * UFS device needs urgent BKOPs.
5338 if (!hba->pm_op_in_progress &&
5339 !ufshcd_eh_in_progress(hba) &&
5340 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
5341 /* Flushed in suspend */
5342 schedule_work(&hba->eeh_work);
5344 if (scsi_status == SAM_STAT_GOOD)
5345 ufshpb_rsp_upiu(hba, lrbp);
5347 case UPIU_TRANSACTION_REJECT_UPIU:
5348 /* TODO: handle Reject UPIU Response */
5349 result = DID_ERROR << 16;
5351 "Reject UPIU not fully implemented\n");
5355 "Unexpected request response code = %x\n",
5357 result = DID_ERROR << 16;
5362 result |= DID_ABORT << 16;
5364 case OCS_INVALID_COMMAND_STATUS:
5365 result |= DID_REQUEUE << 16;
5367 case OCS_INVALID_CMD_TABLE_ATTR:
5368 case OCS_INVALID_PRDT_ATTR:
5369 case OCS_MISMATCH_DATA_BUF_SIZE:
5370 case OCS_MISMATCH_RESP_UPIU_SIZE:
5371 case OCS_PEER_COMM_FAILURE:
5372 case OCS_FATAL_ERROR:
5373 case OCS_DEVICE_FATAL_ERROR:
5374 case OCS_INVALID_CRYPTO_CONFIG:
5375 case OCS_GENERAL_CRYPTO_ERROR:
5377 result |= DID_ERROR << 16;
5379 "OCS error from controller = %x for tag %d\n",
5380 ocs, lrbp->task_tag);
5381 ufshcd_print_evt_hist(hba);
5382 ufshcd_print_host_state(hba);
5384 } /* end of switch */
5386 if ((host_byte(result) != DID_OK) &&
5387 (host_byte(result) != DID_REQUEUE) && !hba->silence_err_logs)
5388 ufshcd_print_tr(hba, lrbp->task_tag, true);
5392 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
5395 if (!ufshcd_is_auto_hibern8_supported(hba) ||
5396 !ufshcd_is_auto_hibern8_enabled(hba))
5399 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
5402 if (hba->active_uic_cmd &&
5403 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
5404 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
5411 * ufshcd_uic_cmd_compl - handle completion of uic command
5412 * @hba: per adapter instance
5413 * @intr_status: interrupt status generated by the controller
5416 * IRQ_HANDLED - If interrupt is valid
5417 * IRQ_NONE - If invalid interrupt
5419 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
5421 irqreturn_t retval = IRQ_NONE;
5423 spin_lock(hba->host->host_lock);
5424 if (ufshcd_is_auto_hibern8_error(hba, intr_status))
5425 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
5427 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
5428 hba->active_uic_cmd->argument2 |=
5429 ufshcd_get_uic_cmd_result(hba);
5430 hba->active_uic_cmd->argument3 =
5431 ufshcd_get_dme_attr_val(hba);
5432 if (!hba->uic_async_done)
5433 hba->active_uic_cmd->cmd_active = 0;
5434 complete(&hba->active_uic_cmd->done);
5435 retval = IRQ_HANDLED;
5438 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done) {
5439 hba->active_uic_cmd->cmd_active = 0;
5440 complete(hba->uic_async_done);
5441 retval = IRQ_HANDLED;
5444 if (retval == IRQ_HANDLED)
5445 ufshcd_add_uic_command_trace(hba, hba->active_uic_cmd,
5447 spin_unlock(hba->host->host_lock);
5451 /* Release the resources allocated for processing a SCSI command. */
5452 void ufshcd_release_scsi_cmd(struct ufs_hba *hba,
5453 struct ufshcd_lrb *lrbp)
5455 struct scsi_cmnd *cmd = lrbp->cmd;
5457 scsi_dma_unmap(cmd);
5458 lrbp->cmd = NULL; /* Mark the command as completed. */
5459 ufshcd_release(hba);
5460 ufshcd_clk_scaling_update_busy(hba);
5464 * ufshcd_compl_one_cqe - handle a completion queue entry
5465 * @hba: per adapter instance
5466 * @task_tag: the task tag of the request to be completed
5467 * @cqe: pointer to the completion queue entry
5469 void ufshcd_compl_one_cqe(struct ufs_hba *hba, int task_tag,
5470 struct cq_entry *cqe)
5472 struct ufshcd_lrb *lrbp;
5473 struct scsi_cmnd *cmd;
5475 lrbp = &hba->lrb[task_tag];
5476 lrbp->compl_time_stamp = ktime_get();
5479 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
5480 ufshcd_update_monitor(hba, lrbp);
5481 ufshcd_add_command_trace(hba, task_tag, UFS_CMD_COMP);
5482 cmd->result = ufshcd_transfer_rsp_status(hba, lrbp, cqe);
5483 ufshcd_release_scsi_cmd(hba, lrbp);
5484 /* Do not touch lrbp after scsi done */
5486 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
5487 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
5488 if (hba->dev_cmd.complete) {
5489 hba->dev_cmd.cqe = cqe;
5490 ufshcd_add_command_trace(hba, task_tag, UFS_DEV_COMP);
5491 complete(hba->dev_cmd.complete);
5492 ufshcd_clk_scaling_update_busy(hba);
5498 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
5499 * @hba: per adapter instance
5500 * @completed_reqs: bitmask that indicates which requests to complete
5502 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
5503 unsigned long completed_reqs)
5507 for_each_set_bit(tag, &completed_reqs, hba->nutrs)
5508 ufshcd_compl_one_cqe(hba, tag, NULL);
5511 /* Any value that is not an existing queue number is fine for this constant. */
5513 UFSHCD_POLL_FROM_INTERRUPT_CONTEXT = -1
5516 static void ufshcd_clear_polled(struct ufs_hba *hba,
5517 unsigned long *completed_reqs)
5521 for_each_set_bit(tag, completed_reqs, hba->nutrs) {
5522 struct scsi_cmnd *cmd = hba->lrb[tag].cmd;
5526 if (scsi_cmd_to_rq(cmd)->cmd_flags & REQ_POLLED)
5527 __clear_bit(tag, completed_reqs);
5532 * Returns > 0 if one or more commands have been completed or 0 if no
5533 * requests have been completed.
5535 static int ufshcd_poll(struct Scsi_Host *shost, unsigned int queue_num)
5537 struct ufs_hba *hba = shost_priv(shost);
5538 unsigned long completed_reqs, flags;
5540 struct ufs_hw_queue *hwq;
5542 if (is_mcq_enabled(hba)) {
5543 hwq = &hba->uhq[queue_num + UFSHCD_MCQ_IO_QUEUE_OFFSET];
5545 return ufshcd_mcq_poll_cqe_lock(hba, hwq);
5548 spin_lock_irqsave(&hba->outstanding_lock, flags);
5549 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5550 completed_reqs = ~tr_doorbell & hba->outstanding_reqs;
5551 WARN_ONCE(completed_reqs & ~hba->outstanding_reqs,
5552 "completed: %#lx; outstanding: %#lx\n", completed_reqs,
5553 hba->outstanding_reqs);
5554 if (queue_num == UFSHCD_POLL_FROM_INTERRUPT_CONTEXT) {
5555 /* Do not complete polled requests from interrupt context. */
5556 ufshcd_clear_polled(hba, &completed_reqs);
5558 hba->outstanding_reqs &= ~completed_reqs;
5559 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
5562 __ufshcd_transfer_req_compl(hba, completed_reqs);
5564 return completed_reqs != 0;
5568 * ufshcd_transfer_req_compl - handle SCSI and query command completion
5569 * @hba: per adapter instance
5572 * IRQ_HANDLED - If interrupt is valid
5573 * IRQ_NONE - If invalid interrupt
5575 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba)
5577 /* Resetting interrupt aggregation counters first and reading the
5578 * DOOR_BELL afterward allows us to handle all the completed requests.
5579 * In order to prevent other interrupts starvation the DB is read once
5580 * after reset. The down side of this solution is the possibility of
5581 * false interrupt if device completes another request after resetting
5582 * aggregation and before reading the DB.
5584 if (ufshcd_is_intr_aggr_allowed(hba) &&
5585 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
5586 ufshcd_reset_intr_aggr(hba);
5588 if (ufs_fail_completion())
5592 * Ignore the ufshcd_poll() return value and return IRQ_HANDLED since we
5593 * do not want polling to trigger spurious interrupt complaints.
5595 ufshcd_poll(hba->host, UFSHCD_POLL_FROM_INTERRUPT_CONTEXT);
5600 int __ufshcd_write_ee_control(struct ufs_hba *hba, u32 ee_ctrl_mask)
5602 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5603 QUERY_ATTR_IDN_EE_CONTROL, 0, 0,
5607 int ufshcd_write_ee_control(struct ufs_hba *hba)
5611 mutex_lock(&hba->ee_ctrl_mutex);
5612 err = __ufshcd_write_ee_control(hba, hba->ee_ctrl_mask);
5613 mutex_unlock(&hba->ee_ctrl_mutex);
5615 dev_err(hba->dev, "%s: failed to write ee control %d\n",
5620 int ufshcd_update_ee_control(struct ufs_hba *hba, u16 *mask,
5621 const u16 *other_mask, u16 set, u16 clr)
5623 u16 new_mask, ee_ctrl_mask;
5626 mutex_lock(&hba->ee_ctrl_mutex);
5627 new_mask = (*mask & ~clr) | set;
5628 ee_ctrl_mask = new_mask | *other_mask;
5629 if (ee_ctrl_mask != hba->ee_ctrl_mask)
5630 err = __ufshcd_write_ee_control(hba, ee_ctrl_mask);
5631 /* Still need to update 'mask' even if 'ee_ctrl_mask' was unchanged */
5633 hba->ee_ctrl_mask = ee_ctrl_mask;
5636 mutex_unlock(&hba->ee_ctrl_mutex);
5641 * ufshcd_disable_ee - disable exception event
5642 * @hba: per-adapter instance
5643 * @mask: exception event to disable
5645 * Disables exception event in the device so that the EVENT_ALERT
5648 * Returns zero on success, non-zero error value on failure.
5650 static inline int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
5652 return ufshcd_update_ee_drv_mask(hba, 0, mask);
5656 * ufshcd_enable_ee - enable exception event
5657 * @hba: per-adapter instance
5658 * @mask: exception event to enable
5660 * Enable corresponding exception event in the device to allow
5661 * device to alert host in critical scenarios.
5663 * Returns zero on success, non-zero error value on failure.
5665 static inline int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
5667 return ufshcd_update_ee_drv_mask(hba, mask, 0);
5671 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
5672 * @hba: per-adapter instance
5674 * Allow device to manage background operations on its own. Enabling
5675 * this might lead to inconsistent latencies during normal data transfers
5676 * as the device is allowed to manage its own way of handling background
5679 * Returns zero on success, non-zero on failure.
5681 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
5685 if (hba->auto_bkops_enabled)
5688 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5689 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5691 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
5696 hba->auto_bkops_enabled = true;
5697 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
5699 /* No need of URGENT_BKOPS exception from the device */
5700 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5702 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5709 * ufshcd_disable_auto_bkops - block device in doing background operations
5710 * @hba: per-adapter instance
5712 * Disabling background operations improves command response latency but
5713 * has drawback of device moving into critical state where the device is
5714 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5715 * host is idle so that BKOPS are managed effectively without any negative
5718 * Returns zero on success, non-zero on failure.
5720 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5724 if (!hba->auto_bkops_enabled)
5728 * If host assisted BKOPs is to be enabled, make sure
5729 * urgent bkops exception is allowed.
5731 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5733 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5738 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5739 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5741 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5743 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5747 hba->auto_bkops_enabled = false;
5748 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
5749 hba->is_urgent_bkops_lvl_checked = false;
5755 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5756 * @hba: per adapter instance
5758 * After a device reset the device may toggle the BKOPS_EN flag
5759 * to default value. The s/w tracking variables should be updated
5760 * as well. This function would change the auto-bkops state based on
5761 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5763 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5765 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5766 hba->auto_bkops_enabled = false;
5767 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5768 ufshcd_enable_auto_bkops(hba);
5770 hba->auto_bkops_enabled = true;
5771 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5772 ufshcd_disable_auto_bkops(hba);
5774 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
5775 hba->is_urgent_bkops_lvl_checked = false;
5778 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5780 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5781 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5785 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5786 * @hba: per-adapter instance
5787 * @status: bkops_status value
5789 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5790 * flag in the device to permit background operations if the device
5791 * bkops_status is greater than or equal to "status" argument passed to
5792 * this function, disable otherwise.
5794 * Returns 0 for success, non-zero in case of failure.
5796 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5797 * to know whether auto bkops is enabled or disabled after this function
5798 * returns control to it.
5800 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5801 enum bkops_status status)
5804 u32 curr_status = 0;
5806 err = ufshcd_get_bkops_status(hba, &curr_status);
5808 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5811 } else if (curr_status > BKOPS_STATUS_MAX) {
5812 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5813 __func__, curr_status);
5818 if (curr_status >= status)
5819 err = ufshcd_enable_auto_bkops(hba);
5821 err = ufshcd_disable_auto_bkops(hba);
5827 * ufshcd_urgent_bkops - handle urgent bkops exception event
5828 * @hba: per-adapter instance
5830 * Enable fBackgroundOpsEn flag in the device to permit background
5833 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5834 * and negative error value for any other failure.
5836 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5838 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5841 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5843 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5844 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5847 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5850 u32 curr_status = 0;
5852 if (hba->is_urgent_bkops_lvl_checked)
5853 goto enable_auto_bkops;
5855 err = ufshcd_get_bkops_status(hba, &curr_status);
5857 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5863 * We are seeing that some devices are raising the urgent bkops
5864 * exception events even when BKOPS status doesn't indicate performace
5865 * impacted or critical. Handle these device by determining their urgent
5866 * bkops status at runtime.
5868 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5869 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5870 __func__, curr_status);
5871 /* update the current status as the urgent bkops level */
5872 hba->urgent_bkops_lvl = curr_status;
5873 hba->is_urgent_bkops_lvl_checked = true;
5877 err = ufshcd_enable_auto_bkops(hba);
5880 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5884 static void ufshcd_temp_exception_event_handler(struct ufs_hba *hba, u16 status)
5888 if (ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5889 QUERY_ATTR_IDN_CASE_ROUGH_TEMP, 0, 0, &value))
5892 dev_info(hba->dev, "exception Tcase %d\n", value - 80);
5894 ufs_hwmon_notify_event(hba, status & MASK_EE_URGENT_TEMP);
5897 * A placeholder for the platform vendors to add whatever additional
5902 static int __ufshcd_wb_toggle(struct ufs_hba *hba, bool set, enum flag_idn idn)
5905 enum query_opcode opcode = set ? UPIU_QUERY_OPCODE_SET_FLAG :
5906 UPIU_QUERY_OPCODE_CLEAR_FLAG;
5908 index = ufshcd_wb_get_query_index(hba);
5909 return ufshcd_query_flag_retry(hba, opcode, idn, index, NULL);
5912 int ufshcd_wb_toggle(struct ufs_hba *hba, bool enable)
5916 if (!ufshcd_is_wb_allowed(hba) ||
5917 hba->dev_info.wb_enabled == enable)
5920 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_EN);
5922 dev_err(hba->dev, "%s: Write Booster %s failed %d\n",
5923 __func__, enable ? "enabling" : "disabling", ret);
5927 hba->dev_info.wb_enabled = enable;
5928 dev_dbg(hba->dev, "%s: Write Booster %s\n",
5929 __func__, enable ? "enabled" : "disabled");
5934 static void ufshcd_wb_toggle_buf_flush_during_h8(struct ufs_hba *hba,
5939 ret = __ufshcd_wb_toggle(hba, enable,
5940 QUERY_FLAG_IDN_WB_BUFF_FLUSH_DURING_HIBERN8);
5942 dev_err(hba->dev, "%s: WB-Buf Flush during H8 %s failed %d\n",
5943 __func__, enable ? "enabling" : "disabling", ret);
5946 dev_dbg(hba->dev, "%s: WB-Buf Flush during H8 %s\n",
5947 __func__, enable ? "enabled" : "disabled");
5950 int ufshcd_wb_toggle_buf_flush(struct ufs_hba *hba, bool enable)
5954 if (!ufshcd_is_wb_allowed(hba) ||
5955 hba->dev_info.wb_buf_flush_enabled == enable)
5958 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN);
5960 dev_err(hba->dev, "%s: WB-Buf Flush %s failed %d\n",
5961 __func__, enable ? "enabling" : "disabling", ret);
5965 hba->dev_info.wb_buf_flush_enabled = enable;
5966 dev_dbg(hba->dev, "%s: WB-Buf Flush %s\n",
5967 __func__, enable ? "enabled" : "disabled");
5972 static bool ufshcd_wb_presrv_usrspc_keep_vcc_on(struct ufs_hba *hba,
5979 index = ufshcd_wb_get_query_index(hba);
5980 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5981 QUERY_ATTR_IDN_CURR_WB_BUFF_SIZE,
5982 index, 0, &cur_buf);
5984 dev_err(hba->dev, "%s: dCurWriteBoosterBufferSize read failed %d\n",
5990 dev_info(hba->dev, "dCurWBBuf: %d WB disabled until free-space is available\n",
5994 /* Let it continue to flush when available buffer exceeds threshold */
5995 return avail_buf < hba->vps->wb_flush_threshold;
5998 static void ufshcd_wb_force_disable(struct ufs_hba *hba)
6000 if (ufshcd_is_wb_buf_flush_allowed(hba))
6001 ufshcd_wb_toggle_buf_flush(hba, false);
6003 ufshcd_wb_toggle_buf_flush_during_h8(hba, false);
6004 ufshcd_wb_toggle(hba, false);
6005 hba->caps &= ~UFSHCD_CAP_WB_EN;
6007 dev_info(hba->dev, "%s: WB force disabled\n", __func__);
6010 static bool ufshcd_is_wb_buf_lifetime_available(struct ufs_hba *hba)
6016 index = ufshcd_wb_get_query_index(hba);
6017 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
6018 QUERY_ATTR_IDN_WB_BUFF_LIFE_TIME_EST,
6019 index, 0, &lifetime);
6022 "%s: bWriteBoosterBufferLifeTimeEst read failed %d\n",
6027 if (lifetime == UFS_WB_EXCEED_LIFETIME) {
6028 dev_err(hba->dev, "%s: WB buf lifetime is exhausted 0x%02X\n",
6029 __func__, lifetime);
6033 dev_dbg(hba->dev, "%s: WB buf lifetime is 0x%02X\n",
6034 __func__, lifetime);
6039 static bool ufshcd_wb_need_flush(struct ufs_hba *hba)
6045 if (!ufshcd_is_wb_allowed(hba))
6048 if (!ufshcd_is_wb_buf_lifetime_available(hba)) {
6049 ufshcd_wb_force_disable(hba);
6054 * The ufs device needs the vcc to be ON to flush.
6055 * With user-space reduction enabled, it's enough to enable flush
6056 * by checking only the available buffer. The threshold
6057 * defined here is > 90% full.
6058 * With user-space preserved enabled, the current-buffer
6059 * should be checked too because the wb buffer size can reduce
6060 * when disk tends to be full. This info is provided by current
6061 * buffer (dCurrentWriteBoosterBufferSize). There's no point in
6062 * keeping vcc on when current buffer is empty.
6064 index = ufshcd_wb_get_query_index(hba);
6065 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
6066 QUERY_ATTR_IDN_AVAIL_WB_BUFF_SIZE,
6067 index, 0, &avail_buf);
6069 dev_warn(hba->dev, "%s: dAvailableWriteBoosterBufferSize read failed %d\n",
6074 if (!hba->dev_info.b_presrv_uspc_en)
6075 return avail_buf <= UFS_WB_BUF_REMAIN_PERCENT(10);
6077 return ufshcd_wb_presrv_usrspc_keep_vcc_on(hba, avail_buf);
6080 static void ufshcd_rpm_dev_flush_recheck_work(struct work_struct *work)
6082 struct ufs_hba *hba = container_of(to_delayed_work(work),
6084 rpm_dev_flush_recheck_work);
6086 * To prevent unnecessary VCC power drain after device finishes
6087 * WriteBooster buffer flush or Auto BKOPs, force runtime resume
6088 * after a certain delay to recheck the threshold by next runtime
6091 ufshcd_rpm_get_sync(hba);
6092 ufshcd_rpm_put_sync(hba);
6096 * ufshcd_exception_event_handler - handle exceptions raised by device
6097 * @work: pointer to work data
6099 * Read bExceptionEventStatus attribute from the device and handle the
6100 * exception event accordingly.
6102 static void ufshcd_exception_event_handler(struct work_struct *work)
6104 struct ufs_hba *hba;
6107 hba = container_of(work, struct ufs_hba, eeh_work);
6109 ufshcd_scsi_block_requests(hba);
6110 err = ufshcd_get_ee_status(hba, &status);
6112 dev_err(hba->dev, "%s: failed to get exception status %d\n",
6117 trace_ufshcd_exception_event(dev_name(hba->dev), status);
6119 if (status & hba->ee_drv_mask & MASK_EE_URGENT_BKOPS)
6120 ufshcd_bkops_exception_event_handler(hba);
6122 if (status & hba->ee_drv_mask & MASK_EE_URGENT_TEMP)
6123 ufshcd_temp_exception_event_handler(hba, status);
6125 ufs_debugfs_exception_event(hba, status);
6127 ufshcd_scsi_unblock_requests(hba);
6130 /* Complete requests that have door-bell cleared */
6131 static void ufshcd_complete_requests(struct ufs_hba *hba)
6133 ufshcd_transfer_req_compl(hba);
6134 ufshcd_tmc_handler(hba);
6138 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
6139 * to recover from the DL NAC errors or not.
6140 * @hba: per-adapter instance
6142 * Returns true if error handling is required, false otherwise
6144 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
6146 unsigned long flags;
6147 bool err_handling = true;
6149 spin_lock_irqsave(hba->host->host_lock, flags);
6151 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
6152 * device fatal error and/or DL NAC & REPLAY timeout errors.
6154 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
6157 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
6158 ((hba->saved_err & UIC_ERROR) &&
6159 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
6162 if ((hba->saved_err & UIC_ERROR) &&
6163 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
6166 * wait for 50ms to see if we can get any other errors or not.
6168 spin_unlock_irqrestore(hba->host->host_lock, flags);
6170 spin_lock_irqsave(hba->host->host_lock, flags);
6173 * now check if we have got any other severe errors other than
6176 if ((hba->saved_err & INT_FATAL_ERRORS) ||
6177 ((hba->saved_err & UIC_ERROR) &&
6178 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
6182 * As DL NAC is the only error received so far, send out NOP
6183 * command to confirm if link is still active or not.
6184 * - If we don't get any response then do error recovery.
6185 * - If we get response then clear the DL NAC error bit.
6188 spin_unlock_irqrestore(hba->host->host_lock, flags);
6189 err = ufshcd_verify_dev_init(hba);
6190 spin_lock_irqsave(hba->host->host_lock, flags);
6195 /* Link seems to be alive hence ignore the DL NAC errors */
6196 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
6197 hba->saved_err &= ~UIC_ERROR;
6198 /* clear NAC error */
6199 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6200 if (!hba->saved_uic_err)
6201 err_handling = false;
6204 spin_unlock_irqrestore(hba->host->host_lock, flags);
6205 return err_handling;
6208 /* host lock must be held before calling this func */
6209 static inline bool ufshcd_is_saved_err_fatal(struct ufs_hba *hba)
6211 return (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR) ||
6212 (hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK));
6215 void ufshcd_schedule_eh_work(struct ufs_hba *hba)
6217 lockdep_assert_held(hba->host->host_lock);
6219 /* handle fatal errors only when link is not in error state */
6220 if (hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6221 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6222 ufshcd_is_saved_err_fatal(hba))
6223 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_FATAL;
6225 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_NON_FATAL;
6226 queue_work(hba->eh_wq, &hba->eh_work);
6230 static void ufshcd_force_error_recovery(struct ufs_hba *hba)
6232 spin_lock_irq(hba->host->host_lock);
6233 hba->force_reset = true;
6234 ufshcd_schedule_eh_work(hba);
6235 spin_unlock_irq(hba->host->host_lock);
6238 static void ufshcd_clk_scaling_allow(struct ufs_hba *hba, bool allow)
6240 mutex_lock(&hba->wb_mutex);
6241 down_write(&hba->clk_scaling_lock);
6242 hba->clk_scaling.is_allowed = allow;
6243 up_write(&hba->clk_scaling_lock);
6244 mutex_unlock(&hba->wb_mutex);
6247 static void ufshcd_clk_scaling_suspend(struct ufs_hba *hba, bool suspend)
6250 if (hba->clk_scaling.is_enabled)
6251 ufshcd_suspend_clkscaling(hba);
6252 ufshcd_clk_scaling_allow(hba, false);
6254 ufshcd_clk_scaling_allow(hba, true);
6255 if (hba->clk_scaling.is_enabled)
6256 ufshcd_resume_clkscaling(hba);
6260 static void ufshcd_err_handling_prepare(struct ufs_hba *hba)
6262 ufshcd_rpm_get_sync(hba);
6263 if (pm_runtime_status_suspended(&hba->ufs_device_wlun->sdev_gendev) ||
6264 hba->is_sys_suspended) {
6265 enum ufs_pm_op pm_op;
6268 * Don't assume anything of resume, if
6269 * resume fails, irq and clocks can be OFF, and powers
6270 * can be OFF or in LPM.
6272 ufshcd_setup_hba_vreg(hba, true);
6273 ufshcd_enable_irq(hba);
6274 ufshcd_setup_vreg(hba, true);
6275 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
6276 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
6277 ufshcd_hold(hba, false);
6278 if (!ufshcd_is_clkgating_allowed(hba))
6279 ufshcd_setup_clocks(hba, true);
6280 ufshcd_release(hba);
6281 pm_op = hba->is_sys_suspended ? UFS_SYSTEM_PM : UFS_RUNTIME_PM;
6282 ufshcd_vops_resume(hba, pm_op);
6284 ufshcd_hold(hba, false);
6285 if (ufshcd_is_clkscaling_supported(hba) &&
6286 hba->clk_scaling.is_enabled)
6287 ufshcd_suspend_clkscaling(hba);
6288 ufshcd_clk_scaling_allow(hba, false);
6290 ufshcd_scsi_block_requests(hba);
6291 /* Drain ufshcd_queuecommand() */
6293 cancel_work_sync(&hba->eeh_work);
6296 static void ufshcd_err_handling_unprepare(struct ufs_hba *hba)
6298 ufshcd_scsi_unblock_requests(hba);
6299 ufshcd_release(hba);
6300 if (ufshcd_is_clkscaling_supported(hba))
6301 ufshcd_clk_scaling_suspend(hba, false);
6302 ufshcd_rpm_put(hba);
6305 static inline bool ufshcd_err_handling_should_stop(struct ufs_hba *hba)
6307 return (!hba->is_powered || hba->shutting_down ||
6308 !hba->ufs_device_wlun ||
6309 hba->ufshcd_state == UFSHCD_STATE_ERROR ||
6310 (!(hba->saved_err || hba->saved_uic_err || hba->force_reset ||
6311 ufshcd_is_link_broken(hba))));
6315 static void ufshcd_recover_pm_error(struct ufs_hba *hba)
6317 struct Scsi_Host *shost = hba->host;
6318 struct scsi_device *sdev;
6319 struct request_queue *q;
6322 hba->is_sys_suspended = false;
6324 * Set RPM status of wlun device to RPM_ACTIVE,
6325 * this also clears its runtime error.
6327 ret = pm_runtime_set_active(&hba->ufs_device_wlun->sdev_gendev);
6329 /* hba device might have a runtime error otherwise */
6331 ret = pm_runtime_set_active(hba->dev);
6333 * If wlun device had runtime error, we also need to resume those
6334 * consumer scsi devices in case any of them has failed to be
6335 * resumed due to supplier runtime resume failure. This is to unblock
6336 * blk_queue_enter in case there are bios waiting inside it.
6339 shost_for_each_device(sdev, shost) {
6340 q = sdev->request_queue;
6341 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
6342 q->rpm_status == RPM_SUSPENDING))
6343 pm_request_resume(q->dev);
6348 static inline void ufshcd_recover_pm_error(struct ufs_hba *hba)
6353 static bool ufshcd_is_pwr_mode_restore_needed(struct ufs_hba *hba)
6355 struct ufs_pa_layer_attr *pwr_info = &hba->pwr_info;
6358 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode);
6360 if (pwr_info->pwr_rx != ((mode >> PWRMODE_RX_OFFSET) & PWRMODE_MASK))
6363 if (pwr_info->pwr_tx != (mode & PWRMODE_MASK))
6369 static bool ufshcd_abort_all(struct ufs_hba *hba)
6371 bool needs_reset = false;
6374 /* Clear pending transfer requests */
6375 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
6376 ret = ufshcd_try_to_abort_task(hba, tag);
6377 dev_err(hba->dev, "Aborting tag %d / CDB %#02x %s\n", tag,
6378 hba->lrb[tag].cmd ? hba->lrb[tag].cmd->cmnd[0] : -1,
6379 ret ? "failed" : "succeeded");
6386 /* Clear pending task management requests */
6387 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
6388 if (ufshcd_clear_tm_cmd(hba, tag)) {
6395 /* Complete the requests that are cleared by s/w */
6396 ufshcd_complete_requests(hba);
6402 * ufshcd_err_handler - handle UFS errors that require s/w attention
6403 * @work: pointer to work structure
6405 static void ufshcd_err_handler(struct work_struct *work)
6407 int retries = MAX_ERR_HANDLER_RETRIES;
6408 struct ufs_hba *hba;
6409 unsigned long flags;
6414 hba = container_of(work, struct ufs_hba, eh_work);
6417 "%s started; HBA state %s; powered %d; shutting down %d; saved_err = %d; saved_uic_err = %d; force_reset = %d%s\n",
6418 __func__, ufshcd_state_name[hba->ufshcd_state],
6419 hba->is_powered, hba->shutting_down, hba->saved_err,
6420 hba->saved_uic_err, hba->force_reset,
6421 ufshcd_is_link_broken(hba) ? "; link is broken" : "");
6423 down(&hba->host_sem);
6424 spin_lock_irqsave(hba->host->host_lock, flags);
6425 if (ufshcd_err_handling_should_stop(hba)) {
6426 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6427 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6428 spin_unlock_irqrestore(hba->host->host_lock, flags);
6432 ufshcd_set_eh_in_progress(hba);
6433 spin_unlock_irqrestore(hba->host->host_lock, flags);
6434 ufshcd_err_handling_prepare(hba);
6435 /* Complete requests that have door-bell cleared by h/w */
6436 ufshcd_complete_requests(hba);
6437 spin_lock_irqsave(hba->host->host_lock, flags);
6439 needs_restore = false;
6440 needs_reset = false;
6442 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6443 hba->ufshcd_state = UFSHCD_STATE_RESET;
6445 * A full reset and restore might have happened after preparation
6446 * is finished, double check whether we should stop.
6448 if (ufshcd_err_handling_should_stop(hba))
6449 goto skip_err_handling;
6451 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6454 spin_unlock_irqrestore(hba->host->host_lock, flags);
6455 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
6456 ret = ufshcd_quirk_dl_nac_errors(hba);
6457 spin_lock_irqsave(hba->host->host_lock, flags);
6458 if (!ret && ufshcd_err_handling_should_stop(hba))
6459 goto skip_err_handling;
6462 if ((hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6463 (hba->saved_uic_err &&
6464 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6465 bool pr_prdt = !!(hba->saved_err & SYSTEM_BUS_FATAL_ERROR);
6467 spin_unlock_irqrestore(hba->host->host_lock, flags);
6468 ufshcd_print_host_state(hba);
6469 ufshcd_print_pwr_info(hba);
6470 ufshcd_print_evt_hist(hba);
6471 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
6472 ufshcd_print_trs_all(hba, pr_prdt);
6473 spin_lock_irqsave(hba->host->host_lock, flags);
6477 * if host reset is required then skip clearing the pending
6478 * transfers forcefully because they will get cleared during
6479 * host reset and restore
6481 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6482 ufshcd_is_saved_err_fatal(hba) ||
6483 ((hba->saved_err & UIC_ERROR) &&
6484 (hba->saved_uic_err & (UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
6485 UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))) {
6491 * If LINERESET was caught, UFS might have been put to PWM mode,
6492 * check if power mode restore is needed.
6494 if (hba->saved_uic_err & UFSHCD_UIC_PA_GENERIC_ERROR) {
6495 hba->saved_uic_err &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6496 if (!hba->saved_uic_err)
6497 hba->saved_err &= ~UIC_ERROR;
6498 spin_unlock_irqrestore(hba->host->host_lock, flags);
6499 if (ufshcd_is_pwr_mode_restore_needed(hba))
6500 needs_restore = true;
6501 spin_lock_irqsave(hba->host->host_lock, flags);
6502 if (!hba->saved_err && !needs_restore)
6503 goto skip_err_handling;
6506 hba->silence_err_logs = true;
6507 /* release lock as clear command might sleep */
6508 spin_unlock_irqrestore(hba->host->host_lock, flags);
6510 needs_reset = ufshcd_abort_all(hba);
6512 spin_lock_irqsave(hba->host->host_lock, flags);
6513 hba->silence_err_logs = false;
6518 * After all reqs and tasks are cleared from doorbell,
6519 * now it is safe to retore power mode.
6521 if (needs_restore) {
6522 spin_unlock_irqrestore(hba->host->host_lock, flags);
6524 * Hold the scaling lock just in case dev cmds
6525 * are sent via bsg and/or sysfs.
6527 down_write(&hba->clk_scaling_lock);
6528 hba->force_pmc = true;
6529 pmc_err = ufshcd_config_pwr_mode(hba, &(hba->pwr_info));
6532 dev_err(hba->dev, "%s: Failed to restore power mode, err = %d\n",
6535 hba->force_pmc = false;
6536 ufshcd_print_pwr_info(hba);
6537 up_write(&hba->clk_scaling_lock);
6538 spin_lock_irqsave(hba->host->host_lock, flags);
6542 /* Fatal errors need reset */
6546 hba->force_reset = false;
6547 spin_unlock_irqrestore(hba->host->host_lock, flags);
6548 err = ufshcd_reset_and_restore(hba);
6550 dev_err(hba->dev, "%s: reset and restore failed with err %d\n",
6553 ufshcd_recover_pm_error(hba);
6554 spin_lock_irqsave(hba->host->host_lock, flags);
6559 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
6560 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6561 if (hba->saved_err || hba->saved_uic_err)
6562 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
6563 __func__, hba->saved_err, hba->saved_uic_err);
6565 /* Exit in an operational state or dead */
6566 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
6567 hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6570 hba->ufshcd_state = UFSHCD_STATE_ERROR;
6572 ufshcd_clear_eh_in_progress(hba);
6573 spin_unlock_irqrestore(hba->host->host_lock, flags);
6574 ufshcd_err_handling_unprepare(hba);
6577 dev_info(hba->dev, "%s finished; HBA state %s\n", __func__,
6578 ufshcd_state_name[hba->ufshcd_state]);
6582 * ufshcd_update_uic_error - check and set fatal UIC error flags.
6583 * @hba: per-adapter instance
6586 * IRQ_HANDLED - If interrupt is valid
6587 * IRQ_NONE - If invalid interrupt
6589 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
6592 irqreturn_t retval = IRQ_NONE;
6594 /* PHY layer error */
6595 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
6596 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
6597 (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) {
6598 ufshcd_update_evt_hist(hba, UFS_EVT_PA_ERR, reg);
6600 * To know whether this error is fatal or not, DB timeout
6601 * must be checked but this error is handled separately.
6603 if (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)
6604 dev_dbg(hba->dev, "%s: UIC Lane error reported\n",
6607 /* Got a LINERESET indication. */
6608 if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) {
6609 struct uic_command *cmd = NULL;
6611 hba->uic_error |= UFSHCD_UIC_PA_GENERIC_ERROR;
6612 if (hba->uic_async_done && hba->active_uic_cmd)
6613 cmd = hba->active_uic_cmd;
6615 * Ignore the LINERESET during power mode change
6616 * operation via DME_SET command.
6618 if (cmd && (cmd->command == UIC_CMD_DME_SET))
6619 hba->uic_error &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6621 retval |= IRQ_HANDLED;
6624 /* PA_INIT_ERROR is fatal and needs UIC reset */
6625 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
6626 if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
6627 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
6628 ufshcd_update_evt_hist(hba, UFS_EVT_DL_ERR, reg);
6630 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
6631 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
6632 else if (hba->dev_quirks &
6633 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6634 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
6636 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6637 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
6638 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
6640 retval |= IRQ_HANDLED;
6643 /* UIC NL/TL/DME errors needs software retry */
6644 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
6645 if ((reg & UIC_NETWORK_LAYER_ERROR) &&
6646 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
6647 ufshcd_update_evt_hist(hba, UFS_EVT_NL_ERR, reg);
6648 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
6649 retval |= IRQ_HANDLED;
6652 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
6653 if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
6654 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
6655 ufshcd_update_evt_hist(hba, UFS_EVT_TL_ERR, reg);
6656 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
6657 retval |= IRQ_HANDLED;
6660 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
6661 if ((reg & UIC_DME_ERROR) &&
6662 (reg & UIC_DME_ERROR_CODE_MASK)) {
6663 ufshcd_update_evt_hist(hba, UFS_EVT_DME_ERR, reg);
6664 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
6665 retval |= IRQ_HANDLED;
6668 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
6669 __func__, hba->uic_error);
6674 * ufshcd_check_errors - Check for errors that need s/w attention
6675 * @hba: per-adapter instance
6676 * @intr_status: interrupt status generated by the controller
6679 * IRQ_HANDLED - If interrupt is valid
6680 * IRQ_NONE - If invalid interrupt
6682 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba, u32 intr_status)
6684 bool queue_eh_work = false;
6685 irqreturn_t retval = IRQ_NONE;
6687 spin_lock(hba->host->host_lock);
6688 hba->errors |= UFSHCD_ERROR_MASK & intr_status;
6690 if (hba->errors & INT_FATAL_ERRORS) {
6691 ufshcd_update_evt_hist(hba, UFS_EVT_FATAL_ERR,
6693 queue_eh_work = true;
6696 if (hba->errors & UIC_ERROR) {
6698 retval = ufshcd_update_uic_error(hba);
6700 queue_eh_work = true;
6703 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
6705 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
6706 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
6708 hba->errors, ufshcd_get_upmcrs(hba));
6709 ufshcd_update_evt_hist(hba, UFS_EVT_AUTO_HIBERN8_ERR,
6711 ufshcd_set_link_broken(hba);
6712 queue_eh_work = true;
6715 if (queue_eh_work) {
6717 * update the transfer error masks to sticky bits, let's do this
6718 * irrespective of current ufshcd_state.
6720 hba->saved_err |= hba->errors;
6721 hba->saved_uic_err |= hba->uic_error;
6723 /* dump controller state before resetting */
6724 if ((hba->saved_err &
6725 (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6726 (hba->saved_uic_err &&
6727 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6728 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
6729 __func__, hba->saved_err,
6730 hba->saved_uic_err);
6731 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE,
6733 ufshcd_print_pwr_info(hba);
6735 ufshcd_schedule_eh_work(hba);
6736 retval |= IRQ_HANDLED;
6739 * if (!queue_eh_work) -
6740 * Other errors are either non-fatal where host recovers
6741 * itself without s/w intervention or errors that will be
6742 * handled by the SCSI core layer.
6746 spin_unlock(hba->host->host_lock);
6751 * ufshcd_tmc_handler - handle task management function completion
6752 * @hba: per adapter instance
6755 * IRQ_HANDLED - If interrupt is valid
6756 * IRQ_NONE - If invalid interrupt
6758 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
6760 unsigned long flags, pending, issued;
6761 irqreturn_t ret = IRQ_NONE;
6764 spin_lock_irqsave(hba->host->host_lock, flags);
6765 pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
6766 issued = hba->outstanding_tasks & ~pending;
6767 for_each_set_bit(tag, &issued, hba->nutmrs) {
6768 struct request *req = hba->tmf_rqs[tag];
6769 struct completion *c = req->end_io_data;
6774 spin_unlock_irqrestore(hba->host->host_lock, flags);
6780 * ufshcd_handle_mcq_cq_events - handle MCQ completion queue events
6781 * @hba: per adapter instance
6783 * Returns IRQ_HANDLED if interrupt is handled
6785 static irqreturn_t ufshcd_handle_mcq_cq_events(struct ufs_hba *hba)
6787 struct ufs_hw_queue *hwq;
6788 unsigned long outstanding_cqs;
6789 unsigned int nr_queues;
6793 ret = ufshcd_vops_get_outstanding_cqs(hba, &outstanding_cqs);
6795 outstanding_cqs = (1U << hba->nr_hw_queues) - 1;
6797 /* Exclude the poll queues */
6798 nr_queues = hba->nr_hw_queues - hba->nr_queues[HCTX_TYPE_POLL];
6799 for_each_set_bit(i, &outstanding_cqs, nr_queues) {
6802 events = ufshcd_mcq_read_cqis(hba, i);
6804 ufshcd_mcq_write_cqis(hba, events, i);
6806 if (events & UFSHCD_MCQ_CQIS_TAIL_ENT_PUSH_STS)
6807 ufshcd_mcq_poll_cqe_nolock(hba, hwq);
6814 * ufshcd_sl_intr - Interrupt service routine
6815 * @hba: per adapter instance
6816 * @intr_status: contains interrupts generated by the controller
6819 * IRQ_HANDLED - If interrupt is valid
6820 * IRQ_NONE - If invalid interrupt
6822 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
6824 irqreturn_t retval = IRQ_NONE;
6826 if (intr_status & UFSHCD_UIC_MASK)
6827 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
6829 if (intr_status & UFSHCD_ERROR_MASK || hba->errors)
6830 retval |= ufshcd_check_errors(hba, intr_status);
6832 if (intr_status & UTP_TASK_REQ_COMPL)
6833 retval |= ufshcd_tmc_handler(hba);
6835 if (intr_status & UTP_TRANSFER_REQ_COMPL)
6836 retval |= ufshcd_transfer_req_compl(hba);
6838 if (intr_status & MCQ_CQ_EVENT_STATUS)
6839 retval |= ufshcd_handle_mcq_cq_events(hba);
6845 * ufshcd_intr - Main interrupt service routine
6847 * @__hba: pointer to adapter instance
6850 * IRQ_HANDLED - If interrupt is valid
6851 * IRQ_NONE - If invalid interrupt
6853 static irqreturn_t ufshcd_intr(int irq, void *__hba)
6855 u32 intr_status, enabled_intr_status = 0;
6856 irqreturn_t retval = IRQ_NONE;
6857 struct ufs_hba *hba = __hba;
6858 int retries = hba->nutrs;
6860 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6861 hba->ufs_stats.last_intr_status = intr_status;
6862 hba->ufs_stats.last_intr_ts = local_clock();
6865 * There could be max of hba->nutrs reqs in flight and in worst case
6866 * if the reqs get finished 1 by 1 after the interrupt status is
6867 * read, make sure we handle them by checking the interrupt status
6868 * again in a loop until we process all of the reqs before returning.
6870 while (intr_status && retries--) {
6871 enabled_intr_status =
6872 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
6873 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
6874 if (enabled_intr_status)
6875 retval |= ufshcd_sl_intr(hba, enabled_intr_status);
6877 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6880 if (enabled_intr_status && retval == IRQ_NONE &&
6881 (!(enabled_intr_status & UTP_TRANSFER_REQ_COMPL) ||
6882 hba->outstanding_reqs) && !ufshcd_eh_in_progress(hba)) {
6883 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x (0x%08x, 0x%08x)\n",
6886 hba->ufs_stats.last_intr_status,
6887 enabled_intr_status);
6888 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
6894 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
6897 u32 mask = 1 << tag;
6898 unsigned long flags;
6900 if (!test_bit(tag, &hba->outstanding_tasks))
6903 spin_lock_irqsave(hba->host->host_lock, flags);
6904 ufshcd_utmrl_clear(hba, tag);
6905 spin_unlock_irqrestore(hba->host->host_lock, flags);
6907 /* poll for max. 1 sec to clear door bell register by h/w */
6908 err = ufshcd_wait_for_register(hba,
6909 REG_UTP_TASK_REQ_DOOR_BELL,
6910 mask, 0, 1000, 1000);
6912 dev_err(hba->dev, "Clearing task management function with tag %d %s\n",
6913 tag, err ? "succeeded" : "failed");
6919 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
6920 struct utp_task_req_desc *treq, u8 tm_function)
6922 struct request_queue *q = hba->tmf_queue;
6923 struct Scsi_Host *host = hba->host;
6924 DECLARE_COMPLETION_ONSTACK(wait);
6925 struct request *req;
6926 unsigned long flags;
6930 * blk_mq_alloc_request() is used here only to get a free tag.
6932 req = blk_mq_alloc_request(q, REQ_OP_DRV_OUT, 0);
6934 return PTR_ERR(req);
6936 req->end_io_data = &wait;
6937 ufshcd_hold(hba, false);
6939 spin_lock_irqsave(host->host_lock, flags);
6941 task_tag = req->tag;
6942 WARN_ONCE(task_tag < 0 || task_tag >= hba->nutmrs, "Invalid tag %d\n",
6944 hba->tmf_rqs[req->tag] = req;
6945 treq->upiu_req.req_header.dword_0 |= cpu_to_be32(task_tag);
6947 memcpy(hba->utmrdl_base_addr + task_tag, treq, sizeof(*treq));
6948 ufshcd_vops_setup_task_mgmt(hba, task_tag, tm_function);
6950 /* send command to the controller */
6951 __set_bit(task_tag, &hba->outstanding_tasks);
6953 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TASK_REQ_DOOR_BELL);
6954 /* Make sure that doorbell is committed immediately */
6957 spin_unlock_irqrestore(host->host_lock, flags);
6959 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_SEND);
6961 /* wait until the task management command is completed */
6962 err = wait_for_completion_io_timeout(&wait,
6963 msecs_to_jiffies(TM_CMD_TIMEOUT));
6965 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_ERR);
6966 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
6967 __func__, tm_function);
6968 if (ufshcd_clear_tm_cmd(hba, task_tag))
6969 dev_WARN(hba->dev, "%s: unable to clear tm cmd (slot %d) after timeout\n",
6970 __func__, task_tag);
6974 memcpy(treq, hba->utmrdl_base_addr + task_tag, sizeof(*treq));
6976 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_COMP);
6979 spin_lock_irqsave(hba->host->host_lock, flags);
6980 hba->tmf_rqs[req->tag] = NULL;
6981 __clear_bit(task_tag, &hba->outstanding_tasks);
6982 spin_unlock_irqrestore(hba->host->host_lock, flags);
6984 ufshcd_release(hba);
6985 blk_mq_free_request(req);
6991 * ufshcd_issue_tm_cmd - issues task management commands to controller
6992 * @hba: per adapter instance
6993 * @lun_id: LUN ID to which TM command is sent
6994 * @task_id: task ID to which the TM command is applicable
6995 * @tm_function: task management function opcode
6996 * @tm_response: task management service response return value
6998 * Returns non-zero value on error, zero on success.
7000 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
7001 u8 tm_function, u8 *tm_response)
7003 struct utp_task_req_desc treq = { { 0 }, };
7004 enum utp_ocs ocs_value;
7007 /* Configure task request descriptor */
7008 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
7009 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
7011 /* Configure task request UPIU */
7012 treq.upiu_req.req_header.dword_0 = cpu_to_be32(lun_id << 8) |
7013 cpu_to_be32(UPIU_TRANSACTION_TASK_REQ << 24);
7014 treq.upiu_req.req_header.dword_1 = cpu_to_be32(tm_function << 16);
7017 * The host shall provide the same value for LUN field in the basic
7018 * header and for Input Parameter.
7020 treq.upiu_req.input_param1 = cpu_to_be32(lun_id);
7021 treq.upiu_req.input_param2 = cpu_to_be32(task_id);
7023 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
7024 if (err == -ETIMEDOUT)
7027 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
7028 if (ocs_value != OCS_SUCCESS)
7029 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
7030 __func__, ocs_value);
7031 else if (tm_response)
7032 *tm_response = be32_to_cpu(treq.upiu_rsp.output_param1) &
7033 MASK_TM_SERVICE_RESP;
7038 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
7039 * @hba: per-adapter instance
7040 * @req_upiu: upiu request
7041 * @rsp_upiu: upiu reply
7042 * @desc_buff: pointer to descriptor buffer, NULL if NA
7043 * @buff_len: descriptor size, 0 if NA
7044 * @cmd_type: specifies the type (NOP, Query...)
7045 * @desc_op: descriptor operation
7047 * Those type of requests uses UTP Transfer Request Descriptor - utrd.
7048 * Therefore, it "rides" the device management infrastructure: uses its tag and
7049 * tasks work queues.
7051 * Since there is only one available tag for device management commands,
7052 * the caller is expected to hold the hba->dev_cmd.lock mutex.
7054 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
7055 struct utp_upiu_req *req_upiu,
7056 struct utp_upiu_req *rsp_upiu,
7057 u8 *desc_buff, int *buff_len,
7058 enum dev_cmd_type cmd_type,
7059 enum query_opcode desc_op)
7061 DECLARE_COMPLETION_ONSTACK(wait);
7062 const u32 tag = hba->reserved_slot;
7063 struct ufshcd_lrb *lrbp;
7067 /* Protects use of hba->reserved_slot. */
7068 lockdep_assert_held(&hba->dev_cmd.lock);
7070 down_read(&hba->clk_scaling_lock);
7072 lrbp = &hba->lrb[tag];
7075 lrbp->task_tag = tag;
7077 lrbp->intr_cmd = true;
7078 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
7079 hba->dev_cmd.type = cmd_type;
7081 if (hba->ufs_version <= ufshci_version(1, 1))
7082 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
7084 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
7086 /* update the task tag in the request upiu */
7087 req_upiu->header.dword_0 |= cpu_to_be32(tag);
7089 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE, 0);
7091 /* just copy the upiu request as it is */
7092 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
7093 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
7094 /* The Data Segment Area is optional depending upon the query
7095 * function value. for WRITE DESCRIPTOR, the data segment
7096 * follows right after the tsf.
7098 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
7102 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
7104 hba->dev_cmd.complete = &wait;
7106 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
7108 ufshcd_send_command(hba, tag, hba->dev_cmd_queue);
7110 * ignore the returning value here - ufshcd_check_query_response is
7111 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
7112 * read the response directly ignoring all errors.
7114 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
7116 /* just copy the upiu response as it is */
7117 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
7118 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
7119 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
7120 u16 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
7121 MASK_QUERY_DATA_SEG_LEN;
7123 if (*buff_len >= resp_len) {
7124 memcpy(desc_buff, descp, resp_len);
7125 *buff_len = resp_len;
7128 "%s: rsp size %d is bigger than buffer size %d",
7129 __func__, resp_len, *buff_len);
7134 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
7135 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
7137 up_read(&hba->clk_scaling_lock);
7142 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
7143 * @hba: per-adapter instance
7144 * @req_upiu: upiu request
7145 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands
7146 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
7147 * @desc_buff: pointer to descriptor buffer, NULL if NA
7148 * @buff_len: descriptor size, 0 if NA
7149 * @desc_op: descriptor operation
7151 * Supports UTP Transfer requests (nop and query), and UTP Task
7152 * Management requests.
7153 * It is up to the caller to fill the upiu conent properly, as it will
7154 * be copied without any further input validations.
7156 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
7157 struct utp_upiu_req *req_upiu,
7158 struct utp_upiu_req *rsp_upiu,
7160 u8 *desc_buff, int *buff_len,
7161 enum query_opcode desc_op)
7164 enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
7165 struct utp_task_req_desc treq = { { 0 }, };
7166 enum utp_ocs ocs_value;
7167 u8 tm_f = be32_to_cpu(req_upiu->header.dword_1) >> 16 & MASK_TM_FUNC;
7170 case UPIU_TRANSACTION_NOP_OUT:
7171 cmd_type = DEV_CMD_TYPE_NOP;
7173 case UPIU_TRANSACTION_QUERY_REQ:
7174 ufshcd_hold(hba, false);
7175 mutex_lock(&hba->dev_cmd.lock);
7176 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
7177 desc_buff, buff_len,
7179 mutex_unlock(&hba->dev_cmd.lock);
7180 ufshcd_release(hba);
7183 case UPIU_TRANSACTION_TASK_REQ:
7184 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
7185 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
7187 memcpy(&treq.upiu_req, req_upiu, sizeof(*req_upiu));
7189 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
7190 if (err == -ETIMEDOUT)
7193 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
7194 if (ocs_value != OCS_SUCCESS) {
7195 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
7200 memcpy(rsp_upiu, &treq.upiu_rsp, sizeof(*rsp_upiu));
7213 * ufshcd_advanced_rpmb_req_handler - handle advanced RPMB request
7214 * @hba: per adapter instance
7215 * @req_upiu: upiu request
7216 * @rsp_upiu: upiu reply
7217 * @req_ehs: EHS field which contains Advanced RPMB Request Message
7218 * @rsp_ehs: EHS field which returns Advanced RPMB Response Message
7219 * @sg_cnt: The number of sg lists actually used
7220 * @sg_list: Pointer to SG list when DATA IN/OUT UPIU is required in ARPMB operation
7221 * @dir: DMA direction
7223 * Returns zero on success, non-zero on failure
7225 int ufshcd_advanced_rpmb_req_handler(struct ufs_hba *hba, struct utp_upiu_req *req_upiu,
7226 struct utp_upiu_req *rsp_upiu, struct ufs_ehs *req_ehs,
7227 struct ufs_ehs *rsp_ehs, int sg_cnt, struct scatterlist *sg_list,
7228 enum dma_data_direction dir)
7230 DECLARE_COMPLETION_ONSTACK(wait);
7231 const u32 tag = hba->reserved_slot;
7232 struct ufshcd_lrb *lrbp;
7239 /* Protects use of hba->reserved_slot. */
7240 ufshcd_hold(hba, false);
7241 mutex_lock(&hba->dev_cmd.lock);
7242 down_read(&hba->clk_scaling_lock);
7244 lrbp = &hba->lrb[tag];
7247 lrbp->task_tag = tag;
7248 lrbp->lun = UFS_UPIU_RPMB_WLUN;
7250 lrbp->intr_cmd = true;
7251 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
7252 hba->dev_cmd.type = DEV_CMD_TYPE_RPMB;
7254 /* Advanced RPMB starts from UFS 4.0, so its command type is UTP_CMD_TYPE_UFS_STORAGE */
7255 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
7257 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, dir, 2);
7259 /* update the task tag and LUN in the request upiu */
7260 req_upiu->header.dword_0 |= cpu_to_be32(upiu_flags << 16 | UFS_UPIU_RPMB_WLUN << 8 | tag);
7262 /* copy the UPIU(contains CDB) request as it is */
7263 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
7264 /* Copy EHS, starting with byte32, immediately after the CDB package */
7265 memcpy(lrbp->ucd_req_ptr + 1, req_ehs, sizeof(*req_ehs));
7267 if (dir != DMA_NONE && sg_list)
7268 ufshcd_sgl_to_prdt(hba, lrbp, sg_cnt, sg_list);
7270 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
7272 hba->dev_cmd.complete = &wait;
7274 ufshcd_send_command(hba, tag, hba->dev_cmd_queue);
7276 err = ufshcd_wait_for_dev_cmd(hba, lrbp, ADVANCED_RPMB_REQ_TIMEOUT);
7279 /* Just copy the upiu response as it is */
7280 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
7281 /* Get the response UPIU result */
7282 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
7284 ehs_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) >> 24;
7286 * Since the bLength in EHS indicates the total size of the EHS Header and EHS Data
7287 * in 32 Byte units, the value of the bLength Request/Response for Advanced RPMB
7290 if (ehs_len == 2 && rsp_ehs) {
7292 * ucd_rsp_ptr points to a buffer with a length of 512 bytes
7293 * (ALIGNED_UPIU_SIZE = 512), and the EHS data just starts from byte32
7295 ehs_data = (u8 *)lrbp->ucd_rsp_ptr + EHS_OFFSET_IN_RESPONSE;
7296 memcpy(rsp_ehs, ehs_data, ehs_len * 32);
7300 up_read(&hba->clk_scaling_lock);
7301 mutex_unlock(&hba->dev_cmd.lock);
7302 ufshcd_release(hba);
7303 return err ? : result;
7307 * ufshcd_eh_device_reset_handler() - Reset a single logical unit.
7308 * @cmd: SCSI command pointer
7310 * Returns SUCCESS/FAILED
7312 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
7314 unsigned long flags, pending_reqs = 0, not_cleared = 0;
7315 struct Scsi_Host *host;
7316 struct ufs_hba *hba;
7317 u32 pos, not_cleared_mask = 0;
7321 host = cmd->device->host;
7322 hba = shost_priv(host);
7324 lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
7325 err = ufshcd_issue_tm_cmd(hba, lun, 0, UFS_LOGICAL_RESET, &resp);
7326 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7332 /* clear the commands that were pending for corresponding LUN */
7333 spin_lock_irqsave(&hba->outstanding_lock, flags);
7334 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs)
7335 if (hba->lrb[pos].lun == lun)
7336 __set_bit(pos, &pending_reqs);
7337 hba->outstanding_reqs &= ~pending_reqs;
7338 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7340 for_each_set_bit(pos, &pending_reqs, hba->nutrs) {
7341 if (ufshcd_clear_cmd(hba, pos) < 0) {
7342 spin_lock_irqsave(&hba->outstanding_lock, flags);
7343 not_cleared = 1U << pos &
7344 ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7345 hba->outstanding_reqs |= not_cleared;
7346 not_cleared_mask |= not_cleared;
7347 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7349 dev_err(hba->dev, "%s: failed to clear request %d\n",
7353 __ufshcd_transfer_req_compl(hba, pending_reqs & ~not_cleared_mask);
7356 hba->req_abort_count = 0;
7357 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, (u32)err);
7361 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7367 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
7369 struct ufshcd_lrb *lrbp;
7372 for_each_set_bit(tag, &bitmap, hba->nutrs) {
7373 lrbp = &hba->lrb[tag];
7374 lrbp->req_abort_skip = true;
7379 * ufshcd_try_to_abort_task - abort a specific task
7380 * @hba: Pointer to adapter instance
7381 * @tag: Task tag/index to be aborted
7383 * Abort the pending command in device by sending UFS_ABORT_TASK task management
7384 * command, and in host controller by clearing the door-bell register. There can
7385 * be race between controller sending the command to the device while abort is
7386 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
7387 * really issued and then try to abort it.
7389 * Returns zero on success, non-zero on failure
7391 int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag)
7393 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7399 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
7400 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7401 UFS_QUERY_TASK, &resp);
7402 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
7403 /* cmd pending in the device */
7404 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
7407 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7409 * cmd not pending in the device, check if it is
7412 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
7414 if (is_mcq_enabled(hba)) {
7416 if (ufshcd_cmd_inflight(lrbp->cmd)) {
7417 /* sleep for max. 200us same delay as in SDB mode */
7418 usleep_range(100, 200);
7421 /* command completed already */
7422 dev_err(hba->dev, "%s: cmd at tag=%d is cleared.\n",
7427 /* Single Doorbell Mode */
7428 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7429 if (reg & (1 << tag)) {
7430 /* sleep for max. 200us to stabilize */
7431 usleep_range(100, 200);
7434 /* command completed already */
7435 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
7440 "%s: no response from device. tag = %d, err %d\n",
7441 __func__, tag, err);
7443 err = resp; /* service response error */
7453 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7454 UFS_ABORT_TASK, &resp);
7455 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7457 err = resp; /* service response error */
7458 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
7459 __func__, tag, err);
7464 err = ufshcd_clear_cmd(hba, tag);
7466 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
7467 __func__, tag, err);
7474 * ufshcd_abort - scsi host template eh_abort_handler callback
7475 * @cmd: SCSI command pointer
7477 * Returns SUCCESS/FAILED
7479 static int ufshcd_abort(struct scsi_cmnd *cmd)
7481 struct Scsi_Host *host = cmd->device->host;
7482 struct ufs_hba *hba = shost_priv(host);
7483 int tag = scsi_cmd_to_rq(cmd)->tag;
7484 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7485 unsigned long flags;
7490 WARN_ONCE(tag < 0, "Invalid tag %d\n", tag);
7492 ufshcd_hold(hba, false);
7494 if (!is_mcq_enabled(hba)) {
7495 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7496 if (!test_bit(tag, &hba->outstanding_reqs)) {
7497 /* If command is already aborted/completed, return FAILED. */
7499 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
7500 __func__, tag, hba->outstanding_reqs, reg);
7505 /* Print Transfer Request of aborted task */
7506 dev_info(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
7509 * Print detailed info about aborted request.
7510 * As more than one request might get aborted at the same time,
7511 * print full information only for the first aborted request in order
7512 * to reduce repeated printouts. For other aborted requests only print
7515 scsi_print_command(cmd);
7516 if (!hba->req_abort_count) {
7517 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, tag);
7518 ufshcd_print_evt_hist(hba);
7519 ufshcd_print_host_state(hba);
7520 ufshcd_print_pwr_info(hba);
7521 ufshcd_print_tr(hba, tag, true);
7523 ufshcd_print_tr(hba, tag, false);
7525 hba->req_abort_count++;
7527 if (!is_mcq_enabled(hba) && !(reg & (1 << tag))) {
7528 /* only execute this code in single doorbell mode */
7530 "%s: cmd was completed, but without a notifying intr, tag = %d",
7532 __ufshcd_transfer_req_compl(hba, 1UL << tag);
7537 * Task abort to the device W-LUN is illegal. When this command
7538 * will fail, due to spec violation, scsi err handling next step
7539 * will be to send LU reset which, again, is a spec violation.
7540 * To avoid these unnecessary/illegal steps, first we clean up
7541 * the lrb taken by this cmd and re-set it in outstanding_reqs,
7542 * then queue the eh_work and bail.
7544 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN) {
7545 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, lrbp->lun);
7547 spin_lock_irqsave(host->host_lock, flags);
7548 hba->force_reset = true;
7549 ufshcd_schedule_eh_work(hba);
7550 spin_unlock_irqrestore(host->host_lock, flags);
7554 if (is_mcq_enabled(hba)) {
7555 /* MCQ mode. Branch off to handle abort for mcq mode */
7556 err = ufshcd_mcq_abort(cmd);
7560 /* Skip task abort in case previous aborts failed and report failure */
7561 if (lrbp->req_abort_skip) {
7562 dev_err(hba->dev, "%s: skipping abort\n", __func__);
7563 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7567 err = ufshcd_try_to_abort_task(hba, tag);
7569 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7570 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7576 * Clear the corresponding bit from outstanding_reqs since the command
7577 * has been aborted successfully.
7579 spin_lock_irqsave(&hba->outstanding_lock, flags);
7580 outstanding = __test_and_clear_bit(tag, &hba->outstanding_reqs);
7581 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7584 ufshcd_release_scsi_cmd(hba, lrbp);
7589 /* Matches the ufshcd_hold() call at the start of this function. */
7590 ufshcd_release(hba);
7595 * ufshcd_host_reset_and_restore - reset and restore host controller
7596 * @hba: per-adapter instance
7598 * Note that host controller reset may issue DME_RESET to
7599 * local and remote (device) Uni-Pro stack and the attributes
7600 * are reset to default state.
7602 * Returns zero on success, non-zero on failure
7604 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
7609 * Stop the host controller and complete the requests
7612 ufshpb_toggle_state(hba, HPB_PRESENT, HPB_RESET);
7613 ufshcd_hba_stop(hba);
7614 hba->silence_err_logs = true;
7615 ufshcd_complete_requests(hba);
7616 hba->silence_err_logs = false;
7618 /* scale up clocks to max frequency before full reinitialization */
7619 ufshcd_scale_clks(hba, true);
7621 err = ufshcd_hba_enable(hba);
7623 /* Establish the link again and restore the device */
7625 err = ufshcd_probe_hba(hba, false);
7628 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
7629 ufshcd_update_evt_hist(hba, UFS_EVT_HOST_RESET, (u32)err);
7634 * ufshcd_reset_and_restore - reset and re-initialize host/device
7635 * @hba: per-adapter instance
7637 * Reset and recover device, host and re-establish link. This
7638 * is helpful to recover the communication in fatal error conditions.
7640 * Returns zero on success, non-zero on failure
7642 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
7645 u32 saved_uic_err = 0;
7647 unsigned long flags;
7648 int retries = MAX_HOST_RESET_RETRIES;
7650 spin_lock_irqsave(hba->host->host_lock, flags);
7653 * This is a fresh start, cache and clear saved error first,
7654 * in case new error generated during reset and restore.
7656 saved_err |= hba->saved_err;
7657 saved_uic_err |= hba->saved_uic_err;
7659 hba->saved_uic_err = 0;
7660 hba->force_reset = false;
7661 hba->ufshcd_state = UFSHCD_STATE_RESET;
7662 spin_unlock_irqrestore(hba->host->host_lock, flags);
7664 /* Reset the attached device */
7665 ufshcd_device_reset(hba);
7667 err = ufshcd_host_reset_and_restore(hba);
7669 spin_lock_irqsave(hba->host->host_lock, flags);
7672 /* Do not exit unless operational or dead */
7673 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
7674 hba->ufshcd_state != UFSHCD_STATE_ERROR &&
7675 hba->ufshcd_state != UFSHCD_STATE_EH_SCHEDULED_NON_FATAL)
7677 } while (err && --retries);
7680 * Inform scsi mid-layer that we did reset and allow to handle
7681 * Unit Attention properly.
7683 scsi_report_bus_reset(hba->host, 0);
7685 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7686 hba->saved_err |= saved_err;
7687 hba->saved_uic_err |= saved_uic_err;
7689 spin_unlock_irqrestore(hba->host->host_lock, flags);
7695 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
7696 * @cmd: SCSI command pointer
7698 * Returns SUCCESS/FAILED
7700 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
7703 unsigned long flags;
7704 struct ufs_hba *hba;
7706 hba = shost_priv(cmd->device->host);
7708 spin_lock_irqsave(hba->host->host_lock, flags);
7709 hba->force_reset = true;
7710 ufshcd_schedule_eh_work(hba);
7711 dev_err(hba->dev, "%s: reset in progress - 1\n", __func__);
7712 spin_unlock_irqrestore(hba->host->host_lock, flags);
7714 flush_work(&hba->eh_work);
7716 spin_lock_irqsave(hba->host->host_lock, flags);
7717 if (hba->ufshcd_state == UFSHCD_STATE_ERROR)
7719 spin_unlock_irqrestore(hba->host->host_lock, flags);
7725 * ufshcd_get_max_icc_level - calculate the ICC level
7726 * @sup_curr_uA: max. current supported by the regulator
7727 * @start_scan: row at the desc table to start scan from
7728 * @buff: power descriptor buffer
7730 * Returns calculated max ICC level for specific regulator
7732 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan,
7740 for (i = start_scan; i >= 0; i--) {
7741 data = get_unaligned_be16(&buff[2 * i]);
7742 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
7743 ATTR_ICC_LVL_UNIT_OFFSET;
7744 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
7746 case UFSHCD_NANO_AMP:
7747 curr_uA = curr_uA / 1000;
7749 case UFSHCD_MILI_AMP:
7750 curr_uA = curr_uA * 1000;
7753 curr_uA = curr_uA * 1000 * 1000;
7755 case UFSHCD_MICRO_AMP:
7759 if (sup_curr_uA >= curr_uA)
7764 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
7771 * ufshcd_find_max_sup_active_icc_level - calculate the max ICC level
7772 * In case regulators are not initialized we'll return 0
7773 * @hba: per-adapter instance
7774 * @desc_buf: power descriptor buffer to extract ICC levels from.
7776 * Returns calculated ICC level
7778 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
7783 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
7784 !hba->vreg_info.vccq2) {
7786 * Using dev_dbg to avoid messages during runtime PM to avoid
7787 * never-ending cycles of messages written back to storage by
7788 * user space causing runtime resume, causing more messages and
7792 "%s: Regulator capability was not set, actvIccLevel=%d",
7793 __func__, icc_level);
7797 if (hba->vreg_info.vcc->max_uA)
7798 icc_level = ufshcd_get_max_icc_level(
7799 hba->vreg_info.vcc->max_uA,
7800 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
7801 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
7803 if (hba->vreg_info.vccq->max_uA)
7804 icc_level = ufshcd_get_max_icc_level(
7805 hba->vreg_info.vccq->max_uA,
7807 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
7809 if (hba->vreg_info.vccq2->max_uA)
7810 icc_level = ufshcd_get_max_icc_level(
7811 hba->vreg_info.vccq2->max_uA,
7813 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
7818 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba)
7824 desc_buf = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
7828 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0,
7829 desc_buf, QUERY_DESC_MAX_SIZE);
7832 "%s: Failed reading power descriptor ret = %d",
7837 icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf);
7838 dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level);
7840 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7841 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level);
7845 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
7846 __func__, icc_level, ret);
7852 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev)
7854 scsi_autopm_get_device(sdev);
7855 blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev);
7856 if (sdev->rpm_autosuspend)
7857 pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev,
7858 RPM_AUTOSUSPEND_DELAY_MS);
7859 scsi_autopm_put_device(sdev);
7863 * ufshcd_scsi_add_wlus - Adds required W-LUs
7864 * @hba: per-adapter instance
7866 * UFS device specification requires the UFS devices to support 4 well known
7868 * "REPORT_LUNS" (address: 01h)
7869 * "UFS Device" (address: 50h)
7870 * "RPMB" (address: 44h)
7871 * "BOOT" (address: 30h)
7872 * UFS device's power management needs to be controlled by "POWER CONDITION"
7873 * field of SSU (START STOP UNIT) command. But this "power condition" field
7874 * will take effect only when its sent to "UFS device" well known logical unit
7875 * hence we require the scsi_device instance to represent this logical unit in
7876 * order for the UFS host driver to send the SSU command for power management.
7878 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
7879 * Block) LU so user space process can control this LU. User space may also
7880 * want to have access to BOOT LU.
7882 * This function adds scsi device instances for each of all well known LUs
7883 * (except "REPORT LUNS" LU).
7885 * Returns zero on success (all required W-LUs are added successfully),
7886 * non-zero error value on failure (if failed to add any of the required W-LU).
7888 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
7891 struct scsi_device *sdev_boot, *sdev_rpmb;
7893 hba->ufs_device_wlun = __scsi_add_device(hba->host, 0, 0,
7894 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
7895 if (IS_ERR(hba->ufs_device_wlun)) {
7896 ret = PTR_ERR(hba->ufs_device_wlun);
7897 hba->ufs_device_wlun = NULL;
7900 scsi_device_put(hba->ufs_device_wlun);
7902 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
7903 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
7904 if (IS_ERR(sdev_rpmb)) {
7905 ret = PTR_ERR(sdev_rpmb);
7906 goto remove_ufs_device_wlun;
7908 ufshcd_blk_pm_runtime_init(sdev_rpmb);
7909 scsi_device_put(sdev_rpmb);
7911 sdev_boot = __scsi_add_device(hba->host, 0, 0,
7912 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
7913 if (IS_ERR(sdev_boot)) {
7914 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
7916 ufshcd_blk_pm_runtime_init(sdev_boot);
7917 scsi_device_put(sdev_boot);
7921 remove_ufs_device_wlun:
7922 scsi_remove_device(hba->ufs_device_wlun);
7927 static void ufshcd_wb_probe(struct ufs_hba *hba, const u8 *desc_buf)
7929 struct ufs_dev_info *dev_info = &hba->dev_info;
7931 u32 d_lu_wb_buf_alloc;
7932 u32 ext_ufs_feature;
7934 if (!ufshcd_is_wb_allowed(hba))
7938 * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or
7939 * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES
7942 if (!(dev_info->wspecversion >= 0x310 ||
7943 dev_info->wspecversion == 0x220 ||
7944 (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES)))
7947 ext_ufs_feature = get_unaligned_be32(desc_buf +
7948 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7950 if (!(ext_ufs_feature & UFS_DEV_WRITE_BOOSTER_SUP))
7954 * WB may be supported but not configured while provisioning. The spec
7955 * says, in dedicated wb buffer mode, a max of 1 lun would have wb
7956 * buffer configured.
7958 dev_info->wb_buffer_type = desc_buf[DEVICE_DESC_PARAM_WB_TYPE];
7960 dev_info->b_presrv_uspc_en =
7961 desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN];
7963 if (dev_info->wb_buffer_type == WB_BUF_MODE_SHARED) {
7964 if (!get_unaligned_be32(desc_buf +
7965 DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS))
7968 for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) {
7969 d_lu_wb_buf_alloc = 0;
7970 ufshcd_read_unit_desc_param(hba,
7972 UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS,
7973 (u8 *)&d_lu_wb_buf_alloc,
7974 sizeof(d_lu_wb_buf_alloc));
7975 if (d_lu_wb_buf_alloc) {
7976 dev_info->wb_dedicated_lu = lun;
7981 if (!d_lu_wb_buf_alloc)
7985 if (!ufshcd_is_wb_buf_lifetime_available(hba))
7991 hba->caps &= ~UFSHCD_CAP_WB_EN;
7994 static void ufshcd_temp_notif_probe(struct ufs_hba *hba, const u8 *desc_buf)
7996 struct ufs_dev_info *dev_info = &hba->dev_info;
7997 u32 ext_ufs_feature;
8000 if (!(hba->caps & UFSHCD_CAP_TEMP_NOTIF) || dev_info->wspecversion < 0x300)
8003 ext_ufs_feature = get_unaligned_be32(desc_buf + DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
8005 if (ext_ufs_feature & UFS_DEV_LOW_TEMP_NOTIF)
8006 mask |= MASK_EE_TOO_LOW_TEMP;
8008 if (ext_ufs_feature & UFS_DEV_HIGH_TEMP_NOTIF)
8009 mask |= MASK_EE_TOO_HIGH_TEMP;
8012 ufshcd_enable_ee(hba, mask);
8013 ufs_hwmon_probe(hba, mask);
8017 static void ufshcd_ext_iid_probe(struct ufs_hba *hba, u8 *desc_buf)
8019 struct ufs_dev_info *dev_info = &hba->dev_info;
8020 u32 ext_ufs_feature;
8024 /* Only UFS-4.0 and above may support EXT_IID */
8025 if (dev_info->wspecversion < 0x400)
8028 ext_ufs_feature = get_unaligned_be32(desc_buf +
8029 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
8030 if (!(ext_ufs_feature & UFS_DEV_EXT_IID_SUP))
8033 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
8034 QUERY_ATTR_IDN_EXT_IID_EN, 0, 0, &ext_iid_en);
8036 dev_err(hba->dev, "failed reading bEXTIIDEn. err = %d\n", err);
8039 dev_info->b_ext_iid_en = ext_iid_en;
8042 void ufshcd_fixup_dev_quirks(struct ufs_hba *hba,
8043 const struct ufs_dev_quirk *fixups)
8045 const struct ufs_dev_quirk *f;
8046 struct ufs_dev_info *dev_info = &hba->dev_info;
8051 for (f = fixups; f->quirk; f++) {
8052 if ((f->wmanufacturerid == dev_info->wmanufacturerid ||
8053 f->wmanufacturerid == UFS_ANY_VENDOR) &&
8054 ((dev_info->model &&
8055 STR_PRFX_EQUAL(f->model, dev_info->model)) ||
8056 !strcmp(f->model, UFS_ANY_MODEL)))
8057 hba->dev_quirks |= f->quirk;
8060 EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks);
8062 static void ufs_fixup_device_setup(struct ufs_hba *hba)
8064 /* fix by general quirk table */
8065 ufshcd_fixup_dev_quirks(hba, ufs_fixups);
8067 /* allow vendors to fix quirks */
8068 ufshcd_vops_fixup_dev_quirks(hba);
8071 static int ufs_get_device_desc(struct ufs_hba *hba)
8075 u8 b_ufs_feature_sup;
8077 struct ufs_dev_info *dev_info = &hba->dev_info;
8079 desc_buf = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
8085 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf,
8086 QUERY_DESC_MAX_SIZE);
8088 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
8094 * getting vendor (manufacturerID) and Bank Index in big endian
8097 dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
8098 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
8100 /* getting Specification Version in big endian format */
8101 dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 |
8102 desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1];
8103 dev_info->bqueuedepth = desc_buf[DEVICE_DESC_PARAM_Q_DPTH];
8104 b_ufs_feature_sup = desc_buf[DEVICE_DESC_PARAM_UFS_FEAT];
8106 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
8108 if (dev_info->wspecversion >= UFS_DEV_HPB_SUPPORT_VERSION &&
8109 (b_ufs_feature_sup & UFS_DEV_HPB_SUPPORT)) {
8110 bool hpb_en = false;
8112 ufshpb_get_dev_info(hba, desc_buf);
8114 if (!ufshpb_is_legacy(hba))
8115 err = ufshcd_query_flag_retry(hba,
8116 UPIU_QUERY_OPCODE_READ_FLAG,
8117 QUERY_FLAG_IDN_HPB_EN, 0,
8120 if (ufshpb_is_legacy(hba) || (!err && hpb_en))
8121 dev_info->hpb_enabled = true;
8124 err = ufshcd_read_string_desc(hba, model_index,
8125 &dev_info->model, SD_ASCII_STD);
8127 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
8132 hba->luns_avail = desc_buf[DEVICE_DESC_PARAM_NUM_LU] +
8133 desc_buf[DEVICE_DESC_PARAM_NUM_WLU];
8135 ufs_fixup_device_setup(hba);
8137 ufshcd_wb_probe(hba, desc_buf);
8139 ufshcd_temp_notif_probe(hba, desc_buf);
8141 if (hba->ext_iid_sup)
8142 ufshcd_ext_iid_probe(hba, desc_buf);
8145 * ufshcd_read_string_desc returns size of the string
8146 * reset the error value
8155 static void ufs_put_device_desc(struct ufs_hba *hba)
8157 struct ufs_dev_info *dev_info = &hba->dev_info;
8159 kfree(dev_info->model);
8160 dev_info->model = NULL;
8164 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
8165 * @hba: per-adapter instance
8167 * PA_TActivate parameter can be tuned manually if UniPro version is less than
8168 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
8169 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
8170 * the hibern8 exit latency.
8172 * Returns zero on success, non-zero error value on failure.
8174 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
8177 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
8179 ret = ufshcd_dme_peer_get(hba,
8181 RX_MIN_ACTIVATETIME_CAPABILITY,
8182 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
8183 &peer_rx_min_activatetime);
8187 /* make sure proper unit conversion is applied */
8188 tuned_pa_tactivate =
8189 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
8190 / PA_TACTIVATE_TIME_UNIT_US);
8191 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
8192 tuned_pa_tactivate);
8199 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
8200 * @hba: per-adapter instance
8202 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
8203 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
8204 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
8205 * This optimal value can help reduce the hibern8 exit latency.
8207 * Returns zero on success, non-zero error value on failure.
8209 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
8212 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
8213 u32 max_hibern8_time, tuned_pa_hibern8time;
8215 ret = ufshcd_dme_get(hba,
8216 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
8217 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
8218 &local_tx_hibern8_time_cap);
8222 ret = ufshcd_dme_peer_get(hba,
8223 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
8224 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
8225 &peer_rx_hibern8_time_cap);
8229 max_hibern8_time = max(local_tx_hibern8_time_cap,
8230 peer_rx_hibern8_time_cap);
8231 /* make sure proper unit conversion is applied */
8232 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
8233 / PA_HIBERN8_TIME_UNIT_US);
8234 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
8235 tuned_pa_hibern8time);
8241 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
8242 * less than device PA_TACTIVATE time.
8243 * @hba: per-adapter instance
8245 * Some UFS devices require host PA_TACTIVATE to be lower than device
8246 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
8249 * Returns zero on success, non-zero error value on failure.
8251 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
8254 u32 granularity, peer_granularity;
8255 u32 pa_tactivate, peer_pa_tactivate;
8256 u32 pa_tactivate_us, peer_pa_tactivate_us;
8257 static const u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
8259 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
8264 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
8269 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
8270 (granularity > PA_GRANULARITY_MAX_VAL)) {
8271 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
8272 __func__, granularity);
8276 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
8277 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
8278 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
8279 __func__, peer_granularity);
8283 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
8287 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
8288 &peer_pa_tactivate);
8292 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
8293 peer_pa_tactivate_us = peer_pa_tactivate *
8294 gran_to_us_table[peer_granularity - 1];
8296 if (pa_tactivate_us >= peer_pa_tactivate_us) {
8297 u32 new_peer_pa_tactivate;
8299 new_peer_pa_tactivate = pa_tactivate_us /
8300 gran_to_us_table[peer_granularity - 1];
8301 new_peer_pa_tactivate++;
8302 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
8303 new_peer_pa_tactivate);
8310 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
8312 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
8313 ufshcd_tune_pa_tactivate(hba);
8314 ufshcd_tune_pa_hibern8time(hba);
8317 ufshcd_vops_apply_dev_quirks(hba);
8319 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
8320 /* set 1ms timeout for PA_TACTIVATE */
8321 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
8323 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
8324 ufshcd_quirk_tune_host_pa_tactivate(hba);
8327 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
8329 hba->ufs_stats.hibern8_exit_cnt = 0;
8330 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
8331 hba->req_abort_count = 0;
8334 static int ufshcd_device_geo_params_init(struct ufs_hba *hba)
8339 desc_buf = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
8345 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0,
8346 desc_buf, QUERY_DESC_MAX_SIZE);
8348 dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n",
8353 if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1)
8354 hba->dev_info.max_lu_supported = 32;
8355 else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0)
8356 hba->dev_info.max_lu_supported = 8;
8358 if (desc_buf[QUERY_DESC_LENGTH_OFFSET] >=
8359 GEOMETRY_DESC_PARAM_HPB_MAX_ACTIVE_REGS)
8360 ufshpb_get_geo_info(hba, desc_buf);
8367 struct ufs_ref_clk {
8368 unsigned long freq_hz;
8369 enum ufs_ref_clk_freq val;
8372 static const struct ufs_ref_clk ufs_ref_clk_freqs[] = {
8373 {19200000, REF_CLK_FREQ_19_2_MHZ},
8374 {26000000, REF_CLK_FREQ_26_MHZ},
8375 {38400000, REF_CLK_FREQ_38_4_MHZ},
8376 {52000000, REF_CLK_FREQ_52_MHZ},
8377 {0, REF_CLK_FREQ_INVAL},
8380 static enum ufs_ref_clk_freq
8381 ufs_get_bref_clk_from_hz(unsigned long freq)
8385 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
8386 if (ufs_ref_clk_freqs[i].freq_hz == freq)
8387 return ufs_ref_clk_freqs[i].val;
8389 return REF_CLK_FREQ_INVAL;
8392 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
8396 freq = clk_get_rate(refclk);
8398 hba->dev_ref_clk_freq =
8399 ufs_get_bref_clk_from_hz(freq);
8401 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
8403 "invalid ref_clk setting = %ld\n", freq);
8406 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
8410 u32 freq = hba->dev_ref_clk_freq;
8412 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
8413 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
8416 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
8421 if (ref_clk == freq)
8422 goto out; /* nothing to update */
8424 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
8425 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
8428 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
8429 ufs_ref_clk_freqs[freq].freq_hz);
8433 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
8434 ufs_ref_clk_freqs[freq].freq_hz);
8440 static int ufshcd_device_params_init(struct ufs_hba *hba)
8445 /* Init UFS geometry descriptor related parameters */
8446 ret = ufshcd_device_geo_params_init(hba);
8450 /* Check and apply UFS device quirks */
8451 ret = ufs_get_device_desc(hba);
8453 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
8458 ufshcd_get_ref_clk_gating_wait(hba);
8460 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
8461 QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag))
8462 hba->dev_info.f_power_on_wp_en = flag;
8464 /* Probe maximum power mode co-supported by both UFS host and device */
8465 if (ufshcd_get_max_pwr_mode(hba))
8467 "%s: Failed getting max supported power mode\n",
8474 * ufshcd_add_lus - probe and add UFS logical units
8475 * @hba: per-adapter instance
8477 static int ufshcd_add_lus(struct ufs_hba *hba)
8481 /* Add required well known logical units to scsi mid layer */
8482 ret = ufshcd_scsi_add_wlus(hba);
8486 /* Initialize devfreq after UFS device is detected */
8487 if (ufshcd_is_clkscaling_supported(hba)) {
8488 memcpy(&hba->clk_scaling.saved_pwr_info,
8490 sizeof(struct ufs_pa_layer_attr));
8491 hba->clk_scaling.is_allowed = true;
8493 ret = ufshcd_devfreq_init(hba);
8497 hba->clk_scaling.is_enabled = true;
8498 ufshcd_init_clk_scaling_sysfs(hba);
8503 scsi_scan_host(hba->host);
8504 pm_runtime_put_sync(hba->dev);
8510 /* SDB - Single Doorbell */
8511 static void ufshcd_release_sdb_queue(struct ufs_hba *hba, int nutrs)
8513 size_t ucdl_size, utrdl_size;
8515 ucdl_size = sizeof(struct utp_transfer_cmd_desc) * nutrs;
8516 dmam_free_coherent(hba->dev, ucdl_size, hba->ucdl_base_addr,
8517 hba->ucdl_dma_addr);
8519 utrdl_size = sizeof(struct utp_transfer_req_desc) * nutrs;
8520 dmam_free_coherent(hba->dev, utrdl_size, hba->utrdl_base_addr,
8521 hba->utrdl_dma_addr);
8523 devm_kfree(hba->dev, hba->lrb);
8526 static int ufshcd_alloc_mcq(struct ufs_hba *hba)
8529 int old_nutrs = hba->nutrs;
8531 ret = ufshcd_mcq_decide_queue_depth(hba);
8536 ret = ufshcd_mcq_init(hba);
8541 * Previously allocated memory for nutrs may not be enough in MCQ mode.
8542 * Number of supported tags in MCQ mode may be larger than SDB mode.
8544 if (hba->nutrs != old_nutrs) {
8545 ufshcd_release_sdb_queue(hba, old_nutrs);
8546 ret = ufshcd_memory_alloc(hba);
8549 ufshcd_host_memory_configure(hba);
8552 ret = ufshcd_mcq_memory_alloc(hba);
8558 hba->nutrs = old_nutrs;
8562 static void ufshcd_config_mcq(struct ufs_hba *hba)
8566 ret = ufshcd_mcq_vops_config_esi(hba);
8567 dev_info(hba->dev, "ESI %sconfigured\n", ret ? "is not " : "");
8569 ufshcd_enable_intr(hba, UFSHCD_ENABLE_MCQ_INTRS);
8570 ufshcd_mcq_make_queues_operational(hba);
8571 ufshcd_mcq_config_mac(hba, hba->nutrs);
8573 hba->host->can_queue = hba->nutrs - UFSHCD_NUM_RESERVED;
8574 hba->reserved_slot = hba->nutrs - UFSHCD_NUM_RESERVED;
8576 /* Select MCQ mode */
8577 ufshcd_writel(hba, ufshcd_readl(hba, REG_UFS_MEM_CFG) | 0x1,
8579 hba->mcq_enabled = true;
8581 dev_info(hba->dev, "MCQ configured, nr_queues=%d, io_queues=%d, read_queue=%d, poll_queues=%d, queue_depth=%d\n",
8582 hba->nr_hw_queues, hba->nr_queues[HCTX_TYPE_DEFAULT],
8583 hba->nr_queues[HCTX_TYPE_READ], hba->nr_queues[HCTX_TYPE_POLL],
8587 static int ufshcd_device_init(struct ufs_hba *hba, bool init_dev_params)
8590 struct Scsi_Host *host = hba->host;
8592 hba->ufshcd_state = UFSHCD_STATE_RESET;
8594 ret = ufshcd_link_startup(hba);
8598 if (hba->quirks & UFSHCD_QUIRK_SKIP_PH_CONFIGURATION)
8601 /* Debug counters initialization */
8602 ufshcd_clear_dbg_ufs_stats(hba);
8604 /* UniPro link is active now */
8605 ufshcd_set_link_active(hba);
8607 /* Reconfigure MCQ upon reset */
8608 if (is_mcq_enabled(hba) && !init_dev_params)
8609 ufshcd_config_mcq(hba);
8611 /* Verify device initialization by sending NOP OUT UPIU */
8612 ret = ufshcd_verify_dev_init(hba);
8616 /* Initiate UFS initialization, and waiting until completion */
8617 ret = ufshcd_complete_dev_init(hba);
8622 * Initialize UFS device parameters used by driver, these
8623 * parameters are associated with UFS descriptors.
8625 if (init_dev_params) {
8626 ret = ufshcd_device_params_init(hba);
8629 if (is_mcq_supported(hba) && !hba->scsi_host_added) {
8630 ret = ufshcd_alloc_mcq(hba);
8632 ufshcd_config_mcq(hba);
8634 /* Continue with SDB mode */
8635 use_mcq_mode = false;
8636 dev_err(hba->dev, "MCQ mode is disabled, err=%d\n",
8639 ret = scsi_add_host(host, hba->dev);
8641 dev_err(hba->dev, "scsi_add_host failed\n");
8644 hba->scsi_host_added = true;
8645 } else if (is_mcq_supported(hba)) {
8646 /* UFSHCD_QUIRK_REINIT_AFTER_MAX_GEAR_SWITCH is set */
8647 ufshcd_config_mcq(hba);
8651 ufshcd_tune_unipro_params(hba);
8653 /* UFS device is also active now */
8654 ufshcd_set_ufs_dev_active(hba);
8655 ufshcd_force_reset_auto_bkops(hba);
8657 /* Gear up to HS gear if supported */
8658 if (hba->max_pwr_info.is_valid) {
8660 * Set the right value to bRefClkFreq before attempting to
8661 * switch to HS gears.
8663 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
8664 ufshcd_set_dev_ref_clk(hba);
8665 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
8667 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
8677 * ufshcd_probe_hba - probe hba to detect device and initialize it
8678 * @hba: per-adapter instance
8679 * @init_dev_params: whether or not to call ufshcd_device_params_init().
8681 * Execute link-startup and verify device initialization
8683 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params)
8685 ktime_t start = ktime_get();
8686 unsigned long flags;
8689 ret = ufshcd_device_init(hba, init_dev_params);
8693 if (hba->quirks & UFSHCD_QUIRK_REINIT_AFTER_MAX_GEAR_SWITCH) {
8694 /* Reset the device and controller before doing reinit */
8695 ufshcd_device_reset(hba);
8696 ufshcd_hba_stop(hba);
8697 ufshcd_vops_reinit_notify(hba);
8698 ret = ufshcd_hba_enable(hba);
8700 dev_err(hba->dev, "Host controller enable failed\n");
8701 ufshcd_print_evt_hist(hba);
8702 ufshcd_print_host_state(hba);
8706 /* Reinit the device */
8707 ret = ufshcd_device_init(hba, init_dev_params);
8712 ufshcd_print_pwr_info(hba);
8715 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec)
8716 * and for removable UFS card as well, hence always set the parameter.
8717 * Note: Error handler may issue the device reset hence resetting
8718 * bActiveICCLevel as well so it is always safe to set this here.
8720 ufshcd_set_active_icc_lvl(hba);
8722 /* Enable UFS Write Booster if supported */
8723 ufshcd_configure_wb(hba);
8725 if (hba->ee_usr_mask)
8726 ufshcd_write_ee_control(hba);
8727 /* Enable Auto-Hibernate if configured */
8728 ufshcd_auto_hibern8_enable(hba);
8730 ufshpb_toggle_state(hba, HPB_RESET, HPB_PRESENT);
8732 spin_lock_irqsave(hba->host->host_lock, flags);
8734 hba->ufshcd_state = UFSHCD_STATE_ERROR;
8735 else if (hba->ufshcd_state == UFSHCD_STATE_RESET)
8736 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
8737 spin_unlock_irqrestore(hba->host->host_lock, flags);
8739 trace_ufshcd_init(dev_name(hba->dev), ret,
8740 ktime_to_us(ktime_sub(ktime_get(), start)),
8741 hba->curr_dev_pwr_mode, hba->uic_link_state);
8746 * ufshcd_async_scan - asynchronous execution for probing hba
8747 * @data: data pointer to pass to this function
8748 * @cookie: cookie data
8750 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
8752 struct ufs_hba *hba = (struct ufs_hba *)data;
8755 down(&hba->host_sem);
8756 /* Initialize hba, detect and initialize UFS device */
8757 ret = ufshcd_probe_hba(hba, true);
8762 /* Probe and add UFS logical units */
8763 ret = ufshcd_add_lus(hba);
8766 * If we failed to initialize the device or the device is not
8767 * present, turn off the power/clocks etc.
8770 pm_runtime_put_sync(hba->dev);
8771 ufshcd_hba_exit(hba);
8775 static enum scsi_timeout_action ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
8777 struct ufs_hba *hba = shost_priv(scmd->device->host);
8779 if (!hba->system_suspending) {
8780 /* Activate the error handler in the SCSI core. */
8781 return SCSI_EH_NOT_HANDLED;
8785 * If we get here we know that no TMFs are outstanding and also that
8786 * the only pending command is a START STOP UNIT command. Handle the
8787 * timeout of that command directly to prevent a deadlock between
8788 * ufshcd_set_dev_pwr_mode() and ufshcd_err_handler().
8790 ufshcd_link_recovery(hba);
8791 dev_info(hba->dev, "%s() finished; outstanding_tasks = %#lx.\n",
8792 __func__, hba->outstanding_tasks);
8794 return hba->outstanding_reqs ? SCSI_EH_RESET_TIMER : SCSI_EH_DONE;
8797 static const struct attribute_group *ufshcd_driver_groups[] = {
8798 &ufs_sysfs_unit_descriptor_group,
8799 &ufs_sysfs_lun_attributes_group,
8800 #ifdef CONFIG_SCSI_UFS_HPB
8801 &ufs_sysfs_hpb_stat_group,
8802 &ufs_sysfs_hpb_param_group,
8807 static struct ufs_hba_variant_params ufs_hba_vps = {
8808 .hba_enable_delay_us = 1000,
8809 .wb_flush_threshold = UFS_WB_BUF_REMAIN_PERCENT(40),
8810 .devfreq_profile.polling_ms = 100,
8811 .devfreq_profile.target = ufshcd_devfreq_target,
8812 .devfreq_profile.get_dev_status = ufshcd_devfreq_get_dev_status,
8813 .ondemand_data.upthreshold = 70,
8814 .ondemand_data.downdifferential = 5,
8817 static const struct scsi_host_template ufshcd_driver_template = {
8818 .module = THIS_MODULE,
8820 .proc_name = UFSHCD,
8821 .map_queues = ufshcd_map_queues,
8822 .queuecommand = ufshcd_queuecommand,
8823 .mq_poll = ufshcd_poll,
8824 .slave_alloc = ufshcd_slave_alloc,
8825 .slave_configure = ufshcd_slave_configure,
8826 .slave_destroy = ufshcd_slave_destroy,
8827 .change_queue_depth = ufshcd_change_queue_depth,
8828 .eh_abort_handler = ufshcd_abort,
8829 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
8830 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
8831 .eh_timed_out = ufshcd_eh_timed_out,
8833 .sg_tablesize = SG_ALL,
8834 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
8835 .can_queue = UFSHCD_CAN_QUEUE,
8836 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX,
8837 .max_sectors = (1 << 20) / SECTOR_SIZE, /* 1 MiB */
8838 .max_host_blocked = 1,
8839 .track_queue_depth = 1,
8840 .skip_settle_delay = 1,
8841 .sdev_groups = ufshcd_driver_groups,
8842 .rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS,
8845 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
8854 * "set_load" operation shall be required on those regulators
8855 * which specifically configured current limitation. Otherwise
8856 * zero max_uA may cause unexpected behavior when regulator is
8857 * enabled or set as high power mode.
8862 ret = regulator_set_load(vreg->reg, ua);
8864 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
8865 __func__, vreg->name, ua, ret);
8871 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
8872 struct ufs_vreg *vreg)
8874 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
8877 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
8878 struct ufs_vreg *vreg)
8883 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
8886 static int ufshcd_config_vreg(struct device *dev,
8887 struct ufs_vreg *vreg, bool on)
8889 if (regulator_count_voltages(vreg->reg) <= 0)
8892 return ufshcd_config_vreg_load(dev, vreg, on ? vreg->max_uA : 0);
8895 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
8899 if (!vreg || vreg->enabled)
8902 ret = ufshcd_config_vreg(dev, vreg, true);
8904 ret = regulator_enable(vreg->reg);
8907 vreg->enabled = true;
8909 dev_err(dev, "%s: %s enable failed, err=%d\n",
8910 __func__, vreg->name, ret);
8915 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
8919 if (!vreg || !vreg->enabled || vreg->always_on)
8922 ret = regulator_disable(vreg->reg);
8925 /* ignore errors on applying disable config */
8926 ufshcd_config_vreg(dev, vreg, false);
8927 vreg->enabled = false;
8929 dev_err(dev, "%s: %s disable failed, err=%d\n",
8930 __func__, vreg->name, ret);
8936 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
8939 struct device *dev = hba->dev;
8940 struct ufs_vreg_info *info = &hba->vreg_info;
8942 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
8946 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
8950 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
8954 ufshcd_toggle_vreg(dev, info->vccq2, false);
8955 ufshcd_toggle_vreg(dev, info->vccq, false);
8956 ufshcd_toggle_vreg(dev, info->vcc, false);
8961 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
8963 struct ufs_vreg_info *info = &hba->vreg_info;
8965 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
8968 int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
8975 vreg->reg = devm_regulator_get(dev, vreg->name);
8976 if (IS_ERR(vreg->reg)) {
8977 ret = PTR_ERR(vreg->reg);
8978 dev_err(dev, "%s: %s get failed, err=%d\n",
8979 __func__, vreg->name, ret);
8984 EXPORT_SYMBOL_GPL(ufshcd_get_vreg);
8986 static int ufshcd_init_vreg(struct ufs_hba *hba)
8989 struct device *dev = hba->dev;
8990 struct ufs_vreg_info *info = &hba->vreg_info;
8992 ret = ufshcd_get_vreg(dev, info->vcc);
8996 ret = ufshcd_get_vreg(dev, info->vccq);
8998 ret = ufshcd_get_vreg(dev, info->vccq2);
9003 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
9005 struct ufs_vreg_info *info = &hba->vreg_info;
9007 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
9010 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
9013 struct ufs_clk_info *clki;
9014 struct list_head *head = &hba->clk_list_head;
9015 unsigned long flags;
9016 ktime_t start = ktime_get();
9017 bool clk_state_changed = false;
9019 if (list_empty(head))
9022 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
9026 list_for_each_entry(clki, head, list) {
9027 if (!IS_ERR_OR_NULL(clki->clk)) {
9029 * Don't disable clocks which are needed
9030 * to keep the link active.
9032 if (ufshcd_is_link_active(hba) &&
9033 clki->keep_link_active)
9036 clk_state_changed = on ^ clki->enabled;
9037 if (on && !clki->enabled) {
9038 ret = clk_prepare_enable(clki->clk);
9040 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
9041 __func__, clki->name, ret);
9044 } else if (!on && clki->enabled) {
9045 clk_disable_unprepare(clki->clk);
9048 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
9049 clki->name, on ? "en" : "dis");
9053 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
9059 list_for_each_entry(clki, head, list) {
9060 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
9061 clk_disable_unprepare(clki->clk);
9063 } else if (!ret && on) {
9064 spin_lock_irqsave(hba->host->host_lock, flags);
9065 hba->clk_gating.state = CLKS_ON;
9066 trace_ufshcd_clk_gating(dev_name(hba->dev),
9067 hba->clk_gating.state);
9068 spin_unlock_irqrestore(hba->host->host_lock, flags);
9071 if (clk_state_changed)
9072 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
9073 (on ? "on" : "off"),
9074 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
9078 static enum ufs_ref_clk_freq ufshcd_parse_ref_clk_property(struct ufs_hba *hba)
9081 int ret = device_property_read_u32(hba->dev, "ref-clk-freq", &freq);
9084 dev_dbg(hba->dev, "Cannot query 'ref-clk-freq' property = %d", ret);
9085 return REF_CLK_FREQ_INVAL;
9088 return ufs_get_bref_clk_from_hz(freq);
9091 static int ufshcd_init_clocks(struct ufs_hba *hba)
9094 struct ufs_clk_info *clki;
9095 struct device *dev = hba->dev;
9096 struct list_head *head = &hba->clk_list_head;
9098 if (list_empty(head))
9101 list_for_each_entry(clki, head, list) {
9105 clki->clk = devm_clk_get(dev, clki->name);
9106 if (IS_ERR(clki->clk)) {
9107 ret = PTR_ERR(clki->clk);
9108 dev_err(dev, "%s: %s clk get failed, %d\n",
9109 __func__, clki->name, ret);
9114 * Parse device ref clk freq as per device tree "ref_clk".
9115 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
9116 * in ufshcd_alloc_host().
9118 if (!strcmp(clki->name, "ref_clk"))
9119 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
9121 if (clki->max_freq) {
9122 ret = clk_set_rate(clki->clk, clki->max_freq);
9124 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
9125 __func__, clki->name,
9126 clki->max_freq, ret);
9129 clki->curr_freq = clki->max_freq;
9131 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
9132 clki->name, clk_get_rate(clki->clk));
9138 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
9145 err = ufshcd_vops_init(hba);
9147 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
9148 __func__, ufshcd_get_var_name(hba), err);
9153 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
9158 ufshcd_vops_exit(hba);
9161 static int ufshcd_hba_init(struct ufs_hba *hba)
9166 * Handle host controller power separately from the UFS device power
9167 * rails as it will help controlling the UFS host controller power
9168 * collapse easily which is different than UFS device power collapse.
9169 * Also, enable the host controller power before we go ahead with rest
9170 * of the initialization here.
9172 err = ufshcd_init_hba_vreg(hba);
9176 err = ufshcd_setup_hba_vreg(hba, true);
9180 err = ufshcd_init_clocks(hba);
9182 goto out_disable_hba_vreg;
9184 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
9185 hba->dev_ref_clk_freq = ufshcd_parse_ref_clk_property(hba);
9187 err = ufshcd_setup_clocks(hba, true);
9189 goto out_disable_hba_vreg;
9191 err = ufshcd_init_vreg(hba);
9193 goto out_disable_clks;
9195 err = ufshcd_setup_vreg(hba, true);
9197 goto out_disable_clks;
9199 err = ufshcd_variant_hba_init(hba);
9201 goto out_disable_vreg;
9203 ufs_debugfs_hba_init(hba);
9205 hba->is_powered = true;
9209 ufshcd_setup_vreg(hba, false);
9211 ufshcd_setup_clocks(hba, false);
9212 out_disable_hba_vreg:
9213 ufshcd_setup_hba_vreg(hba, false);
9218 static void ufshcd_hba_exit(struct ufs_hba *hba)
9220 if (hba->is_powered) {
9221 ufshcd_exit_clk_scaling(hba);
9222 ufshcd_exit_clk_gating(hba);
9224 destroy_workqueue(hba->eh_wq);
9225 ufs_debugfs_hba_exit(hba);
9226 ufshcd_variant_hba_exit(hba);
9227 ufshcd_setup_vreg(hba, false);
9228 ufshcd_setup_clocks(hba, false);
9229 ufshcd_setup_hba_vreg(hba, false);
9230 hba->is_powered = false;
9231 ufs_put_device_desc(hba);
9235 static int ufshcd_execute_start_stop(struct scsi_device *sdev,
9236 enum ufs_dev_pwr_mode pwr_mode,
9237 struct scsi_sense_hdr *sshdr)
9239 const unsigned char cdb[6] = { START_STOP, 0, 0, 0, pwr_mode << 4, 0 };
9240 const struct scsi_exec_args args = {
9242 .req_flags = BLK_MQ_REQ_PM,
9243 .scmd_flags = SCMD_FAIL_IF_RECOVERING,
9246 return scsi_execute_cmd(sdev, cdb, REQ_OP_DRV_IN, /*buffer=*/NULL,
9247 /*bufflen=*/0, /*timeout=*/HZ, /*retries=*/0, &args);
9251 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
9253 * @hba: per adapter instance
9254 * @pwr_mode: device power mode to set
9256 * Returns 0 if requested power mode is set successfully
9257 * Returns < 0 if failed to set the requested power mode
9259 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
9260 enum ufs_dev_pwr_mode pwr_mode)
9262 struct scsi_sense_hdr sshdr;
9263 struct scsi_device *sdp;
9264 unsigned long flags;
9267 spin_lock_irqsave(hba->host->host_lock, flags);
9268 sdp = hba->ufs_device_wlun;
9269 if (sdp && scsi_device_online(sdp))
9270 ret = scsi_device_get(sdp);
9273 spin_unlock_irqrestore(hba->host->host_lock, flags);
9279 * If scsi commands fail, the scsi mid-layer schedules scsi error-
9280 * handling, which would wait for host to be resumed. Since we know
9281 * we are functional while we are here, skip host resume in error
9284 hba->host->eh_noresume = 1;
9287 * Current function would be generally called from the power management
9288 * callbacks hence set the RQF_PM flag so that it doesn't resume the
9289 * already suspended childs.
9291 for (retries = 3; retries > 0; --retries) {
9292 ret = ufshcd_execute_start_stop(sdp, pwr_mode, &sshdr);
9294 * scsi_execute() only returns a negative value if the request
9301 sdev_printk(KERN_WARNING, sdp,
9302 "START_STOP failed for power mode: %d, result %x\n",
9305 if (scsi_sense_valid(&sshdr))
9306 scsi_print_sense_hdr(sdp, NULL, &sshdr);
9310 hba->curr_dev_pwr_mode = pwr_mode;
9313 scsi_device_put(sdp);
9314 hba->host->eh_noresume = 0;
9318 static int ufshcd_link_state_transition(struct ufs_hba *hba,
9319 enum uic_link_state req_link_state,
9320 bool check_for_bkops)
9324 if (req_link_state == hba->uic_link_state)
9327 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
9328 ret = ufshcd_uic_hibern8_enter(hba);
9330 ufshcd_set_link_hibern8(hba);
9332 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
9338 * If autobkops is enabled, link can't be turned off because
9339 * turning off the link would also turn off the device, except in the
9340 * case of DeepSleep where the device is expected to remain powered.
9342 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
9343 (!check_for_bkops || !hba->auto_bkops_enabled)) {
9345 * Let's make sure that link is in low power mode, we are doing
9346 * this currently by putting the link in Hibern8. Otherway to
9347 * put the link in low power mode is to send the DME end point
9348 * to device and then send the DME reset command to local
9349 * unipro. But putting the link in hibern8 is much faster.
9351 * Note also that putting the link in Hibern8 is a requirement
9352 * for entering DeepSleep.
9354 ret = ufshcd_uic_hibern8_enter(hba);
9356 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
9361 * Change controller state to "reset state" which
9362 * should also put the link in off/reset state
9364 ufshcd_hba_stop(hba);
9366 * TODO: Check if we need any delay to make sure that
9367 * controller is reset
9369 ufshcd_set_link_off(hba);
9376 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
9378 bool vcc_off = false;
9381 * It seems some UFS devices may keep drawing more than sleep current
9382 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
9383 * To avoid this situation, add 2ms delay before putting these UFS
9384 * rails in LPM mode.
9386 if (!ufshcd_is_link_active(hba) &&
9387 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
9388 usleep_range(2000, 2100);
9391 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
9394 * If UFS device and link is in OFF state, all power supplies (VCC,
9395 * VCCQ, VCCQ2) can be turned off if power on write protect is not
9396 * required. If UFS link is inactive (Hibern8 or OFF state) and device
9397 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
9399 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
9400 * in low power state which would save some power.
9402 * If Write Booster is enabled and the device needs to flush the WB
9403 * buffer OR if bkops status is urgent for WB, keep Vcc on.
9405 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
9406 !hba->dev_info.is_lu_power_on_wp) {
9407 ufshcd_setup_vreg(hba, false);
9409 } else if (!ufshcd_is_ufs_dev_active(hba)) {
9410 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
9412 if (ufshcd_is_link_hibern8(hba) || ufshcd_is_link_off(hba)) {
9413 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
9414 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
9419 * Some UFS devices require delay after VCC power rail is turned-off.
9421 if (vcc_off && hba->vreg_info.vcc &&
9422 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_AFTER_LPM)
9423 usleep_range(5000, 5100);
9427 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
9431 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
9432 !hba->dev_info.is_lu_power_on_wp) {
9433 ret = ufshcd_setup_vreg(hba, true);
9434 } else if (!ufshcd_is_ufs_dev_active(hba)) {
9435 if (!ufshcd_is_link_active(hba)) {
9436 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
9439 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
9443 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
9448 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
9450 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
9454 #endif /* CONFIG_PM */
9456 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
9458 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
9459 ufshcd_setup_hba_vreg(hba, false);
9462 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
9464 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
9465 ufshcd_setup_hba_vreg(hba, true);
9468 static int __ufshcd_wl_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
9471 bool check_for_bkops;
9472 enum ufs_pm_level pm_lvl;
9473 enum ufs_dev_pwr_mode req_dev_pwr_mode;
9474 enum uic_link_state req_link_state;
9476 hba->pm_op_in_progress = true;
9477 if (pm_op != UFS_SHUTDOWN_PM) {
9478 pm_lvl = pm_op == UFS_RUNTIME_PM ?
9479 hba->rpm_lvl : hba->spm_lvl;
9480 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
9481 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
9483 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
9484 req_link_state = UIC_LINK_OFF_STATE;
9487 ufshpb_suspend(hba);
9490 * If we can't transition into any of the low power modes
9491 * just gate the clocks.
9493 ufshcd_hold(hba, false);
9494 hba->clk_gating.is_suspended = true;
9496 if (ufshcd_is_clkscaling_supported(hba))
9497 ufshcd_clk_scaling_suspend(hba, true);
9499 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
9500 req_link_state == UIC_LINK_ACTIVE_STATE) {
9504 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
9505 (req_link_state == hba->uic_link_state))
9506 goto enable_scaling;
9508 /* UFS device & link must be active before we enter in this function */
9509 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
9511 goto enable_scaling;
9514 if (pm_op == UFS_RUNTIME_PM) {
9515 if (ufshcd_can_autobkops_during_suspend(hba)) {
9517 * The device is idle with no requests in the queue,
9518 * allow background operations if bkops status shows
9519 * that performance might be impacted.
9521 ret = ufshcd_urgent_bkops(hba);
9523 goto enable_scaling;
9525 /* make sure that auto bkops is disabled */
9526 ufshcd_disable_auto_bkops(hba);
9529 * If device needs to do BKOP or WB buffer flush during
9530 * Hibern8, keep device power mode as "active power mode"
9533 hba->dev_info.b_rpm_dev_flush_capable =
9534 hba->auto_bkops_enabled ||
9535 (((req_link_state == UIC_LINK_HIBERN8_STATE) ||
9536 ((req_link_state == UIC_LINK_ACTIVE_STATE) &&
9537 ufshcd_is_auto_hibern8_enabled(hba))) &&
9538 ufshcd_wb_need_flush(hba));
9541 flush_work(&hba->eeh_work);
9543 ret = ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
9545 goto enable_scaling;
9547 if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) {
9548 if (pm_op != UFS_RUNTIME_PM)
9549 /* ensure that bkops is disabled */
9550 ufshcd_disable_auto_bkops(hba);
9552 if (!hba->dev_info.b_rpm_dev_flush_capable) {
9553 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
9554 if (ret && pm_op != UFS_SHUTDOWN_PM) {
9556 * If return err in suspend flow, IO will hang.
9557 * Trigger error handler and break suspend for
9560 ufshcd_force_error_recovery(hba);
9564 goto enable_scaling;
9569 * In the case of DeepSleep, the device is expected to remain powered
9570 * with the link off, so do not check for bkops.
9572 check_for_bkops = !ufshcd_is_ufs_dev_deepsleep(hba);
9573 ret = ufshcd_link_state_transition(hba, req_link_state, check_for_bkops);
9574 if (ret && pm_op != UFS_SHUTDOWN_PM) {
9576 * If return err in suspend flow, IO will hang.
9577 * Trigger error handler and break suspend for
9580 ufshcd_force_error_recovery(hba);
9584 goto set_dev_active;
9588 * Call vendor specific suspend callback. As these callbacks may access
9589 * vendor specific host controller register space call them before the
9590 * host clocks are ON.
9592 ret = ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
9594 goto set_link_active;
9599 * Device hardware reset is required to exit DeepSleep. Also, for
9600 * DeepSleep, the link is off so host reset and restore will be done
9603 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
9604 ufshcd_device_reset(hba);
9605 WARN_ON(!ufshcd_is_link_off(hba));
9607 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
9608 ufshcd_set_link_active(hba);
9609 else if (ufshcd_is_link_off(hba))
9610 ufshcd_host_reset_and_restore(hba);
9612 /* Can also get here needing to exit DeepSleep */
9613 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
9614 ufshcd_device_reset(hba);
9615 ufshcd_host_reset_and_restore(hba);
9617 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
9618 ufshcd_disable_auto_bkops(hba);
9620 if (ufshcd_is_clkscaling_supported(hba))
9621 ufshcd_clk_scaling_suspend(hba, false);
9623 hba->dev_info.b_rpm_dev_flush_capable = false;
9625 if (hba->dev_info.b_rpm_dev_flush_capable) {
9626 schedule_delayed_work(&hba->rpm_dev_flush_recheck_work,
9627 msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS));
9631 ufshcd_update_evt_hist(hba, UFS_EVT_WL_SUSP_ERR, (u32)ret);
9632 hba->clk_gating.is_suspended = false;
9633 ufshcd_release(hba);
9636 hba->pm_op_in_progress = false;
9641 static int __ufshcd_wl_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
9644 enum uic_link_state old_link_state = hba->uic_link_state;
9646 hba->pm_op_in_progress = true;
9649 * Call vendor specific resume callback. As these callbacks may access
9650 * vendor specific host controller register space call them when the
9651 * host clocks are ON.
9653 ret = ufshcd_vops_resume(hba, pm_op);
9657 /* For DeepSleep, the only supported option is to have the link off */
9658 WARN_ON(ufshcd_is_ufs_dev_deepsleep(hba) && !ufshcd_is_link_off(hba));
9660 if (ufshcd_is_link_hibern8(hba)) {
9661 ret = ufshcd_uic_hibern8_exit(hba);
9663 ufshcd_set_link_active(hba);
9665 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
9667 goto vendor_suspend;
9669 } else if (ufshcd_is_link_off(hba)) {
9671 * A full initialization of the host and the device is
9672 * required since the link was put to off during suspend.
9673 * Note, in the case of DeepSleep, the device will exit
9674 * DeepSleep due to device reset.
9676 ret = ufshcd_reset_and_restore(hba);
9678 * ufshcd_reset_and_restore() should have already
9679 * set the link state as active
9681 if (ret || !ufshcd_is_link_active(hba))
9682 goto vendor_suspend;
9685 if (!ufshcd_is_ufs_dev_active(hba)) {
9686 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
9688 goto set_old_link_state;
9691 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
9692 ufshcd_enable_auto_bkops(hba);
9695 * If BKOPs operations are urgently needed at this moment then
9696 * keep auto-bkops enabled or else disable it.
9698 ufshcd_urgent_bkops(hba);
9700 if (hba->ee_usr_mask)
9701 ufshcd_write_ee_control(hba);
9703 if (ufshcd_is_clkscaling_supported(hba))
9704 ufshcd_clk_scaling_suspend(hba, false);
9706 if (hba->dev_info.b_rpm_dev_flush_capable) {
9707 hba->dev_info.b_rpm_dev_flush_capable = false;
9708 cancel_delayed_work(&hba->rpm_dev_flush_recheck_work);
9711 /* Enable Auto-Hibernate if configured */
9712 ufshcd_auto_hibern8_enable(hba);
9718 ufshcd_link_state_transition(hba, old_link_state, 0);
9720 ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
9721 ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
9724 ufshcd_update_evt_hist(hba, UFS_EVT_WL_RES_ERR, (u32)ret);
9725 hba->clk_gating.is_suspended = false;
9726 ufshcd_release(hba);
9727 hba->pm_op_in_progress = false;
9731 static int ufshcd_wl_runtime_suspend(struct device *dev)
9733 struct scsi_device *sdev = to_scsi_device(dev);
9734 struct ufs_hba *hba;
9736 ktime_t start = ktime_get();
9738 hba = shost_priv(sdev->host);
9740 ret = __ufshcd_wl_suspend(hba, UFS_RUNTIME_PM);
9742 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9744 trace_ufshcd_wl_runtime_suspend(dev_name(dev), ret,
9745 ktime_to_us(ktime_sub(ktime_get(), start)),
9746 hba->curr_dev_pwr_mode, hba->uic_link_state);
9751 static int ufshcd_wl_runtime_resume(struct device *dev)
9753 struct scsi_device *sdev = to_scsi_device(dev);
9754 struct ufs_hba *hba;
9756 ktime_t start = ktime_get();
9758 hba = shost_priv(sdev->host);
9760 ret = __ufshcd_wl_resume(hba, UFS_RUNTIME_PM);
9762 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9764 trace_ufshcd_wl_runtime_resume(dev_name(dev), ret,
9765 ktime_to_us(ktime_sub(ktime_get(), start)),
9766 hba->curr_dev_pwr_mode, hba->uic_link_state);
9772 #ifdef CONFIG_PM_SLEEP
9773 static int ufshcd_wl_suspend(struct device *dev)
9775 struct scsi_device *sdev = to_scsi_device(dev);
9776 struct ufs_hba *hba;
9778 ktime_t start = ktime_get();
9780 hba = shost_priv(sdev->host);
9781 down(&hba->host_sem);
9782 hba->system_suspending = true;
9784 if (pm_runtime_suspended(dev))
9787 ret = __ufshcd_wl_suspend(hba, UFS_SYSTEM_PM);
9789 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9795 hba->is_sys_suspended = true;
9796 trace_ufshcd_wl_suspend(dev_name(dev), ret,
9797 ktime_to_us(ktime_sub(ktime_get(), start)),
9798 hba->curr_dev_pwr_mode, hba->uic_link_state);
9803 static int ufshcd_wl_resume(struct device *dev)
9805 struct scsi_device *sdev = to_scsi_device(dev);
9806 struct ufs_hba *hba;
9808 ktime_t start = ktime_get();
9810 hba = shost_priv(sdev->host);
9812 if (pm_runtime_suspended(dev))
9815 ret = __ufshcd_wl_resume(hba, UFS_SYSTEM_PM);
9817 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9819 trace_ufshcd_wl_resume(dev_name(dev), ret,
9820 ktime_to_us(ktime_sub(ktime_get(), start)),
9821 hba->curr_dev_pwr_mode, hba->uic_link_state);
9823 hba->is_sys_suspended = false;
9824 hba->system_suspending = false;
9830 static void ufshcd_wl_shutdown(struct device *dev)
9832 struct scsi_device *sdev = to_scsi_device(dev);
9833 struct ufs_hba *hba;
9835 hba = shost_priv(sdev->host);
9837 down(&hba->host_sem);
9838 hba->shutting_down = true;
9841 /* Turn on everything while shutting down */
9842 ufshcd_rpm_get_sync(hba);
9843 scsi_device_quiesce(sdev);
9844 shost_for_each_device(sdev, hba->host) {
9845 if (sdev == hba->ufs_device_wlun)
9847 scsi_device_quiesce(sdev);
9849 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
9853 * ufshcd_suspend - helper function for suspend operations
9854 * @hba: per adapter instance
9856 * This function will put disable irqs, turn off clocks
9857 * and set vreg and hba-vreg in lpm mode.
9859 static int ufshcd_suspend(struct ufs_hba *hba)
9863 if (!hba->is_powered)
9866 * Disable the host irq as host controller as there won't be any
9867 * host controller transaction expected till resume.
9869 ufshcd_disable_irq(hba);
9870 ret = ufshcd_setup_clocks(hba, false);
9872 ufshcd_enable_irq(hba);
9875 if (ufshcd_is_clkgating_allowed(hba)) {
9876 hba->clk_gating.state = CLKS_OFF;
9877 trace_ufshcd_clk_gating(dev_name(hba->dev),
9878 hba->clk_gating.state);
9881 ufshcd_vreg_set_lpm(hba);
9882 /* Put the host controller in low power mode if possible */
9883 ufshcd_hba_vreg_set_lpm(hba);
9889 * ufshcd_resume - helper function for resume operations
9890 * @hba: per adapter instance
9892 * This function basically turns on the regulators, clocks and
9895 * Returns 0 for success and non-zero for failure
9897 static int ufshcd_resume(struct ufs_hba *hba)
9901 if (!hba->is_powered)
9904 ufshcd_hba_vreg_set_hpm(hba);
9905 ret = ufshcd_vreg_set_hpm(hba);
9909 /* Make sure clocks are enabled before accessing controller */
9910 ret = ufshcd_setup_clocks(hba, true);
9914 /* enable the host irq as host controller would be active soon */
9915 ufshcd_enable_irq(hba);
9920 ufshcd_vreg_set_lpm(hba);
9923 ufshcd_update_evt_hist(hba, UFS_EVT_RESUME_ERR, (u32)ret);
9926 #endif /* CONFIG_PM */
9928 #ifdef CONFIG_PM_SLEEP
9930 * ufshcd_system_suspend - system suspend callback
9931 * @dev: Device associated with the UFS controller.
9933 * Executed before putting the system into a sleep state in which the contents
9934 * of main memory are preserved.
9936 * Returns 0 for success and non-zero for failure
9938 int ufshcd_system_suspend(struct device *dev)
9940 struct ufs_hba *hba = dev_get_drvdata(dev);
9942 ktime_t start = ktime_get();
9944 if (pm_runtime_suspended(hba->dev))
9947 ret = ufshcd_suspend(hba);
9949 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
9950 ktime_to_us(ktime_sub(ktime_get(), start)),
9951 hba->curr_dev_pwr_mode, hba->uic_link_state);
9954 EXPORT_SYMBOL(ufshcd_system_suspend);
9957 * ufshcd_system_resume - system resume callback
9958 * @dev: Device associated with the UFS controller.
9960 * Executed after waking the system up from a sleep state in which the contents
9961 * of main memory were preserved.
9963 * Returns 0 for success and non-zero for failure
9965 int ufshcd_system_resume(struct device *dev)
9967 struct ufs_hba *hba = dev_get_drvdata(dev);
9968 ktime_t start = ktime_get();
9971 if (pm_runtime_suspended(hba->dev))
9974 ret = ufshcd_resume(hba);
9977 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
9978 ktime_to_us(ktime_sub(ktime_get(), start)),
9979 hba->curr_dev_pwr_mode, hba->uic_link_state);
9983 EXPORT_SYMBOL(ufshcd_system_resume);
9984 #endif /* CONFIG_PM_SLEEP */
9988 * ufshcd_runtime_suspend - runtime suspend callback
9989 * @dev: Device associated with the UFS controller.
9991 * Check the description of ufshcd_suspend() function for more details.
9993 * Returns 0 for success and non-zero for failure
9995 int ufshcd_runtime_suspend(struct device *dev)
9997 struct ufs_hba *hba = dev_get_drvdata(dev);
9999 ktime_t start = ktime_get();
10001 ret = ufshcd_suspend(hba);
10003 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
10004 ktime_to_us(ktime_sub(ktime_get(), start)),
10005 hba->curr_dev_pwr_mode, hba->uic_link_state);
10008 EXPORT_SYMBOL(ufshcd_runtime_suspend);
10011 * ufshcd_runtime_resume - runtime resume routine
10012 * @dev: Device associated with the UFS controller.
10014 * This function basically brings controller
10015 * to active state. Following operations are done in this function:
10017 * 1. Turn on all the controller related clocks
10018 * 2. Turn ON VCC rail
10020 int ufshcd_runtime_resume(struct device *dev)
10022 struct ufs_hba *hba = dev_get_drvdata(dev);
10024 ktime_t start = ktime_get();
10026 ret = ufshcd_resume(hba);
10028 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
10029 ktime_to_us(ktime_sub(ktime_get(), start)),
10030 hba->curr_dev_pwr_mode, hba->uic_link_state);
10033 EXPORT_SYMBOL(ufshcd_runtime_resume);
10034 #endif /* CONFIG_PM */
10037 * ufshcd_shutdown - shutdown routine
10038 * @hba: per adapter instance
10040 * This function would turn off both UFS device and UFS hba
10041 * regulators. It would also disable clocks.
10043 * Returns 0 always to allow force shutdown even in case of errors.
10045 int ufshcd_shutdown(struct ufs_hba *hba)
10047 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
10048 ufshcd_suspend(hba);
10050 hba->is_powered = false;
10051 /* allow force shutdown even in case of errors */
10054 EXPORT_SYMBOL(ufshcd_shutdown);
10057 * ufshcd_remove - de-allocate SCSI host and host memory space
10058 * data structure memory
10059 * @hba: per adapter instance
10061 void ufshcd_remove(struct ufs_hba *hba)
10063 if (hba->ufs_device_wlun)
10064 ufshcd_rpm_get_sync(hba);
10065 ufs_hwmon_remove(hba);
10066 ufs_bsg_remove(hba);
10067 ufshpb_remove(hba);
10068 ufs_sysfs_remove_nodes(hba->dev);
10069 blk_mq_destroy_queue(hba->tmf_queue);
10070 blk_put_queue(hba->tmf_queue);
10071 blk_mq_free_tag_set(&hba->tmf_tag_set);
10072 scsi_remove_host(hba->host);
10073 /* disable interrupts */
10074 ufshcd_disable_intr(hba, hba->intr_mask);
10075 ufshcd_hba_stop(hba);
10076 ufshcd_hba_exit(hba);
10078 EXPORT_SYMBOL_GPL(ufshcd_remove);
10080 #ifdef CONFIG_PM_SLEEP
10081 int ufshcd_system_freeze(struct device *dev)
10084 return ufshcd_system_suspend(dev);
10087 EXPORT_SYMBOL_GPL(ufshcd_system_freeze);
10089 int ufshcd_system_restore(struct device *dev)
10092 struct ufs_hba *hba = dev_get_drvdata(dev);
10095 ret = ufshcd_system_resume(dev);
10099 /* Configure UTRL and UTMRL base address registers */
10100 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
10101 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
10102 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
10103 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
10104 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
10105 REG_UTP_TASK_REQ_LIST_BASE_L);
10106 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
10107 REG_UTP_TASK_REQ_LIST_BASE_H);
10109 * Make sure that UTRL and UTMRL base address registers
10110 * are updated with the latest queue addresses. Only after
10111 * updating these addresses, we can queue the new commands.
10115 /* Resuming from hibernate, assume that link was OFF */
10116 ufshcd_set_link_off(hba);
10121 EXPORT_SYMBOL_GPL(ufshcd_system_restore);
10123 int ufshcd_system_thaw(struct device *dev)
10125 return ufshcd_system_resume(dev);
10127 EXPORT_SYMBOL_GPL(ufshcd_system_thaw);
10128 #endif /* CONFIG_PM_SLEEP */
10131 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
10132 * @hba: pointer to Host Bus Adapter (HBA)
10134 void ufshcd_dealloc_host(struct ufs_hba *hba)
10136 scsi_host_put(hba->host);
10138 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
10141 * ufshcd_set_dma_mask - Set dma mask based on the controller
10142 * addressing capability
10143 * @hba: per adapter instance
10145 * Returns 0 for success, non-zero for failure
10147 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
10149 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
10150 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
10153 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
10157 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
10158 * @dev: pointer to device handle
10159 * @hba_handle: driver private handle
10160 * Returns 0 on success, non-zero value on failure
10162 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
10164 struct Scsi_Host *host;
10165 struct ufs_hba *hba;
10170 "Invalid memory reference for dev is NULL\n");
10175 host = scsi_host_alloc(&ufshcd_driver_template,
10176 sizeof(struct ufs_hba));
10178 dev_err(dev, "scsi_host_alloc failed\n");
10182 host->nr_maps = HCTX_TYPE_POLL + 1;
10183 hba = shost_priv(host);
10186 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
10187 hba->nop_out_timeout = NOP_OUT_TIMEOUT;
10188 ufshcd_set_sg_entry_size(hba, sizeof(struct ufshcd_sg_entry));
10189 INIT_LIST_HEAD(&hba->clk_list_head);
10190 spin_lock_init(&hba->outstanding_lock);
10197 EXPORT_SYMBOL(ufshcd_alloc_host);
10199 /* This function exists because blk_mq_alloc_tag_set() requires this. */
10200 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx,
10201 const struct blk_mq_queue_data *qd)
10203 WARN_ON_ONCE(true);
10204 return BLK_STS_NOTSUPP;
10207 static const struct blk_mq_ops ufshcd_tmf_ops = {
10208 .queue_rq = ufshcd_queue_tmf,
10212 * ufshcd_init - Driver initialization routine
10213 * @hba: per-adapter instance
10214 * @mmio_base: base register address
10215 * @irq: Interrupt line of device
10216 * Returns 0 on success, non-zero value on failure
10218 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
10221 struct Scsi_Host *host = hba->host;
10222 struct device *dev = hba->dev;
10223 char eh_wq_name[sizeof("ufs_eh_wq_00")];
10226 * dev_set_drvdata() must be called before any callbacks are registered
10227 * that use dev_get_drvdata() (frequency scaling, clock scaling, hwmon,
10230 dev_set_drvdata(dev, hba);
10234 "Invalid memory reference for mmio_base is NULL\n");
10239 hba->mmio_base = mmio_base;
10241 hba->vps = &ufs_hba_vps;
10243 err = ufshcd_hba_init(hba);
10247 /* Read capabilities registers */
10248 err = ufshcd_hba_capabilities(hba);
10252 /* Get UFS version supported by the controller */
10253 hba->ufs_version = ufshcd_get_ufs_version(hba);
10255 /* Get Interrupt bit mask per version */
10256 hba->intr_mask = ufshcd_get_intr_mask(hba);
10258 err = ufshcd_set_dma_mask(hba);
10260 dev_err(hba->dev, "set dma mask failed\n");
10264 /* Allocate memory for host memory space */
10265 err = ufshcd_memory_alloc(hba);
10267 dev_err(hba->dev, "Memory allocation failed\n");
10271 /* Configure LRB */
10272 ufshcd_host_memory_configure(hba);
10274 host->can_queue = hba->nutrs - UFSHCD_NUM_RESERVED;
10275 host->cmd_per_lun = hba->nutrs - UFSHCD_NUM_RESERVED;
10276 host->max_id = UFSHCD_MAX_ID;
10277 host->max_lun = UFS_MAX_LUNS;
10278 host->max_channel = UFSHCD_MAX_CHANNEL;
10279 host->unique_id = host->host_no;
10280 host->max_cmd_len = UFS_CDB_SIZE;
10282 hba->max_pwr_info.is_valid = false;
10284 /* Initialize work queues */
10285 snprintf(eh_wq_name, sizeof(eh_wq_name), "ufs_eh_wq_%d",
10286 hba->host->host_no);
10287 hba->eh_wq = create_singlethread_workqueue(eh_wq_name);
10289 dev_err(hba->dev, "%s: failed to create eh workqueue\n",
10294 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
10295 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
10297 sema_init(&hba->host_sem, 1);
10299 /* Initialize UIC command mutex */
10300 mutex_init(&hba->uic_cmd_mutex);
10302 /* Initialize mutex for device management commands */
10303 mutex_init(&hba->dev_cmd.lock);
10305 /* Initialize mutex for exception event control */
10306 mutex_init(&hba->ee_ctrl_mutex);
10308 mutex_init(&hba->wb_mutex);
10309 init_rwsem(&hba->clk_scaling_lock);
10311 ufshcd_init_clk_gating(hba);
10313 ufshcd_init_clk_scaling(hba);
10316 * In order to avoid any spurious interrupt immediately after
10317 * registering UFS controller interrupt handler, clear any pending UFS
10318 * interrupt status and disable all the UFS interrupts.
10320 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
10321 REG_INTERRUPT_STATUS);
10322 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
10324 * Make sure that UFS interrupts are disabled and any pending interrupt
10325 * status is cleared before registering UFS interrupt handler.
10329 /* IRQ registration */
10330 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
10332 dev_err(hba->dev, "request irq failed\n");
10335 hba->is_irq_enabled = true;
10338 if (!is_mcq_supported(hba)) {
10339 err = scsi_add_host(host, hba->dev);
10341 dev_err(hba->dev, "scsi_add_host failed\n");
10346 hba->tmf_tag_set = (struct blk_mq_tag_set) {
10348 .queue_depth = hba->nutmrs,
10349 .ops = &ufshcd_tmf_ops,
10350 .flags = BLK_MQ_F_NO_SCHED,
10352 err = blk_mq_alloc_tag_set(&hba->tmf_tag_set);
10354 goto out_remove_scsi_host;
10355 hba->tmf_queue = blk_mq_init_queue(&hba->tmf_tag_set);
10356 if (IS_ERR(hba->tmf_queue)) {
10357 err = PTR_ERR(hba->tmf_queue);
10358 goto free_tmf_tag_set;
10360 hba->tmf_rqs = devm_kcalloc(hba->dev, hba->nutmrs,
10361 sizeof(*hba->tmf_rqs), GFP_KERNEL);
10362 if (!hba->tmf_rqs) {
10364 goto free_tmf_queue;
10367 /* Reset the attached device */
10368 ufshcd_device_reset(hba);
10370 ufshcd_init_crypto(hba);
10372 /* Host controller enable */
10373 err = ufshcd_hba_enable(hba);
10375 dev_err(hba->dev, "Host controller enable failed\n");
10376 ufshcd_print_evt_hist(hba);
10377 ufshcd_print_host_state(hba);
10378 goto free_tmf_queue;
10382 * Set the default power management level for runtime and system PM.
10383 * Default power saving mode is to keep UFS link in Hibern8 state
10384 * and UFS device in sleep state.
10386 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
10387 UFS_SLEEP_PWR_MODE,
10388 UIC_LINK_HIBERN8_STATE);
10389 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
10390 UFS_SLEEP_PWR_MODE,
10391 UIC_LINK_HIBERN8_STATE);
10393 INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work,
10394 ufshcd_rpm_dev_flush_recheck_work);
10396 /* Set the default auto-hiberate idle timer value to 150 ms */
10397 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
10398 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
10399 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
10402 /* Hold auto suspend until async scan completes */
10403 pm_runtime_get_sync(dev);
10404 atomic_set(&hba->scsi_block_reqs_cnt, 0);
10406 * We are assuming that device wasn't put in sleep/power-down
10407 * state exclusively during the boot stage before kernel.
10408 * This assumption helps avoid doing link startup twice during
10409 * ufshcd_probe_hba().
10411 ufshcd_set_ufs_dev_active(hba);
10413 async_schedule(ufshcd_async_scan, hba);
10414 ufs_sysfs_add_nodes(hba->dev);
10416 device_enable_async_suspend(dev);
10420 blk_mq_destroy_queue(hba->tmf_queue);
10421 blk_put_queue(hba->tmf_queue);
10423 blk_mq_free_tag_set(&hba->tmf_tag_set);
10424 out_remove_scsi_host:
10425 scsi_remove_host(hba->host);
10427 hba->is_irq_enabled = false;
10428 ufshcd_hba_exit(hba);
10432 EXPORT_SYMBOL_GPL(ufshcd_init);
10434 void ufshcd_resume_complete(struct device *dev)
10436 struct ufs_hba *hba = dev_get_drvdata(dev);
10438 if (hba->complete_put) {
10439 ufshcd_rpm_put(hba);
10440 hba->complete_put = false;
10443 EXPORT_SYMBOL_GPL(ufshcd_resume_complete);
10445 static bool ufshcd_rpm_ok_for_spm(struct ufs_hba *hba)
10447 struct device *dev = &hba->ufs_device_wlun->sdev_gendev;
10448 enum ufs_dev_pwr_mode dev_pwr_mode;
10449 enum uic_link_state link_state;
10450 unsigned long flags;
10453 spin_lock_irqsave(&dev->power.lock, flags);
10454 dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl);
10455 link_state = ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl);
10456 res = pm_runtime_suspended(dev) &&
10457 hba->curr_dev_pwr_mode == dev_pwr_mode &&
10458 hba->uic_link_state == link_state &&
10459 !hba->dev_info.b_rpm_dev_flush_capable;
10460 spin_unlock_irqrestore(&dev->power.lock, flags);
10465 int __ufshcd_suspend_prepare(struct device *dev, bool rpm_ok_for_spm)
10467 struct ufs_hba *hba = dev_get_drvdata(dev);
10471 * SCSI assumes that runtime-pm and system-pm for scsi drivers
10472 * are same. And it doesn't wake up the device for system-suspend
10473 * if it's runtime suspended. But ufs doesn't follow that.
10474 * Refer ufshcd_resume_complete()
10476 if (hba->ufs_device_wlun) {
10477 /* Prevent runtime suspend */
10478 ufshcd_rpm_get_noresume(hba);
10480 * Check if already runtime suspended in same state as system
10481 * suspend would be.
10483 if (!rpm_ok_for_spm || !ufshcd_rpm_ok_for_spm(hba)) {
10484 /* RPM state is not ok for SPM, so runtime resume */
10485 ret = ufshcd_rpm_resume(hba);
10486 if (ret < 0 && ret != -EACCES) {
10487 ufshcd_rpm_put(hba);
10491 hba->complete_put = true;
10495 EXPORT_SYMBOL_GPL(__ufshcd_suspend_prepare);
10497 int ufshcd_suspend_prepare(struct device *dev)
10499 return __ufshcd_suspend_prepare(dev, true);
10501 EXPORT_SYMBOL_GPL(ufshcd_suspend_prepare);
10503 #ifdef CONFIG_PM_SLEEP
10504 static int ufshcd_wl_poweroff(struct device *dev)
10506 struct scsi_device *sdev = to_scsi_device(dev);
10507 struct ufs_hba *hba = shost_priv(sdev->host);
10509 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
10514 static int ufshcd_wl_probe(struct device *dev)
10516 struct scsi_device *sdev = to_scsi_device(dev);
10518 if (!is_device_wlun(sdev))
10521 blk_pm_runtime_init(sdev->request_queue, dev);
10522 pm_runtime_set_autosuspend_delay(dev, 0);
10523 pm_runtime_allow(dev);
10528 static int ufshcd_wl_remove(struct device *dev)
10530 pm_runtime_forbid(dev);
10534 static const struct dev_pm_ops ufshcd_wl_pm_ops = {
10535 #ifdef CONFIG_PM_SLEEP
10536 .suspend = ufshcd_wl_suspend,
10537 .resume = ufshcd_wl_resume,
10538 .freeze = ufshcd_wl_suspend,
10539 .thaw = ufshcd_wl_resume,
10540 .poweroff = ufshcd_wl_poweroff,
10541 .restore = ufshcd_wl_resume,
10543 SET_RUNTIME_PM_OPS(ufshcd_wl_runtime_suspend, ufshcd_wl_runtime_resume, NULL)
10547 * ufs_dev_wlun_template - describes ufs device wlun
10548 * ufs-device wlun - used to send pm commands
10549 * All luns are consumers of ufs-device wlun.
10551 * Currently, no sd driver is present for wluns.
10552 * Hence the no specific pm operations are performed.
10553 * With ufs design, SSU should be sent to ufs-device wlun.
10554 * Hence register a scsi driver for ufs wluns only.
10556 static struct scsi_driver ufs_dev_wlun_template = {
10558 .name = "ufs_device_wlun",
10559 .owner = THIS_MODULE,
10560 .probe = ufshcd_wl_probe,
10561 .remove = ufshcd_wl_remove,
10562 .pm = &ufshcd_wl_pm_ops,
10563 .shutdown = ufshcd_wl_shutdown,
10567 static int __init ufshcd_core_init(void)
10571 ufs_debugfs_init();
10573 ret = scsi_register_driver(&ufs_dev_wlun_template.gendrv);
10575 ufs_debugfs_exit();
10579 static void __exit ufshcd_core_exit(void)
10581 ufs_debugfs_exit();
10582 scsi_unregister_driver(&ufs_dev_wlun_template.gendrv);
10585 module_init(ufshcd_core_init);
10586 module_exit(ufshcd_core_exit);
10588 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
10589 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
10590 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
10591 MODULE_SOFTDEP("pre: governor_simpleondemand");
10592 MODULE_LICENSE("GPL");